diff --git a/go/src/internal/cpu/cpu_arm64_other.go b/go/src/internal/cpu/cpu_arm64_other.go new file mode 100644 index 0000000000000000000000000000000000000000..44592cfcede8e19d9c9645246a21a48e9596f26e --- /dev/null +++ b/go/src/internal/cpu/cpu_arm64_other.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build arm64 && !linux && !freebsd && !android && (!darwin || ios) && !openbsd + +package cpu + +func osInit() { + // Other operating systems do not support reading HWCap from auxiliary vector, + // reading privileged aarch64 system registers or sysctl in user space to detect + // CPU features at runtime. +} diff --git a/go/src/internal/cpu/cpu_darwin.go b/go/src/internal/cpu/cpu_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..2d4ac54fc2f5c4eb1050eacb0678c9aa70785467 --- /dev/null +++ b/go/src/internal/cpu/cpu_darwin.go @@ -0,0 +1,72 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && !ios + +package cpu + +import _ "unsafe" // for linkname + +// Pushed from runtime. +// +//go:noescape +func sysctlbynameInt32(name []byte) (int32, int32) + +// Pushed from runtime. +// +//go:noescape +func sysctlbynameBytes(name, out []byte) int32 + +// sysctlEnabled should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/bytedance/gopkg +// - github.com/songzhibin97/gkit +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname sysctlEnabled +func sysctlEnabled(name []byte) bool { + ret, value := sysctlbynameInt32(name) + if ret < 0 { + return false + } + return value > 0 +} + +// darwinKernelVersionCheck reports if Darwin kernel version is at +// least major.minor.patch. +// +// Code borrowed from x/sys/cpu. +func darwinKernelVersionCheck(major, minor, patch int) bool { + var release [256]byte + ret := sysctlbynameBytes([]byte("kern.osrelease\x00"), release[:]) + if ret < 0 { + return false + } + + var mmp [3]int + c := 0 +Loop: + for _, b := range release[:] { + switch { + case b >= '0' && b <= '9': + mmp[c] = 10*mmp[c] + int(b-'0') + case b == '.': + c++ + if c > 2 { + return false + } + case b == 0: + break Loop + default: + return false + } + } + if c != 2 { + return false + } + return mmp[0] > major || mmp[0] == major && (mmp[1] > minor || mmp[1] == minor && mmp[2] >= patch) +} diff --git a/go/src/internal/cpu/cpu_loong64.go b/go/src/internal/cpu/cpu_loong64.go new file mode 100644 index 0000000000000000000000000000000000000000..de7eaf0c6c99bbf166aaab0753c6e3f1a5899d12 --- /dev/null +++ b/go/src/internal/cpu/cpu_loong64.go @@ -0,0 +1,55 @@ +// 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 loong64 + +package cpu + +// CacheLinePadSize is used to prevent false sharing of cache lines. +// We choose 64 because Loongson 3A5000 the L1 Dcache is 4-way 256-line 64-byte-per-line. +const CacheLinePadSize = 64 + +// Bit fields for CPUCFG registers, Related reference documents: +// https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#_cpucfg +const ( + // CPUCFG1 bits + cpucfg1_CRC32 = 1 << 25 + + // CPUCFG2 bits + cpucfg2_LAM_BH = 1 << 27 + cpucfg2_LAMCAS = 1 << 28 +) + +// get_cpucfg is implemented in cpu_loong64.s. +func get_cpucfg(reg uint32) uint32 + +func doinit() { + options = []option{ + {Name: "lsx", Feature: &Loong64.HasLSX}, + {Name: "lasx", Feature: &Loong64.HasLASX}, + {Name: "crc32", Feature: &Loong64.HasCRC32}, + {Name: "lamcas", Feature: &Loong64.HasLAMCAS}, + {Name: "lam_bh", Feature: &Loong64.HasLAM_BH}, + } + + // The CPUCFG data on Loong64 only reflects the hardware capabilities, + // not the kernel support status, so features such as LSX and LASX that + // require kernel support cannot be obtained from the CPUCFG data. + // + // These features only require hardware capability support and do not + // require kernel specific support, so they can be obtained directly + // through CPUCFG + cfg1 := get_cpucfg(1) + cfg2 := get_cpucfg(2) + + Loong64.HasCRC32 = cfgIsSet(cfg1, cpucfg1_CRC32) + Loong64.HasLAMCAS = cfgIsSet(cfg2, cpucfg2_LAMCAS) + Loong64.HasLAM_BH = cfgIsSet(cfg2, cpucfg2_LAM_BH) + + osInit() +} + +func cfgIsSet(cfg uint32, val uint32) bool { + return cfg&val != 0 +} diff --git a/go/src/internal/cpu/cpu_loong64.s b/go/src/internal/cpu/cpu_loong64.s new file mode 100644 index 0000000000000000000000000000000000000000..f02a27803d64dee71bac34858999a2f5aa87f087 --- /dev/null +++ b/go/src/internal/cpu/cpu_loong64.s @@ -0,0 +1,12 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func get_cpucfg(reg uint32) uint32 +TEXT ·get_cpucfg(SB), NOSPLIT|NOFRAME, $0-12 + MOVW reg+0(FP), R5 + CPUCFG R5, R4 + MOVW R4, ret+8(FP) + RET diff --git a/go/src/internal/cpu/cpu_loong64_hwcap.go b/go/src/internal/cpu/cpu_loong64_hwcap.go new file mode 100644 index 0000000000000000000000000000000000000000..2b25cc6b4a6c2d5c4ba1d7c766da9a3a9264e6c6 --- /dev/null +++ b/go/src/internal/cpu/cpu_loong64_hwcap.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. + +//go:build loong64 && linux + +package cpu + +// This is initialized by archauxv and should not be changed after it is +// initialized. +var HWCap uint + +// HWCAP bits. These are exposed by the Linux kernel. +const ( + hwcap_LOONGARCH_LSX = 1 << 4 + hwcap_LOONGARCH_LASX = 1 << 5 +) + +func hwcapInit() { + // TODO: Features that require kernel support like LSX and LASX can + // be detected here once needed in std library or by the compiler. + Loong64.HasLSX = hwcIsSet(HWCap, hwcap_LOONGARCH_LSX) + Loong64.HasLASX = hwcIsSet(HWCap, hwcap_LOONGARCH_LASX) +} + +func hwcIsSet(hwc uint, val uint) bool { + return hwc&val != 0 +} diff --git a/go/src/internal/cpu/cpu_loong64_linux.go b/go/src/internal/cpu/cpu_loong64_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..73bc384a54e8433444cb9456a8c791e0961ee0fe --- /dev/null +++ b/go/src/internal/cpu/cpu_loong64_linux.go @@ -0,0 +1,11 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build loong64 && linux + +package cpu + +func osInit() { + hwcapInit() +} diff --git a/go/src/internal/cpu/cpu_mips.go b/go/src/internal/cpu/cpu_mips.go new file mode 100644 index 0000000000000000000000000000000000000000..14a9c975eae68ad10eb3cf4ad4545753dac08e58 --- /dev/null +++ b/go/src/internal/cpu/cpu_mips.go @@ -0,0 +1,10 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cpu + +const CacheLinePadSize = 32 + +func doinit() { +} diff --git a/go/src/internal/cpu/cpu_mips64x.go b/go/src/internal/cpu/cpu_mips64x.go new file mode 100644 index 0000000000000000000000000000000000000000..c452ffd8b30216641232ad2f5c0713652c9488f5 --- /dev/null +++ b/go/src/internal/cpu/cpu_mips64x.go @@ -0,0 +1,32 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build mips64 || mips64le + +package cpu + +const CacheLinePadSize = 32 + +// This is initialized by archauxv and should not be changed after it is +// initialized. +var HWCap uint + +// HWCAP bits. These are exposed by the Linux kernel 5.4. +const ( + // CPU features + hwcap_MIPS_MSA = 1 << 1 +) + +func doinit() { + options = []option{ + {Name: "msa", Feature: &MIPS64X.HasMSA}, + } + + // HWCAP feature bits + MIPS64X.HasMSA = isSet(HWCap, hwcap_MIPS_MSA) +} + +func isSet(hwc uint, value uint) bool { + return hwc&value != 0 +} diff --git a/go/src/internal/cpu/cpu_mipsle.go b/go/src/internal/cpu/cpu_mipsle.go new file mode 100644 index 0000000000000000000000000000000000000000..14a9c975eae68ad10eb3cf4ad4545753dac08e58 --- /dev/null +++ b/go/src/internal/cpu/cpu_mipsle.go @@ -0,0 +1,10 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cpu + +const CacheLinePadSize = 32 + +func doinit() { +} diff --git a/go/src/internal/cpu/cpu_no_name.go b/go/src/internal/cpu/cpu_no_name.go new file mode 100644 index 0000000000000000000000000000000000000000..2adfa1b70994f33a24404a81eb8dd7d09879b6da --- /dev/null +++ b/go/src/internal/cpu/cpu_no_name.go @@ -0,0 +1,18 @@ +// 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 !386 && !amd64 && !ppc64 && !ppc64le + +package cpu + +// Name returns the CPU name given by the vendor +// if it can be read directly from memory or by CPU instructions. +// If the CPU name can not be determined an empty string is returned. +// +// Implementations that use the Operating System (e.g. sysctl or /sys/) +// to gather CPU information for display should be placed in internal/sysinfo. +func Name() string { + // "A CPU has no name". + return "" +} diff --git a/go/src/internal/cpu/cpu_ppc64x.go b/go/src/internal/cpu/cpu_ppc64x.go new file mode 100644 index 0000000000000000000000000000000000000000..c4a08fe1bd9504a00e605c119831c976ed5dc73f --- /dev/null +++ b/go/src/internal/cpu/cpu_ppc64x.go @@ -0,0 +1,35 @@ +// 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 + +package cpu + +const CacheLinePadSize = 128 + +func doinit() { + options = []option{ + {Name: "darn", Feature: &PPC64.HasDARN}, + {Name: "scv", Feature: &PPC64.HasSCV}, + {Name: "power9", Feature: &PPC64.IsPOWER9}, + } + + osinit() +} + +func isSet(hwc uint, value uint) bool { + return hwc&value != 0 +} + +func Name() string { + switch { + case PPC64.IsPOWER10: + return "POWER10" + case PPC64.IsPOWER9: + return "POWER9" + case PPC64.IsPOWER8: + return "POWER8" + } + return "" +} diff --git a/go/src/internal/cpu/cpu_ppc64x_aix.go b/go/src/internal/cpu/cpu_ppc64x_aix.go new file mode 100644 index 0000000000000000000000000000000000000000..f05ed6fad8a5e9cdf9a99fd325a40892244c95c3 --- /dev/null +++ b/go/src/internal/cpu/cpu_ppc64x_aix.go @@ -0,0 +1,25 @@ +// 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 ppc64 || ppc64le + +package cpu + +const ( + // getsystemcfg constants + _SC_IMPL = 2 + _IMPL_POWER8 = 0x10000 + _IMPL_POWER9 = 0x20000 + _IMPL_POWER10 = 0x40000 +) + +func osinit() { + impl := getsystemcfg(_SC_IMPL) + PPC64.IsPOWER8 = isSet(impl, _IMPL_POWER8) + PPC64.IsPOWER9 = isSet(impl, _IMPL_POWER9) + PPC64.IsPOWER10 = isSet(impl, _IMPL_POWER10) +} + +// getsystemcfg is defined in runtime/os2_aix.go +func getsystemcfg(label uint) uint diff --git a/go/src/internal/cpu/cpu_ppc64x_linux.go b/go/src/internal/cpu/cpu_ppc64x_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..9df82ca8a50bb9cb218ae9373c3f94d0cdf91529 --- /dev/null +++ b/go/src/internal/cpu/cpu_ppc64x_linux.go @@ -0,0 +1,33 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ppc64 || ppc64le + +package cpu + +// ppc64 doesn't have a 'cpuid' equivalent, so we rely on HWCAP/HWCAP2. +// These are initialized by archauxv and should not be changed after they are +// initialized. +var HWCap uint +var HWCap2 uint + +// HWCAP bits. These are exposed by Linux. +const ( + // ISA Level + hwcap2_ARCH_2_07 = 0x80000000 + hwcap2_ARCH_3_00 = 0x00800000 + hwcap2_ARCH_3_1 = 0x00040000 + + // CPU features + hwcap2_DARN = 0x00200000 + hwcap2_SCV = 0x00100000 +) + +func osinit() { + PPC64.IsPOWER8 = isSet(HWCap2, hwcap2_ARCH_2_07) + PPC64.IsPOWER9 = isSet(HWCap2, hwcap2_ARCH_3_00) + PPC64.IsPOWER10 = isSet(HWCap2, hwcap2_ARCH_3_1) + PPC64.HasDARN = isSet(HWCap2, hwcap2_DARN) + PPC64.HasSCV = isSet(HWCap2, hwcap2_SCV) +} diff --git a/go/src/internal/cpu/cpu_ppc64x_other.go b/go/src/internal/cpu/cpu_ppc64x_other.go new file mode 100644 index 0000000000000000000000000000000000000000..d5b629dbebb97a0df81050a8cdc59752837a7549 --- /dev/null +++ b/go/src/internal/cpu/cpu_ppc64x_other.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (ppc64 || ppc64le) && !aix && !linux + +package cpu + +func osinit() { + // Other operating systems do not support reading HWCap from auxiliary vector, + // reading privileged system registers or sysctl in user space to detect CPU + // features at runtime. +} diff --git a/go/src/internal/cpu/cpu_riscv64.go b/go/src/internal/cpu/cpu_riscv64.go new file mode 100644 index 0000000000000000000000000000000000000000..0fe1704855fa0c48be8ef2c97727837f6c6a51d4 --- /dev/null +++ b/go/src/internal/cpu/cpu_riscv64.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 cpu + +const CacheLinePadSize = 64 + +// RISC-V doesn't have a 'cpuid' equivalent. On Linux we rely on the riscv_hwprobe syscall. + +func doinit() { + options = []option{ + {Name: "fastmisaligned", Feature: &RISCV64.HasFastMisaligned}, + {Name: "v", Feature: &RISCV64.HasV}, + {Name: "zbb", Feature: &RISCV64.HasZbb}, + } + osInit() +} + +func isSet(hwc uint, value uint) bool { + return hwc&value != 0 +} diff --git a/go/src/internal/cpu/cpu_riscv64_linux.go b/go/src/internal/cpu/cpu_riscv64_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..b67bdf58766f48bd5e8caeb03b7580a95562de0a --- /dev/null +++ b/go/src/internal/cpu/cpu_riscv64_linux.go @@ -0,0 +1,93 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build riscv64 && linux + +package cpu + +import _ "unsafe" + +// RISC-V extension discovery code for Linux. +// +// A note on detection of the Vector extension using HWCAP. +// +// Support for the Vector extension version 1.0 was added to the Linux kernel in release 6.5. +// Support for the riscv_hwprobe syscall was added in 6.4. It follows that if the riscv_hwprobe +// syscall is not available then neither is the Vector extension (which needs kernel support). +// The riscv_hwprobe syscall should then be all we need to detect the Vector extension. +// However, some RISC-V board manufacturers ship boards with an older kernel on top of which +// they have back-ported various versions of the Vector extension patches but not the riscv_hwprobe +// patches. These kernels advertise support for the Vector extension using HWCAP. Falling +// back to HWCAP to detect the Vector extension, if riscv_hwprobe is not available, or simply not +// bothering with riscv_hwprobe at all and just using HWCAP may then seem like an attractive option. +// +// Unfortunately, simply checking the 'V' bit in AT_HWCAP will not work as this bit is used by +// RISC-V board and cloud instance providers to mean different things. The Lichee Pi 4A board +// and the Scaleway RV1 cloud instances use the 'V' bit to advertise their support for the unratified +// 0.7.1 version of the Vector Specification. The Banana Pi BPI-F3 and the CanMV-K230 board use +// it to advertise support for 1.0 of the Vector extension. Versions 0.7.1 and 1.0 of the Vector +// extension are binary incompatible. HWCAP can then not be used in isolation to populate the +// HasV field as this field indicates that the underlying CPU is compatible with RVV 1.0. +// Go will only support the ratified versions >= 1.0 and so any vector code it might generate +// would crash on a Scaleway RV1 instance or a Lichee Pi 4a, if allowed to run. +// +// There is a way at runtime to distinguish between versions 0.7.1 and 1.0 of the Vector +// specification by issuing a RVV 1.0 vsetvli instruction and checking the vill bit of the vtype +// register. This check would allow us to safely detect version 1.0 of the Vector extension +// with HWCAP, if riscv_hwprobe were not available. However, the check cannot +// be added until the assembler supports the Vector instructions. +// +// Note the riscv_hwprobe syscall does not suffer from these ambiguities by design as all of the +// extensions it advertises support for are explicitly versioned. It's also worth noting that +// the riscv_hwprobe syscall is the only way to detect multi-letter RISC-V extensions, e.g., Zvbb. +// These cannot be detected using HWCAP and so riscv_hwprobe must be used to detect the majority +// of RISC-V extensions. +// +// Please see https://docs.kernel.org/arch/riscv/hwprobe.html for more information. + +const ( + // Copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go. + riscv_HWPROBE_KEY_IMA_EXT_0 = 0x4 + riscv_HWPROBE_IMA_V = 0x4 + riscv_HWPROBE_EXT_ZBB = 0x10 + riscv_HWPROBE_KEY_CPUPERF_0 = 0x5 + riscv_HWPROBE_MISALIGNED_FAST = 0x3 + riscv_HWPROBE_MISALIGNED_MASK = 0x7 +) + +// riscvHWProbePairs is copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go. +type riscvHWProbePairs struct { + key int64 + value uint64 +} + +//go:linkname riscvHWProbe +func riscvHWProbe(pairs []riscvHWProbePairs, flags uint) bool + +func osInit() { + // A slice of key/value pair structures is passed to the RISCVHWProbe syscall. The key + // field should be initialised with one of the key constants defined above, e.g., + // RISCV_HWPROBE_KEY_IMA_EXT_0. The syscall will set the value field to the appropriate value. + // If the kernel does not recognise a key it will set the key field to -1 and the value field to 0. + + pairs := []riscvHWProbePairs{ + {riscv_HWPROBE_KEY_IMA_EXT_0, 0}, + {riscv_HWPROBE_KEY_CPUPERF_0, 0}, + } + + // This call only indicates that extensions are supported if they are implemented on all cores. + if !riscvHWProbe(pairs, 0) { + return + } + + if pairs[0].key != -1 { + v := uint(pairs[0].value) + RISCV64.HasV = isSet(v, riscv_HWPROBE_IMA_V) + RISCV64.HasZbb = isSet(v, riscv_HWPROBE_EXT_ZBB) + } + if pairs[1].key != -1 { + v := pairs[1].value & riscv_HWPROBE_MISALIGNED_MASK + RISCV64.HasFastMisaligned = v == riscv_HWPROBE_MISALIGNED_FAST + } +} diff --git a/go/src/internal/cpu/cpu_riscv64_other.go b/go/src/internal/cpu/cpu_riscv64_other.go new file mode 100644 index 0000000000000000000000000000000000000000..1307d822b3257f7349a0d2429004a6d93372e4cf --- /dev/null +++ b/go/src/internal/cpu/cpu_riscv64_other.go @@ -0,0 +1,11 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build riscv64 && !linux + +package cpu + +func osInit() { + // Other operating systems do not support the riscv_hwprobe syscall. +} diff --git a/go/src/internal/cpu/cpu_s390x.go b/go/src/internal/cpu/cpu_s390x.go new file mode 100644 index 0000000000000000000000000000000000000000..45d8ed27f07564ccc96c96f57008de926105ddc4 --- /dev/null +++ b/go/src/internal/cpu/cpu_s390x.go @@ -0,0 +1,205 @@ +// 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 cpu + +const CacheLinePadSize = 256 + +var HWCap uint + +// bitIsSet reports whether the bit at index is set. The bit index +// is in big endian order, so bit index 0 is the leftmost bit. +func bitIsSet(bits []uint64, index uint) bool { + return bits[index/64]&((1<<63)>>(index%64)) != 0 +} + +// function is the function code for the named function. +type function uint8 + +const ( + // KM{,A,C,CTR} function codes + aes128 function = 18 // AES-128 + aes192 function = 19 // AES-192 + aes256 function = 20 // AES-256 + + // K{I,L}MD function codes + sha1 function = 1 // SHA-1 + sha256 function = 2 // SHA-256 + sha512 function = 3 // SHA-512 + sha3_224 function = 32 // SHA3-224 + sha3_256 function = 33 // SHA3-256 + sha3_384 function = 34 // SHA3-384 + sha3_512 function = 35 // SHA3-512 + shake128 function = 36 // SHAKE-128 + shake256 function = 37 // SHAKE-256 + + // KLMD function codes + ghash function = 65 // GHASH +) + +const ( + // KDSA function codes + ecdsaVerifyP256 function = 1 // NIST P256 + ecdsaVerifyP384 function = 2 // NIST P384 + ecdsaVerifyP521 function = 3 // NIST P521 + ecdsaSignP256 function = 9 // NIST P256 + ecdsaSignP384 function = 10 // NIST P384 + ecdsaSignP521 function = 11 // NIST P521 + eddsaVerifyEd25519 function = 32 // Curve25519 + eddsaVerifyEd448 function = 36 // Curve448 + eddsaSignEd25519 function = 40 // Curve25519 + eddsaSignEd448 function = 44 // Curve448 +) + +// queryResult contains the result of a Query function +// call. Bits are numbered in big endian order so the +// leftmost bit (the MSB) is at index 0. +type queryResult struct { + bits [2]uint64 +} + +// Has reports whether the given functions are present. +func (q *queryResult) Has(fns ...function) bool { + if len(fns) == 0 { + panic("no function codes provided") + } + for _, f := range fns { + if !bitIsSet(q.bits[:], uint(f)) { + return false + } + } + return true +} + +// facility is a bit index for the named facility. +type facility uint8 + +const ( + // mandatory facilities + zarch facility = 1 // z architecture mode is active + stflef facility = 7 // store-facility-list-extended + ldisp facility = 18 // long-displacement + eimm facility = 21 // extended-immediate + + // miscellaneous facilities + dfp facility = 42 // decimal-floating-point + etf3eh facility = 30 // extended-translation 3 enhancement + + // cryptography facilities + msa facility = 17 // message-security-assist + msa3 facility = 76 // message-security-assist extension 3 + msa4 facility = 77 // message-security-assist extension 4 + msa5 facility = 57 // message-security-assist extension 5 + msa8 facility = 146 // message-security-assist extension 8 + msa9 facility = 155 // message-security-assist extension 9 + + // vector facilities + vxe facility = 135 // vector-enhancements 1 + + // Note: vx requires kernel support + // and so must be fetched from HWCAP. + + hwcap_VX = 1 << 11 // vector facility +) + +// facilityList contains the result of an STFLE call. +// Bits are numbered in big endian order so the +// leftmost bit (the MSB) is at index 0. +type facilityList struct { + bits [4]uint64 +} + +// Has reports whether the given facilities are present. +func (s *facilityList) Has(fs ...facility) bool { + if len(fs) == 0 { + panic("no facility bits provided") + } + for _, f := range fs { + if !bitIsSet(s.bits[:], uint(f)) { + return false + } + } + return true +} + +// The following feature detection functions are defined in cpu_s390x.s. +// They are likely to be expensive to call so the results should be cached. +func stfle() facilityList +func kmQuery() queryResult +func kmcQuery() queryResult +func kmctrQuery() queryResult +func kmaQuery() queryResult +func kimdQuery() queryResult +func klmdQuery() queryResult +func kdsaQuery() queryResult + +func doinit() { + options = []option{ + {Name: "zarch", Feature: &S390X.HasZARCH}, + {Name: "stfle", Feature: &S390X.HasSTFLE}, + {Name: "ldisp", Feature: &S390X.HasLDISP}, + {Name: "msa", Feature: &S390X.HasMSA}, + {Name: "eimm", Feature: &S390X.HasEIMM}, + {Name: "dfp", Feature: &S390X.HasDFP}, + {Name: "etf3eh", Feature: &S390X.HasETF3EH}, + {Name: "vx", Feature: &S390X.HasVX}, + {Name: "vxe", Feature: &S390X.HasVXE}, + {Name: "kdsa", Feature: &S390X.HasKDSA}, + } + + aes := []function{aes128, aes192, aes256} + facilities := stfle() + + S390X.HasZARCH = facilities.Has(zarch) + S390X.HasSTFLE = facilities.Has(stflef) + S390X.HasLDISP = facilities.Has(ldisp) + S390X.HasEIMM = facilities.Has(eimm) + S390X.HasDFP = facilities.Has(dfp) + S390X.HasETF3EH = facilities.Has(etf3eh) + S390X.HasMSA = facilities.Has(msa) + + if S390X.HasMSA { + // cipher message + km, kmc := kmQuery(), kmcQuery() + S390X.HasAES = km.Has(aes...) + S390X.HasAESCBC = kmc.Has(aes...) + if facilities.Has(msa4) { + kmctr := kmctrQuery() + S390X.HasAESCTR = kmctr.Has(aes...) + } + if facilities.Has(msa8) { + kma := kmaQuery() + S390X.HasAESGCM = kma.Has(aes...) + } + + // compute message digest + kimd := kimdQuery() // intermediate (no padding) + klmd := klmdQuery() // last (padding) + S390X.HasSHA1 = kimd.Has(sha1) && klmd.Has(sha1) + S390X.HasSHA256 = kimd.Has(sha256) && klmd.Has(sha256) + S390X.HasSHA512 = kimd.Has(sha512) && klmd.Has(sha512) + S390X.HasGHASH = kimd.Has(ghash) // KLMD-GHASH does not exist + sha3 := []function{ + sha3_224, sha3_256, sha3_384, sha3_512, + shake128, shake256, + } + S390X.HasSHA3 = kimd.Has(sha3...) && klmd.Has(sha3...) + S390X.HasKDSA = facilities.Has(msa9) // elliptic curves + if S390X.HasKDSA { + kdsa := kdsaQuery() + S390X.HasECDSA = kdsa.Has(ecdsaVerifyP256, ecdsaSignP256, ecdsaVerifyP384, ecdsaSignP384, ecdsaVerifyP521, ecdsaSignP521) + S390X.HasEDDSA = kdsa.Has(eddsaVerifyEd25519, eddsaSignEd25519, eddsaVerifyEd448, eddsaSignEd448) + } + } + + S390X.HasVX = isSet(HWCap, hwcap_VX) + + if S390X.HasVX { + S390X.HasVXE = facilities.Has(vxe) + } +} + +func isSet(hwc uint, value uint) bool { + return hwc&value != 0 +} diff --git a/go/src/internal/cpu/cpu_s390x.s b/go/src/internal/cpu/cpu_s390x.s new file mode 100644 index 0000000000000000000000000000000000000000..4ffbbde38dd3d0549f4b855c425bff17cd1ee21e --- /dev/null +++ b/go/src/internal/cpu/cpu_s390x.s @@ -0,0 +1,63 @@ +// 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" + +// func stfle() facilityList +TEXT ·stfle(SB), NOSPLIT|NOFRAME, $0-32 + MOVD $ret+0(FP), R1 + MOVD $3, R0 // last doubleword index to store + XC $32, (R1), (R1) // clear 4 doublewords (32 bytes) + WORD $0xb2b01000 // store facility list extended (STFLE) + RET + +// func kmQuery() queryResult +TEXT ·kmQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KM-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KM R2, R4 // cipher message (KM) + RET + +// func kmcQuery() queryResult +TEXT ·kmcQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KMC-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KMC R2, R4 // cipher message with chaining (KMC) + RET + +// func kmctrQuery() queryResult +TEXT ·kmctrQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KMCTR-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KMCTR R2, R4, R4 // cipher message with counter (KMCTR) + RET + +// func kmaQuery() queryResult +TEXT ·kmaQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KMA-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KMA R2, R6, R4 // cipher message with authentication (KMA) + RET + +// func kimdQuery() queryResult +TEXT ·kimdQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KIMD-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KIMD R2, R4 // compute intermediate message digest (KIMD) + RET + +// func klmdQuery() queryResult +TEXT ·klmdQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KLMD-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KLMD R2, R4 // compute last message digest (KLMD) + RET + +// func kdsaQuery() queryResult +TEXT ·kdsaQuery(SB), NOSPLIT|NOFRAME, $0-16 + MOVD $0, R0 // set function code to 0 (KLMD-Query) + MOVD $ret+0(FP), R1 // address of 16-byte return value + KDSA R0, R4 // compute digital signature authentication + RET + diff --git a/go/src/internal/cpu/cpu_s390x_test.go b/go/src/internal/cpu/cpu_s390x_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ad86858db01dc0ad242a3d82503b1341ecd09f37 --- /dev/null +++ b/go/src/internal/cpu/cpu_s390x_test.go @@ -0,0 +1,63 @@ +// 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 cpu_test + +import ( + "errors" + . "internal/cpu" + "os" + "regexp" + "testing" +) + +func getFeatureList() ([]string, error) { + cpuinfo, err := os.ReadFile("/proc/cpuinfo") + if err != nil { + return nil, err + } + r := regexp.MustCompile("features\\s*:\\s*(.*)") + b := r.FindSubmatch(cpuinfo) + if len(b) < 2 { + return nil, errors.New("no feature list in /proc/cpuinfo") + } + return regexp.MustCompile("\\s+").Split(string(b[1]), -1), nil +} + +func TestS390XAgainstCPUInfo(t *testing.T) { + // mapping of linux feature strings to S390X fields + mapping := make(map[string]*bool) + for _, option := range Options { + mapping[option.Name] = option.Feature + } + + // these must be true on the machines Go supports + mandatory := make(map[string]bool) + mandatory["zarch"] = false + mandatory["eimm"] = false + mandatory["ldisp"] = false + mandatory["stfle"] = false + + features, err := getFeatureList() + if err != nil { + t.Error(err) + } + for _, feature := range features { + if _, ok := mandatory[feature]; ok { + mandatory[feature] = true + } + if flag, ok := mapping[feature]; ok { + if !*flag { + t.Errorf("feature '%v' not detected", feature) + } + } else { + t.Logf("no entry for '%v'", feature) + } + } + for k, v := range mandatory { + if !v { + t.Errorf("mandatory feature '%v' not detected", k) + } + } +} diff --git a/go/src/internal/cpu/cpu_test.go b/go/src/internal/cpu/cpu_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62e250d1e820061359f9de1821182e74fffec1c2 --- /dev/null +++ b/go/src/internal/cpu/cpu_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 cpu_test + +import ( + . "internal/cpu" + "internal/godebug" + "internal/testenv" + "os/exec" + "runtime" + "testing" +) + +func MustHaveDebugOptionsSupport(t *testing.T) { + switch runtime.GOOS { + case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux": + default: + t.Skipf("skipping test: cpu feature options not supported by OS") + } +} + +func MustSupportFeatureDetection(t *testing.T) { + // TODO: add platforms that do not have CPU feature detection support. +} + +func runDebugOptionsTest(t *testing.T, test string, options string) { + MustHaveDebugOptionsSupport(t) + + env := "GODEBUG=" + options + + cmd := exec.Command(testenv.Executable(t), "-test.run=^"+test+"$") + cmd.Env = append(cmd.Env, env) + + output, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%s with %s: run failed: %v output:\n%s\n", + test, env, err, string(output)) + } +} + +func TestDisableAllCapabilities(t *testing.T) { + MustSupportFeatureDetection(t) + runDebugOptionsTest(t, "TestAllCapabilitiesDisabled", "cpu.all=off") +} + +func TestAllCapabilitiesDisabled(t *testing.T) { + MustHaveDebugOptionsSupport(t) + + if godebug.New("#cpu.all").Value() != "off" { + t.Skipf("skipping test: GODEBUG=cpu.all=off not set") + } + + for _, o := range Options { + want := false + if got := *o.Feature; got != want { + t.Errorf("%v: expected %v, got %v", o.Name, want, got) + } + } +} diff --git a/go/src/internal/cpu/cpu_wasm.go b/go/src/internal/cpu/cpu_wasm.go new file mode 100644 index 0000000000000000000000000000000000000000..2310ad6a4818b9979bfc6ccb6993afb8493a8577 --- /dev/null +++ b/go/src/internal/cpu/cpu_wasm.go @@ -0,0 +1,10 @@ +// 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 cpu + +const CacheLinePadSize = 64 + +func doinit() { +} diff --git a/go/src/internal/cpu/cpu_x86.go b/go/src/internal/cpu/cpu_x86.go new file mode 100644 index 0000000000000000000000000000000000000000..3c0a0adf2888376116d232ae0c432b4aec439632 --- /dev/null +++ b/go/src/internal/cpu/cpu_x86.go @@ -0,0 +1,279 @@ +// 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 386 || amd64 + +package cpu + +const CacheLinePadSize = 64 + +// cpuid is implemented in cpu_x86.s. +func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) + +// xgetbv with ecx = 0 is implemented in cpu_x86.s. +func xgetbv() (eax, edx uint32) + +// getGOAMD64level is implemented in cpu_x86.s. Returns number in [1,4]. +func getGOAMD64level() int32 + +const ( + // eax bits + cpuid_AVXVNNI = 1 << 4 + + // ecx bits + cpuid_SSE3 = 1 << 0 + cpuid_PCLMULQDQ = 1 << 1 + cpuid_AVX512VBMI = 1 << 1 + cpuid_AVX512VBMI2 = 1 << 6 + cpuid_SSSE3 = 1 << 9 + cpuid_AVX512GFNI = 1 << 8 + cpuid_VAES = 1 << 9 + cpuid_AVX512VNNI = 1 << 11 + cpuid_AVX512BITALG = 1 << 12 + cpuid_FMA = 1 << 12 + cpuid_AVX512VPOPCNTDQ = 1 << 14 + cpuid_SSE41 = 1 << 19 + cpuid_SSE42 = 1 << 20 + cpuid_POPCNT = 1 << 23 + cpuid_AES = 1 << 25 + cpuid_OSXSAVE = 1 << 27 + cpuid_AVX = 1 << 28 + + // "Extended Feature Flag" bits returned in EBX for CPUID EAX=0x7 ECX=0x0 + cpuid_BMI1 = 1 << 3 + cpuid_AVX2 = 1 << 5 + cpuid_BMI2 = 1 << 8 + cpuid_ERMS = 1 << 9 + cpuid_AVX512F = 1 << 16 + cpuid_AVX512DQ = 1 << 17 + cpuid_ADX = 1 << 19 + cpuid_AVX512CD = 1 << 28 + cpuid_SHA = 1 << 29 + cpuid_AVX512BW = 1 << 30 + cpuid_AVX512VL = 1 << 31 + + // "Extended Feature Flag" bits returned in ECX for CPUID EAX=0x7 ECX=0x0 + cpuid_AVX512_VBMI = 1 << 1 + cpuid_AVX512_VBMI2 = 1 << 6 + cpuid_GFNI = 1 << 8 + cpuid_AVX512VPCLMULQDQ = 1 << 10 + cpuid_AVX512_BITALG = 1 << 12 + + // edx bits + cpuid_FSRM = 1 << 4 + // edx bits for CPUID 0x80000001 + cpuid_RDTSCP = 1 << 27 +) + +var maxExtendedFunctionInformation uint32 + +func doinit() { + options = []option{ + {Name: "adx", Feature: &X86.HasADX}, + {Name: "aes", Feature: &X86.HasAES}, + {Name: "erms", Feature: &X86.HasERMS}, + {Name: "fsrm", Feature: &X86.HasFSRM}, + {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, + {Name: "rdtscp", Feature: &X86.HasRDTSCP}, + {Name: "sha", Feature: &X86.HasSHA}, + {Name: "vpclmulqdq", Feature: &X86.HasAVX512VPCLMULQDQ}, + } + level := getGOAMD64level() + if level < 2 { + // These options are required at level 2. At lower levels + // they can be turned off. + options = append(options, + option{Name: "popcnt", Feature: &X86.HasPOPCNT}, + option{Name: "sse3", Feature: &X86.HasSSE3}, + option{Name: "sse41", Feature: &X86.HasSSE41}, + option{Name: "sse42", Feature: &X86.HasSSE42}, + option{Name: "ssse3", Feature: &X86.HasSSSE3}) + } + if level < 3 { + // These options are required at level 3. At lower levels + // they can be turned off. + options = append(options, + option{Name: "avx", Feature: &X86.HasAVX}, + option{Name: "avx2", Feature: &X86.HasAVX2}, + option{Name: "bmi1", Feature: &X86.HasBMI1}, + option{Name: "bmi2", Feature: &X86.HasBMI2}, + option{Name: "fma", Feature: &X86.HasFMA}) + } + if level < 4 { + // These options are required at level 4. At lower levels + // they can be turned off. + options = append(options, + option{Name: "avx512f", Feature: &X86.HasAVX512F}, + option{Name: "avx512cd", Feature: &X86.HasAVX512CD}, + option{Name: "avx512bw", Feature: &X86.HasAVX512BW}, + option{Name: "avx512dq", Feature: &X86.HasAVX512DQ}, + option{Name: "avx512vl", Feature: &X86.HasAVX512VL}, + ) + } + + maxID, _, _, _ := cpuid(0, 0) + + if maxID < 1 { + osInit() + return + } + + maxExtendedFunctionInformation, _, _, _ = cpuid(0x80000000, 0) + + _, _, ecx1, _ := cpuid(1, 0) + + X86.HasSSE3 = isSet(ecx1, cpuid_SSE3) + X86.HasPCLMULQDQ = isSet(ecx1, cpuid_PCLMULQDQ) + X86.HasSSSE3 = isSet(ecx1, cpuid_SSSE3) + X86.HasSSE41 = isSet(ecx1, cpuid_SSE41) + X86.HasSSE42 = isSet(ecx1, cpuid_SSE42) + X86.HasPOPCNT = isSet(ecx1, cpuid_POPCNT) + X86.HasAES = isSet(ecx1, cpuid_AES) + + // OSXSAVE can be false when using older Operating Systems + // or when explicitly disabled on newer Operating Systems by + // e.g. setting the xsavedisable boot option on Windows 10. + X86.HasOSXSAVE = isSet(ecx1, cpuid_OSXSAVE) + + osSupportsAVX := false + osSupportsAVX512 := false + // For XGETBV, OSXSAVE bit is required and sufficient. + if X86.HasOSXSAVE { + eax, _ := xgetbv() + // Check if XMM and YMM registers have OS support. + osSupportsAVX = isSet(eax, 1<<1) && isSet(eax, 1<<2) + + // AVX512 detection does not work on Darwin, + // see https://github.com/golang/go/issues/49233 + // + // Check if opmask, ZMMhi256 and Hi16_ZMM have OS support. + osSupportsAVX512 = osSupportsAVX && isSet(eax, 1<<5) && isSet(eax, 1<<6) && isSet(eax, 1<<7) + } + + X86.HasAVX = isSet(ecx1, cpuid_AVX) && osSupportsAVX + + // The FMA instruction set extension requires both the FMA and AVX flags. + // + // Furthermore, the FMA instructions are all VEX prefixed instructions. + // VEX prefixed instructions require OSXSAVE to be enabled. + // See Intel 64 and IA-32 Architecture Software Developer’s Manual Volume 2 + // Section 2.4 "AVX and SSE Instruction Exception Specification" + X86.HasFMA = isSet(ecx1, cpuid_FMA) && X86.HasAVX && X86.HasOSXSAVE + + if maxID < 7 { + osInit() + return + } + + eax7, ebx7, ecx7, edx7 := cpuid(7, 0) + X86.HasBMI1 = isSet(ebx7, cpuid_BMI1) + X86.HasAVX2 = isSet(ebx7, cpuid_AVX2) && osSupportsAVX + X86.HasBMI2 = isSet(ebx7, cpuid_BMI2) + X86.HasERMS = isSet(ebx7, cpuid_ERMS) + X86.HasADX = isSet(ebx7, cpuid_ADX) + X86.HasSHA = isSet(ebx7, cpuid_SHA) + X86.HasVAES = isSet(ecx7, cpuid_VAES) && X86.HasAVX + + X86.HasAVX512F = isSet(ebx7, cpuid_AVX512F) && osSupportsAVX512 + if X86.HasAVX512F { + X86.HasAVX512CD = isSet(ebx7, cpuid_AVX512CD) + X86.HasAVX512BW = isSet(ebx7, cpuid_AVX512BW) + X86.HasAVX512DQ = isSet(ebx7, cpuid_AVX512DQ) + X86.HasAVX512VL = isSet(ebx7, cpuid_AVX512VL) + X86.HasAVX512GFNI = isSet(ecx7, cpuid_AVX512GFNI) + X86.HasAVX512BITALG = isSet(ecx7, cpuid_AVX512BITALG) + X86.HasAVX512VPOPCNTDQ = isSet(ecx7, cpuid_AVX512VPOPCNTDQ) + X86.HasAVX512VBMI = isSet(ecx7, cpuid_AVX512VBMI) + X86.HasAVX512VBMI2 = isSet(ecx7, cpuid_AVX512VBMI2) + X86.HasAVX512VAES = isSet(ecx7, cpuid_VAES) && X86.HasAES && isSet(ebx7, cpuid_AVX512VL) + X86.HasAVX512VNNI = isSet(ecx7, cpuid_AVX512VNNI) + X86.HasAVX512VPCLMULQDQ = isSet(ecx7, cpuid_AVX512VPCLMULQDQ) + X86.HasAVX512VBMI = isSet(ecx7, cpuid_AVX512_VBMI) + X86.HasAVX512VBMI2 = isSet(ecx7, cpuid_AVX512_VBMI2) + X86.HasGFNI = isSet(ecx7, cpuid_GFNI) + X86.HasAVX512BITALG = isSet(ecx7, cpuid_AVX512_BITALG) + } + + X86.HasFSRM = isSet(edx7, cpuid_FSRM) + + var maxExtendedInformation uint32 + maxExtendedInformation, _, _, _ = cpuid(0x80000000, 0) + + if maxExtendedInformation < 0x80000001 { + osInit() + return + } + + _, _, _, edxExt1 := cpuid(0x80000001, 0) + X86.HasRDTSCP = isSet(edxExt1, cpuid_RDTSCP) + + doDerived = func() { + // Rather than carefully gating on fundamental AVX-512 features, we have + // a virtual "AVX512" feature that captures F+CD+BW+DQ+VL. BW, DQ, and + // VL have a huge effect on which AVX-512 instructions are available, + // and these have all been supported on everything except the earliest + // Phi chips with AVX-512. No CPU has had CD without F, so we include + // it. GOAMD64=v4 also implies exactly this set, and these are all + // included in AVX10.1. + X86.HasAVX512 = X86.HasAVX512F && X86.HasAVX512CD && X86.HasAVX512BW && X86.HasAVX512DQ && X86.HasAVX512VL + } + + if eax7 >= 1 { + eax71, _, _, _ := cpuid(7, 1) + if X86.HasAVX { + X86.HasAVXVNNI = isSet(eax71, cpuid_AVXVNNI) + } + } + + osInit() +} + +func isSet(hwc uint32, value uint32) bool { + return hwc&value != 0 +} + +// Name returns the CPU name given by the vendor. +// If the CPU name can not be determined an +// empty string is returned. +func Name() string { + if maxExtendedFunctionInformation < 0x80000004 { + return "" + } + + data := make([]byte, 0, 3*4*4) + + var eax, ebx, ecx, edx uint32 + eax, ebx, ecx, edx = cpuid(0x80000002, 0) + data = appendBytes(data, eax, ebx, ecx, edx) + eax, ebx, ecx, edx = cpuid(0x80000003, 0) + data = appendBytes(data, eax, ebx, ecx, edx) + eax, ebx, ecx, edx = cpuid(0x80000004, 0) + data = appendBytes(data, eax, ebx, ecx, edx) + + // Trim leading spaces. + for len(data) > 0 && data[0] == ' ' { + data = data[1:] + } + + // Trim tail after and including the first null byte. + for i, c := range data { + if c == '\x00' { + data = data[:i] + break + } + } + + return string(data) +} + +func appendBytes(b []byte, args ...uint32) []byte { + for _, arg := range args { + b = append(b, + byte((arg >> 0)), + byte((arg >> 8)), + byte((arg >> 16)), + byte((arg >> 24))) + } + return b +} diff --git a/go/src/internal/cpu/cpu_x86.s b/go/src/internal/cpu/cpu_x86.s new file mode 100644 index 0000000000000000000000000000000000000000..2ee8eca248a614ad3840bdf3f138b9d3651064d1 --- /dev/null +++ b/go/src/internal/cpu/cpu_x86.s @@ -0,0 +1,43 @@ +// 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 386 || amd64 + +#include "textflag.h" + +// func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) +TEXT ·cpuid(SB), NOSPLIT, $0-24 + MOVL eaxArg+0(FP), AX + MOVL ecxArg+4(FP), CX + CPUID + MOVL AX, eax+8(FP) + MOVL BX, ebx+12(FP) + MOVL CX, ecx+16(FP) + MOVL DX, edx+20(FP) + RET + +// func xgetbv() (eax, edx uint32) +TEXT ·xgetbv(SB),NOSPLIT,$0-8 + MOVL $0, CX + XGETBV + MOVL AX, eax+0(FP) + MOVL DX, edx+4(FP) + RET + +// func getGOAMD64level() int32 +TEXT ·getGOAMD64level(SB),NOSPLIT,$0-4 +#ifdef GOAMD64_v4 + MOVL $4, ret+0(FP) +#else +#ifdef GOAMD64_v3 + MOVL $3, ret+0(FP) +#else +#ifdef GOAMD64_v2 + MOVL $2, ret+0(FP) +#else + MOVL $1, ret+0(FP) +#endif +#endif +#endif + RET diff --git a/go/src/internal/cpu/cpu_x86_darwin.go b/go/src/internal/cpu/cpu_x86_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..12380a7802c81930efa9e9b723e038e60b6716e1 --- /dev/null +++ b/go/src/internal/cpu/cpu_x86_darwin.go @@ -0,0 +1,23 @@ +// Copyright 2025 The Go 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) && darwin && !ios + +package cpu + +func osInit() { + if isRosetta() && darwinKernelVersionCheck(24, 0, 0) { + // Apparently, on macOS 15 (Darwin kernel version 24) or newer, + // Rosetta 2 supports AVX1 and 2. However, neither CPUID nor + // sysctl says it has AVX. Detect this situation here and report + // AVX1 and 2 as supported. + // TODO: check if any other feature is actually supported. + X86.HasAVX = true + X86.HasAVX2 = true + } +} + +func isRosetta() bool { + return sysctlEnabled([]byte("sysctl.proc_translated\x00")) +} diff --git a/go/src/internal/cpu/cpu_x86_other.go b/go/src/internal/cpu/cpu_x86_other.go new file mode 100644 index 0000000000000000000000000000000000000000..824131226c643ecc5cf3bebdda7174af63ea6bee --- /dev/null +++ b/go/src/internal/cpu/cpu_x86_other.go @@ -0,0 +1,9 @@ +// Copyright 2025 The Go 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) && (!darwin || ios) + +package cpu + +func osInit() {} diff --git a/go/src/internal/cpu/cpu_x86_test.go b/go/src/internal/cpu/cpu_x86_test.go new file mode 100644 index 0000000000000000000000000000000000000000..cc6552bae8542ccd46e7b096ed985e3716ff5f84 --- /dev/null +++ b/go/src/internal/cpu/cpu_x86_test.go @@ -0,0 +1,57 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build 386 || amd64 + +package cpu_test + +import ( + . "internal/cpu" + "internal/godebug" + "testing" +) + +func TestX86ifAVX2hasAVX(t *testing.T) { + if X86.HasAVX2 && !X86.HasAVX { + t.Fatalf("HasAVX expected true when HasAVX2 is true, got false") + } +} + +func TestX86ifAVX512FhasAVX2(t *testing.T) { + if X86.HasAVX512F && !X86.HasAVX2 { + t.Fatalf("HasAVX2 expected true when HasAVX512F is true, got false") + } +} + +func TestX86ifAVX512BWhasAVX512F(t *testing.T) { + if X86.HasAVX512BW && !X86.HasAVX512F { + t.Fatalf("HasAVX512F expected true when HasAVX512BW is true, got false") + } +} + +func TestX86ifAVX512VLhasAVX512F(t *testing.T) { + if X86.HasAVX512VL && !X86.HasAVX512F { + t.Fatalf("HasAVX512F expected true when HasAVX512VL is true, got false") + } +} + +func TestDisableSSE3(t *testing.T) { + if GetGOAMD64level() > 1 { + t.Skip("skipping test: can't run on GOAMD64>v1 machines") + } + runDebugOptionsTest(t, "TestSSE3DebugOption", "cpu.sse3=off") +} + +func TestSSE3DebugOption(t *testing.T) { + MustHaveDebugOptionsSupport(t) + + if godebug.New("#cpu.sse3").Value() != "off" { + t.Skipf("skipping test: GODEBUG=cpu.sse3=off not set") + } + + want := false + if got := X86.HasSSE3; got != want { + t.Errorf("X86.HasSSE3 expected %v, got %v", want, got) + } +} diff --git a/go/src/internal/cpu/datacache_unsupported.go b/go/src/internal/cpu/datacache_unsupported.go new file mode 100644 index 0000000000000000000000000000000000000000..44544aa8c9e5be409b75b1a6b42bad597f68bb4e --- /dev/null +++ b/go/src/internal/cpu/datacache_unsupported.go @@ -0,0 +1,11 @@ +// Copyright 2025 The Go 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 cpu + +func DataCacheSizes() []uintptr { + return nil +} diff --git a/go/src/internal/cpu/datacache_x86.go b/go/src/internal/cpu/datacache_x86.go new file mode 100644 index 0000000000000000000000000000000000000000..eb7b93b0a263924d86be0db1285eff33d8933278 --- /dev/null +++ b/go/src/internal/cpu/datacache_x86.go @@ -0,0 +1,121 @@ +// Copyright 2025 The Go 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 cpu + +// DataCacheSizes returns the size of each data cache from lowest +// level in the hierarchy to highest. +// +// Unlike other parts of this package's public API, it is not safe +// to reference early in runtime initialization because it allocates. +// It's intended for testing only. +func DataCacheSizes() []uintptr { + maxFunctionInformation, ebx0, ecx0, edx0 := cpuid(0, 0) + if maxFunctionInformation < 1 { + return nil + } + + switch { + // Check for "GenuineIntel" + case ebx0 == 0x756E6547 && ecx0 == 0x6C65746E && edx0 == 0x49656E69: + return getDataCacheSizesIntel(maxFunctionInformation) + // Check for "AuthenticAMD" + case ebx0 == 0x68747541 && ecx0 == 0x444D4163 && edx0 == 0x69746E65: + return getDataCacheSizesAMD() + } + return nil +} + +func extractBits(arg uint32, l int, r int) uint32 { + if l > r { + panic("bad bit range") + } + return (arg >> l) & ((1 << (r - l + 1)) - 1) +} + +func getDataCacheSizesIntel(maxID uint32) []uintptr { + // Constants for cache types + const ( + noCache = 0 + dataCache = 1 + instructionCache = 2 + unifiedCache = 3 + ) + if maxID < 4 { + return nil + } + + // Iterate through CPUID leaf 4 (deterministic cache parameters) + var caches []uintptr + for i := uint32(0); i < 0xFFFF; i++ { + eax, ebx, ecx, _ := cpuid(4, i) + + cacheType := eax & 0xF // EAX bits 4-0: Cache Type + if cacheType == 0 { + break + } + + // Report only data caches. + if !(cacheType == dataCache || cacheType == unifiedCache) { + continue + } + + // Guaranteed to always start counting from 1. + level := (eax >> 5) & 0x7 + + lineSize := extractBits(ebx, 0, 11) + 1 // Bits 11-0: Line size in bytes - 1 + partitions := extractBits(ebx, 12, 21) + 1 // Bits 21-12: Physical line partitions - 1 + ways := extractBits(ebx, 22, 31) + 1 // Bits 31-22: Ways of associativity - 1 + sets := uint64(ecx) + 1 // Number of sets - 1 + size := uint64(ways*partitions*lineSize) * sets // Calculate cache size in bytes + + caches = append(caches, uintptr(size)) + + // If we see more than one cache described per level, or they appear + // out of order, crash. + // + // Going by the SDM, it's not clear whether this is actually possible, + // so this code is purely defensive. + if level != uint32(len(caches)) { + panic("expected levels to be in order and for there to be one data/unified cache per level") + } + } + return caches +} + +func getDataCacheSizesAMD() []uintptr { + maxExtendedFunctionInformation, _, _, _ := cpuid(0x80000000, 0) + if maxExtendedFunctionInformation < 0x80000006 { + return nil + } + + var caches []uintptr + + _, _, ecx5, _ := cpuid(0x80000005, 0) + _, _, ecx6, edx6 := cpuid(0x80000006, 0) + + // The size is return in kb, turning into bytes. + l1dSize := uintptr(extractBits(ecx5, 24, 31) << 10) + caches = append(caches, l1dSize) + + // Check that L2 cache is present. + if l2Assoc := extractBits(ecx6, 12, 15); l2Assoc == 0 { + return caches + } + l2Size := uintptr(extractBits(ecx6, 16, 31) << 10) + caches = append(caches, l2Size) + + // Check that L3 cache is present. + if l3Assoc := extractBits(edx6, 12, 15); l3Assoc == 0 { + return caches + } + // Specifies the L3 cache size is within the following range: + // (L3Size[31:18] * 512KB) <= L3 cache size < ((L3Size[31:18]+1) * 512KB). + l3Size := uintptr(extractBits(edx6, 18, 31) * (512 << 10)) + caches = append(caches, l3Size) + + return caches +} diff --git a/go/src/internal/cpu/datacache_x86_test.go b/go/src/internal/cpu/datacache_x86_test.go new file mode 100644 index 0000000000000000000000000000000000000000..425c525be099f0b7c579ec50f317e7c9294d756a --- /dev/null +++ b/go/src/internal/cpu/datacache_x86_test.go @@ -0,0 +1,26 @@ +// Copyright 2025 The Go 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 cpu_test + +import ( + "internal/cpu" + "testing" +) + +// Tests fetching data cache sizes. This test only checks that DataCacheSizes +// won't explode. Otherwise it's just informational, and dumps the current +// data cache sizes. +func TestDataCacheSizes(t *testing.T) { + // N.B. Don't try to check these values because we don't know what + // kind of environment we're running in. We don't want this test to + // fail on some random x86 chip that happens to not support the right + // CPUID bits for some reason. + caches := cpu.DataCacheSizes() + for i, size := range caches { + t.Logf("L%d: %d", i+1, size) + } +} diff --git a/go/src/internal/cpu/export_test.go b/go/src/internal/cpu/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..91bfc1bbc3b35c011261029a6d2791b7b773042b --- /dev/null +++ b/go/src/internal/cpu/export_test.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 cpu + +var ( + Options = options +) diff --git a/go/src/internal/cpu/export_x86_test.go b/go/src/internal/cpu/export_x86_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a12b6f27234a8e9179ff9a64aa325c428ebb7ca0 --- /dev/null +++ b/go/src/internal/cpu/export_x86_test.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build 386 || amd64 + +package cpu + +var ( + GetGOAMD64level = getGOAMD64level +) diff --git a/go/src/internal/dag/alg.go b/go/src/internal/dag/alg.go new file mode 100644 index 0000000000000000000000000000000000000000..88002797c02a04ce4f9dad32b8f91d9daf6c9b9b --- /dev/null +++ b/go/src/internal/dag/alg.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 dag + +// Transpose reverses all edges in g. +func (g *Graph) Transpose() { + old := g.edges + + g.edges = make(map[string]map[string]bool) + for _, n := range g.Nodes { + g.edges[n] = make(map[string]bool) + } + + for from, tos := range old { + for to := range tos { + g.edges[to][from] = true + } + } +} + +// Topo returns a topological sort of g. This function is deterministic. +func (g *Graph) Topo() []string { + topo := make([]string, 0, len(g.Nodes)) + marks := make(map[string]bool) + + var visit func(n string) + visit = func(n string) { + if marks[n] { + return + } + for _, to := range g.Edges(n) { + visit(to) + } + marks[n] = true + topo = append(topo, n) + } + for _, root := range g.Nodes { + visit(root) + } + for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 { + topo[i], topo[j] = topo[j], topo[i] + } + return topo +} + +// TransitiveReduction removes edges from g that are transitively +// reachable. g must be transitively closed. +func (g *Graph) TransitiveReduction() { + // For i -> j -> k, if i -> k exists, delete it. + for _, i := range g.Nodes { + for _, j := range g.Nodes { + if g.HasEdge(i, j) { + for _, k := range g.Nodes { + if g.HasEdge(j, k) { + g.DelEdge(i, k) + } + } + } + } + } +} diff --git a/go/src/internal/dag/alg_test.go b/go/src/internal/dag/alg_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0659eb18e3476990176654365982aa558d8b3047 --- /dev/null +++ b/go/src/internal/dag/alg_test.go @@ -0,0 +1,46 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package dag + +import ( + "slices" + "strings" + "testing" +) + +func TestTranspose(t *testing.T) { + g := mustParse(t, diamond) + g.Transpose() + wantEdges(t, g, "a->b a->c a->d b->d c->d") +} + +func TestTopo(t *testing.T) { + g := mustParse(t, diamond) + got := g.Topo() + // "d" is the root, so it's first. + // + // "c" and "b" could be in either order, but Topo is + // deterministic in reverse node definition order. + // + // "a" is a leaf. + wantNodes := strings.Fields("d c b a") + if !slices.Equal(wantNodes, got) { + t.Fatalf("want topo sort %v, got %v", wantNodes, got) + } +} + +func TestTransitiveReduction(t *testing.T) { + t.Run("diamond", func(t *testing.T) { + g := mustParse(t, diamond) + g.TransitiveReduction() + wantEdges(t, g, "b->a c->a d->b d->c") + }) + t.Run("chain", func(t *testing.T) { + const chain = `NONE < a < b < c < d; a, d < e;` + g := mustParse(t, chain) + g.TransitiveReduction() + wantEdges(t, g, "e->d d->c c->b b->a") + }) +} diff --git a/go/src/internal/dag/parse.go b/go/src/internal/dag/parse.go new file mode 100644 index 0000000000000000000000000000000000000000..409f0b887eb225dd0bb071f4fcf6d3f4bbfa36d8 --- /dev/null +++ b/go/src/internal/dag/parse.go @@ -0,0 +1,317 @@ +// 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 dag implements a language for expressing directed acyclic +// graphs. +// +// The general syntax of a rule is: +// +// a, b < c, d; +// +// which means c and d come after a and b in the partial order +// (that is, there are edges from c and d to a and b), +// but doesn't provide a relative order between a vs b or c vs d. +// +// The rules can chain together, as in: +// +// e < f, g < h; +// +// which is equivalent to +// +// e < f, g; +// f, g < h; +// +// Except for the special bottom element "NONE", each name +// must appear exactly once on the right-hand side of any rule. +// That rule serves as the definition of the allowed successor +// for that name. The definition must appear before any uses +// of the name on the left-hand side of a rule. (That is, the +// rules themselves must be ordered according to the partial +// order, for easier reading by people.) +// +// Negative assertions double-check the partial order: +// +// i !< j +// +// means that it must NOT be the case that i < j. +// Negative assertions may appear anywhere in the rules, +// even before i and j have been defined. +// +// Comments begin with #. +package dag + +import ( + "cmp" + "fmt" + "slices" + "strings" +) + +type Graph struct { + Nodes []string + byLabel map[string]int + edges map[string]map[string]bool +} + +func newGraph() *Graph { + return &Graph{byLabel: map[string]int{}, edges: map[string]map[string]bool{}} +} + +func (g *Graph) addNode(label string) bool { + if _, ok := g.byLabel[label]; ok { + return false + } + g.byLabel[label] = len(g.Nodes) + g.Nodes = append(g.Nodes, label) + g.edges[label] = map[string]bool{} + return true +} + +func (g *Graph) AddEdge(from, to string) { + g.edges[from][to] = true +} + +func (g *Graph) DelEdge(from, to string) { + delete(g.edges[from], to) +} + +func (g *Graph) HasEdge(from, to string) bool { + return g.edges[from] != nil && g.edges[from][to] +} + +func (g *Graph) Edges(from string) []string { + edges := make([]string, 0, 16) + for k := range g.edges[from] { + edges = append(edges, k) + } + slices.SortFunc(edges, func(a, b string) int { + return cmp.Compare(g.byLabel[a], g.byLabel[b]) + }) + return edges +} + +// Parse parses the DAG language and returns the transitive closure of +// the described graph. In the returned graph, there is an edge from "b" +// to "a" if b < a (or a > b) in the partial order. +func Parse(dag string) (*Graph, error) { + g := newGraph() + disallowed := []rule{} + + rules, err := parseRules(dag) + if err != nil { + return nil, err + } + + // TODO: Add line numbers to errors. + var errors []string + errorf := func(format string, a ...any) { + errors = append(errors, fmt.Sprintf(format, a...)) + } + for _, r := range rules { + if r.op == "!<" { + disallowed = append(disallowed, r) + continue + } + for _, def := range r.def { + if def == "NONE" { + errorf("NONE cannot be a predecessor") + continue + } + if !g.addNode(def) { + errorf("multiple definitions for %s", def) + } + for _, less := range r.less { + if less == "NONE" { + continue + } + if _, ok := g.byLabel[less]; !ok { + errorf("use of %s before its definition", less) + } else { + g.AddEdge(def, less) + } + } + } + } + + // Check for missing definition. + for _, tos := range g.edges { + for to := range tos { + if g.edges[to] == nil { + errorf("missing definition for %s", to) + } + } + } + + // Complete transitive closure. + for _, k := range g.Nodes { + for _, i := range g.Nodes { + for _, j := range g.Nodes { + if i != k && k != j && g.HasEdge(i, k) && g.HasEdge(k, j) { + if i == j { + // Can only happen along with a "use of X before deps" error above, + // but this error is more specific - it makes clear that reordering the + // rules will not be enough to fix the problem. + errorf("graph cycle: %s < %s < %s", j, k, i) + } + g.AddEdge(i, j) + } + } + } + } + + // Check negative assertions against completed allowed graph. + for _, bad := range disallowed { + for _, less := range bad.less { + for _, def := range bad.def { + if g.HasEdge(def, less) { + errorf("graph edge assertion failed: %s !< %s", less, def) + } + } + } + } + + if len(errors) > 0 { + return nil, fmt.Errorf("%s", strings.Join(errors, "\n")) + } + + return g, nil +} + +// A rule is a line in the DAG language where "less < def" or "less !< def". +type rule struct { + less []string + op string // Either "<" or "!<" + def []string +} + +type syntaxError string + +func (e syntaxError) Error() string { + return string(e) +} + +// parseRules parses the rules of a DAG. +func parseRules(rules string) (out []rule, err error) { + defer func() { + e := recover() + switch e := e.(type) { + case nil: + return + case syntaxError: + err = e + default: + panic(e) + } + }() + p := &rulesParser{lineno: 1, text: rules} + + var prev []string + var op string + for { + list, tok := p.nextList() + if tok == "" { + if prev == nil { + break + } + p.syntaxError("unexpected EOF") + } + if prev != nil { + out = append(out, rule{prev, op, list}) + } + prev = list + if tok == ";" { + prev = nil + op = "" + continue + } + if tok != "<" && tok != "!<" { + p.syntaxError("missing <") + } + op = tok + } + + return out, err +} + +// A rulesParser parses the depsRules syntax described above. +type rulesParser struct { + lineno int + lastWord string + text string +} + +// syntaxError reports a parsing error. +func (p *rulesParser) syntaxError(msg string) { + panic(syntaxError(fmt.Sprintf("parsing graph: line %d: syntax error: %s near %s", p.lineno, msg, p.lastWord))) +} + +// nextList parses and returns a comma-separated list of names. +func (p *rulesParser) nextList() (list []string, token string) { + for { + tok := p.nextToken() + switch tok { + case "": + if len(list) == 0 { + return nil, "" + } + fallthrough + case ",", "<", "!<", ";": + p.syntaxError("bad list syntax") + } + list = append(list, tok) + + tok = p.nextToken() + if tok != "," { + return list, tok + } + } +} + +// nextToken returns the next token in the deps rules, +// one of ";" "," "<" "!<" or a name. +func (p *rulesParser) nextToken() string { + for { + if p.text == "" { + return "" + } + switch p.text[0] { + case ';', ',', '<': + t := p.text[:1] + p.text = p.text[1:] + return t + + case '!': + if len(p.text) < 2 || p.text[1] != '<' { + p.syntaxError("unexpected token !") + } + p.text = p.text[2:] + return "!<" + + case '#': + i := strings.Index(p.text, "\n") + if i < 0 { + i = len(p.text) + } + p.text = p.text[i:] + continue + + case '\n': + p.lineno++ + fallthrough + case ' ', '\t': + p.text = p.text[1:] + continue + + default: + i := strings.IndexAny(p.text, "!;,<#\n \t") + if i < 0 { + i = len(p.text) + } + t := p.text[:i] + p.text = p.text[i:] + p.lastWord = t + return t + } + } +} diff --git a/go/src/internal/dag/parse_test.go b/go/src/internal/dag/parse_test.go new file mode 100644 index 0000000000000000000000000000000000000000..dda304ad3eb161d555898752658928dbcaa228a3 --- /dev/null +++ b/go/src/internal/dag/parse_test.go @@ -0,0 +1,61 @@ +// 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 dag + +import ( + "slices" + "strings" + "testing" +) + +const diamond = ` +NONE < a < b, c < d; +` + +func mustParse(t *testing.T, dag string) *Graph { + t.Helper() + g, err := Parse(dag) + if err != nil { + t.Fatal(err) + } + return g +} + +func wantEdges(t *testing.T, g *Graph, edges string) { + t.Helper() + + wantEdges := strings.Fields(edges) + wantEdgeMap := make(map[string]bool) + for _, e := range wantEdges { + wantEdgeMap[e] = true + } + + for _, n1 := range g.Nodes { + for _, n2 := range g.Nodes { + got := g.HasEdge(n1, n2) + want := wantEdgeMap[n1+"->"+n2] + if got && want { + t.Logf("%s->%s", n1, n2) + } else if got && !want { + t.Errorf("%s->%s present but not expected", n1, n2) + } else if want && !got { + t.Errorf("%s->%s missing but expected", n1, n2) + } + } + } +} + +func TestParse(t *testing.T) { + // Basic smoke test for graph parsing. + g := mustParse(t, diamond) + + wantNodes := strings.Fields("a b c d") + if !slices.Equal(wantNodes, g.Nodes) { + t.Fatalf("want nodes %v, got %v", wantNodes, g.Nodes) + } + + // Parse returns the transitive closure, so it adds d->a. + wantEdges(t, g, "b->a c->a d->a d->b d->c") +} diff --git a/go/src/internal/diff/diff.go b/go/src/internal/diff/diff.go new file mode 100644 index 0000000000000000000000000000000000000000..6a40b23fcbf0229ddc05c2bedf6d5d5d1e9c1ca5 --- /dev/null +++ b/go/src/internal/diff/diff.go @@ -0,0 +1,261 @@ +// 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 diff + +import ( + "bytes" + "fmt" + "sort" + "strings" +) + +// A pair is a pair of values tracked for both the x and y side of a diff. +// It is typically a pair of line indexes. +type pair struct{ x, y int } + +// Diff returns an anchored diff of the two texts old and new +// in the “unified diff” format. If old and new are identical, +// Diff returns a nil slice (no output). +// +// Unix diff implementations typically look for a diff with +// the smallest number of lines inserted and removed, +// which can in the worst case take time quadratic in the +// number of lines in the texts. As a result, many implementations +// either can be made to run for a long time or cut off the search +// after a predetermined amount of work. +// +// In contrast, this implementation looks for a diff with the +// smallest number of “unique” lines inserted and removed, +// where unique means a line that appears just once in both old and new. +// We call this an “anchored diff” because the unique lines anchor +// the chosen matching regions. An anchored diff is usually clearer +// than a standard diff, because the algorithm does not try to +// reuse unrelated blank lines or closing braces. +// The algorithm also guarantees to run in O(n log n) time +// instead of the standard O(n²) time. +// +// Some systems call this approach a “patience diff,” named for +// the “patience sorting” algorithm, itself named for a solitaire card game. +// We avoid that name for two reasons. First, the name has been used +// for a few different variants of the algorithm, so it is imprecise. +// Second, the name is frequently interpreted as meaning that you have +// to wait longer (to be patient) for the diff, meaning that it is a slower algorithm, +// when in fact the algorithm is faster than the standard one. +func Diff(oldName string, old []byte, newName string, new []byte) []byte { + if bytes.Equal(old, new) { + return nil + } + x := lines(old) + y := lines(new) + + // Print diff header. + var out bytes.Buffer + fmt.Fprintf(&out, "diff %s %s\n", oldName, newName) + fmt.Fprintf(&out, "--- %s\n", oldName) + fmt.Fprintf(&out, "+++ %s\n", newName) + + // Loop over matches to consider, + // expanding each match to include surrounding lines, + // and then printing diff chunks. + // To avoid setup/teardown cases outside the loop, + // tgs returns a leading {0,0} and trailing {len(x), len(y)} pair + // in the sequence of matches. + var ( + done pair // printed up to x[:done.x] and y[:done.y] + chunk pair // start lines of current chunk + count pair // number of lines from each side in current chunk + ctext []string // lines for current chunk + ) + for _, m := range tgs(x, y) { + if m.x < done.x { + // Already handled scanning forward from earlier match. + continue + } + + // Expand matching lines as far as possible, + // establishing that x[start.x:end.x] == y[start.y:end.y]. + // Note that on the first (or last) iteration we may (or definitely do) + // have an empty match: start.x==end.x and start.y==end.y. + start := m + for start.x > done.x && start.y > done.y && x[start.x-1] == y[start.y-1] { + start.x-- + start.y-- + } + end := m + for end.x < len(x) && end.y < len(y) && x[end.x] == y[end.y] { + end.x++ + end.y++ + } + + // Emit the mismatched lines before start into this chunk. + // (No effect on first sentinel iteration, when start = {0,0}.) + for _, s := range x[done.x:start.x] { + ctext = append(ctext, "-"+s) + count.x++ + } + for _, s := range y[done.y:start.y] { + ctext = append(ctext, "+"+s) + count.y++ + } + + // If we're not at EOF and have too few common lines, + // the chunk includes all the common lines and continues. + const C = 3 // number of context lines + if (end.x < len(x) || end.y < len(y)) && + (end.x-start.x < C || (len(ctext) > 0 && end.x-start.x < 2*C)) { + for _, s := range x[start.x:end.x] { + ctext = append(ctext, " "+s) + count.x++ + count.y++ + } + done = end + continue + } + + // End chunk with common lines for context. + if len(ctext) > 0 { + n := end.x - start.x + if n > C { + n = C + } + for _, s := range x[start.x : start.x+n] { + ctext = append(ctext, " "+s) + count.x++ + count.y++ + } + done = pair{start.x + n, start.y + n} + + // Format and emit chunk. + // Convert line numbers to 1-indexed. + // Special case: empty file shows up as 0,0 not 1,0. + if count.x > 0 { + chunk.x++ + } + if count.y > 0 { + chunk.y++ + } + fmt.Fprintf(&out, "@@ -%d,%d +%d,%d @@\n", chunk.x, count.x, chunk.y, count.y) + for _, s := range ctext { + out.WriteString(s) + } + count.x = 0 + count.y = 0 + ctext = ctext[:0] + } + + // If we reached EOF, we're done. + if end.x >= len(x) && end.y >= len(y) { + break + } + + // Otherwise start a new chunk. + chunk = pair{end.x - C, end.y - C} + for _, s := range x[chunk.x:end.x] { + ctext = append(ctext, " "+s) + count.x++ + count.y++ + } + done = end + } + + return out.Bytes() +} + +// lines returns the lines in the file x, including newlines. +// If the file does not end in a newline, one is supplied +// along with a warning about the missing newline. +func lines(x []byte) []string { + l := strings.SplitAfter(string(x), "\n") + if l[len(l)-1] == "" { + l = l[:len(l)-1] + } else { + // Treat last line as having a message about the missing newline attached, + // using the same text as BSD/GNU diff (including the leading backslash). + l[len(l)-1] += "\n\\ No newline at end of file\n" + } + return l +} + +// tgs returns the pairs of indexes of the longest common subsequence +// of unique lines in x and y, where a unique line is one that appears +// once in x and once in y. +// +// The longest common subsequence algorithm is as described in +// Thomas G. Szymanski, “A Special Case of the Maximal Common +// Subsequence Problem,” Princeton TR #170 (January 1975), +// available at https://research.swtch.com/tgs170.pdf. +func tgs(x, y []string) []pair { + // Count the number of times each string appears in a and b. + // We only care about 0, 1, many, counted as 0, -1, -2 + // for the x side and 0, -4, -8 for the y side. + // Using negative numbers now lets us distinguish positive line numbers later. + m := make(map[string]int) + for _, s := range x { + if c := m[s]; c > -2 { + m[s] = c - 1 + } + } + for _, s := range y { + if c := m[s]; c > -8 { + m[s] = c - 4 + } + } + + // Now unique strings can be identified by m[s] = -1+-4. + // + // Gather the indexes of those strings in x and y, building: + // xi[i] = increasing indexes of unique strings in x. + // yi[i] = increasing indexes of unique strings in y. + // inv[i] = index j such that x[xi[i]] = y[yi[j]]. + var xi, yi, inv []int + for i, s := range y { + if m[s] == -1+-4 { + m[s] = len(yi) + yi = append(yi, i) + } + } + for i, s := range x { + if j, ok := m[s]; ok && j >= 0 { + xi = append(xi, i) + inv = append(inv, j) + } + } + + // Apply Algorithm A from Szymanski's paper. + // In those terms, A = J = inv and B = [0, n). + // We add sentinel pairs {0,0}, and {len(x),len(y)} + // to the returned sequence, to help the processing loop. + J := inv + n := len(xi) + T := make([]int, n) + L := make([]int, n) + for i := range T { + T[i] = n + 1 + } + for i := 0; i < n; i++ { + k := sort.Search(n, func(k int) bool { + return T[k] >= J[i] + }) + T[k] = J[i] + L[i] = k + 1 + } + k := 0 + for _, v := range L { + if k < v { + k = v + } + } + seq := make([]pair, 2+k) + seq[1+k] = pair{len(x), len(y)} // sentinel at end + lastj := n + for i := n - 1; i >= 0; i-- { + if L[i] == k && J[i] < lastj { + seq[k] = pair{xi[i], yi[J[i]]} + k-- + } + } + seq[0] = pair{0, 0} // sentinel at start + return seq +} diff --git a/go/src/internal/diff/diff_test.go b/go/src/internal/diff/diff_test.go new file mode 100644 index 0000000000000000000000000000000000000000..37281c529b91282af3c29157344f526eab854458 --- /dev/null +++ b/go/src/internal/diff/diff_test.go @@ -0,0 +1,43 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package diff + +import ( + "bytes" + "internal/txtar" + "path/filepath" + "testing" +) + +func clean(text []byte) []byte { + text = bytes.ReplaceAll(text, []byte("$\n"), []byte("\n")) + text = bytes.TrimSuffix(text, []byte("^D\n")) + return text +} + +func Test(t *testing.T) { + files, _ := filepath.Glob("testdata/*.txt") + if len(files) == 0 { + t.Fatalf("no testdata") + } + + for _, file := range files { + t.Run(filepath.Base(file), func(t *testing.T) { + a, err := txtar.ParseFile(file) + if err != nil { + t.Fatal(err) + } + if len(a.Files) != 3 || a.Files[2].Name != "diff" { + t.Fatalf("%s: want three files, third named \"diff\"", file) + } + diffs := Diff(a.Files[0].Name, clean(a.Files[0].Data), a.Files[1].Name, clean(a.Files[1].Data)) + want := clean(a.Files[2].Data) + if !bytes.Equal(diffs, want) { + t.Fatalf("%s: have:\n%s\nwant:\n%s\n%s", file, + diffs, want, Diff("have", diffs, "want", want)) + } + }) + } +} diff --git a/go/src/internal/exportdata/exportdata.go b/go/src/internal/exportdata/exportdata.go new file mode 100644 index 0000000000000000000000000000000000000000..861a47f49f94f9d1c5b258b431a561e1bcadd623 --- /dev/null +++ b/go/src/internal/exportdata/exportdata.go @@ -0,0 +1,355 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package exportdata implements common utilities for finding +// and reading gc-generated object files. +package exportdata + +// This file should be kept in sync with src/cmd/compile/internal/gc/obj.go . + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "go/build" + "internal/saferio" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" +) + +// ReadUnified reads the contents of the unified export data from a reader r +// that contains the contents of a GC-created archive file. +// +// On success, the reader will be positioned after the end-of-section marker "\n$$\n". +// +// Supported GC-created archive files have 4 layers of nesting: +// - An archive file containing a package definition file. +// - The package definition file contains headers followed by a data section. +// Headers are lines (≤ 4kb) that do not start with "$$". +// - The data section starts with "$$B\n" followed by export data followed +// by an end of section marker "\n$$\n". (The section start "$$\n" is no +// longer supported.) +// - The export data starts with a format byte ('u') followed by the in +// the given format. (See ReadExportDataHeader for older formats.) +// +// Putting this together, the bytes in a GC-created archive files are expected +// to look like the following. +// See cmd/internal/archive for more details on ar file headers. +// +// | \n | ar file signature +// | __.PKGDEF...size...\n | ar header for __.PKGDEF including size. +// | go object <...>\n | objabi header +// | \n | other headers such as build id +// | $$B\n | binary format marker +// | u\n | unified export +// | $$\n | end-of-section marker +// | [optional padding] | padding byte (0x0A) if size is odd +// | [ar file header] | other ar files +// | [ar file data] | +func ReadUnified(r *bufio.Reader) (data []byte, err error) { + // We historically guaranteed headers at the default buffer size (4096) work. + // This ensures we can use ReadSlice throughout. + const minBufferSize = 4096 + r = bufio.NewReaderSize(r, minBufferSize) + + size, err := FindPackageDefinition(r) + if err != nil { + return + } + n := size + + objapi, headers, err := ReadObjectHeaders(r) + if err != nil { + return + } + n -= len(objapi) + for _, h := range headers { + n -= len(h) + } + + hdrlen, err := ReadExportDataHeader(r) + if err != nil { + return + } + n -= hdrlen + + // size also includes the end of section marker. Remove that many bytes from the end. + const marker = "\n$$\n" + n -= len(marker) + + if n < 0 { + err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", size, n) + return + } + + // Read n bytes from buf. + data, err = saferio.ReadData(r, uint64(n)) + if err != nil { + return + } + + // Check for marker at the end. + var suffix [len(marker)]byte + _, err = io.ReadFull(r, suffix[:]) + if err != nil { + return + } + if s := string(suffix[:]); s != marker { + err = fmt.Errorf("read %q instead of end-of-section marker (%q)", s, marker) + return + } + + return +} + +// FindPackageDefinition positions the reader r at the beginning of a package +// definition file ("__.PKGDEF") within a GC-created archive by reading +// from it, and returns the size of the package definition file in the archive. +// +// The reader must be positioned at the start of the archive file before calling +// this function, and "__.PKGDEF" is assumed to be the first file in the archive. +// +// See cmd/internal/archive for details on the archive format. +func FindPackageDefinition(r *bufio.Reader) (size int, err error) { + // Uses ReadSlice to limit risk of malformed inputs. + + // Read first line to make sure this is an object file. + line, err := r.ReadSlice('\n') + if err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + + // Is the first line an archive file signature? + if string(line) != "!\n" { + err = fmt.Errorf("not the start of an archive file (%q)", line) + return + } + + // package export block should be first + size = readArchiveHeader(r, "__.PKGDEF") + if size <= 0 { + err = fmt.Errorf("not a package file") + return + } + + return +} + +// ReadObjectHeaders reads object headers from the reader. Object headers are +// lines that do not start with an end-of-section marker "$$". The first header +// is the objabi header. On success, the reader will be positioned at the beginning +// of the end-of-section marker. +// +// It returns an error if any header does not fit in r.Size() bytes. +func ReadObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) { + // line is a temporary buffer for headers. + // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs. + var line []byte + + // objapi header should be the first line + if line, err = r.ReadSlice('\n'); err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + objapi = string(line) + + // objapi header begins with "go object ". + if !strings.HasPrefix(objapi, "go object ") { + err = fmt.Errorf("not a go object file: %s", objapi) + return + } + + // process remaining object header lines + for { + // check for an end of section marker "$$" + line, err = r.Peek(2) + if err != nil { + return + } + if string(line) == "$$" { + return // stop + } + + // read next header + line, err = r.ReadSlice('\n') + if err != nil { + return + } + headers = append(headers, string(line)) + } +} + +// ReadExportDataHeader reads the export data header and format from r. +// It returns the number of bytes read, or an error if the format is no longer +// supported or it failed to read. +// +// The only currently supported format is binary export data in the +// unified export format. +func ReadExportDataHeader(r *bufio.Reader) (n int, err error) { + // Read export data header. + line, err := r.ReadSlice('\n') + if err != nil { + return + } + + hdr := string(line) + switch hdr { + case "$$\n": + err = fmt.Errorf("old textual export format no longer supported (recompile package)") + return + + case "$$B\n": + var format byte + format, err = r.ReadByte() + if err != nil { + return + } + // The unified export format starts with a 'u'. + switch format { + case 'u': + default: + // Older no longer supported export formats include: + // indexed export format which started with an 'i'; and + // the older binary export format which started with a 'c', + // 'd', or 'v' (from "version"). + err = fmt.Errorf("binary export format %q is no longer supported (recompile package)", format) + return + } + + default: + err = fmt.Errorf("unknown export data header: %q", hdr) + return + } + + n = len(hdr) + 1 // + 1 is for 'u' + return +} + +// FindPkg returns the filename and unique package id for an import +// path based on package information provided by build.Import (using +// the build.Default build.Context). A relative srcDir is interpreted +// relative to the current working directory. +func FindPkg(path, srcDir string) (filename, id string, err error) { + if path == "" { + return "", "", errors.New("path is empty") + } + + var noext string + switch { + default: + // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" + // Don't require the source files to be present. + if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282 + srcDir = abs + } + var bp *build.Package + bp, err = build.Import(path, srcDir, build.FindOnly|build.AllowBinary) + if bp.PkgObj == "" { + if bp.Goroot && bp.Dir != "" { + filename, err = lookupGorootExport(bp.Dir) + if err == nil { + _, err = os.Stat(filename) + } + if err == nil { + return filename, bp.ImportPath, nil + } + } + goto notfound + } else { + noext = strings.TrimSuffix(bp.PkgObj, ".a") + } + id = bp.ImportPath + + case build.IsLocalImport(path): + // "./x" -> "/this/directory/x.ext", "/this/directory/x" + noext = filepath.Join(srcDir, path) + id = noext + + case filepath.IsAbs(path): + // for completeness only - go/build.Import + // does not support absolute imports + // "/x" -> "/x.ext", "/x" + noext = path + id = path + } + + if false { // for debugging + if path != id { + fmt.Printf("%s -> %s\n", path, id) + } + } + + // try extensions + for _, ext := range pkgExts { + filename = noext + ext + f, statErr := os.Stat(filename) + if statErr == nil && !f.IsDir() { + return filename, id, nil + } + if err == nil { + err = statErr + } + } + +notfound: + if err == nil { + return "", path, fmt.Errorf("can't find import: %q", path) + } + return "", path, fmt.Errorf("can't find import: %q: %w", path, err) +} + +var pkgExts = [...]string{".a", ".o"} // a file from the build cache will have no extension + +var exportMap sync.Map // package dir → func() (string, error) + +// lookupGorootExport returns the location of the export data +// (normally found in the build cache, but located in GOROOT/pkg +// in prior Go releases) for the package located in pkgDir. +// +// (We use the package's directory instead of its import path +// mainly to simplify handling of the packages in src/vendor +// and cmd/vendor.) +func lookupGorootExport(pkgDir string) (string, error) { + f, ok := exportMap.Load(pkgDir) + if !ok { + var ( + listOnce sync.Once + exportPath string + err error + ) + f, _ = exportMap.LoadOrStore(pkgDir, func() (string, error) { + listOnce.Do(func() { + cmd := exec.Command(filepath.Join(build.Default.GOROOT, "bin", "go"), "list", "-export", "-f", "{{.Export}}", pkgDir) + cmd.Dir = build.Default.GOROOT + cmd.Env = append(os.Environ(), "PWD="+cmd.Dir, "GOROOT="+build.Default.GOROOT) + var output []byte + output, err = cmd.Output() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { + err = errors.New(string(ee.Stderr)) + } + return + } + + exports := strings.Split(string(bytes.TrimSpace(output)), "\n") + if len(exports) != 1 { + err = fmt.Errorf("go list reported %d exports; expected 1", len(exports)) + return + } + + exportPath = exports[0] + }) + + return exportPath, err + }) + } + + return f.(func() (string, error))() +} diff --git a/go/src/internal/exportdata/support.go b/go/src/internal/exportdata/support.go new file mode 100644 index 0000000000000000000000000000000000000000..a06401db391e0190e5006c9fef32f433e67db8e1 --- /dev/null +++ b/go/src/internal/exportdata/support.go @@ -0,0 +1,32 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains support functions for exportdata. + +package exportdata + +import ( + "bufio" + "io" + "strconv" + "strings" +) + +// Copy of cmd/internal/archive.ReadHeader. +func readArchiveHeader(b *bufio.Reader, name string) int { + // architecture-independent object file output + const HeaderSize = 60 + + var buf [HeaderSize]byte + if _, err := io.ReadFull(b, buf[:]); err != nil { + return -1 + } + aname := strings.Trim(string(buf[0:16]), " ") + if !strings.HasPrefix(aname, name) { + return -1 + } + asize := strings.Trim(string(buf[48:58]), " ") + i, _ := strconv.Atoi(asize) + return i +} diff --git a/go/src/internal/filepathlite/path.go b/go/src/internal/filepathlite/path.go new file mode 100644 index 0000000000000000000000000000000000000000..4a3729832fa8c8b7e46f0d8f23ee27ae35cf5009 --- /dev/null +++ b/go/src/internal/filepathlite/path.go @@ -0,0 +1,274 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package filepathlite implements a subset of path/filepath, +// only using packages which may be imported by "os". +// +// Tests for these functions are in path/filepath. +package filepathlite + +import ( + "errors" + "internal/stringslite" + "io/fs" + "slices" +) + +var errInvalidPath = errors.New("invalid path") + +// A lazybuf is a lazily constructed path buffer. +// It supports append, reading previously appended bytes, +// and retrieving the final string. It does not allocate a buffer +// to hold the output until that output diverges from s. +type lazybuf struct { + path string + buf []byte + w int + volAndPath string + volLen int +} + +func (b *lazybuf) index(i int) byte { + if b.buf != nil { + return b.buf[i] + } + return b.path[i] +} + +func (b *lazybuf) append(c byte) { + if b.buf == nil { + if b.w < len(b.path) && b.path[b.w] == c { + b.w++ + return + } + b.buf = make([]byte, len(b.path)) + copy(b.buf, b.path[:b.w]) + } + b.buf[b.w] = c + b.w++ +} + +func (b *lazybuf) prepend(prefix ...byte) { + b.buf = slices.Insert(b.buf, 0, prefix...) + b.w += len(prefix) +} + +func (b *lazybuf) string() string { + if b.buf == nil { + return b.volAndPath[:b.volLen+b.w] + } + return b.volAndPath[:b.volLen] + string(b.buf[:b.w]) +} + +// Clean is filepath.Clean. +func Clean(path string) string { + originalPath := path + volLen := volumeNameLen(path) + path = path[volLen:] + if path == "" { + if volLen > 1 && IsPathSeparator(originalPath[0]) && IsPathSeparator(originalPath[1]) { + // should be UNC + return FromSlash(originalPath) + } + return originalPath + "." + } + rooted := IsPathSeparator(path[0]) + + // Invariants: + // reading from path; r is index of next byte to process. + // writing to buf; w is index of next byte to write. + // dotdot is index in buf where .. must stop, either because + // it is the leading slash or it is a leading ../../.. prefix. + n := len(path) + out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen} + r, dotdot := 0, 0 + if rooted { + out.append(Separator) + r, dotdot = 1, 1 + } + + for r < n { + switch { + case IsPathSeparator(path[r]): + // empty path element + r++ + case path[r] == '.' && (r+1 == n || IsPathSeparator(path[r+1])): + // . element + r++ + case path[r] == '.' && path[r+1] == '.' && (r+2 == n || IsPathSeparator(path[r+2])): + // .. element: remove to last separator + r += 2 + switch { + case out.w > dotdot: + // can backtrack + out.w-- + for out.w > dotdot && !IsPathSeparator(out.index(out.w)) { + out.w-- + } + case !rooted: + // cannot backtrack, but not rooted, so append .. element. + if out.w > 0 { + out.append(Separator) + } + out.append('.') + out.append('.') + dotdot = out.w + } + default: + // real path element. + // add slash if needed + if rooted && out.w != 1 || !rooted && out.w != 0 { + out.append(Separator) + } + // copy element + for ; r < n && !IsPathSeparator(path[r]); r++ { + out.append(path[r]) + } + } + } + + // Turn empty string into "." + if out.w == 0 { + out.append('.') + } + + postClean(&out) // avoid creating absolute paths on Windows + return FromSlash(out.string()) +} + +// IsLocal is filepath.IsLocal. +func IsLocal(path string) bool { + return isLocal(path) +} + +func unixIsLocal(path string) bool { + if IsAbs(path) || path == "" { + return false + } + hasDots := false + for p := path; p != ""; { + var part string + part, p, _ = stringslite.Cut(p, "/") + if part == "." || part == ".." { + hasDots = true + break + } + } + if hasDots { + path = Clean(path) + } + if path == ".." || stringslite.HasPrefix(path, "../") { + return false + } + return true +} + +// Localize is filepath.Localize. +func Localize(path string) (string, error) { + if !fs.ValidPath(path) { + return "", errInvalidPath + } + return localize(path) +} + +// ToSlash is filepath.ToSlash. +func ToSlash(path string) string { + if Separator == '/' { + return path + } + return replaceStringByte(path, Separator, '/') +} + +// FromSlash is filepath.FromSlash. +func FromSlash(path string) string { + if Separator == '/' { + return path + } + return replaceStringByte(path, '/', Separator) +} + +func replaceStringByte(s string, old, new byte) string { + if stringslite.IndexByte(s, old) == -1 { + return s + } + n := []byte(s) + for i := range n { + if n[i] == old { + n[i] = new + } + } + return string(n) +} + +// Split is filepath.Split. +func Split(path string) (dir, file string) { + vol := VolumeName(path) + i := len(path) - 1 + for i >= len(vol) && !IsPathSeparator(path[i]) { + i-- + } + return path[:i+1], path[i+1:] +} + +// Ext is filepath.Ext. +func Ext(path string) string { + for i := len(path) - 1; i >= 0 && !IsPathSeparator(path[i]); i-- { + if path[i] == '.' { + return path[i:] + } + } + return "" +} + +// Base is filepath.Base. +func Base(path string) string { + if path == "" { + return "." + } + // Strip trailing slashes. + for len(path) > 0 && IsPathSeparator(path[len(path)-1]) { + path = path[0 : len(path)-1] + } + // Throw away volume name + path = path[len(VolumeName(path)):] + // Find the last element + i := len(path) - 1 + for i >= 0 && !IsPathSeparator(path[i]) { + i-- + } + if i >= 0 { + path = path[i+1:] + } + // If empty now, it had only slashes. + if path == "" { + return string(Separator) + } + return path +} + +// Dir is filepath.Dir. +func Dir(path string) string { + vol := VolumeName(path) + i := len(path) - 1 + for i >= len(vol) && !IsPathSeparator(path[i]) { + i-- + } + dir := Clean(path[len(vol) : i+1]) + if dir == "." && len(vol) > 2 { + // must be UNC + return vol + } + return vol + dir +} + +// VolumeName is filepath.VolumeName. +func VolumeName(path string) string { + return FromSlash(path[:volumeNameLen(path)]) +} + +// VolumeNameLen returns the length of the leading volume name on Windows. +// It returns 0 elsewhere. +func VolumeNameLen(path string) int { + return volumeNameLen(path) +} diff --git a/go/src/internal/filepathlite/path_nonwindows.go b/go/src/internal/filepathlite/path_nonwindows.go new file mode 100644 index 0000000000000000000000000000000000000000..c9c4c02a3da112f274b467512eb6561e765b688b --- /dev/null +++ b/go/src/internal/filepathlite/path_nonwindows.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows + +package filepathlite + +func postClean(out *lazybuf) {} diff --git a/go/src/internal/filepathlite/path_plan9.go b/go/src/internal/filepathlite/path_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..5bbb724f9113c22c8b09c1080a557a2fdd6d1e4b --- /dev/null +++ b/go/src/internal/filepathlite/path_plan9.go @@ -0,0 +1,41 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filepathlite + +import ( + "internal/bytealg" + "internal/stringslite" +) + +const ( + Separator = '/' // OS-specific path separator + ListSeparator = '\000' // OS-specific path list separator +) + +func IsPathSeparator(c uint8) bool { + return Separator == c +} + +func isLocal(path string) bool { + return unixIsLocal(path) +} + +func localize(path string) (string, error) { + if path[0] == '#' || bytealg.IndexByteString(path, 0) >= 0 { + return "", errInvalidPath + } + return path, nil +} + +// IsAbs reports whether the path is absolute. +func IsAbs(path string) bool { + return stringslite.HasPrefix(path, "/") || stringslite.HasPrefix(path, "#") +} + +// volumeNameLen returns length of the leading volume name on Windows. +// It returns 0 elsewhere. +func volumeNameLen(path string) int { + return 0 +} diff --git a/go/src/internal/filepathlite/path_unix.go b/go/src/internal/filepathlite/path_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..e31f1ae74f74799c96c56eccf9da5ab2c4c50eab --- /dev/null +++ b/go/src/internal/filepathlite/path_unix.go @@ -0,0 +1,43 @@ +// 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 filepathlite + +import ( + "internal/bytealg" + "internal/stringslite" +) + +const ( + Separator = '/' // OS-specific path separator + ListSeparator = ':' // OS-specific path list separator +) + +func IsPathSeparator(c uint8) bool { + return Separator == c +} + +func isLocal(path string) bool { + return unixIsLocal(path) +} + +func localize(path string) (string, error) { + if bytealg.IndexByteString(path, 0) >= 0 { + return "", errInvalidPath + } + return path, nil +} + +// IsAbs reports whether the path is absolute. +func IsAbs(path string) bool { + return stringslite.HasPrefix(path, "/") +} + +// volumeNameLen returns length of the leading volume name on Windows. +// It returns 0 elsewhere. +func volumeNameLen(path string) int { + return 0 +} diff --git a/go/src/internal/filepathlite/path_windows.go b/go/src/internal/filepathlite/path_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..011baa96f0243248a742e29fc79468338f6415d2 --- /dev/null +++ b/go/src/internal/filepathlite/path_windows.go @@ -0,0 +1,326 @@ +// 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 filepathlite + +import ( + "internal/bytealg" + "internal/stringslite" + "internal/syscall/windows" + "syscall" +) + +const ( + Separator = '\\' // OS-specific path separator + ListSeparator = ';' // OS-specific path list separator +) + +func IsPathSeparator(c uint8) bool { + return c == '\\' || c == '/' +} + +func isLocal(path string) bool { + if path == "" { + return false + } + if IsPathSeparator(path[0]) { + // Path rooted in the current drive. + return false + } + if stringslite.IndexByte(path, ':') >= 0 { + // Colons are only valid when marking a drive letter ("C:foo"). + // Rejecting any path with a colon is conservative but safe. + return false + } + hasDots := false // contains . or .. path elements + for p := path; p != ""; { + var part string + part, p, _ = cutPath(p) + if part == "." || part == ".." { + hasDots = true + } + if isReservedName(part) { + return false + } + } + if hasDots { + path = Clean(path) + } + if path == ".." || stringslite.HasPrefix(path, `..\`) { + return false + } + return true +} + +func localize(path string) (string, error) { + for i := 0; i < len(path); i++ { + switch path[i] { + case ':', '\\', 0: + return "", errInvalidPath + } + } + containsSlash := false + for p := path; p != ""; { + // Find the next path element. + var element string + i := bytealg.IndexByteString(p, '/') + if i < 0 { + element = p + p = "" + } else { + containsSlash = true + element = p[:i] + p = p[i+1:] + } + if isReservedName(element) { + return "", errInvalidPath + } + } + if containsSlash { + // We can't depend on strings, so substitute \ for / manually. + buf := []byte(path) + for i, b := range buf { + if b == '/' { + buf[i] = '\\' + } + } + path = string(buf) + } + return path, nil +} + +// isReservedName reports if name is a Windows reserved device name. +// It does not detect names with an extension, which are also reserved on some Windows versions. +// +// For details, search for PRN in +// https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file. +func isReservedName(name string) bool { + // Device names can have arbitrary trailing characters following a dot or colon. + base := name + for i := 0; i < len(base); i++ { + switch base[i] { + case ':', '.': + base = base[:i] + } + } + // Trailing spaces in the last path element are ignored. + for len(base) > 0 && base[len(base)-1] == ' ' { + base = base[:len(base)-1] + } + if !isReservedBaseName(base) { + return false + } + if len(base) == len(name) { + return true + } + // The path element is a reserved name with an extension. + // Since Windows 11, reserved names with extensions are no + // longer reserved. For example, "CON.txt" is a valid file + // name. Use RtlIsDosDeviceName_U to see if the name is reserved. + p, err := syscall.UTF16PtrFromString(name) + if err != nil { + return false + } + return windows.RtlIsDosDeviceName_U(p) > 0 +} + +func isReservedBaseName(name string) bool { + if len(name) == 3 { + switch string([]byte{toUpper(name[0]), toUpper(name[1]), toUpper(name[2])}) { + case "CON", "PRN", "AUX", "NUL": + return true + } + } + if len(name) >= 4 { + switch string([]byte{toUpper(name[0]), toUpper(name[1]), toUpper(name[2])}) { + case "COM", "LPT": + if len(name) == 4 && '1' <= name[3] && name[3] <= '9' { + return true + } + // Superscript ¹, ², and ³ are considered numbers as well. + switch name[3:] { + case "\u00b2", "\u00b3", "\u00b9": + return true + } + return false + } + } + + // Passing CONIN$ or CONOUT$ to CreateFile opens a console handle. + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#consoles + // + // While CONIN$ and CONOUT$ aren't documented as being files, + // they behave the same as CON. For example, ./CONIN$ also opens the console input. + if len(name) == 6 && name[5] == '$' && equalFold(name, "CONIN$") { + return true + } + if len(name) == 7 && name[6] == '$' && equalFold(name, "CONOUT$") { + return true + } + return false +} + +func equalFold(a, b string) bool { + if len(a) != len(b) { + return false + } + for i := 0; i < len(a); i++ { + if toUpper(a[i]) != toUpper(b[i]) { + return false + } + } + return true +} + +func toUpper(c byte) byte { + if 'a' <= c && c <= 'z' { + return c - ('a' - 'A') + } + return c +} + +// IsAbs reports whether the path is absolute. +func IsAbs(path string) (b bool) { + l := volumeNameLen(path) + if l == 0 { + return false + } + // If the volume name starts with a double slash, this is an absolute path. + if IsPathSeparator(path[0]) && IsPathSeparator(path[1]) { + return true + } + path = path[l:] + if path == "" { + return false + } + return IsPathSeparator(path[0]) +} + +// volumeNameLen returns length of the leading volume name on Windows. +// It returns 0 elsewhere. +// +// See: +// https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats +// https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html +func volumeNameLen(path string) int { + switch { + case len(path) >= 2 && path[1] == ':': + // Path starts with a drive letter. + // + // Not all Windows functions necessarily enforce the requirement that + // drive letters be in the set A-Z, and we don't try to here. + // + // We don't handle the case of a path starting with a non-ASCII character, + // in which case the "drive letter" might be multiple bytes long. + return 2 + + case len(path) == 0 || !IsPathSeparator(path[0]): + // Path does not have a volume component. + return 0 + + case pathHasPrefixFold(path, `\\.\UNC`): + // We're going to treat the UNC host and share as part of the volume + // prefix for historical reasons, but this isn't really principled; + // Windows's own GetFullPathName will happily remove the first + // component of the path in this space, converting + // \\.\unc\a\b\..\c into \\.\unc\a\c. + return uncLen(path, len(`\\.\UNC\`)) + + case pathHasPrefixFold(path, `\\.`) || + pathHasPrefixFold(path, `\\?`) || pathHasPrefixFold(path, `\??`): + // Path starts with \\.\, and is a Local Device path; or + // path starts with \\?\ or \??\ and is a Root Local Device path. + // + // We treat the next component after the \\.\ prefix as + // part of the volume name, which means Clean(`\\?\c:\`) + // won't remove the trailing \. (See #64028.) + if len(path) == 3 { + return 3 // exactly \\. + } + _, rest, ok := cutPath(path[4:]) + if !ok { + return len(path) + } + return len(path) - len(rest) - 1 + + case len(path) >= 2 && IsPathSeparator(path[1]): + // Path starts with \\, and is a UNC path. + return uncLen(path, 2) + } + return 0 +} + +// pathHasPrefixFold tests whether the path s begins with prefix, +// ignoring case and treating all path separators as equivalent. +// If s is longer than prefix, then s[len(prefix)] must be a path separator. +func pathHasPrefixFold(s, prefix string) bool { + if len(s) < len(prefix) { + return false + } + for i := 0; i < len(prefix); i++ { + if IsPathSeparator(prefix[i]) { + if !IsPathSeparator(s[i]) { + return false + } + } else if toUpper(prefix[i]) != toUpper(s[i]) { + return false + } + } + if len(s) > len(prefix) && !IsPathSeparator(s[len(prefix)]) { + return false + } + return true +} + +// uncLen returns the length of the volume prefix of a UNC path. +// prefixLen is the prefix prior to the start of the UNC host; +// for example, for "//host/share", the prefixLen is len("//")==2. +func uncLen(path string, prefixLen int) int { + count := 0 + for i := prefixLen; i < len(path); i++ { + if IsPathSeparator(path[i]) { + count++ + if count == 2 { + return i + } + } + } + return len(path) +} + +// cutPath slices path around the first path separator. +func cutPath(path string) (before, after string, found bool) { + for i := range path { + if IsPathSeparator(path[i]) { + return path[:i], path[i+1:], true + } + } + return path, "", false +} + +// postClean adjusts the results of Clean to avoid turning a relative path +// into an absolute or rooted one. +func postClean(out *lazybuf) { + if out.volLen != 0 || out.buf == nil { + return + } + // If a ':' appears in the path element at the start of a path, + // insert a .\ at the beginning to avoid converting relative paths + // like a/../c: into c:. + for _, c := range out.buf { + if IsPathSeparator(c) { + break + } + if c == ':' { + out.prepend('.', Separator) + return + } + } + // If a path begins with \??\, insert a \. at the beginning + // to avoid converting paths like \a\..\??\c:\x into \??\c:\x + // (equivalent to c:\x). + if len(out.buf) >= 3 && IsPathSeparator(out.buf[0]) && out.buf[1] == '?' && out.buf[2] == '?' { + out.prepend(Separator, '.') + } +} diff --git a/go/src/internal/fmtsort/export_test.go b/go/src/internal/fmtsort/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..25cbb5d4fca9bbd08160ce639bc5ae0cf6d24575 --- /dev/null +++ b/go/src/internal/fmtsort/export_test.go @@ -0,0 +1,11 @@ +// 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 fmtsort + +import "reflect" + +func Compare(a, b reflect.Value) int { + return compare(a, b) +} diff --git a/go/src/internal/fmtsort/sort.go b/go/src/internal/fmtsort/sort.go new file mode 100644 index 0000000000000000000000000000000000000000..f51cdc7083a4b106bf6b9a16741c0a482e45b02e --- /dev/null +++ b/go/src/internal/fmtsort/sort.go @@ -0,0 +1,154 @@ +// 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 fmtsort provides a general stable ordering mechanism +// for maps, on behalf of the fmt and text/template packages. +// It is not guaranteed to be efficient and works only for types +// that are valid map keys. +package fmtsort + +import ( + "cmp" + "reflect" + "slices" +) + +// Note: Throughout this package we avoid calling reflect.Value.Interface as +// it is not always legal to do so and it's easier to avoid the issue than to face it. + +// SortedMap is a slice of KeyValue pairs that simplifies sorting +// and iterating over map entries. +// +// Each KeyValue pair contains a map key and its corresponding value. +type SortedMap []KeyValue + +// KeyValue holds a single key and value pair found in a map. +type KeyValue struct { + Key, Value reflect.Value +} + +// Sort accepts a map and returns a SortedMap that has the same keys and +// values but in a stable sorted order according to the keys, modulo issues +// raised by unorderable key values such as NaNs. +// +// The ordering rules are more general than with Go's < operator: +// +// - when applicable, nil compares low +// - ints, floats, and strings order by < +// - NaN compares less than non-NaN floats +// - bool compares false before true +// - complex compares real, then imag +// - pointers compare by machine address +// - channel values compare by machine address +// - structs compare each field in turn +// - arrays compare each element in turn. +// Otherwise identical arrays compare by length. +// - interface values compare first by reflect.Type describing the concrete type +// and then by concrete value as described in the previous rules. +func Sort(mapValue reflect.Value) SortedMap { + if mapValue.Type().Kind() != reflect.Map { + return nil + } + // Note: this code is arranged to not panic even in the presence + // of a concurrent map update. The runtime is responsible for + // yelling loudly if that happens. See issue 33275. + n := mapValue.Len() + sorted := make(SortedMap, 0, n) + iter := mapValue.MapRange() + for iter.Next() { + sorted = append(sorted, KeyValue{iter.Key(), iter.Value()}) + } + slices.SortStableFunc(sorted, func(a, b KeyValue) int { + return compare(a.Key, b.Key) + }) + return sorted +} + +// compare compares two values of the same type. It returns -1, 0, 1 +// according to whether a > b (1), a == b (0), or a < b (-1). +// If the types differ, it returns -1. +// See the comment on Sort for the comparison rules. +func compare(aVal, bVal reflect.Value) int { + aType, bType := aVal.Type(), bVal.Type() + if aType != bType { + return -1 // No good answer possible, but don't return 0: they're not equal. + } + switch aVal.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return cmp.Compare(aVal.Int(), bVal.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return cmp.Compare(aVal.Uint(), bVal.Uint()) + case reflect.String: + return cmp.Compare(aVal.String(), bVal.String()) + case reflect.Float32, reflect.Float64: + return cmp.Compare(aVal.Float(), bVal.Float()) + case reflect.Complex64, reflect.Complex128: + a, b := aVal.Complex(), bVal.Complex() + if c := cmp.Compare(real(a), real(b)); c != 0 { + return c + } + return cmp.Compare(imag(a), imag(b)) + case reflect.Bool: + a, b := aVal.Bool(), bVal.Bool() + switch { + case a == b: + return 0 + case a: + return 1 + default: + return -1 + } + case reflect.Pointer, reflect.UnsafePointer: + return cmp.Compare(aVal.Pointer(), bVal.Pointer()) + case reflect.Chan: + if c, ok := nilCompare(aVal, bVal); ok { + return c + } + return cmp.Compare(aVal.Pointer(), bVal.Pointer()) + case reflect.Struct: + for i := 0; i < aVal.NumField(); i++ { + if c := compare(aVal.Field(i), bVal.Field(i)); c != 0 { + return c + } + } + return 0 + case reflect.Array: + for i := 0; i < aVal.Len(); i++ { + if c := compare(aVal.Index(i), bVal.Index(i)); c != 0 { + return c + } + } + return 0 + case reflect.Interface: + if c, ok := nilCompare(aVal, bVal); ok { + return c + } + c := compare(reflect.ValueOf(aVal.Elem().Type()), reflect.ValueOf(bVal.Elem().Type())) + if c != 0 { + return c + } + return compare(aVal.Elem(), bVal.Elem()) + default: + // Certain types cannot appear as keys (maps, funcs, slices), but be explicit. + panic("bad type in compare: " + aType.String()) + } +} + +// nilCompare checks whether either value is nil. If not, the boolean is false. +// If either value is nil, the boolean is true and the integer is the comparison +// value. The comparison is defined to be 0 if both are nil, otherwise the one +// nil value compares low. Both arguments must represent a chan, func, +// interface, map, pointer, or slice. +func nilCompare(aVal, bVal reflect.Value) (int, bool) { + if aVal.IsNil() { + if bVal.IsNil() { + return 0, true + } + return -1, true + } + if bVal.IsNil() { + return 1, true + } + return 0, false +} diff --git a/go/src/internal/fmtsort/sort_test.go b/go/src/internal/fmtsort/sort_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3f2b8a1b839b3226fa505f8fe02b40bf58c8b3d6 --- /dev/null +++ b/go/src/internal/fmtsort/sort_test.go @@ -0,0 +1,280 @@ +// 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 fmtsort_test + +import ( + "cmp" + "fmt" + "internal/fmtsort" + "math" + "reflect" + "runtime" + "slices" + "strings" + "testing" + "unsafe" +) + +var compareTests = [][]reflect.Value{ + ct(reflect.TypeOf(int(0)), -1, 0, 1), + ct(reflect.TypeOf(int8(0)), -1, 0, 1), + ct(reflect.TypeOf(int16(0)), -1, 0, 1), + ct(reflect.TypeOf(int32(0)), -1, 0, 1), + ct(reflect.TypeOf(int64(0)), -1, 0, 1), + ct(reflect.TypeOf(uint(0)), 0, 1, 5), + ct(reflect.TypeOf(uint8(0)), 0, 1, 5), + ct(reflect.TypeOf(uint16(0)), 0, 1, 5), + ct(reflect.TypeOf(uint32(0)), 0, 1, 5), + ct(reflect.TypeOf(uint64(0)), 0, 1, 5), + ct(reflect.TypeOf(uintptr(0)), 0, 1, 5), + ct(reflect.TypeOf(string("")), "", "a", "ab"), + ct(reflect.TypeOf(float32(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)), + ct(reflect.TypeOf(float64(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)), + ct(reflect.TypeOf(complex64(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i), + ct(reflect.TypeOf(complex128(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i), + ct(reflect.TypeOf(false), false, true), + ct(reflect.TypeOf(&ints[0]), &ints[0], &ints[1], &ints[2]), + ct(reflect.TypeOf(unsafe.Pointer(&ints[0])), unsafe.Pointer(&ints[0]), unsafe.Pointer(&ints[1]), unsafe.Pointer(&ints[2])), + ct(reflect.TypeOf(chans[0]), chans[0], chans[1], chans[2]), + ct(reflect.TypeOf(toy{}), toy{0, 1}, toy{0, 2}, toy{1, -1}, toy{1, 1}), + ct(reflect.TypeOf([2]int{}), [2]int{1, 1}, [2]int{1, 2}, [2]int{2, 0}), + ct(reflect.TypeOf(any(0)), iFace, 1, 2, 3), +} + +var iFace any + +func ct(typ reflect.Type, args ...any) []reflect.Value { + value := make([]reflect.Value, len(args)) + for i, v := range args { + x := reflect.ValueOf(v) + if !x.IsValid() { // Make it a typed nil. + x = reflect.Zero(typ) + } else { + x = x.Convert(typ) + } + value[i] = x + } + return value +} + +func TestCompare(t *testing.T) { + for _, test := range compareTests { + for i, v0 := range test { + for j, v1 := range test { + c := fmtsort.Compare(v0, v1) + var expect int + switch { + case i == j: + expect = 0 + case i < j: + expect = -1 + case i > j: + expect = 1 + } + if c != expect { + t.Errorf("%s: compare(%v,%v)=%d; expect %d", v0.Type(), v0, v1, c, expect) + } + } + } + } +} + +type sortTest struct { + data any // Always a map. + print string // Printed result using our custom printer. +} + +var sortTests = []sortTest{ + { + map[int]string{7: "bar", -3: "foo"}, + "-3:foo 7:bar", + }, + { + map[uint8]string{7: "bar", 3: "foo"}, + "3:foo 7:bar", + }, + { + map[string]string{"7": "bar", "3": "foo"}, + "3:foo 7:bar", + }, + { + map[float64]string{7: "bar", -3: "foo", math.NaN(): "nan", math.Inf(0): "inf"}, + "NaN:nan -3:foo 7:bar +Inf:inf", + }, + { + map[complex128]string{7 + 2i: "bar2", 7 + 1i: "bar", -3: "foo", complex(math.NaN(), 0i): "nan", complex(math.Inf(0), 0i): "inf"}, + "(NaN+0i):nan (-3+0i):foo (7+1i):bar (7+2i):bar2 (+Inf+0i):inf", + }, + { + map[bool]string{true: "true", false: "false"}, + "false:false true:true", + }, + { + chanMap(), + "CHAN0:0 CHAN1:1 CHAN2:2", + }, + { + pointerMap(), + "PTR0:0 PTR1:1 PTR2:2", + }, + { + unsafePointerMap(), + "UNSAFEPTR0:0 UNSAFEPTR1:1 UNSAFEPTR2:2", + }, + { + map[toy]string{{7, 2}: "72", {7, 1}: "71", {3, 4}: "34"}, + "{3 4}:34 {7 1}:71 {7 2}:72", + }, + { + map[[2]int]string{{7, 2}: "72", {7, 1}: "71", {3, 4}: "34"}, + "[3 4]:34 [7 1]:71 [7 2]:72", + }, +} + +func sprint(data any) string { + om := fmtsort.Sort(reflect.ValueOf(data)) + if om == nil { + return "nil" + } + b := new(strings.Builder) + for i, m := range om { + if i > 0 { + b.WriteRune(' ') + } + b.WriteString(sprintKey(m.Key)) + b.WriteRune(':') + fmt.Fprint(b, m.Value) + } + return b.String() +} + +// sprintKey formats a reflect.Value but gives reproducible values for some +// problematic types such as pointers. Note that it only does special handling +// for the troublesome types used in the test cases; it is not a general +// printer. +func sprintKey(key reflect.Value) string { + switch str := key.Type().String(); str { + case "*int": + ptr := key.Interface().(*int) + for i := range ints { + if ptr == &ints[i] { + return fmt.Sprintf("PTR%d", i) + } + } + return "PTR???" + case "unsafe.Pointer": + ptr := key.Interface().(unsafe.Pointer) + for i := range ints { + if ptr == unsafe.Pointer(&ints[i]) { + return fmt.Sprintf("UNSAFEPTR%d", i) + } + } + return "UNSAFEPTR???" + case "chan int": + c := key.Interface().(chan int) + for i := range chans { + if c == chans[i] { + return fmt.Sprintf("CHAN%d", i) + } + } + return "CHAN???" + default: + return fmt.Sprint(key) + } +} + +var ( + ints [3]int + chans = makeChans() + pin runtime.Pinner +) + +func makeChans() []chan int { + cs := []chan int{make(chan int), make(chan int), make(chan int)} + // Order channels by address. See issue #49431. + for i := range cs { + pin.Pin(reflect.ValueOf(cs[i]).UnsafePointer()) + } + slices.SortFunc(cs, func(a, b chan int) int { + return cmp.Compare(reflect.ValueOf(a).Pointer(), reflect.ValueOf(b).Pointer()) + }) + return cs +} + +func pointerMap() map[*int]string { + m := make(map[*int]string) + for i := 2; i >= 0; i-- { + m[&ints[i]] = fmt.Sprint(i) + } + return m +} + +func unsafePointerMap() map[unsafe.Pointer]string { + m := make(map[unsafe.Pointer]string) + for i := 2; i >= 0; i-- { + m[unsafe.Pointer(&ints[i])] = fmt.Sprint(i) + } + return m +} + +func chanMap() map[chan int]string { + m := make(map[chan int]string) + for i := 2; i >= 0; i-- { + m[chans[i]] = fmt.Sprint(i) + } + return m +} + +type toy struct { + A int // Exported. + b int // Unexported. +} + +func TestOrder(t *testing.T) { + for _, test := range sortTests { + got := sprint(test.data) + if got != test.print { + t.Errorf("%s: got %q, want %q", reflect.TypeOf(test.data), got, test.print) + } + } +} + +func TestInterface(t *testing.T) { + // A map containing multiple concrete types should be sorted by type, + // then value. However, the relative ordering of types is unspecified, + // so test this by checking the presence of sorted subgroups. + m := map[any]string{ + [2]int{1, 0}: "", + [2]int{0, 1}: "", + true: "", + false: "", + 3.1: "", + 2.1: "", + 1.1: "", + math.NaN(): "", + 3: "", + 2: "", + 1: "", + "c": "", + "b": "", + "a": "", + struct{ x, y int }{1, 0}: "", + struct{ x, y int }{0, 1}: "", + } + got := sprint(m) + typeGroups := []string{ + "NaN: 1.1: 2.1: 3.1:", // float64 + "false: true:", // bool + "1: 2: 3:", // int + "a: b: c:", // string + "[0 1]: [1 0]:", // [2]int + "{0 1}: {1 0}:", // struct{ x int; y int } + } + for _, g := range typeGroups { + if !strings.Contains(got, g) { + t.Errorf("sorted map should contain %q", g) + } + } +} diff --git a/go/src/internal/fuzz/counters_supported.go b/go/src/internal/fuzz/counters_supported.go new file mode 100644 index 0000000000000000000000000000000000000000..a877239186b348190c3f24fe903a6c022173a2f1 --- /dev/null +++ b/go/src/internal/fuzz/counters_supported.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (darwin || linux || windows || freebsd || openbsd) && (amd64 || arm64 || loong64) + +package fuzz + +import ( + "unsafe" +) + +// coverage returns a []byte containing unique 8-bit counters for each edge of +// the instrumented source code. This coverage data will only be generated if +// `-d=libfuzzer` is set at build time. This can be used to understand the code +// coverage of a test execution. +func coverage() []byte { + addr := unsafe.Pointer(&_counters) + size := uintptr(unsafe.Pointer(&_ecounters)) - uintptr(addr) + return unsafe.Slice((*byte)(addr), int(size)) +} diff --git a/go/src/internal/fuzz/counters_unsupported.go b/go/src/internal/fuzz/counters_unsupported.go new file mode 100644 index 0000000000000000000000000000000000000000..af2b56cdd857e8b7ca9ed247d521e1346ec64c73 --- /dev/null +++ b/go/src/internal/fuzz/counters_unsupported.go @@ -0,0 +1,24 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// TODO: expand the set of supported platforms, with testing. Nothing about +// the instrumentation is OS specific, but only amd64 and arm64 are +// supported in the runtime. See src/runtime/libfuzzer*. +// +// If you update this constraint, also update internal/platform.FuzzInstrumented. +// +//go:build !((darwin || linux || windows || freebsd || openbsd) && (amd64 || arm64 || loong64)) + +package fuzz + +// TODO(#48504): re-enable on platforms where instrumentation works. +// In theory, we shouldn't need this file at all: if the binary was built +// without coverage, then _counters and _ecounters should have the same address. +// However, this caused an init failure on aix/ppc64, so it's disabled here. + +// coverage returns a []byte containing unique 8-bit counters for each edge of +// the instrumented source code. This coverage data will only be generated if +// `-d=libfuzzer` is set at build time. This can be used to understand the code +// coverage of a test execution. +func coverage() []byte { return nil } diff --git a/go/src/internal/fuzz/coverage.go b/go/src/internal/fuzz/coverage.go new file mode 100644 index 0000000000000000000000000000000000000000..8b39949b5dd6220d0eccc6801e1897517be619cb --- /dev/null +++ b/go/src/internal/fuzz/coverage.go @@ -0,0 +1,115 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "fmt" + "math/bits" +) + +// ResetCoverage sets all of the counters for each edge of the instrumented +// source code to 0. +func ResetCoverage() { + cov := coverage() + clear(cov) +} + +// SnapshotCoverage copies the current counter values into coverageSnapshot, +// preserving them for later inspection. SnapshotCoverage also rounds each +// counter down to the nearest power of two. This lets the coordinator store +// multiple values for each counter by OR'ing them together. +func SnapshotCoverage() { + cov := coverage() + for i, b := range cov { + coverageSnapshot[i] = pow2Table[b] + } +} + +// diffCoverage returns a set of bits set in snapshot but not in base. +// If there are no new bits set, diffCoverage returns nil. +func diffCoverage(base, snapshot []byte) []byte { + if len(base) != len(snapshot) { + panic(fmt.Sprintf("the number of coverage bits changed: before=%d, after=%d", len(base), len(snapshot))) + } + found := false + for i := range snapshot { + if snapshot[i]&^base[i] != 0 { + found = true + break + } + } + if !found { + return nil + } + diff := make([]byte, len(snapshot)) + for i := range diff { + diff[i] = snapshot[i] &^ base[i] + } + return diff +} + +// countNewCoverageBits returns the number of bits set in snapshot that are not +// set in base. +func countNewCoverageBits(base, snapshot []byte) int { + n := 0 + for i := range snapshot { + n += bits.OnesCount8(snapshot[i] &^ base[i]) + } + return n +} + +// isCoverageSubset returns true if all the base coverage bits are set in +// snapshot. +func isCoverageSubset(base, snapshot []byte) bool { + for i, v := range base { + if v&snapshot[i] != v { + return false + } + } + return true +} + +// hasCoverageBit returns true if snapshot has at least one bit set that is +// also set in base. +func hasCoverageBit(base, snapshot []byte) bool { + for i := range snapshot { + if snapshot[i]&base[i] != 0 { + return true + } + } + return false +} + +func countBits(cov []byte) int { + n := 0 + for _, c := range cov { + n += bits.OnesCount8(c) + } + return n +} + +var ( + coverageEnabled = len(coverage()) > 0 + coverageSnapshot = make([]byte, len(coverage())) + + // _counters and _ecounters mark the start and end, respectively, of where + // the 8-bit coverage counters reside in memory. They're known to cmd/link, + // which specially assigns their addresses for this purpose. + _counters, _ecounters [0]byte + + // lookup table for faster power of two rounding + pow2Table [256]byte +) + +func init() { + for i := range pow2Table { + b := byte(i) + b |= b >> 1 + b |= b >> 2 + b |= b >> 4 + b -= b >> 1 + pow2Table[i] = b + } +} diff --git a/go/src/internal/fuzz/encoding.go b/go/src/internal/fuzz/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..270ef7a1a3a887aab53c1e20ad8f92884e3aeed7 --- /dev/null +++ b/go/src/internal/fuzz/encoding.go @@ -0,0 +1,361 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "bytes" + "fmt" + "go/ast" + "go/parser" + "go/token" + "math" + "strconv" + "strings" + "unicode/utf8" +) + +// encVersion1 will be the first line of a file with version 1 encoding. +var encVersion1 = "go test fuzz v1" + +// marshalCorpusFile encodes an arbitrary number of arguments into the file format for the +// corpus. +func marshalCorpusFile(vals ...any) []byte { + if len(vals) == 0 { + panic("must have at least one value to marshal") + } + b := bytes.NewBuffer([]byte(encVersion1 + "\n")) + // TODO(katiehockman): keep uint8 and int32 encoding where applicable, + // instead of changing to byte and rune respectively. + for _, val := range vals { + switch t := val.(type) { + case int, int8, int16, int64, uint, uint16, uint32, uint64, bool: + fmt.Fprintf(b, "%T(%v)\n", t, t) + case float32: + if math.IsNaN(float64(t)) && math.Float32bits(t) != math.Float32bits(float32(math.NaN())) { + // We encode unusual NaNs as hex values, because that is how users are + // likely to encounter them in literature about floating-point encoding. + // This allows us to reproduce fuzz failures that depend on the specific + // NaN representation (for float32 there are about 2^24 possibilities!), + // not just the fact that the value is *a* NaN. + // + // Note that the specific value of float32(math.NaN()) can vary based on + // whether the architecture represents signaling NaNs using a low bit + // (as is common) or a high bit (as commonly implemented on MIPS + // hardware before around 2012). We believe that the increase in clarity + // from identifying "NaN" with math.NaN() is worth the slight ambiguity + // from a platform-dependent value. + fmt.Fprintf(b, "math.Float32frombits(0x%x)\n", math.Float32bits(t)) + } else { + // We encode all other values — including the NaN value that is + // bitwise-identical to float32(math.Nan()) — using the default + // formatting, which is equivalent to strconv.FormatFloat with format + // 'g' and can be parsed by strconv.ParseFloat. + // + // For an ordinary floating-point number this format includes + // sufficiently many digits to reconstruct the exact value. For positive + // or negative infinity it is the string "+Inf" or "-Inf". For positive + // or negative zero it is "0" or "-0". For NaN, it is the string "NaN". + fmt.Fprintf(b, "%T(%v)\n", t, t) + } + case float64: + if math.IsNaN(t) && math.Float64bits(t) != math.Float64bits(math.NaN()) { + fmt.Fprintf(b, "math.Float64frombits(0x%x)\n", math.Float64bits(t)) + } else { + fmt.Fprintf(b, "%T(%v)\n", t, t) + } + case string: + fmt.Fprintf(b, "string(%q)\n", t) + case rune: // int32 + // Although rune and int32 are represented by the same type, only a subset + // of valid int32 values can be expressed as rune literals. Notably, + // negative numbers, surrogate halves, and values above unicode.MaxRune + // have no quoted representation. + // + // fmt with "%q" (and the corresponding functions in the strconv package) + // would quote out-of-range values to the Unicode replacement character + // instead of the original value (see https://go.dev/issue/51526), so + // they must be treated as int32 instead. + // + // We arbitrarily draw the line at UTF-8 validity, which biases toward the + // "rune" interpretation. (However, we accept either format as input.) + if utf8.ValidRune(t) { + fmt.Fprintf(b, "rune(%q)\n", t) + } else { + fmt.Fprintf(b, "int32(%v)\n", t) + } + case byte: // uint8 + // For bytes, we arbitrarily prefer the character interpretation. + // (Every byte has a valid character encoding.) + fmt.Fprintf(b, "byte(%q)\n", t) + case []byte: // []uint8 + fmt.Fprintf(b, "[]byte(%q)\n", t) + default: + panic(fmt.Sprintf("unsupported type: %T", t)) + } + } + return b.Bytes() +} + +// unmarshalCorpusFile decodes corpus bytes into their respective values. +func unmarshalCorpusFile(b []byte) ([]any, error) { + if len(b) == 0 { + return nil, fmt.Errorf("cannot unmarshal empty string") + } + lines := bytes.Split(b, []byte("\n")) + if len(lines) < 2 { + return nil, fmt.Errorf("must include version and at least one value") + } + version := strings.TrimSuffix(string(lines[0]), "\r") + if version != encVersion1 { + return nil, fmt.Errorf("unknown encoding version: %s", version) + } + var vals []any + for _, line := range lines[1:] { + line = bytes.TrimSpace(line) + if len(line) == 0 { + continue + } + v, err := parseCorpusValue(line) + if err != nil { + return nil, fmt.Errorf("malformed line %q: %v", line, err) + } + vals = append(vals, v) + } + return vals, nil +} + +func parseCorpusValue(line []byte) (any, error) { + fs := token.NewFileSet() + expr, err := parser.ParseExprFrom(fs, "(test)", line, 0) + if err != nil { + return nil, err + } + call, ok := expr.(*ast.CallExpr) + if !ok { + return nil, fmt.Errorf("expected call expression") + } + if len(call.Args) != 1 { + return nil, fmt.Errorf("expected call expression with 1 argument; got %d", len(call.Args)) + } + arg := call.Args[0] + + if arrayType, ok := call.Fun.(*ast.ArrayType); ok { + if arrayType.Len != nil { + return nil, fmt.Errorf("expected []byte or primitive type") + } + elt, ok := arrayType.Elt.(*ast.Ident) + if !ok || elt.Name != "byte" { + return nil, fmt.Errorf("expected []byte") + } + lit, ok := arg.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return nil, fmt.Errorf("string literal required for type []byte") + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + return nil, err + } + return []byte(s), nil + } + + var idType *ast.Ident + if selector, ok := call.Fun.(*ast.SelectorExpr); ok { + xIdent, ok := selector.X.(*ast.Ident) + if !ok || xIdent.Name != "math" { + return nil, fmt.Errorf("invalid selector type") + } + switch selector.Sel.Name { + case "Float64frombits": + idType = &ast.Ident{Name: "float64-bits"} + case "Float32frombits": + idType = &ast.Ident{Name: "float32-bits"} + default: + return nil, fmt.Errorf("invalid selector type") + } + } else { + idType, ok = call.Fun.(*ast.Ident) + if !ok { + return nil, fmt.Errorf("expected []byte or primitive type") + } + if idType.Name == "bool" { + id, ok := arg.(*ast.Ident) + if !ok { + return nil, fmt.Errorf("malformed bool") + } + if id.Name == "true" { + return true, nil + } else if id.Name == "false" { + return false, nil + } else { + return nil, fmt.Errorf("true or false required for type bool") + } + } + } + + var ( + val string + kind token.Token + ) + if op, ok := arg.(*ast.UnaryExpr); ok { + switch lit := op.X.(type) { + case *ast.BasicLit: + if op.Op != token.SUB { + return nil, fmt.Errorf("unsupported operation on int/float: %v", op.Op) + } + // Special case for negative numbers. + val = op.Op.String() + lit.Value // e.g. "-" + "124" + kind = lit.Kind + case *ast.Ident: + if lit.Name != "Inf" { + return nil, fmt.Errorf("expected operation on int or float type") + } + if op.Op == token.SUB { + val = "-Inf" + } else { + val = "+Inf" + } + kind = token.FLOAT + default: + return nil, fmt.Errorf("expected operation on int or float type") + } + } else { + switch lit := arg.(type) { + case *ast.BasicLit: + val, kind = lit.Value, lit.Kind + case *ast.Ident: + if lit.Name != "NaN" { + return nil, fmt.Errorf("literal value required for primitive type") + } + val, kind = "NaN", token.FLOAT + default: + return nil, fmt.Errorf("literal value required for primitive type") + } + } + + switch typ := idType.Name; typ { + case "string": + if kind != token.STRING { + return nil, fmt.Errorf("string literal value required for type string") + } + return strconv.Unquote(val) + case "byte", "rune": + if kind == token.INT { + switch typ { + case "rune": + return parseInt(val, typ) + case "byte": + return parseUint(val, typ) + } + } + if kind != token.CHAR { + return nil, fmt.Errorf("character literal required for byte/rune types") + } + n := len(val) + if n < 2 { + return nil, fmt.Errorf("malformed character literal, missing single quotes") + } + code, _, _, err := strconv.UnquoteChar(val[1:n-1], '\'') + if err != nil { + return nil, err + } + if typ == "rune" { + return code, nil + } + if code >= 256 { + return nil, fmt.Errorf("can only encode single byte to a byte type") + } + return byte(code), nil + case "int", "int8", "int16", "int32", "int64": + if kind != token.INT { + return nil, fmt.Errorf("integer literal required for int types") + } + return parseInt(val, typ) + case "uint", "uint8", "uint16", "uint32", "uint64": + if kind != token.INT { + return nil, fmt.Errorf("integer literal required for uint types") + } + return parseUint(val, typ) + case "float32": + if kind != token.FLOAT && kind != token.INT { + return nil, fmt.Errorf("float or integer literal required for float32 type") + } + v, err := strconv.ParseFloat(val, 32) + return float32(v), err + case "float64": + if kind != token.FLOAT && kind != token.INT { + return nil, fmt.Errorf("float or integer literal required for float64 type") + } + return strconv.ParseFloat(val, 64) + case "float32-bits": + if kind != token.INT { + return nil, fmt.Errorf("integer literal required for math.Float32frombits type") + } + bits, err := parseUint(val, "uint32") + if err != nil { + return nil, err + } + return math.Float32frombits(bits.(uint32)), nil + case "float64-bits": + if kind != token.FLOAT && kind != token.INT { + return nil, fmt.Errorf("integer literal required for math.Float64frombits type") + } + bits, err := parseUint(val, "uint64") + if err != nil { + return nil, err + } + return math.Float64frombits(bits.(uint64)), nil + default: + return nil, fmt.Errorf("expected []byte or primitive type") + } +} + +// parseInt returns an integer of value val and type typ. +func parseInt(val, typ string) (any, error) { + switch typ { + case "int": + // The int type may be either 32 or 64 bits. If 32, the fuzz tests in the + // corpus may include 64-bit values produced by fuzzing runs on 64-bit + // architectures. When running those tests, we implicitly wrap the values to + // fit in a regular int. (The test case is still “interesting”, even if the + // specific values of its inputs are platform-dependent.) + i, err := strconv.ParseInt(val, 0, 64) + return int(i), err + case "int8": + i, err := strconv.ParseInt(val, 0, 8) + return int8(i), err + case "int16": + i, err := strconv.ParseInt(val, 0, 16) + return int16(i), err + case "int32", "rune": + i, err := strconv.ParseInt(val, 0, 32) + return int32(i), err + case "int64": + return strconv.ParseInt(val, 0, 64) + default: + panic("unreachable") + } +} + +// parseUint returns an unsigned integer of value val and type typ. +func parseUint(val, typ string) (any, error) { + switch typ { + case "uint": + i, err := strconv.ParseUint(val, 0, 64) + return uint(i), err + case "uint8", "byte": + i, err := strconv.ParseUint(val, 0, 8) + return uint8(i), err + case "uint16": + i, err := strconv.ParseUint(val, 0, 16) + return uint16(i), err + case "uint32": + i, err := strconv.ParseUint(val, 0, 32) + return uint32(i), err + case "uint64": + return strconv.ParseUint(val, 0, 64) + default: + panic("unreachable") + } +} diff --git a/go/src/internal/fuzz/encoding_test.go b/go/src/internal/fuzz/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5f2af4476b86527153931392d09d732379634822 --- /dev/null +++ b/go/src/internal/fuzz/encoding_test.go @@ -0,0 +1,404 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "math" + "strconv" + "testing" + "unicode" +) + +func TestUnmarshalMarshal(t *testing.T) { + var tests = []struct { + desc string + in string + reject bool + want string // if different from in + }{ + { + desc: "missing version", + in: "int(1234)", + reject: true, + }, + { + desc: "malformed string", + in: `go test fuzz v1 +string("a"bcad")`, + reject: true, + }, + { + desc: "empty value", + in: `go test fuzz v1 +int()`, + reject: true, + }, + { + desc: "negative uint", + in: `go test fuzz v1 +uint(-32)`, + reject: true, + }, + { + desc: "int8 too large", + in: `go test fuzz v1 +int8(1234456)`, + reject: true, + }, + { + desc: "multiplication in int value", + in: `go test fuzz v1 +int(20*5)`, + reject: true, + }, + { + desc: "double negation", + in: `go test fuzz v1 +int(--5)`, + reject: true, + }, + { + desc: "malformed bool", + in: `go test fuzz v1 +bool(0)`, + reject: true, + }, + { + desc: "malformed byte", + in: `go test fuzz v1 +byte('aa)`, + reject: true, + }, + { + desc: "byte out of range", + in: `go test fuzz v1 +byte('☃')`, + reject: true, + }, + { + desc: "extra newline", + in: `go test fuzz v1 +string("has extra newline") +`, + want: `go test fuzz v1 +string("has extra newline")`, + }, + { + desc: "trailing spaces", + in: `go test fuzz v1 +string("extra") +[]byte("spacing") + `, + want: `go test fuzz v1 +string("extra") +[]byte("spacing")`, + }, + { + desc: "float types", + in: `go test fuzz v1 +float64(0) +float32(0)`, + }, + { + desc: "various types", + in: `go test fuzz v1 +int(-23) +int8(-2) +int64(2342425) +uint(1) +uint16(234) +uint32(352342) +uint64(123) +rune('œ') +byte('K') +byte('ÿ') +[]byte("hello¿") +[]byte("a") +bool(true) +string("hello\\xbd\\xb2=\\xbc ⌘") +float64(-12.5) +float32(2.5)`, + }, + { + desc: "float edge cases", + // The two IEEE 754 bit patterns used for the math.Float{64,32}frombits + // encodings are non-math.NAN quiet-NaN values. Since they are not equal + // to math.NaN(), they should be re-encoded to their bit patterns. They + // are, respectively: + // * math.Float64bits(math.NaN())+1 + // * math.Float32bits(float32(math.NaN()))+1 + in: `go test fuzz v1 +float32(-0) +float64(-0) +float32(+Inf) +float32(-Inf) +float32(NaN) +float64(+Inf) +float64(-Inf) +float64(NaN) +math.Float64frombits(0x7ff8000000000002) +math.Float32frombits(0x7fc00001)`, + }, + { + desc: "int variations", + // Although we arbitrarily choose default integer bases (0 or 16), we may + // want to change those arbitrary choices in the future and should not + // break the parser. Verify that integers in the opposite bases still + // parse correctly. + in: `go test fuzz v1 +int(0x0) +int32(0x41) +int64(0xfffffffff) +uint32(0xcafef00d) +uint64(0xffffffffffffffff) +uint8(0b0000000) +byte(0x0) +byte('\000') +byte('\u0000') +byte('\'') +math.Float64frombits(9221120237041090562) +math.Float32frombits(2143289345)`, + want: `go test fuzz v1 +int(0) +rune('A') +int64(68719476735) +uint32(3405705229) +uint64(18446744073709551615) +byte('\x00') +byte('\x00') +byte('\x00') +byte('\x00') +byte('\'') +math.Float64frombits(0x7ff8000000000002) +math.Float32frombits(0x7fc00001)`, + }, + { + desc: "rune validation", + in: `go test fuzz v1 +rune(0) +rune(0x41) +rune(-1) +rune(0xfffd) +rune(0xd800) +rune(0x10ffff) +rune(0x110000) +`, + want: `go test fuzz v1 +rune('\x00') +rune('A') +int32(-1) +rune('�') +int32(55296) +rune('\U0010ffff') +int32(1114112)`, + }, + { + desc: "int overflow", + in: `go test fuzz v1 +int(0x7fffffffffffffff) +uint(0xffffffffffffffff)`, + want: func() string { + switch strconv.IntSize { + case 32: + return `go test fuzz v1 +int(-1) +uint(4294967295)` + case 64: + return `go test fuzz v1 +int(9223372036854775807) +uint(18446744073709551615)` + default: + panic("unreachable") + } + }(), + }, + { + desc: "windows new line", + in: "go test fuzz v1\r\nint(0)\r\n", + want: "go test fuzz v1\nint(0)", + }, + } + for _, test := range tests { + t.Run(test.desc, func(t *testing.T) { + vals, err := unmarshalCorpusFile([]byte(test.in)) + if test.reject { + if err == nil { + t.Fatalf("unmarshal unexpected success") + } + return + } + if err != nil { + t.Fatalf("unmarshal unexpected error: %v", err) + } + newB := marshalCorpusFile(vals...) + if newB[len(newB)-1] != '\n' { + t.Error("didn't write final newline to corpus file") + } + + want := test.want + if want == "" { + want = test.in + } + want += "\n" + got := string(newB) + if got != want { + t.Errorf("unexpected marshaled value\ngot:\n%s\nwant:\n%s", got, want) + } + }) + } +} + +// BenchmarkMarshalCorpusFile measures the time it takes to serialize byte +// slices of various sizes to a corpus file. The slice contains a repeating +// sequence of bytes 0-255 to mix escaped and non-escaped characters. +func BenchmarkMarshalCorpusFile(b *testing.B) { + buf := make([]byte, 1024*1024) + for i := 0; i < len(buf); i++ { + buf[i] = byte(i) + } + + for sz := 1; sz <= len(buf); sz <<= 1 { + b.Run(strconv.Itoa(sz), func(b *testing.B) { + for i := 0; i < b.N; i++ { + b.SetBytes(int64(sz)) + marshalCorpusFile(buf[:sz]) + } + }) + } +} + +// BenchmarkUnmarshalCorpusfile measures the time it takes to deserialize +// files encoding byte slices of various sizes. The slice contains a repeating +// sequence of bytes 0-255 to mix escaped and non-escaped characters. +func BenchmarkUnmarshalCorpusFile(b *testing.B) { + buf := make([]byte, 1024*1024) + for i := 0; i < len(buf); i++ { + buf[i] = byte(i) + } + + for sz := 1; sz <= len(buf); sz <<= 1 { + data := marshalCorpusFile(buf[:sz]) + b.Run(strconv.Itoa(sz), func(b *testing.B) { + for i := 0; i < b.N; i++ { + b.SetBytes(int64(sz)) + unmarshalCorpusFile(data) + } + }) + } +} + +func TestByteRoundTrip(t *testing.T) { + for x := 0; x < 256; x++ { + b1 := byte(x) + buf := marshalCorpusFile(b1) + vs, err := unmarshalCorpusFile(buf) + if err != nil { + t.Fatal(err) + } + b2 := vs[0].(byte) + if b2 != b1 { + t.Fatalf("unmarshaled %v, want %v:\n%s", b2, b1, buf) + } + } +} + +func TestInt8RoundTrip(t *testing.T) { + for x := -128; x < 128; x++ { + i1 := int8(x) + buf := marshalCorpusFile(i1) + vs, err := unmarshalCorpusFile(buf) + if err != nil { + t.Fatal(err) + } + i2 := vs[0].(int8) + if i2 != i1 { + t.Fatalf("unmarshaled %v, want %v:\n%s", i2, i1, buf) + } + } +} + +func FuzzFloat64RoundTrip(f *testing.F) { + f.Add(math.Float64bits(0)) + f.Add(math.Float64bits(math.Copysign(0, -1))) + f.Add(math.Float64bits(math.MaxFloat64)) + f.Add(math.Float64bits(math.SmallestNonzeroFloat64)) + f.Add(math.Float64bits(math.NaN())) + f.Add(uint64(0x7FF0000000000001)) // signaling NaN + f.Add(math.Float64bits(math.Inf(1))) + f.Add(math.Float64bits(math.Inf(-1))) + + f.Fuzz(func(t *testing.T, u1 uint64) { + x1 := math.Float64frombits(u1) + + b := marshalCorpusFile(x1) + t.Logf("marshaled math.Float64frombits(0x%x):\n%s", u1, b) + + xs, err := unmarshalCorpusFile(b) + if err != nil { + t.Fatal(err) + } + if len(xs) != 1 { + t.Fatalf("unmarshaled %d values", len(xs)) + } + x2 := xs[0].(float64) + u2 := math.Float64bits(x2) + if u2 != u1 { + t.Errorf("unmarshaled %v (bits 0x%x)", x2, u2) + } + }) +} + +func FuzzRuneRoundTrip(f *testing.F) { + f.Add(rune(-1)) + f.Add(rune(0xd800)) + f.Add(rune(0xdfff)) + f.Add(rune(unicode.ReplacementChar)) + f.Add(rune(unicode.MaxASCII)) + f.Add(rune(unicode.MaxLatin1)) + f.Add(rune(unicode.MaxRune)) + f.Add(rune(unicode.MaxRune + 1)) + f.Add(rune(-0x80000000)) + f.Add(rune(0x7fffffff)) + + f.Fuzz(func(t *testing.T, r1 rune) { + b := marshalCorpusFile(r1) + t.Logf("marshaled rune(0x%x):\n%s", r1, b) + + rs, err := unmarshalCorpusFile(b) + if err != nil { + t.Fatal(err) + } + if len(rs) != 1 { + t.Fatalf("unmarshaled %d values", len(rs)) + } + r2 := rs[0].(rune) + if r2 != r1 { + t.Errorf("unmarshaled rune(0x%x)", r2) + } + }) +} + +func FuzzStringRoundTrip(f *testing.F) { + f.Add("") + f.Add("\x00") + f.Add(string([]rune{unicode.ReplacementChar})) + + f.Fuzz(func(t *testing.T, s1 string) { + b := marshalCorpusFile(s1) + t.Logf("marshaled %q:\n%s", s1, b) + + rs, err := unmarshalCorpusFile(b) + if err != nil { + t.Fatal(err) + } + if len(rs) != 1 { + t.Fatalf("unmarshaled %d values", len(rs)) + } + s2 := rs[0].(string) + if s2 != s1 { + t.Errorf("unmarshaled %q", s2) + } + }) +} diff --git a/go/src/internal/fuzz/fuzz.go b/go/src/internal/fuzz/fuzz.go new file mode 100644 index 0000000000000000000000000000000000000000..e406c8c400400aa9dda777969c8b39b659e286f4 --- /dev/null +++ b/go/src/internal/fuzz/fuzz.go @@ -0,0 +1,1102 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package fuzz provides common fuzzing functionality for tests built with +// "go test" and for programs that use fuzzing functionality in the testing +// package. +package fuzz + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "internal/godebug" + "io" + "math/bits" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "time" +) + +// CoordinateFuzzingOpts is a set of arguments for CoordinateFuzzing. +// The zero value is valid for each field unless specified otherwise. +type CoordinateFuzzingOpts struct { + // Log is a writer for logging progress messages and warnings. + // If nil, io.Discard will be used instead. + Log io.Writer + + // Timeout is the amount of wall clock time to spend fuzzing after the corpus + // has loaded. If zero, there will be no time limit. + Timeout time.Duration + + // Limit is the number of random values to generate and test. If zero, + // there will be no limit on the number of generated values. + Limit int64 + + // MinimizeTimeout is the amount of wall clock time to spend minimizing + // after discovering a crasher. If zero, there will be no time limit. If + // MinimizeTimeout and MinimizeLimit are both zero, then minimization will + // be disabled. + MinimizeTimeout time.Duration + + // MinimizeLimit is the maximum number of calls to the fuzz function to be + // made while minimizing after finding a crash. If zero, there will be no + // limit. Calls to the fuzz function made when minimizing also count toward + // Limit. If MinimizeTimeout and MinimizeLimit are both zero, then + // minimization will be disabled. + MinimizeLimit int64 + + // parallel is the number of worker processes to run in parallel. If zero, + // CoordinateFuzzing will run GOMAXPROCS workers. + Parallel int + + // Seed is a list of seed values added by the fuzz target with testing.F.Add + // and in testdata. + Seed []CorpusEntry + + // Types is the list of types which make up a corpus entry. + // Types must be set and must match values in Seed. + Types []reflect.Type + + // CorpusDir is a directory where files containing values that crash the + // code being tested may be written. CorpusDir must be set. + CorpusDir string + + // CacheDir is a directory containing additional "interesting" values. + // The fuzzer may derive new values from these, and may write new values here. + CacheDir string +} + +// CoordinateFuzzing creates several worker processes and communicates with +// them to test random inputs that could trigger crashes and expose bugs. +// The worker processes run the same binary in the same directory with the +// same environment variables as the coordinator process. Workers also run +// with the same arguments as the coordinator, except with the -test.fuzzworker +// flag prepended to the argument list. +// +// If a crash occurs, the function will return an error containing information +// about the crash, which can be reported to the user. +func CoordinateFuzzing(ctx context.Context, opts CoordinateFuzzingOpts) (err error) { + if err := ctx.Err(); err != nil { + return err + } + if opts.Log == nil { + opts.Log = io.Discard + } + if opts.Parallel == 0 { + opts.Parallel = runtime.GOMAXPROCS(0) + } + if opts.Limit > 0 && int64(opts.Parallel) > opts.Limit { + // Don't start more workers than we need. + opts.Parallel = int(opts.Limit) + } + + c, err := newCoordinator(opts) + if err != nil { + return err + } + + if opts.Timeout > 0 { + var cancel func() + ctx, cancel = context.WithTimeout(ctx, opts.Timeout) + defer cancel() + } + + // fuzzCtx is used to stop workers, for example, after finding a crasher. + fuzzCtx, cancelWorkers := context.WithCancel(ctx) + defer cancelWorkers() + doneC := ctx.Done() + + // stop is called when a worker encounters a fatal error. + var fuzzErr error + stopping := false + stop := func(err error) { + if shouldPrintDebugInfo() { + _, file, line, ok := runtime.Caller(1) + if ok { + c.debugLogf("stop called at %s:%d. stopping: %t", file, line, stopping) + } else { + c.debugLogf("stop called at unknown. stopping: %t", stopping) + } + } + + if err == fuzzCtx.Err() || isInterruptError(err) { + // Suppress cancellation errors and terminations due to SIGINT. + // The messages are not helpful since either the user triggered the error + // (with ^C) or another more helpful message will be printed (a crasher). + err = nil + } + if err != nil && (fuzzErr == nil || fuzzErr == ctx.Err()) { + fuzzErr = err + } + if stopping { + return + } + stopping = true + cancelWorkers() + doneC = nil + } + + // Ensure that any crash we find is written to the corpus, even if an error + // or interruption occurs while minimizing it. + crashWritten := false + defer func() { + if c.crashMinimizing == nil || crashWritten { + return + } + werr := writeToCorpus(&c.crashMinimizing.entry, opts.CorpusDir) + if werr != nil { + err = fmt.Errorf("%w\n%v", err, werr) + return + } + if err == nil { + err = &crashError{ + path: c.crashMinimizing.entry.Path, + err: errors.New(c.crashMinimizing.crasherMsg), + } + } + }() + + // Start workers. + // TODO(jayconrod): do we want to support fuzzing different binaries? + dir := "" // same as self + binPath := os.Args[0] + args := append([]string{"-test.fuzzworker"}, os.Args[1:]...) + env := os.Environ() // same as self + + errC := make(chan error) + workers := make([]*worker, opts.Parallel) + for i := range workers { + var err error + workers[i], err = newWorker(c, dir, binPath, args, env) + if err != nil { + return err + } + } + for i := range workers { + w := workers[i] + go func() { + err := w.coordinate(fuzzCtx) + if fuzzCtx.Err() != nil || isInterruptError(err) { + err = nil + } + cleanErr := w.cleanup() + if err == nil { + err = cleanErr + } + errC <- err + }() + } + + // Main event loop. + // Do not return until all workers have terminated. We avoid a deadlock by + // receiving messages from workers even after ctx is canceled. + activeWorkers := len(workers) + statTicker := time.NewTicker(3 * time.Second) + defer statTicker.Stop() + defer c.logStats() + + c.logStats() + for { + // If there is an execution limit, and we've reached it, stop. + if c.opts.Limit > 0 && c.count >= c.opts.Limit { + stop(nil) + } + + var inputC chan fuzzInput + input, ok := c.peekInput() + if ok && c.crashMinimizing == nil && !stopping { + inputC = c.inputC + } + + var minimizeC chan fuzzMinimizeInput + minimizeInput, ok := c.peekMinimizeInput() + if ok && !stopping { + minimizeC = c.minimizeC + } + + select { + case <-doneC: + // Interrupted, canceled, or timed out. + // stop sets doneC to nil, so we don't busy wait here. + stop(ctx.Err()) + + case err := <-errC: + // A worker terminated, possibly after encountering a fatal error. + stop(err) + activeWorkers-- + if activeWorkers == 0 { + return fuzzErr + } + + case result := <-c.resultC: + // Received response from worker. + if stopping { + break + } + c.updateStats(result) + + if result.crasherMsg != "" { + if c.warmupRun() && result.entry.IsSeed { + target := filepath.Base(c.opts.CorpusDir) + fmt.Fprintf(c.opts.Log, "failure while testing seed corpus entry: %s/%s\n", target, testName(result.entry.Parent)) + stop(errors.New(result.crasherMsg)) + break + } + if c.canMinimize() && result.canMinimize { + if c.crashMinimizing != nil { + // This crash is not minimized, and another crash is being minimized. + // Ignore this one and wait for the other one to finish. + if shouldPrintDebugInfo() { + c.debugLogf("found unminimized crasher, skipping in favor of minimizable crasher") + } + break + } + // Found a crasher but haven't yet attempted to minimize it. + // Send it back to a worker for minimization. Disable inputC so + // other workers don't continue fuzzing. + c.crashMinimizing = &result + fmt.Fprintf(c.opts.Log, "fuzz: minimizing %d-byte failing input file\n", len(result.entry.Data)) + c.queueForMinimization(result, nil) + } else if !crashWritten { + // Found a crasher that's either minimized or not minimizable. + // Write to corpus and stop. + err := writeToCorpus(&result.entry, opts.CorpusDir) + if err == nil { + crashWritten = true + err = &crashError{ + path: result.entry.Path, + err: errors.New(result.crasherMsg), + } + } + if shouldPrintDebugInfo() { + c.debugLogf( + "found crasher, id: %s, parent: %s, gen: %d, size: %d, exec time: %s", + result.entry.Path, + result.entry.Parent, + result.entry.Generation, + len(result.entry.Data), + result.entryDuration, + ) + } + stop(err) + } + } else if result.coverageData != nil { + if c.warmupRun() { + if shouldPrintDebugInfo() { + c.debugLogf( + "processed an initial input, id: %s, new bits: %d, size: %d, exec time: %s", + result.entry.Parent, + countBits(diffCoverage(c.coverageMask, result.coverageData)), + len(result.entry.Data), + result.entryDuration, + ) + } + c.updateCoverage(result.coverageData) + c.warmupInputLeft-- + if c.warmupInputLeft == 0 { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, gathering baseline coverage: %d/%d completed, now fuzzing with %d workers\n", c.elapsed(), c.warmupInputCount, c.warmupInputCount, c.opts.Parallel) + if shouldPrintDebugInfo() { + c.debugLogf( + "finished processing input corpus, entries: %d, initial coverage bits: %d", + len(c.corpus.entries), + countBits(c.coverageMask), + ) + } + } + } else if keepCoverage := diffCoverage(c.coverageMask, result.coverageData); keepCoverage != nil { + // Found a value that expanded coverage. + // It's not a crasher, but we may want to add it to the on-disk + // corpus and prioritize it for future fuzzing. + // TODO(jayconrod, katiehockman): Prioritize fuzzing these + // values which expanded coverage, perhaps based on the + // number of new edges that this result expanded. + // TODO(jayconrod, katiehockman): Don't write a value that's already + // in the corpus. + if c.canMinimize() && result.canMinimize && c.crashMinimizing == nil { + // Send back to workers to find a smaller value that preserves + // at least one new coverage bit. + c.queueForMinimization(result, keepCoverage) + } else { + // Update the coordinator's coverage mask and save the value. + inputSize := len(result.entry.Data) + entryNew, err := c.addCorpusEntries(true, result.entry) + if err != nil { + stop(err) + break + } + if !entryNew { + if shouldPrintDebugInfo() { + c.debugLogf( + "ignoring duplicate input which increased coverage, id: %s", + result.entry.Path, + ) + } + break + } + c.updateCoverage(keepCoverage) + c.inputQueue.enqueue(result.entry) + c.interestingCount++ + if shouldPrintDebugInfo() { + c.debugLogf( + "new interesting input, id: %s, parent: %s, gen: %d, new bits: %d, total bits: %d, size: %d, exec time: %s", + result.entry.Path, + result.entry.Parent, + result.entry.Generation, + countBits(keepCoverage), + countBits(c.coverageMask), + inputSize, + result.entryDuration, + ) + } + } + } else { + if shouldPrintDebugInfo() { + c.debugLogf( + "worker reported interesting input that doesn't expand coverage, id: %s, parent: %s, canMinimize: %t", + result.entry.Path, + result.entry.Parent, + result.canMinimize, + ) + } + } + } else if c.warmupRun() { + // No error or coverage data was reported for this input during + // warmup, so continue processing results. + c.warmupInputLeft-- + if c.warmupInputLeft == 0 { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, testing seed corpus: %d/%d completed, now fuzzing with %d workers\n", c.elapsed(), c.warmupInputCount, c.warmupInputCount, c.opts.Parallel) + if shouldPrintDebugInfo() { + c.debugLogf( + "finished testing-only phase, entries: %d", + len(c.corpus.entries), + ) + } + } + } + + case inputC <- input: + // Sent the next input to a worker. + c.sentInput(input) + + case minimizeC <- minimizeInput: + // Sent the next input for minimization to a worker. + c.sentMinimizeInput(minimizeInput) + + case <-statTicker.C: + c.logStats() + } + } + + // TODO(jayconrod,katiehockman): if a crasher can't be written to the corpus, + // write to the cache instead. +} + +// crashError wraps a crasher written to the seed corpus. It saves the name +// of the file where the input causing the crasher was saved. The testing +// framework uses this to report a command to re-run that specific input. +type crashError struct { + path string + err error +} + +func (e *crashError) Error() string { + return e.err.Error() +} + +func (e *crashError) Unwrap() error { + return e.err +} + +func (e *crashError) CrashPath() string { + return e.path +} + +type corpus struct { + entries []CorpusEntry + hashes map[[sha256.Size]byte]bool +} + +// addCorpusEntries adds entries to the corpus, and optionally writes the entries +// to the cache directory. If an entry is already in the corpus it is skipped. If +// all of the entries are unique, addCorpusEntries returns true and a nil error, +// if at least one of the entries was a duplicate, it returns false and a nil error. +func (c *coordinator) addCorpusEntries(addToCache bool, entries ...CorpusEntry) (bool, error) { + noDupes := true + for _, e := range entries { + data, err := corpusEntryData(e) + if err != nil { + return false, err + } + h := sha256.Sum256(data) + if c.corpus.hashes[h] { + noDupes = false + continue + } + if addToCache { + if err := writeToCorpus(&e, c.opts.CacheDir); err != nil { + return false, err + } + // For entries written to disk, we don't hold onto the bytes, + // since the corpus would consume a significant amount of + // memory. + e.Data = nil + } + c.corpus.hashes[h] = true + c.corpus.entries = append(c.corpus.entries, e) + } + return noDupes, nil +} + +// CorpusEntry represents an individual input for fuzzing. +// +// We must use an equivalent type in the testing and testing/internal/testdeps +// packages, but testing can't import this package directly, and we don't want +// to export this type from testing. Instead, we use the same struct type and +// use a type alias (not a defined type) for convenience. +type CorpusEntry = struct { + Parent string + + // Path is the path of the corpus file, if the entry was loaded from disk. + // For other entries, including seed values provided by f.Add, Path is the + // name of the test, e.g. seed#0 or its hash. + Path string + + // Data is the raw input data. Data should only be populated for seed + // values. For on-disk corpus files, Data will be nil, as it will be loaded + // from disk using Path. + Data []byte + + // Values is the unmarshaled values from a corpus file. + Values []any + + Generation int + + // IsSeed indicates whether this entry is part of the seed corpus. + IsSeed bool +} + +// corpusEntryData returns the raw input bytes, either from the data struct +// field, or from disk. +func corpusEntryData(ce CorpusEntry) ([]byte, error) { + if ce.Data != nil { + return ce.Data, nil + } + + return os.ReadFile(ce.Path) +} + +type fuzzInput struct { + // entry is the value to test initially. The worker will randomly mutate + // values from this starting point. + entry CorpusEntry + + // timeout is the time to spend fuzzing variations of this input, + // not including starting or cleaning up. + timeout time.Duration + + // limit is the maximum number of calls to the fuzz function the worker may + // make. The worker may make fewer calls, for example, if it finds an + // error early. If limit is zero, there is no limit on calls to the + // fuzz function. + limit int64 + + // warmup indicates whether this is a warmup input before fuzzing begins. If + // true, the input should not be fuzzed. + warmup bool + + // coverageData reflects the coordinator's current coverageMask. + coverageData []byte +} + +type fuzzResult struct { + // entry is an interesting value or a crasher. + entry CorpusEntry + + // crasherMsg is an error message from a crash. It's "" if no crash was found. + crasherMsg string + + // canMinimize is true if the worker should attempt to minimize this result. + // It may be false because an attempt has already been made. + canMinimize bool + + // coverageData is set if the worker found new coverage. + coverageData []byte + + // limit is the number of values the coordinator asked the worker + // to test. 0 if there was no limit. + limit int64 + + // count is the number of values the worker actually tested. + count int64 + + // totalDuration is the time the worker spent testing inputs. + totalDuration time.Duration + + // entryDuration is the time the worker spent execution an interesting result + entryDuration time.Duration +} + +type fuzzMinimizeInput struct { + // entry is an interesting value or crasher to minimize. + entry CorpusEntry + + // crasherMsg is an error message from a crash. It's "" if no crash was found. + // If set, the worker will attempt to find a smaller input that also produces + // an error, though not necessarily the same error. + crasherMsg string + + // limit is the maximum number of calls to the fuzz function the worker may + // make. The worker may make fewer calls, for example, if it can't reproduce + // an error. If limit is zero, there is no limit on calls to the fuzz function. + limit int64 + + // timeout is the time to spend minimizing this input. + // A zero timeout means no limit. + timeout time.Duration + + // keepCoverage is a set of coverage bits that entry found that were not in + // the coordinator's combined set. When minimizing, the worker should find an + // input that preserves at least one of these bits. keepCoverage is nil for + // crashing inputs. + keepCoverage []byte +} + +// coordinator holds channels that workers can use to communicate with +// the coordinator. +type coordinator struct { + opts CoordinateFuzzingOpts + + // startTime is the time we started the workers after loading the corpus. + // Used for logging. + startTime time.Time + + // inputC is sent values to fuzz by the coordinator. Any worker may receive + // values from this channel. Workers send results to resultC. + inputC chan fuzzInput + + // minimizeC is sent values to minimize by the coordinator. Any worker may + // receive values from this channel. Workers send results to resultC. + minimizeC chan fuzzMinimizeInput + + // resultC is sent results of fuzzing by workers. The coordinator + // receives these. Multiple types of messages are allowed. + resultC chan fuzzResult + + // count is the number of values fuzzed so far. + count int64 + + // countLastLog is the number of values fuzzed when the output was last + // logged. + countLastLog int64 + + // timeLastLog is the time at which the output was last logged. + timeLastLog time.Time + + // interestingCount is the number of unique interesting values which have + // been found this execution. + interestingCount int + + // warmupInputCount is the count of all entries in the corpus which will + // need to be received from workers to run once during warmup, but not fuzz. + // This could be for coverage data, or only for the purposes of verifying + // that the seed corpus doesn't have any crashers. See warmupRun. + warmupInputCount int + + // warmupInputLeft is the number of entries in the corpus which still need + // to be received from workers to run once during warmup, but not fuzz. + // See warmupInputLeft. + warmupInputLeft int + + // duration is the time spent fuzzing inside workers, not counting time + // starting up or tearing down. + duration time.Duration + + // countWaiting is the number of fuzzing executions the coordinator is + // waiting on workers to complete. + countWaiting int64 + + // corpus is a set of interesting values, including the seed corpus and + // generated values that workers reported as interesting. + corpus corpus + + // minimizationAllowed is true if one or more of the types of fuzz + // function's parameters can be minimized. + minimizationAllowed bool + + // inputQueue is a queue of inputs that workers should try fuzzing. This is + // initially populated from the seed corpus and cached inputs. More inputs + // may be added as new coverage is discovered. + inputQueue queue + + // minimizeQueue is a queue of inputs that caused errors or exposed new + // coverage. Workers should attempt to find smaller inputs that do the + // same thing. + minimizeQueue queue + + // crashMinimizing is the crash that is currently being minimized. + crashMinimizing *fuzzResult + + // coverageMask aggregates coverage that was found for all inputs in the + // corpus. Each byte represents a single basic execution block. Each set bit + // within the byte indicates that an input has triggered that block at least + // 1 << n times, where n is the position of the bit in the byte. For example, a + // value of 12 indicates that separate inputs have triggered this block + // between 4-7 times and 8-15 times. + coverageMask []byte +} + +func newCoordinator(opts CoordinateFuzzingOpts) (*coordinator, error) { + // Make sure all the seed corpus has marshaled data. + for i := range opts.Seed { + if opts.Seed[i].Data == nil && opts.Seed[i].Values != nil { + opts.Seed[i].Data = marshalCorpusFile(opts.Seed[i].Values...) + } + } + c := &coordinator{ + opts: opts, + startTime: time.Now(), + inputC: make(chan fuzzInput), + minimizeC: make(chan fuzzMinimizeInput), + resultC: make(chan fuzzResult), + timeLastLog: time.Now(), + corpus: corpus{hashes: make(map[[sha256.Size]byte]bool)}, + } + if err := c.readCache(); err != nil { + return nil, err + } + if opts.MinimizeLimit > 0 || opts.MinimizeTimeout > 0 { + for _, t := range opts.Types { + if isMinimizable(t) { + c.minimizationAllowed = true + break + } + } + } + + covSize := len(coverage()) + if covSize == 0 { + fmt.Fprintf(c.opts.Log, "warning: the test binary was not built with coverage instrumentation, so fuzzing will run without coverage guidance and may be inefficient\n") + // Even though a coverage-only run won't occur, we should still run all + // of the seed corpus to make sure there are no existing failures before + // we start fuzzing. + c.warmupInputCount = len(c.opts.Seed) + for _, e := range c.opts.Seed { + c.inputQueue.enqueue(e) + } + } else { + c.warmupInputCount = len(c.corpus.entries) + for _, e := range c.corpus.entries { + c.inputQueue.enqueue(e) + } + // Set c.coverageMask to a clean []byte full of zeros. + c.coverageMask = make([]byte, covSize) + } + c.warmupInputLeft = c.warmupInputCount + + if len(c.corpus.entries) == 0 { + fmt.Fprintf(c.opts.Log, "warning: starting with empty corpus\n") + var vals []any + for _, t := range opts.Types { + vals = append(vals, zeroValue(t)) + } + data := marshalCorpusFile(vals...) + h := sha256.Sum256(data) + name := fmt.Sprintf("%x", h[:4]) + c.addCorpusEntries(false, CorpusEntry{Path: name, Data: data}) + } + + return c, nil +} + +func (c *coordinator) updateStats(result fuzzResult) { + c.count += result.count + c.countWaiting -= result.limit + c.duration += result.totalDuration +} + +func (c *coordinator) logStats() { + now := time.Now() + if c.warmupRun() { + runSoFar := c.warmupInputCount - c.warmupInputLeft + if coverageEnabled { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, gathering baseline coverage: %d/%d completed\n", c.elapsed(), runSoFar, c.warmupInputCount) + } else { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, testing seed corpus: %d/%d completed\n", c.elapsed(), runSoFar, c.warmupInputCount) + } + } else if c.crashMinimizing != nil { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, minimizing\n", c.elapsed()) + } else { + rate := float64(c.count-c.countLastLog) / now.Sub(c.timeLastLog).Seconds() + if coverageEnabled { + total := c.warmupInputCount + c.interestingCount + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, execs: %d (%.0f/sec), new interesting: %d (total: %d)\n", c.elapsed(), c.count, rate, c.interestingCount, total) + } else { + fmt.Fprintf(c.opts.Log, "fuzz: elapsed: %s, execs: %d (%.0f/sec)\n", c.elapsed(), c.count, rate) + } + } + c.countLastLog = c.count + c.timeLastLog = now +} + +// peekInput returns the next value that should be sent to workers. +// If the number of executions is limited, the returned value includes +// a limit for one worker. If there are no executions left, peekInput returns +// a zero value and false. +// +// peekInput doesn't actually remove the input from the queue. The caller +// must call sentInput after sending the input. +// +// If the input queue is empty and the coverage/testing-only run has completed, +// queue refills it from the corpus. +func (c *coordinator) peekInput() (fuzzInput, bool) { + if c.opts.Limit > 0 && c.count+c.countWaiting >= c.opts.Limit { + // Already making the maximum number of calls to the fuzz function. + // Don't send more inputs right now. + return fuzzInput{}, false + } + if c.inputQueue.len == 0 { + if c.warmupRun() { + // Wait for coverage/testing-only run to finish before sending more + // inputs. + return fuzzInput{}, false + } + c.refillInputQueue() + } + + entry, ok := c.inputQueue.peek() + if !ok { + panic("input queue empty after refill") + } + input := fuzzInput{ + entry: entry.(CorpusEntry), + timeout: workerFuzzDuration, + warmup: c.warmupRun(), + } + if c.coverageMask != nil { + input.coverageData = bytes.Clone(c.coverageMask) + } + if input.warmup { + // No fuzzing will occur, but it should count toward the limit set by + // -fuzztime. + input.limit = 1 + return input, true + } + + if c.opts.Limit > 0 { + input.limit = c.opts.Limit / int64(c.opts.Parallel) + if c.opts.Limit%int64(c.opts.Parallel) > 0 { + input.limit++ + } + remaining := c.opts.Limit - c.count - c.countWaiting + if input.limit > remaining { + input.limit = remaining + } + } + return input, true +} + +// sentInput updates internal counters after an input is sent to c.inputC. +func (c *coordinator) sentInput(input fuzzInput) { + c.inputQueue.dequeue() + c.countWaiting += input.limit +} + +// refillInputQueue refills the input queue from the corpus after it becomes +// empty. +func (c *coordinator) refillInputQueue() { + for _, e := range c.corpus.entries { + c.inputQueue.enqueue(e) + } +} + +// queueForMinimization creates a fuzzMinimizeInput from result and adds it +// to the minimization queue to be sent to workers. +func (c *coordinator) queueForMinimization(result fuzzResult, keepCoverage []byte) { + if shouldPrintDebugInfo() { + c.debugLogf( + "queueing input for minimization, id: %s, parent: %s, keepCoverage: %t, crasher: %t", + result.entry.Path, + result.entry.Parent, + keepCoverage != nil, + result.crasherMsg != "", + ) + } + if result.crasherMsg != "" { + c.minimizeQueue.clear() + } + + input := fuzzMinimizeInput{ + entry: result.entry, + crasherMsg: result.crasherMsg, + keepCoverage: keepCoverage, + } + c.minimizeQueue.enqueue(input) +} + +// peekMinimizeInput returns the next input that should be sent to workers for +// minimization. +func (c *coordinator) peekMinimizeInput() (fuzzMinimizeInput, bool) { + if !c.canMinimize() { + // Already making the maximum number of calls to the fuzz function. + // Don't send more inputs right now. + return fuzzMinimizeInput{}, false + } + v, ok := c.minimizeQueue.peek() + if !ok { + return fuzzMinimizeInput{}, false + } + input := v.(fuzzMinimizeInput) + + if c.opts.MinimizeTimeout > 0 { + input.timeout = c.opts.MinimizeTimeout + } + if c.opts.MinimizeLimit > 0 { + input.limit = c.opts.MinimizeLimit + } else if c.opts.Limit > 0 { + if input.crasherMsg != "" { + input.limit = c.opts.Limit + } else { + input.limit = c.opts.Limit / int64(c.opts.Parallel) + if c.opts.Limit%int64(c.opts.Parallel) > 0 { + input.limit++ + } + } + } + if c.opts.Limit > 0 { + remaining := c.opts.Limit - c.count - c.countWaiting + if input.limit > remaining { + input.limit = remaining + } + } + return input, true +} + +// sentMinimizeInput removes an input from the minimization queue after it's +// sent to minimizeC. +func (c *coordinator) sentMinimizeInput(input fuzzMinimizeInput) { + c.minimizeQueue.dequeue() + c.countWaiting += input.limit +} + +// warmupRun returns true while the coordinator is running inputs without +// mutating them as a warmup before fuzzing. This could be to gather baseline +// coverage data for entries in the corpus, or to test all of the seed corpus +// for errors before fuzzing begins. +// +// The coordinator doesn't store coverage data in the cache with each input +// because that data would be invalid when counter offsets in the test binary +// change. +// +// When gathering coverage, the coordinator sends each entry to a worker to +// gather coverage for that entry only, without fuzzing or minimizing. This +// phase ends when all workers have finished, and the coordinator has a combined +// coverage map. +func (c *coordinator) warmupRun() bool { + return c.warmupInputLeft > 0 +} + +// updateCoverage sets bits in c.coverageMask that are set in newCoverage. +// updateCoverage returns the number of newly set bits. See the comment on +// coverageMask for the format. +func (c *coordinator) updateCoverage(newCoverage []byte) int { + if len(newCoverage) != len(c.coverageMask) { + panic(fmt.Sprintf("number of coverage counters changed at runtime: %d, expected %d", len(newCoverage), len(c.coverageMask))) + } + newBitCount := 0 + for i := range newCoverage { + diff := newCoverage[i] &^ c.coverageMask[i] + newBitCount += bits.OnesCount8(diff) + c.coverageMask[i] |= newCoverage[i] + } + return newBitCount +} + +// canMinimize returns whether the coordinator should attempt to find smaller +// inputs that reproduce a crash or new coverage. +func (c *coordinator) canMinimize() bool { + return c.minimizationAllowed && + (c.opts.Limit == 0 || c.count+c.countWaiting < c.opts.Limit) +} + +func (c *coordinator) elapsed() time.Duration { + return time.Since(c.startTime).Round(1 * time.Second) +} + +// readCache creates a combined corpus from seed values and values in the cache +// (in GOCACHE/fuzz). +// +// TODO(fuzzing): need a mechanism that can remove values that +// aren't useful anymore, for example, because they have the wrong type. +func (c *coordinator) readCache() error { + if _, err := c.addCorpusEntries(false, c.opts.Seed...); err != nil { + return err + } + entries, err := ReadCorpus(c.opts.CacheDir, c.opts.Types) + if err != nil { + if _, ok := err.(*MalformedCorpusError); !ok { + // It's okay if some files in the cache directory are malformed and + // are not included in the corpus, but fail if it's an I/O error. + return err + } + // TODO(jayconrod,katiehockman): consider printing some kind of warning + // indicating the number of files which were skipped because they are + // malformed. + } + if _, err := c.addCorpusEntries(false, entries...); err != nil { + return err + } + return nil +} + +// MalformedCorpusError is an error found while reading the corpus from the +// filesystem. All of the errors are stored in the errs list. The testing +// framework uses this to report malformed files in testdata. +type MalformedCorpusError struct { + errs []error +} + +func (e *MalformedCorpusError) Error() string { + var msgs []string + for _, s := range e.errs { + msgs = append(msgs, s.Error()) + } + return strings.Join(msgs, "\n") +} + +// ReadCorpus reads the corpus from the provided dir. The returned corpus +// entries are guaranteed to match the given types. Any malformed files will +// be saved in a MalformedCorpusError and returned, along with the most recent +// error. +func ReadCorpus(dir string, types []reflect.Type) ([]CorpusEntry, error) { + files, err := os.ReadDir(dir) + if os.IsNotExist(err) { + return nil, nil // No corpus to read + } else if err != nil { + return nil, fmt.Errorf("reading seed corpus from testdata: %v", err) + } + var corpus []CorpusEntry + var errs []error + for _, file := range files { + // TODO(jayconrod,katiehockman): determine when a file is a fuzzing input + // based on its name. We should only read files created by writeToCorpus. + // If we read ALL files, we won't be able to change the file format by + // changing the extension. We also won't be able to add files like + // README.txt explaining why the directory exists. + if file.IsDir() { + continue + } + filename := filepath.Join(dir, file.Name()) + data, err := os.ReadFile(filename) + if err != nil { + return nil, fmt.Errorf("failed to read corpus file: %v", err) + } + var vals []any + vals, err = readCorpusData(data, types) + if err != nil { + errs = append(errs, fmt.Errorf("%q: %v", filename, err)) + continue + } + corpus = append(corpus, CorpusEntry{Path: filename, Values: vals}) + } + if len(errs) > 0 { + return corpus, &MalformedCorpusError{errs: errs} + } + return corpus, nil +} + +func readCorpusData(data []byte, types []reflect.Type) ([]any, error) { + vals, err := unmarshalCorpusFile(data) + if err != nil { + return nil, fmt.Errorf("unmarshal: %v", err) + } + if err = CheckCorpus(vals, types); err != nil { + return nil, err + } + return vals, nil +} + +// CheckCorpus verifies that the types in vals match the expected types +// provided. +func CheckCorpus(vals []any, types []reflect.Type) error { + if len(vals) != len(types) { + return fmt.Errorf("wrong number of values in corpus entry: %d, want %d", len(vals), len(types)) + } + valsT := make([]reflect.Type, len(vals)) + for valsI, v := range vals { + valsT[valsI] = reflect.TypeOf(v) + } + for i := range types { + if valsT[i] != types[i] { + return fmt.Errorf("mismatched types in corpus entry: %v, want %v", valsT, types) + } + } + return nil +} + +// writeToCorpus atomically writes the given bytes to a new file in testdata. If +// the directory does not exist, it will create one. If the file already exists, +// writeToCorpus will not rewrite it. writeToCorpus sets entry.Path to the new +// file that was just written or an error if it failed. +func writeToCorpus(entry *CorpusEntry, dir string) (err error) { + sum := fmt.Sprintf("%x", sha256.Sum256(entry.Data))[:16] + entry.Path = filepath.Join(dir, sum) + if err := os.MkdirAll(dir, 0777); err != nil { + return err + } + if err := os.WriteFile(entry.Path, entry.Data, 0666); err != nil { + os.Remove(entry.Path) // remove partially written file + return err + } + return nil +} + +func testName(path string) string { + return filepath.Base(path) +} + +func zeroValue(t reflect.Type) any { + for _, v := range zeroVals { + if reflect.TypeOf(v) == t { + return v + } + } + panic(fmt.Sprintf("unsupported type: %v", t)) +} + +var zeroVals []any = []any{ + []byte(""), + string(""), + false, + byte(0), + rune(0), + float32(0), + float64(0), + int(0), + int8(0), + int16(0), + int32(0), + int64(0), + uint(0), + uint8(0), + uint16(0), + uint32(0), + uint64(0), +} + +var debugInfo = godebug.New("#fuzzdebug").Value() == "1" + +func shouldPrintDebugInfo() bool { + return debugInfo +} + +func (c *coordinator) debugLogf(format string, args ...any) { + t := time.Now().Format("2006-01-02 15:04:05.999999999") + fmt.Fprintf(c.opts.Log, t+" DEBUG "+format+"\n", args...) +} diff --git a/go/src/internal/fuzz/mem.go b/go/src/internal/fuzz/mem.go new file mode 100644 index 0000000000000000000000000000000000000000..4155e4e83e253d210b85a4e3d74a820f660f9725 --- /dev/null +++ b/go/src/internal/fuzz/mem.go @@ -0,0 +1,138 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "bytes" + "fmt" + "os" + "unsafe" +) + +// sharedMem manages access to a region of virtual memory mapped from a file, +// shared between multiple processes. The region includes space for a header and +// a value of variable length. +// +// When fuzzing, the coordinator creates a sharedMem from a temporary file for +// each worker. This buffer is used to pass values to fuzz between processes. +// Care must be taken to manage access to shared memory across processes; +// sharedMem provides no synchronization on its own. See workerComm for an +// explanation. +type sharedMem struct { + // f is the file mapped into memory. + f *os.File + + // region is the mapped region of virtual memory for f. The content of f may + // be read or written through this slice. + region []byte + + // removeOnClose is true if the file should be deleted by Close. + removeOnClose bool + + // sys contains OS-specific information. + sys sharedMemSys +} + +// sharedMemHeader stores metadata in shared memory. +type sharedMemHeader struct { + // count is the number of times the worker has called the fuzz function. + // May be reset by coordinator. + count int64 + + // valueLen is the number of bytes in region which should be read. + valueLen int + + // randState and randInc hold the state of a pseudo-random number generator. + randState, randInc uint64 + + // rawInMem is true if the region holds raw bytes, which occurs during + // minimization. If true after the worker fails during minimization, this + // indicates that an unrecoverable error occurred, and the region can be + // used to retrieve the raw bytes that caused the error. + rawInMem bool +} + +// sharedMemSize returns the size needed for a shared memory buffer that can +// contain values of the given size. +func sharedMemSize(valueSize int) int { + // TODO(jayconrod): set a reasonable maximum size per platform. + return int(unsafe.Sizeof(sharedMemHeader{})) + valueSize +} + +// sharedMemTempFile creates a new temporary file of the given size, then maps +// it into memory. The file will be removed when the Close method is called. +func sharedMemTempFile(size int) (m *sharedMem, err error) { + // Create a temporary file. + f, err := os.CreateTemp("", "fuzz-*") + if err != nil { + return nil, err + } + defer func() { + if err != nil { + f.Close() + os.Remove(f.Name()) + } + }() + + // Resize it to the correct size. + totalSize := sharedMemSize(size) + if err := f.Truncate(int64(totalSize)); err != nil { + return nil, err + } + + // Map the file into memory. + removeOnClose := true + return sharedMemMapFile(f, totalSize, removeOnClose) +} + +// header returns a pointer to metadata within the shared memory region. +func (m *sharedMem) header() *sharedMemHeader { + return (*sharedMemHeader)(unsafe.Pointer(&m.region[0])) +} + +// valueRef returns the value currently stored in shared memory. The returned +// slice points to shared memory; it is not a copy. +func (m *sharedMem) valueRef() []byte { + length := m.header().valueLen + valueOffset := int(unsafe.Sizeof(sharedMemHeader{})) + return m.region[valueOffset : valueOffset+length] +} + +// valueCopy returns a copy of the value stored in shared memory. +func (m *sharedMem) valueCopy() []byte { + ref := m.valueRef() + return bytes.Clone(ref) +} + +// setValue copies the data in b into the shared memory buffer and sets +// the length. len(b) must be less than or equal to the capacity of the buffer +// (as returned by cap(m.value())). +func (m *sharedMem) setValue(b []byte) { + v := m.valueRef() + if len(b) > cap(v) { + panic(fmt.Sprintf("value length %d larger than shared memory capacity %d", len(b), cap(v))) + } + m.header().valueLen = len(b) + copy(v[:cap(v)], b) +} + +// setValueLen sets the length of the shared memory buffer returned by valueRef +// to n, which may be at most the cap of that slice. +// +// Note that we can only store the length in the shared memory header. The full +// slice header contains a pointer, which is likely only valid for one process, +// since each process can map shared memory at a different virtual address. +func (m *sharedMem) setValueLen(n int) { + v := m.valueRef() + if n > cap(v) { + panic(fmt.Sprintf("length %d larger than shared memory capacity %d", n, cap(v))) + } + m.header().valueLen = n +} + +// TODO(jayconrod): add method to resize the buffer. We'll need that when the +// mutator can increase input length. Only the coordinator will be able to +// do it, since we'll need to send a message to the worker telling it to +// remap the file. diff --git a/go/src/internal/fuzz/minimize.go b/go/src/internal/fuzz/minimize.go new file mode 100644 index 0000000000000000000000000000000000000000..0e410fb86a3ff83c50c0bf1bf1c93a1cc2d72514 --- /dev/null +++ b/go/src/internal/fuzz/minimize.go @@ -0,0 +1,95 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "reflect" +) + +func isMinimizable(t reflect.Type) bool { + return t == reflect.TypeOf("") || t == reflect.TypeOf([]byte(nil)) +} + +func minimizeBytes(v []byte, try func([]byte) bool, shouldStop func() bool) { + tmp := make([]byte, len(v)) + // If minimization was successful at any point during minimizeBytes, + // then the vals slice in (*workerServer).minimizeInput will point to + // tmp. Since tmp is altered while making new candidates, we need to + // make sure that it is equal to the correct value, v, before exiting + // this function. + defer copy(tmp, v) + + // First, try to cut the tail. + for n := 1024; n != 0; n /= 2 { + for len(v) > n { + if shouldStop() { + return + } + candidate := v[:len(v)-n] + if !try(candidate) { + break + } + // Set v to the new value to continue iterating. + v = candidate + } + } + + // Then, try to remove each individual byte. + for i := 0; i < len(v)-1; i++ { + if shouldStop() { + return + } + candidate := tmp[:len(v)-1] + copy(candidate[:i], v[:i]) + copy(candidate[i:], v[i+1:]) + if !try(candidate) { + continue + } + // Update v to delete the value at index i. + copy(v[i:], v[i+1:]) + v = v[:len(candidate)] + // v[i] is now different, so decrement i to redo this iteration + // of the loop with the new value. + i-- + } + + // Then, try to remove each possible subset of bytes. + for i := 0; i < len(v)-1; i++ { + copy(tmp, v[:i]) + for j := len(v); j > i+1; j-- { + if shouldStop() { + return + } + candidate := tmp[:len(v)-j+i] + copy(candidate[i:], v[j:]) + if !try(candidate) { + continue + } + // Update v and reset the loop with the new length. + copy(v[i:], v[j:]) + v = v[:len(candidate)] + j = len(v) + } + } + + // Then, try to make it more simplified and human-readable by trying to replace each + // byte with a printable character. + printableChars := []byte("012789ABCXYZabcxyz !\"#$%&'()*+,.") + for i, b := range v { + if shouldStop() { + return + } + + for _, pc := range printableChars { + v[i] = pc + if try(v) { + // Successful. Move on to the next byte in v. + break + } + // Unsuccessful. Revert v[i] back to original value. + v[i] = b + } + } +} diff --git a/go/src/internal/fuzz/minimize_test.go b/go/src/internal/fuzz/minimize_test.go new file mode 100644 index 0000000000000000000000000000000000000000..79d986374f08a142794367673022b414af954738 --- /dev/null +++ b/go/src/internal/fuzz/minimize_test.go @@ -0,0 +1,181 @@ +// 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 darwin || freebsd || linux || openbsd || windows + +package fuzz + +import ( + "bytes" + "context" + "errors" + "fmt" + "reflect" + "testing" + "time" + "unicode" + "unicode/utf8" +) + +func TestMinimizeInput(t *testing.T) { + type testcase struct { + name string + fn func(CorpusEntry) error + input []any + expected []any + } + cases := []testcase{ + { + name: "ones_byte", + fn: func(e CorpusEntry) error { + b := e.Values[0].([]byte) + ones := 0 + for _, v := range b { + if v == 1 { + ones++ + } + } + if ones == 3 { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{[]byte{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + expected: []any{[]byte{1, 1, 1}}, + }, + { + name: "single_bytes", + fn: func(e CorpusEntry) error { + b := e.Values[0].([]byte) + if len(b) < 2 { + return nil + } + if len(b) == 2 && b[0] == 1 && b[1] == 2 { + return nil + } + return fmt.Errorf("bad %v", e.Values[0]) + }, + input: []any{[]byte{1, 2, 3, 4, 5}}, + expected: []any{[]byte("00")}, + }, + { + name: "set_of_bytes", + fn: func(e CorpusEntry) error { + b := e.Values[0].([]byte) + if len(b) < 3 { + return nil + } + if bytes.Equal(b, []byte{0, 1, 2, 3, 4, 5}) || bytes.Equal(b, []byte{0, 4, 5}) { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{[]byte{0, 1, 2, 3, 4, 5}}, + expected: []any{[]byte{0, 4, 5}}, + }, + { + name: "non_ascii_bytes", + fn: func(e CorpusEntry) error { + b := e.Values[0].([]byte) + if len(b) == 3 { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{[]byte("ท")}, // ท is 3 bytes + expected: []any{[]byte("000")}, + }, + { + name: "ones_string", + fn: func(e CorpusEntry) error { + b := e.Values[0].(string) + ones := 0 + for _, v := range b { + if v == '1' { + ones++ + } + } + if ones == 3 { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{"001010001000000000000000000"}, + expected: []any{"111"}, + }, + { + name: "string_length", + fn: func(e CorpusEntry) error { + b := e.Values[0].(string) + if len(b) == 5 { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{"zzzzz"}, + expected: []any{"00000"}, + }, + { + name: "string_with_letter", + fn: func(e CorpusEntry) error { + b := e.Values[0].(string) + r, _ := utf8.DecodeRune([]byte(b)) + if unicode.IsLetter(r) { + return fmt.Errorf("bad %v", e.Values[0]) + } + return nil + }, + input: []any{"ZZZZZ"}, + expected: []any{"A"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ws := &workerServer{ + fuzzFn: func(e CorpusEntry) (time.Duration, error) { + return time.Second, tc.fn(e) + }, + } + mem := &sharedMem{region: make([]byte, 100)} // big enough to hold value and header + vals := tc.input + success, err := ws.minimizeInput(context.Background(), vals, mem, minimizeArgs{}) + if !success { + t.Errorf("minimizeInput did not succeed") + } + if err == nil { + t.Fatal("minimizeInput didn't provide an error") + } + if expected := fmt.Sprintf("bad %v", tc.expected[0]); err.Error() != expected { + t.Errorf("unexpected error: got %q, want %q", err, expected) + } + if !reflect.DeepEqual(vals, tc.expected) { + t.Errorf("unexpected results: got %v, want %v", vals, tc.expected) + } + }) + } +} + +// TestMinimizeFlaky checks that if we're minimizing an interesting +// input and a flaky failure occurs, that minimization was not indicated +// to be successful, and the error isn't returned (since it's flaky). +func TestMinimizeFlaky(t *testing.T) { + ws := &workerServer{fuzzFn: func(e CorpusEntry) (time.Duration, error) { + return time.Second, errors.New("ohno") + }} + mem := &sharedMem{region: make([]byte, 100)} // big enough to hold value and header + vals := []any{[]byte(nil)} + args := minimizeArgs{KeepCoverage: make([]byte, len(coverageSnapshot))} + success, err := ws.minimizeInput(context.Background(), vals, mem, args) + if success { + t.Error("unexpected success") + } + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if count := mem.header().count; count != 1 { + t.Errorf("count: got %d, want 1", count) + } +} diff --git a/go/src/internal/fuzz/mutator.go b/go/src/internal/fuzz/mutator.go new file mode 100644 index 0000000000000000000000000000000000000000..9bba0d627b44bd8f2794060b04ade4130056b8df --- /dev/null +++ b/go/src/internal/fuzz/mutator.go @@ -0,0 +1,293 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "encoding/binary" + "fmt" + "math" + "unsafe" +) + +type mutator struct { + r mutatorRand + scratch []byte // scratch slice to avoid additional allocations +} + +func newMutator() *mutator { + return &mutator{r: newPcgRand()} +} + +func (m *mutator) rand(n int) int { + return m.r.intn(n) +} + +func (m *mutator) randByteOrder() binary.ByteOrder { + if m.r.bool() { + return binary.LittleEndian + } + return binary.BigEndian +} + +// chooseLen chooses length of range mutation in range [1,n]. It gives +// preference to shorter ranges. +func (m *mutator) chooseLen(n int) int { + switch x := m.rand(100); { + case x < 90: + return m.rand(min(8, n)) + 1 + case x < 99: + return m.rand(min(32, n)) + 1 + default: + return m.rand(n) + 1 + } +} + +// mutate performs several mutations on the provided values. +func (m *mutator) mutate(vals []any, maxBytes int) { + // TODO(katiehockman): pull some of these functions into helper methods and + // test that each case is working as expected. + // TODO(katiehockman): perform more types of mutations for []byte. + + // maxPerVal will represent the maximum number of bytes that each value be + // allowed after mutating, giving an equal amount of capacity to each line. + // Allow a little wiggle room for the encoding. + maxPerVal := maxBytes/len(vals) - 100 + + // Pick a random value to mutate. + // TODO: consider mutating more than one value at a time. + i := m.rand(len(vals)) + switch v := vals[i].(type) { + case int: + vals[i] = int(m.mutateInt(int64(v), maxInt)) + case int8: + vals[i] = int8(m.mutateInt(int64(v), math.MaxInt8)) + case int16: + vals[i] = int16(m.mutateInt(int64(v), math.MaxInt16)) + case int64: + vals[i] = m.mutateInt(v, maxInt) + case uint: + vals[i] = uint(m.mutateUInt(uint64(v), maxUint)) + case uint16: + vals[i] = uint16(m.mutateUInt(uint64(v), math.MaxUint16)) + case uint32: + vals[i] = uint32(m.mutateUInt(uint64(v), math.MaxUint32)) + case uint64: + vals[i] = m.mutateUInt(v, maxUint) + case float32: + vals[i] = float32(m.mutateFloat(float64(v), math.MaxFloat32)) + case float64: + vals[i] = m.mutateFloat(v, math.MaxFloat64) + case bool: + if m.rand(2) == 1 { + vals[i] = !v // 50% chance of flipping the bool + } + case rune: // int32 + vals[i] = rune(m.mutateInt(int64(v), math.MaxInt32)) + case byte: // uint8 + vals[i] = byte(m.mutateUInt(uint64(v), math.MaxUint8)) + case string: + if len(v) > maxPerVal { + panic(fmt.Sprintf("cannot mutate bytes of length %d", len(v))) + } + if cap(m.scratch) < maxPerVal { + m.scratch = append(make([]byte, 0, maxPerVal), v...) + } else { + m.scratch = m.scratch[:len(v)] + copy(m.scratch, v) + } + m.mutateBytes(&m.scratch) + vals[i] = string(m.scratch) + case []byte: + if len(v) > maxPerVal { + panic(fmt.Sprintf("cannot mutate bytes of length %d", len(v))) + } + if cap(m.scratch) < maxPerVal { + m.scratch = append(make([]byte, 0, maxPerVal), v...) + } else { + m.scratch = m.scratch[:len(v)] + copy(m.scratch, v) + } + m.mutateBytes(&m.scratch) + vals[i] = m.scratch + default: + panic(fmt.Sprintf("type not supported for mutating: %T", vals[i])) + } +} + +func (m *mutator) mutateInt(v, maxValue int64) int64 { + var max int64 + for { + max = 100 + switch m.rand(2) { + case 0: + // Add a random number + if v >= maxValue { + continue + } + if v > 0 && maxValue-v < max { + // Don't let v exceed maxValue + max = maxValue - v + } + v += int64(1 + m.rand(int(max))) + return v + case 1: + // Subtract a random number + if v <= -maxValue { + continue + } + if v < 0 && maxValue+v < max { + // Don't let v drop below -maxValue + max = maxValue + v + } + v -= int64(1 + m.rand(int(max))) + return v + } + } +} + +func (m *mutator) mutateUInt(v, maxValue uint64) uint64 { + var max uint64 + for { + max = 100 + switch m.rand(2) { + case 0: + // Add a random number + if v >= maxValue { + continue + } + if v > 0 && maxValue-v < max { + // Don't let v exceed maxValue + max = maxValue - v + } + + v += uint64(1 + m.rand(int(max))) + return v + case 1: + // Subtract a random number + if v <= 0 { + continue + } + if v < max { + // Don't let v drop below 0 + max = v + } + v -= uint64(1 + m.rand(int(max))) + return v + } + } +} + +func (m *mutator) mutateFloat(v, maxValue float64) float64 { + var max float64 + for { + switch m.rand(4) { + case 0: + // Add a random number + if v >= maxValue { + continue + } + max = 100 + if v > 0 && maxValue-v < max { + // Don't let v exceed maxValue + max = maxValue - v + } + v += float64(1 + m.rand(int(max))) + return v + case 1: + // Subtract a random number + if v <= -maxValue { + continue + } + max = 100 + if v < 0 && maxValue+v < max { + // Don't let v drop below -maxValue + max = maxValue + v + } + v -= float64(1 + m.rand(int(max))) + return v + case 2: + // Multiply by a random number + absV := math.Abs(v) + if v == 0 || absV >= maxValue { + continue + } + max = 10 + if maxValue/absV < max { + // Don't let v go beyond the minimum or maximum value + max = maxValue / absV + } + v *= float64(1 + m.rand(int(max))) + return v + case 3: + // Divide by a random number + if v == 0 { + continue + } + v /= float64(1 + m.rand(10)) + return v + } + } +} + +type byteSliceMutator func(*mutator, []byte) []byte + +var byteSliceMutators = []byteSliceMutator{ + byteSliceRemoveBytes, + byteSliceInsertRandomBytes, + byteSliceDuplicateBytes, + byteSliceOverwriteBytes, + byteSliceBitFlip, + byteSliceXORByte, + byteSliceSwapByte, + byteSliceArithmeticUint8, + byteSliceArithmeticUint16, + byteSliceArithmeticUint32, + byteSliceArithmeticUint64, + byteSliceOverwriteInterestingUint8, + byteSliceOverwriteInterestingUint16, + byteSliceOverwriteInterestingUint32, + byteSliceInsertConstantBytes, + byteSliceOverwriteConstantBytes, + byteSliceShuffleBytes, + byteSliceSwapBytes, +} + +func (m *mutator) mutateBytes(ptrB *[]byte) { + b := *ptrB + defer func() { + if unsafe.SliceData(*ptrB) != unsafe.SliceData(b) { + panic("data moved to new address") + } + *ptrB = b + }() + + for { + mut := byteSliceMutators[m.rand(len(byteSliceMutators))] + if mutated := mut(m, b); mutated != nil { + b = mutated + return + } + } +} + +var ( + interesting8 = []int8{-128, -1, 0, 1, 16, 32, 64, 100, 127} + interesting16 = []int16{-32768, -129, 128, 255, 256, 512, 1000, 1024, 4096, 32767} + interesting32 = []int32{-2147483648, -100663046, -32769, 32768, 65535, 65536, 100663045, 2147483647} +) + +const ( + maxUint = uint64(^uint(0)) + maxInt = int64(maxUint >> 1) +) + +func init() { + for _, v := range interesting8 { + interesting16 = append(interesting16, int16(v)) + } + for _, v := range interesting16 { + interesting32 = append(interesting32, int32(v)) + } +} diff --git a/go/src/internal/fuzz/mutator_test.go b/go/src/internal/fuzz/mutator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..cea7e2e3be8c33fb52661a3d21dda15653d53cd9 --- /dev/null +++ b/go/src/internal/fuzz/mutator_test.go @@ -0,0 +1,117 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "bytes" + "fmt" + "os" + "strconv" + "testing" +) + +func BenchmarkMutatorBytes(b *testing.B) { + origEnv := os.Getenv("GODEBUG") + defer func() { os.Setenv("GODEBUG", origEnv) }() + os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv)) + m := newMutator() + + for _, size := range []int{ + 1, + 10, + 100, + 1000, + 10000, + 100000, + } { + b.Run(strconv.Itoa(size), func(b *testing.B) { + buf := make([]byte, size) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + // resize buffer to the correct shape and reset the PCG + buf = buf[0:size] + m.r = newPcgRand() + m.mutate([]any{buf}, workerSharedMemSize) + } + }) + } +} + +func BenchmarkMutatorString(b *testing.B) { + origEnv := os.Getenv("GODEBUG") + defer func() { os.Setenv("GODEBUG", origEnv) }() + os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv)) + m := newMutator() + + for _, size := range []int{ + 1, + 10, + 100, + 1000, + 10000, + 100000, + } { + b.Run(strconv.Itoa(size), func(b *testing.B) { + buf := make([]byte, size) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + // resize buffer to the correct shape and reset the PCG + buf = buf[0:size] + m.r = newPcgRand() + m.mutate([]any{string(buf)}, workerSharedMemSize) + } + }) + } +} + +func BenchmarkMutatorAllBasicTypes(b *testing.B) { + origEnv := os.Getenv("GODEBUG") + defer func() { os.Setenv("GODEBUG", origEnv) }() + os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv)) + m := newMutator() + + types := []any{ + []byte(""), + string(""), + false, + float32(0), + float64(0), + int(0), + int8(0), + int16(0), + int32(0), + int64(0), + uint8(0), + uint16(0), + uint32(0), + uint64(0), + } + + for _, t := range types { + b.Run(fmt.Sprintf("%T", t), func(b *testing.B) { + for i := 0; i < b.N; i++ { + m.r = newPcgRand() + m.mutate([]any{t}, workerSharedMemSize) + } + }) + } +} + +func TestStringImmutability(t *testing.T) { + v := []any{"hello"} + m := newMutator() + m.mutate(v, 1024) + original := v[0].(string) + originalCopy := make([]byte, len(original)) + copy(originalCopy, []byte(original)) + for i := 0; i < 25; i++ { + m.mutate(v, 1024) + } + if !bytes.Equal([]byte(original), originalCopy) { + t.Fatalf("string was mutated: got %x, want %x", []byte(original), originalCopy) + } +} diff --git a/go/src/internal/fuzz/mutators_byteslice.go b/go/src/internal/fuzz/mutators_byteslice.go new file mode 100644 index 0000000000000000000000000000000000000000..d9dab1df9f4e859c114d28a3ae1867c035dfb392 --- /dev/null +++ b/go/src/internal/fuzz/mutators_byteslice.go @@ -0,0 +1,313 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +// byteSliceRemoveBytes removes a random chunk of bytes from b. +func byteSliceRemoveBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + pos0 := m.rand(len(b)) + pos1 := pos0 + m.chooseLen(len(b)-pos0) + copy(b[pos0:], b[pos1:]) + b = b[:len(b)-(pos1-pos0)] + return b +} + +// byteSliceInsertRandomBytes inserts a chunk of random bytes into b at a random +// position. +func byteSliceInsertRandomBytes(m *mutator, b []byte) []byte { + pos := m.rand(len(b) + 1) + n := m.chooseLen(1024) + if len(b)+n >= cap(b) { + return nil + } + b = b[:len(b)+n] + copy(b[pos+n:], b[pos:]) + for i := 0; i < n; i++ { + b[pos+i] = byte(m.rand(256)) + } + return b +} + +// byteSliceDuplicateBytes duplicates a chunk of bytes in b and inserts it into +// a random position. +func byteSliceDuplicateBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + src := m.rand(len(b)) + dst := m.rand(len(b)) + for dst == src { + dst = m.rand(len(b)) + } + n := m.chooseLen(len(b) - src) + // Use the end of the slice as scratch space to avoid doing an + // allocation. If the slice is too small abort and try something + // else. + if len(b)+(n*2) >= cap(b) { + return nil + } + end := len(b) + // Increase the size of b to fit the duplicated block as well as + // some extra working space + b = b[:end+(n*2)] + // Copy the block of bytes we want to duplicate to the end of the + // slice + copy(b[end+n:], b[src:src+n]) + // Shift the bytes after the splice point n positions to the right + // to make room for the new block + copy(b[dst+n:end+n], b[dst:end]) + // Insert the duplicate block into the splice point + copy(b[dst:], b[end+n:]) + b = b[:end+n] + return b +} + +// byteSliceOverwriteBytes overwrites a chunk of b with another chunk of b. +func byteSliceOverwriteBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + src := m.rand(len(b)) + dst := m.rand(len(b)) + for dst == src { + dst = m.rand(len(b)) + } + n := m.chooseLen(len(b) - src - 1) + copy(b[dst:], b[src:src+n]) + return b +} + +// byteSliceBitFlip flips a random bit in a random byte in b. +func byteSliceBitFlip(m *mutator, b []byte) []byte { + if len(b) == 0 { + return nil + } + pos := m.rand(len(b)) + b[pos] ^= 1 << uint(m.rand(8)) + return b +} + +// byteSliceXORByte XORs a random byte in b with a random value. +func byteSliceXORByte(m *mutator, b []byte) []byte { + if len(b) == 0 { + return nil + } + pos := m.rand(len(b)) + // In order to avoid a no-op (where the random value matches + // the existing value), use XOR instead of just setting to + // the random value. + b[pos] ^= byte(1 + m.rand(255)) + return b +} + +// byteSliceSwapByte swaps two random bytes in b. +func byteSliceSwapByte(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + src := m.rand(len(b)) + dst := m.rand(len(b)) + for dst == src { + dst = m.rand(len(b)) + } + b[src], b[dst] = b[dst], b[src] + return b +} + +// byteSliceArithmeticUint8 adds/subtracts from a random byte in b. +func byteSliceArithmeticUint8(m *mutator, b []byte) []byte { + if len(b) == 0 { + return nil + } + pos := m.rand(len(b)) + v := byte(m.rand(35) + 1) + if m.r.bool() { + b[pos] += v + } else { + b[pos] -= v + } + return b +} + +// byteSliceArithmeticUint16 adds/subtracts from a random uint16 in b. +func byteSliceArithmeticUint16(m *mutator, b []byte) []byte { + if len(b) < 2 { + return nil + } + v := uint16(m.rand(35) + 1) + if m.r.bool() { + v = 0 - v + } + pos := m.rand(len(b) - 1) + enc := m.randByteOrder() + enc.PutUint16(b[pos:], enc.Uint16(b[pos:])+v) + return b +} + +// byteSliceArithmeticUint32 adds/subtracts from a random uint32 in b. +func byteSliceArithmeticUint32(m *mutator, b []byte) []byte { + if len(b) < 4 { + return nil + } + v := uint32(m.rand(35) + 1) + if m.r.bool() { + v = 0 - v + } + pos := m.rand(len(b) - 3) + enc := m.randByteOrder() + enc.PutUint32(b[pos:], enc.Uint32(b[pos:])+v) + return b +} + +// byteSliceArithmeticUint64 adds/subtracts from a random uint64 in b. +func byteSliceArithmeticUint64(m *mutator, b []byte) []byte { + if len(b) < 8 { + return nil + } + v := uint64(m.rand(35) + 1) + if m.r.bool() { + v = 0 - v + } + pos := m.rand(len(b) - 7) + enc := m.randByteOrder() + enc.PutUint64(b[pos:], enc.Uint64(b[pos:])+v) + return b +} + +// byteSliceOverwriteInterestingUint8 overwrites a random byte in b with an interesting +// value. +func byteSliceOverwriteInterestingUint8(m *mutator, b []byte) []byte { + if len(b) == 0 { + return nil + } + pos := m.rand(len(b)) + b[pos] = byte(interesting8[m.rand(len(interesting8))]) + return b +} + +// byteSliceOverwriteInterestingUint16 overwrites a random uint16 in b with an interesting +// value. +func byteSliceOverwriteInterestingUint16(m *mutator, b []byte) []byte { + if len(b) < 2 { + return nil + } + pos := m.rand(len(b) - 1) + v := uint16(interesting16[m.rand(len(interesting16))]) + m.randByteOrder().PutUint16(b[pos:], v) + return b +} + +// byteSliceOverwriteInterestingUint32 overwrites a random uint16 in b with an interesting +// value. +func byteSliceOverwriteInterestingUint32(m *mutator, b []byte) []byte { + if len(b) < 4 { + return nil + } + pos := m.rand(len(b) - 3) + v := uint32(interesting32[m.rand(len(interesting32))]) + m.randByteOrder().PutUint32(b[pos:], v) + return b +} + +// byteSliceInsertConstantBytes inserts a chunk of constant bytes into a random position in b. +func byteSliceInsertConstantBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + dst := m.rand(len(b)) + // TODO(rolandshoemaker,katiehockman): 4096 was mainly picked + // randomly. We may want to either pick a much larger value + // (AFL uses 32768, paired with a similar impl to chooseLen + // which biases towards smaller lengths that grow over time), + // or set the max based on characteristics of the corpus + // (libFuzzer sets a min/max based on the min/max size of + // entries in the corpus and then picks uniformly from + // that range). + n := m.chooseLen(4096) + if len(b)+n >= cap(b) { + return nil + } + b = b[:len(b)+n] + copy(b[dst+n:], b[dst:]) + rb := byte(m.rand(256)) + for i := dst; i < dst+n; i++ { + b[i] = rb + } + return b +} + +// byteSliceOverwriteConstantBytes overwrites a chunk of b with constant bytes. +func byteSliceOverwriteConstantBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + dst := m.rand(len(b)) + n := m.chooseLen(len(b) - dst) + rb := byte(m.rand(256)) + for i := dst; i < dst+n; i++ { + b[i] = rb + } + return b +} + +// byteSliceShuffleBytes shuffles a chunk of bytes in b. +func byteSliceShuffleBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + dst := m.rand(len(b)) + n := m.chooseLen(len(b) - dst) + if n <= 2 { + return nil + } + // Start at the end of the range, and iterate backwards + // to dst, swapping each element with another element in + // dst:dst+n (Fisher-Yates shuffle). + for i := n - 1; i > 0; i-- { + j := m.rand(i + 1) + b[dst+i], b[dst+j] = b[dst+j], b[dst+i] + } + return b +} + +// byteSliceSwapBytes swaps two chunks of bytes in b. +func byteSliceSwapBytes(m *mutator, b []byte) []byte { + if len(b) <= 1 { + return nil + } + src := m.rand(len(b)) + dst := m.rand(len(b)) + for dst == src { + dst = m.rand(len(b)) + } + // Choose the random length as len(b) - max(src, dst) + // so that we don't attempt to swap a chunk that extends + // beyond the end of the slice + max := dst + if src > max { + max = src + } + n := m.chooseLen(len(b) - max - 1) + // Check that neither chunk intersect, so that we don't end up + // duplicating parts of the input, rather than swapping them + if src > dst && dst+n >= src || dst > src && src+n >= dst { + return nil + } + // Use the end of the slice as scratch space to avoid doing an + // allocation. If the slice is too small abort and try something + // else. + if len(b)+n >= cap(b) { + return nil + } + end := len(b) + b = b[:end+n] + copy(b[end:], b[dst:dst+n]) + copy(b[dst:], b[src:src+n]) + copy(b[src:], b[end:]) + b = b[:end] + return b +} diff --git a/go/src/internal/fuzz/mutators_byteslice_test.go b/go/src/internal/fuzz/mutators_byteslice_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b12ef6cbcdd0bdf250236ecba001c8d9fe1725da --- /dev/null +++ b/go/src/internal/fuzz/mutators_byteslice_test.go @@ -0,0 +1,221 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "bytes" + "fmt" + "testing" +) + +type mockRand struct { + values []int + counter int + b bool +} + +func (mr *mockRand) uint32() uint32 { + c := mr.values[mr.counter] + mr.counter++ + return uint32(c) +} + +func (mr *mockRand) intn(n int) int { + c := mr.values[mr.counter] + mr.counter++ + return c % n +} + +func (mr *mockRand) uint32n(n uint32) uint32 { + c := mr.values[mr.counter] + mr.counter++ + return uint32(c) % n +} + +func (mr *mockRand) bool() bool { + b := mr.b + mr.b = !mr.b + return b +} + +func (mr *mockRand) save(*uint64, *uint64) { + panic("unimplemented") +} + +func (mr *mockRand) restore(uint64, uint64) { + panic("unimplemented") +} + +func TestByteSliceMutators(t *testing.T) { + for _, tc := range []struct { + name string + mutator func(*mutator, []byte) []byte + randVals []int + input []byte + expected []byte + }{ + { + name: "byteSliceRemoveBytes", + mutator: byteSliceRemoveBytes, + input: []byte{1, 2, 3, 4}, + expected: []byte{4}, + }, + { + name: "byteSliceInsertRandomBytes", + mutator: byteSliceInsertRandomBytes, + input: make([]byte, 4, 8), + expected: []byte{3, 4, 5, 0, 0, 0, 0}, + }, + { + name: "byteSliceDuplicateBytes", + mutator: byteSliceDuplicateBytes, + input: append(make([]byte, 0, 13), []byte{1, 2, 3, 4}...), + expected: []byte{1, 1, 2, 3, 4, 2, 3, 4}, + }, + { + name: "byteSliceOverwriteBytes", + mutator: byteSliceOverwriteBytes, + input: []byte{1, 2, 3, 4}, + expected: []byte{1, 1, 3, 4}, + }, + { + name: "byteSliceBitFlip", + mutator: byteSliceBitFlip, + input: []byte{1, 2, 3, 4}, + expected: []byte{3, 2, 3, 4}, + }, + { + name: "byteSliceXORByte", + mutator: byteSliceXORByte, + input: []byte{1, 2, 3, 4}, + expected: []byte{3, 2, 3, 4}, + }, + { + name: "byteSliceSwapByte", + mutator: byteSliceSwapByte, + input: []byte{1, 2, 3, 4}, + expected: []byte{2, 1, 3, 4}, + }, + { + name: "byteSliceArithmeticUint8", + mutator: byteSliceArithmeticUint8, + input: []byte{1, 2, 3, 4}, + expected: []byte{255, 2, 3, 4}, + }, + { + name: "byteSliceArithmeticUint16", + mutator: byteSliceArithmeticUint16, + input: []byte{1, 2, 3, 4}, + expected: []byte{1, 3, 3, 4}, + }, + { + name: "byteSliceArithmeticUint32", + mutator: byteSliceArithmeticUint32, + input: []byte{1, 2, 3, 4}, + expected: []byte{2, 2, 3, 4}, + }, + { + name: "byteSliceArithmeticUint64", + mutator: byteSliceArithmeticUint64, + input: []byte{1, 2, 3, 4, 5, 6, 7, 8}, + expected: []byte{2, 2, 3, 4, 5, 6, 7, 8}, + }, + { + name: "byteSliceOverwriteInterestingUint8", + mutator: byteSliceOverwriteInterestingUint8, + input: []byte{1, 2, 3, 4}, + expected: []byte{255, 2, 3, 4}, + }, + { + name: "byteSliceOverwriteInterestingUint16", + mutator: byteSliceOverwriteInterestingUint16, + input: []byte{1, 2, 3, 4}, + expected: []byte{255, 127, 3, 4}, + }, + { + name: "byteSliceOverwriteInterestingUint32", + mutator: byteSliceOverwriteInterestingUint32, + input: []byte{1, 2, 3, 4}, + expected: []byte{250, 0, 0, 250}, + }, + { + name: "byteSliceInsertConstantBytes", + mutator: byteSliceInsertConstantBytes, + input: append(make([]byte, 0, 8), []byte{1, 2, 3, 4}...), + expected: []byte{3, 3, 3, 1, 2, 3, 4}, + }, + { + name: "byteSliceOverwriteConstantBytes", + mutator: byteSliceOverwriteConstantBytes, + input: []byte{1, 2, 3, 4}, + expected: []byte{3, 3, 3, 4}, + }, + { + name: "byteSliceShuffleBytes", + mutator: byteSliceShuffleBytes, + input: []byte{1, 2, 3, 4}, + expected: []byte{2, 3, 1, 4}, + }, + { + name: "byteSliceSwapBytes", + mutator: byteSliceSwapBytes, + randVals: []int{0, 2, 0, 2}, + input: append(make([]byte, 0, 9), []byte{1, 2, 3, 4}...), + expected: []byte{3, 2, 1, 4}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + r := &mockRand{values: []int{0, 1, 2, 3, 4, 5}} + if tc.randVals != nil { + r.values = tc.randVals + } + m := &mutator{r: r} + b := tc.mutator(m, tc.input) + if !bytes.Equal(b, tc.expected) { + t.Errorf("got %x, want %x", b, tc.expected) + } + }) + } +} + +func BenchmarkByteSliceMutators(b *testing.B) { + tests := [...]struct { + name string + mutator func(*mutator, []byte) []byte + }{ + {"RemoveBytes", byteSliceRemoveBytes}, + {"InsertRandomBytes", byteSliceInsertRandomBytes}, + {"DuplicateBytes", byteSliceDuplicateBytes}, + {"OverwriteBytes", byteSliceOverwriteBytes}, + {"BitFlip", byteSliceBitFlip}, + {"XORByte", byteSliceXORByte}, + {"SwapByte", byteSliceSwapByte}, + {"ArithmeticUint8", byteSliceArithmeticUint8}, + {"ArithmeticUint16", byteSliceArithmeticUint16}, + {"ArithmeticUint32", byteSliceArithmeticUint32}, + {"ArithmeticUint64", byteSliceArithmeticUint64}, + {"OverwriteInterestingUint8", byteSliceOverwriteInterestingUint8}, + {"OverwriteInterestingUint16", byteSliceOverwriteInterestingUint16}, + {"OverwriteInterestingUint32", byteSliceOverwriteInterestingUint32}, + {"InsertConstantBytes", byteSliceInsertConstantBytes}, + {"OverwriteConstantBytes", byteSliceOverwriteConstantBytes}, + {"ShuffleBytes", byteSliceShuffleBytes}, + {"SwapBytes", byteSliceSwapBytes}, + } + + for _, tc := range tests { + b.Run(tc.name, func(b *testing.B) { + for size := 64; size <= 1024; size *= 2 { + b.Run(fmt.Sprintf("%d", size), func(b *testing.B) { + m := &mutator{r: newPcgRand()} + input := make([]byte, size) + for i := 0; i < b.N; i++ { + tc.mutator(m, input) + } + }) + } + }) + } +} diff --git a/go/src/internal/fuzz/pcg.go b/go/src/internal/fuzz/pcg.go new file mode 100644 index 0000000000000000000000000000000000000000..b8251043f1c129207703da27acd8342142f46e6a --- /dev/null +++ b/go/src/internal/fuzz/pcg.go @@ -0,0 +1,139 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "math/bits" + "os" + "strconv" + "strings" + "sync/atomic" + "time" +) + +type mutatorRand interface { + uint32() uint32 + intn(int) int + uint32n(uint32) uint32 + bool() bool + + save(randState, randInc *uint64) + restore(randState, randInc uint64) +} + +// The functions in pcg implement a 32 bit PRNG with a 64 bit period: pcg xsh rr +// 64 32. See https://www.pcg-random.org/ for more information. This +// implementation is geared specifically towards the needs of fuzzing: Simple +// creation and use, no reproducibility, no concurrency safety, just the +// necessary methods, optimized for speed. + +var globalInc atomic.Uint64 // PCG stream + +const multiplier uint64 = 6364136223846793005 + +// pcgRand is a PRNG. It should not be copied or shared. No Rand methods are +// concurrency safe. +type pcgRand struct { + noCopy noCopy // help avoid mistakes: ask vet to ensure that we don't make a copy + state uint64 + inc uint64 +} + +func godebugSeed() *int { + debug := strings.Split(os.Getenv("GODEBUG"), ",") + for _, f := range debug { + if strings.HasPrefix(f, "fuzzseed=") { + seed, err := strconv.Atoi(strings.TrimPrefix(f, "fuzzseed=")) + if err != nil { + panic("malformed fuzzseed") + } + return &seed + } + } + return nil +} + +// newPcgRand generates a new, seeded Rand, ready for use. +func newPcgRand() *pcgRand { + r := new(pcgRand) + now := uint64(time.Now().UnixNano()) + if seed := godebugSeed(); seed != nil { + now = uint64(*seed) + } + inc := globalInc.Add(1) + r.state = now + r.inc = (inc << 1) | 1 + r.step() + r.state += now + r.step() + return r +} + +func (r *pcgRand) step() { + r.state *= multiplier + r.state += r.inc +} + +func (r *pcgRand) save(randState, randInc *uint64) { + *randState = r.state + *randInc = r.inc +} + +func (r *pcgRand) restore(randState, randInc uint64) { + r.state = randState + r.inc = randInc +} + +// uint32 returns a pseudo-random uint32. +func (r *pcgRand) uint32() uint32 { + x := r.state + r.step() + return bits.RotateLeft32(uint32(((x>>18)^x)>>27), -int(x>>59)) +} + +// intn returns a pseudo-random number in [0, n). +// n must fit in a uint32. +func (r *pcgRand) intn(n int) int { + if int(uint32(n)) != n { + panic("large Intn") + } + return int(r.uint32n(uint32(n))) +} + +// uint32n returns a pseudo-random number in [0, n). +// +// For implementation details, see: +// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction +// https://lemire.me/blog/2016/06/30/fast-random-shuffling +func (r *pcgRand) uint32n(n uint32) uint32 { + v := r.uint32() + prod := uint64(v) * uint64(n) + low := uint32(prod) + if low < n { + thresh := uint32(-int32(n)) % n + for low < thresh { + v = r.uint32() + prod = uint64(v) * uint64(n) + low = uint32(prod) + } + } + return uint32(prod >> 32) +} + +// bool generates a random bool. +func (r *pcgRand) bool() bool { + return r.uint32()&1 == 0 +} + +// noCopy may be embedded into structs which must not be copied +// after the first use. +// +// See https://golang.org/issues/8005#issuecomment-190753527 +// for details. +type noCopy struct{} + +// Lock is a no-op used by -copylocks checker from `go vet`. +func (*noCopy) Lock() {} +func (*noCopy) Unlock() {} diff --git a/go/src/internal/fuzz/queue.go b/go/src/internal/fuzz/queue.go new file mode 100644 index 0000000000000000000000000000000000000000..195d6eb7b60e34428d8e8dc37522d1cf6f4a4bc3 --- /dev/null +++ b/go/src/internal/fuzz/queue.go @@ -0,0 +1,71 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +// queue holds a growable sequence of inputs for fuzzing and minimization. +// +// For now, this is a simple ring buffer +// (https://en.wikipedia.org/wiki/Circular_buffer). +// +// TODO(golang.org/issue/46224): use a prioritization algorithm based on input +// size, previous duration, coverage, and any other metrics that seem useful. +type queue struct { + // elems holds a ring buffer. + // The queue is empty when begin = end. + // The queue is full (until grow is called) when end = begin + N - 1 (mod N) + // where N = cap(elems). + elems []any + head, len int +} + +func (q *queue) cap() int { + return len(q.elems) +} + +func (q *queue) grow() { + oldCap := q.cap() + newCap := oldCap * 2 + if newCap == 0 { + newCap = 8 + } + newElems := make([]any, newCap) + oldLen := q.len + for i := 0; i < oldLen; i++ { + newElems[i] = q.elems[(q.head+i)%oldCap] + } + q.elems = newElems + q.head = 0 +} + +func (q *queue) enqueue(e any) { + if q.len+1 > q.cap() { + q.grow() + } + i := (q.head + q.len) % q.cap() + q.elems[i] = e + q.len++ +} + +func (q *queue) dequeue() (any, bool) { + if q.len == 0 { + return nil, false + } + e := q.elems[q.head] + q.elems[q.head] = nil + q.head = (q.head + 1) % q.cap() + q.len-- + return e, true +} + +func (q *queue) peek() (any, bool) { + if q.len == 0 { + return nil, false + } + return q.elems[q.head], true +} + +func (q *queue) clear() { + *q = queue{} +} diff --git a/go/src/internal/fuzz/queue_test.go b/go/src/internal/fuzz/queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3b179afb573ce7bd8a06ea88a4c55032ac0a226a --- /dev/null +++ b/go/src/internal/fuzz/queue_test.go @@ -0,0 +1,58 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import "testing" + +func TestQueue(t *testing.T) { + // Zero valued queue should have 0 length and capacity. + var q queue + if n := q.len; n != 0 { + t.Fatalf("empty queue has len %d; want 0", n) + } + if n := q.cap(); n != 0 { + t.Fatalf("empty queue has cap %d; want 0", n) + } + + // As we add elements, len should grow. + N := 32 + for i := 0; i < N; i++ { + q.enqueue(i) + if n := q.len; n != i+1 { + t.Fatalf("after adding %d elements, queue has len %d", i, n) + } + if v, ok := q.peek(); !ok { + t.Fatalf("couldn't peek after adding %d elements", i) + } else if v.(int) != 0 { + t.Fatalf("after adding %d elements, peek is %d; want 0", i, v) + } + } + + // As we remove and add elements, len should shrink and grow. + // We should also remove elements in the same order they were added. + want := 0 + for _, r := range []int{1, 2, 3, 5, 8, 13, 21} { + s := make([]int, 0, r) + for i := 0; i < r; i++ { + if got, ok := q.dequeue(); !ok { + t.Fatalf("after removing %d of %d elements, could not dequeue", i+1, r) + } else if got != want { + t.Fatalf("after removing %d of %d elements, got %d; want %d", i+1, r, got, want) + } else { + s = append(s, got.(int)) + } + want = (want + 1) % N + if n := q.len; n != N-i-1 { + t.Fatalf("after removing %d of %d elements, len is %d; want %d", i+1, r, n, N-i-1) + } + } + for i, v := range s { + q.enqueue(v) + if n := q.len; n != N-r+i+1 { + t.Fatalf("after adding back %d of %d elements, len is %d; want %d", i+1, r, n, n-r+i+1) + } + } + } +} diff --git a/go/src/internal/fuzz/sys_posix.go b/go/src/internal/fuzz/sys_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..40d3771c2ac0e6dd955ce537ee049d44441d1c63 --- /dev/null +++ b/go/src/internal/fuzz/sys_posix.go @@ -0,0 +1,130 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || freebsd || linux || openbsd + +package fuzz + +import ( + "fmt" + "os" + "os/exec" + "syscall" +) + +type sharedMemSys struct{} + +func sharedMemMapFile(f *os.File, size int, removeOnClose bool) (*sharedMem, error) { + prot := syscall.PROT_READ | syscall.PROT_WRITE + flags := syscall.MAP_FILE | syscall.MAP_SHARED + region, err := syscall.Mmap(int(f.Fd()), 0, size, prot, flags) + if err != nil { + return nil, err + } + + return &sharedMem{f: f, region: region, removeOnClose: removeOnClose}, nil +} + +// Close unmaps the shared memory and closes the temporary file. If this +// sharedMem was created with sharedMemTempFile, Close also removes the file. +func (m *sharedMem) Close() error { + // Attempt all operations, even if we get an error for an earlier operation. + // os.File.Close may fail due to I/O errors, but we still want to delete + // the temporary file. + var errs []error + errs = append(errs, + syscall.Munmap(m.region), + m.f.Close()) + if m.removeOnClose { + errs = append(errs, os.Remove(m.f.Name())) + } + for _, err := range errs { + if err != nil { + return err + } + } + return nil +} + +// setWorkerComm configures communication channels on the cmd that will +// run a worker process. +func setWorkerComm(cmd *exec.Cmd, comm workerComm) { + mem := <-comm.memMu + memFile := mem.f + comm.memMu <- mem + cmd.ExtraFiles = []*os.File{comm.fuzzIn, comm.fuzzOut, memFile} +} + +// getWorkerComm returns communication channels in the worker process. +func getWorkerComm() (comm workerComm, err error) { + fuzzIn := os.NewFile(3, "fuzz_in") + fuzzOut := os.NewFile(4, "fuzz_out") + memFile := os.NewFile(5, "fuzz_mem") + fi, err := memFile.Stat() + if err != nil { + return workerComm{}, err + } + size := int(fi.Size()) + if int64(size) != fi.Size() { + return workerComm{}, fmt.Errorf("fuzz temp file exceeds maximum size") + } + removeOnClose := false + mem, err := sharedMemMapFile(memFile, size, removeOnClose) + if err != nil { + return workerComm{}, err + } + memMu := make(chan *sharedMem, 1) + memMu <- mem + return workerComm{fuzzIn: fuzzIn, fuzzOut: fuzzOut, memMu: memMu}, nil +} + +// isInterruptError returns whether an error was returned by a process that +// was terminated by an interrupt signal (SIGINT). +func isInterruptError(err error) bool { + exitErr, ok := err.(*exec.ExitError) + if !ok || exitErr.ExitCode() >= 0 { + return false + } + status := exitErr.Sys().(syscall.WaitStatus) + return status.Signal() == syscall.SIGINT +} + +// terminationSignal checks if err is an exec.ExitError with a signal status. +// If it is, terminationSignal returns the signal and true. +// If not, -1 and false. +func terminationSignal(err error) (os.Signal, bool) { + exitErr, ok := err.(*exec.ExitError) + if !ok || exitErr.ExitCode() >= 0 { + return syscall.Signal(-1), false + } + status := exitErr.Sys().(syscall.WaitStatus) + return status.Signal(), status.Signaled() +} + +// isCrashSignal returns whether a signal was likely to have been caused by an +// error in the program that received it, triggered by a fuzz input. For +// example, SIGSEGV would be received after a nil pointer dereference. +// Other signals like SIGKILL or SIGHUP are more likely to have been sent by +// another process, and we shouldn't record a crasher if the worker process +// receives one of these. +// +// Note that Go installs its own signal handlers on startup, so some of these +// signals may only be received if signal handlers are changed. For example, +// SIGSEGV is normally transformed into a panic that causes the process to exit +// with status 2 if not recovered, which we handle as a crash. +func isCrashSignal(signal os.Signal) bool { + switch signal { + case + syscall.SIGILL, // illegal instruction + syscall.SIGTRAP, // breakpoint + syscall.SIGABRT, // abort() called + syscall.SIGBUS, // invalid memory access (e.g., misaligned address) + syscall.SIGFPE, // math error, e.g., integer divide by zero + syscall.SIGSEGV, // invalid memory access (e.g., write to read-only) + syscall.SIGPIPE: // sent data to closed pipe or socket + return true + default: + return false + } +} diff --git a/go/src/internal/fuzz/sys_unimplemented.go b/go/src/internal/fuzz/sys_unimplemented.go new file mode 100644 index 0000000000000000000000000000000000000000..30766ba525f2c8d508b2b19aeb7399e93f02c2f9 --- /dev/null +++ b/go/src/internal/fuzz/sys_unimplemented.go @@ -0,0 +1,44 @@ +// 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. + +// If you update this constraint, also update internal/platform.FuzzSupported. +// +//go:build !darwin && !freebsd && !linux && !openbsd && !windows + +package fuzz + +import ( + "os" + "os/exec" +) + +type sharedMemSys struct{} + +func sharedMemMapFile(f *os.File, size int, removeOnClose bool) (*sharedMem, error) { + panic("not implemented") +} + +func (m *sharedMem) Close() error { + panic("not implemented") +} + +func setWorkerComm(cmd *exec.Cmd, comm workerComm) { + panic("not implemented") +} + +func getWorkerComm() (comm workerComm, err error) { + panic("not implemented") +} + +func isInterruptError(err error) bool { + panic("not implemented") +} + +func terminationSignal(err error) (os.Signal, bool) { + panic("not implemented") +} + +func isCrashSignal(signal os.Signal) bool { + panic("not implemented") +} diff --git a/go/src/internal/fuzz/sys_windows.go b/go/src/internal/fuzz/sys_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..82c97034c7ee3f72a3806ee0bfc023484464e836 --- /dev/null +++ b/go/src/internal/fuzz/sys_windows.go @@ -0,0 +1,144 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "fmt" + "os" + "os/exec" + "syscall" + "unsafe" +) + +type sharedMemSys struct { + mapObj syscall.Handle +} + +func sharedMemMapFile(f *os.File, size int, removeOnClose bool) (mem *sharedMem, err error) { + defer func() { + if err != nil { + err = fmt.Errorf("mapping temporary file %s: %w", f.Name(), err) + } + }() + + // Create a file mapping object. The object itself is not shared. + mapObj, err := syscall.CreateFileMapping( + syscall.Handle(f.Fd()), // fhandle + nil, // sa + syscall.PAGE_READWRITE, // prot + 0, // maxSizeHigh + 0, // maxSizeLow + nil, // name + ) + if err != nil { + return nil, err + } + + // Create a view from the file mapping object. + access := uint32(syscall.FILE_MAP_READ | syscall.FILE_MAP_WRITE) + addr, err := syscall.MapViewOfFile( + mapObj, // handle + access, // access + 0, // offsetHigh + 0, // offsetLow + uintptr(size), // length + ) + if err != nil { + syscall.CloseHandle(mapObj) + return nil, err + } + + region := unsafe.Slice((*byte)(unsafe.Pointer(addr)), size) + return &sharedMem{ + f: f, + region: region, + removeOnClose: removeOnClose, + sys: sharedMemSys{mapObj: mapObj}, + }, nil +} + +// Close unmaps the shared memory and closes the temporary file. If this +// sharedMem was created with sharedMemTempFile, Close also removes the file. +func (m *sharedMem) Close() error { + // Attempt all operations, even if we get an error for an earlier operation. + // os.File.Close may fail due to I/O errors, but we still want to delete + // the temporary file. + var errs []error + errs = append(errs, + syscall.UnmapViewOfFile(uintptr(unsafe.Pointer(&m.region[0]))), + syscall.CloseHandle(m.sys.mapObj), + m.f.Close()) + if m.removeOnClose { + errs = append(errs, os.Remove(m.f.Name())) + } + for _, err := range errs { + if err != nil { + return err + } + } + return nil +} + +// setWorkerComm configures communication channels on the cmd that will +// run a worker process. +func setWorkerComm(cmd *exec.Cmd, comm workerComm) { + mem := <-comm.memMu + memFD := mem.f.Fd() + comm.memMu <- mem + syscall.SetHandleInformation(syscall.Handle(comm.fuzzIn.Fd()), syscall.HANDLE_FLAG_INHERIT, 1) + syscall.SetHandleInformation(syscall.Handle(comm.fuzzOut.Fd()), syscall.HANDLE_FLAG_INHERIT, 1) + syscall.SetHandleInformation(syscall.Handle(memFD), syscall.HANDLE_FLAG_INHERIT, 1) + cmd.Env = append(cmd.Env, fmt.Sprintf("GO_TEST_FUZZ_WORKER_HANDLES=%x,%x,%x", comm.fuzzIn.Fd(), comm.fuzzOut.Fd(), memFD)) + cmd.SysProcAttr = &syscall.SysProcAttr{AdditionalInheritedHandles: []syscall.Handle{syscall.Handle(comm.fuzzIn.Fd()), syscall.Handle(comm.fuzzOut.Fd()), syscall.Handle(memFD)}} +} + +// getWorkerComm returns communication channels in the worker process. +func getWorkerComm() (comm workerComm, err error) { + v := os.Getenv("GO_TEST_FUZZ_WORKER_HANDLES") + if v == "" { + return workerComm{}, fmt.Errorf("GO_TEST_FUZZ_WORKER_HANDLES not set") + } + var fuzzInFD, fuzzOutFD, memFileFD uintptr + if _, err := fmt.Sscanf(v, "%x,%x,%x", &fuzzInFD, &fuzzOutFD, &memFileFD); err != nil { + return workerComm{}, fmt.Errorf("parsing GO_TEST_FUZZ_WORKER_HANDLES=%s: %v", v, err) + } + + fuzzIn := os.NewFile(fuzzInFD, "fuzz_in") + fuzzOut := os.NewFile(fuzzOutFD, "fuzz_out") + memFile := os.NewFile(memFileFD, "fuzz_mem") + fi, err := memFile.Stat() + if err != nil { + return workerComm{}, fmt.Errorf("worker checking temp file size: %w", err) + } + size := int(fi.Size()) + if int64(size) != fi.Size() { + return workerComm{}, fmt.Errorf("fuzz temp file exceeds maximum size") + } + removeOnClose := false + mem, err := sharedMemMapFile(memFile, size, removeOnClose) + if err != nil { + return workerComm{}, err + } + memMu := make(chan *sharedMem, 1) + memMu <- mem + + return workerComm{fuzzIn: fuzzIn, fuzzOut: fuzzOut, memMu: memMu}, nil +} + +func isInterruptError(err error) bool { + // On Windows, we can't tell whether the process was interrupted by the error + // returned by Wait. It looks like an ExitError with status 1. + return false +} + +// terminationSignal returns -1 and false because Windows doesn't have signals. +func terminationSignal(err error) (os.Signal, bool) { + return syscall.Signal(-1), false +} + +// isCrashSignal is not implemented because Windows doesn't have signals. +func isCrashSignal(signal os.Signal) bool { + panic("not implemented: no signals on windows") +} diff --git a/go/src/internal/fuzz/trace.go b/go/src/internal/fuzz/trace.go new file mode 100644 index 0000000000000000000000000000000000000000..a15c37006334b9375615477517c4a44f6e48e7f5 --- /dev/null +++ b/go/src/internal/fuzz/trace.go @@ -0,0 +1,35 @@ +// 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 !libfuzzer + +package fuzz + +import _ "unsafe" // for go:linkname + +//go:linkname libfuzzerTraceCmp1 runtime.libfuzzerTraceCmp1 +//go:linkname libfuzzerTraceCmp2 runtime.libfuzzerTraceCmp2 +//go:linkname libfuzzerTraceCmp4 runtime.libfuzzerTraceCmp4 +//go:linkname libfuzzerTraceCmp8 runtime.libfuzzerTraceCmp8 + +//go:linkname libfuzzerTraceConstCmp1 runtime.libfuzzerTraceConstCmp1 +//go:linkname libfuzzerTraceConstCmp2 runtime.libfuzzerTraceConstCmp2 +//go:linkname libfuzzerTraceConstCmp4 runtime.libfuzzerTraceConstCmp4 +//go:linkname libfuzzerTraceConstCmp8 runtime.libfuzzerTraceConstCmp8 + +//go:linkname libfuzzerHookStrCmp runtime.libfuzzerHookStrCmp +//go:linkname libfuzzerHookEqualFold runtime.libfuzzerHookEqualFold + +func libfuzzerTraceCmp1(arg0, arg1 uint8, fakePC uint) {} +func libfuzzerTraceCmp2(arg0, arg1 uint16, fakePC uint) {} +func libfuzzerTraceCmp4(arg0, arg1 uint32, fakePC uint) {} +func libfuzzerTraceCmp8(arg0, arg1 uint64, fakePC uint) {} + +func libfuzzerTraceConstCmp1(arg0, arg1 uint8, fakePC uint) {} +func libfuzzerTraceConstCmp2(arg0, arg1 uint16, fakePC uint) {} +func libfuzzerTraceConstCmp4(arg0, arg1 uint32, fakePC uint) {} +func libfuzzerTraceConstCmp8(arg0, arg1 uint64, fakePC uint) {} + +func libfuzzerHookStrCmp(arg0, arg1 string, fakePC uint) {} +func libfuzzerHookEqualFold(arg0, arg1 string, fakePC uint) {} diff --git a/go/src/internal/fuzz/worker.go b/go/src/internal/fuzz/worker.go new file mode 100644 index 0000000000000000000000000000000000000000..9ee2f27296dc3aadb245168421a0e89b1f1cca87 --- /dev/null +++ b/go/src/internal/fuzz/worker.go @@ -0,0 +1,1195 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "reflect" + "runtime" + "sync" + "time" +) + +const ( + // workerFuzzDuration is the amount of time a worker can spend testing random + // variations of an input given by the coordinator. + workerFuzzDuration = 100 * time.Millisecond + + // workerTimeoutDuration is the amount of time a worker can go without + // responding to the coordinator before being stopped. + workerTimeoutDuration = 1 * time.Second + + // workerExitCode is used as an exit code by fuzz worker processes after an internal error. + // This distinguishes internal errors from uncontrolled panics and other crashes. + // Keep in sync with internal/fuzz.workerExitCode. + workerExitCode = 70 + + // workerSharedMemSize is the maximum size of the shared memory file used to + // communicate with workers. This limits the size of fuzz inputs. + workerSharedMemSize = 100 << 20 // 100 MB +) + +// worker manages a worker process running a test binary. The worker object +// exists only in the coordinator (the process started by 'go test -fuzz'). +// workerClient is used by the coordinator to send RPCs to the worker process, +// which handles them with workerServer. +type worker struct { + dir string // working directory, same as package directory + binPath string // path to test executable + args []string // arguments for test executable + env []string // environment for test executable + + coordinator *coordinator + + memMu chan *sharedMem // mutex guarding shared memory with worker; persists across processes. + + cmd *exec.Cmd // current worker process + client *workerClient // used to communicate with worker process + waitErr error // last error returned by wait, set before termC is closed. + interrupted bool // true after stop interrupts a running worker. + termC chan struct{} // closed by wait when worker process terminates +} + +func newWorker(c *coordinator, dir, binPath string, args, env []string) (*worker, error) { + mem, err := sharedMemTempFile(workerSharedMemSize) + if err != nil { + return nil, err + } + memMu := make(chan *sharedMem, 1) + memMu <- mem + return &worker{ + dir: dir, + binPath: binPath, + args: args, + env: env[:len(env):len(env)], // copy on append to ensure workers don't overwrite each other. + coordinator: c, + memMu: memMu, + }, nil +} + +// cleanup releases persistent resources associated with the worker. +func (w *worker) cleanup() error { + mem := <-w.memMu + if mem == nil { + return nil + } + close(w.memMu) + return mem.Close() +} + +// coordinate runs the test binary to perform fuzzing. +// +// coordinate loops until ctx is canceled or a fatal error is encountered. +// If a test process terminates unexpectedly while fuzzing, coordinate will +// attempt to restart and continue unless the termination can be attributed +// to an interruption (from a timer or the user). +// +// While looping, coordinate receives inputs from the coordinator, passes +// those inputs to the worker process, then passes the results back to +// the coordinator. +func (w *worker) coordinate(ctx context.Context) error { + // Main event loop. + for { + // Start or restart the worker if it's not running. + if !w.isRunning() { + if err := w.startAndPing(ctx); err != nil { + return err + } + } + + select { + case <-ctx.Done(): + // Worker was told to stop. + err := w.stop() + if err != nil && !w.interrupted && !isInterruptError(err) { + return err + } + return ctx.Err() + + case <-w.termC: + // Worker process terminated unexpectedly while waiting for input. + err := w.stop() + if w.interrupted { + panic("worker interrupted after unexpected termination") + } + if err == nil || isInterruptError(err) { + // Worker stopped, either by exiting with status 0 or after being + // interrupted with a signal that was not sent by the coordinator. + // + // When the user presses ^C, on POSIX platforms, SIGINT is delivered to + // all processes in the group concurrently, and the worker may see it + // before the coordinator. The worker should exit 0 gracefully (in + // theory). + // + // This condition is probably intended by the user, so suppress + // the error. + return nil + } + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == workerExitCode { + // Worker exited with a code indicating F.Fuzz was not called correctly, + // for example, F.Fail was called first. + return fmt.Errorf("fuzzing process exited unexpectedly due to an internal failure: %w", err) + } + // Worker exited non-zero or was terminated by a non-interrupt + // signal (for example, SIGSEGV) while fuzzing. + return fmt.Errorf("fuzzing process hung or terminated unexpectedly: %w", err) + // TODO(jayconrod,katiehockman): if -keepfuzzing, restart worker. + + case input := <-w.coordinator.inputC: + // Received input from coordinator. + args := fuzzArgs{ + Limit: input.limit, + Timeout: input.timeout, + Warmup: input.warmup, + CoverageData: input.coverageData, + } + entry, resp, isInternalError, err := w.client.fuzz(ctx, input.entry, args) + canMinimize := true + if err != nil { + // Error communicating with worker. + w.stop() + if ctx.Err() != nil { + // Timeout or interruption. + return ctx.Err() + } + if w.interrupted { + // Communication error before we stopped the worker. + // Report an error, but don't record a crasher. + return fmt.Errorf("communicating with fuzzing process: %v", err) + } + if sig, ok := terminationSignal(w.waitErr); ok && !isCrashSignal(sig) { + // Worker terminated by a signal that probably wasn't caused by a + // specific input to the fuzz function. For example, on Linux, + // the kernel (OOM killer) may send SIGKILL to a process using a lot + // of memory. Or the shell might send SIGHUP when the terminal + // is closed. Don't record a crasher. + return fmt.Errorf("fuzzing process terminated by unexpected signal; no crash will be recorded: %v", w.waitErr) + } + if isInternalError { + // An internal error occurred which shouldn't be considered + // a crash. + return err + } + // Unexpected termination. Set error message and fall through. + // We'll restart the worker on the next iteration. + // Don't attempt to minimize this since it crashed the worker. + resp.Err = fmt.Sprintf("fuzzing process hung or terminated unexpectedly: %v", w.waitErr) + canMinimize = false + } + result := fuzzResult{ + limit: input.limit, + count: resp.Count, + totalDuration: resp.TotalDuration, + entryDuration: resp.InterestingDuration, + entry: entry, + crasherMsg: resp.Err, + coverageData: resp.CoverageData, + canMinimize: canMinimize, + } + w.coordinator.resultC <- result + + case input := <-w.coordinator.minimizeC: + // Received input to minimize from coordinator. + result, err := w.minimize(ctx, input) + if err != nil { + // Error minimizing. Send back the original input. If it didn't cause + // an error before, report it as causing an error now. + // TODO: double-check this is handled correctly when + // implementing -keepfuzzing. + result = fuzzResult{ + entry: input.entry, + crasherMsg: input.crasherMsg, + canMinimize: false, + limit: input.limit, + } + if result.crasherMsg == "" { + result.crasherMsg = err.Error() + } + } + if shouldPrintDebugInfo() { + w.coordinator.debugLogf( + "input minimized, id: %s, original id: %s, crasher: %t, originally crasher: %t, minimizing took: %s", + result.entry.Path, + input.entry.Path, + result.crasherMsg != "", + input.crasherMsg != "", + result.totalDuration, + ) + } + w.coordinator.resultC <- result + } + } +} + +// minimize tells a worker process to attempt to find a smaller value that +// either causes an error (if we started minimizing because we found an input +// that causes an error) or preserves new coverage (if we started minimizing +// because we found an input that expands coverage). +func (w *worker) minimize(ctx context.Context, input fuzzMinimizeInput) (min fuzzResult, err error) { + if w.coordinator.opts.MinimizeTimeout != 0 { + var cancel func() + ctx, cancel = context.WithTimeout(ctx, w.coordinator.opts.MinimizeTimeout) + defer cancel() + } + + args := minimizeArgs{ + Limit: input.limit, + Timeout: input.timeout, + KeepCoverage: input.keepCoverage, + } + entry, resp, err := w.client.minimize(ctx, input.entry, args) + if err != nil { + // Error communicating with worker. + w.stop() + if ctx.Err() != nil || w.interrupted || isInterruptError(w.waitErr) { + // Worker was interrupted, possibly by the user pressing ^C. + // Normally, workers can handle interrupts and timeouts gracefully and + // will return without error. An error here indicates the worker + // may not have been in a good state, but the error won't be meaningful + // to the user. Just return the original crasher without logging anything. + return fuzzResult{ + entry: input.entry, + crasherMsg: input.crasherMsg, + coverageData: input.keepCoverage, + canMinimize: false, + limit: input.limit, + }, nil + } + return fuzzResult{ + entry: entry, + crasherMsg: fmt.Sprintf("fuzzing process hung or terminated unexpectedly while minimizing: %v", err), + canMinimize: false, + limit: input.limit, + count: resp.Count, + totalDuration: resp.Duration, + }, nil + } + + if input.crasherMsg != "" && resp.Err == "" { + return fuzzResult{}, fmt.Errorf("attempted to minimize a crash but could not reproduce") + } + + return fuzzResult{ + entry: entry, + crasherMsg: resp.Err, + coverageData: resp.CoverageData, + canMinimize: false, + limit: input.limit, + count: resp.Count, + totalDuration: resp.Duration, + }, nil +} + +func (w *worker) isRunning() bool { + return w.cmd != nil +} + +// startAndPing starts the worker process and sends it a message to make sure it +// can communicate. +// +// startAndPing returns an error if any part of this didn't work, including if +// the context is expired or the worker process was interrupted before it +// responded. Errors that happen after start but before the ping response +// likely indicate that the worker did not call F.Fuzz or called F.Fail first. +// We don't record crashers for these errors. +func (w *worker) startAndPing(ctx context.Context) error { + if ctx.Err() != nil { + return ctx.Err() + } + if err := w.start(); err != nil { + return err + } + if err := w.client.ping(ctx); err != nil { + w.stop() + if ctx.Err() != nil { + return ctx.Err() + } + if isInterruptError(err) { + // User may have pressed ^C before worker responded. + return err + } + // TODO: record and return stderr. + return fmt.Errorf("fuzzing process terminated without fuzzing: %w", err) + } + return nil +} + +// start runs a new worker process. +// +// If the process couldn't be started, start returns an error. Start won't +// return later termination errors from the process if they occur. +// +// If the process starts successfully, start returns nil. stop must be called +// once later to clean up, even if the process terminates on its own. +// +// When the process terminates, w.waitErr is set to the error (if any), and +// w.termC is closed. +func (w *worker) start() (err error) { + if w.isRunning() { + panic("worker already started") + } + w.waitErr = nil + w.interrupted = false + w.termC = nil + + cmd := exec.Command(w.binPath, w.args...) + cmd.Dir = w.dir + cmd.Env = w.env[:len(w.env):len(w.env)] // copy on append to ensure workers don't overwrite each other. + + // Create the "fuzz_in" and "fuzz_out" pipes so we can communicate with + // the worker. We don't use stdin and stdout, since the test binary may + // do something else with those. + // + // Each pipe has a reader and a writer. The coordinator writes to fuzzInW + // and reads from fuzzOutR. The worker inherits fuzzInR and fuzzOutW. + // The coordinator closes fuzzInR and fuzzOutW after starting the worker, + // since we have no further need of them. + fuzzInR, fuzzInW, err := os.Pipe() + if err != nil { + return err + } + defer fuzzInR.Close() + fuzzOutR, fuzzOutW, err := os.Pipe() + if err != nil { + fuzzInW.Close() + return err + } + defer fuzzOutW.Close() + setWorkerComm(cmd, workerComm{fuzzIn: fuzzInR, fuzzOut: fuzzOutW, memMu: w.memMu}) + + // Start the worker process. + if err := cmd.Start(); err != nil { + fuzzInW.Close() + fuzzOutR.Close() + return err + } + + // Worker started successfully. + // After this, w.client owns fuzzInW and fuzzOutR, so w.client.Close must be + // called later by stop. + w.cmd = cmd + w.termC = make(chan struct{}) + comm := workerComm{fuzzIn: fuzzInW, fuzzOut: fuzzOutR, memMu: w.memMu} + m := newMutator() + w.client = newWorkerClient(comm, m) + + go func() { + w.waitErr = w.cmd.Wait() + close(w.termC) + }() + + return nil +} + +// stop tells the worker process to exit by closing w.client, then blocks until +// it terminates. If the worker doesn't terminate after a short time, stop +// signals it with os.Interrupt (where supported), then os.Kill. +// +// stop returns the error the process terminated with, if any (same as +// w.waitErr). +// +// stop must be called at least once after start returns successfully, even if +// the worker process terminates unexpectedly. +func (w *worker) stop() error { + if w.termC == nil { + panic("worker was not started successfully") + } + select { + case <-w.termC: + // Worker already terminated. + if w.client == nil { + // stop already called. + return w.waitErr + } + // Possible unexpected termination. + w.client.Close() + w.cmd = nil + w.client = nil + return w.waitErr + default: + // Worker still running. + } + + // Tell the worker to stop by closing fuzz_in. It won't actually stop until it + // finishes with earlier calls. + closeC := make(chan struct{}) + go func() { + w.client.Close() + close(closeC) + }() + + sig := os.Interrupt + if runtime.GOOS == "windows" { + // Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on + // Windows; using it with os.Process.Signal will return an error.” + // Fall back to Kill instead. + sig = os.Kill + } + + t := time.NewTimer(workerTimeoutDuration) + for { + select { + case <-w.termC: + // Worker terminated. + t.Stop() + <-closeC + w.cmd = nil + w.client = nil + return w.waitErr + + case <-t.C: + // Timer fired before worker terminated. + w.interrupted = true + switch sig { + case os.Interrupt: + // Try to stop the worker with SIGINT and wait a little longer. + w.cmd.Process.Signal(sig) + sig = os.Kill + t.Reset(workerTimeoutDuration) + + case os.Kill: + // Try to stop the worker with SIGKILL and keep waiting. + w.cmd.Process.Signal(sig) + sig = nil + t.Reset(workerTimeoutDuration) + + case nil: + // Still waiting. Print a message to let the user know why. + fmt.Fprintf(w.coordinator.opts.Log, "waiting for fuzzing process to terminate...\n") + } + } + } +} + +// RunFuzzWorker is called in a worker process to communicate with the +// coordinator process in order to fuzz random inputs. RunFuzzWorker loops +// until the coordinator tells it to stop. +// +// fn is a wrapper on the fuzz function. It may return an error to indicate +// a given input "crashed". The coordinator will also record a crasher if +// the function times out or terminates the process. +// +// RunFuzzWorker returns an error if it could not communicate with the +// coordinator process. +func RunFuzzWorker(ctx context.Context, fn func(CorpusEntry) error) error { + comm, err := getWorkerComm() + if err != nil { + return err + } + srv := &workerServer{ + workerComm: comm, + fuzzFn: func(e CorpusEntry) (time.Duration, error) { + timer := time.AfterFunc(10*time.Second, func() { + panic("deadlocked!") // this error message won't be printed + }) + defer timer.Stop() + start := time.Now() + err := fn(e) + return time.Since(start), err + }, + m: newMutator(), + } + return srv.serve(ctx) +} + +// call is serialized and sent from the coordinator on fuzz_in. It acts as +// a minimalist RPC mechanism. Exactly one of its fields must be set to indicate +// which method to call. +type call struct { + Ping *pingArgs + Fuzz *fuzzArgs + Minimize *minimizeArgs +} + +// minimizeArgs contains arguments to workerServer.minimize. The value to +// minimize is already in shared memory. +type minimizeArgs struct { + // Timeout is the time to spend minimizing. This may include time to start up, + // especially if the input causes the worker process to terminated, requiring + // repeated restarts. + Timeout time.Duration + + // Limit is the maximum number of values to test, without spending more time + // than Duration. 0 indicates no limit. + Limit int64 + + // KeepCoverage is a set of coverage counters the worker should attempt to + // keep in minimized values. When provided, the worker will reject inputs that + // don't cause at least one of these bits to be set. + KeepCoverage []byte + + // Index is the index of the fuzz target parameter to be minimized. + Index int +} + +// minimizeResponse contains results from workerServer.minimize. +type minimizeResponse struct { + // WroteToMem is true if the worker found a smaller input and wrote it to + // shared memory. If minimizeArgs.KeepCoverage was set, the minimized input + // preserved at least one coverage bit and did not cause an error. + // Otherwise, the minimized input caused some error, recorded in Err. + WroteToMem bool + + // Err is the error string caused by the value in shared memory, if any. + Err string + + // CoverageData is the set of coverage bits activated by the minimized value + // in shared memory. When set, it contains at least one bit from KeepCoverage. + // CoverageData will be nil if Err is set or if minimization failed. + CoverageData []byte + + // Duration is the time spent minimizing, not including starting or cleaning up. + Duration time.Duration + + // Count is the number of values tested. + Count int64 +} + +// fuzzArgs contains arguments to workerServer.fuzz. The value to fuzz is +// passed in shared memory. +type fuzzArgs struct { + // Timeout is the time to spend fuzzing, not including starting or + // cleaning up. + Timeout time.Duration + + // Limit is the maximum number of values to test, without spending more time + // than Duration. 0 indicates no limit. + Limit int64 + + // Warmup indicates whether this is part of a warmup run, meaning that + // fuzzing should not occur. If coverageEnabled is true, then coverage data + // should be reported. + Warmup bool + + // CoverageData is the coverage data. If set, the worker should update its + // local coverage data prior to fuzzing. + CoverageData []byte +} + +// fuzzResponse contains results from workerServer.fuzz. +type fuzzResponse struct { + // Duration is the time spent fuzzing, not including starting or cleaning up. + TotalDuration time.Duration + InterestingDuration time.Duration + + // Count is the number of values tested. + Count int64 + + // CoverageData is set if the value in shared memory expands coverage + // and therefore may be interesting to the coordinator. + CoverageData []byte + + // Err is the error string caused by the value in shared memory, which is + // non-empty if the value in shared memory caused a crash. + Err string + + // InternalErr is the error string caused by an internal error in the + // worker. This shouldn't be considered a crasher. + InternalErr string +} + +// pingArgs contains arguments to workerServer.ping. +type pingArgs struct{} + +// pingResponse contains results from workerServer.ping. +type pingResponse struct{} + +// workerComm holds pipes and shared memory used for communication +// between the coordinator process (client) and a worker process (server). +// These values are unique to each worker; they are shared only with the +// coordinator, not with other workers. +// +// Access to shared memory is synchronized implicitly over the RPC protocol +// implemented in workerServer and workerClient. During a call, the client +// (worker) has exclusive access to shared memory; at other times, the server +// (coordinator) has exclusive access. +type workerComm struct { + fuzzIn, fuzzOut *os.File + memMu chan *sharedMem // mutex guarding shared memory +} + +// workerServer is a minimalist RPC server, run by fuzz worker processes. +// It allows the coordinator process (using workerClient) to call methods in a +// worker process. This system allows the coordinator to run multiple worker +// processes in parallel and to collect inputs that caused crashes from shared +// memory after a worker process terminates unexpectedly. +type workerServer struct { + workerComm + m *mutator + + // coverageMask is the local coverage data for the worker. It is + // periodically updated to reflect the data in the coordinator when new + // coverage is found. + coverageMask []byte + + // fuzzFn runs the worker's fuzz target on the given input and returns an + // error if it finds a crasher (the process may also exit or crash), and the + // time it took to run the input. It sets a deadline of 10 seconds, at which + // point it will panic with the assumption that the process is hanging or + // deadlocked. + fuzzFn func(CorpusEntry) (time.Duration, error) +} + +// serve reads serialized RPC messages on fuzzIn. When serve receives a message, +// it calls the corresponding method, then sends the serialized result back +// on fuzzOut. +// +// serve handles RPC calls synchronously; it will not attempt to read a message +// until the previous call has finished. +// +// serve returns errors that occurred when communicating over pipes. serve +// does not return errors from method calls; those are passed through serialized +// responses. +func (ws *workerServer) serve(ctx context.Context) error { + enc := json.NewEncoder(ws.fuzzOut) + dec := json.NewDecoder(&contextReader{ctx: ctx, r: ws.fuzzIn}) + for { + var c call + if err := dec.Decode(&c); err != nil { + if err == io.EOF || err == ctx.Err() { + return nil + } else { + return err + } + } + + var resp any + switch { + case c.Fuzz != nil: + resp = ws.fuzz(ctx, *c.Fuzz) + case c.Minimize != nil: + resp = ws.minimize(ctx, *c.Minimize) + case c.Ping != nil: + resp = ws.ping(ctx, *c.Ping) + default: + return errors.New("no arguments provided for any call") + } + + if err := enc.Encode(resp); err != nil { + return err + } + } +} + +// chainedMutations is how many mutations are applied before the worker +// resets the input to its original state. +// NOTE: this number was picked without much thought. It is low enough that +// it seems to create a significant diversity in mutated inputs. We may want +// to consider looking into this more closely once we have a proper performance +// testing framework. Another option is to randomly pick the number of chained +// mutations on each invocation of the workerServer.fuzz method (this appears to +// be what libFuzzer does, although there seems to be no documentation which +// explains why this choice was made.) +const chainedMutations = 5 + +// fuzz runs the test function on random variations of the input value in shared +// memory for a limited duration or number of iterations. +// +// fuzz returns early if it finds an input that crashes the fuzz function (with +// fuzzResponse.Err set) or an input that expands coverage (with +// fuzzResponse.InterestingDuration set). +// +// fuzz does not modify the input in shared memory. Instead, it saves the +// initial PRNG state in shared memory and increments a counter in shared +// memory before each call to the test function. The caller may reconstruct +// the crashing input with this information, since the PRNG is deterministic. +func (ws *workerServer) fuzz(ctx context.Context, args fuzzArgs) (resp fuzzResponse) { + if args.CoverageData != nil { + if ws.coverageMask != nil && len(args.CoverageData) != len(ws.coverageMask) { + resp.InternalErr = fmt.Sprintf("unexpected size for CoverageData: got %d, expected %d", len(args.CoverageData), len(ws.coverageMask)) + return resp + } + ws.coverageMask = args.CoverageData + } + start := time.Now() + defer func() { resp.TotalDuration = time.Since(start) }() + + if args.Timeout != 0 { + var cancel func() + ctx, cancel = context.WithTimeout(ctx, args.Timeout) + defer cancel() + } + mem := <-ws.memMu + ws.m.r.save(&mem.header().randState, &mem.header().randInc) + defer func() { + resp.Count = mem.header().count + ws.memMu <- mem + }() + if args.Limit > 0 && mem.header().count >= args.Limit { + resp.InternalErr = fmt.Sprintf("mem.header().count %d already exceeds args.Limit %d", mem.header().count, args.Limit) + return resp + } + + originalVals, err := unmarshalCorpusFile(mem.valueCopy()) + if err != nil { + resp.InternalErr = err.Error() + return resp + } + vals := make([]any, len(originalVals)) + copy(vals, originalVals) + + shouldStop := func() bool { + return args.Limit > 0 && mem.header().count >= args.Limit + } + fuzzOnce := func(entry CorpusEntry) (dur time.Duration, cov []byte, errMsg string) { + mem.header().count++ + var err error + dur, err = ws.fuzzFn(entry) + if err != nil { + errMsg = err.Error() + if errMsg == "" { + errMsg = "fuzz function failed with no input" + } + return dur, nil, errMsg + } + if ws.coverageMask != nil && countNewCoverageBits(ws.coverageMask, coverageSnapshot) > 0 { + return dur, coverageSnapshot, "" + } + return dur, nil, "" + } + + if args.Warmup { + dur, _, errMsg := fuzzOnce(CorpusEntry{Values: vals}) + if errMsg != "" { + resp.Err = errMsg + return resp + } + resp.InterestingDuration = dur + if coverageEnabled { + resp.CoverageData = coverageSnapshot + } + return resp + } + + for { + select { + case <-ctx.Done(): + return resp + default: + if mem.header().count%chainedMutations == 0 { + copy(vals, originalVals) + ws.m.r.save(&mem.header().randState, &mem.header().randInc) + } + ws.m.mutate(vals, cap(mem.valueRef())) + + entry := CorpusEntry{Values: vals} + dur, cov, errMsg := fuzzOnce(entry) + if errMsg != "" { + resp.Err = errMsg + return resp + } + if cov != nil { + resp.CoverageData = cov + resp.InterestingDuration = dur + return resp + } + if shouldStop() { + return resp + } + } + } +} + +func (ws *workerServer) minimize(ctx context.Context, args minimizeArgs) (resp minimizeResponse) { + start := time.Now() + defer func() { resp.Duration = time.Since(start) }() + mem := <-ws.memMu + defer func() { ws.memMu <- mem }() + vals, err := unmarshalCorpusFile(mem.valueCopy()) + if err != nil { + panic(err) + } + inpHash := sha256.Sum256(mem.valueCopy()) + if args.Timeout != 0 { + var cancel func() + ctx, cancel = context.WithTimeout(ctx, args.Timeout) + defer cancel() + } + + // Minimize the values in vals, then write to shared memory. We only write + // to shared memory after completing minimization. + success, err := ws.minimizeInput(ctx, vals, mem, args) + if success { + writeToMem(vals, mem) + outHash := sha256.Sum256(mem.valueCopy()) + mem.header().rawInMem = false + resp.WroteToMem = true + if err != nil { + resp.Err = err.Error() + } else { + // If the values didn't change during minimization then coverageSnapshot is likely + // a dirty snapshot which represents the very last step of minimization, not the + // coverage for the initial input. In that case just return the coverage we were + // given initially, since it more accurately represents the coverage map for the + // input we are returning. + if outHash != inpHash { + resp.CoverageData = coverageSnapshot + } else { + resp.CoverageData = args.KeepCoverage + } + } + } + return resp +} + +// minimizeInput applies a series of minimizing transformations on the provided +// vals, ensuring that each minimization still causes an error, or keeps +// coverage, in fuzzFn. It uses the context to determine how long to run, +// stopping once closed. It returns a bool indicating whether minimization was +// successful and an error if one was found. +func (ws *workerServer) minimizeInput(ctx context.Context, vals []any, mem *sharedMem, args minimizeArgs) (success bool, retErr error) { + keepCoverage := args.KeepCoverage + memBytes := mem.valueRef() + bPtr := &memBytes + count := &mem.header().count + shouldStop := func() bool { + return ctx.Err() != nil || + (args.Limit > 0 && *count >= args.Limit) + } + if shouldStop() { + return false, nil + } + + // Check that the original value preserves coverage or causes an error. + // If not, then whatever caused us to think the value was interesting may + // have been a flake, and we can't minimize it. + *count++ + _, retErr = ws.fuzzFn(CorpusEntry{Values: vals}) + if keepCoverage != nil { + if !hasCoverageBit(keepCoverage, coverageSnapshot) || retErr != nil { + return false, nil + } + } else if retErr == nil { + return false, nil + } + mem.header().rawInMem = true + + // tryMinimized runs the fuzz function with candidate replacing the value + // at index valI. tryMinimized returns whether the input with candidate is + // interesting for the same reason as the original input: it returns + // an error if one was expected, or it preserves coverage. + tryMinimized := func(candidate []byte) bool { + prev := vals[args.Index] + switch prev.(type) { + case []byte: + vals[args.Index] = candidate + case string: + vals[args.Index] = string(candidate) + default: + panic("impossible") + } + copy(*bPtr, candidate) + *bPtr = (*bPtr)[:len(candidate)] + mem.setValueLen(len(candidate)) + *count++ + _, err := ws.fuzzFn(CorpusEntry{Values: vals}) + if err != nil { + retErr = err + if keepCoverage != nil { + // Now that we've found a crash, that's more important than any + // minimization of interesting inputs that was being done. Clear out + // keepCoverage to only minimize the crash going forward. + keepCoverage = nil + } + return true + } + // Minimization should preserve coverage bits. + if keepCoverage != nil && isCoverageSubset(keepCoverage, coverageSnapshot) { + return true + } + vals[args.Index] = prev + return false + } + switch v := vals[args.Index].(type) { + case string: + minimizeBytes([]byte(v), tryMinimized, shouldStop) + case []byte: + minimizeBytes(v, tryMinimized, shouldStop) + default: + panic("impossible") + } + return true, retErr +} + +func writeToMem(vals []any, mem *sharedMem) { + b := marshalCorpusFile(vals...) + mem.setValue(b) +} + +// ping does nothing. The coordinator calls this method to ensure the worker +// has called F.Fuzz and can communicate. +func (ws *workerServer) ping(ctx context.Context, args pingArgs) pingResponse { + return pingResponse{} +} + +// workerClient is a minimalist RPC client. The coordinator process uses a +// workerClient to call methods in each worker process (handled by +// workerServer). +type workerClient struct { + workerComm + m *mutator + + // mu is the mutex protecting the workerComm.fuzzIn pipe. This must be + // locked before making calls to the workerServer. It prevents + // workerClient.Close from closing fuzzIn while workerClient methods are + // writing to it concurrently, and prevents multiple callers from writing to + // fuzzIn concurrently. + mu sync.Mutex +} + +func newWorkerClient(comm workerComm, m *mutator) *workerClient { + return &workerClient{workerComm: comm, m: m} +} + +// Close shuts down the connection to the RPC server (the worker process) by +// closing fuzz_in. Close drains fuzz_out (avoiding a SIGPIPE in the worker), +// and closes it after the worker process closes the other end. +func (wc *workerClient) Close() error { + wc.mu.Lock() + defer wc.mu.Unlock() + + // Close fuzzIn. This signals to the server that there are no more calls, + // and it should exit. + if err := wc.fuzzIn.Close(); err != nil { + wc.fuzzOut.Close() + return err + } + + // Drain fuzzOut and close it. When the server exits, the kernel will close + // its end of fuzzOut, and we'll get EOF. + if _, err := io.Copy(io.Discard, wc.fuzzOut); err != nil { + wc.fuzzOut.Close() + return err + } + return wc.fuzzOut.Close() +} + +// errSharedMemClosed is returned by workerClient methods that cannot access +// shared memory because it was closed and unmapped by another goroutine. That +// can happen when worker.cleanup is called in the worker goroutine while a +// workerClient.fuzz call runs concurrently. +// +// This error should not be reported. It indicates the operation was +// interrupted. +var errSharedMemClosed = errors.New("internal error: shared memory was closed and unmapped") + +// minimize tells the worker to call the minimize method. See +// workerServer.minimize. +func (wc *workerClient) minimize(ctx context.Context, entryIn CorpusEntry, args minimizeArgs) (entryOut CorpusEntry, resp minimizeResponse, retErr error) { + wc.mu.Lock() + defer wc.mu.Unlock() + + mem, ok := <-wc.memMu + if !ok { + return CorpusEntry{}, minimizeResponse{}, errSharedMemClosed + } + defer func() { wc.memMu <- mem }() + mem.header().count = 0 + inp, err := corpusEntryData(entryIn) + if err != nil { + return CorpusEntry{}, minimizeResponse{}, err + } + mem.setValue(inp) + entryOut = entryIn + entryOut.Values, err = unmarshalCorpusFile(inp) + if err != nil { + return CorpusEntry{}, minimizeResponse{}, fmt.Errorf("workerClient.minimize unmarshaling provided value: %v", err) + } + for i, v := range entryOut.Values { + if !isMinimizable(reflect.TypeOf(v)) { + continue + } + + wc.memMu <- mem + args.Index = i + c := call{Minimize: &args} + callErr := wc.callLocked(ctx, c, &resp) + mem, ok = <-wc.memMu + if !ok { + return CorpusEntry{}, minimizeResponse{}, errSharedMemClosed + } + + if callErr != nil { + retErr = callErr + if !mem.header().rawInMem { + // An unrecoverable error occurred before minimization began. + return entryIn, minimizeResponse{}, retErr + } + // An unrecoverable error occurred during minimization. mem now + // holds the raw, unmarshaled bytes of entryIn.Values[i] that + // caused the error. + switch entryOut.Values[i].(type) { + case string: + entryOut.Values[i] = string(mem.valueCopy()) + case []byte: + entryOut.Values[i] = mem.valueCopy() + default: + panic("impossible") + } + entryOut.Data = marshalCorpusFile(entryOut.Values...) + // Stop minimizing; another unrecoverable error is likely to occur. + break + } + + if resp.WroteToMem { + // Minimization succeeded, and mem holds the marshaled data. + entryOut.Data = mem.valueCopy() + entryOut.Values, err = unmarshalCorpusFile(entryOut.Data) + if err != nil { + return CorpusEntry{}, minimizeResponse{}, fmt.Errorf("workerClient.minimize unmarshaling minimized value: %v", err) + } + } + + // Prepare for next iteration of the loop. + if args.Timeout != 0 { + args.Timeout -= resp.Duration + if args.Timeout <= 0 { + break + } + } + if args.Limit != 0 { + args.Limit -= mem.header().count + if args.Limit <= 0 { + break + } + } + } + resp.Count = mem.header().count + h := sha256.Sum256(entryOut.Data) + entryOut.Path = fmt.Sprintf("%x", h[:4]) + return entryOut, resp, retErr +} + +// fuzz tells the worker to call the fuzz method. See workerServer.fuzz. +func (wc *workerClient) fuzz(ctx context.Context, entryIn CorpusEntry, args fuzzArgs) (entryOut CorpusEntry, resp fuzzResponse, isInternalError bool, err error) { + wc.mu.Lock() + defer wc.mu.Unlock() + + mem, ok := <-wc.memMu + if !ok { + return CorpusEntry{}, fuzzResponse{}, true, errSharedMemClosed + } + mem.header().count = 0 + inp, err := corpusEntryData(entryIn) + if err != nil { + wc.memMu <- mem + return CorpusEntry{}, fuzzResponse{}, true, err + } + mem.setValue(inp) + wc.memMu <- mem + + c := call{Fuzz: &args} + callErr := wc.callLocked(ctx, c, &resp) + if resp.InternalErr != "" { + return CorpusEntry{}, fuzzResponse{}, true, errors.New(resp.InternalErr) + } + mem, ok = <-wc.memMu + if !ok { + return CorpusEntry{}, fuzzResponse{}, true, errSharedMemClosed + } + defer func() { wc.memMu <- mem }() + resp.Count = mem.header().count + + if !bytes.Equal(inp, mem.valueRef()) { + return CorpusEntry{}, fuzzResponse{}, true, errors.New("workerServer.fuzz modified input") + } + needEntryOut := callErr != nil || resp.Err != "" || + (!args.Warmup && resp.CoverageData != nil) + if needEntryOut { + valuesOut, err := unmarshalCorpusFile(inp) + if err != nil { + return CorpusEntry{}, fuzzResponse{}, true, fmt.Errorf("unmarshaling fuzz input value after call: %v", err) + } + wc.m.r.restore(mem.header().randState, mem.header().randInc) + if !args.Warmup { + // Only mutate the valuesOut if fuzzing actually occurred. + numMutations := ((resp.Count - 1) % chainedMutations) + 1 + for i := int64(0); i < numMutations; i++ { + wc.m.mutate(valuesOut, cap(mem.valueRef())) + } + } + dataOut := marshalCorpusFile(valuesOut...) + + h := sha256.Sum256(dataOut) + name := fmt.Sprintf("%x", h[:4]) + entryOut = CorpusEntry{ + Parent: entryIn.Path, + Path: name, + Data: dataOut, + Generation: entryIn.Generation + 1, + } + if args.Warmup { + // The bytes weren't mutated, so if entryIn was a seed corpus value, + // then entryOut is too. + entryOut.IsSeed = entryIn.IsSeed + } + } + + return entryOut, resp, false, callErr +} + +// ping tells the worker to call the ping method. See workerServer.ping. +func (wc *workerClient) ping(ctx context.Context) error { + wc.mu.Lock() + defer wc.mu.Unlock() + c := call{Ping: &pingArgs{}} + var resp pingResponse + return wc.callLocked(ctx, c, &resp) +} + +// callLocked sends an RPC from the coordinator to the worker process and waits +// for the response. The callLocked may be canceled with ctx. +func (wc *workerClient) callLocked(ctx context.Context, c call, resp any) (err error) { + enc := json.NewEncoder(wc.fuzzIn) + dec := json.NewDecoder(&contextReader{ctx: ctx, r: wc.fuzzOut}) + if err := enc.Encode(c); err != nil { + return err + } + return dec.Decode(resp) +} + +// contextReader wraps a Reader with a Context. If the context is canceled +// while the underlying reader is blocked, Read returns immediately. +// +// This is useful for reading from a pipe. Closing a pipe file descriptor does +// not unblock pending Reads on that file descriptor. All copies of the pipe's +// other file descriptor (the write end) must be closed in all processes that +// inherit it. This is difficult to do correctly in the situation we care about +// (process group termination). +type contextReader struct { + ctx context.Context + r io.Reader +} + +func (cr *contextReader) Read(b []byte) (int, error) { + if ctxErr := cr.ctx.Err(); ctxErr != nil { + return 0, ctxErr + } + done := make(chan struct{}) + + // This goroutine may stay blocked after Read returns because the underlying + // read is blocked. + var n int + var err error + go func() { + n, err = cr.r.Read(b) + close(done) + }() + + select { + case <-cr.ctx.Done(): + return 0, cr.ctx.Err() + case <-done: + return n, err + } +} diff --git a/go/src/internal/fuzz/worker_test.go b/go/src/internal/fuzz/worker_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9420248d2c0d60902d0a3ac08374907278410d8a --- /dev/null +++ b/go/src/internal/fuzz/worker_test.go @@ -0,0 +1,205 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fuzz + +import ( + "context" + "errors" + "flag" + "fmt" + "internal/race" + "io" + "os" + "os/signal" + "reflect" + "strconv" + "testing" + "time" +) + +var benchmarkWorkerFlag = flag.Bool("benchmarkworker", false, "") + +func TestMain(m *testing.M) { + flag.Parse() + if *benchmarkWorkerFlag { + runBenchmarkWorker() + return + } + os.Exit(m.Run()) +} + +func BenchmarkWorkerFuzzOverhead(b *testing.B) { + if race.Enabled { + b.Skip("TODO(48504): fix and re-enable") + } + origEnv := os.Getenv("GODEBUG") + defer func() { os.Setenv("GODEBUG", origEnv) }() + os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv)) + + ws := &workerServer{ + fuzzFn: func(_ CorpusEntry) (time.Duration, error) { return time.Second, nil }, + workerComm: workerComm{memMu: make(chan *sharedMem, 1)}, + } + + mem, err := sharedMemTempFile(workerSharedMemSize) + if err != nil { + b.Fatalf("failed to create temporary shared memory file: %s", err) + } + defer func() { + if err := mem.Close(); err != nil { + b.Error(err) + } + }() + + initialVal := []any{make([]byte, 32)} + encodedVals := marshalCorpusFile(initialVal...) + mem.setValue(encodedVals) + + ws.memMu <- mem + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ws.m = newMutator() + mem.setValue(encodedVals) + mem.header().count = 0 + + ws.fuzz(context.Background(), fuzzArgs{Limit: 1}) + } +} + +// BenchmarkWorkerPing acts as the coordinator and measures the time it takes +// a worker to respond to N pings. This is a rough measure of our RPC latency. +func BenchmarkWorkerPing(b *testing.B) { + if race.Enabled { + b.Skip("TODO(48504): fix and re-enable") + } + b.SetParallelism(1) + w := newWorkerForTest(b) + for i := 0; i < b.N; i++ { + if err := w.client.ping(context.Background()); err != nil { + b.Fatal(err) + } + } +} + +// BenchmarkWorkerFuzz acts as the coordinator and measures the time it takes +// a worker to mutate a given input and call a trivial fuzz function N times. +func BenchmarkWorkerFuzz(b *testing.B) { + if race.Enabled { + b.Skip("TODO(48504): fix and re-enable") + } + b.SetParallelism(1) + w := newWorkerForTest(b) + entry := CorpusEntry{Values: []any{[]byte(nil)}} + entry.Data = marshalCorpusFile(entry.Values...) + for i := int64(0); i < int64(b.N); { + args := fuzzArgs{ + Limit: int64(b.N) - i, + Timeout: workerFuzzDuration, + } + _, resp, _, err := w.client.fuzz(context.Background(), entry, args) + if err != nil { + b.Fatal(err) + } + if resp.Err != "" { + b.Fatal(resp.Err) + } + if resp.Count == 0 { + b.Fatal("worker did not make progress") + } + i += resp.Count + } +} + +// newWorkerForTest creates and starts a worker process for testing or +// benchmarking. The worker process calls RunFuzzWorker, which responds to +// RPC messages until it's stopped. The process is stopped and cleaned up +// automatically when the test is done. +func newWorkerForTest(tb testing.TB) *worker { + tb.Helper() + c, err := newCoordinator(CoordinateFuzzingOpts{ + Types: []reflect.Type{reflect.TypeOf([]byte(nil))}, + Log: io.Discard, + }) + if err != nil { + tb.Fatal(err) + } + dir := "" // same as self + binPath := os.Args[0] // same as self + args := append(os.Args[1:], "-benchmarkworker") + env := os.Environ() // same as self + w, err := newWorker(c, dir, binPath, args, env) + if err != nil { + tb.Fatal(err) + } + tb.Cleanup(func() { + if err := w.cleanup(); err != nil { + tb.Error(err) + } + }) + if err := w.startAndPing(context.Background()); err != nil { + tb.Fatal(err) + } + tb.Cleanup(func() { + if err := w.stop(); err != nil { + tb.Error(err) + } + }) + return w +} + +func runBenchmarkWorker() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) + defer cancel() + fn := func(CorpusEntry) error { return nil } + if err := RunFuzzWorker(ctx, fn); err != nil && err != ctx.Err() { + panic(err) + } +} + +func BenchmarkWorkerMinimize(b *testing.B) { + if race.Enabled { + b.Skip("TODO(48504): fix and re-enable") + } + + ws := &workerServer{ + workerComm: workerComm{memMu: make(chan *sharedMem, 1)}, + } + + mem, err := sharedMemTempFile(workerSharedMemSize) + if err != nil { + b.Fatalf("failed to create temporary shared memory file: %s", err) + } + defer func() { + if err := mem.Close(); err != nil { + b.Error(err) + } + }() + ws.memMu <- mem + + bytes := make([]byte, 1024) + ctx := context.Background() + for sz := 1; sz <= len(bytes); sz <<= 1 { + input := []any{bytes[:sz]} + encodedVals := marshalCorpusFile(input...) + mem = <-ws.memMu + mem.setValue(encodedVals) + ws.memMu <- mem + b.Run(strconv.Itoa(sz), func(b *testing.B) { + i := 0 + ws.fuzzFn = func(_ CorpusEntry) (time.Duration, error) { + if i == 0 { + i++ + return time.Second, errors.New("initial failure for deflake") + } + return time.Second, nil + } + for i := 0; i < b.N; i++ { + b.SetBytes(int64(sz)) + ws.minimize(ctx, minimizeArgs{}) + } + }) + } +} diff --git a/go/src/internal/goarch/gengoarch.go b/go/src/internal/goarch/gengoarch.go new file mode 100644 index 0000000000000000000000000000000000000000..a52936efb60aaac96edaa8d90483567f32c3cab2 --- /dev/null +++ b/go/src/internal/goarch/gengoarch.go @@ -0,0 +1,60 @@ +// 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 ignore + +package main + +import ( + "bytes" + "fmt" + "log" + "os" + "strings" +) + +var goarches []string + +func main() { + data, err := os.ReadFile("../../internal/syslist/syslist.go") + if err != nil { + log.Fatal(err) + } + const goarchPrefix = `var KnownArch = map[string]bool{` + inGOARCH := false + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, goarchPrefix) { + inGOARCH = true + } else if inGOARCH && strings.HasPrefix(line, "}") { + break + } else if inGOARCH { + goarch := strings.Fields(line)[0] + goarch = strings.TrimPrefix(goarch, `"`) + goarch = strings.TrimSuffix(goarch, `":`) + goarches = append(goarches, goarch) + } + } + + for _, target := range goarches { + if target == "amd64p32" { + continue + } + var buf bytes.Buffer + fmt.Fprintf(&buf, "// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT.\n\n") + fmt.Fprintf(&buf, "//go:build %s\n\n", target) // must explicitly include target for bootstrapping purposes + fmt.Fprintf(&buf, "package goarch\n\n") + fmt.Fprintf(&buf, "const GOARCH = `%s`\n\n", target) + for _, goarch := range goarches { + value := 0 + if goarch == target { + value = 1 + } + fmt.Fprintf(&buf, "const Is%s = %d\n", strings.Title(goarch), value) + } + err := os.WriteFile("zgoarch_"+target+".go", buf.Bytes(), 0666) + if err != nil { + log.Fatal(err) + } + } +} diff --git a/go/src/internal/goarch/goarch.go b/go/src/internal/goarch/goarch.go new file mode 100644 index 0000000000000000000000000000000000000000..efcf298d3b7b35227cf767fbf935f784b93488eb --- /dev/null +++ b/go/src/internal/goarch/goarch.go @@ -0,0 +1,65 @@ +// 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 goarch contains GOARCH-specific constants. +package goarch + +// The next line makes 'go generate' write the zgoarch*.go files with +// per-arch information, including constants named $GOARCH for every +// GOARCH. The constant is 1 on the current system, 0 otherwise; multiplying +// by them is useful for defining GOARCH-specific constants. +// +//go:generate go run gengoarch.go + +// ArchFamilyType represents a family of one or more related architectures. +// For example, ppc64 and ppc64le are both members of the PPC64 family. +type ArchFamilyType int + +const ( + AMD64 ArchFamilyType = iota + ARM + ARM64 + I386 + LOONG64 + MIPS + MIPS64 + PPC64 + RISCV64 + S390X + WASM +) + +// PtrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant. +// It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit). +const PtrSize = 4 << (^uintptr(0) >> 63) + +// PtrBits is bit width of a pointer. +const PtrBits = PtrSize * 8 + +// ArchFamily is the architecture family (AMD64, ARM, ...) +const ArchFamily ArchFamilyType = _ArchFamily + +// BigEndian reports whether the architecture is big-endian. +const BigEndian = IsArmbe|IsArm64be|IsMips|IsMips64|IsPpc|IsPpc64|IsS390|IsS390x|IsSparc|IsSparc64 == 1 + +// DefaultPhysPageSize is the default physical page size. +const DefaultPhysPageSize = _DefaultPhysPageSize + +// PCQuantum is the minimal unit for a program counter (1 on x86, 4 on most other systems). +// The various PC tables record PC deltas pre-divided by PCQuantum. +const PCQuantum = _PCQuantum + +// Int64Align is the required alignment for a 64-bit integer (4 on 32-bit systems, 8 on 64-bit). +const Int64Align = PtrSize + +// MinFrameSize is the size of the system-reserved words at the bottom +// of a frame (just above the architectural stack pointer). +// It is zero on x86 and PtrSize on most non-x86 (LR-based) systems. +// On PowerPC it is larger, to cover three more reserved words: +// the compiler word, the link editor word, and the TOC save word. +const MinFrameSize = _MinFrameSize + +// StackAlign is the required alignment of the SP register. +// The stack must be at least word aligned, but some architectures require more. +const StackAlign = _StackAlign diff --git a/go/src/internal/goarch/goarch_386.go b/go/src/internal/goarch/goarch_386.go new file mode 100644 index 0000000000000000000000000000000000000000..c6214217fcf339a5eb279c0bf80e15441acfd9b1 --- /dev/null +++ b/go/src/internal/goarch/goarch_386.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = I386 + _DefaultPhysPageSize = 4096 + _PCQuantum = 1 + _MinFrameSize = 0 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_amd64.go b/go/src/internal/goarch/goarch_amd64.go new file mode 100644 index 0000000000000000000000000000000000000000..911e3e72421720f95412579c50917d54e781bc7b --- /dev/null +++ b/go/src/internal/goarch/goarch_amd64.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = AMD64 + _DefaultPhysPageSize = 4096 + _PCQuantum = 1 + _MinFrameSize = 0 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_arm.go b/go/src/internal/goarch/goarch_arm.go new file mode 100644 index 0000000000000000000000000000000000000000..a6591713c8204006a3d9cff45f56f345092b3b01 --- /dev/null +++ b/go/src/internal/goarch/goarch_arm.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = ARM + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 4 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_arm64.go b/go/src/internal/goarch/goarch_arm64.go new file mode 100644 index 0000000000000000000000000000000000000000..85d0b4763913212bb2be2e81d0c6880bfa0b88d4 --- /dev/null +++ b/go/src/internal/goarch/goarch_arm64.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = ARM64 + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 8 + _StackAlign = 16 +) diff --git a/go/src/internal/goarch/goarch_loong64.go b/go/src/internal/goarch/goarch_loong64.go new file mode 100644 index 0000000000000000000000000000000000000000..dae1f4da315b2d77a00cb8d59170ba40fcb5c18f --- /dev/null +++ b/go/src/internal/goarch/goarch_loong64.go @@ -0,0 +1,15 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build loong64 + +package goarch + +const ( + _ArchFamily = LOONG64 + _DefaultPhysPageSize = 16384 + _PCQuantum = 4 + _MinFrameSize = 8 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_mips.go b/go/src/internal/goarch/goarch_mips.go new file mode 100644 index 0000000000000000000000000000000000000000..59f3995e2a54fda0d1df6bfdbc883840fbfef0d6 --- /dev/null +++ b/go/src/internal/goarch/goarch_mips.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = MIPS + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 4 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_mips64.go b/go/src/internal/goarch/goarch_mips64.go new file mode 100644 index 0000000000000000000000000000000000000000..9e4f82797d410ae88a5bd6a7c8e6260c170b8da5 --- /dev/null +++ b/go/src/internal/goarch/goarch_mips64.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = MIPS64 + _DefaultPhysPageSize = 16384 + _PCQuantum = 4 + _MinFrameSize = 8 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_mips64le.go b/go/src/internal/goarch/goarch_mips64le.go new file mode 100644 index 0000000000000000000000000000000000000000..9e4f82797d410ae88a5bd6a7c8e6260c170b8da5 --- /dev/null +++ b/go/src/internal/goarch/goarch_mips64le.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = MIPS64 + _DefaultPhysPageSize = 16384 + _PCQuantum = 4 + _MinFrameSize = 8 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_mipsle.go b/go/src/internal/goarch/goarch_mipsle.go new file mode 100644 index 0000000000000000000000000000000000000000..3e6642bb86399ba7b01378d53111460a4a30ef21 --- /dev/null +++ b/go/src/internal/goarch/goarch_mipsle.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = MIPS + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 4 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_ppc64.go b/go/src/internal/goarch/goarch_ppc64.go new file mode 100644 index 0000000000000000000000000000000000000000..60cc846e6a380aae4cf1574739661e8a06efb392 --- /dev/null +++ b/go/src/internal/goarch/goarch_ppc64.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = PPC64 + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 32 + _StackAlign = 16 +) diff --git a/go/src/internal/goarch/goarch_ppc64le.go b/go/src/internal/goarch/goarch_ppc64le.go new file mode 100644 index 0000000000000000000000000000000000000000..60cc846e6a380aae4cf1574739661e8a06efb392 --- /dev/null +++ b/go/src/internal/goarch/goarch_ppc64le.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = PPC64 + _DefaultPhysPageSize = 65536 + _PCQuantum = 4 + _MinFrameSize = 32 + _StackAlign = 16 +) diff --git a/go/src/internal/goarch/goarch_riscv64.go b/go/src/internal/goarch/goarch_riscv64.go new file mode 100644 index 0000000000000000000000000000000000000000..468f9a6374b9ac0fb5ef2412641d70afaf1bee9a --- /dev/null +++ b/go/src/internal/goarch/goarch_riscv64.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = RISCV64 + _DefaultPhysPageSize = 4096 + _PCQuantum = 2 + _MinFrameSize = 8 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_s390x.go b/go/src/internal/goarch/goarch_s390x.go new file mode 100644 index 0000000000000000000000000000000000000000..20c5705581e79ce5c897c3b6c6e442a3c92c8a02 --- /dev/null +++ b/go/src/internal/goarch/goarch_s390x.go @@ -0,0 +1,13 @@ +// 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 goarch + +const ( + _ArchFamily = S390X + _DefaultPhysPageSize = 4096 + _PCQuantum = 2 + _MinFrameSize = 8 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/goarch_wasm.go b/go/src/internal/goarch/goarch_wasm.go new file mode 100644 index 0000000000000000000000000000000000000000..98618d6980edd7e0ae4329c7f0575e62d64023e8 --- /dev/null +++ b/go/src/internal/goarch/goarch_wasm.go @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package goarch + +const ( + _ArchFamily = WASM + _DefaultPhysPageSize = 65536 + _PCQuantum = 1 + _MinFrameSize = 0 + _StackAlign = PtrSize +) diff --git a/go/src/internal/goarch/zgoarch_386.go b/go/src/internal/goarch/zgoarch_386.go new file mode 100644 index 0000000000000000000000000000000000000000..4a9b0e67c454a7212c804269400f76a509aa3f2e --- /dev/null +++ b/go/src/internal/goarch/zgoarch_386.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build 386 + +package goarch + +const GOARCH = `386` + +const Is386 = 1 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_amd64.go b/go/src/internal/goarch/zgoarch_amd64.go new file mode 100644 index 0000000000000000000000000000000000000000..7926392b77510ceade8475edd1978559e248679e --- /dev/null +++ b/go/src/internal/goarch/zgoarch_amd64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build amd64 + +package goarch + +const GOARCH = `amd64` + +const Is386 = 0 +const IsAmd64 = 1 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_arm.go b/go/src/internal/goarch/zgoarch_arm.go new file mode 100644 index 0000000000000000000000000000000000000000..6c03b8b060c1b4b7728e297bd46bf44a20737a52 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_arm.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build arm + +package goarch + +const GOARCH = `arm` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 1 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_arm64.go b/go/src/internal/goarch/zgoarch_arm64.go new file mode 100644 index 0000000000000000000000000000000000000000..ad342d79c96bb2feb1038cb1ff6588bf4bc48b81 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_arm64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build arm64 + +package goarch + +const GOARCH = `arm64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 1 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_arm64be.go b/go/src/internal/goarch/zgoarch_arm64be.go new file mode 100644 index 0000000000000000000000000000000000000000..0f260030908ecad894c655cdac66113d593ff415 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_arm64be.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build arm64be + +package goarch + +const GOARCH = `arm64be` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 1 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_armbe.go b/go/src/internal/goarch/zgoarch_armbe.go new file mode 100644 index 0000000000000000000000000000000000000000..6092fee7516e3805f21eda7f2ad37cb093822203 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_armbe.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build armbe + +package goarch + +const GOARCH = `armbe` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 1 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_loong64.go b/go/src/internal/goarch/zgoarch_loong64.go new file mode 100644 index 0000000000000000000000000000000000000000..21c67e1176838ece2818fb177b15970432361a95 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_loong64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build loong64 + +package goarch + +const GOARCH = `loong64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 1 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mips.go b/go/src/internal/goarch/zgoarch_mips.go new file mode 100644 index 0000000000000000000000000000000000000000..0db19746556adf77af6c6b938a7622c18217a8ce --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mips.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mips + +package goarch + +const GOARCH = `mips` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 1 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mips64.go b/go/src/internal/goarch/zgoarch_mips64.go new file mode 100644 index 0000000000000000000000000000000000000000..738806f0aef0afa8eee1011c0065a46fcfc55fef --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mips64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mips64 + +package goarch + +const GOARCH = `mips64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 1 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mips64le.go b/go/src/internal/goarch/zgoarch_mips64le.go new file mode 100644 index 0000000000000000000000000000000000000000..8de5beb88197290bc0afd54e19687cfd608523dc --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mips64le.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mips64le + +package goarch + +const GOARCH = `mips64le` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 1 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mips64p32.go b/go/src/internal/goarch/zgoarch_mips64p32.go new file mode 100644 index 0000000000000000000000000000000000000000..ea461bed70c26ceee2d68d65c57f23239ef80b24 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mips64p32.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mips64p32 + +package goarch + +const GOARCH = `mips64p32` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 1 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mips64p32le.go b/go/src/internal/goarch/zgoarch_mips64p32le.go new file mode 100644 index 0000000000000000000000000000000000000000..15473ce6c7a047fa0a4768cd9c2784c35f27e48f --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mips64p32le.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mips64p32le + +package goarch + +const GOARCH = `mips64p32le` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 1 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_mipsle.go b/go/src/internal/goarch/zgoarch_mipsle.go new file mode 100644 index 0000000000000000000000000000000000000000..4955142e876539c6b8d328a429347750c4c055f7 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_mipsle.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build mipsle + +package goarch + +const GOARCH = `mipsle` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 1 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_ppc.go b/go/src/internal/goarch/zgoarch_ppc.go new file mode 100644 index 0000000000000000000000000000000000000000..ec01763b3c3ca5cdd7c891e0ee148b5341760b0f --- /dev/null +++ b/go/src/internal/goarch/zgoarch_ppc.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build ppc + +package goarch + +const GOARCH = `ppc` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 1 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_ppc64.go b/go/src/internal/goarch/zgoarch_ppc64.go new file mode 100644 index 0000000000000000000000000000000000000000..39be3925c8e919ac6f379dd44136b2a367261858 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_ppc64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build ppc64 + +package goarch + +const GOARCH = `ppc64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 1 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_ppc64le.go b/go/src/internal/goarch/zgoarch_ppc64le.go new file mode 100644 index 0000000000000000000000000000000000000000..5f959e0e0245efbf5c0c6f1dbe58ac31dcbb04f8 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_ppc64le.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build ppc64le + +package goarch + +const GOARCH = `ppc64le` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 1 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_riscv.go b/go/src/internal/goarch/zgoarch_riscv.go new file mode 100644 index 0000000000000000000000000000000000000000..8d81a14dd9beace1427502533023265c69675eaa --- /dev/null +++ b/go/src/internal/goarch/zgoarch_riscv.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build riscv + +package goarch + +const GOARCH = `riscv` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 1 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_riscv64.go b/go/src/internal/goarch/zgoarch_riscv64.go new file mode 100644 index 0000000000000000000000000000000000000000..1df989c2a696ed0eedd8b4ddaa31e441bf55f90b --- /dev/null +++ b/go/src/internal/goarch/zgoarch_riscv64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build riscv64 + +package goarch + +const GOARCH = `riscv64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 1 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_s390.go b/go/src/internal/goarch/zgoarch_s390.go new file mode 100644 index 0000000000000000000000000000000000000000..56815b9f435567794cdc2dc5999772497719f944 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_s390.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build s390 + +package goarch + +const GOARCH = `s390` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 1 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_s390x.go b/go/src/internal/goarch/zgoarch_s390x.go new file mode 100644 index 0000000000000000000000000000000000000000..e61e9bd5938a8bb5b2c30ae761b1081611c09bc4 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_s390x.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build s390x + +package goarch + +const GOARCH = `s390x` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 1 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_sparc.go b/go/src/internal/goarch/zgoarch_sparc.go new file mode 100644 index 0000000000000000000000000000000000000000..ee5b746566ddd2d4fc7b717167933a5e19d5206f --- /dev/null +++ b/go/src/internal/goarch/zgoarch_sparc.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build sparc + +package goarch + +const GOARCH = `sparc` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 1 +const IsSparc64 = 0 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_sparc64.go b/go/src/internal/goarch/zgoarch_sparc64.go new file mode 100644 index 0000000000000000000000000000000000000000..519aaa10c13bb591f2a0e681e2856b3e0e7a54a4 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_sparc64.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build sparc64 + +package goarch + +const GOARCH = `sparc64` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 1 +const IsWasm = 0 diff --git a/go/src/internal/goarch/zgoarch_wasm.go b/go/src/internal/goarch/zgoarch_wasm.go new file mode 100644 index 0000000000000000000000000000000000000000..25567a1b6481f6dbf2c864c527db3f53a5c83a03 --- /dev/null +++ b/go/src/internal/goarch/zgoarch_wasm.go @@ -0,0 +1,32 @@ +// Code generated by gengoarch.go using 'go generate'. DO NOT EDIT. + +//go:build wasm + +package goarch + +const GOARCH = `wasm` + +const Is386 = 0 +const IsAmd64 = 0 +const IsAmd64p32 = 0 +const IsArm = 0 +const IsArmbe = 0 +const IsArm64 = 0 +const IsArm64be = 0 +const IsLoong64 = 0 +const IsMips = 0 +const IsMipsle = 0 +const IsMips64 = 0 +const IsMips64le = 0 +const IsMips64p32 = 0 +const IsMips64p32le = 0 +const IsPpc = 0 +const IsPpc64 = 0 +const IsPpc64le = 0 +const IsRiscv = 0 +const IsRiscv64 = 0 +const IsS390 = 0 +const IsS390x = 0 +const IsSparc = 0 +const IsSparc64 = 0 +const IsWasm = 1 diff --git a/go/src/internal/godebug/godebug.go b/go/src/internal/godebug/godebug.go new file mode 100644 index 0000000000000000000000000000000000000000..8c66a8a19af4ba15cc2574e7f10cd46940020bff --- /dev/null +++ b/go/src/internal/godebug/godebug.go @@ -0,0 +1,316 @@ +// 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 godebug makes the settings in the $GODEBUG environment variable +// available to other packages. These settings are often used for compatibility +// tweaks, when we need to change a default behavior but want to let users +// opt back in to the original. For example GODEBUG=http2server=0 disables +// HTTP/2 support in the net/http server. +// +// In typical usage, code should declare a Setting as a global +// and then call Value each time the current setting value is needed: +// +// var http2server = godebug.New("http2server") +// +// func ServeConn(c net.Conn) { +// if http2server.Value() == "0" { +// disallow HTTP/2 +// ... +// } +// ... +// } +// +// Each time a non-default setting causes a change in program behavior, +// code must call [Setting.IncNonDefault] to increment a counter that can +// be reported by [runtime/metrics.Read]. The call must only happen when +// the program executes a non-default behavior, not just when the setting +// is set to a non-default value. This is occasionally (but very rarely) +// infeasible, in which case the internal/godebugs table entry must set +// Opaque: true, and the documentation in doc/godebug.md should +// mention that metrics are unavailable. +// +// Conventionally, the global variable representing a godebug is named +// for the godebug itself, with no case changes: +// +// var gotypesalias = godebug.New("gotypesalias") // this +// var goTypesAlias = godebug.New("gotypesalias") // NOT THIS +// +// The test in internal/godebugs that checks for use of IncNonDefault +// requires the use of this convention. +// +// Note that counters used with IncNonDefault must be added to +// various tables in other packages. See the [Setting.IncNonDefault] +// documentation for details. +package godebug + +// Note: Be careful about new imports here. Any package +// that internal/godebug imports cannot itself import internal/godebug, +// meaning it cannot introduce a GODEBUG setting of its own. +// We keep imports to the absolute bare minimum. +import ( + "internal/bisect" + "internal/godebugs" + "sync" + "sync/atomic" + "unsafe" + _ "unsafe" // go:linkname +) + +// A Setting is a single setting in the $GODEBUG environment variable. +type Setting struct { + name string + once sync.Once + *setting +} + +type setting struct { + value atomic.Pointer[value] + nonDefaultOnce sync.Once + nonDefault atomic.Uint64 + info *godebugs.Info +} + +type value struct { + text string + bisect *bisect.Matcher +} + +// New returns a new Setting for the $GODEBUG setting with the given name. +// +// GODEBUGs meant for use by end users must be listed in ../godebugs/table.go, +// which is used for generating and checking various documentation. +// If the name is not listed in that table, New will succeed but calling Value +// on the returned Setting will panic. +// To disable that panic for access to an undocumented setting, +// prefix the name with a #, as in godebug.New("#gofsystrace"). +// The # is a signal to New but not part of the key used in $GODEBUG. +// +// Note that almost all settings should arrange to call [IncNonDefault] precisely +// when program behavior is changing from the default due to the setting +// (not just when the setting is different, but when program behavior changes). +// See the [internal/godebug] package comment for more. +func New(name string) *Setting { + return &Setting{name: name} +} + +// Name returns the name of the setting. +func (s *Setting) Name() string { + if s.name != "" && s.name[0] == '#' { + return s.name[1:] + } + return s.name +} + +// Undocumented reports whether this is an undocumented setting. +func (s *Setting) Undocumented() bool { + return s.name != "" && s.name[0] == '#' +} + +// String returns a printable form for the setting: name=value. +func (s *Setting) String() string { + return s.Name() + "=" + s.Value() +} + +// IncNonDefault increments the non-default behavior counter +// associated with the given setting. +// This counter is exposed in the runtime/metrics value +// /godebug/non-default-behavior/:events. +// +// Note that Value must be called at least once before IncNonDefault. +func (s *Setting) IncNonDefault() { + s.nonDefaultOnce.Do(s.register) + s.nonDefault.Add(1) +} + +func (s *Setting) register() { + if s.info == nil || s.info.Opaque { + panic("godebug: unexpected IncNonDefault of " + s.name) + } + registerMetric("/godebug/non-default-behavior/"+s.Name()+":events", s.nonDefault.Load) +} + +// cache is a cache of all the GODEBUG settings, +// a locked map[string]*atomic.Pointer[string]. +// +// All Settings with the same name share a single +// *atomic.Pointer[string], so that when GODEBUG +// changes only that single atomic string pointer +// needs to be updated. +// +// A name appears in the values map either if it is the +// name of a Setting for which Value has been called +// at least once, or if the name has ever appeared in +// a name=value pair in the $GODEBUG environment variable. +// Once entered into the map, the name is never removed. +var cache sync.Map // name string -> value *atomic.Pointer[string] + +var empty value + +// Value returns the current value for the GODEBUG setting s. +// +// Value maintains an internal cache that is synchronized +// with changes to the $GODEBUG environment variable, +// making Value efficient to call as frequently as needed. +// Clients should therefore typically not attempt their own +// caching of Value's result. +func (s *Setting) Value() string { + s.once.Do(func() { + s.setting = lookup(s.Name()) + if s.info == nil && !s.Undocumented() { + panic("godebug: Value of name not listed in godebugs.All: " + s.name) + } + }) + v := *s.value.Load() + if v.bisect != nil && !v.bisect.Stack(&stderr) { + return "" + } + return v.text +} + +// lookup returns the unique *setting value for the given name. +func lookup(name string) *setting { + if v, ok := cache.Load(name); ok { + return v.(*setting) + } + s := new(setting) + s.info = godebugs.Lookup(name) + s.value.Store(&empty) + if v, loaded := cache.LoadOrStore(name, s); loaded { + // Lost race: someone else created it. Use theirs. + return v.(*setting) + } + + return s +} + +// setUpdate is provided by package runtime. +// It calls update(def, env), where def is the default GODEBUG setting +// and env is the current value of the $GODEBUG environment variable. +// After that first call, the runtime calls update(def, env) +// again each time the environment variable changes +// (due to use of os.Setenv, for example). +// +//go:linkname setUpdate +func setUpdate(update func(string, string)) + +// registerMetric is provided by package runtime. +// It forwards registrations to runtime/metrics. +// +//go:linkname registerMetric +func registerMetric(name string, read func() uint64) + +// setNewIncNonDefault is provided by package runtime. +// The runtime can do +// +// inc := newNonDefaultInc(name) +// +// instead of +// +// inc := godebug.New(name).IncNonDefault +// +// since it cannot import godebug. +// +//go:linkname setNewIncNonDefault +func setNewIncNonDefault(newIncNonDefault func(string) func()) + +func init() { + setUpdate(update) + setNewIncNonDefault(newIncNonDefault) +} + +func newIncNonDefault(name string) func() { + s := New(name) + s.Value() + return s.IncNonDefault +} + +var updateMu sync.Mutex + +// update records an updated GODEBUG setting. +// def is the default GODEBUG setting for the running binary, +// and env is the current value of the $GODEBUG environment variable. +func update(def, env string) { + updateMu.Lock() + defer updateMu.Unlock() + + // Update all the cached values, creating new ones as needed. + // We parse the environment variable first, so that any settings it has + // are already locked in place (did[name] = true) before we consider + // the defaults. Existing immutable settings are always locked. + did := make(map[string]bool) + cache.Range(func(name, s any) bool { + if info := s.(*setting).info; info != nil && info.Immutable { + did[name.(string)] = true + } + return true + }) + parse(did, env) + parse(did, def) + + // Clear any cached values that are no longer present. + cache.Range(func(name, s any) bool { + if !did[name.(string)] { + s.(*setting).value.Store(&empty) + } + return true + }) +} + +// parse parses the GODEBUG setting string s, +// which has the form k=v,k2=v2,k3=v3. +// Later settings override earlier ones. +// Parse only updates settings k=v for which did[k] = false. +// It also sets did[k] = true for settings that it updates. +// Each value v can also have the form v#pattern, +// in which case the GODEBUG is only enabled for call stacks +// matching pattern, for use with golang.org/x/tools/cmd/bisect. +func parse(did map[string]bool, s string) { + // Scan the string backward so that later settings are used + // and earlier settings are ignored. + // Note that a forward scan would cause cached values + // to temporarily use the ignored value before being + // updated to the "correct" one. + end := len(s) + eq := -1 + for i := end - 1; i >= -1; i-- { + if i == -1 || s[i] == ',' { + if eq >= 0 { + name, arg := s[i+1:eq], s[eq+1:end] + if !did[name] { + did[name] = true + v := &value{text: arg} + for j := 0; j < len(arg); j++ { + if arg[j] == '#' { + v.text = arg[:j] + v.bisect, _ = bisect.New(arg[j+1:]) + break + } + } + lookup(name).value.Store(v) + } + } + eq = -1 + end = i + } else if s[i] == '=' { + eq = i + } + } +} + +type runtimeStderr struct{} + +var stderr runtimeStderr + +func (*runtimeStderr) Write(b []byte) (int, error) { + if len(b) > 0 { + write(2, unsafe.Pointer(&b[0]), int32(len(b))) + } + return len(b), nil +} + +// Since we cannot import os or syscall, use the runtime's write function +// to print to standard error. +// +//go:linkname write runtime.write +func write(fd uintptr, p unsafe.Pointer, n int32) int32 diff --git a/go/src/internal/godebug/godebug_test.go b/go/src/internal/godebug/godebug_test.go new file mode 100644 index 0000000000000000000000000000000000000000..47f4cc276102169d13e609ffeb9f925c8a9afc51 --- /dev/null +++ b/go/src/internal/godebug/godebug_test.go @@ -0,0 +1,193 @@ +// 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 godebug_test + +import ( + "fmt" + . "internal/godebug" + "internal/race" + "internal/testenv" + "os" + "os/exec" + "runtime/metrics" + "slices" + "strings" + "testing" +) + +func TestGet(t *testing.T) { + foo := New("#foo") + tests := []struct { + godebug string + setting *Setting + want string + }{ + {"", New("#"), ""}, + {"", foo, ""}, + {"foo=bar", foo, "bar"}, + {"foo=bar,after=x", foo, "bar"}, + {"before=x,foo=bar,after=x", foo, "bar"}, + {"before=x,foo=bar", foo, "bar"}, + {",,,foo=bar,,,", foo, "bar"}, + {"foodecoy=wrong,foo=bar", foo, "bar"}, + {"foo=", foo, ""}, + {"foo", foo, ""}, + {",foo", foo, ""}, + {"foo=bar,baz", New("#loooooooong"), ""}, + } + for _, tt := range tests { + t.Setenv("GODEBUG", tt.godebug) + got := tt.setting.Value() + if got != tt.want { + t.Errorf("get(%q, %q) = %q; want %q", tt.godebug, tt.setting.Name(), got, tt.want) + } + } +} + +func TestMetrics(t *testing.T) { + const name = "http2client" // must be a real name so runtime will accept it + + var m [1]metrics.Sample + m[0].Name = "/godebug/non-default-behavior/" + name + ":events" + metrics.Read(m[:]) + if kind := m[0].Value.Kind(); kind != metrics.KindUint64 { + t.Fatalf("NonDefault kind = %v, want uint64", kind) + } + + s := New(name) + s.Value() + s.IncNonDefault() + s.IncNonDefault() + s.IncNonDefault() + metrics.Read(m[:]) + if kind := m[0].Value.Kind(); kind != metrics.KindUint64 { + t.Fatalf("NonDefault kind = %v, want uint64", kind) + } + if count := m[0].Value.Uint64(); count != 3 { + t.Fatalf("NonDefault value = %d, want 3", count) + } +} + +// TestPanicNilRace checks for a race in the runtime caused by use of runtime +// atomics (not visible to usual race detection) to install the counter for +// non-default panic(nil) semantics. For #64649. +func TestPanicNilRace(t *testing.T) { + if !race.Enabled { + t.Skip("Skipping test intended for use with -race.") + } + if os.Getenv("GODEBUG") != "panicnil=1" { + cmd := testenv.CleanCmdEnv(testenv.Command(t, testenv.Executable(t), "-test.run=^TestPanicNilRace$", "-test.v", "-test.parallel=2", "-test.count=1")) + cmd.Env = append(cmd.Env, "GODEBUG=panicnil=1") + out, err := cmd.CombinedOutput() + t.Logf("output:\n%s", out) + + if err != nil { + t.Errorf("Was not expecting a crash") + } + return + } + + test := func(t *testing.T) { + t.Parallel() + defer func() { + recover() + }() + panic(nil) + } + t.Run("One", test) + t.Run("Two", test) +} + +func TestCmdBisect(t *testing.T) { + testenv.MustHaveGoRun(t) + out, err := exec.Command(testenv.GoToolPath(t), "run", "cmd/vendor/golang.org/x/tools/cmd/bisect", "GODEBUG=buggy=1#PATTERN", os.Args[0], "-test.run=^TestBisectTestCase$").CombinedOutput() + if err != nil { + t.Fatalf("exec bisect: %v\n%s", err, out) + } + + var want []string + src, err := os.ReadFile("godebug_test.go") + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(src), "\n") { + if strings.Contains(line, "BISECT"+" "+"BUG") { + want = append(want, fmt.Sprintf("godebug_test.go:%d", i+1)) + } + } + slices.Sort(want) + + var have []string + for _, line := range strings.Split(string(out), "\n") { + if strings.Contains(line, "godebug_test.go:") { + have = append(have, line[strings.LastIndex(line, "godebug_test.go:"):]) + } + } + slices.Sort(have) + + if !slices.Equal(have, want) { + t.Errorf("bad bisect output:\nhave %v\nwant %v\ncomplete output:\n%s", have, want, string(out)) + } +} + +// This test does nothing by itself, but you can run +// +// bisect 'GODEBUG=buggy=1#PATTERN' go test -run='^TestBisectTestCase$' +// +// to see that the GODEBUG bisect support is working. +// TestCmdBisect above does exactly that. +func TestBisectTestCase(t *testing.T) { + s := New("#buggy") + for i := 0; i < 10; i++ { + a := s.Value() == "1" + b := s.Value() == "1" + c := s.Value() == "1" // BISECT BUG + d := s.Value() == "1" // BISECT BUG + e := s.Value() == "1" // BISECT BUG + + if a { + t.Log("ok") + } + if b { + t.Log("ok") + } + if c { + t.Error("bug") + } + if d && + e { + t.Error("bug") + } + } +} + +func TestImmutable(t *testing.T) { + defer func(godebug string) { + os.Setenv("GODEBUG", godebug) + }(os.Getenv("GODEBUG")) + + setting := New("fips140") + value := setting.Value() + + os.Setenv("GODEBUG", "fips140=off") + if setting.Value() != value { + t.Errorf("Value() changed after setting GODEBUG=fips140=off") + } + + os.Setenv("GODEBUG", "fips140=on") + if setting.Value() != value { + t.Errorf("Value() changed after setting GODEBUG=fips140=on") + } + + os.Setenv("GODEBUG", "fips140=") + if setting.Value() != value { + t.Errorf("Value() changed after setting GODEBUG=fips140=") + } + + os.Setenv("GODEBUG", "") + if setting.Value() != value { + t.Errorf("Value() changed after setting GODEBUG=") + } +} diff --git a/go/src/internal/godebugs/godebugs_test.go b/go/src/internal/godebugs/godebugs_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e242f58c5536c8b58884e2c99442c204e884232b --- /dev/null +++ b/go/src/internal/godebugs/godebugs_test.go @@ -0,0 +1,103 @@ +// 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 godebugs_test + +import ( + "internal/godebugs" + "internal/testenv" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "testing" +) + +func TestAll(t *testing.T) { + testenv.MustHaveGoBuild(t) + + data, err := os.ReadFile("../../../doc/godebug.md") + if err != nil { + if os.IsNotExist(err) && (testenv.Builder() == "" || runtime.GOOS != "linux") { + t.Skip(err) + } + t.Fatal(err) + } + doc := string(data) + + incs := incNonDefaults(t) + + last := "" + for _, info := range godebugs.All { + if info.Name <= last { + t.Errorf("All not sorted: %s then %s", last, info.Name) + } + last = info.Name + + if info.Package == "" { + t.Errorf("Name=%s missing Package", info.Name) + } + if info.Changed != 0 && info.Old == "" { + t.Errorf("Name=%s has Changed, missing Old", info.Name) + } + if info.Old != "" && info.Changed == 0 { + t.Errorf("Name=%s has Old, missing Changed", info.Name) + } + if !strings.Contains(doc, "`"+info.Name+"`") && + !strings.Contains(doc, "`"+info.Name+"=") { + t.Errorf("Name=%s not documented in doc/godebug.md", info.Name) + } + if !info.Opaque && !incs[info.Name] { + t.Errorf("Name=%s missing IncNonDefault calls; see 'go doc internal/godebug'", info.Name) + } + } +} + +var incNonDefaultRE = regexp.MustCompile(`([\pL\p{Nd}_]+)\.IncNonDefault\(\)`) + +func incNonDefaults(t *testing.T) map[string]bool { + // Build list of all files importing internal/godebug. + // Tried a more sophisticated search in go list looking for + // imports containing "internal/godebug", but that turned + // up a bug in go list instead. #66218 + out, err := exec.Command("go", "list", "-f={{.Dir}}", "std", "cmd").CombinedOutput() + if err != nil { + t.Fatalf("go list: %v\n%s", err, out) + } + + seen := map[string]bool{} + for _, dir := range strings.Split(string(out), "\n") { + if dir == "" { + continue + } + files, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, file := range files { + name := file.Name() + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + data, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + for _, m := range incNonDefaultRE.FindAllSubmatch(data, -1) { + seen[string(m[1])] = true + } + } + } + return seen +} + +func TestRemoved(t *testing.T) { + for _, info := range godebugs.Removed { + if godebugs.Lookup(info.Name) != nil { + t.Fatalf("GODEBUG: %v exists in both Removed and All", info.Name) + } + } +} diff --git a/go/src/internal/godebugs/table.go b/go/src/internal/godebugs/table.go new file mode 100644 index 0000000000000000000000000000000000000000..014229399d04ba022ac8db2de3447d821b1990b1 --- /dev/null +++ b/go/src/internal/godebugs/table.go @@ -0,0 +1,114 @@ +// 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 godebugs provides a table of known GODEBUG settings, +// for use by a variety of other packages, including internal/godebug, +// runtime, runtime/metrics, and cmd/go/internal/load. +package godebugs + +// An Info describes a single known GODEBUG setting. +type Info struct { + Name string // name of the setting ("panicnil") + Package string // package that uses the setting ("runtime") + Changed int // minor version when default changed, if any; 21 means Go 1.21 + Old string // value that restores behavior prior to Changed + Opaque bool // setting does not export information to runtime/metrics using [internal/godebug.Setting.IncNonDefault] + Immutable bool // setting cannot be changed after program start +} + +// All is the table of known settings, sorted by Name. +// +// Note: After adding entries to this table, run 'go generate runtime/metrics' +// to update the runtime/metrics doc comment. +// (Otherwise the runtime/metrics test will fail.) +// +// Note: After adding entries to this table, update the list in doc/godebug.md as well. +// (Otherwise the test in this package will fail.) +var All = []Info{ + {Name: "allowmultiplevcs", Package: "cmd/go"}, + {Name: "asynctimerchan", Package: "time", Changed: 23, Old: "1"}, + {Name: "containermaxprocs", Package: "runtime", Changed: 25, Old: "0"}, + {Name: "cryptocustomrand", Package: "crypto", Changed: 26, Old: "1"}, + {Name: "dataindependenttiming", Package: "crypto/subtle", Opaque: true}, + {Name: "decoratemappings", Package: "runtime", Opaque: true, Changed: 25, Old: "0"}, + {Name: "embedfollowsymlinks", Package: "cmd/go"}, + {Name: "execerrdot", Package: "os/exec"}, + {Name: "fips140", Package: "crypto/fips140", Opaque: true, Immutable: true}, + {Name: "gocachehash", Package: "cmd/go"}, + {Name: "gocachetest", Package: "cmd/go"}, + {Name: "gocacheverify", Package: "cmd/go"}, + {Name: "gotestjsonbuildtext", Package: "cmd/go", Changed: 24, Old: "1"}, + {Name: "gotypesalias", Package: "go/types", Changed: 23, Old: "0"}, + {Name: "htmlmetacontenturlescape", Package: "html/template"}, + {Name: "http2client", Package: "net/http"}, + {Name: "http2debug", Package: "net/http", Opaque: true}, + {Name: "http2server", Package: "net/http"}, + {Name: "httpcookiemaxnum", Package: "net/http", Changed: 24, Old: "0"}, + {Name: "httplaxcontentlength", Package: "net/http", Changed: 22, Old: "1"}, + {Name: "httpmuxgo121", Package: "net/http", Changed: 22, Old: "1"}, + {Name: "httpservecontentkeepheaders", Package: "net/http", Changed: 23, Old: "1"}, + {Name: "installgoroot", Package: "go/build"}, + {Name: "jstmpllitinterp", Package: "html/template", Opaque: true}, // bug #66217: remove Opaque + //{Name: "multipartfiles", Package: "mime/multipart"}, + {Name: "multipartmaxheaders", Package: "mime/multipart"}, + {Name: "multipartmaxparts", Package: "mime/multipart"}, + {Name: "multipathtcp", Package: "net", Changed: 24, Old: "0"}, + {Name: "netdns", Package: "net", Opaque: true}, + {Name: "netedns0", Package: "net", Changed: 19, Old: "0"}, + {Name: "panicnil", Package: "runtime", Changed: 21, Old: "1"}, + {Name: "randautoseed", Package: "math/rand"}, + {Name: "randseednop", Package: "math/rand", Changed: 24, Old: "0"}, + {Name: "rsa1024min", Package: "crypto/rsa", Changed: 24, Old: "0"}, + {Name: "tarinsecurepath", Package: "archive/tar"}, + {Name: "tls10server", Package: "crypto/tls", Changed: 22, Old: "1"}, + {Name: "tls3des", Package: "crypto/tls", Changed: 23, Old: "1"}, + {Name: "tlsmaxrsasize", Package: "crypto/tls"}, + {Name: "tlsmlkem", Package: "crypto/tls", Changed: 24, Old: "0", Opaque: true}, + {Name: "tlsrsakex", Package: "crypto/tls", Changed: 22, Old: "1"}, + {Name: "tlssecpmlkem", Package: "crypto/tls", Changed: 26, Old: "0", Opaque: true}, + {Name: "tlssha1", Package: "crypto/tls", Changed: 25, Old: "1"}, + {Name: "tlsunsafeekm", Package: "crypto/tls", Changed: 22, Old: "1"}, + {Name: "updatemaxprocs", Package: "runtime", Changed: 25, Old: "0"}, + {Name: "urlmaxqueryparams", Package: "net/url", Changed: 24, Old: "0"}, + {Name: "urlstrictcolons", Package: "net/url", Changed: 26, Old: "0"}, + {Name: "winreadlinkvolume", Package: "os", Changed: 23, Old: "0"}, + {Name: "winsymlink", Package: "os", Changed: 23, Old: "0"}, + {Name: "x509keypairleaf", Package: "crypto/tls", Changed: 23, Old: "0"}, + {Name: "x509negativeserial", Package: "crypto/x509", Changed: 23, Old: "1"}, + {Name: "x509rsacrt", Package: "crypto/x509", Changed: 24, Old: "0"}, + {Name: "x509sha256skid", Package: "crypto/x509", Changed: 25, Old: "0"}, + {Name: "x509usefallbackroots", Package: "crypto/x509"}, + {Name: "x509usepolicies", Package: "crypto/x509", Changed: 24, Old: "0"}, + {Name: "zipinsecurepath", Package: "archive/zip"}, +} + +type RemovedInfo struct { + Name string // name of the removed GODEBUG setting. + Removed int // minor version of Go, when the removal happened +} + +// Removed contains all GODEBUGs that we have removed. +var Removed = []RemovedInfo{ + {Name: "x509sha1", Removed: 24}, +} + +// Lookup returns the Info with the given name. +func Lookup(name string) *Info { + // binary search, avoiding import of sort. + lo := 0 + hi := len(All) + for lo < hi { + m := int(uint(lo+hi) >> 1) + mid := All[m].Name + if name == mid { + return &All[m] + } + if name < mid { + hi = m + } else { + lo = m + 1 + } + } + return nil +} diff --git a/go/src/internal/goexperiment/exp_arenas_off.go b/go/src/internal/goexperiment/exp_arenas_off.go new file mode 100644 index 0000000000000000000000000000000000000000..01f5332e5cb6fb8f68ae393879a7572e855ca057 --- /dev/null +++ b/go/src/internal/goexperiment/exp_arenas_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.arenas + +package goexperiment + +const Arenas = false +const ArenasInt = 0 diff --git a/go/src/internal/goexperiment/exp_arenas_on.go b/go/src/internal/goexperiment/exp_arenas_on.go new file mode 100644 index 0000000000000000000000000000000000000000..609dfbca99fece662285243b04722d5dbbaf3551 --- /dev/null +++ b/go/src/internal/goexperiment/exp_arenas_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.arenas + +package goexperiment + +const Arenas = true +const ArenasInt = 1 diff --git a/go/src/internal/goexperiment/exp_boringcrypto_off.go b/go/src/internal/goexperiment/exp_boringcrypto_off.go new file mode 100644 index 0000000000000000000000000000000000000000..de712670fd6e9a70d067d2a0d9799df8d2e2e7e2 --- /dev/null +++ b/go/src/internal/goexperiment/exp_boringcrypto_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.boringcrypto + +package goexperiment + +const BoringCrypto = false +const BoringCryptoInt = 0 diff --git a/go/src/internal/goexperiment/exp_boringcrypto_on.go b/go/src/internal/goexperiment/exp_boringcrypto_on.go new file mode 100644 index 0000000000000000000000000000000000000000..ce476faa057144e1390f6b2b946eb8d3bc8adcb3 --- /dev/null +++ b/go/src/internal/goexperiment/exp_boringcrypto_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.boringcrypto + +package goexperiment + +const BoringCrypto = true +const BoringCryptoInt = 1 diff --git a/go/src/internal/goexperiment/exp_cgocheck2_off.go b/go/src/internal/goexperiment/exp_cgocheck2_off.go new file mode 100644 index 0000000000000000000000000000000000000000..e99ad0786121eb9573b49d1325b615bee85326e6 --- /dev/null +++ b/go/src/internal/goexperiment/exp_cgocheck2_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.cgocheck2 + +package goexperiment + +const CgoCheck2 = false +const CgoCheck2Int = 0 diff --git a/go/src/internal/goexperiment/exp_cgocheck2_on.go b/go/src/internal/goexperiment/exp_cgocheck2_on.go new file mode 100644 index 0000000000000000000000000000000000000000..f6d1790d4ca690440595caaac27aa6a04b3d5e40 --- /dev/null +++ b/go/src/internal/goexperiment/exp_cgocheck2_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.cgocheck2 + +package goexperiment + +const CgoCheck2 = true +const CgoCheck2Int = 1 diff --git a/go/src/internal/goexperiment/exp_dwarf5_off.go b/go/src/internal/goexperiment/exp_dwarf5_off.go new file mode 100644 index 0000000000000000000000000000000000000000..b89dd9f2d98d75050b0dd4f729e4e9e3eff576a6 --- /dev/null +++ b/go/src/internal/goexperiment/exp_dwarf5_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.dwarf5 + +package goexperiment + +const Dwarf5 = false +const Dwarf5Int = 0 diff --git a/go/src/internal/goexperiment/exp_dwarf5_on.go b/go/src/internal/goexperiment/exp_dwarf5_on.go new file mode 100644 index 0000000000000000000000000000000000000000..02b28d74e249d4b0eef1466ac25bd423d833da8f --- /dev/null +++ b/go/src/internal/goexperiment/exp_dwarf5_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.dwarf5 + +package goexperiment + +const Dwarf5 = true +const Dwarf5Int = 1 diff --git a/go/src/internal/goexperiment/exp_fieldtrack_off.go b/go/src/internal/goexperiment/exp_fieldtrack_off.go new file mode 100644 index 0000000000000000000000000000000000000000..ccced94cb0d94d75a26b4b77a6afcc2be2bdfe1d --- /dev/null +++ b/go/src/internal/goexperiment/exp_fieldtrack_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.fieldtrack + +package goexperiment + +const FieldTrack = false +const FieldTrackInt = 0 diff --git a/go/src/internal/goexperiment/exp_fieldtrack_on.go b/go/src/internal/goexperiment/exp_fieldtrack_on.go new file mode 100644 index 0000000000000000000000000000000000000000..a49756750a3b11a9134b7d36ced37725dc2661a4 --- /dev/null +++ b/go/src/internal/goexperiment/exp_fieldtrack_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.fieldtrack + +package goexperiment + +const FieldTrack = true +const FieldTrackInt = 1 diff --git a/go/src/internal/goexperiment/exp_goroutineleakprofile_off.go b/go/src/internal/goexperiment/exp_goroutineleakprofile_off.go new file mode 100644 index 0000000000000000000000000000000000000000..63eafe9e6c74db38e93d5c0bf588d18d5eec8842 --- /dev/null +++ b/go/src/internal/goexperiment/exp_goroutineleakprofile_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.goroutineleakprofile + +package goexperiment + +const GoroutineLeakProfile = false +const GoroutineLeakProfileInt = 0 diff --git a/go/src/internal/goexperiment/exp_goroutineleakprofile_on.go b/go/src/internal/goexperiment/exp_goroutineleakprofile_on.go new file mode 100644 index 0000000000000000000000000000000000000000..28a662eceb46f816b124551ba25f95984cc9b982 --- /dev/null +++ b/go/src/internal/goexperiment/exp_goroutineleakprofile_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.goroutineleakprofile + +package goexperiment + +const GoroutineLeakProfile = true +const GoroutineLeakProfileInt = 1 diff --git a/go/src/internal/goexperiment/exp_greenteagc_off.go b/go/src/internal/goexperiment/exp_greenteagc_off.go new file mode 100644 index 0000000000000000000000000000000000000000..dce9d8c997434ca73fcf217cea7a1e33c7d70b29 --- /dev/null +++ b/go/src/internal/goexperiment/exp_greenteagc_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.greenteagc + +package goexperiment + +const GreenTeaGC = false +const GreenTeaGCInt = 0 diff --git a/go/src/internal/goexperiment/exp_greenteagc_on.go b/go/src/internal/goexperiment/exp_greenteagc_on.go new file mode 100644 index 0000000000000000000000000000000000000000..10a007d757c148b9162e20226652e8f36267a028 --- /dev/null +++ b/go/src/internal/goexperiment/exp_greenteagc_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.greenteagc + +package goexperiment + +const GreenTeaGC = true +const GreenTeaGCInt = 1 diff --git a/go/src/internal/goexperiment/exp_heapminimum512kib_off.go b/go/src/internal/goexperiment/exp_heapminimum512kib_off.go new file mode 100644 index 0000000000000000000000000000000000000000..d67c5bb6747f4f56719cb5a847d332a1bf69c214 --- /dev/null +++ b/go/src/internal/goexperiment/exp_heapminimum512kib_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.heapminimum512kib + +package goexperiment + +const HeapMinimum512KiB = false +const HeapMinimum512KiBInt = 0 diff --git a/go/src/internal/goexperiment/exp_heapminimum512kib_on.go b/go/src/internal/goexperiment/exp_heapminimum512kib_on.go new file mode 100644 index 0000000000000000000000000000000000000000..2d29c98e1b110394957ad21e7538c36e6c749673 --- /dev/null +++ b/go/src/internal/goexperiment/exp_heapminimum512kib_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.heapminimum512kib + +package goexperiment + +const HeapMinimum512KiB = true +const HeapMinimum512KiBInt = 1 diff --git a/go/src/internal/goexperiment/exp_jsonv2_off.go b/go/src/internal/goexperiment/exp_jsonv2_off.go new file mode 100644 index 0000000000000000000000000000000000000000..a973a35ec2fe626640a54a125ccb5d5d61355aa9 --- /dev/null +++ b/go/src/internal/goexperiment/exp_jsonv2_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.jsonv2 + +package goexperiment + +const JSONv2 = false +const JSONv2Int = 0 diff --git a/go/src/internal/goexperiment/exp_jsonv2_on.go b/go/src/internal/goexperiment/exp_jsonv2_on.go new file mode 100644 index 0000000000000000000000000000000000000000..119d086874f834b85c6ea4a8773078b23f38b933 --- /dev/null +++ b/go/src/internal/goexperiment/exp_jsonv2_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.jsonv2 + +package goexperiment + +const JSONv2 = true +const JSONv2Int = 1 diff --git a/go/src/internal/goexperiment/exp_loopvar_off.go b/go/src/internal/goexperiment/exp_loopvar_off.go new file mode 100644 index 0000000000000000000000000000000000000000..cfede5405268d73e7774b6f0463b652c385795d0 --- /dev/null +++ b/go/src/internal/goexperiment/exp_loopvar_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.loopvar + +package goexperiment + +const LoopVar = false +const LoopVarInt = 0 diff --git a/go/src/internal/goexperiment/exp_loopvar_on.go b/go/src/internal/goexperiment/exp_loopvar_on.go new file mode 100644 index 0000000000000000000000000000000000000000..e158e0a666ab077e19c9df3ae700dcbeefb7ccc1 --- /dev/null +++ b/go/src/internal/goexperiment/exp_loopvar_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.loopvar + +package goexperiment + +const LoopVar = true +const LoopVarInt = 1 diff --git a/go/src/internal/goexperiment/exp_newinliner_off.go b/go/src/internal/goexperiment/exp_newinliner_off.go new file mode 100644 index 0000000000000000000000000000000000000000..d94e736528f60bd7b6cc9e78dcd3fc7ff1dbc0ef --- /dev/null +++ b/go/src/internal/goexperiment/exp_newinliner_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.newinliner + +package goexperiment + +const NewInliner = false +const NewInlinerInt = 0 diff --git a/go/src/internal/goexperiment/exp_newinliner_on.go b/go/src/internal/goexperiment/exp_newinliner_on.go new file mode 100644 index 0000000000000000000000000000000000000000..6777dbc048759847ba0b687f1c2b63b811af2bf8 --- /dev/null +++ b/go/src/internal/goexperiment/exp_newinliner_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.newinliner + +package goexperiment + +const NewInliner = true +const NewInlinerInt = 1 diff --git a/go/src/internal/goexperiment/exp_preemptibleloops_off.go b/go/src/internal/goexperiment/exp_preemptibleloops_off.go new file mode 100644 index 0000000000000000000000000000000000000000..cddcc1b8cc20328acedc74faab8516a9ba8c84a5 --- /dev/null +++ b/go/src/internal/goexperiment/exp_preemptibleloops_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.preemptibleloops + +package goexperiment + +const PreemptibleLoops = false +const PreemptibleLoopsInt = 0 diff --git a/go/src/internal/goexperiment/exp_preemptibleloops_on.go b/go/src/internal/goexperiment/exp_preemptibleloops_on.go new file mode 100644 index 0000000000000000000000000000000000000000..7f474c035772586662ba4c53832745df14e41f48 --- /dev/null +++ b/go/src/internal/goexperiment/exp_preemptibleloops_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.preemptibleloops + +package goexperiment + +const PreemptibleLoops = true +const PreemptibleLoopsInt = 1 diff --git a/go/src/internal/goexperiment/exp_randomizedheapbase64_off.go b/go/src/internal/goexperiment/exp_randomizedheapbase64_off.go new file mode 100644 index 0000000000000000000000000000000000000000..0a578535a4444284f72d5ccabd1d1cf76e6a051d --- /dev/null +++ b/go/src/internal/goexperiment/exp_randomizedheapbase64_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.randomizedheapbase64 + +package goexperiment + +const RandomizedHeapBase64 = false +const RandomizedHeapBase64Int = 0 diff --git a/go/src/internal/goexperiment/exp_randomizedheapbase64_on.go b/go/src/internal/goexperiment/exp_randomizedheapbase64_on.go new file mode 100644 index 0000000000000000000000000000000000000000..10d59c702884a5da17f76d8ee031b2a7f484b13a --- /dev/null +++ b/go/src/internal/goexperiment/exp_randomizedheapbase64_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.randomizedheapbase64 + +package goexperiment + +const RandomizedHeapBase64 = true +const RandomizedHeapBase64Int = 1 diff --git a/go/src/internal/goexperiment/exp_regabiargs_off.go b/go/src/internal/goexperiment/exp_regabiargs_off.go new file mode 100644 index 0000000000000000000000000000000000000000..a8c8536fa01c6934ba7d6f0f079855527dbbf1ed --- /dev/null +++ b/go/src/internal/goexperiment/exp_regabiargs_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.regabiargs + +package goexperiment + +const RegabiArgs = false +const RegabiArgsInt = 0 diff --git a/go/src/internal/goexperiment/exp_regabiargs_on.go b/go/src/internal/goexperiment/exp_regabiargs_on.go new file mode 100644 index 0000000000000000000000000000000000000000..def3b9400475ca2c518c2fdc5456ffd5be0eb27f --- /dev/null +++ b/go/src/internal/goexperiment/exp_regabiargs_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.regabiargs + +package goexperiment + +const RegabiArgs = true +const RegabiArgsInt = 1 diff --git a/go/src/internal/goexperiment/exp_regabiwrappers_off.go b/go/src/internal/goexperiment/exp_regabiwrappers_off.go new file mode 100644 index 0000000000000000000000000000000000000000..a65ed3649d6251d3bc6e65eae8141ad139a1462e --- /dev/null +++ b/go/src/internal/goexperiment/exp_regabiwrappers_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.regabiwrappers + +package goexperiment + +const RegabiWrappers = false +const RegabiWrappersInt = 0 diff --git a/go/src/internal/goexperiment/exp_regabiwrappers_on.go b/go/src/internal/goexperiment/exp_regabiwrappers_on.go new file mode 100644 index 0000000000000000000000000000000000000000..d525c9a86d15ec35fca72c806fe2e2b58ccb0d66 --- /dev/null +++ b/go/src/internal/goexperiment/exp_regabiwrappers_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.regabiwrappers + +package goexperiment + +const RegabiWrappers = true +const RegabiWrappersInt = 1 diff --git a/go/src/internal/goexperiment/exp_runtimefreegc_off.go b/go/src/internal/goexperiment/exp_runtimefreegc_off.go new file mode 100644 index 0000000000000000000000000000000000000000..195f031b0b398032ef523f12cdcde088b63332c6 --- /dev/null +++ b/go/src/internal/goexperiment/exp_runtimefreegc_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.runtimefreegc + +package goexperiment + +const RuntimeFreegc = false +const RuntimeFreegcInt = 0 diff --git a/go/src/internal/goexperiment/exp_runtimefreegc_on.go b/go/src/internal/goexperiment/exp_runtimefreegc_on.go new file mode 100644 index 0000000000000000000000000000000000000000..2afe0558ec88700e3f3c83d796527dc6e2da1985 --- /dev/null +++ b/go/src/internal/goexperiment/exp_runtimefreegc_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.runtimefreegc + +package goexperiment + +const RuntimeFreegc = true +const RuntimeFreegcInt = 1 diff --git a/go/src/internal/goexperiment/exp_runtimesecret_off.go b/go/src/internal/goexperiment/exp_runtimesecret_off.go new file mode 100644 index 0000000000000000000000000000000000000000..d203589249c52d0b9629a14a1813320db6c6638c --- /dev/null +++ b/go/src/internal/goexperiment/exp_runtimesecret_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.runtimesecret + +package goexperiment + +const RuntimeSecret = false +const RuntimeSecretInt = 0 diff --git a/go/src/internal/goexperiment/exp_runtimesecret_on.go b/go/src/internal/goexperiment/exp_runtimesecret_on.go new file mode 100644 index 0000000000000000000000000000000000000000..3788953db8b0345d89ce15c7401356c27341c43a --- /dev/null +++ b/go/src/internal/goexperiment/exp_runtimesecret_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.runtimesecret + +package goexperiment + +const RuntimeSecret = true +const RuntimeSecretInt = 1 diff --git a/go/src/internal/goexperiment/exp_simd_off.go b/go/src/internal/goexperiment/exp_simd_off.go new file mode 100644 index 0000000000000000000000000000000000000000..ebc40b308e384d9f4dcd912e443eebfb3513216b --- /dev/null +++ b/go/src/internal/goexperiment/exp_simd_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.simd + +package goexperiment + +const SIMD = false +const SIMDInt = 0 diff --git a/go/src/internal/goexperiment/exp_simd_on.go b/go/src/internal/goexperiment/exp_simd_on.go new file mode 100644 index 0000000000000000000000000000000000000000..137d1dd1ba3fbadf7d8f355eed41695c557c25fc --- /dev/null +++ b/go/src/internal/goexperiment/exp_simd_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.simd + +package goexperiment + +const SIMD = true +const SIMDInt = 1 diff --git a/go/src/internal/goexperiment/exp_sizespecializedmalloc_off.go b/go/src/internal/goexperiment/exp_sizespecializedmalloc_off.go new file mode 100644 index 0000000000000000000000000000000000000000..2642a12d798607da31f4bc3d1d018ae2b37eae4e --- /dev/null +++ b/go/src/internal/goexperiment/exp_sizespecializedmalloc_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.sizespecializedmalloc + +package goexperiment + +const SizeSpecializedMalloc = false +const SizeSpecializedMallocInt = 0 diff --git a/go/src/internal/goexperiment/exp_sizespecializedmalloc_on.go b/go/src/internal/goexperiment/exp_sizespecializedmalloc_on.go new file mode 100644 index 0000000000000000000000000000000000000000..a135cc889e84a751a07641bcb5b5b885378e93f8 --- /dev/null +++ b/go/src/internal/goexperiment/exp_sizespecializedmalloc_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.sizespecializedmalloc + +package goexperiment + +const SizeSpecializedMalloc = true +const SizeSpecializedMallocInt = 1 diff --git a/go/src/internal/goexperiment/exp_staticlockranking_off.go b/go/src/internal/goexperiment/exp_staticlockranking_off.go new file mode 100644 index 0000000000000000000000000000000000000000..5fafff2591c6442ecc26f66d62a716ebaa844634 --- /dev/null +++ b/go/src/internal/goexperiment/exp_staticlockranking_off.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build !goexperiment.staticlockranking + +package goexperiment + +const StaticLockRanking = false +const StaticLockRankingInt = 0 diff --git a/go/src/internal/goexperiment/exp_staticlockranking_on.go b/go/src/internal/goexperiment/exp_staticlockranking_on.go new file mode 100644 index 0000000000000000000000000000000000000000..dfd32a8ad9cb64a741f8215d91cfd13b78961d65 --- /dev/null +++ b/go/src/internal/goexperiment/exp_staticlockranking_on.go @@ -0,0 +1,8 @@ +// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build goexperiment.staticlockranking + +package goexperiment + +const StaticLockRanking = true +const StaticLockRankingInt = 1 diff --git a/go/src/internal/goexperiment/flags.go b/go/src/internal/goexperiment/flags.go new file mode 100644 index 0000000000000000000000000000000000000000..2cfb71578b421b5328289cae2078f9e7a2547427 --- /dev/null +++ b/go/src/internal/goexperiment/flags.go @@ -0,0 +1,131 @@ +// 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 goexperiment implements support for toolchain experiments. +// +// Toolchain experiments are controlled by the GOEXPERIMENT +// environment variable. GOEXPERIMENT is a comma-separated list of +// experiment names. GOEXPERIMENT can be set at make.bash time, which +// sets the default experiments for binaries built with the tool +// chain; or it can be set at build time. GOEXPERIMENT can also be set +// to "none", which disables any experiments that were enabled at +// make.bash time. +// +// Experiments are exposed to the build in the following ways: +// +// - Build tag goexperiment.x is set if experiment x (lower case) is +// enabled. +// +// - For each experiment x (in camel case), this package contains a +// boolean constant x and an integer constant xInt. +// +// - In runtime assembly, the macro GOEXPERIMENT_x is defined if +// experiment x (lower case) is enabled. +// +// In the toolchain, the set of experiments enabled for the current +// build should be accessed via objabi.Experiment. +// +// The set of experiments is included in the output of [runtime.Version]() +// and "go version " if it differs from the default experiments. +// +// For the set of experiments supported by the current toolchain, see +// "go doc goexperiment.Flags". +// +// Note that this package defines the set of experiments (in [Flags]) +// and records the experiments that were enabled when the package +// was compiled (as boolean and integer constants). +// +// Note especially that this package does not itself change behavior +// at run time based on the GOEXPERIMENT variable. +// The code used in builds to interpret the GOEXPERIMENT variable +// is in the separate package [internal/buildcfg]. +package goexperiment + +//go:generate go run mkconsts.go + +// Flags is the set of experiments that can be enabled or disabled in +// the current toolchain. +// +// When specified in the GOEXPERIMENT environment variable or as build +// tags, experiments use the strings.ToLower of their field name. +// +// For the baseline experimental configuration, see +// [internal/buildcfg.Experiment]. +// +// If you change this struct definition, run "go generate". +type Flags struct { + FieldTrack bool + PreemptibleLoops bool + StaticLockRanking bool + BoringCrypto bool + + // Regabi is split into several sub-experiments that can be + // enabled individually. Not all combinations work. + // The "regabi" GOEXPERIMENT is an alias for all "working" + // subexperiments. + + // RegabiWrappers enables ABI wrappers for calling between + // ABI0 and ABIInternal functions. Without this, the ABIs are + // assumed to be identical so cross-ABI calls are direct. + RegabiWrappers bool + // RegabiArgs enables register arguments/results in all + // compiled Go functions. + // + // Requires wrappers (to do ABI translation), and reflect (so + // reflection calls use registers). + RegabiArgs bool + + // HeapMinimum512KiB reduces the minimum heap size to 512 KiB. + // + // This was originally reduced as part of PacerRedesign, but + // has been broken out to its own experiment that is disabled + // by default. + HeapMinimum512KiB bool + + // Arenas causes the "arena" standard library package to be visible + // to the outside world. + Arenas bool + + // CgoCheck2 enables an expensive cgo rule checker. + // When this experiment is enabled, cgo rule checks occur regardless + // of the GODEBUG=cgocheck setting provided at runtime. + CgoCheck2 bool + + // LoopVar changes loop semantics so that each iteration gets its own + // copy of the iteration variable. + LoopVar bool + + // NewInliner enables a new+improved version of the function + // inlining phase within the Go compiler. + NewInliner bool + + // Dwarf5 enables DWARF version 5 debug info generation. + Dwarf5 bool + + // JSONv2 enables the json/v2 package. + JSONv2 bool + + // GreenTeaGC enables the Green Tea GC implementation. + GreenTeaGC bool + + // RandomizedHeapBase enables heap base address randomization on 64-bit + // platforms. + RandomizedHeapBase64 bool + + // RuntimeFreegc enables the runtime to free and reuse memory more eagerly in some circumstances with compiler help. + RuntimeFreegc bool + + // SizeSpecializedMalloc enables malloc implementations that are specialized per size class. + SizeSpecializedMalloc bool + + // GoroutineLeakProfile enables the collection of goroutine leak profiles. + GoroutineLeakProfile bool + + // SIMD enables the simd package and the compiler's handling + // of SIMD intrinsics. + SIMD bool + + // RuntimeSecret enables the runtime/secret package. + RuntimeSecret bool +} diff --git a/go/src/internal/goexperiment/mkconsts.go b/go/src/internal/goexperiment/mkconsts.go new file mode 100644 index 0000000000000000000000000000000000000000..65c100fa3a6563a8552121370989071a4f47dd56 --- /dev/null +++ b/go/src/internal/goexperiment/mkconsts.go @@ -0,0 +1,72 @@ +// 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 ignore + +// mkconsts generates const definition files for each GOEXPERIMENT. +package main + +import ( + "bytes" + "fmt" + "internal/goexperiment" + "log" + "os" + "reflect" + "strings" +) + +func main() { + // Delete existing experiment constant files. + ents, err := os.ReadDir(".") + if err != nil { + log.Fatal(err) + } + for _, ent := range ents { + name := ent.Name() + if !strings.HasPrefix(name, "exp_") { + continue + } + // Check that this is definitely a generated file. + data, err := os.ReadFile(name) + if err != nil { + log.Fatalf("reading %s: %v", name, err) + } + if !bytes.Contains(data, []byte("Code generated by mkconsts")) { + log.Fatalf("%s: expected generated file", name) + } + if err := os.Remove(name); err != nil { + log.Fatal(err) + } + } + + // Generate new experiment constant files. + rt := reflect.TypeOf(&goexperiment.Flags{}).Elem() + for i := 0; i < rt.NumField(); i++ { + f := rt.Field(i).Name + buildTag := "goexperiment." + strings.ToLower(f) + for _, val := range []bool{false, true} { + name := fmt.Sprintf("exp_%s_%s.go", strings.ToLower(f), pick(val, "off", "on")) + data := fmt.Sprintf(`// Code generated by mkconsts.go. DO NOT EDIT. + +//go:build %s%s + +package goexperiment + +const %s = %v +const %sInt = %s +`, pick(val, "!", ""), buildTag, f, val, f, pick(val, "0", "1")) + if err := os.WriteFile(name, []byte(data), 0666); err != nil { + log.Fatalf("writing %s: %v", name, err) + } + } + } +} + +func pick(v bool, f, t string) string { + if v { + return t + } + return f +} diff --git a/go/src/internal/goos/gengoos.go b/go/src/internal/goos/gengoos.go new file mode 100644 index 0000000000000000000000000000000000000000..e0d4d38e898e890c7b0c20a41d5562b0301f9f21 --- /dev/null +++ b/go/src/internal/goos/gengoos.go @@ -0,0 +1,71 @@ +// 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 ignore + +package main + +import ( + "bytes" + "fmt" + "log" + "os" + "strings" +) + +var gooses []string + +func main() { + data, err := os.ReadFile("../../internal/syslist/syslist.go") + if err != nil { + log.Fatal(err) + } + const goosPrefix = `var KnownOS = map[string]bool{` + inGOOS := false + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, goosPrefix) { + inGOOS = true + } else if inGOOS && strings.HasPrefix(line, "}") { + break + } else if inGOOS { + goos := strings.Fields(line)[0] + goos = strings.TrimPrefix(goos, `"`) + goos = strings.TrimSuffix(goos, `":`) + gooses = append(gooses, goos) + } + } + + for _, target := range gooses { + if target == "nacl" { + continue + } + var tags []string + if target == "linux" { + tags = append(tags, "!android") // must explicitly exclude android for linux + } + if target == "solaris" { + tags = append(tags, "!illumos") // must explicitly exclude illumos for solaris + } + if target == "darwin" { + tags = append(tags, "!ios") // must explicitly exclude ios for darwin + } + tags = append(tags, target) // must explicitly include target for bootstrapping purposes + var buf bytes.Buffer + fmt.Fprintf(&buf, "// Code generated by gengoos.go using 'go generate'. DO NOT EDIT.\n\n") + fmt.Fprintf(&buf, "//go:build %s\n\n", strings.Join(tags, " && ")) + fmt.Fprintf(&buf, "package goos\n\n") + fmt.Fprintf(&buf, "const GOOS = `%s`\n\n", target) + for _, goos := range gooses { + value := 0 + if goos == target { + value = 1 + } + fmt.Fprintf(&buf, "const Is%s = %d\n", strings.Title(goos), value) + } + err := os.WriteFile("zgoos_"+target+".go", buf.Bytes(), 0666) + if err != nil { + log.Fatal(err) + } + } +} diff --git a/go/src/internal/goos/goos.go b/go/src/internal/goos/goos.go new file mode 100644 index 0000000000000000000000000000000000000000..02dc9688cb21075dc58b7d82899eb1f810c69836 --- /dev/null +++ b/go/src/internal/goos/goos.go @@ -0,0 +1,13 @@ +// 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 goos contains GOOS-specific constants. +package goos + +// The next line makes 'go generate' write the zgoos*.go files with +// per-OS information, including constants named Is$GOOS for every +// known GOOS. The constant is 1 on the current system, 0 otherwise; +// multiplying by them is useful for defining GOOS-specific constants. +// +//go:generate go run gengoos.go diff --git a/go/src/internal/goos/nonunix.go b/go/src/internal/goos/nonunix.go new file mode 100644 index 0000000000000000000000000000000000000000..2ba5c8555a303042783bb5c19e863b1201b3083c --- /dev/null +++ b/go/src/internal/goos/nonunix.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. + +//go:build !unix + +package goos + +const IsUnix = false diff --git a/go/src/internal/goos/unix.go b/go/src/internal/goos/unix.go new file mode 100644 index 0000000000000000000000000000000000000000..6cfd5ef67527b2099974ad9337802e0ca9776244 --- /dev/null +++ b/go/src/internal/goos/unix.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. + +//go:build unix + +package goos + +const IsUnix = true diff --git a/go/src/internal/goos/zgoos_aix.go b/go/src/internal/goos/zgoos_aix.go new file mode 100644 index 0000000000000000000000000000000000000000..24e05c933e5e752cadea93db410ef012ee137562 --- /dev/null +++ b/go/src/internal/goos/zgoos_aix.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build aix + +package goos + +const GOOS = `aix` + +const IsAix = 1 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_android.go b/go/src/internal/goos/zgoos_android.go new file mode 100644 index 0000000000000000000000000000000000000000..3c4a318590a8bb903588994922bf5f772c774562 --- /dev/null +++ b/go/src/internal/goos/zgoos_android.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build android + +package goos + +const GOOS = `android` + +const IsAix = 0 +const IsAndroid = 1 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_darwin.go b/go/src/internal/goos/zgoos_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..10b14998955126a439dca5a1d223fb6356df22c7 --- /dev/null +++ b/go/src/internal/goos/zgoos_darwin.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build !ios && darwin + +package goos + +const GOOS = `darwin` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 1 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_dragonfly.go b/go/src/internal/goos/zgoos_dragonfly.go new file mode 100644 index 0000000000000000000000000000000000000000..b92d1269f1f2864a80f41620d237711e54fc325f --- /dev/null +++ b/go/src/internal/goos/zgoos_dragonfly.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build dragonfly + +package goos + +const GOOS = `dragonfly` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 1 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_freebsd.go b/go/src/internal/goos/zgoos_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..f547591ab1e521268fce6897cfd80f8f8a8ff3cd --- /dev/null +++ b/go/src/internal/goos/zgoos_freebsd.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build freebsd + +package goos + +const GOOS = `freebsd` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 1 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_hurd.go b/go/src/internal/goos/zgoos_hurd.go new file mode 100644 index 0000000000000000000000000000000000000000..1189d65d74599e7eb03d3b10196d72e53693905b --- /dev/null +++ b/go/src/internal/goos/zgoos_hurd.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build hurd + +package goos + +const GOOS = `hurd` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 1 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_illumos.go b/go/src/internal/goos/zgoos_illumos.go new file mode 100644 index 0000000000000000000000000000000000000000..4f0254081c31f1ccd572d99b760813b86c4b51e6 --- /dev/null +++ b/go/src/internal/goos/zgoos_illumos.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build illumos + +package goos + +const GOOS = `illumos` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 1 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_ios.go b/go/src/internal/goos/zgoos_ios.go new file mode 100644 index 0000000000000000000000000000000000000000..02f3586fa4017755f8e74cbe1a7be5182e9c22d8 --- /dev/null +++ b/go/src/internal/goos/zgoos_ios.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build ios + +package goos + +const GOOS = `ios` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 1 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_js.go b/go/src/internal/goos/zgoos_js.go new file mode 100644 index 0000000000000000000000000000000000000000..481874189199116e973c1ae562648ff6ef060c8a --- /dev/null +++ b/go/src/internal/goos/zgoos_js.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build js + +package goos + +const GOOS = `js` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 1 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_linux.go b/go/src/internal/goos/zgoos_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..6f4d4e07530a92a6d9ef8eeb62e65cb5ed145e14 --- /dev/null +++ b/go/src/internal/goos/zgoos_linux.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build !android && linux + +package goos + +const GOOS = `linux` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 1 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_netbsd.go b/go/src/internal/goos/zgoos_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..948603df0df73bcc7c6243e0e30495cc59418bd3 --- /dev/null +++ b/go/src/internal/goos/zgoos_netbsd.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build netbsd + +package goos + +const GOOS = `netbsd` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 1 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_openbsd.go b/go/src/internal/goos/zgoos_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..f4b201457b59a41315657a98bb6409057836b941 --- /dev/null +++ b/go/src/internal/goos/zgoos_openbsd.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build openbsd + +package goos + +const GOOS = `openbsd` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 1 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_plan9.go b/go/src/internal/goos/zgoos_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..95572dff37067da0cdbd00df59ec34de9f997e57 --- /dev/null +++ b/go/src/internal/goos/zgoos_plan9.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build plan9 + +package goos + +const GOOS = `plan9` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 1 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_solaris.go b/go/src/internal/goos/zgoos_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..c7058260f8e0d166817ed8a7daa20696bfbe3ded --- /dev/null +++ b/go/src/internal/goos/zgoos_solaris.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build !illumos && solaris + +package goos + +const GOOS = `solaris` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 1 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_wasip1.go b/go/src/internal/goos/zgoos_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..ae35eebac6142b817ff4bb80333c3caa7286376a --- /dev/null +++ b/go/src/internal/goos/zgoos_wasip1.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build wasip1 + +package goos + +const GOOS = `wasip1` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 1 +const IsWindows = 0 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_windows.go b/go/src/internal/goos/zgoos_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..f89f4cf82946594325e8b4221a27ce68c2faf806 --- /dev/null +++ b/go/src/internal/goos/zgoos_windows.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build windows + +package goos + +const GOOS = `windows` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 1 +const IsZos = 0 diff --git a/go/src/internal/goos/zgoos_zos.go b/go/src/internal/goos/zgoos_zos.go new file mode 100644 index 0000000000000000000000000000000000000000..29fb0f8babbbd0110366839ce261b98016b4c9e6 --- /dev/null +++ b/go/src/internal/goos/zgoos_zos.go @@ -0,0 +1,26 @@ +// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. + +//go:build zos + +package goos + +const GOOS = `zos` + +const IsAix = 0 +const IsAndroid = 0 +const IsDarwin = 0 +const IsDragonfly = 0 +const IsFreebsd = 0 +const IsHurd = 0 +const IsIllumos = 0 +const IsIos = 0 +const IsJs = 0 +const IsLinux = 0 +const IsNacl = 0 +const IsNetbsd = 0 +const IsOpenbsd = 0 +const IsPlan9 = 0 +const IsSolaris = 0 +const IsWasip1 = 0 +const IsWindows = 0 +const IsZos = 1 diff --git a/go/src/internal/goroot/gc.go b/go/src/internal/goroot/gc.go new file mode 100644 index 0000000000000000000000000000000000000000..534ad57e709fa645174c06f53dd63c8876e4dd49 --- /dev/null +++ b/go/src/internal/goroot/gc.go @@ -0,0 +1,139 @@ +// 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 gc + +package goroot + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "sync" +) + +// IsStandardPackage reports whether path is a standard package, +// given goroot and compiler. +func IsStandardPackage(goroot, compiler, path string) bool { + switch compiler { + case "gc": + dir := filepath.Join(goroot, "src", path) + dirents, err := os.ReadDir(dir) + if err != nil { + return false + } + for _, dirent := range dirents { + if strings.HasSuffix(dirent.Name(), ".go") { + return true + } + } + return false + case "gccgo": + return gccgoSearch.isStandard(path) + default: + panic("unknown compiler " + compiler) + } +} + +// gccgoDirs holds the gccgo search directories. +type gccgoDirs struct { + once sync.Once + dirs []string +} + +// gccgoSearch is used to check whether a gccgo package exists in the +// standard library. +var gccgoSearch gccgoDirs + +// init finds the gccgo search directories. If this fails it leaves dirs == nil. +func (gd *gccgoDirs) init() { + gccgo := os.Getenv("GCCGO") + if gccgo == "" { + gccgo = "gccgo" + } + bin, err := exec.LookPath(gccgo) + if err != nil { + return + } + + allDirs, err := exec.Command(bin, "-print-search-dirs").Output() + if err != nil { + return + } + versionB, err := exec.Command(bin, "-dumpversion").Output() + if err != nil { + return + } + version := strings.TrimSpace(string(versionB)) + machineB, err := exec.Command(bin, "-dumpmachine").Output() + if err != nil { + return + } + machine := strings.TrimSpace(string(machineB)) + + dirsEntries := strings.Split(string(allDirs), "\n") + const prefix = "libraries: =" + var dirs []string + for _, dirEntry := range dirsEntries { + if after, ok := strings.CutPrefix(dirEntry, prefix); ok { + dirs = filepath.SplitList(after) + break + } + } + if len(dirs) == 0 { + return + } + + var lastDirs []string + for _, dir := range dirs { + goDir := filepath.Join(dir, "go", version) + if fi, err := os.Stat(goDir); err == nil && fi.IsDir() { + gd.dirs = append(gd.dirs, goDir) + goDir = filepath.Join(goDir, machine) + if fi, err = os.Stat(goDir); err == nil && fi.IsDir() { + gd.dirs = append(gd.dirs, goDir) + } + } + if fi, err := os.Stat(dir); err == nil && fi.IsDir() { + lastDirs = append(lastDirs, dir) + } + } + gd.dirs = append(gd.dirs, lastDirs...) +} + +// isStandard reports whether path is a standard library for gccgo. +func (gd *gccgoDirs) isStandard(path string) bool { + // Quick check: if the first path component has a '.', it's not + // in the standard library. This skips most GOPATH directories. + i := strings.Index(path, "/") + if i < 0 { + i = len(path) + } + if strings.Contains(path[:i], ".") { + return false + } + + if path == "unsafe" { + // Special case. + return true + } + + gd.once.Do(gd.init) + if gd.dirs == nil { + // We couldn't find the gccgo search directories. + // Best guess, since the first component did not contain + // '.', is that this is a standard library package. + return true + } + + for _, dir := range gd.dirs { + full := filepath.Join(dir, path) + ".gox" + if fi, err := os.Stat(full); err == nil && !fi.IsDir() { + return true + } + } + + return false +} diff --git a/go/src/internal/goroot/gccgo.go b/go/src/internal/goroot/gccgo.go new file mode 100644 index 0000000000000000000000000000000000000000..2bbf4cda2b3ec97e5b6d6ef275748e04ebf693f0 --- /dev/null +++ b/go/src/internal/goroot/gccgo.go @@ -0,0 +1,36 @@ +// 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 gccgo + +package goroot + +import ( + "os" + "path/filepath" + "strings" +) + +// IsStandardPackage reports whether path is a standard package, +// given goroot and compiler. +func IsStandardPackage(goroot, compiler, path string) bool { + switch compiler { + case "gc": + dir := filepath.Join(goroot, "src", path) + dirents, err := os.ReadDir(dir) + if err != nil { + return false + } + for _, dirent := range dirents { + if strings.HasSuffix(dirent.Name(), ".go") { + return true + } + } + return false + case "gccgo": + return stdpkg[path] + default: + panic("unknown compiler " + compiler) + } +} diff --git a/go/src/internal/gover/gover.go b/go/src/internal/gover/gover.go new file mode 100644 index 0000000000000000000000000000000000000000..2ad068464dd28d637d64fb45b64e86847690cd78 --- /dev/null +++ b/go/src/internal/gover/gover.go @@ -0,0 +1,223 @@ +// 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 gover implements support for Go toolchain versions like 1.21.0 and 1.21rc1. +// (For historical reasons, Go does not use semver for its toolchains.) +// This package provides the same basic analysis that golang.org/x/mod/semver does for semver. +// +// The go/version package should be imported instead of this one when possible. +// Note that this package works on "1.21" while go/version works on "go1.21". +package gover + +import ( + "cmp" +) + +// A Version is a parsed Go version: major[.Minor[.Patch]][kind[pre]] +// The numbers are the original decimal strings to avoid integer overflows +// and since there is very little actual math. (Probably overflow doesn't matter in practice, +// but at the time this code was written, there was an existing test that used +// go1.99999999999, which does not fit in an int on 32-bit platforms. +// The "big decimal" representation avoids the problem entirely.) +type Version struct { + Major string // decimal + Minor string // decimal or "" + Patch string // decimal or "" + Kind string // "", "alpha", "beta", "rc" + Pre string // decimal or "" +} + +// Compare returns -1, 0, or +1 depending on whether +// x < y, x == y, or x > y, interpreted as toolchain versions. +// The versions x and y must not begin with a "go" prefix: just "1.21" not "go1.21". +// Malformed versions compare less than well-formed versions and equal to each other. +// The language version "1.21" compares less than the release candidate and eventual releases "1.21rc1" and "1.21.0". +func Compare(x, y string) int { + vx := Parse(x) + vy := Parse(y) + + if c := CmpInt(vx.Major, vy.Major); c != 0 { + return c + } + if c := CmpInt(vx.Minor, vy.Minor); c != 0 { + return c + } + if c := CmpInt(vx.Patch, vy.Patch); c != 0 { + return c + } + if c := cmp.Compare(vx.Kind, vy.Kind); c != 0 { // "" < alpha < beta < rc + return c + } + if c := CmpInt(vx.Pre, vy.Pre); c != 0 { + return c + } + return 0 +} + +// Max returns the maximum of x and y interpreted as toolchain versions, +// compared using Compare. +// If x and y compare equal, Max returns x. +func Max(x, y string) string { + if Compare(x, y) < 0 { + return y + } + return x +} + +// IsLang reports whether v denotes the overall Go language version +// and not a specific release. Starting with the Go 1.21 release, "1.x" denotes +// the overall language version; the first release is "1.x.0". +// The distinction is important because the relative ordering is +// +// 1.21 < 1.21rc1 < 1.21.0 +// +// meaning that Go 1.21rc1 and Go 1.21.0 will both handle go.mod files that +// say "go 1.21", but Go 1.21rc1 will not handle files that say "go 1.21.0". +func IsLang(x string) bool { + v := Parse(x) + return v != Version{} && v.Patch == "" && v.Kind == "" && v.Pre == "" +} + +// Lang returns the Go language version. For example, Lang("1.2.3") == "1.2". +func Lang(x string) string { + v := Parse(x) + if v.Minor == "" || v.Major == "1" && v.Minor == "0" { + return v.Major + } + return v.Major + "." + v.Minor +} + +// IsValid reports whether the version x is valid. +func IsValid(x string) bool { + return Parse(x) != Version{} +} + +// Parse parses the Go version string x into a version. +// It returns the zero version if x is malformed. +func Parse(x string) Version { + var v Version + + // Parse major version. + var ok bool + v.Major, x, ok = cutInt(x) + if !ok { + return Version{} + } + if x == "" { + // Interpret "1" as "1.0.0". + v.Minor = "0" + v.Patch = "0" + return v + } + + // Parse . before minor version. + if x[0] != '.' { + return Version{} + } + + // Parse minor version. + v.Minor, x, ok = cutInt(x[1:]) + if !ok { + return Version{} + } + if x == "" { + // Patch missing is same as "0" for older versions. + // Starting in Go 1.21, patch missing is different from explicit .0. + if CmpInt(v.Minor, "21") < 0 { + v.Patch = "0" + } + return v + } + + // Parse patch if present. + if x[0] == '.' { + v.Patch, x, ok = cutInt(x[1:]) + if !ok || x != "" { + // Note that we are disallowing prereleases (alpha, beta, rc) for patch releases here (x != ""). + // Allowing them would be a bit confusing because we already have: + // 1.21 < 1.21rc1 + // But a prerelease of a patch would have the opposite effect: + // 1.21.3rc1 < 1.21.3 + // We've never needed them before, so let's not start now. + return Version{} + } + return v + } + + // Parse prerelease. + i := 0 + for i < len(x) && (x[i] < '0' || '9' < x[i]) { + if x[i] < 'a' || 'z' < x[i] { + return Version{} + } + i++ + } + if i == 0 { + return Version{} + } + v.Kind, x = x[:i], x[i:] + if x == "" { + return v + } + v.Pre, x, ok = cutInt(x) + if !ok || x != "" { + return Version{} + } + + return v +} + +// cutInt scans the leading decimal number at the start of x to an integer +// and returns that value and the rest of the string. +func cutInt(x string) (n, rest string, ok bool) { + i := 0 + for i < len(x) && '0' <= x[i] && x[i] <= '9' { + i++ + } + if i == 0 || x[0] == '0' && i != 1 { // no digits or unnecessary leading zero + return "", "", false + } + return x[:i], x[i:], true +} + +// CmpInt returns cmp.Compare(x, y) interpreting x and y as decimal numbers. +// (Copied from golang.org/x/mod/semver's compareInt.) +func CmpInt(x, y string) int { + if x == y { + return 0 + } + if len(x) < len(y) { + return -1 + } + if len(x) > len(y) { + return +1 + } + if x < y { + return -1 + } else { + return +1 + } +} + +// DecInt returns the decimal string decremented by 1, or the empty string +// if the decimal is all zeroes. +// (Copied from golang.org/x/mod/module's decDecimal.) +func DecInt(decimal string) string { + // Scan right to left turning 0s to 9s until you find a digit to decrement. + digits := []byte(decimal) + i := len(digits) - 1 + for ; i >= 0 && digits[i] == '0'; i-- { + digits[i] = '9' + } + if i < 0 { + // decimal is all zeros + return "" + } + if i == 0 && digits[i] == '1' && len(digits) > 1 { + digits = digits[1:] + } else { + digits[i]-- + } + return string(digits) +} diff --git a/go/src/internal/gover/gover_test.go b/go/src/internal/gover/gover_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0edfb1f47df055357b66232502d6201d273ce4a8 --- /dev/null +++ b/go/src/internal/gover/gover_test.go @@ -0,0 +1,138 @@ +// 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 gover + +import ( + "reflect" + "testing" +) + +func TestCompare(t *testing.T) { test2(t, compareTests, "Compare", Compare) } + +var compareTests = []testCase2[string, string, int]{ + {"", "", 0}, + {"x", "x", 0}, + {"", "x", 0}, + {"1", "1.1", -1}, + {"1.5", "1.6", -1}, + {"1.5", "1.10", -1}, + {"1.6", "1.6.1", -1}, + {"1.19", "1.19.0", 0}, + {"1.19rc1", "1.19", -1}, + {"1.20", "1.20.0", 0}, + {"1.20rc1", "1.20", -1}, + {"1.21", "1.21.0", -1}, + {"1.21", "1.21rc1", -1}, + {"1.21rc1", "1.21.0", -1}, + {"1.6", "1.19", -1}, + {"1.19", "1.19.1", -1}, + {"1.19rc1", "1.19", -1}, + {"1.19rc1", "1.19.1", -1}, + {"1.19rc1", "1.19rc2", -1}, + {"1.19.0", "1.19.1", -1}, + {"1.19rc1", "1.19.0", -1}, + {"1.19alpha3", "1.19beta2", -1}, + {"1.19beta2", "1.19rc1", -1}, + {"1.1", "1.99999999999999998", -1}, + {"1.99999999999999998", "1.99999999999999999", -1}, +} + +func TestParse(t *testing.T) { test1(t, parseTests, "Parse", Parse) } + +var parseTests = []testCase1[string, Version]{ + {"1", Version{"1", "0", "0", "", ""}}, + {"1.2", Version{"1", "2", "0", "", ""}}, + {"1.2.3", Version{"1", "2", "3", "", ""}}, + {"1.2rc3", Version{"1", "2", "", "rc", "3"}}, + {"1.20", Version{"1", "20", "0", "", ""}}, + {"1.21", Version{"1", "21", "", "", ""}}, + {"1.21rc3", Version{"1", "21", "", "rc", "3"}}, + {"1.21.0", Version{"1", "21", "0", "", ""}}, + {"1.24", Version{"1", "24", "", "", ""}}, + {"1.24rc3", Version{"1", "24", "", "rc", "3"}}, + {"1.24.0", Version{"1", "24", "0", "", ""}}, + {"1.999testmod", Version{"1", "999", "", "testmod", ""}}, + {"1.99999999999999999", Version{"1", "99999999999999999", "", "", ""}}, +} + +func TestLang(t *testing.T) { test1(t, langTests, "Lang", Lang) } + +var langTests = []testCase1[string, string]{ + {"1.2rc3", "1.2"}, + {"1.2.3", "1.2"}, + {"1.2", "1.2"}, + {"1", "1"}, + {"1.999testmod", "1.999"}, +} + +func TestIsLang(t *testing.T) { test1(t, isLangTests, "IsLang", IsLang) } + +var isLangTests = []testCase1[string, bool]{ + {"1.2rc3", false}, + {"1.2.3", false}, + {"1.999testmod", false}, + {"1.22", true}, + {"1.21", true}, + {"1.20", false}, // == 1.20.0 + {"1.19", false}, // == 1.20.0 + {"1.3", false}, // == 1.3.0 + {"1.2", false}, // == 1.2.0 + {"1", false}, // == 1.0.0 +} + +func TestIsValid(t *testing.T) { test1(t, isValidTests, "IsValid", IsValid) } + +var isValidTests = []testCase1[string, bool]{ + {"1.2rc3", true}, + {"1.2.3", true}, + {"1.999testmod", true}, + {"1.600+auto", false}, + {"1.22", true}, + {"1.21.0", true}, + {"1.21rc2", true}, + {"1.21", true}, + {"1.20.0", true}, + {"1.20", true}, + {"1.19", true}, + {"1.3", true}, + {"1.2", true}, + {"1", true}, +} + +type testCase1[In, Out any] struct { + in In + out Out +} + +type testCase2[In1, In2, Out any] struct { + in1 In1 + in2 In2 + out Out +} + +type testCase3[In1, In2, In3, Out any] struct { + in1 In1 + in2 In2 + in3 In3 + out Out +} + +func test1[In, Out any](t *testing.T, tests []testCase1[In, Out], name string, f func(In) Out) { + t.Helper() + for _, tt := range tests { + if out := f(tt.in); !reflect.DeepEqual(out, tt.out) { + t.Errorf("%s(%v) = %v, want %v", name, tt.in, out, tt.out) + } + } +} + +func test2[In1, In2, Out any](t *testing.T, tests []testCase2[In1, In2, Out], name string, f func(In1, In2) Out) { + t.Helper() + for _, tt := range tests { + if out := f(tt.in1, tt.in2); !reflect.DeepEqual(out, tt.out) { + t.Errorf("%s(%+v, %+v) = %+v, want %+v", name, tt.in1, tt.in2, out, tt.out) + } + } +} diff --git a/go/src/internal/goversion/goversion.go b/go/src/internal/goversion/goversion.go new file mode 100644 index 0000000000000000000000000000000000000000..d8bfe7e085b62e374fe415add9317840fbf837e9 --- /dev/null +++ b/go/src/internal/goversion/goversion.go @@ -0,0 +1,12 @@ +// 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 goversion + +// Version is the Go 1.x version which is currently +// in development and will eventually get released. +// +// It should be updated at the start of each development cycle to be +// the version of the next Go 1.x release. See go.dev/issue/40705. +const Version = 26 diff --git a/go/src/internal/lazyregexp/lazyre.go b/go/src/internal/lazyregexp/lazyre.go new file mode 100644 index 0000000000000000000000000000000000000000..2681af35af1954b1384eecc12bcea655462a8776 --- /dev/null +++ b/go/src/internal/lazyregexp/lazyre.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 lazyregexp is a thin wrapper over regexp, allowing the use of global +// regexp variables without forcing them to be compiled at init. +package lazyregexp + +import ( + "os" + "regexp" + "strings" + "sync" +) + +// Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be +// compiled the first time it is needed. +type Regexp struct { + str string + once sync.Once + rx *regexp.Regexp +} + +func (r *Regexp) re() *regexp.Regexp { + r.once.Do(r.build) + return r.rx +} + +func (r *Regexp) build() { + r.rx = regexp.MustCompile(r.str) + r.str = "" +} + +func (r *Regexp) FindSubmatch(s []byte) [][]byte { + return r.re().FindSubmatch(s) +} + +func (r *Regexp) FindStringSubmatch(s string) []string { + return r.re().FindStringSubmatch(s) +} + +func (r *Regexp) FindStringSubmatchIndex(s string) []int { + return r.re().FindStringSubmatchIndex(s) +} + +func (r *Regexp) ReplaceAllString(src, repl string) string { + return r.re().ReplaceAllString(src, repl) +} + +func (r *Regexp) FindString(s string) string { + return r.re().FindString(s) +} + +func (r *Regexp) FindAllString(s string, n int) []string { + return r.re().FindAllString(s, n) +} + +func (r *Regexp) MatchString(s string) bool { + return r.re().MatchString(s) +} + +func (r *Regexp) SubexpNames() []string { + return r.re().SubexpNames() +} + +var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") + +// New creates a new lazy regexp, delaying the compiling work until it is first +// needed. If the code is being run as part of tests, the regexp compiling will +// happen immediately. +func New(str string) *Regexp { + lr := &Regexp{str: str} + if inTest { + // In tests, always compile the regexps early. + lr.re() + } + return lr +} diff --git a/go/src/internal/lazytemplate/lazytemplate.go b/go/src/internal/lazytemplate/lazytemplate.go new file mode 100644 index 0000000000000000000000000000000000000000..8eeed5a527ac6a8aeb2fb318835630d34fd6db37 --- /dev/null +++ b/go/src/internal/lazytemplate/lazytemplate.go @@ -0,0 +1,52 @@ +// 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 lazytemplate is a thin wrapper over text/template, allowing the use +// of global template variables without forcing them to be parsed at init. +package lazytemplate + +import ( + "io" + "os" + "strings" + "sync" + "text/template" +) + +// Template is a wrapper around text/template.Template, where the underlying +// template will be parsed the first time it is needed. +type Template struct { + name, text string + + once sync.Once + tmpl *template.Template +} + +func (r *Template) tp() *template.Template { + r.once.Do(r.build) + return r.tmpl +} + +func (r *Template) build() { + r.tmpl = template.Must(template.New(r.name).Parse(r.text)) + r.name, r.text = "", "" +} + +func (r *Template) Execute(w io.Writer, data any) error { + return r.tp().Execute(w, data) +} + +var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") + +// New creates a new lazy template, delaying the parsing work until it is first +// needed. If the code is being run as part of tests, the template parsing will +// happen immediately. +func New(name, text string) *Template { + lt := &Template{name: name, text: text} + if inTest { + // In tests, always parse the templates early. + lt.tp() + } + return lt +} diff --git a/go/src/internal/msan/doc.go b/go/src/internal/msan/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..e68d341e7ad2d735f129c56418008ac842a6348c --- /dev/null +++ b/go/src/internal/msan/doc.go @@ -0,0 +1,9 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package msan contains helper functions for manually instrumenting code +// for the memory sanitizer. +// This package exports the private msan routines in runtime unconditionally +// but without the "msan" build tag they are no-ops. +package msan diff --git a/go/src/internal/msan/msan.go b/go/src/internal/msan/msan.go new file mode 100644 index 0000000000000000000000000000000000000000..518153ee5a9150e562ba5dff9632bb4c73ea3321 --- /dev/null +++ b/go/src/internal/msan/msan.go @@ -0,0 +1,28 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build msan + +package msan + +import ( + "unsafe" +) + +const Enabled = true + +//go:linkname Read runtime.msanread +func Read(addr unsafe.Pointer, sz uintptr) + +//go:linkname Write runtime.msanwrite +func Write(addr unsafe.Pointer, sz uintptr) + +//go:linkname Malloc runtime.msanmalloc +func Malloc(addr unsafe.Pointer, sz uintptr) + +//go:linkname Free runtime.msanfree +func Free(addr unsafe.Pointer, sz uintptr) + +//go:linkname Move runtime.msanmove +func Move(dst, src unsafe.Pointer, sz uintptr) diff --git a/go/src/internal/msan/nomsan.go b/go/src/internal/msan/nomsan.go new file mode 100644 index 0000000000000000000000000000000000000000..3dccda3ffd4a02e8b1f336c0d39f28ac35aba6f7 --- /dev/null +++ b/go/src/internal/msan/nomsan.go @@ -0,0 +1,28 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !msan + +package msan + +import ( + "unsafe" +) + +const Enabled = false + +func Read(addr unsafe.Pointer, sz uintptr) { +} + +func Write(addr unsafe.Pointer, sz uintptr) { +} + +func Malloc(addr unsafe.Pointer, sz uintptr) { +} + +func Free(addr unsafe.Pointer, sz uintptr) { +} + +func Move(dst, src unsafe.Pointer, sz uintptr) { +} diff --git a/go/src/internal/nettrace/nettrace.go b/go/src/internal/nettrace/nettrace.go new file mode 100644 index 0000000000000000000000000000000000000000..7d46268a1c59b7b3b6bc6fec738c5b294bf89015 --- /dev/null +++ b/go/src/internal/nettrace/nettrace.go @@ -0,0 +1,46 @@ +// 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 nettrace contains internal hooks for tracing activity in +// the net package. This package is purely internal for use by the +// net/http/httptrace package and has no stable API exposed to end +// users. +package nettrace + +// TraceKey is a context.Context Value key. Its associated value should +// be a *Trace struct. +type TraceKey struct{} + +// LookupIPAltResolverKey is a context.Context Value key used by tests to +// specify an alternate resolver func. +// It is not exposed to outsider users. (But see issue 12503) +// The value should be the same type as lookupIP: +// +// func lookupIP(ctx context.Context, host string) ([]IPAddr, error) +type LookupIPAltResolverKey struct{} + +// Trace contains a set of hooks for tracing events within +// the net package. Any specific hook may be nil. +type Trace struct { + // DNSStart is called with the hostname of a DNS lookup + // before it begins. + DNSStart func(name string) + + // DNSDone is called after a DNS lookup completes (or fails). + // The coalesced parameter is whether singleflight de-duped + // the call. The addrs are of type net.IPAddr but can't + // actually be for circular dependency reasons. + DNSDone func(netIPs []any, coalesced bool, err error) + + // ConnectStart is called before a Dial, excluding Dials made + // during DNS lookups. In the case of DualStack (Happy Eyeballs) + // dialing, this may be called multiple times, from multiple + // goroutines. + ConnectStart func(network, addr string) + + // ConnectDone is called after a Dial with the results, excluding + // Dials made during DNS lookups. It may also be called multiple + // times, like ConnectStart. + ConnectDone func(network, addr string, err error) +} diff --git a/go/src/internal/obscuretestdata/obscuretestdata.go b/go/src/internal/obscuretestdata/obscuretestdata.go new file mode 100644 index 0000000000000000000000000000000000000000..d54d3f68c2a277e626cc9960333288e16fc7b1db --- /dev/null +++ b/go/src/internal/obscuretestdata/obscuretestdata.go @@ -0,0 +1,65 @@ +// 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 obscuretestdata contains functionality used by tests to more easily +// work with testdata that must be obscured primarily due to +// golang.org/issue/34986. +package obscuretestdata + +import ( + "encoding/base64" + "io" + "os" +) + +// Rot13 returns the rot13 encoding or decoding of its input. +func Rot13(data []byte) []byte { + out := make([]byte, len(data)) + copy(out, data) + for i, c := range out { + switch { + case 'A' <= c && c <= 'M' || 'a' <= c && c <= 'm': + out[i] = c + 13 + case 'N' <= c && c <= 'Z' || 'n' <= c && c <= 'z': + out[i] = c - 13 + } + } + return out +} + +// DecodeToTempFile decodes the named file to a temporary location. +// If successful, it returns the path of the decoded file. +// The caller is responsible for ensuring that the temporary file is removed. +func DecodeToTempFile(name string) (path string, err error) { + f, err := os.Open(name) + if err != nil { + return "", err + } + defer f.Close() + + tmp, err := os.CreateTemp("", "obscuretestdata-decoded-") + if err != nil { + return "", err + } + if _, err := io.Copy(tmp, base64.NewDecoder(base64.StdEncoding, f)); err != nil { + tmp.Close() + os.Remove(tmp.Name()) + return "", err + } + if err := tmp.Close(); err != nil { + os.Remove(tmp.Name()) + return "", err + } + return tmp.Name(), nil +} + +// ReadFile reads the named file and returns its decoded contents. +func ReadFile(name string) ([]byte, error) { + f, err := os.Open(name) + if err != nil { + return nil, err + } + defer f.Close() + return io.ReadAll(base64.NewDecoder(base64.StdEncoding, f)) +} diff --git a/go/src/internal/oserror/errors.go b/go/src/internal/oserror/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..28a1ab32d32c5fc03b9dfaf8587f77e9090ab4a0 --- /dev/null +++ b/go/src/internal/oserror/errors.go @@ -0,0 +1,18 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package oserror defines errors values used in the os package. +// +// These types are defined here to permit the syscall package to reference them. +package oserror + +import "errors" + +var ( + ErrInvalid = errors.New("invalid argument") + ErrPermission = errors.New("permission denied") + ErrExist = errors.New("file already exists") + ErrNotExist = errors.New("file does not exist") + ErrClosed = errors.New("file already closed") +) diff --git a/go/src/internal/pkgbits/codes.go b/go/src/internal/pkgbits/codes.go new file mode 100644 index 0000000000000000000000000000000000000000..f0cabde96eba92f937f973f45c36a346cae36ce7 --- /dev/null +++ b/go/src/internal/pkgbits/codes.go @@ -0,0 +1,77 @@ +// 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 pkgbits + +// A Code is an enum value that can be encoded into bitstreams. +// +// Code types are preferable for enum types, because they allow +// Decoder to detect desyncs. +type Code interface { + // Marker returns the SyncMarker for the Code's dynamic type. + Marker() SyncMarker + + // Value returns the Code's ordinal value. + Value() int +} + +// A CodeVal distinguishes among go/constant.Value encodings. +type CodeVal int + +func (c CodeVal) Marker() SyncMarker { return SyncVal } +func (c CodeVal) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + ValBool CodeVal = iota + ValString + ValInt64 + ValBigInt + ValBigRat + ValBigFloat +) + +// A CodeType distinguishes among go/types.Type encodings. +type CodeType int + +func (c CodeType) Marker() SyncMarker { return SyncType } +func (c CodeType) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + TypeBasic CodeType = iota + TypeNamed + TypePointer + TypeSlice + TypeArray + TypeChan + TypeMap + TypeSignature + TypeStruct + TypeInterface + TypeUnion + TypeTypeParam +) + +// A CodeObj distinguishes among go/types.Object encodings. +type CodeObj int + +func (c CodeObj) Marker() SyncMarker { return SyncCodeObj } +func (c CodeObj) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + ObjAlias CodeObj = iota + ObjConst + ObjType + ObjFunc + ObjVar + ObjStub +) diff --git a/go/src/internal/pkgbits/decoder.go b/go/src/internal/pkgbits/decoder.go new file mode 100644 index 0000000000000000000000000000000000000000..f9e37b9e1e4f25de6941410f0b05945e25409779 --- /dev/null +++ b/go/src/internal/pkgbits/decoder.go @@ -0,0 +1,519 @@ +// 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 pkgbits + +import ( + "encoding/binary" + "errors" + "fmt" + "go/constant" + "go/token" + "io" + "math/big" + "os" + "runtime" + "strings" +) + +// A PkgDecoder provides methods for decoding a package's Unified IR +// export data. +type PkgDecoder struct { + // version is the file format version. + version Version + + // sync indicates whether the file uses sync markers. + sync bool + + // pkgPath is the package path for the package to be decoded. + // + // TODO(mdempsky): Remove; unneeded since CL 391014. + pkgPath string + + // elemData is the full data payload of the encoded package. + // Elements are densely and contiguously packed together. + // + // The last 8 bytes of elemData are the package fingerprint. + elemData string + + // elemEnds stores the byte-offset end positions of element + // bitstreams within elemData. + // + // For example, element I's bitstream data starts at elemEnds[I-1] + // (or 0, if I==0) and ends at elemEnds[I]. + // + // Note: elemEnds is indexed by absolute indices, not + // section-relative indices. + elemEnds []uint32 + + // elemEndsEnds stores the index-offset end positions of relocation + // sections within elemEnds. + // + // For example, section K's end positions start at elemEndsEnds[K-1] + // (or 0, if K==0) and end at elemEndsEnds[K]. + elemEndsEnds [numRelocs]uint32 + + scratchRelocEnt []RefTableEntry +} + +// PkgPath returns the package path for the package +// +// TODO(mdempsky): Remove; unneeded since CL 391014. +func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath } + +// SyncMarkers reports whether pr uses sync markers. +func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync } + +// NewPkgDecoder returns a PkgDecoder initialized to read the Unified +// IR export data from input. pkgPath is the package path for the +// compilation unit that produced the export data. +func NewPkgDecoder(pkgPath, input string) PkgDecoder { + pr := PkgDecoder{ + pkgPath: pkgPath, + } + + // TODO(mdempsky): Implement direct indexing of input string to + // avoid copying the position information. + + r := strings.NewReader(input) + + var ver uint32 + assert(binary.Read(r, binary.LittleEndian, &ver) == nil) + pr.version = Version(ver) + + if pr.version >= numVersions { + panic(fmt.Errorf("cannot decode %q, export data version %d is greater than maximum supported version %d", pkgPath, pr.version, numVersions-1)) + } + + if pr.version.Has(Flags) { + var flags uint32 + assert(binary.Read(r, binary.LittleEndian, &flags) == nil) + pr.sync = flags&flagSyncMarkers != 0 + } + + assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil) + + pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1]) + assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil) + + pos, err := r.Seek(0, io.SeekCurrent) + assert(err == nil) + + pr.elemData = input[pos:] + + const fingerprintSize = 8 + assert(len(pr.elemData)-fingerprintSize == int(pr.elemEnds[len(pr.elemEnds)-1])) + + return pr +} + +// NumElems returns the number of elements in section k. +func (pr *PkgDecoder) NumElems(k SectionKind) int { + count := int(pr.elemEndsEnds[k]) + if k > 0 { + count -= int(pr.elemEndsEnds[k-1]) + } + return count +} + +// TotalElems returns the total number of elements across all sections. +func (pr *PkgDecoder) TotalElems() int { + return len(pr.elemEnds) +} + +// Fingerprint returns the package fingerprint. +func (pr *PkgDecoder) Fingerprint() [8]byte { + var fp [8]byte + copy(fp[:], pr.elemData[len(pr.elemData)-8:]) + return fp +} + +// AbsIdx returns the absolute index for the given (section, index) +// pair. +func (pr *PkgDecoder) AbsIdx(k SectionKind, idx RelElemIdx) int { + absIdx := int(idx) + if k > 0 { + absIdx += int(pr.elemEndsEnds[k-1]) + } + if absIdx >= int(pr.elemEndsEnds[k]) { + panicf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds) + } + return absIdx +} + +// DataIdx returns the raw element bitstream for the given (section, +// index) pair. +func (pr *PkgDecoder) DataIdx(k SectionKind, idx RelElemIdx) string { + absIdx := pr.AbsIdx(k, idx) + + var start uint32 + if absIdx > 0 { + start = pr.elemEnds[absIdx-1] + } + end := pr.elemEnds[absIdx] + + return pr.elemData[start:end] +} + +// StringIdx returns the string value for the given string index. +func (pr *PkgDecoder) StringIdx(idx RelElemIdx) string { + return pr.DataIdx(SectionString, idx) +} + +// NewDecoder returns a Decoder for the given (section, index) pair, +// and decodes the given SyncMarker from the element bitstream. +func (pr *PkgDecoder) NewDecoder(k SectionKind, idx RelElemIdx, marker SyncMarker) Decoder { + r := pr.NewDecoderRaw(k, idx) + r.Sync(marker) + return r +} + +// TempDecoder returns a Decoder for the given (section, index) pair, +// and decodes the given SyncMarker from the element bitstream. +// If possible the Decoder should be RetireDecoder'd when it is no longer +// needed, this will avoid heap allocations. +func (pr *PkgDecoder) TempDecoder(k SectionKind, idx RelElemIdx, marker SyncMarker) Decoder { + r := pr.TempDecoderRaw(k, idx) + r.Sync(marker) + return r +} + +func (pr *PkgDecoder) RetireDecoder(d *Decoder) { + pr.scratchRelocEnt = d.Relocs + d.Relocs = nil +} + +// NewDecoderRaw returns a Decoder for the given (section, index) pair. +// +// Most callers should use NewDecoder instead. +func (pr *PkgDecoder) NewDecoderRaw(k SectionKind, idx RelElemIdx) Decoder { + r := Decoder{ + common: pr, + k: k, + Idx: idx, + } + + r.Data.Reset(pr.DataIdx(k, idx)) + r.Sync(SyncRelocs) + r.Relocs = make([]RefTableEntry, r.Len()) + for i := range r.Relocs { + r.Sync(SyncReloc) + r.Relocs[i] = RefTableEntry{SectionKind(r.Len()), RelElemIdx(r.Len())} + } + + return r +} + +func (pr *PkgDecoder) TempDecoderRaw(k SectionKind, idx RelElemIdx) Decoder { + r := Decoder{ + common: pr, + k: k, + Idx: idx, + } + + r.Data.Reset(pr.DataIdx(k, idx)) + r.Sync(SyncRelocs) + l := r.Len() + if cap(pr.scratchRelocEnt) >= l { + r.Relocs = pr.scratchRelocEnt[:l] + pr.scratchRelocEnt = nil + } else { + r.Relocs = make([]RefTableEntry, l) + } + for i := range r.Relocs { + r.Sync(SyncReloc) + r.Relocs[i] = RefTableEntry{SectionKind(r.Len()), RelElemIdx(r.Len())} + } + + return r +} + +// A Decoder provides methods for decoding an individual element's +// bitstream data. +type Decoder struct { + common *PkgDecoder + + Relocs []RefTableEntry + Data strings.Reader + + k SectionKind + Idx RelElemIdx +} + +func (r *Decoder) checkErr(err error) { + if err != nil { + panicf("unexpected decoding error: %w", err) + } +} + +func (r *Decoder) rawUvarint() uint64 { + x, err := readUvarint(&r.Data) + r.checkErr(err) + return x +} + +// readUvarint is a type-specialized copy of encoding/binary.ReadUvarint. +// This avoids the interface conversion and thus has better escape properties, +// which flows up the stack. +func readUvarint(r *strings.Reader) (uint64, error) { + var x uint64 + var s uint + for i := 0; i < binary.MaxVarintLen64; i++ { + b, err := r.ReadByte() + if err != nil { + if i > 0 && err == io.EOF { + err = io.ErrUnexpectedEOF + } + return x, err + } + if b < 0x80 { + if i == binary.MaxVarintLen64-1 && b > 1 { + return x, overflow + } + return x | uint64(b)<> 1) + if ux&1 != 0 { + x = ^x + } + return x +} + +func (r *Decoder) rawReloc(k SectionKind, idx int) RelElemIdx { + e := r.Relocs[idx] + assert(e.Kind == k) + return e.Idx +} + +// Sync decodes a sync marker from the element bitstream and asserts +// that it matches the expected marker. +// +// If EnableSync is false, then Sync is a no-op. +func (r *Decoder) Sync(mWant SyncMarker) { + if !r.common.sync { + return + } + + pos, _ := r.Data.Seek(0, io.SeekCurrent) + mHave := SyncMarker(r.rawUvarint()) + writerPCs := make([]int, r.rawUvarint()) + for i := range writerPCs { + writerPCs[i] = int(r.rawUvarint()) + } + + if mHave == mWant { + return + } + + // There's some tension here between printing: + // + // (1) full file paths that tools can recognize (e.g., so emacs + // hyperlinks the "file:line" text for easy navigation), or + // + // (2) short file paths that are easier for humans to read (e.g., by + // omitting redundant or irrelevant details, so it's easier to + // focus on the useful bits that remain). + // + // The current formatting favors the former, as it seems more + // helpful in practice. But perhaps the formatting could be improved + // to better address both concerns. For example, use relative file + // paths if they would be shorter, or rewrite file paths to contain + // "$GOROOT" (like objabi.AbsFile does) if tools can be taught how + // to reliably expand that again. + + fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos) + + fmt.Printf("\nfound %v, written at:\n", mHave) + if len(writerPCs) == 0 { + fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath) + } + for _, pc := range writerPCs { + fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(SectionString, pc))) + } + + fmt.Printf("\nexpected %v, reading at:\n", mWant) + var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size? + n := runtime.Callers(2, readerPCs[:]) + for _, pc := range fmtFrames(readerPCs[:n]...) { + fmt.Printf("\t%s\n", pc) + } + + // We already printed a stack trace for the reader, so now we can + // simply exit. Printing a second one with panic or base.Fatalf + // would just be noise. + os.Exit(1) +} + +// Bool decodes and returns a bool value from the element bitstream. +func (r *Decoder) Bool() bool { + r.Sync(SyncBool) + x, err := r.Data.ReadByte() + r.checkErr(err) + assert(x < 2) + return x != 0 +} + +// Int64 decodes and returns an int64 value from the element bitstream. +func (r *Decoder) Int64() int64 { + r.Sync(SyncInt64) + return r.rawVarint() +} + +// Uint64 decodes and returns a uint64 value from the element bitstream. +func (r *Decoder) Uint64() uint64 { + r.Sync(SyncUint64) + return r.rawUvarint() +} + +// Len decodes and returns a non-negative int value from the element bitstream. +func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v } + +// Int decodes and returns an int value from the element bitstream. +func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v } + +// Uint decodes and returns a uint value from the element bitstream. +func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v } + +// Code decodes a Code value from the element bitstream and returns +// its ordinal value. It's the caller's responsibility to convert the +// result to an appropriate Code type. +// +// TODO(mdempsky): Ideally this method would have signature "Code[T +// Code] T" instead, but we don't allow generic methods and the +// compiler can't depend on generics yet anyway. +func (r *Decoder) Code(mark SyncMarker) int { + r.Sync(mark) + return r.Len() +} + +// Reloc decodes a relocation of expected section k from the element +// bitstream and returns an index to the referenced element. +func (r *Decoder) Reloc(k SectionKind) RelElemIdx { + r.Sync(SyncUseReloc) + return r.rawReloc(k, r.Len()) +} + +// String decodes and returns a string value from the element +// bitstream. +func (r *Decoder) String() string { + r.Sync(SyncString) + return r.common.StringIdx(r.Reloc(SectionString)) +} + +// Strings decodes and returns a variable-length slice of strings from +// the element bitstream. +func (r *Decoder) Strings() []string { + res := make([]string, r.Len()) + for i := range res { + res[i] = r.String() + } + return res +} + +// Value decodes and returns a constant.Value from the element +// bitstream. +func (r *Decoder) Value() constant.Value { + r.Sync(SyncValue) + isComplex := r.Bool() + val := r.scalar() + if isComplex { + val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar())) + } + return val +} + +func (r *Decoder) scalar() constant.Value { + switch tag := CodeVal(r.Code(SyncVal)); tag { + default: + panic(fmt.Errorf("unexpected scalar tag: %v", tag)) + + case ValBool: + return constant.MakeBool(r.Bool()) + case ValString: + return constant.MakeString(r.String()) + case ValInt64: + return constant.MakeInt64(r.Int64()) + case ValBigInt: + return constant.Make(r.bigInt()) + case ValBigRat: + num := r.bigInt() + denom := r.bigInt() + return constant.Make(new(big.Rat).SetFrac(num, denom)) + case ValBigFloat: + return constant.Make(r.bigFloat()) + } +} + +func (r *Decoder) bigInt() *big.Int { + v := new(big.Int).SetBytes([]byte(r.String())) + if r.Bool() { + v.Neg(v) + } + return v +} + +func (r *Decoder) bigFloat() *big.Float { + v := new(big.Float).SetPrec(512) + assert(v.UnmarshalText([]byte(r.String())) == nil) + return v +} + +// @@@ Helpers + +// TODO(mdempsky): These should probably be removed. I think they're a +// smell that the export data format is not yet quite right. + +// PeekPkgPath returns the package path for the specified package +// index. +func (pr *PkgDecoder) PeekPkgPath(idx RelElemIdx) string { + var path string + { + r := pr.TempDecoder(SectionPkg, idx, SyncPkgDef) + path = r.String() + pr.RetireDecoder(&r) + } + if path == "" { + path = pr.pkgPath + } + return path +} + +// PeekObj returns the package path, object name, and CodeObj for the +// specified object index. +func (pr *PkgDecoder) PeekObj(idx RelElemIdx) (string, string, CodeObj) { + var ridx RelElemIdx + var name string + var rcode int + { + r := pr.TempDecoder(SectionName, idx, SyncObject1) + r.Sync(SyncSym) + r.Sync(SyncPkg) + ridx = r.Reloc(SectionPkg) + name = r.String() + rcode = r.Code(SyncCodeObj) + pr.RetireDecoder(&r) + } + + path := pr.PeekPkgPath(ridx) + assert(name != "") + + tag := CodeObj(rcode) + + return path, name, tag +} + +// Version reports the version of the bitstream. +func (w *Decoder) Version() Version { return w.common.version } diff --git a/go/src/internal/pkgbits/doc.go b/go/src/internal/pkgbits/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..5c2a937afadb5a2ac58f7047a89d1660db3128e7 --- /dev/null +++ b/go/src/internal/pkgbits/doc.go @@ -0,0 +1,107 @@ +// 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. + +/* +The Unified IR (UIR) format for primitive types is implicitly defined by the +package pkgbits. + +The most basic primitives are laid out as below. + + Bool = [ Sync ] byte . + Int64 = [ Sync ] zvarint . + Uint64 = [ Sync ] uvarint . + + zvarint = (* a zig-zag encoded signed variable-width integer *) . + uvarint = (* an unsigned variable-width integer *) . + +# References +References specify the location of a value. While the representation here is +fixed, the interpretation of a reference is left to other packages. + + Ref[T] = [ Sync ] Uint64 . // points to a value of type T + +# Markers +Markers provide a mechanism for asserting that encoders and decoders +are synchronized. If an unexpected marker is found, decoding panics. + + Sync = uvarint // indicates what should follow if synchronized + WriterPCs + . + +A marker also records a configurable number of program counters (PCs) during +encoding to assist with debugging. + + WriterPCs = uvarint // the number of PCs that follow + { uvarint } // the PCs + . + +Note that markers are always defined using terminals — they never contain a +marker themselves. + +# Strings +A string is a series of bytes. + + // TODO(markfreeman): Does this need a marker? + String = { byte } . + +Strings are typically not encoded directly. Rather, they are deduplicated +during encoding and referenced where needed; this process is called interning. + + StringRef = [ Sync ] Ref[String] . + +Note that StringRef is *not* equivalent to Ref[String] due to the extra marker. + +# Slices +Slices are a convenience for encoding a series of values of the same type. + + // TODO(markfreeman): Does this need a marker? + Slice[T] = Uint64 // the number of values in the slice + { T } // the values + . + +# Constants +Constants appear as defined via the package constant. + + Constant = [ Sync ] + Bool // whether the constant is a complex number + Scalar // the real part + [ Scalar ] // if complex, the imaginary part + . + +A scalar represents a value using one of several potential formats. The exact +format and interpretation is distinguished by a code preceding the value. + + Scalar = [ Sync ] + Uint64 // the code indicating the type of Val + Val + . + + Val = Bool + | Int64 + | StringRef + | Term // big integer + | Term Term // big ratio, numerator / denominator + | BigBytes // big float, precision 512 + . + + Term = BigBytes + Bool // whether the term is negative + . + + BigBytes = StringRef . // bytes of a big value +*/ + +// Package pkgbits implements low-level coding abstractions for Unified IR's +// (UIR) binary export data format. +// +// At a low-level, the exported objects of a package are encoded as a byte +// array. This array contains byte representations of primitive, potentially +// variable-length values, such as integers, booleans, strings, and constants. +// +// Additionally, the array may contain values which denote indices in the byte +// array itself. These are termed "relocations" and allow for references. +// +// The details of mapping high-level Go constructs to primitives are left to +// other packages. +package pkgbits diff --git a/go/src/internal/pkgbits/encoder.go b/go/src/internal/pkgbits/encoder.go new file mode 100644 index 0000000000000000000000000000000000000000..6e3716570fcd319e9c350a83b9a8db1a974df0d8 --- /dev/null +++ b/go/src/internal/pkgbits/encoder.go @@ -0,0 +1,395 @@ +// 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 pkgbits + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "go/constant" + "io" + "math/big" + "runtime" + "strings" +) + +// A PkgEncoder provides methods for encoding a package's Unified IR +// export data. +type PkgEncoder struct { + // version of the bitstream. + version Version + + // elems holds the bitstream for previously encoded elements. + elems [numRelocs][]string + + // stringsIdx maps previously encoded strings to their index within + // the RelocString section, to allow deduplication. That is, + // elems[RelocString][stringsIdx[s]] == s (if present). + stringsIdx map[string]RelElemIdx + + // syncFrames is the number of frames to write at each sync + // marker. A negative value means sync markers are omitted. + syncFrames int +} + +// SyncMarkers reports whether pw uses sync markers. +func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 } + +// NewPkgEncoder returns an initialized PkgEncoder. +// +// syncFrames is the number of caller frames that should be serialized +// at Sync points. Serializing additional frames results in larger +// export data files, but can help diagnosing desync errors in +// higher-level Unified IR reader/writer code. If syncFrames is +// negative, then sync markers are omitted entirely. +func NewPkgEncoder(version Version, syncFrames int) PkgEncoder { + return PkgEncoder{ + version: version, + stringsIdx: make(map[string]RelElemIdx), + syncFrames: syncFrames, + } +} + +// DumpTo writes the package's encoded data to out0 and returns the +// package fingerprint. +func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) { + h := sha256.New() + out := io.MultiWriter(out0, h) + + writeUint32 := func(x uint32) { + assert(binary.Write(out, binary.LittleEndian, x) == nil) + } + + writeUint32(uint32(pw.version)) + + if pw.version.Has(Flags) { + var flags uint32 + if pw.SyncMarkers() { + flags |= flagSyncMarkers + } + writeUint32(flags) + } + + // TODO(markfreeman): Also can use delta encoding to write section ends, + // but not as impactful. + var sum uint32 + for _, elems := range &pw.elems { + sum += uint32(len(elems)) + writeUint32(sum) + } + + // TODO(markfreeman): Use delta encoding to store element ends and inflate + // back to this representation during decoding; the numbers will be much + // smaller. + sum = 0 + for _, elems := range &pw.elems { + for _, elem := range elems { + sum += uint32(len(elem)) + writeUint32(sum) + } + } + + // Write elemData. + for _, elems := range &pw.elems { + for _, elem := range elems { + _, err := io.WriteString(out, elem) + assert(err == nil) + } + } + + // Write fingerprint. + copy(fingerprint[:], h.Sum(nil)) + _, err := out0.Write(fingerprint[:]) + assert(err == nil) + + return +} + +// StringIdx adds a string value to the strings section, if not +// already present, and returns its index. +func (pw *PkgEncoder) StringIdx(s string) RelElemIdx { + if idx, ok := pw.stringsIdx[s]; ok { + assert(pw.elems[SectionString][idx] == s) + return idx + } + + idx := RelElemIdx(len(pw.elems[SectionString])) + pw.elems[SectionString] = append(pw.elems[SectionString], s) + pw.stringsIdx[s] = idx + return idx +} + +// NewEncoder returns an Encoder for a new element within the given +// section, and encodes the given SyncMarker as the start of the +// element bitstream. +func (pw *PkgEncoder) NewEncoder(k SectionKind, marker SyncMarker) *Encoder { + e := pw.NewEncoderRaw(k) + e.Sync(marker) + return e +} + +// NewEncoderRaw returns an Encoder for a new element within the given +// section. +// +// Most callers should use NewEncoder instead. +func (pw *PkgEncoder) NewEncoderRaw(k SectionKind) *Encoder { + idx := RelElemIdx(len(pw.elems[k])) + pw.elems[k] = append(pw.elems[k], "") // placeholder + + return &Encoder{ + p: pw, + k: k, + Idx: idx, + } +} + +// An Encoder provides methods for encoding an individual element's +// bitstream data. +type Encoder struct { + p *PkgEncoder + + Relocs []RefTableEntry + RelocMap map[RefTableEntry]uint32 + Data bytes.Buffer // accumulated element bitstream data + + encodingRelocHeader bool + + k SectionKind + Idx RelElemIdx // index within relocation section +} + +// Flush finalizes the element's bitstream and returns its [RelElemIdx]. +func (w *Encoder) Flush() RelElemIdx { + var sb strings.Builder + + // Backup the data so we write the relocations at the front. + var tmp bytes.Buffer + io.Copy(&tmp, &w.Data) + + // TODO(mdempsky): Consider writing these out separately so they're + // easier to strip, along with function bodies, so that we can prune + // down to just the data that's relevant to go/types. + if w.encodingRelocHeader { + panic("encodingRelocHeader already true; recursive flush?") + } + w.encodingRelocHeader = true + w.Sync(SyncRelocs) + w.Len(len(w.Relocs)) + for _, rEnt := range w.Relocs { + w.Sync(SyncReloc) + w.Len(int(rEnt.Kind)) + w.Len(int(rEnt.Idx)) + } + + io.Copy(&sb, &w.Data) + io.Copy(&sb, &tmp) + w.p.elems[w.k][w.Idx] = sb.String() + + return w.Idx +} + +func (w *Encoder) checkErr(err error) { + if err != nil { + panicf("unexpected encoding error: %v", err) + } +} + +func (w *Encoder) rawUvarint(x uint64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutUvarint(buf[:], x) + _, err := w.Data.Write(buf[:n]) + w.checkErr(err) +} + +func (w *Encoder) rawVarint(x int64) { + // Zig-zag encode. + ux := uint64(x) << 1 + if x < 0 { + ux = ^ux + } + + w.rawUvarint(ux) +} + +func (w *Encoder) rawReloc(k SectionKind, idx RelElemIdx) int { + e := RefTableEntry{k, idx} + if w.RelocMap != nil { + if i, ok := w.RelocMap[e]; ok { + return int(i) + } + } else { + w.RelocMap = make(map[RefTableEntry]uint32) + } + + i := len(w.Relocs) + w.RelocMap[e] = uint32(i) + w.Relocs = append(w.Relocs, e) + return i +} + +func (w *Encoder) Sync(m SyncMarker) { + if !w.p.SyncMarkers() { + return + } + + // Writing out stack frame string references requires working + // relocations, but writing out the relocations themselves involves + // sync markers. To prevent infinite recursion, we simply trim the + // stack frame for sync markers within the relocation header. + var frames []string + if !w.encodingRelocHeader && w.p.syncFrames > 0 { + pcs := make([]uintptr, w.p.syncFrames) + n := runtime.Callers(2, pcs) + frames = fmtFrames(pcs[:n]...) + } + + // TODO(mdempsky): Save space by writing out stack frames as a + // linked list so we can share common stack frames. + w.rawUvarint(uint64(m)) + w.rawUvarint(uint64(len(frames))) + for _, frame := range frames { + w.rawUvarint(uint64(w.rawReloc(SectionString, w.p.StringIdx(frame)))) + } +} + +// Bool encodes and writes a bool value into the element bitstream, +// and then returns the bool value. +// +// For simple, 2-alternative encodings, the idiomatic way to call Bool +// is something like: +// +// if w.Bool(x != 0) { +// // alternative #1 +// } else { +// // alternative #2 +// } +// +// For multi-alternative encodings, use Code instead. +func (w *Encoder) Bool(b bool) bool { + w.Sync(SyncBool) + var x byte + if b { + x = 1 + } + err := w.Data.WriteByte(x) + w.checkErr(err) + return b +} + +// Int64 encodes and writes an int64 value into the element bitstream. +func (w *Encoder) Int64(x int64) { + w.Sync(SyncInt64) + w.rawVarint(x) +} + +// Uint64 encodes and writes a uint64 value into the element bitstream. +func (w *Encoder) Uint64(x uint64) { + w.Sync(SyncUint64) + w.rawUvarint(x) +} + +// Len encodes and writes a non-negative int value into the element bitstream. +func (w *Encoder) Len(x int) { assert(x >= 0); w.Uint64(uint64(x)) } + +// Int encodes and writes an int value into the element bitstream. +func (w *Encoder) Int(x int) { w.Int64(int64(x)) } + +// Uint encodes and writes a uint value into the element bitstream. +func (w *Encoder) Uint(x uint) { w.Uint64(uint64(x)) } + +// Reloc encodes and writes a relocation for the given (section, +// index) pair into the element bitstream. +// +// Note: Only the index is formally written into the element +// bitstream, so bitstream decoders must know from context which +// section an encoded relocation refers to. +func (w *Encoder) Reloc(k SectionKind, idx RelElemIdx) { + w.Sync(SyncUseReloc) + w.Len(w.rawReloc(k, idx)) +} + +// Code encodes and writes a Code value into the element bitstream. +func (w *Encoder) Code(c Code) { + w.Sync(c.Marker()) + w.Len(c.Value()) +} + +// String encodes and writes a string value into the element +// bitstream. +// +// Internally, strings are deduplicated by adding them to the strings +// section (if not already present), and then writing a relocation +// into the element bitstream. +func (w *Encoder) String(s string) { + w.StringRef(w.p.StringIdx(s)) +} + +// StringRef writes a reference to the given index, which must be a +// previously encoded string value. +func (w *Encoder) StringRef(idx RelElemIdx) { + w.Sync(SyncString) + w.Reloc(SectionString, idx) +} + +// Strings encodes and writes a variable-length slice of strings into +// the element bitstream. +func (w *Encoder) Strings(ss []string) { + w.Len(len(ss)) + for _, s := range ss { + w.String(s) + } +} + +// Value encodes and writes a constant.Value into the element +// bitstream. +func (w *Encoder) Value(val constant.Value) { + w.Sync(SyncValue) + if w.Bool(val.Kind() == constant.Complex) { + w.scalar(constant.Real(val)) + w.scalar(constant.Imag(val)) + } else { + w.scalar(val) + } +} + +func (w *Encoder) scalar(val constant.Value) { + switch v := constant.Val(val).(type) { + default: + panicf("unhandled %v (%v)", val, val.Kind()) + case bool: + w.Code(ValBool) + w.Bool(v) + case string: + w.Code(ValString) + w.String(v) + case int64: + w.Code(ValInt64) + w.Int64(v) + case *big.Int: + w.Code(ValBigInt) + w.bigInt(v) + case *big.Rat: + w.Code(ValBigRat) + w.bigInt(v.Num()) + w.bigInt(v.Denom()) + case *big.Float: + w.Code(ValBigFloat) + w.bigFloat(v) + } +} + +func (w *Encoder) bigInt(v *big.Int) { + b := v.Bytes() + w.String(string(b)) // TODO: More efficient encoding. + w.Bool(v.Sign() < 0) +} + +func (w *Encoder) bigFloat(v *big.Float) { + b := v.Append(nil, 'p', -1) + w.String(string(b)) // TODO: More efficient encoding. +} + +// Version reports the version of the bitstream. +func (w *Encoder) Version() Version { return w.p.version } diff --git a/go/src/internal/pkgbits/flags.go b/go/src/internal/pkgbits/flags.go new file mode 100644 index 0000000000000000000000000000000000000000..654222745facd222bec7f8c9989c1fb5f5e204af --- /dev/null +++ b/go/src/internal/pkgbits/flags.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 pkgbits + +const ( + flagSyncMarkers = 1 << iota // file format contains sync markers +) diff --git a/go/src/internal/pkgbits/pkgbits_test.go b/go/src/internal/pkgbits/pkgbits_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f67267189f5edea4f356ac1a689421a2b1e9bf4e --- /dev/null +++ b/go/src/internal/pkgbits/pkgbits_test.go @@ -0,0 +1,76 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits_test + +import ( + "internal/pkgbits" + "strings" + "testing" +) + +func TestRoundTrip(t *testing.T) { + for _, version := range []pkgbits.Version{ + pkgbits.V0, + pkgbits.V1, + pkgbits.V2, + } { + pw := pkgbits.NewPkgEncoder(version, -1) + w := pw.NewEncoder(pkgbits.SectionMeta, pkgbits.SyncPublic) + w.Flush() + + var b strings.Builder + _ = pw.DumpTo(&b) + input := b.String() + + pr := pkgbits.NewPkgDecoder("package_id", input) + r := pr.NewDecoder(pkgbits.SectionMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic) + + if r.Version() != w.Version() { + t.Errorf("Expected reader version %d to be the writer version %d", r.Version(), w.Version()) + } + } +} + +// Type checker to enforce that know V* have the constant values they must have. +var _ [0]bool = [pkgbits.V0]bool{} +var _ [1]bool = [pkgbits.V1]bool{} + +func TestVersions(t *testing.T) { + type vfpair struct { + v pkgbits.Version + f pkgbits.Field + } + + // has field tests + for _, c := range []vfpair{ + {pkgbits.V1, pkgbits.Flags}, + {pkgbits.V2, pkgbits.Flags}, + {pkgbits.V0, pkgbits.HasInit}, + {pkgbits.V1, pkgbits.HasInit}, + {pkgbits.V0, pkgbits.DerivedFuncInstance}, + {pkgbits.V1, pkgbits.DerivedFuncInstance}, + {pkgbits.V0, pkgbits.DerivedInfoNeeded}, + {pkgbits.V1, pkgbits.DerivedInfoNeeded}, + {pkgbits.V2, pkgbits.AliasTypeParamNames}, + } { + if !c.v.Has(c.f) { + t.Errorf("Expected version %v to have field %v", c.v, c.f) + } + } + + // does not have field tests + for _, c := range []vfpair{ + {pkgbits.V0, pkgbits.Flags}, + {pkgbits.V2, pkgbits.HasInit}, + {pkgbits.V2, pkgbits.DerivedFuncInstance}, + {pkgbits.V2, pkgbits.DerivedInfoNeeded}, + {pkgbits.V0, pkgbits.AliasTypeParamNames}, + {pkgbits.V1, pkgbits.AliasTypeParamNames}, + } { + if c.v.Has(c.f) { + t.Errorf("Expected version %v to not have field %v", c.v, c.f) + } + } +} diff --git a/go/src/internal/pkgbits/reloc.go b/go/src/internal/pkgbits/reloc.go new file mode 100644 index 0000000000000000000000000000000000000000..6074296d9ee3f95f138ae66c89b0ac4e0305d169 --- /dev/null +++ b/go/src/internal/pkgbits/reloc.go @@ -0,0 +1,114 @@ +// 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 pkgbits + +// A SectionKind indicates a section, as well as the ordering of sections within +// unified export data. Any object given a dedicated section can be referred to +// via a section / index pair (and thus dereferenced) in other sections. +type SectionKind int32 // TODO(markfreeman): Replace with uint8. + +const ( + SectionString SectionKind = iota + SectionMeta + SectionPosBase + SectionPkg + SectionName + SectionType + SectionObj + SectionObjExt + SectionObjDict + SectionBody + + numRelocs = iota +) + +// An Index represents a bitstream element index *within* (i.e., relative to) a +// particular section. +type Index int32 + +// An AbsElemIdx, or absolute element index, is an index into the elements +// that is not relative to some other index. +type AbsElemIdx = uint32 + +// TODO(markfreeman): Make this its own type. +// A RelElemIdx, or relative element index, is an index into the elements +// relative to some other index, such as the start of a section. +type RelElemIdx = Index + +/* +All elements are preceded by a reference table. Reference tables provide an +additional indirection layer for element references. That is, for element A to +reference element B, A encodes the reference table index pointing to B, rather +than the table entry itself. + +# Functional Considerations +Reference table layout is important primarily to the UIR linker. After noding, +the UIR linker sees a UIR file for each package with imported objects +represented as stubs. In a simple sense, the job of the UIR linker is to merge +these "stubbed" UIR files into a single "linked" UIR file for the target package +with stubs replaced by object definitions. + +To do this, the UIR linker walks each stubbed UIR file and pulls in elements in +dependency order; that is, if A references B, then B must be placed into the +linked UIR file first. This depth-first traversal is done by recursing through +each element's reference table. + +When placing A in the linked UIR file, the reference table entry for B must be +updated, since B is unlikely to be at the same relative element index as it was +in the stubbed UIR file. + +Without reference tables, the UIR linker would need to read in the element to +discover its references. Note that the UIR linker cannot jump directly to the +reference locations after discovering merely the type of the element; +variable-width primitives prevent this. + +After updating the reference table, the rest of the element may be copied +directly into the linked UIR file. Note that the UIR linker may decide to read +in the element anyway (for unrelated reasons). + +In short, reference tables provide an efficient mechanism for traversing, +discovering, and updating element references during UIR linking. + +# Storage Considerations +Reference tables also have compactness benefits: + - If A refers to B multiple times, the entry is deduplicated and referred to + more compactly by the index. + - Relative (to a section) element indices are typically smaller than absolute + element indices, and thus fit into smaller varints. + - Most elements do not reference many elements; thus table size indicators and + table indices are typically a byte each. + +Thus, the storage performance is as follows: ++-----------------------------+-----------+--------------+ +| Scenario | Best Case | Typical Case | ++-----------------------------+-----------+--------------+ +| First reference from A to B | 3 Bytes | 4 Bytes | +| Other reference from A to B | 1 Byte | 1 Byte | ++-----------------------------+-----------+--------------+ + +The typical case for the first scenario changes because many sections have more +than 127 (range of a 1-byte uvarint) elements and thus the relative index is +typically 2 bytes, though this depends on the distribution of referenced indices +within the section. + +The second does not because most elements do not reference more than 127 +elements and the table index can thus keep to 1 byte. + +Typically, A will only reference B once, so most references are 4 bytes. +*/ + +// A RefTableEntry is an entry in an element's reference table. All +// elements are preceded by a reference table which provides locations +// for referenced elements. +type RefTableEntry struct { + Kind SectionKind + Idx RelElemIdx +} + +// Reserved indices within the [SectionMeta] section. +const ( + PublicRootIdx RelElemIdx = 0 + PrivateRootIdx RelElemIdx = 1 +) diff --git a/go/src/internal/pkgbits/support.go b/go/src/internal/pkgbits/support.go new file mode 100644 index 0000000000000000000000000000000000000000..50534a295536386b54322d764db6c0f8ee397a28 --- /dev/null +++ b/go/src/internal/pkgbits/support.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +import "fmt" + +func assert(b bool) { + if !b { + panic("assertion failed") + } +} + +func panicf(format string, args ...any) { + panic(fmt.Errorf(format, args...)) +} diff --git a/go/src/internal/pkgbits/sync.go b/go/src/internal/pkgbits/sync.go new file mode 100644 index 0000000000000000000000000000000000000000..1520b73afb9e960c166c587981bc934017ecbb74 --- /dev/null +++ b/go/src/internal/pkgbits/sync.go @@ -0,0 +1,136 @@ +// 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 pkgbits + +import ( + "fmt" + "runtime" + "strings" +) + +// fmtFrames formats a backtrace for reporting reader/writer desyncs. +func fmtFrames(pcs ...uintptr) []string { + res := make([]string, 0, len(pcs)) + walkFrames(pcs, func(file string, line int, name string, offset uintptr) { + // Trim package from function name. It's just redundant noise. + name = strings.TrimPrefix(name, "cmd/compile/internal/noder.") + + res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset)) + }) + return res +} + +type frameVisitor func(file string, line int, name string, offset uintptr) + +// walkFrames calls visit for each call frame represented by pcs. +// +// pcs should be a slice of PCs, as returned by runtime.Callers. +func walkFrames(pcs []uintptr, visit frameVisitor) { + if len(pcs) == 0 { + return + } + + frames := runtime.CallersFrames(pcs) + for { + frame, more := frames.Next() + visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry) + if !more { + return + } + } +} + +// SyncMarker is an enum type that represents markers that may be +// written to export data to ensure the reader and writer stay +// synchronized. +type SyncMarker int + +//go:generate stringer -type=SyncMarker -trimprefix=Sync + +const ( + _ SyncMarker = iota + + // Public markers (known to go/types importers). + + // Low-level coding markers. + SyncEOF + SyncBool + SyncInt64 + SyncUint64 + SyncString + SyncValue + SyncVal + SyncRelocs + SyncReloc + SyncUseReloc + + // Higher-level object and type markers. + SyncPublic + SyncPos + SyncPosBase + SyncObject + SyncObject1 + SyncPkg + SyncPkgDef + SyncMethod + SyncType + SyncTypeIdx + SyncTypeParamNames + SyncSignature + SyncParams + SyncParam + SyncCodeObj + SyncSym + SyncLocalIdent + SyncSelector + + // Private markers (only known to cmd/compile). + SyncPrivate + + SyncFuncExt + SyncVarExt + SyncTypeExt + SyncPragma + + SyncExprList + SyncExprs + SyncExpr + SyncExprType + SyncAssign + SyncOp + SyncFuncLit + SyncCompLit + + SyncDecl + SyncFuncBody + SyncOpenScope + SyncCloseScope + SyncCloseAnotherScope + SyncDeclNames + SyncDeclName + + SyncStmts + SyncBlockStmt + SyncIfStmt + SyncForStmt + SyncSwitchStmt + SyncRangeStmt + SyncCaseClause + SyncCommClause + SyncSelectStmt + SyncDecls + SyncLabeledStmt + SyncUseObjLocal + SyncAddLocal + SyncLinkname + SyncStmt1 + SyncStmtsEnd + SyncLabel + SyncOptLabel + + SyncMultiExpr + SyncRType + SyncConvRTTI +) diff --git a/go/src/internal/pkgbits/syncmarker_string.go b/go/src/internal/pkgbits/syncmarker_string.go new file mode 100644 index 0000000000000000000000000000000000000000..582ad56d3e09f3dfd7c4390312a0e9141aec50ab --- /dev/null +++ b/go/src/internal/pkgbits/syncmarker_string.go @@ -0,0 +1,92 @@ +// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT. + +package pkgbits + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[SyncEOF-1] + _ = x[SyncBool-2] + _ = x[SyncInt64-3] + _ = x[SyncUint64-4] + _ = x[SyncString-5] + _ = x[SyncValue-6] + _ = x[SyncVal-7] + _ = x[SyncRelocs-8] + _ = x[SyncReloc-9] + _ = x[SyncUseReloc-10] + _ = x[SyncPublic-11] + _ = x[SyncPos-12] + _ = x[SyncPosBase-13] + _ = x[SyncObject-14] + _ = x[SyncObject1-15] + _ = x[SyncPkg-16] + _ = x[SyncPkgDef-17] + _ = x[SyncMethod-18] + _ = x[SyncType-19] + _ = x[SyncTypeIdx-20] + _ = x[SyncTypeParamNames-21] + _ = x[SyncSignature-22] + _ = x[SyncParams-23] + _ = x[SyncParam-24] + _ = x[SyncCodeObj-25] + _ = x[SyncSym-26] + _ = x[SyncLocalIdent-27] + _ = x[SyncSelector-28] + _ = x[SyncPrivate-29] + _ = x[SyncFuncExt-30] + _ = x[SyncVarExt-31] + _ = x[SyncTypeExt-32] + _ = x[SyncPragma-33] + _ = x[SyncExprList-34] + _ = x[SyncExprs-35] + _ = x[SyncExpr-36] + _ = x[SyncExprType-37] + _ = x[SyncAssign-38] + _ = x[SyncOp-39] + _ = x[SyncFuncLit-40] + _ = x[SyncCompLit-41] + _ = x[SyncDecl-42] + _ = x[SyncFuncBody-43] + _ = x[SyncOpenScope-44] + _ = x[SyncCloseScope-45] + _ = x[SyncCloseAnotherScope-46] + _ = x[SyncDeclNames-47] + _ = x[SyncDeclName-48] + _ = x[SyncStmts-49] + _ = x[SyncBlockStmt-50] + _ = x[SyncIfStmt-51] + _ = x[SyncForStmt-52] + _ = x[SyncSwitchStmt-53] + _ = x[SyncRangeStmt-54] + _ = x[SyncCaseClause-55] + _ = x[SyncCommClause-56] + _ = x[SyncSelectStmt-57] + _ = x[SyncDecls-58] + _ = x[SyncLabeledStmt-59] + _ = x[SyncUseObjLocal-60] + _ = x[SyncAddLocal-61] + _ = x[SyncLinkname-62] + _ = x[SyncStmt1-63] + _ = x[SyncStmtsEnd-64] + _ = x[SyncLabel-65] + _ = x[SyncOptLabel-66] + _ = x[SyncMultiExpr-67] + _ = x[SyncRType-68] + _ = x[SyncConvRTTI-69] +} + +const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI" + +var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480} + +func (i SyncMarker) String() string { + i -= 1 + if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) { + return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]] +} diff --git a/go/src/internal/pkgbits/version.go b/go/src/internal/pkgbits/version.go new file mode 100644 index 0000000000000000000000000000000000000000..ba664f45554aabc69c53629af54db35254f30bc3 --- /dev/null +++ b/go/src/internal/pkgbits/version.go @@ -0,0 +1,85 @@ +// 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 pkgbits + +// Version indicates a version of a unified IR bitstream. +// Each Version indicates the addition, removal, or change of +// new data in the bitstream. +// +// These are serialized to disk and the interpretation remains fixed. +type Version uint32 + +const ( + // V0: initial prototype. + // + // All data that is not assigned a Field is in version V0 + // and has not been deprecated. + V0 Version = iota + + // V1: adds the Flags uint32 word + V1 + + // V2: removes unused legacy fields and supports type parameters for aliases. + // - remove the legacy "has init" bool from the public root + // - remove obj's "derived func instance" bool + // - add a TypeParamNames field to ObjAlias + // - remove derived info "needed" bool + V2 + + numVersions = iota +) + +// Field denotes a unit of data in the serialized unified IR bitstream. +// It is conceptually a like field in a structure. +// +// We only really need Fields when the data may or may not be present +// in a stream based on the Version of the bitstream. +// +// Unlike much of pkgbits, Fields are not serialized and +// can change values as needed. +type Field int + +const ( + // Flags in a uint32 in the header of a bitstream + // that is used to indicate whether optional features are enabled. + Flags Field = iota + + // Deprecated: HasInit was a bool indicating whether a package + // has any init functions. + HasInit + + // Deprecated: DerivedFuncInstance was a bool indicating + // whether an object was a function instance. + DerivedFuncInstance + + // ObjAlias has a list of TypeParamNames. + AliasTypeParamNames + + // Deprecated: DerivedInfoNeeded was a bool indicating + // whether a type was a derived type. + DerivedInfoNeeded + + numFields = iota +) + +// introduced is the version a field was added. +var introduced = [numFields]Version{ + Flags: V1, + AliasTypeParamNames: V2, +} + +// removed is the version a field was removed in or 0 for fields +// that have not yet been deprecated. +// (So removed[f]-1 is the last version it is included in.) +var removed = [numFields]Version{ + HasInit: V2, + DerivedFuncInstance: V2, + DerivedInfoNeeded: V2, +} + +// Has reports whether field f is present in a bitstream at version v. +func (v Version) Has(f Field) bool { + return introduced[f] <= v && (v < removed[f] || removed[f] == V0) +} diff --git a/go/src/internal/platform/supported.go b/go/src/internal/platform/supported.go new file mode 100644 index 0000000000000000000000000000000000000000..778d727086ac498e6aaac90c60c8f4a2cd3fe4ba --- /dev/null +++ b/go/src/internal/platform/supported.go @@ -0,0 +1,283 @@ +// 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:generate go test . -run=^TestGenerated$ -fix + +package platform + +// An OSArch is a pair of GOOS and GOARCH values indicating a platform. +type OSArch struct { + GOOS, GOARCH string +} + +func (p OSArch) String() string { + return p.GOOS + "/" + p.GOARCH +} + +// RaceDetectorSupported reports whether goos/goarch supports the race +// detector. There is a copy of this function in cmd/dist/test.go. +// Race detector only supports 48-bit VMA on arm64. But it will always +// return true for arm64, because we don't have VMA size information during +// the compile time. +func RaceDetectorSupported(goos, goarch string) bool { + switch goos { + case "linux": + return goarch == "amd64" || goarch == "arm64" || goarch == "loong64" || goarch == "ppc64le" || goarch == "riscv64" || goarch == "s390x" + case "darwin": + return goarch == "amd64" || goarch == "arm64" + case "freebsd", "netbsd", "windows": + return goarch == "amd64" + default: + return false + } +} + +// MSanSupported reports whether goos/goarch supports the memory +// sanitizer option. +func MSanSupported(goos, goarch string) bool { + switch goos { + case "linux": + return goarch == "amd64" || goarch == "arm64" || goarch == "loong64" + case "freebsd": + return goarch == "amd64" + default: + return false + } +} + +// ASanSupported reports whether goos/goarch supports the address +// sanitizer option. +func ASanSupported(goos, goarch string) bool { + switch goos { + case "linux": + return goarch == "arm64" || goarch == "amd64" || goarch == "loong64" || goarch == "riscv64" || goarch == "ppc64le" + default: + return false + } +} + +// FuzzSupported reports whether goos/goarch supports fuzzing +// ('go test -fuzz=.'). +func FuzzSupported(goos, goarch string) bool { + switch goos { + case "darwin", "freebsd", "linux", "openbsd", "windows": + return true + default: + return false + } +} + +// FuzzInstrumented reports whether fuzzing on goos/goarch uses coverage +// instrumentation. (FuzzInstrumented implies FuzzSupported.) +func FuzzInstrumented(goos, goarch string) bool { + switch goarch { + case "amd64", "arm64", "loong64": + // TODO(#14565): support more architectures. + return FuzzSupported(goos, goarch) + default: + return false + } +} + +// MustLinkExternal reports whether goos/goarch requires external linking +// with or without cgo dependencies. +func MustLinkExternal(goos, goarch string, withCgo bool) bool { + if withCgo { + switch goarch { + case "mips", "mipsle", "mips64", "mips64le": + // Internally linking cgo is incomplete on some architectures. + // https://go.dev/issue/14449 + return true + case "ppc64": + // Big Endian PPC64 cgo internal linking is not implemented for aix or linux. + // https://go.dev/issue/8912 + if goos == "aix" || goos == "linux" { + return true + } + } + + switch goos { + case "android": + return true + case "dragonfly": + // It seems that on Dragonfly thread local storage is + // set up by the dynamic linker, so internal cgo linking + // doesn't work. Test case is "go test runtime/cgo". + return true + } + } + + switch goos { + case "android": + if goarch != "arm64" { + return true + } + case "ios": + if goarch == "arm64" { + return true + } + } + return false +} + +// BuildModeSupported reports whether goos/goarch supports the given build mode +// using the given compiler. +// There is a copy of this function in cmd/dist/test.go. +func BuildModeSupported(compiler, buildmode, goos, goarch string) bool { + if compiler == "gccgo" { + return true + } + + if _, ok := distInfo[OSArch{goos, goarch}]; !ok { + return false // platform unrecognized + } + + platform := goos + "/" + goarch + switch buildmode { + case "archive": + return true + + case "c-archive": + switch goos { + case "aix", "darwin", "ios", "windows": + return true + case "linux": + switch goarch { + case "386", "amd64", "arm", "armbe", "arm64", "arm64be", "loong64", "ppc64le", "riscv64", "s390x": + // linux/ppc64 not supported because it does + // not support external linking mode yet. + return true + default: + // Other targets do not support -shared, + // per ParseFlags in + // cmd/compile/internal/base/flag.go. + // For c-archive the Go tool passes -shared, + // so that the result is suitable for inclusion + // in a PIE or shared library. + return false + } + case "freebsd": + return goarch == "amd64" + } + return false + + case "c-shared": + switch platform { + case "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/386", "linux/ppc64le", "linux/riscv64", "linux/s390x", + "android/amd64", "android/arm", "android/arm64", "android/386", + "freebsd/amd64", + "darwin/amd64", "darwin/arm64", + "windows/amd64", "windows/386", "windows/arm64", + "wasip1/wasm": + return true + } + return false + + case "default": + return true + + case "exe": + return true + + case "pie": + switch platform { + case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/loong64", "linux/ppc64le", "linux/riscv64", "linux/s390x", + "android/amd64", "android/arm", "android/arm64", "android/386", + "freebsd/amd64", + "darwin/amd64", "darwin/arm64", + "ios/amd64", "ios/arm64", + "aix/ppc64", + "openbsd/arm64", + "windows/386", "windows/amd64", "windows/arm64": + return true + } + return false + + case "shared": + switch platform { + case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x": + return true + } + return false + + case "plugin": + switch platform { + case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "linux/loong64", "linux/riscv64", "linux/s390x", "linux/ppc64le", + "android/amd64", "android/386", + "darwin/amd64", "darwin/arm64", + "freebsd/amd64": + return true + } + return false + + default: + return false + } +} + +func InternalLinkPIESupported(goos, goarch string) bool { + switch goos + "/" + goarch { + case "android/arm64", + "darwin/amd64", "darwin/arm64", + "linux/amd64", "linux/arm64", "linux/loong64", "linux/ppc64le", + "windows/386", "windows/amd64", "windows/arm64": + return true + } + return false +} + +// DefaultPIE reports whether goos/goarch produces a PIE binary when using the +// "default" buildmode. On Windows this is affected by -race, +// so force the caller to pass that in to centralize that choice. +func DefaultPIE(goos, goarch string, isRace bool) bool { + switch goos { + case "android", "ios": + return true + case "windows": + if isRace { + // PIE is not supported with -race on windows; + // see https://go.dev/cl/416174. + return false + } + return true + case "darwin": + return true + } + return false +} + +// ExecutableHasDWARF reports whether the linked executable includes DWARF +// symbols on goos/goarch. +func ExecutableHasDWARF(goos, goarch string) bool { + switch goos { + case "plan9", "ios": + return false + } + return true +} + +// osArchInfo describes information about an OSArch extracted from cmd/dist and +// stored in the generated distInfo map. +type osArchInfo struct { + CgoSupported bool + FirstClass bool + Broken bool +} + +// CgoSupported reports whether goos/goarch supports cgo. +func CgoSupported(goos, goarch string) bool { + return distInfo[OSArch{goos, goarch}].CgoSupported +} + +// FirstClass reports whether goos/goarch is considered a “first class” port. +// (See https://go.dev/wiki/PortingPolicy#first-class-ports.) +func FirstClass(goos, goarch string) bool { + return distInfo[OSArch{goos, goarch}].FirstClass +} + +// Broken reports whether goos/goarch is considered a broken port. +// (See https://go.dev/wiki/PortingPolicy#broken-ports.) +func Broken(goos, goarch string) bool { + return distInfo[OSArch{goos, goarch}].Broken +} diff --git a/go/src/internal/platform/zosarch.go b/go/src/internal/platform/zosarch.go new file mode 100644 index 0000000000000000000000000000000000000000..a2f5b22ea9a6560401f4d6840fecae5de564c5c3 --- /dev/null +++ b/go/src/internal/platform/zosarch.go @@ -0,0 +1,114 @@ +// Code generated by go test internal/platform -fix. DO NOT EDIT. + +// To change the information in this file, edit the cgoEnabled and/or firstClass +// maps in cmd/dist/build.go, then run 'go generate internal/platform'. + +package platform + +// List is the list of all valid GOOS/GOARCH combinations, +// including known-broken ports. +var List = []OSArch{ + {"aix", "ppc64"}, + {"android", "386"}, + {"android", "amd64"}, + {"android", "arm"}, + {"android", "arm64"}, + {"darwin", "amd64"}, + {"darwin", "arm64"}, + {"dragonfly", "amd64"}, + {"freebsd", "386"}, + {"freebsd", "amd64"}, + {"freebsd", "arm"}, + {"freebsd", "arm64"}, + {"freebsd", "riscv64"}, + {"illumos", "amd64"}, + {"ios", "amd64"}, + {"ios", "arm64"}, + {"js", "wasm"}, + {"linux", "386"}, + {"linux", "amd64"}, + {"linux", "arm"}, + {"linux", "arm64"}, + {"linux", "loong64"}, + {"linux", "mips"}, + {"linux", "mips64"}, + {"linux", "mips64le"}, + {"linux", "mipsle"}, + {"linux", "ppc64"}, + {"linux", "ppc64le"}, + {"linux", "riscv64"}, + {"linux", "s390x"}, + {"linux", "sparc64"}, + {"netbsd", "386"}, + {"netbsd", "amd64"}, + {"netbsd", "arm"}, + {"netbsd", "arm64"}, + {"openbsd", "386"}, + {"openbsd", "amd64"}, + {"openbsd", "arm"}, + {"openbsd", "arm64"}, + {"openbsd", "mips64"}, + {"openbsd", "ppc64"}, + {"openbsd", "riscv64"}, + {"plan9", "386"}, + {"plan9", "amd64"}, + {"plan9", "arm"}, + {"solaris", "amd64"}, + {"wasip1", "wasm"}, + {"windows", "386"}, + {"windows", "amd64"}, + {"windows", "arm64"}, +} + +var distInfo = map[OSArch]osArchInfo{ + {"aix", "ppc64"}: {CgoSupported: true}, + {"android", "386"}: {CgoSupported: true}, + {"android", "amd64"}: {CgoSupported: true}, + {"android", "arm"}: {CgoSupported: true}, + {"android", "arm64"}: {CgoSupported: true}, + {"darwin", "amd64"}: {CgoSupported: true, FirstClass: true}, + {"darwin", "arm64"}: {CgoSupported: true, FirstClass: true}, + {"dragonfly", "amd64"}: {CgoSupported: true}, + {"freebsd", "386"}: {CgoSupported: true}, + {"freebsd", "amd64"}: {CgoSupported: true}, + {"freebsd", "arm"}: {CgoSupported: true}, + {"freebsd", "arm64"}: {CgoSupported: true}, + {"freebsd", "riscv64"}: {CgoSupported: true, Broken: true}, + {"illumos", "amd64"}: {CgoSupported: true}, + {"ios", "amd64"}: {CgoSupported: true}, + {"ios", "arm64"}: {CgoSupported: true}, + {"js", "wasm"}: {}, + {"linux", "386"}: {CgoSupported: true, FirstClass: true}, + {"linux", "amd64"}: {CgoSupported: true, FirstClass: true}, + {"linux", "arm"}: {CgoSupported: true, FirstClass: true}, + {"linux", "arm64"}: {CgoSupported: true, FirstClass: true}, + {"linux", "loong64"}: {CgoSupported: true}, + {"linux", "mips"}: {CgoSupported: true}, + {"linux", "mips64"}: {CgoSupported: true}, + {"linux", "mips64le"}: {CgoSupported: true}, + {"linux", "mipsle"}: {CgoSupported: true}, + {"linux", "ppc64"}: {}, + {"linux", "ppc64le"}: {CgoSupported: true}, + {"linux", "riscv64"}: {CgoSupported: true}, + {"linux", "s390x"}: {CgoSupported: true}, + {"linux", "sparc64"}: {CgoSupported: true, Broken: true}, + {"netbsd", "386"}: {CgoSupported: true}, + {"netbsd", "amd64"}: {CgoSupported: true}, + {"netbsd", "arm"}: {CgoSupported: true}, + {"netbsd", "arm64"}: {CgoSupported: true}, + {"openbsd", "386"}: {CgoSupported: true}, + {"openbsd", "amd64"}: {CgoSupported: true}, + {"openbsd", "arm"}: {CgoSupported: true}, + {"openbsd", "arm64"}: {CgoSupported: true}, + {"openbsd", "mips64"}: {CgoSupported: true, Broken: true}, + {"openbsd", "ppc64"}: {}, + {"openbsd", "riscv64"}: {CgoSupported: true}, + {"plan9", "386"}: {}, + {"plan9", "amd64"}: {}, + {"plan9", "arm"}: {}, + {"solaris", "amd64"}: {CgoSupported: true}, + {"wasip1", "wasm"}: {}, + {"windows", "386"}: {CgoSupported: true, FirstClass: true}, + {"windows", "amd64"}: {CgoSupported: true, FirstClass: true}, + {"windows", "arm64"}: {CgoSupported: true}, +} diff --git a/go/src/internal/platform/zosarch_test.go b/go/src/internal/platform/zosarch_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e8ffe9e75d4a11dc0626c7f612d8c06f934c73ad --- /dev/null +++ b/go/src/internal/platform/zosarch_test.go @@ -0,0 +1,109 @@ +// 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 platform_test + +import ( + "bytes" + "encoding/json" + "flag" + "internal/diff" + "internal/testenv" + "os" + "os/exec" + "testing" + "text/template" +) + +var flagFix = flag.Bool("fix", false, "if true, fix out-of-date generated files") + +// TestGenerated verifies that zosarch.go is up to date, +// or regenerates it if the -fix flag is set. +func TestGenerated(t *testing.T) { + testenv.MustHaveGoRun(t) + + // Here we use 'go run cmd/dist' instead of 'go tool dist' in case the + // installed cmd/dist is stale or missing. We don't want to miss a + // skew in the data due to a stale binary. + cmd := testenv.Command(t, "go", "run", "cmd/dist", "list", "-json", "-broken") + + // cmd/dist requires GOROOT to be set explicitly in the environment. + cmd.Env = append(cmd.Environ(), "GOROOT="+testenv.GOROOT(t)) + + out, err := cmd.Output() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { + t.Logf("stderr:\n%s", ee.Stderr) + } + t.Fatalf("%v: %v", cmd, err) + } + + type listEntry struct { + GOOS, GOARCH string + CgoSupported bool + FirstClass bool + Broken bool + } + var entries []listEntry + if err := json.Unmarshal(out, &entries); err != nil { + t.Fatal(err) + } + + tmplOut := new(bytes.Buffer) + tmpl := template.Must(template.New("zosarch").Parse(zosarchTmpl)) + err = tmpl.Execute(tmplOut, entries) + if err != nil { + t.Fatal(err) + } + + cmd = testenv.Command(t, "gofmt") + cmd.Stdin = bytes.NewReader(tmplOut.Bytes()) + want, err := cmd.Output() + if err != nil { + t.Logf("stdin:\n%s", tmplOut.Bytes()) + if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { + t.Logf("stderr:\n%s", ee.Stderr) + } + t.Fatalf("%v: %v", cmd, err) + } + + got, err := os.ReadFile("zosarch.go") + if err == nil && bytes.Equal(got, want) { + return + } + + if !*flagFix { + if err != nil { + t.Log(err) + } else { + t.Logf("diff:\n%s", diff.Diff("zosarch.go", got, "want", want)) + } + t.Fatalf("zosarch.go is missing or out of date; to regenerate, run\ngo generate internal/platform") + } + + if err := os.WriteFile("zosarch.go", want, 0666); err != nil { + t.Fatal(err) + } +} + +const zosarchTmpl = `// Code generated by go test internal/platform -fix. DO NOT EDIT. + +// To change the information in this file, edit the cgoEnabled and/or firstClass +// maps in cmd/dist/build.go, then run 'go generate internal/platform'. + +package platform + +// List is the list of all valid GOOS/GOARCH combinations, +// including known-broken ports. +var List = []OSArch{ +{{range .}} { {{ printf "%q" .GOOS }}, {{ printf "%q" .GOARCH }} }, +{{end}} +} + +var distInfo = map[OSArch]osArchInfo { +{{range .}} { {{ printf "%q" .GOOS }}, {{ printf "%q" .GOARCH }} }: +{ {{if .CgoSupported}}CgoSupported: true, {{end}}{{if .FirstClass}}FirstClass: true, {{end}}{{if .Broken}} Broken: true, {{end}} }, +{{end}} +} +` diff --git a/go/src/internal/poll/copy_file_range_freebsd.go b/go/src/internal/poll/copy_file_range_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..63fa013e46cc3d48095ecffb6ea5e43b72ed67db --- /dev/null +++ b/go/src/internal/poll/copy_file_range_freebsd.go @@ -0,0 +1,53 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll + +import ( + "internal/syscall/unix" + "syscall" +) + +func supportCopyFileRange() bool { + return unix.SupportCopyFileRange() +} + +// For best performance, call copy_file_range() with the largest len value +// possible. It is interruptible on most file systems, so there is no penalty +// for using very large len values, even SSIZE_MAX. +const maxCopyFileRangeRound = 1<<31 - 1 + +func handleCopyFileRangeErr(err error, copied, written int64) (bool, error) { + switch err { + case syscall.ENOSYS: + // The copy_file_range(2) function first appeared in FreeBSD 13.0. + // Go supports FreeBSD >= 12, so the system call + // may not be present. We've detected the FreeBSD version with + // unix.SupportCopyFileRange() at the beginning of this function, + // but we still want to check for ENOSYS here to prevent some rare + // case like https://go.dev/issue/58592 + // + // If we see ENOSYS, we have certainly not transferred + // any data, so we can tell the caller that we + // couldn't handle the transfer and let them fall + // back to more generic code. + return false, nil + case syscall.EFBIG, syscall.EINVAL, syscall.EIO: + // For EFBIG, the copy has exceeds the process's file size limit + // or the maximum file size for the filesystem dst resides on, in + // this case, we leave it to generic copy. + // + // For EINVAL, there could be a few reasons: + // 1. Either dst or src refers to a file object that + // is not a regular file, for instance, a pipe. + // 2. src and dst refer to the same file and byte ranges + // overlap. + // 3. The flags argument is not 0. + // Neither of these cases should be considered handled by + // copy_file_range(2) because there is no data transfer, so + // just fall back to generic copy. + return false, nil + } + return true, err +} diff --git a/go/src/internal/poll/copy_file_range_linux.go b/go/src/internal/poll/copy_file_range_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..d7cbd984651678303a66e75a2aa851f5c8779f63 --- /dev/null +++ b/go/src/internal/poll/copy_file_range_linux.go @@ -0,0 +1,79 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll + +import ( + "internal/syscall/unix" + "sync" + "syscall" +) + +var supportCopyFileRange = sync.OnceValue(func() bool { + // copy_file_range(2) is broken in various ways on kernels older than 5.3, + // see https://go.dev/issue/42400 and + // https://man7.org/linux/man-pages/man2/copy_file_range.2.html#VERSIONS + return unix.KernelVersionGE(5, 3) +}) + +// For best performance, call copy_file_range() with the largest len value +// possible. Linux sets up a limitation of data transfer for most of its I/O +// system calls, as MAX_RW_COUNT (INT_MAX & PAGE_MASK). This value equals to +// the maximum integer value minus a page size that is typically 2^12=4096 bytes. +// That is to say, it's the maximum integer value with the lowest 12 bits unset, +// which is 0x7ffff000. +const maxCopyFileRangeRound = 0x7ffff000 + +func handleCopyFileRangeErr(err error, copied, written int64) (bool, error) { + switch err { + case syscall.ENOSYS: + // copy_file_range(2) was introduced in Linux 4.5. + // Go supports Linux >= 3.2, so the system call + // may not be present. + // + // If we see ENOSYS, we have certainly not transferred + // any data, so we can tell the caller that we + // couldn't handle the transfer and let them fall + // back to more generic code. + return false, nil + case syscall.EXDEV, syscall.EINVAL, syscall.EIO, syscall.EOPNOTSUPP, syscall.EPERM: + // Prior to Linux 5.3, it was not possible to + // copy_file_range across file systems. Similarly to + // the ENOSYS case above, if we see EXDEV, we have + // not transferred any data, and we can let the caller + // fall back to generic code. + // + // As for EINVAL, that is what we see if, for example, + // dst or src refer to a pipe rather than a regular + // file. This is another case where no data has been + // transferred, so we consider it unhandled. + // + // If src and dst are on CIFS, we can see EIO. + // See issue #42334. + // + // If the file is on NFS, we can see EOPNOTSUPP. + // See issue #40731. + // + // If the process is running inside a Docker container, + // we might see EPERM instead of ENOSYS. See issue + // #40893. Since EPERM might also be a legitimate error, + // don't mark copy_file_range(2) as unsupported. + return false, nil + case nil: + if copied == 0 { + // Prior to Linux 5.19 + // (https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=868f9f2f8e004bfe0d3935b1976f625b2924893b), + // copy_file_range can silently fail by reporting + // success and 0 bytes written. Assume such cases are + // failure and fallback to a different copy mechanism. + if written == 0 { + return false, nil + } + + // Otherwise src is at EOF, which means + // we are done. + } + } + return true, err +} diff --git a/go/src/internal/poll/copy_file_range_unix.go b/go/src/internal/poll/copy_file_range_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..d39c5a339d5895ca1480a74fbe39e435810449d1 --- /dev/null +++ b/go/src/internal/poll/copy_file_range_unix.go @@ -0,0 +1,67 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build freebsd || linux + +package poll + +import "internal/syscall/unix" + +// CopyFileRange copies at most remain bytes of data from src to dst, using +// the copy_file_range system call. dst and src must refer to regular files. +func CopyFileRange(dst, src *FD, remain int64) (written int64, handled bool, err error) { + if !supportCopyFileRange() { + return 0, false, nil + } + + for remain > 0 { + max := min(remain, maxCopyFileRangeRound) + n, e := copyFileRange(dst, src, int(max)) + if n > 0 { + remain -= n + written += n + } + handled, err = handleCopyFileRangeErr(e, n, written) + if n == 0 || !handled || err != nil { + return + } + } + + return written, true, nil +} + +// copyFileRange performs one round of copy_file_range(2). +func copyFileRange(dst, src *FD, max int) (written int64, err error) { + // For Linux, the signature of copy_file_range(2) is: + // + // ssize_t copy_file_range(int fd_in, loff_t *off_in, + // int fd_out, loff_t *off_out, + // size_t len, unsigned int flags); + // + // For FreeBSD, the signature of copy_file_range(2) is: + // + // ssize_t + // copy_file_range(int infd, off_t *inoffp, int outfd, off_t *outoffp, + // size_t len, unsigned int flags); + // + // Note that in the call to unix.CopyFileRange below, we use nil + // values for off_in/off_out and inoffp/outoffp, which means "the file + // offset for infd(fd_in) or outfd(fd_out) respectively will be used and + // updated by the number of bytes copied". + // + // That is why we must acquire locks for both file descriptors (and why + // this whole machinery is in the internal/poll package to begin with). + if err := dst.writeLock(); err != nil { + return 0, err + } + defer dst.writeUnlock() + if err := src.readLock(); err != nil { + return 0, err + } + defer src.readUnlock() + return ignoringEINTR2(func() (int64, error) { + n, err := unix.CopyFileRange(src.Sysfd, nil, dst.Sysfd, nil, max, 0) + return int64(n), err + }) +} diff --git a/go/src/internal/poll/errno_unix.go b/go/src/internal/poll/errno_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..d1a18abda4917a0a1a6d04b13c9e1dea0e7f2e99 --- /dev/null +++ b/go/src/internal/poll/errno_unix.go @@ -0,0 +1,33 @@ +// 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 unix || wasip1 + +package poll + +import "syscall" + +// Do the interface allocations only once for common +// Errno values. +var ( + errEAGAIN error = syscall.EAGAIN + errEINVAL error = syscall.EINVAL + errENOENT error = syscall.ENOENT +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return nil + case syscall.EAGAIN: + return errEAGAIN + case syscall.EINVAL: + return errEINVAL + case syscall.ENOENT: + return errENOENT + } + return e +} diff --git a/go/src/internal/poll/errno_windows.go b/go/src/internal/poll/errno_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..63814793fda8c3465a3f8c5ee3db74a81a267d4f --- /dev/null +++ b/go/src/internal/poll/errno_windows.go @@ -0,0 +1,31 @@ +// 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 windows + +package poll + +import "syscall" + +// Do the interface allocations only once for common +// Errno values. + +var ( + errERROR_IO_PENDING error = syscall.Errno(syscall.ERROR_IO_PENDING) +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return nil + case syscall.ERROR_IO_PENDING: + return errERROR_IO_PENDING + } + // TODO: add more here, after collecting data on the common + // error values see on Windows. (perhaps when running + // all.bat?) + return e +} diff --git a/go/src/internal/poll/error_linux_test.go b/go/src/internal/poll/error_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..059fb8eac9f8bccd8ac4ecde3557eb328fe37887 --- /dev/null +++ b/go/src/internal/poll/error_linux_test.go @@ -0,0 +1,31 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll_test + +import ( + "errors" + "internal/poll" + "os" + "syscall" +) + +func badStateFile() (*os.File, error) { + if os.Getuid() != 0 { + return nil, errors.New("must be root") + } + // Using OpenFile for a device file is an easy way to make a + // file attached to the runtime-integrated network poller and + // configured in halfway. + return os.OpenFile("/dev/net/tun", os.O_RDWR, 0) +} + +func isBadStateFileError(err error) (string, bool) { + switch err { + case poll.ErrNotPollable, syscall.EBADFD: + return "", true + default: + return "not pollable or file in bad state error", false + } +} diff --git a/go/src/internal/poll/error_stub_test.go b/go/src/internal/poll/error_stub_test.go new file mode 100644 index 0000000000000000000000000000000000000000..48e095254d38639c3f5c047cce701e901acb2643 --- /dev/null +++ b/go/src/internal/poll/error_stub_test.go @@ -0,0 +1,21 @@ +// 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 !linux + +package poll_test + +import ( + "errors" + "os" + "runtime" +) + +func badStateFile() (*os.File, error) { + return nil, errors.New("not supported on " + runtime.GOOS) +} + +func isBadStateFileError(err error) (string, bool) { + return "", false +} diff --git a/go/src/internal/poll/error_test.go b/go/src/internal/poll/error_test.go new file mode 100644 index 0000000000000000000000000000000000000000..abc8b1684f5aaa233117bf4eff6b75c380f2b70d --- /dev/null +++ b/go/src/internal/poll/error_test.go @@ -0,0 +1,51 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll_test + +import ( + "fmt" + "io/fs" + "net" + "os" + "testing" + "time" +) + +func TestReadError(t *testing.T) { + t.Run("ErrNotPollable", func(t *testing.T) { + f, err := badStateFile() + if err != nil { + t.Skip(err) + } + defer f.Close() + + // Give scheduler a chance to have two separated + // goroutines: an event poller and an event waiter. + time.Sleep(100 * time.Millisecond) + + var b [1]byte + _, err = f.Read(b[:]) + if perr := parseReadError(err, isBadStateFileError); perr != nil { + t.Fatal(perr) + } + }) +} + +func parseReadError(nestedErr error, verify func(error) (string, bool)) error { + err := nestedErr + if nerr, ok := err.(*net.OpError); ok { + err = nerr.Err + } + if nerr, ok := err.(*fs.PathError); ok { + err = nerr.Err + } + if nerr, ok := err.(*os.SyscallError); ok { + err = nerr.Err + } + if s, ok := verify(err); !ok { + return fmt.Errorf("got %v; want %s", nestedErr, s) + } + return nil +} diff --git a/go/src/internal/poll/export_linux_test.go b/go/src/internal/poll/export_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7fba79369740d2e8e6b0438872b3951f4ac5024e --- /dev/null +++ b/go/src/internal/poll/export_linux_test.go @@ -0,0 +1,22 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Export guts for testing on linux. +// Since testing imports os and os imports internal/poll, +// the internal/poll tests can not be in package poll. + +package poll + +var ( + GetPipe = getPipe + PutPipe = putPipe + NewPipe = newPipe + DestroyPipe = destroyPipe +) + +func GetPipeFds(p *SplicePipe) (int, int) { + return p.rfd, p.wfd +} + +type SplicePipe = splicePipe diff --git a/go/src/internal/poll/export_posix_test.go b/go/src/internal/poll/export_posix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3415ab383981797c471ff01492a9a44ee3aaee75 --- /dev/null +++ b/go/src/internal/poll/export_posix_test.go @@ -0,0 +1,15 @@ +// 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 || windows + +// Export guts for testing on posix. +// Since testing imports os and os imports internal/poll, +// the internal/poll tests can not be in package poll. + +package poll + +func (fd *FD) EOFError(n int, err error) error { + return fd.eofError(n, err) +} diff --git a/go/src/internal/poll/export_test.go b/go/src/internal/poll/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..66d7c3274bed638dbd53d670e6b602881d4f29e9 --- /dev/null +++ b/go/src/internal/poll/export_test.go @@ -0,0 +1,35 @@ +// 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. + +// Export guts for testing. +// Since testing imports os and os imports internal/poll, +// the internal/poll tests can not be in package poll. + +package poll + +var Consume = consume + +type XFDMutex struct { + fdMutex +} + +func (mu *XFDMutex) Incref() bool { + return mu.incref() +} + +func (mu *XFDMutex) IncrefAndClose() bool { + return mu.increfAndClose() +} + +func (mu *XFDMutex) Decref() bool { + return mu.decref() +} + +func (mu *XFDMutex) RWLock(read bool) bool { + return mu.rwlock(read) +} + +func (mu *XFDMutex) RWUnlock(read bool) bool { + return mu.rwunlock(read) +} diff --git a/go/src/internal/poll/fd.go b/go/src/internal/poll/fd.go new file mode 100644 index 0000000000000000000000000000000000000000..4e038d00ddab8b306924850849c04cf7e2f665bf --- /dev/null +++ b/go/src/internal/poll/fd.go @@ -0,0 +1,94 @@ +// 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 poll supports non-blocking I/O on file descriptors with polling. +// This supports I/O operations that block only a goroutine, not a thread. +// This is used by the net and os packages. +// It uses a poller built into the runtime, with support from the +// runtime scheduler. +package poll + +import ( + "errors" +) + +// errNetClosing is the type of the variable ErrNetClosing. +// This is used to implement the net.Error interface. +type errNetClosing struct{} + +// Error returns the error message for ErrNetClosing. +// Keep this string consistent because of issue #4373: +// since historically programs have not been able to detect +// this error, they look for the string. +func (e errNetClosing) Error() string { return "use of closed network connection" } + +func (e errNetClosing) Timeout() bool { return false } +func (e errNetClosing) Temporary() bool { return false } + +// ErrNetClosing is returned when a network descriptor is used after +// it has been closed. +var ErrNetClosing = errNetClosing{} + +// ErrFileClosing is returned when a file descriptor is used after it +// has been closed. +var ErrFileClosing = errors.New("use of closed file") + +// ErrNoDeadline is returned when a request is made to set a deadline +// on a file type that does not use the poller. +var ErrNoDeadline = errors.New("file type does not support deadline") + +// Return the appropriate closing error based on isFile. +func errClosing(isFile bool) error { + if isFile { + return ErrFileClosing + } + return ErrNetClosing +} + +// ErrDeadlineExceeded is returned for an expired deadline. +// This is exported by the os package as os.ErrDeadlineExceeded. +var ErrDeadlineExceeded error = &DeadlineExceededError{} + +// DeadlineExceededError is returned for an expired deadline. +type DeadlineExceededError struct{} + +// Implement the net.Error interface. +// The string is "i/o timeout" because that is what was returned +// by earlier Go versions. Changing it may break programs that +// match on error strings. +func (e *DeadlineExceededError) Error() string { return "i/o timeout" } +func (e *DeadlineExceededError) Timeout() bool { return true } +func (e *DeadlineExceededError) Temporary() bool { return true } + +// ErrNotPollable is returned when the file or socket is not suitable +// for event notification. +var ErrNotPollable = errors.New("not pollable") + +// consume removes data from a slice of byte slices, for writev. +func consume(v *[][]byte, n int64) { + for len(*v) > 0 { + ln0 := int64(len((*v)[0])) + if ln0 > n { + (*v)[0] = (*v)[0][n:] + return + } + n -= ln0 + (*v)[0] = nil + *v = (*v)[1:] + } +} + +// TestHookDidWritev is a hook for testing writev. +var TestHookDidWritev = func(wrote int) {} + +// String is an internal string definition for methods/functions +// that is not intended for use outside the standard libraries. +// +// Other packages in std that import internal/poll and have some +// exported APIs (now we've got some in net.rawConn) which are only used +// internally and are not intended to be used outside the standard libraries, +// Therefore, we make those APIs use internal types like poll.FD or poll.String +// in their function signatures to disable the usability of these APIs from +// external codebase. +type String string diff --git a/go/src/internal/poll/fd_fsync_darwin.go b/go/src/internal/poll/fd_fsync_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..e55b490d41a405e264c572d4d0c71807a3e1ffd9 --- /dev/null +++ b/go/src/internal/poll/fd_fsync_darwin.go @@ -0,0 +1,32 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll + +import ( + "errors" + "internal/syscall/unix" + "syscall" +) + +// Fsync invokes SYS_FCNTL with SYS_FULLFSYNC because +// on OS X, SYS_FSYNC doesn't fully flush contents to disk. +// See Issue #26650 as well as the man page for fsync on OS X. +func (fd *FD) Fsync() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + _, err := unix.Fcntl(fd.Sysfd, syscall.F_FULLFSYNC, 0) + + // There are scenarios such as SMB mounts where fcntl will fail + // with ENOTSUP. In those cases fallback to fsync. + // See #64215 + if err != nil && errors.Is(err, syscall.ENOTSUP) { + err = syscall.Fsync(fd.Sysfd) + } + return err + }) +} diff --git a/go/src/internal/poll/fd_fsync_posix.go b/go/src/internal/poll/fd_fsync_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..469ca75b628ca727fe845dd3383c7d95763ad3cc --- /dev/null +++ b/go/src/internal/poll/fd_fsync_posix.go @@ -0,0 +1,20 @@ +// 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 aix || dragonfly || freebsd || (js && wasm) || linux || netbsd || openbsd || solaris || wasip1 + +package poll + +import "syscall" + +// Fsync wraps syscall.Fsync. +func (fd *FD) Fsync() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return syscall.Fsync(fd.Sysfd) + }) +} diff --git a/go/src/internal/poll/fd_fsync_windows.go b/go/src/internal/poll/fd_fsync_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..fb1211985db2a76b3d6049fa47105a20902dce28 --- /dev/null +++ b/go/src/internal/poll/fd_fsync_windows.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. + +package poll + +import "syscall" + +// Fsync wraps syscall.Fsync. +func (fd *FD) Fsync() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.Fsync(fd.Sysfd) +} diff --git a/go/src/internal/poll/fd_io_plan9.go b/go/src/internal/poll/fd_io_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..ab9ae13eb45a89f3d128d4eb0fd408c0ad437db1 --- /dev/null +++ b/go/src/internal/poll/fd_io_plan9.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 poll + +import ( + "internal/strconv" + "runtime" + "sync" + "syscall" +) + +// asyncIO implements asynchronous cancelable I/O. +// An asyncIO represents a single asynchronous Read or Write +// operation. The result is returned on the result channel. +// The undergoing I/O system call can either complete or be +// interrupted by a note. +type asyncIO struct { + res chan result + + // mu guards the pid field. + mu sync.Mutex + + // pid holds the process id of + // the process running the IO operation. + pid int +} + +// result is the return value of a Read or Write operation. +type result struct { + n int + err error +} + +// newAsyncIO returns a new asyncIO that performs an I/O +// operation by calling fn, which must do one and only one +// interruptible system call. +func newAsyncIO(fn func([]byte) (int, error), b []byte) *asyncIO { + aio := &asyncIO{ + res: make(chan result, 0), + } + aio.mu.Lock() + go func() { + // Lock the current goroutine to its process + // and store the pid in io so that Cancel can + // interrupt it. We ignore the "hangup" signal, + // so the signal does not take down the entire + // Go runtime. + runtime.LockOSThread() + runtime_ignoreHangup() + aio.pid = syscall.Getpid() + aio.mu.Unlock() + + n, err := fn(b) + + aio.mu.Lock() + aio.pid = -1 + runtime_unignoreHangup() + aio.mu.Unlock() + + aio.res <- result{n, err} + }() + return aio +} + +// Cancel interrupts the I/O operation, causing +// the Wait function to return. +func (aio *asyncIO) Cancel() { + aio.mu.Lock() + defer aio.mu.Unlock() + if aio.pid == -1 { + return + } + f, e := syscall.Open("/proc/"+strconv.Itoa(aio.pid)+"/note", syscall.O_WRONLY) + if e != nil { + return + } + syscall.Write(f, []byte("hangup")) + syscall.Close(f) +} + +// Wait for the I/O operation to complete. +func (aio *asyncIO) Wait() (int, error) { + res := <-aio.res + return res.n, res.err +} + +// The following functions, provided by the runtime, are used to +// ignore and unignore the "hangup" signal received by the process. +func runtime_ignoreHangup() +func runtime_unignoreHangup() diff --git a/go/src/internal/poll/fd_mutex.go b/go/src/internal/poll/fd_mutex.go new file mode 100644 index 0000000000000000000000000000000000000000..f71c7739a1aa6e1a1eb1962264a9e00644b0a90a --- /dev/null +++ b/go/src/internal/poll/fd_mutex.go @@ -0,0 +1,276 @@ +// 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 poll + +import "sync/atomic" + +// fdMutex is a specialized synchronization primitive that manages +// lifetime of an fd and serializes access to Read, Write and Close +// methods on FD. +type fdMutex struct { + state uint64 + rsema uint32 + wsema uint32 +} + +// fdMutex.state is organized as follows: +// 1 bit - whether FD is closed, if set all subsequent lock operations will fail. +// 1 bit - lock for read operations. +// 1 bit - lock for write operations. +// 20 bits - total number of references (read+write+misc). +// 20 bits - number of outstanding read waiters. +// 20 bits - number of outstanding write waiters. +const ( + mutexClosed = 1 << 0 + mutexRLock = 1 << 1 + mutexWLock = 1 << 2 + mutexRef = 1 << 3 + mutexRefMask = (1<<20 - 1) << 3 + mutexRWait = 1 << 23 + mutexRMask = (1<<20 - 1) << 23 + mutexWWait = 1 << 43 + mutexWMask = (1<<20 - 1) << 43 +) + +const overflowMsg = "too many concurrent operations on a single file or socket (max 1048575)" + +// Read operations must do rwlock(true)/rwunlock(true). +// +// Write operations must do rwlock(false)/rwunlock(false). +// +// Misc operations must do incref/decref. +// Misc operations include functions like setsockopt and setDeadline. +// They need to use incref/decref to ensure that they operate on the +// correct fd in presence of a concurrent close call (otherwise fd can +// be closed under their feet). +// +// Close operations must do increfAndClose/decref. + +// incref adds a reference to mu. +// It reports whether mu is available for reading or writing. +func (mu *fdMutex) incref() bool { + for { + old := atomic.LoadUint64(&mu.state) + if old&mutexClosed != 0 { + return false + } + new := old + mutexRef + if new&mutexRefMask == 0 { + panic(overflowMsg) + } + if atomic.CompareAndSwapUint64(&mu.state, old, new) { + return true + } + } +} + +// increfAndClose sets the state of mu to closed. +// It returns false if the file was already closed. +func (mu *fdMutex) increfAndClose() bool { + for { + old := atomic.LoadUint64(&mu.state) + if old&mutexClosed != 0 { + return false + } + // Mark as closed and acquire a reference. + new := (old | mutexClosed) + mutexRef + if new&mutexRefMask == 0 { + panic(overflowMsg) + } + // Remove all read and write waiters. + new &^= mutexRMask | mutexWMask + if atomic.CompareAndSwapUint64(&mu.state, old, new) { + // Wake all read and write waiters, + // they will observe closed flag after wakeup. + for old&mutexRMask != 0 { + old -= mutexRWait + runtime_Semrelease(&mu.rsema) + } + for old&mutexWMask != 0 { + old -= mutexWWait + runtime_Semrelease(&mu.wsema) + } + return true + } + } +} + +// decref removes a reference from mu. +// It reports whether there is no remaining reference. +func (mu *fdMutex) decref() bool { + for { + old := atomic.LoadUint64(&mu.state) + if old&mutexRefMask == 0 { + panic("inconsistent poll.fdMutex") + } + new := old - mutexRef + if atomic.CompareAndSwapUint64(&mu.state, old, new) { + return new&(mutexClosed|mutexRefMask) == mutexClosed + } + } +} + +// lock adds a reference to mu and locks mu. +// It reports whether mu is available for reading or writing. +func (mu *fdMutex) rwlock(read bool) bool { + var mutexBit, mutexWait, mutexMask uint64 + var mutexSema *uint32 + if read { + mutexBit = mutexRLock + mutexWait = mutexRWait + mutexMask = mutexRMask + mutexSema = &mu.rsema + } else { + mutexBit = mutexWLock + mutexWait = mutexWWait + mutexMask = mutexWMask + mutexSema = &mu.wsema + } + for { + old := atomic.LoadUint64(&mu.state) + if old&mutexClosed != 0 { + return false + } + var new uint64 + if old&mutexBit == 0 { + // Lock is free, acquire it. + new = (old | mutexBit) + mutexRef + if new&mutexRefMask == 0 { + panic(overflowMsg) + } + } else { + // Wait for lock. + new = old + mutexWait + if new&mutexMask == 0 { + panic(overflowMsg) + } + } + if atomic.CompareAndSwapUint64(&mu.state, old, new) { + if old&mutexBit == 0 { + return true + } + runtime_Semacquire(mutexSema) + // The signaller has subtracted mutexWait. + } + } +} + +// unlock removes a reference from mu and unlocks mu. +// It reports whether there is no remaining reference. +func (mu *fdMutex) rwunlock(read bool) bool { + var mutexBit, mutexWait, mutexMask uint64 + var mutexSema *uint32 + if read { + mutexBit = mutexRLock + mutexWait = mutexRWait + mutexMask = mutexRMask + mutexSema = &mu.rsema + } else { + mutexBit = mutexWLock + mutexWait = mutexWWait + mutexMask = mutexWMask + mutexSema = &mu.wsema + } + for { + old := atomic.LoadUint64(&mu.state) + if old&mutexBit == 0 || old&mutexRefMask == 0 { + panic("inconsistent poll.fdMutex") + } + // Drop lock, drop reference and wake read waiter if present. + new := (old &^ mutexBit) - mutexRef + if old&mutexMask != 0 { + new -= mutexWait + } + if atomic.CompareAndSwapUint64(&mu.state, old, new) { + if old&mutexMask != 0 { + runtime_Semrelease(mutexSema) + } + return new&(mutexClosed|mutexRefMask) == mutexClosed + } + } +} + +// Implemented in runtime package. +func runtime_Semacquire(sema *uint32) +func runtime_Semrelease(sema *uint32) + +// incref adds a reference to fd. +// It returns an error when fd cannot be used. +func (fd *FD) incref() error { + if !fd.fdmu.incref() { + return errClosing(fd.isFile) + } + return nil +} + +// decref removes a reference from fd. +// It also closes fd when the state of fd is set to closed and there +// is no remaining reference. +func (fd *FD) decref() error { + if fd.fdmu.decref() { + return fd.destroy() + } + return nil +} + +// readLock adds a reference to fd and locks fd for reading. +// It returns an error when fd cannot be used for reading. +func (fd *FD) readLock() error { + if !fd.fdmu.rwlock(true) { + return errClosing(fd.isFile) + } + return nil +} + +// readUnlock removes a reference from fd and unlocks fd for reading. +// It also closes fd when the state of fd is set to closed and there +// is no remaining reference. +func (fd *FD) readUnlock() { + if fd.fdmu.rwunlock(true) { + fd.destroy() + } +} + +// writeLock adds a reference to fd and locks fd for writing. +// It returns an error when fd cannot be used for writing. +func (fd *FD) writeLock() error { + if !fd.fdmu.rwlock(false) { + return errClosing(fd.isFile) + } + return nil +} + +// writeUnlock removes a reference from fd and unlocks fd for writing. +// It also closes fd when the state of fd is set to closed and there +// is no remaining reference. +func (fd *FD) writeUnlock() { + if fd.fdmu.rwunlock(false) { + fd.destroy() + } +} + +// readWriteLock adds a reference to fd and locks fd for reading and writing. +// It returns an error when fd cannot be used for reading and writing. +func (fd *FD) readWriteLock() error { + if !fd.fdmu.rwlock(true) || !fd.fdmu.rwlock(false) { + return errClosing(fd.isFile) + } + return nil +} + +// readWriteUnlock removes a reference from fd and unlocks fd for reading and writing. +// It also closes fd when the state of fd is set to closed and there +// is no remaining reference. +func (fd *FD) readWriteUnlock() { + fd.fdmu.rwunlock(true) + if fd.fdmu.rwunlock(false) { + fd.destroy() + } +} + +// closing returns true if fd is closing. +func (fd *FD) closing() bool { + return atomic.LoadUint64(&fd.fdmu.state)&mutexClosed != 0 +} diff --git a/go/src/internal/poll/fd_mutex_test.go b/go/src/internal/poll/fd_mutex_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62f953192d751eeae80fc819443d5b8b8dc60d61 --- /dev/null +++ b/go/src/internal/poll/fd_mutex_test.go @@ -0,0 +1,222 @@ +// 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 poll_test + +import ( + . "internal/poll" + "math/rand" + "runtime" + "strings" + "testing" + "time" +) + +func TestMutexLock(t *testing.T) { + var mu XFDMutex + + if !mu.Incref() { + t.Fatal("broken") + } + if mu.Decref() { + t.Fatal("broken") + } + + if !mu.RWLock(true) { + t.Fatal("broken") + } + if mu.RWUnlock(true) { + t.Fatal("broken") + } + + if !mu.RWLock(false) { + t.Fatal("broken") + } + if mu.RWUnlock(false) { + t.Fatal("broken") + } +} + +func TestMutexClose(t *testing.T) { + var mu XFDMutex + if !mu.IncrefAndClose() { + t.Fatal("broken") + } + + if mu.Incref() { + t.Fatal("broken") + } + if mu.RWLock(true) { + t.Fatal("broken") + } + if mu.RWLock(false) { + t.Fatal("broken") + } + if mu.IncrefAndClose() { + t.Fatal("broken") + } +} + +func TestMutexCloseUnblock(t *testing.T) { + c := make(chan bool, 4) + var mu XFDMutex + mu.RWLock(true) + for i := 0; i < 4; i++ { + go func() { + if mu.RWLock(true) { + t.Error("broken") + return + } + c <- true + }() + } + // Concurrent goroutines must not be able to read lock the mutex. + time.Sleep(time.Millisecond) + select { + case <-c: + t.Fatal("broken") + default: + } + mu.IncrefAndClose() // Must unblock the readers. + for i := 0; i < 4; i++ { + select { + case <-c: + case <-time.After(10 * time.Second): + t.Fatal("broken") + } + } + if mu.Decref() { + t.Fatal("broken") + } + if !mu.RWUnlock(true) { + t.Fatal("broken") + } +} + +func TestMutexPanic(t *testing.T) { + ensurePanics := func(f func()) { + defer func() { + if recover() == nil { + t.Fatal("does not panic") + } + }() + f() + } + + var mu XFDMutex + ensurePanics(func() { mu.Decref() }) + ensurePanics(func() { mu.RWUnlock(true) }) + ensurePanics(func() { mu.RWUnlock(false) }) + + ensurePanics(func() { mu.Incref(); mu.Decref(); mu.Decref() }) + ensurePanics(func() { mu.RWLock(true); mu.RWUnlock(true); mu.RWUnlock(true) }) + ensurePanics(func() { mu.RWLock(false); mu.RWUnlock(false); mu.RWUnlock(false) }) + + // ensure that it's still not broken + mu.Incref() + mu.Decref() + mu.RWLock(true) + mu.RWUnlock(true) + mu.RWLock(false) + mu.RWUnlock(false) +} + +func TestMutexOverflowPanic(t *testing.T) { + defer func() { + r := recover() + if r == nil { + t.Fatal("did not panic") + } + msg, ok := r.(string) + if !ok { + t.Fatalf("unexpected panic type %T", r) + } + if !strings.Contains(msg, "too many") || strings.Contains(msg, "inconsistent") { + t.Fatalf("wrong panic message %q", msg) + } + }() + + var mu1 XFDMutex + for i := 0; i < 1<<21; i++ { + mu1.Incref() + } +} + +func TestMutexStress(t *testing.T) { + P := 8 + N := int(1e6) + if testing.Short() { + P = 4 + N = 1e4 + } + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(P)) + done := make(chan bool, P) + var mu XFDMutex + var readState [2]uint64 + var writeState [2]uint64 + for p := 0; p < P; p++ { + go func() { + defer func() { + done <- !t.Failed() + }() + r := rand.New(rand.NewSource(rand.Int63())) + for i := 0; i < N; i++ { + switch r.Intn(3) { + case 0: + if !mu.Incref() { + t.Error("broken") + return + } + if mu.Decref() { + t.Error("broken") + return + } + case 1: + if !mu.RWLock(true) { + t.Error("broken") + return + } + // Ensure that it provides mutual exclusion for readers. + if readState[0] != readState[1] { + t.Error("broken") + return + } + readState[0]++ + readState[1]++ + if mu.RWUnlock(true) { + t.Error("broken") + return + } + case 2: + if !mu.RWLock(false) { + t.Error("broken") + return + } + // Ensure that it provides mutual exclusion for writers. + if writeState[0] != writeState[1] { + t.Error("broken") + return + } + writeState[0]++ + writeState[1]++ + if mu.RWUnlock(false) { + t.Error("broken") + return + } + } + } + }() + } + for p := 0; p < P; p++ { + if !<-done { + t.FailNow() + } + } + if !mu.IncrefAndClose() { + t.Fatal("broken") + } + if !mu.Decref() { + t.Fatal("broken") + } +} diff --git a/go/src/internal/poll/fd_opendir_darwin.go b/go/src/internal/poll/fd_opendir_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..3ae2dc8448215e2b8a24d92ac4030ffaba677e98 --- /dev/null +++ b/go/src/internal/poll/fd_opendir_darwin.go @@ -0,0 +1,39 @@ +// 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 poll + +import ( + "syscall" + _ "unsafe" // for go:linkname +) + +// OpenDir returns a pointer to a DIR structure suitable for +// ReadDir. In case of an error, the name of the failed +// syscall is returned along with a syscall.Errno. +func (fd *FD) OpenDir() (uintptr, string, error) { + // fdopendir(3) takes control of the file descriptor, + // so use a dup. + fd2, call, err := fd.Dup() + if err != nil { + return 0, call, err + } + var dir uintptr + for { + dir, err = fdopendir(fd2) + if err != syscall.EINTR { + break + } + } + if err != nil { + syscall.Close(fd2) + return 0, "fdopendir", err + } + return dir, "", nil +} + +// Implemented in syscall/syscall_darwin.go. +// +//go:linkname fdopendir syscall.fdopendir +func fdopendir(fd int) (dir uintptr, err error) diff --git a/go/src/internal/poll/fd_plan9.go b/go/src/internal/poll/fd_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..b65485200add69bf9d0ba5bb0ed891d6050e5a7f --- /dev/null +++ b/go/src/internal/poll/fd_plan9.go @@ -0,0 +1,245 @@ +// 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 poll + +import ( + "errors" + "internal/stringslite" + "io" + "sync" + "syscall" + "time" +) + +type FD struct { + // Lock sysfd and serialize access to Read and Write methods. + fdmu fdMutex + + Destroy func() + + // deadlines + rmu sync.Mutex + wmu sync.Mutex + raio *asyncIO + waio *asyncIO + rtimer *time.Timer + wtimer *time.Timer + rtimedout bool // set true when read deadline has been reached + wtimedout bool // set true when write deadline has been reached + + // Whether this is a normal file. + // On Plan 9 we do not use this package for ordinary files, + // so this is always false, but the field is present because + // shared code in fd_mutex.go checks it. + isFile bool +} + +// We need this to close out a file descriptor when it is unlocked, +// but the real implementation has to live in the net package because +// it uses os.File's. +func (fd *FD) destroy() error { + if fd.Destroy != nil { + fd.Destroy() + } + return nil +} + +// Close handles the locking for closing an FD. The real operation +// is in the net package. +func (fd *FD) Close() error { + if !fd.fdmu.increfAndClose() { + return errClosing(fd.isFile) + } + return nil +} + +// Read implements io.Reader. +func (fd *FD) Read(fn func([]byte) (int, error), b []byte) (int, error) { + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + if len(b) == 0 { + return 0, nil + } + fd.rmu.Lock() + if fd.rtimedout { + fd.rmu.Unlock() + return 0, ErrDeadlineExceeded + } + fd.raio = newAsyncIO(fn, b) + fd.rmu.Unlock() + n, err := fd.raio.Wait() + fd.raio = nil + if isHangup(err) { + err = io.EOF + } + if isInterrupted(err) { + err = ErrDeadlineExceeded + } + return n, err +} + +// Write implements io.Writer. +func (fd *FD) Write(fn func([]byte) (int, error), b []byte) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + fd.wmu.Lock() + if fd.wtimedout { + fd.wmu.Unlock() + return 0, ErrDeadlineExceeded + } + fd.waio = newAsyncIO(fn, b) + fd.wmu.Unlock() + n, err := fd.waio.Wait() + fd.waio = nil + if isInterrupted(err) { + err = ErrDeadlineExceeded + } + return n, err +} + +// SetDeadline sets the read and write deadlines associated with fd. +func (fd *FD) SetDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r'+'w') +} + +// SetReadDeadline sets the read deadline associated with fd. +func (fd *FD) SetReadDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r') +} + +// SetWriteDeadline sets the write deadline associated with fd. +func (fd *FD) SetWriteDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'w') +} + +func setDeadlineImpl(fd *FD, t time.Time, mode int) error { + d := t.Sub(time.Now()) + if mode == 'r' || mode == 'r'+'w' { + fd.rmu.Lock() + defer fd.rmu.Unlock() + if fd.rtimer != nil { + fd.rtimer.Stop() + fd.rtimer = nil + } + fd.rtimedout = false + } + if mode == 'w' || mode == 'r'+'w' { + fd.wmu.Lock() + defer fd.wmu.Unlock() + if fd.wtimer != nil { + fd.wtimer.Stop() + fd.wtimer = nil + } + fd.wtimedout = false + } + if !t.IsZero() && d > 0 { + // Interrupt I/O operation once timer has expired + if mode == 'r' || mode == 'r'+'w' { + var timer *time.Timer + timer = time.AfterFunc(d, func() { + fd.rmu.Lock() + defer fd.rmu.Unlock() + if fd.rtimer != timer { + // deadline was changed + return + } + fd.rtimedout = true + if fd.raio != nil { + fd.raio.Cancel() + } + }) + fd.rtimer = timer + } + if mode == 'w' || mode == 'r'+'w' { + var timer *time.Timer + timer = time.AfterFunc(d, func() { + fd.wmu.Lock() + defer fd.wmu.Unlock() + if fd.wtimer != timer { + // deadline was changed + return + } + fd.wtimedout = true + if fd.waio != nil { + fd.waio.Cancel() + } + }) + fd.wtimer = timer + } + } + if !t.IsZero() && d <= 0 { + // Interrupt current I/O operation + if mode == 'r' || mode == 'r'+'w' { + fd.rtimedout = true + if fd.raio != nil { + fd.raio.Cancel() + } + } + if mode == 'w' || mode == 'r'+'w' { + fd.wtimedout = true + if fd.waio != nil { + fd.waio.Cancel() + } + } + } + return nil +} + +// On Plan 9 only, expose the locking for the net code. + +// ReadLock wraps FD.readLock. +func (fd *FD) ReadLock() error { + return fd.readLock() +} + +// ReadUnlock wraps FD.readUnlock. +func (fd *FD) ReadUnlock() { + fd.readUnlock() +} + +func isHangup(err error) bool { + return err != nil && stringslite.HasSuffix(err.Error(), "Hangup") +} + +func isInterrupted(err error) bool { + return err != nil && stringslite.HasSuffix(err.Error(), "interrupted") +} + +// IsPollDescriptor reports whether fd is the descriptor being used by the poller. +// This is only used for testing. +func IsPollDescriptor(fd uintptr) bool { + return false +} + +// RawControl invokes the user-defined function f for a non-IO +// operation. +func (fd *FD) RawControl(f func(uintptr)) error { + return errors.New("not implemented") +} + +// RawRead invokes the user-defined function f for a read operation. +func (fd *FD) RawRead(f func(uintptr) bool) error { + return errors.New("not implemented") +} + +// RawWrite invokes the user-defined function f for a write operation. +func (fd *FD) RawWrite(f func(uintptr) bool) error { + return errors.New("not implemented") +} + +func DupCloseOnExec(fd int) (int, string, error) { + nfd, err := syscall.Dup(int(fd), -1) + if err != nil { + return 0, "dup", err + } + // Plan9 has no syscall.CloseOnExec but + // its forkAndExecInChild closes all fds + // not related to the fork+exec. + return nfd, "", nil +} diff --git a/go/src/internal/poll/fd_poll_js.go b/go/src/internal/poll/fd_poll_js.go new file mode 100644 index 0000000000000000000000000000000000000000..fe5e73a149f6508a03aadbcd5e2e52562dfd635f --- /dev/null +++ b/go/src/internal/poll/fd_poll_js.go @@ -0,0 +1,99 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm + +package poll + +import ( + "syscall" + "time" +) + +type pollDesc struct { + fd *FD + closing bool +} + +func (pd *pollDesc) init(fd *FD) error { pd.fd = fd; return nil } + +func (pd *pollDesc) close() {} + +func (pd *pollDesc) evict() { + pd.closing = true + if pd.fd != nil { + syscall.StopIO(pd.fd.Sysfd) + } +} + +func (pd *pollDesc) prepare(mode int, isFile bool) error { + if pd.closing { + return errClosing(isFile) + } + return nil +} + +func (pd *pollDesc) prepareRead(isFile bool) error { return pd.prepare('r', isFile) } + +func (pd *pollDesc) prepareWrite(isFile bool) error { return pd.prepare('w', isFile) } + +func (pd *pollDesc) wait(mode int, isFile bool) error { + if pd.closing { + return errClosing(isFile) + } + if isFile { // TODO(neelance): js/wasm: Use callbacks from JS to block until the read/write finished. + return nil + } + return ErrDeadlineExceeded +} + +func (pd *pollDesc) waitRead(isFile bool) error { return pd.wait('r', isFile) } + +func (pd *pollDesc) waitWrite(isFile bool) error { return pd.wait('w', isFile) } + +func (pd *pollDesc) waitCanceled(mode int) {} + +func (pd *pollDesc) pollable() bool { return true } + +// SetDeadline sets the read and write deadlines associated with fd. +func (fd *FD) SetDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r'+'w') +} + +// SetReadDeadline sets the read deadline associated with fd. +func (fd *FD) SetReadDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r') +} + +// SetWriteDeadline sets the write deadline associated with fd. +func (fd *FD) SetWriteDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'w') +} + +func setDeadlineImpl(fd *FD, t time.Time, mode int) error { + d := t.UnixNano() + if t.IsZero() { + d = 0 + } + if err := fd.incref(); err != nil { + return err + } + switch mode { + case 'r': + syscall.SetReadDeadline(fd.Sysfd, d) + case 'w': + syscall.SetWriteDeadline(fd.Sysfd, d) + case 'r' + 'w': + syscall.SetReadDeadline(fd.Sysfd, d) + syscall.SetWriteDeadline(fd.Sysfd, d) + } + fd.decref() + return nil +} + +// IsPollDescriptor reports whether fd is the descriptor being used by the poller. +// This is only used for testing. +func IsPollDescriptor(fd uintptr) bool { + return false +} diff --git a/go/src/internal/poll/fd_poll_runtime.go b/go/src/internal/poll/fd_poll_runtime.go new file mode 100644 index 0000000000000000000000000000000000000000..2aef11243ad34e386e78ff28d5ee801105e6ca0b --- /dev/null +++ b/go/src/internal/poll/fd_poll_runtime.go @@ -0,0 +1,180 @@ +// 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 || windows || wasip1 + +package poll + +import ( + "errors" + "sync" + "syscall" + "time" + _ "unsafe" // for go:linkname +) + +// runtimeNano returns the current value of the runtime clock in nanoseconds. +// +//go:linkname runtimeNano runtime.nanotime +func runtimeNano() int64 + +func runtime_pollServerInit() +func runtime_pollOpen(fd uintptr) (uintptr, int) +func runtime_pollClose(ctx uintptr) +func runtime_pollWait(ctx uintptr, mode int) int +func runtime_pollWaitCanceled(ctx uintptr, mode int) +func runtime_pollReset(ctx uintptr, mode int) int +func runtime_pollSetDeadline(ctx uintptr, d int64, mode int) +func runtime_pollUnblock(ctx uintptr) +func runtime_isPollServerDescriptor(fd uintptr) bool + +type pollDesc struct { + runtimeCtx uintptr +} + +var serverInit sync.Once + +func (pd *pollDesc) init(fd *FD) error { + serverInit.Do(runtime_pollServerInit) + ctx, errno := runtime_pollOpen(uintptr(fd.Sysfd)) + if errno != 0 { + return errnoErr(syscall.Errno(errno)) + } + pd.runtimeCtx = ctx + return nil +} + +func (pd *pollDesc) close() { + if pd.runtimeCtx == 0 { + return + } + runtime_pollClose(pd.runtimeCtx) + pd.runtimeCtx = 0 +} + +// Evict evicts fd from the pending list, unblocking any I/O running on fd. +func (pd *pollDesc) evict() { + if pd.runtimeCtx == 0 { + return + } + runtime_pollUnblock(pd.runtimeCtx) +} + +func (pd *pollDesc) prepare(mode int, isFile bool) error { + if pd.runtimeCtx == 0 { + return nil + } + res := runtime_pollReset(pd.runtimeCtx, mode) + return convertErr(res, isFile) +} + +func (pd *pollDesc) prepareRead(isFile bool) error { + return pd.prepare('r', isFile) +} + +func (pd *pollDesc) prepareWrite(isFile bool) error { + return pd.prepare('w', isFile) +} + +func (pd *pollDesc) wait(mode int, isFile bool) error { + if pd.runtimeCtx == 0 { + return errors.New("waiting for unsupported file type") + } + res := runtime_pollWait(pd.runtimeCtx, mode) + return convertErr(res, isFile) +} + +func (pd *pollDesc) waitRead(isFile bool) error { + return pd.wait('r', isFile) +} + +func (pd *pollDesc) waitWrite(isFile bool) error { + return pd.wait('w', isFile) +} + +func (pd *pollDesc) waitCanceled(mode int) { + if pd.runtimeCtx == 0 { + return + } + runtime_pollWaitCanceled(pd.runtimeCtx, mode) +} + +func (pd *pollDesc) pollable() bool { + return pd.runtimeCtx != 0 +} + +// Error values returned by runtime_pollReset and runtime_pollWait. +// These must match the values in runtime/netpoll.go. +const ( + pollNoError = 0 + pollErrClosing = 1 + pollErrTimeout = 2 + pollErrNotPollable = 3 +) + +func convertErr(res int, isFile bool) error { + switch res { + case pollNoError: + return nil + case pollErrClosing: + return errClosing(isFile) + case pollErrTimeout: + return ErrDeadlineExceeded + case pollErrNotPollable: + return ErrNotPollable + } + println("unreachable: ", res) + panic("unreachable") +} + +// SetDeadline sets the read and write deadlines associated with fd. +func (fd *FD) SetDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r'+'w') +} + +// SetReadDeadline sets the read deadline associated with fd. +func (fd *FD) SetReadDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'r') +} + +// SetWriteDeadline sets the write deadline associated with fd. +func (fd *FD) SetWriteDeadline(t time.Time) error { + return setDeadlineImpl(fd, t, 'w') +} + +func setDeadlineImpl(fd *FD, t time.Time, mode int) error { + var d int64 + if !t.IsZero() { + d = int64(time.Until(t)) + if d == 0 { + d = -1 // don't confuse deadline right now with no deadline + } + } + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + + if fd.pd.runtimeCtx == 0 { + return ErrNoDeadline + } + runtime_pollSetDeadline(fd.pd.runtimeCtx, d, mode) + return nil +} + +// IsPollDescriptor reports whether fd is the descriptor being used by the poller. +// This is only used for testing. +// +// IsPollDescriptor should be an internal detail, +// but widely used packages access it using linkname. +// Notable members of the hall of shame include: +// - github.com/opencontainers/runc +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname IsPollDescriptor +func IsPollDescriptor(fd uintptr) bool { + return runtime_isPollServerDescriptor(fd) +} diff --git a/go/src/internal/poll/fd_posix.go b/go/src/internal/poll/fd_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..12f138644b38afa2bc083b2312ee54f97ea002c4 --- /dev/null +++ b/go/src/internal/poll/fd_posix.go @@ -0,0 +1,89 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || (js && wasm) || wasip1 || windows + +package poll + +import ( + "io" + "syscall" +) + +// eofError returns io.EOF when fd is available for reading end of +// file. +func (fd *FD) eofError(n int, err error) error { + if n == 0 && err == nil && fd.ZeroReadIsEOF { + return io.EOF + } + return err +} + +// Shutdown wraps syscall.Shutdown. +func (fd *FD) Shutdown(how int) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.Shutdown(fd.Sysfd, how) +} + +// Fchown wraps syscall.Fchown. +func (fd *FD) Fchown(uid, gid int) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return syscall.Fchown(fd.Sysfd, uid, gid) + }) +} + +// Ftruncate wraps syscall.Ftruncate. +func (fd *FD) Ftruncate(size int64) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return syscall.Ftruncate(fd.Sysfd, size) + }) +} + +// RawControl invokes the user-defined function f for a non-IO +// operation. +func (fd *FD) RawControl(f func(uintptr)) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + f(uintptr(fd.Sysfd)) + return nil +} + +// ignoringEINTR makes a function call and repeats it if it returns +// an EINTR error. This appears to be required even though we install all +// signal handlers with SA_RESTART: see #22838, #38033, #38836, #40846. +// Also #20400 and #36644 are issues in which a signal handler is +// installed without setting SA_RESTART. None of these are the common case, +// but there are enough of them that it seems that we can't avoid +// an EINTR loop. +func ignoringEINTR(fn func() error) error { + for { + err := fn() + if err != syscall.EINTR { + return err + } + } +} + +// ignoringEINTR2 is ignoringEINTR, but returning an additional value. +func ignoringEINTR2[T any](fn func() (T, error)) (T, error) { + for { + v, err := fn() + if err != syscall.EINTR { + return v, err + } + } +} diff --git a/go/src/internal/poll/fd_posix_test.go b/go/src/internal/poll/fd_posix_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b97e46595a5cc125ab95eed6398f554a2aa49ea1 --- /dev/null +++ b/go/src/internal/poll/fd_posix_test.go @@ -0,0 +1,43 @@ +// 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. + +//go:build unix || windows + +package poll_test + +import ( + . "internal/poll" + "io" + "testing" +) + +var eofErrorTests = []struct { + n int + err error + fd *FD + expected error +}{ + {100, nil, &FD{ZeroReadIsEOF: true}, nil}, + {100, io.EOF, &FD{ZeroReadIsEOF: true}, io.EOF}, + {100, ErrNetClosing, &FD{ZeroReadIsEOF: true}, ErrNetClosing}, + {0, nil, &FD{ZeroReadIsEOF: true}, io.EOF}, + {0, io.EOF, &FD{ZeroReadIsEOF: true}, io.EOF}, + {0, ErrNetClosing, &FD{ZeroReadIsEOF: true}, ErrNetClosing}, + + {100, nil, &FD{ZeroReadIsEOF: false}, nil}, + {100, io.EOF, &FD{ZeroReadIsEOF: false}, io.EOF}, + {100, ErrNetClosing, &FD{ZeroReadIsEOF: false}, ErrNetClosing}, + {0, nil, &FD{ZeroReadIsEOF: false}, nil}, + {0, io.EOF, &FD{ZeroReadIsEOF: false}, io.EOF}, + {0, ErrNetClosing, &FD{ZeroReadIsEOF: false}, ErrNetClosing}, +} + +func TestEOFError(t *testing.T) { + for _, tt := range eofErrorTests { + actual := tt.fd.EOFError(tt.n, tt.err) + if actual != tt.expected { + t.Errorf("eofError(%v, %v, %v): expected %v, actual %v", tt.n, tt.err, tt.fd.ZeroReadIsEOF, tt.expected, actual) + } + } +} diff --git a/go/src/internal/poll/fd_unix.go b/go/src/internal/poll/fd_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..f56173524d721cd7f2e68899061a8e31183811d0 --- /dev/null +++ b/go/src/internal/poll/fd_unix.go @@ -0,0 +1,743 @@ +// 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 && wasm) || wasip1 + +package poll + +import ( + "internal/strconv" + "internal/syscall/unix" + "io" + "sync/atomic" + "syscall" +) + +// FD is a file descriptor. The net and os packages use this type as a +// field of a larger type representing a network connection or OS file. +type FD struct { + // Lock sysfd and serialize access to Read and Write methods. + fdmu fdMutex + + // System file descriptor. Immutable until Close. + Sysfd int + + // Platform dependent state of the file descriptor. + SysFile + + // I/O poller. + pd pollDesc + + // Semaphore signaled when file is closed. + csema uint32 + + // Non-zero if this file has been set to blocking mode. + isBlocking uint32 + + // Whether this is a streaming descriptor, as opposed to a + // packet-based descriptor like a UDP socket. Immutable. + IsStream bool + + // Whether a zero byte read indicates EOF. This is false for a + // message based socket connection. + ZeroReadIsEOF bool + + // Whether this is a file rather than a network socket. + isFile bool +} + +// Init initializes the FD. The Sysfd field should already be set. +// This can be called multiple times on a single FD. +// The net argument is a network name from the net package (e.g., "tcp"), +// or "file". +// Set pollable to true if fd should be managed by runtime netpoll. +func (fd *FD) Init(net string, pollable bool) error { + fd.SysFile.init() + + // We don't actually care about the various network types. + if net == "file" { + fd.isFile = true + } + if !pollable { + fd.isBlocking = 1 + return nil + } + err := fd.pd.init(fd) + if err != nil { + // If we could not initialize the runtime poller, + // assume we are using blocking mode. + fd.isBlocking = 1 + } + return err +} + +// Destroy closes the file descriptor. This is called when there are +// no remaining references. +func (fd *FD) destroy() error { + // Poller may want to unregister fd in readiness notification mechanism, + // so this must be executed before CloseFunc. + fd.pd.close() + + err := fd.SysFile.destroy(fd.Sysfd) + + fd.Sysfd = -1 + runtime_Semrelease(&fd.csema) + return err +} + +// Close closes the FD. The underlying file descriptor is closed by the +// destroy method when there are no remaining references. +func (fd *FD) Close() error { + if !fd.fdmu.increfAndClose() { + return errClosing(fd.isFile) + } + + // Unblock any I/O. Once it all unblocks and returns, + // so that it cannot be referring to fd.sysfd anymore, + // the final decref will close fd.sysfd. This should happen + // fairly quickly, since all the I/O is non-blocking, and any + // attempts to block in the pollDesc will return errClosing(fd.isFile). + fd.pd.evict() + + // The call to decref will call destroy if there are no other + // references. + err := fd.decref() + + // Wait until the descriptor is closed. If this was the only + // reference, it is already closed. Only wait if the file has + // not been set to blocking mode, as otherwise any current I/O + // may be blocking, and that would block the Close. + // No need for an atomic read of isBlocking, increfAndClose means + // we have exclusive access to fd. + if fd.isBlocking == 0 { + runtime_Semacquire(&fd.csema) + } + + return err +} + +// SetBlocking puts the file into blocking mode. +func (fd *FD) SetBlocking() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + // Atomic store so that concurrent calls to SetBlocking + // do not cause a race condition. isBlocking only ever goes + // from 0 to 1 so there is no real race here. + atomic.StoreUint32(&fd.isBlocking, 1) + return syscall.SetNonblock(fd.Sysfd, false) +} + +// Darwin and FreeBSD can't read or write 2GB+ files at a time, +// even on 64-bit systems. +// The same is true of socket implementations on many systems. +// See golang.org/issue/7812 and golang.org/issue/16266. +// Use 1GB instead of, say, 2GB-1, to keep subsequent reads aligned. +const maxRW = 1 << 30 + +// Read implements io.Reader. +func (fd *FD) Read(p []byte) (int, error) { + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + if len(p) == 0 { + // If the caller wanted a zero byte read, return immediately + // without trying (but after acquiring the readLock). + // Otherwise syscall.Read returns 0, nil which looks like + // io.EOF. + // TODO(bradfitz): make it wait for readability? (Issue 15735) + return 0, nil + } + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, err + } + if fd.IsStream && len(p) > maxRW { + p = p[:maxRW] + } + for { + n, err := ignoringEINTRIO(syscall.Read, fd.Sysfd, p) + if err != nil { + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, err + } +} + +// Pread wraps the pread system call. +func (fd *FD) Pread(p []byte, off int64) (int, error) { + // Call incref, not readLock, because since pread specifies the + // offset it is independent from other reads. + // Similarly, using the poller doesn't make sense for pread. + if err := fd.incref(); err != nil { + return 0, err + } + if fd.IsStream && len(p) > maxRW { + p = p[:maxRW] + } + n, err := ignoringEINTR2(func() (int, error) { + return syscall.Pread(fd.Sysfd, p, off) + }) + if err != nil { + n = 0 + } + fd.decref() + err = fd.eofError(n, err) + return n, err +} + +// ReadFrom wraps the recvfrom network call. +func (fd *FD) ReadFrom(p []byte) (int, syscall.Sockaddr, error) { + if err := fd.readLock(); err != nil { + return 0, nil, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, nil, err + } + for { + n, sa, err := syscall.Recvfrom(fd.Sysfd, p, 0) + if err != nil { + if err == syscall.EINTR { + continue + } + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, sa, err + } +} + +// ReadFromInet4 wraps the recvfrom network call for IPv4. +func (fd *FD) ReadFromInet4(p []byte, from *syscall.SockaddrInet4) (int, error) { + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, err + } + for { + n, err := unix.RecvfromInet4(fd.Sysfd, p, 0, from) + if err != nil { + if err == syscall.EINTR { + continue + } + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, err + } +} + +// ReadFromInet6 wraps the recvfrom network call for IPv6. +func (fd *FD) ReadFromInet6(p []byte, from *syscall.SockaddrInet6) (int, error) { + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, err + } + for { + n, err := unix.RecvfromInet6(fd.Sysfd, p, 0, from) + if err != nil { + if err == syscall.EINTR { + continue + } + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, err + } +} + +// ReadMsg wraps the recvmsg network call. +func (fd *FD) ReadMsg(p []byte, oob []byte, flags int) (int, int, int, syscall.Sockaddr, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, nil, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, 0, 0, nil, err + } + for { + n, oobn, sysflags, sa, err := syscall.Recvmsg(fd.Sysfd, p, oob, flags) + if err != nil { + if err == syscall.EINTR { + continue + } + // TODO(dfc) should n and oobn be set to 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, oobn, sysflags, sa, err + } +} + +// ReadMsgInet4 is ReadMsg, but specialized for syscall.SockaddrInet4. +func (fd *FD) ReadMsgInet4(p []byte, oob []byte, flags int, sa4 *syscall.SockaddrInet4) (int, int, int, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, 0, 0, err + } + for { + n, oobn, sysflags, err := unix.RecvmsgInet4(fd.Sysfd, p, oob, flags, sa4) + if err != nil { + if err == syscall.EINTR { + continue + } + // TODO(dfc) should n and oobn be set to 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, oobn, sysflags, err + } +} + +// ReadMsgInet6 is ReadMsg, but specialized for syscall.SockaddrInet6. +func (fd *FD) ReadMsgInet6(p []byte, oob []byte, flags int, sa6 *syscall.SockaddrInet6) (int, int, int, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return 0, 0, 0, err + } + for { + n, oobn, sysflags, err := unix.RecvmsgInet6(fd.Sysfd, p, oob, flags, sa6) + if err != nil { + if err == syscall.EINTR { + continue + } + // TODO(dfc) should n and oobn be set to 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + err = fd.eofError(n, err) + return n, oobn, sysflags, err + } +} + +// Write implements io.Writer. +func (fd *FD) Write(p []byte) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, err + } + var nn int + for { + max := len(p) + if fd.IsStream && max-nn > maxRW { + max = nn + maxRW + } + n, err := ignoringEINTRIO(syscall.Write, fd.Sysfd, p[nn:max]) + if n > 0 { + if n > max-nn { + // This can reportedly happen when using + // some VPN software. Issue #61060. + // If we don't check this we will panic + // with slice bounds out of range. + // Use a more informative panic. + panic("invalid return from write: got " + strconv.Itoa(n) + " from a write of " + strconv.Itoa(max-nn)) + } + nn += n + } + if nn == len(p) { + return nn, err + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return nn, err + } + if n == 0 { + return nn, io.ErrUnexpectedEOF + } + } +} + +// Pwrite wraps the pwrite system call. +func (fd *FD) Pwrite(p []byte, off int64) (int, error) { + // Call incref, not writeLock, because since pwrite specifies the + // offset it is independent from other writes. + // Similarly, using the poller doesn't make sense for pwrite. + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + var nn int + for { + max := len(p) + if fd.IsStream && max-nn > maxRW { + max = nn + maxRW + } + n, err := syscall.Pwrite(fd.Sysfd, p[nn:max], off+int64(nn)) + if err == syscall.EINTR { + continue + } + if n > 0 { + nn += n + } + if nn == len(p) { + return nn, err + } + if err != nil { + return nn, err + } + if n == 0 { + return nn, io.ErrUnexpectedEOF + } + } +} + +// WriteToInet4 wraps the sendto network call for IPv4 addresses. +func (fd *FD) WriteToInet4(p []byte, sa *syscall.SockaddrInet4) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, err + } + for { + err := unix.SendtoInet4(fd.Sysfd, p, 0, sa) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return 0, err + } + return len(p), nil + } +} + +// WriteToInet6 wraps the sendto network call for IPv6 addresses. +func (fd *FD) WriteToInet6(p []byte, sa *syscall.SockaddrInet6) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, err + } + for { + err := unix.SendtoInet6(fd.Sysfd, p, 0, sa) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return 0, err + } + return len(p), nil + } +} + +// WriteTo wraps the sendto network call. +func (fd *FD) WriteTo(p []byte, sa syscall.Sockaddr) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, err + } + for { + err := syscall.Sendto(fd.Sysfd, p, 0, sa) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return 0, err + } + return len(p), nil + } +} + +// WriteMsg wraps the sendmsg network call. +func (fd *FD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (int, int, error) { + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, 0, err + } + for { + n, err := syscall.SendmsgN(fd.Sysfd, p, oob, sa, 0) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return n, 0, err + } + return n, len(oob), err + } +} + +// WriteMsgInet4 is WriteMsg specialized for syscall.SockaddrInet4. +func (fd *FD) WriteMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (int, int, error) { + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, 0, err + } + for { + n, err := unix.SendmsgNInet4(fd.Sysfd, p, oob, sa, 0) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return n, 0, err + } + return n, len(oob), err + } +} + +// WriteMsgInet6 is WriteMsg specialized for syscall.SockaddrInet6. +func (fd *FD) WriteMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (int, int, error) { + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, 0, err + } + for { + n, err := unix.SendmsgNInet6(fd.Sysfd, p, oob, sa, 0) + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + if err != nil { + return n, 0, err + } + return n, len(oob), err + } +} + +// Accept wraps the accept network call. +func (fd *FD) Accept() (int, syscall.Sockaddr, string, error) { + if err := fd.readLock(); err != nil { + return -1, nil, "", err + } + defer fd.readUnlock() + + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return -1, nil, "", err + } + for { + s, rsa, errcall, err := accept(fd.Sysfd) + if err == nil { + return s, rsa, "", err + } + switch err { + case syscall.EINTR: + continue + case syscall.EAGAIN: + if fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + case syscall.ECONNABORTED: + // This means that a socket on the listen + // queue was closed before we Accept()ed it; + // it's a silly error, so try again. + continue + } + return -1, nil, errcall, err + } +} + +// Fchmod wraps syscall.Fchmod. +func (fd *FD) Fchmod(mode uint32) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return syscall.Fchmod(fd.Sysfd, mode) + }) +} + +// Fstat wraps syscall.Fstat +func (fd *FD) Fstat(s *syscall.Stat_t) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return syscall.Fstat(fd.Sysfd, s) + }) +} + +// dupCloexecUnsupported indicates whether F_DUPFD_CLOEXEC is supported by the kernel. +var dupCloexecUnsupported atomic.Bool + +// DupCloseOnExec dups fd and marks it close-on-exec. +func DupCloseOnExec(fd int) (int, string, error) { + if syscall.F_DUPFD_CLOEXEC != 0 && !dupCloexecUnsupported.Load() { + r0, err := unix.Fcntl(fd, syscall.F_DUPFD_CLOEXEC, 0) + if err == nil { + return r0, "", nil + } + switch err { + case syscall.EINVAL, syscall.ENOSYS: + // Old kernel, or js/wasm (which returns + // ENOSYS). Fall back to the portable way from + // now on. + dupCloexecUnsupported.Store(true) + default: + return -1, "fcntl", err + } + } + return dupCloseOnExecOld(fd) +} + +// Dup duplicates the file descriptor. +func (fd *FD) Dup() (int, string, error) { + if err := fd.incref(); err != nil { + return -1, "", err + } + defer fd.decref() + return DupCloseOnExec(fd.Sysfd) +} + +// On Unix variants only, expose the IO event for the net code. + +// WaitWrite waits until data can be written to fd. +func (fd *FD) WaitWrite() error { + return fd.pd.waitWrite(fd.isFile) +} + +// WriteOnce is for testing only. It makes a single write call. +func (fd *FD) WriteOnce(p []byte) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + return ignoringEINTRIO(syscall.Write, fd.Sysfd, p) +} + +// RawRead invokes the user-defined function f for a read operation. +func (fd *FD) RawRead(f func(uintptr) bool) error { + if err := fd.readLock(); err != nil { + return err + } + defer fd.readUnlock() + if err := fd.pd.prepareRead(fd.isFile); err != nil { + return err + } + for { + if f(uintptr(fd.Sysfd)) { + return nil + } + if err := fd.pd.waitRead(fd.isFile); err != nil { + return err + } + } +} + +// RawWrite invokes the user-defined function f for a write operation. +func (fd *FD) RawWrite(f func(uintptr) bool) error { + if err := fd.writeLock(); err != nil { + return err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return err + } + for { + if f(uintptr(fd.Sysfd)) { + return nil + } + if err := fd.pd.waitWrite(fd.isFile); err != nil { + return err + } + } +} + +// ignoringEINTRIO is like ignoringEINTR, but just for IO calls. +func ignoringEINTRIO(fn func(fd int, p []byte) (int, error), fd int, p []byte) (int, error) { + for { + n, err := fn(fd, p) + if err != syscall.EINTR { + return n, err + } + } +} diff --git a/go/src/internal/poll/fd_unixjs.go b/go/src/internal/poll/fd_unixjs.go new file mode 100644 index 0000000000000000000000000000000000000000..090974d2b0d666d8145f15132ff743473897cec0 --- /dev/null +++ b/go/src/internal/poll/fd_unixjs.go @@ -0,0 +1,79 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || (js && wasm) + +package poll + +import "syscall" + +type SysFile struct { + // Writev cache. + iovecs *[]syscall.Iovec +} + +func (s *SysFile) init() {} + +func (s *SysFile) destroy(fd int) error { + // We don't use ignoringEINTR here because POSIX does not define + // whether the descriptor is closed if close returns EINTR. + // If the descriptor is indeed closed, using a loop would race + // with some other goroutine opening a new descriptor. + // (The Linux kernel guarantees that it is closed on an EINTR error.) + return CloseFunc(fd) +} + +// dupCloseOnExecOld is the traditional way to dup an fd and +// set its O_CLOEXEC bit, using two system calls. +func dupCloseOnExecOld(fd int) (int, string, error) { + syscall.ForkLock.RLock() + defer syscall.ForkLock.RUnlock() + newfd, err := syscall.Dup(fd) + if err != nil { + return -1, "dup", err + } + syscall.CloseOnExec(newfd) + return newfd, "", nil +} + +// Fchdir wraps syscall.Fchdir. +func (fd *FD) Fchdir() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.Fchdir(fd.Sysfd) +} + +// ReadDirent wraps syscall.ReadDirent. +// We treat this like an ordinary system call rather than a call +// that tries to fill the buffer. +func (fd *FD) ReadDirent(buf []byte) (int, error) { + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + for { + n, err := ignoringEINTRIO(syscall.ReadDirent, fd.Sysfd, buf) + if err != nil { + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + // Do not call eofError; caller does not expect to see io.EOF. + return n, err + } +} + +// Seek wraps syscall.Seek. +func (fd *FD) Seek(offset int64, whence int) (int64, error) { + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + return syscall.Seek(fd.Sysfd, offset, whence) +} diff --git a/go/src/internal/poll/fd_wasip1.go b/go/src/internal/poll/fd_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..4f83d287370c128a6dc9c426b0b9651caa777a84 --- /dev/null +++ b/go/src/internal/poll/fd_wasip1.go @@ -0,0 +1,236 @@ +// 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 poll + +import ( + "internal/byteorder" + "sync/atomic" + "syscall" + "unsafe" +) + +type SysFile struct { + // RefCountPtr is a pointer to the reference count of Sysfd. + // + // WASI preview 1 lacks a dup(2) system call. When the os and net packages + // need to share a file/socket, instead of duplicating the underlying file + // descriptor, we instead provide a way to copy FD instances and manage the + // underlying file descriptor with reference counting. + RefCountPtr *int32 + + // RefCount is the reference count of Sysfd. When a copy of an FD is made, + // it points to the reference count of the original FD instance. + RefCount int32 + + // Cache for the file type, lazily initialized when Seek is called. + Filetype uint32 + + // If the file represents a directory, this field contains the current + // readdir position. It is reset to zero if the program calls Seek(0, 0). + Dircookie uint64 + + // Absolute path of the file, as returned by syscall.PathOpen; + // this is used by Fchdir to emulate setting the current directory + // to an open file descriptor. + Path string + + // TODO(achille): it could be meaningful to move isFile from FD to a method + // on this struct type, and expose it as `IsFile() bool` which derives the + // result from the Filetype field. We would need to ensure that Filetype is + // always set instead of being lazily initialized. +} + +func (s *SysFile) init() { + if s.RefCountPtr == nil { + s.RefCount = 1 + s.RefCountPtr = &s.RefCount + } +} + +func (s *SysFile) ref() SysFile { + atomic.AddInt32(s.RefCountPtr, +1) + return SysFile{RefCountPtr: s.RefCountPtr} +} + +func (s *SysFile) destroy(fd int) error { + if s.RefCountPtr != nil && atomic.AddInt32(s.RefCountPtr, -1) > 0 { + return nil + } + + // We don't use ignoringEINTR here because POSIX does not define + // whether the descriptor is closed if close returns EINTR. + // If the descriptor is indeed closed, using a loop would race + // with some other goroutine opening a new descriptor. + // (The Linux kernel guarantees that it is closed on an EINTR error.) + return CloseFunc(fd) +} + +// Copy creates a copy of the FD. +// +// The FD instance points to the same underlying file descriptor. The file +// descriptor isn't closed until all FD instances that refer to it have been +// closed/destroyed. +func (fd *FD) Copy() FD { + return FD{ + Sysfd: fd.Sysfd, + SysFile: fd.SysFile.ref(), + IsStream: fd.IsStream, + ZeroReadIsEOF: fd.ZeroReadIsEOF, + isBlocking: fd.isBlocking, + isFile: fd.isFile, + } +} + +// dupCloseOnExecOld always errors on wasip1 because there is no mechanism to +// duplicate file descriptors. +func dupCloseOnExecOld(fd int) (int, string, error) { + return -1, "dup", syscall.ENOSYS +} + +// Fchdir wraps syscall.Fchdir. +func (fd *FD) Fchdir() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.Chdir(fd.Path) +} + +// ReadDir wraps syscall.ReadDir. +// We treat this like an ordinary system call rather than a call +// that tries to fill the buffer. +func (fd *FD) ReadDir(buf []byte, cookie syscall.Dircookie) (int, error) { + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + for { + n, err := syscall.ReadDir(fd.Sysfd, buf, cookie) + if err != nil { + n = 0 + if err == syscall.EAGAIN && fd.pd.pollable() { + if err = fd.pd.waitRead(fd.isFile); err == nil { + continue + } + } + } + // Do not call eofError; caller does not expect to see io.EOF. + return n, err + } +} + +func (fd *FD) ReadDirent(buf []byte) (int, error) { + n, err := fd.ReadDir(buf, fd.Dircookie) + if err != nil { + return 0, err + } + if n <= 0 { + return n, nil // EOF + } + + // We assume that the caller of ReadDirent will consume the entire buffer + // up to the last full entry, so we scan through the buffer looking for the + // value of the last next cookie. + b := buf[:n] + + for len(b) > 0 { + next, ok := direntNext(b) + if !ok { + break + } + size, ok := direntReclen(b) + if !ok { + break + } + if size > uint64(len(b)) { + break + } + fd.Dircookie = syscall.Dircookie(next) + b = b[size:] + } + + // Trim a potentially incomplete trailing entry; this is necessary because + // the code in src/os/dir_unix.go does not deal well with partial values in + // calls to direntReclen, etc... and ends up causing an early EOF before all + // directory entries were consumed. ReadDirent is called with a large enough + // buffer (8 KiB) that at least one entry should always fit, tho this seems + // a bit brittle but cannot be addressed without a large change of the + // algorithm in the os.(*File).readdir method. + return n - len(b), nil +} + +// Seek wraps syscall.Seek. +func (fd *FD) Seek(offset int64, whence int) (int64, error) { + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + // syscall.Filetype is a uint8 but we store it as a uint32 in SysFile in + // order to use atomic load/store on the field, which is why we have to + // perform this type conversion. + fileType := syscall.Filetype(atomic.LoadUint32(&fd.Filetype)) + + if fileType == syscall.FILETYPE_UNKNOWN { + var stat syscall.Stat_t + if err := fd.Fstat(&stat); err != nil { + return 0, err + } + fileType = stat.Filetype + atomic.StoreUint32(&fd.Filetype, uint32(fileType)) + } + + if fileType == syscall.FILETYPE_DIRECTORY { + // If the file descriptor is opened on a directory, we reset the readdir + // cookie when seeking back to the beginning to allow reusing the file + // descriptor to scan the directory again. + if offset == 0 && whence == 0 { + fd.Dircookie = 0 + return 0, nil + } else { + return 0, syscall.EINVAL + } + } + + return syscall.Seek(fd.Sysfd, offset, whence) +} + +// https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#-dirent-record +const sizeOfDirent = 24 + +func direntReclen(buf []byte) (uint64, bool) { + namelen, ok := direntNamlen(buf) + return sizeOfDirent + namelen, ok +} + +func direntNamlen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Namlen), unsafe.Sizeof(syscall.Dirent{}.Namlen)) +} + +func direntNext(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Next), unsafe.Sizeof(syscall.Dirent{}.Next)) +} + +// readInt returns the size-bytes unsigned integer in native byte order at offset off. +func readInt(b []byte, off, size uintptr) (u uint64, ok bool) { + if len(b) < int(off+size) { + return 0, false + } + return readIntLE(b[off:], size), true +} + +func readIntLE(b []byte, size uintptr) uint64 { + switch size { + case 1: + return uint64(b[0]) + case 2: + return uint64(byteorder.LEUint16(b)) + case 4: + return uint64(byteorder.LEUint32(b)) + case 8: + return uint64(byteorder.LEUint64(b)) + default: + panic("internal/poll: readInt with unsupported size") + } +} diff --git a/go/src/internal/poll/fd_windows.go b/go/src/internal/poll/fd_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..26319548e3c310090bc050b6d922fd61c0e46c9d --- /dev/null +++ b/go/src/internal/poll/fd_windows.go @@ -0,0 +1,1547 @@ +// 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 poll + +import ( + "errors" + "internal/race" + "internal/syscall/windows" + "io" + "runtime" + "sync" + "sync/atomic" + "syscall" + "unicode/utf16" + "unicode/utf8" + "unsafe" +) + +var ( + initErr error + ioSync uint64 +) + +// This package uses the SetFileCompletionNotificationModes Windows +// API to skip calling GetQueuedCompletionStatus if an IO operation +// completes synchronously. There is a known bug where +// SetFileCompletionNotificationModes crashes on some systems (see +// https://support.microsoft.com/kb/2568167 for details). + +var socketCanUseSetFileCompletionNotificationModes bool // determines is SetFileCompletionNotificationModes is present and sockets can safely use it + +// checkSetFileCompletionNotificationModes verifies that +// SetFileCompletionNotificationModes Windows API is present +// on the system and is safe to use. +// See https://support.microsoft.com/kb/2568167 for details. +func checkSetFileCompletionNotificationModes() { + err := syscall.LoadSetFileCompletionNotificationModes() + if err != nil { + return + } + protos := [2]int32{syscall.IPPROTO_TCP, 0} + var buf [32]syscall.WSAProtocolInfo + len := uint32(unsafe.Sizeof(buf)) + n, err := syscall.WSAEnumProtocols(&protos[0], &buf[0], &len) + if err != nil { + return + } + for i := int32(0); i < n; i++ { + if buf[i].ServiceFlags1&syscall.XP1_IFS_HANDLES == 0 { + return + } + } + socketCanUseSetFileCompletionNotificationModes = true +} + +// InitWSA initiates the use of the Winsock DLL by the current process. +// It is called from the net package at init time to avoid +// loading ws2_32.dll when net is not used. +var InitWSA = sync.OnceFunc(func() { + var d syscall.WSAData + e := syscall.WSAStartup(uint32(0x202), &d) + if e != nil { + initErr = e + } + checkSetFileCompletionNotificationModes() +}) + +// operation contains superset of data necessary to perform all async IO. +type operation struct { + // Used by IOCP interface, it must be first field + // of the struct, as our code relies on it. + o syscall.Overlapped + + // fields used by runtime.netpoll + runtimeCtx uintptr + mode int32 +} + +func (fd *FD) overlapped(o *operation) *syscall.Overlapped { + if fd.isBlocking { + // Don't return the overlapped object if the file handle + // doesn't use overlapped I/O. It could be used, but + // that would then use the file pointer stored in the + // overlapped object rather than the real file pointer. + return nil + } + return &o.o +} + +func newWsaBuf(b []byte) *syscall.WSABuf { + return &syscall.WSABuf{Buf: unsafe.SliceData(b), Len: uint32(len(b))} +} + +var wsaBufsPool = sync.Pool{ + New: func() any { + buf := make([]syscall.WSABuf, 0, 16) + return &buf + }, +} + +func newWSABufs(buf *[][]byte) *[]syscall.WSABuf { + bufsPtr := wsaBufsPool.Get().(*[]syscall.WSABuf) + *bufsPtr = (*bufsPtr)[:0] + for _, b := range *buf { + if len(b) == 0 { + *bufsPtr = append(*bufsPtr, syscall.WSABuf{}) + continue + } + for len(b) > maxRW { + *bufsPtr = append(*bufsPtr, syscall.WSABuf{Len: maxRW, Buf: &b[0]}) + b = b[maxRW:] + } + if len(b) > 0 { + *bufsPtr = append(*bufsPtr, syscall.WSABuf{Len: uint32(len(b)), Buf: &b[0]}) + } + } + return bufsPtr +} + +func freeWSABufs(bufsPtr *[]syscall.WSABuf) { + // Clear pointers to buffers so they can be released by garbage collector. + bufs := *bufsPtr + for i := range bufs { + bufs[i].Buf = nil + } + // 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(*bufsPtr) > 128 { + *bufsPtr = nil + } + wsaBufsPool.Put(bufsPtr) +} + +// wsaMsgPool is a pool of WSAMsg structures that can only hold a single WSABuf. +var wsaMsgPool = sync.Pool{ + New: func() any { + return &windows.WSAMsg{ + Buffers: &syscall.WSABuf{}, + BufferCount: 1, + } + }, +} + +// newWSAMsg creates a new WSAMsg with the provided parameters. +// Use [freeWSAMsg] to free it. +func newWSAMsg(p []byte, oob []byte, flags int, rsa *wsaRsa) *windows.WSAMsg { + // The returned object can't be allocated in the stack because it is accessed asynchronously + // by Windows in between several system calls. If the stack frame is moved while that happens, + // then Windows may access invalid memory. + // TODO(qmuntal): investigate using runtime.Pinner keeping this path allocation-free. + + // Use a pool to reuse allocations. + msg := wsaMsgPool.Get().(*windows.WSAMsg) + msg.Buffers.Len = uint32(len(p)) + msg.Buffers.Buf = unsafe.SliceData(p) + if len(oob) > 0 { + msg.Control = syscall.WSABuf{ + Len: uint32(len(oob)), + Buf: unsafe.SliceData(oob), + } + } + msg.Flags = uint32(flags) + if rsa != nil { + msg.Name = &rsa.name + msg.Namelen = rsa.namelen + } + return msg +} + +func freeWSAMsg(msg *windows.WSAMsg) { + // Clear pointers to buffers so they can be released by garbage collector. + msg.Name = nil + msg.Namelen = 0 + msg.Buffers.Len = 0 + msg.Buffers.Buf = nil + msg.Control.Len = 0 + msg.Control.Buf = nil + wsaMsgPool.Put(msg) +} + +// wsaRsa bundles a [syscall.RawSockaddrAny] with its length for efficient caching. +// +// When used by WSARecvFrom, wsaRsa must be on the heap. See +// https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecvfrom. +type wsaRsa struct { + name syscall.RawSockaddrAny + namelen int32 +} + +var wsaRsaPool = sync.Pool{ + New: func() any { + return new(wsaRsa) + }, +} + +func newWSARsa() *wsaRsa { + rsa := wsaRsaPool.Get().(*wsaRsa) + rsa.name = syscall.RawSockaddrAny{} + rsa.namelen = int32(unsafe.Sizeof(syscall.RawSockaddrAny{})) + return rsa +} + +var operationPool = sync.Pool{ + New: func() any { + return new(operation) + }, +} + +// waitIO waits for the IO operation o to complete. +func (fd *FD) waitIO(o *operation) error { + if fd.isBlocking { + panic("can't wait on blocking operations") + } + if !fd.pollable() { + // The overlapped handle is not added to the runtime poller, + // the only way to wait for the IO to complete is block until + // the overlapped event is signaled. + _, err := syscall.WaitForSingleObject(o.o.HEvent, syscall.INFINITE) + return err + } + // Wait for our request to complete. + err := fd.pd.wait(int(o.mode), fd.isFile) + switch err { + case nil, ErrNetClosing, ErrFileClosing, ErrDeadlineExceeded: + // No other error is expected. + default: + panic("unexpected runtime.netpoll error: " + err.Error()) + } + return err +} + +// cancelIO cancels the IO operation o and waits for it to complete. +func (fd *FD) cancelIO(o *operation) { + if !fd.pollable() { + return + } + // Cancel our request. + err := syscall.CancelIoEx(fd.Sysfd, &o.o) + // Assuming ERROR_NOT_FOUND is returned, if IO is completed. + if err != nil && err != syscall.ERROR_NOT_FOUND { + // TODO(brainman): maybe do something else, but panic. + panic(err) + } + fd.pd.waitCanceled(int(o.mode)) +} + +// pin pins ptr for the duration of the IO operation. +// If fd is in blocking mode, pin does nothing. +func (fd *FD) pin(mode int, ptr any) { + if fd.isBlocking { + return + } + if mode == 'r' { + fd.readPinner.Pin(ptr) + } else { + fd.writePinner.Pin(ptr) + } +} + +// execIO executes a single IO operation o. +// It supports both synchronous and asynchronous IO. +func (fd *FD) execIO(mode int, submit func(o *operation) (uint32, error)) (int, error) { + if mode == 'r' { + defer fd.readPinner.Unpin() + } else { + defer fd.writePinner.Unpin() + } + // Notify runtime netpoll about starting IO. + err := fd.pd.prepare(mode, fd.isFile) + if err != nil { + return 0, err + } + o := operationPool.Get().(*operation) + defer operationPool.Put(o) + *o = operation{ + o: syscall.Overlapped{ + OffsetHigh: uint32(fd.offset >> 32), + Offset: uint32(fd.offset), + }, + runtimeCtx: fd.pd.runtimeCtx, + mode: int32(mode), + } + // Start IO. + if !fd.isBlocking && !fd.pollable() { + // If the handle is opened for overlapped IO but we can't + // use the runtime poller, then we need to use an + // event to wait for the IO to complete. + h, err := windows.CreateEvent(nil, 0, 0, nil) + if err != nil { + // This shouldn't happen when all CreateEvent arguments are zero. + panic(err) + } + // Set the low bit so that the external IOCP doesn't receive the completion packet. + o.o.HEvent = h | 1 + defer syscall.CloseHandle(h) + } + fd.pin(mode, o) + qty, err := submit(o) + var waitErr error + // Blocking operations shouldn't return ERROR_IO_PENDING. + // Continue without waiting if that happens. + if !fd.isBlocking && (err == syscall.ERROR_IO_PENDING || (err == nil && !fd.skipSyncNotif)) { + // IO started asynchronously or completed synchronously but + // a sync notification is required. Wait for it to complete. + waitErr = fd.waitIO(o) + if waitErr != nil { + // IO interrupted by "close" or "timeout". + fd.cancelIO(o) + // We issued a cancellation request, but the IO operation may still succeeded + // before the cancellation request runs. + } + if fd.isFile { + err = windows.GetOverlappedResult(fd.Sysfd, &o.o, &qty, false) + } else { + var flags uint32 + err = windows.WSAGetOverlappedResult(fd.Sysfd, &o.o, &qty, false, &flags) + } + } + switch err { + case syscall.ERROR_OPERATION_ABORTED: + // ERROR_OPERATION_ABORTED may have been caused by us. In that case, + // map it to our own error. Don't do more than that, each submitted + // function may have its own meaning for each error. + if waitErr != nil { + // IO canceled by the poller while waiting for completion. + err = waitErr + } else if fd.kind == kindPipe && fd.closing() { + // Close uses CancelIoEx to interrupt concurrent I/O for pipes. + // If the fd is a pipe and the Write was interrupted by CancelIoEx, + // we assume it is interrupted by Close. + err = errClosing(fd.isFile) + } + case windows.ERROR_IO_INCOMPLETE: + // waitIO couldn't wait for the IO to complete. + if waitErr != nil { + // The wait error will be more informative. + err = waitErr + } + } + return int(qty), err +} + +// FD is a file descriptor. The net and os packages embed this type in +// a larger type representing a network connection or OS file. +type FD struct { + // Lock sysfd and serialize access to Read and Write methods. + fdmu fdMutex + + // System file descriptor. Immutable until Close. + Sysfd syscall.Handle + + // I/O poller. + pd pollDesc + + // The file offset for the next read or write. + // Overlapped IO operations don't use the real file pointer, + // so we need to keep track of the offset ourselves. + offset int64 + + // For console I/O. + lastbits []byte // first few bytes of the last incomplete rune in last write + readuint16 []uint16 // buffer to hold uint16s obtained with ReadConsole + readbyte []byte // buffer to hold decoding of readuint16 from utf16 to utf8 + readbyteOffset int // readbyte[readOffset:] is yet to be consumed with file.Read + + // Semaphore signaled when file is closed. + csema uint32 + + skipSyncNotif bool + + // Whether this is a streaming descriptor, as opposed to a + // packet-based descriptor like a UDP socket. + IsStream bool + + // Whether a zero byte read indicates EOF. This is false for a + // message based socket connection. + ZeroReadIsEOF bool + + // Whether the handle is owned by os.File. + isFile bool + + // The kind of this file. + kind fileKind + + // Whether FILE_FLAG_OVERLAPPED was not set when opening the file. + isBlocking bool + + disassociated atomic.Bool + + // readPinner and writePinner are automatically unpinned + // before execIO returns. + readPinner runtime.Pinner + writePinner runtime.Pinner +} + +// setOffset sets the offset fields of the overlapped object +// to the given offset. The fd read/write lock must be held. +// +// Overlapped IO operations don't update the offset fields +// of the overlapped object nor the file pointer automatically, +// so we do that manually here. +// Note that this is a best effort that only works if the file +// pointer is completely owned by this operation. We could +// call seek to allow other processes or other operations on the +// same file to see the updated offset. That would be inefficient +// and won't work for concurrent operations anyway. If concurrent +// operations are needed, then the caller should serialize them +// using an external mechanism. +func (fd *FD) setOffset(off int64) { + fd.offset = off +} + +// addOffset adds the given offset to the current offset. +func (fd *FD) addOffset(off int) { + fd.setOffset(fd.offset + int64(off)) +} + +// pollable should be used instead of fd.pd.pollable(), +// as it is aware of the disassociated state. +func (fd *FD) pollable() bool { + return fd.pd.pollable() && !fd.disassociated.Load() +} + +// fileKind describes the kind of file. +type fileKind byte + +const ( + kindNet fileKind = iota + kindFile + kindConsole + kindPipe + kindFileNet +) + +// Init initializes the FD. The Sysfd field should already be set. +// This can be called multiple times on a single FD. +// The net argument is a network name from the net package (e.g., "tcp"), +// or "file" or "console" or "dir". +// Set pollable to true if fd should be managed by runtime netpoll. +// Pollable must be set to true for overlapped fds. +func (fd *FD) Init(net string, pollable bool) error { + if initErr != nil { + return initErr + } + + switch net { + case "file": + fd.kind = kindFile + case "console": + fd.kind = kindConsole + case "pipe": + fd.kind = kindPipe + case "file+net": + fd.kind = kindFileNet + default: + // We don't actually care about the various network types. + fd.kind = kindNet + } + fd.isFile = fd.kind != kindNet + fd.isBlocking = !pollable + + if !pollable { + return nil + } + + // It is safe to add overlapped handles that also perform I/O + // outside of the runtime poller. The runtime poller will ignore + // I/O completion notifications not initiated by us. + err := fd.pd.init(fd) + if err != nil { + return err + } + if fd.kind != kindNet || socketCanUseSetFileCompletionNotificationModes { + // Non-socket handles can use SetFileCompletionNotificationModes without problems. + err := syscall.SetFileCompletionNotificationModes(fd.Sysfd, + syscall.FILE_SKIP_SET_EVENT_ON_HANDLE|syscall.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS, + ) + fd.skipSyncNotif = err == nil + } + return nil +} + +// DisassociateIOCP disassociates the file handle from the IOCP. +// The disassociate operation will not succeed if there is any +// in-progress IO operation on the file handle. +func (fd *FD) DisassociateIOCP() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + + if fd.isBlocking || !fd.pollable() { + // Nothing to disassociate. + return nil + } + + info := windows.FILE_COMPLETION_INFORMATION{} + if err := windows.NtSetInformationFile(fd.Sysfd, &windows.IO_STATUS_BLOCK{}, unsafe.Pointer(&info), uint32(unsafe.Sizeof(info)), windows.FileReplaceCompletionInformation); err != nil { + return err + } + fd.disassociated.Store(true) + // Don't call fd.pd.close(), it would be too racy. + // There is no harm on leaving fd.pd open until Close is called. + return nil +} + +func (fd *FD) destroy() error { + if fd.Sysfd == syscall.InvalidHandle { + return syscall.EINVAL + } + // Poller may want to unregister fd in readiness notification mechanism, + // so this must be executed before fd.CloseFunc. + fd.pd.close() + var err error + switch fd.kind { + case kindNet, kindFileNet: + // The net package uses the CloseFunc variable for testing. + err = CloseFunc(fd.Sysfd) + default: + err = syscall.CloseHandle(fd.Sysfd) + } + fd.Sysfd = syscall.InvalidHandle + runtime_Semrelease(&fd.csema) + return err +} + +// Close closes the FD. The underlying file descriptor is closed by +// the destroy method when there are no remaining references. +func (fd *FD) Close() error { + if !fd.fdmu.increfAndClose() { + return errClosing(fd.isFile) + } + + if fd.kind == kindPipe { + syscall.CancelIoEx(fd.Sysfd, nil) + } + // unblock pending reader and writer + fd.pd.evict() + err := fd.decref() + // Wait until the descriptor is closed. If this was the only + // reference, it is already closed. + runtime_Semacquire(&fd.csema) + return err +} + +// Windows ReadFile and WSARecv use DWORD (uint32) parameter to pass buffer length. +// This prevents us reading blocks larger than 4GB. +// See golang.org/issue/26923. +const maxRW = 1 << 30 // 1GB is large enough and keeps subsequent reads aligned + +// Read implements io.Reader. +func (fd *FD) Read(buf []byte) (int, error) { + if fd.kind == kindFile { + if err := fd.readWriteLock(); err != nil { + return 0, err + } + defer fd.readWriteUnlock() + } else { + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + } + + if len(buf) > 0 { + fd.pin('r', &buf[0]) + } + + if len(buf) > maxRW { + buf = buf[:maxRW] + } + + var n int + var err error + switch fd.kind { + case kindConsole: + n, err = fd.readConsole(buf) + case kindFile, kindPipe: + n, err = fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = syscall.ReadFile(fd.Sysfd, buf, &qty, fd.overlapped(o)) + return qty, err + }) + fd.addOffset(n) + switch err { + case syscall.ERROR_HANDLE_EOF: + err = io.EOF + case syscall.ERROR_BROKEN_PIPE: + // ReadFile only documents ERROR_BROKEN_PIPE for pipes. + if fd.kind == kindPipe { + err = io.EOF + } + } + case kindNet: + n, err = fd.execIO('r', func(o *operation) (qty uint32, err error) { + var flags uint32 + err = syscall.WSARecv(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &o.o, nil) + return qty, err + }) + if race.Enabled { + race.Acquire(unsafe.Pointer(&ioSync)) + } + } + if len(buf) != 0 { + err = fd.eofError(n, err) + } + return n, err +} + +var ReadConsole = syscall.ReadConsole // changed for testing + +// readConsole reads utf16 characters from console File, +// encodes them into utf8 and stores them in buffer b. +// It returns the number of utf8 bytes read and an error, if any. +func (fd *FD) readConsole(b []byte) (int, error) { + if len(b) == 0 { + return 0, nil + } + + if fd.readuint16 == nil { + // Note: syscall.ReadConsole fails for very large buffers. + // The limit is somewhere around (but not exactly) 16384. + // Stay well below. + fd.readuint16 = make([]uint16, 0, 10000) + fd.readbyte = make([]byte, 0, 4*cap(fd.readuint16)) + } + + for fd.readbyteOffset >= len(fd.readbyte) { + n := cap(fd.readuint16) - len(fd.readuint16) + if n > len(b) { + n = len(b) + } + var nw uint32 + err := ReadConsole(fd.Sysfd, &fd.readuint16[:len(fd.readuint16)+1][len(fd.readuint16)], uint32(n), &nw, nil) + if err != nil { + return 0, err + } + uint16s := fd.readuint16[:len(fd.readuint16)+int(nw)] + fd.readuint16 = fd.readuint16[:0] + buf := fd.readbyte[:0] + for i := 0; i < len(uint16s); i++ { + r := rune(uint16s[i]) + if utf16.IsSurrogate(r) { + if i+1 == len(uint16s) { + if nw > 0 { + // Save half surrogate pair for next time. + fd.readuint16 = fd.readuint16[:1] + fd.readuint16[0] = uint16(r) + break + } + r = utf8.RuneError + } else { + r = utf16.DecodeRune(r, rune(uint16s[i+1])) + if r != utf8.RuneError { + i++ + } + } + } + buf = utf8.AppendRune(buf, r) + } + fd.readbyte = buf + fd.readbyteOffset = 0 + if nw == 0 { + break + } + } + + src := fd.readbyte[fd.readbyteOffset:] + var i int + for i = 0; i < len(src) && i < len(b); i++ { + x := src[i] + if x == 0x1A { // Ctrl-Z + if i == 0 { + fd.readbyteOffset++ + } + break + } + b[i] = x + } + fd.readbyteOffset += i + return i, nil +} + +// Pread emulates the Unix pread system call. +func (fd *FD) Pread(buf []byte, off int64) (int, error) { + if fd.kind == kindPipe { + // Pread does not work with pipes + return 0, syscall.ESPIPE + } + + if err := fd.readWriteLock(); err != nil { + return 0, err + } + defer fd.readWriteUnlock() + + if len(buf) > 0 { + fd.pin('r', &buf[0]) + } + + if len(buf) > maxRW { + buf = buf[:maxRW] + } + + if fd.isBlocking { + curoffset, err := syscall.Seek(fd.Sysfd, 0, io.SeekCurrent) + if err != nil { + return 0, err + } + defer syscall.Seek(fd.Sysfd, curoffset, io.SeekStart) + defer fd.setOffset(curoffset) + } else { + // Overlapped handles don't have the file pointer updated + // when performing I/O operations, so there is no need to + // call Seek to reset the file pointer. + // Also, some overlapped file handles don't support seeking. + // See https://go.dev/issues/74951. + curoffset := fd.offset + defer fd.setOffset(curoffset) + } + fd.setOffset(off) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = syscall.ReadFile(fd.Sysfd, buf, &qty, &o.o) + return qty, err + }) + if err == syscall.ERROR_HANDLE_EOF { + err = io.EOF + } + if len(buf) != 0 { + err = fd.eofError(n, err) + } + return n, err +} + +// ReadFrom wraps the recvfrom network call. +func (fd *FD) ReadFrom(buf []byte) (int, syscall.Sockaddr, error) { + if len(buf) == 0 { + return 0, nil, nil + } + if len(buf) > maxRW { + buf = buf[:maxRW] + } + if err := fd.readLock(); err != nil { + return 0, nil, err + } + defer fd.readUnlock() + + fd.pin('r', &buf[0]) + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + var flags uint32 + err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + if err != nil { + return n, nil, err + } + sa, _ := rsa.name.Sockaddr() + return n, sa, nil +} + +// ReadFromInet4 wraps the recvfrom network call for IPv4. +func (fd *FD) ReadFromInet4(buf []byte, sa4 *syscall.SockaddrInet4) (int, error) { + if len(buf) == 0 { + return 0, nil + } + if len(buf) > maxRW { + buf = buf[:maxRW] + } + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + + fd.pin('r', &buf[0]) + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + var flags uint32 + err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + if err != nil { + return n, err + } + rawToSockaddrInet4(&rsa.name, sa4) + return n, err +} + +// ReadFromInet6 wraps the recvfrom network call for IPv6. +func (fd *FD) ReadFromInet6(buf []byte, sa6 *syscall.SockaddrInet6) (int, error) { + if len(buf) == 0 { + return 0, nil + } + if len(buf) > maxRW { + buf = buf[:maxRW] + } + if err := fd.readLock(); err != nil { + return 0, err + } + defer fd.readUnlock() + + fd.pin('r', &buf[0]) + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + var flags uint32 + err = syscall.WSARecvFrom(fd.Sysfd, newWsaBuf(buf), 1, &qty, &flags, &rsa.name, &rsa.namelen, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + if err != nil { + return n, err + } + rawToSockaddrInet6(&rsa.name, sa6) + return n, err +} + +// Write implements io.Writer. +func (fd *FD) Write(buf []byte) (int, error) { + if fd.kind == kindFile { + if err := fd.readWriteLock(); err != nil { + return 0, err + } + defer fd.readWriteUnlock() + } else { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + } + + if len(buf) > 0 { + fd.pin('w', &buf[0]) + } + var ntotal int + for { + max := len(buf) + if max-ntotal > maxRW { + max = ntotal + maxRW + } + b := buf[ntotal:max] + var n int + var err error + switch fd.kind { + case kindConsole: + n, err = fd.writeConsole(b) + case kindPipe, kindFile: + n, err = fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WriteFile(fd.Sysfd, b, &qty, fd.overlapped(o)) + return qty, err + }) + fd.addOffset(n) + case kindNet: + if race.Enabled { + race.ReleaseMerge(unsafe.Pointer(&ioSync)) + } + n, err = fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WSASend(fd.Sysfd, newWsaBuf(b), 1, &qty, 0, &o.o, nil) + return qty, err + }) + } + ntotal += n + if ntotal == len(buf) || err != nil { + return ntotal, err + } + if n == 0 { + return ntotal, io.ErrUnexpectedEOF + } + } +} + +// writeConsole writes len(b) bytes to the console File. +// It returns the number of bytes written and an error, if any. +func (fd *FD) writeConsole(b []byte) (int, error) { + n := len(b) + runes := make([]rune, 0, 256) + if len(fd.lastbits) > 0 { + b = append(fd.lastbits, b...) + fd.lastbits = nil + + } + for len(b) >= utf8.UTFMax || utf8.FullRune(b) { + r, l := utf8.DecodeRune(b) + runes = append(runes, r) + b = b[l:] + } + if len(b) > 0 { + fd.lastbits = make([]byte, len(b)) + copy(fd.lastbits, b) + } + // syscall.WriteConsole seems to fail, if given large buffer. + // So limit the buffer to 16000 characters. This number was + // discovered by experimenting with syscall.WriteConsole. + const maxWrite = 16000 + for len(runes) > 0 { + m := len(runes) + if m > maxWrite { + m = maxWrite + } + chunk := runes[:m] + runes = runes[m:] + uint16s := utf16.Encode(chunk) + for len(uint16s) > 0 { + var written uint32 + err := syscall.WriteConsole(fd.Sysfd, &uint16s[0], uint32(len(uint16s)), &written, nil) + if err != nil { + return 0, err + } + uint16s = uint16s[written:] + } + } + return n, nil +} + +// Pwrite emulates the Unix pwrite system call. +func (fd *FD) Pwrite(buf []byte, off int64) (int, error) { + if fd.kind == kindPipe { + // Pwrite does not work with pipes + return 0, syscall.ESPIPE + } + + if err := fd.readWriteLock(); err != nil { + return 0, err + } + defer fd.readWriteUnlock() + + if len(buf) > 0 { + fd.pin('w', &buf[0]) + } + + if fd.isBlocking { + curoffset, err := syscall.Seek(fd.Sysfd, 0, io.SeekCurrent) + if err != nil { + return 0, err + } + defer syscall.Seek(fd.Sysfd, curoffset, io.SeekStart) + defer fd.setOffset(curoffset) + } else { + // Overlapped handles don't have the file pointer updated + // when performing I/O operations, so there is no need to + // call Seek to reset the file pointer. + // Also, some overlapped file handles don't support seeking. + // See https://go.dev/issues/74951. + curoffset := fd.offset + defer fd.setOffset(curoffset) + } + + var ntotal int + for { + max := len(buf) + if max-ntotal > maxRW { + max = ntotal + maxRW + } + fd.setOffset(off + int64(ntotal)) + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WriteFile(fd.Sysfd, buf[ntotal:max], &qty, &o.o) + return qty, err + }) + if n > 0 { + ntotal += n + } + if ntotal == len(buf) || err != nil { + return ntotal, err + } + if n == 0 { + return ntotal, io.ErrUnexpectedEOF + } + } +} + +// Writev emulates the Unix writev system call. +func (fd *FD) Writev(buf *[][]byte) (int64, error) { + if len(*buf) == 0 { + return 0, nil + } + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if race.Enabled { + race.ReleaseMerge(unsafe.Pointer(&ioSync)) + } + bufs := newWSABufs(buf) + defer freeWSABufs(bufs) + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WSASend(fd.Sysfd, &(*bufs)[0], uint32(len(*bufs)), &qty, 0, &o.o, nil) + return qty, err + }) + TestHookDidWritev(n) + consume(buf, int64(n)) + return int64(n), err +} + +// WriteTo wraps the sendto network call. +func (fd *FD) WriteTo(buf []byte, sa syscall.Sockaddr) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + + if len(buf) == 0 { + // handle zero-byte payload + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WSASendto(fd.Sysfd, &syscall.WSABuf{}, 1, &qty, 0, sa, &o.o, nil) + return qty, err + }) + return n, err + } + + fd.pin('w', &buf[0]) + + ntotal := 0 + for len(buf) > 0 { + b := buf + if len(b) > maxRW { + b = b[:maxRW] + } + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = syscall.WSASendto(fd.Sysfd, newWsaBuf(b), 1, &qty, 0, sa, &o.o, nil) + return qty, err + }) + ntotal += int(n) + if err != nil { + return ntotal, err + } + buf = buf[n:] + } + return ntotal, nil +} + +// WriteToInet4 is WriteTo, specialized for syscall.SockaddrInet4. +func (fd *FD) WriteToInet4(buf []byte, sa4 *syscall.SockaddrInet4) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + + if len(buf) == 0 { + // handle zero-byte payload + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendtoInet4(fd.Sysfd, &syscall.WSABuf{}, 1, &qty, 0, sa4, &o.o, nil) + return qty, err + }) + return n, err + } + + fd.pin('w', &buf[0]) + + ntotal := 0 + for len(buf) > 0 { + b := buf + if len(b) > maxRW { + b = b[:maxRW] + } + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendtoInet4(fd.Sysfd, newWsaBuf(b), 1, &qty, 0, sa4, &o.o, nil) + return qty, err + }) + ntotal += int(n) + if err != nil { + return ntotal, err + } + buf = buf[n:] + } + return ntotal, nil +} + +// WriteToInet6 is WriteTo, specialized for syscall.SockaddrInet6. +func (fd *FD) WriteToInet6(buf []byte, sa6 *syscall.SockaddrInet6) (int, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + + if len(buf) == 0 { + // handle zero-byte payload + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendtoInet6(fd.Sysfd, &syscall.WSABuf{}, 1, &qty, 0, sa6, &o.o, nil) + return qty, err + }) + return n, err + } + + fd.pin('w', &buf[0]) + + ntotal := 0 + for len(buf) > 0 { + b := buf + if len(b) > maxRW { + b = b[:maxRW] + } + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendtoInet6(fd.Sysfd, newWsaBuf(b), 1, &qty, 0, sa6, &o.o, nil) + return qty, err + }) + ntotal += int(n) + if err != nil { + return ntotal, err + } + buf = buf[n:] + } + return ntotal, nil +} + +// Call ConnectEx. This doesn't need any locking, since it is only +// called when the descriptor is first created. This is here rather +// than in the net package so that it can use fd.wop. +func (fd *FD) ConnectEx(ra syscall.Sockaddr) error { + _, err := fd.execIO('w', func(o *operation) (uint32, error) { + return 0, ConnectExFunc(fd.Sysfd, ra, nil, 0, nil, &o.o) + }) + return err +} + +func (fd *FD) acceptOne(s syscall.Handle, rawsa []syscall.RawSockaddrAny) (string, error) { + // Submit accept request. + rsan := uint32(unsafe.Sizeof(rawsa[0])) + _, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = AcceptFunc(fd.Sysfd, s, (*byte)(unsafe.Pointer(&rawsa[0])), 0, rsan, rsan, &qty, &o.o) + return qty, err + + }) + if err != nil { + CloseFunc(s) + return "acceptex", err + } + + // Inherit properties of the listening socket. + err = syscall.Setsockopt(s, syscall.SOL_SOCKET, syscall.SO_UPDATE_ACCEPT_CONTEXT, (*byte)(unsafe.Pointer(&fd.Sysfd)), int32(unsafe.Sizeof(fd.Sysfd))) + if err != nil { + CloseFunc(s) + return "setsockopt", err + } + + return "", nil +} + +// Accept handles accepting a socket. The sysSocket parameter is used +// to allocate the net socket. +func (fd *FD) Accept(sysSocket func() (syscall.Handle, error)) (syscall.Handle, []syscall.RawSockaddrAny, uint32, string, error) { + if err := fd.readLock(); err != nil { + return syscall.InvalidHandle, nil, 0, "", err + } + defer fd.readUnlock() + + var rawsa [2]syscall.RawSockaddrAny + for { + s, err := sysSocket() + if err != nil { + return syscall.InvalidHandle, nil, 0, "", err + } + + errcall, err := fd.acceptOne(s, rawsa[:]) + if err == nil { + return s, rawsa[:], uint32(unsafe.Sizeof(rawsa[0])), "", nil + } + + // Sometimes we see WSAECONNRESET and ERROR_NETNAME_DELETED is + // returned here. These happen if connection reset is received + // before AcceptEx could complete. These errors relate to new + // connection, not to AcceptEx, so ignore broken connection and + // try AcceptEx again for more connections. + errno, ok := err.(syscall.Errno) + if !ok { + return syscall.InvalidHandle, nil, 0, errcall, err + } + switch errno { + case syscall.ERROR_NETNAME_DELETED, syscall.WSAECONNRESET: + // ignore these and try again + default: + return syscall.InvalidHandle, nil, 0, errcall, err + } + } +} + +// Seek wraps syscall.Seek. +func (fd *FD) Seek(offset int64, whence int) (int64, error) { + if fd.kind == kindPipe { + return 0, syscall.ESPIPE + } + if err := fd.readWriteLock(); err != nil { + return 0, err + } + defer fd.readWriteUnlock() + + if !fd.isBlocking { + // Windows doesn't use the file pointer for overlapped file handles, + // there is no point on calling syscall.Seek. + var newOffset int64 + switch whence { + case io.SeekStart: + newOffset = offset + case io.SeekCurrent: + newOffset = fd.offset + offset + case io.SeekEnd: + var size int64 + if err := windows.GetFileSizeEx(fd.Sysfd, &size); err != nil { + return 0, err + } + newOffset = size + offset + default: + return 0, windows.ERROR_INVALID_PARAMETER + } + if newOffset < 0 { + return 0, windows.ERROR_NEGATIVE_SEEK + } + fd.setOffset(newOffset) + return newOffset, nil + } + n, err := syscall.Seek(fd.Sysfd, offset, whence) + fd.setOffset(n) + return n, err +} + +// Fchmod updates syscall.ByHandleFileInformation.Fileattributes when needed. +func (fd *FD) Fchmod(mode uint32) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + + var d syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(fd.Sysfd, &d); err != nil { + return err + } + attrs := d.FileAttributes + if mode&syscall.S_IWRITE != 0 { + attrs &^= syscall.FILE_ATTRIBUTE_READONLY + } else { + attrs |= syscall.FILE_ATTRIBUTE_READONLY + } + if attrs == d.FileAttributes { + return nil + } + + var du windows.FILE_BASIC_INFO + du.FileAttributes = attrs + return windows.SetFileInformationByHandle(fd.Sysfd, windows.FileBasicInfo, unsafe.Pointer(&du), uint32(unsafe.Sizeof(du))) +} + +// Fchdir wraps syscall.Fchdir. +func (fd *FD) Fchdir() error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.Fchdir(fd.Sysfd) +} + +// GetFileType wraps syscall.GetFileType. +func (fd *FD) GetFileType() (uint32, error) { + if err := fd.incref(); err != nil { + return 0, err + } + defer fd.decref() + return syscall.GetFileType(fd.Sysfd) +} + +// GetFileInformationByHandle wraps GetFileInformationByHandle. +func (fd *FD) GetFileInformationByHandle(data *syscall.ByHandleFileInformation) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.GetFileInformationByHandle(fd.Sysfd, data) +} + +// RawRead invokes the user-defined function f for a read operation. +func (fd *FD) RawRead(f func(uintptr) bool) error { + if err := fd.readLock(); err != nil { + return err + } + defer fd.readUnlock() + for { + if f(uintptr(fd.Sysfd)) { + return nil + } + + // Use a zero-byte read as a way to get notified when this + // socket is readable. h/t https://stackoverflow.com/a/42019668/332798 + _, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + var flags uint32 + if !fd.IsStream { + flags |= windows.MSG_PEEK + } + err = syscall.WSARecv(fd.Sysfd, &syscall.WSABuf{}, 1, &qty, &flags, &o.o, nil) + return qty, err + }) + if err == windows.WSAEMSGSIZE { + // expected with a 0-byte peek, ignore. + } else if err != nil { + return err + } + } +} + +// RawWrite invokes the user-defined function f for a write operation. +func (fd *FD) RawWrite(f func(uintptr) bool) error { + if err := fd.writeLock(); err != nil { + return err + } + defer fd.writeUnlock() + + if f(uintptr(fd.Sysfd)) { + return nil + } + + // TODO(tmm1): find a way to detect socket writability + return syscall.EWINDOWS +} + +func sockaddrInet4ToRaw(rsa *syscall.RawSockaddrAny, sa *syscall.SockaddrInet4) int32 { + *rsa = syscall.RawSockaddrAny{} + raw := (*syscall.RawSockaddrInet4)(unsafe.Pointer(rsa)) + raw.Family = syscall.AF_INET + p := (*[2]byte)(unsafe.Pointer(&raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + raw.Addr = sa.Addr + return int32(unsafe.Sizeof(*raw)) +} + +func sockaddrInet6ToRaw(rsa *syscall.RawSockaddrAny, sa *syscall.SockaddrInet6) int32 { + *rsa = syscall.RawSockaddrAny{} + raw := (*syscall.RawSockaddrInet6)(unsafe.Pointer(rsa)) + raw.Family = syscall.AF_INET6 + p := (*[2]byte)(unsafe.Pointer(&raw.Port)) + p[0] = byte(sa.Port >> 8) + p[1] = byte(sa.Port) + raw.Scope_id = sa.ZoneId + raw.Addr = sa.Addr + return int32(unsafe.Sizeof(*raw)) +} + +func rawToSockaddrInet4(rsa *syscall.RawSockaddrAny, sa *syscall.SockaddrInet4) { + pp := (*syscall.RawSockaddrInet4)(unsafe.Pointer(rsa)) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.Addr = pp.Addr +} + +func rawToSockaddrInet6(rsa *syscall.RawSockaddrAny, sa *syscall.SockaddrInet6) { + pp := (*syscall.RawSockaddrInet6)(unsafe.Pointer(rsa)) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + sa.Addr = pp.Addr +} + +func sockaddrToRaw(rsa *syscall.RawSockaddrAny, sa syscall.Sockaddr) (int32, error) { + switch sa := sa.(type) { + case *syscall.SockaddrInet4: + sz := sockaddrInet4ToRaw(rsa, sa) + return sz, nil + case *syscall.SockaddrInet6: + sz := sockaddrInet6ToRaw(rsa, sa) + return sz, nil + default: + return 0, syscall.EWINDOWS + } +} + +// ReadMsg wraps the WSARecvMsg network call. +func (fd *FD) ReadMsg(p []byte, oob []byte, flags int) (int, int, int, syscall.Sockaddr, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, nil, err + } + defer fd.readUnlock() + + if len(p) > maxRW { + p = p[:maxRW] + } + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + msg := newWSAMsg(p, oob, flags, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + var sa syscall.Sockaddr + if err == nil { + sa, err = msg.Name.Sockaddr() + } + return n, int(msg.Control.Len), int(msg.Flags), sa, err +} + +// ReadMsgInet4 is ReadMsg, but specialized to return a syscall.SockaddrInet4. +func (fd *FD) ReadMsgInet4(p []byte, oob []byte, flags int, sa4 *syscall.SockaddrInet4) (int, int, int, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, err + } + defer fd.readUnlock() + + if len(p) > maxRW { + p = p[:maxRW] + } + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + msg := newWSAMsg(p, oob, flags, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + if err == nil { + rawToSockaddrInet4(msg.Name, sa4) + } + return n, int(msg.Control.Len), int(msg.Flags), err +} + +// ReadMsgInet6 is ReadMsg, but specialized to return a syscall.SockaddrInet6. +func (fd *FD) ReadMsgInet6(p []byte, oob []byte, flags int, sa6 *syscall.SockaddrInet6) (int, int, int, error) { + if err := fd.readLock(); err != nil { + return 0, 0, 0, err + } + defer fd.readUnlock() + + if len(p) > maxRW { + p = p[:maxRW] + } + + rsa := newWSARsa() + defer wsaRsaPool.Put(rsa) + msg := newWSAMsg(p, oob, flags, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('r', func(o *operation) (qty uint32, err error) { + err = windows.WSARecvMsg(fd.Sysfd, msg, &qty, &o.o, nil) + return qty, err + }) + err = fd.eofError(n, err) + if err == nil { + rawToSockaddrInet6(msg.Name, sa6) + } + return n, int(msg.Control.Len), int(msg.Flags), err +} + +// WriteMsg wraps the WSASendMsg network call. +func (fd *FD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (int, int, error) { + if len(p) > maxRW { + return 0, 0, errors.New("packet is too large (only 1GB is allowed)") + } + + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + + var rsa *wsaRsa + if sa != nil { + rsa = newWSARsa() + defer wsaRsaPool.Put(rsa) + var err error + rsa.namelen, err = sockaddrToRaw(&rsa.name, sa) + if err != nil { + return 0, 0, err + } + } + msg := newWSAMsg(p, oob, 0, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil) + return qty, err + }) + return n, int(msg.Control.Len), err +} + +// WriteMsgInet4 is WriteMsg specialized for syscall.SockaddrInet4. +func (fd *FD) WriteMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (int, int, error) { + if len(p) > maxRW { + return 0, 0, errors.New("packet is too large (only 1GB is allowed)") + } + + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + + var rsa *wsaRsa + if sa != nil { + rsa = newWSARsa() + defer wsaRsaPool.Put(rsa) + rsa.namelen = sockaddrInet4ToRaw(&rsa.name, sa) + } + msg := newWSAMsg(p, oob, 0, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil) + return qty, err + }) + return n, int(msg.Control.Len), err +} + +// WriteMsgInet6 is WriteMsg specialized for syscall.SockaddrInet6. +func (fd *FD) WriteMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (int, int, error) { + if len(p) > maxRW { + return 0, 0, errors.New("packet is too large (only 1GB is allowed)") + } + + if err := fd.writeLock(); err != nil { + return 0, 0, err + } + defer fd.writeUnlock() + + var rsa *wsaRsa + if sa != nil { + rsa = newWSARsa() + defer wsaRsaPool.Put(rsa) + rsa.namelen = sockaddrInet6ToRaw(&rsa.name, sa) + } + msg := newWSAMsg(p, oob, 0, rsa) + defer freeWSAMsg(msg) + n, err := fd.execIO('w', func(o *operation) (qty uint32, err error) { + err = windows.WSASendMsg(fd.Sysfd, msg, 0, nil, &o.o, nil) + return qty, err + }) + return n, int(msg.Control.Len), err +} + +func DupCloseOnExec(fd int) (int, string, error) { + proc, err := syscall.GetCurrentProcess() + if err != nil { + return 0, "GetCurrentProcess", err + } + + var nfd syscall.Handle + const inherit = false // analogous to CLOEXEC + if err := syscall.DuplicateHandle(proc, syscall.Handle(fd), proc, &nfd, 0, inherit, syscall.DUPLICATE_SAME_ACCESS); err != nil { + return 0, "DuplicateHandle", err + } + return int(nfd), "", nil +} diff --git a/go/src/internal/poll/fd_windows_test.go b/go/src/internal/poll/fd_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6c7604fd74d305cd68b003f96750d7daa092c373 --- /dev/null +++ b/go/src/internal/poll/fd_windows_test.go @@ -0,0 +1,166 @@ +// 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 poll_test + +import ( + "errors" + "internal/poll" + "internal/syscall/windows" + "io" + "os" + "path/filepath" + "syscall" + "testing" + "unsafe" +) + +func init() { + poll.InitWSA() +} + +func TestWSASocketConflict(t *testing.T) { + t.Parallel() + s, err := windows.WSASocket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP, nil, 0, windows.WSA_FLAG_OVERLAPPED) + if err != nil { + t.Fatal(err) + } + fd := poll.FD{Sysfd: s, IsStream: true, ZeroReadIsEOF: true} + if err = fd.Init("tcp", true); err != nil { + syscall.CloseHandle(s) + t.Fatal(err) + } + defer fd.Close() + + const SIO_TCP_INFO = syscall.IOC_INOUT | syscall.IOC_VENDOR | 39 + inbuf := uint32(0) + var outbuf _TCP_INFO_v0 + cbbr := uint32(0) + + var ov syscall.Overlapped + // Create an event so that we can efficiently wait for completion + // of a requested overlapped I/O operation. + ov.HEvent, _ = windows.CreateEvent(nil, 0, 0, nil) + if ov.HEvent == 0 { + t.Fatalf("could not create the event!") + } + defer syscall.CloseHandle(ov.HEvent) + + if err = fd.WSAIoctl( + SIO_TCP_INFO, + (*byte)(unsafe.Pointer(&inbuf)), + uint32(unsafe.Sizeof(inbuf)), + (*byte)(unsafe.Pointer(&outbuf)), + uint32(unsafe.Sizeof(outbuf)), + &cbbr, + &ov, + 0, + ); err != nil && !errors.Is(err, syscall.ERROR_IO_PENDING) { + t.Fatalf("could not perform the WSAIoctl: %v", err) + } + + if err != nil && errors.Is(err, syscall.ERROR_IO_PENDING) { + // It is possible that the overlapped I/O operation completed + // immediately so there is no need to wait for it to complete. + if res, err := syscall.WaitForSingleObject(ov.HEvent, syscall.INFINITE); res != 0 { + t.Fatalf("waiting for the completion of the overlapped IO failed: %v", err) + } + } +} + +type _TCP_INFO_v0 struct { + State uint32 + Mss uint32 + ConnectionTimeMs uint64 + TimestampsEnabled bool + RttUs uint32 + MinRttUs uint32 + BytesInFlight uint32 + Cwnd uint32 + SndWnd uint32 + RcvWnd uint32 + RcvBuf uint32 + BytesOut uint64 + BytesIn uint64 + BytesReordered uint32 + BytesRetrans uint32 + FastRetrans uint32 + DupAcksIn uint32 + TimeoutEpisodes uint32 + SynRetrans uint8 +} + +func newFD(t testing.TB, h syscall.Handle, kind string, overlapped bool) *poll.FD { + fd := poll.FD{ + Sysfd: h, + IsStream: true, + ZeroReadIsEOF: true, + } + err := fd.Init(kind, overlapped) + if overlapped && err != nil { + // Overlapped file handles should not error. + fd.Close() + t.Fatal(err) + } + t.Cleanup(func() { + fd.Close() + }) + return &fd +} + +func newFile(t testing.TB, name string, overlapped bool) *poll.FD { + namep, err := syscall.UTF16PtrFromString(name) + if err != nil { + t.Fatal(err) + } + flags := syscall.FILE_ATTRIBUTE_NORMAL + if overlapped { + flags |= syscall.FILE_FLAG_OVERLAPPED + } + h, err := syscall.CreateFile(namep, + syscall.GENERIC_READ|syscall.GENERIC_WRITE, + syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_READ, + nil, syscall.OPEN_ALWAYS, uint32(flags), 0) + if err != nil { + t.Fatal(err) + } + typ, err := syscall.GetFileType(h) + if err != nil { + syscall.CloseHandle(h) + t.Fatal(err) + } + kind := "file" + if typ == syscall.FILE_TYPE_PIPE { + kind = "pipe" + } + return newFD(t, h, kind, overlapped) +} + +func BenchmarkReadOverlapped(b *testing.B) { + benchmarkRead(b, true) +} + +func BenchmarkReadSync(b *testing.B) { + benchmarkRead(b, false) +} + +func benchmarkRead(b *testing.B, overlapped bool) { + name := filepath.Join(b.TempDir(), "foo") + const content = "hello world" + err := os.WriteFile(name, []byte(content), 0644) + if err != nil { + b.Fatal(err) + } + file := newFile(b, name, overlapped) + var buf [len(content)]byte + for b.Loop() { + _, err := io.ReadFull(file, buf[:]) + if err != nil { + b.Fatal(err) + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + b.Fatal(err) + } + } +} diff --git a/go/src/internal/poll/fd_writev_libc.go b/go/src/internal/poll/fd_writev_libc.go new file mode 100644 index 0000000000000000000000000000000000000000..0a60473b3e6099a2dc4253af6055eb519548ebbd --- /dev/null +++ b/go/src/internal/poll/fd_writev_libc.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build aix || darwin || (openbsd && !mips64) || solaris + +package poll + +import ( + "syscall" + _ "unsafe" // for go:linkname +) + +//go:linkname writev syscall.writev +func writev(fd int, iovecs []syscall.Iovec) (uintptr, error) diff --git a/go/src/internal/poll/fd_writev_unix.go b/go/src/internal/poll/fd_writev_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..005638b06f2adf4d581607def7c28470b70b5243 --- /dev/null +++ b/go/src/internal/poll/fd_writev_unix.go @@ -0,0 +1,29 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || freebsd || linux || netbsd || (openbsd && mips64) + +package poll + +import ( + "syscall" + "unsafe" +) + +func writev(fd int, iovecs []syscall.Iovec) (uintptr, error) { + var ( + r uintptr + e syscall.Errno + ) + for { + r, _, e = syscall.Syscall(syscall.SYS_WRITEV, uintptr(fd), uintptr(unsafe.Pointer(&iovecs[0])), uintptr(len(iovecs))) + if e != syscall.EINTR { + break + } + } + if e != 0 { + return r, e + } + return r, nil +} diff --git a/go/src/internal/poll/file_plan9.go b/go/src/internal/poll/file_plan9.go new file mode 100644 index 0000000000000000000000000000000000000000..57dc0c668f1d8479a78a98ce17e6ed9b7187c834 --- /dev/null +++ b/go/src/internal/poll/file_plan9.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. + +package poll + +// Expose fdMutex for use by the os package on Plan 9. +// On Plan 9 we don't want to use async I/O for file operations, +// but we still want the locking semantics that fdMutex provides. + +// FDMutex is an exported fdMutex, only for Plan 9. +type FDMutex struct { + fdmu fdMutex +} + +func (fdmu *FDMutex) Incref() bool { + return fdmu.fdmu.incref() +} + +func (fdmu *FDMutex) Decref() bool { + return fdmu.fdmu.decref() +} + +func (fdmu *FDMutex) IncrefAndClose() bool { + return fdmu.fdmu.increfAndClose() +} + +func (fdmu *FDMutex) ReadLock() bool { + return fdmu.fdmu.rwlock(true) +} + +func (fdmu *FDMutex) ReadUnlock() bool { + return fdmu.fdmu.rwunlock(true) +} + +func (fdmu *FDMutex) WriteLock() bool { + return fdmu.fdmu.rwlock(false) +} + +func (fdmu *FDMutex) WriteUnlock() bool { + return fdmu.fdmu.rwunlock(false) +} diff --git a/go/src/internal/poll/fstatat_unix.go b/go/src/internal/poll/fstatat_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..cde8551a775de40d71ab83b14331edbc692068ff --- /dev/null +++ b/go/src/internal/poll/fstatat_unix.go @@ -0,0 +1,22 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || wasip1 + +package poll + +import ( + "internal/syscall/unix" + "syscall" +) + +func (fd *FD) Fstatat(name string, s *syscall.Stat_t, flags int) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return ignoringEINTR(func() error { + return unix.Fstatat(fd.Sysfd, name, s, flags) + }) +} diff --git a/go/src/internal/poll/hook_cloexec.go b/go/src/internal/poll/hook_cloexec.go new file mode 100644 index 0000000000000000000000000000000000000000..5b3cdcec283cb23d58f2d71835c271d45d3b149e --- /dev/null +++ b/go/src/internal/poll/hook_cloexec.go @@ -0,0 +1,12 @@ +// 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 dragonfly || freebsd || linux || netbsd || openbsd || solaris + +package poll + +import "syscall" + +// Accept4Func is used to hook the accept4 call. +var Accept4Func func(int, int) (int, syscall.Sockaddr, error) = syscall.Accept4 diff --git a/go/src/internal/poll/hook_unix.go b/go/src/internal/poll/hook_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..b3f4f9eb17682ffcc1b20f3f0e99e041d5060e8c --- /dev/null +++ b/go/src/internal/poll/hook_unix.go @@ -0,0 +1,15 @@ +// 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 && wasm) || wasip1 + +package poll + +import "syscall" + +// CloseFunc is used to hook the close call. +var CloseFunc func(int) error = syscall.Close + +// AcceptFunc is used to hook the accept call. +var AcceptFunc func(int) (int, syscall.Sockaddr, error) = syscall.Accept diff --git a/go/src/internal/poll/hook_windows.go b/go/src/internal/poll/hook_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..0bd950ebe46d7f5f823333bc155dbe89d469096a --- /dev/null +++ b/go/src/internal/poll/hook_windows.go @@ -0,0 +1,16 @@ +// 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 poll + +import "syscall" + +// CloseFunc is used to hook the close call. +var CloseFunc func(syscall.Handle) error = syscall.Closesocket + +// AcceptFunc is used to hook the accept call. +var AcceptFunc func(syscall.Handle, syscall.Handle, *byte, uint32, uint32, uint32, *uint32, *syscall.Overlapped) error = syscall.AcceptEx + +// ConnectExFunc is used to hook the ConnectEx call. +var ConnectExFunc func(syscall.Handle, syscall.Sockaddr, *byte, uint32, *uint32, *syscall.Overlapped) error = syscall.ConnectEx diff --git a/go/src/internal/poll/iovec_solaris.go b/go/src/internal/poll/iovec_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..e68f833d2d5e02db1c530d46169c6ba8da160562 --- /dev/null +++ b/go/src/internal/poll/iovec_solaris.go @@ -0,0 +1,14 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll + +import ( + "syscall" + "unsafe" +) + +func newIovecWithBase(base *byte) syscall.Iovec { + return syscall.Iovec{Base: (*int8)(unsafe.Pointer(base))} +} diff --git a/go/src/internal/poll/iovec_unix.go b/go/src/internal/poll/iovec_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..3f2833e728dace621fe1239cb64a59233fb62036 --- /dev/null +++ b/go/src/internal/poll/iovec_unix.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd + +package poll + +import "syscall" + +func newIovecWithBase(base *byte) syscall.Iovec { + return syscall.Iovec{Base: base} +} diff --git a/go/src/internal/poll/read_test.go b/go/src/internal/poll/read_test.go new file mode 100644 index 0000000000000000000000000000000000000000..598a52ee44c42d4de03d06efb02df81ee1c28acc --- /dev/null +++ b/go/src/internal/poll/read_test.go @@ -0,0 +1,61 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll_test + +import ( + "os" + "runtime" + "sync" + "testing" + "time" +) + +func TestRead(t *testing.T) { + t.Run("SpecialFile", func(t *testing.T) { + var wg sync.WaitGroup + for _, p := range specialFiles() { + for i := 0; i < 4; i++ { + wg.Add(1) + go func(p string) { + defer wg.Done() + for i := 0; i < 100; i++ { + if _, err := os.ReadFile(p); err != nil { + t.Error(err) + return + } + time.Sleep(time.Nanosecond) + } + }(p) + } + } + wg.Wait() + }) +} + +func specialFiles() []string { + var ps []string + switch runtime.GOOS { + case "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd": + ps = []string{ + "/dev/null", + } + case "linux": + ps = []string{ + "/dev/null", + "/proc/stat", + "/sys/devices/system/cpu/online", + } + } + nps := ps[:0] + for _, p := range ps { + f, err := os.Open(p) + if err != nil { + continue + } + f.Close() + nps = append(nps, p) + } + return nps +} diff --git a/go/src/internal/poll/sendfile.go b/go/src/internal/poll/sendfile.go new file mode 100644 index 0000000000000000000000000000000000000000..696d93353ebea2a1bd8b51fc0d35a099b3b7a760 --- /dev/null +++ b/go/src/internal/poll/sendfile.go @@ -0,0 +1,7 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll + +var TestHookDidSendFile = func(dstFD *FD, src uintptr, written int64, err error, handled bool) {} diff --git a/go/src/internal/poll/sendfile_solaris.go b/go/src/internal/poll/sendfile_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..605323b976686d7c1e3f65435c76f94125a908e4 --- /dev/null +++ b/go/src/internal/poll/sendfile_solaris.go @@ -0,0 +1,12 @@ +// 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 poll + +//go:cgo_ldflag "-lsendfile" + +// Not strictly needed, but very helpful for debugging, see issue #10221. +// +//go:cgo_import_dynamic _ _ "libsendfile.so" +//go:cgo_import_dynamic _ _ "libsocket.so" diff --git a/go/src/internal/poll/sendfile_unix.go b/go/src/internal/poll/sendfile_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..4b7e9fea9e8dc98eb54e3055de8bf9910f4f75b2 --- /dev/null +++ b/go/src/internal/poll/sendfile_unix.go @@ -0,0 +1,170 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || linux || solaris + +package poll + +import ( + "io" + "runtime" + "syscall" +) + +// SendFile wraps the sendfile system call. +// +// It copies data from src (a file descriptor) to dstFD, +// starting at the current position of src. +// It updates the current position of src to after the +// copied data. +// +// If size is zero, it copies the rest of src. +// Otherwise, it copies up to size bytes. +// +// The handled return parameter indicates whether SendFile +// was able to handle some or all of the operation. +// If handled is false, sendfile was unable to perform the copy, +// has not modified the source or destination, +// and the caller should perform the copy using a fallback implementation. +func SendFile(dstFD *FD, src uintptr, size int64) (n int64, err error, handled bool) { + if goos := runtime.GOOS; goos == "linux" || goos == "android" { + // Linux's sendfile doesn't require any setup: + // It sends from the current position of the source file and + // updates the position of the source after sending. + return sendFile(dstFD, int(src), nil, size) + } + + // Non-Linux sendfile implementations don't use the current position of the source file, + // so we need to look up the position, pass it explicitly, and adjust it after + // sendfile returns. + start, err := ignoringEINTR2(func() (int64, error) { + return syscall.Seek(int(src), 0, io.SeekCurrent) + }) + if err != nil { + return 0, err, false + } + + pos := start + n, err, handled = sendFile(dstFD, int(src), &pos, size) + if n > 0 { + ignoringEINTR2(func() (int64, error) { + return syscall.Seek(int(src), start+n, io.SeekStart) + }) + } + return n, err, handled +} + +// sendFile wraps the sendfile system call. +func sendFile(dstFD *FD, src int, offset *int64, size int64) (written int64, err error, handled bool) { + defer func() { + TestHookDidSendFile(dstFD, uintptr(src), written, err, handled) + }() + if err := dstFD.writeLock(); err != nil { + return 0, err, false + } + defer dstFD.writeUnlock() + + if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil { + return 0, err, false + } + + dst := dstFD.Sysfd + for { + // Some platforms support passing 0 to read to the end of the source, + // but all platforms support just writing a large value. + // + // Limit the maximum size to fit in an int32, to avoid any possible overflow. + chunk := 1<<31 - 1 + if size > 0 { + chunk = int(min(size-written, int64(chunk))) + } + var n int + n, err = sendFileChunk(dst, src, offset, chunk, written) + if n > 0 { + written += int64(n) + } + switch err { + case nil: + // We're done if sendfile copied no bytes + // (we're at the end of the source) + // or if we have a size limit and have reached it. + // + // If sendfile copied some bytes and we don't have a size limit, + // try again to see if there is more data to copy. + if n == 0 || (size > 0 && written >= size) { + return written, nil, true + } + case syscall.EAGAIN: + // *BSD and Darwin can return EAGAIN with n > 0, + // so check to see if the write has completed. + // So far as we know all other platforms only + // return EAGAIN when n == 0, but checking is harmless. + if size > 0 && written >= size { + return written, nil, true + } + if err = dstFD.pd.waitWrite(dstFD.isFile); err != nil { + return written, err, true + } + case syscall.EINTR: + // Retry. + case syscall.ENOSYS, syscall.EOPNOTSUPP, syscall.EINVAL: + // ENOSYS indicates no kernel support for sendfile. + // EINVAL indicates a FD type that does not support sendfile. + // + // On Linux, copy_file_range can return EOPNOTSUPP when copying + // to a NFS file (issue #40731); check for it here just in case. + return written, err, written > 0 + default: + // We want to handle ENOTSUP like EOPNOTSUPP. + // It's a pain to put it as a switch case + // because on Linux systems ENOTSUP == EOPNOTSUPP, + // so the compiler complains about a duplicate case. + if err == syscall.ENOTSUP { + return written, err, written > 0 + } + + // Not a retryable error. + return written, err, true + } + } +} + +func sendFileChunk(dst, src int, offset *int64, size int, written int64) (n int, err error) { + switch runtime.GOOS { + case "linux", "android": + // The offset is always nil on Linux. + n, err = syscall.Sendfile(dst, src, offset, size) + case "solaris", "illumos": + // Trust the offset, not the return value from sendfile. + start := *offset + n, err = syscall.Sendfile(dst, src, offset, size) + n = int(*offset - start) + // A quirk on Solaris/illumos: sendfile claims to support out_fd + // as a regular file but returns EINVAL when the out_fd + // is not a socket of SOCK_STREAM, while it actually sends + // out data anyway and updates the file offset. + // + // Another quirk: sendfile transfers data and returns EINVAL when being + // asked to transfer bytes more than the actual file size. For instance, + // the source file is wrapped in an io.LimitedReader with larger size + // than the actual file size. + // + // To handle these cases we ignore EINVAL if any call to sendfile was + // able to send data. + if err == syscall.EINVAL && (n > 0 || written > 0) { + err = nil + } + default: + start := *offset + n, err = syscall.Sendfile(dst, src, offset, size) + if n > 0 { + // The BSD implementations of syscall.Sendfile don't + // update the offset parameter (despite it being a *int64). + // + // Trust the return value from sendfile, not the offset. + *offset = start + int64(n) + } + } + return +} diff --git a/go/src/internal/poll/sendfile_windows.go b/go/src/internal/poll/sendfile_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..e0bb1ae18213aa6791f09fb6ac277efa156a448a --- /dev/null +++ b/go/src/internal/poll/sendfile_windows.go @@ -0,0 +1,90 @@ +// 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 poll + +import ( + "io" + "syscall" +) + +// SendFile wraps the TransmitFile call. +func SendFile(fd *FD, src uintptr, size int64) (written int64, err error, handled bool) { + defer func() { + TestHookDidSendFile(fd, 0, written, err, written > 0) + }() + if fd.kind == kindPipe { + // TransmitFile does not work with pipes + return 0, syscall.ESPIPE, false + } + hsrc := syscall.Handle(src) + if ft, _ := syscall.GetFileType(hsrc); ft == syscall.FILE_TYPE_PIPE { + return 0, syscall.ESPIPE, false + } + + if err := fd.writeLock(); err != nil { + return 0, err, false + } + defer fd.writeUnlock() + + // Get the file size so we don't read past the end of the file. + var fi syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(hsrc, &fi); err != nil { + return 0, err, false + } + fileSize := int64(fi.FileSizeHigh)<<32 + int64(fi.FileSizeLow) + startpos, err := syscall.Seek(hsrc, 0, io.SeekCurrent) + if err != nil { + return 0, err, false + } + maxSize := fileSize - startpos + if size <= 0 { + size = maxSize + } else { + size = min(size, maxSize) + } + + defer func() { + if written > 0 { + // Some versions of Windows (Windows 10 1803) do not set + // file position after TransmitFile completes. + // So just use Seek to set file position. + _, serr := syscall.Seek(hsrc, startpos+written, io.SeekStart) + if err != nil { + err = serr + } + } + }() + + // TransmitFile can be invoked in one call with at most + // 2,147,483,646 bytes: the maximum value for a 32-bit integer minus 1. + // See https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-transmitfile + const maxChunkSizePerCall = int64(0x7fffffff - 1) + + for size > 0 { + chunkSize := maxChunkSizePerCall + if chunkSize > size { + chunkSize = size + } + + n, err := fd.execIO('w', func(o *operation) (uint32, error) { + off := startpos + written + o.o.OffsetHigh = uint32(off >> 32) + o.o.Offset = uint32(off) + err := syscall.TransmitFile(fd.Sysfd, hsrc, uint32(chunkSize), 0, &o.o, nil, syscall.TF_WRITE_BEHIND) + if err != nil { + return 0, err + } + return uint32(chunkSize), nil + }) + if err != nil { + return written, err, written > 0 + } + + size -= int64(n) + written += int64(n) + } + + return written, nil, written > 0 +} diff --git a/go/src/internal/poll/sock_cloexec.go b/go/src/internal/poll/sock_cloexec.go new file mode 100644 index 0000000000000000000000000000000000000000..466ee3139ccdac5f6469474b0f253995b0dc187d --- /dev/null +++ b/go/src/internal/poll/sock_cloexec.go @@ -0,0 +1,22 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements accept for platforms that provide a fast path for +// setting SetNonblock and CloseOnExec. + +//go:build dragonfly || freebsd || linux || netbsd || openbsd + +package poll + +import "syscall" + +// Wrapper around the accept system call that marks the returned file +// descriptor as nonblocking and close-on-exec. +func accept(s int) (int, syscall.Sockaddr, string, error) { + ns, sa, err := Accept4Func(s, syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC) + if err != nil { + return -1, nil, "accept4", err + } + return ns, sa, "", nil +} diff --git a/go/src/internal/poll/sock_cloexec_solaris.go b/go/src/internal/poll/sock_cloexec_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..92f150b6e5d82976abff45aa4326641ec912547a --- /dev/null +++ b/go/src/internal/poll/sock_cloexec_solaris.go @@ -0,0 +1,47 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements accept for platforms that provide a fast path for +// setting SetNonblock and CloseOnExec, but don't necessarily have accept4. +// The accept4(3c) function was added to Oracle Solaris in the Solaris 11.4.0 +// release. Thus, on releases prior to 11.4, we fall back to the combination +// of accept(3c) and fcntl(2). + +package poll + +import ( + "internal/syscall/unix" + "syscall" +) + +// Wrapper around the accept system call that marks the returned file +// descriptor as nonblocking and close-on-exec. +func accept(s int) (int, syscall.Sockaddr, string, error) { + // Perform a cheap test and try the fast path first. + if unix.SupportAccept4() { + ns, sa, err := Accept4Func(s, syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC) + if err != nil { + return -1, nil, "accept4", err + } + return ns, sa, "", nil + } + + // See ../syscall/exec_unix.go for description of ForkLock. + // It is probably okay to hold the lock across syscall.Accept + // because we have put fd.sysfd into non-blocking mode. + // However, a call to the File method will put it back into + // blocking mode. We can't take that risk, so no use of ForkLock here. + ns, sa, err := AcceptFunc(s) + if err == nil { + syscall.CloseOnExec(ns) + } + if err != nil { + return -1, nil, "accept", err + } + if err = syscall.SetNonblock(ns, true); err != nil { + CloseFunc(ns) + return -1, nil, "setnonblock", err + } + return ns, sa, "", nil +} diff --git a/go/src/internal/poll/sockopt.go b/go/src/internal/poll/sockopt.go new file mode 100644 index 0000000000000000000000000000000000000000..a87a9e64135a430c36c6ea13fb6ea69942fd8c11 --- /dev/null +++ b/go/src/internal/poll/sockopt.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 unix || windows + +package poll + +import "syscall" + +// SetsockoptInt wraps the setsockopt network call with an int argument. +func (fd *FD) SetsockoptInt(level, name, arg int) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptInt(fd.Sysfd, level, name, arg) +} + +// SetsockoptInet4Addr wraps the setsockopt network call with an IPv4 address. +func (fd *FD) SetsockoptInet4Addr(level, name int, arg [4]byte) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptInet4Addr(fd.Sysfd, level, name, arg) +} + +// SetsockoptLinger wraps the setsockopt network call with a Linger argument. +func (fd *FD) SetsockoptLinger(level, name int, l *syscall.Linger) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptLinger(fd.Sysfd, level, name, l) +} + +// GetsockoptInt wraps the getsockopt network call with an int argument. +func (fd *FD) GetsockoptInt(level, name int) (int, error) { + if err := fd.incref(); err != nil { + return -1, err + } + defer fd.decref() + return syscall.GetsockoptInt(fd.Sysfd, level, name) +} diff --git a/go/src/internal/poll/sockopt_linux.go b/go/src/internal/poll/sockopt_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..bc79c350aceb92522aeb3d00f913236900edb891 --- /dev/null +++ b/go/src/internal/poll/sockopt_linux.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. + +package poll + +import "syscall" + +// SetsockoptIPMreqn wraps the setsockopt network call with an IPMreqn argument. +func (fd *FD) SetsockoptIPMreqn(level, name int, mreq *syscall.IPMreqn) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptIPMreqn(fd.Sysfd, level, name, mreq) +} diff --git a/go/src/internal/poll/sockopt_unix.go b/go/src/internal/poll/sockopt_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..9cba44da9d139884b37bf4c25419e4890d54a6b8 --- /dev/null +++ b/go/src/internal/poll/sockopt_unix.go @@ -0,0 +1,18 @@ +// 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 + +package poll + +import "syscall" + +// SetsockoptByte wraps the setsockopt network call with a byte argument. +func (fd *FD) SetsockoptByte(level, name int, arg byte) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptByte(fd.Sysfd, level, name, arg) +} diff --git a/go/src/internal/poll/sockopt_windows.go b/go/src/internal/poll/sockopt_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..f32bca4f0fe17142f42f38e973f73cf432841477 --- /dev/null +++ b/go/src/internal/poll/sockopt_windows.go @@ -0,0 +1,16 @@ +// 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 poll + +import "syscall" + +// WSAIoctl wraps the WSAIoctl network call. +func (fd *FD) WSAIoctl(iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *syscall.Overlapped, completionRoutine uintptr) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.WSAIoctl(fd.Sysfd, iocc, inbuf, cbif, outbuf, cbob, cbbr, overlapped, completionRoutine) +} diff --git a/go/src/internal/poll/sockoptip.go b/go/src/internal/poll/sockoptip.go new file mode 100644 index 0000000000000000000000000000000000000000..41955e1fda0403d5a162736a40adcf1f063fe15a --- /dev/null +++ b/go/src/internal/poll/sockoptip.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 unix || windows + +package poll + +import "syscall" + +// SetsockoptIPMreq wraps the setsockopt network call with an IPMreq argument. +func (fd *FD) SetsockoptIPMreq(level, name int, mreq *syscall.IPMreq) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptIPMreq(fd.Sysfd, level, name, mreq) +} + +// SetsockoptIPv6Mreq wraps the setsockopt network call with an IPv6Mreq argument. +func (fd *FD) SetsockoptIPv6Mreq(level, name int, mreq *syscall.IPv6Mreq) error { + if err := fd.incref(); err != nil { + return err + } + defer fd.decref() + return syscall.SetsockoptIPv6Mreq(fd.Sysfd, level, name, mreq) +} diff --git a/go/src/internal/poll/splice_linux.go b/go/src/internal/poll/splice_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..4409d2f33600a4df25a85a12e931071845c3a871 --- /dev/null +++ b/go/src/internal/poll/splice_linux.go @@ -0,0 +1,244 @@ +// 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 poll + +import ( + "internal/syscall/unix" + "runtime" + "sync" + "syscall" +) + +const ( + // spliceNonblock doesn't make the splice itself necessarily nonblocking + // (because the actual file descriptors that are spliced from/to may block + // unless they have the O_NONBLOCK flag set), but it makes the splice pipe + // operations nonblocking. + spliceNonblock = 0x2 + + // maxSpliceSize is the maximum amount of data Splice asks + // the kernel to move in a single call to splice(2). + // We use 1MB as Splice writes data through a pipe, and 1MB is the default maximum pipe buffer size, + // which is determined by /proc/sys/fs/pipe-max-size. + maxSpliceSize = 1 << 20 +) + +// Splice transfers at most remain bytes of data from src to dst, using the +// splice system call to minimize copies of data from and to userspace. +// +// Splice gets a pipe buffer from the pool or creates a new one if needed, to serve as a buffer for the data transfer. +// src and dst must both be stream-oriented sockets. +func Splice(dst, src *FD, remain int64) (written int64, handled bool, err error) { + p, err := getPipe() + if err != nil { + return 0, false, err + } + defer putPipe(p) + var inPipe, n int + for err == nil && remain > 0 { + max := maxSpliceSize + if int64(max) > remain { + max = int(remain) + } + inPipe, err = spliceDrain(p.wfd, src, max) + // The operation is considered handled if splice returns no + // error, or an error other than EINVAL. An EINVAL means the + // kernel does not support splice for the socket type of src. + // The failed syscall does not consume any data so it is safe + // to fall back to a generic copy. + // + // spliceDrain should never return EAGAIN, so if err != nil, + // Splice cannot continue. + // + // If inPipe == 0 && err == nil, src is at EOF, and the + // transfer is complete. + handled = handled || (err != syscall.EINVAL) + if err != nil || inPipe == 0 { + break + } + p.data += inPipe + + n, err = splicePump(dst, p.rfd, inPipe) + if n > 0 { + written += int64(n) + remain -= int64(n) + p.data -= n + } + } + if err != nil { + return written, handled, err + } + return written, true, nil +} + +// spliceDrain moves data from a socket to a pipe. +// +// Invariant: when entering spliceDrain, the pipe is empty. It is either in its +// initial state, or splicePump has emptied it previously. +// +// Given this, spliceDrain can reasonably assume that the pipe is ready for +// writing, so if splice returns EAGAIN, it must be because the socket is not +// ready for reading. +// +// If spliceDrain returns (0, nil), src is at EOF. +func spliceDrain(pipefd int, sock *FD, max int) (int, error) { + if err := sock.readLock(); err != nil { + return 0, err + } + defer sock.readUnlock() + if err := sock.pd.prepareRead(sock.isFile); err != nil { + return 0, err + } + for { + // In theory calling splice(2) with SPLICE_F_NONBLOCK could end up an infinite loop here, + // because it could return EAGAIN ceaselessly when the write end of the pipe is full, + // but this shouldn't be a concern here, since the pipe buffer must be sufficient for + // this data transmission on the basis of the workflow in Splice. + n, err := splice(pipefd, sock.Sysfd, max, spliceNonblock) + if err == syscall.EINTR { + continue + } + if err != syscall.EAGAIN { + return n, err + } + if sock.pd.pollable() { + if err := sock.pd.waitRead(sock.isFile); err != nil { + return n, err + } + } + } +} + +// splicePump moves all the buffered data from a pipe to a socket. +// +// Invariant: when entering splicePump, there are exactly inPipe +// bytes of data in the pipe, from a previous call to spliceDrain. +// +// By analogy to the condition from spliceDrain, splicePump +// only needs to poll the socket for readiness, if splice returns +// EAGAIN. +// +// If splicePump cannot move all the data in a single call to +// splice(2), it loops over the buffered data until it has written +// all of it to the socket. This behavior is similar to the Write +// step of an io.Copy in userspace. +func splicePump(sock *FD, pipefd int, inPipe int) (int, error) { + if err := sock.writeLock(); err != nil { + return 0, err + } + defer sock.writeUnlock() + if err := sock.pd.prepareWrite(sock.isFile); err != nil { + return 0, err + } + written := 0 + for inPipe > 0 { + // In theory calling splice(2) with SPLICE_F_NONBLOCK could end up an infinite loop here, + // because it could return EAGAIN ceaselessly when the read end of the pipe is empty, + // but this shouldn't be a concern here, since the pipe buffer must contain inPipe size of + // data on the basis of the workflow in Splice. + n, err := splice(sock.Sysfd, pipefd, inPipe, spliceNonblock) + if err == syscall.EINTR { + continue + } + // Here, the condition n == 0 && err == nil should never be + // observed, since Splice controls the write side of the pipe. + if n > 0 { + inPipe -= n + written += n + continue + } + if err != syscall.EAGAIN { + return written, err + } + if sock.pd.pollable() { + if err := sock.pd.waitWrite(sock.isFile); err != nil { + return written, err + } + } + } + return written, nil +} + +// splice wraps the splice system call. Since the current implementation +// only uses splice on sockets and pipes, the offset arguments are unused. +// splice returns int instead of int64, because callers never ask it to +// move more data in a single call than can fit in an int32. +func splice(out int, in int, max int, flags int) (int, error) { + n, err := syscall.Splice(in, nil, out, nil, max, flags) + return int(n), err +} + +type splicePipeFields struct { + rfd int + wfd int + data int +} + +type splicePipe struct { + splicePipeFields + cleanup runtime.Cleanup +} + +// splicePipePool caches pipes to avoid high-frequency construction and destruction of pipe buffers. +// The garbage collector will free all pipes in the sync.Pool periodically, thus we need to set up +// a finalizer for each pipe to close its file descriptors before the actual GC. +var splicePipePool = sync.Pool{New: newPoolPipe} + +func newPoolPipe() any { + // Discard the error which occurred during the creation of pipe buffer, + // redirecting the data transmission to the conventional way utilizing read() + write() as a fallback. + p := newPipe() + if p == nil { + return nil + } + + p.cleanup = runtime.AddCleanup(p, func(spf splicePipeFields) { + destroyPipe(&splicePipe{splicePipeFields: spf}) + }, p.splicePipeFields) + return p +} + +// getPipe tries to acquire a pipe buffer from the pool or create a new one with newPipe() if it gets nil from the cache. +func getPipe() (*splicePipe, error) { + v := splicePipePool.Get() + if v == nil { + return nil, syscall.EINVAL + } + return v.(*splicePipe), nil +} + +func putPipe(p *splicePipe) { + // If there is still data left in the pipe, + // then close and discard it instead of putting it back into the pool. + if p.data != 0 { + p.cleanup.Stop() + destroyPipe(p) + return + } + splicePipePool.Put(p) +} + +// newPipe sets up a pipe for a splice operation. +func newPipe() *splicePipe { + var fds [2]int + if err := syscall.Pipe2(fds[:], syscall.O_CLOEXEC|syscall.O_NONBLOCK); err != nil { + return nil + } + + // Splice will loop writing maxSpliceSize bytes from the source to the pipe, + // and then write those bytes from the pipe to the destination. + // Set the pipe buffer size to maxSpliceSize to optimize that. + // Ignore errors here, as a smaller buffer size will work, + // although it will require more system calls. + unix.Fcntl(fds[0], syscall.F_SETPIPE_SZ, maxSpliceSize) + + return &splicePipe{splicePipeFields: splicePipeFields{rfd: fds[0], wfd: fds[1]}} +} + +// destroyPipe destroys a pipe. +func destroyPipe(p *splicePipe) { + CloseFunc(p.rfd) + CloseFunc(p.wfd) +} diff --git a/go/src/internal/poll/splice_linux_test.go b/go/src/internal/poll/splice_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9f2b8f94612a16728c579053f986ec7e54390e25 --- /dev/null +++ b/go/src/internal/poll/splice_linux_test.go @@ -0,0 +1,136 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poll_test + +import ( + "internal/poll" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" +) + +var closeHook atomic.Value // func(fd int) + +func init() { + closeFunc := poll.CloseFunc + poll.CloseFunc = func(fd int) (err error) { + if v := closeHook.Load(); v != nil { + if hook := v.(func(int)); hook != nil { + hook(fd) + } + } + return closeFunc(fd) + } +} + +func TestSplicePipePool(t *testing.T) { + const N = 64 + var ( + p *poll.SplicePipe + ps []*poll.SplicePipe + allFDs []int + pendingFDs sync.Map // fd → struct{}{} + err error + ) + + closeHook.Store(func(fd int) { pendingFDs.Delete(fd) }) + t.Cleanup(func() { closeHook.Store((func(int))(nil)) }) + + for i := 0; i < N; i++ { + p, err = poll.GetPipe() + if err != nil { + t.Skipf("failed to create pipe due to error(%v), skip this test", err) + } + _, pwfd := poll.GetPipeFds(p) + allFDs = append(allFDs, pwfd) + pendingFDs.Store(pwfd, struct{}{}) + ps = append(ps, p) + } + for _, p = range ps { + poll.PutPipe(p) + } + ps = nil + p = nil + + // Exploit the timeout of "go test" as a timer for the subsequent verification. + timeout := 5 * time.Minute + if deadline, ok := t.Deadline(); ok { + timeout = time.Until(deadline) + timeout -= timeout / 10 // Leave 10% headroom for cleanup. + } + expiredTime := time.NewTimer(timeout) + defer expiredTime.Stop() + + // Trigger garbage collection repeatedly, waiting for all pipes in sync.Pool + // to either be deallocated and closed, or to time out. + for { + runtime.GC() + time.Sleep(10 * time.Millisecond) + + // Detect whether all pipes are closed properly. + var leakedFDs []int + pendingFDs.Range(func(k, v any) bool { + leakedFDs = append(leakedFDs, k.(int)) + return true + }) + if len(leakedFDs) == 0 { + break + } + + select { + case <-expiredTime.C: + t.Logf("all descriptors: %v", allFDs) + t.Fatalf("leaked descriptors: %v", leakedFDs) + default: + } + } +} + +func BenchmarkSplicePipe(b *testing.B) { + b.Run("SplicePipeWithPool", func(b *testing.B) { + for i := 0; i < b.N; i++ { + p, err := poll.GetPipe() + if err != nil { + continue + } + poll.PutPipe(p) + } + }) + b.Run("SplicePipeWithoutPool", func(b *testing.B) { + for i := 0; i < b.N; i++ { + p := poll.NewPipe() + if p == nil { + b.Skip("newPipe returned nil") + } + poll.DestroyPipe(p) + } + }) +} + +func BenchmarkSplicePipePoolParallel(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + p, err := poll.GetPipe() + if err != nil { + continue + } + poll.PutPipe(p) + } + }) +} + +func BenchmarkSplicePipeNativeParallel(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + p := poll.NewPipe() + if p == nil { + b.Skip("newPipe returned nil") + } + poll.DestroyPipe(p) + } + }) +} diff --git a/go/src/internal/poll/sys_cloexec.go b/go/src/internal/poll/sys_cloexec.go new file mode 100644 index 0000000000000000000000000000000000000000..2c5da7d3fe548de916de4ffdc4b2d32c6759b543 --- /dev/null +++ b/go/src/internal/poll/sys_cloexec.go @@ -0,0 +1,36 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements accept for platforms that do not provide a fast path for +// setting SetNonblock and CloseOnExec. + +//go:build aix || darwin || (js && wasm) || wasip1 + +package poll + +import ( + "syscall" +) + +// Wrapper around the accept system call that marks the returned file +// descriptor as nonblocking and close-on-exec. +func accept(s int) (int, syscall.Sockaddr, string, error) { + // See ../syscall/exec_unix.go for description of ForkLock. + // It is probably okay to hold the lock across syscall.Accept + // because we have put fd.sysfd into non-blocking mode. + // However, a call to the File method will put it back into + // blocking mode. We can't take that risk, so no use of ForkLock here. + ns, sa, err := AcceptFunc(s) + if err == nil { + syscall.CloseOnExec(ns) + } + if err != nil { + return -1, nil, "accept", err + } + if err = syscall.SetNonblock(ns, true); err != nil { + CloseFunc(ns) + return -1, nil, "setnonblock", err + } + return ns, sa, "", nil +} diff --git a/go/src/internal/poll/writev.go b/go/src/internal/poll/writev.go new file mode 100644 index 0000000000000000000000000000000000000000..fb15c2730983094fa571c8724654ecd779a5dbfa --- /dev/null +++ b/go/src/internal/poll/writev.go @@ -0,0 +1,90 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package poll + +import ( + "io" + "runtime" + "syscall" +) + +// Writev wraps the writev system call. +func (fd *FD) Writev(v *[][]byte) (int64, error) { + if err := fd.writeLock(); err != nil { + return 0, err + } + defer fd.writeUnlock() + if err := fd.pd.prepareWrite(fd.isFile); err != nil { + return 0, err + } + + var iovecs []syscall.Iovec + if fd.iovecs != nil { + iovecs = *fd.iovecs + } + // TODO: read from sysconf(_SC_IOV_MAX)? The Linux default is + // 1024 and this seems conservative enough for now. Darwin's + // UIO_MAXIOV also seems to be 1024. + maxVec := 1024 + if runtime.GOOS == "aix" || runtime.GOOS == "solaris" { + // IOV_MAX is set to XOPEN_IOV_MAX on AIX and Solaris. + maxVec = 16 + } + + var n int64 + var err error + for len(*v) > 0 { + iovecs = iovecs[:0] + for _, chunk := range *v { + if len(chunk) == 0 { + continue + } + iovecs = append(iovecs, newIovecWithBase(&chunk[0])) + if fd.IsStream && len(chunk) > 1<<30 { + iovecs[len(iovecs)-1].SetLen(1 << 30) + break // continue chunk on next writev + } + iovecs[len(iovecs)-1].SetLen(len(chunk)) + if len(iovecs) == maxVec { + break + } + } + if len(iovecs) == 0 { + break + } + if fd.iovecs == nil { + fd.iovecs = new([]syscall.Iovec) + } + *fd.iovecs = iovecs // cache + + var wrote uintptr + wrote, err = writev(fd.Sysfd, iovecs) + if wrote == ^uintptr(0) { + wrote = 0 + } + TestHookDidWritev(int(wrote)) + n += int64(wrote) + consume(v, int64(wrote)) + clear(iovecs) + if err != nil { + if err == syscall.EINTR { + continue + } + if err == syscall.EAGAIN { + if err = fd.pd.waitWrite(fd.isFile); err == nil { + continue + } + } + break + } + if n == 0 { + err = io.ErrUnexpectedEOF + break + } + } + return n, err +} diff --git a/go/src/internal/poll/writev_test.go b/go/src/internal/poll/writev_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b46657ce960239c67dff21e0926be3bdebd3a96c --- /dev/null +++ b/go/src/internal/poll/writev_test.go @@ -0,0 +1,62 @@ +// 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 poll_test + +import ( + "internal/poll" + "reflect" + "testing" +) + +func TestConsume(t *testing.T) { + tests := []struct { + in [][]byte + consume int64 + want [][]byte + }{ + { + in: [][]byte{[]byte("foo"), []byte("bar")}, + consume: 0, + want: [][]byte{[]byte("foo"), []byte("bar")}, + }, + { + in: [][]byte{[]byte("foo"), []byte("bar")}, + consume: 2, + want: [][]byte{[]byte("o"), []byte("bar")}, + }, + { + in: [][]byte{[]byte("foo"), []byte("bar")}, + consume: 3, + want: [][]byte{[]byte("bar")}, + }, + { + in: [][]byte{[]byte("foo"), []byte("bar")}, + consume: 4, + want: [][]byte{[]byte("ar")}, + }, + { + in: [][]byte{nil, nil, nil, []byte("bar")}, + consume: 1, + want: [][]byte{[]byte("ar")}, + }, + { + in: [][]byte{nil, nil, nil, []byte("foo")}, + consume: 0, + want: [][]byte{[]byte("foo")}, + }, + { + in: [][]byte{nil, nil, nil}, + consume: 0, + want: [][]byte{}, + }, + } + for i, tt := range tests { + in := tt.in + poll.Consume(&in, tt.consume) + if !reflect.DeepEqual(in, tt.want) { + t.Errorf("%d. after consume(%d) = %+v, want %+v", i, tt.consume, in, tt.want) + } + } +} diff --git a/go/src/internal/profile/encode.go b/go/src/internal/profile/encode.go new file mode 100644 index 0000000000000000000000000000000000000000..94d04bf094bab3a89c747734161753598ae4f2cd --- /dev/null +++ b/go/src/internal/profile/encode.go @@ -0,0 +1,482 @@ +// 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 profile + +import ( + "errors" + "fmt" + "sort" +) + +func (p *Profile) decoder() []decoder { + return profileDecoder +} + +// preEncode populates the unexported fields to be used by encode +// (with suffix X) from the corresponding exported fields. The +// exported fields are cleared up to facilitate testing. +func (p *Profile) preEncode() { + strings := make(map[string]int) + addString(strings, "") + + for _, st := range p.SampleType { + st.typeX = addString(strings, st.Type) + st.unitX = addString(strings, st.Unit) + } + + for _, s := range p.Sample { + s.labelX = nil + var keys []string + for k := range s.Label { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + vs := s.Label[k] + for _, v := range vs { + s.labelX = append(s.labelX, + Label{ + keyX: addString(strings, k), + strX: addString(strings, v), + }, + ) + } + } + var numKeys []string + for k := range s.NumLabel { + numKeys = append(numKeys, k) + } + sort.Strings(numKeys) + for _, k := range numKeys { + vs := s.NumLabel[k] + for _, v := range vs { + s.labelX = append(s.labelX, + Label{ + keyX: addString(strings, k), + numX: v, + }, + ) + } + } + s.locationIDX = nil + for _, l := range s.Location { + s.locationIDX = append(s.locationIDX, l.ID) + } + } + + for _, m := range p.Mapping { + m.fileX = addString(strings, m.File) + m.buildIDX = addString(strings, m.BuildID) + } + + for _, l := range p.Location { + for i, ln := range l.Line { + if ln.Function != nil { + l.Line[i].functionIDX = ln.Function.ID + } else { + l.Line[i].functionIDX = 0 + } + } + if l.Mapping != nil { + l.mappingIDX = l.Mapping.ID + } else { + l.mappingIDX = 0 + } + } + for _, f := range p.Function { + f.nameX = addString(strings, f.Name) + f.systemNameX = addString(strings, f.SystemName) + f.filenameX = addString(strings, f.Filename) + } + + p.dropFramesX = addString(strings, p.DropFrames) + p.keepFramesX = addString(strings, p.KeepFrames) + + if pt := p.PeriodType; pt != nil { + pt.typeX = addString(strings, pt.Type) + pt.unitX = addString(strings, pt.Unit) + } + + p.stringTable = make([]string, len(strings)) + for s, i := range strings { + p.stringTable[i] = s + } +} + +func (p *Profile) encode(b *buffer) { + for _, x := range p.SampleType { + encodeMessage(b, 1, x) + } + for _, x := range p.Sample { + encodeMessage(b, 2, x) + } + for _, x := range p.Mapping { + encodeMessage(b, 3, x) + } + for _, x := range p.Location { + encodeMessage(b, 4, x) + } + for _, x := range p.Function { + encodeMessage(b, 5, x) + } + encodeStrings(b, 6, p.stringTable) + encodeInt64Opt(b, 7, p.dropFramesX) + encodeInt64Opt(b, 8, p.keepFramesX) + encodeInt64Opt(b, 9, p.TimeNanos) + encodeInt64Opt(b, 10, p.DurationNanos) + if pt := p.PeriodType; pt != nil && (pt.typeX != 0 || pt.unitX != 0) { + encodeMessage(b, 11, p.PeriodType) + } + encodeInt64Opt(b, 12, p.Period) +} + +var profileDecoder = []decoder{ + nil, // 0 + // repeated ValueType sample_type = 1 + func(b *buffer, m message) error { + x := new(ValueType) + pp := m.(*Profile) + pp.SampleType = append(pp.SampleType, x) + return decodeMessage(b, x) + }, + // repeated Sample sample = 2 + func(b *buffer, m message) error { + x := new(Sample) + pp := m.(*Profile) + pp.Sample = append(pp.Sample, x) + return decodeMessage(b, x) + }, + // repeated Mapping mapping = 3 + func(b *buffer, m message) error { + x := new(Mapping) + pp := m.(*Profile) + pp.Mapping = append(pp.Mapping, x) + return decodeMessage(b, x) + }, + // repeated Location location = 4 + func(b *buffer, m message) error { + x := new(Location) + pp := m.(*Profile) + pp.Location = append(pp.Location, x) + return decodeMessage(b, x) + }, + // repeated Function function = 5 + func(b *buffer, m message) error { + x := new(Function) + pp := m.(*Profile) + pp.Function = append(pp.Function, x) + return decodeMessage(b, x) + }, + // repeated string string_table = 6 + func(b *buffer, m message) error { + err := decodeStrings(b, &m.(*Profile).stringTable) + if err != nil { + return err + } + if m.(*Profile).stringTable[0] != "" { + return errors.New("string_table[0] must be ''") + } + return nil + }, + // repeated int64 drop_frames = 7 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).dropFramesX) }, + // repeated int64 keep_frames = 8 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).keepFramesX) }, + // repeated int64 time_nanos = 9 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).TimeNanos) }, + // repeated int64 duration_nanos = 10 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).DurationNanos) }, + // optional string period_type = 11 + func(b *buffer, m message) error { + x := new(ValueType) + pp := m.(*Profile) + pp.PeriodType = x + return decodeMessage(b, x) + }, + // repeated int64 period = 12 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).Period) }, + // repeated int64 comment = 13 + func(b *buffer, m message) error { return decodeInt64s(b, &m.(*Profile).commentX) }, + // int64 defaultSampleType = 14 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).defaultSampleTypeX) }, +} + +// postDecode takes the unexported fields populated by decode (with +// suffix X) and populates the corresponding exported fields. +// The unexported fields are cleared up to facilitate testing. +func (p *Profile) postDecode() error { + var err error + + mappings := make(map[uint64]*Mapping) + for _, m := range p.Mapping { + m.File, err = getString(p.stringTable, &m.fileX, err) + m.BuildID, err = getString(p.stringTable, &m.buildIDX, err) + mappings[m.ID] = m + } + + functions := make(map[uint64]*Function) + for _, f := range p.Function { + f.Name, err = getString(p.stringTable, &f.nameX, err) + f.SystemName, err = getString(p.stringTable, &f.systemNameX, err) + f.Filename, err = getString(p.stringTable, &f.filenameX, err) + functions[f.ID] = f + } + + locations := make(map[uint64]*Location) + for _, l := range p.Location { + l.Mapping = mappings[l.mappingIDX] + l.mappingIDX = 0 + for i, ln := range l.Line { + if id := ln.functionIDX; id != 0 { + l.Line[i].Function = functions[id] + if l.Line[i].Function == nil { + return fmt.Errorf("Function ID %d not found", id) + } + l.Line[i].functionIDX = 0 + } + } + locations[l.ID] = l + } + + for _, st := range p.SampleType { + st.Type, err = getString(p.stringTable, &st.typeX, err) + st.Unit, err = getString(p.stringTable, &st.unitX, err) + } + + for _, s := range p.Sample { + labels := make(map[string][]string) + numLabels := make(map[string][]int64) + for _, l := range s.labelX { + var key, value string + key, err = getString(p.stringTable, &l.keyX, err) + if l.strX != 0 { + value, err = getString(p.stringTable, &l.strX, err) + labels[key] = append(labels[key], value) + } else { + numLabels[key] = append(numLabels[key], l.numX) + } + } + if len(labels) > 0 { + s.Label = labels + } + if len(numLabels) > 0 { + s.NumLabel = numLabels + } + s.Location = nil + for _, lid := range s.locationIDX { + s.Location = append(s.Location, locations[lid]) + } + s.locationIDX = nil + } + + p.DropFrames, err = getString(p.stringTable, &p.dropFramesX, err) + p.KeepFrames, err = getString(p.stringTable, &p.keepFramesX, err) + + if pt := p.PeriodType; pt == nil { + p.PeriodType = &ValueType{} + } + + if pt := p.PeriodType; pt != nil { + pt.Type, err = getString(p.stringTable, &pt.typeX, err) + pt.Unit, err = getString(p.stringTable, &pt.unitX, err) + } + for _, i := range p.commentX { + var c string + c, err = getString(p.stringTable, &i, err) + p.Comments = append(p.Comments, c) + } + + p.commentX = nil + p.DefaultSampleType, err = getString(p.stringTable, &p.defaultSampleTypeX, err) + p.stringTable = nil + return err +} + +func (p *ValueType) decoder() []decoder { + return valueTypeDecoder +} + +func (p *ValueType) encode(b *buffer) { + encodeInt64Opt(b, 1, p.typeX) + encodeInt64Opt(b, 2, p.unitX) +} + +var valueTypeDecoder = []decoder{ + nil, // 0 + // optional int64 type = 1 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*ValueType).typeX) }, + // optional int64 unit = 2 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*ValueType).unitX) }, +} + +func (p *Sample) decoder() []decoder { + return sampleDecoder +} + +func (p *Sample) encode(b *buffer) { + encodeUint64s(b, 1, p.locationIDX) + for _, x := range p.Value { + encodeInt64(b, 2, x) + } + for _, x := range p.labelX { + encodeMessage(b, 3, x) + } +} + +var sampleDecoder = []decoder{ + nil, // 0 + // repeated uint64 location = 1 + func(b *buffer, m message) error { return decodeUint64s(b, &m.(*Sample).locationIDX) }, + // repeated int64 value = 2 + func(b *buffer, m message) error { return decodeInt64s(b, &m.(*Sample).Value) }, + // repeated Label label = 3 + func(b *buffer, m message) error { + s := m.(*Sample) + n := len(s.labelX) + s.labelX = append(s.labelX, Label{}) + return decodeMessage(b, &s.labelX[n]) + }, +} + +func (p Label) decoder() []decoder { + return labelDecoder +} + +func (p Label) encode(b *buffer) { + encodeInt64Opt(b, 1, p.keyX) + encodeInt64Opt(b, 2, p.strX) + encodeInt64Opt(b, 3, p.numX) +} + +var labelDecoder = []decoder{ + nil, // 0 + // optional int64 key = 1 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Label).keyX) }, + // optional int64 str = 2 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Label).strX) }, + // optional int64 num = 3 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Label).numX) }, +} + +func (p *Mapping) decoder() []decoder { + return mappingDecoder +} + +func (p *Mapping) encode(b *buffer) { + encodeUint64Opt(b, 1, p.ID) + encodeUint64Opt(b, 2, p.Start) + encodeUint64Opt(b, 3, p.Limit) + encodeUint64Opt(b, 4, p.Offset) + encodeInt64Opt(b, 5, p.fileX) + encodeInt64Opt(b, 6, p.buildIDX) + encodeBoolOpt(b, 7, p.HasFunctions) + encodeBoolOpt(b, 8, p.HasFilenames) + encodeBoolOpt(b, 9, p.HasLineNumbers) + encodeBoolOpt(b, 10, p.HasInlineFrames) +} + +var mappingDecoder = []decoder{ + nil, // 0 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Mapping).ID) }, // optional uint64 id = 1 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Mapping).Start) }, // optional uint64 memory_offset = 2 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Mapping).Limit) }, // optional uint64 memory_limit = 3 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Mapping).Offset) }, // optional uint64 file_offset = 4 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Mapping).fileX) }, // optional int64 filename = 5 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Mapping).buildIDX) }, // optional int64 build_id = 6 + func(b *buffer, m message) error { return decodeBool(b, &m.(*Mapping).HasFunctions) }, // optional bool has_functions = 7 + func(b *buffer, m message) error { return decodeBool(b, &m.(*Mapping).HasFilenames) }, // optional bool has_filenames = 8 + func(b *buffer, m message) error { return decodeBool(b, &m.(*Mapping).HasLineNumbers) }, // optional bool has_line_numbers = 9 + func(b *buffer, m message) error { return decodeBool(b, &m.(*Mapping).HasInlineFrames) }, // optional bool has_inline_frames = 10 +} + +func (p *Location) decoder() []decoder { + return locationDecoder +} + +func (p *Location) encode(b *buffer) { + encodeUint64Opt(b, 1, p.ID) + encodeUint64Opt(b, 2, p.mappingIDX) + encodeUint64Opt(b, 3, p.Address) + for i := range p.Line { + encodeMessage(b, 4, &p.Line[i]) + } +} + +var locationDecoder = []decoder{ + nil, // 0 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Location).ID) }, // optional uint64 id = 1; + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Location).mappingIDX) }, // optional uint64 mapping_id = 2; + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Location).Address) }, // optional uint64 address = 3; + func(b *buffer, m message) error { // repeated Line line = 4 + pp := m.(*Location) + n := len(pp.Line) + pp.Line = append(pp.Line, Line{}) + return decodeMessage(b, &pp.Line[n]) + }, +} + +func (p *Line) decoder() []decoder { + return lineDecoder +} + +func (p *Line) encode(b *buffer) { + encodeUint64Opt(b, 1, p.functionIDX) + encodeInt64Opt(b, 2, p.Line) +} + +var lineDecoder = []decoder{ + nil, // 0 + // optional uint64 function_id = 1 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Line).functionIDX) }, + // optional int64 line = 2 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Line).Line) }, +} + +func (p *Function) decoder() []decoder { + return functionDecoder +} + +func (p *Function) encode(b *buffer) { + encodeUint64Opt(b, 1, p.ID) + encodeInt64Opt(b, 2, p.nameX) + encodeInt64Opt(b, 3, p.systemNameX) + encodeInt64Opt(b, 4, p.filenameX) + encodeInt64Opt(b, 5, p.StartLine) +} + +var functionDecoder = []decoder{ + nil, // 0 + // optional uint64 id = 1 + func(b *buffer, m message) error { return decodeUint64(b, &m.(*Function).ID) }, + // optional int64 function_name = 2 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Function).nameX) }, + // optional int64 function_system_name = 3 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Function).systemNameX) }, + // repeated int64 filename = 4 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Function).filenameX) }, + // optional int64 start_line = 5 + func(b *buffer, m message) error { return decodeInt64(b, &m.(*Function).StartLine) }, +} + +func addString(strings map[string]int, s string) int64 { + i, ok := strings[s] + if !ok { + i = len(strings) + strings[s] = i + } + return int64(i) +} + +func getString(strings []string, strng *int64, err error) (string, error) { + if err != nil { + return "", err + } + s := int(*strng) + if s < 0 || s >= len(strings) { + return "", errMalformed + } + *strng = 0 + return strings[s], nil +} diff --git a/go/src/internal/profile/filter.go b/go/src/internal/profile/filter.go new file mode 100644 index 0000000000000000000000000000000000000000..1da580aea89b6de536da48e6ae969db623ce2e26 --- /dev/null +++ b/go/src/internal/profile/filter.go @@ -0,0 +1,54 @@ +// 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. + +// Implements methods to filter samples from profiles. + +package profile + +// TagMatch selects tags for filtering +type TagMatch func(key, val string, nval int64) bool + +// FilterSamplesByTag removes all samples from the profile, except +// those that match focus and do not match the ignore regular +// expression. +func (p *Profile) FilterSamplesByTag(focus, ignore TagMatch) (fm, im bool) { + samples := make([]*Sample, 0, len(p.Sample)) + for _, s := range p.Sample { + focused, ignored := focusedSample(s, focus, ignore) + fm = fm || focused + im = im || ignored + if focused && !ignored { + samples = append(samples, s) + } + } + p.Sample = samples + return +} + +// focusedSample checks a sample against focus and ignore regexps. +// Returns whether the focus/ignore regexps match any tags. +func focusedSample(s *Sample, focus, ignore TagMatch) (fm, im bool) { + fm = focus == nil + for key, vals := range s.Label { + for _, val := range vals { + if ignore != nil && ignore(key, val, 0) { + im = true + } + if !fm && focus(key, val, 0) { + fm = true + } + } + } + for key, vals := range s.NumLabel { + for _, val := range vals { + if ignore != nil && ignore(key, "", val) { + im = true + } + if !fm && focus(key, "", val) { + fm = true + } + } + } + return fm, im +} diff --git a/go/src/internal/profile/graph.go b/go/src/internal/profile/graph.go new file mode 100644 index 0000000000000000000000000000000000000000..e3c755a65d85234425b7dac6c21cd8aa77877962 --- /dev/null +++ b/go/src/internal/profile/graph.go @@ -0,0 +1,515 @@ +// Copyright 2014 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package profile represents a pprof profile as a directed graph. +// +// This package is a simplified fork of github.com/google/pprof/internal/graph. +package profile + +import ( + "fmt" + "sort" + "strings" +) + +// Options encodes the options for constructing a graph +type Options struct { + SampleValue func(s []int64) int64 // Function to compute the value of a sample + SampleMeanDivisor func(s []int64) int64 // Function to compute the divisor for mean graphs, or nil + + DropNegative bool // Drop nodes with overall negative values + + KeptNodes NodeSet // If non-nil, only use nodes in this set +} + +// Nodes is an ordered collection of graph nodes. +type Nodes []*Node + +// Node is an entry on a profiling report. It represents a unique +// program location. +type Node struct { + // Info describes the source location associated to this node. + Info NodeInfo + + // Function represents the function that this node belongs to. On + // graphs with sub-function resolution (eg line number or + // addresses), two nodes in a NodeMap that are part of the same + // function have the same value of Node.Function. If the Node + // represents the whole function, it points back to itself. + Function *Node + + // Values associated to this node. Flat is exclusive to this node, + // Cum includes all descendents. + Flat, FlatDiv, Cum, CumDiv int64 + + // In and out Contains the nodes immediately reaching or reached by + // this node. + In, Out EdgeMap +} + +// Graph summarizes a performance profile into a format that is +// suitable for visualization. +type Graph struct { + Nodes Nodes +} + +// FlatValue returns the exclusive value for this node, computing the +// mean if a divisor is available. +func (n *Node) FlatValue() int64 { + if n.FlatDiv == 0 { + return n.Flat + } + return n.Flat / n.FlatDiv +} + +// CumValue returns the inclusive value for this node, computing the +// mean if a divisor is available. +func (n *Node) CumValue() int64 { + if n.CumDiv == 0 { + return n.Cum + } + return n.Cum / n.CumDiv +} + +// AddToEdge increases the weight of an edge between two nodes. If +// there isn't such an edge one is created. +func (n *Node) AddToEdge(to *Node, v int64, residual, inline bool) { + n.AddToEdgeDiv(to, 0, v, residual, inline) +} + +// AddToEdgeDiv increases the weight of an edge between two nodes. If +// there isn't such an edge one is created. +func (n *Node) AddToEdgeDiv(to *Node, dv, v int64, residual, inline bool) { + if e := n.Out.FindTo(to); e != nil { + e.WeightDiv += dv + e.Weight += v + if residual { + e.Residual = true + } + if !inline { + e.Inline = false + } + return + } + + info := &Edge{Src: n, Dest: to, WeightDiv: dv, Weight: v, Residual: residual, Inline: inline} + n.Out.Add(info) + to.In.Add(info) +} + +// NodeInfo contains the attributes for a node. +type NodeInfo struct { + Name string + Address uint64 + StartLine, Lineno int +} + +// PrintableName calls the Node's Formatter function with a single space separator. +func (i *NodeInfo) PrintableName() string { + return strings.Join(i.NameComponents(), " ") +} + +// NameComponents returns the components of the printable name to be used for a node. +func (i *NodeInfo) NameComponents() []string { + var name []string + if i.Address != 0 { + name = append(name, fmt.Sprintf("%016x", i.Address)) + } + if fun := i.Name; fun != "" { + name = append(name, fun) + } + + switch { + case i.Lineno != 0: + // User requested line numbers, provide what we have. + name = append(name, fmt.Sprintf(":%d", i.Lineno)) + case i.Name != "": + // User requested function name. It was already included. + default: + // Do not leave it empty if there is no information at all. + name = append(name, "") + } + return name +} + +// NodeMap maps from a node info struct to a node. It is used to merge +// report entries with the same info. +type NodeMap map[NodeInfo]*Node + +// NodeSet is a collection of node info structs. +type NodeSet map[NodeInfo]bool + +// NodePtrSet is a collection of nodes. Trimming a graph or tree requires a set +// of objects which uniquely identify the nodes to keep. In a graph, NodeInfo +// works as a unique identifier; however, in a tree multiple nodes may share +// identical NodeInfos. A *Node does uniquely identify a node so we can use that +// instead. Though a *Node also uniquely identifies a node in a graph, +// currently, during trimming, graphs are rebuilt from scratch using only the +// NodeSet, so there would not be the required context of the initial graph to +// allow for the use of *Node. +type NodePtrSet map[*Node]bool + +// FindOrInsertNode takes the info for a node and either returns a matching node +// from the node map if one exists, or adds one to the map if one does not. +// If kept is non-nil, nodes are only added if they can be located on it. +func (nm NodeMap) FindOrInsertNode(info NodeInfo, kept NodeSet) *Node { + if kept != nil { + if _, ok := kept[info]; !ok { + return nil + } + } + + if n, ok := nm[info]; ok { + return n + } + + n := &Node{ + Info: info, + } + nm[info] = n + if info.Address == 0 && info.Lineno == 0 { + // This node represents the whole function, so point Function + // back to itself. + n.Function = n + return n + } + // Find a node that represents the whole function. + info.Address = 0 + info.Lineno = 0 + n.Function = nm.FindOrInsertNode(info, nil) + return n +} + +// EdgeMap is used to represent the incoming/outgoing edges from a node. +type EdgeMap []*Edge + +func (em EdgeMap) FindTo(n *Node) *Edge { + for _, e := range em { + if e.Dest == n { + return e + } + } + return nil +} + +func (em *EdgeMap) Add(e *Edge) { + *em = append(*em, e) +} + +func (em *EdgeMap) Delete(e *Edge) { + for i, edge := range *em { + if edge == e { + (*em)[i] = (*em)[len(*em)-1] + *em = (*em)[:len(*em)-1] + return + } + } +} + +// Edge contains any attributes to be represented about edges in a graph. +type Edge struct { + Src, Dest *Node + // The summary weight of the edge + Weight, WeightDiv int64 + + // residual edges connect nodes that were connected through a + // separate node, which has been removed from the report. + Residual bool + // An inline edge represents a call that was inlined into the caller. + Inline bool +} + +// WeightValue returns the weight value for this edge, normalizing if a +// divisor is available. +func (e *Edge) WeightValue() int64 { + if e.WeightDiv == 0 { + return e.Weight + } + return e.Weight / e.WeightDiv +} + +// NewGraph computes a graph from a profile. +func NewGraph(prof *Profile, o *Options) *Graph { + nodes, locationMap := CreateNodes(prof, o) + seenNode := make(map[*Node]bool) + seenEdge := make(map[nodePair]bool) + for _, sample := range prof.Sample { + var w, dw int64 + w = o.SampleValue(sample.Value) + if o.SampleMeanDivisor != nil { + dw = o.SampleMeanDivisor(sample.Value) + } + if dw == 0 && w == 0 { + continue + } + clear(seenNode) + clear(seenEdge) + var parent *Node + // A residual edge goes over one or more nodes that were not kept. + residual := false + + // Group the sample frames, based on a global map. + // Count only the last two frames as a call edge. Frames higher up + // the stack are unlikely to be repeated calls (e.g. runtime.main + // calling main.main). So adding weights to call edges higher up + // the stack may be not reflecting the actual call edge weights + // in the program. Without a branch profile this is just an + // approximation. + i := 1 + if last := len(sample.Location) - 1; last < i { + i = last + } + for ; i >= 0; i-- { + l := sample.Location[i] + locNodes := locationMap.get(l.ID) + for ni := len(locNodes) - 1; ni >= 0; ni-- { + n := locNodes[ni] + if n == nil { + residual = true + continue + } + // Add cum weight to all nodes in stack, avoiding double counting. + _, sawNode := seenNode[n] + if !sawNode { + seenNode[n] = true + n.addSample(dw, w, false) + } + // Update edge weights for all edges in stack, avoiding double counting. + if (!sawNode || !seenEdge[nodePair{n, parent}]) && parent != nil && n != parent { + seenEdge[nodePair{n, parent}] = true + parent.AddToEdgeDiv(n, dw, w, residual, ni != len(locNodes)-1) + } + + parent = n + residual = false + } + } + if parent != nil && !residual { + // Add flat weight to leaf node. + parent.addSample(dw, w, true) + } + } + + return selectNodesForGraph(nodes, o.DropNegative) +} + +func selectNodesForGraph(nodes Nodes, dropNegative bool) *Graph { + // Collect nodes into a graph. + gNodes := make(Nodes, 0, len(nodes)) + for _, n := range nodes { + if n == nil { + continue + } + if n.Cum == 0 && n.Flat == 0 { + continue + } + if dropNegative && isNegative(n) { + continue + } + gNodes = append(gNodes, n) + } + return &Graph{gNodes} +} + +type nodePair struct { + src, dest *Node +} + +// isNegative returns true if the node is considered as "negative" for the +// purposes of drop_negative. +func isNegative(n *Node) bool { + switch { + case n.Flat < 0: + return true + case n.Flat == 0 && n.Cum < 0: + return true + default: + return false + } +} + +type locationMap struct { + s []Nodes // a slice for small sequential IDs + m map[uint64]Nodes // fallback for large IDs (unlikely) +} + +func (l *locationMap) add(id uint64, n Nodes) { + if id < uint64(len(l.s)) { + l.s[id] = n + } else { + l.m[id] = n + } +} + +func (l locationMap) get(id uint64) Nodes { + if id < uint64(len(l.s)) { + return l.s[id] + } else { + return l.m[id] + } +} + +// CreateNodes creates graph nodes for all locations in a profile. It +// returns set of all nodes, plus a mapping of each location to the +// set of corresponding nodes (one per location.Line). +func CreateNodes(prof *Profile, o *Options) (Nodes, locationMap) { + locations := locationMap{make([]Nodes, len(prof.Location)+1), make(map[uint64]Nodes)} + nm := make(NodeMap, len(prof.Location)) + for _, l := range prof.Location { + lines := l.Line + if len(lines) == 0 { + lines = []Line{{}} // Create empty line to include location info. + } + nodes := make(Nodes, len(lines)) + for ln := range lines { + nodes[ln] = nm.findOrInsertLine(l, lines[ln], o) + } + locations.add(l.ID, nodes) + } + return nm.nodes(), locations +} + +func (nm NodeMap) nodes() Nodes { + nodes := make(Nodes, 0, len(nm)) + for _, n := range nm { + nodes = append(nodes, n) + } + return nodes +} + +func (nm NodeMap) findOrInsertLine(l *Location, li Line, o *Options) *Node { + var objfile string + if m := l.Mapping; m != nil && m.File != "" { + objfile = m.File + } + + if ni := nodeInfo(l, li, objfile, o); ni != nil { + return nm.FindOrInsertNode(*ni, o.KeptNodes) + } + return nil +} + +func nodeInfo(l *Location, line Line, objfile string, o *Options) *NodeInfo { + if line.Function == nil { + return &NodeInfo{Address: l.Address} + } + ni := &NodeInfo{ + Address: l.Address, + Lineno: int(line.Line), + Name: line.Function.Name, + } + ni.StartLine = int(line.Function.StartLine) + return ni +} + +// Sum adds the flat and cum values of a set of nodes. +func (ns Nodes) Sum() (flat int64, cum int64) { + for _, n := range ns { + flat += n.Flat + cum += n.Cum + } + return +} + +func (n *Node) addSample(dw, w int64, flat bool) { + // Update sample value + if flat { + n.FlatDiv += dw + n.Flat += w + } else { + n.CumDiv += dw + n.Cum += w + } +} + +// String returns a text representation of a graph, for debugging purposes. +func (g *Graph) String() string { + var s []string + + nodeIndex := make(map[*Node]int, len(g.Nodes)) + + for i, n := range g.Nodes { + nodeIndex[n] = i + 1 + } + + for i, n := range g.Nodes { + name := n.Info.PrintableName() + var in, out []int + + for _, from := range n.In { + in = append(in, nodeIndex[from.Src]) + } + for _, to := range n.Out { + out = append(out, nodeIndex[to.Dest]) + } + s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out)) + } + return strings.Join(s, "\n") +} + +// Sort returns a slice of the edges in the map, in a consistent +// order. The sort order is first based on the edge weight +// (higher-to-lower) and then by the node names to avoid flakiness. +func (em EdgeMap) Sort() []*Edge { + el := make(edgeList, 0, len(em)) + for _, w := range em { + el = append(el, w) + } + + sort.Sort(el) + return el +} + +// Sum returns the total weight for a set of nodes. +func (em EdgeMap) Sum() int64 { + var ret int64 + for _, edge := range em { + ret += edge.Weight + } + return ret +} + +type edgeList []*Edge + +func (el edgeList) Len() int { + return len(el) +} + +func (el edgeList) Less(i, j int) bool { + if el[i].Weight != el[j].Weight { + return abs64(el[i].Weight) > abs64(el[j].Weight) + } + + from1 := el[i].Src.Info.PrintableName() + from2 := el[j].Src.Info.PrintableName() + if from1 != from2 { + return from1 < from2 + } + + to1 := el[i].Dest.Info.PrintableName() + to2 := el[j].Dest.Info.PrintableName() + + return to1 < to2 +} + +func (el edgeList) Swap(i, j int) { + el[i], el[j] = el[j], el[i] +} + +func abs64(i int64) int64 { + if i < 0 { + return -i + } + return i +} diff --git a/go/src/internal/profile/merge.go b/go/src/internal/profile/merge.go new file mode 100644 index 0000000000000000000000000000000000000000..3ea7d4cf42b921e8195d916e1f7e545715f07bbd --- /dev/null +++ b/go/src/internal/profile/merge.go @@ -0,0 +1,461 @@ +// 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 profile + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +// Merge merges all the profiles in profs into a single Profile. +// Returns a new profile independent of the input profiles. The merged +// profile is compacted to eliminate unused samples, locations, +// functions and mappings. Profiles must have identical profile sample +// and period types or the merge will fail. profile.Period of the +// resulting profile will be the maximum of all profiles, and +// profile.TimeNanos will be the earliest nonzero one. +func Merge(srcs []*Profile) (*Profile, error) { + if len(srcs) == 0 { + return nil, fmt.Errorf("no profiles to merge") + } + p, err := combineHeaders(srcs) + if err != nil { + return nil, err + } + + pm := &profileMerger{ + p: p, + samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)), + locations: make(map[locationKey]*Location, len(srcs[0].Location)), + functions: make(map[functionKey]*Function, len(srcs[0].Function)), + mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)), + } + + for _, src := range srcs { + // Clear the profile-specific hash tables + pm.locationsByID = make(map[uint64]*Location, len(src.Location)) + pm.functionsByID = make(map[uint64]*Function, len(src.Function)) + pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping)) + + if len(pm.mappings) == 0 && len(src.Mapping) > 0 { + // The Mapping list has the property that the first mapping + // represents the main binary. Take the first Mapping we see, + // otherwise the operations below will add mappings in an + // arbitrary order. + pm.mapMapping(src.Mapping[0]) + } + + for _, s := range src.Sample { + if !isZeroSample(s) { + pm.mapSample(s) + } + } + } + + for _, s := range p.Sample { + if isZeroSample(s) { + // If there are any zero samples, re-merge the profile to GC + // them. + return Merge([]*Profile{p}) + } + } + + return p, nil +} + +// Normalize normalizes the source profile by multiplying each value in profile by the +// ratio of the sum of the base profile's values of that sample type to the sum of the +// source profile's value of that sample type. +func (p *Profile) Normalize(pb *Profile) error { + + if err := p.compatible(pb); err != nil { + return err + } + + baseVals := make([]int64, len(p.SampleType)) + for _, s := range pb.Sample { + for i, v := range s.Value { + baseVals[i] += v + } + } + + srcVals := make([]int64, len(p.SampleType)) + for _, s := range p.Sample { + for i, v := range s.Value { + srcVals[i] += v + } + } + + normScale := make([]float64, len(baseVals)) + for i := range baseVals { + if srcVals[i] == 0 { + normScale[i] = 0.0 + } else { + normScale[i] = float64(baseVals[i]) / float64(srcVals[i]) + } + } + p.ScaleN(normScale) + return nil +} + +func isZeroSample(s *Sample) bool { + for _, v := range s.Value { + if v != 0 { + return false + } + } + return true +} + +type profileMerger struct { + p *Profile + + // Memoization tables within a profile. + locationsByID map[uint64]*Location + functionsByID map[uint64]*Function + mappingsByID map[uint64]mapInfo + + // Memoization tables for profile entities. + samples map[sampleKey]*Sample + locations map[locationKey]*Location + functions map[functionKey]*Function + mappings map[mappingKey]*Mapping +} + +type mapInfo struct { + m *Mapping + offset int64 +} + +func (pm *profileMerger) mapSample(src *Sample) *Sample { + s := &Sample{ + Location: make([]*Location, len(src.Location)), + Value: make([]int64, len(src.Value)), + Label: make(map[string][]string, len(src.Label)), + NumLabel: make(map[string][]int64, len(src.NumLabel)), + NumUnit: make(map[string][]string, len(src.NumLabel)), + } + for i, l := range src.Location { + s.Location[i] = pm.mapLocation(l) + } + for k, v := range src.Label { + vv := make([]string, len(v)) + copy(vv, v) + s.Label[k] = vv + } + for k, v := range src.NumLabel { + u := src.NumUnit[k] + vv := make([]int64, len(v)) + uu := make([]string, len(u)) + copy(vv, v) + copy(uu, u) + s.NumLabel[k] = vv + s.NumUnit[k] = uu + } + // Check memoization table. Must be done on the remapped location to + // account for the remapped mapping. Add current values to the + // existing sample. + k := s.key() + if ss, ok := pm.samples[k]; ok { + for i, v := range src.Value { + ss.Value[i] += v + } + return ss + } + copy(s.Value, src.Value) + pm.samples[k] = s + pm.p.Sample = append(pm.p.Sample, s) + return s +} + +// key generates sampleKey to be used as a key for maps. +func (sample *Sample) key() sampleKey { + ids := make([]string, len(sample.Location)) + for i, l := range sample.Location { + ids[i] = strconv.FormatUint(l.ID, 16) + } + + labels := make([]string, 0, len(sample.Label)) + for k, v := range sample.Label { + labels = append(labels, fmt.Sprintf("%q%q", k, v)) + } + sort.Strings(labels) + + numlabels := make([]string, 0, len(sample.NumLabel)) + for k, v := range sample.NumLabel { + numlabels = append(numlabels, fmt.Sprintf("%q%x%x", k, v, sample.NumUnit[k])) + } + sort.Strings(numlabels) + + return sampleKey{ + strings.Join(ids, "|"), + strings.Join(labels, ""), + strings.Join(numlabels, ""), + } +} + +type sampleKey struct { + locations string + labels string + numlabels string +} + +func (pm *profileMerger) mapLocation(src *Location) *Location { + if src == nil { + return nil + } + + if l, ok := pm.locationsByID[src.ID]; ok { + pm.locationsByID[src.ID] = l + return l + } + + mi := pm.mapMapping(src.Mapping) + l := &Location{ + ID: uint64(len(pm.p.Location) + 1), + Mapping: mi.m, + Address: uint64(int64(src.Address) + mi.offset), + Line: make([]Line, len(src.Line)), + IsFolded: src.IsFolded, + } + for i, ln := range src.Line { + l.Line[i] = pm.mapLine(ln) + } + // Check memoization table. Must be done on the remapped location to + // account for the remapped mapping ID. + k := l.key() + if ll, ok := pm.locations[k]; ok { + pm.locationsByID[src.ID] = ll + return ll + } + pm.locationsByID[src.ID] = l + pm.locations[k] = l + pm.p.Location = append(pm.p.Location, l) + return l +} + +// key generates locationKey to be used as a key for maps. +func (l *Location) key() locationKey { + key := locationKey{ + addr: l.Address, + isFolded: l.IsFolded, + } + if l.Mapping != nil { + // Normalizes address to handle address space randomization. + key.addr -= l.Mapping.Start + key.mappingID = l.Mapping.ID + } + lines := make([]string, len(l.Line)*2) + for i, line := range l.Line { + if line.Function != nil { + lines[i*2] = strconv.FormatUint(line.Function.ID, 16) + } + lines[i*2+1] = strconv.FormatInt(line.Line, 16) + } + key.lines = strings.Join(lines, "|") + return key +} + +type locationKey struct { + addr, mappingID uint64 + lines string + isFolded bool +} + +func (pm *profileMerger) mapMapping(src *Mapping) mapInfo { + if src == nil { + return mapInfo{} + } + + if mi, ok := pm.mappingsByID[src.ID]; ok { + return mi + } + + // Check memoization tables. + mk := src.key() + if m, ok := pm.mappings[mk]; ok { + mi := mapInfo{m, int64(m.Start) - int64(src.Start)} + pm.mappingsByID[src.ID] = mi + return mi + } + m := &Mapping{ + ID: uint64(len(pm.p.Mapping) + 1), + Start: src.Start, + Limit: src.Limit, + Offset: src.Offset, + File: src.File, + BuildID: src.BuildID, + HasFunctions: src.HasFunctions, + HasFilenames: src.HasFilenames, + HasLineNumbers: src.HasLineNumbers, + HasInlineFrames: src.HasInlineFrames, + } + pm.p.Mapping = append(pm.p.Mapping, m) + + // Update memoization tables. + pm.mappings[mk] = m + mi := mapInfo{m, 0} + pm.mappingsByID[src.ID] = mi + return mi +} + +// key generates encoded strings of Mapping to be used as a key for +// maps. +func (m *Mapping) key() mappingKey { + // Normalize addresses to handle address space randomization. + // Round up to next 4K boundary to avoid minor discrepancies. + const mapsizeRounding = 0x1000 + + size := m.Limit - m.Start + size = size + mapsizeRounding - 1 + size = size - (size % mapsizeRounding) + key := mappingKey{ + size: size, + offset: m.Offset, + } + + switch { + case m.BuildID != "": + key.buildIDOrFile = m.BuildID + case m.File != "": + key.buildIDOrFile = m.File + default: + // A mapping containing neither build ID nor file name is a fake mapping. A + // key with empty buildIDOrFile is used for fake mappings so that they are + // treated as the same mapping during merging. + } + return key +} + +type mappingKey struct { + size, offset uint64 + buildIDOrFile string +} + +func (pm *profileMerger) mapLine(src Line) Line { + ln := Line{ + Function: pm.mapFunction(src.Function), + Line: src.Line, + } + return ln +} + +func (pm *profileMerger) mapFunction(src *Function) *Function { + if src == nil { + return nil + } + if f, ok := pm.functionsByID[src.ID]; ok { + return f + } + k := src.key() + if f, ok := pm.functions[k]; ok { + pm.functionsByID[src.ID] = f + return f + } + f := &Function{ + ID: uint64(len(pm.p.Function) + 1), + Name: src.Name, + SystemName: src.SystemName, + Filename: src.Filename, + StartLine: src.StartLine, + } + pm.functions[k] = f + pm.functionsByID[src.ID] = f + pm.p.Function = append(pm.p.Function, f) + return f +} + +// key generates a struct to be used as a key for maps. +func (f *Function) key() functionKey { + return functionKey{ + f.StartLine, + f.Name, + f.SystemName, + f.Filename, + } +} + +type functionKey struct { + startLine int64 + name, systemName, fileName string +} + +// combineHeaders checks that all profiles can be merged and returns +// their combined profile. +func combineHeaders(srcs []*Profile) (*Profile, error) { + for _, s := range srcs[1:] { + if err := srcs[0].compatible(s); err != nil { + return nil, err + } + } + + var timeNanos, durationNanos, period int64 + var comments []string + seenComments := map[string]bool{} + var defaultSampleType string + for _, s := range srcs { + if timeNanos == 0 || s.TimeNanos < timeNanos { + timeNanos = s.TimeNanos + } + durationNanos += s.DurationNanos + if period == 0 || period < s.Period { + period = s.Period + } + for _, c := range s.Comments { + if seen := seenComments[c]; !seen { + comments = append(comments, c) + seenComments[c] = true + } + } + if defaultSampleType == "" { + defaultSampleType = s.DefaultSampleType + } + } + + p := &Profile{ + SampleType: make([]*ValueType, len(srcs[0].SampleType)), + + DropFrames: srcs[0].DropFrames, + KeepFrames: srcs[0].KeepFrames, + + TimeNanos: timeNanos, + DurationNanos: durationNanos, + PeriodType: srcs[0].PeriodType, + Period: period, + + Comments: comments, + DefaultSampleType: defaultSampleType, + } + copy(p.SampleType, srcs[0].SampleType) + return p, nil +} + +// compatible determines if two profiles can be compared/merged. +// returns nil if the profiles are compatible; otherwise an error with +// details on the incompatibility. +func (p *Profile) compatible(pb *Profile) error { + if !equalValueType(p.PeriodType, pb.PeriodType) { + return fmt.Errorf("incompatible period types %v and %v", p.PeriodType, pb.PeriodType) + } + + if len(p.SampleType) != len(pb.SampleType) { + return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType) + } + + for i := range p.SampleType { + if !equalValueType(p.SampleType[i], pb.SampleType[i]) { + return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType) + } + } + return nil +} + +// equalValueType returns true if the two value types are semantically +// equal. It ignores the internal fields used during encode/decode. +func equalValueType(st1, st2 *ValueType) bool { + return st1.Type == st2.Type && st1.Unit == st2.Unit +} diff --git a/go/src/internal/profile/profile.go b/go/src/internal/profile/profile.go new file mode 100644 index 0000000000000000000000000000000000000000..afd1dd72ee2d8d07770ed758a923a40375e857f8 --- /dev/null +++ b/go/src/internal/profile/profile.go @@ -0,0 +1,568 @@ +// 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 profile provides a representation of +// github.com/google/pprof/proto/profile.proto and +// methods to encode/decode/merge profiles in this format. +package profile + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "strings" + "time" +) + +// Profile is an in-memory representation of profile.proto. +type Profile struct { + SampleType []*ValueType + DefaultSampleType string + Sample []*Sample + Mapping []*Mapping + Location []*Location + Function []*Function + Comments []string + + DropFrames string + KeepFrames string + + TimeNanos int64 + DurationNanos int64 + PeriodType *ValueType + Period int64 + + commentX []int64 + dropFramesX int64 + keepFramesX int64 + stringTable []string + defaultSampleTypeX int64 +} + +// ValueType corresponds to Profile.ValueType +type ValueType struct { + Type string // cpu, wall, inuse_space, etc + Unit string // seconds, nanoseconds, bytes, etc + + typeX int64 + unitX int64 +} + +// Sample corresponds to Profile.Sample +type Sample struct { + Location []*Location + Value []int64 + Label map[string][]string + NumLabel map[string][]int64 + NumUnit map[string][]string + + locationIDX []uint64 + labelX []Label +} + +// Label corresponds to Profile.Label +type Label struct { + keyX int64 + // Exactly one of the two following values must be set + strX int64 + numX int64 // Integer value for this label +} + +// Mapping corresponds to Profile.Mapping +type Mapping struct { + ID uint64 + Start uint64 + Limit uint64 + Offset uint64 + File string + BuildID string + HasFunctions bool + HasFilenames bool + HasLineNumbers bool + HasInlineFrames bool + + fileX int64 + buildIDX int64 +} + +// Location corresponds to Profile.Location +type Location struct { + ID uint64 + Mapping *Mapping + Address uint64 + Line []Line + IsFolded bool + + mappingIDX uint64 +} + +// Line corresponds to Profile.Line +type Line struct { + Function *Function + Line int64 + + functionIDX uint64 +} + +// Function corresponds to Profile.Function +type Function struct { + ID uint64 + Name string + SystemName string + Filename string + StartLine int64 + + nameX int64 + systemNameX int64 + filenameX int64 +} + +// Parse parses a profile and checks for its validity. The input must be an +// encoded pprof protobuf, which may optionally be gzip-compressed. +func Parse(r io.Reader) (*Profile, error) { + orig, err := io.ReadAll(r) + if err != nil { + return nil, err + } + + if len(orig) >= 2 && orig[0] == 0x1f && orig[1] == 0x8b { + gz, err := gzip.NewReader(bytes.NewBuffer(orig)) + if err != nil { + return nil, fmt.Errorf("decompressing profile: %v", err) + } + data, err := io.ReadAll(gz) + if err != nil { + return nil, fmt.Errorf("decompressing profile: %v", err) + } + orig = data + } + + p, err := parseUncompressed(orig) + if err != nil { + return nil, fmt.Errorf("parsing profile: %w", err) + } + + if err := p.CheckValid(); err != nil { + return nil, fmt.Errorf("malformed profile: %v", err) + } + return p, nil +} + +var errMalformed = fmt.Errorf("malformed profile format") +var ErrNoData = fmt.Errorf("empty input file") + +func parseUncompressed(data []byte) (*Profile, error) { + if len(data) == 0 { + return nil, ErrNoData + } + + p := &Profile{} + if err := unmarshal(data, p); err != nil { + return nil, err + } + + if err := p.postDecode(); err != nil { + return nil, err + } + + return p, nil +} + +// Write writes the profile as a gzip-compressed marshaled protobuf. +func (p *Profile) Write(w io.Writer) error { + p.preEncode() + b := marshal(p) + zw := gzip.NewWriter(w) + defer zw.Close() + _, err := zw.Write(b) + return err +} + +// CheckValid tests whether the profile is valid. Checks include, but are +// not limited to: +// - len(Profile.Sample[n].value) == len(Profile.value_unit) +// - Sample.id has a corresponding Profile.Location +func (p *Profile) CheckValid() error { + // Check that sample values are consistent + sampleLen := len(p.SampleType) + if sampleLen == 0 && len(p.Sample) != 0 { + return fmt.Errorf("missing sample type information") + } + for _, s := range p.Sample { + if len(s.Value) != sampleLen { + return fmt.Errorf("mismatch: sample has: %d values vs. %d types", len(s.Value), len(p.SampleType)) + } + } + + // Check that all mappings/locations/functions are in the tables + // Check that there are no duplicate ids + mappings := make(map[uint64]*Mapping, len(p.Mapping)) + for _, m := range p.Mapping { + if m.ID == 0 { + return fmt.Errorf("found mapping with reserved ID=0") + } + if mappings[m.ID] != nil { + return fmt.Errorf("multiple mappings with same id: %d", m.ID) + } + mappings[m.ID] = m + } + functions := make(map[uint64]*Function, len(p.Function)) + for _, f := range p.Function { + if f.ID == 0 { + return fmt.Errorf("found function with reserved ID=0") + } + if functions[f.ID] != nil { + return fmt.Errorf("multiple functions with same id: %d", f.ID) + } + functions[f.ID] = f + } + locations := make(map[uint64]*Location, len(p.Location)) + for _, l := range p.Location { + if l.ID == 0 { + return fmt.Errorf("found location with reserved id=0") + } + if locations[l.ID] != nil { + return fmt.Errorf("multiple locations with same id: %d", l.ID) + } + locations[l.ID] = l + if m := l.Mapping; m != nil { + if m.ID == 0 || mappings[m.ID] != m { + return fmt.Errorf("inconsistent mapping %p: %d", m, m.ID) + } + } + for _, ln := range l.Line { + if f := ln.Function; f != nil { + if f.ID == 0 || functions[f.ID] != f { + return fmt.Errorf("inconsistent function %p: %d", f, f.ID) + } + } + } + } + return nil +} + +// Aggregate merges the locations in the profile into equivalence +// classes preserving the request attributes. It also updates the +// samples to point to the merged locations. +func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address bool) error { + for _, m := range p.Mapping { + m.HasInlineFrames = m.HasInlineFrames && inlineFrame + m.HasFunctions = m.HasFunctions && function + m.HasFilenames = m.HasFilenames && filename + m.HasLineNumbers = m.HasLineNumbers && linenumber + } + + // Aggregate functions + if !function || !filename { + for _, f := range p.Function { + if !function { + f.Name = "" + f.SystemName = "" + } + if !filename { + f.Filename = "" + } + } + } + + // Aggregate locations + if !inlineFrame || !address || !linenumber { + for _, l := range p.Location { + if !inlineFrame && len(l.Line) > 1 { + l.Line = l.Line[len(l.Line)-1:] + } + if !linenumber { + for i := range l.Line { + l.Line[i].Line = 0 + } + } + if !address { + l.Address = 0 + } + } + } + + return p.CheckValid() +} + +// Print dumps a text representation of a profile. Intended mainly +// for debugging purposes. +func (p *Profile) String() string { + + ss := make([]string, 0, len(p.Sample)+len(p.Mapping)+len(p.Location)) + if pt := p.PeriodType; pt != nil { + ss = append(ss, fmt.Sprintf("PeriodType: %s %s", pt.Type, pt.Unit)) + } + ss = append(ss, fmt.Sprintf("Period: %d", p.Period)) + if p.TimeNanos != 0 { + ss = append(ss, fmt.Sprintf("Time: %v", time.Unix(0, p.TimeNanos))) + } + if p.DurationNanos != 0 { + ss = append(ss, fmt.Sprintf("Duration: %v", time.Duration(p.DurationNanos))) + } + + ss = append(ss, "Samples:") + var sh1 string + for _, s := range p.SampleType { + sh1 = sh1 + fmt.Sprintf("%s/%s ", s.Type, s.Unit) + } + ss = append(ss, strings.TrimSpace(sh1)) + for _, s := range p.Sample { + var sv string + for _, v := range s.Value { + sv = fmt.Sprintf("%s %10d", sv, v) + } + sv = sv + ": " + for _, l := range s.Location { + sv = sv + fmt.Sprintf("%d ", l.ID) + } + ss = append(ss, sv) + const labelHeader = " " + if len(s.Label) > 0 { + ls := labelHeader + for k, v := range s.Label { + ls = ls + fmt.Sprintf("%s:%v ", k, v) + } + ss = append(ss, ls) + } + if len(s.NumLabel) > 0 { + ls := labelHeader + for k, v := range s.NumLabel { + ls = ls + fmt.Sprintf("%s:%v ", k, v) + } + ss = append(ss, ls) + } + } + + ss = append(ss, "Locations") + for _, l := range p.Location { + locStr := fmt.Sprintf("%6d: %#x ", l.ID, l.Address) + if m := l.Mapping; m != nil { + locStr = locStr + fmt.Sprintf("M=%d ", m.ID) + } + if len(l.Line) == 0 { + ss = append(ss, locStr) + } + for li := range l.Line { + lnStr := "??" + if fn := l.Line[li].Function; fn != nil { + lnStr = fmt.Sprintf("%s %s:%d s=%d", + fn.Name, + fn.Filename, + l.Line[li].Line, + fn.StartLine) + if fn.Name != fn.SystemName { + lnStr = lnStr + "(" + fn.SystemName + ")" + } + } + ss = append(ss, locStr+lnStr) + // Do not print location details past the first line + locStr = " " + } + } + + ss = append(ss, "Mappings") + for _, m := range p.Mapping { + bits := "" + if m.HasFunctions { + bits += "[FN]" + } + if m.HasFilenames { + bits += "[FL]" + } + if m.HasLineNumbers { + bits += "[LN]" + } + if m.HasInlineFrames { + bits += "[IN]" + } + ss = append(ss, fmt.Sprintf("%d: %#x/%#x/%#x %s %s %s", + m.ID, + m.Start, m.Limit, m.Offset, + m.File, + m.BuildID, + bits)) + } + + return strings.Join(ss, "\n") + "\n" +} + +// Merge adds profile p adjusted by ratio r into profile p. Profiles +// must be compatible (same Type and SampleType). +// TODO(rsilvera): consider normalizing the profiles based on the +// total samples collected. +func (p *Profile) Merge(pb *Profile, r float64) error { + if err := p.Compatible(pb); err != nil { + return err + } + + pb = pb.Copy() + + // Keep the largest of the two periods. + if pb.Period > p.Period { + p.Period = pb.Period + } + + p.DurationNanos += pb.DurationNanos + + p.Mapping = append(p.Mapping, pb.Mapping...) + for i, m := range p.Mapping { + m.ID = uint64(i + 1) + } + p.Location = append(p.Location, pb.Location...) + for i, l := range p.Location { + l.ID = uint64(i + 1) + } + p.Function = append(p.Function, pb.Function...) + for i, f := range p.Function { + f.ID = uint64(i + 1) + } + + if r != 1.0 { + for _, s := range pb.Sample { + for i, v := range s.Value { + s.Value[i] = int64((float64(v) * r)) + } + } + } + p.Sample = append(p.Sample, pb.Sample...) + return p.CheckValid() +} + +// Compatible determines if two profiles can be compared/merged. +// returns nil if the profiles are compatible; otherwise an error with +// details on the incompatibility. +func (p *Profile) Compatible(pb *Profile) error { + if !compatibleValueTypes(p.PeriodType, pb.PeriodType) { + return fmt.Errorf("incompatible period types %v and %v", p.PeriodType, pb.PeriodType) + } + + if len(p.SampleType) != len(pb.SampleType) { + return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType) + } + + for i := range p.SampleType { + if !compatibleValueTypes(p.SampleType[i], pb.SampleType[i]) { + return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType) + } + } + + return nil +} + +// HasFunctions determines if all locations in this profile have +// symbolized function information. +func (p *Profile) HasFunctions() bool { + for _, l := range p.Location { + if l.Mapping == nil || !l.Mapping.HasFunctions { + return false + } + } + return true +} + +// HasFileLines determines if all locations in this profile have +// symbolized file and line number information. +func (p *Profile) HasFileLines() bool { + for _, l := range p.Location { + if l.Mapping == nil || (!l.Mapping.HasFilenames || !l.Mapping.HasLineNumbers) { + return false + } + } + return true +} + +func compatibleValueTypes(v1, v2 *ValueType) bool { + if v1 == nil || v2 == nil { + return true // No grounds to disqualify. + } + return v1.Type == v2.Type && v1.Unit == v2.Unit +} + +// Copy makes a fully independent copy of a profile. +func (p *Profile) Copy() *Profile { + p.preEncode() + b := marshal(p) + + pp := &Profile{} + if err := unmarshal(b, pp); err != nil { + panic(err) + } + if err := pp.postDecode(); err != nil { + panic(err) + } + + return pp +} + +// Demangler maps symbol names to a human-readable form. This may +// include C++ demangling and additional simplification. Names that +// are not demangled may be missing from the resulting map. +type Demangler func(name []string) (map[string]string, error) + +// Demangle attempts to demangle and optionally simplify any function +// names referenced in the profile. It works on a best-effort basis: +// it will silently preserve the original names in case of any errors. +func (p *Profile) Demangle(d Demangler) error { + // Collect names to demangle. + var names []string + for _, fn := range p.Function { + names = append(names, fn.SystemName) + } + + // Update profile with demangled names. + demangled, err := d(names) + if err != nil { + return err + } + for _, fn := range p.Function { + if dd, ok := demangled[fn.SystemName]; ok { + fn.Name = dd + } + } + return nil +} + +// Empty reports whether the profile contains no samples. +func (p *Profile) Empty() bool { + return len(p.Sample) == 0 +} + +// Scale multiplies all sample values in a profile by a constant. +func (p *Profile) Scale(ratio float64) { + if ratio == 1 { + return + } + ratios := make([]float64, len(p.SampleType)) + for i := range p.SampleType { + ratios[i] = ratio + } + p.ScaleN(ratios) +} + +// ScaleN multiplies each sample values in a sample by a different amount. +func (p *Profile) ScaleN(ratios []float64) error { + if len(p.SampleType) != len(ratios) { + return fmt.Errorf("mismatched scale ratios, got %d, want %d", len(ratios), len(p.SampleType)) + } + allOnes := true + for _, r := range ratios { + if r != 1 { + allOnes = false + break + } + } + if allOnes { + return nil + } + for _, s := range p.Sample { + for i, v := range s.Value { + if ratios[i] != 1 { + s.Value[i] = int64(float64(v) * ratios[i]) + } + } + } + return nil +} diff --git a/go/src/internal/profile/proto.go b/go/src/internal/profile/proto.go new file mode 100644 index 0000000000000000000000000000000000000000..ad6f621f883c7d6b75ff652786cbd3fd60f66158 --- /dev/null +++ b/go/src/internal/profile/proto.go @@ -0,0 +1,373 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a simple protocol buffer encoder and decoder. +// +// A protocol message must implement the message interface: +// decoder() []decoder +// encode(*buffer) +// +// The decode method returns a slice indexed by field number that gives the +// function to decode that field. +// The encode method encodes its receiver into the given buffer. +// +// The two methods are simple enough to be implemented by hand rather than +// by using a protocol compiler. +// +// See profile.go for examples of messages implementing this interface. +// +// There is no support for groups, message sets, or "has" bits. + +package profile + +import ( + "errors" + "fmt" + "slices" +) + +type buffer struct { + field int + typ int + u64 uint64 + data []byte + tmp [16]byte +} + +type decoder func(*buffer, message) error + +type message interface { + decoder() []decoder + encode(*buffer) +} + +func marshal(m message) []byte { + var b buffer + m.encode(&b) + return b.data +} + +func encodeVarint(b *buffer, x uint64) { + for x >= 128 { + b.data = append(b.data, byte(x)|0x80) + x >>= 7 + } + b.data = append(b.data, byte(x)) +} + +func encodeLength(b *buffer, tag int, len int) { + encodeVarint(b, uint64(tag)<<3|2) + encodeVarint(b, uint64(len)) +} + +func encodeUint64(b *buffer, tag int, x uint64) { + // append varint to b.data + encodeVarint(b, uint64(tag)<<3|0) + encodeVarint(b, x) +} + +func encodeUint64s(b *buffer, tag int, x []uint64) { + if len(x) > 2 { + // Use packed encoding + n1 := len(b.data) + for _, u := range x { + encodeVarint(b, u) + } + n2 := len(b.data) + encodeLength(b, tag, n2-n1) + n3 := len(b.data) + copy(b.tmp[:], b.data[n2:n3]) + copy(b.data[n1+(n3-n2):], b.data[n1:n2]) + copy(b.data[n1:], b.tmp[:n3-n2]) + return + } + for _, u := range x { + encodeUint64(b, tag, u) + } +} + +func encodeUint64Opt(b *buffer, tag int, x uint64) { + if x == 0 { + return + } + encodeUint64(b, tag, x) +} + +func encodeInt64(b *buffer, tag int, x int64) { + u := uint64(x) + encodeUint64(b, tag, u) +} + +func encodeInt64Opt(b *buffer, tag int, x int64) { + if x == 0 { + return + } + encodeInt64(b, tag, x) +} + +func encodeInt64s(b *buffer, tag int, x []int64) { + if len(x) > 2 { + // Use packed encoding + n1 := len(b.data) + for _, u := range x { + encodeVarint(b, uint64(u)) + } + n2 := len(b.data) + encodeLength(b, tag, n2-n1) + n3 := len(b.data) + copy(b.tmp[:], b.data[n2:n3]) + copy(b.data[n1+(n3-n2):], b.data[n1:n2]) + copy(b.data[n1:], b.tmp[:n3-n2]) + return + } + for _, u := range x { + encodeInt64(b, tag, u) + } +} + +func encodeString(b *buffer, tag int, x string) { + encodeLength(b, tag, len(x)) + b.data = append(b.data, x...) +} + +func encodeStrings(b *buffer, tag int, x []string) { + for _, s := range x { + encodeString(b, tag, s) + } +} + +func encodeBool(b *buffer, tag int, x bool) { + if x { + encodeUint64(b, tag, 1) + } else { + encodeUint64(b, tag, 0) + } +} + +func encodeBoolOpt(b *buffer, tag int, x bool) { + if !x { + return + } + encodeBool(b, tag, x) +} + +func encodeMessage(b *buffer, tag int, m message) { + n1 := len(b.data) + m.encode(b) + n2 := len(b.data) + encodeLength(b, tag, n2-n1) + n3 := len(b.data) + copy(b.tmp[:], b.data[n2:n3]) + copy(b.data[n1+(n3-n2):], b.data[n1:n2]) + copy(b.data[n1:], b.tmp[:n3-n2]) +} + +func unmarshal(data []byte, m message) (err error) { + b := buffer{data: data, typ: 2} + return decodeMessage(&b, m) +} + +func le64(p []byte) uint64 { + return uint64(p[0]) | uint64(p[1])<<8 | uint64(p[2])<<16 | uint64(p[3])<<24 | uint64(p[4])<<32 | uint64(p[5])<<40 | uint64(p[6])<<48 | uint64(p[7])<<56 +} + +func le32(p []byte) uint32 { + return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24 +} + +func peekNumVarints(data []byte) (numVarints int) { + for ; len(data) > 0; numVarints++ { + var err error + if _, data, err = decodeVarint(data); err != nil { + break + } + } + return numVarints +} + +func decodeVarint(data []byte) (uint64, []byte, error) { + var i int + var u uint64 + for i = 0; ; i++ { + if i >= 10 || i >= len(data) { + return 0, nil, errors.New("bad varint") + } + u |= uint64(data[i]&0x7F) << uint(7*i) + if data[i]&0x80 == 0 { + return u, data[i+1:], nil + } + } +} + +func decodeField(b *buffer, data []byte) ([]byte, error) { + x, data, err := decodeVarint(data) + if err != nil { + return nil, err + } + b.field = int(x >> 3) + b.typ = int(x & 7) + b.data = nil + b.u64 = 0 + switch b.typ { + case 0: + b.u64, data, err = decodeVarint(data) + if err != nil { + return nil, err + } + case 1: + if len(data) < 8 { + return nil, errors.New("not enough data") + } + b.u64 = le64(data[:8]) + data = data[8:] + case 2: + var n uint64 + n, data, err = decodeVarint(data) + if err != nil { + return nil, err + } + if n > uint64(len(data)) { + return nil, errors.New("too much data") + } + b.data = data[:n] + data = data[n:] + case 5: + if len(data) < 4 { + return nil, errors.New("not enough data") + } + b.u64 = uint64(le32(data[:4])) + data = data[4:] + default: + return nil, fmt.Errorf("unknown wire type: %d", b.typ) + } + + return data, nil +} + +func checkType(b *buffer, typ int) error { + if b.typ != typ { + return errors.New("type mismatch") + } + return nil +} + +func decodeMessage(b *buffer, m message) error { + if err := checkType(b, 2); err != nil { + return err + } + dec := m.decoder() + data := b.data + for len(data) > 0 { + // pull varint field# + type + var err error + data, err = decodeField(b, data) + if err != nil { + return err + } + if b.field >= len(dec) || dec[b.field] == nil { + continue + } + if err := dec[b.field](b, m); err != nil { + return err + } + } + return nil +} + +func decodeInt64(b *buffer, x *int64) error { + if err := checkType(b, 0); err != nil { + return err + } + *x = int64(b.u64) + return nil +} + +func decodeInt64s(b *buffer, x *[]int64) error { + if b.typ == 2 { + // Packed encoding + dataLen := peekNumVarints(b.data) + *x = slices.Grow(*x, dataLen) + + data := b.data + for len(data) > 0 { + var u uint64 + var err error + + if u, data, err = decodeVarint(data); err != nil { + return err + } + *x = append(*x, int64(u)) + } + return nil + } + var i int64 + if err := decodeInt64(b, &i); err != nil { + return err + } + *x = append(*x, i) + return nil +} + +func decodeUint64(b *buffer, x *uint64) error { + if err := checkType(b, 0); err != nil { + return err + } + *x = b.u64 + return nil +} + +func decodeUint64s(b *buffer, x *[]uint64) error { + if b.typ == 2 { + // Packed encoding + dataLen := peekNumVarints(b.data) + *x = slices.Grow(*x, dataLen) + + data := b.data + for len(data) > 0 { + var u uint64 + var err error + + if u, data, err = decodeVarint(data); err != nil { + return err + } + *x = append(*x, u) + } + return nil + } + var u uint64 + if err := decodeUint64(b, &u); err != nil { + return err + } + *x = append(*x, u) + return nil +} + +func decodeString(b *buffer, x *string) error { + if err := checkType(b, 2); err != nil { + return err + } + *x = string(b.data) + return nil +} + +func decodeStrings(b *buffer, x *[]string) error { + var s string + if err := decodeString(b, &s); err != nil { + return err + } + *x = append(*x, s) + return nil +} + +func decodeBool(b *buffer, x *bool) error { + if err := checkType(b, 0); err != nil { + return err + } + if int64(b.u64) == 0 { + *x = false + } else { + *x = true + } + return nil +} diff --git a/go/src/internal/profile/proto_test.go b/go/src/internal/profile/proto_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4c09f7c47e1411ae033a3993f562246d8c03e386 --- /dev/null +++ b/go/src/internal/profile/proto_test.go @@ -0,0 +1,71 @@ +// 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 profile + +import ( + "slices" + "testing" +) + +func TestPackedEncoding(t *testing.T) { + + type testcase struct { + uint64s []uint64 + int64s []int64 + encoded []byte + } + for i, tc := range []testcase{ + { + []uint64{0, 1, 10, 100, 1000, 10000}, + []int64{1000, 0, 1000}, + []byte{10, 8, 0, 1, 10, 100, 232, 7, 144, 78, 18, 5, 232, 7, 0, 232, 7}, + }, + { + []uint64{10000}, + nil, + []byte{8, 144, 78}, + }, + { + nil, + []int64{-10000}, + []byte{16, 240, 177, 255, 255, 255, 255, 255, 255, 255, 1}, + }, + } { + source := &packedInts{tc.uint64s, tc.int64s} + if got, want := marshal(source), tc.encoded; !slices.Equal(got, want) { + t.Errorf("failed encode %d, got %v, want %v", i, got, want) + } + + dest := new(packedInts) + if err := unmarshal(tc.encoded, dest); err != nil { + t.Errorf("failed decode %d: %v", i, err) + continue + } + if got, want := dest.uint64s, tc.uint64s; !slices.Equal(got, want) { + t.Errorf("failed decode uint64s %d, got %v, want %v", i, got, want) + } + if got, want := dest.int64s, tc.int64s; !slices.Equal(got, want) { + t.Errorf("failed decode int64s %d, got %v, want %v", i, got, want) + } + } +} + +type packedInts struct { + uint64s []uint64 + int64s []int64 +} + +func (u *packedInts) decoder() []decoder { + return []decoder{ + nil, + func(b *buffer, m message) error { return decodeUint64s(b, &m.(*packedInts).uint64s) }, + func(b *buffer, m message) error { return decodeInt64s(b, &m.(*packedInts).int64s) }, + } +} + +func (u *packedInts) encode(b *buffer) { + encodeUint64s(b, 1, u.uint64s) + encodeInt64s(b, 2, u.int64s) +} diff --git a/go/src/internal/profile/prune.go b/go/src/internal/profile/prune.go new file mode 100644 index 0000000000000000000000000000000000000000..1924fada7a506e377661ef950ae1aea4cc3bf2d6 --- /dev/null +++ b/go/src/internal/profile/prune.go @@ -0,0 +1,97 @@ +// 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. + +// Implements methods to remove frames from profiles. + +package profile + +import ( + "fmt" + "regexp" +) + +// Prune removes all nodes beneath a node matching dropRx, and not +// matching keepRx. If the root node of a Sample matches, the sample +// will have an empty stack. +func (p *Profile) Prune(dropRx, keepRx *regexp.Regexp) { + prune := make(map[uint64]bool) + pruneBeneath := make(map[uint64]bool) + + for _, loc := range p.Location { + var i int + for i = len(loc.Line) - 1; i >= 0; i-- { + if fn := loc.Line[i].Function; fn != nil && fn.Name != "" { + funcName := fn.Name + // Account for leading '.' on the PPC ELF v1 ABI. + if funcName[0] == '.' { + funcName = funcName[1:] + } + if dropRx.MatchString(funcName) { + if keepRx == nil || !keepRx.MatchString(funcName) { + break + } + } + } + } + + if i >= 0 { + // Found matching entry to prune. + pruneBeneath[loc.ID] = true + + // Remove the matching location. + if i == len(loc.Line)-1 { + // Matched the top entry: prune the whole location. + prune[loc.ID] = true + } else { + loc.Line = loc.Line[i+1:] + } + } + } + + // Prune locs from each Sample + for _, sample := range p.Sample { + // Scan from the root to the leaves to find the prune location. + // Do not prune frames before the first user frame, to avoid + // pruning everything. + foundUser := false + for i := len(sample.Location) - 1; i >= 0; i-- { + id := sample.Location[i].ID + if !prune[id] && !pruneBeneath[id] { + foundUser = true + continue + } + if !foundUser { + continue + } + if prune[id] { + sample.Location = sample.Location[i+1:] + break + } + if pruneBeneath[id] { + sample.Location = sample.Location[i:] + break + } + } + } +} + +// RemoveUninteresting prunes and elides profiles using built-in +// tables of uninteresting function names. +func (p *Profile) RemoveUninteresting() error { + var keep, drop *regexp.Regexp + var err error + + if p.DropFrames != "" { + if drop, err = regexp.Compile("^(" + p.DropFrames + ")$"); err != nil { + return fmt.Errorf("failed to compile regexp %s: %v", p.DropFrames, err) + } + if p.KeepFrames != "" { + if keep, err = regexp.Compile("^(" + p.KeepFrames + ")$"); err != nil { + return fmt.Errorf("failed to compile regexp %s: %v", p.KeepFrames, err) + } + } + p.Prune(drop, keep) + } + return nil +} diff --git a/go/src/internal/profilerecord/profilerecord.go b/go/src/internal/profilerecord/profilerecord.go new file mode 100644 index 0000000000000000000000000000000000000000..a5efdced8f77c9992797d01f4878943d6da84a90 --- /dev/null +++ b/go/src/internal/profilerecord/profilerecord.go @@ -0,0 +1,28 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package profilerecord holds internal types used to represent profiling +// records with deep stack traces. +// +// TODO: Consider moving this to internal/runtime, see golang.org/issue/65355. +package profilerecord + +type StackRecord struct { + Stack []uintptr +} + +type MemProfileRecord struct { + AllocBytes, FreeBytes int64 + AllocObjects, FreeObjects int64 + Stack []uintptr +} + +func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes } +func (r *MemProfileRecord) InUseObjects() int64 { return r.AllocObjects - r.FreeObjects } + +type BlockProfileRecord struct { + Count int64 + Cycles int64 + Stack []uintptr +} diff --git a/go/src/internal/race/doc.go b/go/src/internal/race/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..8fa44ce6f19ef2dbfb49e11275af0aaa9d8e0945 --- /dev/null +++ b/go/src/internal/race/doc.go @@ -0,0 +1,11 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package race contains helper functions for manually instrumenting code for the race detector. + +The runtime package intentionally exports these functions only in the race build; +this package exports them unconditionally but without the "race" build tag they are no-ops. +*/ +package race diff --git a/go/src/internal/race/norace.go b/go/src/internal/race/norace.go new file mode 100644 index 0000000000000000000000000000000000000000..3fb00573a070efc892f277bc6dad4383f570cc44 --- /dev/null +++ b/go/src/internal/race/norace.go @@ -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. + +//go:build !race + +package race + +import ( + "internal/abi" + "unsafe" +) + +const Enabled = false + +func Acquire(addr unsafe.Pointer) { +} + +func Release(addr unsafe.Pointer) { +} + +func ReleaseMerge(addr unsafe.Pointer) { +} + +func Disable() { +} + +func Enable() { +} + +func Read(addr unsafe.Pointer) { +} + +func ReadPC(addr unsafe.Pointer, callerpc, pc uintptr) { +} + +func ReadObjectPC(t *abi.Type, addr unsafe.Pointer, callerpc, pc uintptr) { +} + +func Write(addr unsafe.Pointer) { +} + +func WritePC(addr unsafe.Pointer, callerpc, pc uintptr) { +} + +func WriteObjectPC(t *abi.Type, addr unsafe.Pointer, callerpc, pc uintptr) { +} + +func ReadRange(addr unsafe.Pointer, len int) { +} + +func WriteRange(addr unsafe.Pointer, len int) { +} + +func Errors() int { return 0 } diff --git a/go/src/internal/race/race.go b/go/src/internal/race/race.go new file mode 100644 index 0000000000000000000000000000000000000000..bfcb24a2694e853042ce3690e1508102f6e1a172 --- /dev/null +++ b/go/src/internal/race/race.go @@ -0,0 +1,58 @@ +// 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 race + +package race + +import ( + "internal/abi" + "unsafe" +) + +const Enabled = true + +// Functions below pushed from runtime. + +//go:linkname Acquire +func Acquire(addr unsafe.Pointer) + +//go:linkname Release +func Release(addr unsafe.Pointer) + +//go:linkname ReleaseMerge +func ReleaseMerge(addr unsafe.Pointer) + +//go:linkname Disable +func Disable() + +//go:linkname Enable +func Enable() + +//go:linkname Read +func Read(addr unsafe.Pointer) + +//go:linkname ReadPC +func ReadPC(addr unsafe.Pointer, callerpc, pc uintptr) + +//go:linkname ReadObjectPC +func ReadObjectPC(t *abi.Type, addr unsafe.Pointer, callerpc, pc uintptr) + +//go:linkname Write +func Write(addr unsafe.Pointer) + +//go:linkname WritePC +func WritePC(addr unsafe.Pointer, callerpc, pc uintptr) + +//go:linkname WriteObjectPC +func WriteObjectPC(t *abi.Type, addr unsafe.Pointer, callerpc, pc uintptr) + +//go:linkname ReadRange +func ReadRange(addr unsafe.Pointer, len int) + +//go:linkname WriteRange +func WriteRange(addr unsafe.Pointer, len int) + +//go:linkname Errors +func Errors() int diff --git a/go/src/internal/reflectlite/all_test.go b/go/src/internal/reflectlite/all_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a78f9ae70f9e3eacefd6d247c870dd30144ea982 --- /dev/null +++ b/go/src/internal/reflectlite/all_test.go @@ -0,0 +1,1039 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package reflectlite_test + +import ( + "encoding/base64" + "fmt" + "internal/abi" + . "internal/reflectlite" + "math" + "reflect" + "runtime" + "testing" + "unsafe" +) + +func ToValue(v Value) reflect.Value { + return reflect.ValueOf(ToInterface(v)) +} + +func TypeString(t Type) string { + return fmt.Sprintf("%T", ToInterface(Zero(t))) +} + +type integer int +type T struct { + a int + b float64 + c string + d *int +} + +type pair struct { + i any + s string +} + +func assert(t *testing.T, s, want string) { + t.Helper() + if s != want { + t.Errorf("have %#q want %#q", s, want) + } +} + +var typeTests = []pair{ + {struct{ x int }{}, "int"}, + {struct{ x int8 }{}, "int8"}, + {struct{ x int16 }{}, "int16"}, + {struct{ x int32 }{}, "int32"}, + {struct{ x int64 }{}, "int64"}, + {struct{ x uint }{}, "uint"}, + {struct{ x uint8 }{}, "uint8"}, + {struct{ x uint16 }{}, "uint16"}, + {struct{ x uint32 }{}, "uint32"}, + {struct{ x uint64 }{}, "uint64"}, + {struct{ x float32 }{}, "float32"}, + {struct{ x float64 }{}, "float64"}, + {struct{ x int8 }{}, "int8"}, + {struct{ x (**int8) }{}, "**int8"}, + {struct{ x (**integer) }{}, "**reflectlite_test.integer"}, + {struct{ x ([32]int32) }{}, "[32]int32"}, + {struct{ x ([]int8) }{}, "[]int8"}, + {struct{ x (map[string]int32) }{}, "map[string]int32"}, + {struct{ x (chan<- string) }{}, "chan<- string"}, + {struct { + x struct { + c chan *int32 + d float32 + } + }{}, + "struct { c chan *int32; d float32 }", + }, + {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"}, + {struct { + x struct { + c func(chan *integer, *int8) + } + }{}, + "struct { c func(chan *reflectlite_test.integer, *int8) }", + }, + {struct { + x struct { + a int8 + b int32 + } + }{}, + "struct { a int8; b int32 }", + }, + {struct { + x struct { + a int8 + b int8 + c int32 + } + }{}, + "struct { a int8; b int8; c int32 }", + }, + {struct { + x struct { + a int8 + b int8 + c int8 + d int32 + } + }{}, + "struct { a int8; b int8; c int8; d int32 }", + }, + {struct { + x struct { + a int8 + b int8 + c int8 + d int8 + e int32 + } + }{}, + "struct { a int8; b int8; c int8; d int8; e int32 }", + }, + {struct { + x struct { + a int8 + b int8 + c int8 + d int8 + e int8 + f int32 + } + }{}, + "struct { a int8; b int8; c int8; d int8; e int8; f int32 }", + }, + {struct { + x struct { + a int8 `reflect:"hi there"` + } + }{}, + `struct { a int8 "reflect:\"hi there\"" }`, + }, + {struct { + x struct { + a int8 `reflect:"hi \x00there\t\n\"\\"` + } + }{}, + `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`, + }, + {struct { + x struct { + f func(args ...int) + } + }{}, + "struct { f func(...int) }", + }, + // {struct { + // x (interface { + // a(func(func(int) int) func(func(int)) int) + // b() + // }) + // }{}, + // "interface { reflectlite_test.a(func(func(int) int) func(func(int)) int); reflectlite_test.b() }", + // }, + {struct { + x struct { + int32 + int64 + } + }{}, + "struct { int32; int64 }", + }, +} + +var valueTests = []pair{ + {new(int), "132"}, + {new(int8), "8"}, + {new(int16), "16"}, + {new(int32), "32"}, + {new(int64), "64"}, + {new(uint), "132"}, + {new(uint8), "8"}, + {new(uint16), "16"}, + {new(uint32), "32"}, + {new(uint64), "64"}, + {new(float32), "256.25"}, + {new(float64), "512.125"}, + {new(complex64), "532.125+10i"}, + {new(complex128), "564.25+1i"}, + {new(string), "stringy cheese"}, + {new(bool), "true"}, + {new(*int8), "*int8(0)"}, + {new(**int8), "**int8(0)"}, + {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"}, + {new(**integer), "**reflectlite_test.integer(0)"}, + {new(map[string]int32), "map[string]int32{}"}, + {new(chan<- string), "chan<- string"}, + {new(func(a int8, b int32)), "func(int8, int32)(arg)"}, + {new(struct { + c chan *int32 + d float32 + }), + "struct { c chan *int32; d float32 }{chan *int32, 0}", + }, + {new(struct{ c func(chan *integer, *int8) }), + "struct { c func(chan *reflectlite_test.integer, *int8) }{func(chan *reflectlite_test.integer, *int8)(arg)}", + }, + {new(struct { + a int8 + b int32 + }), + "struct { a int8; b int32 }{0, 0}", + }, + {new(struct { + a int8 + b int8 + c int32 + }), + "struct { a int8; b int8; c int32 }{0, 0, 0}", + }, +} + +func testType(t *testing.T, i int, typ Type, want string) { + s := TypeString(typ) + if s != want { + t.Errorf("#%d: have %#q, want %#q", i, s, want) + } +} + +func testReflectType(t *testing.T, i int, typ Type, want string) { + s := TypeString(typ) + if s != want { + t.Errorf("#%d: have %#q, want %#q", i, s, want) + } +} + +func TestTypes(t *testing.T) { + for i, tt := range typeTests { + testReflectType(t, i, Field(ValueOf(tt.i), 0).Type(), tt.s) + } +} + +func TestSetValue(t *testing.T) { + for i, tt := range valueTests { + v := ValueOf(tt.i).Elem() + switch v.Kind() { + case abi.Int: + v.Set(ValueOf(int(132))) + case abi.Int8: + v.Set(ValueOf(int8(8))) + case abi.Int16: + v.Set(ValueOf(int16(16))) + case abi.Int32: + v.Set(ValueOf(int32(32))) + case abi.Int64: + v.Set(ValueOf(int64(64))) + case abi.Uint: + v.Set(ValueOf(uint(132))) + case abi.Uint8: + v.Set(ValueOf(uint8(8))) + case abi.Uint16: + v.Set(ValueOf(uint16(16))) + case abi.Uint32: + v.Set(ValueOf(uint32(32))) + case abi.Uint64: + v.Set(ValueOf(uint64(64))) + case abi.Float32: + v.Set(ValueOf(float32(256.25))) + case abi.Float64: + v.Set(ValueOf(512.125)) + case abi.Complex64: + v.Set(ValueOf(complex64(532.125 + 10i))) + case abi.Complex128: + v.Set(ValueOf(complex128(564.25 + 1i))) + case abi.String: + v.Set(ValueOf("stringy cheese")) + case abi.Bool: + v.Set(ValueOf(true)) + } + s := valueToString(v) + if s != tt.s { + t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) + } + } +} + +func TestCanSetField(t *testing.T) { + type embed struct{ x, X int } + type Embed struct{ x, X int } + type S1 struct { + embed + x, X int + } + type S2 struct { + *embed + x, X int + } + type S3 struct { + Embed + x, X int + } + type S4 struct { + *Embed + x, X int + } + + type testCase struct { + index []int + canSet bool + } + tests := []struct { + val Value + cases []testCase + }{{ + val: ValueOf(&S1{}), + cases: []testCase{ + {[]int{0}, false}, + {[]int{0, 0}, false}, + {[]int{0, 1}, true}, + {[]int{1}, false}, + {[]int{2}, true}, + }, + }, { + val: ValueOf(&S2{embed: &embed{}}), + cases: []testCase{ + {[]int{0}, false}, + {[]int{0, 0}, false}, + {[]int{0, 1}, true}, + {[]int{1}, false}, + {[]int{2}, true}, + }, + }, { + val: ValueOf(&S3{}), + cases: []testCase{ + {[]int{0}, true}, + {[]int{0, 0}, false}, + {[]int{0, 1}, true}, + {[]int{1}, false}, + {[]int{2}, true}, + }, + }, { + val: ValueOf(&S4{Embed: &Embed{}}), + cases: []testCase{ + {[]int{0}, true}, + {[]int{0, 0}, false}, + {[]int{0, 1}, true}, + {[]int{1}, false}, + {[]int{2}, true}, + }, + }} + + for _, tt := range tests { + t.Run(tt.val.Type().Name(), func(t *testing.T) { + for _, tc := range tt.cases { + f := tt.val + for _, i := range tc.index { + if f.Kind() == Ptr { + f = f.Elem() + } + f = Field(f, i) + } + if got := f.CanSet(); got != tc.canSet { + t.Errorf("CanSet() = %v, want %v", got, tc.canSet) + } + } + }) + } +} + +var _i = 7 + +var valueToStringTests = []pair{ + {123, "123"}, + {123.5, "123.5"}, + {byte(123), "123"}, + {"abc", "abc"}, + {T{123, 456.75, "hello", &_i}, "reflectlite_test.T{123, 456.75, hello, *int(&7)}"}, + {new(chan *T), "*chan *reflectlite_test.T(&chan *reflectlite_test.T)"}, + {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, + {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, + {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"}, +} + +func TestValueToString(t *testing.T) { + for i, test := range valueToStringTests { + s := valueToString(ValueOf(test.i)) + if s != test.s { + t.Errorf("#%d: have %#q, want %#q", i, s, test.s) + } + } +} + +func TestPtrSetNil(t *testing.T) { + var i int32 = 1234 + ip := &i + vip := ValueOf(&ip) + vip.Elem().Set(Zero(vip.Elem().Type())) + if ip != nil { + t.Errorf("got non-nil (%d), want nil", *ip) + } +} + +func TestMapSetNil(t *testing.T) { + m := make(map[string]int) + vm := ValueOf(&m) + vm.Elem().Set(Zero(vm.Elem().Type())) + if m != nil { + t.Errorf("got non-nil (%p), want nil", m) + } +} + +func TestAll(t *testing.T) { + testType(t, 1, TypeOf((int8)(0)), "int8") + testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8") + + typ := TypeOf((*struct { + c chan *int32 + d float32 + })(nil)) + testType(t, 3, typ, "*struct { c chan *int32; d float32 }") + etyp := typ.Elem() + testType(t, 4, etyp, "struct { c chan *int32; d float32 }") +} + +func TestInterfaceValue(t *testing.T) { + var inter struct { + E any + } + inter.E = 123.456 + v1 := ValueOf(&inter) + v2 := Field(v1.Elem(), 0) + // assert(t, TypeString(v2.Type()), "interface {}") + v3 := v2.Elem() + assert(t, TypeString(v3.Type()), "float64") + + i3 := ToInterface(v2) + if _, ok := i3.(float64); !ok { + t.Error("v2.Interface() did not return float64, got ", TypeOf(i3)) + } +} + +func TestFunctionValue(t *testing.T) { + var x any = func() {} + v := ValueOf(x) + if fmt.Sprint(ToInterface(v)) != fmt.Sprint(x) { + t.Fatalf("TestFunction returned wrong pointer") + } + assert(t, TypeString(v.Type()), "func()") +} + +var appendTests = []struct { + orig, extra []int +}{ + {make([]int, 2, 4), []int{22}}, + {make([]int, 2, 4), []int{22, 33, 44}}, +} + +func sameInts(x, y []int) bool { + if len(x) != len(y) { + return false + } + for i, xx := range x { + if xx != y[i] { + return false + } + } + return true +} + +func TestBigUnnamedStruct(t *testing.T) { + b := struct{ a, b, c, d int64 }{1, 2, 3, 4} + v := ValueOf(b) + b1 := ToInterface(v).(struct { + a, b, c, d int64 + }) + if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d { + t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1) + } +} + +type big struct { + a, b, c, d, e int64 +} + +func TestBigStruct(t *testing.T) { + b := big{1, 2, 3, 4, 5} + v := ValueOf(b) + b1 := ToInterface(v).(big) + if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e { + t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1) + } +} + +type Basic struct { + x int + y float32 +} + +type NotBasic Basic + +type DeepEqualTest struct { + a, b any + eq bool +} + +// Simple functions for DeepEqual tests. +var ( + fn1 func() // nil. + fn2 func() // nil. + fn3 = func() { fn1() } // Not nil. +) + +type self struct{} + +type Loop *Loop +type Loopy any + +var loop1, loop2 Loop +var loopy1, loopy2 Loopy + +func init() { + loop1 = &loop2 + loop2 = &loop1 + + loopy1 = &loopy2 + loopy2 = &loopy1 +} + +var typeOfTests = []DeepEqualTest{ + // Equalities + {nil, nil, true}, + {1, 1, true}, + {int32(1), int32(1), true}, + {0.5, 0.5, true}, + {float32(0.5), float32(0.5), true}, + {"hello", "hello", true}, + {make([]int, 10), make([]int, 10), true}, + {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true}, + {Basic{1, 0.5}, Basic{1, 0.5}, true}, + {error(nil), error(nil), true}, + {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true}, + {fn1, fn2, true}, + + // Inequalities + {1, 2, false}, + {int32(1), int32(2), false}, + {0.5, 0.6, false}, + {float32(0.5), float32(0.6), false}, + {"hello", "hey", false}, + {make([]int, 10), make([]int, 11), false}, + {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false}, + {Basic{1, 0.5}, Basic{1, 0.6}, false}, + {Basic{1, 0}, Basic{2, 0}, false}, + {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false}, + {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false}, + {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false}, + {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false}, + {nil, 1, false}, + {1, nil, false}, + {fn1, fn3, false}, + {fn3, fn3, false}, + {[][]int{{1}}, [][]int{{2}}, false}, + {math.NaN(), math.NaN(), false}, + {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false}, + {&[1]float64{math.NaN()}, self{}, true}, + {[]float64{math.NaN()}, []float64{math.NaN()}, false}, + {[]float64{math.NaN()}, self{}, true}, + {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false}, + {map[float64]float64{math.NaN(): 1}, self{}, true}, + + // Nil vs empty: not the same. + {[]int{}, []int(nil), false}, + {[]int{}, []int{}, true}, + {[]int(nil), []int(nil), true}, + {map[int]int{}, map[int]int(nil), false}, + {map[int]int{}, map[int]int{}, true}, + {map[int]int(nil), map[int]int(nil), true}, + + // Mismatched types + {1, 1.0, false}, + {int32(1), int64(1), false}, + {0.5, "hello", false}, + {[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, + {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false}, + {Basic{1, 0.5}, NotBasic{1, 0.5}, false}, + {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, + + // Possible loops. + {&loop1, &loop1, true}, + {&loop1, &loop2, true}, + {&loopy1, &loopy1, true}, + {&loopy1, &loopy2, true}, +} + +func TestTypeOf(t *testing.T) { + // Special case for nil + if typ := TypeOf(nil); typ != nil { + t.Errorf("expected nil type for nil value; got %v", typ) + } + for _, test := range typeOfTests { + v := ValueOf(test.a) + if !v.IsValid() { + continue + } + typ := TypeOf(test.a) + if typ != v.Type() { + t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type()) + } + } +} + +func Nil(a any, t *testing.T) { + n := Field(ValueOf(a), 0) + if !n.IsNil() { + t.Errorf("%v should be nil", a) + } +} + +func NotNil(a any, t *testing.T) { + n := Field(ValueOf(a), 0) + if n.IsNil() { + t.Errorf("value of type %v should not be nil", TypeString(ValueOf(a).Type())) + } +} + +func TestIsNil(t *testing.T) { + // These implement IsNil. + // Wrap in extra struct to hide interface type. + doNil := []any{ + struct{ x *int }{}, + struct{ x any }{}, + struct{ x map[string]int }{}, + struct{ x func() bool }{}, + struct{ x chan int }{}, + struct{ x []string }{}, + struct{ x unsafe.Pointer }{}, + } + for _, ts := range doNil { + ty := TField(TypeOf(ts), 0) + v := Zero(ty) + v.IsNil() // panics if not okay to call + } + + // Check the implementations + var pi struct { + x *int + } + Nil(pi, t) + pi.x = new(int) + NotNil(pi, t) + + var si struct { + x []int + } + Nil(si, t) + si.x = make([]int, 10) + NotNil(si, t) + + var ci struct { + x chan int + } + Nil(ci, t) + ci.x = make(chan int) + NotNil(ci, t) + + var mi struct { + x map[int]int + } + Nil(mi, t) + mi.x = make(map[int]int) + NotNil(mi, t) + + var ii struct { + x any + } + Nil(ii, t) + ii.x = 2 + NotNil(ii, t) + + var fi struct { + x func(t *testing.T) + } + Nil(fi, t) + fi.x = TestIsNil + NotNil(fi, t) +} + +// Indirect returns the value that v points to. +// If v is a nil pointer, Indirect returns a zero Value. +// If v is not a pointer, Indirect returns v. +func Indirect(v Value) Value { + if v.Kind() != Ptr { + return v + } + return v.Elem() +} + +func TestNilPtrValueSub(t *testing.T) { + var pi *int + if pv := ValueOf(pi); pv.Elem().IsValid() { + t.Error("ValueOf((*int)(nil)).Elem().IsValid()") + } +} + +type Point struct { + x, y int +} + +// This will be index 0. +func (p Point) AnotherMethod(scale int) int { + return -1 +} + +// This will be index 1. +func (p Point) Dist(scale int) int { + //println("Point.Dist", p.x, p.y, scale) + return p.x*p.x*scale + p.y*p.y*scale +} + +// This will be index 2. +func (p Point) GCMethod(k int) int { + runtime.GC() + return k + p.x +} + +// This will be index 3. +func (p Point) NoArgs() { + // Exercise no-argument/no-result paths. +} + +// This will be index 4. +func (p Point) TotalDist(points ...Point) int { + tot := 0 + for _, q := range points { + dx := q.x - p.x + dy := q.y - p.y + tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test. + + } + return tot +} + +type D1 struct { + d int +} +type D2 struct { + d int +} + +func TestImportPath(t *testing.T) { + tests := []struct { + t Type + path string + }{ + {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"}, + {TypeOf(int(0)), ""}, + {TypeOf(int8(0)), ""}, + {TypeOf(int16(0)), ""}, + {TypeOf(int32(0)), ""}, + {TypeOf(int64(0)), ""}, + {TypeOf(uint(0)), ""}, + {TypeOf(uint8(0)), ""}, + {TypeOf(uint16(0)), ""}, + {TypeOf(uint32(0)), ""}, + {TypeOf(uint64(0)), ""}, + {TypeOf(uintptr(0)), ""}, + {TypeOf(float32(0)), ""}, + {TypeOf(float64(0)), ""}, + {TypeOf(complex64(0)), ""}, + {TypeOf(complex128(0)), ""}, + {TypeOf(byte(0)), ""}, + {TypeOf(rune(0)), ""}, + {TypeOf([]byte(nil)), ""}, + {TypeOf([]rune(nil)), ""}, + {TypeOf(string("")), ""}, + {TypeOf((*any)(nil)).Elem(), ""}, + {TypeOf((*byte)(nil)), ""}, + {TypeOf((*rune)(nil)), ""}, + {TypeOf((*int64)(nil)), ""}, + {TypeOf(map[string]int{}), ""}, + {TypeOf((*error)(nil)).Elem(), ""}, + {TypeOf((*Point)(nil)), ""}, + {TypeOf((*Point)(nil)).Elem(), "internal/reflectlite_test"}, + } + for _, test := range tests { + if path := test.t.PkgPath(); path != test.path { + t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path) + } + } +} + +func noAlloc(t *testing.T, n int, f func(int)) { + if testing.Short() { + t.Skip("skipping malloc count in short mode") + } + if runtime.GOMAXPROCS(0) > 1 { + t.Skip("skipping; GOMAXPROCS>1") + } + i := -1 + allocs := testing.AllocsPerRun(n, func() { + f(i) + i++ + }) + if allocs > 0 { + t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs) + } +} + +func TestAllocations(t *testing.T) { + noAlloc(t, 100, func(j int) { + var i any + var v Value + + i = []int{j, j, j} + v = ValueOf(i) + if v.Len() != 3 { + panic("wrong length") + } + }) + noAlloc(t, 100, func(j int) { + var i any + var v Value + + i = func(j int) int { return j } + v = ValueOf(i) + if ToInterface(v).(func(int) int)(j) != j { + panic("wrong result") + } + }) +} + +func TestSetPanic(t *testing.T) { + ok := func(f func()) { f() } + bad := shouldPanic + clear := func(v Value) { v.Set(Zero(v.Type())) } + + type t0 struct { + W int + } + + type t1 struct { + Y int + t0 + } + + type T2 struct { + Z int + namedT0 t0 + } + + type T struct { + X int + t1 + T2 + NamedT1 t1 + NamedT2 T2 + namedT1 t1 + namedT2 T2 + } + + // not addressable + v := ValueOf(T{}) + bad(func() { clear(Field(v, 0)) }) // .X + bad(func() { clear(Field(v, 1)) }) // .t1 + bad(func() { clear(Field(Field(v, 1), 0)) }) // .t1.Y + bad(func() { clear(Field(Field(v, 1), 1)) }) // .t1.t0 + bad(func() { clear(Field(Field(Field(v, 1), 1), 0)) }) // .t1.t0.W + bad(func() { clear(Field(v, 2)) }) // .T2 + bad(func() { clear(Field(Field(v, 2), 0)) }) // .T2.Z + bad(func() { clear(Field(Field(v, 2), 1)) }) // .T2.namedT0 + bad(func() { clear(Field(Field(Field(v, 2), 1), 0)) }) // .T2.namedT0.W + bad(func() { clear(Field(v, 3)) }) // .NamedT1 + bad(func() { clear(Field(Field(v, 3), 0)) }) // .NamedT1.Y + bad(func() { clear(Field(Field(v, 3), 1)) }) // .NamedT1.t0 + bad(func() { clear(Field(Field(Field(v, 3), 1), 0)) }) // .NamedT1.t0.W + bad(func() { clear(Field(v, 4)) }) // .NamedT2 + bad(func() { clear(Field(Field(v, 4), 0)) }) // .NamedT2.Z + bad(func() { clear(Field(Field(v, 4), 1)) }) // .NamedT2.namedT0 + bad(func() { clear(Field(Field(Field(v, 4), 1), 0)) }) // .NamedT2.namedT0.W + bad(func() { clear(Field(v, 5)) }) // .namedT1 + bad(func() { clear(Field(Field(v, 5), 0)) }) // .namedT1.Y + bad(func() { clear(Field(Field(v, 5), 1)) }) // .namedT1.t0 + bad(func() { clear(Field(Field(Field(v, 5), 1), 0)) }) // .namedT1.t0.W + bad(func() { clear(Field(v, 6)) }) // .namedT2 + bad(func() { clear(Field(Field(v, 6), 0)) }) // .namedT2.Z + bad(func() { clear(Field(Field(v, 6), 1)) }) // .namedT2.namedT0 + bad(func() { clear(Field(Field(Field(v, 6), 1), 0)) }) // .namedT2.namedT0.W + + // addressable + v = ValueOf(&T{}).Elem() + ok(func() { clear(Field(v, 0)) }) // .X + bad(func() { clear(Field(v, 1)) }) // .t1 + ok(func() { clear(Field(Field(v, 1), 0)) }) // .t1.Y + bad(func() { clear(Field(Field(v, 1), 1)) }) // .t1.t0 + ok(func() { clear(Field(Field(Field(v, 1), 1), 0)) }) // .t1.t0.W + ok(func() { clear(Field(v, 2)) }) // .T2 + ok(func() { clear(Field(Field(v, 2), 0)) }) // .T2.Z + bad(func() { clear(Field(Field(v, 2), 1)) }) // .T2.namedT0 + bad(func() { clear(Field(Field(Field(v, 2), 1), 0)) }) // .T2.namedT0.W + ok(func() { clear(Field(v, 3)) }) // .NamedT1 + ok(func() { clear(Field(Field(v, 3), 0)) }) // .NamedT1.Y + bad(func() { clear(Field(Field(v, 3), 1)) }) // .NamedT1.t0 + ok(func() { clear(Field(Field(Field(v, 3), 1), 0)) }) // .NamedT1.t0.W + ok(func() { clear(Field(v, 4)) }) // .NamedT2 + ok(func() { clear(Field(Field(v, 4), 0)) }) // .NamedT2.Z + bad(func() { clear(Field(Field(v, 4), 1)) }) // .NamedT2.namedT0 + bad(func() { clear(Field(Field(Field(v, 4), 1), 0)) }) // .NamedT2.namedT0.W + bad(func() { clear(Field(v, 5)) }) // .namedT1 + bad(func() { clear(Field(Field(v, 5), 0)) }) // .namedT1.Y + bad(func() { clear(Field(Field(v, 5), 1)) }) // .namedT1.t0 + bad(func() { clear(Field(Field(Field(v, 5), 1), 0)) }) // .namedT1.t0.W + bad(func() { clear(Field(v, 6)) }) // .namedT2 + bad(func() { clear(Field(Field(v, 6), 0)) }) // .namedT2.Z + bad(func() { clear(Field(Field(v, 6), 1)) }) // .namedT2.namedT0 + bad(func() { clear(Field(Field(Field(v, 6), 1), 0)) }) // .namedT2.namedT0.W +} + +func shouldPanic(f func()) { + defer func() { + if recover() == nil { + panic("did not panic") + } + }() + f() +} + +type S struct { + i1 int64 + i2 int64 +} + +func TestBigZero(t *testing.T) { + const size = 1 << 10 + var v [size]byte + z := ToInterface(Zero(ValueOf(v).Type())).([size]byte) + for i := 0; i < size; i++ { + if z[i] != 0 { + t.Fatalf("Zero object not all zero, index %d", i) + } + } +} + +func TestInvalid(t *testing.T) { + // Used to have inconsistency between IsValid() and Kind() != Invalid. + type T struct{ v any } + + v := Field(ValueOf(T{}), 0) + if v.IsValid() != true || v.Kind() != Interface { + t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind()) + } + v = v.Elem() + if v.IsValid() != false || v.Kind() != abi.Invalid { + t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind()) + } +} + +type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int + +type nameTest struct { + v any + want string +} + +type A struct{} +type B[T any] struct{} + +var nameTests = []nameTest{ + {(*int32)(nil), "int32"}, + {(*D1)(nil), "D1"}, + {(*[]D1)(nil), ""}, + {(*chan D1)(nil), ""}, + {(*func() D1)(nil), ""}, + {(*<-chan D1)(nil), ""}, + {(*chan<- D1)(nil), ""}, + {(*any)(nil), ""}, + {(*interface { + F() + })(nil), ""}, + {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"}, + {(*B[A])(nil), "B[internal/reflectlite_test.A]"}, + {(*B[B[A]])(nil), "B[internal/reflectlite_test.B[internal/reflectlite_test.A]]"}, +} + +func TestNames(t *testing.T) { + for _, test := range nameTests { + typ := TypeOf(test.v).Elem() + if got := typ.Name(); got != test.want { + t.Errorf("%v Name()=%q, want %q", typ, got, test.want) + } + } +} + +// TestUnaddressableField tests that the reflect package will not allow +// a type from another package to be used as a named type with an +// unexported field. +// +// This ensures that unexported fields cannot be modified by other packages. +func TestUnaddressableField(t *testing.T) { + var b Buffer // type defined in reflect, a different package + var localBuffer struct { + buf []byte + } + lv := ValueOf(&localBuffer).Elem() + rv := ValueOf(b) + shouldPanic(func() { + lv.Set(rv) + }) +} + +type Tint int + +type Tint2 = Tint + +type Talias1 struct { + byte + uint8 + int + int32 + rune +} + +type Talias2 struct { + Tint + Tint2 +} + +func TestAliasNames(t *testing.T) { + t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5} + out := fmt.Sprintf("%#v", t1) + want := "reflectlite_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}" + if out != want { + t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want) + } + + t2 := Talias2{Tint: 1, Tint2: 2} + out = fmt.Sprintf("%#v", t2) + want = "reflectlite_test.Talias2{Tint:1, Tint2:2}" + if out != want { + t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want) + } +} diff --git a/go/src/internal/reflectlite/asm.s b/go/src/internal/reflectlite/asm.s new file mode 100644 index 0000000000000000000000000000000000000000..a7b69b65ba52530aafca36fbb154c58c767252aa --- /dev/null +++ b/go/src/internal/reflectlite/asm.s @@ -0,0 +1,5 @@ +// 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. + +// Trigger build without complete flag. \ No newline at end of file diff --git a/go/src/internal/reflectlite/export_test.go b/go/src/internal/reflectlite/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..93762a83874106ef7dfbfabee1721a5714f14e88 --- /dev/null +++ b/go/src/internal/reflectlite/export_test.go @@ -0,0 +1,117 @@ +// 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 reflectlite + +import ( + "unsafe" +) + +// Field returns the i'th field of the struct v. +// It panics if v's Kind is not Struct or i is out of range. +func Field(v Value, i int) Value { + if v.kind() != Struct { + panic(&ValueError{"reflect.Value.Field", v.kind()}) + } + tt := (*structType)(unsafe.Pointer(v.typ())) + if uint(i) >= uint(len(tt.Fields)) { + panic("reflect: Field index out of range") + } + field := &tt.Fields[i] + typ := field.Typ + + // Inherit permission bits from v, but clear flagEmbedRO. + fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind()) + // Using an unexported field forces flagRO. + if !field.Name.IsExported() { + if field.Embedded() { + fl |= flagEmbedRO + } else { + fl |= flagStickyRO + } + } + // Either flagIndir is set and v.ptr points at struct, + // or flagIndir is not set and v.ptr is the actual struct data. + // In the former case, we want v.ptr + offset. + // In the latter case, we must have field.offset = 0, + // so v.ptr + field.offset is still the correct address. + ptr := add(v.ptr, field.Offset, "same as non-reflect &v.field") + return Value{typ, ptr, fl} +} + +func TField(typ Type, i int) Type { + t := typ.(rtype) + if t.Kind() != Struct { + panic("reflect: Field of non-struct type") + } + tt := (*structType)(unsafe.Pointer(t.Type)) + + return StructFieldType(tt, i) +} + +// Field returns the i'th struct field. +func StructFieldType(t *structType, i int) Type { + if i < 0 || i >= len(t.Fields) { + panic("reflect: Field index out of bounds") + } + p := &t.Fields[i] + return toType(p.Typ) +} + +// Zero returns a Value representing the zero value for the specified type. +// The result is different from the zero value of the Value struct, +// which represents no value at all. +// For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. +// The returned value is neither addressable nor settable. +func Zero(typ Type) Value { + if typ == nil { + panic("reflect: Zero(nil)") + } + t := typ.common() + fl := flag(t.Kind()) + if !t.IsDirectIface() { + return Value{t, unsafe_New(t), fl | flagIndir} + } + return Value{t, nil, fl} +} + +// ToInterface returns v's current value as an interface{}. +// It is equivalent to: +// +// var i interface{} = (v's underlying value) +// +// It panics if the Value was obtained by accessing +// unexported struct fields. +func ToInterface(v Value) (i any) { + return valueInterface(v) +} + +type EmbedWithUnexpMeth struct{} + +func (EmbedWithUnexpMeth) f() {} + +type pinUnexpMeth interface { + f() +} + +var pinUnexpMethI = pinUnexpMeth(EmbedWithUnexpMeth{}) + +func FirstMethodNameBytes(t Type) *byte { + _ = pinUnexpMethI + + ut := t.uncommon() + if ut == nil { + panic("type has no methods") + } + m := ut.Methods()[0] + mname := t.(rtype).nameOff(m.Name) + if *mname.DataChecked(0, "name flag field")&(1<<2) == 0 { + panic("method name does not have pkgPath *string") + } + return mname.Bytes +} + +type Buffer struct { + buf []byte +} diff --git a/go/src/internal/reflectlite/reflect_mirror_test.go b/go/src/internal/reflectlite/reflect_mirror_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c5642d092d99826de2ee6642c4da78ae26d4d7a1 --- /dev/null +++ b/go/src/internal/reflectlite/reflect_mirror_test.go @@ -0,0 +1,127 @@ +// 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 reflectlite_test + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "testing" +) + +var typeNames = []string{ + "uncommonType", + "arrayType", + "chanType", + "funcType", + "interfaceType", + "ptrType", + "sliceType", + "structType", +} + +type visitor struct { + m map[string]map[string]bool +} + +func newVisitor() visitor { + v := visitor{} + v.m = make(map[string]map[string]bool) + + return v +} +func (v visitor) filter(name string) bool { + return slices.Contains(typeNames, name) +} + +func (v visitor) Visit(n ast.Node) ast.Visitor { + switch x := n.(type) { + case *ast.TypeSpec: + if v.filter(x.Name.String()) { + if st, ok := x.Type.(*ast.StructType); ok { + v.m[x.Name.String()] = make(map[string]bool) + for _, field := range st.Fields.List { + k := fmt.Sprintf("%s", field.Type) + if len(field.Names) > 0 { + k = field.Names[0].Name + } + v.m[x.Name.String()][k] = true + } + } + } + } + return v +} + +func loadTypes(path, pkgName string, v visitor) { + fset := token.NewFileSet() + + filter := func(fi fs.FileInfo) bool { + return strings.HasSuffix(fi.Name(), ".go") + } + pkgs, err := parser.ParseDir(fset, path, filter, 0) + if err != nil { + panic(err) + } + + pkg := pkgs[pkgName] + + for _, f := range pkg.Files { + ast.Walk(v, f) + } +} + +func TestMirrorWithReflect(t *testing.T) { + // TODO when the dust clears, figure out what this should actually test. + t.Skipf("reflect and reflectlite are out of sync for now") + reflectDir := filepath.Join(runtime.GOROOT(), "src", "reflect") + if _, err := os.Stat(reflectDir); os.IsNotExist(err) { + // On some mobile builders, the test binary executes on a machine without a + // complete GOROOT source tree. + t.Skipf("GOROOT source not present") + } + + var wg sync.WaitGroup + rl, r := newVisitor(), newVisitor() + + for _, tc := range []struct { + path, pkg string + v visitor + }{ + {".", "reflectlite", rl}, + {reflectDir, "reflect", r}, + } { + wg.Add(1) + go func() { + defer wg.Done() + loadTypes(tc.path, tc.pkg, tc.v) + }() + } + wg.Wait() + + if len(rl.m) != len(r.m) { + t.Fatalf("number of types mismatch, reflect: %d, reflectlite: %d (%+v, %+v)", len(r.m), len(rl.m), r.m, rl.m) + } + + for typName := range r.m { + if len(r.m[typName]) != len(rl.m[typName]) { + t.Errorf("type %s number of fields mismatch, reflect: %d, reflectlite: %d", typName, len(r.m[typName]), len(rl.m[typName])) + continue + } + for field := range r.m[typName] { + if _, ok := rl.m[typName][field]; !ok { + t.Errorf(`Field mismatch, reflect have "%s", relectlite does not.`, field) + } + } + } +} diff --git a/go/src/internal/reflectlite/set_test.go b/go/src/internal/reflectlite/set_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ca7ea9b0bc39d9732c8c4051a90cf1eb15eb20c1 --- /dev/null +++ b/go/src/internal/reflectlite/set_test.go @@ -0,0 +1,101 @@ +// 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 reflectlite_test + +import ( + "bytes" + "go/ast" + "go/token" + . "internal/reflectlite" + "io" + "testing" +) + +func TestImplicitSetConversion(t *testing.T) { + // Assume TestImplicitMapConversion covered the basics. + // Just make sure conversions are being applied at all. + var r io.Reader + b := new(bytes.Buffer) + rv := ValueOf(&r).Elem() + rv.Set(ValueOf(b)) + if r != b { + t.Errorf("after Set: r=%T(%v)", r, r) + } +} + +var implementsTests = []struct { + x any + t any + b bool +}{ + {new(*bytes.Buffer), new(io.Reader), true}, + {new(bytes.Buffer), new(io.Reader), false}, + {new(*bytes.Buffer), new(io.ReaderAt), false}, + {new(*ast.Ident), new(ast.Expr), true}, + {new(*notAnExpr), new(ast.Expr), false}, + {new(*ast.Ident), new(notASTExpr), false}, + {new(notASTExpr), new(ast.Expr), false}, + {new(ast.Expr), new(notASTExpr), false}, + {new(*notAnExpr), new(notASTExpr), true}, + {new(mapError), new(error), true}, + {new(*mapError), new(error), true}, +} + +type notAnExpr struct{} + +func (notAnExpr) Pos() token.Pos { return token.NoPos } +func (notAnExpr) End() token.Pos { return token.NoPos } +func (notAnExpr) exprNode() {} + +type notASTExpr interface { + Pos() token.Pos + End() token.Pos + exprNode() +} + +type mapError map[string]string + +func (mapError) Error() string { return "mapError" } + +var _ error = mapError{} +var _ error = new(mapError) + +func TestImplements(t *testing.T) { + for _, tt := range implementsTests { + xv := TypeOf(tt.x).Elem() + xt := TypeOf(tt.t).Elem() + if b := xv.Implements(xt); b != tt.b { + t.Errorf("(%s).Implements(%s) = %v, want %v", TypeString(xv), TypeString(xt), b, tt.b) + } + } +} + +var assignableTests = []struct { + x any + t any + b bool +}{ + {new(chan int), new(<-chan int), true}, + {new(<-chan int), new(chan int), false}, + {new(*int), new(IntPtr), true}, + {new(IntPtr), new(*int), true}, + {new(IntPtr), new(IntPtr1), false}, + {new(Ch), new(<-chan any), true}, + // test runs implementsTests too +} + +type IntPtr *int +type IntPtr1 *int +type Ch <-chan any + +func TestAssignableTo(t *testing.T) { + for i, tt := range append(assignableTests, implementsTests...) { + xv := TypeOf(tt.x).Elem() + xt := TypeOf(tt.t).Elem() + if b := xv.AssignableTo(xt); b != tt.b { + t.Errorf("%d:AssignableTo: got %v, want %v", i, b, tt.b) + } + } +} diff --git a/go/src/internal/reflectlite/swapper.go b/go/src/internal/reflectlite/swapper.go new file mode 100644 index 0000000000000000000000000000000000000000..e5ea535d5f85ff1a8bf7e1b278c08491e47dd8b3 --- /dev/null +++ b/go/src/internal/reflectlite/swapper.go @@ -0,0 +1,78 @@ +// 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 reflectlite + +import ( + "internal/goarch" + "internal/unsafeheader" + "unsafe" +) + +// Swapper returns a function that swaps the elements in the provided +// slice. +// +// Swapper panics if the provided interface is not a slice. +func Swapper(slice any) func(i, j int) { + v := ValueOf(slice) + if v.Kind() != Slice { + panic(&ValueError{Method: "Swapper", Kind: v.Kind()}) + } + // Fast path for slices of size 0 and 1. Nothing to swap. + switch v.Len() { + case 0: + return func(i, j int) { panic("reflect: slice index out of range") } + case 1: + return func(i, j int) { + if i != 0 || j != 0 { + panic("reflect: slice index out of range") + } + } + } + + typ := v.Type().Elem().common() + size := typ.Size() + hasPtr := typ.Pointers() + + // Some common & small cases, without using memmove: + if hasPtr { + if size == goarch.PtrSize { + ps := *(*[]unsafe.Pointer)(v.ptr) + return func(i, j int) { ps[i], ps[j] = ps[j], ps[i] } + } + if typ.Kind() == String { + ss := *(*[]string)(v.ptr) + return func(i, j int) { ss[i], ss[j] = ss[j], ss[i] } + } + } else { + switch size { + case 8: + is := *(*[]int64)(v.ptr) + return func(i, j int) { is[i], is[j] = is[j], is[i] } + case 4: + is := *(*[]int32)(v.ptr) + return func(i, j int) { is[i], is[j] = is[j], is[i] } + case 2: + is := *(*[]int16)(v.ptr) + return func(i, j int) { is[i], is[j] = is[j], is[i] } + case 1: + is := *(*[]int8)(v.ptr) + return func(i, j int) { is[i], is[j] = is[j], is[i] } + } + } + + s := (*unsafeheader.Slice)(v.ptr) + tmp := unsafe_New(typ) // swap scratch space + + return func(i, j int) { + if uint(i) >= uint(s.Len) || uint(j) >= uint(s.Len) { + panic("reflect: slice index out of range") + } + val1 := arrayAt(s.Data, i, size, "i < s.Len") + val2 := arrayAt(s.Data, j, size, "j < s.Len") + typedmemmove(typ, tmp, val1) + typedmemmove(typ, val1, val2) + typedmemmove(typ, val2, tmp) + } +} diff --git a/go/src/internal/reflectlite/tostring_test.go b/go/src/internal/reflectlite/tostring_test.go new file mode 100644 index 0000000000000000000000000000000000000000..966b0bd849920337c648c6a017251f70c3728255 --- /dev/null +++ b/go/src/internal/reflectlite/tostring_test.go @@ -0,0 +1,98 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Formatting of reflection types and values for debugging. +// Not defined as methods so they do not need to be linked into most binaries; +// the functions are not used by the library itself, only in tests. + +package reflectlite_test + +import ( + . "internal/reflectlite" + "reflect" + "strconv" +) + +// valueToString returns a textual representation of the reflection value val. +// For debugging only. +func valueToString(v Value) string { + return valueToStringImpl(reflect.ValueOf(ToInterface(v))) +} + +func valueToStringImpl(val reflect.Value) string { + var str string + if !val.IsValid() { + return "" + } + typ := val.Type() + switch val.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return strconv.FormatInt(val.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return strconv.FormatUint(val.Uint(), 10) + case reflect.Float32, reflect.Float64: + return strconv.FormatFloat(val.Float(), 'g', -1, 64) + case reflect.Complex64, reflect.Complex128: + c := val.Complex() + return strconv.FormatFloat(real(c), 'g', -1, 64) + "+" + strconv.FormatFloat(imag(c), 'g', -1, 64) + "i" + case reflect.String: + return val.String() + case reflect.Bool: + if val.Bool() { + return "true" + } else { + return "false" + } + case reflect.Pointer: + v := val + str = typ.String() + "(" + if v.IsNil() { + str += "0" + } else { + str += "&" + valueToStringImpl(v.Elem()) + } + str += ")" + return str + case reflect.Array, reflect.Slice: + v := val + str += typ.String() + str += "{" + for i := 0; i < v.Len(); i++ { + if i > 0 { + str += ", " + } + str += valueToStringImpl(v.Index(i)) + } + str += "}" + return str + case reflect.Map: + str += typ.String() + str += "{" + str += "" + str += "}" + return str + case reflect.Chan: + str = typ.String() + return str + case reflect.Struct: + t := typ + v := val + str += t.String() + str += "{" + for i, n := 0, v.NumField(); i < n; i++ { + if i > 0 { + str += ", " + } + str += valueToStringImpl(v.Field(i)) + } + str += "}" + return str + case reflect.Interface: + return typ.String() + "(" + valueToStringImpl(val.Elem()) + ")" + case reflect.Func: + return typ.String() + "(arg)" + default: + panic("valueToString: can't print type " + typ.String()) + } +} diff --git a/go/src/internal/reflectlite/type.go b/go/src/internal/reflectlite/type.go new file mode 100644 index 0000000000000000000000000000000000000000..88cc50db9eda358176b1dd48f3e9c444782d08be --- /dev/null +++ b/go/src/internal/reflectlite/type.go @@ -0,0 +1,643 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package reflectlite implements lightweight version of reflect, not using +// any package except for "runtime", "unsafe", and "internal/abi" +package reflectlite + +import ( + "internal/abi" + "unsafe" +) + +// Type is the representation of a Go type. +// +// Not all methods apply to all kinds of types. Restrictions, +// if any, are noted in the documentation for each method. +// Use the Kind method to find out the kind of type before +// calling kind-specific methods. Calling a method +// inappropriate to the kind of type causes a run-time panic. +// +// Type values are comparable, such as with the == operator, +// so they can be used as map keys. +// Two Type values are equal if they represent identical types. +type Type interface { + // Methods applicable to all types. + + // Name returns the type's name within its package for a defined type. + // For other (non-defined) types it returns the empty string. + Name() string + + // PkgPath returns a defined type's package path, that is, the import path + // that uniquely identifies the package, such as "encoding/base64". + // If the type was predeclared (string, error) or not defined (*T, struct{}, + // []int, or A where A is an alias for a non-defined type), the package path + // will be the empty string. + PkgPath() string + + // Size returns the number of bytes needed to store + // a value of the given type; it is analogous to unsafe.Sizeof. + Size() uintptr + + // Kind returns the specific kind of this type. + Kind() Kind + + // Implements reports whether the type implements the interface type u. + Implements(u Type) bool + + // AssignableTo reports whether a value of the type is assignable to type u. + AssignableTo(u Type) bool + + // Comparable reports whether values of this type are comparable. + Comparable() bool + + // String returns a string representation of the type. + // The string representation may use shortened package names + // (e.g., base64 instead of "encoding/base64") and is not + // guaranteed to be unique among types. To test for type identity, + // compare the Types directly. + String() string + + // Elem returns a type's element type. + // It panics if the type's Kind is not Ptr. + Elem() Type + + common() *abi.Type + uncommon() *uncommonType +} + +/* + * These data structures are known to the compiler (../../cmd/internal/reflectdata/reflect.go). + * A few are known to ../runtime/type.go to convey to debuggers. + * They are also known to ../runtime/type.go. + */ + +// A Kind represents the specific kind of type that a Type represents. +// The zero Kind is not a valid kind. +type Kind = abi.Kind + +const Ptr = abi.Pointer + +const ( + // Import-and-export these constants as necessary + Interface = abi.Interface + Slice = abi.Slice + String = abi.String + Struct = abi.Struct +) + +type nameOff = abi.NameOff +type typeOff = abi.TypeOff +type textOff = abi.TextOff + +type rtype struct { + *abi.Type +} + +// uncommonType is present only for defined types or types with methods +// (if T is a defined type, the uncommonTypes for T and *T have methods). +// Using a pointer to this struct reduces the overall size required +// to describe a non-defined type with no methods. +type uncommonType = abi.UncommonType + +// arrayType represents a fixed array type. +type arrayType = abi.ArrayType + +// chanType represents a channel type. +type chanType = abi.ChanType + +type funcType = abi.FuncType + +type interfaceType = abi.InterfaceType + +// ptrType represents a pointer type. +type ptrType = abi.PtrType + +// sliceType represents a slice type. +type sliceType = abi.SliceType + +// structType represents a struct type. +type structType = abi.StructType + +// name is an encoded type name with optional extra data. +// +// The first byte is a bit field containing: +// +// 1<<0 the name is exported +// 1<<1 tag data follows the name +// 1<<2 pkgPath nameOff follows the name and tag +// +// The next two bytes are the data length: +// +// l := uint16(data[1])<<8 | uint16(data[2]) +// +// Bytes [3:3+l] are the string data. +// +// If tag data follows then bytes 3+l and 3+l+1 are the tag length, +// with the data following. +// +// If the import path follows, then 4 bytes at the end of +// the data form a nameOff. The import path is only set for concrete +// methods that are defined in a different package than their type. +// +// If a name starts with "*", then the exported bit represents +// whether the pointed to type is exported. +type name struct { + bytes *byte +} + +func (n name) data(off int, whySafe string) *byte { + return (*byte)(add(unsafe.Pointer(n.bytes), uintptr(off), whySafe)) +} + +func (n name) isExported() bool { + return (*n.bytes)&(1<<0) != 0 +} + +func (n name) hasTag() bool { + return (*n.bytes)&(1<<1) != 0 +} + +func (n name) embedded() bool { + return (*n.bytes)&(1<<3) != 0 +} + +// readVarint parses a varint as encoded by encoding/binary. +// It returns the number of encoded bytes and the encoded value. +func (n name) readVarint(off int) (int, int) { + v := 0 + for i := 0; ; i++ { + x := *n.data(off+i, "read varint") + v += int(x&0x7f) << (7 * i) + if x&0x80 == 0 { + return i + 1, v + } + } +} + +func (n name) name() string { + if n.bytes == nil { + return "" + } + i, l := n.readVarint(1) + return unsafe.String(n.data(1+i, "non-empty string"), l) +} + +func (n name) tag() string { + if !n.hasTag() { + return "" + } + i, l := n.readVarint(1) + i2, l2 := n.readVarint(1 + i + l) + return unsafe.String(n.data(1+i+l+i2, "non-empty string"), l2) +} + +func pkgPath(n abi.Name) string { + if n.Bytes == nil || *n.DataChecked(0, "name flag field")&(1<<2) == 0 { + return "" + } + i, l := n.ReadVarint(1) + off := 1 + i + l + if n.HasTag() { + i2, l2 := n.ReadVarint(off) + off += i2 + l2 + } + var nameOff int32 + // Note that this field may not be aligned in memory, + // so we cannot use a direct int32 assignment here. + copy((*[4]byte)(unsafe.Pointer(&nameOff))[:], (*[4]byte)(unsafe.Pointer(n.DataChecked(off, "name offset field")))[:]) + pkgPathName := name{(*byte)(resolveTypeOff(unsafe.Pointer(n.Bytes), nameOff))} + return pkgPathName.name() +} + +/* + * The compiler knows the exact layout of all the data structures above. + * The compiler does not know about the data structures and methods below. + */ + +// resolveNameOff resolves a name offset from a base pointer. +// The (*rtype).nameOff method is a convenience wrapper for this function. +// Implemented in the runtime package. +// +//go:noescape +func resolveNameOff(ptrInModule unsafe.Pointer, off int32) unsafe.Pointer + +// resolveTypeOff resolves an *rtype offset from a base type. +// The (*rtype).typeOff method is a convenience wrapper for this function. +// Implemented in the runtime package. +// +//go:noescape +func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer + +func (t rtype) nameOff(off nameOff) abi.Name { + return abi.Name{Bytes: (*byte)(resolveNameOff(unsafe.Pointer(t.Type), int32(off)))} +} + +func (t rtype) typeOff(off typeOff) *abi.Type { + return (*abi.Type)(resolveTypeOff(unsafe.Pointer(t.Type), int32(off))) +} + +func (t rtype) uncommon() *uncommonType { + return t.Uncommon() +} + +func (t rtype) String() string { + s := t.nameOff(t.Str).Name() + if t.TFlag&abi.TFlagExtraStar != 0 { + return s[1:] + } + return s +} + +func (t rtype) common() *abi.Type { return t.Type } + +func (t rtype) exportedMethods() []abi.Method { + ut := t.uncommon() + if ut == nil { + return nil + } + return ut.ExportedMethods() +} + +func (t rtype) NumMethod() int { + tt := t.Type.InterfaceType() + if tt != nil { + return tt.NumMethod() + } + return len(t.exportedMethods()) +} + +func (t rtype) PkgPath() string { + if t.TFlag&abi.TFlagNamed == 0 { + return "" + } + ut := t.uncommon() + if ut == nil { + return "" + } + return t.nameOff(ut.PkgPath).Name() +} + +func (t rtype) Name() string { + if !t.HasName() { + return "" + } + s := t.String() + i := len(s) - 1 + sqBrackets := 0 + for i >= 0 && (s[i] != '.' || sqBrackets != 0) { + switch s[i] { + case ']': + sqBrackets++ + case '[': + sqBrackets-- + } + i-- + } + return s[i+1:] +} + +func toRType(t *abi.Type) rtype { + return rtype{t} +} + +func elem(t *abi.Type) *abi.Type { + et := t.Elem() + if et != nil { + return et + } + panic("reflect: Elem of invalid type " + toRType(t).String()) +} + +func (t rtype) Elem() Type { + return toType(elem(t.common())) +} + +func (t rtype) In(i int) Type { + tt := t.Type.FuncType() + if tt == nil { + panic("reflect: In of non-func type") + } + return toType(tt.InSlice()[i]) +} + +func (t rtype) Key() Type { + tt := t.Type.MapType() + if tt == nil { + panic("reflect: Key of non-map type") + } + return toType(tt.Key) +} + +func (t rtype) Len() int { + tt := t.Type.ArrayType() + if tt == nil { + panic("reflect: Len of non-array type") + } + return int(tt.Len) +} + +func (t rtype) NumField() int { + tt := t.Type.StructType() + if tt == nil { + panic("reflect: NumField of non-struct type") + } + return len(tt.Fields) +} + +func (t rtype) NumIn() int { + tt := t.Type.FuncType() + if tt == nil { + panic("reflect: NumIn of non-func type") + } + return int(tt.InCount) +} + +func (t rtype) NumOut() int { + tt := t.Type.FuncType() + if tt == nil { + panic("reflect: NumOut of non-func type") + } + return tt.NumOut() +} + +func (t rtype) Out(i int) Type { + tt := t.Type.FuncType() + if tt == nil { + panic("reflect: Out of non-func type") + } + return toType(tt.OutSlice()[i]) +} + +// add returns p+x. +// +// The whySafe string is ignored, so that the function still inlines +// as efficiently as p+x, but all call sites should use the string to +// record why the addition is safe, which is to say why the addition +// does not cause x to advance to the very end of p's allocation +// and therefore point incorrectly at the next block in memory. +func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer { + return unsafe.Pointer(uintptr(p) + x) +} + +// TypeOf returns the reflection Type that represents the dynamic type of i. +// If i is a nil interface value, TypeOf returns nil. +func TypeOf(i any) Type { + return toType(abi.TypeOf(i)) +} + +func (t rtype) Implements(u Type) bool { + if u == nil { + panic("reflect: nil type passed to Type.Implements") + } + if u.Kind() != Interface { + panic("reflect: non-interface type passed to Type.Implements") + } + return implements(u.common(), t.common()) +} + +func (t rtype) AssignableTo(u Type) bool { + if u == nil { + panic("reflect: nil type passed to Type.AssignableTo") + } + uu := u.common() + tt := t.common() + return directlyAssignable(uu, tt) || implements(uu, tt) +} + +func (t rtype) Comparable() bool { + return t.Equal != nil +} + +// implements reports whether the type V implements the interface type T. +func implements(T, V *abi.Type) bool { + t := T.InterfaceType() + if t == nil { + return false + } + if len(t.Methods) == 0 { + return true + } + rT := toRType(T) + rV := toRType(V) + + // The same algorithm applies in both cases, but the + // method tables for an interface type and a concrete type + // are different, so the code is duplicated. + // In both cases the algorithm is a linear scan over the two + // lists - T's methods and V's methods - simultaneously. + // Since method tables are stored in a unique sorted order + // (alphabetical, with no duplicate method names), the scan + // through V's methods must hit a match for each of T's + // methods along the way, or else V does not implement T. + // This lets us run the scan in overall linear time instead of + // the quadratic time a naive search would require. + // See also ../runtime/iface.go. + if V.Kind() == Interface { + v := (*interfaceType)(unsafe.Pointer(V)) + i := 0 + for j := 0; j < len(v.Methods); j++ { + tm := &t.Methods[i] + tmName := rT.nameOff(tm.Name) + vm := &v.Methods[j] + vmName := rV.nameOff(vm.Name) + if vmName.Name() == tmName.Name() && rV.typeOff(vm.Typ) == rT.typeOff(tm.Typ) { + if !tmName.IsExported() { + tmPkgPath := pkgPath(tmName) + if tmPkgPath == "" { + tmPkgPath = t.PkgPath.Name() + } + vmPkgPath := pkgPath(vmName) + if vmPkgPath == "" { + vmPkgPath = v.PkgPath.Name() + } + if tmPkgPath != vmPkgPath { + continue + } + } + if i++; i >= len(t.Methods) { + return true + } + } + } + return false + } + + v := V.Uncommon() + if v == nil { + return false + } + i := 0 + vmethods := v.Methods() + for j := 0; j < int(v.Mcount); j++ { + tm := &t.Methods[i] + tmName := rT.nameOff(tm.Name) + vm := vmethods[j] + vmName := rV.nameOff(vm.Name) + if vmName.Name() == tmName.Name() && rV.typeOff(vm.Mtyp) == rT.typeOff(tm.Typ) { + if !tmName.IsExported() { + tmPkgPath := pkgPath(tmName) + if tmPkgPath == "" { + tmPkgPath = t.PkgPath.Name() + } + vmPkgPath := pkgPath(vmName) + if vmPkgPath == "" { + vmPkgPath = rV.nameOff(v.PkgPath).Name() + } + if tmPkgPath != vmPkgPath { + continue + } + } + if i++; i >= len(t.Methods) { + return true + } + } + } + return false +} + +// directlyAssignable reports whether a value x of type V can be directly +// assigned (using memmove) to a value of type T. +// https://golang.org/doc/go_spec.html#Assignability +// Ignoring the interface rules (implemented elsewhere) +// and the ideal constant rules (no ideal constants at run time). +func directlyAssignable(T, V *abi.Type) bool { + // x's type V is identical to T? + if T == V { + return true + } + + // Otherwise at least one of T and V must not be defined + // and they must have the same kind. + if T.HasName() && V.HasName() || T.Kind() != V.Kind() { + return false + } + + // x's type T and V must have identical underlying types. + return haveIdenticalUnderlyingType(T, V, true) +} + +func haveIdenticalType(T, V *abi.Type, cmpTags bool) bool { + if cmpTags { + return T == V + } + + if toRType(T).Name() != toRType(V).Name() || T.Kind() != V.Kind() { + return false + } + + return haveIdenticalUnderlyingType(T, V, false) +} + +func haveIdenticalUnderlyingType(T, V *abi.Type, cmpTags bool) bool { + if T == V { + return true + } + + kind := T.Kind() + if kind != V.Kind() { + return false + } + + // Non-composite types of equal kind have same underlying type + // (the predefined instance of the type). + if abi.Bool <= kind && kind <= abi.Complex128 || kind == abi.String || kind == abi.UnsafePointer { + return true + } + + // Composite types. + switch kind { + case abi.Array: + return T.Len() == V.Len() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags) + + case abi.Chan: + // Special case: + // x is a bidirectional channel value, T is a channel type, + // and x's type V and T have identical element types. + if V.ChanDir() == abi.BothDir && haveIdenticalType(T.Elem(), V.Elem(), cmpTags) { + return true + } + + // Otherwise continue test for identical underlying type. + return V.ChanDir() == T.ChanDir() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags) + + case abi.Func: + t := (*funcType)(unsafe.Pointer(T)) + v := (*funcType)(unsafe.Pointer(V)) + if t.OutCount != v.OutCount || t.InCount != v.InCount { + return false + } + for i := 0; i < t.NumIn(); i++ { + if !haveIdenticalType(t.In(i), v.In(i), cmpTags) { + return false + } + } + for i := 0; i < t.NumOut(); i++ { + if !haveIdenticalType(t.Out(i), v.Out(i), cmpTags) { + return false + } + } + return true + + case Interface: + t := (*interfaceType)(unsafe.Pointer(T)) + v := (*interfaceType)(unsafe.Pointer(V)) + if len(t.Methods) == 0 && len(v.Methods) == 0 { + return true + } + // Might have the same methods but still + // need a run time conversion. + return false + + case abi.Map: + return haveIdenticalType(T.Key(), V.Key(), cmpTags) && haveIdenticalType(T.Elem(), V.Elem(), cmpTags) + + case Ptr, abi.Slice: + return haveIdenticalType(T.Elem(), V.Elem(), cmpTags) + + case abi.Struct: + t := (*structType)(unsafe.Pointer(T)) + v := (*structType)(unsafe.Pointer(V)) + if len(t.Fields) != len(v.Fields) { + return false + } + if t.PkgPath.Name() != v.PkgPath.Name() { + return false + } + for i := range t.Fields { + tf := &t.Fields[i] + vf := &v.Fields[i] + if tf.Name.Name() != vf.Name.Name() { + return false + } + if !haveIdenticalType(tf.Typ, vf.Typ, cmpTags) { + return false + } + if cmpTags && tf.Name.Tag() != vf.Name.Tag() { + return false + } + if tf.Offset != vf.Offset { + return false + } + if tf.Embedded() != vf.Embedded() { + return false + } + } + return true + } + + return false +} + +// toType converts from a *rtype to a Type that can be returned +// to the client of package reflect. In gc, the only concern is that +// a nil *rtype must be replaced by a nil Type, but in gccgo this +// function takes care of ensuring that multiple *rtype for the same +// type are coalesced into a single Type. +func toType(t *abi.Type) Type { + if t == nil { + return nil + } + return toRType(t) +} diff --git a/go/src/internal/reflectlite/value.go b/go/src/internal/reflectlite/value.go new file mode 100644 index 0000000000000000000000000000000000000000..a92df613f55d1eb1ecf73f469788d86f07a9ae2f --- /dev/null +++ b/go/src/internal/reflectlite/value.go @@ -0,0 +1,480 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package reflectlite + +import ( + "internal/abi" + "internal/goarch" + "internal/unsafeheader" + "runtime" + "unsafe" +) + +// Value is the reflection interface to a Go value. +// +// Not all methods apply to all kinds of values. Restrictions, +// if any, are noted in the documentation for each method. +// Use the Kind method to find out the kind of value before +// calling kind-specific methods. Calling a method +// inappropriate to the kind of type causes a run time panic. +// +// The zero Value represents no value. +// Its IsValid method returns false, its Kind method returns Invalid, +// its String method returns "", and all other methods panic. +// Most functions and methods never return an invalid value. +// If one does, its documentation states the conditions explicitly. +// +// A Value can be used concurrently by multiple goroutines provided that +// the underlying Go value can be used concurrently for the equivalent +// direct operations. +// +// To compare two Values, compare the results of the Interface method. +// Using == on two Values does not compare the underlying values +// they represent. +type Value struct { + // typ_ holds the type of the value represented by a Value. + // Access using the typ method to avoid escape of v. + typ_ *abi.Type + + // Pointer-valued data or, if flagIndir is set, pointer to data. + // Valid when either flagIndir is set or typ.pointers() is true. + ptr unsafe.Pointer + + // flag holds metadata about the value. + // + // The lowest five bits give the Kind of the value, mirroring typ.Kind(). + // + // The next set of bits are flag bits: + // - flagStickyRO: obtained via unexported not embedded field, so read-only + // - flagEmbedRO: obtained via unexported embedded field, so read-only + // - flagIndir: val holds a pointer to the data + // - flagAddr: v.CanAddr is true (implies flagIndir and ptr is non-nil) + // - flagMethod: v is a method value. + // If !typ.IsDirectIface(), code can assume that flagIndir is set. + // + // The remaining 22+ bits give a method number for method values. + // If flag.kind() != Func, code can assume that flagMethod is unset. + flag + + // A method value represents a curried method invocation + // like r.Read for some receiver r. The typ+val+flag bits describe + // the receiver r, but the flag's Kind bits say Func (methods are + // functions), and the top bits of the flag give the method number + // in r's type's method table. +} + +type flag uintptr + +const ( + flagKindWidth = 5 // there are 27 kinds + flagKindMask flag = 1<= len, +// because then the result will point outside the array. +// whySafe must explain why i < len. (Passing "i < len" is fine; +// the benefit is to surface this assumption at the call site.) +func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer { + return add(p, uintptr(i)*eltSize, "i < len") +} + +func ifaceE2I(t *abi.Type, src any, dst unsafe.Pointer) + +// typedmemmove copies a value of type t to dst from src. +// +//go:noescape +func typedmemmove(t *abi.Type, dst, src unsafe.Pointer) + +// Dummy annotation marking that the value x escapes, +// for use in cases where the reflect code is so clever that +// the compiler cannot follow. +func escapes(x any) { + if dummy.b { + dummy.x = x + } +} + +var dummy struct { + b bool + x any +} diff --git a/go/src/internal/routebsd/address.go b/go/src/internal/routebsd/address.go new file mode 100644 index 0000000000000000000000000000000000000000..aa1bc21d3f00ae432d4c33a865ae0b64890a4281 --- /dev/null +++ b/go/src/internal/routebsd/address.go @@ -0,0 +1,300 @@ +// 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 darwin || dragonfly || freebsd || netbsd || openbsd + +package routebsd + +import ( + "net/netip" + "runtime" + "syscall" +) + +// An Addr represents an address associated with packet routing. +type Addr interface { + // Family returns an address family. + Family() int +} + +// A LinkAddr represents a link-layer address. +type LinkAddr struct { + Index int // interface index when attached + Name string // interface name when attached + Addr []byte // link-layer address when attached +} + +// Family implements the Family method of Addr interface. +func (a *LinkAddr) Family() int { return syscall.AF_LINK } + +func parseLinkAddr(b []byte) (Addr, error) { + if len(b) < 8 { + return nil, errInvalidAddr + } + _, a, err := parseKernelLinkAddr(syscall.AF_LINK, b[4:]) + if err != nil { + return nil, err + } + a.(*LinkAddr).Index = int(nativeEndian.Uint16(b[2:4])) + return a, nil +} + +// parseKernelLinkAddr parses b as a link-layer address in +// conventional BSD kernel form. +func parseKernelLinkAddr(_ int, b []byte) (int, Addr, error) { + // The encoding looks like the following: + // +----------------------------+ + // | Type (1 octet) | + // +----------------------------+ + // | Name length (1 octet) | + // +----------------------------+ + // | Address length (1 octet) | + // +----------------------------+ + // | Selector length (1 octet) | + // +----------------------------+ + // | Data (variable) | + // +----------------------------+ + // + // On some platforms, all-bit-one of length field means "don't + // care". + nlen, alen, slen := int(b[1]), int(b[2]), int(b[3]) + if nlen == 0xff { + nlen = 0 + } + if alen == 0xff { + alen = 0 + } + if slen == 0xff { + slen = 0 + } + l := 4 + nlen + alen + slen + if len(b) < l { + return 0, nil, errInvalidAddr + } + data := b[4:] + var name string + var addr []byte + if nlen > 0 { + name = string(data[:nlen]) + data = data[nlen:] + } + if alen > 0 { + addr = data[:alen] + data = data[alen:] + } + return l, &LinkAddr{Name: name, Addr: addr}, nil +} + +// An InetAddr represent an internet address using IPv4 or IPv6. +type InetAddr struct { + IP netip.Addr +} + +func (a *InetAddr) Family() int { + if a.IP.Is4() { + return syscall.AF_INET + } else { + return syscall.AF_INET6 + } +} + +// parseInetAddr parses b as an internet address for IPv4 or IPv6. +func parseInetAddr(af int, b []byte) (Addr, error) { + const ( + off4 = 4 // offset of in_addr + off6 = 8 // offset of in6_addr + ipv4Len = 4 // length of IPv4 address in bytes + ipv6Len = 16 // length of IPv6 address in bytes + ) + switch af { + case syscall.AF_INET: + if len(b) < (off4+1) || len(b) < int(b[0]) { + return nil, errInvalidAddr + } + sockAddrLen := int(b[0]) + var ip [ipv4Len]byte + if sockAddrLen != 0 { + // Calculate how many bytes of the address to copy: + // either full IPv4 length or the available length. + n := off4 + ipv4Len + if sockAddrLen < n { + n = sockAddrLen + } + copy(ip[:], b[off4:n]) + } + a := &InetAddr{ + IP: netip.AddrFrom4(ip), + } + return a, nil + case syscall.AF_INET6: + if len(b) < (off6+1) || len(b) < int(b[0]) { + return nil, errInvalidAddr + } + var ip [ipv6Len]byte + sockAddrLen := int(b[0]) + if sockAddrLen != 0 { + n := off6 + ipv6Len + if sockAddrLen < n { + n = sockAddrLen + } + copy(ip[:], b[off6:n]) + if ip[0] == 0xfe && ip[1]&0xc0 == 0x80 || ip[0] == 0xff && (ip[1]&0x0f == 0x01 || ip[1]&0x0f == 0x02) { + // KAME based IPv6 protocol stack usually + // embeds the interface index in the + // interface-local or link-local address as + // the kernel-internal form. + id := int(bigEndian.Uint16(ip[2:4])) + if id != 0 { + ip[2], ip[3] = 0, 0 + } + } + } + // The kernel can provide an integer zone ID. + // We ignore it. + a := &InetAddr{ + IP: netip.AddrFrom16(ip), + } + return a, nil + default: + return nil, errInvalidAddr + } +} + +// parseKernelInetAddr parses b as an internet address in conventional +// BSD kernel form. +func parseKernelInetAddr(af int, b []byte) (int, Addr, error) { + // The encoding looks similar to the NLRI encoding. + // +----------------------------+ + // | Length (1 octet) | + // +----------------------------+ + // | Address prefix (variable) | + // +----------------------------+ + // + // The differences between the kernel form and the NLRI + // encoding are: + // + // - The length field of the kernel form indicates the prefix + // length in bytes, not in bits + // + // - In the kernel form, zero value of the length field + // doesn't mean 0.0.0.0/0 or ::/0 + // + // - The kernel form appends leading bytes to the prefix field + // to make the tuple to be conformed with + // the routing message boundary + l := int(b[0]) + if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { + // On Darwin, an address in the kernel form is also + // used as a message filler. + if l == 0 || len(b) > roundup(l) { + l = roundup(l) + } + } else { + l = roundup(l) + } + if len(b) < l { + return 0, nil, errInvalidAddr + } + // Don't reorder case expressions. + // The case expressions for IPv6 must come first. + const ( + off4 = 4 // offset of in_addr + off6 = 8 // offset of in6_addr + ) + switch { + case b[0] == syscall.SizeofSockaddrInet6: + a := &InetAddr{ + IP: netip.AddrFrom16([16]byte(b[off6 : off6+16])), + } + return int(b[0]), a, nil + case af == syscall.AF_INET6: + var ab [16]byte + if l-1 < off6 { + copy(ab[:], b[1:l]) + } else { + copy(ab[:], b[l-off6:l]) + } + a := &InetAddr{ + IP: netip.AddrFrom16(ab), + } + return int(b[0]), a, nil + case b[0] == syscall.SizeofSockaddrInet4: + a := &InetAddr{ + IP: netip.AddrFrom4([4]byte(b[off4 : off4+4])), + } + return int(b[0]), a, nil + default: // an old fashion, AF_UNSPEC or unknown means AF_INET + var ab [4]byte + if l-1 < off4 { + copy(ab[:], b[1:l]) + } else { + copy(ab[:], b[l-off4:l]) + } + a := &InetAddr{ + IP: netip.AddrFrom4(ab), + } + return int(b[0]), a, nil + } +} + +func parseAddrs(attrs uint, b []byte) ([]Addr, error) { + var as [syscall.RTAX_MAX]Addr + af := int(syscall.AF_UNSPEC) + for i := uint(0); i < syscall.RTAX_MAX && len(b) >= roundup(0); i++ { + if attrs&(1< 4 { + nmsgs++ + l := int(nativeEndian.Uint16(b[:2])) + if l == 0 { + return nil, errInvalidMessage + } + if len(b) < l { + return nil, errMessageTooShort + } + if b[2] != rtmVersion { + b = b[l:] + continue + } + if w, ok := wireFormats[int(b[3])]; !ok { + nskips++ + } else { + m, err := w.parse(b[:l]) + if err != nil { + return nil, err + } + if m == nil { + nskips++ + } else { + msgs = append(msgs, m) + } + } + b = b[l:] + } + + // We failed to parse any of the messages - version mismatch? + if nmsgs != len(msgs)+nskips { + return nil, errMessageMismatch + } + return msgs, nil +} diff --git a/go/src/internal/routebsd/message_darwin_test.go b/go/src/internal/routebsd/message_darwin_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f224f0a73d4547be68b2889d7c44078c283cc005 --- /dev/null +++ b/go/src/internal/routebsd/message_darwin_test.go @@ -0,0 +1,28 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package routebsd + +import ( + "syscall" + "testing" +) + +func TestFetchRIBMessagesOnDarwin(t *testing.T) { + for _, typ := range []int{syscall.NET_RT_FLAGS, syscall.NET_RT_DUMP2, syscall.NET_RT_IFLIST2} { + ms, err := FetchRIBMessages(typ, 0) + if err != nil { + t.Error(typ, err) + continue + } + ss, err := msgs(ms).validate() + if err != nil { + t.Error(typ, err) + continue + } + for _, s := range ss { + t.Log(s) + } + } +} diff --git a/go/src/internal/routebsd/message_freebsd_test.go b/go/src/internal/routebsd/message_freebsd_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f0065198c8f2ef392cebb345881a651b21bc161c --- /dev/null +++ b/go/src/internal/routebsd/message_freebsd_test.go @@ -0,0 +1,28 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package routebsd + +import ( + "syscall" + "testing" +) + +func TestFetchRIBMessagesOnFreeBSD(t *testing.T) { + for _, typ := range []int{syscall.NET_RT_IFMALIST} { + ms, err := FetchRIBMessages(typ, 0) + if err != nil { + t.Error(typ, err) + continue + } + ss, err := msgs(ms).validate() + if err != nil { + t.Error(typ, err) + continue + } + for _, s := range ss { + t.Log(s) + } + } +} diff --git a/go/src/internal/routebsd/message_test.go b/go/src/internal/routebsd/message_test.go new file mode 100644 index 0000000000000000000000000000000000000000..958f2010628a0635e68c64ffa3e82aa80914a7d2 --- /dev/null +++ b/go/src/internal/routebsd/message_test.go @@ -0,0 +1,51 @@ +// 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 darwin || dragonfly || freebsd || netbsd || openbsd + +package routebsd + +import ( + "syscall" + "testing" +) + +func TestFetchRIBMessages(t *testing.T) { + for _, typ := range []int{syscall.NET_RT_DUMP, syscall.NET_RT_IFLIST} { + ms, err := FetchRIBMessages(typ, 0) + if err != nil { + t.Error(typ, err) + continue + } + ss, err := msgs(ms).validate() + if err != nil { + t.Error(typ, err) + continue + } + for _, s := range ss { + t.Log(typ, s) + } + } +} + +func TestParseRIBWithFuzz(t *testing.T) { + for _, fuzz := range []string{ + "0\x00\x05\x050000000000000000" + + "00000000000000000000" + + "00000000000000000000" + + "00000000000000000000" + + "0000000000000\x02000000" + + "00000000", + "\x02\x00\x05\f0000000000000000" + + "0\x0200000000000000", + "\x02\x00\x05\x100000000000000\x1200" + + "0\x00\xff\x00", + "\x02\x00\x05\f0000000000000000" + + "0\x12000\x00\x02\x0000", + "\x00\x00\x00\x01\x00", + "00000", + } { + parseRIB([]byte(fuzz)) + } +} diff --git a/go/src/internal/routebsd/route.go b/go/src/internal/routebsd/route.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6062e125869dafc9be17464ecafaafbe64de9c --- /dev/null +++ b/go/src/internal/routebsd/route.go @@ -0,0 +1,59 @@ +// 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 darwin || dragonfly || freebsd || netbsd || openbsd + +// Package routebsd supports reading interface addresses on BSD systems. +// This is a very stripped down version of x/net/route, +// for use by the net package in the standard library. +package routebsd + +import ( + "errors" + "syscall" +) + +var ( + errMessageMismatch = errors.New("message mismatch") + errMessageTooShort = errors.New("message too short") + errInvalidMessage = errors.New("invalid message") + errInvalidAddr = errors.New("invalid address") +) + +// fetchRIB fetches a routing information base from the operating +// system. +// +// The arg is an interface index or 0 for all. +func fetchRIB(typ, arg int) ([]byte, error) { + try := 0 + for { + try++ + b, err := syscall.RouteRIB(typ, arg) + + // If the sysctl failed because the data got larger + // between the two sysctl calls, try a few times + // before failing (issue #45736). + const maxTries = 3 + if err == syscall.ENOMEM && try < maxTries { + continue + } + + return b, err + } +} + +// FetchRIBMessages fetches a list of addressing messages for an interface. +// The typ argument is something like syscall.NET_RT_IFLIST. +// The argument is an interface index or 0 for all. +func FetchRIBMessages(typ, arg int) ([]Message, error) { + b, err := fetchRIB(typ, arg) + if err != nil { + return nil, err + } + ms, err := parseRIB(b) + if err != nil { + return nil, err + } + return ms, nil +} diff --git a/go/src/internal/routebsd/route_test.go b/go/src/internal/routebsd/route_test.go new file mode 100644 index 0000000000000000000000000000000000000000..613175e388eceba13aac48a3a72924d7dc222f83 --- /dev/null +++ b/go/src/internal/routebsd/route_test.go @@ -0,0 +1,239 @@ +// 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 darwin || dragonfly || freebsd || netbsd || openbsd + +package routebsd + +import ( + "fmt" + "runtime" + "syscall" +) + +func (m *InterfaceMessage) String() string { + var attrs addrAttrs + if runtime.GOOS == "openbsd" { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) + } else { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) + } + return fmt.Sprintf("%s", attrs) +} + +func (m *InterfaceAddrMessage) String() string { + var attrs addrAttrs + if runtime.GOOS == "openbsd" { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) + } else { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) + } + return fmt.Sprintf("%s", attrs) +} + +func (m *InterfaceMulticastAddrMessage) String() string { + return fmt.Sprintf("%s", addrAttrs(nativeEndian.Uint32(m.raw[4:8]))) +} + +type addrAttrs uint + +var addrAttrNames = [...]string{ + "dst", + "gateway", + "netmask", + "genmask", + "ifp", + "ifa", + "author", + "brd", + "df:mpls1-n:tag-o:src", // mpls1 for dragonfly, tag for netbsd, src for openbsd + "df:mpls2-o:srcmask", // mpls2 for dragonfly, srcmask for openbsd + "df:mpls3-o:label", // mpls3 for dragonfly, label for openbsd + "o:bfd", // bfd for openbsd + "o:dns", // dns for openbsd + "o:static", // static for openbsd + "o:search", // search for openbsd +} + +func (attrs addrAttrs) String() string { + var s string + for i, name := range addrAttrNames { + if attrs&(1<" + } + return s +} + +type msgs []Message + +func (ms msgs) validate() ([]string, error) { + var ss []string + for _, m := range ms { + switch m := m.(type) { + case *InterfaceMessage: + var attrs addrAttrs + if runtime.GOOS == "openbsd" { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) + } else { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) + } + if err := addrs(m.Addrs).match(attrs); err != nil { + return nil, err + } + ss = append(ss, m.String()+" "+addrs(m.Addrs).String()) + case *InterfaceAddrMessage: + var attrs addrAttrs + if runtime.GOOS == "openbsd" { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) + } else { + attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) + } + if err := addrs(m.Addrs).match(attrs); err != nil { + return nil, err + } + ss = append(ss, m.String()+" "+addrs(m.Addrs).String()) + case *InterfaceMulticastAddrMessage: + if err := addrs(m.Addrs).match(addrAttrs(nativeEndian.Uint32(m.raw[4:8]))); err != nil { + return nil, err + } + ss = append(ss, m.String()+" "+addrs(m.Addrs).String()) + default: + ss = append(ss, fmt.Sprintf("%+v", m)) + } + } + return ss, nil +} + +type addrFamily int + +func (af addrFamily) String() string { + switch af { + case syscall.AF_UNSPEC: + return "unspec" + case syscall.AF_LINK: + return "link" + case syscall.AF_INET: + return "inet4" + case syscall.AF_INET6: + return "inet6" + default: + return fmt.Sprintf("%d", af) + } +} + +const hexDigit = "0123456789abcdef" + +type llAddr []byte + +func (a llAddr) String() string { + if len(a) == 0 { + return "" + } + buf := make([]byte, 0, len(a)*3-1) + for i, b := range a { + if i > 0 { + buf = append(buf, ':') + } + buf = append(buf, hexDigit[b>>4]) + buf = append(buf, hexDigit[b&0xF]) + } + return string(buf) +} + +type ipAddr []byte + +func (a ipAddr) String() string { + if len(a) == 0 { + return "" + } + if len(a) == 4 { + return fmt.Sprintf("%d.%d.%d.%d", a[0], a[1], a[2], a[3]) + } + if len(a) == 16 { + return fmt.Sprintf("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]) + } + s := make([]byte, len(a)*2) + for i, tn := range a { + s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] + } + return string(s) +} + +func (a *LinkAddr) String() string { + name := a.Name + if name == "" { + name = "" + } + lla := llAddr(a.Addr).String() + if lla == "" { + lla = "" + } + return fmt.Sprintf("(%v %d %s %s)", addrFamily(a.Family()), a.Index, name, lla) +} + +func (a *InetAddr) String() string { + return fmt.Sprintf("(%v %v)", addrFamily(a.Family()), a.IP) +} + +type addrs []Addr + +func (as addrs) String() string { + var s string + for _, a := range as { + if a == nil { + continue + } + if len(s) > 0 { + s += " " + } + switch a := a.(type) { + case *LinkAddr: + s += a.String() + case *InetAddr: + s += a.String() + } + } + if s == "" { + return "" + } + return s +} + +func (as addrs) match(attrs addrAttrs) error { + var ts addrAttrs + af := syscall.AF_UNSPEC + for i := range as { + if as[i] != nil { + ts |= 1 << uint(i) + } + switch addr := as[i].(type) { + case *InetAddr: + got := 0 + if addr.IP.Is4() { + got = syscall.AF_INET + } else if addr.IP.Is6() { + got = syscall.AF_INET6 + } + if af == syscall.AF_UNSPEC { + if got != 0 { + af = got + } + } + if got != 0 && af != got { + return fmt.Errorf("got %v; want %v", addrs(as), addrFamily(af)) + } + } + } + if ts != attrs && ts > attrs { + return fmt.Errorf("%v not included in %v", ts, attrs) + } + return nil +} diff --git a/go/src/internal/routebsd/sys.go b/go/src/internal/routebsd/sys.go new file mode 100644 index 0000000000000000000000000000000000000000..8805bca97e7cf2447a89d5d03f20fdf8647b22df --- /dev/null +++ b/go/src/internal/routebsd/sys.go @@ -0,0 +1,45 @@ +// 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 darwin || dragonfly || freebsd || netbsd || openbsd + +package routebsd + +import ( + "syscall" + "unsafe" +) + +var ( + nativeEndian binaryByteOrder + kernelAlign int + rtmVersion byte + wireFormats map[int]*wireFormat +) + +func init() { + i := uint32(1) + b := (*[4]byte)(unsafe.Pointer(&i)) + if b[0] == 1 { + nativeEndian = littleEndian + } else { + nativeEndian = bigEndian + } + // might get overridden in probeRoutingStack + rtmVersion = syscall.RTM_VERSION + kernelAlign, wireFormats = probeRoutingStack() +} + +func roundup(l int) int { + if l == 0 { + return kernelAlign + } + return (l + kernelAlign - 1) &^ (kernelAlign - 1) +} + +type wireFormat struct { + extOff int // offset of header extension + bodyOff int // offset of message body + parse func([]byte) (Message, error) +} diff --git a/go/src/internal/routebsd/sys_darwin.go b/go/src/internal/routebsd/sys_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..14864e2e327df2d41ee9e5966275a840f9a9ac69 --- /dev/null +++ b/go/src/internal/routebsd/sys_darwin.go @@ -0,0 +1,38 @@ +// 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 routebsd + +import "syscall" + +// MTU returns the interface MTU. +func (m *InterfaceMessage) MTU() int { + return int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])) +} + +// sizeofIfMsghdr2 is copied from x/sys/unix. +const sizeofIfMsghdr2 = 0xa0 + +func probeRoutingStack() (int, map[int]*wireFormat) { + ifm := &wireFormat{extOff: 16, bodyOff: syscall.SizeofIfMsghdr} + ifm.parse = ifm.parseInterfaceMessage + ifm2 := &wireFormat{extOff: 32, bodyOff: sizeofIfMsghdr2} + ifm2.parse = ifm2.parseInterfaceMessage + ifam := &wireFormat{extOff: syscall.SizeofIfaMsghdr, bodyOff: syscall.SizeofIfaMsghdr} + ifam.parse = ifam.parseInterfaceAddrMessage + ifmam := &wireFormat{extOff: syscall.SizeofIfmaMsghdr, bodyOff: syscall.SizeofIfmaMsghdr} + ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage + ifmam2 := &wireFormat{extOff: syscall.SizeofIfmaMsghdr2, bodyOff: syscall.SizeofIfmaMsghdr2} + ifmam2.parse = ifmam2.parseInterfaceMulticastAddrMessage + // Darwin kernels require 32-bit aligned access to routing facilities. + return 4, map[int]*wireFormat{ + syscall.RTM_NEWADDR: ifam, + syscall.RTM_DELADDR: ifam, + syscall.RTM_IFINFO: ifm, + syscall.RTM_NEWMADDR: ifmam, + syscall.RTM_DELMADDR: ifmam, + syscall.RTM_IFINFO2: ifm2, + syscall.RTM_NEWMADDR2: ifmam2, + } +} diff --git a/go/src/internal/routebsd/sys_dragonfly.go b/go/src/internal/routebsd/sys_dragonfly.go new file mode 100644 index 0000000000000000000000000000000000000000..ce0e6fd403924553ee72b7ad9da54a3b24f118e1 --- /dev/null +++ b/go/src/internal/routebsd/sys_dragonfly.go @@ -0,0 +1,41 @@ +// 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 routebsd + +import ( + "syscall" + "unsafe" +) + +// MTU returns the interface MTU. +func (m *InterfaceMessage) MTU() int { + return int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])) +} + +func probeRoutingStack() (int, map[int]*wireFormat) { + var p uintptr + ifm := &wireFormat{extOff: 16, bodyOff: syscall.SizeofIfMsghdr} + ifm.parse = ifm.parseInterfaceMessage + ifam := &wireFormat{extOff: syscall.SizeofIfaMsghdr, bodyOff: syscall.SizeofIfaMsghdr} + ifam.parse = ifam.parseInterfaceAddrMessage + ifmam := &wireFormat{extOff: syscall.SizeofIfmaMsghdr, bodyOff: syscall.SizeofIfmaMsghdr} + ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage + + rel, _ := syscall.SysctlUint32("kern.osreldate") + if rel >= 500705 { + // https://github.com/DragonFlyBSD/DragonFlyBSD/commit/43a373152df2d405c9940983e584e6a25e76632d + // but only the size of struct ifa_msghdr actually changed + rtmVersion = 7 + ifam.bodyOff = 0x18 + } + + return int(unsafe.Sizeof(p)), map[int]*wireFormat{ + syscall.RTM_NEWADDR: ifam, + syscall.RTM_DELADDR: ifam, + syscall.RTM_IFINFO: ifm, + syscall.RTM_NEWMADDR: ifmam, + syscall.RTM_DELMADDR: ifmam, + } +} diff --git a/go/src/internal/routebsd/sys_freebsd.go b/go/src/internal/routebsd/sys_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..5d5f49e42e01ea121d91ea5afedadf6977e70880 --- /dev/null +++ b/go/src/internal/routebsd/sys_freebsd.go @@ -0,0 +1,62 @@ +// 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 routebsd + +import ( + "syscall" + "unsafe" +) + +// MTU returns the interface MTU. +func (m *InterfaceMessage) MTU() int { + return int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])) +} + +// sizeofIfMsghdr is the size used on FreeBSD 11 for all platforms. +const sizeofIfMsghdr = 0xa8 + +func probeRoutingStack() (int, map[int]*wireFormat) { + var p uintptr + wordSize := int(unsafe.Sizeof(p)) + align := wordSize + // In the case of kern.supported_archs="amd64 i386", we need + // to know the underlying kernel's architecture because the + // alignment for routing facilities are set at the build time + // of the kernel. + conf, _ := syscall.Sysctl("kern.conftxt") + for i, j := 0, 0; j < len(conf); j++ { + if conf[j] != '\n' { + continue + } + s := conf[i:j] + i = j + 1 + if len(s) > len("machine") && s[:len("machine")] == "machine" { + s = s[len("machine"):] + for k := 0; k < len(s); k++ { + if s[k] == ' ' || s[k] == '\t' { + s = s[1:] + } + break + } + if s == "amd64" { + align = 8 + } + break + } + } + ifm := &wireFormat{extOff: 16, bodyOff: sizeofIfMsghdr} + ifm.parse = ifm.parseInterfaceMessage + ifam := &wireFormat{extOff: syscall.SizeofIfaMsghdr, bodyOff: syscall.SizeofIfaMsghdr} + ifam.parse = ifam.parseInterfaceAddrMessage + ifmam := &wireFormat{extOff: syscall.SizeofIfmaMsghdr, bodyOff: syscall.SizeofIfmaMsghdr} + ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage + return align, map[int]*wireFormat{ + syscall.RTM_NEWADDR: ifam, + syscall.RTM_DELADDR: ifam, + syscall.RTM_IFINFO: ifm, + syscall.RTM_NEWMADDR: ifmam, + syscall.RTM_DELMADDR: ifmam, + } +} diff --git a/go/src/internal/routebsd/sys_netbsd.go b/go/src/internal/routebsd/sys_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..b181f727c25ca5a6013e21cebf8d8f641076e013 --- /dev/null +++ b/go/src/internal/routebsd/sys_netbsd.go @@ -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. + +package routebsd + +import "syscall" + +// MTU returns the interface MTU. +func (m *InterfaceMessage) MTU() int { + return int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])) +} + +func probeRoutingStack() (int, map[int]*wireFormat) { + ifm := &wireFormat{extOff: 16, bodyOff: syscall.SizeofIfMsghdr} + ifm.parse = ifm.parseInterfaceMessage + ifam := &wireFormat{extOff: syscall.SizeofIfaMsghdr, bodyOff: syscall.SizeofIfaMsghdr} + ifam.parse = ifam.parseInterfaceAddrMessage + // NetBSD 6 and above kernels require 64-bit aligned access to + // routing facilities. + return 8, map[int]*wireFormat{ + syscall.RTM_NEWADDR: ifam, + syscall.RTM_DELADDR: ifam, + syscall.RTM_IFINFO: ifm, + } +} diff --git a/go/src/internal/routebsd/sys_openbsd.go b/go/src/internal/routebsd/sys_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..83256c8fabfa5907a8a518f70a3af6337819a048 --- /dev/null +++ b/go/src/internal/routebsd/sys_openbsd.go @@ -0,0 +1,28 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package routebsd + +import ( + "syscall" + "unsafe" +) + +// MTU returns the interface MTU. +func (m *InterfaceMessage) MTU() int { + return int(nativeEndian.Uint32(m.raw[28:32])) +} + +func probeRoutingStack() (int, map[int]*wireFormat) { + var p uintptr + ifm := &wireFormat{extOff: -1, bodyOff: -1} + ifm.parse = ifm.parseInterfaceMessage + ifam := &wireFormat{extOff: -1, bodyOff: -1} + ifam.parse = ifam.parseInterfaceAddrMessage + return int(unsafe.Sizeof(p)), map[int]*wireFormat{ + syscall.RTM_NEWADDR: ifam, + syscall.RTM_DELADDR: ifam, + syscall.RTM_IFINFO: ifm, + } +} diff --git a/go/src/internal/saferio/io.go b/go/src/internal/saferio/io.go new file mode 100644 index 0000000000000000000000000000000000000000..5c428e6ff49d33da783ce4129d265f3dcf57f458 --- /dev/null +++ b/go/src/internal/saferio/io.go @@ -0,0 +1,132 @@ +// 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 saferio provides I/O functions that avoid allocating large +// amounts of memory unnecessarily. This is intended for packages that +// read data from an [io.Reader] where the size is part of the input +// data but the input may be corrupt, or may be provided by an +// untrustworthy attacker. +package saferio + +import ( + "io" + "unsafe" +) + +// chunk is an arbitrary limit on how much memory we are willing +// to allocate without concern. +const chunk = 10 << 20 // 10M + +// ReadData reads n bytes from the input stream, but avoids allocating +// all n bytes if n is large. This avoids crashing the program by +// allocating all n bytes in cases where n is incorrect. +// +// The error is io.EOF only if no bytes were read. +// If an io.EOF happens after reading some but not all the bytes, +// ReadData returns io.ErrUnexpectedEOF. +func ReadData(r io.Reader, n uint64) ([]byte, error) { + if int64(n) < 0 || n != uint64(int(n)) { + // n is too large to fit in int, so we can't allocate + // a buffer large enough. Treat this as a read failure. + return nil, io.ErrUnexpectedEOF + } + + if n < chunk { + buf := make([]byte, n) + _, err := io.ReadFull(r, buf) + if err != nil { + return nil, err + } + return buf, nil + } + + var buf []byte + buf1 := make([]byte, chunk) + for n > 0 { + next := n + if next > chunk { + next = chunk + } + _, err := io.ReadFull(r, buf1[:next]) + if err != nil { + if len(buf) > 0 && err == io.EOF { + err = io.ErrUnexpectedEOF + } + return nil, err + } + buf = append(buf, buf1[:next]...) + n -= next + } + return buf, nil +} + +// ReadDataAt reads n bytes from the input stream at off, but avoids +// allocating all n bytes if n is large. This avoids crashing the program +// by allocating all n bytes in cases where n is incorrect. +func ReadDataAt(r io.ReaderAt, n uint64, off int64) ([]byte, error) { + if int64(n) < 0 || n != uint64(int(n)) { + // n is too large to fit in int, so we can't allocate + // a buffer large enough. Treat this as a read failure. + return nil, io.ErrUnexpectedEOF + } + + if n < chunk { + buf := make([]byte, n) + _, err := r.ReadAt(buf, off) + if err != nil { + // io.SectionReader can return EOF for n == 0, + // but for our purposes that is a success. + if err != io.EOF || n > 0 { + return nil, err + } + } + return buf, nil + } + + var buf []byte + buf1 := make([]byte, chunk) + for n > 0 { + next := n + if next > chunk { + next = chunk + } + _, err := r.ReadAt(buf1[:next], off) + if err != nil { + return nil, err + } + buf = append(buf, buf1[:next]...) + n -= next + off += int64(next) + } + return buf, nil +} + +// SliceCapWithSize returns the capacity to use when allocating a slice. +// After the slice is allocated with the capacity, it should be +// built using append. This will avoid allocating too much memory +// if the capacity is large and incorrect. +// +// A negative result means that the value is always too big. +func SliceCapWithSize(size, c uint64) int { + if int64(c) < 0 || c != uint64(int(c)) { + return -1 + } + if size > 0 && c > (1<<64-1)/size { + return -1 + } + if c*size > chunk { + c = chunk / size + if c == 0 { + c = 1 + } + } + return int(c) +} + +// SliceCap is like SliceCapWithSize but using generics. +func SliceCap[E any](c uint64) int { + var v E + size := uint64(unsafe.Sizeof(v)) + return SliceCapWithSize(size, c) +} diff --git a/go/src/internal/saferio/io_test.go b/go/src/internal/saferio/io_test.go new file mode 100644 index 0000000000000000000000000000000000000000..696356f0952072b39f944c00701aa6365319cf8f --- /dev/null +++ b/go/src/internal/saferio/io_test.go @@ -0,0 +1,136 @@ +// 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 saferio + +import ( + "bytes" + "io" + "testing" +) + +func TestReadData(t *testing.T) { + const count = 100 + input := bytes.Repeat([]byte{'a'}, count) + + t.Run("small", func(t *testing.T) { + got, err := ReadData(bytes.NewReader(input), count) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, input) { + t.Errorf("got %v, want %v", got, input) + } + }) + + t.Run("large", func(t *testing.T) { + _, err := ReadData(bytes.NewReader(input), 10<<30) + if err == nil { + t.Error("large read succeeded unexpectedly") + } + }) + + t.Run("maxint", func(t *testing.T) { + _, err := ReadData(bytes.NewReader(input), 1<<62) + if err == nil { + t.Error("large read succeeded unexpectedly") + } + }) + + t.Run("small-EOF", func(t *testing.T) { + _, err := ReadData(bytes.NewReader(nil), chunk-1) + if err != io.EOF { + t.Errorf("ReadData = %v, want io.EOF", err) + } + }) + + t.Run("large-EOF", func(t *testing.T) { + _, err := ReadData(bytes.NewReader(nil), chunk+1) + if err != io.EOF { + t.Errorf("ReadData = %v, want io.EOF", err) + } + }) + + t.Run("large-UnexpectedEOF", func(t *testing.T) { + _, err := ReadData(bytes.NewReader(make([]byte, chunk)), chunk+1) + if err != io.ErrUnexpectedEOF { + t.Errorf("ReadData = %v, want io.ErrUnexpectedEOF", err) + } + }) +} + +func TestReadDataAt(t *testing.T) { + const count = 100 + input := bytes.Repeat([]byte{'a'}, count) + + t.Run("small", func(t *testing.T) { + got, err := ReadDataAt(bytes.NewReader(input), count, 0) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, input) { + t.Errorf("got %v, want %v", got, input) + } + }) + + t.Run("large", func(t *testing.T) { + _, err := ReadDataAt(bytes.NewReader(input), 10<<30, 0) + if err == nil { + t.Error("large read succeeded unexpectedly") + } + }) + + t.Run("maxint", func(t *testing.T) { + _, err := ReadDataAt(bytes.NewReader(input), 1<<62, 0) + if err == nil { + t.Error("large read succeeded unexpectedly") + } + }) + + t.Run("SectionReader", func(t *testing.T) { + // Reading 0 bytes from an io.SectionReader at the end + // of the section will return EOF, but ReadDataAt + // should succeed and return 0 bytes. + sr := io.NewSectionReader(bytes.NewReader(input), 0, 0) + got, err := ReadDataAt(sr, 0, 0) + if err != nil { + t.Fatal(err) + } + if len(got) > 0 { + t.Errorf("got %d bytes, expected 0", len(got)) + } + }) +} + +func TestSliceCap(t *testing.T) { + t.Run("small", func(t *testing.T) { + c := SliceCap[int](10) + if c != 10 { + t.Errorf("got capacity %d, want %d", c, 10) + } + }) + + t.Run("large", func(t *testing.T) { + c := SliceCap[byte](1 << 30) + if c < 0 { + t.Error("SliceCap failed unexpectedly") + } else if c == 1<<30 { + t.Errorf("got capacity %d which is too high", c) + } + }) + + t.Run("maxint", func(t *testing.T) { + c := SliceCap[byte](1 << 63) + if c >= 0 { + t.Errorf("SliceCap returned %d, expected failure", c) + } + }) + + t.Run("overflow", func(t *testing.T) { + c := SliceCap[int64](1 << 62) + if c >= 0 { + t.Errorf("SliceCap returned %d, expected failure", c) + } + }) +} diff --git a/go/src/internal/singleflight/singleflight.go b/go/src/internal/singleflight/singleflight.go new file mode 100644 index 0000000000000000000000000000000000000000..d0e6d2f84afbefbe94defa609c2d808bf09189cb --- /dev/null +++ b/go/src/internal/singleflight/singleflight.go @@ -0,0 +1,123 @@ +// 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 singleflight provides a duplicate function call suppression +// mechanism. +package singleflight + +import "sync" + +// call is an in-flight or completed singleflight.Do call +type call struct { + wg sync.WaitGroup + + // These fields are written once before the WaitGroup is done + // and are only read after the WaitGroup is done. + val any + err error + + // These fields are read and written with the singleflight + // mutex held before the WaitGroup is done, and are read but + // not written after the WaitGroup is done. + dups int + chans []chan<- Result +} + +// Group represents a class of work and forms a namespace in +// which units of work can be executed with duplicate suppression. +type Group struct { + mu sync.Mutex // protects m + m map[string]*call // lazily initialized +} + +// Result holds the results of Do, so they can be passed +// on a channel. +type Result struct { + Val any + Err error + Shared bool +} + +// Do executes and returns the results of the given function, making +// sure that only one execution is in-flight for a given key at a +// time. If a duplicate comes in, the duplicate caller waits for the +// original to complete and receives the same results. +// The return value shared indicates whether v was given to multiple callers. +func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool) { + g.mu.Lock() + if g.m == nil { + g.m = make(map[string]*call) + } + if c, ok := g.m[key]; ok { + c.dups++ + g.mu.Unlock() + c.wg.Wait() + return c.val, c.err, true + } + c := new(call) + c.wg.Add(1) + g.m[key] = c + g.mu.Unlock() + + g.doCall(c, key, fn) + return c.val, c.err, c.dups > 0 +} + +// DoChan is like Do but returns a channel that will receive the +// results when they are ready. +func (g *Group) DoChan(key string, fn func() (any, error)) <-chan Result { + ch := make(chan Result, 1) + g.mu.Lock() + if g.m == nil { + g.m = make(map[string]*call) + } + if c, ok := g.m[key]; ok { + c.dups++ + c.chans = append(c.chans, ch) + g.mu.Unlock() + return ch + } + c := &call{chans: []chan<- Result{ch}} + c.wg.Add(1) + g.m[key] = c + g.mu.Unlock() + + go g.doCall(c, key, fn) + + return ch +} + +// doCall handles the single call for a key. +func (g *Group) doCall(c *call, key string, fn func() (any, error)) { + c.val, c.err = fn() + + g.mu.Lock() + c.wg.Done() + if g.m[key] == c { + delete(g.m, key) + } + for _, ch := range c.chans { + ch <- Result{c.val, c.err, c.dups > 0} + } + g.mu.Unlock() +} + +// ForgetUnshared tells the singleflight to forget about a key if it is not +// shared with any other goroutines. Future calls to Do for a forgotten key +// will call the function rather than waiting for an earlier call to complete. +// Returns whether the key was forgotten or unknown--that is, whether no +// other goroutines are waiting for the result. +func (g *Group) ForgetUnshared(key string) bool { + g.mu.Lock() + defer g.mu.Unlock() + c, ok := g.m[key] + if !ok { + return true + } + if c.dups == 0 { + delete(g.m, key) + return true + } + return false +} diff --git a/go/src/internal/singleflight/singleflight_test.go b/go/src/internal/singleflight/singleflight_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0cce6a7422b34603709c46106e33555206295cf9 --- /dev/null +++ b/go/src/internal/singleflight/singleflight_test.go @@ -0,0 +1,186 @@ +// 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 singleflight + +import ( + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestDo(t *testing.T) { + var g Group + v, err, _ := g.Do("key", func() (any, error) { + return "bar", nil + }) + if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { + t.Errorf("Do = %v; want %v", got, want) + } + if err != nil { + t.Errorf("Do error = %v", err) + } +} + +func TestDoErr(t *testing.T) { + var g Group + someErr := errors.New("some error") + v, err, _ := g.Do("key", func() (any, error) { + return nil, someErr + }) + if err != someErr { + t.Errorf("Do error = %v; want someErr %v", err, someErr) + } + if v != nil { + t.Errorf("unexpected non-nil value %#v", v) + } +} + +func TestDoDupSuppress(t *testing.T) { + var g Group + var wg1, wg2 sync.WaitGroup + c := make(chan string, 1) + var calls atomic.Int32 + fn := func() (any, error) { + if calls.Add(1) == 1 { + // First invocation. + wg1.Done() + } + v := <-c + c <- v // pump; make available for any future calls + + time.Sleep(10 * time.Millisecond) // let more goroutines enter Do + + return v, nil + } + + const n = 10 + wg1.Add(1) + for i := 0; i < n; i++ { + wg1.Add(1) + wg2.Add(1) + go func() { + defer wg2.Done() + wg1.Done() + v, err, _ := g.Do("key", fn) + if err != nil { + t.Errorf("Do error: %v", err) + return + } + if s, _ := v.(string); s != "bar" { + t.Errorf("Do = %T %v; want %q", v, v, "bar") + } + }() + } + wg1.Wait() + // At least one goroutine is in fn now and all of them have at + // least reached the line before the Do. + c <- "bar" + wg2.Wait() + if got := calls.Load(); got <= 0 || got >= n { + t.Errorf("number of calls = %d; want over 0 and less than %d", got, n) + } +} + +func TestForgetUnshared(t *testing.T) { + var g Group + + var firstStarted, firstFinished sync.WaitGroup + + firstStarted.Add(1) + firstFinished.Add(1) + + key := "key" + firstCh := make(chan struct{}) + go func() { + g.Do(key, func() (i any, e error) { + firstStarted.Done() + <-firstCh + return + }) + firstFinished.Done() + }() + + firstStarted.Wait() + g.ForgetUnshared(key) // from this point no two function using same key should be executed concurrently + + secondCh := make(chan struct{}) + go func() { + g.Do(key, func() (i any, e error) { + // Notify that we started + secondCh <- struct{}{} + <-secondCh + return 2, nil + }) + }() + + <-secondCh + + resultCh := g.DoChan(key, func() (i any, e error) { + panic("third must not be started") + }) + + if g.ForgetUnshared(key) { + t.Errorf("Before first goroutine finished, key %q is shared, should return false", key) + } + + close(firstCh) + firstFinished.Wait() + + if g.ForgetUnshared(key) { + t.Errorf("After first goroutine finished, key %q is still shared, should return false", key) + } + + secondCh <- struct{}{} + + if result := <-resultCh; result.Val != 2 { + t.Errorf("We should receive result produced by second call, expected: 2, got %d", result.Val) + } +} + +func TestDoAndForgetUnsharedRace(t *testing.T) { + t.Parallel() + + var g Group + key := "key" + d := time.Millisecond + for { + var calls, shared atomic.Int64 + const n = 1000 + var wg sync.WaitGroup + wg.Add(n) + for i := 0; i < n; i++ { + go func() { + g.Do(key, func() (any, error) { + time.Sleep(d) + return calls.Add(1), nil + }) + if !g.ForgetUnshared(key) { + shared.Add(1) + } + wg.Done() + }() + } + wg.Wait() + + if calls.Load() != 1 { + // The goroutines didn't park in g.Do in time, + // so the key was re-added and may have been shared after the call. + // Try again with more time to park. + d *= 2 + continue + } + + // All of the Do calls ended up sharing the first + // invocation, so the key should have been unused + // (and therefore unshared) when they returned. + if shared.Load() > 0 { + t.Errorf("after a single shared Do, ForgetUnshared returned false %d times", shared.Load()) + } + break + } +} diff --git a/go/src/internal/strconv/atob.go b/go/src/internal/strconv/atob.go new file mode 100644 index 0000000000000000000000000000000000000000..cbeba7f8bc940866115fa30da0b03a62e06310f8 --- /dev/null +++ b/go/src/internal/strconv/atob.go @@ -0,0 +1,35 @@ +// 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 strconv + +// ParseBool returns the boolean value represented by the string. +// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. +// Any other value returns an error. +func ParseBool(str string) (bool, error) { + switch str { + case "1", "t", "T", "true", "TRUE", "True": + return true, nil + case "0", "f", "F", "false", "FALSE", "False": + return false, nil + } + return false, ErrSyntax +} + +// FormatBool returns "true" or "false" according to the value of b. +func FormatBool(b bool) string { + if b { + return "true" + } + return "false" +} + +// AppendBool appends "true" or "false", according to the value of b, +// to dst and returns the extended buffer. +func AppendBool(dst []byte, b bool) []byte { + if b { + return append(dst, "true"...) + } + return append(dst, "false"...) +} diff --git a/go/src/internal/strconv/atob_test.go b/go/src/internal/strconv/atob_test.go new file mode 100644 index 0000000000000000000000000000000000000000..61f543df3081a8d5b4be8a6c98ebf3338addccbd --- /dev/null +++ b/go/src/internal/strconv/atob_test.go @@ -0,0 +1,76 @@ +// 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 strconv_test + +import ( + "bytes" + . "internal/strconv" + "testing" +) + +type atobTest struct { + in string + out bool + err error +} + +var atobtests = []atobTest{ + {"", false, ErrSyntax}, + {"asdf", false, ErrSyntax}, + {"0", false, nil}, + {"f", false, nil}, + {"F", false, nil}, + {"FALSE", false, nil}, + {"false", false, nil}, + {"False", false, nil}, + {"1", true, nil}, + {"t", true, nil}, + {"T", true, nil}, + {"TRUE", true, nil}, + {"true", true, nil}, + {"True", true, nil}, +} + +func TestParseBool(t *testing.T) { + for _, test := range atobtests { + b, e := ParseBool(test.in) + if b != test.out || e != test.err { + t.Errorf("ParseBool(%s) = %v, %v, want %v, %v", test.in, b, e, test.out, test.err) + } + } +} + +var boolString = map[bool]string{ + true: "true", + false: "false", +} + +func TestFormatBool(t *testing.T) { + for b, s := range boolString { + if f := FormatBool(b); f != s { + t.Errorf("FormatBool(%v) = %q; want %q", b, f, s) + } + } +} + +type appendBoolTest struct { + b bool + in []byte + out []byte +} + +var appendBoolTests = []appendBoolTest{ + {true, []byte("foo "), []byte("foo true")}, + {false, []byte("foo "), []byte("foo false")}, +} + +func TestAppendBool(t *testing.T) { + for _, test := range appendBoolTests { + b := AppendBool(test.in, test.b) + if !bytes.Equal(b, test.out) { + t.Errorf("AppendBool(%q, %v) = %q; want %q", test.in, test.b, b, test.out) + } + } +} diff --git a/go/src/internal/strconv/atoc.go b/go/src/internal/strconv/atoc.go new file mode 100644 index 0000000000000000000000000000000000000000..52f2fc82af3bf181de968a140e1eb703aa419e4a --- /dev/null +++ b/go/src/internal/strconv/atoc.go @@ -0,0 +1,88 @@ +// 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 strconv + +// ParseComplex converts the string s to a complex number +// with the precision specified by bitSize: 64 for complex64, or 128 for complex128. +// When bitSize=64, the result still has type complex128, but it will be +// convertible to complex64 without changing its value. +// +// The number represented by s must be of the form N, Ni, or N±Ni, where N stands +// for a floating-point number as recognized by [ParseFloat], and i is the imaginary +// component. If the second N is unsigned, a + sign is required between the two components +// as indicated by the ±. If the second N is NaN, only a + sign is accepted. +// The form may be parenthesized and cannot contain any spaces. +// The resulting complex number consists of the two components converted by ParseFloat. +// +// The errors that ParseComplex returns have concrete type [*NumError] +// and include err.Num = s. +// +// If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax. +// +// If s is syntactically well-formed but either component is more than 1/2 ULP +// away from the largest floating point number of the given component's size, +// ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component. +func ParseComplex(s string, bitSize int) (complex128, error) { + size := 64 + if bitSize == 64 { + size = 32 // complex64 uses float32 parts + } + + // Remove parentheses, if any. + if len(s) >= 2 && s[0] == '(' && s[len(s)-1] == ')' { + s = s[1 : len(s)-1] + } + + var pending error // pending range error, or nil + + // Read real part (possibly imaginary part if followed by 'i'). + re, n, err := parseFloatPrefix(s, size) + if err != nil { + if err != ErrRange { + return 0, err + } + pending = err + } + s = s[n:] + + // If we have nothing left, we're done. + if len(s) == 0 { + return complex(re, 0), pending + } + + // Otherwise, look at the next character. + switch s[0] { + case '+': + // Consume the '+' to avoid an error if we have "+NaNi", but + // do this only if we don't have a "++" (don't hide that error). + if len(s) > 1 && s[1] != '+' { + s = s[1:] + } + case '-': + // ok + case 'i': + // If 'i' is the last character, we only have an imaginary part. + if len(s) == 1 { + return complex(0, re), pending + } + fallthrough + default: + return 0, ErrSyntax + } + + // Read imaginary part. + im, n, err := parseFloatPrefix(s, size) + if err != nil { + if err != ErrRange { + return 0, err + } + pending = err + } + s = s[n:] + if s != "i" { + return 0, ErrSyntax + } + return complex(re, im), pending +} diff --git a/go/src/internal/strconv/atoc_test.go b/go/src/internal/strconv/atoc_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f1bde2939ae45836b59510649ca9c4ccd4237300 --- /dev/null +++ b/go/src/internal/strconv/atoc_test.go @@ -0,0 +1,222 @@ +// 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 strconv_test + +import ( + . "internal/strconv" + "math" + "math/cmplx" + "testing" +) + +var ( + infp0 = complex(math.Inf(+1), 0) + infm0 = complex(math.Inf(-1), 0) + inf0p = complex(0, math.Inf(+1)) + inf0m = complex(0, math.Inf(-1)) + + infpp = complex(math.Inf(+1), math.Inf(+1)) + infpm = complex(math.Inf(+1), math.Inf(-1)) + infmp = complex(math.Inf(-1), math.Inf(+1)) + infmm = complex(math.Inf(-1), math.Inf(-1)) +) + +type atocTest struct { + in string + out complex128 + err error +} + +func TestParseComplex(t *testing.T) { + tests := []atocTest{ + // Clearly invalid + {"", 0, ErrSyntax}, + {" ", 0, ErrSyntax}, + {"(", 0, ErrSyntax}, + {")", 0, ErrSyntax}, + {"i", 0, ErrSyntax}, + {"+i", 0, ErrSyntax}, + {"-i", 0, ErrSyntax}, + {"1I", 0, ErrSyntax}, + {"10 + 5i", 0, ErrSyntax}, + {"3+", 0, ErrSyntax}, + {"3+5", 0, ErrSyntax}, + {"3+5+5i", 0, ErrSyntax}, + + // Parentheses + {"()", 0, ErrSyntax}, + {"(i)", 0, ErrSyntax}, + {"(0)", 0, nil}, + {"(1i)", 1i, nil}, + {"(3.0+5.5i)", 3.0 + 5.5i, nil}, + {"(1)+1i", 0, ErrSyntax}, + {"(3.0+5.5i", 0, ErrSyntax}, + {"3.0+5.5i)", 0, ErrSyntax}, + + // NaNs + {"NaN", complex(math.NaN(), 0), nil}, + {"NANi", complex(0, math.NaN()), nil}, + {"nan+nAni", complex(math.NaN(), math.NaN()), nil}, + {"+NaN", 0, ErrSyntax}, + {"-NaN", 0, ErrSyntax}, + {"NaN-NaNi", 0, ErrSyntax}, + + // Infs + {"Inf", infp0, nil}, + {"+inf", infp0, nil}, + {"-inf", infm0, nil}, + {"Infinity", infp0, nil}, + {"+INFINITY", infp0, nil}, + {"-infinity", infm0, nil}, + {"+infi", inf0p, nil}, + {"0-infinityi", inf0m, nil}, + {"Inf+Infi", infpp, nil}, + {"+Inf-Infi", infpm, nil}, + {"-Infinity+Infi", infmp, nil}, + {"inf-inf", 0, ErrSyntax}, + + // Zeros + {"0", 0, nil}, + {"0i", 0, nil}, + {"-0.0i", 0, nil}, + {"0+0.0i", 0, nil}, + {"0e+0i", 0, nil}, + {"0e-0+0i", 0, nil}, + {"-0.0-0.0i", 0, nil}, + {"0e+012345", 0, nil}, + {"0x0p+012345i", 0, nil}, + {"0x0.00p-012345i", 0, nil}, + {"+0e-0+0e-0i", 0, nil}, + {"0e+0+0e+0i", 0, nil}, + {"-0e+0-0e+0i", 0, nil}, + + // Regular non-zeroes + {"0.1", 0.1, nil}, + {"0.1i", 0 + 0.1i, nil}, + {"0.123", 0.123, nil}, + {"0.123i", 0 + 0.123i, nil}, + {"0.123+0.123i", 0.123 + 0.123i, nil}, + {"99", 99, nil}, + {"+99", 99, nil}, + {"-99", -99, nil}, + {"+1i", 1i, nil}, + {"-1i", -1i, nil}, + {"+3+1i", 3 + 1i, nil}, + {"30+3i", 30 + 3i, nil}, + {"+3e+3-3e+3i", 3e+3 - 3e+3i, nil}, + {"+3e+3+3e+3i", 3e+3 + 3e+3i, nil}, + {"+3e+3+3e+3i+", 0, ErrSyntax}, + + // Separators + {"0.1", 0.1, nil}, + {"0.1i", 0 + 0.1i, nil}, + {"0.1_2_3", 0.123, nil}, + {"+0x_3p3i", 0x3p3i, nil}, + {"0_0+0x_0p0i", 0, nil}, + {"0x_10.3p-8+0x3p3i", 0x10.3p-8 + 0x3p3i, nil}, + {"+0x_1_0.3p-8+0x_3_0p3i", 0x10.3p-8 + 0x30p3i, nil}, + {"0x1_0.3p+8-0x_3p3i", 0x10.3p+8 - 0x3p3i, nil}, + + // Hexadecimals + {"0x10.3p-8+0x3p3i", 0x10.3p-8 + 0x3p3i, nil}, + {"+0x10.3p-8+0x3p3i", 0x10.3p-8 + 0x3p3i, nil}, + {"0x10.3p+8-0x3p3i", 0x10.3p+8 - 0x3p3i, nil}, + {"0x1p0", 1, nil}, + {"0x1p1", 2, nil}, + {"0x1p-1", 0.5, nil}, + {"0x1ep-1", 15, nil}, + {"-0x1ep-1", -15, nil}, + {"-0x2p3", -16, nil}, + {"0x1e2", 0, ErrSyntax}, + {"1p2", 0, ErrSyntax}, + {"0x1e2i", 0, ErrSyntax}, + + // ErrRange + // next float64 - too large + {"+0x1p1024", infp0, ErrRange}, + {"-0x1p1024", infm0, ErrRange}, + {"+0x1p1024i", inf0p, ErrRange}, + {"-0x1p1024i", inf0m, ErrRange}, + {"+0x1p1024+0x1p1024i", infpp, ErrRange}, + {"+0x1p1024-0x1p1024i", infpm, ErrRange}, + {"-0x1p1024+0x1p1024i", infmp, ErrRange}, + {"-0x1p1024-0x1p1024i", infmm, ErrRange}, + // the border is ...158079 + // borderline - okay + {"+0x1.fffffffffffff7fffp1023+0x1.fffffffffffff7fffp1023i", 1.7976931348623157e+308 + 1.7976931348623157e+308i, nil}, + {"+0x1.fffffffffffff7fffp1023-0x1.fffffffffffff7fffp1023i", 1.7976931348623157e+308 - 1.7976931348623157e+308i, nil}, + {"-0x1.fffffffffffff7fffp1023+0x1.fffffffffffff7fffp1023i", -1.7976931348623157e+308 + 1.7976931348623157e+308i, nil}, + {"-0x1.fffffffffffff7fffp1023-0x1.fffffffffffff7fffp1023i", -1.7976931348623157e+308 - 1.7976931348623157e+308i, nil}, + // borderline - too large + {"+0x1.fffffffffffff8p1023", infp0, ErrRange}, + {"-0x1fffffffffffff.8p+971", infm0, ErrRange}, + {"+0x1.fffffffffffff8p1023i", inf0p, ErrRange}, + {"-0x1fffffffffffff.8p+971i", inf0m, ErrRange}, + {"+0x1.fffffffffffff8p1023+0x1.fffffffffffff8p1023i", infpp, ErrRange}, + {"+0x1.fffffffffffff8p1023-0x1.fffffffffffff8p1023i", infpm, ErrRange}, + {"-0x1fffffffffffff.8p+971+0x1fffffffffffff.8p+971i", infmp, ErrRange}, + {"-0x1fffffffffffff8p+967-0x1fffffffffffff8p+967i", infmm, ErrRange}, + // a little too large + {"1e308+1e308i", 1e+308 + 1e+308i, nil}, + {"2e308+2e308i", infpp, ErrRange}, + {"1e309+1e309i", infpp, ErrRange}, + {"0x1p1025+0x1p1025i", infpp, ErrRange}, + {"2e308", infp0, ErrRange}, + {"1e309", infp0, ErrRange}, + {"0x1p1025", infp0, ErrRange}, + {"2e308i", inf0p, ErrRange}, + {"1e309i", inf0p, ErrRange}, + {"0x1p1025i", inf0p, ErrRange}, + // way too large + {"+1e310+1e310i", infpp, ErrRange}, + {"+1e310-1e310i", infpm, ErrRange}, + {"-1e310+1e310i", infmp, ErrRange}, + {"-1e310-1e310i", infmm, ErrRange}, + // under/overflow exponent + {"1e-4294967296", 0, nil}, + {"1e-4294967296i", 0, nil}, + {"1e-4294967296+1i", 1i, nil}, + {"1+1e-4294967296i", 1, nil}, + {"1e-4294967296+1e-4294967296i", 0, nil}, + {"1e+4294967296", infp0, ErrRange}, + {"1e+4294967296i", inf0p, ErrRange}, + {"1e+4294967296+1e+4294967296i", infpp, ErrRange}, + {"1e+4294967296-1e+4294967296i", infpm, ErrRange}, + } + for i := range tests { + test := &tests[i] + c, e := ParseComplex(test.in, 128) + if !sameComplex(c, test.out) || e != test.err { + t.Errorf("ParseComplex(%s, 128) = %v, %v, want %v, %v", test.in, c, e, test.out, test.err) + } + if complex128(complex64(test.out)) == test.out { + c, e := ParseComplex(test.in, 64) + c64 := complex64(c) + if !sameComplex(complex128(c64), test.out) || e != test.err { + t.Errorf("ParseComplex(%s, 64) = %v, %v, want %v, %v", test.in, c, e, test.out, test.err) + } + } + } +} + +func sameComplex(c1, c2 complex128) bool { + return cmplx.IsNaN(c1) && cmplx.IsNaN(c2) || c1 == c2 +} + +// Issue 42297: allow ParseComplex(s, not_32_or_64) for legacy reasons +func TestParseComplexIncorrectBitSize(t *testing.T) { + const s = "1.5e308+1.0e307i" + const want = 1.5e308 + 1.0e307i + + for _, bitSize := range []int{0, 10, 100, 256} { + c, err := ParseComplex(s, bitSize) + if err != nil { + t.Fatalf("ParseComplex(%q, %d) gave error %s", s, bitSize, err) + } + if c != want { + t.Fatalf("ParseComplex(%q, %d) = %g (expected %g)", s, bitSize, c, want) + } + } +} diff --git a/go/src/internal/strconv/atof.go b/go/src/internal/strconv/atof.go new file mode 100644 index 0000000000000000000000000000000000000000..ada45dc0aa92c14fcdb2a5f0827da7f49ea617ae --- /dev/null +++ b/go/src/internal/strconv/atof.go @@ -0,0 +1,706 @@ +// 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 strconv + +// decimal to binary floating point conversion. +// Algorithm: +// 1) Store input in multiprecision decimal. +// 2) Multiply/divide decimal by powers of two until in range [0.5, 1) +// 3) Multiply by 2^precision and round to get mantissa. + +var optimize = true // set to false to force slow-path conversions for testing + +// commonPrefixLenIgnoreCase returns the length of the common +// prefix of s and prefix, with the character case of s ignored. +// The prefix argument must be all lower-case. +func commonPrefixLenIgnoreCase(s, prefix string) int { + n := min(len(prefix), len(s)) + for i := 0; i < n; i++ { + c := s[i] + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + if c != prefix[i] { + return i + } + } + return n +} + +// special returns the floating-point value for the special, +// possibly signed floating-point representations inf, infinity, +// and NaN. The result is ok if a prefix of s contains one +// of these representations and n is the length of that prefix. +// The character case is ignored. +func special(s string) (f float64, n int, ok bool) { + if len(s) == 0 { + return 0, 0, false + } + sign := 1 + nsign := 0 + switch s[0] { + case '+', '-': + if s[0] == '-' { + sign = -1 + } + nsign = 1 + s = s[1:] + fallthrough + case 'i', 'I': + n := commonPrefixLenIgnoreCase(s, "infinity") + // Anything longer than "inf" is ok, but if we + // don't have "infinity", only consume "inf". + if 3 < n && n < 8 { + n = 3 + } + if n == 3 || n == 8 { + return inf(sign), nsign + n, true + } + case 'n', 'N': + if commonPrefixLenIgnoreCase(s, "nan") == 3 { + return nan(), 3, true + } + } + return 0, 0, false +} + +func (b *decimal) set(s string) (ok bool) { + i := 0 + b.neg = false + b.trunc = false + + // optional sign + if i >= len(s) { + return + } + switch s[i] { + case '+': + i++ + case '-': + i++ + b.neg = true + } + + // digits + sawdot := false + sawdigits := false + for ; i < len(s); i++ { + switch { + case s[i] == '_': + // readFloat already checked underscores + continue + case s[i] == '.': + if sawdot { + return + } + sawdot = true + b.dp = b.nd + continue + + case '0' <= s[i] && s[i] <= '9': + sawdigits = true + if s[i] == '0' && b.nd == 0 { // ignore leading zeros + b.dp-- + continue + } + if b.nd < len(b.d) { + b.d[b.nd] = s[i] + b.nd++ + } else if s[i] != '0' { + b.trunc = true + } + continue + } + break + } + if !sawdigits { + return + } + if !sawdot { + b.dp = b.nd + } + + // optional exponent moves decimal point. + // if we read a very large, very long number, + // just be sure to move the decimal point by + // a lot (say, 100000). it doesn't matter if it's + // not the exact number. + if i < len(s) && lower(s[i]) == 'e' { + i++ + if i >= len(s) { + return + } + esign := 1 + switch s[i] { + case '+': + i++ + case '-': + i++ + esign = -1 + } + if i >= len(s) || s[i] < '0' || s[i] > '9' { + return + } + e := 0 + for ; i < len(s) && ('0' <= s[i] && s[i] <= '9' || s[i] == '_'); i++ { + if s[i] == '_' { + // readFloat already checked underscores + continue + } + if e < 10000 { + e = e*10 + int(s[i]) - '0' + } + } + b.dp += e * esign + } + + if i != len(s) { + return + } + + ok = true + return +} + +// readFloat reads a decimal or hexadecimal mantissa and exponent from a float +// string representation in s; the number may be followed by other characters. +// readFloat reports the number of bytes consumed (i), and whether the number +// is valid (ok). +func readFloat(s string) (mantissa uint64, exp int, neg, trunc, hex bool, i int, ok bool) { + underscores := false + + // optional sign + if i >= len(s) { + return + } + switch s[i] { + case '+': + i++ + case '-': + i++ + neg = true + } + + // digits + base := uint64(10) + maxMantDigits := 19 // 10^19 fits in uint64 + expChar := byte('e') + if i+2 < len(s) && s[i] == '0' && lower(s[i+1]) == 'x' { + base = 16 + maxMantDigits = 16 // 16^16 fits in uint64 + i += 2 + expChar = 'p' + hex = true + } + sawdot := false + sawdigits := false + nd := 0 + ndMant := 0 + dp := 0 +loop: + for ; i < len(s); i++ { + switch c := s[i]; true { + case c == '_': + underscores = true + continue + + case c == '.': + if sawdot { + break loop + } + sawdot = true + dp = nd + continue + + case '0' <= c && c <= '9': + sawdigits = true + if c == '0' && nd == 0 { // ignore leading zeros + dp-- + continue + } + nd++ + if ndMant < maxMantDigits { + mantissa *= base + mantissa += uint64(c - '0') + ndMant++ + } else if c != '0' { + trunc = true + } + continue + + case base == 16 && 'a' <= lower(c) && lower(c) <= 'f': + sawdigits = true + nd++ + if ndMant < maxMantDigits { + mantissa *= 16 + mantissa += uint64(lower(c) - 'a' + 10) + ndMant++ + } else { + trunc = true + } + continue + } + break + } + if !sawdigits { + return + } + if !sawdot { + dp = nd + } + + if base == 16 { + dp *= 4 + ndMant *= 4 + } + + // optional exponent moves decimal point. + // if we read a very large, very long number, + // just be sure to move the decimal point by + // a lot (say, 100000). it doesn't matter if it's + // not the exact number. + if i < len(s) && lower(s[i]) == expChar { + i++ + if i >= len(s) { + return + } + esign := 1 + switch s[i] { + case '+': + i++ + case '-': + i++ + esign = -1 + } + if i >= len(s) || s[i] < '0' || s[i] > '9' { + return + } + e := 0 + for ; i < len(s) && ('0' <= s[i] && s[i] <= '9' || s[i] == '_'); i++ { + if s[i] == '_' { + underscores = true + continue + } + if e < 10000 { + e = e*10 + int(s[i]) - '0' + } + } + dp += e * esign + } else if base == 16 { + // Must have exponent. + return + } + + if mantissa != 0 { + exp = dp - ndMant + } + + if underscores && !underscoreOK(s[:i]) { + return + } + + ok = true + return +} + +// decimal power of ten to binary power of two. +var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26} + +func (d *decimal) floatBits(flt *floatInfo) (b uint64, overflow bool) { + var exp int + var mant uint64 + + // Zero is always a special case. + if d.nd == 0 { + mant = 0 + exp = flt.bias + goto out + } + + // Obvious overflow/underflow. + // These bounds are for 64-bit floats. + // Will have to change if we want to support 80-bit floats in the future. + if d.dp > 310 { + goto overflow + } + if d.dp < -330 { + // zero + mant = 0 + exp = flt.bias + goto out + } + + // Scale by powers of two until in range [0.5, 1.0) + exp = 0 + for d.dp > 0 { + var n int + if d.dp >= len(powtab) { + n = 27 + } else { + n = powtab[d.dp] + } + d.Shift(-n) + exp += n + } + for d.dp < 0 || d.dp == 0 && d.d[0] < '5' { + var n int + if -d.dp >= len(powtab) { + n = 27 + } else { + n = powtab[-d.dp] + } + d.Shift(n) + exp -= n + } + + // Our range is [0.5,1) but floating point range is [1,2). + exp-- + + // Minimum representable exponent is flt.bias+1. + // If the exponent is smaller, move it up and + // adjust d accordingly. + if exp < flt.bias+1 { + n := flt.bias + 1 - exp + d.Shift(-n) + exp += n + } + + if exp-flt.bias >= 1<>= 1 + exp++ + if exp-flt.bias >= 1<>float64info.mantbits != 0 { + return + } + f = float64(mantissa) + if neg { + f = -f + } + switch { + case exp == 0: + // an integer. + return f, true + // Exact integers are <= 10^15. + // Exact powers of ten are <= 10^22. + case exp > 0 && exp <= 15+22: // int * 10^k + // If exponent is big but number of digits is not, + // can move a few zeros into the integer part. + if exp > 22 { + f *= float64pow10[exp-22] + exp = 22 + } + if f > 1e15 || f < -1e15 { + // the exponent was really too large. + return + } + return f * float64pow10[exp], true + case exp < 0 && exp >= -22: // int / 10^k + return f / float64pow10[-exp], true + } + return +} + +// If possible to compute mantissa*10^exp to 32-bit float f exactly, +// entirely in floating-point math, do so, avoiding the machinery above. +func atof32exact(mantissa uint64, exp int, neg bool) (f float32, ok bool) { + if mantissa>>float32MantBits != 0 { + return + } + f = float32(mantissa) + if neg { + f = -f + } + switch { + case exp == 0: + return f, true + // Exact integers are <= 10^7. + // Exact powers of ten are <= 10^10. + case exp > 0 && exp <= 7+10: // int * 10^k + // If exponent is big but number of digits is not, + // can move a few zeros into the integer part. + if exp > 10 { + f *= float32pow10[exp-10] + exp = 10 + } + if f > 1e7 || f < -1e7 { + // the exponent was really too large. + return + } + return f * float32pow10[exp], true + case exp < 0 && exp >= -10: // int / 10^k + return f / float32pow10[-exp], true + } + return +} + +// atofHex converts the hex floating-point string s +// to a rounded float32 or float64 value (depending on flt==&float32info or flt==&float64info) +// and returns it as a float64. +// The string s has already been parsed into a mantissa, exponent, and sign (neg==true for negative). +// If trunc is true, trailing non-zero bits have been omitted from the mantissa. +func atofHex(s string, flt *floatInfo, mantissa uint64, exp int, neg, trunc bool) (float64, error) { + maxExp := 1<>(flt.mantbits+2) == 0 { + mantissa <<= 1 + exp-- + } + if trunc { + mantissa |= 1 + } + for mantissa>>(1+flt.mantbits+2) != 0 { + mantissa = mantissa>>1 | mantissa&1 + exp++ + } + + // If exponent is too negative, + // denormalize in hopes of making it representable. + // (The -2 is for the rounding bits.) + for mantissa > 1 && exp < minExp-2 { + mantissa = mantissa>>1 | mantissa&1 + exp++ + } + + // Round using two bottom bits. + round := mantissa & 3 + mantissa >>= 2 + round |= mantissa & 1 // round to even (round up if mantissa is odd) + exp += 2 + if round == 3 { + mantissa++ + if mantissa == 1<<(1+flt.mantbits) { + mantissa >>= 1 + exp++ + } + } + + if mantissa>>flt.mantbits == 0 { // Denormal or zero. + exp = flt.bias + } + var err error + if exp > maxExp { // infinity and range error + mantissa = 1 << flt.mantbits + exp = maxExp + 1 + err = ErrRange + } + + bits := mantissa & (1<", "(", ")", "i", "init"} { + in := test.in + suffix + _, n, err := parseFloatPrefix(in, 64) + if err != nil { + t.Errorf("ParseFloatPrefix(%q, 64): err = %v; want no error", in, err) + } + if n != len(test.in) { + t.Errorf("ParseFloatPrefix(%q, 64): n = %d; want %d", in, n, len(test.in)) + } + } + } +} + +func testAtof(t *testing.T, opt bool) { + initAtof() + oldopt := SetOptimize(opt) + for i := 0; i < len(atoftests); i++ { + test := &atoftests[i] + out, err := ParseFloat(test.in, 64) + outs := FormatFloat(out, 'g', -1, 64) + if outs != test.out || !reflect.DeepEqual(err, test.err) { + t.Errorf("ParseFloat(%v, 64) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + + if float64(float32(out)) == out { + out, err := ParseFloat(test.in, 32) + out32 := float32(out) + if float64(out32) != out { + t.Errorf("ParseFloat(%v, 32) = %v, not a float32 (closest is %v)", test.in, out, float64(out32)) + continue + } + outs := FormatFloat(float64(out32), 'g', -1, 32) + if outs != test.out || !reflect.DeepEqual(err, test.err) { + t.Errorf("ParseFloat(%v, 32) = %v, %v want %v, %v # %v", + test.in, out32, err, test.out, test.err, out) + } + } + } + for _, test := range atof32tests { + out, err := ParseFloat(test.in, 32) + out32 := float32(out) + if float64(out32) != out { + t.Errorf("ParseFloat(%v, 32) = %v, not a float32 (closest is %v)", test.in, out, float64(out32)) + continue + } + outs := FormatFloat(float64(out32), 'g', -1, 32) + if outs != test.out || !reflect.DeepEqual(err, test.err) { + t.Errorf("ParseFloat(%v, 32) = %v, %v want %v, %v # %v", + test.in, out32, err, test.out, test.err, out) + } + } + SetOptimize(oldopt) +} + +func TestAtof(t *testing.T) { testAtof(t, true) } + +func TestAtofSlow(t *testing.T) { testAtof(t, false) } + +func TestAtofRandom(t *testing.T) { + initAtof() + for _, test := range atofRandomTests { + x, _ := ParseFloat(test.s, 64) + switch { + default: + t.Errorf("number %s badly parsed as %b (expected %b)", test.s, x, test.x) + case x == test.x: + case math.IsNaN(test.x) && math.IsNaN(x): + } + } + t.Logf("tested %d random numbers", len(atofRandomTests)) +} + +var roundTripCases = []struct { + f float64 + s string +}{ + // Issue 2917. + // This test will break the optimized conversion if the + // FPU is using 80-bit registers instead of 64-bit registers, + // usually because the operating system initialized the + // thread with 80-bit precision and the Go runtime didn't + // fix the FP control word. + {8865794286000691 << 39, "4.87402195346389e+27"}, + {8865794286000692 << 39, "4.8740219534638903e+27"}, +} + +func TestRoundTrip(t *testing.T) { + for _, tt := range roundTripCases { + old := SetOptimize(false) + s := FormatFloat(tt.f, 'g', -1, 64) + if s != tt.s { + t.Errorf("no-opt FormatFloat(%b) = %s, want %s", tt.f, s, tt.s) + } + f, err := ParseFloat(tt.s, 64) + if f != tt.f || err != nil { + t.Errorf("no-opt ParseFloat(%s) = %b, %v want %b, nil", tt.s, f, err, tt.f) + } + SetOptimize(true) + s = FormatFloat(tt.f, 'g', -1, 64) + if s != tt.s { + t.Errorf("opt FormatFloat(%b) = %s, want %s", tt.f, s, tt.s) + } + f, err = ParseFloat(tt.s, 64) + if f != tt.f || err != nil { + t.Errorf("opt ParseFloat(%s) = %b, %v want %b, nil", tt.s, f, err, tt.f) + } + SetOptimize(old) + } +} + +// TestRoundTrip32 tries a fraction of all finite positive float32 values. +func TestRoundTrip32(t *testing.T) { + step := uint32(997) + if testing.Short() { + step = 99991 + } + count := 0 + for i := uint32(0); i < 0xff<<23; i += step { + f := math.Float32frombits(i) + if i&1 == 1 { + f = -f // negative + } + s := FormatFloat(float64(f), 'g', -1, 32) + + parsed, err := ParseFloat(s, 32) + parsed32 := float32(parsed) + switch { + case err != nil: + t.Errorf("ParseFloat(%q, 32) gave error %s", s, err) + case float64(parsed32) != parsed: + t.Errorf("ParseFloat(%q, 32) = %v, not a float32 (nearest is %v)", s, parsed, parsed32) + case parsed32 != f: + t.Errorf("ParseFloat(%q, 32) = %b (expected %b)", s, parsed32, f) + } + count++ + } + t.Logf("tested %d float32's", count) +} + +// Issue 42297: a lot of code in the wild accidentally calls ParseFloat(s, 10) +// or ParseFloat(s, 0), so allow bitSize values other than 32 and 64. +func TestParseFloatIncorrectBitSize(t *testing.T) { + const s = "1.5e308" + const want = 1.5e308 + + for _, bitSize := range []int{0, 10, 100, 128} { + f, err := ParseFloat(s, bitSize) + if err != nil { + t.Fatalf("ParseFloat(%q, %d) gave error %s", s, bitSize, err) + } + if f != want { + t.Fatalf("ParseFloat(%q, %d) = %g (expected %g)", s, bitSize, f, want) + } + } +} + +func BenchmarkAtof64Decimal(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("33909", 64) + } +} + +func BenchmarkAtof64Float(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("339.7784", 64) + } +} + +func BenchmarkAtof64FloatExp(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("-5.09e75", 64) + } +} + +func BenchmarkAtof64Big(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("123456789123456789123456789", 64) + } +} + +func BenchmarkAtof64RandomBits(b *testing.B) { + initAtof() + b.ResetTimer() + for i := 0; i < b.N; i++ { + ParseFloat(benchmarksRandomBits[i%1024], 64) + } +} + +func BenchmarkAtof64RandomFloats(b *testing.B) { + initAtof() + b.ResetTimer() + for i := 0; i < b.N; i++ { + ParseFloat(benchmarksRandomNormal[i%1024], 64) + } +} + +func BenchmarkAtof64RandomLongFloats(b *testing.B) { + initAtof() + samples := make([]string, len(atofRandomTests)) + for i, t := range atofRandomTests { + samples[i] = FormatFloat(t.x, 'g', 20, 64) + } + b.ResetTimer() + idx := 0 + for i := 0; i < b.N; i++ { + ParseFloat(samples[idx], 64) + idx++ + if idx == len(samples) { + idx = 0 + } + } +} + +func BenchmarkAtof32Decimal(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("33909", 32) + } +} + +func BenchmarkAtof32Float(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("339.778", 32) + } +} + +func BenchmarkAtof32FloatExp(b *testing.B) { + for i := 0; i < b.N; i++ { + ParseFloat("12.3456e32", 32) + } +} + +func BenchmarkAtof32Random(b *testing.B) { + n := uint32(997) + var float32strings [4096]string + for i := range float32strings { + n = (99991*n + 42) % (0xff << 23) + float32strings[i] = FormatFloat(float64(math.Float32frombits(n)), 'g', -1, 32) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + ParseFloat(float32strings[i%4096], 32) + } +} + +func BenchmarkAtof32RandomLong(b *testing.B) { + n := uint32(997) + var float32strings [4096]string + for i := range float32strings { + n = (99991*n + 42) % (0xff << 23) + float32strings[i] = FormatFloat(float64(math.Float32frombits(n)), 'g', 20, 32) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + ParseFloat(float32strings[i%4096], 32) + } +} diff --git a/go/src/internal/strconv/atofeisel.go b/go/src/internal/strconv/atofeisel.go new file mode 100644 index 0000000000000000000000000000000000000000..5fa92908b49cedf75856a4144335e6b3b1653b3b --- /dev/null +++ b/go/src/internal/strconv/atofeisel.go @@ -0,0 +1,166 @@ +// 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 strconv + +// This file implements the Eisel-Lemire ParseFloat algorithm, published in +// 2020 and discussed extensively at +// https://nigeltao.github.io/blog/2020/eisel-lemire.html +// +// The original C++ implementation is at +// https://github.com/lemire/fast_double_parser/blob/644bef4306059d3be01a04e77d3cc84b379c596f/include/fast_double_parser.h#L840 +// +// This Go re-implementation closely follows the C re-implementation at +// https://github.com/google/wuffs/blob/ba3818cb6b473a2ed0b38ecfc07dbbd3a97e8ae7/internal/cgen/base/floatconv-submodule-code.c#L990 +// +// Additional testing (on over several million test strings) is done by +// https://github.com/nigeltao/parse-number-fxx-test-data/blob/5280dcfccf6d0b02a65ae282dad0b6d9de50e039/script/test-go-strconv.go + +import ( + "math/bits" +) + +func eiselLemire64(man uint64, exp10 int, neg bool) (f float64, ok bool) { + // The terse comments in this function body refer to sections of the + // https://nigeltao.github.io/blog/2020/eisel-lemire.html blog post. + + // Exp10 Range. + if man == 0 { + if neg { + f = float64frombits(0x8000000000000000) // Negative zero. + } + return f, true + } + pow, exp2, ok := pow10(exp10) + if !ok { + return 0, false + } + + // Normalization. + clz := bits.LeadingZeros64(man) + man <<= uint(clz) + retExp2 := uint64(exp2+63-float64Bias) - uint64(clz) + + // Multiplication. + xHi, xLo := bits.Mul64(man, pow.Hi) + + // Wider Approximation. + if xHi&0x1FF == 0x1FF && xLo+man < man { + yHi, yLo := bits.Mul64(man, pow.Lo) + mergedHi, mergedLo := xHi, xLo+yHi + if mergedLo < xLo { + mergedHi++ + } + if mergedHi&0x1FF == 0x1FF && mergedLo+1 == 0 && yLo+man < man { + return 0, false + } + xHi, xLo = mergedHi, mergedLo + } + + // Shifting to 54 Bits. + msb := xHi >> 63 + retMantissa := xHi >> (msb + 9) + retExp2 -= 1 ^ msb + + // Half-way Ambiguity. + if xLo == 0 && xHi&0x1FF == 0 && retMantissa&3 == 1 { + return 0, false + } + + // From 54 to 53 Bits. + retMantissa += retMantissa & 1 + retMantissa >>= 1 + if retMantissa>>53 > 0 { + retMantissa >>= 1 + retExp2 += 1 + } + // retExp2 is a uint64. Zero or underflow means that we're in subnormal + // float64 space. 0x7FF or above means that we're in Inf/NaN float64 space. + // + // The if block is equivalent to (but has fewer branches than): + // if retExp2 <= 0 || retExp2 >= 0x7FF { etc } + if retExp2-1 >= 0x7FF-1 { + return 0, false + } + retBits := retExp2<> 63 + retMantissa := xHi >> (msb + 38) + retExp2 -= 1 ^ msb + + // Half-way Ambiguity. + if xLo == 0 && xHi&0x3FFFFFFFFF == 0 && retMantissa&3 == 1 { + return 0, false + } + + // From 54 to 53 Bits (and for float32, it's from 25 to 24 bits). + retMantissa += retMantissa & 1 + retMantissa >>= 1 + if retMantissa>>24 > 0 { + retMantissa >>= 1 + retExp2 += 1 + } + // retExp2 is a uint64. Zero or underflow means that we're in subnormal + // float32 space. 0xFF or above means that we're in Inf/NaN float32 space. + // + // The if block is equivalent to (but has fewer branches than): + // if retExp2 <= 0 || retExp2 >= 0xFF { etc } + if retExp2-1 >= 0xFF-1 { + return 0, false + } + retBits := retExp2<> 63) + +// IntSize is the size in bits of an int or uint value. +const IntSize = intSize + +// ParseUint is like [ParseInt] but for unsigned numbers. +// +// A sign prefix is not permitted. +func ParseUint(s string, base int, bitSize int) (uint64, error) { + const fnParseUint = "ParseUint" + + if s == "" { + return 0, ErrSyntax + } + + base0 := base == 0 + + s0 := s + switch { + case 2 <= base && base <= 36: + // valid base; nothing to do + + case base == 0: + // Look for octal, hex prefix. + base = 10 + if s[0] == '0' { + switch { + case len(s) >= 3 && lower(s[1]) == 'b': + base = 2 + s = s[2:] + case len(s) >= 3 && lower(s[1]) == 'o': + base = 8 + s = s[2:] + case len(s) >= 3 && lower(s[1]) == 'x': + base = 16 + s = s[2:] + default: + base = 8 + s = s[1:] + } + } + + default: + return 0, ErrBase + } + + if bitSize == 0 { + bitSize = IntSize + } else if bitSize < 0 || bitSize > 64 { + return 0, ErrBitSize + } + + // Cutoff is the smallest number such that cutoff*base > maxUint64. + // Use compile-time constants for common cases. + var cutoff uint64 + switch base { + case 10: + cutoff = maxUint64/10 + 1 + case 16: + cutoff = maxUint64/16 + 1 + default: + cutoff = maxUint64/uint64(base) + 1 + } + + maxVal := uint64(1)<= byte(base) { + return 0, ErrSyntax + } + + if n >= cutoff { + // n*base overflows + return maxVal, ErrRange + } + n *= uint64(base) + + n1 := n + uint64(d) + if n1 < n || n1 > maxVal { + // n+d overflows + return maxVal, ErrRange + } + n = n1 + } + + if underscores && !underscoreOK(s0) { + return 0, ErrSyntax + } + + return n, nil +} + +// ParseInt interprets a string s in the given base (0, 2 to 36) and +// bit size (0 to 64) and returns the corresponding value i. +// +// The string may begin with a leading sign: "+" or "-". +// +// If the base argument is 0, the true base is implied by the string's +// prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o", +// 16 for "0x", and 10 otherwise. Also, for argument base 0 only, +// underscore characters are permitted as defined by the Go syntax for +// [integer literals]. +// +// The bitSize argument specifies the integer type +// that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 +// correspond to int, int8, int16, int32, and int64. +// If bitSize is below 0 or above 64, an error is returned. +// +// The errors that ParseInt returns have concrete type [*NumError] +// and include err.Num = s. If s is empty or contains invalid +// digits, err.Err = [ErrSyntax] and the returned value is 0; +// if the value corresponding to s cannot be represented by a +// signed integer of the given size, err.Err = [ErrRange] and the +// returned value is the maximum magnitude integer of the +// appropriate bitSize and sign. +// +// [integer literals]: https://go.dev/ref/spec#Integer_literals +func ParseInt(s string, base int, bitSize int) (i int64, err error) { + const fnParseInt = "ParseInt" + + if s == "" { + return 0, ErrSyntax + } + + // Pick off leading sign. + neg := false + switch s[0] { + case '+': + s = s[1:] + case '-': + s = s[1:] + neg = true + } + + // Convert unsigned and check range. + var un uint64 + un, err = ParseUint(s, base, bitSize) + if err != nil && err != ErrRange { + return 0, err + } + + if bitSize == 0 { + bitSize = IntSize + } + + cutoff := uint64(1 << uint(bitSize-1)) + if !neg && un >= cutoff { + return int64(cutoff - 1), ErrRange + } + if neg && un > cutoff { + return -int64(cutoff), ErrRange + } + n := int64(un) + if neg { + n = -n + } + return n, nil +} + +// Atoi is equivalent to ParseInt(s, 10, 0), converted to type int. +func Atoi(s string) (int, error) { + const fnAtoi = "Atoi" + + sLen := len(s) + if intSize == 32 && (0 < sLen && sLen < 10) || + intSize == 64 && (0 < sLen && sLen < 19) { + // Fast path for small integers that fit int type. + s0 := s + if s[0] == '-' || s[0] == '+' { + s = s[1:] + if len(s) < 1 { + return 0, ErrSyntax + } + } + + n := 0 + for _, ch := range []byte(s) { + ch -= '0' + if ch > 9 { + return 0, ErrSyntax + } + n = n*10 + int(ch) + } + if s0[0] == '-' { + n = -n + } + return n, nil + } + + // Slow path for invalid, big, or underscored integers. + i64, err := ParseInt(s, 10, 0) + return int(i64), err +} + +// underscoreOK reports whether the underscores in s are allowed. +// Checking them in this one function lets all the parsers skip over them simply. +// Underscore must appear only between digits or between a base prefix and a digit. +func underscoreOK(s string) bool { + // saw tracks the last character (class) we saw: + // ^ for beginning of number, + // 0 for a digit or base prefix, + // _ for an underscore, + // ! for none of the above. + saw := '^' + i := 0 + + // Optional sign. + if len(s) >= 1 && (s[0] == '-' || s[0] == '+') { + s = s[1:] + } + + // Optional base prefix. + hex := false + if len(s) >= 2 && s[0] == '0' && (lower(s[1]) == 'b' || lower(s[1]) == 'o' || lower(s[1]) == 'x') { + i = 2 + saw = '0' // base prefix counts as a digit for "underscore as digit separator" + hex = lower(s[1]) == 'x' + } + + // Number proper. + for ; i < len(s); i++ { + // Digits are always okay. + if '0' <= s[i] && s[i] <= '9' || hex && 'a' <= lower(s[i]) && lower(s[i]) <= 'f' { + saw = '0' + continue + } + // Underscore must follow digit. + if s[i] == '_' { + if saw != '0' { + return false + } + saw = '_' + continue + } + // Underscore must also be followed by digit. + if saw == '_' { + return false + } + // Saw non-digit, non-underscore. + saw = '!' + } + return saw != '_' +} diff --git a/go/src/internal/strconv/atoi_test.go b/go/src/internal/strconv/atoi_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c9c9a4e4e9f74bda7029d8f2a1e5491344c1b6d9 --- /dev/null +++ b/go/src/internal/strconv/atoi_test.go @@ -0,0 +1,589 @@ +// 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 strconv_test + +import ( + "fmt" + . "internal/strconv" + "reflect" + "testing" +) + +type parseUint64Test struct { + in string + out uint64 + err error +} + +var parseUint64Tests = []parseUint64Test{ + {"", 0, ErrSyntax}, + {"0", 0, nil}, + {"1", 1, nil}, + {"12345", 12345, nil}, + {"012345", 12345, nil}, + {"12345x", 0, ErrSyntax}, + {"98765432100", 98765432100, nil}, + {"18446744073709551615", 1<<64 - 1, nil}, + {"18446744073709551616", 1<<64 - 1, ErrRange}, + {"18446744073709551620", 1<<64 - 1, ErrRange}, + {"1_2_3_4_5", 0, ErrSyntax}, // base=10 so no underscores allowed + {"_12345", 0, ErrSyntax}, + {"1__2345", 0, ErrSyntax}, + {"12345_", 0, ErrSyntax}, + {"-0", 0, ErrSyntax}, + {"-1", 0, ErrSyntax}, + {"+1", 0, ErrSyntax}, +} + +type parseUint64BaseTest struct { + in string + base int + out uint64 + err error +} + +var parseUint64BaseTests = []parseUint64BaseTest{ + {"", 0, 0, ErrSyntax}, + {"0", 0, 0, nil}, + {"0x", 0, 0, ErrSyntax}, + {"0X", 0, 0, ErrSyntax}, + {"1", 0, 1, nil}, + {"12345", 0, 12345, nil}, + {"012345", 0, 012345, nil}, + {"0x12345", 0, 0x12345, nil}, + {"0X12345", 0, 0x12345, nil}, + {"12345x", 0, 0, ErrSyntax}, + {"0xabcdefg123", 0, 0, ErrSyntax}, + {"123456789abc", 0, 0, ErrSyntax}, + {"98765432100", 0, 98765432100, nil}, + {"18446744073709551615", 0, 1<<64 - 1, nil}, + {"18446744073709551616", 0, 1<<64 - 1, ErrRange}, + {"18446744073709551620", 0, 1<<64 - 1, ErrRange}, + {"0xFFFFFFFFFFFFFFFF", 0, 1<<64 - 1, nil}, + {"0x10000000000000000", 0, 1<<64 - 1, ErrRange}, + {"01777777777777777777777", 0, 1<<64 - 1, nil}, + {"01777777777777777777778", 0, 0, ErrSyntax}, + {"02000000000000000000000", 0, 1<<64 - 1, ErrRange}, + {"0200000000000000000000", 0, 1 << 61, nil}, + {"0b", 0, 0, ErrSyntax}, + {"0B", 0, 0, ErrSyntax}, + {"0b101", 0, 5, nil}, + {"0B101", 0, 5, nil}, + {"0o", 0, 0, ErrSyntax}, + {"0O", 0, 0, ErrSyntax}, + {"0o377", 0, 255, nil}, + {"0O377", 0, 255, nil}, + + // underscores allowed with base == 0 only + {"1_2_3_4_5", 0, 12345, nil}, // base 0 => 10 + {"_12345", 0, 0, ErrSyntax}, + {"1__2345", 0, 0, ErrSyntax}, + {"12345_", 0, 0, ErrSyntax}, + + {"1_2_3_4_5", 10, 0, ErrSyntax}, // base 10 + {"_12345", 10, 0, ErrSyntax}, + {"1__2345", 10, 0, ErrSyntax}, + {"12345_", 10, 0, ErrSyntax}, + + {"0x_1_2_3_4_5", 0, 0x12345, nil}, // base 0 => 16 + {"_0x12345", 0, 0, ErrSyntax}, + {"0x__12345", 0, 0, ErrSyntax}, + {"0x1__2345", 0, 0, ErrSyntax}, + {"0x1234__5", 0, 0, ErrSyntax}, + {"0x12345_", 0, 0, ErrSyntax}, + + {"1_2_3_4_5", 16, 0, ErrSyntax}, // base 16 + {"_12345", 16, 0, ErrSyntax}, + {"1__2345", 16, 0, ErrSyntax}, + {"1234__5", 16, 0, ErrSyntax}, + {"12345_", 16, 0, ErrSyntax}, + + {"0_1_2_3_4_5", 0, 012345, nil}, // base 0 => 8 (0377) + {"_012345", 0, 0, ErrSyntax}, + {"0__12345", 0, 0, ErrSyntax}, + {"01234__5", 0, 0, ErrSyntax}, + {"012345_", 0, 0, ErrSyntax}, + + {"0o_1_2_3_4_5", 0, 012345, nil}, // base 0 => 8 (0o377) + {"_0o12345", 0, 0, ErrSyntax}, + {"0o__12345", 0, 0, ErrSyntax}, + {"0o1234__5", 0, 0, ErrSyntax}, + {"0o12345_", 0, 0, ErrSyntax}, + + {"0_1_2_3_4_5", 8, 0, ErrSyntax}, // base 8 + {"_012345", 8, 0, ErrSyntax}, + {"0__12345", 8, 0, ErrSyntax}, + {"01234__5", 8, 0, ErrSyntax}, + {"012345_", 8, 0, ErrSyntax}, + + {"0b_1_0_1", 0, 5, nil}, // base 0 => 2 (0b101) + {"_0b101", 0, 0, ErrSyntax}, + {"0b__101", 0, 0, ErrSyntax}, + {"0b1__01", 0, 0, ErrSyntax}, + {"0b10__1", 0, 0, ErrSyntax}, + {"0b101_", 0, 0, ErrSyntax}, + + {"1_0_1", 2, 0, ErrSyntax}, // base 2 + {"_101", 2, 0, ErrSyntax}, + {"1_01", 2, 0, ErrSyntax}, + {"10_1", 2, 0, ErrSyntax}, + {"101_", 2, 0, ErrSyntax}, +} + +type parseInt64Test struct { + in string + out int64 + err error +} + +var parseInt64Tests = []parseInt64Test{ + {"", 0, ErrSyntax}, + {"0", 0, nil}, + {"-0", 0, nil}, + {"+0", 0, nil}, + {"1", 1, nil}, + {"-1", -1, nil}, + {"+1", 1, nil}, + {"12345", 12345, nil}, + {"-12345", -12345, nil}, + {"012345", 12345, nil}, + {"-012345", -12345, nil}, + {"98765432100", 98765432100, nil}, + {"-98765432100", -98765432100, nil}, + {"9223372036854775807", 1<<63 - 1, nil}, + {"-9223372036854775807", -(1<<63 - 1), nil}, + {"9223372036854775808", 1<<63 - 1, ErrRange}, + {"-9223372036854775808", -1 << 63, nil}, + {"9223372036854775809", 1<<63 - 1, ErrRange}, + {"-9223372036854775809", -1 << 63, ErrRange}, + {"-1_2_3_4_5", 0, ErrSyntax}, // base=10 so no underscores allowed + {"-_12345", 0, ErrSyntax}, + {"_12345", 0, ErrSyntax}, + {"1__2345", 0, ErrSyntax}, + {"12345_", 0, ErrSyntax}, + {"123%45", 0, ErrSyntax}, +} + +type parseInt64BaseTest struct { + in string + base int + out int64 + err error +} + +var parseInt64BaseTests = []parseInt64BaseTest{ + {"", 0, 0, ErrSyntax}, + {"0", 0, 0, nil}, + {"-0", 0, 0, nil}, + {"1", 0, 1, nil}, + {"-1", 0, -1, nil}, + {"12345", 0, 12345, nil}, + {"-12345", 0, -12345, nil}, + {"012345", 0, 012345, nil}, + {"-012345", 0, -012345, nil}, + {"0x12345", 0, 0x12345, nil}, + {"-0X12345", 0, -0x12345, nil}, + {"12345x", 0, 0, ErrSyntax}, + {"-12345x", 0, 0, ErrSyntax}, + {"98765432100", 0, 98765432100, nil}, + {"-98765432100", 0, -98765432100, nil}, + {"9223372036854775807", 0, 1<<63 - 1, nil}, + {"-9223372036854775807", 0, -(1<<63 - 1), nil}, + {"9223372036854775808", 0, 1<<63 - 1, ErrRange}, + {"-9223372036854775808", 0, -1 << 63, nil}, + {"9223372036854775809", 0, 1<<63 - 1, ErrRange}, + {"-9223372036854775809", 0, -1 << 63, ErrRange}, + + // other bases + {"g", 17, 16, nil}, + {"10", 25, 25, nil}, + {"holycow", 35, (((((17*35+24)*35+21)*35+34)*35+12)*35+24)*35 + 32, nil}, + {"holycow", 36, (((((17*36+24)*36+21)*36+34)*36+12)*36+24)*36 + 32, nil}, + + // base 2 + {"0", 2, 0, nil}, + {"-1", 2, -1, nil}, + {"1010", 2, 10, nil}, + {"1000000000000000", 2, 1 << 15, nil}, + {"111111111111111111111111111111111111111111111111111111111111111", 2, 1<<63 - 1, nil}, + {"1000000000000000000000000000000000000000000000000000000000000000", 2, 1<<63 - 1, ErrRange}, + {"-1000000000000000000000000000000000000000000000000000000000000000", 2, -1 << 63, nil}, + {"-1000000000000000000000000000000000000000000000000000000000000001", 2, -1 << 63, ErrRange}, + + // base 8 + {"-10", 8, -8, nil}, + {"57635436545", 8, 057635436545, nil}, + {"100000000", 8, 1 << 24, nil}, + + // base 16 + {"10", 16, 16, nil}, + {"-123456789abcdef", 16, -0x123456789abcdef, nil}, + {"7fffffffffffffff", 16, 1<<63 - 1, nil}, + + // underscores + {"-0x_1_2_3_4_5", 0, -0x12345, nil}, + {"0x_1_2_3_4_5", 0, 0x12345, nil}, + {"-_0x12345", 0, 0, ErrSyntax}, + {"_-0x12345", 0, 0, ErrSyntax}, + {"_0x12345", 0, 0, ErrSyntax}, + {"0x__12345", 0, 0, ErrSyntax}, + {"0x1__2345", 0, 0, ErrSyntax}, + {"0x1234__5", 0, 0, ErrSyntax}, + {"0x12345_", 0, 0, ErrSyntax}, + + {"-0_1_2_3_4_5", 0, -012345, nil}, // octal + {"0_1_2_3_4_5", 0, 012345, nil}, // octal + {"-_012345", 0, 0, ErrSyntax}, + {"_-012345", 0, 0, ErrSyntax}, + {"_012345", 0, 0, ErrSyntax}, + {"0__12345", 0, 0, ErrSyntax}, + {"01234__5", 0, 0, ErrSyntax}, + {"012345_", 0, 0, ErrSyntax}, + + {"+0xf", 0, 0xf, nil}, + {"-0xf", 0, -0xf, nil}, + {"0x+f", 0, 0, ErrSyntax}, + {"0x-f", 0, 0, ErrSyntax}, +} + +type parseUint32Test struct { + in string + out uint32 + err error +} + +var parseUint32Tests = []parseUint32Test{ + {"", 0, ErrSyntax}, + {"0", 0, nil}, + {"1", 1, nil}, + {"12345", 12345, nil}, + {"012345", 12345, nil}, + {"12345x", 0, ErrSyntax}, + {"987654321", 987654321, nil}, + {"4294967295", 1<<32 - 1, nil}, + {"4294967296", 1<<32 - 1, ErrRange}, + {"1_2_3_4_5", 0, ErrSyntax}, // base=10 so no underscores allowed + {"_12345", 0, ErrSyntax}, + {"_12345", 0, ErrSyntax}, + {"1__2345", 0, ErrSyntax}, + {"12345_", 0, ErrSyntax}, +} + +type parseInt32Test struct { + in string + out int32 + err error +} + +var parseInt32Tests = []parseInt32Test{ + {"", 0, ErrSyntax}, + {"0", 0, nil}, + {"-0", 0, nil}, + {"1", 1, nil}, + {"-1", -1, nil}, + {"12345", 12345, nil}, + {"-12345", -12345, nil}, + {"012345", 12345, nil}, + {"-012345", -12345, nil}, + {"12345x", 0, ErrSyntax}, + {"-12345x", 0, ErrSyntax}, + {"987654321", 987654321, nil}, + {"-987654321", -987654321, nil}, + {"2147483647", 1<<31 - 1, nil}, + {"-2147483647", -(1<<31 - 1), nil}, + {"2147483648", 1<<31 - 1, ErrRange}, + {"-2147483648", -1 << 31, nil}, + {"2147483649", 1<<31 - 1, ErrRange}, + {"-2147483649", -1 << 31, ErrRange}, + {"-1_2_3_4_5", 0, ErrSyntax}, // base=10 so no underscores allowed + {"-_12345", 0, ErrSyntax}, + {"_12345", 0, ErrSyntax}, + {"1__2345", 0, ErrSyntax}, + {"12345_", 0, ErrSyntax}, + {"123%45", 0, ErrSyntax}, +} + +type numErrorTest struct { + num, want string +} + +var numErrorTests = []numErrorTest{ + {"0", `strconv.ParseFloat: parsing "0": failed`}, + {"`", "strconv.ParseFloat: parsing \"`\": failed"}, + {"1\x00.2", `strconv.ParseFloat: parsing "1\x00.2": failed`}, +} + +func TestParseUint32(t *testing.T) { + for i := range parseUint32Tests { + test := &parseUint32Tests[i] + out, err := ParseUint(test.in, 10, 32) + if uint64(test.out) != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseUint(%q, 10, 32) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } +} + +func TestParseUint64(t *testing.T) { + for i := range parseUint64Tests { + test := &parseUint64Tests[i] + out, err := ParseUint(test.in, 10, 64) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseUint(%q, 10, 64) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } +} + +func TestParseUint64Base(t *testing.T) { + for i := range parseUint64BaseTests { + test := &parseUint64BaseTests[i] + out, err := ParseUint(test.in, test.base, 64) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseUint(%q, %v, 64) = %v, %v want %v, %v", + test.in, test.base, out, err, test.out, test.err) + } + } +} + +func TestParseInt32(t *testing.T) { + for i := range parseInt32Tests { + test := &parseInt32Tests[i] + out, err := ParseInt(test.in, 10, 32) + if int64(test.out) != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseInt(%q, 10 ,32) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } +} + +func TestParseInt64(t *testing.T) { + for i := range parseInt64Tests { + test := &parseInt64Tests[i] + out, err := ParseInt(test.in, 10, 64) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseInt(%q, 10, 64) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } +} + +func TestParseInt64Base(t *testing.T) { + for i := range parseInt64BaseTests { + test := &parseInt64BaseTests[i] + out, err := ParseInt(test.in, test.base, 64) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseInt(%q, %v, 64) = %v, %v want %v, %v", + test.in, test.base, out, err, test.out, test.err) + } + } +} + +func TestParseUint(t *testing.T) { + switch IntSize { + case 32: + for i := range parseUint32Tests { + test := &parseUint32Tests[i] + out, err := ParseUint(test.in, 10, 0) + if uint64(test.out) != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseUint(%q, 10, 0) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } + case 64: + for i := range parseUint64Tests { + test := &parseUint64Tests[i] + out, err := ParseUint(test.in, 10, 0) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseUint(%q, 10, 0) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } + } +} + +func TestParseInt(t *testing.T) { + switch IntSize { + case 32: + for i := range parseInt32Tests { + test := &parseInt32Tests[i] + out, err := ParseInt(test.in, 10, 0) + if int64(test.out) != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseInt(%q, 10, 0) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } + case 64: + for i := range parseInt64Tests { + test := &parseInt64Tests[i] + out, err := ParseInt(test.in, 10, 0) + if test.out != out || !reflect.DeepEqual(test.err, err) { + t.Errorf("ParseInt(%q, 10, 0) = %v, %v want %v, %v", + test.in, out, err, test.out, test.err) + } + } + } +} + +func TestAtoi(t *testing.T) { + switch IntSize { + case 32: + for i := range parseInt32Tests { + test := &parseInt32Tests[i] + out, err := Atoi(test.in) + if out != int(test.out) || err != test.err { + t.Errorf("Atoi(%q) = %v, %v, want %v, %v", test.in, out, err, test.out, test.err) + } + } + case 64: + for i := range parseInt64Tests { + test := &parseInt64Tests[i] + out, err := Atoi(test.in) + if int64(out) != test.out || err != test.err { + t.Errorf("Atoi(%q) = %v, %v, want %v, %v", test.in, out, err, test.out, test.err) + } + } + } +} + +type parseErrorTest struct { + arg int + err error +} + +var parseBitSizeTests = []parseErrorTest{ + {-1, ErrBitSize}, + {0, nil}, + {64, nil}, + {65, ErrBitSize}, +} + +var parseBaseTests = []parseErrorTest{ + {-1, ErrBase}, + {0, nil}, + {1, ErrBase}, + {2, nil}, + {36, nil}, + {37, ErrBase}, +} + +func equalError(a, b error) bool { + if a == nil { + return b == nil + } + if b == nil { + return a == nil + } + return a.Error() == b.Error() +} + +func TestParseIntBitSize(t *testing.T) { + for i := range parseBitSizeTests { + test := &parseBitSizeTests[i] + _, err := ParseInt("0", 0, test.arg) + if err != test.err { + t.Errorf("ParseInt(\"0\", 0, %v) = 0, %v want 0, %v", + test.arg, err, test.err) + } + } +} + +func TestParseUintBitSize(t *testing.T) { + for i := range parseBitSizeTests { + test := &parseBitSizeTests[i] + _, err := ParseUint("0", 0, test.arg) + if err != test.err { + t.Errorf("ParseUint(\"0\", 0, %v) = 0, %v want 0, %v", + test.arg, err, test.err) + } + } +} + +func TestParseIntBase(t *testing.T) { + for i := range parseBaseTests { + test := &parseBaseTests[i] + _, err := ParseInt("0", test.arg, 0) + if err != test.err { + t.Errorf("ParseInt(\"0\", %v, 0) = 0, %v want 0, %v", + test.arg, err, test.err) + } + } +} + +func TestParseUintBase(t *testing.T) { + for i := range parseBaseTests { + test := &parseBaseTests[i] + _, err := ParseUint("0", test.arg, 0) + if err != test.err { + t.Errorf("ParseUint(\"0\", %v, 0) = 0, %v want 0, %v", + test.arg, err, test.err) + } + } +} + +func BenchmarkParseInt(b *testing.B) { + b.Run("Pos", func(b *testing.B) { + benchmarkParseInt(b, 1) + }) + b.Run("Neg", func(b *testing.B) { + benchmarkParseInt(b, -1) + }) +} + +type benchCase struct { + name string + num int64 +} + +func benchmarkParseInt(b *testing.B, neg int) { + cases := []benchCase{ + {"7bit", 1<<7 - 1}, + {"26bit", 1<<26 - 1}, + {"31bit", 1<<31 - 1}, + {"56bit", 1<<56 - 1}, + {"63bit", 1<<63 - 1}, + } + for _, cs := range cases { + b.Run(cs.name, func(b *testing.B) { + s := fmt.Sprintf("%d", cs.num*int64(neg)) + for i := 0; i < b.N; i++ { + out, _ := ParseInt(s, 10, 64) + BenchSink += int(out) + } + }) + } +} + +func BenchmarkAtoi(b *testing.B) { + b.Run("Pos", func(b *testing.B) { + benchmarkAtoi(b, 1) + }) + b.Run("Neg", func(b *testing.B) { + benchmarkAtoi(b, -1) + }) +} + +func benchmarkAtoi(b *testing.B, neg int) { + cases := []benchCase{ + {"7bit", 1<<7 - 1}, + {"26bit", 1<<26 - 1}, + {"31bit", 1<<31 - 1}, + } + if IntSize == 64 { + cases = append(cases, []benchCase{ + {"56bit", 1<<56 - 1}, + {"63bit", 1<<63 - 1}, + }...) + } + for _, cs := range cases { + b.Run(cs.name, func(b *testing.B) { + s := fmt.Sprintf("%d", cs.num*int64(neg)) + for i := 0; i < b.N; i++ { + out, _ := Atoi(s) + BenchSink += out + } + }) + } +} diff --git a/go/src/internal/strconv/ctoa.go b/go/src/internal/strconv/ctoa.go new file mode 100644 index 0000000000000000000000000000000000000000..89921c856c879b7608ab59548b5fbeb556b2d47e --- /dev/null +++ b/go/src/internal/strconv/ctoa.go @@ -0,0 +1,40 @@ +// 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 strconv + +// FormatComplex converts the complex number c to a string of the +// form (a+bi) where a and b are the real and imaginary parts, +// formatted according to the format fmt and precision prec. +// +// The format fmt and precision prec have the same meaning as in [FormatFloat]. +// It rounds the result assuming that the original was obtained from a complex +// value of bitSize bits, which must be 64 for complex64 and 128 for complex128. +func FormatComplex(c complex128, fmt byte, prec, bitSize int) string { + var buf [64]byte + return string(AppendComplex(buf[:0], c, fmt, prec, bitSize)) +} + +// AppendComplex appends the result of FormatComplex to dst. +// It is here for the runtime. +// There is no public strconv.AppendComplex. +func AppendComplex(dst []byte, c complex128, fmt byte, prec, bitSize int) []byte { + if bitSize != 64 && bitSize != 128 { + panic("invalid bitSize") + } + bitSize >>= 1 // complex64 uses float32 internally + + dst = append(dst, '(') + dst = AppendFloat(dst, real(c), fmt, prec, bitSize) + i := len(dst) + dst = AppendFloat(dst, imag(c), fmt, prec, bitSize) + // Check if imaginary part has a sign. If not, add one. + if dst[i] != '+' && dst[i] != '-' { + dst = append(dst, 0) + copy(dst[i+1:], dst[i:]) + dst[i] = '+' + } + dst = append(dst, "i)"...) + return dst +} diff --git a/go/src/internal/strconv/ctoa_test.go b/go/src/internal/strconv/ctoa_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c24f30272a2c1e0f077dceb0c949d22d579409b8 --- /dev/null +++ b/go/src/internal/strconv/ctoa_test.go @@ -0,0 +1,53 @@ +// 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 strconv_test + +import ( + . "internal/strconv" + "testing" +) + +func TestFormatComplex(t *testing.T) { + tests := []struct { + c complex128 + fmt byte + prec int + bitSize int + out string + }{ + // a variety of signs + {1 + 2i, 'g', -1, 128, "(1+2i)"}, + {3 - 4i, 'g', -1, 128, "(3-4i)"}, + {-5 + 6i, 'g', -1, 128, "(-5+6i)"}, + {-7 - 8i, 'g', -1, 128, "(-7-8i)"}, + + // test that fmt and prec are working + {3.14159 + 0.00123i, 'e', 3, 128, "(3.142e+00+1.230e-03i)"}, + {3.14159 + 0.00123i, 'f', 3, 128, "(3.142+0.001i)"}, + {3.14159 + 0.00123i, 'g', 3, 128, "(3.14+0.00123i)"}, + + // ensure bitSize rounding is working + {1.2345678901234567 + 9.876543210987654i, 'f', -1, 128, "(1.2345678901234567+9.876543210987654i)"}, + {1.2345678901234567 + 9.876543210987654i, 'f', -1, 64, "(1.2345679+9.876543i)"}, + + // other cases are handled by FormatFloat tests + } + for _, test := range tests { + out := FormatComplex(test.c, test.fmt, test.prec, test.bitSize) + if out != test.out { + t.Fatalf("FormatComplex(%v, %q, %d, %d) = %q; want %q", + test.c, test.fmt, test.prec, test.bitSize, out, test.out) + } + } +} + +func TestFormatComplexInvalidBitSize(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic due to invalid bitSize") + } + }() + _ = FormatComplex(1+2i, 'g', -1, 100) +} diff --git a/go/src/internal/strconv/decimal.go b/go/src/internal/strconv/decimal.go new file mode 100644 index 0000000000000000000000000000000000000000..b58001888e8002fb4bad8380d99abe43e37ed02c --- /dev/null +++ b/go/src/internal/strconv/decimal.go @@ -0,0 +1,415 @@ +// 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. + +// Multiprecision decimal numbers. +// For floating-point formatting only; not general purpose. +// Only operations are assign and (binary) left/right shift. +// Can do binary floating point in multiprecision decimal precisely +// because 2 divides 10; cannot do decimal floating point +// in multiprecision binary precisely. + +package strconv + +type decimal struct { + d [800]byte // digits, big-endian representation + nd int // number of digits used + dp int // decimal point + neg bool // negative flag + trunc bool // discarded nonzero digits beyond d[:nd] +} + +func (a *decimal) String() string { + n := 10 + a.nd + if a.dp > 0 { + n += a.dp + } + if a.dp < 0 { + n += -a.dp + } + + buf := make([]byte, n) + w := 0 + switch { + case a.nd == 0: + return "0" + + case a.dp <= 0: + // zeros fill space between decimal point and digits + buf[w] = '0' + w++ + buf[w] = '.' + w++ + w += digitZero(buf[w : w+-a.dp]) + w += copy(buf[w:], a.d[0:a.nd]) + + case a.dp < a.nd: + // decimal point in middle of digits + w += copy(buf[w:], a.d[0:a.dp]) + buf[w] = '.' + w++ + w += copy(buf[w:], a.d[a.dp:a.nd]) + + default: + // zeros fill space between digits and decimal point + w += copy(buf[w:], a.d[0:a.nd]) + w += digitZero(buf[w : w+a.dp-a.nd]) + } + return string(buf[0:w]) +} + +func digitZero(dst []byte) int { + for i := range dst { + dst[i] = '0' + } + return len(dst) +} + +// trim trailing zeros from number. +// (They are meaningless; the decimal point is tracked +// independent of the number of digits.) +func trim(a *decimal) { + for a.nd > 0 && a.d[a.nd-1] == '0' { + a.nd-- + } + if a.nd == 0 { + a.dp = 0 + } +} + +// Assign v to a. +func (a *decimal) Assign(v uint64) { + var buf [24]byte + + // Write reversed decimal in buf. + n := 0 + for v > 0 { + v1 := v / 10 + v -= 10 * v1 + buf[n] = byte(v + '0') + n++ + v = v1 + } + + // Reverse again to produce forward decimal in a.d. + a.nd = 0 + for n--; n >= 0; n-- { + a.d[a.nd] = buf[n] + a.nd++ + } + a.dp = a.nd + trim(a) +} + +// Maximum shift that we can do in one pass without overflow. +// A uint has 32 or 64 bits, and we have to be able to accommodate 9<> 63) +const maxShift = uintSize - 4 + +// Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow. +func rightShift(a *decimal, k uint) { + r := 0 // read pointer + w := 0 // write pointer + + // Pick up enough leading digits to cover first shift. + var n uint + for ; n>>k == 0; r++ { + if r >= a.nd { + if n == 0 { + // a == 0; shouldn't get here, but handle anyway. + a.nd = 0 + return + } + for n>>k == 0 { + n = n * 10 + r++ + } + break + } + c := uint(a.d[r]) + n = n*10 + c - '0' + } + a.dp -= r - 1 + + var mask uint = (1 << k) - 1 + + // Pick up a digit, put down a digit. + for ; r < a.nd; r++ { + c := uint(a.d[r]) + dig := n >> k + n &= mask + a.d[w] = byte(dig + '0') + w++ + n = n*10 + c - '0' + } + + // Put down extra digits. + for n > 0 { + dig := n >> k + n &= mask + if w < len(a.d) { + a.d[w] = byte(dig + '0') + w++ + } else if dig > 0 { + a.trunc = true + } + n = n * 10 + } + + a.nd = w + trim(a) +} + +// Cheat sheet for left shift: table indexed by shift count giving +// number of new digits that will be introduced by that shift. +// +// For example, leftcheats[4] = {2, "625"}. That means that +// if we are shifting by 4 (multiplying by 16), it will add 2 digits +// when the string prefix is "625" through "999", and one fewer digit +// if the string prefix is "000" through "624". +// +// Credit for this trick goes to Ken. + +type leftCheat struct { + delta int // number of new digits + cutoff string // minus one digit if original < a. +} + +var leftcheats = []leftCheat{ + // Leading digits of 1/2^i = 5^i. + // 5^23 is not an exact 64-bit floating point number, + // so have to use bc for the math. + // Go up to 60 to be large enough for 32bit and 64bit platforms. + /* + seq 60 | sed 's/^/5^/' | bc | + awk 'BEGIN{ print "\t{ 0, \"\" }," } + { + log2 = log(2)/log(10) + printf("\t{ %d, \"%s\" },\t// * %d\n", + int(log2*NR+1), $0, 2**NR) + }' + */ + {0, ""}, + {1, "5"}, // * 2 + {1, "25"}, // * 4 + {1, "125"}, // * 8 + {2, "625"}, // * 16 + {2, "3125"}, // * 32 + {2, "15625"}, // * 64 + {3, "78125"}, // * 128 + {3, "390625"}, // * 256 + {3, "1953125"}, // * 512 + {4, "9765625"}, // * 1024 + {4, "48828125"}, // * 2048 + {4, "244140625"}, // * 4096 + {4, "1220703125"}, // * 8192 + {5, "6103515625"}, // * 16384 + {5, "30517578125"}, // * 32768 + {5, "152587890625"}, // * 65536 + {6, "762939453125"}, // * 131072 + {6, "3814697265625"}, // * 262144 + {6, "19073486328125"}, // * 524288 + {7, "95367431640625"}, // * 1048576 + {7, "476837158203125"}, // * 2097152 + {7, "2384185791015625"}, // * 4194304 + {7, "11920928955078125"}, // * 8388608 + {8, "59604644775390625"}, // * 16777216 + {8, "298023223876953125"}, // * 33554432 + {8, "1490116119384765625"}, // * 67108864 + {9, "7450580596923828125"}, // * 134217728 + {9, "37252902984619140625"}, // * 268435456 + {9, "186264514923095703125"}, // * 536870912 + {10, "931322574615478515625"}, // * 1073741824 + {10, "4656612873077392578125"}, // * 2147483648 + {10, "23283064365386962890625"}, // * 4294967296 + {10, "116415321826934814453125"}, // * 8589934592 + {11, "582076609134674072265625"}, // * 17179869184 + {11, "2910383045673370361328125"}, // * 34359738368 + {11, "14551915228366851806640625"}, // * 68719476736 + {12, "72759576141834259033203125"}, // * 137438953472 + {12, "363797880709171295166015625"}, // * 274877906944 + {12, "1818989403545856475830078125"}, // * 549755813888 + {13, "9094947017729282379150390625"}, // * 1099511627776 + {13, "45474735088646411895751953125"}, // * 2199023255552 + {13, "227373675443232059478759765625"}, // * 4398046511104 + {13, "1136868377216160297393798828125"}, // * 8796093022208 + {14, "5684341886080801486968994140625"}, // * 17592186044416 + {14, "28421709430404007434844970703125"}, // * 35184372088832 + {14, "142108547152020037174224853515625"}, // * 70368744177664 + {15, "710542735760100185871124267578125"}, // * 140737488355328 + {15, "3552713678800500929355621337890625"}, // * 281474976710656 + {15, "17763568394002504646778106689453125"}, // * 562949953421312 + {16, "88817841970012523233890533447265625"}, // * 1125899906842624 + {16, "444089209850062616169452667236328125"}, // * 2251799813685248 + {16, "2220446049250313080847263336181640625"}, // * 4503599627370496 + {16, "11102230246251565404236316680908203125"}, // * 9007199254740992 + {17, "55511151231257827021181583404541015625"}, // * 18014398509481984 + {17, "277555756156289135105907917022705078125"}, // * 36028797018963968 + {17, "1387778780781445675529539585113525390625"}, // * 72057594037927936 + {18, "6938893903907228377647697925567626953125"}, // * 144115188075855872 + {18, "34694469519536141888238489627838134765625"}, // * 288230376151711744 + {18, "173472347597680709441192448139190673828125"}, // * 576460752303423488 + {19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976 +} + +// Is the leading prefix of b lexicographically less than s? +func prefixIsLessThan(b []byte, s string) bool { + for i := 0; i < len(s); i++ { + if i >= len(b) { + return true + } + if b[i] != s[i] { + return b[i] < s[i] + } + } + return false +} + +// Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow. +func leftShift(a *decimal, k uint) { + delta := leftcheats[k].delta + if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) { + delta-- + } + + r := a.nd // read index + w := a.nd + delta // write index + + // Pick up a digit, put down a digit. + var n uint + for r--; r >= 0; r-- { + n += (uint(a.d[r]) - '0') << k + quo := n / 10 + rem := n - 10*quo + w-- + if w < len(a.d) { + a.d[w] = byte(rem + '0') + } else if rem != 0 { + a.trunc = true + } + n = quo + } + + // Put down extra digits. + for n > 0 { + quo := n / 10 + rem := n - 10*quo + w-- + if w < len(a.d) { + a.d[w] = byte(rem + '0') + } else if rem != 0 { + a.trunc = true + } + n = quo + } + + a.nd += delta + if a.nd >= len(a.d) { + a.nd = len(a.d) + } + a.dp += delta + trim(a) +} + +// Binary shift left (k > 0) or right (k < 0). +func (a *decimal) Shift(k int) { + switch { + case a.nd == 0: + // nothing to do: a == 0 + case k > 0: + for k > maxShift { + leftShift(a, maxShift) + k -= maxShift + } + leftShift(a, uint(k)) + case k < 0: + for k < -maxShift { + rightShift(a, maxShift) + k += maxShift + } + rightShift(a, uint(-k)) + } +} + +// If we chop a at nd digits, should we round up? +func shouldRoundUp(a *decimal, nd int) bool { + if nd < 0 || nd >= a.nd { + return false + } + if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even + // if we truncated, a little higher than what's recorded - always round up + if a.trunc { + return true + } + return nd > 0 && (a.d[nd-1]-'0')%2 != 0 + } + // not halfway - digit tells all + return a.d[nd] >= '5' +} + +// Round a to nd digits (or fewer). +// If nd is zero, it means we're rounding +// just to the left of the digits, as in +// 0.09 -> 0.1. +func (a *decimal) Round(nd int) { + if nd < 0 || nd >= a.nd { + return + } + if shouldRoundUp(a, nd) { + a.RoundUp(nd) + } else { + a.RoundDown(nd) + } +} + +// Round a down to nd digits (or fewer). +func (a *decimal) RoundDown(nd int) { + if nd < 0 || nd >= a.nd { + return + } + a.nd = nd + trim(a) +} + +// Round a up to nd digits (or fewer). +func (a *decimal) RoundUp(nd int) { + if nd < 0 || nd >= a.nd { + return + } + + // round up + for i := nd - 1; i >= 0; i-- { + c := a.d[i] + if c < '9' { // can stop after this digit + a.d[i]++ + a.nd = i + 1 + return + } + } + + // Number is all 9s. + // Change to single 1 with adjusted decimal point. + a.d[0] = '1' + a.nd = 1 + a.dp++ +} + +// Extract integer part, rounded appropriately. +// No guarantees about overflow. +func (a *decimal) RoundedInteger() uint64 { + if a.dp > 20 { + return 0xFFFFFFFFFFFFFFFF + } + var i int + n := uint64(0) + for i = 0; i < a.dp && i < a.nd; i++ { + n = n*10 + uint64(a.d[i]-'0') + } + for ; i < a.dp; i++ { + n *= 10 + } + if shouldRoundUp(a, a.dp) { + n++ + } + return n +} diff --git a/go/src/internal/strconv/decimal_test.go b/go/src/internal/strconv/decimal_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a60096e1c8e5b91c7b2535fcf22694d403c3d0c5 --- /dev/null +++ b/go/src/internal/strconv/decimal_test.go @@ -0,0 +1,127 @@ +// 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 strconv_test + +import ( + . "internal/strconv" + "testing" +) + +type shiftTest struct { + i uint64 + shift int + out string +} + +var shifttests = []shiftTest{ + {0, -100, "0"}, + {0, 100, "0"}, + {1, 100, "1267650600228229401496703205376"}, + {1, -100, + "0.00000000000000000000000000000078886090522101180541" + + "17285652827862296732064351090230047702789306640625", + }, + {12345678, 8, "3160493568"}, + {12345678, -8, "48225.3046875"}, + {195312, 9, "99999744"}, + {1953125, 9, "1000000000"}, +} + +func TestDecimalShift(t *testing.T) { + for i := 0; i < len(shifttests); i++ { + test := &shifttests[i] + d := NewDecimal(test.i) + d.Shift(test.shift) + s := d.String() + if s != test.out { + t.Errorf("Decimal %v << %v = %v, want %v", + test.i, test.shift, s, test.out) + } + } +} + +type roundTest struct { + i uint64 + nd int + down, round, up string + int uint64 +} + +var roundtests = []roundTest{ + {0, 4, "0", "0", "0", 0}, + {12344999, 4, "12340000", "12340000", "12350000", 12340000}, + {12345000, 4, "12340000", "12340000", "12350000", 12340000}, + {12345001, 4, "12340000", "12350000", "12350000", 12350000}, + {23454999, 4, "23450000", "23450000", "23460000", 23450000}, + {23455000, 4, "23450000", "23460000", "23460000", 23460000}, + {23455001, 4, "23450000", "23460000", "23460000", 23460000}, + + {99994999, 4, "99990000", "99990000", "100000000", 99990000}, + {99995000, 4, "99990000", "100000000", "100000000", 100000000}, + {99999999, 4, "99990000", "100000000", "100000000", 100000000}, + + {12994999, 4, "12990000", "12990000", "13000000", 12990000}, + {12995000, 4, "12990000", "13000000", "13000000", 13000000}, + {12999999, 4, "12990000", "13000000", "13000000", 13000000}, +} + +func TestDecimalRound(t *testing.T) { + for i := 0; i < len(roundtests); i++ { + test := &roundtests[i] + d := NewDecimal(test.i) + d.RoundDown(test.nd) + s := d.String() + if s != test.down { + t.Errorf("Decimal %v RoundDown %d = %v, want %v", + test.i, test.nd, s, test.down) + } + d = NewDecimal(test.i) + d.Round(test.nd) + s = d.String() + if s != test.round { + t.Errorf("Decimal %v Round %d = %v, want %v", + test.i, test.nd, s, test.down) + } + d = NewDecimal(test.i) + d.RoundUp(test.nd) + s = d.String() + if s != test.up { + t.Errorf("Decimal %v RoundUp %d = %v, want %v", + test.i, test.nd, s, test.up) + } + } +} + +type roundIntTest struct { + i uint64 + shift int + int uint64 +} + +var roundinttests = []roundIntTest{ + {0, 100, 0}, + {512, -8, 2}, + {513, -8, 2}, + {640, -8, 2}, + {641, -8, 3}, + {384, -8, 2}, + {385, -8, 2}, + {383, -8, 1}, + {1, 100, 1<<64 - 1}, + {1000, 0, 1000}, +} + +func TestDecimalRoundedInteger(t *testing.T) { + for i := 0; i < len(roundinttests); i++ { + test := roundinttests[i] + d := NewDecimal(test.i) + d.Shift(test.shift) + int := d.RoundedInteger() + if int != test.int { + t.Errorf("Decimal %v >> %v RoundedInteger = %v, want %v", + test.i, test.shift, int, test.int) + } + } +} diff --git a/go/src/internal/strconv/deps.go b/go/src/internal/strconv/deps.go new file mode 100644 index 0000000000000000000000000000000000000000..04331130c2174f0d0fec861f213d640b4da7cd0e --- /dev/null +++ b/go/src/internal/strconv/deps.go @@ -0,0 +1,30 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv + +import "unsafe" + +// Implementations to avoid importing other dependencies. + +// package math + +func float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) } +func float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) } +func float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) } +func float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) } + +func inf(sign int) float64 { + var v uint64 + if sign >= 0 { + v = 0x7FF0000000000000 + } else { + v = 0xFFF0000000000000 + } + return float64frombits(v) +} + +func isNaN(f float64) (is bool) { return f != f } + +func nan() float64 { return float64frombits(0x7FF8000000000001) } diff --git a/go/src/internal/strconv/export_test.go b/go/src/internal/strconv/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c879f24480a450bb8d78ee729fcaebf81ce775da --- /dev/null +++ b/go/src/internal/strconv/export_test.go @@ -0,0 +1,36 @@ +// 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 strconv + +type Uint128 = uint128 + +const ( + Pow10Min = pow10Min + Pow10Max = pow10Max +) + +var ( + MulLog10_2 = mulLog10_2 + MulLog2_10 = mulLog2_10 + ParseFloatPrefix = parseFloatPrefix + Pow10 = pow10 + Umul128 = umul128 + Umul192 = umul192 + Div5Tab = div5Tab + DivisiblePow5 = divisiblePow5 + TrimZeros = trimZeros +) + +func NewDecimal(i uint64) *decimal { + d := new(decimal) + d.Assign(i) + return d +} + +func SetOptimize(b bool) bool { + old := optimize + optimize = b + return old +} diff --git a/go/src/internal/strconv/fp_test.go b/go/src/internal/strconv/fp_test.go new file mode 100644 index 0000000000000000000000000000000000000000..92a663c6e331b47f2990e9bb17a58758d9c1d383 --- /dev/null +++ b/go/src/internal/strconv/fp_test.go @@ -0,0 +1,263 @@ +// 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 strconv_test + +import ( + _ "embed" + "flag" + "fmt" + . "internal/strconv" + "io" + "net/http" + "os" + "strings" + "testing" +) + +func pow2(i int) float64 { + switch { + case i < 0: + return 1 / pow2(-i) + case i == 0: + return 1 + case i == 1: + return 2 + } + return pow2(i/2) * pow2(i-i/2) +} + +// Wrapper around ParseFloat(x, 64). Handles dddddp+ddd (binary exponent) +// itself, passes the rest on to ParseFloat. +func myatof64(s string) (f float64, ok bool) { + if mant, exp, ok := strings.Cut(s, "p"); ok { + n, err := ParseInt(mant, 10, 64) + if err != nil { + return 0, false + } + e, err1 := Atoi(exp) + if err1 != nil { + println("bad e", exp) + return 0, false + } + v := float64(n) + // We expect that v*pow2(e) fits in a float64, + // but pow2(e) by itself may not. Be careful. + if e <= -1000 { + v *= pow2(-1000) + e += 1000 + for e < 0 { + v /= 2 + e++ + } + return v, true + } + if e >= 1000 { + v *= pow2(1000) + e -= 1000 + for e > 0 { + v *= 2 + e-- + } + return v, true + } + return v * pow2(e), true + } + f1, err := ParseFloat(s, 64) + if err != nil { + return 0, false + } + return f1, true +} + +// Wrapper around strconv.ParseFloat(x, 32). Handles dddddp+ddd (binary exponent) +// itself, passes the rest on to strconv.ParseFloat. +func myatof32(s string) (f float32, ok bool) { + if mant, exp, ok := strings.Cut(s, "p"); ok { + n, err := Atoi(mant) + if err != nil { + println("bad n", mant) + return 0, false + } + e, err1 := Atoi(exp) + if err1 != nil { + println("bad p", exp) + return 0, false + } + return float32(float64(n) * pow2(e)), true + } + f64, err1 := ParseFloat(s, 32) + f1 := float32(f64) + if err1 != nil { + return 0, false + } + return f1, true +} + +//go:embed testdata/testfp.txt +var testfp string + +func TestFp(t *testing.T) { + lineno := 0 + for line := range strings.Lines(testfp) { + lineno++ + line, _, _ = strings.Cut(line, "#") + line = strings.TrimSpace(line) + if line == "" { + continue + } + a := strings.Split(line, " ") + if len(a) != 4 { + t.Errorf("testdata/testfp.txt:%d: wrong field count", lineno) + continue + } + var s string + var v float64 + switch a[0] { + case "float64": + var ok bool + v, ok = myatof64(a[2]) + if !ok { + t.Errorf("testdata/testfp.txt:%d: cannot atof64 %s", lineno, a[2]) + continue + } + s = fmt.Sprintf(a[1], v) + case "float32": + v1, ok := myatof32(a[2]) + if !ok { + t.Errorf("testdata/testfp.txt:%d: cannot atof32 %s", lineno, a[2]) + continue + } + s = fmt.Sprintf(a[1], v1) + v = float64(v1) + } + if s != a[3] { + t.Errorf("testdata/testfp.txt:%d: %s %s %s %s: have %s want %s", lineno, a[0], a[1], a[2], a[3], s, a[3]) + } + } +} + +// The -testbase flag runs the full testbase input set instead of the +// random sample in testdata/*1k.txt. See testdata/README for details. +var testbase = flag.Bool("testbase", false, "download and test full testbase testdata") + +// testbaseURL is the URL for downloading the full testbase testdata. +// There is also a copy on "https://swtch.com/testbase/". +var testbaseURL = "https://gist.githubusercontent.com/rsc/606b378b0bf95c24a6fd6cef99e262e1/raw/128a03890e536bdf403e6cc768b0737405c6734d/" + +//go:embed testdata/atof1k.txt +var atof1ktxt string + +//go:embed testdata/ftoa1k.txt +var ftoa1ktxt string + +// openTestbase opens the named testbase data file. +// By default it opens testdata/name1k.txt, +// but if the -testbase flag has been set, +// then it opens the full testdata/name.txt, +// downloading that file if necessary. +func openTestbase(t *testing.T, name string) (file, data string) { + if !*testbase { + switch name { + case "atof": + return "testdata/atof1k.txt", atof1ktxt + case "ftoa": + return "testdata/ftoa1k.txt", ftoa1ktxt + } + t.Fatalf("unknown file %s", name) + } + + // Use cached copy if present. + file = "testdata/" + name + ".txt" + if data, err := os.ReadFile(file); err == nil { + return file, string(data) + } + + // Download copy. + url := testbaseURL + name + ".txt" + resp, err := http.Get(url) + if err != nil { + t.Fatalf("%s: %s", url, err) + } + if resp.StatusCode != 200 { + t.Fatalf("%s: %s", url, resp.Status) + } + bytes, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + t.Fatalf("%s: %s", url, err) + } + if err := os.WriteFile(file, bytes, 0666); err != nil { + t.Fatal(err) + } + return file, string(bytes) +} + +func TestParseFloatTestdata(t *testing.T) { + // Test testbase inputs, optimized against not. + name, data := openTestbase(t, "atof") + fail := 0 + lineno := 0 + for line := range strings.Lines(data) { + lineno++ + s := strings.TrimSpace(line) + if strings.HasPrefix(s, "#") || s == "" { + continue + } + SetOptimize(false) + want, err1 := ParseFloat(s, 64) + SetOptimize(true) + have, err2 := ParseFloat(s, 64) + if err1 != nil { + // Error in test data; should not happen. + t.Errorf("%s:%d: ParseFloat(%#q): %v", name, lineno, s, err1) + continue + } + if err2 != nil { + t.Errorf("ParseFloat(%#q): %v", s, err2) + if fail++; fail > 100 { + t.Fatalf("too many failures") + } + continue + } + if have != want { + t.Errorf("ParseFloat(%#q) = %#x, want %#x", s, have, want) + if fail++; fail > 100 { + t.Fatalf("too many failures") + } + } + } +} + +func TestFormatFloatTestdata(t *testing.T) { + // Test testbase inputs, optimized against not. + name, data := openTestbase(t, "ftoa") + fail := 0 + lineno := 0 + for line := range strings.Lines(data) { + lineno++ + s := strings.TrimSpace(line) + if strings.HasPrefix(s, "#") || s == "" { + continue + } + f, err := ParseFloat(s, 64) + if err != nil { + // Error in test data; should not happen. + t.Errorf("%s:%d: ParseFloat(%#q): %v", name, lineno, s, err) + continue + } + for i := range 19 { + SetOptimize(false) + want := FormatFloat(f, 'e', i, 64) + SetOptimize(true) + have := FormatFloat(f, 'e', i, 64) + if have != want { + t.Errorf("FormatFloat(%#x, 'e', %d) = %s, want %s", f, i, have, want) + if fail++; fail > 100 { + t.Fatalf("too many failures") + } + } + } + } +} diff --git a/go/src/internal/strconv/ftoa.go b/go/src/internal/strconv/ftoa.go new file mode 100644 index 0000000000000000000000000000000000000000..c8c98c138040b73fbf68cc3cf04eb4fdfa3a75ee --- /dev/null +++ b/go/src/internal/strconv/ftoa.go @@ -0,0 +1,596 @@ +// 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. + +// Binary to decimal floating point conversion. +// Algorithm: +// 1) store mantissa in multiprecision decimal +// 2) shift decimal by exponent +// 3) read digits out & format + +package strconv + +const ( + lowerhex = "0123456789abcdef" + upperhex = "0123456789ABCDEF" +) + +type floatInfo struct { + mantbits uint + expbits uint + bias int +} + +const ( + float32MantBits = 23 + float32ExpBits = 8 + float32Bias = -127 + float64MantBits = 52 + float64ExpBits = 11 + float64Bias = -1023 +) + +var ( + float32info = floatInfo{float32MantBits, float32ExpBits, float32Bias} + float64info = floatInfo{float64MantBits, float64ExpBits, float64Bias} +) + +// FormatFloat converts the floating-point number f to a string, +// according to the format fmt and precision prec. It rounds the +// result assuming that the original was obtained from a floating-point +// value of bitSize bits (32 for float32, 64 for float64). +// +// The format fmt is one of +// - 'b' (-ddddp±ddd, a binary exponent), +// - 'e' (-d.dddde±dd, a decimal exponent), +// - 'E' (-d.ddddE±dd, a decimal exponent), +// - 'f' (-ddd.dddd, no exponent), +// - 'g' ('e' for large exponents, 'f' otherwise), +// - 'G' ('E' for large exponents, 'f' otherwise), +// - 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or +// - 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent). +// +// The precision prec controls the number of digits (excluding the exponent) +// printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats. +// For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point. +// For 'g' and 'G' it is the maximum number of significant digits (trailing +// zeros are removed). +// The special precision -1 uses the smallest number of digits +// necessary such that ParseFloat will return f exactly. +// The exponent is written as a decimal integer; +// for all formats other than 'b', it will be at least two digits. +func FormatFloat(f float64, fmt byte, prec, bitSize int) string { + return string(genericFtoa(make([]byte, 0, max(prec+4, 24)), f, fmt, prec, bitSize)) +} + +// AppendFloat appends the string form of the floating-point number f, +// as generated by [FormatFloat], to dst and returns the extended buffer. +func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte { + return genericFtoa(dst, f, fmt, prec, bitSize) +} + +func genericFtoa(dst []byte, val float64, fmt byte, prec, bitSize int) []byte { + var bits uint64 + var flt *floatInfo + switch bitSize { + case 32: + bits = uint64(float32bits(float32(val))) + flt = &float32info + case 64: + bits = float64bits(val) + flt = &float64info + default: + panic("strconv: illegal AppendFloat/FormatFloat bitSize") + } + + neg := bits>>(flt.expbits+flt.mantbits) != 0 + exp := int(bits>>flt.mantbits) & (1<= 0 { + digits = 1 + mulLog10_2(1+exp) + prec + } else { + digits = 1 + prec - mulLog10_2(-exp) + } + case 'e', 'E': + digits++ + case 'g', 'G': + if prec == 0 { + prec = 1 + } + digits = prec + default: + // Invalid mode. + digits = 1 + } + if digits <= 18 { + // digits <= 0 happens for %f on very small numbers + // and means that we're guaranteed to print all zeros. + if digits > 0 { + var buf [24]byte + digs.d = buf[:] + fixedFtoa(&digs, mant, exp-int(flt.mantbits), digits, prec, fmt) + } + return formatDigits(dst, false, neg, digs, prec, fmt) + } + + return bigFtoa(dst, prec, fmt, neg, mant, exp, flt) +} + +// bigFtoa uses multiprecision computations to format a float. +func bigFtoa(dst []byte, prec int, fmt byte, neg bool, mant uint64, exp int, flt *floatInfo) []byte { + d := new(decimal) + d.Assign(mant) + d.Shift(exp - int(flt.mantbits)) + var digs decimalSlice + shortest := prec < 0 + if shortest { + roundShortest(d, mant, exp, flt) + digs = decimalSlice{d: d.d[:], nd: d.nd, dp: d.dp} + // Precision for shortest representation mode. + switch fmt { + case 'e', 'E': + prec = digs.nd - 1 + case 'f': + prec = max(digs.nd-digs.dp, 0) + case 'g', 'G': + prec = digs.nd + } + } else { + // Round appropriately. + switch fmt { + case 'e', 'E': + d.Round(prec + 1) + case 'f': + d.Round(d.dp + prec) + case 'g', 'G': + if prec == 0 { + prec = 1 + } + d.Round(prec) + } + digs = decimalSlice{d: d.d[:], nd: d.nd, dp: d.dp} + } + return formatDigits(dst, shortest, neg, digs, prec, fmt) +} + +func formatDigits(dst []byte, shortest bool, neg bool, digs decimalSlice, prec int, fmt byte) []byte { + switch fmt { + case 'e', 'E': + return fmtE(dst, neg, digs, prec, fmt) + case 'f': + return fmtF(dst, neg, digs, prec) + case 'g', 'G': + // trailing fractional zeros in 'e' form will be trimmed. + eprec := prec + if eprec > digs.nd && digs.nd >= digs.dp { + eprec = digs.nd + } + // %e is used if the exponent from the conversion + // is less than -4 or greater than or equal to the precision. + // if precision was the shortest possible, use precision 6 for this decision. + if shortest { + eprec = 6 + } + exp := digs.dp - 1 + if exp < -4 || exp >= eprec { + if prec > digs.nd { + prec = digs.nd + } + return fmtE(dst, neg, digs, prec-1, fmt+'e'-'g') + } + if prec > digs.dp { + prec = digs.nd + } + return fmtF(dst, neg, digs, max(prec-digs.dp, 0)) + } + + // unknown format + return append(dst, '%', fmt) +} + +// roundShortest rounds d (= mant * 2^exp) to the shortest number of digits +// that will let the original floating point value be precisely reconstructed. +func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) { + // If mantissa is zero, the number is zero; stop now. + if mant == 0 { + d.nd = 0 + return + } + + // Compute upper and lower such that any decimal number + // between upper and lower (possibly inclusive) + // will round to the original floating point number. + + // We may see at once that the number is already shortest. + // + // Suppose d is not denormal, so that 2^exp <= d < 10^dp. + // The closest shorter number is at least 10^(dp-nd) away. + // The lower/upper bounds computed below are at distance + // at most 2^(exp-mantbits). + // + // So the number is already shortest if 10^(dp-nd) > 2^(exp-mantbits), + // or equivalently log2(10)*(dp-nd) > exp-mantbits. + // It is true if 332/100*(dp-nd) >= exp-mantbits (log2(10) > 3.32). + minexp := flt.bias + 1 // minimum possible exponent + if exp > minexp && 332*(d.dp-d.nd) >= 100*(exp-int(flt.mantbits)) { + // The number is already shortest. + return + } + + // d = mant << (exp - mantbits) + // Next highest floating point number is mant+1 << exp-mantbits. + // Our upper bound is halfway between, mant*2+1 << exp-mantbits-1. + upper := new(decimal) + upper.Assign(mant*2 + 1) + upper.Shift(exp - int(flt.mantbits) - 1) + + // d = mant << (exp - mantbits) + // Next lowest floating point number is mant-1 << exp-mantbits, + // unless mant-1 drops the significant bit and exp is not the minimum exp, + // in which case the next lowest is mant*2-1 << exp-mantbits-1. + // Either way, call it mantlo << explo-mantbits. + // Our lower bound is halfway between, mantlo*2+1 << explo-mantbits-1. + var mantlo uint64 + var explo int + if mant > 1<= d.nd { + break + } + li := ui - upper.dp + lower.dp + l := byte('0') // lower digit + if li >= 0 && li < lower.nd { + l = lower.d[li] + } + m := byte('0') // middle digit + if mi >= 0 { + m = d.d[mi] + } + u := byte('0') // upper digit + if ui < upper.nd { + u = upper.d[ui] + } + + // Okay to round down (truncate) if lower has a different digit + // or if lower is inclusive and is exactly the result of rounding + // down (i.e., and we have reached the final digit of lower). + okdown := l != m || inclusive && li+1 == lower.nd + + switch { + case upperdelta == 0 && m+1 < u: + // Example: + // m = 12345xxx + // u = 12347xxx + upperdelta = 2 + case upperdelta == 0 && m != u: + // Example: + // m = 12345xxx + // u = 12346xxx + upperdelta = 1 + case upperdelta == 1 && (m != '9' || u != '0'): + // Example: + // m = 1234598x + // u = 1234600x + upperdelta = 2 + } + // Okay to round up if upper has a different digit and either upper + // is inclusive or upper is bigger than the result of rounding up. + okup := upperdelta > 0 && (inclusive || upperdelta > 1 || ui+1 < upper.nd) + + // If it's okay to do either, then round to the nearest one. + // If it's okay to do only one, do it. + switch { + case okdown && okup: + d.Round(mi + 1) + return + case okdown: + d.RoundDown(mi + 1) + return + case okup: + d.RoundUp(mi + 1) + return + } + } +} + +type decimalSlice struct { + d []byte + nd, dp int +} + +// %e: -d.ddddde±dd +func fmtE(dst []byte, neg bool, d decimalSlice, prec int, fmt byte) []byte { + // sign + if neg { + dst = append(dst, '-') + } + + // first digit + ch := byte('0') + if d.nd != 0 { + ch = d.d[0] + } + dst = append(dst, ch) + + // .moredigits + if prec > 0 { + dst = append(dst, '.') + i := 1 + m := min(d.nd, prec+1) + if i < m { + dst = append(dst, d.d[i:m]...) + i = m + } + for ; i <= prec; i++ { + dst = append(dst, '0') + } + } + + // e± + dst = append(dst, fmt) + exp := d.dp - 1 + if d.nd == 0 { // special case: 0 has exponent 0 + exp = 0 + } + if exp < 0 { + ch = '-' + exp = -exp + } else { + ch = '+' + } + dst = append(dst, ch) + + // dd or ddd + switch { + case exp < 10: + dst = append(dst, '0', byte(exp)+'0') + case exp < 100: + dst = append(dst, byte(exp/10)+'0', byte(exp%10)+'0') + default: + dst = append(dst, byte(exp/100)+'0', byte(exp/10)%10+'0', byte(exp%10)+'0') + } + + return dst +} + +// %f: -ddddddd.ddddd +func fmtF(dst []byte, neg bool, d decimalSlice, prec int) []byte { + // sign + if neg { + dst = append(dst, '-') + } + + // integer, padded with zeros as needed. + if d.dp > 0 { + m := min(d.nd, d.dp) + dst = append(dst, d.d[:m]...) + for ; m < d.dp; m++ { + dst = append(dst, '0') + } + } else { + dst = append(dst, '0') + } + + // fraction + if prec > 0 { + dst = append(dst, '.') + for i := 0; i < prec; i++ { + ch := byte('0') + if j := d.dp + i; 0 <= j && j < d.nd { + ch = d.d[j] + } + dst = append(dst, ch) + } + } + + return dst +} + +// %b: -ddddddddp±ddd +func fmtB(dst []byte, neg bool, mant uint64, exp int, flt *floatInfo) []byte { + // sign + if neg { + dst = append(dst, '-') + } + + // mantissa + dst = AppendUint(dst, mant, 10) + + // p + dst = append(dst, 'p') + + // ±exponent + exp -= int(flt.mantbits) + if exp >= 0 { + dst = append(dst, '+') + } + dst = AppendInt(dst, int64(exp), 10) + + return dst +} + +// %x: -0x1.yyyyyyyyp±ddd or -0x0p+0. (y is hex digit, d is decimal digit) +func fmtX(dst []byte, prec int, fmt byte, neg bool, mant uint64, exp int, flt *floatInfo) []byte { + if mant == 0 { + exp = 0 + } + + // Shift digits so leading 1 (if any) is at bit 1<<60. + mant <<= 60 - flt.mantbits + for mant != 0 && mant&(1<<60) == 0 { + mant <<= 1 + exp-- + } + + // Round if requested. + if prec >= 0 && prec < 15 { + shift := uint(prec * 4) + extra := (mant << shift) & (1<<60 - 1) + mant >>= 60 - shift + if extra|(mant&1) > 1<<59 { + mant++ + } + mant <<= 60 - shift + if mant&(1<<61) != 0 { + // Wrapped around. + mant >>= 1 + exp++ + } + } + + hex := lowerhex + if fmt == 'X' { + hex = upperhex + } + + // sign, 0x, leading digit + if neg { + dst = append(dst, '-') + } + dst = append(dst, '0', fmt, '0'+byte((mant>>60)&1)) + + // .fraction + mant <<= 4 // remove leading 0 or 1 + if prec < 0 && mant != 0 { + dst = append(dst, '.') + for mant != 0 { + dst = append(dst, hex[(mant>>60)&15]) + mant <<= 4 + } + } else if prec > 0 { + dst = append(dst, '.') + for i := 0; i < prec; i++ { + dst = append(dst, hex[(mant>>60)&15]) + mant <<= 4 + } + } + + // p± + ch := byte('P') + if fmt == lower(fmt) { + ch = 'p' + } + dst = append(dst, ch) + if exp < 0 { + ch = '-' + exp = -exp + } else { + ch = '+' + } + dst = append(dst, ch) + + // dd or ddd or dddd + switch { + case exp < 100: + dst = append(dst, byte(exp/10)+'0', byte(exp%10)+'0') + case exp < 1000: + dst = append(dst, byte(exp/100)+'0', byte((exp/10)%10)+'0', byte(exp%10)+'0') + default: + dst = append(dst, byte(exp/1000)+'0', byte(exp/100)%10+'0', byte((exp/10)%10)+'0', byte(exp%10)+'0') + } + + return dst +} diff --git a/go/src/internal/strconv/ftoa_test.go b/go/src/internal/strconv/ftoa_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d5179a1bbd83d4cddc10a545968fa52493393444 --- /dev/null +++ b/go/src/internal/strconv/ftoa_test.go @@ -0,0 +1,386 @@ +// 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 strconv_test + +import ( + . "internal/strconv" + "math" + "math/rand" + "testing" +) + +type ftoaTest struct { + f float64 + fmt byte + prec int + s string +} + +func fdiv(a, b float64) float64 { return a / b } + +const ( + below1e23 = 99999999999999974834176 + above1e23 = 100000000000000008388608 +) + +var ftoatests = []ftoaTest{ + {1, 'e', 5, "1.00000e+00"}, + {1, 'f', 5, "1.00000"}, + {1, 'g', 5, "1"}, + {1, 'g', -1, "1"}, + {1, 'x', -1, "0x1p+00"}, + {1, 'x', 5, "0x1.00000p+00"}, + {20, 'g', -1, "20"}, + {20, 'x', -1, "0x1.4p+04"}, + {1234567.8, 'g', -1, "1.2345678e+06"}, + {1234567.8, 'x', -1, "0x1.2d687cccccccdp+20"}, + {200000, 'g', -1, "200000"}, + {200000, 'x', -1, "0x1.86ap+17"}, + {200000, 'X', -1, "0X1.86AP+17"}, + {2000000, 'g', -1, "2e+06"}, + {1e10, 'g', -1, "1e+10"}, + + // f conversion basic cases + {12345, 'f', 2, "12345.00"}, + {1234.5, 'f', 2, "1234.50"}, + {123.45, 'f', 2, "123.45"}, + {12.345, 'f', 2, "12.35"}, + {1.2345, 'f', 2, "1.23"}, + {0.12345, 'f', 2, "0.12"}, + {0.12945, 'f', 2, "0.13"}, + {0.012345, 'f', 2, "0.01"}, + {0.015, 'f', 2, "0.01"}, + {0.016, 'f', 2, "0.02"}, + {0.0052345, 'f', 2, "0.01"}, + {0.0012345, 'f', 2, "0.00"}, + {0.00012345, 'f', 2, "0.00"}, + {0.000012345, 'f', 2, "0.00"}, + + {0.996644984, 'f', 6, "0.996645"}, + {0.996644984, 'f', 5, "0.99664"}, + {0.996644984, 'f', 4, "0.9966"}, + {0.996644984, 'f', 3, "0.997"}, + {0.996644984, 'f', 2, "1.00"}, + {0.996644984, 'f', 1, "1.0"}, + + // g conversion and zero suppression + {400, 'g', 2, "4e+02"}, + {40, 'g', 2, "40"}, + {4, 'g', 2, "4"}, + {.4, 'g', 2, "0.4"}, + {.04, 'g', 2, "0.04"}, + {.004, 'g', 2, "0.004"}, + {.0004, 'g', 2, "0.0004"}, + {.00004, 'g', 2, "4e-05"}, + {.000004, 'g', 2, "4e-06"}, + + {0, 'e', 5, "0.00000e+00"}, + {0, 'f', 5, "0.00000"}, + {0, 'g', 5, "0"}, + {0, 'g', -1, "0"}, + {0, 'x', 5, "0x0.00000p+00"}, + + {-1, 'e', 5, "-1.00000e+00"}, + {-1, 'f', 5, "-1.00000"}, + {-1, 'g', 5, "-1"}, + {-1, 'g', -1, "-1"}, + + {12, 'e', 5, "1.20000e+01"}, + {12, 'f', 5, "12.00000"}, + {12, 'g', 5, "12"}, + {12, 'g', -1, "12"}, + + {123456700, 'e', 5, "1.23457e+08"}, + {123456700, 'f', 5, "123456700.00000"}, + {123456700, 'g', 5, "1.2346e+08"}, + {123456700, 'g', -1, "1.234567e+08"}, + + {1.2345e6, 'e', 5, "1.23450e+06"}, + {1.2345e6, 'f', 5, "1234500.00000"}, + {1.2345e6, 'g', 5, "1.2345e+06"}, + + // Round to even + {1.2345e6, 'e', 3, "1.234e+06"}, + {1.2355e6, 'e', 3, "1.236e+06"}, + {1.2345, 'f', 3, "1.234"}, + {1.2355, 'f', 3, "1.236"}, + {1234567890123456.5, 'e', 15, "1.234567890123456e+15"}, + {1234567890123457.5, 'e', 15, "1.234567890123458e+15"}, + {108678236358137.625, 'g', -1, "1.0867823635813762e+14"}, + + {1e23, 'e', 17, "9.99999999999999916e+22"}, + {1e23, 'f', 17, "99999999999999991611392.00000000000000000"}, + {1e23, 'g', 17, "9.9999999999999992e+22"}, + + {1e23, 'e', -1, "1e+23"}, + {1e23, 'f', -1, "100000000000000000000000"}, + {1e23, 'g', -1, "1e+23"}, + + {below1e23, 'e', 17, "9.99999999999999748e+22"}, + {below1e23, 'f', 17, "99999999999999974834176.00000000000000000"}, + {below1e23, 'g', 17, "9.9999999999999975e+22"}, + + {below1e23, 'e', -1, "9.999999999999997e+22"}, + {below1e23, 'f', -1, "99999999999999970000000"}, + {below1e23, 'g', -1, "9.999999999999997e+22"}, + + {above1e23, 'e', 17, "1.00000000000000008e+23"}, + {above1e23, 'f', 17, "100000000000000008388608.00000000000000000"}, + {above1e23, 'g', 17, "1.0000000000000001e+23"}, + + {above1e23, 'e', -1, "1.0000000000000001e+23"}, + {above1e23, 'f', -1, "100000000000000010000000"}, + {above1e23, 'g', -1, "1.0000000000000001e+23"}, + + {fdiv(5e-304, 1e20), 'g', -1, "5e-324"}, // avoid constant arithmetic + {fdiv(-5e-304, 1e20), 'g', -1, "-5e-324"}, // avoid constant arithmetic + + {32, 'g', -1, "32"}, + {32, 'g', 0, "3e+01"}, + + {100, 'x', -1, "0x1.9p+06"}, + {100, 'y', -1, "%y"}, + + {math.NaN(), 'g', -1, "NaN"}, + {-math.NaN(), 'g', -1, "NaN"}, + {math.Inf(0), 'g', -1, "+Inf"}, + {math.Inf(-1), 'g', -1, "-Inf"}, + {-math.Inf(0), 'g', -1, "-Inf"}, + + {-1, 'b', -1, "-4503599627370496p-52"}, + + // fixed bugs + {0.9, 'f', 1, "0.9"}, + {0.09, 'f', 1, "0.1"}, + {0.0999, 'f', 1, "0.1"}, + {0.05, 'f', 1, "0.1"}, + {0.05, 'f', 0, "0"}, + {0.5, 'f', 1, "0.5"}, + {0.5, 'f', 0, "0"}, + {1.5, 'f', 0, "2"}, + + // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/ + {2.2250738585072012e-308, 'g', -1, "2.2250738585072014e-308"}, + // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ + {2.2250738585072011e-308, 'g', -1, "2.225073858507201e-308"}, + + // Issue 2625. + {383260575764816448, 'f', 0, "383260575764816448"}, + {383260575764816448, 'g', -1, "3.8326057576481645e+17"}, + + // Issue 29491. + {498484681984085570, 'f', -1, "498484681984085570"}, + {-5.8339553793802237e+23, 'g', -1, "-5.8339553793802237e+23"}, + + // Issue 52187 + {123.45, '?', 0, "%?"}, + {123.45, '?', 1, "%?"}, + {123.45, '?', -1, "%?"}, + + // rounding + {2.275555555555555, 'x', -1, "0x1.23456789abcdep+01"}, + {2.275555555555555, 'x', 0, "0x1p+01"}, + {2.275555555555555, 'x', 2, "0x1.23p+01"}, + {2.275555555555555, 'x', 16, "0x1.23456789abcde000p+01"}, + {2.275555555555555, 'x', 21, "0x1.23456789abcde00000000p+01"}, + {2.2755555510520935, 'x', -1, "0x1.2345678p+01"}, + {2.2755555510520935, 'x', 6, "0x1.234568p+01"}, + {2.275555431842804, 'x', -1, "0x1.2345668p+01"}, + {2.275555431842804, 'x', 6, "0x1.234566p+01"}, + {3.999969482421875, 'x', -1, "0x1.ffffp+01"}, + {3.999969482421875, 'x', 4, "0x1.ffffp+01"}, + {3.999969482421875, 'x', 3, "0x1.000p+02"}, + {3.999969482421875, 'x', 2, "0x1.00p+02"}, + {3.999969482421875, 'x', 1, "0x1.0p+02"}, + {3.999969482421875, 'x', 0, "0x1p+02"}, + + // Cases that Java once mishandled, from David Chase. + {1.801439850948199e+16, 'g', -1, "1.801439850948199e+16"}, + {5.960464477539063e-08, 'g', -1, "5.960464477539063e-08"}, + {1.012e-320, 'g', -1, "1.012e-320"}, + + // Cases from TestFtoaRandom that caught bugs in fixedFtoa. + {8177880169308380. * (1 << 1), 'e', 14, "1.63557603386168e+16"}, + {8393378656576888. * (1 << 1), 'e', 15, "1.678675731315378e+16"}, + {8738676561280626. * (1 << 4), 'e', 16, "1.3981882498049002e+17"}, + {8291032395191335. / (1 << 30), 'e', 5, "7.72163e+06"}, + {8880392441509914. / (1 << 80), 'e', 16, "7.3456884594794477e-09"}, + + // Exercise divisiblePow5 case in fixedFtoa + {2384185791015625. * (1 << 12), 'e', 5, "9.76562e+18"}, + {2384185791015625. * (1 << 13), 'e', 5, "1.95312e+19"}, + + // Exercise potential mistakes in fixedFtoa. + // Found by introducing mistakes and running 'go test -testbase'. + {0x1.000000000005p+71, 'e', 16, "2.3611832414348645e+21"}, + {0x1.0000p-27, 'e', 17, "7.45058059692382812e-09"}, + {0x1.0000p-41, 'e', 17, "4.54747350886464119e-13"}, +} + +func TestFtoa(t *testing.T) { + for i := 0; i < len(ftoatests); i++ { + test := &ftoatests[i] + s := FormatFloat(test.f, test.fmt, test.prec, 64) + if s != test.s { + t.Error("testN=64", test.f, string(test.fmt), test.prec, "want", test.s, "got", s) + } + x := AppendFloat([]byte("abc"), test.f, test.fmt, test.prec, 64) + if string(x) != "abc"+test.s { + t.Error("AppendFloat testN=64", test.f, string(test.fmt), test.prec, "want", "abc"+test.s, "got", string(x)) + } + if float64(float32(test.f)) == test.f && test.fmt != 'b' { + test_s := test.s + if test.f == 5.960464477539063e-08 { + // This test is an exact float32 but asking for float64 precision in the string. + // (All our other float64-only tests fail to exactness check above.) + test_s = "5.9604645e-08" + continue + } + s := FormatFloat(test.f, test.fmt, test.prec, 32) + if s != test.s { + t.Error("testN=32", test.f, string(test.fmt), test.prec, "want", test_s, "got", s) + } + x := AppendFloat([]byte("abc"), test.f, test.fmt, test.prec, 32) + if string(x) != "abc"+test_s { + t.Error("AppendFloat testN=32", test.f, string(test.fmt), test.prec, "want", "abc"+test_s, "got", string(x)) + } + } + } +} + +func TestFtoaPowersOfTwo(t *testing.T) { + for exp := -2048; exp <= 2048; exp++ { + f := math.Ldexp(1, exp) + if !math.IsInf(f, 0) { + s := FormatFloat(f, 'e', -1, 64) + if x, _ := ParseFloat(s, 64); x != f { + t.Errorf("failed roundtrip %v => %s => %v", f, s, x) + } + } + f32 := float32(f) + if !math.IsInf(float64(f32), 0) { + s := FormatFloat(float64(f32), 'e', -1, 32) + if x, _ := ParseFloat(s, 32); float32(x) != f32 { + t.Errorf("failed roundtrip %v => %s => %v", f32, s, float32(x)) + } + } + } +} + +func TestFtoaRandom(t *testing.T) { + N := int(1e4) + if testing.Short() { + N = 100 + } + t.Logf("testing %d random numbers with fast and slow FormatFloat", N) + for i := 0; i < N; i++ { + bits := uint64(rand.Uint32())<<32 | uint64(rand.Uint32()) + x := math.Float64frombits(bits) + + shortFast := FormatFloat(x, 'g', -1, 64) + SetOptimize(false) + shortSlow := FormatFloat(x, 'g', -1, 64) + SetOptimize(true) + if shortSlow != shortFast { + t.Errorf("%b printed as %s, want %s", x, shortFast, shortSlow) + } + + prec := rand.Intn(12) + 5 + shortFast = FormatFloat(x, 'e', prec, 64) + SetOptimize(false) + shortSlow = FormatFloat(x, 'e', prec, 64) + SetOptimize(true) + if shortSlow != shortFast { + t.Errorf("%b printed with %%.%de as %s, want %s", x, prec, shortFast, shortSlow) + } + } +} + +func TestFormatFloatInvalidBitSize(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic due to invalid bitSize") + } + }() + _ = FormatFloat(3.14, 'g', -1, 100) +} + +var ftoaBenches = []struct { + name string + float float64 + fmt byte + prec int + bitSize int +}{ + {"Decimal", 33909, 'g', -1, 64}, + {"Float", 339.7784, 'g', -1, 64}, + {"Exp", -5.09e75, 'g', -1, 64}, + {"NegExp", -5.11e-95, 'g', -1, 64}, + {"LongExp", 1.234567890123456e-78, 'g', -1, 64}, + + {"Big", 123456789123456789123456789, 'g', -1, 64}, + {"BinaryExp", -1, 'b', -1, 64}, + + {"32Integer", 33909, 'g', -1, 32}, + {"32ExactFraction", 3.375, 'g', -1, 32}, + {"32Point", 339.7784, 'g', -1, 32}, + {"32Exp", -5.09e25, 'g', -1, 32}, + {"32NegExp", -5.11e-25, 'g', -1, 32}, + {"32Shortest", 1.234567e-8, 'g', -1, 32}, + {"32Fixed8Hard", math.Ldexp(15961084, -125), 'e', 8, 32}, + {"32Fixed9Hard", math.Ldexp(14855922, -83), 'e', 9, 32}, + + {"64Fixed1", 123456, 'e', 3, 64}, + {"64Fixed2", 123.456, 'e', 3, 64}, + {"64Fixed2.5", 1.2345e+06, 'e', 3, 64}, + {"64Fixed3", 1.23456e+78, 'e', 3, 64}, + {"64Fixed4", 1.23456e-78, 'e', 3, 64}, + {"64Fixed5Hard", 4.096e+25, 'e', 5, 64}, // needs divisiblePow5(..., 20) + {"64Fixed12", 1.23456e-78, 'e', 12, 64}, + {"64Fixed16", 1.23456e-78, 'e', 16, 64}, + // From testdata/testfp.txt + {"64Fixed12Hard", math.Ldexp(6965949469487146, -249), 'e', 12, 64}, + {"64Fixed17Hard", math.Ldexp(8887055249355788, 665), 'e', 17, 64}, + {"64Fixed18Hard", math.Ldexp(6994187472632449, 690), 'e', 18, 64}, + + {"64FixedF1", 123.456, 'f', 6, 64}, + {"64FixedF2", 0.0123, 'f', 6, 64}, + {"64FixedF3", 12.3456, 'f', 2, 64}, + + // Trigger slow path (see issue #15672). + // The shortest is: 8.034137530808823e+43 + {"Slowpath64", 8.03413753080882349e+43, 'e', -1, 64}, + // This denormal is pathological because the lower/upper + // halfways to neighboring floats are: + // 622666234635.321003e-320 ~= 622666234635.321e-320 + // 622666234635.321497e-320 ~= 622666234635.3215e-320 + // making it hard to find the 3rd digit + {"SlowpathDenormal64", 622666234635.3213e-320, 'e', -1, 64}, + + // Trigger the shorter interval case (3.90625e-3 = 1/256). + {"ShorterIntervalCase32", 3.90625e-3, 'e', -1, 32}, + {"ShorterIntervalCase64", 3.90625e-3, 'e', -1, 64}, +} + +func BenchmarkFormatFloat(b *testing.B) { + for _, c := range ftoaBenches { + b.Run(c.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + FormatFloat(c.float, c.fmt, c.prec, c.bitSize) + } + }) + } +} + +func BenchmarkAppendFloat(b *testing.B) { + dst := make([]byte, 30) + for _, c := range ftoaBenches { + b.Run(c.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + AppendFloat(dst[:0], c.float, c.fmt, c.prec, c.bitSize) + } + }) + } +} diff --git a/go/src/internal/strconv/ftoadbox.go b/go/src/internal/strconv/ftoadbox.go new file mode 100644 index 0000000000000000000000000000000000000000..bdd9cd1ea5b1f7c13d7f8d96d52b048a81535634 --- /dev/null +++ b/go/src/internal/strconv/ftoadbox.go @@ -0,0 +1,349 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv + +// Binary to decimal conversion using the Dragonbox algorithm by Junekey Jeon. +// +// Fixed precision format is not supported by the Dragonbox algorithm +// so we continue to use Ryū-printf for this purpose. +// See https://github.com/jk-jeon/dragonbox/issues/38 for more details. +// +// For binary to decimal rounding, uses round to nearest, tie to even. +// For decimal to binary rounding, assumes round to nearest, tie to even. +// +// The original paper by Junekey Jeon can be found at: +// https://github.com/jk-jeon/dragonbox/blob/d5dc40ae6a3f1a4559cda816738df2d6255b4e24/other_files/Dragonbox.pdf +// +// The reference implementation in C++ by Junekey Jeon can be found at: +// https://github.com/jk-jeon/dragonbox/blob/6c7c925b571d54486b9ffae8d9d18a822801cbda/subproject/simple/include/simple_dragonbox.h + +// dragonboxFtoa computes the decimal significand and exponent +// from the binary significand and exponent using the Dragonbox algorithm +// and formats the decimal floating point number in d. +func dboxFtoa(d *decimalSlice, mant uint64, exp int, denorm bool, bitSize int) { + if bitSize == 32 { + dboxFtoa32(d, uint32(mant), exp, denorm) + return + } + dboxFtoa64(d, mant, exp, denorm) +} + +func dboxFtoa64(d *decimalSlice, mant uint64, exp int, denorm bool) { + if mant == 1<> 32) + yl := uint32(y) + + xyh := umul64(x, yh) + xyl := umul64(x, yl) + + return xyh + (xyl >> 32) +} + +// umul96Lower64 returns the lower 64 bits (out of 96 bits) of x * y. +func umul96Lower64(x uint32, y uint64) uint64 { + return uint64(uint64(x) * y) +} + +// umul128Upper64 returns the upper 64 bits (out of 128 bits) of x * y. +func umul128Upper64(x, y uint64) uint64 { + a := uint32(x >> 32) + b := uint32(x) + c := uint32(y >> 32) + d := uint32(y) + + ac := umul64(a, c) + bc := umul64(b, c) + ad := umul64(a, d) + bd := umul64(b, d) + + intermediate := (bd >> 32) + uint64(uint32(ad)) + uint64(uint32(bc)) + + return ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32) +} + +// umul192Upper128 returns the upper 128 bits (out of 192 bits) of x * y. +func umul192Upper128(x uint64, y uint128) uint128 { + r := umul128(x, y.Hi) + t := umul128Upper64(x, y.Lo) + return uadd128(r, t) +} + +// umul192Lower128 returns the lower 128 bits (out of 192 bits) of x * y. +func umul192Lower128(x uint64, y uint128) uint128 { + high := x * y.Hi + highLow := umul128(x, y.Lo) + return uint128{uint64(high + highLow.Hi), highLow.Lo} +} + +// dboxMulPow64 computes x^(i), y^(i), z^(i) +// from the precomputed value of φ̃k for float64 +// and also checks if x^(f), y^(f), z^(f) == 0 (section 5.2.1). +func dboxMulPow64(u uint64, phi uint128) (intPart uint64, isInt bool) { + r := umul192Upper128(u, phi) + intPart = r.Hi + isInt = r.Lo == 0 + return +} + +// dboxMulPow32 computes x^(i), y^(i), z^(i) +// from the precomputed value of φ̃k for float32 +// and also checks if x^(f), y^(f), z^(f) == 0 (section 5.2.1). +func dboxMulPow32(u uint32, phi uint64) (intPart uint32, isInt bool) { + r := umul96Upper64(u, phi) + intPart = uint32(r >> 32) + isInt = uint32(r) == 0 + return +} + +// dboxParity64 computes only the parity of x^(i), y^(i), z^(i) +// from the precomputed value of φ̃k for float64 +// and also checks if x^(f), y^(f), z^(f) = 0 (section 5.2.1). +func dboxParity64(mant2 uint64, phi uint128, beta int) (parity bool, isInt bool) { + r := umul192Lower128(mant2, phi) + parity = ((r.Hi >> (64 - beta)) & 1) != 0 + isInt = ((uint64(r.Hi << beta)) | (r.Lo >> (64 - beta))) == 0 + return +} + +// dboxParity32 computes only the parity of x^(i), y^(i), z^(i) +// from the precomputed value of φ̃k for float32 +// and also checks if x^(f), y^(f), z^(f) = 0 (section 5.2.1). +func dboxParity32(mant2 uint32, phi uint64, beta int) (parity bool, isInt bool) { + r := umul96Lower64(mant2, phi) + parity = ((r >> (64 - beta)) & 1) != 0 + isInt = uint32(r>>(32-beta)) == 0 + return +} + +// dboxDelta64 returns δ^(i) from the precomputed value of φ̃k for float64. +func dboxDelta64(φ uint128, β int) uint32 { + return uint32(φ.Hi >> (64 - 1 - β)) +} + +// dboxDelta32 returns δ^(i) from the precomputed value of φ̃k for float32. +func dboxDelta32(φ uint64, β int) uint32 { + return uint32(φ >> (64 - 1 - β)) +} + +// mulLog10_2MinusLog10_4Over3 computes +// ⌊e*log10(2)-log10(4/3)⌋ = ⌊log10(2^e)-log10(4/3)⌋ (section 6.3). +func mulLog10_2MinusLog10_4Over3(e int) int { + // e should be in the range [-2985, 2936]. + return (e*631305 - 261663) >> 21 +} + +const ( + floatMantBits64 = 52 // p = 52 for float64. + floatMantBits32 = 23 // p = 23 for float32. +) + +// dboxRange64 returns the left and right float64 endpoints. +func dboxRange64(φ uint128, β int) (left, right uint64) { + left = (φ.Hi - (φ.Hi >> (float64MantBits + 2))) >> (64 - float64MantBits - 1 - β) + right = (φ.Hi + (φ.Hi >> (float64MantBits + 1))) >> (64 - float64MantBits - 1 - β) + return left, right +} + +// dboxRange32 returns the left and right float32 endpoints. +func dboxRange32(φ uint64, β int) (left, right uint32) { + left = uint32((φ - (φ >> (floatMantBits32 + 2))) >> (64 - floatMantBits32 - 1 - β)) + right = uint32((φ + (φ >> (floatMantBits32 + 1))) >> (64 - floatMantBits32 - 1 - β)) + return left, right +} + +// dboxRoundUp64 computes the round up of y (i.e., y^(ru)). +func dboxRoundUp64(phi uint128, beta int) uint64 { + return (phi.Hi>>(128/2-floatMantBits64-2-beta) + 1) / 2 +} + +// dboxRoundUp32 computes the round up of y (i.e., y^(ru)). +func dboxRoundUp32(phi uint64, beta int) uint32 { + return uint32(phi>>(64-floatMantBits32-2-beta)+1) / 2 +} + +// dboxPow64 gets the precomputed value of φ̃̃k for float64. +func dboxPow64(k, e int) (φ uint128, β int) { + φ, e1, _ := pow10(k) + if k < 0 || k > 55 { + φ.Lo++ + } + β = e + e1 - 1 + return φ, β +} + +// dboxPow32 gets the precomputed value of φ̃̃k for float32. +func dboxPow32(k, e int) (mant uint64, exp int) { + m, e1, _ := pow10(k) + if k < 0 || k > 27 { + m.Hi++ + } + exp = e + e1 - 1 + return m.Hi, exp +} diff --git a/go/src/internal/strconv/ftoafixed.go b/go/src/internal/strconv/ftoafixed.go new file mode 100644 index 0000000000000000000000000000000000000000..7f297e924e160682843cafd1178235548de810d3 --- /dev/null +++ b/go/src/internal/strconv/ftoafixed.go @@ -0,0 +1,184 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv + +import "math/bits" + +var uint64pow10 = [...]uint64{ + 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, +} + +// fixedFtoa formats a number of decimal digits of mant*(2^exp) into d, +// where mant > 0 and 1 ≤ digits ≤ 18. +// If fmt == 'f', digits is a conservative overestimate, and the final +// number of digits is prec past the decimal point. +func fixedFtoa(d *decimalSlice, mant uint64, exp, digits, prec int, fmt byte) { + // The strategy here is to multiply (mant * 2^exp) by a power of 10 + // to make the resulting integer be the number of digits we want. + // + // Adams proved in the Ryu paper that 128-bit precision in the + // power-of-10 constant is sufficient to produce correctly + // rounded output for all float64s, up to 18 digits. + // https://dl.acm.org/doi/10.1145/3192366.3192369 + // + // TODO(rsc): The paper is not focused on, nor terribly clear about, + // this fact in this context, and the proof seems too complicated. + // Post a shorter, more direct proof and link to it here. + + if digits > 18 { + panic("fixedFtoa called with digits > 18") + } + + // Shift mantissa to have 64 bits, + // so that the 192-bit product below will + // have at least 63 bits in its top word. + b := 64 - bits.Len64(mant) + mant <<= b + exp -= b + + // We have f = mant * 2^exp ≥ 2^(63+exp) + // and we want to multiply it by some 10^p + // to make it have the number of digits plus one rounding bit: + // + // 2 * 10^(digits-1) ≤ f * 10^p < ~2 * 10^digits + // + // The lower bound is required, but the upper bound is approximate: + // we must not have too few digits, but we can round away extra ones. + // + // f * 10^p ≥ 2 * 10^(digits-1) + // 10^p ≥ 2 * 10^(digits-1) / f [dividing by f] + // p ≥ (log₁₀ 2) + (digits-1) - log₁₀ f [taking log₁₀] + // p ≥ (log₁₀ 2) + (digits-1) - log₁₀ (mant * 2^exp) [expanding f] + // p ≥ (log₁₀ 2) + (digits-1) - (log₁₀ 2) * (64 + exp) [mant < 2⁶⁴] + // p ≥ (digits - 1) - (log₁₀ 2) * (63 + exp) [refactoring] + // + // Once we have p, we can compute the scaled value: + // + // dm * 2^de = mant * 2^exp * 10^p + // = mant * 2^exp * pow/2^128 * 2^exp2. + // = (mant * pow/2^128) * 2^(exp+exp2). + p := (digits - 1) - mulLog10_2(63+exp) + pow, exp2, ok := pow10(p) + if !ok { + // This never happens due to the range of float32/float64 exponent + panic("fixedFtoa: pow10 out of range") + } + if -22 <= p && p < 0 { + // Special case: Let q=-p. q is in [1,22]. We are dividing by 10^q + // and the mantissa may be a multiple of 5^q (5^22 < 2^53), + // in which case the division must be computed exactly and + // recorded as exact for correct rounding. Our normal computation is: + // + // dm = floor(mant * floor(10^p * 2^s)) + // + // for some scaling shift s. To make this an exact division, + // it suffices to change the inner floor to a ceil: + // + // dm = floor(mant * ceil(10^p * 2^s)) + // + // In the range of values we are using, the floor and ceil + // cancel each other out and the high 64 bits of the product + // come out exactly right. + // (This is the same trick compilers use for division by constants. + // See Hacker's Delight, 2nd ed., Chapter 10.) + pow.Lo++ + } + dm, lo1, lo0 := umul192(mant, pow) + de := exp + exp2 + + // Check whether any bits have been truncated from dm. + // If so, set dt != 0. If not, leave dt == 0 (meaning dm is exact). + var dt uint + switch { + default: + // Most powers of 10 use a truncated constant, + // meaning the result is also truncated. + dt = 1 + case 0 <= p && p <= 55: + // Small positive powers of 10 (up to 10⁵⁵) can be represented + // precisely in a 128-bit mantissa (5⁵⁵ ≤ 2¹²⁸), so the only truncation + // comes from discarding the low bits of the 192-bit product. + // + // TODO(rsc): The new proof mentioned above should also + // prove that we can't have lo1 == 0 and lo0 != 0. + // After proving that, drop computation and use of lo0 here. + dt = bool2uint(lo1|lo0 != 0) + case -22 <= p && p < 0 && divisiblePow5(mant, -p): + // If the original mantissa was a multiple of 5^p, + // the result is exact. (See comment above for pow.Lo++.) + dt = 0 + } + + // The value we want to format is dm * 2^de, where de < 0. + // Multply by 2^de by shifting, but leave one extra bit for rounding. + // After the shift, the "integer part" of dm is dm>>1, + // the "rounding bit" (the first fractional bit) is dm&1, + // and the "truncated bit" (have any bits been discarded?) is dt. + shift := -de - 1 + dt |= bool2uint(dm&(1<>= shift + + // Set decimal point in eventual formatted digits, + // so we can update it as we adjust the digits. + d.dp = digits - p + + // Trim excess digit if any, updating truncation and decimal point. + // The << 1 is leaving room for the rounding bit. + max := uint64pow10[digits] << 1 + if dm >= max { + var r uint + dm, r = dm/10, uint(dm%10) + dt |= bool2uint(r != 0) + d.dp++ + } + + // If this is %.*f we may have overestimated the digits needed. + // Now that we know where the decimal point is, + // trim to the actual number of digits, which is d.dp+prec. + if fmt == 'f' && digits != d.dp+prec { + for digits > d.dp+prec { + var r uint + dm, r = dm/10, uint(dm%10) + dt |= bool2uint(r != 0) + digits-- + } + + // Dropping those digits can create a new leftmost + // non-zero digit, like if we are formatting %.1f and + // convert 0.09 -> 0.1. Detect and adjust for that. + if digits <= 0 { + digits = 1 + d.dp++ + } + + max = uint64pow10[digits] << 1 + } + + // Round and shift away rounding bit. + // We want to round up when + // (a) the fractional part is > 0.5 (dm&1 != 0 and dt == 1) + // (b) or the fractional part is ≥ 0.5 and the integer part is odd + // (dm&1 != 0 and dm&2 != 0). + // The bitwise expression encodes that logic. + dm += uint64(uint(dm) & (dt | uint(dm)>>1) & 1) + dm >>= 1 + if dm == max>>1 { + // 999... rolled over to 1000... + dm = uint64pow10[digits-1] + d.dp++ + } + + // Format digits into d. + if dm != 0 { + if formatBase10(d.d[:digits], dm) != 0 { + panic("formatBase10") + } + d.nd = digits + for d.d[d.nd-1] == '0' { + d.nd-- + } + } +} diff --git a/go/src/internal/strconv/import_test.go b/go/src/internal/strconv/import_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3dab2bf9e56e2b98e5372a69aea35529faea723a --- /dev/null +++ b/go/src/internal/strconv/import_test.go @@ -0,0 +1,26 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv_test + +import . "internal/strconv" + +type uint128 = Uint128 + +const ( + pow10Min = Pow10Min + pow10Max = Pow10Max +) + +var ( + mulLog10_2 = MulLog10_2 + mulLog2_10 = MulLog2_10 + parseFloatPrefix = ParseFloatPrefix + pow10 = Pow10 + umul128 = Umul128 + umul192 = Umul192 + div5Tab = Div5Tab + divisiblePow5 = DivisiblePow5 + trimZeros = TrimZeros +) diff --git a/go/src/internal/strconv/itoa.go b/go/src/internal/strconv/itoa.go new file mode 100644 index 0000000000000000000000000000000000000000..2375e034f5978691d5f48974dbeb69880a71d32c --- /dev/null +++ b/go/src/internal/strconv/itoa.go @@ -0,0 +1,237 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv + +import "math/bits" + +// FormatUint returns the string representation of i in the given base, +// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' +// for digit values >= 10. +func FormatUint(i uint64, base int) string { + if base == 10 { + if i < nSmalls { + return small(int(i)) + } + var a [24]byte + j := formatBase10(a[:], i) + return string(a[j:]) + } + _, s := formatBits(nil, i, base, false, false) + return s +} + +// FormatInt returns the string representation of i in the given base, +// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' +// for digit values >= 10. +func FormatInt(i int64, base int) string { + if base == 10 { + if 0 <= i && i < nSmalls { + return small(int(i)) + } + var a [24]byte + u := uint64(i) + if i < 0 { + u = -u + } + j := formatBase10(a[:], u) + if i < 0 { + j-- + a[j] = '-' + } + return string(a[j:]) + } + _, s := formatBits(nil, uint64(i), base, i < 0, false) + return s +} + +// Itoa is equivalent to [FormatInt](int64(i), 10). +func Itoa(i int) string { + return FormatInt(int64(i), 10) +} + +// AppendInt appends the string form of the integer i, +// as generated by [FormatInt], to dst and returns the extended buffer. +func AppendInt(dst []byte, i int64, base int) []byte { + u := uint64(i) + if i < 0 { + dst = append(dst, '-') + u = -u + } + return AppendUint(dst, u, base) +} + +// AppendUint appends the string form of the unsigned integer i, +// as generated by [FormatUint], to dst and returns the extended buffer. +func AppendUint(dst []byte, i uint64, base int) []byte { + if base == 10 { + if i < nSmalls { + return append(dst, small(int(i))...) + } + var a [24]byte + j := formatBase10(a[:], i) + return append(dst, a[j:]...) + } + dst, _ = formatBits(dst, i, base, false, true) + return dst +} + +const digits = "0123456789abcdefghijklmnopqrstuvwxyz" + +// formatBits computes the string representation of u in the given base. +// If neg is set, u is treated as negative int64 value. If append_ is +// set, the string is appended to dst and the resulting byte slice is +// returned as the first result value; otherwise the string is returned +// as the second result value. +// The caller is expected to have handled base 10 separately for speed. +func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string) { + if base < 2 || base == 10 || base > len(digits) { + panic("strconv: illegal AppendInt/FormatInt base") + } + // 2 <= base && base <= len(digits) + + var a [64 + 1]byte // +1 for sign of 64bit value in base 2 + i := len(a) + if neg { + u = -u + } + + // convert bits + // We use uint values where we can because those will + // fit into a single register even on a 32bit machine. + if isPowerOfTwo(base) { + // Use shifts and masks instead of / and %. + shift := uint(bits.TrailingZeros(uint(base))) + b := uint64(base) + m := uint(base) - 1 // == 1<= b { + i-- + a[i] = digits[uint(u)&m] + u >>= shift + } + // u < base + i-- + a[i] = digits[uint(u)] + } else { + // general case + b := uint64(base) + for u >= b { + i-- + // Avoid using r = a%b in addition to q = a/b + // since 64bit division and modulo operations + // are calculated by runtime functions on 32bit machines. + q := u / b + a[i] = digits[uint(u-q*b)] + u = q + } + // u < base + i-- + a[i] = digits[uint(u)] + } + + // add sign, if any + if neg { + i-- + a[i] = '-' + } + + if append_ { + d = append(dst, a[i:]...) + return + } + s = string(a[i:]) + return +} + +func isPowerOfTwo(x int) bool { + return x&(x-1) == 0 +} + +const nSmalls = 100 + +// smalls is the formatting of 00..99 concatenated. +// It is then padded out with 56 x's to 256 bytes, +// so that smalls[x&0xFF] has no bounds check. +const smalls = "00010203040506070809" + + "10111213141516171819" + + "20212223242526272829" + + "30313233343536373839" + + "40414243444546474849" + + "50515253545556575859" + + "60616263646566676869" + + "70717273747576777879" + + "80818283848586878889" + + "90919293949596979899" + +const host64bit = ^uint(0)>>32 != 0 + +// small returns the string for an i with 0 <= i < nSmalls. +func small(i int) string { + if i < 10 { + return digits[i : i+1] + } + return smalls[i*2 : i*2+2] +} + +// RuntimeFormatBase10 formats u into the tail of a +// and returns the offset to the first byte written to a. +// It is only for use by package runtime. +// Other packages should use AppendUint. +func RuntimeFormatBase10(a []byte, u uint64) int { + return formatBase10(a, u) +} + +// formatBase10 formats the decimal representation of u into the tail of a +// and returns the offset of the first byte written to a. That is, after +// +// i := formatBase10(a, u) +// +// the decimal representation is in a[i:]. +func formatBase10(a []byte, u uint64) int { + // Split into 9-digit chunks that fit in uint32s + // and convert each chunk using uint32 math instead of uint64 math. + // The obvious way to write the outer loop is "for u >= 1e9", but most numbers are small, + // so the setup for the comparison u >= 1e9 is usually pure overhead. + // Instead, we approximate it by u>>29 != 0, which is usually faster and good enough. + i := len(a) + for (host64bit && u>>29 != 0) || (!host64bit && uint32(u)>>29|uint32(u>>32) != 0) { + var lo uint32 + u, lo = u/1e9, uint32(u%1e9) + + // Convert 9 digits. + for range 4 { + var dd uint32 + lo, dd = lo/100, (lo%100)*2 + i -= 2 + a[i+0], a[i+1] = smalls[dd+0], smalls[dd+1] + } + i-- + a[i] = smalls[lo*2+1] + + // If we'd been using u >= 1e9 then we would be guaranteed that u/1e9 > 0, + // but since we used u>>29 != 0, u/1e9 might be 0, so we might be done. + // (If u is now 0, then at the start we had 2²⁹ ≤ u < 10⁹, so it was still correct + // to write 9 digits; we have not accidentally written any leading zeros.) + if u == 0 { + return i + } + } + + // Convert final chunk, at most 8 digits. + lo := uint32(u) + for lo >= 100 { + var dd uint32 + lo, dd = lo/100, (lo%100)*2 + i -= 2 + a[i+0], a[i+1] = smalls[dd+0], smalls[dd+1] + } + i-- + dd := lo * 2 + a[i] = smalls[dd+1] + if lo >= 10 { + i-- + a[i] = smalls[dd+0] + } + return i +} diff --git a/go/src/internal/strconv/itoa_test.go b/go/src/internal/strconv/itoa_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1629e45d48c4a020b054fde845ee661806cc2bd6 --- /dev/null +++ b/go/src/internal/strconv/itoa_test.go @@ -0,0 +1,244 @@ +// 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 strconv_test + +import ( + "fmt" + . "internal/strconv" + "testing" +) + +type itob64Test struct { + in int64 + base int + out string +} + +var itob64tests = []itob64Test{ + {0, 10, "0"}, + {1, 10, "1"}, + {-1, 10, "-1"}, + {12345678, 10, "12345678"}, + {-987654321, 10, "-987654321"}, + {1<<31 - 1, 10, "2147483647"}, + {-1<<31 + 1, 10, "-2147483647"}, + {1 << 31, 10, "2147483648"}, + {-1 << 31, 10, "-2147483648"}, + {1<<31 + 1, 10, "2147483649"}, + {-1<<31 - 1, 10, "-2147483649"}, + {1<<32 - 1, 10, "4294967295"}, + {-1<<32 + 1, 10, "-4294967295"}, + {1 << 32, 10, "4294967296"}, + {-1 << 32, 10, "-4294967296"}, + {1<<32 + 1, 10, "4294967297"}, + {-1<<32 - 1, 10, "-4294967297"}, + {1 << 50, 10, "1125899906842624"}, + {1<<63 - 1, 10, "9223372036854775807"}, + {-1<<63 + 1, 10, "-9223372036854775807"}, + {-1 << 63, 10, "-9223372036854775808"}, + + {0, 2, "0"}, + {10, 2, "1010"}, + {-1, 2, "-1"}, + {1 << 15, 2, "1000000000000000"}, + + {-8, 8, "-10"}, + {057635436545, 8, "57635436545"}, + {1 << 24, 8, "100000000"}, + + {16, 16, "10"}, + {-0x123456789abcdef, 16, "-123456789abcdef"}, + {1<<63 - 1, 16, "7fffffffffffffff"}, + {1<<63 - 1, 2, "111111111111111111111111111111111111111111111111111111111111111"}, + {-1 << 63, 2, "-1000000000000000000000000000000000000000000000000000000000000000"}, + + {16, 17, "g"}, + {25, 25, "10"}, + {(((((17*35+24)*35+21)*35+34)*35+12)*35+24)*35 + 32, 35, "holycow"}, + {(((((17*36+24)*36+21)*36+34)*36+12)*36+24)*36 + 32, 36, "holycow"}, +} + +func TestItoa(t *testing.T) { + for _, test := range itob64tests { + s := FormatInt(test.in, test.base) + if s != test.out { + t.Errorf("FormatInt(%v, %v) = %v want %v", + test.in, test.base, s, test.out) + } + x := AppendInt([]byte("abc"), test.in, test.base) + if string(x) != "abc"+test.out { + t.Errorf("AppendInt(%q, %v, %v) = %q want %v", + "abc", test.in, test.base, x, test.out) + } + + if test.in >= 0 { + s := FormatUint(uint64(test.in), test.base) + if s != test.out { + t.Errorf("FormatUint(%v, %v) = %v want %v", + test.in, test.base, s, test.out) + } + x := AppendUint(nil, uint64(test.in), test.base) + if string(x) != test.out { + t.Errorf("AppendUint(%q, %v, %v) = %q want %v", + "abc", uint64(test.in), test.base, x, test.out) + } + } + + if test.base == 10 && int64(int(test.in)) == test.in { + s := Itoa(int(test.in)) + if s != test.out { + t.Errorf("Itoa(%v) = %v want %v", + test.in, s, test.out) + } + } + } + + // Override when base is illegal + defer func() { + if r := recover(); r == nil { + t.Fatalf("expected panic due to illegal base") + } + }() + FormatUint(12345678, 1) +} + +type uitob64Test struct { + in uint64 + base int + out string +} + +var uitob64tests = []uitob64Test{ + {1<<63 - 1, 10, "9223372036854775807"}, + {1 << 63, 10, "9223372036854775808"}, + {1<<63 + 1, 10, "9223372036854775809"}, + {1<<64 - 2, 10, "18446744073709551614"}, + {1<<64 - 1, 10, "18446744073709551615"}, + {1<<64 - 1, 2, "1111111111111111111111111111111111111111111111111111111111111111"}, +} + +func TestUitoa(t *testing.T) { + for _, test := range uitob64tests { + s := FormatUint(test.in, test.base) + if s != test.out { + t.Errorf("FormatUint(%v, %v) = %v want %v", + test.in, test.base, s, test.out) + } + x := AppendUint([]byte("abc"), test.in, test.base) + if string(x) != "abc"+test.out { + t.Errorf("AppendUint(%q, %v, %v) = %q want %v", + "abc", test.in, test.base, x, test.out) + } + + } +} + +var varlenUints = []struct { + in uint64 + out string +}{ + {1, "1"}, + {12, "12"}, + {123, "123"}, + {1234, "1234"}, + {12345, "12345"}, + {123456, "123456"}, + {1234567, "1234567"}, + {12345678, "12345678"}, + {123456789, "123456789"}, + {1234567890, "1234567890"}, + {12345678901, "12345678901"}, + {123456789012, "123456789012"}, + {1234567890123, "1234567890123"}, + {12345678901234, "12345678901234"}, + {123456789012345, "123456789012345"}, + {1234567890123456, "1234567890123456"}, + {12345678901234567, "12345678901234567"}, + {123456789012345678, "123456789012345678"}, + {1234567890123456789, "1234567890123456789"}, + {12345678901234567890, "12345678901234567890"}, +} + +func TestFormatUintVarlen(t *testing.T) { + for _, test := range varlenUints { + s := FormatUint(test.in, 10) + if s != test.out { + t.Errorf("FormatUint(%v, 10) = %v want %v", test.in, s, test.out) + } + } +} + +func BenchmarkFormatInt(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, test := range itob64tests { + s := FormatInt(test.in, test.base) + BenchSink += len(s) + } + } +} + +func BenchmarkAppendInt(b *testing.B) { + dst := make([]byte, 0, 30) + for i := 0; i < b.N; i++ { + for _, test := range itob64tests { + dst = AppendInt(dst[:0], test.in, test.base) + BenchSink += len(dst) + } + } +} + +func BenchmarkFormatUint(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, test := range uitob64tests { + s := FormatUint(test.in, test.base) + BenchSink += len(s) + } + } +} + +func BenchmarkAppendUint(b *testing.B) { + dst := make([]byte, 0, 30) + for i := 0; i < b.N; i++ { + for _, test := range uitob64tests { + dst = AppendUint(dst[:0], test.in, test.base) + BenchSink += len(dst) + } + } +} + +func BenchmarkFormatIntSmall(b *testing.B) { + smallInts := []int64{7, 42} + for _, smallInt := range smallInts { + b.Run(Itoa(int(smallInt)), func(b *testing.B) { + for i := 0; i < b.N; i++ { + s := FormatInt(smallInt, 10) + BenchSink += len(s) + } + }) + } +} + +func BenchmarkAppendIntSmall(b *testing.B) { + dst := make([]byte, 0, 30) + const smallInt = 42 + for i := 0; i < b.N; i++ { + dst = AppendInt(dst[:0], smallInt, 10) + BenchSink += len(dst) + } +} + +func BenchmarkAppendUintVarlen(b *testing.B) { + for _, test := range varlenUints { + b.Run(fmt.Sprint("digits=", len(test.out)), func(b *testing.B) { + dst := make([]byte, 0, 30) + for j := 0; j < b.N; j++ { + dst = AppendUint(dst[:0], test.in, 10) + BenchSink += len(dst) + } + }) + } +} + +var BenchSink int // make sure compiler cannot optimize away benchmarks diff --git a/go/src/internal/strconv/math.go b/go/src/internal/strconv/math.go new file mode 100644 index 0000000000000000000000000000000000000000..3b884e846a62224d780f8c88d552b2fbf431460e --- /dev/null +++ b/go/src/internal/strconv/math.go @@ -0,0 +1,179 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv + +import "math/bits" + +// A uint128 is a 128-bit uint. +// The fields are exported to make them visible to package strconv_test. +type uint128 struct { + Hi uint64 + Lo uint64 +} + +// umul128 returns the 128-bit product x*y. +func umul128(x, y uint64) uint128 { + hi, lo := bits.Mul64(x, y) + return uint128{hi, lo} +} + +// umul192 returns the 192-bit product x*y in three uint64s. +func umul192(x uint64, y uint128) (hi, mid, lo uint64) { + mid1, lo := bits.Mul64(x, y.Lo) + hi, mid2 := bits.Mul64(x, y.Hi) + mid, carry := bits.Add64(mid1, mid2, 0) + return hi + carry, mid, lo +} + +// pow10 returns the 128-bit mantissa and binary exponent of 10**e. +// That is, 10^e = mant/2^128 * 2**exp. +// If e is out of range, pow10 returns ok=false. +func pow10(e int) (mant uint128, exp int, ok bool) { + if e < pow10Min || e > pow10Max { + return + } + return pow10Tab[e-pow10Min], 1 + mulLog2_10(e), true +} + +// mulLog10_2 returns math.Floor(x * log(2)/log(10)) for an integer x in +// the range -1600 <= x && x <= +1600. +// +// The range restriction lets us work in faster integer arithmetic instead of +// slower floating point arithmetic. Correctness is verified by unit tests. +func mulLog10_2(x int) int { + // log(2)/log(10) ≈ 0.30102999566 ≈ 78913 / 2^18 + return (x * 78913) >> 18 +} + +// mulLog2_10 returns math.Floor(x * log(10)/log(2)) for an integer x in +// the range -500 <= x && x <= +500. +// +// The range restriction lets us work in faster integer arithmetic instead of +// slower floating point arithmetic. Correctness is verified by unit tests. +func mulLog2_10(x int) int { + // log(10)/log(2) ≈ 3.32192809489 ≈ 108853 / 2^15 + return (x * 108853) >> 15 +} + +func bool2uint(b bool) uint { + if b { + return 1 + } + return 0 +} + +// Exact Division and Remainder Checking +// +// An exact division x/c (exact means x%c == 0) +// can be implemented by x*m where m is the multiplicative inverse of c (m*c == 1). +// +// Since c is also the multiplicative inverse of m, x*m is lossless, +// and all the exact multiples of c map to all of [0, maxUint64/c]. +// The non-multiples are forced to map to larger values. +// This also gives a quick test for whether x is an exact multiple of c: +// compute the exact division and check whether it's at most maxUint64/c: +// x%c == 0 => x*m <= maxUint64/c. +// +// Only odd c have multiplicative inverses mod powers of two. +// To do an exact divide x / (c<>s instead. +// And to check for remainder, we need to check that those low s +// bits are all zero before we shift them away. We can merge that +// with the <= for the exact odd remainder check by rotating the +// shifted bits into the high part instead: +// x%(c< bits.RotateLeft64(x*m, -s) <= maxUint64/c. +// +// The compiler does this transformation automatically in general, +// but we apply it here by hand in a few ways that the compiler can't help with. +// +// For a more detailed explanation, see +// Henry S. Warren, Jr., Hacker's Delight, 2nd ed., sections 10-16 and 10-17. + +// divisiblePow5 reports whether x is divisible by 5^p. +// It returns false for p not in [1, 22], +// because we only care about float64 mantissas, and 5^23 > 2^53. +func divisiblePow5(x uint64, p int) bool { + return 1 <= p && p <= 22 && x*div5Tab[p-1][0] <= div5Tab[p-1][1] +} + +const maxUint64 = 1<<64 - 1 + +// div5Tab[p-1] is the multiplicative inverse of 5^p and maxUint64/5^p. +var div5Tab = [22][2]uint64{ + {0xcccccccccccccccd, maxUint64 / 5}, + {0x8f5c28f5c28f5c29, maxUint64 / 5 / 5}, + {0x1cac083126e978d5, maxUint64 / 5 / 5 / 5}, + {0xd288ce703afb7e91, maxUint64 / 5 / 5 / 5 / 5}, + {0x5d4e8fb00bcbe61d, maxUint64 / 5 / 5 / 5 / 5 / 5}, + {0x790fb65668c26139, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xe5032477ae8d46a5, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xc767074b22e90e21, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x8e47ce423a2e9c6d, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x4fa7f60d3ed61f49, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x0fee64690c913975, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x3662e0e1cf503eb1, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xa47a2cf9f6433fbd, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x54186f653140a659, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x7738164770402145, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xe4a4d1417cd9a041, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xc75429d9e5c5200d, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xc1773b91fac10669, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x26b172506559ce15, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0xd489e3a9addec2d1, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x90e860bb892c8d5d, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, + {0x502e79bf1b6f4f79, maxUint64 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5 / 5}, +} + +// trimZeros trims trailing zeros from x. +// It finds the largest p such that x % 10^p == 0 +// and then returns x / 10^p, p. +// +// This is here for reference and tested, because it is an optimization +// used by other ftoa algorithms, but in our implementations it has +// never been benchmarked to be faster than trimming zeros after +// formatting into decimal bytes. +func trimZeros(x uint64) (uint64, int) { + const ( + div1e8m = 0xc767074b22e90e21 + div1e8le = maxUint64 / 100000000 + + div1e4m = 0xd288ce703afb7e91 + div1e4le = maxUint64 / 10000 + + div1e2m = 0x8f5c28f5c28f5c29 + div1e2le = maxUint64 / 100 + + div1e1m = 0xcccccccccccccccd + div1e1le = maxUint64 / 10 + ) + + // _ = assert[x - y] asserts at compile time that x == y. + // Assert that the multiplicative inverses are correct + // by checking that (div1eNm * 5^N) % 1<<64 == 1. + var assert [1]struct{} + _ = assert[(div1e8m*5*5*5*5*5*5*5*5)%(1<<64)-1] + _ = assert[(div1e4m*5*5*5*5)%(1<<64)-1] + _ = assert[(div1e2m*5*5)%(1<<64)-1] + _ = assert[(div1e1m*5)%(1<<64)-1] + + // Cut 8 zeros, then 4, then 2, then 1. + p := 0 + for d := bits.RotateLeft64(x*div1e8m, -8); d <= div1e8le; d = bits.RotateLeft64(x*div1e8m, -8) { + x = d + p += 8 + } + if d := bits.RotateLeft64(x*div1e4m, -4); d <= div1e4le { + x = d + p += 4 + } + if d := bits.RotateLeft64(x*div1e2m, -2); d <= div1e2le { + x = d + p += 2 + } + if d := bits.RotateLeft64(x*div1e1m, -1); d <= div1e1le { + x = d + p += 1 + } + return x, p +} diff --git a/go/src/internal/strconv/math_test.go b/go/src/internal/strconv/math_test.go new file mode 100644 index 0000000000000000000000000000000000000000..55e25f98cfee284141057a15fe6073e4131460db --- /dev/null +++ b/go/src/internal/strconv/math_test.go @@ -0,0 +1,165 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package strconv_test + +import ( + . "internal/strconv" + "math" + "testing" +) + +var pow10Tests = []struct { + exp10 int + mant uint128 + exp2 int + ok bool +}{ + {-349, uint128{0, 0}, 0, false}, + {-348, uint128{0xFA8FD5A0081C0288, 0x1732C869CD60E453}, -1156, true}, + {0, uint128{0x8000000000000000, 0x0000000000000000}, 1, true}, + {347, uint128{0xD13EB46469447567, 0x4B7195F2D2D1A9FB}, 1153, true}, + {348, uint128{0, 0}, 0, false}, +} + +func TestPow10(t *testing.T) { + for _, tt := range pow10Tests { + mant, exp2, ok := pow10(tt.exp10) + if mant != tt.mant || exp2 != tt.exp2 { + t.Errorf("pow10(%d) = %#016x, %#016x, %d, %v want %#016x,%#016x, %d, %v", + tt.exp10, mant.Hi, mant.Lo, exp2, ok, + tt.mant.Hi, tt.mant.Lo, tt.exp2, tt.ok) + } + } + + for p := pow10Min; p <= pow10Max; p++ { + mant, exp2, ok := pow10(p) + if !ok { + t.Errorf("pow10(%d) not ok", p) + continue + } + // Note: -64 instead of -128 because we only used mant.Hi, not all of mant. + have := math.Ldexp(float64(mant.Hi), exp2-64) + want := math.Pow(10, float64(p)) + if math.Abs(have-want)/want > 0.00001 { + t.Errorf("pow10(%d) = %#016x%016x/2^128 * 2^%d = %g want ~%g", p, mant.Hi, mant.Lo, exp2, have, want) + } + } + +} + +func u128(hi, lo uint64) uint128 { + return uint128{Hi: hi, Lo: lo} +} + +var umul192Tests = []struct { + x uint64 + y uint128 + hi uint64 + mid uint64 + lo uint64 +}{ + {0, u128(0, 0), 0, 0, 0}, + {^uint64(0), u128(^uint64(0), ^uint64(0)), ^uint64(1), ^uint64(0), 1}, +} + +func TestUmul192(t *testing.T) { + for _, tt := range umul192Tests { + hi, mid, lo := Umul192(tt.x, tt.y) + if hi != tt.hi || mid != tt.mid || lo != tt.lo { + t.Errorf("umul192(%#x, {%#x,%#x}) = %#x, %#x, %#x, want %#x, %#x, %#x", + tt.x, tt.y.Hi, tt.y.Lo, hi, mid, lo, tt.hi, tt.mid, tt.lo) + } + } +} + +func TestMulLog10_2(t *testing.T) { + for x := -1600; x <= +1600; x++ { + iMath := mulLog10_2(x) + fMath := int(math.Floor(float64(x) * math.Ln2 / math.Ln10)) + if iMath != fMath { + t.Errorf("mulLog10_2(%d) failed: %d vs %d\n", x, iMath, fMath) + } + } +} + +func TestMulLog2_10(t *testing.T) { + for x := -500; x <= +500; x++ { + iMath := mulLog2_10(x) + fMath := int(math.Floor(float64(x) * math.Ln10 / math.Ln2)) + if iMath != fMath { + t.Errorf("mulLog2_10(%d) failed: %d vs %d\n", x, iMath, fMath) + } + } +} + +func pow5(p int) uint64 { + x := uint64(1) + for range p { + x *= 5 + } + return x +} + +func TestDivisiblePow5(t *testing.T) { + for p := 1; p <= 22; p++ { + x := pow5(p) + if divisiblePow5(1, p) { + t.Errorf("divisiblePow5(1, %d) = true, want, false", p) + } + if divisiblePow5(x-1, p) { + t.Errorf("divisiblePow5(%d, %d) = true, want false", x-1, p) + } + if divisiblePow5(x+1, p) { + t.Errorf("divisiblePow5(%d, %d) = true, want false", x-1, p) + } + if divisiblePow5(x/5, p) { + t.Errorf("divisiblePow5(%d, %d) = true, want false", x/5, p) + } + if !divisiblePow5(0, p) { + t.Errorf("divisiblePow5(0, %d) = false, want true", p) + } + if !divisiblePow5(x, p) { + t.Errorf("divisiblePow5(%d, %d) = false, want true", x, p) + } + if 2*x > x && !divisiblePow5(2*x, p) { + t.Errorf("divisiblePow5(%d, %d) = false, want true", 2*x, p) + } + } +} + +func TestDiv5Tab(t *testing.T) { + for p := 1; p <= 22; p++ { + m := div5Tab[p-1][0] + le := div5Tab[p-1][1] + + // See comment in math.go on div5Tab. + // m needs to be multiplicative inverse of pow5(p). + if m*pow5(p) != 1 { + t.Errorf("pow5Tab[%d-1][0] = %#x, but %#x * (5**%d) = %d, want 1", p, m, m, p, m*pow5(p)) + } + + // le needs to be ⌊(1<<64 - 1) / 5^p⌋. + want := (1<<64 - 1) / pow5(p) + if le != want { + t.Errorf("pow5Tab[%d-1][1] = %#x, want %#x", p, le, want) + } + } +} + +func TestTrimZeros(t *testing.T) { + for _, x := range []uint64{1, 2, 3, 4, 101, 123} { + want := x + for p := range 20 { + haveX, haveP := trimZeros(x) + if haveX != want || haveP != p { + t.Errorf("trimZeros(%d) = %d, %d, want %d, %d", x, haveX, haveP, want, p) + } + if x >= (1<<64-1)/10 { + break + } + x *= 10 + } + } +} diff --git a/go/src/internal/strconv/pow10gen.go b/go/src/internal/strconv/pow10gen.go new file mode 100644 index 0000000000000000000000000000000000000000..2d428fe088e3c13205b74d8ced32fc9d77a5b268 --- /dev/null +++ b/go/src/internal/strconv/pow10gen.go @@ -0,0 +1,91 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ignore + +package main + +import ( + "bytes" + "fmt" + "go/format" + "log" + "math/big" + "os" +) + +const ( + minExp = -348 + maxExp = 347 +) + +func main() { + log.SetPrefix("pow10gen: ") + log.SetFlags(0) + + var ( + one = big.NewInt(1) + ten = big.NewInt(10) + + b1p64 = new(big.Int).Lsh(one, 64) + b1p128 = new(big.Int).Lsh(one, 128) + + r2 = big.NewRat(2, 1) + r1p128 = new(big.Rat).SetInt(b1p128) + ) + + var out bytes.Buffer + fmt.Fprintf(&out, top, minExp, maxExp) + for e := int64(minExp); e <= maxExp; e++ { + var r *big.Rat + if e >= 0 { + r = new(big.Rat).SetInt(new(big.Int).Exp(ten, big.NewInt(e), nil)) + } else { + r = new(big.Rat).SetFrac(one, new(big.Int).Exp(ten, big.NewInt(-e), nil)) + } + be := 0 + for r.Cmp(r1p128) < 0 { + r.Mul(r, r2) + be++ + } + for r.Cmp(r1p128) >= 0 { + r.Quo(r, r2) + be-- + } + d := new(big.Int).Div(r.Num(), r.Denom()) + hi, lo := new(big.Int).DivMod(d, b1p64, new(big.Int)) + fmt.Fprintf(&out, "\t{%#016x, %#016x}, // 1e%d * 2**%d\n", hi.Uint64(), lo.Uint64(), e, be) + } + fmt.Fprintf(&out, "}\n") + + src, err := format.Source(out.Bytes()) + if err != nil { + log.Fatal(err) + } + + if err := os.WriteFile("pow10tab.go", src, 0666); err != nil { + log.Fatal(err) + } +} + +var top = `// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by: go run pow10gen.go. DO NOT EDIT. +// +//go:generate go run pow10gen.go + +package strconv + +const ( + pow10Min = %d + pow10Max = %d +) + + +// pow10Tab holds 128-bit mantissas of powers of 10. +// The values are scaled so the high bit is always set; there is no "implicit leading 1 bit". +var pow10Tab = [...]uint128{ +` diff --git a/go/src/internal/strconv/pow10tab.go b/go/src/internal/strconv/pow10tab.go new file mode 100644 index 0000000000000000000000000000000000000000..029ae02b6603f07a30c24ad74b6971cbae41f1cc --- /dev/null +++ b/go/src/internal/strconv/pow10tab.go @@ -0,0 +1,715 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by: go run pow10gen.go. DO NOT EDIT. +// +//go:generate go run pow10gen.go + +package strconv + +const ( + pow10Min = -348 + pow10Max = 347 +) + +// pow10Tab holds 128-bit mantissas of powers of 10. +// The values are scaled so the high bit is always set; there is no "implicit leading 1 bit". +var pow10Tab = [...]uint128{ + {0xfa8fd5a0081c0288, 0x1732c869cd60e453}, // 1e-348 * 2**1284 + {0x9c99e58405118195, 0x0e7fbd42205c8eb4}, // 1e-347 * 2**1280 + {0xc3c05ee50655e1fa, 0x521fac92a873b261}, // 1e-346 * 2**1277 + {0xf4b0769e47eb5a78, 0xe6a797b752909ef9}, // 1e-345 * 2**1274 + {0x98ee4a22ecf3188b, 0x9028bed2939a635c}, // 1e-344 * 2**1270 + {0xbf29dcaba82fdeae, 0x7432ee873880fc33}, // 1e-343 * 2**1267 + {0xeef453d6923bd65a, 0x113faa2906a13b3f}, // 1e-342 * 2**1264 + {0x9558b4661b6565f8, 0x4ac7ca59a424c507}, // 1e-341 * 2**1260 + {0xbaaee17fa23ebf76, 0x5d79bcf00d2df649}, // 1e-340 * 2**1257 + {0xe95a99df8ace6f53, 0xf4d82c2c107973dc}, // 1e-339 * 2**1254 + {0x91d8a02bb6c10594, 0x79071b9b8a4be869}, // 1e-338 * 2**1250 + {0xb64ec836a47146f9, 0x9748e2826cdee284}, // 1e-337 * 2**1247 + {0xe3e27a444d8d98b7, 0xfd1b1b2308169b25}, // 1e-336 * 2**1244 + {0x8e6d8c6ab0787f72, 0xfe30f0f5e50e20f7}, // 1e-335 * 2**1240 + {0xb208ef855c969f4f, 0xbdbd2d335e51a935}, // 1e-334 * 2**1237 + {0xde8b2b66b3bc4723, 0xad2c788035e61382}, // 1e-333 * 2**1234 + {0x8b16fb203055ac76, 0x4c3bcb5021afcc31}, // 1e-332 * 2**1230 + {0xaddcb9e83c6b1793, 0xdf4abe242a1bbf3d}, // 1e-331 * 2**1227 + {0xd953e8624b85dd78, 0xd71d6dad34a2af0d}, // 1e-330 * 2**1224 + {0x87d4713d6f33aa6b, 0x8672648c40e5ad68}, // 1e-329 * 2**1220 + {0xa9c98d8ccb009506, 0x680efdaf511f18c2}, // 1e-328 * 2**1217 + {0xd43bf0effdc0ba48, 0x0212bd1b2566def2}, // 1e-327 * 2**1214 + {0x84a57695fe98746d, 0x014bb630f7604b57}, // 1e-326 * 2**1210 + {0xa5ced43b7e3e9188, 0x419ea3bd35385e2d}, // 1e-325 * 2**1207 + {0xcf42894a5dce35ea, 0x52064cac828675b9}, // 1e-324 * 2**1204 + {0x818995ce7aa0e1b2, 0x7343efebd1940993}, // 1e-323 * 2**1200 + {0xa1ebfb4219491a1f, 0x1014ebe6c5f90bf8}, // 1e-322 * 2**1197 + {0xca66fa129f9b60a6, 0xd41a26e077774ef6}, // 1e-321 * 2**1194 + {0xfd00b897478238d0, 0x8920b098955522b4}, // 1e-320 * 2**1191 + {0x9e20735e8cb16382, 0x55b46e5f5d5535b0}, // 1e-319 * 2**1187 + {0xc5a890362fddbc62, 0xeb2189f734aa831d}, // 1e-318 * 2**1184 + {0xf712b443bbd52b7b, 0xa5e9ec7501d523e4}, // 1e-317 * 2**1181 + {0x9a6bb0aa55653b2d, 0x47b233c92125366e}, // 1e-316 * 2**1177 + {0xc1069cd4eabe89f8, 0x999ec0bb696e840a}, // 1e-315 * 2**1174 + {0xf148440a256e2c76, 0xc00670ea43ca250d}, // 1e-314 * 2**1171 + {0x96cd2a865764dbca, 0x380406926a5e5728}, // 1e-313 * 2**1167 + {0xbc807527ed3e12bc, 0xc605083704f5ecf2}, // 1e-312 * 2**1164 + {0xeba09271e88d976b, 0xf7864a44c633682e}, // 1e-311 * 2**1161 + {0x93445b8731587ea3, 0x7ab3ee6afbe0211d}, // 1e-310 * 2**1157 + {0xb8157268fdae9e4c, 0x5960ea05bad82964}, // 1e-309 * 2**1154 + {0xe61acf033d1a45df, 0x6fb92487298e33bd}, // 1e-308 * 2**1151 + {0x8fd0c16206306bab, 0xa5d3b6d479f8e056}, // 1e-307 * 2**1147 + {0xb3c4f1ba87bc8696, 0x8f48a4899877186c}, // 1e-306 * 2**1144 + {0xe0b62e2929aba83c, 0x331acdabfe94de87}, // 1e-305 * 2**1141 + {0x8c71dcd9ba0b4925, 0x9ff0c08b7f1d0b14}, // 1e-304 * 2**1137 + {0xaf8e5410288e1b6f, 0x07ecf0ae5ee44dd9}, // 1e-303 * 2**1134 + {0xdb71e91432b1a24a, 0xc9e82cd9f69d6150}, // 1e-302 * 2**1131 + {0x892731ac9faf056e, 0xbe311c083a225cd2}, // 1e-301 * 2**1127 + {0xab70fe17c79ac6ca, 0x6dbd630a48aaf406}, // 1e-300 * 2**1124 + {0xd64d3d9db981787d, 0x092cbbccdad5b108}, // 1e-299 * 2**1121 + {0x85f0468293f0eb4e, 0x25bbf56008c58ea5}, // 1e-298 * 2**1117 + {0xa76c582338ed2621, 0xaf2af2b80af6f24e}, // 1e-297 * 2**1114 + {0xd1476e2c07286faa, 0x1af5af660db4aee1}, // 1e-296 * 2**1111 + {0x82cca4db847945ca, 0x50d98d9fc890ed4d}, // 1e-295 * 2**1107 + {0xa37fce126597973c, 0xe50ff107bab528a0}, // 1e-294 * 2**1104 + {0xcc5fc196fefd7d0c, 0x1e53ed49a96272c8}, // 1e-293 * 2**1101 + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7a}, // 1e-292 * 2**1098 + {0x9faacf3df73609b1, 0x77b191618c54e9ac}, // 1e-291 * 2**1094 + {0xc795830d75038c1d, 0xd59df5b9ef6a2417}, // 1e-290 * 2**1091 + {0xf97ae3d0d2446f25, 0x4b0573286b44ad1d}, // 1e-289 * 2**1088 + {0x9becce62836ac577, 0x4ee367f9430aec32}, // 1e-288 * 2**1084 + {0xc2e801fb244576d5, 0x229c41f793cda73f}, // 1e-287 * 2**1081 + {0xf3a20279ed56d48a, 0x6b43527578c1110f}, // 1e-286 * 2**1078 + {0x9845418c345644d6, 0x830a13896b78aaa9}, // 1e-285 * 2**1074 + {0xbe5691ef416bd60c, 0x23cc986bc656d553}, // 1e-284 * 2**1071 + {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa8}, // 1e-283 * 2**1068 + {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6a9}, // 1e-282 * 2**1064 + {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc53}, // 1e-281 * 2**1061 + {0xe858ad248f5c22c9, 0xd1b3400f8f9cff68}, // 1e-280 * 2**1058 + {0x91376c36d99995be, 0x23100809b9c21fa1}, // 1e-279 * 2**1054 + {0xb58547448ffffb2d, 0xabd40a0c2832a78a}, // 1e-278 * 2**1051 + {0xe2e69915b3fff9f9, 0x16c90c8f323f516c}, // 1e-277 * 2**1048 + {0x8dd01fad907ffc3b, 0xae3da7d97f6792e3}, // 1e-276 * 2**1044 + {0xb1442798f49ffb4a, 0x99cd11cfdf41779c}, // 1e-275 * 2**1041 + {0xdd95317f31c7fa1d, 0x40405643d711d583}, // 1e-274 * 2**1038 + {0x8a7d3eef7f1cfc52, 0x482835ea666b2572}, // 1e-273 * 2**1034 + {0xad1c8eab5ee43b66, 0xda3243650005eecf}, // 1e-272 * 2**1031 + {0xd863b256369d4a40, 0x90bed43e40076a82}, // 1e-271 * 2**1028 + {0x873e4f75e2224e68, 0x5a7744a6e804a291}, // 1e-270 * 2**1024 + {0xa90de3535aaae202, 0x711515d0a205cb36}, // 1e-269 * 2**1021 + {0xd3515c2831559a83, 0x0d5a5b44ca873e03}, // 1e-268 * 2**1018 + {0x8412d9991ed58091, 0xe858790afe9486c2}, // 1e-267 * 2**1014 + {0xa5178fff668ae0b6, 0x626e974dbe39a872}, // 1e-266 * 2**1011 + {0xce5d73ff402d98e3, 0xfb0a3d212dc8128f}, // 1e-265 * 2**1008 + {0x80fa687f881c7f8e, 0x7ce66634bc9d0b99}, // 1e-264 * 2**1004 + {0xa139029f6a239f72, 0x1c1fffc1ebc44e80}, // 1e-263 * 2**1001 + {0xc987434744ac874e, 0xa327ffb266b56220}, // 1e-262 * 2**998 + {0xfbe9141915d7a922, 0x4bf1ff9f0062baa8}, // 1e-261 * 2**995 + {0x9d71ac8fada6c9b5, 0x6f773fc3603db4a9}, // 1e-260 * 2**991 + {0xc4ce17b399107c22, 0xcb550fb4384d21d3}, // 1e-259 * 2**988 + {0xf6019da07f549b2b, 0x7e2a53a146606a48}, // 1e-258 * 2**985 + {0x99c102844f94e0fb, 0x2eda7444cbfc426d}, // 1e-257 * 2**981 + {0xc0314325637a1939, 0xfa911155fefb5308}, // 1e-256 * 2**978 + {0xf03d93eebc589f88, 0x793555ab7eba27ca}, // 1e-255 * 2**975 + {0x96267c7535b763b5, 0x4bc1558b2f3458de}, // 1e-254 * 2**971 + {0xbbb01b9283253ca2, 0x9eb1aaedfb016f16}, // 1e-253 * 2**968 + {0xea9c227723ee8bcb, 0x465e15a979c1cadc}, // 1e-252 * 2**965 + {0x92a1958a7675175f, 0x0bfacd89ec191ec9}, // 1e-251 * 2**961 + {0xb749faed14125d36, 0xcef980ec671f667b}, // 1e-250 * 2**958 + {0xe51c79a85916f484, 0x82b7e12780e7401a}, // 1e-249 * 2**955 + {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908810}, // 1e-248 * 2**951 + {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa15}, // 1e-247 * 2**948 + {0xdfbdcece67006ac9, 0x67a791e093e1d49a}, // 1e-246 * 2**945 + {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e0}, // 1e-245 * 2**941 + {0xaecc49914078536d, 0x58fae9f773886e18}, // 1e-244 * 2**938 + {0xda7f5bf590966848, 0xaf39a475506a899e}, // 1e-243 * 2**935 + {0x888f99797a5e012d, 0x6d8406c952429603}, // 1e-242 * 2**931 + {0xaab37fd7d8f58178, 0xc8e5087ba6d33b83}, // 1e-241 * 2**928 + {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a64}, // 1e-240 * 2**925 + {0x855c3be0a17fcd26, 0x5cf2eea09a55067f}, // 1e-239 * 2**921 + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481e}, // 1e-238 * 2**918 + {0xd0601d8efc57b08b, 0xf13b94daf124da26}, // 1e-237 * 2**915 + {0x823c12795db6ce57, 0x76c53d08d6b70858}, // 1e-236 * 2**911 + {0xa2cb1717b52481ed, 0x54768c4b0c64ca6e}, // 1e-235 * 2**908 + {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd09}, // 1e-234 * 2**905 + {0xfe5d54150b090b02, 0xd3f93b35435d7c4c}, // 1e-233 * 2**902 + {0x9efa548d26e5a6e1, 0xc47bc5014a1a6daf}, // 1e-232 * 2**898 + {0xc6b8e9b0709f109a, 0x359ab6419ca1091b}, // 1e-231 * 2**895 + {0xf867241c8cc6d4c0, 0xc30163d203c94b62}, // 1e-230 * 2**892 + {0x9b407691d7fc44f8, 0x79e0de63425dcf1d}, // 1e-229 * 2**888 + {0xc21094364dfb5636, 0x985915fc12f542e4}, // 1e-228 * 2**885 + {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939d}, // 1e-227 * 2**882 + {0x979cf3ca6cec5b5a, 0xa705992ceecf9c42}, // 1e-226 * 2**878 + {0xbd8430bd08277231, 0x50c6ff782a838353}, // 1e-225 * 2**875 + {0xece53cec4a314ebd, 0xa4f8bf5635246428}, // 1e-224 * 2**872 + {0x940f4613ae5ed136, 0x871b7795e136be99}, // 1e-223 * 2**868 + {0xb913179899f68584, 0x28e2557b59846e3f}, // 1e-222 * 2**865 + {0xe757dd7ec07426e5, 0x331aeada2fe589cf}, // 1e-221 * 2**862 + {0x9096ea6f3848984f, 0x3ff0d2c85def7621}, // 1e-220 * 2**858 + {0xb4bca50b065abe63, 0x0fed077a756b53a9}, // 1e-219 * 2**855 + {0xe1ebce4dc7f16dfb, 0xd3e8495912c62894}, // 1e-218 * 2**852 + {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95c}, // 1e-217 * 2**848 + {0xb080392cc4349dec, 0xbd8d794d96aacfb3}, // 1e-216 * 2**845 + {0xdca04777f541c567, 0xecf0d7a0fc5583a0}, // 1e-215 * 2**842 + {0x89e42caaf9491b60, 0xf41686c49db57244}, // 1e-214 * 2**838 + {0xac5d37d5b79b6239, 0x311c2875c522ced5}, // 1e-213 * 2**835 + {0xd77485cb25823ac7, 0x7d633293366b828b}, // 1e-212 * 2**832 + {0x86a8d39ef77164bc, 0xae5dff9c02033197}, // 1e-211 * 2**828 + {0xa8530886b54dbdeb, 0xd9f57f830283fdfc}, // 1e-210 * 2**825 + {0xd267caa862a12d66, 0xd072df63c324fd7b}, // 1e-209 * 2**822 + {0x8380dea93da4bc60, 0x4247cb9e59f71e6d}, // 1e-208 * 2**818 + {0xa46116538d0deb78, 0x52d9be85f074e608}, // 1e-207 * 2**815 + {0xcd795be870516656, 0x67902e276c921f8b}, // 1e-206 * 2**812 + {0x806bd9714632dff6, 0x00ba1cd8a3db53b6}, // 1e-205 * 2**808 + {0xa086cfcd97bf97f3, 0x80e8a40eccd228a4}, // 1e-204 * 2**805 + {0xc8a883c0fdaf7df0, 0x6122cd128006b2cd}, // 1e-203 * 2**802 + {0xfad2a4b13d1b5d6c, 0x796b805720085f81}, // 1e-202 * 2**799 + {0x9cc3a6eec6311a63, 0xcbe3303674053bb0}, // 1e-201 * 2**795 + {0xc3f490aa77bd60fc, 0xbedbfc4411068a9c}, // 1e-200 * 2**792 + {0xf4f1b4d515acb93b, 0xee92fb5515482d44}, // 1e-199 * 2**789 + {0x991711052d8bf3c5, 0x751bdd152d4d1c4a}, // 1e-198 * 2**785 + {0xbf5cd54678eef0b6, 0xd262d45a78a0635d}, // 1e-197 * 2**782 + {0xef340a98172aace4, 0x86fb897116c87c34}, // 1e-196 * 2**779 + {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da0}, // 1e-195 * 2**775 + {0xbae0a846d2195712, 0x8974836059cca109}, // 1e-194 * 2**772 + {0xe998d258869facd7, 0x2bd1a438703fc94b}, // 1e-193 * 2**769 + {0x91ff83775423cc06, 0x7b6306a34627ddcf}, // 1e-192 * 2**765 + {0xb67f6455292cbf08, 0x1a3bc84c17b1d542}, // 1e-191 * 2**762 + {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a93}, // 1e-190 * 2**759 + {0x8e938662882af53e, 0x547eb47b7282ee9c}, // 1e-189 * 2**755 + {0xb23867fb2a35b28d, 0xe99e619a4f23aa43}, // 1e-188 * 2**752 + {0xdec681f9f4c31f31, 0x6405fa00e2ec94d4}, // 1e-187 * 2**749 + {0x8b3c113c38f9f37e, 0xde83bc408dd3dd04}, // 1e-186 * 2**745 + {0xae0b158b4738705e, 0x9624ab50b148d445}, // 1e-185 * 2**742 + {0xd98ddaee19068c76, 0x3badd624dd9b0957}, // 1e-184 * 2**739 + {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d6}, // 1e-183 * 2**735 + {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4c}, // 1e-182 * 2**732 + {0xd47487cc8470652b, 0x7647c3200069671f}, // 1e-181 * 2**729 + {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e073}, // 1e-180 * 2**725 + {0xa5fb0a17c777cf09, 0xf468107100525890}, // 1e-179 * 2**722 + {0xcf79cc9db955c2cc, 0x7182148d4066eeb4}, // 1e-178 * 2**719 + {0x81ac1fe293d599bf, 0xc6f14cd848405530}, // 1e-177 * 2**715 + {0xa21727db38cb002f, 0xb8ada00e5a506a7c}, // 1e-176 * 2**712 + {0xca9cf1d206fdc03b, 0xa6d90811f0e4851c}, // 1e-175 * 2**709 + {0xfd442e4688bd304a, 0x908f4a166d1da663}, // 1e-174 * 2**706 + {0x9e4a9cec15763e2e, 0x9a598e4e043287fe}, // 1e-173 * 2**702 + {0xc5dd44271ad3cdba, 0x40eff1e1853f29fd}, // 1e-172 * 2**699 + {0xf7549530e188c128, 0xd12bee59e68ef47c}, // 1e-171 * 2**696 + {0x9a94dd3e8cf578b9, 0x82bb74f8301958ce}, // 1e-170 * 2**692 + {0xc13a148e3032d6e7, 0xe36a52363c1faf01}, // 1e-169 * 2**689 + {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac1}, // 1e-168 * 2**686 + {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0b9}, // 1e-167 * 2**682 + {0xbcb2b812db11a5de, 0x7415d448f6b6f0e7}, // 1e-166 * 2**679 + {0xebdf661791d60f56, 0x111b495b3464ad21}, // 1e-165 * 2**676 + {0x936b9fcebb25c995, 0xcab10dd900beec34}, // 1e-164 * 2**672 + {0xb84687c269ef3bfb, 0x3d5d514f40eea742}, // 1e-163 * 2**669 + {0xe65829b3046b0afa, 0x0cb4a5a3112a5112}, // 1e-162 * 2**666 + {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ab}, // 1e-161 * 2**662 + {0xb3f4e093db73a093, 0x59ed216765690f56}, // 1e-160 * 2**659 + {0xe0f218b8d25088b8, 0x306869c13ec3532c}, // 1e-159 * 2**656 + {0x8c974f7383725573, 0x1e414218c73a13fb}, // 1e-158 * 2**652 + {0xafbd2350644eeacf, 0xe5d1929ef90898fa}, // 1e-157 * 2**649 + {0xdbac6c247d62a583, 0xdf45f746b74abf39}, // 1e-156 * 2**646 + {0x894bc396ce5da772, 0x6b8bba8c328eb783}, // 1e-155 * 2**642 + {0xab9eb47c81f5114f, 0x066ea92f3f326564}, // 1e-154 * 2**639 + {0xd686619ba27255a2, 0xc80a537b0efefebd}, // 1e-153 * 2**636 + {0x8613fd0145877585, 0xbd06742ce95f5f36}, // 1e-152 * 2**632 + {0xa798fc4196e952e7, 0x2c48113823b73704}, // 1e-151 * 2**629 + {0xd17f3b51fca3a7a0, 0xf75a15862ca504c5}, // 1e-150 * 2**626 + {0x82ef85133de648c4, 0x9a984d73dbe722fb}, // 1e-149 * 2**622 + {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebba}, // 1e-148 * 2**619 + {0xcc963fee10b7d1b3, 0x318df905079926a8}, // 1e-147 * 2**616 + {0xffbbcfe994e5c61f, 0xfdf17746497f7052}, // 1e-146 * 2**613 + {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa633}, // 1e-145 * 2**609 + {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc0}, // 1e-144 * 2**606 + {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b0}, // 1e-143 * 2**603 + {0x9c1661a651213e2d, 0x06bea10ca65c084e}, // 1e-142 * 2**599 + {0xc31bfa0fe5698db8, 0x486e494fcff30a62}, // 1e-141 * 2**596 + {0xf3e2f893dec3f126, 0x5a89dba3c3efccfa}, // 1e-140 * 2**593 + {0x986ddb5c6b3a76b7, 0xf89629465a75e01c}, // 1e-139 * 2**589 + {0xbe89523386091465, 0xf6bbb397f1135823}, // 1e-138 * 2**586 + {0xee2ba6c0678b597f, 0x746aa07ded582e2c}, // 1e-137 * 2**583 + {0x94db483840b717ef, 0xa8c2a44eb4571cdc}, // 1e-136 * 2**579 + {0xba121a4650e4ddeb, 0x92f34d62616ce413}, // 1e-135 * 2**576 + {0xe896a0d7e51e1566, 0x77b020baf9c81d17}, // 1e-134 * 2**573 + {0x915e2486ef32cd60, 0x0ace1474dc1d122e}, // 1e-133 * 2**569 + {0xb5b5ada8aaff80b8, 0x0d819992132456ba}, // 1e-132 * 2**566 + {0xe3231912d5bf60e6, 0x10e1fff697ed6c69}, // 1e-131 * 2**563 + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c1}, // 1e-130 * 2**559 + {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb2}, // 1e-129 * 2**556 + {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbde}, // 1e-128 * 2**553 + {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96b}, // 1e-127 * 2**549 + {0xad4ab7112eb3929d, 0x86c16c98d2c953c6}, // 1e-126 * 2**546 + {0xd89d64d57a607744, 0xe871c7bf077ba8b7}, // 1e-125 * 2**543 + {0x87625f056c7c4a8b, 0x11471cd764ad4972}, // 1e-124 * 2**539 + {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bcf}, // 1e-123 * 2**536 + {0xd389b47879823479, 0x4aff1d108d4ec2c3}, // 1e-122 * 2**533 + {0x843610cb4bf160cb, 0xcedf722a585139ba}, // 1e-121 * 2**529 + {0xa54394fe1eedb8fe, 0xc2974eb4ee658828}, // 1e-120 * 2**526 + {0xce947a3da6a9273e, 0x733d226229feea32}, // 1e-119 * 2**523 + {0x811ccc668829b887, 0x0806357d5a3f525f}, // 1e-118 * 2**519 + {0xa163ff802a3426a8, 0xca07c2dcb0cf26f7}, // 1e-117 * 2**516 + {0xc9bcff6034c13052, 0xfc89b393dd02f0b5}, // 1e-116 * 2**513 + {0xfc2c3f3841f17c67, 0xbbac2078d443ace2}, // 1e-115 * 2**510 + {0x9d9ba7832936edc0, 0xd54b944b84aa4c0d}, // 1e-114 * 2**506 + {0xc5029163f384a931, 0x0a9e795e65d4df11}, // 1e-113 * 2**503 + {0xf64335bcf065d37d, 0x4d4617b5ff4a16d5}, // 1e-112 * 2**500 + {0x99ea0196163fa42e, 0x504bced1bf8e4e45}, // 1e-111 * 2**496 + {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d6}, // 1e-110 * 2**493 + {0xf07da27a82c37088, 0x5d767327bb4e5a4c}, // 1e-109 * 2**490 + {0x964e858c91ba2655, 0x3a6a07f8d510f86f}, // 1e-108 * 2**486 + {0xbbe226efb628afea, 0x890489f70a55368b}, // 1e-107 * 2**483 + {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842e}, // 1e-106 * 2**480 + {0x92c8ae6b464fc96f, 0x3b0b8bc90012929d}, // 1e-105 * 2**476 + {0xb77ada0617e3bbcb, 0x09ce6ebb40173744}, // 1e-104 * 2**473 + {0xe55990879ddcaabd, 0xcc420a6a101d0515}, // 1e-103 * 2**470 + {0x8f57fa54c2a9eab6, 0x9fa946824a12232d}, // 1e-102 * 2**466 + {0xb32df8e9f3546564, 0x47939822dc96abf9}, // 1e-101 * 2**463 + {0xdff9772470297ebd, 0x59787e2b93bc56f7}, // 1e-100 * 2**460 + {0x8bfbea76c619ef36, 0x57eb4edb3c55b65a}, // 1e-99 * 2**456 + {0xaefae51477a06b03, 0xede622920b6b23f1}, // 1e-98 * 2**453 + {0xdab99e59958885c4, 0xe95fab368e45eced}, // 1e-97 * 2**450 + {0x88b402f7fd75539b, 0x11dbcb0218ebb414}, // 1e-96 * 2**446 + {0xaae103b5fcd2a881, 0xd652bdc29f26a119}, // 1e-95 * 2**443 + {0xd59944a37c0752a2, 0x4be76d3346f0495f}, // 1e-94 * 2**440 + {0x857fcae62d8493a5, 0x6f70a4400c562ddb}, // 1e-93 * 2**436 + {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb952}, // 1e-92 * 2**433 + {0xd097ad07a71f26b2, 0x7e2000a41346a7a7}, // 1e-91 * 2**430 + {0x825ecc24c873782f, 0x8ed400668c0c28c8}, // 1e-90 * 2**426 + {0xa2f67f2dfa90563b, 0x728900802f0f32fa}, // 1e-89 * 2**423 + {0xcbb41ef979346bca, 0x4f2b40a03ad2ffb9}, // 1e-88 * 2**420 + {0xfea126b7d78186bc, 0xe2f610c84987bfa8}, // 1e-87 * 2**417 + {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7c9}, // 1e-86 * 2**413 + {0xc6ede63fa05d3143, 0x91503d1c79720dbb}, // 1e-85 * 2**410 + {0xf8a95fcf88747d94, 0x75a44c6397ce912a}, // 1e-84 * 2**407 + {0x9b69dbe1b548ce7c, 0xc986afbe3ee11aba}, // 1e-83 * 2**403 + {0xc24452da229b021b, 0xfbe85badce996168}, // 1e-82 * 2**400 + {0xf2d56790ab41c2a2, 0xfae27299423fb9c3}, // 1e-81 * 2**397 + {0x97c560ba6b0919a5, 0xdccd879fc967d41a}, // 1e-80 * 2**393 + {0xbdb6b8e905cb600f, 0x5400e987bbc1c920}, // 1e-79 * 2**390 + {0xed246723473e3813, 0x290123e9aab23b68}, // 1e-78 * 2**387 + {0x9436c0760c86e30b, 0xf9a0b6720aaf6521}, // 1e-77 * 2**383 + {0xb94470938fa89bce, 0xf808e40e8d5b3e69}, // 1e-76 * 2**380 + {0xe7958cb87392c2c2, 0xb60b1d1230b20e04}, // 1e-75 * 2**377 + {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c2}, // 1e-74 * 2**373 + {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af3}, // 1e-73 * 2**370 + {0xe2280b6c20dd5232, 0x25c6da63c38de1b0}, // 1e-72 * 2**367 + {0x8d590723948a535f, 0x579c487e5a38ad0e}, // 1e-71 * 2**363 + {0xb0af48ec79ace837, 0x2d835a9df0c6d851}, // 1e-70 * 2**360 + {0xdcdb1b2798182244, 0xf8e431456cf88e65}, // 1e-69 * 2**357 + {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b58ff}, // 1e-68 * 2**353 + {0xac8b2d36eed2dac5, 0xe272467e3d222f3f}, // 1e-67 * 2**350 + {0xd7adf884aa879177, 0x5b0ed81dcc6abb0f}, // 1e-66 * 2**347 + {0x86ccbb52ea94baea, 0x98e947129fc2b4e9}, // 1e-65 * 2**343 + {0xa87fea27a539e9a5, 0x3f2398d747b36224}, // 1e-64 * 2**340 + {0xd29fe4b18e88640e, 0x8eec7f0d19a03aad}, // 1e-63 * 2**337 + {0x83a3eeeef9153e89, 0x1953cf68300424ac}, // 1e-62 * 2**333 + {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd7}, // 1e-61 * 2**330 + {0xcdb02555653131b6, 0x3792f412cb06794d}, // 1e-60 * 2**327 + {0x808e17555f3ebf11, 0xe2bbd88bbee40bd0}, // 1e-59 * 2**323 + {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec4}, // 1e-58 * 2**320 + {0xc8de047564d20a8b, 0xf245825a5a445275}, // 1e-57 * 2**317 + {0xfb158592be068d2e, 0xeed6e2f0f0d56712}, // 1e-56 * 2**314 + {0x9ced737bb6c4183d, 0x55464dd69685606b}, // 1e-55 * 2**310 + {0xc428d05aa4751e4c, 0xaa97e14c3c26b886}, // 1e-54 * 2**307 + {0xf53304714d9265df, 0xd53dd99f4b3066a8}, // 1e-53 * 2**304 + {0x993fe2c6d07b7fab, 0xe546a8038efe4029}, // 1e-52 * 2**300 + {0xbf8fdb78849a5f96, 0xde98520472bdd033}, // 1e-51 * 2**297 + {0xef73d256a5c0f77c, 0x963e66858f6d4440}, // 1e-50 * 2**294 + {0x95a8637627989aad, 0xdde7001379a44aa8}, // 1e-49 * 2**290 + {0xbb127c53b17ec159, 0x5560c018580d5d52}, // 1e-48 * 2**287 + {0xe9d71b689dde71af, 0xaab8f01e6e10b4a6}, // 1e-47 * 2**284 + {0x9226712162ab070d, 0xcab3961304ca70e8}, // 1e-46 * 2**280 + {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d22}, // 1e-45 * 2**277 + {0xe45c10c42a2b3b05, 0x8cb89a7db77c506a}, // 1e-44 * 2**274 + {0x8eb98a7a9a5b04e3, 0x77f3608e92adb242}, // 1e-43 * 2**270 + {0xb267ed1940f1c61c, 0x55f038b237591ed3}, // 1e-42 * 2**267 + {0xdf01e85f912e37a3, 0x6b6c46dec52f6688}, // 1e-41 * 2**264 + {0x8b61313bbabce2c6, 0x2323ac4b3b3da015}, // 1e-40 * 2**260 + {0xae397d8aa96c1b77, 0xabec975e0a0d081a}, // 1e-39 * 2**257 + {0xd9c7dced53c72255, 0x96e7bd358c904a21}, // 1e-38 * 2**254 + {0x881cea14545c7575, 0x7e50d64177da2e54}, // 1e-37 * 2**250 + {0xaa242499697392d2, 0xdde50bd1d5d0b9e9}, // 1e-36 * 2**247 + {0xd4ad2dbfc3d07787, 0x955e4ec64b44e864}, // 1e-35 * 2**244 + {0x84ec3c97da624ab4, 0xbd5af13bef0b113e}, // 1e-34 * 2**240 + {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58e}, // 1e-33 * 2**237 + {0xcfb11ead453994ba, 0x67de18eda5814af2}, // 1e-32 * 2**234 + {0x81ceb32c4b43fcf4, 0x80eacf948770ced7}, // 1e-31 * 2**230 + {0xa2425ff75e14fc31, 0xa1258379a94d028d}, // 1e-30 * 2**227 + {0xcad2f7f5359a3b3e, 0x096ee45813a04330}, // 1e-29 * 2**224 + {0xfd87b5f28300ca0d, 0x8bca9d6e188853fc}, // 1e-28 * 2**221 + {0x9e74d1b791e07e48, 0x775ea264cf55347d}, // 1e-27 * 2**217 + {0xc612062576589dda, 0x95364afe032a819d}, // 1e-26 * 2**214 + {0xf79687aed3eec551, 0x3a83ddbd83f52204}, // 1e-25 * 2**211 + {0x9abe14cd44753b52, 0xc4926a9672793542}, // 1e-24 * 2**207 + {0xc16d9a0095928a27, 0x75b7053c0f178293}, // 1e-23 * 2**204 + {0xf1c90080baf72cb1, 0x5324c68b12dd6338}, // 1e-22 * 2**201 + {0x971da05074da7bee, 0xd3f6fc16ebca5e03}, // 1e-21 * 2**197 + {0xbce5086492111aea, 0x88f4bb1ca6bcf584}, // 1e-20 * 2**194 + {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e5}, // 1e-19 * 2**191 + {0x9392ee8e921d5d07, 0x3aff322e62439fcf}, // 1e-18 * 2**187 + {0xb877aa3236a4b449, 0x09befeb9fad487c2}, // 1e-17 * 2**184 + {0xe69594bec44de15b, 0x4c2ebe687989a9b3}, // 1e-16 * 2**181 + {0x901d7cf73ab0acd9, 0x0f9d37014bf60a10}, // 1e-15 * 2**177 + {0xb424dc35095cd80f, 0x538484c19ef38c94}, // 1e-14 * 2**174 + {0xe12e13424bb40e13, 0x2865a5f206b06fb9}, // 1e-13 * 2**171 + {0x8cbccc096f5088cb, 0xf93f87b7442e45d3}, // 1e-12 * 2**167 + {0xafebff0bcb24aafe, 0xf78f69a51539d748}, // 1e-11 * 2**164 + {0xdbe6fecebdedd5be, 0xb573440e5a884d1b}, // 1e-10 * 2**161 + {0x89705f4136b4a597, 0x31680a88f8953030}, // 1e-9 * 2**157 + {0xabcc77118461cefc, 0xfdc20d2b36ba7c3d}, // 1e-8 * 2**154 + {0xd6bf94d5e57a42bc, 0x3d32907604691b4c}, // 1e-7 * 2**151 + {0x8637bd05af6c69b5, 0xa63f9a49c2c1b10f}, // 1e-6 * 2**147 + {0xa7c5ac471b478423, 0x0fcf80dc33721d53}, // 1e-5 * 2**144 + {0xd1b71758e219652b, 0xd3c36113404ea4a8}, // 1e-4 * 2**141 + {0x83126e978d4fdf3b, 0x645a1cac083126e9}, // 1e-3 * 2**137 + {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a3}, // 1e-2 * 2**134 + {0xcccccccccccccccc, 0xcccccccccccccccc}, // 1e-1 * 2**131 + {0x8000000000000000, 0x0000000000000000}, // 1e0 * 2**127 + {0xa000000000000000, 0x0000000000000000}, // 1e1 * 2**124 + {0xc800000000000000, 0x0000000000000000}, // 1e2 * 2**121 + {0xfa00000000000000, 0x0000000000000000}, // 1e3 * 2**118 + {0x9c40000000000000, 0x0000000000000000}, // 1e4 * 2**114 + {0xc350000000000000, 0x0000000000000000}, // 1e5 * 2**111 + {0xf424000000000000, 0x0000000000000000}, // 1e6 * 2**108 + {0x9896800000000000, 0x0000000000000000}, // 1e7 * 2**104 + {0xbebc200000000000, 0x0000000000000000}, // 1e8 * 2**101 + {0xee6b280000000000, 0x0000000000000000}, // 1e9 * 2**98 + {0x9502f90000000000, 0x0000000000000000}, // 1e10 * 2**94 + {0xba43b74000000000, 0x0000000000000000}, // 1e11 * 2**91 + {0xe8d4a51000000000, 0x0000000000000000}, // 1e12 * 2**88 + {0x9184e72a00000000, 0x0000000000000000}, // 1e13 * 2**84 + {0xb5e620f480000000, 0x0000000000000000}, // 1e14 * 2**81 + {0xe35fa931a0000000, 0x0000000000000000}, // 1e15 * 2**78 + {0x8e1bc9bf04000000, 0x0000000000000000}, // 1e16 * 2**74 + {0xb1a2bc2ec5000000, 0x0000000000000000}, // 1e17 * 2**71 + {0xde0b6b3a76400000, 0x0000000000000000}, // 1e18 * 2**68 + {0x8ac7230489e80000, 0x0000000000000000}, // 1e19 * 2**64 + {0xad78ebc5ac620000, 0x0000000000000000}, // 1e20 * 2**61 + {0xd8d726b7177a8000, 0x0000000000000000}, // 1e21 * 2**58 + {0x878678326eac9000, 0x0000000000000000}, // 1e22 * 2**54 + {0xa968163f0a57b400, 0x0000000000000000}, // 1e23 * 2**51 + {0xd3c21bcecceda100, 0x0000000000000000}, // 1e24 * 2**48 + {0x84595161401484a0, 0x0000000000000000}, // 1e25 * 2**44 + {0xa56fa5b99019a5c8, 0x0000000000000000}, // 1e26 * 2**41 + {0xcecb8f27f4200f3a, 0x0000000000000000}, // 1e27 * 2**38 + {0x813f3978f8940984, 0x4000000000000000}, // 1e28 * 2**34 + {0xa18f07d736b90be5, 0x5000000000000000}, // 1e29 * 2**31 + {0xc9f2c9cd04674ede, 0xa400000000000000}, // 1e30 * 2**28 + {0xfc6f7c4045812296, 0x4d00000000000000}, // 1e31 * 2**25 + {0x9dc5ada82b70b59d, 0xf020000000000000}, // 1e32 * 2**21 + {0xc5371912364ce305, 0x6c28000000000000}, // 1e33 * 2**18 + {0xf684df56c3e01bc6, 0xc732000000000000}, // 1e34 * 2**15 + {0x9a130b963a6c115c, 0x3c7f400000000000}, // 1e35 * 2**11 + {0xc097ce7bc90715b3, 0x4b9f100000000000}, // 1e36 * 2**8 + {0xf0bdc21abb48db20, 0x1e86d40000000000}, // 1e37 * 2**5 + {0x96769950b50d88f4, 0x1314448000000000}, // 1e38 * 2**1 + {0xbc143fa4e250eb31, 0x17d955a000000000}, // 1e39 * 2**-2 + {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, // 1e40 * 2**-5 + {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, // 1e41 * 2**-9 + {0xb7abc627050305ad, 0xf14a3d9e40000000}, // 1e42 * 2**-12 + {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, // 1e43 * 2**-15 + {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, // 1e44 * 2**-19 + {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, // 1e45 * 2**-22 + {0xe0352f62a19e306e, 0xd50b2037ad200000}, // 1e46 * 2**-25 + {0x8c213d9da502de45, 0x4526f422cc340000}, // 1e47 * 2**-29 + {0xaf298d050e4395d6, 0x9670b12b7f410000}, // 1e48 * 2**-32 + {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, // 1e49 * 2**-35 + {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, // 1e50 * 2**-39 + {0xab0e93b6efee0053, 0x8eea0d047a457a00}, // 1e51 * 2**-42 + {0xd5d238a4abe98068, 0x72a4904598d6d880}, // 1e52 * 2**-45 + {0x85a36366eb71f041, 0x47a6da2b7f864750}, // 1e53 * 2**-49 + {0xa70c3c40a64e6c51, 0x999090b65f67d924}, // 1e54 * 2**-52 + {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, // 1e55 * 2**-55 + {0x82818f1281ed449f, 0xbff8f10e7a8921a4}, // 1e56 * 2**-59 + {0xa321f2d7226895c7, 0xaff72d52192b6a0d}, // 1e57 * 2**-62 + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490}, // 1e58 * 2**-65 + {0xfee50b7025c36a08, 0x02f236d04753d5b4}, // 1e59 * 2**-68 + {0x9f4f2726179a2245, 0x01d762422c946590}, // 1e60 * 2**-72 + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5}, // 1e61 * 2**-75 + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2}, // 1e62 * 2**-78 + {0x9b934c3b330c8577, 0x63cc55f49f88eb2f}, // 1e63 * 2**-82 + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb}, // 1e64 * 2**-85 + {0xf316271c7fc3908a, 0x8bef464e3945ef7a}, // 1e65 * 2**-88 + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac}, // 1e66 * 2**-92 + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317}, // 1e67 * 2**-95 + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd}, // 1e68 * 2**-98 + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a}, // 1e69 * 2**-102 + {0xb975d6b6ee39e436, 0xb3e2fd538e122b44}, // 1e70 * 2**-105 + {0xe7d34c64a9c85d44, 0x60dbbca87196b616}, // 1e71 * 2**-108 + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd}, // 1e72 * 2**-112 + {0xb51d13aea4a488dd, 0x6babab6398bdbe41}, // 1e73 * 2**-115 + {0xe264589a4dcdab14, 0xc696963c7eed2dd1}, // 1e74 * 2**-118 + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2}, // 1e75 * 2**-122 + {0xb0de65388cc8ada8, 0x3b25a55f43294bcb}, // 1e76 * 2**-125 + {0xdd15fe86affad912, 0x49ef0eb713f39ebe}, // 1e77 * 2**-128 + {0x8a2dbf142dfcc7ab, 0x6e3569326c784337}, // 1e78 * 2**-132 + {0xacb92ed9397bf996, 0x49c2c37f07965404}, // 1e79 * 2**-135 + {0xd7e77a8f87daf7fb, 0xdc33745ec97be906}, // 1e80 * 2**-138 + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3}, // 1e81 * 2**-142 + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c}, // 1e82 * 2**-145 + {0xd2d80db02aabd62b, 0xf50a3fa490c30190}, // 1e83 * 2**-148 + {0x83c7088e1aab65db, 0x792667c6da79e0fa}, // 1e84 * 2**-152 + {0xa4b8cab1a1563f52, 0x577001b891185938}, // 1e85 * 2**-155 + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86}, // 1e86 * 2**-158 + {0x80b05e5ac60b6178, 0x544f8158315b05b4}, // 1e87 * 2**-162 + {0xa0dc75f1778e39d6, 0x696361ae3db1c721}, // 1e88 * 2**-165 + {0xc913936dd571c84c, 0x03bc3a19cd1e38e9}, // 1e89 * 2**-168 + {0xfb5878494ace3a5f, 0x04ab48a04065c723}, // 1e90 * 2**-171 + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76}, // 1e91 * 2**-175 + {0xc45d1df942711d9a, 0x3ba5d0bd324f8394}, // 1e92 * 2**-178 + {0xf5746577930d6500, 0xca8f44ec7ee36479}, // 1e93 * 2**-181 + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb}, // 1e94 * 2**-185 + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e}, // 1e95 * 2**-188 + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e}, // 1e96 * 2**-191 + {0x95d04aee3b80ece5, 0xbba1f1d158724a12}, // 1e97 * 2**-195 + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97}, // 1e98 * 2**-198 + {0xea1575143cf97226, 0xf52d09d71a3293bd}, // 1e99 * 2**-201 + {0x924d692ca61be758, 0x593c2626705f9c56}, // 1e100 * 2**-205 + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c}, // 1e101 * 2**-208 + {0xe498f455c38b997a, 0x0b6dfb9c0f956447}, // 1e102 * 2**-211 + {0x8edf98b59a373fec, 0x4724bd4189bd5eac}, // 1e103 * 2**-215 + {0xb2977ee300c50fe7, 0x58edec91ec2cb657}, // 1e104 * 2**-218 + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed}, // 1e105 * 2**-221 + {0x8b865b215899f46c, 0xbd79e0d20082ee74}, // 1e106 * 2**-225 + {0xae67f1e9aec07187, 0xecd8590680a3aa11}, // 1e107 * 2**-228 + {0xda01ee641a708de9, 0xe80e6f4820cc9495}, // 1e108 * 2**-231 + {0x884134fe908658b2, 0x3109058d147fdcdd}, // 1e109 * 2**-235 + {0xaa51823e34a7eede, 0xbd4b46f0599fd415}, // 1e110 * 2**-238 + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a}, // 1e111 * 2**-241 + {0x850fadc09923329e, 0x03e2cf6bc604ddb0}, // 1e112 * 2**-245 + {0xa6539930bf6bff45, 0x84db8346b786151c}, // 1e113 * 2**-248 + {0xcfe87f7cef46ff16, 0xe612641865679a63}, // 1e114 * 2**-251 + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e}, // 1e115 * 2**-255 + {0xa26da3999aef7749, 0xe3be5e330f38f09d}, // 1e116 * 2**-258 + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5}, // 1e117 * 2**-261 + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6}, // 1e118 * 2**-264 + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa}, // 1e119 * 2**-268 + {0xc646d63501a1511d, 0xb281e1fd541501b8}, // 1e120 * 2**-271 + {0xf7d88bc24209a565, 0x1f225a7ca91a4226}, // 1e121 * 2**-274 + {0x9ae757596946075f, 0x3375788de9b06958}, // 1e122 * 2**-278 + {0xc1a12d2fc3978937, 0x0052d6b1641c83ae}, // 1e123 * 2**-281 + {0xf209787bb47d6b84, 0xc0678c5dbd23a49a}, // 1e124 * 2**-284 + {0x9745eb4d50ce6332, 0xf840b7ba963646e0}, // 1e125 * 2**-288 + {0xbd176620a501fbff, 0xb650e5a93bc3d898}, // 1e126 * 2**-291 + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe}, // 1e127 * 2**-294 + {0x93ba47c980e98cdf, 0xc66f336c36b10137}, // 1e128 * 2**-298 + {0xb8a8d9bbe123f017, 0xb80b0047445d4184}, // 1e129 * 2**-301 + {0xe6d3102ad96cec1d, 0xa60dc059157491e5}, // 1e130 * 2**-304 + {0x9043ea1ac7e41392, 0x87c89837ad68db2f}, // 1e131 * 2**-308 + {0xb454e4a179dd1877, 0x29babe4598c311fb}, // 1e132 * 2**-311 + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a}, // 1e133 * 2**-314 + {0x8ce2529e2734bb1d, 0x1899e4a65f58660c}, // 1e134 * 2**-318 + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f}, // 1e135 * 2**-321 + {0xdc21a1171d42645d, 0x76707543f4fa1f73}, // 1e136 * 2**-324 + {0x899504ae72497eba, 0x6a06494a791c53a8}, // 1e137 * 2**-328 + {0xabfa45da0edbde69, 0x0487db9d17636892}, // 1e138 * 2**-331 + {0xd6f8d7509292d603, 0x45a9d2845d3c42b6}, // 1e139 * 2**-334 + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2}, // 1e140 * 2**-338 + {0xa7f26836f282b732, 0x8e6cac7768d7141e}, // 1e141 * 2**-341 + {0xd1ef0244af2364ff, 0x3207d795430cd926}, // 1e142 * 2**-344 + {0x8335616aed761f1f, 0x7f44e6bd49e807b8}, // 1e143 * 2**-348 + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6}, // 1e144 * 2**-351 + {0xcd036837130890a1, 0x36dba887c37a8c0f}, // 1e145 * 2**-354 + {0x802221226be55a64, 0xc2494954da2c9789}, // 1e146 * 2**-358 + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c}, // 1e147 * 2**-361 + {0xc83553c5c8965d3d, 0x6f92829494e5acc7}, // 1e148 * 2**-364 + {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9}, // 1e149 * 2**-367 + {0x9c69a97284b578d7, 0xff2a760414536efb}, // 1e150 * 2**-371 + {0xc38413cf25e2d70d, 0xfef5138519684aba}, // 1e151 * 2**-374 + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69}, // 1e152 * 2**-377 + {0x98bf2f79d5993802, 0xef2f773ffbd97a61}, // 1e153 * 2**-381 + {0xbeeefb584aff8603, 0xaafb550ffacfd8fa}, // 1e154 * 2**-384 + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38}, // 1e155 * 2**-387 + {0x952ab45cfa97a0b2, 0xdd945a747bf26183}, // 1e156 * 2**-391 + {0xba756174393d88df, 0x94f971119aeef9e4}, // 1e157 * 2**-394 + {0xe912b9d1478ceb17, 0x7a37cd5601aab85d}, // 1e158 * 2**-397 + {0x91abb422ccb812ee, 0xac62e055c10ab33a}, // 1e159 * 2**-401 + {0xb616a12b7fe617aa, 0x577b986b314d6009}, // 1e160 * 2**-404 + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b}, // 1e161 * 2**-407 + {0x8e41ade9fbebc27d, 0x14588f13be847307}, // 1e162 * 2**-411 + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8}, // 1e163 * 2**-414 + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb}, // 1e164 * 2**-417 + {0x8aec23d680043bee, 0x25de7bb9480d5854}, // 1e165 * 2**-421 + {0xada72ccc20054ae9, 0xaf561aa79a10ae6a}, // 1e166 * 2**-424 + {0xd910f7ff28069da4, 0x1b2ba1518094da04}, // 1e167 * 2**-427 + {0x87aa9aff79042286, 0x90fb44d2f05d0842}, // 1e168 * 2**-431 + {0xa99541bf57452b28, 0x353a1607ac744a53}, // 1e169 * 2**-434 + {0xd3fa922f2d1675f2, 0x42889b8997915ce8}, // 1e170 * 2**-437 + {0x847c9b5d7c2e09b7, 0x69956135febada11}, // 1e171 * 2**-441 + {0xa59bc234db398c25, 0x43fab9837e699095}, // 1e172 * 2**-444 + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb}, // 1e173 * 2**-447 + {0x8161afb94b44f57d, 0x1d1be0eebac278f5}, // 1e174 * 2**-451 + {0xa1ba1ba79e1632dc, 0x6462d92a69731732}, // 1e175 * 2**-454 + {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe}, // 1e176 * 2**-457 + {0xfcb2cb35e702af78, 0x5cda735244c3d43e}, // 1e177 * 2**-460 + {0x9defbf01b061adab, 0x3a0888136afa64a7}, // 1e178 * 2**-464 + {0xc56baec21c7a1916, 0x088aaa1845b8fdd0}, // 1e179 * 2**-467 + {0xf6c69a72a3989f5b, 0x8aad549e57273d45}, // 1e180 * 2**-470 + {0x9a3c2087a63f6399, 0x36ac54e2f678864b}, // 1e181 * 2**-474 + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd}, // 1e182 * 2**-477 + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5}, // 1e183 * 2**-480 + {0x969eb7c47859e743, 0x9f644ae5a4b1b325}, // 1e184 * 2**-484 + {0xbc4665b596706114, 0x873d5d9f0dde1fee}, // 1e185 * 2**-487 + {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea}, // 1e186 * 2**-490 + {0x9316ff75dd87cbd8, 0x09a7f12442d588f2}, // 1e187 * 2**-494 + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f}, // 1e188 * 2**-497 + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa}, // 1e189 * 2**-500 + {0x8fa475791a569d10, 0xf96e017d694487bc}, // 1e190 * 2**-504 + {0xb38d92d760ec4455, 0x37c981dcc395a9ac}, // 1e191 * 2**-507 + {0xe070f78d3927556a, 0x85bbe253f47b1417}, // 1e192 * 2**-510 + {0x8c469ab843b89562, 0x93956d7478ccec8e}, // 1e193 * 2**-514 + {0xaf58416654a6babb, 0x387ac8d1970027b2}, // 1e194 * 2**-517 + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e}, // 1e195 * 2**-520 + {0x88fcf317f22241e2, 0x441fece3bdf81f03}, // 1e196 * 2**-524 + {0xab3c2fddeeaad25a, 0xd527e81cad7626c3}, // 1e197 * 2**-527 + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074}, // 1e198 * 2**-530 + {0x85c7056562757456, 0xf6872d5667844e49}, // 1e199 * 2**-534 + {0xa738c6bebb12d16c, 0xb428f8ac016561db}, // 1e200 * 2**-537 + {0xd106f86e69d785c7, 0xe13336d701beba52}, // 1e201 * 2**-540 + {0x82a45b450226b39c, 0xecc0024661173473}, // 1e202 * 2**-544 + {0xa34d721642b06084, 0x27f002d7f95d0190}, // 1e203 * 2**-547 + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4}, // 1e204 * 2**-550 + {0xff290242c83396ce, 0x7e67047175a15271}, // 1e205 * 2**-553 + {0x9f79a169bd203e41, 0x0f0062c6e984d386}, // 1e206 * 2**-557 + {0xc75809c42c684dd1, 0x52c07b78a3e60868}, // 1e207 * 2**-560 + {0xf92e0c3537826145, 0xa7709a56ccdf8a82}, // 1e208 * 2**-563 + {0x9bbcc7a142b17ccb, 0x88a66076400bb691}, // 1e209 * 2**-567 + {0xc2abf989935ddbfe, 0x6acff893d00ea435}, // 1e210 * 2**-570 + {0xf356f7ebf83552fe, 0x0583f6b8c4124d43}, // 1e211 * 2**-573 + {0x98165af37b2153de, 0xc3727a337a8b704a}, // 1e212 * 2**-577 + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c}, // 1e213 * 2**-580 + {0xeda2ee1c7064130c, 0x1162def06f79df73}, // 1e214 * 2**-583 + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8}, // 1e215 * 2**-587 + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692}, // 1e216 * 2**-590 + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437}, // 1e217 * 2**-593 + {0x910ab1d4db9914a0, 0x1d9c9892400a22a2}, // 1e218 * 2**-597 + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b}, // 1e219 * 2**-600 + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d}, // 1e220 * 2**-603 + {0x8da471a9de737e24, 0x5ceaecfed289e5d2}, // 1e221 * 2**-607 + {0xb10d8e1456105dad, 0x7425a83e872c5f47}, // 1e222 * 2**-610 + {0xdd50f1996b947518, 0xd12f124e28f77719}, // 1e223 * 2**-613 + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f}, // 1e224 * 2**-617 + {0xace73cbfdc0bfb7b, 0x636cc64d1001550b}, // 1e225 * 2**-620 + {0xd8210befd30efa5a, 0x3c47f7e05401aa4e}, // 1e226 * 2**-623 + {0x8714a775e3e95c78, 0x65acfaec34810a71}, // 1e227 * 2**-627 + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d}, // 1e228 * 2**-630 + {0xd31045a8341ca07c, 0x1ede48111209a050}, // 1e229 * 2**-633 + {0x83ea2b892091e44d, 0x934aed0aab460432}, // 1e230 * 2**-637 + {0xa4e4b66b68b65d60, 0xf81da84d5617853f}, // 1e231 * 2**-640 + {0xce1de40642e3f4b9, 0x36251260ab9d668e}, // 1e232 * 2**-643 + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019}, // 1e233 * 2**-647 + {0xa1075a24e4421730, 0xb24cf65b8612f81f}, // 1e234 * 2**-650 + {0xc94930ae1d529cfc, 0xdee033f26797b627}, // 1e235 * 2**-653 + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1}, // 1e236 * 2**-656 + {0x9d412e0806e88aa5, 0x8e1f289560ee864e}, // 1e237 * 2**-660 + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2}, // 1e238 * 2**-663 + {0xf5b5d7ec8acb58a2, 0xae10af696774b1db}, // 1e239 * 2**-666 + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29}, // 1e240 * 2**-670 + {0xbff610b0cc6edd3f, 0x17fd090a58d32af3}, // 1e241 * 2**-673 + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0}, // 1e242 * 2**-676 + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e}, // 1e243 * 2**-680 + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1}, // 1e244 * 2**-683 + {0xea53df5fd18d5513, 0x84c86189216dc5ed}, // 1e245 * 2**-686 + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4}, // 1e246 * 2**-690 + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1}, // 1e247 * 2**-693 + {0xe4d5e82392a40515, 0x0fabaf3feaa5334a}, // 1e248 * 2**-696 + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e}, // 1e249 * 2**-700 + {0xb2c71d5bca9023f8, 0x743e20e9ef511012}, // 1e250 * 2**-703 + {0xdf78e4b2bd342cf6, 0x914da9246b255416}, // 1e251 * 2**-706 + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e}, // 1e252 * 2**-710 + {0xae9672aba3d0c320, 0xa184ac2473b529b1}, // 1e253 * 2**-713 + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e}, // 1e254 * 2**-716 + {0x8865899617fb1871, 0x7e2fa67c7a658892}, // 1e255 * 2**-720 + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7}, // 1e256 * 2**-723 + {0xd51ea6fa85785631, 0x552a74227f3ea565}, // 1e257 * 2**-726 + {0x8533285c936b35de, 0xd53a88958f87275f}, // 1e258 * 2**-730 + {0xa67ff273b8460356, 0x8a892abaf368f137}, // 1e259 * 2**-733 + {0xd01fef10a657842c, 0x2d2b7569b0432d85}, // 1e260 * 2**-736 + {0x8213f56a67f6b29b, 0x9c3b29620e29fc73}, // 1e261 * 2**-740 + {0xa298f2c501f45f42, 0x8349f3ba91b47b8f}, // 1e262 * 2**-743 + {0xcb3f2f7642717713, 0x241c70a936219a73}, // 1e263 * 2**-746 + {0xfe0efb53d30dd4d7, 0xed238cd383aa0110}, // 1e264 * 2**-749 + {0x9ec95d1463e8a506, 0xf4363804324a40aa}, // 1e265 * 2**-753 + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5}, // 1e266 * 2**-756 + {0xf81aa16fdc1b81da, 0xdd94b7868e94050a}, // 1e267 * 2**-759 + {0x9b10a4e5e9913128, 0xca7cf2b4191c8326}, // 1e268 * 2**-763 + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0}, // 1e269 * 2**-766 + {0xf24a01a73cf2dccf, 0xbc633b39673c8cec}, // 1e270 * 2**-769 + {0x976e41088617ca01, 0xd5be0503e085d813}, // 1e271 * 2**-773 + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18}, // 1e272 * 2**-776 + {0xec9c459d51852ba2, 0xddf8e7d60ed1219e}, // 1e273 * 2**-779 + {0x93e1ab8252f33b45, 0xcabb90e5c942b503}, // 1e274 * 2**-783 + {0xb8da1662e7b00a17, 0x3d6a751f3b936243}, // 1e275 * 2**-786 + {0xe7109bfba19c0c9d, 0x0cc512670a783ad4}, // 1e276 * 2**-789 + {0x906a617d450187e2, 0x27fb2b80668b24c5}, // 1e277 * 2**-793 + {0xb484f9dc9641e9da, 0xb1f9f660802dedf6}, // 1e278 * 2**-796 + {0xe1a63853bbd26451, 0x5e7873f8a0396973}, // 1e279 * 2**-799 + {0x8d07e33455637eb2, 0xdb0b487b6423e1e8}, // 1e280 * 2**-803 + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62}, // 1e281 * 2**-806 + {0xdc5c5301c56b75f7, 0x7641a140cc7810fb}, // 1e282 * 2**-809 + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d}, // 1e283 * 2**-813 + {0xac2820d9623bf429, 0x546345fa9fbdcd44}, // 1e284 * 2**-816 + {0xd732290fbacaf133, 0xa97c177947ad4095}, // 1e285 * 2**-819 + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d}, // 1e286 * 2**-823 + {0xa81f301449ee8c70, 0x5c68f256bfff5a74}, // 1e287 * 2**-826 + {0xd226fc195c6a2f8c, 0x73832eec6fff3111}, // 1e288 * 2**-829 + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab}, // 1e289 * 2**-833 + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55}, // 1e290 * 2**-836 + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb}, // 1e291 * 2**-839 + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3}, // 1e292 * 2**-843 + {0xa0555e361951c366, 0xd7e105bcc332621f}, // 1e293 * 2**-846 + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7}, // 1e294 * 2**-849 + {0xfa856334878fc150, 0xb14f98f6f0feb951}, // 1e295 * 2**-852 + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3}, // 1e296 * 2**-856 + {0xc3b8358109e84f07, 0x0a862f80ec4700c8}, // 1e297 * 2**-859 + {0xf4a642e14c6262c8, 0xcd27bb612758c0fa}, // 1e298 * 2**-862 + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c}, // 1e299 * 2**-866 + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3}, // 1e300 * 2**-869 + {0xeeea5d5004981478, 0x1858ccfce06cac74}, // 1e301 * 2**-872 + {0x95527a5202df0ccb, 0x0f37801e0c43ebc8}, // 1e302 * 2**-876 + {0xbaa718e68396cffd, 0xd30560258f54e6ba}, // 1e303 * 2**-879 + {0xe950df20247c83fd, 0x47c6b82ef32a2069}, // 1e304 * 2**-882 + {0x91d28b7416cdd27e, 0x4cdc331d57fa5441}, // 1e305 * 2**-886 + {0xb6472e511c81471d, 0xe0133fe4adf8e952}, // 1e306 * 2**-889 + {0xe3d8f9e563a198e5, 0x58180fddd97723a6}, // 1e307 * 2**-892 + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648}, // 1e308 * 2**-896 + {0xb201833b35d63f73, 0x2cd2cc6551e513da}, // 1e309 * 2**-899 + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1}, // 1e310 * 2**-902 + {0x8b112e86420f6191, 0xfb04afaf27faf782}, // 1e311 * 2**-906 + {0xadd57a27d29339f6, 0x79c5db9af1f9b563}, // 1e312 * 2**-909 + {0xd94ad8b1c7380874, 0x18375281ae7822bc}, // 1e313 * 2**-912 + {0x87cec76f1c830548, 0x8f2293910d0b15b5}, // 1e314 * 2**-916 + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22}, // 1e315 * 2**-919 + {0xd433179d9c8cb841, 0x5fa60692a46151eb}, // 1e316 * 2**-922 + {0x849feec281d7f328, 0xdbc7c41ba6bcd333}, // 1e317 * 2**-926 + {0xa5c7ea73224deff3, 0x12b9b522906c0800}, // 1e318 * 2**-929 + {0xcf39e50feae16bef, 0xd768226b34870a00}, // 1e319 * 2**-932 + {0x81842f29f2cce375, 0xe6a1158300d46640}, // 1e320 * 2**-936 + {0xa1e53af46f801c53, 0x60495ae3c1097fd0}, // 1e321 * 2**-939 + {0xca5e89b18b602368, 0x385bb19cb14bdfc4}, // 1e322 * 2**-942 + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5}, // 1e323 * 2**-945 + {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d1}, // 1e324 * 2**-949 + {0xc5a05277621be293, 0xc7098b7305241885}, // 1e325 * 2**-952 + {0xf70867153aa2db38, 0xb8cbee4fc66d1ea7}, // 1e326 * 2**-955 + {0x9a65406d44a5c903, 0x737f74f1dc043328}, // 1e327 * 2**-959 + {0xc0fe908895cf3b44, 0x505f522e53053ff2}, // 1e328 * 2**-962 + {0xf13e34aabb430a15, 0x647726b9e7c68fef}, // 1e329 * 2**-965 + {0x96c6e0eab509e64d, 0x5eca783430dc19f5}, // 1e330 * 2**-969 + {0xbc789925624c5fe0, 0xb67d16413d132072}, // 1e331 * 2**-972 + {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e88f}, // 1e332 * 2**-975 + {0x933e37a534cbaae7, 0x8e91b962f7b6f159}, // 1e333 * 2**-979 + {0xb80dc58e81fe95a1, 0x723627bbb5a4adb0}, // 1e334 * 2**-982 + {0xe61136f2227e3b09, 0xcec3b1aaa30dd91c}, // 1e335 * 2**-985 + {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b1}, // 1e336 * 2**-989 + {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19d}, // 1e337 * 2**-992 + {0xe0accfa875af45a7, 0x93eb1b80a33b8605}, // 1e338 * 2**-995 + {0x8c6c01c9498d8b88, 0xbc72f130660533c3}, // 1e339 * 2**-999 + {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b4}, // 1e340 * 2**-1002 + {0xdb68c2ca82ed2a05, 0xa67398db9f6820e1}, // 1e341 * 2**-1005 + {0x892179be91d43a43, 0x88083f8943a1148c}, // 1e342 * 2**-1009 + {0xab69d82e364948d4, 0x6a0a4f6b948959b0}, // 1e343 * 2**-1012 + {0xd6444e39c3db9b09, 0x848ce34679abb01c}, // 1e344 * 2**-1015 + {0x85eab0e41a6940e5, 0xf2d80e0c0c0b4e11}, // 1e345 * 2**-1019 + {0xa7655d1d2103911f, 0x6f8e118f0f0e2195}, // 1e346 * 2**-1022 + {0xd13eb46469447567, 0x4b7195f2d2d1a9fb}, // 1e347 * 2**-1025 +} diff --git a/go/src/internal/stringslite/strings.go b/go/src/internal/stringslite/strings.go new file mode 100644 index 0000000000000000000000000000000000000000..3a09e08cf4f7bd360e6e8b7435a655c83332f53c --- /dev/null +++ b/go/src/internal/stringslite/strings.go @@ -0,0 +1,150 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package stringslite implements a subset of strings, +// only using packages that may be imported by "os". +// +// Tests for these functions are in the strings package. +package stringslite + +import ( + "internal/bytealg" + "unsafe" +) + +func HasPrefix(s, prefix string) bool { + return len(s) >= len(prefix) && s[:len(prefix)] == prefix +} + +func HasSuffix(s, suffix string) bool { + return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix +} + +func IndexByte(s string, c byte) int { + return bytealg.IndexByteString(s, c) +} + +func Index(s, substr string) int { + n := len(substr) + switch { + case n == 0: + return 0 + case n == 1: + return IndexByte(s, substr[0]) + case n == len(s): + if substr == s { + return 0 + } + return -1 + case n > len(s): + return -1 + case n <= bytealg.MaxLen: + // Use brute force when s and substr both are small + if len(s) <= bytealg.MaxBruteForce { + return bytealg.IndexString(s, substr) + } + c0 := substr[0] + c1 := substr[1] + i := 0 + t := len(s) - n + 1 + fails := 0 + for i < t { + if s[i] != c0 { + // IndexByte is faster than bytealg.IndexString, 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 && s[i:i+n] == substr { + return i + } + fails++ + i++ + // Switch to bytealg.IndexString when IndexByte produces too many false positives. + if fails > bytealg.Cutover(i) { + r := bytealg.IndexString(s[i:], substr) + if r >= 0 { + return r + i + } + return -1 + } + } + return -1 + } + c0 := substr[0] + c1 := substr[1] + i := 0 + t := len(s) - n + 1 + fails := 0 + for i < t { + if s[i] != c0 { + o := IndexByte(s[i+1:t], c0) + if o < 0 { + return -1 + } + i += o + 1 + } + if s[i+1] == c1 && s[i:i+n] == substr { + return i + } + i++ + fails++ + if fails >= 4+i>>4 && i < t { + // See comment in ../bytes/bytes.go. + j := bytealg.IndexRabinKarp(s[i:], substr) + if j < 0 { + return -1 + } + return i + j + } + } + return -1 +} + +func Cut(s, sep string) (before, after string, found bool) { + if i := Index(s, sep); i >= 0 { + return s[:i], s[i+len(sep):], true + } + return s, "", false +} + +func CutPrefix(s, prefix string) (after string, found bool) { + if !HasPrefix(s, prefix) { + return s, false + } + return s[len(prefix):], true +} + +func CutSuffix(s, suffix string) (before string, found bool) { + if !HasSuffix(s, suffix) { + return s, false + } + return s[:len(s)-len(suffix)], true +} + +func TrimPrefix(s, prefix string) string { + if HasPrefix(s, prefix) { + return s[len(prefix):] + } + return s +} + +func TrimSuffix(s, suffix string) string { + if HasSuffix(s, suffix) { + return s[:len(s)-len(suffix)] + } + return s +} + +func Clone(s string) string { + if len(s) == 0 { + return "" + } + b := make([]byte, len(s)) + copy(b, s) + return unsafe.String(&b[0], len(b)) +} diff --git a/go/src/internal/sync/export_test.go b/go/src/internal/sync/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c6449bf3e0aa8b3f6dda94716cfa16de3e095e0f --- /dev/null +++ b/go/src/internal/sync/export_test.go @@ -0,0 +1,38 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sync + +import ( + "internal/abi" + "unsafe" +) + +// NewBadHashTrieMap creates a new HashTrieMap for the provided key and value +// but with an intentionally bad hash function. +func NewBadHashTrieMap[K, V comparable]() *HashTrieMap[K, V] { + // Stub out the good hash function with a terrible one. + // Everything should still work as expected. + var m HashTrieMap[K, V] + m.init() + m.keyHash = func(_ unsafe.Pointer, _ uintptr) uintptr { + return 0 + } + return &m +} + +// NewTruncHashTrieMap creates a new HashTrieMap for the provided key and value +// but with an intentionally bad hash function. +func NewTruncHashTrieMap[K, V comparable]() *HashTrieMap[K, V] { + // Stub out the good hash function with a terrible one. + // Everything should still work as expected. + var m HashTrieMap[K, V] + var mx map[string]int + mapType := abi.TypeOf(mx).MapType() + hasher := mapType.Hasher + m.keyHash = func(p unsafe.Pointer, n uintptr) uintptr { + return hasher(p, n) & ((uintptr(1) << 4) - 1) + } + return &m +} diff --git a/go/src/internal/sync/hashtriemap.go b/go/src/internal/sync/hashtriemap.go new file mode 100644 index 0000000000000000000000000000000000000000..db832974278f1635fb1491c5bc75bff34cf911e2 --- /dev/null +++ b/go/src/internal/sync/hashtriemap.go @@ -0,0 +1,724 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sync + +import ( + "internal/abi" + "internal/goarch" + "sync/atomic" + "unsafe" +) + +// HashTrieMap is an implementation of a concurrent hash-trie. The implementation +// is designed around frequent loads, but offers decent performance for stores +// and deletes as well, especially if the map is larger. Its primary use-case is +// the unique package, but can be used elsewhere as well. +// +// The zero HashTrieMap is empty and ready to use. +// It must not be copied after first use. +type HashTrieMap[K comparable, V any] struct { + inited atomic.Uint32 + initMu Mutex + root atomic.Pointer[indirect[K, V]] + keyHash hashFunc + valEqual equalFunc + seed uintptr +} + +func (ht *HashTrieMap[K, V]) init() { + if ht.inited.Load() == 0 { + ht.initSlow() + } +} + +//go:noinline +func (ht *HashTrieMap[K, V]) initSlow() { + ht.initMu.Lock() + defer ht.initMu.Unlock() + + if ht.inited.Load() != 0 { + // Someone got to it while we were waiting. + return + } + + // Set up root node, derive the hash function for the key, and the + // equal function for the value, if any. + var m map[K]V + mapType := abi.TypeOf(m).MapType() + ht.root.Store(newIndirectNode[K, V](nil)) + ht.keyHash = mapType.Hasher + ht.valEqual = mapType.Elem.Equal + ht.seed = uintptr(runtime_rand()) + + ht.inited.Store(1) +} + +type hashFunc func(unsafe.Pointer, uintptr) uintptr +type equalFunc func(unsafe.Pointer, unsafe.Pointer) bool + +// Load returns the value stored in the map for a key, or nil if no +// value is present. +// The ok result indicates whether value was found in the map. +func (ht *HashTrieMap[K, V]) Load(key K) (value V, ok bool) { + ht.init() + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + + i := ht.root.Load() + hashShift := 8 * goarch.PtrSize + for hashShift != 0 { + hashShift -= nChildrenLog2 + + n := i.children[(hash>>hashShift)&nChildrenMask].Load() + if n == nil { + return *new(V), false + } + if n.isEntry { + return n.entry().lookup(key) + } + i = n.indirect() + } + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") +} + +// LoadOrStore returns the existing value for the key if present. +// Otherwise, it stores and returns the given value. +// The loaded result is true if the value was loaded, false if stored. +func (ht *HashTrieMap[K, V]) LoadOrStore(key K, value V) (result V, loaded bool) { + ht.init() + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + var i *indirect[K, V] + var hashShift uint + var slot *atomic.Pointer[node[K, V]] + var n *node[K, V] + for { + // Find the key or a candidate location for insertion. + i = ht.root.Load() + hashShift = 8 * goarch.PtrSize + haveInsertPoint := false + for hashShift != 0 { + hashShift -= nChildrenLog2 + + slot = &i.children[(hash>>hashShift)&nChildrenMask] + n = slot.Load() + if n == nil { + // We found a nil slot which is a candidate for insertion. + haveInsertPoint = true + break + } + if n.isEntry { + // We found an existing entry, which is as far as we can go. + // If it stays this way, we'll have to replace it with an + // indirect node. + if v, ok := n.entry().lookup(key); ok { + return v, true + } + haveInsertPoint = true + break + } + i = n.indirect() + } + if !haveInsertPoint { + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") + } + + // Grab the lock and double-check what we saw. + i.mu.Lock() + n = slot.Load() + if (n == nil || n.isEntry) && !i.dead.Load() { + // What we saw is still true, so we can continue with the insert. + break + } + // We have to start over. + i.mu.Unlock() + } + // N.B. This lock is held from when we broke out of the outer loop above. + // We specifically break this out so that we can use defer here safely. + // One option is to break this out into a new function instead, but + // there's so much local iteration state used below that this turns out + // to be cleaner. + defer i.mu.Unlock() + + var oldEntry *entry[K, V] + if n != nil { + oldEntry = n.entry() + if v, ok := oldEntry.lookup(key); ok { + // Easy case: by loading again, it turns out exactly what we wanted is here! + return v, true + } + } + newEntry := newEntryNode(key, value) + if oldEntry == nil { + // Easy case: create a new entry and store it. + slot.Store(&newEntry.node) + } else { + // We possibly need to expand the entry already there into one or more new nodes. + // + // Publish the node last, which will make both oldEntry and newEntry visible. We + // don't want readers to be able to observe that oldEntry isn't in the tree. + slot.Store(ht.expand(oldEntry, newEntry, hash, hashShift, i)) + } + return value, false +} + +// expand takes oldEntry and newEntry whose hashes conflict from bit 64 down to hashShift and +// produces a subtree of indirect nodes to hold the two new entries. +func (ht *HashTrieMap[K, V]) expand(oldEntry, newEntry *entry[K, V], newHash uintptr, hashShift uint, parent *indirect[K, V]) *node[K, V] { + // Check for a hash collision. + oldHash := ht.keyHash(unsafe.Pointer(&oldEntry.key), ht.seed) + if oldHash == newHash { + // Store the old entry in the new entry's overflow list, then store + // the new entry. + newEntry.overflow.Store(oldEntry) + return &newEntry.node + } + // We have to add an indirect node. Worse still, we may need to add more than one. + newIndirect := newIndirectNode(parent) + top := newIndirect + for { + if hashShift == 0 { + panic("internal/sync.HashTrieMap: ran out of hash bits while inserting (incorrect use of unsafe or cgo, or data race?)") + } + hashShift -= nChildrenLog2 // hashShift is for the level parent is at. We need to go deeper. + oi := (oldHash >> hashShift) & nChildrenMask + ni := (newHash >> hashShift) & nChildrenMask + if oi != ni { + newIndirect.children[oi].Store(&oldEntry.node) + newIndirect.children[ni].Store(&newEntry.node) + break + } + nextIndirect := newIndirectNode(newIndirect) + newIndirect.children[oi].Store(&nextIndirect.node) + newIndirect = nextIndirect + } + return &top.node +} + +// Store sets the value for a key. +func (ht *HashTrieMap[K, V]) Store(key K, new V) { + _, _ = ht.Swap(key, new) +} + +// Swap swaps the value for a key and returns the previous value if any. +// The loaded result reports whether the key was present. +func (ht *HashTrieMap[K, V]) Swap(key K, new V) (previous V, loaded bool) { + ht.init() + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + var i *indirect[K, V] + var hashShift uint + var slot *atomic.Pointer[node[K, V]] + var n *node[K, V] + for { + // Find the key or a candidate location for insertion. + i = ht.root.Load() + hashShift = 8 * goarch.PtrSize + haveInsertPoint := false + for hashShift != 0 { + hashShift -= nChildrenLog2 + + slot = &i.children[(hash>>hashShift)&nChildrenMask] + n = slot.Load() + if n == nil || n.isEntry { + // We found a nil slot which is a candidate for insertion, + // or an existing entry that we'll replace. + haveInsertPoint = true + break + } + i = n.indirect() + } + if !haveInsertPoint { + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") + } + + // Grab the lock and double-check what we saw. + i.mu.Lock() + n = slot.Load() + if (n == nil || n.isEntry) && !i.dead.Load() { + // What we saw is still true, so we can continue with the insert. + break + } + // We have to start over. + i.mu.Unlock() + } + // N.B. This lock is held from when we broke out of the outer loop above. + // We specifically break this out so that we can use defer here safely. + // One option is to break this out into a new function instead, but + // there's so much local iteration state used below that this turns out + // to be cleaner. + defer i.mu.Unlock() + + var zero V + var oldEntry *entry[K, V] + if n != nil { + // Swap if the keys compare. + oldEntry = n.entry() + newEntry, old, swapped := oldEntry.swap(key, new) + if swapped { + slot.Store(&newEntry.node) + return old, true + } + } + // The keys didn't compare, so we're doing an insertion. + newEntry := newEntryNode(key, new) + if oldEntry == nil { + // Easy case: create a new entry and store it. + slot.Store(&newEntry.node) + } else { + // We possibly need to expand the entry already there into one or more new nodes. + // + // Publish the node last, which will make both oldEntry and newEntry visible. We + // don't want readers to be able to observe that oldEntry isn't in the tree. + slot.Store(ht.expand(oldEntry, newEntry, hash, hashShift, i)) + } + return zero, false +} + +// CompareAndSwap swaps the old and new values for key +// if the value stored in the map is equal to old. +// The value type must be of a comparable type, otherwise CompareAndSwap will panic. +func (ht *HashTrieMap[K, V]) CompareAndSwap(key K, old, new V) (swapped bool) { + ht.init() + if ht.valEqual == nil { + panic("called CompareAndSwap when value is not of comparable type") + } + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + + // Find a node with the key and compare with it. n != nil if we found the node. + i, _, slot, n := ht.find(key, hash, ht.valEqual, old) + if i != nil { + defer i.mu.Unlock() + } + if n == nil { + return false + } + + // Try to swap the entry. + e, swapped := n.entry().compareAndSwap(key, old, new, ht.valEqual) + if !swapped { + // Nothing was actually swapped, which means the node is no longer there. + return false + } + // Store the entry back because it changed. + slot.Store(&e.node) + return true +} + +// LoadAndDelete deletes the value for a key, returning the previous value if any. +// The loaded result reports whether the key was present. +func (ht *HashTrieMap[K, V]) LoadAndDelete(key K) (value V, loaded bool) { + ht.init() + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + + // Find a node with the key and compare with it. n != nil if we found the node. + i, hashShift, slot, n := ht.find(key, hash, nil, *new(V)) + if n == nil { + if i != nil { + i.mu.Unlock() + } + return *new(V), false + } + + // Try to delete the entry. + v, e, loaded := n.entry().loadAndDelete(key) + if !loaded { + // Nothing was actually deleted, which means the node is no longer there. + i.mu.Unlock() + return *new(V), false + } + if e != nil { + // We didn't actually delete the whole entry, just one entry in the chain. + // Nothing else to do, since the parent is definitely not empty. + slot.Store(&e.node) + i.mu.Unlock() + return v, true + } + // Delete the entry. + slot.Store(nil) + + // Check if the node is now empty (and isn't the root), and delete it if able. + for i.parent != nil && i.empty() { + if hashShift == 8*goarch.PtrSize { + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") + } + hashShift += nChildrenLog2 + + // Delete the current node in the parent. + parent := i.parent + parent.mu.Lock() + i.dead.Store(true) + parent.children[(hash>>hashShift)&nChildrenMask].Store(nil) + i.mu.Unlock() + i = parent + } + i.mu.Unlock() + return v, true +} + +// Delete deletes the value for a key. +func (ht *HashTrieMap[K, V]) Delete(key K) { + _, _ = ht.LoadAndDelete(key) +} + +// CompareAndDelete deletes the entry for key if its value is equal to old. +// The value type must be comparable, otherwise this CompareAndDelete will panic. +// +// If there is no current value for key in the map, CompareAndDelete returns false +// (even if the old value is the nil interface value). +func (ht *HashTrieMap[K, V]) CompareAndDelete(key K, old V) (deleted bool) { + ht.init() + if ht.valEqual == nil { + panic("called CompareAndDelete when value is not of comparable type") + } + hash := ht.keyHash(abi.NoEscape(unsafe.Pointer(&key)), ht.seed) + + // Find a node with the key. n != nil if we found the node. + i, hashShift, slot, n := ht.find(key, hash, nil, *new(V)) + if n == nil { + if i != nil { + i.mu.Unlock() + } + return false + } + + // Try to delete the entry. + e, deleted := n.entry().compareAndDelete(key, old, ht.valEqual) + if !deleted { + // Nothing was actually deleted, which means the node is no longer there. + i.mu.Unlock() + return false + } + if e != nil { + // We didn't actually delete the whole entry, just one entry in the chain. + // Nothing else to do, since the parent is definitely not empty. + slot.Store(&e.node) + i.mu.Unlock() + return true + } + // Delete the entry. + slot.Store(nil) + + // Check if the node is now empty (and isn't the root), and delete it if able. + for i.parent != nil && i.empty() { + if hashShift == 8*goarch.PtrSize { + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") + } + hashShift += nChildrenLog2 + + // Delete the current node in the parent. + parent := i.parent + parent.mu.Lock() + i.dead.Store(true) + parent.children[(hash>>hashShift)&nChildrenMask].Store(nil) + i.mu.Unlock() + i = parent + } + i.mu.Unlock() + return true +} + +// find searches the tree for a node that contains key (hash must be the hash of key). +// If valEqual != nil, then it will also enforce that the values are equal as well. +// +// Returns a non-nil node, which will always be an entry, if found. +// +// If i != nil then i.mu is locked, and it is the caller's responsibility to unlock it. +func (ht *HashTrieMap[K, V]) find(key K, hash uintptr, valEqual equalFunc, value V) (i *indirect[K, V], hashShift uint, slot *atomic.Pointer[node[K, V]], n *node[K, V]) { + for { + // Find the key or return if it's not there. + i = ht.root.Load() + hashShift = 8 * goarch.PtrSize + found := false + for hashShift != 0 { + hashShift -= nChildrenLog2 + + slot = &i.children[(hash>>hashShift)&nChildrenMask] + n = slot.Load() + if n == nil { + // Nothing to compare with. Give up. + i = nil + return + } + if n.isEntry { + // We found an entry. Check if it matches. + if _, ok := n.entry().lookupWithValue(key, value, valEqual); !ok { + // No match, comparison failed. + i = nil + n = nil + return + } + // We've got a match. Prepare to perform an operation on the key. + found = true + break + } + i = n.indirect() + } + if !found { + panic("internal/sync.HashTrieMap: ran out of hash bits while iterating") + } + + // Grab the lock and double-check what we saw. + i.mu.Lock() + n = slot.Load() + if !i.dead.Load() && (n == nil || n.isEntry) { + // Either we've got a valid node or the node is now nil under the lock. + // In either case, we're done here. + return + } + // We have to start over. + i.mu.Unlock() + } +} + +// All returns an iterator over each key and value present in the map. +// +// The iterator does not necessarily correspond to any consistent snapshot of the +// HashTrieMap's contents: no key will be visited more than once, but if the value +// for any key is stored or deleted concurrently (including by yield), the iterator +// may reflect any mapping for that key from any point during iteration. The iterator +// does not block other methods on the receiver; even yield itself may call any +// method on the HashTrieMap. +func (ht *HashTrieMap[K, V]) All() func(yield func(K, V) bool) { + ht.init() + return func(yield func(key K, value V) bool) { + ht.iter(ht.root.Load(), yield) + } +} + +// Range calls f sequentially for each key and value present in the map. +// If f returns false, range stops the iteration. +// +// This exists for compatibility with sync.Map; All should be preferred. +// It provides the same guarantees as sync.Map, and All. +func (ht *HashTrieMap[K, V]) Range(yield func(K, V) bool) { + ht.init() + ht.iter(ht.root.Load(), yield) +} + +func (ht *HashTrieMap[K, V]) iter(i *indirect[K, V], yield func(key K, value V) bool) bool { + for j := range i.children { + n := i.children[j].Load() + if n == nil { + continue + } + if !n.isEntry { + if !ht.iter(n.indirect(), yield) { + return false + } + continue + } + e := n.entry() + for e != nil { + if !yield(e.key, e.value) { + return false + } + e = e.overflow.Load() + } + } + return true +} + +// Clear deletes all the entries, resulting in an empty HashTrieMap. +func (ht *HashTrieMap[K, V]) Clear() { + ht.init() + + // It's sufficient to just drop the root on the floor, but the root + // must always be non-nil. + ht.root.Store(newIndirectNode[K, V](nil)) +} + +const ( + // 16 children. This seems to be the sweet spot for + // load performance: any smaller and we lose out on + // 50% or more in CPU performance. Any larger and the + // returns are minuscule (~1% improvement for 32 children). + nChildrenLog2 = 4 + nChildren = 1 << nChildrenLog2 + nChildrenMask = nChildren - 1 +) + +// indirect is an internal node in the hash-trie. +type indirect[K comparable, V any] struct { + node[K, V] + dead atomic.Bool + mu Mutex // Protects mutation to children and any children that are entry nodes. + parent *indirect[K, V] + children [nChildren]atomic.Pointer[node[K, V]] +} + +func newIndirectNode[K comparable, V any](parent *indirect[K, V]) *indirect[K, V] { + return &indirect[K, V]{node: node[K, V]{isEntry: false}, parent: parent} +} + +func (i *indirect[K, V]) empty() bool { + nc := 0 + for j := range i.children { + if i.children[j].Load() != nil { + nc++ + } + } + return nc == 0 +} + +// entry is a leaf node in the hash-trie. +type entry[K comparable, V any] struct { + node[K, V] + overflow atomic.Pointer[entry[K, V]] // Overflow for hash collisions. + key K + value V +} + +func newEntryNode[K comparable, V any](key K, value V) *entry[K, V] { + return &entry[K, V]{ + node: node[K, V]{isEntry: true}, + key: key, + value: value, + } +} + +func (e *entry[K, V]) lookup(key K) (V, bool) { + for e != nil { + if e.key == key { + return e.value, true + } + e = e.overflow.Load() + } + return *new(V), false +} + +func (e *entry[K, V]) lookupWithValue(key K, value V, valEqual equalFunc) (V, bool) { + for e != nil { + if e.key == key && (valEqual == nil || valEqual(unsafe.Pointer(&e.value), abi.NoEscape(unsafe.Pointer(&value)))) { + return e.value, true + } + e = e.overflow.Load() + } + return *new(V), false +} + +// swap replaces an entry in the overflow chain if keys compare equal. Returns the new entry chain, +// the old value, and whether or not anything was swapped. +// +// swap must be called under the mutex of the indirect node which e is a child of. +func (head *entry[K, V]) swap(key K, new V) (*entry[K, V], V, bool) { + if head.key == key { + // Return the new head of the list. + e := newEntryNode(key, new) + if chain := head.overflow.Load(); chain != nil { + e.overflow.Store(chain) + } + return e, head.value, true + } + i := &head.overflow + e := i.Load() + for e != nil { + if e.key == key { + eNew := newEntryNode(key, new) + eNew.overflow.Store(e.overflow.Load()) + i.Store(eNew) + return head, e.value, true + } + i = &e.overflow + e = e.overflow.Load() + } + var zero V + return head, zero, false +} + +// compareAndSwap replaces an entry in the overflow chain if both the key and value compare +// equal. Returns the new entry chain and whether or not anything was swapped. +// +// compareAndSwap must be called under the mutex of the indirect node which e is a child of. +func (head *entry[K, V]) compareAndSwap(key K, old, new V, valEqual equalFunc) (*entry[K, V], bool) { + if head.key == key && valEqual(unsafe.Pointer(&head.value), abi.NoEscape(unsafe.Pointer(&old))) { + // Return the new head of the list. + e := newEntryNode(key, new) + if chain := head.overflow.Load(); chain != nil { + e.overflow.Store(chain) + } + return e, true + } + i := &head.overflow + e := i.Load() + for e != nil { + if e.key == key && valEqual(unsafe.Pointer(&e.value), abi.NoEscape(unsafe.Pointer(&old))) { + eNew := newEntryNode(key, new) + eNew.overflow.Store(e.overflow.Load()) + i.Store(eNew) + return head, true + } + i = &e.overflow + e = e.overflow.Load() + } + return head, false +} + +// loadAndDelete deletes an entry in the overflow chain by key. Returns the value for the key, the new +// entry chain and whether or not anything was loaded (and deleted). +// +// loadAndDelete must be called under the mutex of the indirect node which e is a child of. +func (head *entry[K, V]) loadAndDelete(key K) (V, *entry[K, V], bool) { + if head.key == key { + // Drop the head of the list. + return head.value, head.overflow.Load(), true + } + i := &head.overflow + e := i.Load() + for e != nil { + if e.key == key { + i.Store(e.overflow.Load()) + return e.value, head, true + } + i = &e.overflow + e = e.overflow.Load() + } + return *new(V), head, false +} + +// compareAndDelete deletes an entry in the overflow chain if both the key and value compare +// equal. Returns the new entry chain and whether or not anything was deleted. +// +// compareAndDelete must be called under the mutex of the indirect node which e is a child of. +func (head *entry[K, V]) compareAndDelete(key K, value V, valEqual equalFunc) (*entry[K, V], bool) { + if head.key == key && valEqual(unsafe.Pointer(&head.value), abi.NoEscape(unsafe.Pointer(&value))) { + // Drop the head of the list. + return head.overflow.Load(), true + } + i := &head.overflow + e := i.Load() + for e != nil { + if e.key == key && valEqual(unsafe.Pointer(&e.value), abi.NoEscape(unsafe.Pointer(&value))) { + i.Store(e.overflow.Load()) + return head, true + } + i = &e.overflow + e = e.overflow.Load() + } + return head, false +} + +// node is the header for a node. It's polymorphic and +// is actually either an entry or an indirect. +type node[K comparable, V any] struct { + isEntry bool +} + +func (n *node[K, V]) entry() *entry[K, V] { + if !n.isEntry { + panic("called entry on non-entry node") + } + return (*entry[K, V])(unsafe.Pointer(n)) +} + +func (n *node[K, V]) indirect() *indirect[K, V] { + if n.isEntry { + panic("called indirect on entry node") + } + return (*indirect[K, V])(unsafe.Pointer(n)) +} + +// Pull in runtime.rand so that we don't need to take a dependency +// on math/rand/v2. +// +//go:linkname runtime_rand runtime.rand +func runtime_rand() uint64 diff --git a/go/src/internal/sync/hashtriemap_bench_test.go b/go/src/internal/sync/hashtriemap_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fc10d8220283454cb86cfdcd04ce96f8df9e618b --- /dev/null +++ b/go/src/internal/sync/hashtriemap_bench_test.go @@ -0,0 +1,65 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sync_test + +import ( + isync "internal/sync" + "testing" +) + +func BenchmarkHashTrieMapLoadSmall(b *testing.B) { + benchmarkHashTrieMapLoad(b, testDataSmall[:]) +} + +func BenchmarkHashTrieMapLoad(b *testing.B) { + benchmarkHashTrieMapLoad(b, testData[:]) +} + +func BenchmarkHashTrieMapLoadLarge(b *testing.B) { + benchmarkHashTrieMapLoad(b, testDataLarge[:]) +} + +func benchmarkHashTrieMapLoad(b *testing.B, data []string) { + b.ReportAllocs() + var m isync.HashTrieMap[string, int] + for i := range data { + m.LoadOrStore(data[i], i) + } + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + i := 0 + for pb.Next() { + _, _ = m.Load(data[i]) + i++ + if i >= len(data) { + i = 0 + } + } + }) +} + +func BenchmarkHashTrieMapLoadOrStore(b *testing.B) { + benchmarkHashTrieMapLoadOrStore(b, testData[:]) +} + +func BenchmarkHashTrieMapLoadOrStoreLarge(b *testing.B) { + benchmarkHashTrieMapLoadOrStore(b, testDataLarge[:]) +} + +func benchmarkHashTrieMapLoadOrStore(b *testing.B, data []string) { + b.ReportAllocs() + var m isync.HashTrieMap[string, int] + + b.RunParallel(func(pb *testing.PB) { + i := 0 + for pb.Next() { + _, _ = m.LoadOrStore(data[i], i) + i++ + if i >= len(data) { + i = 0 + } + } + }) +} diff --git a/go/src/internal/sync/hashtriemap_test.go b/go/src/internal/sync/hashtriemap_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d9219f841a8bdfd6878ae69c242480129d5cfc0b --- /dev/null +++ b/go/src/internal/sync/hashtriemap_test.go @@ -0,0 +1,982 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sync_test + +import ( + "fmt" + isync "internal/sync" + "math" + "runtime" + "strconv" + "sync" + "testing" + "weak" +) + +func TestHashTrieMap(t *testing.T) { + testHashTrieMap(t, func() *isync.HashTrieMap[string, int] { + var m isync.HashTrieMap[string, int] + return &m + }) +} + +func TestHashTrieMapBadHash(t *testing.T) { + testHashTrieMap(t, func() *isync.HashTrieMap[string, int] { + return isync.NewBadHashTrieMap[string, int]() + }) +} + +func TestHashTrieMapTruncHash(t *testing.T) { + testHashTrieMap(t, func() *isync.HashTrieMap[string, int] { + // Stub out the good hash function with a different terrible one + // (truncated hash). Everything should still work as expected. + // This is useful to test independently to catch issues with + // near collisions, where only the last few bits of the hash differ. + return isync.NewTruncHashTrieMap[string, int]() + }) +} + +func testHashTrieMap(t *testing.T, newMap func() *isync.HashTrieMap[string, int]) { + t.Run("LoadEmpty", func(t *testing.T) { + m := newMap() + + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }) + t.Run("LoadOrStore", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for i, s := range testData { + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + }) + t.Run("All", func(t *testing.T) { + m := newMap() + + testAll(t, m, testDataMap(testData[:]), func(_ string, _ int) bool { + return true + }) + }) + t.Run("Clear", func(t *testing.T) { + t.Run("Simple", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + m.Clear() + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }) + t.Run("Concurrent", func(t *testing.T) { + m := newMap() + + // Load up the map. + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + } + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + for _, s := range testData { + // Try a couple things to interfere with the clear. + expectNotDeleted(t, s, math.MaxInt)(m.CompareAndDelete(s, math.MaxInt)) + m.CompareAndSwap(s, i, i+1) // May succeed or fail; we don't care. + } + }(i) + } + + // Concurrently clear the map. + runtime.Gosched() + m.Clear() + + // Wait for workers to finish. + wg.Wait() + + // It should all be empty now. + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }) + }) + t.Run("CompareAndDelete", func(t *testing.T) { + t.Run("All", func(t *testing.T) { + m := newMap() + + for range 3 { + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for i, s := range testData { + expectPresent(t, s, i)(m.Load(s)) + expectNotDeleted(t, s, math.MaxInt)(m.CompareAndDelete(s, math.MaxInt)) + expectDeleted(t, s, i)(m.CompareAndDelete(s, i)) + expectNotDeleted(t, s, i)(m.CompareAndDelete(s, i)) + expectMissing(t, s, 0)(m.Load(s)) + } + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + } + }) + t.Run("One", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + expectNotDeleted(t, testData[15], math.MaxInt)(m.CompareAndDelete(testData[15], math.MaxInt)) + expectDeleted(t, testData[15], 15)(m.CompareAndDelete(testData[15], 15)) + expectNotDeleted(t, testData[15], 15)(m.CompareAndDelete(testData[15], 15)) + for i, s := range testData { + if i == 15 { + expectMissing(t, s, 0)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Multiple", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for _, i := range []int{1, 105, 6, 85} { + expectNotDeleted(t, testData[i], math.MaxInt)(m.CompareAndDelete(testData[i], math.MaxInt)) + expectDeleted(t, testData[i], i)(m.CompareAndDelete(testData[i], i)) + expectNotDeleted(t, testData[i], i)(m.CompareAndDelete(testData[i], i)) + } + for i, s := range testData { + if i == 1 || i == 105 || i == 6 || i == 85 { + expectMissing(t, s, 0)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Iterate", func(t *testing.T) { + m := newMap() + + testAll(t, m, testDataMap(testData[:]), func(s string, i int) bool { + expectDeleted(t, s, i)(m.CompareAndDelete(s, i)) + return true + }) + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }) + t.Run("ConcurrentUnsharedKeys", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectStored(t, key, id)(m.LoadOrStore(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoaded(t, key, id)(m.LoadOrStore(key, 0)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectDeleted(t, key, id)(m.CompareAndDelete(key, id)) + expectMissing(t, key, 0)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentSharedKeys", func(t *testing.T) { + m := newMap() + + // Load up the map. + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + } + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + for i, s := range testData { + expectNotDeleted(t, s, math.MaxInt)(m.CompareAndDelete(s, math.MaxInt)) + m.CompareAndDelete(s, i) + expectMissing(t, s, 0)(m.Load(s)) + } + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }(i) + } + wg.Wait() + }) + }) + t.Run("CompareAndSwap", func(t *testing.T) { + t.Run("All", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for j := range 3 { + for i, s := range testData { + expectPresent(t, s, i+j)(m.Load(s)) + expectNotSwapped(t, s, math.MaxInt, i+j+1)(m.CompareAndSwap(s, math.MaxInt, i+j+1)) + expectSwapped(t, s, i, i+j+1)(m.CompareAndSwap(s, i+j, i+j+1)) + expectNotSwapped(t, s, i+j, i+j+1)(m.CompareAndSwap(s, i+j, i+j+1)) + expectPresent(t, s, i+j+1)(m.Load(s)) + } + } + for i, s := range testData { + expectPresent(t, s, i+3)(m.Load(s)) + } + }) + t.Run("One", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + expectNotSwapped(t, testData[15], math.MaxInt, 16)(m.CompareAndSwap(testData[15], math.MaxInt, 16)) + expectSwapped(t, testData[15], 15, 16)(m.CompareAndSwap(testData[15], 15, 16)) + expectNotSwapped(t, testData[15], 15, 16)(m.CompareAndSwap(testData[15], 15, 16)) + for i, s := range testData { + if i == 15 { + expectPresent(t, s, 16)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Multiple", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for _, i := range []int{1, 105, 6, 85} { + expectNotSwapped(t, testData[i], math.MaxInt, i+1)(m.CompareAndSwap(testData[i], math.MaxInt, i+1)) + expectSwapped(t, testData[i], i, i+1)(m.CompareAndSwap(testData[i], i, i+1)) + expectNotSwapped(t, testData[i], i, i+1)(m.CompareAndSwap(testData[i], i, i+1)) + } + for i, s := range testData { + if i == 1 || i == 105 || i == 6 || i == 85 { + expectPresent(t, s, i+1)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + + t.Run("ConcurrentUnsharedKeys", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectStored(t, key, id)(m.LoadOrStore(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoaded(t, key, id)(m.LoadOrStore(key, 0)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectSwapped(t, key, id, id+1)(m.CompareAndSwap(key, id, id+1)) + expectPresent(t, key, id+1)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id+1)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentUnsharedKeysWithDelete", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectStored(t, key, id)(m.LoadOrStore(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoaded(t, key, id)(m.LoadOrStore(key, 0)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectSwapped(t, key, id, id+1)(m.CompareAndSwap(key, id, id+1)) + expectPresent(t, key, id+1)(m.Load(key)) + expectDeleted(t, key, id+1)(m.CompareAndDelete(key, id+1)) + expectNotSwapped(t, key, id+1, id+2)(m.CompareAndSwap(key, id+1, id+2)) + expectNotDeleted(t, key, id+1)(m.CompareAndDelete(key, id+1)) + expectMissing(t, key, 0)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentSharedKeys", func(t *testing.T) { + m := newMap() + + // Load up the map. + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + } + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + for i, s := range testData { + expectNotSwapped(t, s, math.MaxInt, i+1)(m.CompareAndSwap(s, math.MaxInt, i+1)) + m.CompareAndSwap(s, i, i+1) + expectPresent(t, s, i+1)(m.Load(s)) + } + for i, s := range testData { + expectPresent(t, s, i+1)(m.Load(s)) + } + }(i) + } + wg.Wait() + }) + }) + t.Run("Swap", func(t *testing.T) { + t.Run("All", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectNotLoadedFromSwap(t, s, i)(m.Swap(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoadedFromSwap(t, s, i, i)(m.Swap(s, i)) + } + for j := range 3 { + for i, s := range testData { + expectPresent(t, s, i+j)(m.Load(s)) + expectLoadedFromSwap(t, s, i+j, i+j+1)(m.Swap(s, i+j+1)) + expectPresent(t, s, i+j+1)(m.Load(s)) + } + } + for i, s := range testData { + expectLoadedFromSwap(t, s, i+3, i+3)(m.Swap(s, i+3)) + } + }) + t.Run("One", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectNotLoadedFromSwap(t, s, i)(m.Swap(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoadedFromSwap(t, s, i, i)(m.Swap(s, i)) + } + expectLoadedFromSwap(t, testData[15], 15, 16)(m.Swap(testData[15], 16)) + for i, s := range testData { + if i == 15 { + expectPresent(t, s, 16)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Multiple", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectNotLoadedFromSwap(t, s, i)(m.Swap(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoadedFromSwap(t, s, i, i)(m.Swap(s, i)) + } + for _, i := range []int{1, 105, 6, 85} { + expectLoadedFromSwap(t, testData[i], i, i+1)(m.Swap(testData[i], i+1)) + } + for i, s := range testData { + if i == 1 || i == 105 || i == 6 || i == 85 { + expectPresent(t, s, i+1)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("ConcurrentUnsharedKeys", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectNotLoadedFromSwap(t, key, id)(m.Swap(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoadedFromSwap(t, key, id, id)(m.Swap(key, id)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectLoadedFromSwap(t, key, id, id+1)(m.Swap(key, id+1)) + expectPresent(t, key, id+1)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id+1)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentUnsharedKeysWithDelete", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectNotLoadedFromSwap(t, key, id)(m.Swap(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoadedFromSwap(t, key, id, id)(m.Swap(key, id)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectLoadedFromSwap(t, key, id, id+1)(m.Swap(key, id+1)) + expectPresent(t, key, id+1)(m.Load(key)) + expectDeleted(t, key, id+1)(m.CompareAndDelete(key, id+1)) + expectNotLoadedFromSwap(t, key, id+2)(m.Swap(key, id+2)) + expectPresent(t, key, id+2)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id+2)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentSharedKeys", func(t *testing.T) { + m := newMap() + + // Load up the map. + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + } + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + for i, s := range testData { + m.Swap(s, i+1) + expectPresent(t, s, i+1)(m.Load(s)) + } + for i, s := range testData { + expectPresent(t, s, i+1)(m.Load(s)) + } + }(i) + } + wg.Wait() + }) + }) + t.Run("LoadAndDelete", func(t *testing.T) { + t.Run("All", func(t *testing.T) { + m := newMap() + + for range 3 { + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for i, s := range testData { + expectPresent(t, s, i)(m.Load(s)) + expectLoadedFromDelete(t, s, i)(m.LoadAndDelete(s)) + expectMissing(t, s, 0)(m.Load(s)) + expectNotLoadedFromDelete(t, s, 0)(m.LoadAndDelete(s)) + } + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + } + }) + t.Run("One", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + expectPresent(t, testData[15], 15)(m.Load(testData[15])) + expectLoadedFromDelete(t, testData[15], 15)(m.LoadAndDelete(testData[15])) + expectMissing(t, testData[15], 0)(m.Load(testData[15])) + expectNotLoadedFromDelete(t, testData[15], 0)(m.LoadAndDelete(testData[15])) + for i, s := range testData { + if i == 15 { + expectMissing(t, s, 0)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Multiple", func(t *testing.T) { + m := newMap() + + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + expectPresent(t, s, i)(m.Load(s)) + expectLoaded(t, s, i)(m.LoadOrStore(s, 0)) + } + for _, i := range []int{1, 105, 6, 85} { + expectPresent(t, testData[i], i)(m.Load(testData[i])) + expectLoadedFromDelete(t, testData[i], i)(m.LoadAndDelete(testData[i])) + expectMissing(t, testData[i], 0)(m.Load(testData[i])) + expectNotLoadedFromDelete(t, testData[i], 0)(m.LoadAndDelete(testData[i])) + } + for i, s := range testData { + if i == 1 || i == 105 || i == 6 || i == 85 { + expectMissing(t, s, 0)(m.Load(s)) + } else { + expectPresent(t, s, i)(m.Load(s)) + } + } + }) + t.Run("Iterate", func(t *testing.T) { + m := newMap() + + testAll(t, m, testDataMap(testData[:]), func(s string, i int) bool { + expectLoadedFromDelete(t, s, i)(m.LoadAndDelete(s)) + return true + }) + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }) + t.Run("ConcurrentUnsharedKeys", func(t *testing.T) { + m := newMap() + + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + makeKey := func(s string) string { + return s + "-" + strconv.Itoa(id) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + expectStored(t, key, id)(m.LoadOrStore(key, id)) + expectPresent(t, key, id)(m.Load(key)) + expectLoaded(t, key, id)(m.LoadOrStore(key, 0)) + } + for _, s := range testData { + key := makeKey(s) + expectPresent(t, key, id)(m.Load(key)) + expectLoadedFromDelete(t, key, id)(m.LoadAndDelete(key)) + expectMissing(t, key, 0)(m.Load(key)) + } + for _, s := range testData { + key := makeKey(s) + expectMissing(t, key, 0)(m.Load(key)) + } + }(i) + } + wg.Wait() + }) + t.Run("ConcurrentSharedKeys", func(t *testing.T) { + m := newMap() + + // Load up the map. + for i, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + expectStored(t, s, i)(m.LoadOrStore(s, i)) + } + gmp := runtime.GOMAXPROCS(-1) + var wg sync.WaitGroup + for i := range gmp { + wg.Add(1) + go func(id int) { + defer wg.Done() + + for _, s := range testData { + m.LoadAndDelete(s) + expectMissing(t, s, 0)(m.Load(s)) + } + for _, s := range testData { + expectMissing(t, s, 0)(m.Load(s)) + } + }(i) + } + wg.Wait() + }) + }) +} + +func testAll[K, V comparable](t *testing.T, m *isync.HashTrieMap[K, V], testData map[K]V, yield func(K, V) bool) { + for k, v := range testData { + expectStored(t, k, v)(m.LoadOrStore(k, v)) + } + visited := make(map[K]int) + m.All()(func(key K, got V) bool { + want, ok := testData[key] + if !ok { + t.Errorf("unexpected key %v in map", key) + return false + } + if got != want { + t.Errorf("expected key %v to have value %v, got %v", key, want, got) + return false + } + visited[key]++ + return yield(key, got) + }) + for key, n := range visited { + if n > 1 { + t.Errorf("visited key %v more than once", key) + } + } +} + +func expectPresent[K, V comparable](t *testing.T, key K, want V) func(got V, ok bool) { + t.Helper() + return func(got V, ok bool) { + t.Helper() + + if !ok { + t.Errorf("expected key %v to be present in map", key) + } + if ok && got != want { + t.Errorf("expected key %v to have value %v, got %v", key, want, got) + } + } +} + +func expectMissing[K, V comparable](t *testing.T, key K, want V) func(got V, ok bool) { + t.Helper() + if want != *new(V) { + // This is awkward, but the want argument is necessary to smooth over type inference. + // Just make sure the want argument always looks the same. + panic("expectMissing must always have a zero value variable") + } + return func(got V, ok bool) { + t.Helper() + + if ok { + t.Errorf("expected key %v to be missing from map, got value %v", key, got) + } + if !ok && got != want { + t.Errorf("expected missing key %v to be paired with the zero value; got %v", key, got) + } + } +} + +func expectLoaded[K, V comparable](t *testing.T, key K, want V) func(got V, loaded bool) { + t.Helper() + return func(got V, loaded bool) { + t.Helper() + + if !loaded { + t.Errorf("expected key %v to have been loaded, not stored", key) + } + if got != want { + t.Errorf("expected key %v to have value %v, got %v", key, want, got) + } + } +} + +func expectStored[K, V comparable](t *testing.T, key K, want V) func(got V, loaded bool) { + t.Helper() + return func(got V, loaded bool) { + t.Helper() + + if loaded { + t.Errorf("expected inserted key %v to have been stored, not loaded", key) + } + if got != want { + t.Errorf("expected inserted key %v to have value %v, got %v", key, want, got) + } + } +} + +func expectDeleted[K, V comparable](t *testing.T, key K, old V) func(deleted bool) { + t.Helper() + return func(deleted bool) { + t.Helper() + + if !deleted { + t.Errorf("expected key %v with value %v to be in map and deleted", key, old) + } + } +} + +func expectNotDeleted[K, V comparable](t *testing.T, key K, old V) func(deleted bool) { + t.Helper() + return func(deleted bool) { + t.Helper() + + if deleted { + t.Errorf("expected key %v with value %v to not be in map and thus not deleted", key, old) + } + } +} + +func expectSwapped[K, V comparable](t *testing.T, key K, old, new V) func(swapped bool) { + t.Helper() + return func(swapped bool) { + t.Helper() + + if !swapped { + t.Errorf("expected key %v with value %v to be in map and swapped for %v", key, old, new) + } + } +} + +func expectNotSwapped[K, V comparable](t *testing.T, key K, old, new V) func(swapped bool) { + t.Helper() + return func(swapped bool) { + t.Helper() + + if swapped { + t.Errorf("expected key %v with value %v to not be in map or not swapped for %v", key, old, new) + } + } +} + +func expectLoadedFromSwap[K, V comparable](t *testing.T, key K, want, new V) func(got V, loaded bool) { + t.Helper() + return func(got V, loaded bool) { + t.Helper() + + if !loaded { + t.Errorf("expected key %v to be in map and for %v to have been swapped for %v", key, want, new) + } else if want != got { + t.Errorf("key %v had its value %v swapped for %v, but expected it to have value %v", key, got, new, want) + } + } +} + +func expectNotLoadedFromSwap[K, V comparable](t *testing.T, key K, new V) func(old V, loaded bool) { + t.Helper() + return func(old V, loaded bool) { + t.Helper() + + if loaded { + t.Errorf("expected key %v to not be in map, but found value %v for it", key, old) + } + } +} + +func expectLoadedFromDelete[K, V comparable](t *testing.T, key K, want V) func(got V, loaded bool) { + t.Helper() + return func(got V, loaded bool) { + t.Helper() + + if !loaded { + t.Errorf("expected key %v to be in map to be deleted", key) + } else if want != got { + t.Errorf("key %v was deleted with value %v, but expected it to have value %v", key, got, want) + } + } +} + +func expectNotLoadedFromDelete[K, V comparable](t *testing.T, key K, _ V) func(old V, loaded bool) { + t.Helper() + return func(old V, loaded bool) { + t.Helper() + + if loaded { + t.Errorf("expected key %v to not be in map, but found value %v for it", key, old) + } + } +} + +func testDataMap(data []string) map[string]int { + m := make(map[string]int) + for i, s := range data { + m[s] = i + } + return m +} + +var ( + testDataSmall [8]string + testData [128]string + testDataLarge [128 << 10]string +) + +func init() { + for i := range testDataSmall { + testDataSmall[i] = fmt.Sprintf("%b", i) + } + for i := range testData { + testData[i] = fmt.Sprintf("%b", i) + } + for i := range testDataLarge { + testDataLarge[i] = fmt.Sprintf("%b", i) + } +} + +// TestConcurrentCache tests HashTrieMap in a scenario where it is used as +// the basis of a memory-efficient concurrent cache. We're specifically +// looking to make sure that CompareAndSwap and CompareAndDelete are +// atomic with respect to one another. When competing for the same +// key-value pair, they must not both succeed. +// +// This test is a regression test for issue #70970. +func TestConcurrentCache(t *testing.T) { + type dummy [32]byte + + var m isync.HashTrieMap[int, weak.Pointer[dummy]] + + type cleanupArg struct { + key int + value weak.Pointer[dummy] + } + cleanup := func(arg cleanupArg) { + m.CompareAndDelete(arg.key, arg.value) + } + get := func(m *isync.HashTrieMap[int, weak.Pointer[dummy]], key int) *dummy { + nv := new(dummy) + nw := weak.Make(nv) + for { + w, loaded := m.LoadOrStore(key, nw) + if !loaded { + runtime.AddCleanup(nv, cleanup, cleanupArg{key, nw}) + return nv + } + if v := w.Value(); v != nil { + return v + } + + // Weak pointer was reclaimed, try to replace it with nw. + if m.CompareAndSwap(key, w, nw) { + runtime.AddCleanup(nv, cleanup, cleanupArg{key, nw}) + return nv + } + } + } + + const N = 100_000 + const P = 5_000 + + var wg sync.WaitGroup + wg.Add(N) + for i := range N { + go func() { + defer wg.Done() + a := get(&m, i%P) + b := get(&m, i%P) + if a != b { + t.Errorf("consecutive cache reads returned different values: a != b (%p vs %p)\n", a, b) + } + }() + } + wg.Wait() +} diff --git a/go/src/internal/sync/mutex.go b/go/src/internal/sync/mutex.go new file mode 100644 index 0000000000000000000000000000000000000000..c0c526a77cbb77f4105ae90dcbc75128c33bf12c --- /dev/null +++ b/go/src/internal/sync/mutex.go @@ -0,0 +1,234 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package sync provides basic synchronization primitives such as mutual +// exclusion locks to internal packages (including ones that depend on sync). +// +// Tests are defined in package [sync]. +package sync + +import ( + "internal/race" + "sync/atomic" + "unsafe" +) + +// A Mutex is a mutual exclusion lock. +// +// See package [sync.Mutex] documentation. +type Mutex struct { + state int32 + sema uint32 +} + +const ( + mutexLocked = 1 << iota // mutex is locked + mutexWoken + mutexStarving + mutexWaiterShift = iota + + // Mutex fairness. + // + // Mutex can be in 2 modes of operations: normal and starvation. + // In normal mode waiters are queued in FIFO order, but a woken up waiter + // does not own the mutex and competes with new arriving goroutines over + // the ownership. New arriving goroutines have an advantage -- they are + // already running on CPU and there can be lots of them, so a woken up + // waiter has good chances of losing. In such case it is queued at front + // of the wait queue. If a waiter fails to acquire the mutex for more than 1ms, + // it switches mutex to the starvation mode. + // + // In starvation mode ownership of the mutex is directly handed off from + // the unlocking goroutine to the waiter at the front of the queue. + // New arriving goroutines don't try to acquire the mutex even if it appears + // to be unlocked, and don't try to spin. Instead they queue themselves at + // the tail of the wait queue. + // + // If a waiter receives ownership of the mutex and sees that either + // (1) it is the last waiter in the queue, or (2) it waited for less than 1 ms, + // it switches mutex back to normal operation mode. + // + // Normal mode has considerably better performance as a goroutine can acquire + // a mutex several times in a row even if there are blocked waiters. + // Starvation mode is important to prevent pathological cases of tail latency. + starvationThresholdNs = 1e6 +) + +// Lock locks m. +// +// See package [sync.Mutex] documentation. +func (m *Mutex) Lock() { + // Fast path: grab unlocked mutex. + if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) { + if race.Enabled { + race.Acquire(unsafe.Pointer(m)) + } + return + } + // Slow path (outlined so that the fast path can be inlined) + m.lockSlow() +} + +// TryLock tries to lock m and reports whether it succeeded. +// +// See package [sync.Mutex] documentation. +func (m *Mutex) TryLock() bool { + old := m.state + if old&(mutexLocked|mutexStarving) != 0 { + return false + } + + // There may be a goroutine waiting for the mutex, but we are + // running now and can try to grab the mutex before that + // goroutine wakes up. + if !atomic.CompareAndSwapInt32(&m.state, old, old|mutexLocked) { + return false + } + + if race.Enabled { + race.Acquire(unsafe.Pointer(m)) + } + return true +} + +func (m *Mutex) lockSlow() { + var waitStartTime int64 + starving := false + awoke := false + iter := 0 + old := m.state + for { + // Don't spin in starvation mode, ownership is handed off to waiters + // so we won't be able to acquire the mutex anyway. + if old&(mutexLocked|mutexStarving) == mutexLocked && runtime_canSpin(iter) { + // Active spinning makes sense. + // Try to set mutexWoken flag to inform Unlock + // to not wake other blocked goroutines. + if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 && + atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) { + awoke = true + } + runtime_doSpin() + iter++ + old = m.state + continue + } + new := old + // Don't try to acquire starving mutex, new arriving goroutines must queue. + if old&mutexStarving == 0 { + new |= mutexLocked + } + if old&(mutexLocked|mutexStarving) != 0 { + new += 1 << mutexWaiterShift + } + // The current goroutine switches mutex to starvation mode. + // But if the mutex is currently unlocked, don't do the switch. + // Unlock expects that starving mutex has waiters, which will not + // be true in this case. + if starving && old&mutexLocked != 0 { + new |= mutexStarving + } + if awoke { + // The goroutine has been woken from sleep, + // so we need to reset the flag in either case. + if new&mutexWoken == 0 { + throw("sync: inconsistent mutex state") + } + new &^= mutexWoken + } + if atomic.CompareAndSwapInt32(&m.state, old, new) { + if old&(mutexLocked|mutexStarving) == 0 { + break // locked the mutex with CAS + } + // If we were already waiting before, queue at the front of the queue. + queueLifo := waitStartTime != 0 + if waitStartTime == 0 { + waitStartTime = runtime_nanotime() + } + runtime_SemacquireMutex(&m.sema, queueLifo, 2) + starving = starving || runtime_nanotime()-waitStartTime > starvationThresholdNs + old = m.state + if old&mutexStarving != 0 { + // If this goroutine was woken and mutex is in starvation mode, + // ownership was handed off to us but mutex is in somewhat + // inconsistent state: mutexLocked is not set and we are still + // accounted as waiter. Fix that. + if old&(mutexLocked|mutexWoken) != 0 || old>>mutexWaiterShift == 0 { + throw("sync: inconsistent mutex state") + } + delta := int32(mutexLocked - 1<>mutexWaiterShift == 1 { + // Exit starvation mode. + // Critical to do it here and consider wait time. + // Starvation mode is so inefficient, that two goroutines + // can go lock-step infinitely once they switch mutex + // to starvation mode. + delta -= mutexStarving + } + atomic.AddInt32(&m.state, delta) + break + } + awoke = true + iter = 0 + } else { + old = m.state + } + } + + if race.Enabled { + race.Acquire(unsafe.Pointer(m)) + } +} + +// Unlock unlocks m. +// +// See package [sync.Mutex] documentation. +func (m *Mutex) Unlock() { + if race.Enabled { + _ = m.state + race.Release(unsafe.Pointer(m)) + } + + // Fast path: drop lock bit. + new := atomic.AddInt32(&m.state, -mutexLocked) + if new != 0 { + // Outlined slow path to allow inlining the fast path. + // To hide unlockSlow during tracing we skip one extra frame when tracing GoUnblock. + m.unlockSlow(new) + } +} + +func (m *Mutex) unlockSlow(new int32) { + if (new+mutexLocked)&mutexLocked == 0 { + fatal("sync: unlock of unlocked mutex") + } + if new&mutexStarving == 0 { + old := new + for { + // If there are no waiters or a goroutine has already + // been woken or grabbed the lock, no need to wake anyone. + // In starvation mode ownership is directly handed off from unlocking + // goroutine to the next waiter. We are not part of this chain, + // since we did not observe mutexStarving when we unlocked the mutex above. + // So get off the way. + if old>>mutexWaiterShift == 0 || old&(mutexLocked|mutexWoken|mutexStarving) != 0 { + return + } + // Grab the right to wake someone. + new = (old - 1<= 3 { + break + } + } + }() + want := []time.Time{ + time.Now(), + time.Now().Add(1 * time.Second), + time.Now().Add(2 * time.Second), + } + time.Sleep(5 * time.Second) + synctest.Wait() + if !slices.Equal(got, want) { + t.Errorf("got: %v; want: %v", got, want) + } + }) +} + +func TestIteratorPull(t *testing.T) { + synctest.Run(func() { + seq := func(yield func(time.Time) bool) { + for yield(time.Now()) { + time.Sleep(1 * time.Second) + } + } + var got []time.Time + go func() { + next, stop := iter.Pull(seq) + defer stop() + for len(got) < 3 { + now, _ := next() + got = append(got, now) + } + }() + want := []time.Time{ + time.Now(), + time.Now().Add(1 * time.Second), + time.Now().Add(2 * time.Second), + } + time.Sleep(5 * time.Second) + synctest.Wait() + if !slices.Equal(got, want) { + t.Errorf("got: %v; want: %v", got, want) + } + }) +} + +func TestReflectFuncOf(t *testing.T) { + mkfunc := func(name string, i int) { + reflect.FuncOf([]reflect.Type{ + reflect.StructOf([]reflect.StructField{{ + Name: name + strconv.Itoa(i), + Type: reflect.TypeOf(0), + }}), + }, nil, false) + } + go func() { + for i := 0; i < 100000; i++ { + mkfunc("A", i) + } + }() + synctest.Run(func() { + for i := 0; i < 100000; i++ { + mkfunc("A", i) + } + }) +} + +func TestWaitGroupInBubble(t *testing.T) { + synctest.Run(func() { + var wg sync.WaitGroup + wg.Add(1) + const delay = 1 * time.Second + go func() { + time.Sleep(delay) + wg.Done() + }() + start := time.Now() + wg.Wait() + if got := time.Since(start); got != delay { + t.Fatalf("WaitGroup.Wait() took %v, want %v", got, delay) + } + }) +} + +// https://go.dev/issue/74386 +func TestWaitGroupRacingAdds(t *testing.T) { + synctest.Run(func() { + var wg sync.WaitGroup + for range 100 { + wg.Go(func() {}) + } + wg.Wait() + }) +} + +func TestWaitGroupOutOfBubble(t *testing.T) { + var wg sync.WaitGroup + wg.Add(1) + donec := make(chan struct{}) + go synctest.Run(func() { + // Since wg.Add was called outside the bubble, Wait is not durably blocking + // and this waits until wg.Done is called below. + wg.Wait() + close(donec) + }) + select { + case <-donec: + t.Fatalf("synctest.Run finished before WaitGroup.Done called") + case <-time.After(1 * time.Millisecond): + } + wg.Done() + <-donec +} + +func TestWaitGroupMovedIntoBubble(t *testing.T) { + wantFatal(t, "fatal error: sync: WaitGroup.Add called from inside and outside synctest bubble", func() { + var wg sync.WaitGroup + wg.Add(1) + synctest.Run(func() { + wg.Add(1) + }) + }) +} + +func TestWaitGroupMovedOutOfBubble(t *testing.T) { + wantFatal(t, "fatal error: sync: WaitGroup.Add called from inside and outside synctest bubble", func() { + var wg sync.WaitGroup + synctest.Run(func() { + wg.Add(1) + }) + wg.Add(1) + }) +} + +func TestWaitGroupMovedBetweenBubblesWithNonZeroCount(t *testing.T) { + wantFatal(t, "fatal error: sync: WaitGroup.Add called from multiple synctest bubbles", func() { + var wg sync.WaitGroup + synctest.Run(func() { + wg.Add(1) + }) + synctest.Run(func() { + wg.Add(1) + }) + }) +} + +func TestWaitGroupDisassociateInWait(t *testing.T) { + var wg sync.WaitGroup + synctest.Run(func() { + wg.Add(1) + wg.Done() + // Count and waiters are 0, so Wait disassociates the WaitGroup. + wg.Wait() + }) + synctest.Run(func() { + // Reusing the WaitGroup is safe, because it is no longer bubbled. + wg.Add(1) + wg.Done() + }) +} + +func TestWaitGroupDisassociateInAdd(t *testing.T) { + var wg sync.WaitGroup + synctest.Run(func() { + wg.Add(1) + go wg.Wait() + synctest.Wait() // wait for Wait to block + // Count is 0 and waiters != 0, so Done wakes the waiters and + // disassociates the WaitGroup. + wg.Done() + }) + synctest.Run(func() { + // Reusing the WaitGroup is safe, because it is no longer bubbled. + wg.Add(1) + wg.Done() + }) +} + +var testWaitGroupLinkerAllocatedWG sync.WaitGroup + +func TestWaitGroupLinkerAllocated(t *testing.T) { + synctest.Run(func() { + // This WaitGroup is probably linker-allocated and has no span, + // so we won't be able to add a special to it associating it with + // this bubble. + // + // Operations on it may not be durably blocking, + // but they shouldn't fail. + testWaitGroupLinkerAllocatedWG.Go(func() {}) + testWaitGroupLinkerAllocatedWG.Wait() + }) +} + +var testWaitGroupHeapAllocatedWG = new(sync.WaitGroup) + +func TestWaitGroupHeapAllocated(t *testing.T) { + synctest.Run(func() { + // This package-scoped WaitGroup var should have been heap-allocated, + // so we can associate it with a bubble. + testWaitGroupHeapAllocatedWG.Add(1) + go testWaitGroupHeapAllocatedWG.Wait() + synctest.Wait() + testWaitGroupHeapAllocatedWG.Done() + }) +} + +// Issue #75134: Many racing bubble associations. +func TestWaitGroupManyBubbles(t *testing.T) { + var wg sync.WaitGroup + for range 100 { + wg.Go(func() { + synctest.Run(func() { + cancelc := make(chan struct{}) + var wg2 sync.WaitGroup + for range 100 { + wg2.Go(func() { + <-cancelc + }) + } + synctest.Wait() + close(cancelc) + wg2.Wait() + }) + }) + } + wg.Wait() +} + +func TestHappensBefore(t *testing.T) { + // Use two parallel goroutines accessing different vars to ensure that + // we correctly account for multiple goroutines in the bubble. + var v1 int + var v2 int + synctest.Run(func() { + v1++ // 1 + v2++ // 1 + + // Wait returns after these goroutines exit. + go func() { + v1++ // 2 + }() + go func() { + v2++ // 2 + }() + synctest.Wait() + + v1++ // 3 + v2++ // 3 + + // Wait returns after these goroutines block. + ch1 := make(chan struct{}) + go func() { + v1++ // 4 + <-ch1 + }() + go func() { + v2++ // 4 + <-ch1 + }() + synctest.Wait() + + v1++ // 5 + v2++ // 5 + close(ch1) + + // Wait returns after these timers run. + time.AfterFunc(0, func() { + v1++ // 6 + }) + time.AfterFunc(0, func() { + v2++ // 6 + }) + synctest.Wait() + + v1++ // 7 + v2++ // 7 + + // Wait returns after these timer goroutines block. + ch2 := make(chan struct{}) + time.AfterFunc(0, func() { + v1++ // 8 + <-ch2 + }) + time.AfterFunc(0, func() { + v2++ // 8 + <-ch2 + }) + synctest.Wait() + + v1++ // 9 + v2++ // 9 + close(ch2) + }) + // This Run happens after the previous Run returns. + synctest.Run(func() { + go func() { + go func() { + v1++ // 10 + }() + }() + go func() { + go func() { + v2++ // 10 + }() + }() + }) + // These tests happen after Run returns. + if got, want := v1, 10; got != want { + t.Errorf("v1 = %v, want %v", got, want) + } + if got, want := v2, 10; got != want { + t.Errorf("v2 = %v, want %v", got, want) + } +} + +// https://go.dev/issue/73817 +func TestWeak(t *testing.T) { + synctest.Run(func() { + for range 5 { + runtime.GC() + b := make([]byte, 1024) + weak.Make(&b) + } + }) +} + +func wantPanic(t *testing.T, want string) { + if e := recover(); e != nil { + if got := fmt.Sprint(e); got != want { + t.Errorf("got panic message %q, want %q", got, want) + } + } else { + t.Errorf("got no panic, want one") + } +} + +func wantFatal(t *testing.T, want string, f func()) { + t.Helper() + + if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { + f() + return + } + + cmd := testenv.Command(t, testenv.Executable(t), "-test.run=^"+t.Name()+"$") + cmd = testenv.CleanCmdEnv(cmd) + cmd.Env = append(cmd.Env, "GO_WANT_HELPER_PROCESS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Errorf("expected test function to panic, but test returned successfully") + } + if !strings.Contains(string(out), want) { + t.Errorf("wanted test output contaiing %q; got %q", want, string(out)) + } +} diff --git a/go/src/internal/syscall/execenv/execenv_default.go b/go/src/internal/syscall/execenv/execenv_default.go new file mode 100644 index 0000000000000000000000000000000000000000..335647c63813cd87ee7ddbfce44eca25d70edd90 --- /dev/null +++ b/go/src/internal/syscall/execenv/execenv_default.go @@ -0,0 +1,19 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows + +package execenv + +import "syscall" + +// Default will return the default environment +// variables based on the process attributes +// provided. +// +// Defaults to syscall.Environ() on all platforms +// other than Windows. +func Default(sys *syscall.SysProcAttr) ([]string, error) { + return syscall.Environ(), nil +} diff --git a/go/src/internal/syscall/execenv/execenv_windows.go b/go/src/internal/syscall/execenv/execenv_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..2a89ed1f58f1c42c04ec88b384cfc8d6436f77aa --- /dev/null +++ b/go/src/internal/syscall/execenv/execenv_windows.go @@ -0,0 +1,47 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build windows + +package execenv + +import ( + "internal/syscall/windows" + "syscall" + "unsafe" +) + +// Default will return the default environment +// variables based on the process attributes +// provided. +// +// If the process attributes contain a token, then +// the environment variables will be sourced from +// the defaults for that user token, otherwise they +// will be sourced from syscall.Environ(). +func Default(sys *syscall.SysProcAttr) (env []string, err error) { + if sys == nil || sys.Token == 0 { + return syscall.Environ(), nil + } + var blockp *uint16 + err = windows.CreateEnvironmentBlock(&blockp, sys.Token, false) + if err != nil { + return nil, err + } + defer windows.DestroyEnvironmentBlock(blockp) + + const size = unsafe.Sizeof(*blockp) + for *blockp != 0 { // environment block ends with empty string + // find NUL terminator + end := unsafe.Add(unsafe.Pointer(blockp), size) + for *(*uint16)(end) != 0 { + end = unsafe.Add(end, size) + } + + entry := unsafe.Slice(blockp, (uintptr(end)-uintptr(unsafe.Pointer(blockp)))/2) + env = append(env, syscall.UTF16ToString(entry)) + blockp = (*uint16)(unsafe.Add(end, size)) + } + return +} diff --git a/go/src/internal/syscall/unix/arandom_netbsd.go b/go/src/internal/syscall/unix/arandom_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..23ca8739e81b2394c10248acc7ee69c43d6cdc2b --- /dev/null +++ b/go/src/internal/syscall/unix/arandom_netbsd.go @@ -0,0 +1,36 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" + "unsafe" +) + +const ( + _CTL_KERN = 1 + + _KERN_ARND = 81 +) + +func Arandom(p []byte) error { + mib := [2]uint32{_CTL_KERN, _KERN_ARND} + n := uintptr(len(p)) + _, _, errno := syscall.Syscall6( + syscall.SYS___SYSCTL, + uintptr(unsafe.Pointer(&mib[0])), + uintptr(len(mib)), + uintptr(unsafe.Pointer(&p[0])), // olddata + uintptr(unsafe.Pointer(&n)), // &oldlen + uintptr(unsafe.Pointer(nil)), // newdata + 0) // newlen + if errno != 0 { + return syscall.Errno(errno) + } + if n != uintptr(len(p)) { + return syscall.EINVAL + } + return nil +} diff --git a/go/src/internal/syscall/unix/arc4random_darwin.go b/go/src/internal/syscall/unix/arc4random_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..a78204a3559a86a88d2675d8e075a1f82f7700fb --- /dev/null +++ b/go/src/internal/syscall/unix/arc4random_darwin.go @@ -0,0 +1,24 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "internal/abi" + "unsafe" +) + +//go:cgo_import_dynamic libc_arc4random_buf arc4random_buf "/usr/lib/libSystem.B.dylib" + +func libc_arc4random_buf_trampoline() + +// ARC4Random calls the macOS arc4random_buf(3) function. +func ARC4Random(p []byte) { + // macOS 11 and 12 abort if length is 0. + if len(p) == 0 { + return + } + syscall_syscall(abi.FuncPCABI0(libc_arc4random_buf_trampoline), + uintptr(unsafe.Pointer(unsafe.SliceData(p))), uintptr(len(p)), 0) +} diff --git a/go/src/internal/syscall/unix/arc4random_openbsd.go b/go/src/internal/syscall/unix/arc4random_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..652e0cb19d600f1109d6db92dd3614672e2aa32d --- /dev/null +++ b/go/src/internal/syscall/unix/arc4random_openbsd.go @@ -0,0 +1,23 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +//go:linkname syscall_syscall syscall.syscall +func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:cgo_import_dynamic libc_arc4random_buf arc4random_buf "libc.so" + +func libc_arc4random_buf_trampoline() + +func ARC4Random(p []byte) { + syscall_syscall(abi.FuncPCABI0(libc_arc4random_buf_trampoline), + uintptr(unsafe.Pointer(unsafe.SliceData(p))), uintptr(len(p)), 0) +} diff --git a/go/src/internal/syscall/unix/asm_aix_ppc64.s b/go/src/internal/syscall/unix/asm_aix_ppc64.s new file mode 100644 index 0000000000000000000000000000000000000000..9e82e3eb88bb88dffd44bfa57f2fcfd8036ef92c --- /dev/null +++ b/go/src/internal/syscall/unix/asm_aix_ppc64.s @@ -0,0 +1,12 @@ +// 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" + +// +// System calls for aix/ppc64 are implemented in syscall/syscall_aix.go +// + +TEXT ·syscall6(SB),NOSPLIT,$0 + JMP syscall·syscall6(SB) diff --git a/go/src/internal/syscall/unix/asm_darwin.s b/go/src/internal/syscall/unix/asm_darwin.s new file mode 100644 index 0000000000000000000000000000000000000000..9803c7260f08fe70e59bcd8c133adbdac45d9bb5 --- /dev/null +++ b/go/src/internal/syscall/unix/asm_darwin.s @@ -0,0 +1,32 @@ +// 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. + +#include "textflag.h" + +TEXT ·libc_arc4random_buf_trampoline(SB),NOSPLIT,$0-0; JMP libc_arc4random_buf(SB) +TEXT ·libc_getaddrinfo_trampoline(SB),NOSPLIT,$0-0; JMP libc_getaddrinfo(SB) +TEXT ·libc_freeaddrinfo_trampoline(SB),NOSPLIT,$0-0; JMP libc_freeaddrinfo(SB) +TEXT ·libc_getnameinfo_trampoline(SB),NOSPLIT,$0-0; JMP libc_getnameinfo(SB) +TEXT ·libc_gai_strerror_trampoline(SB),NOSPLIT,$0-0; JMP libc_gai_strerror(SB) +TEXT ·libresolv_res_9_ninit_trampoline(SB),NOSPLIT,$0-0; JMP libresolv_res_9_ninit(SB) +TEXT ·libresolv_res_9_nclose_trampoline(SB),NOSPLIT,$0-0; JMP libresolv_res_9_nclose(SB) +TEXT ·libresolv_res_9_nsearch_trampoline(SB),NOSPLIT,$0-0; JMP libresolv_res_9_nsearch(SB) +TEXT ·libc_grantpt_trampoline(SB),NOSPLIT,$0-0; JMP libc_grantpt(SB) +TEXT ·libc_unlockpt_trampoline(SB),NOSPLIT,$0-0; JMP libc_unlockpt(SB) +TEXT ·libc_ptsname_r_trampoline(SB),NOSPLIT,$0-0; JMP libc_ptsname_r(SB) +TEXT ·libc_posix_openpt_trampoline(SB),NOSPLIT,$0-0; JMP libc_posix_openpt(SB) +TEXT ·libc_getgrouplist_trampoline(SB),NOSPLIT,$0-0; JMP libc_getgrouplist(SB) +TEXT ·libc_getpwnam_r_trampoline(SB),NOSPLIT,$0-0; JMP libc_getpwnam_r(SB) +TEXT ·libc_getpwuid_r_trampoline(SB),NOSPLIT,$0-0; JMP libc_getpwuid_r(SB) +TEXT ·libc_getgrnam_r_trampoline(SB),NOSPLIT,$0-0; JMP libc_getgrnam_r(SB) +TEXT ·libc_getgrgid_r_trampoline(SB),NOSPLIT,$0-0; JMP libc_getgrgid_r(SB) +TEXT ·libc_sysconf_trampoline(SB),NOSPLIT,$0-0; JMP libc_sysconf(SB) +TEXT ·libc_faccessat_trampoline(SB),NOSPLIT,$0-0; JMP libc_faccessat(SB) +TEXT ·libc_readlinkat_trampoline(SB),NOSPLIT,$0-0; JMP libc_readlinkat(SB) +TEXT ·libc_mkdirat_trampoline(SB),NOSPLIT,$0-0; JMP libc_mkdirat(SB) +TEXT ·libc_fchmodat_trampoline(SB),NOSPLIT,$0-0; JMP libc_fchmodat(SB) +TEXT ·libc_fchownat_trampoline(SB),NOSPLIT,$0-0; JMP libc_fchownat(SB) +TEXT ·libc_renameat_trampoline(SB),NOSPLIT,$0-0; JMP libc_renameat(SB) +TEXT ·libc_linkat_trampoline(SB),NOSPLIT,$0-0; JMP libc_linkat(SB) +TEXT ·libc_symlinkat_trampoline(SB),NOSPLIT,$0-0; JMP libc_symlinkat(SB) diff --git a/go/src/internal/syscall/unix/asm_openbsd.s b/go/src/internal/syscall/unix/asm_openbsd.s new file mode 100644 index 0000000000000000000000000000000000000000..d7c230555c3bbc2aab322933454ee754a1164726 --- /dev/null +++ b/go/src/internal/syscall/unix/asm_openbsd.s @@ -0,0 +1,26 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build openbsd && !mips64 + +#include "textflag.h" + +TEXT ·libc_faccessat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_faccessat(SB) +TEXT ·libc_arc4random_buf_trampoline(SB),NOSPLIT,$0-0 + JMP libc_arc4random_buf(SB) +TEXT ·libc_readlinkat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_readlinkat(SB) +TEXT ·libc_mkdirat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_mkdirat(SB) +TEXT ·libc_fchmodat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchmodat(SB) +TEXT ·libc_fchownat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchownat(SB) +TEXT ·libc_renameat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_renameat(SB) +TEXT ·libc_linkat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_linkat(SB) +TEXT ·libc_symlinkat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_symlinkat(SB) diff --git a/go/src/internal/syscall/unix/asm_solaris.s b/go/src/internal/syscall/unix/asm_solaris.s new file mode 100644 index 0000000000000000000000000000000000000000..361ca7fc2a8ca2d6d7b1611db3da7013383f04bd --- /dev/null +++ b/go/src/internal/syscall/unix/asm_solaris.s @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// System calls for Solaris are implemented in runtime/syscall_solaris.go + +TEXT ·syscall6(SB),NOSPLIT,$0-88 + JMP syscall·sysvicall6(SB) + +TEXT ·rawSyscall6(SB),NOSPLIT,$0-88 + JMP syscall·rawSysvicall6(SB) diff --git a/go/src/internal/syscall/unix/at.go b/go/src/internal/syscall/unix/at.go new file mode 100644 index 0000000000000000000000000000000000000000..359a2da995e5fdad180eb750c3c5913f4eb1c846 --- /dev/null +++ b/go/src/internal/syscall/unix/at.go @@ -0,0 +1,162 @@ +// 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 dragonfly || freebsd || linux || netbsd || (openbsd && mips64) + +package unix + +import ( + "syscall" + "unsafe" +) + +func Unlinkat(dirfd int, path string, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall.Syscall(unlinkatTrap, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(flags)) + if errno != 0 { + return errno + } + + return nil +} + +func Openat(dirfd int, path string, flags int, perm uint32) (int, error) { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + + fd, _, errno := syscall.Syscall6(openatTrap, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(flags), uintptr(perm), 0, 0) + if errno != 0 { + return 0, errno + } + + return int(fd), nil +} + +func Readlinkat(dirfd int, path string, buf []byte) (int, error) { + p0, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + var p1 unsafe.Pointer + if len(buf) > 0 { + p1 = unsafe.Pointer(&buf[0]) + } else { + p1 = unsafe.Pointer(&_zero) + } + n, _, errno := syscall.Syscall6(readlinkatTrap, + uintptr(dirfd), + uintptr(unsafe.Pointer(p0)), + uintptr(p1), + uintptr(len(buf)), + 0, 0) + if errno != 0 { + return 0, errno + } + + return int(n), nil +} + +func Mkdirat(dirfd int, path string, mode uint32) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall.Syscall6(mkdiratTrap, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} + +func Fchownat(dirfd int, path string, uid, gid int, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall.Syscall6(fchownatTrap, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(uid), + uintptr(gid), + uintptr(flags), + 0) + if errno != 0 { + return errno + } + return nil +} + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall.Syscall6(renameatTrap, + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flag int) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall.Syscall6(linkatTrap, + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + uintptr(flag), + 0) + if errno != 0 { + return errno + } + return nil +} + +func Symlinkat(oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall.Syscall(symlinkatTrap, + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp))) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/at_aix.go b/go/src/internal/syscall/unix/at_aix.go new file mode 100644 index 0000000000000000000000000000000000000000..8bf7b4dd81bb8e768f8eac112b82bd578d38951c --- /dev/null +++ b/go/src/internal/syscall/unix/at_aix.go @@ -0,0 +1,24 @@ +// 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 unix + +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_fchownat fchownat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_fstatat fstatat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_linkat linkat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_openat openat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_renameat renameat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.a/shr_64.o" +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.a/shr_64.o" + +const ( + AT_EACCESS = 0x1 + AT_FDCWD = -0x02 + AT_REMOVEDIR = 0x1 + AT_SYMLINK_NOFOLLOW = 0x1 + UTIME_OMIT = -0x3 +) diff --git a/go/src/internal/syscall/unix/at_darwin.go b/go/src/internal/syscall/unix/at_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..c74c827626a575c0a5cb05eb7ce9a861e82f3dd3 --- /dev/null +++ b/go/src/internal/syscall/unix/at_darwin.go @@ -0,0 +1,182 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +func libc_readlinkat_trampoline() + +//go:cgo_import_dynamic libc_readlinkat readlinkat "/usr/lib/libSystem.B.dylib" + +func Readlinkat(dirfd int, path string, buf []byte) (int, error) { + p0, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + var p1 unsafe.Pointer + if len(buf) > 0 { + p1 = unsafe.Pointer(&buf[0]) + } else { + p1 = unsafe.Pointer(&_zero) + } + n, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_readlinkat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p0)), + uintptr(p1), + uintptr(len(buf)), + 0, + 0) + if errno != 0 { + return 0, errno + } + return int(n), nil +} + +func libc_mkdirat_trampoline() + +//go:cgo_import_dynamic libc_mkdirat mkdirat "/usr/lib/libSystem.B.dylib" + +func Mkdirat(dirfd int, path string, mode uint32) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall(abi.FuncPCABI0(libc_mkdirat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode)) + if errno != 0 { + return errno + } + return nil +} + +func libc_fchmodat_trampoline() + +//go:cgo_import_dynamic libc_fchmodat fchmodat "/usr/lib/libSystem.B.dylib" + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_fchmodat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + uintptr(flags), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_fchownat_trampoline() + +//go:cgo_import_dynamic libc_fchownat fchownat "/usr/lib/libSystem.B.dylib" + +func Fchownat(dirfd int, path string, uid, gid int, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_fchownat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(uid), + uintptr(gid), + uintptr(flags), + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_renameat_trampoline() + +//go:cgo_import_dynamic libc_renameat renameat "/usr/lib/libSystem.B.dylib" + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_renameat_trampoline), + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_linkat_trampoline() + +//go:cgo_import_dynamic libc_linkat linkat "/usr/lib/libSystem.B.dylib" + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flag int) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_linkat_trampoline), + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + uintptr(flag), + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_symlinkat_trampoline() + +//go:cgo_import_dynamic libc_symlinkat symlinkat "/usr/lib/libSystem.B.dylib" + +func Symlinkat(oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_symlinkat_trampoline), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0, + 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/at_fstatat.go b/go/src/internal/syscall/unix/at_fstatat.go new file mode 100644 index 0000000000000000000000000000000000000000..18cd62be203556f2348693c8a8c78903e263af58 --- /dev/null +++ b/go/src/internal/syscall/unix/at_fstatat.go @@ -0,0 +1,27 @@ +// 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 dragonfly || (linux && !(loong64 || mips64 || mips64le)) || netbsd || (openbsd && mips64) + +package unix + +import ( + "syscall" + "unsafe" +) + +func Fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error { + var p *byte + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall.Syscall6(fstatatTrap, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if errno != 0 { + return errno + } + + return nil +} diff --git a/go/src/internal/syscall/unix/at_fstatat2.go b/go/src/internal/syscall/unix/at_fstatat2.go new file mode 100644 index 0000000000000000000000000000000000000000..b09aecbcdda4dd137a7a0f6b4143a85d442a1f6b --- /dev/null +++ b/go/src/internal/syscall/unix/at_fstatat2.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build freebsd || (linux && (loong64 || mips64 || mips64le)) + +package unix + +import "syscall" + +func Fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error { + return syscall.Fstatat(dirfd, path, stat, flags) +} diff --git a/go/src/internal/syscall/unix/at_js.go b/go/src/internal/syscall/unix/at_js.go new file mode 100644 index 0000000000000000000000000000000000000000..d05ccce8957b10e5e834370f1c1c84ad84c1ca0f --- /dev/null +++ b/go/src/internal/syscall/unix/at_js.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +const ( + // UTIME_OMIT is the sentinel value to indicate that a time value should not + // be changed. It is useful for example to indicate for example with UtimesNano + // to avoid changing AccessTime or ModifiedTime. + // Its value must match syscall/fs_js.go + UTIME_OMIT = -0x2 +) diff --git a/go/src/internal/syscall/unix/at_libc.go b/go/src/internal/syscall/unix/at_libc.go new file mode 100644 index 0000000000000000000000000000000000000000..5c64b34d48f5d75b3c7fcbea1f8d6a896cdd3c5c --- /dev/null +++ b/go/src/internal/syscall/unix/at_libc.go @@ -0,0 +1,232 @@ +// 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 aix || solaris + +package unix + +import ( + "syscall" + "unsafe" +) + +//go:linkname procFstatat libc_fstatat +//go:linkname procOpenat libc_openat +//go:linkname procUnlinkat libc_unlinkat +//go:linkname procReadlinkat libc_readlinkat +//go:linkname procMkdirat libc_mkdirat +//go:linkname procFchmodat libc_fchmodat +//go:linkname procFchownat libc_fchownat +//go:linkname procRenameat libc_renameat +//go:linkname procLinkat libc_linkat +//go:linkname procSymlinkat libc_symlinkat + +var ( + procFstatat, + procOpenat, + procUnlinkat, + procReadlinkat, + procMkdirat, + procFchmodat, + procFchownat, + procRenameat, + procLinkat, + procSymlinkat uintptr +) + +func Unlinkat(dirfd int, path string, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procUnlinkat)), 3, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(flags), + 0, 0, 0) + if errno != 0 { + return errno + } + + return nil +} + +func Openat(dirfd int, path string, flags int, perm uint32) (int, error) { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + + fd, _, errno := syscall6(uintptr(unsafe.Pointer(&procOpenat)), 4, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(flags), + uintptr(perm), + 0, 0) + if errno != 0 { + return 0, errno + } + + return int(fd), nil +} + +func Fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procFstatat)), 4, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(unsafe.Pointer(stat)), + uintptr(flags), + 0, 0) + if errno != 0 { + return errno + } + + return nil +} + +func Readlinkat(dirfd int, path string, buf []byte) (int, error) { + p0, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + var p1 unsafe.Pointer + if len(buf) > 0 { + p1 = unsafe.Pointer(&buf[0]) + } else { + p1 = unsafe.Pointer(&_zero) + } + n, _, errno := syscall6(uintptr(unsafe.Pointer(&procReadlinkat)), 4, + uintptr(dirfd), + uintptr(unsafe.Pointer(p0)), + uintptr(p1), + uintptr(len(buf)), + 0, 0) + if errno != 0 { + return 0, errno + } + + return int(n), nil +} + +func Mkdirat(dirfd int, path string, mode uint32) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + uintptr(flags), + 0, 0) + if errno != 0 { + return errno + } + return nil +} + +func Fchownat(dirfd int, path string, uid, gid int, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procFchownat)), 5, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(uid), + uintptr(gid), + uintptr(flags), + 0) + if errno != 0 { + return errno + } + return nil +} + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procRenameat)), 4, + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flag int) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procLinkat)), 5, + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + uintptr(flag), + 0) + if errno != 0 { + return errno + } + return nil +} + +func Symlinkat(oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procSymlinkat)), 3, + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/at_libc2.go b/go/src/internal/syscall/unix/at_libc2.go new file mode 100644 index 0000000000000000000000000000000000000000..93d0cf4443f1f366c0883a99ade6b01f032e11f4 --- /dev/null +++ b/go/src/internal/syscall/unix/at_libc2.go @@ -0,0 +1,33 @@ +// 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 darwin || (openbsd && !mips64) + +package unix + +import ( + "syscall" + _ "unsafe" // for linkname +) + +func Unlinkat(dirfd int, path string, flags int) error { + return unlinkat(dirfd, path, flags) +} + +func Openat(dirfd int, path string, flags int, perm uint32) (int, error) { + return openat(dirfd, path, flags, perm) +} + +func Fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error { + return fstatat(dirfd, path, stat, flags) +} + +//go:linkname unlinkat syscall.unlinkat +func unlinkat(dirfd int, path string, flags int) error + +//go:linkname openat syscall.openat +func openat(dirfd int, path string, flags int, perm uint32) (int, error) + +//go:linkname fstatat syscall.fstatat +func fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error diff --git a/go/src/internal/syscall/unix/at_openbsd.go b/go/src/internal/syscall/unix/at_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..96e77eb408454b9d51fb15146aaf7aa4146d164b --- /dev/null +++ b/go/src/internal/syscall/unix/at_openbsd.go @@ -0,0 +1,173 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build openbsd && !mips64 + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.so" + +func libc_readlinkat_trampoline() + +func Readlinkat(dirfd int, path string, buf []byte) (int, error) { + p0, err := syscall.BytePtrFromString(path) + if err != nil { + return 0, err + } + var p1 unsafe.Pointer + if len(buf) > 0 { + p1 = unsafe.Pointer(&buf[0]) + } else { + p1 = unsafe.Pointer(&_zero) + } + n, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_readlinkat_trampoline), uintptr(dirfd), uintptr(unsafe.Pointer(p0)), uintptr(p1), uintptr(len(buf)), 0, 0) + if errno != 0 { + return 0, errno + } + return int(n), nil +} + +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" + +func libc_mkdirat_trampoline() + +func Mkdirat(dirfd int, path string, mode uint32) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_mkdirat_trampoline), uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(mode), 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" + +func libc_fchmodat_trampoline() + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_fchmodat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + uintptr(flags), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" + +func libc_fchownat_trampoline() + +func Fchownat(dirfd int, path string, uid, gid int, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_fchownat_trampoline), + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(uid), + uintptr(gid), + uintptr(flags), + 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libc_renameat renameat "libc.so" + +func libc_renameat_trampoline() + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_renameat_trampoline), + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_linkat_trampoline() + +//go:cgo_import_dynamic libc_linkat linkat "libc.so" + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flag int) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_linkat_trampoline), + uintptr(olddirfd), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + uintptr(flag), + 0) + if errno != 0 { + return errno + } + return nil +} + +func libc_symlinkat_trampoline() + +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.so" + +func Symlinkat(oldpath string, newdirfd int, newpath string) error { + oldp, err := syscall.BytePtrFromString(oldpath) + if err != nil { + return err + } + newp, err := syscall.BytePtrFromString(newpath) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_symlinkat_trampoline), + uintptr(unsafe.Pointer(oldp)), + uintptr(newdirfd), + uintptr(unsafe.Pointer(newp)), + 0, + 0, + 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/at_solaris.go b/go/src/internal/syscall/unix/at_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..5d69ae5bee7f89cde6890e2dc91500bef4406ac4 --- /dev/null +++ b/go/src/internal/syscall/unix/at_solaris.go @@ -0,0 +1,35 @@ +// 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 unix + +import "syscall" + +// Implemented as sysvicall6 in runtime/syscall_solaris.go. +func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +// Implemented as rawsysvicall6 in runtime/syscall_solaris.go. +func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:cgo_import_dynamic libc_faccessat faccessat "libc.so" +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" +//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" +//go:cgo_import_dynamic libc_linkat linkat "libc.so" +//go:cgo_import_dynamic libc_openat openat "libc.so" +//go:cgo_import_dynamic libc_renameat renameat "libc.so" +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.so" +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.so" +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" +//go:cgo_import_dynamic libc_uname uname "libc.so" + +const ( + AT_EACCESS = 0x4 + AT_FDCWD = 0xffd19553 + AT_REMOVEDIR = 0x1 + AT_SYMLINK_NOFOLLOW = 0x1000 + + UTIME_OMIT = -0x2 +) diff --git a/go/src/internal/syscall/unix/at_sysnum_darwin.go b/go/src/internal/syscall/unix/at_sysnum_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..77b0af80b5de22ff8a83330dfb391cf87fae5185 --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_darwin.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 unix + +const ( + AT_EACCESS = 0x10 + AT_FDCWD = -0x2 + AT_REMOVEDIR = 0x80 + AT_SYMLINK_NOFOLLOW = 0x0020 + + UTIME_OMIT = -0x2 +) diff --git a/go/src/internal/syscall/unix/at_sysnum_dragonfly.go b/go/src/internal/syscall/unix/at_sysnum_dragonfly.go new file mode 100644 index 0000000000000000000000000000000000000000..9728b969c4e8d9a08d2e12927bd2c80866d89afb --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_dragonfly.go @@ -0,0 +1,27 @@ +// 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 unix + +import "syscall" + +const ( + unlinkatTrap uintptr = syscall.SYS_UNLINKAT + openatTrap uintptr = syscall.SYS_OPENAT + fstatatTrap uintptr = syscall.SYS_FSTATAT + readlinkatTrap uintptr = syscall.SYS_READLINKAT + mkdiratTrap uintptr = syscall.SYS_MKDIRAT + fchmodatTrap uintptr = syscall.SYS_FCHMODAT + fchownatTrap uintptr = syscall.SYS_FCHOWNAT + renameatTrap uintptr = syscall.SYS_RENAMEAT + linkatTrap uintptr = syscall.SYS_LINKAT + symlinkatTrap uintptr = syscall.SYS_SYMLINKAT + + AT_EACCESS = 0x4 + AT_FDCWD = 0xfffafdcd + AT_REMOVEDIR = 0x2 + AT_SYMLINK_NOFOLLOW = 0x1 + + UTIME_OMIT = -0x2 +) diff --git a/go/src/internal/syscall/unix/at_sysnum_freebsd.go b/go/src/internal/syscall/unix/at_sysnum_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..c1fdcabf4136aae3111665fe7fdef71919399785 --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_freebsd.go @@ -0,0 +1,27 @@ +// 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 unix + +import "syscall" + +const ( + AT_EACCESS = 0x100 + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x800 + AT_SYMLINK_NOFOLLOW = 0x200 + + UTIME_OMIT = -0x2 + + unlinkatTrap uintptr = syscall.SYS_UNLINKAT + openatTrap uintptr = syscall.SYS_OPENAT + posixFallocateTrap uintptr = syscall.SYS_POSIX_FALLOCATE + readlinkatTrap uintptr = syscall.SYS_READLINKAT + mkdiratTrap uintptr = syscall.SYS_MKDIRAT + fchmodatTrap uintptr = syscall.SYS_FCHMODAT + fchownatTrap uintptr = syscall.SYS_FCHOWNAT + renameatTrap uintptr = syscall.SYS_RENAMEAT + linkatTrap uintptr = syscall.SYS_LINKAT + symlinkatTrap uintptr = syscall.SYS_SYMLINKAT +) diff --git a/go/src/internal/syscall/unix/at_sysnum_fstatat64_linux.go b/go/src/internal/syscall/unix/at_sysnum_fstatat64_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..445b0c38546ac089e976471771370679bfcf390d --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_fstatat64_linux.go @@ -0,0 +1,11 @@ +// 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 arm || mips || mipsle || 386 + +package unix + +import "syscall" + +const fstatatTrap uintptr = syscall.SYS_FSTATAT64 diff --git a/go/src/internal/syscall/unix/at_sysnum_fstatat_linux.go b/go/src/internal/syscall/unix/at_sysnum_fstatat_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..73a3da5bff2112b7940caccbe1b939d4f98d96c5 --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_fstatat_linux.go @@ -0,0 +1,11 @@ +// 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 arm64 || riscv64 + +package unix + +import "syscall" + +const fstatatTrap uintptr = syscall.SYS_FSTATAT diff --git a/go/src/internal/syscall/unix/at_sysnum_linux.go b/go/src/internal/syscall/unix/at_sysnum_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..d260a239a92c98709a9abe7c6cde14adac3f9dec --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_linux.go @@ -0,0 +1,28 @@ +// 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 unix + +import "syscall" + +const ( + unlinkatTrap uintptr = syscall.SYS_UNLINKAT + openatTrap uintptr = syscall.SYS_OPENAT + readlinkatTrap uintptr = syscall.SYS_READLINKAT + mkdiratTrap uintptr = syscall.SYS_MKDIRAT + fchownatTrap uintptr = syscall.SYS_FCHOWNAT + linkatTrap uintptr = syscall.SYS_LINKAT + symlinkatTrap uintptr = syscall.SYS_SYMLINKAT +) + +const ( + AT_EACCESS = 0x200 + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x200 + AT_SYMLINK_NOFOLLOW = 0x100 + + UTIME_OMIT = 0x3ffffffe + + O_PATH = 0x200000 +) diff --git a/go/src/internal/syscall/unix/at_sysnum_netbsd.go b/go/src/internal/syscall/unix/at_sysnum_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..db17852b748e325ad170343f86242b075d726fd7 --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_netbsd.go @@ -0,0 +1,30 @@ +// 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 unix + +import "syscall" + +const ( + unlinkatTrap uintptr = syscall.SYS_UNLINKAT + openatTrap uintptr = syscall.SYS_OPENAT + fstatatTrap uintptr = syscall.SYS_FSTATAT + readlinkatTrap uintptr = syscall.SYS_READLINKAT + mkdiratTrap uintptr = syscall.SYS_MKDIRAT + fchmodatTrap uintptr = syscall.SYS_FCHMODAT + fchownatTrap uintptr = syscall.SYS_FCHOWNAT + renameatTrap uintptr = syscall.SYS_RENAMEAT + linkatTrap uintptr = syscall.SYS_LINKAT + symlinkatTrap uintptr = syscall.SYS_SYMLINKAT + posixFallocateTrap uintptr = 479 +) + +const ( + AT_EACCESS = 0x100 + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x800 + AT_SYMLINK_NOFOLLOW = 0x200 + + UTIME_OMIT = (1 << 30) - 2 +) diff --git a/go/src/internal/syscall/unix/at_sysnum_newfstatat_linux.go b/go/src/internal/syscall/unix/at_sysnum_newfstatat_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..76edf675227f9b40611a2e67ae6542ec3f3eaf4b --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_newfstatat_linux.go @@ -0,0 +1,11 @@ +// 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 amd64 || mips64 || mips64le || ppc64 || ppc64le || s390x + +package unix + +import "syscall" + +const fstatatTrap uintptr = syscall.SYS_NEWFSTATAT diff --git a/go/src/internal/syscall/unix/at_sysnum_openbsd.go b/go/src/internal/syscall/unix/at_sysnum_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..7672414cf7690efb8811d3334ec7157eae22dbd4 --- /dev/null +++ b/go/src/internal/syscall/unix/at_sysnum_openbsd.go @@ -0,0 +1,24 @@ +// 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 unix + +import "syscall" + +const ( + unlinkatTrap uintptr = syscall.SYS_UNLINKAT + openatTrap uintptr = syscall.SYS_OPENAT + fstatatTrap uintptr = syscall.SYS_FSTATAT + readlinkatTrap uintptr = syscall.SYS_READLINKAT + mkdiratTrap uintptr = syscall.SYS_MKDIRAT +) + +const ( + AT_EACCESS = 0x1 + AT_FDCWD = -0x64 + AT_REMOVEDIR = 0x08 + AT_SYMLINK_NOFOLLOW = 0x02 + + UTIME_OMIT = -0x1 +) diff --git a/go/src/internal/syscall/unix/at_wasip1.go b/go/src/internal/syscall/unix/at_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..dfbb365f2a6fedbdcde41a66aee3b0922dcb7a5e --- /dev/null +++ b/go/src/internal/syscall/unix/at_wasip1.go @@ -0,0 +1,177 @@ +// 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 wasip1 + +package unix + +import ( + "syscall" + "unsafe" +) + +// The values of these constants are not part of the WASI API. +const ( + // UTIME_OMIT is the sentinel value to indicate that a time value should not + // be changed. It is useful for example to indicate for example with UtimesNano + // to avoid changing AccessTime or ModifiedTime. + // Its value must match syscall/fs_wasip1.go + UTIME_OMIT = -0x2 + + AT_REMOVEDIR = 0x200 + AT_SYMLINK_NOFOLLOW = 0x100 +) + +func Unlinkat(dirfd int, path string, flags int) error { + if flags&AT_REMOVEDIR == 0 { + return errnoErr(path_unlink_file( + int32(dirfd), + unsafe.StringData(path), + size(len(path)), + )) + } else { + return errnoErr(path_remove_directory( + int32(dirfd), + unsafe.StringData(path), + size(len(path)), + )) + } +} + +//go:wasmimport wasi_snapshot_preview1 path_unlink_file +//go:noescape +func path_unlink_file(fd int32, path *byte, pathLen size) syscall.Errno + +//go:wasmimport wasi_snapshot_preview1 path_remove_directory +//go:noescape +func path_remove_directory(fd int32, path *byte, pathLen size) syscall.Errno + +func Openat(dirfd int, path string, flags int, perm uint32) (int, error) { + return syscall.Openat(dirfd, path, flags, perm) +} + +func Fstatat(dirfd int, path string, stat *syscall.Stat_t, flags int) error { + var filestatFlags uint32 + if flags&AT_SYMLINK_NOFOLLOW == 0 { + filestatFlags |= syscall.LOOKUP_SYMLINK_FOLLOW + } + return errnoErr(path_filestat_get( + int32(dirfd), + uint32(filestatFlags), + unsafe.StringData(path), + size(len(path)), + unsafe.Pointer(stat), + )) +} + +//go:wasmimport wasi_snapshot_preview1 path_filestat_get +//go:noescape +func path_filestat_get(fd int32, flags uint32, path *byte, pathLen size, buf unsafe.Pointer) syscall.Errno + +func Readlinkat(dirfd int, path string, buf []byte) (int, error) { + var nwritten size + errno := path_readlink( + int32(dirfd), + unsafe.StringData(path), + size(len(path)), + &buf[0], + size(len(buf)), + &nwritten) + return int(nwritten), errnoErr(errno) + +} + +type ( + size = uint32 +) + +//go:wasmimport wasi_snapshot_preview1 path_readlink +//go:noescape +func path_readlink(fd int32, path *byte, pathLen size, buf *byte, bufLen size, nwritten *size) syscall.Errno + +func Mkdirat(dirfd int, path string, mode uint32) error { + if path == "" { + return syscall.EINVAL + } + return errnoErr(path_create_directory( + int32(dirfd), + unsafe.StringData(path), + size(len(path)), + )) +} + +//go:wasmimport wasi_snapshot_preview1 path_create_directory +//go:noescape +func path_create_directory(fd int32, path *byte, pathLen size) syscall.Errno + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + // WASI preview 1 doesn't support changing file modes. + return syscall.ENOSYS +} + +func Fchownat(dirfd int, path string, uid, gid int, flags int) error { + // WASI preview 1 doesn't support changing file ownership. + return syscall.ENOSYS +} + +func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) error { + if oldpath == "" || newpath == "" { + return syscall.EINVAL + } + return errnoErr(path_rename( + int32(olddirfd), + unsafe.StringData(oldpath), + size(len(oldpath)), + int32(newdirfd), + unsafe.StringData(newpath), + size(len(newpath)), + )) +} + +//go:wasmimport wasi_snapshot_preview1 path_rename +//go:noescape +func path_rename(oldFd int32, oldPath *byte, oldPathLen size, newFd int32, newPath *byte, newPathLen size) syscall.Errno + +func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flag int) error { + if oldpath == "" || newpath == "" { + return syscall.EINVAL + } + return errnoErr(path_link( + int32(olddirfd), + 0, + unsafe.StringData(oldpath), + size(len(oldpath)), + int32(newdirfd), + unsafe.StringData(newpath), + size(len(newpath)), + )) +} + +//go:wasmimport wasi_snapshot_preview1 path_link +//go:noescape +func path_link(oldFd int32, oldFlags uint32, oldPath *byte, oldPathLen size, newFd int32, newPath *byte, newPathLen size) syscall.Errno + +func Symlinkat(oldpath string, newdirfd int, newpath string) error { + if oldpath == "" || newpath == "" { + return syscall.EINVAL + } + return errnoErr(path_symlink( + unsafe.StringData(oldpath), + size(len(oldpath)), + int32(newdirfd), + unsafe.StringData(newpath), + size(len(newpath)), + )) +} + +//go:wasmimport wasi_snapshot_preview1 path_symlink +//go:noescape +func path_symlink(oldPath *byte, oldPathLen size, fd int32, newPath *byte, newPathLen size) syscall.Errno + +func errnoErr(errno syscall.Errno) error { + if errno == 0 { + return nil + } + return errno +} diff --git a/go/src/internal/syscall/unix/constants.go b/go/src/internal/syscall/unix/constants.go new file mode 100644 index 0000000000000000000000000000000000000000..6a78dda79565867c01bcc3ccb4696273e3683822 --- /dev/null +++ b/go/src/internal/syscall/unix/constants.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || wasip1 + +package unix + +const ( + R_OK = 0x4 + W_OK = 0x2 + X_OK = 0x1 + + // NoFollowErrno is the error returned from open/openat called with + // O_NOFOLLOW flag, when the trailing component (basename) of the path + // is a symbolic link. + NoFollowErrno = noFollowErrno +) diff --git a/go/src/internal/syscall/unix/copy_file_range_unix.go b/go/src/internal/syscall/unix/copy_file_range_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..16a434219e19875a1d286f6b5357230a2dc9200b --- /dev/null +++ b/go/src/internal/syscall/unix/copy_file_range_unix.go @@ -0,0 +1,28 @@ +// 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 freebsd || linux + +package unix + +import ( + "syscall" + "unsafe" +) + +func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r1, _, errno := syscall.Syscall6(copyFileRangeTrap, + uintptr(rfd), + uintptr(unsafe.Pointer(roff)), + uintptr(wfd), + uintptr(unsafe.Pointer(woff)), + uintptr(len), + uintptr(flags), + ) + n = int(r1) + if errno != 0 { + err = errno + } + return +} diff --git a/go/src/internal/syscall/unix/eaccess.go b/go/src/internal/syscall/unix/eaccess.go new file mode 100644 index 0000000000000000000000000000000000000000..3c12314a9c7d4495458e922f5838b8ec99d5756b --- /dev/null +++ b/go/src/internal/syscall/unix/eaccess.go @@ -0,0 +1,24 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package unix + +import ( + "runtime" + "syscall" +) + +func Eaccess(path string, mode uint32) error { + if runtime.GOOS == "android" { + // syscall.Faccessat for Android implements AT_EACCESS check in + // userspace. Since Android doesn't have setuid programs and + // never runs code with euid!=uid, AT_EACCESS check is not + // really required. Return ENOSYS so the callers can fall back + // to permission bits check. + return syscall.ENOSYS + } + return faccessat(AT_FDCWD, path, mode, AT_EACCESS) +} diff --git a/go/src/internal/syscall/unix/faccessat_bsd.go b/go/src/internal/syscall/unix/faccessat_bsd.go new file mode 100644 index 0000000000000000000000000000000000000000..1db54c35b26ac5482b375c13f5571ca864491080 --- /dev/null +++ b/go/src/internal/syscall/unix/faccessat_bsd.go @@ -0,0 +1,24 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || freebsd || netbsd || (openbsd && mips64) + +package unix + +import ( + "syscall" + "unsafe" +) + +func faccessat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall.Syscall6(syscall.SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(mode), uintptr(flags), 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/faccessat_darwin.go b/go/src/internal/syscall/unix/faccessat_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..ef790aa949a9a48c0ee14a3fac34f0d53078a1aa --- /dev/null +++ b/go/src/internal/syscall/unix/faccessat_darwin.go @@ -0,0 +1,27 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +func libc_faccessat_trampoline() + +//go:cgo_import_dynamic libc_faccessat faccessat "/usr/lib/libSystem.B.dylib" + +func faccessat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_faccessat_trampoline), uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(mode), uintptr(flags), 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/faccessat_openbsd.go b/go/src/internal/syscall/unix/faccessat_openbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..3519532154a75de52a7e5b66e5c04b905fe22177 --- /dev/null +++ b/go/src/internal/syscall/unix/faccessat_openbsd.go @@ -0,0 +1,32 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build openbsd && !mips64 + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +//go:linkname syscall_syscall6 syscall.syscall6 +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +func libc_faccessat_trampoline() + +//go:cgo_import_dynamic libc_faccessat faccessat "libc.so" + +func faccessat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_faccessat_trampoline), uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(mode), uintptr(flags), 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/faccessat_solaris.go b/go/src/internal/syscall/unix/faccessat_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..47e05fb2c09b6f780aa03d37bbabd2234b7fa78e --- /dev/null +++ b/go/src/internal/syscall/unix/faccessat_solaris.go @@ -0,0 +1,28 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" + "unsafe" +) + +//go:linkname procFaccessat libc_faccessat + +var procFaccessat uintptr + +func faccessat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + _, _, errno := syscall6(uintptr(unsafe.Pointer(&procFaccessat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(p)), uintptr(mode), uintptr(flags), 0, 0) + if errno != 0 { + return errno + } + + return nil +} diff --git a/go/src/internal/syscall/unix/faccessat_syscall.go b/go/src/internal/syscall/unix/faccessat_syscall.go new file mode 100644 index 0000000000000000000000000000000000000000..865e40b2c6f3f492b3a255461a4bd81728d59709 --- /dev/null +++ b/go/src/internal/syscall/unix/faccessat_syscall.go @@ -0,0 +1,11 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build aix || linux + +package unix + +import "syscall" + +var faccessat = syscall.Faccessat diff --git a/go/src/internal/syscall/unix/fallocate_bsd_386.go b/go/src/internal/syscall/unix/fallocate_bsd_386.go new file mode 100644 index 0000000000000000000000000000000000000000..1dcdff4a5391d0d1d963e1df9da6fd38cc65d155 --- /dev/null +++ b/go/src/internal/syscall/unix/fallocate_bsd_386.go @@ -0,0 +1,20 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (freebsd || netbsd) && 386 + +package unix + +import "syscall" + +func PosixFallocate(fd int, off int64, size int64) error { + // If successful, posix_fallocate() returns zero. It returns an error on failure, without + // setting errno. See https://man.freebsd.org/cgi/man.cgi?query=posix_fallocate&sektion=2&n=1 + // and https://man.netbsd.org/posix_fallocate.2#RETURN%20VALUES + r1, _, _ := syscall.Syscall6(posixFallocateTrap, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(size), uintptr(size>>32), 0) + if r1 != 0 { + return syscall.Errno(r1) + } + return nil +} diff --git a/go/src/internal/syscall/unix/fallocate_bsd_64bit.go b/go/src/internal/syscall/unix/fallocate_bsd_64bit.go new file mode 100644 index 0000000000000000000000000000000000000000..177bb48382d54ccf68cca0a16a4b57e1fed8de18 --- /dev/null +++ b/go/src/internal/syscall/unix/fallocate_bsd_64bit.go @@ -0,0 +1,20 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (freebsd || netbsd) && (amd64 || arm64 || riscv64) + +package unix + +import "syscall" + +func PosixFallocate(fd int, off int64, size int64) error { + // If successful, posix_fallocate() returns zero. It returns an error on failure, without + // setting errno. See https://man.freebsd.org/cgi/man.cgi?query=posix_fallocate&sektion=2&n=1 + // and https://man.netbsd.org/posix_fallocate.2#RETURN%20VALUES + r1, _, _ := syscall.Syscall(posixFallocateTrap, uintptr(fd), uintptr(off), uintptr(size)) + if r1 != 0 { + return syscall.Errno(r1) + } + return nil +} diff --git a/go/src/internal/syscall/unix/fallocate_bsd_arm.go b/go/src/internal/syscall/unix/fallocate_bsd_arm.go new file mode 100644 index 0000000000000000000000000000000000000000..15e99d02b1c790a14a2d2ad8af4a036463b908e8 --- /dev/null +++ b/go/src/internal/syscall/unix/fallocate_bsd_arm.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 (freebsd || netbsd) && arm + +package unix + +import "syscall" + +func PosixFallocate(fd int, off int64, size int64) error { + // If successful, posix_fallocate() returns zero. It returns an error on failure, without + // setting errno. See https://man.freebsd.org/cgi/man.cgi?query=posix_fallocate&sektion=2&n=1 + // and https://man.netbsd.org/posix_fallocate.2#RETURN%20VALUES + // + // The padding 0 argument is needed because the ARM calling convention requires that if an + // argument (off in this case) needs double-word alignment (8-byte), the NCRN (next core + // register number) is rounded up to the next even register number. + // See https://github.com/ARM-software/abi-aa/blob/2bcab1e3b22d55170c563c3c7940134089176746/aapcs32/aapcs32.rst#parameter-passing + r1, _, _ := syscall.Syscall6(posixFallocateTrap, uintptr(fd), 0, uintptr(off), uintptr(off>>32), uintptr(size), uintptr(size>>32)) + if r1 != 0 { + return syscall.Errno(r1) + } + return nil +} diff --git a/go/src/internal/syscall/unix/fchmodat_linux.go b/go/src/internal/syscall/unix/fchmodat_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..786ec29df2482457f1fc007c8ee8dc80ec84fc41 --- /dev/null +++ b/go/src/internal/syscall/unix/fchmodat_linux.go @@ -0,0 +1,51 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux + +package unix + +import ( + "internal/strconv" + "syscall" +) + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + // On Linux, the fchmodat syscall silently ignores the AT_SYMLINK_NOFOLLOW flag. + // We need to use fchmodat2 instead. + // syscall.Fchmodat handles this. + if err := syscall.Fchmodat(dirfd, path, mode, flags); err != syscall.EOPNOTSUPP { + return err + } + + // This kernel doesn't appear to support fchmodat2 (added in Linux 6.6). + // We can't fall back to Fchmod, because it requires write permissions on the file. + // Instead, use the same workaround as GNU libc and musl, which is to open the file + // and then fchmodat the FD in /proc/self/fd. + // See: https://lwn.net/Articles/939217/ + fd, err := Openat(dirfd, path, O_PATH|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0) + if err != nil { + return err + } + defer syscall.Close(fd) + procPath := "/proc/self/fd/" + strconv.Itoa(fd) + + // Check to see if this file is a symlink. + // (We passed O_NOFOLLOW above, but O_PATH|O_NOFOLLOW will open a symlink.) + var st syscall.Stat_t + if err := syscall.Stat(procPath, &st); err != nil { + if err == syscall.ENOENT { + // /proc has probably not been mounted. Give up. + return syscall.EOPNOTSUPP + } + return err + } + if st.Mode&syscall.S_IFMT == syscall.S_IFLNK { + // fchmodat on the proc FD for a symlink apparently gives inconsistent + // results, so just refuse to try. + return syscall.EOPNOTSUPP + } + + return syscall.Fchmodat(AT_FDCWD, procPath, mode, flags&^AT_SYMLINK_NOFOLLOW) +} diff --git a/go/src/internal/syscall/unix/fchmodat_other.go b/go/src/internal/syscall/unix/fchmodat_other.go new file mode 100644 index 0000000000000000000000000000000000000000..76f478c4ae15bcf17e95546e1a849e4d78a6cfa7 --- /dev/null +++ b/go/src/internal/syscall/unix/fchmodat_other.go @@ -0,0 +1,29 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || freebsd || netbsd || (openbsd && mips64) + +package unix + +import ( + "syscall" + "unsafe" +) + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + p, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + _, _, errno := syscall.Syscall6(fchmodatTrap, + uintptr(dirfd), + uintptr(unsafe.Pointer(p)), + uintptr(mode), + uintptr(flags), + 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/fchmodat_test.go b/go/src/internal/syscall/unix/fchmodat_test.go new file mode 100644 index 0000000000000000000000000000000000000000..49a098535d35796726920c00f678fa094bf4f74f --- /dev/null +++ b/go/src/internal/syscall/unix/fchmodat_test.go @@ -0,0 +1,62 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix || wasip1 + +package unix_test + +import ( + "internal/syscall/unix" + "os" + "runtime" + "testing" +) + +// TestFchmodAtSymlinkNofollow verifies that Fchmodat honors the AT_SYMLINK_NOFOLLOW flag. +func TestFchmodatSymlinkNofollow(t *testing.T) { + if runtime.GOOS == "wasip1" { + t.Skip("wasip1 doesn't support chmod") + } + + dir := t.TempDir() + filename := dir + "/file" + linkname := dir + "/symlink" + if err := os.WriteFile(filename, nil, 0o100); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filename, linkname); err != nil { + t.Fatal(err) + } + + parent, err := os.Open(dir) + if err != nil { + t.Fatal(err) + } + defer parent.Close() + + lstatMode := func(path string) os.FileMode { + st, err := os.Lstat(path) + if err != nil { + t.Fatal(err) + } + return st.Mode() + } + + // Fchmodat with no flags follows symlinks. + const mode1 = 0o200 + if err := unix.Fchmodat(int(parent.Fd()), "symlink", mode1, 0); err != nil { + t.Fatal(err) + } + if got, want := lstatMode(filename), os.FileMode(mode1); got != want { + t.Errorf("after Fchmodat(parent, symlink, %v, 0); mode = %v, want %v", mode1, got, want) + } + + // Fchmodat with AT_SYMLINK_NOFOLLOW does not follow symlinks. + // The Fchmodat call may fail or chmod the symlink itself, depending on the kernel version. + const mode2 = 0o400 + unix.Fchmodat(int(parent.Fd()), "symlink", mode2, unix.AT_SYMLINK_NOFOLLOW) + if got, want := lstatMode(filename), os.FileMode(mode1); got != want { + t.Errorf("after Fchmodat(parent, symlink, %v, AT_SYMLINK_NOFOLLOW); mode = %v, want %v", mode1, got, want) + } +} diff --git a/go/src/internal/syscall/unix/fcntl_js.go b/go/src/internal/syscall/unix/fcntl_js.go new file mode 100644 index 0000000000000000000000000000000000000000..bdfb8e046d3ffe86ec26f7d9f347f73713da80cf --- /dev/null +++ b/go/src/internal/syscall/unix/fcntl_js.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm + +package unix + +import "syscall" + +func Fcntl(fd int, cmd int, arg int) (int, error) { + return 0, syscall.ENOSYS +} diff --git a/go/src/internal/syscall/unix/fcntl_unix.go b/go/src/internal/syscall/unix/fcntl_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..6f9e124394cfd7d367dc7be214dfd7028d33338b --- /dev/null +++ b/go/src/internal/syscall/unix/fcntl_unix.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 unix + +package unix + +import ( + "syscall" + _ "unsafe" // for go:linkname +) + +// Implemented in the runtime package. +// +//go:linkname fcntl runtime.fcntl +func fcntl(fd int32, cmd int32, arg int32) (int32, int32) + +func Fcntl(fd int, cmd int, arg int) (int, error) { + val, errno := fcntl(int32(fd), int32(cmd), int32(arg)) + if val == -1 { + return int(val), syscall.Errno(errno) + } + return int(val), nil +} diff --git a/go/src/internal/syscall/unix/fcntl_wasip1.go b/go/src/internal/syscall/unix/fcntl_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..e70cd74b49c780f94bd3e1f7be0ac141684e31d9 --- /dev/null +++ b/go/src/internal/syscall/unix/fcntl_wasip1.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasip1 + +package unix + +import "syscall" + +func Fcntl(fd int, cmd int, arg int) (int, error) { + if cmd == syscall.F_GETFL { + flags, err := fd_fdstat_get_flags(fd) + return int(flags), err + } + return 0, syscall.ENOSYS +} diff --git a/go/src/internal/syscall/unix/getrandom.go b/go/src/internal/syscall/unix/getrandom.go new file mode 100644 index 0000000000000000000000000000000000000000..db3e7ac0f0d3be0f208de0dc6e994c7153c7c166 --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom.go @@ -0,0 +1,47 @@ +// 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 dragonfly || freebsd || linux + +package unix + +import ( + "sync/atomic" + "syscall" + "unsafe" +) + +//go:linkname vgetrandom runtime.vgetrandom +//go:noescape +func vgetrandom(p []byte, flags uint32) (ret int, supported bool) + +var getrandomUnsupported atomic.Bool + +// GetRandomFlag is a flag supported by the getrandom system call. +type GetRandomFlag uintptr + +// GetRandom calls the getrandom system call. +func GetRandom(p []byte, flags GetRandomFlag) (n int, err error) { + ret, supported := vgetrandom(p, uint32(flags)) + if supported { + if ret < 0 { + return 0, syscall.Errno(-ret) + } + return ret, nil + } + if getrandomUnsupported.Load() { + return 0, syscall.ENOSYS + } + r1, _, errno := syscall.Syscall(getrandomTrap, + uintptr(unsafe.Pointer(unsafe.SliceData(p))), + uintptr(len(p)), + uintptr(flags)) + if errno != 0 { + if errno == syscall.ENOSYS { + getrandomUnsupported.Store(true) + } + return 0, errno + } + return int(r1), nil +} diff --git a/go/src/internal/syscall/unix/getrandom_dragonfly.go b/go/src/internal/syscall/unix/getrandom_dragonfly.go new file mode 100644 index 0000000000000000000000000000000000000000..fbf78f9de804f86375df034caa0b35bc9a2062ce --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom_dragonfly.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +// DragonFlyBSD getrandom system call number. +const getrandomTrap uintptr = 550 + +const ( + // GRND_RANDOM is only set for portability purpose, no-op on DragonFlyBSD. + GRND_RANDOM GetRandomFlag = 0x0001 + + // GRND_NONBLOCK means return EAGAIN rather than blocking. + GRND_NONBLOCK GetRandomFlag = 0x0002 +) diff --git a/go/src/internal/syscall/unix/getrandom_freebsd.go b/go/src/internal/syscall/unix/getrandom_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..8c4f3dff82377e5324c400fb98fd3f5a9b1b4681 --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom_freebsd.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. + +package unix + +// FreeBSD getrandom system call number. +const getrandomTrap uintptr = 563 + +const ( + // GRND_NONBLOCK means return EAGAIN rather than blocking. + GRND_NONBLOCK GetRandomFlag = 0x0001 + + // GRND_RANDOM is only set for portability purpose, no-op on FreeBSD. + GRND_RANDOM GetRandomFlag = 0x0002 +) diff --git a/go/src/internal/syscall/unix/getrandom_linux.go b/go/src/internal/syscall/unix/getrandom_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..8ccd8d328af1feb980ac35c062f944ca3c0219f6 --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom_linux.go @@ -0,0 +1,13 @@ +// 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 unix + +const ( + // GRND_NONBLOCK means return EAGAIN rather than blocking. + GRND_NONBLOCK GetRandomFlag = 0x0001 + + // GRND_RANDOM means use the /dev/random pool instead of /dev/urandom. + GRND_RANDOM GetRandomFlag = 0x0002 +) diff --git a/go/src/internal/syscall/unix/getrandom_linux_test.go b/go/src/internal/syscall/unix/getrandom_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e1778c19e82493642eaaf67cb705af693949379a --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom_linux_test.go @@ -0,0 +1,22 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix_test + +import ( + "internal/syscall/unix" + "testing" +) + +func BenchmarkParallelGetRandom(b *testing.B) { + b.SetBytes(4) + b.RunParallel(func(pb *testing.PB) { + var buf [4]byte + for pb.Next() { + if _, err := unix.GetRandom(buf[:], 0); err != nil { + b.Fatal(err) + } + } + }) +} diff --git a/go/src/internal/syscall/unix/getrandom_solaris.go b/go/src/internal/syscall/unix/getrandom_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..cf4f35a4198d1f4931167d599e8ad1dea9ab8d76 --- /dev/null +++ b/go/src/internal/syscall/unix/getrandom_solaris.go @@ -0,0 +1,53 @@ +// 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 unix + +import ( + "sync/atomic" + "syscall" + "unsafe" +) + +//go:cgo_import_dynamic libc_getrandom getrandom "libc.so" + +//go:linkname procGetrandom libc_getrandom + +var procGetrandom uintptr + +var getrandomUnsupported atomic.Bool + +// GetRandomFlag is a flag supported by the getrandom system call. +type GetRandomFlag uintptr + +const ( + // GRND_NONBLOCK means return EAGAIN rather than blocking. + GRND_NONBLOCK GetRandomFlag = 0x0001 + + // GRND_RANDOM means use the /dev/random pool instead of /dev/urandom. + GRND_RANDOM GetRandomFlag = 0x0002 +) + +// GetRandom calls the getrandom system call. +func GetRandom(p []byte, flags GetRandomFlag) (n int, err error) { + if len(p) == 0 { + return 0, nil + } + if getrandomUnsupported.Load() { + return 0, syscall.ENOSYS + } + r1, _, errno := syscall6(uintptr(unsafe.Pointer(&procGetrandom)), + 3, + uintptr(unsafe.Pointer(&p[0])), + uintptr(len(p)), + uintptr(flags), + 0, 0, 0) + if errno != 0 { + if errno == syscall.ENOSYS { + getrandomUnsupported.Store(true) + } + return 0, errno + } + return int(r1), nil +} diff --git a/go/src/internal/syscall/unix/ioctl_aix.go b/go/src/internal/syscall/unix/ioctl_aix.go new file mode 100644 index 0000000000000000000000000000000000000000..d361533b5c4a43bdf3789f7711077d74278560bd --- /dev/null +++ b/go/src/internal/syscall/unix/ioctl_aix.go @@ -0,0 +1,25 @@ +// 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 unix + +import ( + "syscall" + "unsafe" +) + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.a/shr_64.o" +//go:linkname libc_ioctl libc_ioctl +var libc_ioctl uintptr + +// Implemented in syscall/syscall_aix.go. +func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +func Ioctl(fd int, cmd int, args unsafe.Pointer) (err error) { + _, _, e1 := syscall6(uintptr(unsafe.Pointer(&libc_ioctl)), 3, uintptr(fd), uintptr(cmd), uintptr(args), 0, 0, 0) + if e1 != 0 { + err = e1 + } + return +} diff --git a/go/src/internal/syscall/unix/kernel_version_freebsd.go b/go/src/internal/syscall/unix/kernel_version_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..db3519ddfb70f6ffbbe57876afa8fc43a607cc3c --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_freebsd.go @@ -0,0 +1,50 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "sync" + "syscall" +) + +// KernelVersion returns major and minor kernel version numbers +// parsed from the syscall.Sysctl("kern.osrelease")'s value, +// or (0, 0) if the version can't be obtained or parsed. +func KernelVersion() (major, minor int) { + release, err := syscall.Sysctl("kern.osrelease") + if err != nil { + return 0, 0 + } + + parseNext := func() (n int) { + for i, c := range release { + if c == '.' { + release = release[i+1:] + return + } + if '0' <= c && c <= '9' { + n = n*10 + int(c-'0') + } + } + release = "" + return + } + + major = parseNext() + minor = parseNext() + + return +} + +// SupportCopyFileRange reports whether the kernel supports the copy_file_range(2). +// This function will examine both the kernel version and the availability of the system call. +var SupportCopyFileRange = sync.OnceValue(func() bool { + // The copy_file_range() function first appeared in FreeBSD 13.0. + if !KernelVersionGE(13, 0) { + return false + } + _, err := CopyFileRange(0, nil, 0, nil, 0, 0) + return err != syscall.ENOSYS +}) diff --git a/go/src/internal/syscall/unix/kernel_version_freebsd_test.go b/go/src/internal/syscall/unix/kernel_version_freebsd_test.go new file mode 100644 index 0000000000000000000000000000000000000000..694440e3254d8225576021984bb38fe931188dcb --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_freebsd_test.go @@ -0,0 +1,23 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix_test + +import ( + "internal/syscall/unix" + "syscall" + "testing" +) + +func TestSupportCopyFileRange(t *testing.T) { + major, minor := unix.KernelVersion() + t.Logf("Running on FreeBSD %d.%d\n", major, minor) + + _, err := unix.CopyFileRange(0, nil, 0, nil, 0, 0) + want := err != syscall.ENOSYS + got := unix.SupportCopyFileRange() + if want != got { + t.Fatalf("SupportCopyFileRange, got %t; want %t", got, want) + } +} diff --git a/go/src/internal/syscall/unix/kernel_version_ge.go b/go/src/internal/syscall/unix/kernel_version_ge.go new file mode 100644 index 0000000000000000000000000000000000000000..a1424041993b852adbaaa0bc75bda914058a20df --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_ge.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +// KernelVersionGE checks if the running kernel version +// is greater than or equal to the provided version. +func KernelVersionGE(x, y int) bool { + xx, yy := KernelVersion() + + return xx > x || (xx == x && yy >= y) +} diff --git a/go/src/internal/syscall/unix/kernel_version_ge_test.go b/go/src/internal/syscall/unix/kernel_version_ge_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f4b1b23cd2e839d7a8b5dafc418a3d65dd2cb66d --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_ge_test.go @@ -0,0 +1,67 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix_test + +import ( + "internal/syscall/unix" + "testing" +) + +func TestKernelVersionGE(t *testing.T) { + major, minor := unix.KernelVersion() + t.Logf("Running on kernel %d.%d", major, minor) + + tests := []struct { + name string + x, y int + want bool + }{ + { + name: "current version equals itself", + x: major, + y: minor, + want: true, + }, + { + name: "older major version", + x: major - 1, + y: 0, + want: true, + }, + { + name: "same major, older minor version", + x: major, + y: minor - 1, + want: true, + }, + { + name: "newer major version", + x: major + 1, + y: 0, + want: false, + }, + { + name: "same major, newer minor version", + x: major, + y: minor + 1, + want: false, + }, + { + name: "min version (0.0)", + x: 0, + y: 0, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := unix.KernelVersionGE(tt.x, tt.y) + if got != tt.want { + t.Errorf("KernelVersionGE(%d, %d): got %v, want %v", tt.x, tt.y, got, tt.want) + } + }) + } +} diff --git a/go/src/internal/syscall/unix/kernel_version_linux.go b/go/src/internal/syscall/unix/kernel_version_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..f3656288ef33fe0df1d98fac340ff411a28186ba --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_linux.go @@ -0,0 +1,40 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" +) + +// KernelVersion returns major and minor kernel version numbers +// parsed from the syscall.Uname's Release field, or (0, 0) if +// the version can't be obtained or parsed. +func KernelVersion() (major, minor int) { + var uname syscall.Utsname + if err := syscall.Uname(&uname); err != nil { + return + } + + var ( + values [2]int + value, vi int + ) + for _, c := range uname.Release { + if '0' <= c && c <= '9' { + value = (value * 10) + int(c-'0') + } else { + // Note that we're assuming N.N.N here. + // If we see anything else, we are likely to mis-parse it. + values[vi] = value + vi++ + if vi >= len(values) { + break + } + value = 0 + } + } + + return values[0], values[1] +} diff --git a/go/src/internal/syscall/unix/kernel_version_other.go b/go/src/internal/syscall/unix/kernel_version_other.go new file mode 100644 index 0000000000000000000000000000000000000000..91c14b31d999bcc64e1bed29540d7bc18ae8b76e --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_other.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !freebsd && !linux && !solaris + +package unix + +func KernelVersion() (major int, minor int) { + return 0, 0 +} diff --git a/go/src/internal/syscall/unix/kernel_version_solaris.go b/go/src/internal/syscall/unix/kernel_version_solaris.go new file mode 100644 index 0000000000000000000000000000000000000000..7904e1f4295707bcd4a531ecd22320ea611d2015 --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_solaris.go @@ -0,0 +1,104 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "runtime" + "sync" + "syscall" + "unsafe" +) + +//go:linkname procUname libc_uname + +var procUname uintptr + +// utsname represents the fields of a struct utsname defined in . +type utsname struct { + Sysname [257]byte + Nodename [257]byte + Release [257]byte + Version [257]byte + Machine [257]byte +} + +// KernelVersion returns major and minor kernel version numbers +// parsed from the syscall.Uname's Version field, or (0, 0) if the +// version can't be obtained or parsed. +func KernelVersion() (major int, minor int) { + var un utsname + _, _, errno := rawSyscall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(&un)), 0, 0, 0, 0, 0) + if errno != 0 { + return 0, 0 + } + + // The version string is in the form "...." + // on Solaris: https://blogs.oracle.com/solaris/post/whats-in-a-uname- + // Therefore, we use the Version field on Solaris when available. + ver := un.Version[:] + if runtime.GOOS == "illumos" { + // Illumos distributions use different formats without a parsable + // and unified pattern for the Version field while Release level + // string is guaranteed to be in x.y or x.y.z format regardless of + // whether the kernel is Solaris or illumos. + ver = un.Release[:] + } + + parseNext := func() (n int) { + for i, c := range ver { + if c == '.' { + ver = ver[i+1:] + return + } + if '0' <= c && c <= '9' { + n = n*10 + int(c-'0') + } + } + ver = nil + return + } + + major = parseNext() + minor = parseNext() + + return +} + +// SupportSockNonblockCloexec tests if SOCK_NONBLOCK and SOCK_CLOEXEC are supported +// for socket() system call, returns true if affirmative. +var SupportSockNonblockCloexec = sync.OnceValue(func() bool { + // First test if socket() supports SOCK_NONBLOCK and SOCK_CLOEXEC directly. + s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0) + if err == nil { + syscall.Close(s) + return true + } + if err != syscall.EPROTONOSUPPORT && err != syscall.EINVAL { + // Something wrong with socket(), fall back to checking the kernel version. + if runtime.GOOS == "illumos" { + return KernelVersionGE(5, 11) // Minimal requirement is SunOS 5.11. + } + return KernelVersionGE(11, 4) + } + return false +}) + +// SupportAccept4 tests whether accept4 system call is available. +var SupportAccept4 = sync.OnceValue(func() bool { + for { + // Test if the accept4() is available. + _, _, err := syscall.Accept4(0, syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC) + if err == syscall.EINTR { + continue + } + return err != syscall.ENOSYS + } +}) + +// SupportTCPKeepAliveIdleIntvlCNT determines whether the TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT +// are available by checking the kernel version for Solaris 11.4. +var SupportTCPKeepAliveIdleIntvlCNT = sync.OnceValue(func() bool { + return KernelVersionGE(11, 4) +}) diff --git a/go/src/internal/syscall/unix/kernel_version_solaris_test.go b/go/src/internal/syscall/unix/kernel_version_solaris_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1c51c55fa0999531aa19794039aa45940f5d593e --- /dev/null +++ b/go/src/internal/syscall/unix/kernel_version_solaris_test.go @@ -0,0 +1,59 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build solaris + +package unix_test + +import ( + "internal/syscall/unix" + "runtime" + "syscall" + "testing" +) + +func TestSupportSockNonblockCloexec(t *testing.T) { + // Test that SupportSockNonblockCloexec returns true if socket succeeds with SOCK_NONBLOCK and SOCK_CLOEXEC. + s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0) + if err == nil { + syscall.Close(s) + } + wantSock := err != syscall.EPROTONOSUPPORT && err != syscall.EINVAL + gotSock := unix.SupportSockNonblockCloexec() + if wantSock != gotSock { + t.Fatalf("SupportSockNonblockCloexec, got %t; want %t", gotSock, wantSock) + } + + // Test that SupportAccept4 returns true if accept4 is available. + for { + _, _, err = syscall.Accept4(0, syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC) + if err != syscall.EINTR { + break + } + } + wantAccept4 := err != syscall.ENOSYS + gotAccept4 := unix.SupportAccept4() + if wantAccept4 != gotAccept4 { + t.Fatalf("SupportAccept4, got %t; want %t", gotAccept4, wantAccept4) + } + + // Test that the version returned by KernelVersion matches expectations. + major, minor := unix.KernelVersion() + t.Logf("Kernel version: %d.%d", major, minor) + if runtime.GOOS == "illumos" { + if gotSock && gotAccept4 && (major < 5 || (major == 5 && minor < 11)) { + t.Fatalf("SupportSockNonblockCloexec and SupportAccept4 are true, but kernel version is older than 5.11, SunOS version: %d.%d", major, minor) + } + if !gotSock && !gotAccept4 && (major > 5 || (major == 5 && minor >= 11)) { + t.Errorf("SupportSockNonblockCloexec and SupportAccept4 are false, but kernel version is 5.11 or newer, SunOS version: %d.%d", major, minor) + } + } else { // Solaris + if gotSock && gotAccept4 && (major < 11 || (major == 11 && minor < 4)) { + t.Fatalf("SupportSockNonblockCloexec and SupportAccept4 are true, but kernel version is older than 11.4, Solaris version: %d.%d", major, minor) + } + if !gotSock && !gotAccept4 && (major > 11 || (major == 11 && minor >= 4)) { + t.Errorf("SupportSockNonblockCloexec and SupportAccept4 are false, but kernel version is 11.4 or newer, Solaris version: %d.%d", major, minor) + } + } +} diff --git a/go/src/internal/syscall/unix/net.go b/go/src/internal/syscall/unix/net.go new file mode 100644 index 0000000000000000000000000000000000000000..5618d40ae0f79385066b90ec4a32b97bd31e8eaf --- /dev/null +++ b/go/src/internal/syscall/unix/net.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 + +package unix + +import ( + "syscall" + _ "unsafe" +) + +//go:linkname RecvfromInet4 syscall.recvfromInet4 +//go:noescape +func RecvfromInet4(fd int, p []byte, flags int, from *syscall.SockaddrInet4) (int, error) + +//go:linkname RecvfromInet6 syscall.recvfromInet6 +//go:noescape +func RecvfromInet6(fd int, p []byte, flags int, from *syscall.SockaddrInet6) (n int, err error) + +//go:linkname SendtoInet4 syscall.sendtoInet4 +//go:noescape +func SendtoInet4(fd int, p []byte, flags int, to *syscall.SockaddrInet4) (err error) + +//go:linkname SendtoInet6 syscall.sendtoInet6 +//go:noescape +func SendtoInet6(fd int, p []byte, flags int, to *syscall.SockaddrInet6) (err error) + +//go:linkname SendmsgNInet4 syscall.sendmsgNInet4 +//go:noescape +func SendmsgNInet4(fd int, p, oob []byte, to *syscall.SockaddrInet4, flags int) (n int, err error) + +//go:linkname SendmsgNInet6 syscall.sendmsgNInet6 +//go:noescape +func SendmsgNInet6(fd int, p, oob []byte, to *syscall.SockaddrInet6, flags int) (n int, err error) + +//go:linkname RecvmsgInet4 syscall.recvmsgInet4 +//go:noescape +func RecvmsgInet4(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet4) (n, oobn int, recvflags int, err error) + +//go:linkname RecvmsgInet6 syscall.recvmsgInet6 +//go:noescape +func RecvmsgInet6(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet6) (n, oobn int, recvflags int, err error) diff --git a/go/src/internal/syscall/unix/net_darwin.go b/go/src/internal/syscall/unix/net_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..7e8f2ac12c6ba4b6564bb53e78ba3de316b3f3cd --- /dev/null +++ b/go/src/internal/syscall/unix/net_darwin.go @@ -0,0 +1,164 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +const ( + AI_CANONNAME = 0x2 + AI_ALL = 0x100 + AI_V4MAPPED = 0x800 + AI_MASK = 0x1407 + + EAI_ADDRFAMILY = 1 + EAI_AGAIN = 2 + EAI_NODATA = 7 + EAI_NONAME = 8 + EAI_SERVICE = 9 + EAI_SYSTEM = 11 + EAI_OVERFLOW = 14 + + NI_NAMEREQD = 4 +) + +type Addrinfo struct { + Flags int32 + Family int32 + Socktype int32 + Protocol int32 + Addrlen uint32 + Canonname *byte + Addr *syscall.RawSockaddr + Next *Addrinfo +} + +//go:cgo_ldflag "-lresolv" + +//go:cgo_import_dynamic libc_getaddrinfo getaddrinfo "/usr/lib/libSystem.B.dylib" +func libc_getaddrinfo_trampoline() + +func Getaddrinfo(hostname, servname *byte, hints *Addrinfo, res **Addrinfo) (int, error) { + gerrno, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_getaddrinfo_trampoline), + uintptr(unsafe.Pointer(hostname)), + uintptr(unsafe.Pointer(servname)), + uintptr(unsafe.Pointer(hints)), + uintptr(unsafe.Pointer(res)), + 0, + 0) + var err error + if errno != 0 { + err = errno + } + return int(gerrno), err +} + +//go:cgo_import_dynamic libc_freeaddrinfo freeaddrinfo "/usr/lib/libSystem.B.dylib" +func libc_freeaddrinfo_trampoline() + +func Freeaddrinfo(ai *Addrinfo) { + syscall_syscall6(abi.FuncPCABI0(libc_freeaddrinfo_trampoline), + uintptr(unsafe.Pointer(ai)), + 0, 0, 0, 0, 0) +} + +//go:cgo_import_dynamic libc_getnameinfo getnameinfo "/usr/lib/libSystem.B.dylib" +func libc_getnameinfo_trampoline() + +func Getnameinfo(sa *syscall.RawSockaddr, salen int, host *byte, hostlen int, serv *byte, servlen int, flags int) (int, error) { + gerrno, _, errno := syscall_syscall9(abi.FuncPCABI0(libc_getnameinfo_trampoline), + uintptr(unsafe.Pointer(sa)), + uintptr(salen), + uintptr(unsafe.Pointer(host)), + uintptr(hostlen), + uintptr(unsafe.Pointer(serv)), + uintptr(servlen), + uintptr(flags), + 0, + 0) + var err error + if errno != 0 { + err = errno + } + return int(gerrno), err +} + +//go:cgo_import_dynamic libc_gai_strerror gai_strerror "/usr/lib/libSystem.B.dylib" +func libc_gai_strerror_trampoline() + +func GaiStrerror(ecode int) string { + r1, _, _ := syscall_syscall(abi.FuncPCABI0(libc_gai_strerror_trampoline), + uintptr(ecode), + 0, 0) + return GoString((*byte)(unsafe.Pointer(r1))) +} + +// Implemented in the runtime package. +func gostring(*byte) string + +func GoString(p *byte) string { + return gostring(p) +} + +//go:linkname syscall_syscall syscall.syscall +func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:linkname syscall_syscallPtr syscall.syscallPtr +func syscall_syscallPtr(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:linkname syscall_syscall6 syscall.syscall6 +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:linkname syscall_syscall6X syscall.syscall6X +func syscall_syscall6X(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:linkname syscall_syscall9 syscall.syscall9 +func syscall_syscall9(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) + +type ResState struct { + unexported [69]uintptr +} + +//go:cgo_import_dynamic libresolv_res_9_ninit res_9_ninit "/usr/lib/libresolv.9.dylib" +func libresolv_res_9_ninit_trampoline() + +func ResNinit(state *ResState) error { + _, _, errno := syscall_syscall(abi.FuncPCABI0(libresolv_res_9_ninit_trampoline), + uintptr(unsafe.Pointer(state)), + 0, 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libresolv_res_9_nclose res_9_nclose "/usr/lib/libresolv.9.dylib" +func libresolv_res_9_nclose_trampoline() + +func ResNclose(state *ResState) { + syscall_syscall(abi.FuncPCABI0(libresolv_res_9_nclose_trampoline), + uintptr(unsafe.Pointer(state)), + 0, 0) +} + +//go:cgo_import_dynamic libresolv_res_9_nsearch res_9_nsearch "/usr/lib/libresolv.9.dylib" +func libresolv_res_9_nsearch_trampoline() + +func ResNsearch(state *ResState, dname *byte, class, typ int, ans *byte, anslen int) (int, error) { + r1, _, errno := syscall_syscall6(abi.FuncPCABI0(libresolv_res_9_nsearch_trampoline), + uintptr(unsafe.Pointer(state)), + uintptr(unsafe.Pointer(dname)), + uintptr(class), + uintptr(typ), + uintptr(unsafe.Pointer(ans)), + uintptr(anslen)) + if errno != 0 { + return 0, errno + } + return int(int32(r1)), nil +} diff --git a/go/src/internal/syscall/unix/net_js.go b/go/src/internal/syscall/unix/net_js.go new file mode 100644 index 0000000000000000000000000000000000000000..622fc8eb14aa03f31d4475575fff1c17f48eb20c --- /dev/null +++ b/go/src/internal/syscall/unix/net_js.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 js + +package unix + +import ( + "syscall" + _ "unsafe" +) + +func RecvfromInet4(fd int, p []byte, flags int, from *syscall.SockaddrInet4) (int, error) { + return 0, syscall.ENOSYS +} + +func RecvfromInet6(fd int, p []byte, flags int, from *syscall.SockaddrInet6) (n int, err error) { + return 0, syscall.ENOSYS +} + +func SendtoInet4(fd int, p []byte, flags int, to *syscall.SockaddrInet4) (err error) { + return syscall.ENOSYS +} + +func SendtoInet6(fd int, p []byte, flags int, to *syscall.SockaddrInet6) (err error) { + return syscall.ENOSYS +} + +func SendmsgNInet4(fd int, p, oob []byte, to *syscall.SockaddrInet4, flags int) (n int, err error) { + return 0, syscall.ENOSYS +} + +func SendmsgNInet6(fd int, p, oob []byte, to *syscall.SockaddrInet6, flags int) (n int, err error) { + return 0, syscall.ENOSYS +} + +func RecvmsgInet4(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet4) (n, oobn int, recvflags int, err error) { + return 0, 0, 0, syscall.ENOSYS +} + +func RecvmsgInet6(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet6) (n, oobn int, recvflags int, err error) { + return 0, 0, 0, syscall.ENOSYS +} diff --git a/go/src/internal/syscall/unix/net_wasip1.go b/go/src/internal/syscall/unix/net_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..8a60e8f7a1ad31496bb4eacb99e92db233c91912 --- /dev/null +++ b/go/src/internal/syscall/unix/net_wasip1.go @@ -0,0 +1,44 @@ +// 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 unix + +import ( + "syscall" + _ "unsafe" +) + +func RecvfromInet4(fd int, p []byte, flags int, from *syscall.SockaddrInet4) (int, error) { + return 0, syscall.ENOSYS +} + +func RecvfromInet6(fd int, p []byte, flags int, from *syscall.SockaddrInet6) (n int, err error) { + return 0, syscall.ENOSYS +} + +func SendtoInet4(fd int, p []byte, flags int, to *syscall.SockaddrInet4) (err error) { + return syscall.ENOSYS +} + +func SendtoInet6(fd int, p []byte, flags int, to *syscall.SockaddrInet6) (err error) { + return syscall.ENOSYS +} + +func SendmsgNInet4(fd int, p, oob []byte, to *syscall.SockaddrInet4, flags int) (n int, err error) { + return 0, syscall.ENOSYS +} + +func SendmsgNInet6(fd int, p, oob []byte, to *syscall.SockaddrInet6, flags int) (n int, err error) { + return 0, syscall.ENOSYS +} + +func RecvmsgInet4(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet4) (n, oobn int, recvflags int, err error) { + return 0, 0, 0, syscall.ENOSYS +} + +func RecvmsgInet6(fd int, p, oob []byte, flags int, from *syscall.SockaddrInet6) (n, oobn int, recvflags int, err error) { + return 0, 0, 0, syscall.ENOSYS +} diff --git a/go/src/internal/syscall/unix/nofollow_bsd.go b/go/src/internal/syscall/unix/nofollow_bsd.go new file mode 100644 index 0000000000000000000000000000000000000000..32c4de11901228c3b2987d547e8e99d19d4b467f --- /dev/null +++ b/go/src/internal/syscall/unix/nofollow_bsd.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build dragonfly || freebsd + +package unix + +import "syscall" + +// References: +// - https://man.freebsd.org/cgi/man.cgi?open(2) +// - https://man.dragonflybsd.org/?command=open§ion=2 +const noFollowErrno = syscall.EMLINK diff --git a/go/src/internal/syscall/unix/nofollow_netbsd.go b/go/src/internal/syscall/unix/nofollow_netbsd.go new file mode 100644 index 0000000000000000000000000000000000000000..3ae91e79cddc20e47a1943bac5a3ab06f70c60eb --- /dev/null +++ b/go/src/internal/syscall/unix/nofollow_netbsd.go @@ -0,0 +1,10 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import "syscall" + +// Reference: https://man.netbsd.org/open.2 +const noFollowErrno = syscall.EFTYPE diff --git a/go/src/internal/syscall/unix/nofollow_posix.go b/go/src/internal/syscall/unix/nofollow_posix.go new file mode 100644 index 0000000000000000000000000000000000000000..3a5e0af05d33fd99da6765fa0ca6a33974d78535 --- /dev/null +++ b/go/src/internal/syscall/unix/nofollow_posix.go @@ -0,0 +1,22 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (unix && !dragonfly && !freebsd && !netbsd) || wasip1 + +package unix + +import "syscall" + +// POSIX.1-2008 says it's ELOOP. Most platforms follow: +// +// - aix: O_NOFOLLOW not documented (https://www.ibm.com/docs/ssw_aix_73/o_bostechref/open.html), assuming ELOOP +// - android: see linux +// - darwin: https://github.com/apple/darwin-xnu/blob/main/bsd/man/man2/open.2 +// - hurd: who knows if it works at all (https://www.gnu.org/software/hurd/open_issues/open_symlink.html) +// - illumos: https://illumos.org/man/2/open +// - ios: see darwin +// - linux: https://man7.org/linux/man-pages/man2/openat.2.html +// - openbsd: https://man.openbsd.org/open.2 +// - solaris: https://docs.oracle.com/cd/E23824_01/html/821-1463/open-2.html +const noFollowErrno = syscall.ELOOP diff --git a/go/src/internal/syscall/unix/nonblocking_js.go b/go/src/internal/syscall/unix/nonblocking_js.go new file mode 100644 index 0000000000000000000000000000000000000000..cfe78c58d8de2c2bac2f173e98a6908aac051b95 --- /dev/null +++ b/go/src/internal/syscall/unix/nonblocking_js.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build js && wasm + +package unix + +func IsNonblock(fd int) (nonblocking bool, err error) { + return false, nil +} + +func HasNonblockFlag(flag int) bool { + return false +} diff --git a/go/src/internal/syscall/unix/nonblocking_unix.go b/go/src/internal/syscall/unix/nonblocking_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..fc0bc27916f4e99721578a4d2bfbbeddc1ef1bbe --- /dev/null +++ b/go/src/internal/syscall/unix/nonblocking_unix.go @@ -0,0 +1,21 @@ +// 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 + +package unix + +import "syscall" + +func IsNonblock(fd int) (nonblocking bool, err error) { + flag, e1 := Fcntl(fd, syscall.F_GETFL, 0) + if e1 != nil { + return false, e1 + } + return flag&syscall.O_NONBLOCK != 0, nil +} + +func HasNonblockFlag(flag int) bool { + return flag&syscall.O_NONBLOCK != 0 +} diff --git a/go/src/internal/syscall/unix/nonblocking_wasip1.go b/go/src/internal/syscall/unix/nonblocking_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..5b2b53bf5c3c6860e413229c43ad52e86574f5d4 --- /dev/null +++ b/go/src/internal/syscall/unix/nonblocking_wasip1.go @@ -0,0 +1,31 @@ +// 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 unix + +import ( + "syscall" + _ "unsafe" // for go:linkname +) + +func IsNonblock(fd int) (nonblocking bool, err error) { + flags, e1 := fd_fdstat_get_flags(fd) + if e1 != nil { + return false, e1 + } + return flags&syscall.FDFLAG_NONBLOCK != 0, nil +} + +func HasNonblockFlag(flag int) bool { + return flag&syscall.FDFLAG_NONBLOCK != 0 +} + +// 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_flags syscall.fd_fdstat_get_flags +func fd_fdstat_get_flags(fd int) (uint32, error) diff --git a/go/src/internal/syscall/unix/pidfd_linux.go b/go/src/internal/syscall/unix/pidfd_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..e9417623db79e8bd8f76c836f30b1d900a2960e9 --- /dev/null +++ b/go/src/internal/syscall/unix/pidfd_linux.go @@ -0,0 +1,23 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import "syscall" + +func PidFDSendSignal(pidfd uintptr, s syscall.Signal) error { + _, _, errno := syscall.Syscall(pidfdSendSignalTrap, pidfd, uintptr(s), 0) + if errno != 0 { + return errno + } + return nil +} + +func PidFDOpen(pid, flags int) (uintptr, error) { + pidfd, _, errno := syscall.Syscall(pidfdOpenTrap, uintptr(pid), uintptr(flags), 0) + if errno != 0 { + return ^uintptr(0), errno + } + return uintptr(pidfd), nil +} diff --git a/go/src/internal/syscall/unix/pty_darwin.go b/go/src/internal/syscall/unix/pty_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..b43321a42ef9be10a4227b9c95b3e401bd210b70 --- /dev/null +++ b/go/src/internal/syscall/unix/pty_darwin.go @@ -0,0 +1,65 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "internal/abi" + "unsafe" +) + +//go:cgo_import_dynamic libc_grantpt grantpt "/usr/lib/libSystem.B.dylib" +func libc_grantpt_trampoline() + +func Grantpt(fd int) error { + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_grantpt_trampoline), uintptr(fd), 0, 0, 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libc_unlockpt unlockpt "/usr/lib/libSystem.B.dylib" +func libc_unlockpt_trampoline() + +func Unlockpt(fd int) error { + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_unlockpt_trampoline), uintptr(fd), 0, 0, 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} + +//go:cgo_import_dynamic libc_ptsname_r ptsname_r "/usr/lib/libSystem.B.dylib" +func libc_ptsname_r_trampoline() + +func Ptsname(fd int) (string, error) { + buf := make([]byte, 256) + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_ptsname_r_trampoline), + uintptr(fd), + uintptr(unsafe.Pointer(&buf[0])), + uintptr(len(buf)-1), + 0, 0, 0) + if errno != 0 { + return "", errno + } + for i, c := range buf { + if c == 0 { + buf = buf[:i] + break + } + } + return string(buf), nil +} + +//go:cgo_import_dynamic libc_posix_openpt posix_openpt "/usr/lib/libSystem.B.dylib" +func libc_posix_openpt_trampoline() + +func PosixOpenpt(flag int) (fd int, err error) { + ufd, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_posix_openpt_trampoline), uintptr(flag), 0, 0, 0, 0, 0) + if errno != 0 { + return -1, errno + } + return int(ufd), nil +} diff --git a/go/src/internal/syscall/unix/renameat2_sysnum_linux.go b/go/src/internal/syscall/unix/renameat2_sysnum_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..e41a65db79abc85aa75d3a2fac503e0c6022b428 --- /dev/null +++ b/go/src/internal/syscall/unix/renameat2_sysnum_linux.go @@ -0,0 +1,16 @@ +// Copyright 2025 The Go 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 && (loong64 || riscv64) + +package unix + +import "syscall" + +const ( + // loong64 and riscv64 only have renameat2. + // renameat2 has an extra flags parameter. + // When called with a 0 flags it is identical to renameat. + renameatTrap uintptr = syscall.SYS_RENAMEAT2 +) diff --git a/go/src/internal/syscall/unix/renameat_sysnum_linux.go b/go/src/internal/syscall/unix/renameat_sysnum_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..d3663ad1dc4832126b79b671b11afd85632b9952 --- /dev/null +++ b/go/src/internal/syscall/unix/renameat_sysnum_linux.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go 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 && !(loong64 || riscv64) + +package unix + +import "syscall" + +const ( + renameatTrap uintptr = syscall.SYS_RENAMEAT +) diff --git a/go/src/internal/syscall/unix/siginfo_linux.go b/go/src/internal/syscall/unix/siginfo_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..9f83114e45cfd522a8c2de896484ca45ec7e7369 --- /dev/null +++ b/go/src/internal/syscall/unix/siginfo_linux.go @@ -0,0 +1,64 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" +) + +const is64bit = ^uint(0) >> 63 // 0 for 32-bit hosts, 1 for 64-bit ones. + +// SiginfoChild is a struct filled in by Linux waitid syscall. +// In C, siginfo_t contains a union with multiple members; +// this struct corresponds to one used when Signo is SIGCHLD. +// +// NOTE fields are exported to be used by TestSiginfoChildLayout. +type SiginfoChild struct { + Signo int32 + siErrnoCode // Two int32 fields, swapped on MIPS. + _ [is64bit]int32 // Extra padding for 64-bit hosts only. + + // End of common part. Beginning of signal-specific part. + + Pid int32 + Uid uint32 + Status int32 + + // Pad to 128 bytes. + _ [128 - (6+is64bit)*4]byte +} + +const ( + // Possible values for SiginfoChild.Code field. + _CLD_EXITED int32 = 1 + _CLD_KILLED = 2 + _CLD_DUMPED = 3 + _CLD_TRAPPED = 4 + _CLD_STOPPED = 5 + _CLD_CONTINUED = 6 + + // These are the same as in syscall/syscall_linux.go. + core = 0x80 + stopped = 0x7f + continued = 0xffff +) + +// WaitStatus converts SiginfoChild, as filled in by the waitid syscall, +// to syscall.WaitStatus. +func (s *SiginfoChild) WaitStatus() (ws syscall.WaitStatus) { + switch s.Code { + case _CLD_EXITED: + ws = syscall.WaitStatus(s.Status << 8) + case _CLD_DUMPED: + ws = syscall.WaitStatus(s.Status) | core + case _CLD_KILLED: + ws = syscall.WaitStatus(s.Status) + case _CLD_TRAPPED, _CLD_STOPPED: + ws = syscall.WaitStatus(s.Status<<8) | stopped + case _CLD_CONTINUED: + ws = continued + } + return +} diff --git a/go/src/internal/syscall/unix/siginfo_linux_mipsx.go b/go/src/internal/syscall/unix/siginfo_linux_mipsx.go new file mode 100644 index 0000000000000000000000000000000000000000..2fca0c55055ed24fa004a5e3ab46c6f19f111837 --- /dev/null +++ b/go/src/internal/syscall/unix/siginfo_linux_mipsx.go @@ -0,0 +1,12 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && (mips || mipsle || mips64 || mips64le) + +package unix + +type siErrnoCode struct { + Code int32 + Errno int32 +} diff --git a/go/src/internal/syscall/unix/siginfo_linux_other.go b/go/src/internal/syscall/unix/siginfo_linux_other.go new file mode 100644 index 0000000000000000000000000000000000000000..cfdc4ddf51ce20659079f34aceacd82f96338367 --- /dev/null +++ b/go/src/internal/syscall/unix/siginfo_linux_other.go @@ -0,0 +1,12 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && !(mips || mipsle || mips64 || mips64le) + +package unix + +type siErrnoCode struct { + Errno int32 + Code int32 +} diff --git a/go/src/internal/syscall/unix/siginfo_linux_test.go b/go/src/internal/syscall/unix/siginfo_linux_test.go new file mode 100644 index 0000000000000000000000000000000000000000..596c2ebee3facf1c89d31c941d37b1f86eb3227c --- /dev/null +++ b/go/src/internal/syscall/unix/siginfo_linux_test.go @@ -0,0 +1,59 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix_test + +import ( + "internal/goarch" + "internal/syscall/unix" + "runtime" + "strings" + "testing" + "unsafe" +) + +// TestSiginfoChildLayout validates SiginfoChild layout. Modelled after +// static assertions in linux kernel's arch/*/kernel/signal*.c. +func TestSiginfoChildLayout(t *testing.T) { + var si unix.SiginfoChild + + const host64bit = goarch.PtrSize == 8 + + if v := unsafe.Sizeof(si); v != 128 { + t.Fatalf("sizeof: got %d, want 128", v) + } + + ofSigno := 0 + ofErrno := 4 + ofCode := 8 + if strings.HasPrefix(runtime.GOARCH, "mips") { + // These two fields are swapped on MIPS platforms. + ofErrno, ofCode = ofCode, ofErrno + } + ofPid := 12 + if host64bit { + ofPid = 16 + } + ofUid := ofPid + 4 + ofStatus := ofPid + 8 + + offsets := []struct { + name string + got uintptr + want int + }{ + {"Signo", unsafe.Offsetof(si.Signo), ofSigno}, + {"Errno", unsafe.Offsetof(si.Errno), ofErrno}, + {"Code", unsafe.Offsetof(si.Code), ofCode}, + {"Pid", unsafe.Offsetof(si.Pid), ofPid}, + {"Uid", unsafe.Offsetof(si.Uid), ofUid}, + {"Status", unsafe.Offsetof(si.Status), ofStatus}, + } + + for _, tc := range offsets { + if int(tc.got) != tc.want { + t.Errorf("offsetof %s: got %d, want %d", tc.name, tc.got, tc.want) + } + } +} diff --git a/go/src/internal/syscall/unix/syscall.go b/go/src/internal/syscall/unix/syscall.go new file mode 100644 index 0000000000000000000000000000000000000000..99805d986be97318ee5699010b1c9e85ba41054c --- /dev/null +++ b/go/src/internal/syscall/unix/syscall.go @@ -0,0 +1,8 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +// Single-word zero for use when we need a valid pointer to 0 bytes. +var _zero uintptr diff --git a/go/src/internal/syscall/unix/sysnum_freebsd.go b/go/src/internal/syscall/unix/sysnum_freebsd.go new file mode 100644 index 0000000000000000000000000000000000000000..2c81110409e6f05a4a7acb4148a334ecebe60e2a --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_freebsd.go @@ -0,0 +1,7 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +const copyFileRangeTrap uintptr = 569 diff --git a/go/src/internal/syscall/unix/sysnum_linux_386.go b/go/src/internal/syscall/unix/sysnum_linux_386.go new file mode 100644 index 0000000000000000000000000000000000000000..c83beef74906bf596a68fa2990aff01d8339ef25 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_386.go @@ -0,0 +1,13 @@ +// 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 unix + +const ( + getrandomTrap uintptr = 355 + copyFileRangeTrap uintptr = 377 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_amd64.go b/go/src/internal/syscall/unix/sysnum_linux_amd64.go new file mode 100644 index 0000000000000000000000000000000000000000..098e3320a0c7edb083bfdd5c20136b7203d164c6 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_amd64.go @@ -0,0 +1,13 @@ +// 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 unix + +const ( + getrandomTrap uintptr = 318 + copyFileRangeTrap uintptr = 326 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_arm.go b/go/src/internal/syscall/unix/sysnum_linux_arm.go new file mode 100644 index 0000000000000000000000000000000000000000..f0cd45f9b004896fd369f91e924a26d0cfe0c633 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_arm.go @@ -0,0 +1,13 @@ +// 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 unix + +const ( + getrandomTrap uintptr = 384 + copyFileRangeTrap uintptr = 391 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_generic.go b/go/src/internal/syscall/unix/sysnum_linux_generic.go new file mode 100644 index 0000000000000000000000000000000000000000..ec622cff0d6ef69ff08af5dab2888d795be70233 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_generic.go @@ -0,0 +1,19 @@ +// 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 linux && (arm64 || loong64 || riscv64) + +package unix + +// This file is named "generic" because at a certain point Linux started +// standardizing on system call numbers across architectures. So far this +// means only arm64 loong64 and riscv64 use the standard numbers. + +const ( + getrandomTrap uintptr = 278 + copyFileRangeTrap uintptr = 285 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_mips64x.go b/go/src/internal/syscall/unix/sysnum_linux_mips64x.go new file mode 100644 index 0000000000000000000000000000000000000000..3875105d7de02ee9fd94c0e7a2d766bf62a283c5 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_mips64x.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 mips64 || mips64le + +package unix + +const ( + getrandomTrap uintptr = 5313 + copyFileRangeTrap uintptr = 5320 + pidfdSendSignalTrap uintptr = 5424 + pidfdOpenTrap uintptr = 5434 + openat2Trap uintptr = 5437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_mipsx.go b/go/src/internal/syscall/unix/sysnum_linux_mipsx.go new file mode 100644 index 0000000000000000000000000000000000000000..bdd2fef2c30881e54235b2a4bf469a7ec0f2b726 --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_mipsx.go @@ -0,0 +1,15 @@ +// 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 mips || mipsle + +package unix + +const ( + getrandomTrap uintptr = 4353 + copyFileRangeTrap uintptr = 4360 + pidfdSendSignalTrap uintptr = 4424 + pidfdOpenTrap uintptr = 4434 + openat2Trap uintptr = 4437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_ppc64x.go b/go/src/internal/syscall/unix/sysnum_linux_ppc64x.go new file mode 100644 index 0000000000000000000000000000000000000000..9291d58f5de9e0b31141001697a65aebf9c6dc7e --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_ppc64x.go @@ -0,0 +1,15 @@ +// 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 ppc64 || ppc64le + +package unix + +const ( + getrandomTrap uintptr = 359 + copyFileRangeTrap uintptr = 379 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/sysnum_linux_s390x.go b/go/src/internal/syscall/unix/sysnum_linux_s390x.go new file mode 100644 index 0000000000000000000000000000000000000000..65a82d1c3d63689595c5c1753571750b9ac3461c --- /dev/null +++ b/go/src/internal/syscall/unix/sysnum_linux_s390x.go @@ -0,0 +1,13 @@ +// 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 unix + +const ( + getrandomTrap uintptr = 349 + copyFileRangeTrap uintptr = 375 + pidfdSendSignalTrap uintptr = 424 + pidfdOpenTrap uintptr = 434 + openat2Trap uintptr = 437 +) diff --git a/go/src/internal/syscall/unix/tcsetpgrp_bsd.go b/go/src/internal/syscall/unix/tcsetpgrp_bsd.go new file mode 100644 index 0000000000000000000000000000000000000000..bac614df97c0af6cd5b8c7e2019412a708eccb25 --- /dev/null +++ b/go/src/internal/syscall/unix/tcsetpgrp_bsd.go @@ -0,0 +1,22 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package unix + +import ( + "syscall" + "unsafe" +) + +//go:linkname ioctlPtr syscall.ioctlPtr +func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) + +// Note that pgid should really be pid_t, however _C_int (aka int32) is +// generally equivalent. + +func Tcsetpgrp(fd int, pgid int32) (err error) { + return ioctlPtr(fd, syscall.TIOCSPGRP, unsafe.Pointer(&pgid)) +} diff --git a/go/src/internal/syscall/unix/tcsetpgrp_linux.go b/go/src/internal/syscall/unix/tcsetpgrp_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..be208d9cd2edaedb9b70efc1b734ca51a8d5f48e --- /dev/null +++ b/go/src/internal/syscall/unix/tcsetpgrp_linux.go @@ -0,0 +1,21 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" + "unsafe" +) + +// Note that pgid should really be pid_t, however _C_int (aka int32) is +// generally equivalent. + +func Tcsetpgrp(fd int, pgid int32) (err error) { + _, _, errno := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCSPGRP), uintptr(unsafe.Pointer(&pgid)), 0, 0, 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/unix/user_darwin.go b/go/src/internal/syscall/unix/user_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..d05acdaa490514f22b12870f0a24cf18b80e0b50 --- /dev/null +++ b/go/src/internal/syscall/unix/user_darwin.go @@ -0,0 +1,121 @@ +// 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 unix + +import ( + "internal/abi" + "syscall" + "unsafe" +) + +//go:cgo_import_dynamic libc_getgrouplist getgrouplist "/usr/lib/libSystem.B.dylib" +func libc_getgrouplist_trampoline() + +func Getgrouplist(name *byte, gid uint32, gids *uint32, n *int32) error { + _, _, errno := syscall_syscall6(abi.FuncPCABI0(libc_getgrouplist_trampoline), + uintptr(unsafe.Pointer(name)), uintptr(gid), uintptr(unsafe.Pointer(gids)), + uintptr(unsafe.Pointer(n)), 0, 0) + if errno != 0 { + return errno + } + return nil +} + +const ( + SC_GETGR_R_SIZE_MAX = 0x46 + SC_GETPW_R_SIZE_MAX = 0x47 +) + +type Passwd struct { + Name *byte + Passwd *byte + Uid uint32 // uid_t + Gid uint32 // gid_t + Change int64 // time_t + Class *byte + Gecos *byte + Dir *byte + Shell *byte + Expire int64 // time_t +} + +type Group struct { + Name *byte + Passwd *byte + Gid uint32 // gid_t + Mem **byte +} + +//go:cgo_import_dynamic libc_getpwnam_r getpwnam_r "/usr/lib/libSystem.B.dylib" +func libc_getpwnam_r_trampoline() + +func Getpwnam(name *byte, pwd *Passwd, buf *byte, size uintptr, result **Passwd) syscall.Errno { + // Note: Returns an errno as its actual result, not in global errno. + errno, _, _ := syscall_syscall6(abi.FuncPCABI0(libc_getpwnam_r_trampoline), + uintptr(unsafe.Pointer(name)), + uintptr(unsafe.Pointer(pwd)), + uintptr(unsafe.Pointer(buf)), + size, + uintptr(unsafe.Pointer(result)), + 0) + return syscall.Errno(errno) +} + +//go:cgo_import_dynamic libc_getpwuid_r getpwuid_r "/usr/lib/libSystem.B.dylib" +func libc_getpwuid_r_trampoline() + +func Getpwuid(uid uint32, pwd *Passwd, buf *byte, size uintptr, result **Passwd) syscall.Errno { + // Note: Returns an errno as its actual result, not in global errno. + errno, _, _ := syscall_syscall6(abi.FuncPCABI0(libc_getpwuid_r_trampoline), + uintptr(uid), + uintptr(unsafe.Pointer(pwd)), + uintptr(unsafe.Pointer(buf)), + size, + uintptr(unsafe.Pointer(result)), + 0) + return syscall.Errno(errno) +} + +//go:cgo_import_dynamic libc_getgrnam_r getgrnam_r "/usr/lib/libSystem.B.dylib" +func libc_getgrnam_r_trampoline() + +func Getgrnam(name *byte, grp *Group, buf *byte, size uintptr, result **Group) syscall.Errno { + // Note: Returns an errno as its actual result, not in global errno. + errno, _, _ := syscall_syscall6(abi.FuncPCABI0(libc_getgrnam_r_trampoline), + uintptr(unsafe.Pointer(name)), + uintptr(unsafe.Pointer(grp)), + uintptr(unsafe.Pointer(buf)), + size, + uintptr(unsafe.Pointer(result)), + 0) + return syscall.Errno(errno) +} + +//go:cgo_import_dynamic libc_getgrgid_r getgrgid_r "/usr/lib/libSystem.B.dylib" +func libc_getgrgid_r_trampoline() + +func Getgrgid(gid uint32, grp *Group, buf *byte, size uintptr, result **Group) syscall.Errno { + // Note: Returns an errno as its actual result, not in global errno. + errno, _, _ := syscall_syscall6(abi.FuncPCABI0(libc_getgrgid_r_trampoline), + uintptr(gid), + uintptr(unsafe.Pointer(grp)), + uintptr(unsafe.Pointer(buf)), + size, + uintptr(unsafe.Pointer(result)), + 0) + return syscall.Errno(errno) +} + +//go:cgo_import_dynamic libc_sysconf sysconf "/usr/lib/libSystem.B.dylib" +func libc_sysconf_trampoline() + +func Sysconf(key int32) int64 { + val, _, errno := syscall_syscall6X(abi.FuncPCABI0(libc_sysconf_trampoline), + uintptr(key), 0, 0, 0, 0, 0) + if errno != 0 { + return -1 + } + return int64(val) +} diff --git a/go/src/internal/syscall/unix/utimes.go b/go/src/internal/syscall/unix/utimes.go new file mode 100644 index 0000000000000000000000000000000000000000..332a4b69bb2f336057f72fdb1ef134236270eaf3 --- /dev/null +++ b/go/src/internal/syscall/unix/utimes.go @@ -0,0 +1,15 @@ +// Copyright 2025 The Go 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 && !wasip1 + +package unix + +import ( + "syscall" + _ "unsafe" // for //go:linkname +) + +//go:linkname Utimensat syscall.utimensat +func Utimensat(dirfd int, path string, times *[2]syscall.Timespec, flag int) error diff --git a/go/src/internal/syscall/unix/utimes_wasip1.go b/go/src/internal/syscall/unix/utimes_wasip1.go new file mode 100644 index 0000000000000000000000000000000000000000..a0711b0c042910059d905586cf138336969f30cd --- /dev/null +++ b/go/src/internal/syscall/unix/utimes_wasip1.go @@ -0,0 +1,42 @@ +// Copyright 2025 The Go 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 unix + +import ( + "syscall" + "unsafe" +) + +//go:wasmimport wasi_snapshot_preview1 path_filestat_set_times +//go:noescape +func path_filestat_set_times(fd int32, flags uint32, path *byte, pathLen size, atim uint64, mtim uint64, fstflags uint32) syscall.Errno + +func Utimensat(dirfd int, path string, times *[2]syscall.Timespec, flag int) error { + if path == "" { + return syscall.EINVAL + } + atime := syscall.TimespecToNsec(times[0]) + mtime := syscall.TimespecToNsec(times[1]) + + var fflag uint32 + if times[0].Nsec != UTIME_OMIT { + fflag |= syscall.FILESTAT_SET_ATIM + } + if times[1].Nsec != UTIME_OMIT { + fflag |= syscall.FILESTAT_SET_MTIM + } + errno := path_filestat_set_times( + int32(dirfd), + syscall.LOOKUP_SYMLINK_FOLLOW, + unsafe.StringData(path), + size(len(path)), + uint64(atime), + uint64(mtime), + fflag, + ) + return errnoErr(errno) +} diff --git a/go/src/internal/syscall/unix/waitid_linux.go b/go/src/internal/syscall/unix/waitid_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..240a7f744ce21fabf2eda2c207beee754b973b8c --- /dev/null +++ b/go/src/internal/syscall/unix/waitid_linux.go @@ -0,0 +1,23 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unix + +import ( + "syscall" + "unsafe" +) + +const ( + P_PID = 1 + P_PIDFD = 3 +) + +func Waitid(idType int, id int, info *SiginfoChild, options int, rusage *syscall.Rusage) error { + _, _, errno := syscall.Syscall6(syscall.SYS_WAITID, uintptr(idType), uintptr(id), uintptr(unsafe.Pointer(info)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/go/src/internal/syscall/windows/at_windows.go b/go/src/internal/syscall/windows/at_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..81361c98e4e58388c7f48a93a2378fa4fd6ed218 --- /dev/null +++ b/go/src/internal/syscall/windows/at_windows.go @@ -0,0 +1,657 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package windows + +import ( + "internal/oserror" + "runtime" + "structs" + "syscall" + "unsafe" +) + +// Openat flags supported by syscall.Open. +const ( + O_DIRECTORY = 0x04000 // target must be a directory +) + +// Openat flags not supported by syscall.Open. +// +// These are invented values, use values in the 33-63 bit range +// to avoid overlap with flags and attributes supported by [syscall.Open]. +// +// When adding a new flag here, add an unexported version to +// the set of invented O_ values in syscall/types_windows.go +// to avoid overlap. +const ( + O_NOFOLLOW_ANY = 0x200000000 // disallow symlinks anywhere in the path + O_WRITE_ATTRS = 0x800000000 // FILE_WRITE_ATTRIBUTES, used by Chmod +) + +func Openat(dirfd syscall.Handle, name string, flag uint64, perm uint32) (_ syscall.Handle, e1 error) { + if len(name) == 0 { + return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND + } + + var access, options uint32 + // Map Win32 file flags to NT create options. + fileFlags := uint32(flag) & FileFlagsMask + if fileFlags&^ValidFileFlagsMask != 0 { + return syscall.InvalidHandle, oserror.ErrInvalid + } + if fileFlags&O_FILE_FLAG_OVERLAPPED == 0 { + options |= FILE_SYNCHRONOUS_IO_NONALERT + } + if fileFlags&O_FILE_FLAG_DELETE_ON_CLOSE != 0 { + access |= DELETE + } + setOptionFlag := func(ntFlag, win32Flag uint32) { + if fileFlags&win32Flag != 0 { + options |= ntFlag + } + } + setOptionFlag(FILE_NO_INTERMEDIATE_BUFFERING, O_FILE_FLAG_NO_BUFFERING) + setOptionFlag(FILE_WRITE_THROUGH, O_FILE_FLAG_WRITE_THROUGH) + setOptionFlag(FILE_SEQUENTIAL_ONLY, O_FILE_FLAG_SEQUENTIAL_SCAN) + setOptionFlag(FILE_RANDOM_ACCESS, O_FILE_FLAG_RANDOM_ACCESS) + setOptionFlag(FILE_OPEN_FOR_BACKUP_INTENT, O_FILE_FLAG_BACKUP_SEMANTICS) + setOptionFlag(FILE_SESSION_AWARE, O_FILE_FLAG_SESSION_AWARE) + setOptionFlag(FILE_DELETE_ON_CLOSE, O_FILE_FLAG_DELETE_ON_CLOSE) + setOptionFlag(FILE_OPEN_NO_RECALL, O_FILE_FLAG_OPEN_NO_RECALL) + setOptionFlag(FILE_OPEN_REPARSE_POINT, O_FILE_FLAG_OPEN_REPARSE_POINT) + + switch flag & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) { + case syscall.O_RDONLY: + // FILE_GENERIC_READ includes FILE_LIST_DIRECTORY. + access |= FILE_GENERIC_READ + case syscall.O_WRONLY: + access |= FILE_GENERIC_WRITE + options |= FILE_NON_DIRECTORY_FILE + case syscall.O_RDWR: + access |= FILE_GENERIC_READ | FILE_GENERIC_WRITE + options |= FILE_NON_DIRECTORY_FILE + default: + // Stat opens files without requesting read or write permissions, + // but we still need to request SYNCHRONIZE. + access |= SYNCHRONIZE + } + if flag&syscall.O_CREAT != 0 { + access |= FILE_GENERIC_WRITE + } + if fileFlags&O_FILE_FLAG_NO_BUFFERING != 0 { + // Disable buffering implies no implicit append access. + access &^= FILE_APPEND_DATA + } + if flag&syscall.O_APPEND != 0 { + access |= FILE_APPEND_DATA + // Remove FILE_WRITE_DATA access unless O_TRUNC is set, + // in which case we need it to truncate the file. + if flag&syscall.O_TRUNC == 0 { + access &^= FILE_WRITE_DATA + } + } + if flag&O_DIRECTORY != 0 { + options |= FILE_DIRECTORY_FILE + access |= FILE_LIST_DIRECTORY + } + if flag&syscall.O_SYNC != 0 { + options |= FILE_WRITE_THROUGH + } + if flag&O_WRITE_ATTRS != 0 { + access |= FILE_WRITE_ATTRIBUTES + } + // Allow File.Stat. + access |= STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | FILE_READ_EA + + objAttrs := &OBJECT_ATTRIBUTES{} + if flag&O_NOFOLLOW_ANY != 0 { + objAttrs.Attributes |= OBJ_DONT_REPARSE + } + if flag&syscall.O_CLOEXEC == 0 { + objAttrs.Attributes |= OBJ_INHERIT + } + if fileFlags&O_FILE_FLAG_POSIX_SEMANTICS == 0 { + objAttrs.Attributes |= OBJ_CASE_INSENSITIVE + } + if err := objAttrs.init(dirfd, name); err != nil { + return syscall.InvalidHandle, err + } + + // We don't use FILE_OVERWRITE/FILE_OVERWRITE_IF, because when opening + // a file with FILE_ATTRIBUTE_READONLY these will replace an existing + // file with a new, read-only one. + // + // Instead, we ftruncate the file after opening when O_TRUNC is set. + var disposition uint32 + switch { + case flag&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL): + disposition = FILE_CREATE + options |= FILE_OPEN_REPARSE_POINT // don't follow symlinks + case flag&syscall.O_CREAT == syscall.O_CREAT: + disposition = FILE_OPEN_IF + default: + disposition = FILE_OPEN + } + + fileAttrs := uint32(FILE_ATTRIBUTE_NORMAL) + if perm&syscall.S_IWRITE == 0 { + fileAttrs = FILE_ATTRIBUTE_READONLY + } + + var h syscall.Handle + err := NtCreateFile( + &h, + SYNCHRONIZE|access, + objAttrs, + &IO_STATUS_BLOCK{}, + nil, + fileAttrs, + FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, + disposition, + FILE_OPEN_FOR_BACKUP_INTENT|options, + nil, + 0, + ) + if err != nil { + return h, ntCreateFileError(err, flag) + } + + if flag&syscall.O_TRUNC != 0 { + err = syscall.Ftruncate(h, 0) + if err == ERROR_INVALID_PARAMETER { + // ERROR_INVALID_PARAMETER means truncation is not supported on this file handle. + // Unix's O_TRUNC specification says to ignore O_TRUNC on named pipes and terminal devices. + // We do the same here. + if t, err1 := syscall.GetFileType(h); err1 == nil && (t == syscall.FILE_TYPE_PIPE || t == syscall.FILE_TYPE_CHAR) { + err = nil + } + } + if err != nil { + syscall.CloseHandle(h) + return syscall.InvalidHandle, err + } + } + + return h, nil +} + +// ntCreateFileError maps error returns from NTCreateFile to user-visible errors. +func ntCreateFileError(err error, flag uint64) error { + s, ok := err.(NTStatus) + if !ok { + // Shouldn't really be possible, NtCreateFile always returns NTStatus. + return err + } + switch s { + case STATUS_REPARSE_POINT_ENCOUNTERED: + return syscall.ELOOP + case STATUS_NOT_A_DIRECTORY: + // ENOTDIR is the errno returned by open when O_DIRECTORY is specified + // and the target is not a directory. + // + // NtCreateFile can return STATUS_NOT_A_DIRECTORY under other circumstances, + // such as when opening "file/" where "file" is not a directory. + // (This might be Windows version dependent.) + // + // Only map STATUS_NOT_A_DIRECTORY to ENOTDIR when O_DIRECTORY is specified. + if flag&O_DIRECTORY != 0 { + return syscall.ENOTDIR + } + case STATUS_FILE_IS_A_DIRECTORY: + return syscall.EISDIR + case STATUS_OBJECT_NAME_COLLISION: + return syscall.EEXIST + } + return s.Errno() +} + +func Mkdirat(dirfd syscall.Handle, name string, mode uint32) error { + objAttrs := &OBJECT_ATTRIBUTES{} + if err := objAttrs.init(dirfd, name); err != nil { + return err + } + var h syscall.Handle + err := NtCreateFile( + &h, + FILE_GENERIC_READ, + objAttrs, + &IO_STATUS_BLOCK{}, + nil, + syscall.FILE_ATTRIBUTE_NORMAL, + syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, + FILE_CREATE, + FILE_DIRECTORY_FILE, + nil, + 0, + ) + if err != nil { + return ntCreateFileError(err, 0) + } + syscall.CloseHandle(h) + return nil +} + +func Deleteat(dirfd syscall.Handle, name string, options uint32) error { + if name == "." { + // NtOpenFile's documentation isn't explicit about what happens when deleting ".". + // Make this an error consistent with that of POSIX. + return syscall.EINVAL + } + objAttrs := &OBJECT_ATTRIBUTES{} + if err := objAttrs.init(dirfd, name); err != nil { + return err + } + var h syscall.Handle + err := NtOpenFile( + &h, + FILE_READ_ATTRIBUTES|DELETE, + objAttrs, + &IO_STATUS_BLOCK{}, + FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT|options, + ) + if err != nil { + if ntStatus, ok := err.(NTStatus); !ok || ntStatus != STATUS_ACCESS_DENIED { + return ntCreateFileError(err, 0) + } + + // Access denied, try opening with DELETE only. + // This may succeed if the file has restrictive permissions + // but the caller has delete child permission on the parent directory. + err = NtOpenFile( + &h, + DELETE, + objAttrs, + &IO_STATUS_BLOCK{}, + FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT|options, + ) + if err != nil { + return ntCreateFileError(err, 0) + } + } + defer syscall.CloseHandle(h) + + if TestDeleteatFallback { + return deleteatFallback(h) + } + + const FileDispositionInformationEx = 64 + + // First, attempt to delete the file using POSIX semantics + // (which permit a file to be deleted while it is still open). + // This matches the behavior of DeleteFileW. + // + // The following call uses features available on different Windows versions: + // - FILE_DISPOSITION_INFORMATION_EX: Windows 10, version 1607 (aka RS1) + // - FILE_DISPOSITION_POSIX_SEMANTICS: Windows 10, version 1607 (aka RS1) + // - FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE: Windows 10, version 1809 (aka RS5) + // + // Also, some file systems, like FAT32, don't support POSIX semantics. + err = NtSetInformationFile( + h, + &IO_STATUS_BLOCK{}, + unsafe.Pointer(&FILE_DISPOSITION_INFORMATION_EX{ + Flags: FILE_DISPOSITION_DELETE | + FILE_DISPOSITION_FORCE_IMAGE_SECTION_CHECK | + FILE_DISPOSITION_POSIX_SEMANTICS | + // This differs from DeleteFileW, but matches os.Remove's + // behavior on Unix platforms of permitting deletion of + // read-only files. + FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE, + }), + uint32(unsafe.Sizeof(FILE_DISPOSITION_INFORMATION_EX{})), + FileDispositionInformationEx, + ) + switch err { + case nil: + return nil + case STATUS_INVALID_INFO_CLASS, // the operating system doesn't support FileDispositionInformationEx + STATUS_INVALID_PARAMETER, // the operating system doesn't support one of the flags + STATUS_NOT_SUPPORTED: // the file system doesn't support FILE_DISPOSITION_INFORMATION_EX or one of the flags + return deleteatFallback(h) + default: + return err.(NTStatus).Errno() + } +} + +// TestDeleteatFallback should only be used for testing purposes. +// When set, [Deleteat] uses the fallback path unconditionally. +var TestDeleteatFallback bool + +// deleteatFallback is a deleteat implementation that strives +// for compatibility with older Windows versions and file systems +// over performance. +func deleteatFallback(h syscall.Handle) error { + var data syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(h, &data); err == nil && data.FileAttributes&syscall.FILE_ATTRIBUTE_READONLY != 0 { + // Remove read-only attribute. Reopen the file, as it was previously open without FILE_WRITE_ATTRIBUTES access + // in order to maximize compatibility in the happy path. + wh, err := ReOpenFile(h, + FILE_WRITE_ATTRIBUTES, + FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, + syscall.FILE_FLAG_OPEN_REPARSE_POINT|syscall.FILE_FLAG_BACKUP_SEMANTICS, + ) + if err != nil { + return err + } + err = SetFileInformationByHandle( + wh, + FileBasicInfo, + unsafe.Pointer(&FILE_BASIC_INFO{ + FileAttributes: data.FileAttributes &^ FILE_ATTRIBUTE_READONLY, + }), + uint32(unsafe.Sizeof(FILE_BASIC_INFO{})), + ) + syscall.CloseHandle(wh) + if err != nil { + return err + } + } + + return SetFileInformationByHandle( + h, + FileDispositionInfo, + unsafe.Pointer(&FILE_DISPOSITION_INFO{ + DeleteFile: true, + }), + uint32(unsafe.Sizeof(FILE_DISPOSITION_INFO{})), + ) +} + +func Renameat(olddirfd syscall.Handle, oldpath string, newdirfd syscall.Handle, newpath string) error { + objAttrs := &OBJECT_ATTRIBUTES{} + if err := objAttrs.init(olddirfd, oldpath); err != nil { + return err + } + var h syscall.Handle + err := NtOpenFile( + &h, + SYNCHRONIZE|DELETE, + objAttrs, + &IO_STATUS_BLOCK{}, + FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT|FILE_SYNCHRONOUS_IO_NONALERT, + ) + if err != nil { + return ntCreateFileError(err, 0) + } + defer syscall.CloseHandle(h) + + renameInfoEx := FILE_RENAME_INFORMATION_EX{ + Flags: FILE_RENAME_REPLACE_IF_EXISTS | + FILE_RENAME_POSIX_SEMANTICS, + RootDirectory: newdirfd, + } + p16, err := syscall.UTF16FromString(newpath) + if err != nil { + return err + } + if len(p16) > len(renameInfoEx.FileName) { + return syscall.EINVAL + } + copy(renameInfoEx.FileName[:], p16) + renameInfoEx.FileNameLength = uint32((len(p16) - 1) * 2) + + const ( + FileRenameInformation = 10 + FileRenameInformationEx = 65 + ) + err = NtSetInformationFile( + h, + &IO_STATUS_BLOCK{}, + unsafe.Pointer(&renameInfoEx), + uint32(unsafe.Sizeof(FILE_RENAME_INFORMATION_EX{})), + FileRenameInformationEx, + ) + if err == nil { + return nil + } + + // If the prior rename failed, the filesystem might not support + // POSIX semantics (for example, FAT), or might not have implemented + // FILE_RENAME_INFORMATION_EX. + // + // Try again. + renameInfo := FILE_RENAME_INFORMATION{ + ReplaceIfExists: true, + RootDirectory: newdirfd, + } + copy(renameInfo.FileName[:], p16) + renameInfo.FileNameLength = renameInfoEx.FileNameLength + + err = NtSetInformationFile( + h, + &IO_STATUS_BLOCK{}, + unsafe.Pointer(&renameInfo), + uint32(unsafe.Sizeof(FILE_RENAME_INFORMATION{})), + FileRenameInformation, + ) + if st, ok := err.(NTStatus); ok { + return st.Errno() + } + return err +} + +func Linkat(olddirfd syscall.Handle, oldpath string, newdirfd syscall.Handle, newpath string) error { + objAttrs := &OBJECT_ATTRIBUTES{} + if err := objAttrs.init(olddirfd, oldpath); err != nil { + return err + } + var h syscall.Handle + err := NtOpenFile( + &h, + SYNCHRONIZE|FILE_WRITE_ATTRIBUTES, + objAttrs, + &IO_STATUS_BLOCK{}, + FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT|FILE_SYNCHRONOUS_IO_NONALERT, + ) + if err != nil { + return ntCreateFileError(err, 0) + } + defer syscall.CloseHandle(h) + + linkInfo := FILE_LINK_INFORMATION{ + RootDirectory: newdirfd, + } + p16, err := syscall.UTF16FromString(newpath) + if err != nil { + return err + } + if len(p16) > len(linkInfo.FileName) { + return syscall.EINVAL + } + copy(linkInfo.FileName[:], p16) + linkInfo.FileNameLength = uint32((len(p16) - 1) * 2) + + const ( + FileLinkInformation = 11 + ) + err = NtSetInformationFile( + h, + &IO_STATUS_BLOCK{}, + unsafe.Pointer(&linkInfo), + uint32(unsafe.Sizeof(FILE_LINK_INFORMATION{})), + FileLinkInformation, + ) + if st, ok := err.(NTStatus); ok { + return st.Errno() + } + return err +} + +// SymlinkatFlags configure Symlinkat. +// +// Symbolic links have two properties: They may be directory or file links, +// and they may be absolute or relative. +// +// The Windows API defines flags describing these properties +// (SYMBOLIC_LINK_FLAG_DIRECTORY and SYMLINK_FLAG_RELATIVE), +// but the flags are passed to different system calls and +// do not have distinct values, so we define our own enumeration +// that permits expressing both. +type SymlinkatFlags uint + +const ( + SYMLINKAT_DIRECTORY = SymlinkatFlags(1 << iota) + SYMLINKAT_RELATIVE +) + +func Symlinkat(oldname string, newdirfd syscall.Handle, newname string, flags SymlinkatFlags) error { + // Temporarily acquire symlink-creating privileges if possible. + // This is the behavior of CreateSymbolicLinkW. + // + // (When passed the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag, + // CreateSymbolicLinkW ignores errors in acquiring privileges, as we do here.) + return withPrivilege("SeCreateSymbolicLinkPrivilege", func() error { + return symlinkat(oldname, newdirfd, newname, flags) + }) +} + +func symlinkat(oldname string, newdirfd syscall.Handle, newname string, flags SymlinkatFlags) error { + oldnameu16, err := syscall.UTF16FromString(oldname) + if err != nil { + return err + } + oldnameu16 = oldnameu16[:len(oldnameu16)-1] // trim off terminal NUL + + var options uint32 + if flags&SYMLINKAT_DIRECTORY != 0 { + options |= FILE_DIRECTORY_FILE + } else { + options |= FILE_NON_DIRECTORY_FILE + } + + objAttrs := &OBJECT_ATTRIBUTES{} + if err := objAttrs.init(newdirfd, newname); err != nil { + return err + } + var h syscall.Handle + err = NtCreateFile( + &h, + SYNCHRONIZE|FILE_WRITE_ATTRIBUTES|DELETE, + objAttrs, + &IO_STATUS_BLOCK{}, + nil, + syscall.FILE_ATTRIBUTE_NORMAL, + 0, + FILE_CREATE, + FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT|FILE_SYNCHRONOUS_IO_NONALERT|options, + nil, + 0, + ) + if err != nil { + return ntCreateFileError(err, 0) + } + defer syscall.CloseHandle(h) + + // https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_reparse_data_buffer + type reparseDataBufferT struct { + _ structs.HostLayout + + ReparseTag uint32 + ReparseDataLength uint16 + Reserved uint16 + + SubstituteNameOffset uint16 + SubstituteNameLength uint16 + PrintNameOffset uint16 + PrintNameLength uint16 + Flags uint32 + } + + const ( + headerSize = uint16(unsafe.Offsetof(reparseDataBufferT{}.SubstituteNameOffset)) + bufferSize = uint16(unsafe.Sizeof(reparseDataBufferT{})) + ) + + // Data buffer containing a SymbolicLinkReparseBuffer followed by the link target. + rdbbuf := make([]byte, bufferSize+uint16(2*len(oldnameu16))) + + rdb := (*reparseDataBufferT)(unsafe.Pointer(&rdbbuf[0])) + rdb.ReparseTag = syscall.IO_REPARSE_TAG_SYMLINK + rdb.ReparseDataLength = uint16(len(rdbbuf)) - uint16(headerSize) + rdb.SubstituteNameOffset = 0 + rdb.SubstituteNameLength = uint16(2 * len(oldnameu16)) + rdb.PrintNameOffset = 0 + rdb.PrintNameLength = rdb.SubstituteNameLength + if flags&SYMLINKAT_RELATIVE != 0 { + rdb.Flags = SYMLINK_FLAG_RELATIVE + } + + namebuf := rdbbuf[bufferSize:] + copy(namebuf, unsafe.String((*byte)(unsafe.Pointer(&oldnameu16[0])), 2*len(oldnameu16))) + + err = syscall.DeviceIoControl( + h, + FSCTL_SET_REPARSE_POINT, + &rdbbuf[0], + uint32(len(rdbbuf)), + nil, + 0, + nil, + nil) + if err != nil { + // Creating the symlink has failed, so try to remove the file. + const FileDispositionInformation = 13 + NtSetInformationFile( + h, + &IO_STATUS_BLOCK{}, + unsafe.Pointer(&FILE_DISPOSITION_INFORMATION{ + DeleteFile: true, + }), + uint32(unsafe.Sizeof(FILE_DISPOSITION_INFORMATION{})), + FileDispositionInformation, + ) + return err + } + + return nil +} + +// withPrivilege temporariliy acquires the named privilege and runs f. +// If the privilege cannot be acquired it runs f anyway, +// which should fail with an appropriate error. +func withPrivilege(privilege string, f func() error) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + err := ImpersonateSelf(SecurityImpersonation) + if err != nil { + return f() + } + defer RevertToSelf() + + curThread, err := GetCurrentThread() + if err != nil { + return f() + } + var token syscall.Token + err = OpenThreadToken(curThread, syscall.TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, false, &token) + if err != nil { + return f() + } + defer syscall.CloseHandle(syscall.Handle(token)) + + privStr, err := syscall.UTF16PtrFromString(privilege) + if err != nil { + return f() + } + var tokenPriv TOKEN_PRIVILEGES + err = LookupPrivilegeValue(nil, privStr, &tokenPriv.Privileges[0].Luid) + if err != nil { + return f() + } + + tokenPriv.PrivilegeCount = 1 + tokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED + err = AdjustTokenPrivileges(token, false, &tokenPriv, 0, nil, nil) + if err != nil { + return f() + } + + return f() +} diff --git a/go/src/internal/syscall/windows/at_windows_test.go b/go/src/internal/syscall/windows/at_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a0b8e15da65daab1c85edf6d7c0794b492f0b695 --- /dev/null +++ b/go/src/internal/syscall/windows/at_windows_test.go @@ -0,0 +1,167 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package windows_test + +import ( + "internal/syscall/windows" + "os" + "path/filepath" + "syscall" + "testing" + "unsafe" +) + +func TestOpen(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + file := filepath.Join(dir, "a") + f, err := os.Create(file) + if err != nil { + t.Fatal(err) + } + f.Close() + + tests := []struct { + path string + flag int + err error + }{ + {dir, syscall.O_RDONLY, nil}, + {dir, syscall.O_CREAT, nil}, + {dir, syscall.O_RDONLY | syscall.O_CREAT, nil}, + {file, syscall.O_APPEND | syscall.O_WRONLY | os.O_CREATE, nil}, + {file, syscall.O_APPEND | syscall.O_WRONLY | os.O_CREATE | os.O_TRUNC, nil}, + {dir, syscall.O_RDONLY | syscall.O_TRUNC, syscall.ERROR_ACCESS_DENIED}, + {dir, syscall.O_WRONLY | syscall.O_RDWR, nil}, // TODO: syscall.Open returns EISDIR here, we should reconcile this + {dir, syscall.O_WRONLY, syscall.EISDIR}, + {dir, syscall.O_RDWR, syscall.EISDIR}, + } + for i, tt := range tests { + dir := filepath.Dir(tt.path) + dirfd, err := syscall.Open(dir, syscall.O_RDONLY, 0) + if err != nil { + t.Error(err) + continue + } + base := filepath.Base(tt.path) + h, err := windows.Openat(dirfd, base, uint64(tt.flag), 0o660) + syscall.CloseHandle(dirfd) + if err == nil { + syscall.CloseHandle(h) + } + if err != tt.err { + t.Errorf("%d: Open got %q, want %q", i, err, tt.err) + } + } +} + +func TestDeleteAt(t *testing.T) { + testCases := []struct { + name string + modifier func(t *testing.T, path string) + }{ + {"DeleteAt removes normal file", func(t *testing.T, name string) {}}, + {"DeleteAt removes file with no read permission", makeFileNotReadable}, + {"DeleteAt removes readonly file", makeFileReadonly}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + file := filepath.Join(dir, "a") + f, err := os.Create(file) + if err != nil { + t.Fatal(err) + } + f.Close() + + // Remove all permissions from the file. + // Do not use os.Chmod it sets only readonly attribute on Windows. + tc.modifier(t, file) + + // delete file using DeleteAt + dirfd, err := syscall.Open(dir, syscall.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + base := filepath.Base(file) + err = windows.Deleteat(dirfd, base, 0) + syscall.CloseHandle(dirfd) + if err != nil { + t.Fatalf("Deleteat failed: %v", err) + } + + // Verify the file has been deleted. + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatalf("file still exists after DeleteAt") + } + }) + } +} + +func makeFileReadonly(t *testing.T, name string) { + if err := os.Chmod(name, 0); err != nil { + t.Fatal(err) + } +} + +func makeFileNotReadable(t *testing.T, name string) { + creatorOwnerSID, err := syscall.StringToSid("S-1-3-0") + if err != nil { + t.Fatal(err) + } + creatorGroupSID, err := syscall.StringToSid("S-1-3-1") + if err != nil { + t.Fatal(err) + } + everyoneSID, err := syscall.StringToSid("S-1-1-0") + if err != nil { + t.Fatal(err) + } + + entryForSid := func(sid *syscall.SID) windows.EXPLICIT_ACCESS { + return windows.EXPLICIT_ACCESS{ + AccessPermissions: 0, + AccessMode: windows.GRANT_ACCESS, + Inheritance: windows.SUB_CONTAINERS_AND_OBJECTS_INHERIT, + Trustee: windows.TRUSTEE{ + TrusteeForm: windows.TRUSTEE_IS_SID, + Name: (uintptr)(unsafe.Pointer(sid)), + }, + } + } + + entries := []windows.EXPLICIT_ACCESS{ + entryForSid(creatorOwnerSID), + entryForSid(creatorGroupSID), + entryForSid(everyoneSID), + } + + var oldAcl, newAcl *windows.ACL + if err := windows.SetEntriesInAcl( + uint32(len(entries)), + &entries[0], + oldAcl, + &newAcl, + ); err != nil { + t.Fatal(err) + } + + defer syscall.LocalFree((syscall.Handle)(unsafe.Pointer(newAcl))) + if err := windows.SetNamedSecurityInfo( + name, + windows.SE_FILE_OBJECT, + windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, + nil, + nil, + newAcl, + nil, + ); err != nil { + t.Fatal(err) + } +} diff --git a/go/src/internal/syscall/windows/exec_windows_test.go b/go/src/internal/syscall/windows/exec_windows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d10d8c269c5871c3128635c4d23d10ab0a5f43df --- /dev/null +++ b/go/src/internal/syscall/windows/exec_windows_test.go @@ -0,0 +1,140 @@ +// 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 windows + +package windows_test + +import ( + "fmt" + "internal/syscall/windows" + "internal/testenv" + "os" + "os/exec" + "syscall" + "testing" + "unsafe" +) + +func TestRunAtLowIntegrity(t *testing.T) { + if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { + wil, err := getProcessIntegrityLevel() + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) + os.Exit(9) + return + } + fmt.Printf("%s", wil) + os.Exit(0) + return + } + + cmd := exec.Command(testenv.Executable(t), "-test.run=^TestRunAtLowIntegrity$", "--") + cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} + + token, err := getIntegrityLevelToken(sidWilLow) + if err != nil { + t.Fatal(err) + } + defer token.Close() + + cmd.SysProcAttr = &syscall.SysProcAttr{ + Token: token, + } + + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatal(err) + } + + if string(out) != sidWilLow { + t.Fatalf("Child process did not run as low integrity level: %s", string(out)) + } +} + +const ( + sidWilLow = `S-1-16-4096` +) + +func getProcessIntegrityLevel() (string, error) { + procToken, err := syscall.OpenCurrentProcessToken() + if err != nil { + return "", err + } + defer procToken.Close() + + p, err := tokenGetInfo(procToken, syscall.TokenIntegrityLevel, 64) + if err != nil { + return "", err + } + + tml := (*windows.TOKEN_MANDATORY_LABEL)(p) + + sid := (*syscall.SID)(unsafe.Pointer(tml.Label.Sid)) + + return sid.String() +} + +func tokenGetInfo(t syscall.Token, class uint32, initSize int) (unsafe.Pointer, error) { + n := uint32(initSize) + for { + b := make([]byte, n) + e := syscall.GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) + if e == nil { + return unsafe.Pointer(&b[0]), nil + } + if e != syscall.ERROR_INSUFFICIENT_BUFFER { + return nil, e + } + if n <= uint32(len(b)) { + return nil, e + } + } +} + +func getIntegrityLevelToken(wns string) (syscall.Token, error) { + var procToken, token syscall.Token + + proc, err := syscall.GetCurrentProcess() + if err != nil { + return 0, err + } + defer syscall.CloseHandle(proc) + + err = syscall.OpenProcessToken(proc, + syscall.TOKEN_DUPLICATE| + syscall.TOKEN_ADJUST_DEFAULT| + syscall.TOKEN_QUERY| + syscall.TOKEN_ASSIGN_PRIMARY, + &procToken) + if err != nil { + return 0, err + } + defer procToken.Close() + + sid, err := syscall.StringToSid(wns) + if err != nil { + return 0, err + } + + tml := &windows.TOKEN_MANDATORY_LABEL{} + tml.Label.Attributes = windows.SE_GROUP_INTEGRITY + tml.Label.Sid = sid + + err = windows.DuplicateTokenEx(procToken, 0, nil, windows.SecurityImpersonation, + windows.TokenPrimary, &token) + if err != nil { + return 0, err + } + + err = windows.SetTokenInformation(token, + syscall.TokenIntegrityLevel, + unsafe.Pointer(tml), + tml.Size()) + if err != nil { + token.Close() + return 0, err + } + return token, nil +} diff --git a/go/src/internal/syscall/windows/mksyscall.go b/go/src/internal/syscall/windows/mksyscall.go new file mode 100644 index 0000000000000000000000000000000000000000..f97ab526f8150c8aa3e58357e4fca68e0efe2b1c --- /dev/null +++ b/go/src/internal/syscall/windows/mksyscall.go @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build generate + +package windows + +//go:generate go run ../../../syscall/mksyscall_windows.go -output zsyscall_windows.go syscall_windows.go security_windows.go psapi_windows.go symlink_windows.go version_windows.go diff --git a/go/src/internal/syscall/windows/net_windows.go b/go/src/internal/syscall/windows/net_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..023ddaaa8c1af683a62f24dfb6d96593d9af2906 --- /dev/null +++ b/go/src/internal/syscall/windows/net_windows.go @@ -0,0 +1,30 @@ +// 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 windows + +import ( + "syscall" + _ "unsafe" +) + +//go:linkname WSASendtoInet4 syscall.wsaSendtoInet4 +//go:noescape +func WSASendtoInet4(s syscall.Handle, bufs *syscall.WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *syscall.SockaddrInet4, overlapped *syscall.Overlapped, croutine *byte) (err error) + +//go:linkname WSASendtoInet6 syscall.wsaSendtoInet6 +//go:noescape +func WSASendtoInet6(s syscall.Handle, bufs *syscall.WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *syscall.SockaddrInet6, overlapped *syscall.Overlapped, croutine *byte) (err error) + +const ( + SO_TYPE = 0x1008 + SIO_TCP_INITIAL_RTO = syscall.IOC_IN | syscall.IOC_VENDOR | 17 + TCP_INITIAL_RTO_UNSPECIFIED_RTT = ^uint16(0) + TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS = ^uint8(1) +) + +type TCP_INITIAL_RTO_PARAMETERS struct { + Rtt uint16 + MaxSynRetransmissions uint8 +} diff --git a/go/src/internal/syscall/windows/nonblocking_windows.go b/go/src/internal/syscall/windows/nonblocking_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..1565e87e2658f75b6dec0a209a26bfbecb973f1e --- /dev/null +++ b/go/src/internal/syscall/windows/nonblocking_windows.go @@ -0,0 +1,21 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package windows + +import ( + "syscall" + "unsafe" +) + +// IsNonblock returns whether the file descriptor fd is opened +// in non-blocking mode, that is, the [windows.O_FILE_FLAG_OVERLAPPED] flag +// was set when the file was opened. +func IsNonblock(fd syscall.Handle) (nonblocking bool, err error) { + var info FILE_MODE_INFORMATION + if err := NtQueryInformationFile(syscall.Handle(fd), &IO_STATUS_BLOCK{}, unsafe.Pointer(&info), uint32(unsafe.Sizeof(info)), FileModeInformation); err != nil { + return false, err + } + return info.Mode&(FILE_SYNCHRONOUS_IO_ALERT|FILE_SYNCHRONOUS_IO_NONALERT) == 0, nil +} diff --git a/go/src/internal/syscall/windows/psapi_windows.go b/go/src/internal/syscall/windows/psapi_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..b138e658a930bdd859cc089f5bf7c524ae80aba8 --- /dev/null +++ b/go/src/internal/syscall/windows/psapi_windows.go @@ -0,0 +1,20 @@ +// 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 windows + +type PROCESS_MEMORY_COUNTERS struct { + CB uint32 + PageFaultCount uint32 + PeakWorkingSetSize uintptr + WorkingSetSize uintptr + QuotaPeakPagedPoolUsage uintptr + QuotaPagedPoolUsage uintptr + QuotaPeakNonPagedPoolUsage uintptr + QuotaNonPagedPoolUsage uintptr + PagefileUsage uintptr + PeakPagefileUsage uintptr +} + +//sys GetProcessMemoryInfo(handle syscall.Handle, memCounters *PROCESS_MEMORY_COUNTERS, cb uint32) (err error) = psapi.GetProcessMemoryInfo diff --git a/go/src/internal/syscall/windows/reparse_windows.go b/go/src/internal/syscall/windows/reparse_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..241dd523c54110c7107ba05df36135c1a46b9a2f --- /dev/null +++ b/go/src/internal/syscall/windows/reparse_windows.go @@ -0,0 +1,94 @@ +// 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 windows + +import ( + "syscall" + "unsafe" +) + +// Reparse tag values are taken from +// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c8e77b37-3909-4fe6-a4ea-2b9d423b1ee4 +const ( + FSCTL_SET_REPARSE_POINT = 0x000900A4 + IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 + IO_REPARSE_TAG_DEDUP = 0x80000013 + IO_REPARSE_TAG_AF_UNIX = 0x80000023 + + SYMLINK_FLAG_RELATIVE = 1 +) + +// These structures are described +// in https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/ca069dad-ed16-42aa-b057-b6b207f447cc +// and https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/b41f1cbf-10df-4a47-98d4-1c52a833d913. + +type REPARSE_DATA_BUFFER struct { + ReparseTag uint32 + ReparseDataLength uint16 + Reserved uint16 + DUMMYUNIONNAME byte +} + +// REPARSE_DATA_BUFFER_HEADER is a common part of REPARSE_DATA_BUFFER structure. +type REPARSE_DATA_BUFFER_HEADER struct { + ReparseTag uint32 + // The size, in bytes, of the reparse data that follows + // the common portion of the REPARSE_DATA_BUFFER element. + // This value is the length of the data starting at the + // SubstituteNameOffset field. + ReparseDataLength uint16 + Reserved uint16 +} + +type SymbolicLinkReparseBuffer struct { + // The integer that contains the offset, in bytes, + // of the substitute name string in the PathBuffer array, + // computed as an offset from byte 0 of PathBuffer. Note that + // this offset must be divided by 2 to get the array index. + SubstituteNameOffset uint16 + // The integer that contains the length, in bytes, of the + // substitute name string. If this string is null-terminated, + // SubstituteNameLength does not include the Unicode null character. + SubstituteNameLength uint16 + // PrintNameOffset is similar to SubstituteNameOffset. + PrintNameOffset uint16 + // PrintNameLength is similar to SubstituteNameLength. + PrintNameLength uint16 + // Flags specifies whether the substitute name is a full path name or + // a path name relative to the directory containing the symbolic link. + Flags uint32 + PathBuffer [1]uint16 +} + +// Path returns path stored in rb. +func (rb *SymbolicLinkReparseBuffer) Path() string { + n1 := rb.SubstituteNameOffset / 2 + n2 := (rb.SubstituteNameOffset + rb.SubstituteNameLength) / 2 + return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(&rb.PathBuffer[0]))[n1:n2:n2]) +} + +type MountPointReparseBuffer struct { + // The integer that contains the offset, in bytes, + // of the substitute name string in the PathBuffer array, + // computed as an offset from byte 0 of PathBuffer. Note that + // this offset must be divided by 2 to get the array index. + SubstituteNameOffset uint16 + // The integer that contains the length, in bytes, of the + // substitute name string. If this string is null-terminated, + // SubstituteNameLength does not include the Unicode null character. + SubstituteNameLength uint16 + // PrintNameOffset is similar to SubstituteNameOffset. + PrintNameOffset uint16 + // PrintNameLength is similar to SubstituteNameLength. + PrintNameLength uint16 + PathBuffer [1]uint16 +} + +// Path returns path stored in rb. +func (rb *MountPointReparseBuffer) Path() string { + n1 := rb.SubstituteNameOffset / 2 + n2 := (rb.SubstituteNameOffset + rb.SubstituteNameLength) / 2 + return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(&rb.PathBuffer[0]))[n1:n2:n2]) +} diff --git a/go/src/internal/syscall/windows/security_windows.go b/go/src/internal/syscall/windows/security_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..f0ab52ac819baf74d29698ff76671c34d648f754 --- /dev/null +++ b/go/src/internal/syscall/windows/security_windows.go @@ -0,0 +1,264 @@ +// 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 windows + +import ( + "runtime" + "syscall" + "unsafe" +) + +const ( + SecurityAnonymous = 0 + SecurityIdentification = 1 + SecurityImpersonation = 2 + SecurityDelegation = 3 +) + +//sys ImpersonateSelf(impersonationlevel uint32) (err error) = advapi32.ImpersonateSelf +//sys RevertToSelf() (err error) = advapi32.RevertToSelf +//sys ImpersonateLoggedOnUser(token syscall.Token) (err error) = advapi32.ImpersonateLoggedOnUser +//sys LogonUser(username *uint16, domain *uint16, password *uint16, logonType uint32, logonProvider uint32, token *syscall.Token) (err error) = advapi32.LogonUserW + +const ( + TOKEN_ADJUST_PRIVILEGES = 0x0020 + SE_PRIVILEGE_ENABLED = 0x00000002 +) + +type LUID struct { + LowPart uint32 + HighPart int32 +} + +type LUID_AND_ATTRIBUTES struct { + Luid LUID + Attributes uint32 +} + +type TOKEN_PRIVILEGES struct { + PrivilegeCount uint32 + Privileges [1]LUID_AND_ATTRIBUTES +} + +//sys OpenThreadToken(h syscall.Handle, access uint32, openasself bool, token *syscall.Token) (err error) = advapi32.OpenThreadToken +//sys LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) = advapi32.LookupPrivilegeValueW +//sys adjustTokenPrivileges(token syscall.Token, disableAllPrivileges bool, newstate *TOKEN_PRIVILEGES, buflen uint32, prevstate *TOKEN_PRIVILEGES, returnlen *uint32) (ret uint32, err error) [true] = advapi32.AdjustTokenPrivileges + +func AdjustTokenPrivileges(token syscall.Token, disableAllPrivileges bool, newstate *TOKEN_PRIVILEGES, buflen uint32, prevstate *TOKEN_PRIVILEGES, returnlen *uint32) error { + ret, err := adjustTokenPrivileges(token, disableAllPrivileges, newstate, buflen, prevstate, returnlen) + if ret == 0 { + // AdjustTokenPrivileges call failed + return err + } + // AdjustTokenPrivileges call succeeded + if err == syscall.EINVAL { + // GetLastError returned ERROR_SUCCESS + return nil + } + return err +} + +//sys DuplicateTokenEx(hExistingToken syscall.Token, dwDesiredAccess uint32, lpTokenAttributes *syscall.SecurityAttributes, impersonationLevel uint32, tokenType TokenType, phNewToken *syscall.Token) (err error) = advapi32.DuplicateTokenEx +//sys SetTokenInformation(tokenHandle syscall.Token, tokenInformationClass uint32, tokenInformation unsafe.Pointer, tokenInformationLength uint32) (err error) = advapi32.SetTokenInformation + +type SID_AND_ATTRIBUTES struct { + Sid *syscall.SID + Attributes uint32 +} + +type TOKEN_MANDATORY_LABEL struct { + Label SID_AND_ATTRIBUTES +} + +func (tml *TOKEN_MANDATORY_LABEL) Size() uint32 { + return uint32(unsafe.Sizeof(TOKEN_MANDATORY_LABEL{})) + syscall.GetLengthSid(tml.Label.Sid) +} + +const SE_GROUP_INTEGRITY = 0x00000020 + +type TokenType uint32 + +const ( + TokenPrimary TokenType = 1 + TokenImpersonation TokenType = 2 +) + +//sys GetProfilesDirectory(dir *uint16, dirLen *uint32) (err error) = userenv.GetProfilesDirectoryW + +const ( + LG_INCLUDE_INDIRECT = 0x1 + MAX_PREFERRED_LENGTH = 0xFFFFFFFF +) + +type LocalGroupUserInfo0 struct { + Name *uint16 +} + +const ( + NERR_UserNotFound syscall.Errno = 2221 + NERR_UserExists syscall.Errno = 2224 +) + +const ( + USER_PRIV_USER = 1 +) + +type UserInfo1 struct { + Name *uint16 + Password *uint16 + PasswordAge uint32 + Priv uint32 + HomeDir *uint16 + Comment *uint16 + Flags uint32 + ScriptPath *uint16 +} + +type UserInfo4 struct { + Name *uint16 + Password *uint16 + PasswordAge uint32 + Priv uint32 + HomeDir *uint16 + Comment *uint16 + Flags uint32 + ScriptPath *uint16 + AuthFlags uint32 + FullName *uint16 + UsrComment *uint16 + Parms *uint16 + Workstations *uint16 + LastLogon uint32 + LastLogoff uint32 + AcctExpires uint32 + MaxStorage uint32 + UnitsPerWeek uint32 + LogonHours *byte + BadPwCount uint32 + NumLogons uint32 + LogonServer *uint16 + CountryCode uint32 + CodePage uint32 + UserSid *syscall.SID + PrimaryGroupID uint32 + Profile *uint16 + HomeDirDrive *uint16 + PasswordExpired uint32 +} + +//sys NetUserAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint32) (neterr error) = netapi32.NetUserAdd +//sys NetUserDel(serverName *uint16, userName *uint16) (neterr error) = netapi32.NetUserDel +//sys NetUserGetLocalGroups(serverName *uint16, userName *uint16, level uint32, flags uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32) (neterr error) = netapi32.NetUserGetLocalGroups + +// GetSystemDirectory retrieves the path to current location of the system +// directory, which is typically, though not always, `C:\Windows\System32`. +// +//go:linkname GetSystemDirectory +func GetSystemDirectory() string // Implemented in runtime package. + +// GetUserName retrieves the user name of the current thread +// in the specified format. +func GetUserName(format uint32) (string, error) { + n := uint32(50) + for { + b := make([]uint16, n) + e := syscall.GetUserNameEx(format, &b[0], &n) + if e == nil { + return syscall.UTF16ToString(b[:n]), nil + } + if e != syscall.ERROR_MORE_DATA { + return "", e + } + if n <= uint32(len(b)) { + return "", e + } + } +} + +// getTokenInfo retrieves a specified type of information about an access token. +func getTokenInfo(t syscall.Token, class uint32, initSize int) (unsafe.Pointer, error) { + n := uint32(initSize) + for { + b := make([]byte, n) + e := syscall.GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) + if e == nil { + return unsafe.Pointer(&b[0]), nil + } + if e != syscall.ERROR_INSUFFICIENT_BUFFER { + return nil, e + } + if n <= uint32(len(b)) { + return nil, e + } + } +} + +type TOKEN_GROUPS struct { + GroupCount uint32 + Groups [1]SID_AND_ATTRIBUTES +} + +func (g *TOKEN_GROUPS) AllGroups() []SID_AND_ATTRIBUTES { + return (*[(1 << 28) - 1]SID_AND_ATTRIBUTES)(unsafe.Pointer(&g.Groups[0]))[:g.GroupCount:g.GroupCount] +} + +func GetTokenGroups(t syscall.Token) (*TOKEN_GROUPS, error) { + i, e := getTokenInfo(t, syscall.TokenGroups, 50) + if e != nil { + return nil, e + } + return (*TOKEN_GROUPS)(i), nil +} + +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid_identifier_authority +type SID_IDENTIFIER_AUTHORITY struct { + Value [6]byte +} + +const ( + SID_REVISION = 1 + // https://learn.microsoft.com/en-us/windows/win32/services/localsystem-account + SECURITY_LOCAL_SYSTEM_RID = 18 + // https://learn.microsoft.com/en-us/windows/win32/services/localservice-account + SECURITY_LOCAL_SERVICE_RID = 19 + // https://learn.microsoft.com/en-us/windows/win32/services/networkservice-account + SECURITY_NETWORK_SERVICE_RID = 20 +) + +var SECURITY_NT_AUTHORITY = SID_IDENTIFIER_AUTHORITY{ + Value: [6]byte{0, 0, 0, 0, 0, 5}, +} + +//sys IsValidSid(sid *syscall.SID) (valid bool) = advapi32.IsValidSid +//sys getSidIdentifierAuthority(sid *syscall.SID) (idauth uintptr) = advapi32.GetSidIdentifierAuthority +//sys getSidSubAuthority(sid *syscall.SID, subAuthorityIdx uint32) (subAuth uintptr) = advapi32.GetSidSubAuthority +//sys getSidSubAuthorityCount(sid *syscall.SID) (count uintptr) = advapi32.GetSidSubAuthorityCount + +// The following GetSid* functions are marked as //go:nocheckptr because checkptr +// instrumentation can't see that the pointer returned by the syscall is pointing +// into the sid's memory, which is normally allocated on the Go heap. Therefore, +// the checkptr instrumentation would incorrectly flag the pointer dereference +// as pointing to an invalid allocation. +// Also, use runtime.KeepAlive to ensure that the sid is not garbage collected +// before the GetSid* functions return, as the Go GC is not aware that the +// pointers returned by the syscall are pointing into the sid's memory. + +//go:nocheckptr +func GetSidIdentifierAuthority(sid *syscall.SID) SID_IDENTIFIER_AUTHORITY { + defer runtime.KeepAlive(sid) + return *(*SID_IDENTIFIER_AUTHORITY)(unsafe.Pointer(getSidIdentifierAuthority(sid))) +} + +//go:nocheckptr +func GetSidSubAuthority(sid *syscall.SID, subAuthorityIdx uint32) uint32 { + defer runtime.KeepAlive(sid) + return *(*uint32)(unsafe.Pointer(getSidSubAuthority(sid, subAuthorityIdx))) +} + +//go:nocheckptr +func GetSidSubAuthorityCount(sid *syscall.SID) uint8 { + defer runtime.KeepAlive(sid) + return *(*uint8)(unsafe.Pointer(getSidSubAuthorityCount(sid))) +} diff --git a/go/src/internal/sysinfo/cpuinfo_bsd.go b/go/src/internal/sysinfo/cpuinfo_bsd.go new file mode 100644 index 0000000000000000000000000000000000000000..4396a6352ac0aed57021e754270730e993d28cac --- /dev/null +++ b/go/src/internal/sysinfo/cpuinfo_bsd.go @@ -0,0 +1,14 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin || freebsd || netbsd || openbsd + +package sysinfo + +import "syscall" + +func osCPUInfoName() string { + cpu, _ := syscall.Sysctl("machdep.cpu.brand_string") + return cpu +} diff --git a/go/src/internal/sysinfo/cpuinfo_linux.go b/go/src/internal/sysinfo/cpuinfo_linux.go new file mode 100644 index 0000000000000000000000000000000000000000..ae92c51afa10e4ea80730107e687db3bf8856676 --- /dev/null +++ b/go/src/internal/sysinfo/cpuinfo_linux.go @@ -0,0 +1,75 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sysinfo + +import ( + "bufio" + "bytes" + "io" + "os" + "strings" +) + +func readLinuxProcCPUInfo(buf []byte) error { + f, err := os.Open("/proc/cpuinfo") + if err != nil { + return err + } + defer f.Close() + + _, err = io.ReadFull(f, buf) + if err != nil && err != io.ErrUnexpectedEOF { + return err + } + + return nil +} + +func osCPUInfoName() string { + modelName := "" + cpuMHz := "" + + // The 512-byte buffer is enough to hold the contents of CPU0 + buf := make([]byte, 512) + err := readLinuxProcCPUInfo(buf) + if err != nil { + return "" + } + + scanner := bufio.NewScanner(bytes.NewReader(buf)) + for scanner.Scan() { + key, value, found := strings.Cut(scanner.Text(), ": ") + if !found { + continue + } + switch strings.TrimSpace(key) { + case "Model Name", "model name": + modelName = value + case "CPU MHz", "cpu MHz": + cpuMHz = value + } + } + + if modelName == "" { + return "" + } + + if cpuMHz == "" { + return modelName + } + + // The modelName field already contains the frequency information, + // so the cpuMHz field information is not needed. + // modelName filed example: + // Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz + f := [...]string{"GHz", "MHz"} + for _, v := range f { + if strings.Contains(modelName, v) { + return modelName + } + } + + return modelName + " @ " + cpuMHz + "MHz" +} diff --git a/go/src/internal/sysinfo/cpuinfo_stub.go b/go/src/internal/sysinfo/cpuinfo_stub.go new file mode 100644 index 0000000000000000000000000000000000000000..2ac7ffafe4bbd7b0b14d5456160be8cd65a58a20 --- /dev/null +++ b/go/src/internal/sysinfo/cpuinfo_stub.go @@ -0,0 +1,11 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !(darwin || freebsd || linux || netbsd || openbsd) + +package sysinfo + +func osCPUInfoName() string { + return "" +} diff --git a/go/src/internal/sysinfo/export_test.go b/go/src/internal/sysinfo/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..809a68379b36b38460dfb976b32fadca4d852f1d --- /dev/null +++ b/go/src/internal/sysinfo/export_test.go @@ -0,0 +1,7 @@ +// 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 sysinfo + +var XosCPUInfoName = osCPUInfoName diff --git a/go/src/internal/sysinfo/sysinfo.go b/go/src/internal/sysinfo/sysinfo.go new file mode 100644 index 0000000000000000000000000000000000000000..7debaa1e956d06fd6c17dffc7201608567789a40 --- /dev/null +++ b/go/src/internal/sysinfo/sysinfo.go @@ -0,0 +1,24 @@ +// 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 sysinfo implements high level hardware information gathering +// that can be used for debugging or information purposes. +package sysinfo + +import ( + "internal/cpu" + "sync" +) + +var CPUName = sync.OnceValue(func() string { + if name := cpu.Name(); name != "" { + return name + } + + if name := osCPUInfoName(); name != "" { + return name + } + + return "" +}) diff --git a/go/src/internal/sysinfo/sysinfo_test.go b/go/src/internal/sysinfo/sysinfo_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fd9d1662612499f6282948c70c5bde2fd65b4a6b --- /dev/null +++ b/go/src/internal/sysinfo/sysinfo_test.go @@ -0,0 +1,15 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sysinfo_test + +import ( + . "internal/sysinfo" + "testing" +) + +func TestCPUName(t *testing.T) { + t.Logf("CPUName: %s", CPUName()) + t.Logf("osCPUInfoName: %s", XosCPUInfoName()) +} diff --git a/go/src/internal/syslist/syslist.go b/go/src/internal/syslist/syslist.go new file mode 100644 index 0000000000000000000000000000000000000000..2349b6ea64a6d3ae1cc8b8a92820c4a78d38ba1e --- /dev/null +++ b/go/src/internal/syslist/syslist.go @@ -0,0 +1,83 @@ +// 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 syslist stores tables of OS and ARCH names that are +// (or at one point were) acceptable build targets. + +package syslist + +// Note that this file is read by internal/goarch/gengoarch.go and by +// internal/goos/gengoos.go. If you change this file, look at those +// files as well. + +// KnownOS is the list of past, present, and future known GOOS values. +// Do not remove from this list, as it is used for filename matching. +// If you add an entry to this list, look at UnixOS, below. +var KnownOS = map[string]bool{ + "aix": true, + "android": true, + "darwin": true, + "dragonfly": true, + "freebsd": true, + "hurd": true, + "illumos": true, + "ios": true, + "js": true, + "linux": true, + "nacl": true, + "netbsd": true, + "openbsd": true, + "plan9": true, + "solaris": true, + "wasip1": true, + "windows": true, + "zos": true, +} + +// UnixOS is the set of GOOS values matched by the "unix" build tag. +// This is not used for filename matching. +// This list also appears in cmd/dist/build.go. +var UnixOS = map[string]bool{ + "aix": true, + "android": true, + "darwin": true, + "dragonfly": true, + "freebsd": true, + "hurd": true, + "illumos": true, + "ios": true, + "linux": true, + "netbsd": true, + "openbsd": true, + "solaris": true, +} + +// KnownArch is the list of past, present, and future known GOARCH values. +// Do not remove from this list, as it is used for filename matching. +var KnownArch = map[string]bool{ + "386": true, + "amd64": true, + "amd64p32": true, + "arm": true, + "armbe": true, + "arm64": true, + "arm64be": true, + "loong64": true, + "mips": true, + "mipsle": true, + "mips64": true, + "mips64le": true, + "mips64p32": true, + "mips64p32le": true, + "ppc": true, + "ppc64": true, + "ppc64le": true, + "riscv": true, + "riscv64": true, + "s390": true, + "s390x": true, + "sparc": true, + "sparc64": true, + "wasm": true, +} diff --git a/go/src/internal/testenv/exec.go b/go/src/internal/testenv/exec.go new file mode 100644 index 0000000000000000000000000000000000000000..7b251b602237f3e9d8145d58cce432fd2e5a543e --- /dev/null +++ b/go/src/internal/testenv/exec.go @@ -0,0 +1,242 @@ +// 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 testenv + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// MustHaveExec checks that the current system can start new processes +// using os.StartProcess or (more commonly) exec.Command. +// If not, MustHaveExec calls t.Skip with an explanation. +// +// On some platforms MustHaveExec checks for exec support by re-executing the +// current executable, which must be a binary built by 'go test'. +// We intentionally do not provide a HasExec function because of the risk of +// inappropriate recursion in TestMain functions. +// +// To check for exec support outside of a test, just try to exec the command. +// If exec is not supported, testenv.SyscallIsNotSupported will return true +// for the resulting error. +func MustHaveExec(t testing.TB) { + if err := tryExec(); err != nil { + msg := fmt.Sprintf("cannot exec subprocess on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) + if t == nil { + panic(msg) + } + t.Helper() + t.Skip("skipping test:", msg) + } +} + +var tryExec = sync.OnceValue(func() error { + switch runtime.GOOS { + case "wasip1", "js", "ios": + default: + // Assume that exec always works on non-mobile platforms and Android. + return nil + } + + // ios has an exec syscall but on real iOS devices it might return a + // permission error. In an emulated environment (such as a Corellium host) + // it might succeed, so if we need to exec we'll just have to try it and + // find out. + // + // As of 2023-04-19 wasip1 and js don't have exec syscalls at all, but we + // may as well use the same path so that this branch can be tested without + // an ios environment. + + if !testing.Testing() { + // This isn't a standard 'go test' binary, so we don't know how to + // self-exec in a way that should succeed without side effects. + // Just forget it. + return errors.New("can't probe for exec support with a non-test executable") + } + + // We know that this is a test executable. We should be able to run it with a + // no-op flag to check for overall exec support. + exe, err := exePath() + if err != nil { + return fmt.Errorf("can't probe for exec support: %w", err) + } + cmd := exec.Command(exe, "-test.list=^$") + cmd.Env = origEnv + return cmd.Run() +}) + +// Executable is a wrapper around [MustHaveExec] and [os.Executable]. +// It returns the path name for the executable that started the current process, +// or skips the test if the current system can't start new processes, +// or fails the test if the path can not be obtained. +func Executable(t testing.TB) string { + MustHaveExec(t) + + exe, err := exePath() + if err != nil { + msg := fmt.Sprintf("os.Executable error: %v", err) + if t == nil { + panic(msg) + } + t.Fatal(msg) + } + return exe +} + +var exePath = sync.OnceValues(func() (string, error) { + return os.Executable() +}) + +var execPaths sync.Map // path -> error + +// MustHaveExecPath checks that the current system can start the named executable +// using os.StartProcess or (more commonly) exec.Command. +// If not, MustHaveExecPath calls t.Skip with an explanation. +func MustHaveExecPath(t testing.TB, path string) { + MustHaveExec(t) + + err, found := execPaths.Load(path) + if !found { + _, err = exec.LookPath(path) + err, _ = execPaths.LoadOrStore(path, err) + } + if err != nil { + t.Helper() + t.Skipf("skipping test: %s: %s", path, err) + } +} + +// CleanCmdEnv will fill cmd.Env with the environment, excluding certain +// variables that could modify the behavior of the Go tools such as +// GODEBUG and GOTRACEBACK. +// +// If the caller wants to set cmd.Dir, set it before calling this function, +// so PWD will be set correctly in the environment. +func CleanCmdEnv(cmd *exec.Cmd) *exec.Cmd { + if cmd.Env != nil { + panic("environment already set") + } + for _, env := range cmd.Environ() { + // Exclude GODEBUG from the environment to prevent its output + // from breaking tests that are trying to parse other command output. + if strings.HasPrefix(env, "GODEBUG=") { + continue + } + // Exclude GOTRACEBACK for the same reason. + if strings.HasPrefix(env, "GOTRACEBACK=") { + continue + } + cmd.Env = append(cmd.Env, env) + } + return cmd +} + +// CommandContext is like exec.CommandContext, but: +// - skips t if the platform does not support os/exec, +// - sends SIGQUIT (if supported by the platform) instead of SIGKILL +// in its Cancel function +// - if the test has a deadline, adds a Context timeout and WaitDelay +// for an arbitrary grace period before the test's deadline expires, +// - fails the test if the command does not complete before the test's deadline, and +// - sets a Cleanup function that verifies that the test did not leak a subprocess. +func CommandContext(t testing.TB, ctx context.Context, name string, args ...string) *exec.Cmd { + t.Helper() + MustHaveExec(t) + + var ( + cancelCtx context.CancelFunc + gracePeriod time.Duration // unlimited unless the test has a deadline (to allow for interactive debugging) + ) + + if t, ok := t.(interface { + testing.TB + Deadline() (time.Time, bool) + }); ok { + if td, ok := t.Deadline(); ok { + // Start with a minimum grace period, just long enough to consume the + // output of a reasonable program after it terminates. + gracePeriod = 100 * time.Millisecond + if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" { + scale, err := strconv.Atoi(s) + if err != nil { + t.Fatalf("invalid GO_TEST_TIMEOUT_SCALE: %v", err) + } + gracePeriod *= time.Duration(scale) + } + + // If time allows, increase the termination grace period to 5% of the + // test's remaining time. + testTimeout := time.Until(td) + if gp := testTimeout / 20; gp > gracePeriod { + gracePeriod = gp + } + + // When we run commands that execute subprocesses, we want to reserve two + // grace periods to clean up: one for the delay between the first + // termination signal being sent (via the Cancel callback when the Context + // expires) and the process being forcibly terminated (via the WaitDelay + // field), and a second one for the delay between the process being + // terminated and the test logging its output for debugging. + // + // (We want to ensure that the test process itself has enough time to + // log the output before it is also terminated.) + cmdTimeout := testTimeout - 2*gracePeriod + + if cd, ok := ctx.Deadline(); !ok || time.Until(cd) > cmdTimeout { + // Either ctx doesn't have a deadline, or its deadline would expire + // after (or too close before) the test has already timed out. + // Add a shorter timeout so that the test will produce useful output. + ctx, cancelCtx = context.WithTimeout(ctx, cmdTimeout) + } + } + } + + cmd := exec.CommandContext(ctx, name, args...) + cmd.Cancel = func() error { + if cancelCtx != nil && ctx.Err() == context.DeadlineExceeded { + // The command timed out due to running too close to the test's deadline. + // There is no way the test did that intentionally — it's too close to the + // wire! — so mark it as a test failure. That way, if the test expects the + // command to fail for some other reason, it doesn't have to distinguish + // between that reason and a timeout. + t.Errorf("test timed out while running command: %v", cmd) + } else { + // The command is being terminated due to ctx being canceled, but + // apparently not due to an explicit test deadline that we added. + // Log that information in case it is useful for diagnosing a failure, + // but don't actually fail the test because of it. + t.Logf("%v: terminating command: %v", ctx.Err(), cmd) + } + return cmd.Process.Signal(Sigquit) + } + cmd.WaitDelay = gracePeriod + + t.Cleanup(func() { + if cancelCtx != nil { + cancelCtx() + } + if cmd.Process != nil && cmd.ProcessState == nil { + t.Errorf("command was started, but test did not wait for it to complete: %v", cmd) + } + }) + + return cmd +} + +// Command is like exec.Command, but applies the same changes as +// testenv.CommandContext (with a default Context). +func Command(t testing.TB, name string, args ...string) *exec.Cmd { + t.Helper() + return CommandContext(t, context.Background(), name, args...) +} diff --git a/go/src/internal/testenv/noopt.go b/go/src/internal/testenv/noopt.go new file mode 100644 index 0000000000000000000000000000000000000000..ae2a3d011a07c409813c6fdddcc22d08ef57030e --- /dev/null +++ b/go/src/internal/testenv/noopt.go @@ -0,0 +1,12 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build noopt + +package testenv + +// OptimizationOff reports whether optimization is disabled. +func OptimizationOff() bool { + return true +} diff --git a/go/src/internal/testenv/opt.go b/go/src/internal/testenv/opt.go new file mode 100644 index 0000000000000000000000000000000000000000..1bb96f73a129443df08fadc629ee6b71c2c1bfe5 --- /dev/null +++ b/go/src/internal/testenv/opt.go @@ -0,0 +1,12 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !noopt + +package testenv + +// OptimizationOff reports whether optimization is disabled. +func OptimizationOff() bool { + return false +} diff --git a/go/src/internal/testenv/testenv.go b/go/src/internal/testenv/testenv.go new file mode 100644 index 0000000000000000000000000000000000000000..96eacc60a3a07d1df6479cd90407e85613c809d9 --- /dev/null +++ b/go/src/internal/testenv/testenv.go @@ -0,0 +1,548 @@ +// 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 testenv provides information about what functionality +// is available in different testing environments run by the Go team. +// +// It is an internal package because these details are specific +// to the Go team's test setup (on build.golang.org) and not +// fundamental to tests in general. +package testenv + +import ( + "bytes" + "errors" + "flag" + "fmt" + "internal/cfg" + "internal/goarch" + "internal/platform" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "testing" +) + +// Save the original environment during init for use in checks. A test +// binary may modify its environment before calling HasExec to change its +// behavior (such as mimicking a command-line tool), and that modified +// environment might cause environment checks to behave erratically. +var origEnv = os.Environ() + +// Builder reports the name of the builder running this test. For example, +// "gotip-linux-amd64_avx512-test_only" or "go1.24-windows-arm64" on LUCI, +// or "linux-amd64" on our old infrastructure. Prefer using runtime.GOOS, +// runtime.GOARCH, race.Enabled, reading the OS version, checking CPU +// feature flags with internal/cpu, etc. over parsing builder names when +// possible. When matching builder names, prefer a fuzzy match instead +// of a strict comparison. +// If the test is not running on the build infrastructure, +// Builder returns the empty string. +func Builder() string { + return os.Getenv("GO_BUILDER_NAME") +} + +// HasGoBuild reports whether the current system can build programs with “go build” +// and then run them with os.StartProcess or exec.Command. +func HasGoBuild() bool { + if os.Getenv("GO_GCFLAGS") != "" { + // It's too much work to require every caller of the go command + // to pass along "-gcflags="+os.Getenv("GO_GCFLAGS"). + // For now, if $GO_GCFLAGS is set, report that we simply can't + // run go build. + return false + } + + return tryGoBuild() == nil +} + +var tryGoBuild = sync.OnceValue(func() error { + // To run 'go build', we need to be able to exec a 'go' command. + // We somewhat arbitrarily choose to exec 'go tool -n compile' because that + // also confirms that cmd/go can find the compiler. (Before CL 472096, + // we sometimes ended up with cmd/go installed in the test environment + // without a cmd/compile it could use to actually build things.) + goTool, err := goTool() + if err != nil { + return err + } + cmd := exec.Command(goTool, "tool", "-n", "compile") + cmd.Env = origEnv + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("%v: %w", cmd, err) + } + out = bytes.TrimSpace(out) + if len(out) == 0 { + return fmt.Errorf("%v: no tool reported", cmd) + } + if _, err := exec.LookPath(string(out)); err != nil { + return err + } + + if platform.MustLinkExternal(runtime.GOOS, runtime.GOARCH, false) { + // We can assume that we always have a complete Go toolchain available. + // However, this platform requires a C linker to build even pure Go + // programs, including tests. Do we have one in the test environment? + // (On Android, for example, the device running the test might not have a + // C toolchain installed.) + // + // If CC is set explicitly, assume that we do. Otherwise, use 'go env CC' + // to determine which toolchain it would use by default. + if os.Getenv("CC") == "" { + cmd := exec.Command(goTool, "env", "CC") + cmd.Env = origEnv + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("%v: %w", cmd, err) + } + out = bytes.TrimSpace(out) + if len(out) == 0 { + return fmt.Errorf("%v: no CC reported", cmd) + } + _, err = exec.LookPath(string(out)) + return err + } + } + return nil +}) + +// MustHaveGoBuild checks that the current system can build programs with “go build” +// and then run them with os.StartProcess or exec.Command. +// If not, MustHaveGoBuild calls t.Skip with an explanation. +func MustHaveGoBuild(t testing.TB) { + if os.Getenv("GO_GCFLAGS") != "" { + t.Helper() + t.Skipf("skipping test: 'go build' not compatible with setting $GO_GCFLAGS") + } + if !HasGoBuild() { + t.Helper() + t.Skipf("skipping test: 'go build' unavailable: %v", tryGoBuild()) + } +} + +// HasGoRun reports whether the current system can run programs with “go run”. +func HasGoRun() bool { + // For now, having go run and having go build are the same. + return HasGoBuild() +} + +// MustHaveGoRun checks that the current system can run programs with “go run”. +// If not, MustHaveGoRun calls t.Skip with an explanation. +func MustHaveGoRun(t testing.TB) { + if !HasGoRun() { + t.Helper() + t.Skipf("skipping test: 'go run' not available on %s/%s", runtime.GOOS, runtime.GOARCH) + } +} + +// HasParallelism reports whether the current system can execute multiple +// threads in parallel. +// There is a copy of this function in cmd/dist/test.go. +func HasParallelism() bool { + switch runtime.GOOS { + case "js", "wasip1": + return false + } + return true +} + +// MustHaveParallelism checks that the current system can execute multiple +// threads in parallel. If not, MustHaveParallelism calls t.Skip with an explanation. +func MustHaveParallelism(t testing.TB) { + if !HasParallelism() { + t.Helper() + t.Skipf("skipping test: no parallelism available on %s/%s", runtime.GOOS, runtime.GOARCH) + } +} + +// GoToolPath reports the path to the Go tool. +// It is a convenience wrapper around GoTool. +// If the tool is unavailable GoToolPath calls t.Skip. +// If the tool should be available and isn't, GoToolPath calls t.Fatal. +func GoToolPath(t testing.TB) string { + MustHaveGoBuild(t) + path, err := GoTool() + if err != nil { + t.Fatal(err) + } + // Add all environment variables that affect the Go command to test metadata. + // Cached test results will be invalidate when these variables change. + // See golang.org/issue/32285. + for _, envVar := range strings.Fields(cfg.KnownEnv) { + os.Getenv(envVar) + } + return path +} + +var findGOROOT = sync.OnceValues(func() (path string, err error) { + if path := runtime.GOROOT(); path != "" { + // If runtime.GOROOT() is non-empty, assume that it is valid. + // + // (It might not be: for example, the user may have explicitly set GOROOT + // to the wrong directory. But this case is + // rare, and if that happens the user can fix what they broke.) + return path, nil + } + + // runtime.GOROOT doesn't know where GOROOT is (perhaps because the test + // binary was built with -trimpath). + // + // Since this is internal/testenv, we can cheat and assume that the caller + // is a test of some package in a subdirectory of GOROOT/src. ('go test' + // runs the test in the directory containing the packaged under test.) That + // means that if we start walking up the tree, we should eventually find + // GOROOT/src/go.mod, and we can report the parent directory of that. + // + // Notably, this works even if we can't run 'go env GOROOT' as a + // subprocess. + + cwd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("finding GOROOT: %w", err) + } + + dir := cwd + for { + parent := filepath.Dir(dir) + if parent == dir { + // dir is either "." or only a volume name. + return "", fmt.Errorf("failed to locate GOROOT/src in any parent directory") + } + + if base := filepath.Base(dir); base != "src" { + dir = parent + continue // dir cannot be GOROOT/src if it doesn't end in "src". + } + + b, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil { + if os.IsNotExist(err) { + dir = parent + continue + } + return "", fmt.Errorf("finding GOROOT: %w", err) + } + goMod := string(b) + + for goMod != "" { + var line string + line, goMod, _ = strings.Cut(goMod, "\n") + fields := strings.Fields(line) + if len(fields) >= 2 && fields[0] == "module" && fields[1] == "std" { + // Found "module std", which is the module declaration in GOROOT/src! + return parent, nil + } + } + } +}) + +// GOROOT reports the path to the directory containing the root of the Go +// project source tree. This is normally equivalent to runtime.GOROOT, but +// works even if the test binary was built with -trimpath and cannot exec +// 'go env GOROOT'. +// +// If GOROOT cannot be found, GOROOT skips t if t is non-nil, +// or panics otherwise. +func GOROOT(t testing.TB) string { + path, err := findGOROOT() + if err != nil { + if t == nil { + panic(err) + } + t.Helper() + t.Skip(err) + } + return path +} + +// GoTool reports the path to the Go tool. +func GoTool() (string, error) { + if !HasGoBuild() { + return "", errors.New("platform cannot run go tool") + } + return goTool() +} + +var goTool = sync.OnceValues(func() (string, error) { + return exec.LookPath("go") +}) + +// MustHaveSource checks that the entire source tree is available under GOROOT. +// If not, it calls t.Skip with an explanation. +func MustHaveSource(t testing.TB) { + switch runtime.GOOS { + case "ios": + t.Helper() + t.Skip("skipping test: no source tree on " + runtime.GOOS) + } +} + +// HasExternalNetwork reports whether the current system can use +// external (non-localhost) networks. +func HasExternalNetwork() bool { + return !testing.Short() && runtime.GOOS != "js" && runtime.GOOS != "wasip1" +} + +// MustHaveExternalNetwork checks that the current system can use +// external (non-localhost) networks. +// If not, MustHaveExternalNetwork calls t.Skip with an explanation. +func MustHaveExternalNetwork(t testing.TB) { + if runtime.GOOS == "js" || runtime.GOOS == "wasip1" { + t.Helper() + t.Skipf("skipping test: no external network on %s", runtime.GOOS) + } + if testing.Short() { + t.Helper() + t.Skipf("skipping test: no external network in -short mode") + } +} + +// HasCGO reports whether the current system can use cgo. +func HasCGO() bool { + return hasCgo() +} + +var hasCgo = sync.OnceValue(func() bool { + goTool, err := goTool() + if err != nil { + return false + } + cmd := exec.Command(goTool, "env", "CGO_ENABLED") + cmd.Env = origEnv + out, err := cmd.Output() + if err != nil { + panic(fmt.Sprintf("%v: %v", cmd, out)) + } + ok, err := strconv.ParseBool(string(bytes.TrimSpace(out))) + if err != nil { + panic(fmt.Sprintf("%v: non-boolean output %q", cmd, out)) + } + return ok +}) + +// MustHaveCGO calls t.Skip if cgo is not available. +func MustHaveCGO(t testing.TB) { + if !HasCGO() { + t.Helper() + t.Skipf("skipping test: no cgo") + } +} + +// CanInternalLink reports whether the current system can link programs with +// internal linking. +func CanInternalLink(withCgo bool) bool { + return !platform.MustLinkExternal(runtime.GOOS, runtime.GOARCH, withCgo) +} + +// SpecialBuildTypes are interesting build types that may affect linking. +type SpecialBuildTypes struct { + Cgo bool + Asan bool + Msan bool + Race bool +} + +// NoSpecialBuildTypes indicates a standard, no cgo go build. +var NoSpecialBuildTypes SpecialBuildTypes + +// MustInternalLink checks that the current system can link programs with internal +// linking. +// If not, MustInternalLink calls t.Skip with an explanation. +func MustInternalLink(t testing.TB, with SpecialBuildTypes) { + if with.Asan || with.Msan || with.Race { + t.Skipf("skipping test: internal linking with sanitizers is not supported") + } + if !CanInternalLink(with.Cgo) { + t.Helper() + if with.Cgo && CanInternalLink(false) { + t.Skipf("skipping test: internal linking on %s/%s is not supported with cgo", runtime.GOOS, runtime.GOARCH) + } + t.Skipf("skipping test: internal linking on %s/%s is not supported", runtime.GOOS, runtime.GOARCH) + } +} + +// MustInternalLinkPIE checks whether the current system can link PIE binary using +// internal linking. +// If not, MustInternalLinkPIE calls t.Skip with an explanation. +func MustInternalLinkPIE(t testing.TB) { + if !platform.InternalLinkPIESupported(runtime.GOOS, runtime.GOARCH) { + t.Helper() + t.Skipf("skipping test: internal linking for buildmode=pie on %s/%s is not supported", runtime.GOOS, runtime.GOARCH) + } +} + +// MustHaveBuildMode reports whether the current system can build programs in +// the given build mode. +// If not, MustHaveBuildMode calls t.Skip with an explanation. +func MustHaveBuildMode(t testing.TB, buildmode string) { + if !platform.BuildModeSupported(runtime.Compiler, buildmode, runtime.GOOS, runtime.GOARCH) { + t.Helper() + t.Skipf("skipping test: build mode %s on %s/%s is not supported by the %s compiler", buildmode, runtime.GOOS, runtime.GOARCH, runtime.Compiler) + } +} + +// HasSymlink reports whether the current system can use os.Symlink. +func HasSymlink() bool { + ok, _ := hasSymlink() + return ok +} + +// MustHaveSymlink reports whether the current system can use os.Symlink. +// If not, MustHaveSymlink calls t.Skip with an explanation. +func MustHaveSymlink(t testing.TB) { + ok, reason := hasSymlink() + if !ok { + t.Helper() + t.Skipf("skipping test: cannot make symlinks on %s/%s: %s", runtime.GOOS, runtime.GOARCH, reason) + } +} + +// HasLink reports whether the current system can use os.Link. +func HasLink() bool { + // From Android release M (Marshmallow), hard linking files is blocked + // and an attempt to call link() on a file will return EACCES. + // - https://code.google.com/p/android-developer-preview/issues/detail?id=3150 + return runtime.GOOS != "plan9" && runtime.GOOS != "android" +} + +// MustHaveLink reports whether the current system can use os.Link. +// If not, MustHaveLink calls t.Skip with an explanation. +func MustHaveLink(t testing.TB) { + if !HasLink() { + t.Helper() + t.Skipf("skipping test: hardlinks are not supported on %s/%s", runtime.GOOS, runtime.GOARCH) + } +} + +var flaky = flag.Bool("flaky", false, "run known-flaky tests too") + +func SkipFlaky(t testing.TB, issue int) { + if !*flaky { + t.Helper() + t.Skipf("skipping known flaky test without the -flaky flag; see golang.org/issue/%d", issue) + } +} + +func SkipFlakyNet(t testing.TB) { + if v, _ := strconv.ParseBool(os.Getenv("GO_BUILDER_FLAKY_NET")); v { + t.Helper() + t.Skip("skipping test on builder known to have frequent network failures") + } +} + +// CPUIsSlow reports whether the CPU running the test is suspected to be slow. +func CPUIsSlow() bool { + switch runtime.GOARCH { + case "arm", "mips", "mipsle", "mips64", "mips64le", "wasm": + return true + } + return false +} + +// SkipIfShortAndSlow skips t if -short is set and the CPU running the test is +// suspected to be slow. +// +// (This is useful for CPU-intensive tests that otherwise complete quickly.) +func SkipIfShortAndSlow(t testing.TB) { + if testing.Short() && CPUIsSlow() { + t.Helper() + t.Skipf("skipping test in -short mode on %s", runtime.GOARCH) + } +} + +// SkipIfOptimizationOff skips t if optimization is disabled. +func SkipIfOptimizationOff(t testing.TB) { + if OptimizationOff() { + t.Helper() + t.Skip("skipping test with optimization disabled") + } +} + +// WriteImportcfg writes an importcfg file used by the compiler or linker to +// dstPath containing entries for the file mappings in packageFiles, as well +// as for the packages transitively imported by the package(s) in pkgs. +// +// pkgs may include any package pattern that is valid to pass to 'go list', +// so it may also be a list of Go source files all in the same directory. +func WriteImportcfg(t testing.TB, dstPath string, packageFiles map[string]string, pkgs ...string) { + t.Helper() + + icfg := new(bytes.Buffer) + icfg.WriteString("# import config\n") + for k, v := range packageFiles { + fmt.Fprintf(icfg, "packagefile %s=%s\n", k, v) + } + + if len(pkgs) > 0 { + // Use 'go list' to resolve any missing packages and rewrite the import map. + cmd := Command(t, GoToolPath(t), "list", "-export", "-deps", "-f", `{{if ne .ImportPath "command-line-arguments"}}{{if .Export}}{{.ImportPath}}={{.Export}}{{end}}{{end}}`) + cmd.Args = append(cmd.Args, pkgs...) + cmd.Stderr = new(strings.Builder) + out, err := cmd.Output() + if err != nil { + t.Fatalf("%v: %v\n%s", cmd, err, cmd.Stderr) + } + + for line := range strings.SplitSeq(string(out), "\n") { + if line == "" { + continue + } + importPath, export, ok := strings.Cut(line, "=") + if !ok { + t.Fatalf("invalid line in output from %v:\n%s", cmd, line) + } + if packageFiles[importPath] == "" { + fmt.Fprintf(icfg, "packagefile %s=%s\n", importPath, export) + } + } + } + + if err := os.WriteFile(dstPath, icfg.Bytes(), 0666); err != nil { + t.Fatal(err) + } +} + +// SyscallIsNotSupported reports whether err may indicate that a system call is +// not supported by the current platform or execution environment. +func SyscallIsNotSupported(err error) bool { + return syscallIsNotSupported(err) +} + +// ParallelOn64Bit calls t.Parallel() unless there is a case that cannot be parallel. +// This function should be used when it is necessary to avoid t.Parallel on +// 32-bit machines, typically because the test uses lots of memory. +func ParallelOn64Bit(t *testing.T) { + if goarch.PtrSize == 4 { + return + } + t.Parallel() +} + +// CPUProfilingBroken returns true if CPU profiling has known issues on this +// platform. +func CPUProfilingBroken() bool { + switch runtime.GOOS { + case "plan9": + // Profiling unimplemented. + return true + case "aix": + // See https://golang.org/issue/45170. + return true + case "ios", "dragonfly", "netbsd", "illumos", "solaris": + // See https://golang.org/issue/13841. + return true + case "openbsd": + if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" { + // See https://golang.org/issue/13841. + return true + } + } + + return false +} diff --git a/go/src/internal/testenv/testenv_notunix.go b/go/src/internal/testenv/testenv_notunix.go new file mode 100644 index 0000000000000000000000000000000000000000..a7df5f5ddcecea267bccc61cabd74a25a4d80312 --- /dev/null +++ b/go/src/internal/testenv/testenv_notunix.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build windows || plan9 || (js && wasm) || wasip1 + +package testenv + +import ( + "errors" + "io/fs" + "os" +) + +// Sigquit is the signal to send to kill a hanging subprocess. +// On Unix we send SIGQUIT, but on non-Unix we only have os.Kill. +var Sigquit = os.Kill + +func syscallIsNotSupported(err error) bool { + return errors.Is(err, fs.ErrPermission) || errors.Is(err, errors.ErrUnsupported) +} diff --git a/go/src/internal/testenv/testenv_notwin.go b/go/src/internal/testenv/testenv_notwin.go new file mode 100644 index 0000000000000000000000000000000000000000..9dddea94d05798982aaf14e9e8dc2c63bb70dacf --- /dev/null +++ b/go/src/internal/testenv/testenv_notwin.go @@ -0,0 +1,47 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !windows + +package testenv + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "sync" +) + +var hasSymlink = sync.OnceValues(func() (ok bool, reason string) { + switch runtime.GOOS { + case "plan9": + return false, "" + case "android", "wasip1": + // For wasip1, some runtimes forbid absolute symlinks, + // or symlinks that escape the current working directory. + // Perform a simple test to see whether the runtime + // supports symlinks or not. If we get a permission + // error, the runtime does not support symlinks. + dir, err := os.MkdirTemp("", "") + if err != nil { + return false, "" + } + defer func() { + _ = os.RemoveAll(dir) + }() + fpath := filepath.Join(dir, "testfile.txt") + if err := os.WriteFile(fpath, nil, 0644); err != nil { + return false, "" + } + if err := os.Symlink(fpath, filepath.Join(dir, "testlink")); err != nil { + if SyscallIsNotSupported(err) { + return false, fmt.Sprintf("symlinks unsupported: %s", err.Error()) + } + return false, "" + } + } + + return true, "" +}) diff --git a/go/src/internal/testenv/testenv_test.go b/go/src/internal/testenv/testenv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..769db3a0334643b1d9c300d62833bdec2a42b57f --- /dev/null +++ b/go/src/internal/testenv/testenv_test.go @@ -0,0 +1,208 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testenv_test + +import ( + "internal/platform" + "internal/testenv" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestGoToolLocation(t *testing.T) { + testenv.MustHaveGoBuild(t) + + var exeSuffix string + if runtime.GOOS == "windows" { + exeSuffix = ".exe" + } + + // Tests are defined to run within their package source directory, + // and this package's source directory is $GOROOT/src/internal/testenv. + // The 'go' command is installed at $GOROOT/bin/go, so if the environment + // is correct then testenv.GoTool() should be identical to ../../../bin/go. + + relWant := "../../../bin/go" + exeSuffix + absWant, err := filepath.Abs(relWant) + if err != nil { + t.Fatal(err) + } + + wantInfo, err := os.Stat(absWant) + if err != nil { + t.Fatal(err) + } + t.Logf("found go tool at %q (%q)", relWant, absWant) + + goTool, err := testenv.GoTool() + if err != nil { + t.Fatalf("testenv.GoTool(): %v", err) + } + t.Logf("testenv.GoTool() = %q", goTool) + + gotInfo, err := os.Stat(goTool) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(wantInfo, gotInfo) { + t.Fatalf("%q is not the same file as %q", absWant, goTool) + } +} + +func TestHasGoBuild(t *testing.T) { + if !testenv.HasGoBuild() { + switch runtime.GOOS { + case "js", "wasip1": + // No exec syscall, so these shouldn't be able to 'go build'. + t.Logf("HasGoBuild is false on %s", runtime.GOOS) + return + } + + b := testenv.Builder() + if b == "" { + // We shouldn't make assumptions about what kind of sandbox or build + // environment external Go users may be running in. + t.Skipf("skipping: 'go build' unavailable") + } + + // Since we control the Go builders, we know which ones ought + // to be able to run 'go build'. Check that they can. + // + // (Note that we don't verify that any builders *can't* run 'go build'. + // If a builder starts running 'go build' tests when it shouldn't, + // we will presumably find out about it when those tests fail.) + switch runtime.GOOS { + case "ios": + if isCorelliumBuilder(b) { + // The corellium environment is self-hosting, so it should be able + // to build even though real "ios" devices can't exec. + } else { + // The usual iOS sandbox does not allow the app to start another + // process. If we add builders on stock iOS devices, they presumably + // will not be able to exec, so we may as well allow that now. + t.Logf("HasGoBuild is false on %s", b) + return + } + case "android": + if isEmulatedBuilder(b) && platform.MustLinkExternal(runtime.GOOS, runtime.GOARCH, false) { + // As of 2023-05-02, the test environment on the emulated builders is + // missing a C linker. + t.Logf("HasGoBuild is false on %s", b) + return + } + } + + if strings.Contains(b, "-noopt") { + // The -noopt builder sets GO_GCFLAGS, which causes tests of 'go build' to + // be skipped. + t.Logf("HasGoBuild is false on %s", b) + return + } + + t.Fatalf("HasGoBuild unexpectedly false on %s", b) + } + + t.Logf("HasGoBuild is true; checking consistency with other functions") + + hasExec := false + hasExecGo := false + t.Run("MustHaveExec", func(t *testing.T) { + testenv.MustHaveExec(t) + hasExec = true + }) + t.Run("MustHaveExecPath", func(t *testing.T) { + testenv.MustHaveExecPath(t, "go") + hasExecGo = true + }) + if !hasExec { + t.Errorf(`MustHaveExec(t) skipped unexpectedly`) + } + if !hasExecGo { + t.Errorf(`MustHaveExecPath(t, "go") skipped unexpectedly`) + } + + dir := t.TempDir() + mainGo := filepath.Join(dir, "main.go") + if err := os.WriteFile(mainGo, []byte("package main\nfunc main() {}\n"), 0644); err != nil { + t.Fatal(err) + } + cmd := testenv.Command(t, "go", "build", "-o", os.DevNull, mainGo) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v: %v\n%s", cmd, err, out) + } +} + +func TestMustHaveExec(t *testing.T) { + hasExec := false + t.Run("MustHaveExec", func(t *testing.T) { + testenv.MustHaveExec(t) + t.Logf("MustHaveExec did not skip") + hasExec = true + }) + + switch runtime.GOOS { + case "js", "wasip1": + if hasExec { + // js and wasip1 lack an “exec” syscall. + t.Errorf("expected MustHaveExec to skip on %v", runtime.GOOS) + } + case "ios": + if b := testenv.Builder(); isCorelliumBuilder(b) && !hasExec { + // Most ios environments can't exec, but the corellium builder can. + t.Errorf("expected MustHaveExec not to skip on %v", b) + } + default: + if b := testenv.Builder(); b != "" && !hasExec { + t.Errorf("expected MustHaveExec not to skip on %v", b) + } + } +} + +func TestCleanCmdEnvPWD(t *testing.T) { + // Test that CleanCmdEnv sets PWD if cmd.Dir is set. + switch runtime.GOOS { + case "plan9", "windows": + t.Skipf("PWD is not used on %s", runtime.GOOS) + } + dir := t.TempDir() + cmd := testenv.Command(t, testenv.GoToolPath(t), "help") + cmd.Dir = dir + cmd = testenv.CleanCmdEnv(cmd) + + for _, env := range cmd.Env { + if strings.HasPrefix(env, "PWD=") { + pwd := strings.TrimPrefix(env, "PWD=") + if pwd != dir { + t.Errorf("unexpected PWD: want %s, got %s", dir, pwd) + } + return + } + } + t.Error("PWD not set in cmd.Env") +} + +func isCorelliumBuilder(builderName string) bool { + // Support both the old infra's builder names and the LUCI builder names. + // The former's names are ad-hoc so we could maintain this invariant on + // the builder side. The latter's names are structured, and "corellium" will + // appear as a "host" suffix after the GOOS and GOARCH, which always begin + // with an underscore. + return strings.HasSuffix(builderName, "-corellium") || strings.Contains(builderName, "_corellium") +} + +func isEmulatedBuilder(builderName string) bool { + // Support both the old infra's builder names and the LUCI builder names. + // The former's names are ad-hoc so we could maintain this invariant on + // the builder side. The latter's names are structured, and the signifier + // of emulation "emu" will appear as a "host" suffix after the GOOS and + // GOARCH because it modifies the run environment in such a way that it + // the target GOOS and GOARCH may not match the host. This suffix always + // begins with an underscore. + return strings.HasSuffix(builderName, "-emu") || strings.Contains(builderName, "_emu") +} diff --git a/go/src/internal/testenv/testenv_unix.go b/go/src/internal/testenv/testenv_unix.go new file mode 100644 index 0000000000000000000000000000000000000000..22eeca220da017d6e03be7375ece51e9bb10186e --- /dev/null +++ b/go/src/internal/testenv/testenv_unix.go @@ -0,0 +1,42 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build unix + +package testenv + +import ( + "errors" + "io/fs" + "syscall" +) + +// Sigquit is the signal to send to kill a hanging subprocess. +// Send SIGQUIT to get a stack trace. +var Sigquit = syscall.SIGQUIT + +func syscallIsNotSupported(err error) bool { + if err == nil { + return false + } + + if errno, ok := errors.AsType[syscall.Errno](err); ok { + switch errno { + case syscall.EPERM, syscall.EROFS: + // User lacks permission: either the call requires root permission and the + // user is not root, or the call is denied by a container security policy. + return true + case syscall.EINVAL: + // Some containers return EINVAL instead of EPERM if a system call is + // denied by security policy. + return true + } + } + + if errors.Is(err, fs.ErrPermission) || errors.Is(err, errors.ErrUnsupported) { + return true + } + + return false +} diff --git a/go/src/internal/testenv/testenv_windows.go b/go/src/internal/testenv/testenv_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..eed53cdfb2b9065833373e1d74f5fa6e63221d27 --- /dev/null +++ b/go/src/internal/testenv/testenv_windows.go @@ -0,0 +1,32 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testenv + +import ( + "errors" + "os" + "path/filepath" + "sync" + "syscall" +) + +var hasSymlink = sync.OnceValues(func() (bool, string) { + tmpdir, err := os.MkdirTemp("", "symtest") + if err != nil { + panic("failed to create temp directory: " + err.Error()) + } + defer os.RemoveAll(tmpdir) + + err = os.Symlink("target", filepath.Join(tmpdir, "symlink")) + switch { + case err == nil: + return true, "" + case errors.Is(err, syscall.EWINDOWS): + return false, ": symlinks are not supported on your version of Windows" + case errors.Is(err, syscall.ERROR_PRIVILEGE_NOT_HELD): + return false, ": you don't have enough privileges to create symlinks" + } + return false, "" +}) diff --git a/go/src/internal/testhash/hash.go b/go/src/internal/testhash/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..3413d5c20de29b6a0f5be558486eee3f2ece1959 --- /dev/null +++ b/go/src/internal/testhash/hash.go @@ -0,0 +1,231 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testhash + +import ( + "bytes" + "hash" + "io" + "math/rand" + "testing" + "time" +) + +type MakeHash func() hash.Hash + +// TestHash performs a set of tests on hash.Hash implementations, checking the +// documented requirements of Write, Sum, Reset, Size, and BlockSize. +func TestHash(t *testing.T, mh MakeHash) { + TestHashWithoutClone(t, mh) + + // Test whether the results after cloning are consistent. + t.Run("Clone", func(t *testing.T) { + h, ok := mh().(hash.Cloner) + if !ok { + t.Fatalf("%T does not implement hash.Cloner", mh) + } + h3, err := h.Clone() + if err != nil { + t.Fatalf("Clone failed: %v", err) + } + prefix := []byte("tmp") + writeToHash(t, h, prefix) + h2, err := h.Clone() + if err != nil { + t.Fatalf("Clone failed: %v", err) + } + prefixSum := h.Sum(nil) + if !bytes.Equal(prefixSum, h2.Sum(nil)) { + t.Fatalf("%T Clone results are inconsistent", h) + } + suffix := []byte("tmp2") + writeToHash(t, h, suffix) + writeToHash(t, h3, append(prefix, suffix...)) + compositeSum := h3.Sum(nil) + if !bytes.Equal(h.Sum(nil), compositeSum) { + t.Fatalf("%T Clone results are inconsistent", h) + } + if !bytes.Equal(h2.Sum(nil), prefixSum) { + t.Fatalf("%T Clone results are inconsistent", h) + } + writeToHash(t, h2, suffix) + if !bytes.Equal(h.Sum(nil), compositeSum) { + t.Fatalf("%T Clone results are inconsistent", h) + } + if !bytes.Equal(h2.Sum(nil), compositeSum) { + t.Fatalf("%T Clone results are inconsistent", h) + } + }) +} + +func TestHashWithoutClone(t *testing.T, mh MakeHash) { + // Test that Sum returns an appended digest matching output of Size + t.Run("SumAppend", func(t *testing.T) { + h := mh() + rng := newRandReader(t) + + emptyBuff := []byte("") + shortBuff := []byte("a") + longBuff := make([]byte, h.BlockSize()+1) + rng.Read(longBuff) + + // Set of example strings to append digest to + prefixes := [][]byte{nil, emptyBuff, shortBuff, longBuff} + + // Go to each string and check digest gets appended to and is correct size. + for _, prefix := range prefixes { + h.Reset() + + sum := getSum(t, h, prefix) // Append new digest to prefix + + // Check that Sum didn't alter the prefix + if !bytes.Equal(sum[:len(prefix)], prefix) { + t.Errorf("Sum alters passed buffer instead of appending; got %x, want %x", sum[:len(prefix)], prefix) + } + + // Check that the appended sum wasn't affected by the prefix + if expectedSum := getSum(t, h, nil); !bytes.Equal(sum[len(prefix):], expectedSum) { + t.Errorf("Sum behavior affected by data in the input buffer; got %x, want %x", sum[len(prefix):], expectedSum) + } + + // Check size of append + if got, want := len(sum)-len(prefix), h.Size(); got != want { + t.Errorf("Sum appends number of bytes != Size; got %v , want %v", got, want) + } + } + }) + + // Test that Hash.Write never returns error. + t.Run("WriteWithoutError", func(t *testing.T) { + h := mh() + rng := newRandReader(t) + + emptySlice := []byte("") + shortSlice := []byte("a") + longSlice := make([]byte, h.BlockSize()+1) + rng.Read(longSlice) + + // Set of example strings to append digest to + slices := [][]byte{emptySlice, shortSlice, longSlice} + + for _, slice := range slices { + writeToHash(t, h, slice) // Writes and checks Write doesn't error + } + }) + + t.Run("ResetState", func(t *testing.T) { + h := mh() + rng := newRandReader(t) + + emptySum := getSum(t, h, nil) + + // Write to hash and then Reset it and see if Sum is same as emptySum + writeEx := make([]byte, h.BlockSize()) + rng.Read(writeEx) + writeToHash(t, h, writeEx) + h.Reset() + resetSum := getSum(t, h, nil) + + if !bytes.Equal(emptySum, resetSum) { + t.Errorf("Reset hash yields different Sum than new hash; got %x, want %x", emptySum, resetSum) + } + }) + + // Check that Write isn't reading from beyond input slice's bounds + t.Run("OutOfBoundsRead", func(t *testing.T) { + h := mh() + blockSize := h.BlockSize() + rng := newRandReader(t) + + msg := make([]byte, blockSize) + rng.Read(msg) + writeToHash(t, h, msg) + expectedDigest := getSum(t, h, nil) // Record control digest + + h.Reset() + + // Make a buffer with msg in the middle and data on either end + buff := make([]byte, blockSize*3) + endOfPrefix, startOfSuffix := blockSize, blockSize*2 + + copy(buff[endOfPrefix:startOfSuffix], msg) + rng.Read(buff[:endOfPrefix]) + rng.Read(buff[startOfSuffix:]) + + writeToHash(t, h, buff[endOfPrefix:startOfSuffix]) + testDigest := getSum(t, h, nil) + + if !bytes.Equal(testDigest, expectedDigest) { + t.Errorf("Write affected by data outside of input slice bounds; got %x, want %x", testDigest, expectedDigest) + } + }) + + // Test that multiple calls to Write is stateful + t.Run("StatefulWrite", func(t *testing.T) { + h := mh() + rng := newRandReader(t) + + prefix, suffix := make([]byte, h.BlockSize()), make([]byte, h.BlockSize()) + rng.Read(prefix) + rng.Read(suffix) + + // Write prefix then suffix sequentially and record resulting hash + writeToHash(t, h, prefix) + writeToHash(t, h, suffix) + serialSum := getSum(t, h, nil) + + h.Reset() + + // Write prefix and suffix at the same time and record resulting hash + writeToHash(t, h, append(prefix, suffix...)) + compositeSum := getSum(t, h, nil) + + // Check that sequential writing results in the same as writing all at once + if !bytes.Equal(compositeSum, serialSum) { + t.Errorf("two successive Write calls resulted in a different Sum than a single one; got %x, want %x", compositeSum, serialSum) + } + }) +} + +// Helper function for writing. Verifies that Write does not error. +func writeToHash(t *testing.T, h hash.Hash, p []byte) { + t.Helper() + + before := make([]byte, len(p)) + copy(before, p) + + n, err := h.Write(p) + if err != nil || n != len(p) { + t.Errorf("Write returned error; got (%v, %v), want (nil, %v)", err, n, len(p)) + } + + if !bytes.Equal(p, before) { + t.Errorf("Write modified input slice; got %x, want %x", p, before) + } +} + +// Helper function for getting Sum. Checks that Sum doesn't change hash state. +func getSum(t *testing.T, h hash.Hash, buff []byte) []byte { + t.Helper() + + testBuff := make([]byte, len(buff)) + copy(testBuff, buff) + + sum := h.Sum(buff) + testSum := h.Sum(testBuff) + + // Check that Sum doesn't change underlying hash state + if !bytes.Equal(sum, testSum) { + t.Errorf("successive calls to Sum yield different results; got %x, want %x", sum, testSum) + } + + return sum +} + +func newRandReader(t *testing.T) io.Reader { + seed := time.Now().UnixNano() + t.Logf("Deterministic RNG seed: 0x%x", seed) + return rand.New(rand.NewSource(seed)) +} diff --git a/go/src/internal/testlog/exit.go b/go/src/internal/testlog/exit.go new file mode 100644 index 0000000000000000000000000000000000000000..b985c6b3f79b128aeba95d086d7a9e6d56be2cfd --- /dev/null +++ b/go/src/internal/testlog/exit.go @@ -0,0 +1,45 @@ +// 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 testlog + +import ( + "sync" + _ "unsafe" // for linkname +) + +// PanicOnExit0 reports whether to panic on a call to os.Exit(0). +// This is in the testlog package because, like other definitions in +// package testlog, it is a hook between the testing package and the +// os package. This is used to ensure that an early call to os.Exit(0) +// does not cause a test to pass. +func PanicOnExit0() bool { + panicOnExit0.mu.Lock() + defer panicOnExit0.mu.Unlock() + return panicOnExit0.val +} + +// panicOnExit0 is the flag used for PanicOnExit0. This uses a lock +// because the value can be cleared via a timer call that may race +// with calls to os.Exit +var panicOnExit0 struct { + mu sync.Mutex + val bool +} + +// SetPanicOnExit0 sets panicOnExit0 to v. +// +// SetPanicOnExit0 should be an internal detail, +// but alternate implementations of go test in other +// build systems may need to access it using linkname. +// +// Do not remove or change the type signature. +// See go.dev/issue/67401. +// +//go:linkname SetPanicOnExit0 +func SetPanicOnExit0(v bool) { + panicOnExit0.mu.Lock() + defer panicOnExit0.mu.Unlock() + panicOnExit0.val = v +} diff --git a/go/src/internal/testlog/log.go b/go/src/internal/testlog/log.go new file mode 100644 index 0000000000000000000000000000000000000000..d8b9dcfafe3d88d8e3b1416d96ab42af6e0dae12 --- /dev/null +++ b/go/src/internal/testlog/log.go @@ -0,0 +1,68 @@ +// 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 testlog provides a back-channel communication path +// between tests and package os, so that cmd/go can see which +// environment variables and files a test consults. +package testlog + +import "sync/atomic" + +// Interface is the interface required of test loggers. +// The os package will invoke the interface's methods to indicate that +// it is inspecting the given environment variables or files. +// Multiple goroutines may call these methods simultaneously. +type Interface interface { + Getenv(key string) + Stat(file string) + Open(file string) + Chdir(dir string) +} + +// logger is the current logger Interface. +// We use an atomic.Pointer in case test startup +// is racing with goroutines started during init. +// That must not cause a race detector failure, +// although it will still result in limited visibility +// into exactly what those goroutines do. +var logger atomic.Pointer[Interface] + +// SetLogger sets the test logger implementation for the current process. +// It must be called only once, at process startup. +func SetLogger(impl Interface) { + if !logger.CompareAndSwap(nil, &impl) { + panic("testlog: SetLogger must be called only once") + } +} + +// Logger returns the current test logger implementation. +// It returns nil if there is no logger. +func Logger() Interface { + impl := logger.Load() + if impl == nil { + return nil + } + return *impl +} + +// Getenv calls Logger().Getenv, if a logger has been set. +func Getenv(name string) { + if log := Logger(); log != nil { + log.Getenv(name) + } +} + +// Open calls Logger().Open, if a logger has been set. +func Open(name string) { + if log := Logger(); log != nil { + log.Open(name) + } +} + +// Stat calls Logger().Stat, if a logger has been set. +func Stat(name string) { + if log := Logger(); log != nil { + log.Stat(name) + } +} diff --git a/go/src/internal/testpty/pty.go b/go/src/internal/testpty/pty.go new file mode 100644 index 0000000000000000000000000000000000000000..f0b2a331b8d801516306c4fc499237dfd1fd2a4f --- /dev/null +++ b/go/src/internal/testpty/pty.go @@ -0,0 +1,38 @@ +// 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 testpty is a simple pseudo-terminal package for Unix systems, +// implemented by calling C functions via cgo. +package testpty + +import ( + "errors" + "fmt" + "os" +) + +type PtyError struct { + FuncName string + ErrorString string + Errno error +} + +func ptyError(name string, err error) *PtyError { + return &PtyError{name, err.Error(), err} +} + +func (e *PtyError) Error() string { + return fmt.Sprintf("%s: %s", e.FuncName, e.ErrorString) +} + +func (e *PtyError) Unwrap() error { return e.Errno } + +var ErrNotSupported = errors.New("testpty.Open not implemented on this platform") + +// Open returns a control pty and the name of the linked process tty. +// +// If Open is not implemented on this platform, it returns ErrNotSupported. +func Open() (pty *os.File, processTTY string, err error) { + return open() +} diff --git a/go/src/internal/testpty/pty_cgo.go b/go/src/internal/testpty/pty_cgo.go new file mode 100644 index 0000000000000000000000000000000000000000..442fbcf6184a438fc37bf6ce1ba275c7d4a38684 --- /dev/null +++ b/go/src/internal/testpty/pty_cgo.go @@ -0,0 +1,34 @@ +// 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 cgo && (aix || dragonfly || freebsd || (linux && !android) || netbsd || openbsd) + +package testpty + +/* +#define _XOPEN_SOURCE 600 +#include +#include +#include +*/ +import "C" + +import "os" + +func open() (pty *os.File, processTTY string, err error) { + m, err := C.posix_openpt(C.O_RDWR) + if m < 0 { + return nil, "", ptyError("posix_openpt", err) + } + if res, err := C.grantpt(m); res < 0 { + C.close(m) + return nil, "", ptyError("grantpt", err) + } + if res, err := C.unlockpt(m); res < 0 { + C.close(m) + return nil, "", ptyError("unlockpt", err) + } + processTTY = C.GoString(C.ptsname(m)) + return os.NewFile(uintptr(m), "pty"), processTTY, nil +} diff --git a/go/src/internal/testpty/pty_darwin.go b/go/src/internal/testpty/pty_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..f29517c0e25efae48c05f0a79672b6298dc935cc --- /dev/null +++ b/go/src/internal/testpty/pty_darwin.go @@ -0,0 +1,32 @@ +// 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 testpty + +import ( + "internal/syscall/unix" + "os" + "syscall" +) + +func open() (pty *os.File, processTTY string, err error) { + m, err := unix.PosixOpenpt(syscall.O_RDWR) + if err != nil { + return nil, "", ptyError("posix_openpt", err) + } + if err := unix.Grantpt(m); err != nil { + syscall.Close(m) + return nil, "", ptyError("grantpt", err) + } + if err := unix.Unlockpt(m); err != nil { + syscall.Close(m) + return nil, "", ptyError("unlockpt", err) + } + processTTY, err = unix.Ptsname(m) + if err != nil { + syscall.Close(m) + return nil, "", ptyError("ptsname", err) + } + return os.NewFile(uintptr(m), "pty"), processTTY, nil +} diff --git a/go/src/internal/testpty/pty_none.go b/go/src/internal/testpty/pty_none.go new file mode 100644 index 0000000000000000000000000000000000000000..4f9e2b7c1704c0bfb0f199ba07703e9510f0b72a --- /dev/null +++ b/go/src/internal/testpty/pty_none.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !(cgo && (aix || dragonfly || freebsd || (linux && !android) || netbsd || openbsd)) && !darwin + +package testpty + +import "os" + +func open() (pty *os.File, processTTY string, err error) { + return nil, "", ErrNotSupported +} diff --git a/go/src/internal/trace/base.go b/go/src/internal/trace/base.go new file mode 100644 index 0000000000000000000000000000000000000000..a452622973eedfa910466396bca7b7dcb0f5a1d4 --- /dev/null +++ b/go/src/internal/trace/base.go @@ -0,0 +1,274 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains data types that all implementations of the trace format +// parser need to provide to the rest of the package. + +package trace + +import ( + "fmt" + "math" + "strings" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// timedEventArgs is an array that is able to hold the arguments for any +// timed event. +type timedEventArgs [tracev2.MaxTimedEventArgs - 1]uint64 + +// baseEvent is the basic unprocessed event. This serves as a common +// fundamental data structure across. +type baseEvent struct { + typ tracev2.EventType + time Time + args timedEventArgs +} + +// extra returns a slice representing extra available space in args +// that the parser can use to pass data up into Event. +func (e *baseEvent) extra(v version.Version) []uint64 { + switch v { + case version.Go122: + return e.args[len(tracev2.Specs()[e.typ].Args)-1:] + } + panic(fmt.Sprintf("unsupported version: go 1.%d", v)) +} + +// evTable contains the per-generation data necessary to +// interpret an individual event. +type evTable struct { + sync + strings dataTable[stringID, string] + stacks dataTable[stackID, stack] + pcs map[uint64]frame + + // extraStrings are strings that get generated during + // parsing but haven't come directly from the trace, so + // they don't appear in strings. + extraStrings []string + extraStringIDs map[string]extraStringID + nextExtra extraStringID + + // expBatches contains extra unparsed data relevant to a specific experiment. + expBatches map[tracev2.Experiment][]ExperimentalBatch +} + +// addExtraString adds an extra string to the evTable and returns +// a unique ID for the string in the table. +func (t *evTable) addExtraString(s string) extraStringID { + if s == "" { + return 0 + } + if t.extraStringIDs == nil { + t.extraStringIDs = make(map[string]extraStringID) + } + if id, ok := t.extraStringIDs[s]; ok { + return id + } + t.nextExtra++ + id := t.nextExtra + t.extraStrings = append(t.extraStrings, s) + t.extraStringIDs[s] = id + return id +} + +// getExtraString returns the extra string for the provided ID. +// The ID must have been produced by addExtraString for this evTable. +func (t *evTable) getExtraString(id extraStringID) string { + if id == 0 { + return "" + } + return t.extraStrings[id-1] +} + +// dataTable is a mapping from EIs to Es. +type dataTable[EI ~uint64, E any] struct { + present []uint8 + dense []E + sparse map[EI]E +} + +// insert tries to add a mapping from id to s. +// +// Returns an error if a mapping for id already exists, regardless +// of whether or not s is the same in content. This should be used +// for validation during parsing. +func (d *dataTable[EI, E]) insert(id EI, data E) error { + if d.sparse == nil { + d.sparse = make(map[EI]E) + } + if existing, ok := d.get(id); ok { + return fmt.Errorf("multiple %Ts with the same ID: id=%d, new=%v, existing=%v", data, id, data, existing) + } + d.sparse[id] = data + return nil +} + +// append adds a new element to the data table and returns its ID. +func (d *dataTable[EI, E]) append(data E) EI { + if d.sparse == nil { + d.sparse = make(map[EI]E) + } + id := EI(len(d.sparse)) + 1 + d.sparse[id] = data + return id +} + +// compactify attempts to compact sparse into dense. +// +// This is intended to be called only once after insertions are done. +func (d *dataTable[EI, E]) compactify() { + if d.sparse == nil || len(d.dense) != 0 { + // Already compactified. + return + } + // Find the range of IDs. + maxID := EI(0) + minID := ^EI(0) + for id := range d.sparse { + if id > maxID { + maxID = id + } + if id < minID { + minID = id + } + } + if maxID >= math.MaxInt { + // We can't create a slice big enough to hold maxID elements + return + } + // We're willing to waste at most 2x memory. + if int(maxID-minID) > max(len(d.sparse), 2*len(d.sparse)) { + return + } + if int(minID) > len(d.sparse) { + return + } + size := int(maxID) + 1 + d.present = make([]uint8, (size+7)/8) + d.dense = make([]E, size) + for id, data := range d.sparse { + d.dense[id] = data + d.present[id/8] |= uint8(1) << (id % 8) + } + d.sparse = nil +} + +// get returns the E for id or false if it doesn't +// exist. This should be used for validation during parsing. +func (d *dataTable[EI, E]) get(id EI) (E, bool) { + if id == 0 { + return *new(E), true + } + if uint64(id) < uint64(len(d.dense)) { + if d.present[id/8]&(uint8(1)<<(id%8)) != 0 { + return d.dense[id], true + } + } else if d.sparse != nil { + if data, ok := d.sparse[id]; ok { + return data, true + } + } + return *new(E), false +} + +// forEach iterates over all ID/value pairs in the data table. +func (d *dataTable[EI, E]) forEach(yield func(EI, E) bool) bool { + for id, value := range d.dense { + if d.present[id/8]&(uint8(1)<<(id%8)) == 0 { + continue + } + if !yield(EI(id), value) { + return false + } + } + if d.sparse == nil { + return true + } + for id, value := range d.sparse { + if !yield(id, value) { + return false + } + } + return true +} + +// mustGet returns the E for id or panics if it fails. +// +// This should only be used if id has already been validated. +func (d *dataTable[EI, E]) mustGet(id EI) E { + data, ok := d.get(id) + if !ok { + panic(fmt.Sprintf("expected id %d in %T table", id, data)) + } + return data +} + +// frequency is nanoseconds per timestamp unit. +type frequency float64 + +// mul multiplies an unprocessed to produce a time in nanoseconds. +func (f frequency) mul(t timestamp) Time { + return Time(float64(t) * float64(f)) +} + +// stringID is an index into the string table for a generation. +type stringID uint64 + +// extraStringID is an index into the extra string table for a generation. +type extraStringID uint64 + +// stackID is an index into the stack table for a generation. +type stackID uint64 + +// cpuSample represents a CPU profiling sample captured by the trace. +type cpuSample struct { + schedCtx + time Time + stack stackID +} + +// asEvent produces a complete Event from a cpuSample. It needs +// the evTable from the generation that created it. +// +// We don't just store it as an Event in generation to minimize +// the amount of pointer data floating around. +func (s cpuSample) asEvent(table *evTable) Event { + // TODO(mknyszek): This is go122-specific, but shouldn't be. + // Generalize this in the future. + e := Event{ + table: table, + ctx: s.schedCtx, + base: baseEvent{ + typ: tracev2.EvCPUSample, + time: s.time, + }, + } + e.base.args[0] = uint64(s.stack) + return e +} + +// stack represents a goroutine stack sample. +type stack struct { + pcs []uint64 +} + +func (s stack) String() string { + var sb strings.Builder + for _, frame := range s.pcs { + fmt.Fprintf(&sb, "\t%#v\n", frame) + } + return sb.String() +} + +// frame represents a single stack frame. +type frame struct { + pc uint64 + funcID stringID + fileID stringID + line uint64 +} diff --git a/go/src/internal/trace/batch.go b/go/src/internal/trace/batch.go new file mode 100644 index 0000000000000000000000000000000000000000..1f50350273d3e7669d3b86d5288a46ca47a68c39 --- /dev/null +++ b/go/src/internal/trace/batch.go @@ -0,0 +1,120 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// timestamp is an unprocessed timestamp. +type timestamp uint64 + +// batch represents a batch of trace events. +// It is unparsed except for its header. +type batch struct { + m ThreadID + time timestamp + data []byte + exp tracev2.Experiment +} + +func (b *batch) isStringsBatch() bool { + return b.exp == tracev2.NoExperiment && len(b.data) > 0 && tracev2.EventType(b.data[0]) == tracev2.EvStrings +} + +func (b *batch) isStacksBatch() bool { + return b.exp == tracev2.NoExperiment && len(b.data) > 0 && tracev2.EventType(b.data[0]) == tracev2.EvStacks +} + +func (b *batch) isCPUSamplesBatch() bool { + return b.exp == tracev2.NoExperiment && len(b.data) > 0 && tracev2.EventType(b.data[0]) == tracev2.EvCPUSamples +} + +func (b *batch) isSyncBatch(ver version.Version) bool { + return (b.exp == tracev2.NoExperiment && len(b.data) > 0) && + ((tracev2.EventType(b.data[0]) == tracev2.EvFrequency && ver < version.Go125) || + (tracev2.EventType(b.data[0]) == tracev2.EvSync && ver >= version.Go125)) +} + +func (b *batch) isEndOfGeneration() bool { + return b.exp == tracev2.NoExperiment && len(b.data) > 0 && tracev2.EventType(b.data[0]) == tracev2.EvEndOfGeneration +} + +// readBatch reads the next full batch from r. +func readBatch(r interface { + io.Reader + io.ByteReader +}) (batch, uint64, error) { + // Read batch header byte. + b, err := r.ReadByte() + if err != nil { + return batch{}, 0, err + } + if typ := tracev2.EventType(b); typ == tracev2.EvEndOfGeneration { + return batch{m: NoThread, exp: tracev2.NoExperiment, data: []byte{b}}, 0, nil + } + if typ := tracev2.EventType(b); typ != tracev2.EvEventBatch && typ != tracev2.EvExperimentalBatch { + return batch{}, 0, fmt.Errorf("expected batch event, got event %d", typ) + } + + // Read the experiment of we have one. + exp := tracev2.NoExperiment + if tracev2.EventType(b) == tracev2.EvExperimentalBatch { + e, err := r.ReadByte() + if err != nil { + return batch{}, 0, err + } + exp = tracev2.Experiment(e) + } + + // Read the batch header: gen (generation), thread (M) ID, base timestamp + // for the batch. + gen, err := binary.ReadUvarint(r) + if err != nil { + return batch{}, gen, fmt.Errorf("error reading batch gen: %w", err) + } + m, err := binary.ReadUvarint(r) + if err != nil { + return batch{}, gen, fmt.Errorf("error reading batch M ID: %w", err) + } + ts, err := binary.ReadUvarint(r) + if err != nil { + return batch{}, gen, fmt.Errorf("error reading batch timestamp: %w", err) + } + + // Read in the size of the batch to follow. + size, err := binary.ReadUvarint(r) + if err != nil { + return batch{}, gen, fmt.Errorf("error reading batch size: %w", err) + } + if size > tracev2.MaxBatchSize { + return batch{}, gen, fmt.Errorf("invalid batch size %d, maximum is %d", size, tracev2.MaxBatchSize) + } + + // Copy out the batch for later processing. + var data bytes.Buffer + data.Grow(int(size)) + n, err := io.CopyN(&data, r, int64(size)) + if n != int64(size) { + return batch{}, gen, fmt.Errorf("failed to read full batch: read %d but wanted %d", n, size) + } + if err != nil { + return batch{}, gen, fmt.Errorf("copying batch data: %w", err) + } + + // Return the batch. + return batch{ + m: ThreadID(m), + time: timestamp(ts), + data: data.Bytes(), + exp: exp, + }, gen, nil +} diff --git a/go/src/internal/trace/batchcursor.go b/go/src/internal/trace/batchcursor.go new file mode 100644 index 0000000000000000000000000000000000000000..8582f30bb06e8800e29d934b3f08665c44fb8cb3 --- /dev/null +++ b/go/src/internal/trace/batchcursor.go @@ -0,0 +1,173 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "cmp" + "encoding/binary" + "fmt" + + "internal/trace/tracev2" +) + +type batchCursor struct { + m ThreadID + lastTs Time + idx int // next index into []batch + dataOff int // next index into batch.data + ev baseEvent // last read event +} + +func (b *batchCursor) nextEvent(batches []batch, freq frequency) (ok bool, err error) { + // Batches should generally always have at least one event, + // but let's be defensive about that and accept empty batches. + for b.idx < len(batches) && len(batches[b.idx].data) == b.dataOff { + b.idx++ + b.dataOff = 0 + b.lastTs = 0 + } + // Have we reached the end of the batches? + if b.idx == len(batches) { + return false, nil + } + // Initialize lastTs if it hasn't been yet. + if b.lastTs == 0 { + b.lastTs = freq.mul(batches[b.idx].time) + } + // Read an event out. + n, tsdiff, err := readTimedBaseEvent(batches[b.idx].data[b.dataOff:], &b.ev) + if err != nil { + return false, err + } + // Complete the timestamp from the cursor's last timestamp. + b.ev.time = freq.mul(tsdiff) + b.lastTs + + // Move the cursor's timestamp forward. + b.lastTs = b.ev.time + + // Move the cursor forward. + b.dataOff += n + return true, nil +} + +func (b *batchCursor) compare(a *batchCursor) int { + return cmp.Compare(b.ev.time, a.ev.time) +} + +// readTimedBaseEvent reads out the raw event data from b +// into e. It does not try to interpret the arguments +// but it does validate that the event is a regular +// event with a timestamp (vs. a structural event). +// +// It requires that the event its reading be timed, which must +// be the case for every event in a plain EventBatch. +func readTimedBaseEvent(b []byte, e *baseEvent) (int, timestamp, error) { + // Get the event type. + typ := tracev2.EventType(b[0]) + specs := tracev2.Specs() + if int(typ) >= len(specs) { + return 0, 0, fmt.Errorf("found invalid event type: %v", typ) + } + e.typ = typ + + // Get spec. + spec := &specs[typ] + if len(spec.Args) == 0 || !spec.IsTimedEvent { + return 0, 0, fmt.Errorf("found event without a timestamp: type=%v", typ) + } + n := 1 + + // Read timestamp diff. + ts, nb := binary.Uvarint(b[n:]) + if nb <= 0 { + return 0, 0, fmt.Errorf("found invalid uvarint for timestamp") + } + n += nb + + // Read the rest of the arguments. + for i := 0; i < len(spec.Args)-1; i++ { + arg, nb := binary.Uvarint(b[n:]) + if nb <= 0 { + return 0, 0, fmt.Errorf("found invalid uvarint") + } + e.args[i] = arg + n += nb + } + return n, timestamp(ts), nil +} + +func heapInsert(heap []*batchCursor, bc *batchCursor) []*batchCursor { + // Add the cursor to the end of the heap. + heap = append(heap, bc) + + // Sift the new entry up to the right place. + heapSiftUp(heap, len(heap)-1) + return heap +} + +func heapUpdate(heap []*batchCursor, i int) { + // Try to sift up. + if heapSiftUp(heap, i) != i { + return + } + // Try to sift down, if sifting up failed. + heapSiftDown(heap, i) +} + +func heapRemove(heap []*batchCursor, i int) []*batchCursor { + // Sift index i up to the root, ignoring actual values. + for i > 0 { + heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2] + i = (i - 1) / 2 + } + // Swap the root with the last element, then remove it. + heap[0], heap[len(heap)-1] = heap[len(heap)-1], heap[0] + heap = heap[:len(heap)-1] + // Sift the root down. + heapSiftDown(heap, 0) + return heap +} + +func heapSiftUp(heap []*batchCursor, i int) int { + for i > 0 && heap[(i-1)/2].ev.time > heap[i].ev.time { + heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2] + i = (i - 1) / 2 + } + return i +} + +func heapSiftDown(heap []*batchCursor, i int) int { + for { + m := min3(heap, i, 2*i+1, 2*i+2) + if m == i { + // Heap invariant already applies. + break + } + heap[i], heap[m] = heap[m], heap[i] + i = m + } + return i +} + +func min3(b []*batchCursor, i0, i1, i2 int) int { + minIdx := i0 + minT := maxTime + if i0 < len(b) { + minT = b[i0].ev.time + } + if i1 < len(b) { + if t := b[i1].ev.time; t < minT { + minT = t + minIdx = i1 + } + } + if i2 < len(b) { + if t := b[i2].ev.time; t < minT { + minT = t + minIdx = i2 + } + } + return minIdx +} diff --git a/go/src/internal/trace/batchcursor_test.go b/go/src/internal/trace/batchcursor_test.go new file mode 100644 index 0000000000000000000000000000000000000000..69731e5254088262d77e488cece1fc186bbec22b --- /dev/null +++ b/go/src/internal/trace/batchcursor_test.go @@ -0,0 +1,126 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "fmt" + "strings" + "testing" + + "slices" +) + +func TestHeap(t *testing.T) { + var heap []*batchCursor + + // Insert a bunch of values into the heap. + checkHeap(t, heap) + heap = heapInsert(heap, makeBatchCursor(5)) + checkHeap(t, heap) + for i := int64(-20); i < 20; i++ { + heap = heapInsert(heap, makeBatchCursor(i)) + checkHeap(t, heap) + } + + // Update an element in the middle to be the new minimum. + for i := range heap { + if heap[i].ev.time == 5 { + heap[i].ev.time = -21 + heapUpdate(heap, i) + break + } + } + checkHeap(t, heap) + if heap[0].ev.time != -21 { + t.Fatalf("heap update failed, expected %d as heap min: %s", -21, heapDebugString(heap)) + } + + // Update the minimum element to be smaller. There should be no change. + heap[0].ev.time = -22 + heapUpdate(heap, 0) + checkHeap(t, heap) + if heap[0].ev.time != -22 { + t.Fatalf("heap update failed, expected %d as heap min: %s", -22, heapDebugString(heap)) + } + + // Update the last element to be larger. There should be no change. + heap[len(heap)-1].ev.time = 21 + heapUpdate(heap, len(heap)-1) + checkHeap(t, heap) + if heap[len(heap)-1].ev.time != 21 { + t.Fatalf("heap update failed, expected %d as heap min: %s", 21, heapDebugString(heap)) + } + + // Update the last element to be smaller. + heap[len(heap)-1].ev.time = 7 + heapUpdate(heap, len(heap)-1) + checkHeap(t, heap) + if heap[len(heap)-1].ev.time == 21 { + t.Fatalf("heap update failed, unexpected %d as heap min: %s", 21, heapDebugString(heap)) + } + + // Remove an element in the middle. + for i := range heap { + if heap[i].ev.time == 5 { + heap = heapRemove(heap, i) + break + } + } + checkHeap(t, heap) + for i := range heap { + if heap[i].ev.time == 5 { + t.Fatalf("failed to remove heap elem with time %d: %s", 5, heapDebugString(heap)) + } + } + + // Remove tail. + heap = heapRemove(heap, len(heap)-1) + checkHeap(t, heap) + + // Remove from the head, and make sure the result is sorted. + l := len(heap) + var removed []*batchCursor + for i := 0; i < l; i++ { + removed = append(removed, heap[0]) + heap = heapRemove(heap, 0) + checkHeap(t, heap) + } + if !slices.IsSortedFunc(removed, (*batchCursor).compare) { + t.Fatalf("heap elements not removed in sorted order, got: %s", heapDebugString(removed)) + } +} + +func makeBatchCursor(v int64) *batchCursor { + return &batchCursor{ev: baseEvent{time: Time(v)}} +} + +func heapDebugString(heap []*batchCursor) string { + var sb strings.Builder + fmt.Fprintf(&sb, "[") + for i := range heap { + if i != 0 { + fmt.Fprintf(&sb, ", ") + } + fmt.Fprintf(&sb, "%d", heap[i].ev.time) + } + fmt.Fprintf(&sb, "]") + return sb.String() +} + +func checkHeap(t *testing.T, heap []*batchCursor) { + t.Helper() + + for i := range heap { + if i == 0 { + continue + } + if heap[(i-1)/2].compare(heap[i]) > 0 { + t.Errorf("heap invariant not maintained between index %d and parent %d: %s", i, i/2, heapDebugString(heap)) + } + } + if t.Failed() { + t.FailNow() + } +} diff --git a/go/src/internal/trace/event.go b/go/src/internal/trace/event.go new file mode 100644 index 0000000000000000000000000000000000000000..a891472962234f98c6d64452a1f67281c190d0e6 --- /dev/null +++ b/go/src/internal/trace/event.go @@ -0,0 +1,1393 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "errors" + "fmt" + "io" + "iter" + "math" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// EventKind indicates the kind of event this is. +// +// Use this information to obtain a more specific event that +// allows access to more detailed information. +type EventKind uint16 + +const ( + EventBad EventKind = iota + + // EventKindSync is an event that indicates a global synchronization + // point in the trace. At the point of a sync event, the + // trace reader can be certain that all resources (e.g. threads, + // goroutines) that have existed until that point have been enumerated. + EventSync + + // EventMetric is an event that represents the value of a metric at + // a particular point in time. + EventMetric + + // EventLabel attaches a label to a resource. + EventLabel + + // EventStackSample represents an execution sample, indicating what a + // thread/proc/goroutine was doing at a particular point in time via + // its backtrace. + // + // Note: Samples should be considered a close approximation of + // what a thread/proc/goroutine was executing at a given point in time. + // These events may slightly contradict the situation StateTransitions + // describe, so they should only be treated as a best-effort annotation. + EventStackSample + + // EventRangeBegin and EventRangeEnd are a pair of generic events representing + // a special range of time. Ranges are named and scoped to some resource + // (identified via ResourceKind). A range that has begun but has not ended + // is considered active. + // + // EvRangeBegin and EvRangeEnd will share the same name, and an End will always + // follow a Begin on the same instance of the resource. The associated + // resource ID can be obtained from the Event. ResourceNone indicates the + // range is globally scoped. That is, any goroutine/proc/thread can start or + // stop, but only one such range may be active at any given time. + // + // EventRangeActive is like EventRangeBegin, but indicates that the range was + // already active. In this case, the resource referenced may not be in the current + // context. + EventRangeBegin + EventRangeActive + EventRangeEnd + + // EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task. + EventTaskBegin + EventTaskEnd + + // EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region. + EventRegionBegin + EventRegionEnd + + // EventLog represents a runtime/trace.Log call. + EventLog + + // EventStateTransition represents a state change for some resource. + EventStateTransition + + // EventExperimental is an experimental event that is unvalidated and exposed in a raw form. + // Users are expected to understand the format and perform their own validation. These events + // may always be safely ignored. + EventExperimental +) + +// String returns a string form of the EventKind. +func (e EventKind) String() string { + if int(e) >= len(eventKindStrings) { + return eventKindStrings[0] + } + return eventKindStrings[e] +} + +var eventKindStrings = [...]string{ + EventBad: "Bad", + EventSync: "Sync", + EventMetric: "Metric", + EventLabel: "Label", + EventStackSample: "StackSample", + EventRangeBegin: "RangeBegin", + EventRangeActive: "RangeActive", + EventRangeEnd: "RangeEnd", + EventTaskBegin: "TaskBegin", + EventTaskEnd: "TaskEnd", + EventRegionBegin: "RegionBegin", + EventRegionEnd: "RegionEnd", + EventLog: "Log", + EventStateTransition: "StateTransition", + EventExperimental: "Experimental", +} + +const maxTime = Time(math.MaxInt64) + +// Time is a timestamp in nanoseconds. +// +// It corresponds to the monotonic clock on the platform that the +// trace was taken, and so is possible to correlate with timestamps +// for other traces taken on the same machine using the same clock +// (i.e. no reboots in between). +// +// The actual absolute value of the timestamp is only meaningful in +// relation to other timestamps from the same clock. +// +// BUG: Timestamps coming from traces on Windows platforms are +// only comparable with timestamps from the same trace. Timestamps +// across traces cannot be compared, because the system clock is +// not used as of Go 1.22. +// +// BUG: Traces produced by Go versions 1.21 and earlier cannot be +// compared with timestamps from other traces taken on the same +// machine. This is because the system clock was not used at all +// to collect those timestamps. +type Time int64 + +// Sub subtracts t0 from t, returning the duration in nanoseconds. +func (t Time) Sub(t0 Time) time.Duration { + return time.Duration(int64(t) - int64(t0)) +} + +// Metric provides details about a Metric event. +type Metric struct { + // Name is the name of the sampled metric. + // + // Names follow the same convention as metric names in the + // runtime/metrics package, meaning they include the unit. + // Names that match with the runtime/metrics package represent + // the same quantity. Note that this corresponds to the + // runtime/metrics package for the Go version this trace was + // collected for. + Name string + + // Value is the sampled value of the metric. + // + // The Value's Kind is tied to the name of the metric, and so is + // guaranteed to be the same for metric samples for the same metric. + Value Value +} + +// Label provides details about a Label event. +type Label struct { + // Label is the label applied to some resource. + Label string + + // Resource is the resource to which this label should be applied. + Resource ResourceID +} + +// Range provides details about a Range event. +type Range struct { + // Name is a human-readable name for the range. + // + // This name can be used to identify the end of the range for the resource + // its scoped to, because only one of each type of range may be active on + // a particular resource. The relevant resource should be obtained from the + // Event that produced these details. The corresponding RangeEnd will have + // an identical name. + Name string + + // Scope is the resource that the range is scoped to. + // + // For example, a ResourceGoroutine scope means that the same goroutine + // must have a start and end for the range, and that goroutine can only + // have one range of a particular name active at any given time. The + // ID that this range is scoped to may be obtained via Event.Goroutine. + // + // The ResourceNone scope means that the range is globally scoped. As a + // result, any goroutine/proc/thread may start or end the range, and only + // one such named range may be active globally at any given time. + // + // For RangeBegin and RangeEnd events, this will always reference some + // resource ID in the current execution context. For RangeActive events, + // this may reference a resource not in the current context. Prefer Scope + // over the current execution context. + Scope ResourceID +} + +// RangeAttribute provides attributes about a completed Range. +type RangeAttribute struct { + // Name is the human-readable name for the range. + Name string + + // Value is the value of the attribute. + Value Value +} + +// TaskID is the internal ID of a task used to disambiguate tasks (even if they +// are of the same type). +type TaskID uint64 + +const ( + // NoTask indicates the lack of a task. + NoTask = TaskID(^uint64(0)) + + // BackgroundTask is the global task that events are attached to if there was + // no other task in the context at the point the event was emitted. + BackgroundTask = TaskID(0) +) + +// Task provides details about a Task event. +type Task struct { + // ID is a unique identifier for the task. + // + // This can be used to associate the beginning of a task with its end. + ID TaskID + + // ParentID is the ID of the parent task. + Parent TaskID + + // Type is the taskType that was passed to runtime/trace.NewTask. + // + // May be "" if a task's TaskBegin event isn't present in the trace. + Type string +} + +// Region provides details about a Region event. +type Region struct { + // Task is the ID of the task this region is associated with. + Task TaskID + + // Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion. + Type string +} + +// Log provides details about a Log event. +type Log struct { + // Task is the ID of the task this region is associated with. + Task TaskID + + // Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf. + Category string + + // Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf. + Message string +} + +// StackSample is used to construct StackSample events via MakeEvent. There are +// no details associated with it, use EventConfig.Stack instead. +type StackSample struct{} + +// MakeStack create a stack from a list of stack frames. +func MakeStack(frames []StackFrame) Stack { + // TODO(felixge): support evTable reuse. + tbl := &evTable{pcs: make(map[uint64]frame)} + tbl.strings.compactify() + tbl.stacks.compactify() + return Stack{table: tbl, id: addStack(tbl, frames)} +} + +// Stack represents a stack. It's really a handle to a stack and it's trivially comparable. +// +// If two Stacks are equal then their Frames are guaranteed to be identical. If they are not +// equal, however, their Frames may still be equal. +type Stack struct { + table *evTable + id stackID +} + +// Frames is an iterator over the frames in a Stack. +func (s Stack) Frames() iter.Seq[StackFrame] { + return func(yield func(StackFrame) bool) { + if s.id == 0 { + return + } + stk := s.table.stacks.mustGet(s.id) + for _, pc := range stk.pcs { + f := s.table.pcs[pc] + sf := StackFrame{ + PC: f.pc, + Func: s.table.strings.mustGet(f.funcID), + File: s.table.strings.mustGet(f.fileID), + Line: f.line, + } + if !yield(sf) { + return + } + } + } +} + +// String returns the stack as a human-readable string. +// +// The format of the string is intended for debugging and is subject to change. +func (s Stack) String() string { + var sb strings.Builder + printStack(&sb, "", s.Frames()) + return sb.String() +} + +func printStack(w io.Writer, prefix string, frames iter.Seq[StackFrame]) { + for f := range frames { + fmt.Fprintf(w, "%s%s @ 0x%x\n", prefix, f.Func, f.PC) + fmt.Fprintf(w, "%s\t%s:%d\n", prefix, f.File, f.Line) + } +} + +// NoStack is a sentinel value that can be compared against any Stack value, indicating +// a lack of a stack trace. +var NoStack = Stack{} + +// StackFrame represents a single frame of a stack. +type StackFrame struct { + // PC is the program counter of the function call if this + // is not a leaf frame. If it's a leaf frame, it's the point + // at which the stack trace was taken. + PC uint64 + + // Func is the name of the function this frame maps to. + Func string + + // File is the file which contains the source code of Func. + File string + + // Line is the line number within File which maps to PC. + Line uint64 +} + +// ExperimentalEvent presents a raw view of an experimental event's arguments and their names. +type ExperimentalEvent struct { + // Name is the name of the event. + Name string + + // Experiment is the name of the experiment this event is a part of. + Experiment string + + // Args lists the names of the event's arguments in order. + Args []string + + // argValues contains the raw integer arguments which are interpreted + // by ArgValue using table. + table *evTable + argValues []uint64 +} + +// ArgValue returns a typed Value for the i'th argument in the experimental event. +func (e ExperimentalEvent) ArgValue(i int) Value { + if i < 0 || i >= len(e.Args) { + panic(fmt.Sprintf("experimental event argument index %d out of bounds [0, %d)", i, len(e.Args))) + } + if strings.HasSuffix(e.Args[i], "string") { + s := e.table.strings.mustGet(stringID(e.argValues[i])) + return StringValue(s) + } + return Uint64Value(e.argValues[i]) +} + +// ExperimentalBatch represents a packet of unparsed data along with metadata about that packet. +type ExperimentalBatch struct { + // Thread is the ID of the thread that produced a packet of data. + Thread ThreadID + + // Data is a packet of unparsed data all produced by one thread. + Data []byte +} + +type EventDetails interface { + Metric | Label | Range | StateTransition | Sync | Task | Region | Log | StackSample +} + +// EventConfig holds the data for constructing a trace event. +type EventConfig[T EventDetails] struct { + // Time is the timestamp of the event. + Time Time + + // Kind is the kind of the event. + Kind EventKind + + // Goroutine is the goroutine ID of the event. + Goroutine GoID + + // Proc is the proc ID of the event. + Proc ProcID + + // Thread is the thread ID of the event. + Thread ThreadID + + // Stack is the stack of the event. + Stack Stack + + // Details is the kind specific details of the event. + Details T +} + +// MakeEvent creates a new trace event from the given configuration. +func MakeEvent[T EventDetails](c EventConfig[T]) (e Event, err error) { + // TODO(felixge): make the evTable reusable. + e = Event{ + table: &evTable{pcs: make(map[uint64]frame), sync: sync{freq: 1}}, + base: baseEvent{time: c.Time}, + ctx: schedCtx{G: c.Goroutine, P: c.Proc, M: c.Thread}, + } + defer func() { + // N.b. evSync is not in tracev2.Specs() + if err != nil || e.base.typ == evSync { + return + } + spec := tracev2.Specs()[e.base.typ] + if len(spec.StackIDs) > 0 && c.Stack != NoStack { + // The stack for the main execution context is always the + // first stack listed in StackIDs. Subtract one from this + // because we've peeled away the timestamp argument. + e.base.args[spec.StackIDs[0]-1] = uint64(addStack(e.table, slices.Collect(c.Stack.Frames()))) + } + + e.table.strings.compactify() + e.table.stacks.compactify() + }() + var defaultKind EventKind + switch c.Kind { + case defaultKind: + return Event{}, fmt.Errorf("the Kind field must be provided") + case EventMetric: + if m, ok := any(c.Details).(Metric); ok { + return makeMetricEvent(e, m) + } + case EventLabel: + if l, ok := any(c.Details).(Label); ok { + return makeLabelEvent(e, l) + } + case EventRangeBegin, EventRangeActive, EventRangeEnd: + if r, ok := any(c.Details).(Range); ok { + return makeRangeEvent(e, c.Kind, r) + } + case EventStateTransition: + if t, ok := any(c.Details).(StateTransition); ok { + return makeStateTransitionEvent(e, t) + } + case EventSync: + if s, ok := any(c.Details).(Sync); ok { + return makeSyncEvent(e, s) + } + case EventTaskBegin, EventTaskEnd: + if t, ok := any(c.Details).(Task); ok { + return makeTaskEvent(e, c.Kind, t) + } + case EventRegionBegin, EventRegionEnd: + if r, ok := any(c.Details).(Region); ok { + return makeRegionEvent(e, c.Kind, r) + } + case EventLog: + if l, ok := any(c.Details).(Log); ok { + return makeLogEvent(e, l) + } + case EventStackSample: + if _, ok := any(c.Details).(StackSample); ok { + return makeStackSampleEvent(e, c.Stack) + } + } + return Event{}, fmt.Errorf("the Kind field %s is incompatible with Details type %T", c.Kind, c.Details) +} + +func makeMetricEvent(e Event, m Metric) (Event, error) { + if m.Value.Kind() != ValueUint64 { + return Event{}, fmt.Errorf("metric value must be a uint64, got: %s", m.Value.String()) + } + switch m.Name { + case "/sched/gomaxprocs:threads": + e.base.typ = tracev2.EvProcsChange + case "/memory/classes/heap/objects:bytes": + e.base.typ = tracev2.EvHeapAlloc + case "/gc/heap/goal:bytes": + e.base.typ = tracev2.EvHeapGoal + default: + return Event{}, fmt.Errorf("unknown metric name: %s", m.Name) + } + e.base.args[0] = uint64(m.Value.Uint64()) + return e, nil +} + +func makeLabelEvent(e Event, l Label) (Event, error) { + if l.Resource.Kind != ResourceGoroutine { + return Event{}, fmt.Errorf("resource must be a goroutine: %s", l.Resource) + } + e.base.typ = tracev2.EvGoLabel + e.base.args[0] = uint64(e.table.strings.append(l.Label)) + // TODO(felixge): check against sched ctx and return error on mismatch + e.ctx.G = l.Resource.Goroutine() + return e, nil +} + +var stwRangeRegexp = regexp.MustCompile(`^stop-the-world \((.*)\)$`) + +// TODO(felixge): should this ever manipulate the e ctx? Or just report mismatches? +func makeRangeEvent(e Event, kind EventKind, r Range) (Event, error) { + // TODO(felixge): Should we add dedicated range kinds rather than using + // string names? + switch r.Name { + case "GC concurrent mark phase": + if r.Scope.Kind != ResourceNone { + return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope) + } + switch kind { + case EventRangeBegin: + e.base.typ = tracev2.EvGCBegin + case EventRangeActive: + e.base.typ = tracev2.EvGCActive + case EventRangeEnd: + e.base.typ = tracev2.EvGCEnd + default: + return Event{}, fmt.Errorf("unexpected range kind: %s", kind) + } + case "GC incremental sweep": + if r.Scope.Kind != ResourceProc { + return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope) + } + switch kind { + case EventRangeBegin: + e.base.typ = tracev2.EvGCSweepBegin + e.ctx.P = r.Scope.Proc() + case EventRangeActive: + e.base.typ = tracev2.EvGCSweepActive + e.base.args[0] = uint64(r.Scope.Proc()) + case EventRangeEnd: + e.base.typ = tracev2.EvGCSweepEnd + // TODO(felixge): check against sched ctx and return error on mismatch + e.ctx.P = r.Scope.Proc() + default: + return Event{}, fmt.Errorf("unexpected range kind: %s", kind) + } + case "GC mark assist": + if r.Scope.Kind != ResourceGoroutine { + return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope) + } + switch kind { + case EventRangeBegin: + e.base.typ = tracev2.EvGCMarkAssistBegin + e.ctx.G = r.Scope.Goroutine() + case EventRangeActive: + e.base.typ = tracev2.EvGCMarkAssistActive + e.base.args[0] = uint64(r.Scope.Goroutine()) + case EventRangeEnd: + e.base.typ = tracev2.EvGCMarkAssistEnd + // TODO(felixge): check against sched ctx and return error on mismatch + e.ctx.G = r.Scope.Goroutine() + default: + return Event{}, fmt.Errorf("unexpected range kind: %s", kind) + } + default: + match := stwRangeRegexp.FindStringSubmatch(r.Name) + if len(match) != 2 { + return Event{}, fmt.Errorf("unexpected range name: %s", r.Name) + } + if r.Scope.Kind != ResourceGoroutine { + return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope) + } + switch kind { + case EventRangeBegin: + e.base.typ = tracev2.EvSTWBegin + // TODO(felixge): check against sched ctx and return error on mismatch + e.ctx.G = r.Scope.Goroutine() + case EventRangeEnd: + e.base.typ = tracev2.EvSTWEnd + // TODO(felixge): check against sched ctx and return error on mismatch + e.ctx.G = r.Scope.Goroutine() + default: + return Event{}, fmt.Errorf("unexpected range kind: %s", kind) + } + e.base.args[0] = uint64(e.table.strings.append(match[1])) + } + return e, nil +} + +func makeStateTransitionEvent(e Event, t StateTransition) (Event, error) { + switch t.Resource.Kind { + case ResourceProc: + from, to := ProcState(t.oldState), ProcState(t.newState) + switch { + case from == ProcIdle && to == ProcIdle: + // TODO(felixge): Could this also be a ProcStatus event? + e.base.typ = tracev2.EvProcSteal + e.base.args[0] = uint64(t.Resource.Proc()) + e.base.extra(version.Go122)[0] = uint64(tracev2.ProcSyscallAbandoned) + case from == ProcIdle && to == ProcRunning: + e.base.typ = tracev2.EvProcStart + e.base.args[0] = uint64(t.Resource.Proc()) + case from == ProcRunning && to == ProcIdle: + e.base.typ = tracev2.EvProcStop + if t.Resource.Proc() != e.ctx.P { + e.base.typ = tracev2.EvProcSteal + e.base.args[0] = uint64(t.Resource.Proc()) + } + default: + e.base.typ = tracev2.EvProcStatus + e.base.args[0] = uint64(t.Resource.Proc()) + e.base.args[1] = uint64(procState2Tracev2ProcStatus[to]) + e.base.extra(version.Go122)[0] = uint64(procState2Tracev2ProcStatus[from]) + return e, nil + } + case ResourceGoroutine: + from, to := GoState(t.oldState), GoState(t.newState) + stack := slices.Collect(t.Stack.Frames()) + goroutine := t.Resource.Goroutine() + + if (from == GoUndetermined || from == to) && from != GoNotExist { + e.base.typ = tracev2.EvGoStatus + if len(stack) > 0 { + e.base.typ = tracev2.EvGoStatusStack + } + e.base.args[0] = uint64(goroutine) + e.base.args[2] = uint64(from)<<32 | uint64(goState2Tracev2GoStatus[to]) + } else { + switch from { + case GoNotExist: + switch to { + case GoWaiting: + e.base.typ = tracev2.EvGoCreateBlocked + e.base.args[0] = uint64(goroutine) + e.base.args[1] = uint64(addStack(e.table, stack)) + case GoRunnable: + e.base.typ = tracev2.EvGoCreate + e.base.args[0] = uint64(goroutine) + e.base.args[1] = uint64(addStack(e.table, stack)) + case GoSyscall: + e.base.typ = tracev2.EvGoCreateSyscall + e.base.args[0] = uint64(goroutine) + default: + return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to) + } + case GoRunnable: + e.base.typ = tracev2.EvGoStart + e.base.args[0] = uint64(goroutine) + case GoRunning: + switch to { + case GoNotExist: + e.base.typ = tracev2.EvGoDestroy + e.ctx.G = goroutine + case GoRunnable: + e.base.typ = tracev2.EvGoStop + e.ctx.G = goroutine + e.base.args[0] = uint64(e.table.strings.append(t.Reason)) + case GoWaiting: + e.base.typ = tracev2.EvGoBlock + e.ctx.G = goroutine + e.base.args[0] = uint64(e.table.strings.append(t.Reason)) + case GoSyscall: + e.base.typ = tracev2.EvGoSyscallBegin + e.ctx.G = goroutine + default: + return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to) + } + case GoSyscall: + switch to { + case GoNotExist: + e.base.typ = tracev2.EvGoDestroySyscall + e.ctx.G = goroutine + case GoRunning: + e.base.typ = tracev2.EvGoSyscallEnd + e.ctx.G = goroutine + case GoRunnable: + e.base.typ = tracev2.EvGoSyscallEndBlocked + e.ctx.G = goroutine + default: + return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to) + } + case GoWaiting: + switch to { + case GoRunnable: + e.base.typ = tracev2.EvGoUnblock + e.base.args[0] = uint64(goroutine) + default: + return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to) + } + default: + return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to) + } + } + default: + return Event{}, fmt.Errorf("unsupported state transition resource: %s", t.Resource) + } + return e, nil +} + +func makeSyncEvent(e Event, s Sync) (Event, error) { + e.base.typ = evSync + e.base.args[0] = uint64(s.N) + if e.table.expBatches == nil { + e.table.expBatches = make(map[tracev2.Experiment][]ExperimentalBatch) + } + for name, batches := range s.ExperimentalBatches { + var found bool + for id, exp := range tracev2.Experiments() { + if exp == name { + found = true + e.table.expBatches[tracev2.Experiment(id)] = batches + break + } + } + if !found { + return Event{}, fmt.Errorf("unknown experiment: %s", name) + } + } + if s.ClockSnapshot != nil { + e.table.hasClockSnapshot = true + e.table.snapWall = s.ClockSnapshot.Wall + e.table.snapMono = s.ClockSnapshot.Mono + // N.b. MakeEvent sets e.table.freq to 1. + e.table.snapTime = timestamp(s.ClockSnapshot.Trace) + } + return e, nil +} + +func makeTaskEvent(e Event, kind EventKind, t Task) (Event, error) { + if t.ID == NoTask { + return Event{}, errors.New("task ID cannot be NoTask") + } + e.base.args[0] = uint64(t.ID) + switch kind { + case EventTaskBegin: + e.base.typ = tracev2.EvUserTaskBegin + e.base.args[1] = uint64(t.Parent) + e.base.args[2] = uint64(e.table.strings.append(t.Type)) + case EventTaskEnd: + e.base.typ = tracev2.EvUserTaskEnd + e.base.extra(version.Go122)[0] = uint64(t.Parent) + e.base.extra(version.Go122)[1] = uint64(e.table.addExtraString(t.Type)) + default: + // TODO(felixge): also do this for ranges? + panic("unexpected task kind") + } + return e, nil +} + +func makeRegionEvent(e Event, kind EventKind, r Region) (Event, error) { + e.base.args[0] = uint64(r.Task) + e.base.args[1] = uint64(e.table.strings.append(r.Type)) + switch kind { + case EventRegionBegin: + e.base.typ = tracev2.EvUserRegionBegin + case EventRegionEnd: + e.base.typ = tracev2.EvUserRegionEnd + default: + panic("unexpected region kind") + } + return e, nil +} + +func makeLogEvent(e Event, l Log) (Event, error) { + e.base.typ = tracev2.EvUserLog + e.base.args[0] = uint64(l.Task) + e.base.args[1] = uint64(e.table.strings.append(l.Category)) + e.base.args[2] = uint64(e.table.strings.append(l.Message)) + return e, nil +} + +func makeStackSampleEvent(e Event, s Stack) (Event, error) { + e.base.typ = tracev2.EvCPUSample + frames := slices.Collect(s.Frames()) + e.base.args[0] = uint64(addStack(e.table, frames)) + return e, nil +} + +func addStack(table *evTable, frames []StackFrame) stackID { + var pcs []uint64 + for _, f := range frames { + table.pcs[f.PC] = frame{ + pc: f.PC, + funcID: table.strings.append(f.Func), + fileID: table.strings.append(f.File), + line: f.Line, + } + pcs = append(pcs, f.PC) + } + return table.stacks.append(stack{pcs: pcs}) +} + +// Event represents a single event in the trace. +type Event struct { + table *evTable + ctx schedCtx + base baseEvent +} + +// Kind returns the kind of event that this is. +func (e Event) Kind() EventKind { + return tracev2Type2Kind[e.base.typ] +} + +// Time returns the timestamp of the event. +func (e Event) Time() Time { + return e.base.time +} + +// Goroutine returns the ID of the goroutine that was executing when +// this event happened. It describes part of the execution context +// for this event. +// +// Note that for goroutine state transitions this always refers to the +// state before the transition. For example, if a goroutine is just +// starting to run on this thread and/or proc, then this will return +// NoGoroutine. In this case, the goroutine starting to run will be +// can be found at Event.StateTransition().Resource. +func (e Event) Goroutine() GoID { + return e.ctx.G +} + +// Proc returns the ID of the proc this event event pertains to. +// +// Note that for proc state transitions this always refers to the +// state before the transition. For example, if a proc is just +// starting to run on this thread, then this will return NoProc. +func (e Event) Proc() ProcID { + return e.ctx.P +} + +// Thread returns the ID of the thread this event pertains to. +// +// Note that for thread state transitions this always refers to the +// state before the transition. For example, if a thread is just +// starting to run, then this will return NoThread. +// +// Note: tracking thread state is not currently supported, so this +// will always return a valid thread ID. However thread state transitions +// may be tracked in the future, and callers must be robust to this +// possibility. +func (e Event) Thread() ThreadID { + return e.ctx.M +} + +// Stack returns a handle to a stack associated with the event. +// +// This represents a stack trace at the current moment in time for +// the current execution context. +func (e Event) Stack() Stack { + if e.base.typ == evSync { + return NoStack + } + if e.base.typ == tracev2.EvCPUSample { + return Stack{table: e.table, id: stackID(e.base.args[0])} + } + spec := tracev2.Specs()[e.base.typ] + if len(spec.StackIDs) == 0 { + return NoStack + } + // The stack for the main execution context is always the + // first stack listed in StackIDs. Subtract one from this + // because we've peeled away the timestamp argument. + id := stackID(e.base.args[spec.StackIDs[0]-1]) + if id == 0 { + return NoStack + } + return Stack{table: e.table, id: id} +} + +// Metric returns details about a Metric event. +// +// Panics if Kind != EventMetric. +func (e Event) Metric() Metric { + if e.Kind() != EventMetric { + panic("Metric called on non-Metric event") + } + var m Metric + switch e.base.typ { + case tracev2.EvProcsChange: + m.Name = "/sched/gomaxprocs:threads" + m.Value = Uint64Value(e.base.args[0]) + case tracev2.EvHeapAlloc: + m.Name = "/memory/classes/heap/objects:bytes" + m.Value = Uint64Value(e.base.args[0]) + case tracev2.EvHeapGoal: + m.Name = "/gc/heap/goal:bytes" + m.Value = Uint64Value(e.base.args[0]) + default: + panic(fmt.Sprintf("internal error: unexpected wire-format event type for Metric kind: %d", e.base.typ)) + } + return m +} + +// Label returns details about a Label event. +// +// Panics if Kind != EventLabel. +func (e Event) Label() Label { + if e.Kind() != EventLabel { + panic("Label called on non-Label event") + } + if e.base.typ != tracev2.EvGoLabel { + panic(fmt.Sprintf("internal error: unexpected wire-format event type for Label kind: %d", e.base.typ)) + } + return Label{ + Label: e.table.strings.mustGet(stringID(e.base.args[0])), + Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)}, + } +} + +// Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event. +// +// Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd. +func (e Event) Range() Range { + if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd { + panic("Range called on non-Range event") + } + var r Range + switch e.base.typ { + case tracev2.EvSTWBegin, tracev2.EvSTWEnd: + // N.B. ordering.advance smuggles in the STW reason as e.base.args[0] + // for tracev2.EvSTWEnd (it's already there for Begin). + r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")" + r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())} + case tracev2.EvGCBegin, tracev2.EvGCActive, tracev2.EvGCEnd: + r.Name = "GC concurrent mark phase" + r.Scope = ResourceID{Kind: ResourceNone} + case tracev2.EvGCSweepBegin, tracev2.EvGCSweepActive, tracev2.EvGCSweepEnd: + r.Name = "GC incremental sweep" + r.Scope = ResourceID{Kind: ResourceProc} + if e.base.typ == tracev2.EvGCSweepActive { + r.Scope.id = int64(e.base.args[0]) + } else { + r.Scope.id = int64(e.Proc()) + } + case tracev2.EvGCMarkAssistBegin, tracev2.EvGCMarkAssistActive, tracev2.EvGCMarkAssistEnd: + r.Name = "GC mark assist" + r.Scope = ResourceID{Kind: ResourceGoroutine} + if e.base.typ == tracev2.EvGCMarkAssistActive { + r.Scope.id = int64(e.base.args[0]) + } else { + r.Scope.id = int64(e.Goroutine()) + } + default: + panic(fmt.Sprintf("internal error: unexpected wire-event type for Range kind: %d", e.base.typ)) + } + return r +} + +// RangeAttributes returns attributes for a completed range. +// +// Panics if Kind != EventRangeEnd. +func (e Event) RangeAttributes() []RangeAttribute { + if e.Kind() != EventRangeEnd { + panic("Range called on non-Range event") + } + if e.base.typ != tracev2.EvGCSweepEnd { + return nil + } + return []RangeAttribute{ + { + Name: "bytes swept", + Value: Uint64Value(e.base.args[0]), + }, + { + Name: "bytes reclaimed", + Value: Uint64Value(e.base.args[1]), + }, + } +} + +// Task returns details about a TaskBegin or TaskEnd event. +// +// Panics if Kind != EventTaskBegin and Kind != EventTaskEnd. +func (e Event) Task() Task { + if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd { + panic("Task called on non-Task event") + } + parentID := NoTask + var typ string + switch e.base.typ { + case tracev2.EvUserTaskBegin: + parentID = TaskID(e.base.args[1]) + typ = e.table.strings.mustGet(stringID(e.base.args[2])) + case tracev2.EvUserTaskEnd: + parentID = TaskID(e.base.extra(version.Go122)[0]) + typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1])) + default: + panic(fmt.Sprintf("internal error: unexpected wire-format event type for Task kind: %d", e.base.typ)) + } + return Task{ + ID: TaskID(e.base.args[0]), + Parent: parentID, + Type: typ, + } +} + +// Region returns details about a RegionBegin or RegionEnd event. +// +// Panics if Kind != EventRegionBegin and Kind != EventRegionEnd. +func (e Event) Region() Region { + if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd { + panic("Region called on non-Region event") + } + if e.base.typ != tracev2.EvUserRegionBegin && e.base.typ != tracev2.EvUserRegionEnd { + panic(fmt.Sprintf("internal error: unexpected wire-format event type for Region kind: %d", e.base.typ)) + } + return Region{ + Task: TaskID(e.base.args[0]), + Type: e.table.strings.mustGet(stringID(e.base.args[1])), + } +} + +// Log returns details about a Log event. +// +// Panics if Kind != EventLog. +func (e Event) Log() Log { + if e.Kind() != EventLog { + panic("Log called on non-Log event") + } + if e.base.typ != tracev2.EvUserLog { + panic(fmt.Sprintf("internal error: unexpected wire-format event type for Log kind: %d", e.base.typ)) + } + return Log{ + Task: TaskID(e.base.args[0]), + Category: e.table.strings.mustGet(stringID(e.base.args[1])), + Message: e.table.strings.mustGet(stringID(e.base.args[2])), + } +} + +// StateTransition returns details about a StateTransition event. +// +// Panics if Kind != EventStateTransition. +func (e Event) StateTransition() StateTransition { + if e.Kind() != EventStateTransition { + panic("StateTransition called on non-StateTransition event") + } + var s StateTransition + switch e.base.typ { + case tracev2.EvProcStart: + s = MakeProcStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning) + case tracev2.EvProcStop: + s = MakeProcStateTransition(e.ctx.P, ProcRunning, ProcIdle) + case tracev2.EvProcSteal: + // N.B. ordering.advance populates e.base.extra. + beforeState := ProcRunning + if tracev2.ProcStatus(e.base.extra(version.Go122)[0]) == tracev2.ProcSyscallAbandoned { + // We've lost information because this ProcSteal advanced on a + // SyscallAbandoned state. Treat the P as idle because ProcStatus + // treats SyscallAbandoned as Idle. Otherwise we'll have an invalid + // transition. + beforeState = ProcIdle + } + s = MakeProcStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle) + case tracev2.EvProcStatus: + // N.B. ordering.advance populates e.base.extra. + s = MakeProcStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), tracev2ProcStatus2ProcState[e.base.args[1]]) + case tracev2.EvGoCreate, tracev2.EvGoCreateBlocked: + status := GoRunnable + if e.base.typ == tracev2.EvGoCreateBlocked { + status = GoWaiting + } + s = MakeGoStateTransition(GoID(e.base.args[0]), GoNotExist, status) + s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])} + case tracev2.EvGoCreateSyscall: + s = MakeGoStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall) + case tracev2.EvGoStart: + s = MakeGoStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning) + case tracev2.EvGoDestroy: + s = MakeGoStateTransition(e.ctx.G, GoRunning, GoNotExist) + case tracev2.EvGoDestroySyscall: + s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoNotExist) + case tracev2.EvGoStop: + s = MakeGoStateTransition(e.ctx.G, GoRunning, GoRunnable) + s.Reason = e.table.strings.mustGet(stringID(e.base.args[0])) + s.Stack = e.Stack() // This event references the resource the event happened on. + case tracev2.EvGoBlock: + s = MakeGoStateTransition(e.ctx.G, GoRunning, GoWaiting) + s.Reason = e.table.strings.mustGet(stringID(e.base.args[0])) + s.Stack = e.Stack() // This event references the resource the event happened on. + case tracev2.EvGoUnblock, tracev2.EvGoSwitch, tracev2.EvGoSwitchDestroy: + // N.B. GoSwitch and GoSwitchDestroy both emit additional events, but + // the first thing they both do is unblock the goroutine they name, + // identically to an unblock event (even their arguments match). + s = MakeGoStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable) + case tracev2.EvGoSyscallBegin: + s = MakeGoStateTransition(e.ctx.G, GoRunning, GoSyscall) + s.Stack = e.Stack() // This event references the resource the event happened on. + case tracev2.EvGoSyscallEnd: + s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoRunning) + case tracev2.EvGoSyscallEndBlocked: + s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoRunnable) + case tracev2.EvGoStatus, tracev2.EvGoStatusStack: + packedStatus := e.base.args[2] + from, to := packedStatus>>32, packedStatus&((1<<32)-1) + s = MakeGoStateTransition(GoID(e.base.args[0]), GoState(from), tracev2GoStatus2GoState[to]) + s.Stack = e.Stack() // This event references the resource the event happened on. + default: + panic(fmt.Sprintf("internal error: unexpected wire-format event type for StateTransition kind: %d", e.base.typ)) + } + return s +} + +// Sync returns details that are relevant for the following events, up to but excluding the +// next EventSync event. +func (e Event) Sync() Sync { + if e.Kind() != EventSync { + panic("Sync called on non-Sync event") + } + s := Sync{N: int(e.base.args[0])} + if e.table != nil { + expBatches := make(map[string][]ExperimentalBatch) + for exp, batches := range e.table.expBatches { + expBatches[tracev2.Experiments()[exp]] = batches + } + s.ExperimentalBatches = expBatches + if e.table.hasClockSnapshot { + s.ClockSnapshot = &ClockSnapshot{ + Trace: e.table.freq.mul(e.table.snapTime), + Wall: e.table.snapWall, + Mono: e.table.snapMono, + } + } + } + return s +} + +// Sync contains details potentially relevant to all the following events, up to but excluding +// the next EventSync event. +type Sync struct { + // N indicates that this is the Nth sync event in the trace. + N int + + // ClockSnapshot represents a near-simultaneous clock reading of several + // different system clocks. The snapshot can be used as a reference to + // convert timestamps to different clocks, which is helpful for correlating + // timestamps with data captured by other tools. The value is nil for traces + // before go1.25. + ClockSnapshot *ClockSnapshot + + // ExperimentalBatches contain all the unparsed batches of data for a given experiment. + ExperimentalBatches map[string][]ExperimentalBatch +} + +// ClockSnapshot represents a near-simultaneous clock reading of several +// different system clocks. The snapshot can be used as a reference to convert +// timestamps to different clocks, which is helpful for correlating timestamps +// with data captured by other tools. +type ClockSnapshot struct { + // Trace is a snapshot of the trace clock. + Trace Time + + // Wall is a snapshot of the system's wall clock. + Wall time.Time + + // Mono is a snapshot of the system's monotonic clock. + Mono uint64 +} + +// Experimental returns a view of the raw event for an experimental event. +// +// Panics if Kind != EventExperimental. +func (e Event) Experimental() ExperimentalEvent { + if e.Kind() != EventExperimental { + panic("Experimental called on non-Experimental event") + } + spec := tracev2.Specs()[e.base.typ] + argNames := spec.Args[1:] // Skip timestamp; already handled. + return ExperimentalEvent{ + Name: spec.Name, + Experiment: tracev2.Experiments()[spec.Experiment], + Args: argNames, + table: e.table, + argValues: e.base.args[:len(argNames)], + } +} + +const evSync = ^tracev2.EventType(0) + +var tracev2Type2Kind = [...]EventKind{ + tracev2.EvCPUSample: EventStackSample, + tracev2.EvProcsChange: EventMetric, + tracev2.EvProcStart: EventStateTransition, + tracev2.EvProcStop: EventStateTransition, + tracev2.EvProcSteal: EventStateTransition, + tracev2.EvProcStatus: EventStateTransition, + tracev2.EvGoCreate: EventStateTransition, + tracev2.EvGoCreateSyscall: EventStateTransition, + tracev2.EvGoStart: EventStateTransition, + tracev2.EvGoDestroy: EventStateTransition, + tracev2.EvGoDestroySyscall: EventStateTransition, + tracev2.EvGoStop: EventStateTransition, + tracev2.EvGoBlock: EventStateTransition, + tracev2.EvGoUnblock: EventStateTransition, + tracev2.EvGoSyscallBegin: EventStateTransition, + tracev2.EvGoSyscallEnd: EventStateTransition, + tracev2.EvGoSyscallEndBlocked: EventStateTransition, + tracev2.EvGoStatus: EventStateTransition, + tracev2.EvSTWBegin: EventRangeBegin, + tracev2.EvSTWEnd: EventRangeEnd, + tracev2.EvGCActive: EventRangeActive, + tracev2.EvGCBegin: EventRangeBegin, + tracev2.EvGCEnd: EventRangeEnd, + tracev2.EvGCSweepActive: EventRangeActive, + tracev2.EvGCSweepBegin: EventRangeBegin, + tracev2.EvGCSweepEnd: EventRangeEnd, + tracev2.EvGCMarkAssistActive: EventRangeActive, + tracev2.EvGCMarkAssistBegin: EventRangeBegin, + tracev2.EvGCMarkAssistEnd: EventRangeEnd, + tracev2.EvHeapAlloc: EventMetric, + tracev2.EvHeapGoal: EventMetric, + tracev2.EvGoLabel: EventLabel, + tracev2.EvUserTaskBegin: EventTaskBegin, + tracev2.EvUserTaskEnd: EventTaskEnd, + tracev2.EvUserRegionBegin: EventRegionBegin, + tracev2.EvUserRegionEnd: EventRegionEnd, + tracev2.EvUserLog: EventLog, + tracev2.EvGoSwitch: EventStateTransition, + tracev2.EvGoSwitchDestroy: EventStateTransition, + tracev2.EvGoCreateBlocked: EventStateTransition, + tracev2.EvGoStatusStack: EventStateTransition, + tracev2.EvSpan: EventExperimental, + tracev2.EvSpanAlloc: EventExperimental, + tracev2.EvSpanFree: EventExperimental, + tracev2.EvHeapObject: EventExperimental, + tracev2.EvHeapObjectAlloc: EventExperimental, + tracev2.EvHeapObjectFree: EventExperimental, + tracev2.EvGoroutineStack: EventExperimental, + tracev2.EvGoroutineStackAlloc: EventExperimental, + tracev2.EvGoroutineStackFree: EventExperimental, + evSync: EventSync, +} + +var tracev2GoStatus2GoState = [...]GoState{ + tracev2.GoRunnable: GoRunnable, + tracev2.GoRunning: GoRunning, + tracev2.GoWaiting: GoWaiting, + tracev2.GoSyscall: GoSyscall, +} + +var goState2Tracev2GoStatus = [...]tracev2.GoStatus{ + GoRunnable: tracev2.GoRunnable, + GoRunning: tracev2.GoRunning, + GoWaiting: tracev2.GoWaiting, + GoSyscall: tracev2.GoSyscall, +} + +var tracev2ProcStatus2ProcState = [...]ProcState{ + tracev2.ProcRunning: ProcRunning, + tracev2.ProcIdle: ProcIdle, + tracev2.ProcSyscall: ProcRunning, + tracev2.ProcSyscallAbandoned: ProcIdle, +} + +var procState2Tracev2ProcStatus = [...]tracev2.ProcStatus{ + ProcRunning: tracev2.ProcRunning, + ProcIdle: tracev2.ProcIdle, + // TODO(felixge): how to map ProcSyscall and ProcSyscallAbandoned? +} + +// String returns the event as a human-readable string. +// +// The format of the string is intended for debugging and is subject to change. +func (e Event) String() string { + var sb strings.Builder + fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine()) + fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time()) + // Kind-specific fields. + switch kind := e.Kind(); kind { + case EventMetric: + m := e.Metric() + v := m.Value.String() + if m.Value.Kind() == ValueString { + v = strconv.Quote(v) + } + fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, m.Value) + case EventLabel: + l := e.Label() + fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource) + case EventRangeBegin, EventRangeActive, EventRangeEnd: + r := e.Range() + fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope) + if kind == EventRangeEnd { + fmt.Fprintf(&sb, " Attributes=[") + for i, attr := range e.RangeAttributes() { + if i != 0 { + fmt.Fprintf(&sb, " ") + } + fmt.Fprintf(&sb, "%q=%s", attr.Name, attr.Value) + } + fmt.Fprintf(&sb, "]") + } + case EventTaskBegin, EventTaskEnd: + t := e.Task() + fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type) + case EventRegionBegin, EventRegionEnd: + r := e.Region() + fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type) + case EventLog: + l := e.Log() + fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message) + case EventStateTransition: + s := e.StateTransition() + switch s.Resource.Kind { + case ResourceGoroutine: + id := s.Resource.Goroutine() + old, new := s.Goroutine() + fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new) + case ResourceProc: + id := s.Resource.Proc() + old, new := s.Proc() + fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new) + } + fmt.Fprintf(&sb, " Reason=%q", s.Reason) + if s.Stack != NoStack { + fmt.Fprintln(&sb) + fmt.Fprintln(&sb, "TransitionStack=") + printStack(&sb, "\t", s.Stack.Frames()) + } + case EventExperimental: + r := e.Experimental() + fmt.Fprintf(&sb, " Name=%s Args=[", r.Name) + for i, arg := range r.Args { + if i != 0 { + fmt.Fprintf(&sb, ", ") + } + fmt.Fprintf(&sb, "%s=%s", arg, r.ArgValue(i).String()) + } + fmt.Fprintf(&sb, "]") + case EventSync: + s := e.Sync() + fmt.Fprintf(&sb, " N=%d", s.N) + if s.ClockSnapshot != nil { + fmt.Fprintf(&sb, " Trace=%d Mono=%d Wall=%s", + s.ClockSnapshot.Trace, + s.ClockSnapshot.Mono, + s.ClockSnapshot.Wall.Format(time.RFC3339Nano), + ) + } + } + if stk := e.Stack(); stk != NoStack { + fmt.Fprintln(&sb) + fmt.Fprintln(&sb, "Stack=") + printStack(&sb, "\t", stk.Frames()) + } + return sb.String() +} + +// validateTableIDs checks to make sure lookups in e.table +// will work. +func (e Event) validateTableIDs() error { + if e.base.typ == evSync { + return nil + } + spec := tracev2.Specs()[e.base.typ] + + // Check stacks. + for _, i := range spec.StackIDs { + id := stackID(e.base.args[i-1]) + _, ok := e.table.stacks.get(id) + if !ok { + return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name) + } + } + // N.B. Strings referenced by stack frames are validated + // early on, when reading the stacks in to begin with. + + // Check strings. + for _, i := range spec.StringIDs { + id := stringID(e.base.args[i-1]) + _, ok := e.table.strings.get(id) + if !ok { + return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name) + } + } + return nil +} + +func syncEvent(table *evTable, ts Time, n int) Event { + ev := Event{ + table: table, + ctx: schedCtx{ + G: NoGoroutine, + P: NoProc, + M: NoThread, + }, + base: baseEvent{ + typ: evSync, + time: ts, + }, + } + ev.base.args[0] = uint64(n) + return ev +} diff --git a/go/src/internal/trace/event_test.go b/go/src/internal/trace/event_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ae01af2c19f7cc043c0a19454df5c61d1edc019 --- /dev/null +++ b/go/src/internal/trace/event_test.go @@ -0,0 +1,784 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "fmt" + "internal/diff" + "reflect" + "slices" + "testing" + "time" +) + +func TestMakeEvent(t *testing.T) { + checkTime := func(t *testing.T, ev Event, want Time) { + t.Helper() + if ev.Time() != want { + t.Errorf("expected time to be %d, got %d", want, ev.Time()) + } + } + checkValid := func(t *testing.T, err error, valid bool) bool { + t.Helper() + if valid && err == nil { + return true + } + if valid && err != nil { + t.Errorf("expected no error, got %v", err) + } else if !valid && err == nil { + t.Errorf("expected error, got %v", err) + } + return false + } + type stackType string + const ( + schedStack stackType = "sched stack" + stStack stackType = "state transition stack" + ) + checkStack := func(t *testing.T, got Stack, want Stack, which stackType) { + t.Helper() + diff := diff.Diff("want", []byte(want.String()), "got", []byte(got.String())) + if len(diff) > 0 { + t.Errorf("unexpected %s: %s", which, diff) + } + } + stk1 := MakeStack([]StackFrame{ + {PC: 1, Func: "foo", File: "foo.go", Line: 10}, + {PC: 2, Func: "bar", File: "bar.go", Line: 20}, + }) + stk2 := MakeStack([]StackFrame{ + {PC: 1, Func: "foo", File: "foo.go", Line: 10}, + {PC: 2, Func: "bar", File: "bar.go", Line: 20}, + }) + + t.Run("Metric", func(t *testing.T) { + tests := []struct { + name string + metric string + val uint64 + stack Stack + valid bool + }{ + {name: "gomaxprocs", metric: "/sched/gomaxprocs:threads", valid: true, val: 1, stack: NoStack}, + {name: "gomaxprocs with stack", metric: "/sched/gomaxprocs:threads", valid: true, val: 1, stack: stk1}, + {name: "heap objects", metric: "/memory/classes/heap/objects:bytes", valid: true, val: 2, stack: NoStack}, + {name: "heap goal", metric: "/gc/heap/goal:bytes", valid: true, val: 3, stack: NoStack}, + {name: "invalid metric", metric: "/test", valid: false, val: 4, stack: NoStack}, + } + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Metric]{ + Kind: EventMetric, + Time: Time(42 + i), + Details: Metric{Name: test.metric, Value: Uint64Value(test.val)}, + Stack: test.stack, + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + checkStack(t, ev.Stack(), test.stack, schedStack) + got := ev.Metric() + if got.Name != test.metric { + t.Errorf("expected name to be %q, got %q", test.metric, got.Name) + } + if got.Value.Uint64() != test.val { + t.Errorf("expected value to be %d, got %d", test.val, got.Value.Uint64()) + } + }) + } + }) + + t.Run("Label", func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Label]{ + Kind: EventLabel, + Time: 42, + Details: Label{Label: "test", Resource: MakeResourceID(GoID(23))}, + }) + if !checkValid(t, err, true) { + return + } + label := ev.Label() + if label.Label != "test" { + t.Errorf("expected label to be test, got %q", label.Label) + } + if label.Resource.Kind != ResourceGoroutine { + t.Errorf("expected label resource to be goroutine, got %d", label.Resource.Kind) + } + if label.Resource.id != 23 { + t.Errorf("expected label resource to be 23, got %d", label.Resource.id) + } + checkTime(t, ev, 42) + }) + + t.Run("Range", func(t *testing.T) { + tests := []struct { + kind EventKind + name string + scope ResourceID + valid bool + }{ + {kind: EventRangeBegin, name: "GC concurrent mark phase", scope: ResourceID{}, valid: true}, + {kind: EventRangeActive, name: "GC concurrent mark phase", scope: ResourceID{}, valid: true}, + {kind: EventRangeEnd, name: "GC concurrent mark phase", scope: ResourceID{}, valid: true}, + {kind: EventMetric, name: "GC concurrent mark phase", scope: ResourceID{}, valid: false}, + {kind: EventRangeBegin, name: "GC concurrent mark phase - INVALID", scope: ResourceID{}, valid: false}, + + {kind: EventRangeBegin, name: "GC incremental sweep", scope: MakeResourceID(ProcID(1)), valid: true}, + {kind: EventRangeActive, name: "GC incremental sweep", scope: MakeResourceID(ProcID(2)), valid: true}, + {kind: EventRangeEnd, name: "GC incremental sweep", scope: MakeResourceID(ProcID(3)), valid: true}, + {kind: EventMetric, name: "GC incremental sweep", scope: MakeResourceID(ProcID(4)), valid: false}, + {kind: EventRangeBegin, name: "GC incremental sweep - INVALID", scope: MakeResourceID(ProcID(5)), valid: false}, + + {kind: EventRangeBegin, name: "GC mark assist", scope: MakeResourceID(GoID(1)), valid: true}, + {kind: EventRangeActive, name: "GC mark assist", scope: MakeResourceID(GoID(2)), valid: true}, + {kind: EventRangeEnd, name: "GC mark assist", scope: MakeResourceID(GoID(3)), valid: true}, + {kind: EventMetric, name: "GC mark assist", scope: MakeResourceID(GoID(4)), valid: false}, + {kind: EventRangeBegin, name: "GC mark assist - INVALID", scope: MakeResourceID(GoID(5)), valid: false}, + + {kind: EventRangeBegin, name: "stop-the-world (for a good reason)", scope: MakeResourceID(GoID(1)), valid: true}, + {kind: EventRangeActive, name: "stop-the-world (for a good reason)", scope: MakeResourceID(GoID(2)), valid: false}, + {kind: EventRangeEnd, name: "stop-the-world (for a good reason)", scope: MakeResourceID(GoID(3)), valid: true}, + {kind: EventMetric, name: "stop-the-world (for a good reason)", scope: MakeResourceID(GoID(4)), valid: false}, + {kind: EventRangeBegin, name: "stop-the-world (for a good reason) - INVALID", scope: MakeResourceID(GoID(5)), valid: false}, + } + + for i, test := range tests { + name := fmt.Sprintf("%s/%s/%s", test.kind, test.name, test.scope) + t.Run(name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Range]{ + Time: Time(42 + i), + Kind: test.kind, + Details: Range{Name: test.name, Scope: test.scope}, + }) + if !checkValid(t, err, test.valid) { + return + } + got := ev.Range() + if got.Name != test.name { + t.Errorf("expected name to be %q, got %q", test.name, got.Name) + } + if ev.Kind() != test.kind { + t.Errorf("expected kind to be %s, got %s", test.kind, ev.Kind()) + } + if got.Scope.String() != test.scope.String() { + t.Errorf("expected scope to be %s, got %s", test.scope.String(), got.Scope.String()) + } + checkTime(t, ev, Time(42+i)) + }) + } + }) + + t.Run("GoroutineTransition", func(t *testing.T) { + const anotherG = 999 // indicates hat sched g is different from transition g + tests := []struct { + name string + g GoID + stack Stack + stG GoID + from GoState + to GoState + reason string + stStack Stack + valid bool + }{ + { + name: "EvGoCreate", + g: anotherG, + stack: stk1, + stG: 1, + from: GoNotExist, + to: GoRunnable, + reason: "", + stStack: stk2, + valid: true, + }, + { + name: "EvGoCreateBlocked", + g: anotherG, + stack: stk1, + stG: 2, + from: GoNotExist, + to: GoWaiting, + reason: "", + stStack: stk2, + valid: true, + }, + { + name: "EvGoCreateSyscall", + g: anotherG, + stack: NoStack, + stG: 3, + from: GoNotExist, + to: GoSyscall, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "EvGoStart", + g: anotherG, + stack: NoStack, + stG: 4, + from: GoRunnable, + to: GoRunning, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "EvGoDestroy", + g: 5, + stack: NoStack, + stG: 5, + from: GoRunning, + to: GoNotExist, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "EvGoDestroySyscall", + g: 6, + stack: NoStack, + stG: 6, + from: GoSyscall, + to: GoNotExist, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "EvGoStop", + g: 7, + stack: stk1, + stG: 7, + from: GoRunning, + to: GoRunnable, + reason: "preempted", + stStack: stk1, + valid: true, + }, + { + name: "EvGoBlock", + g: 8, + stack: stk1, + stG: 8, + from: GoRunning, + to: GoWaiting, + reason: "blocked", + stStack: stk1, + valid: true, + }, + { + name: "EvGoUnblock", + g: 9, + stack: stk1, + stG: anotherG, + from: GoWaiting, + to: GoRunnable, + reason: "", + stStack: NoStack, + valid: true, + }, + // N.b. EvGoUnblock, EvGoSwitch and EvGoSwitchDestroy cannot be + // distinguished from each other in Event form, so MakeEvent only + // produces EvGoUnblock events for Waiting -> Runnable transitions. + { + name: "EvGoSyscallBegin", + g: 10, + stack: stk1, + stG: 10, + from: GoRunning, + to: GoSyscall, + reason: "", + stStack: stk1, + valid: true, + }, + { + name: "EvGoSyscallEnd", + g: 11, + stack: NoStack, + stG: 11, + from: GoSyscall, + to: GoRunning, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "EvGoSyscallEndBlocked", + g: 12, + stack: NoStack, + stG: 12, + from: GoSyscall, + to: GoRunnable, + reason: "", + stStack: NoStack, + valid: true, + }, + // TODO(felixge): Use coverage testsing to check if we need all these GoStatus/GoStatusStack cases + { + name: "GoStatus Undetermined->Waiting", + g: anotherG, + stack: NoStack, + stG: 13, + from: GoUndetermined, + to: GoWaiting, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "GoStatus Undetermined->Running", + g: anotherG, + stack: NoStack, + stG: 14, + from: GoUndetermined, + to: GoRunning, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "GoStatusStack Undetermined->Waiting", + g: anotherG, + stack: stk1, + stG: 15, + from: GoUndetermined, + to: GoWaiting, + reason: "", + stStack: stk1, + valid: true, + }, + { + name: "GoStatusStack Undetermined->Runnable", + g: anotherG, + stack: stk1, + stG: 16, + from: GoUndetermined, + to: GoRunnable, + reason: "", + stStack: stk1, + valid: true, + }, + { + name: "GoStatus Runnable->Runnable", + g: anotherG, + stack: NoStack, + stG: 17, + from: GoRunnable, + to: GoRunnable, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "GoStatus Runnable->Running", + g: anotherG, + stack: NoStack, + stG: 18, + from: GoRunnable, + to: GoRunning, + reason: "", + stStack: NoStack, + valid: true, + }, + { + name: "invalid NotExits->NotExists", + g: anotherG, + stack: stk1, + stG: 18, + from: GoNotExist, + to: GoNotExist, + reason: "", + stStack: NoStack, + valid: false, + }, + { + name: "invalid Running->Undetermined", + g: anotherG, + stack: stk1, + stG: 19, + from: GoRunning, + to: GoUndetermined, + reason: "", + stStack: NoStack, + valid: false, + }, + } + + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + st := MakeGoStateTransition(test.stG, test.from, test.to) + st.Stack = test.stStack + st.Reason = test.reason + ev, err := MakeEvent(EventConfig[StateTransition]{ + Kind: EventStateTransition, + Time: Time(42 + i), + Goroutine: test.g, + Stack: test.stack, + Details: st, + }) + if !checkValid(t, err, test.valid) { + return + } + checkStack(t, ev.Stack(), test.stack, schedStack) + if ev.Goroutine() != test.g { + t.Errorf("expected goroutine to be %d, got %d", test.g, ev.Goroutine()) + } + got := ev.StateTransition() + if got.Resource.Goroutine() != test.stG { + t.Errorf("expected resource to be %d, got %d", test.stG, got.Resource.Goroutine()) + } + from, to := got.Goroutine() + if from != test.from { + t.Errorf("from got=%s want=%s", from, test.from) + } + if to != test.to { + t.Errorf("to got=%s want=%s", to, test.to) + } + if got.Reason != test.reason { + t.Errorf("expected reason to be %s, got %s", test.reason, got.Reason) + } + checkStack(t, got.Stack, test.stStack, stStack) + checkTime(t, ev, Time(42+i)) + }) + } + }) + + t.Run("ProcTransition", func(t *testing.T) { + tests := []struct { + name string + proc ProcID + schedProc ProcID + from ProcState + to ProcState + valid bool + }{ + {name: "ProcStart", proc: 1, schedProc: 99, from: ProcIdle, to: ProcRunning, valid: true}, + {name: "ProcStop", proc: 2, schedProc: 2, from: ProcRunning, to: ProcIdle, valid: true}, + {name: "ProcSteal", proc: 3, schedProc: 99, from: ProcRunning, to: ProcIdle, valid: true}, + {name: "ProcSteal lost info", proc: 4, schedProc: 99, from: ProcIdle, to: ProcIdle, valid: true}, + {name: "ProcStatus", proc: 5, schedProc: 99, from: ProcUndetermined, to: ProcRunning, valid: true}, + } + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + st := MakeProcStateTransition(test.proc, test.from, test.to) + ev, err := MakeEvent(EventConfig[StateTransition]{ + Kind: EventStateTransition, + Time: Time(42 + i), + Proc: test.schedProc, + Details: st, + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + gotSt := ev.StateTransition() + from, to := gotSt.Proc() + if from != test.from { + t.Errorf("from got=%s want=%s", from, test.from) + } + if to != test.to { + t.Errorf("to got=%s want=%s", to, test.to) + } + if ev.Proc() != test.schedProc { + t.Errorf("expected proc to be %d, got %d", test.schedProc, ev.Proc()) + } + if gotSt.Resource.Proc() != test.proc { + t.Errorf("expected resource to be %d, got %d", test.proc, gotSt.Resource.Proc()) + } + }) + } + }) + + t.Run("Sync", func(t *testing.T) { + tests := []struct { + name string + kind EventKind + n int + clock *ClockSnapshot + batches map[string][]ExperimentalBatch + valid bool + }{ + { + name: "invalid kind", + n: 1, + valid: false, + }, + { + name: "N", + kind: EventSync, + n: 1, + batches: map[string][]ExperimentalBatch{}, + valid: true, + }, + { + name: "N+ClockSnapshot", + kind: EventSync, + n: 1, + batches: map[string][]ExperimentalBatch{}, + clock: &ClockSnapshot{ + Trace: 1, + Wall: time.Unix(59, 123456789), + Mono: 2, + }, + valid: true, + }, + { + name: "N+Batches", + kind: EventSync, + n: 1, + batches: map[string][]ExperimentalBatch{ + "AllocFree": {{Thread: 1, Data: []byte{1, 2, 3}}}, + }, + valid: true, + }, + { + name: "unknown experiment", + kind: EventSync, + n: 1, + batches: map[string][]ExperimentalBatch{ + "does-not-exist": {{Thread: 1, Data: []byte{1, 2, 3}}}, + }, + valid: false, + }, + } + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Sync]{ + Kind: test.kind, + Time: Time(42 + i), + Details: Sync{N: test.n, ClockSnapshot: test.clock, ExperimentalBatches: test.batches}, + }) + if !checkValid(t, err, test.valid) { + return + } + got := ev.Sync() + checkTime(t, ev, Time(42+i)) + if got.N != test.n { + t.Errorf("expected N to be %d, got %d", test.n, got.N) + } + if test.clock != nil && got.ClockSnapshot == nil { + t.Fatalf("expected ClockSnapshot to be non-nil") + } else if test.clock == nil && got.ClockSnapshot != nil { + t.Fatalf("expected ClockSnapshot to be nil") + } else if test.clock != nil && got.ClockSnapshot != nil { + if got.ClockSnapshot.Trace != test.clock.Trace { + t.Errorf("expected ClockSnapshot.Trace to be %d, got %d", test.clock.Trace, got.ClockSnapshot.Trace) + } + if !got.ClockSnapshot.Wall.Equal(test.clock.Wall) { + t.Errorf("expected ClockSnapshot.Wall to be %s, got %s", test.clock.Wall, got.ClockSnapshot.Wall) + } + if got.ClockSnapshot.Mono != test.clock.Mono { + t.Errorf("expected ClockSnapshot.Mono to be %d, got %d", test.clock.Mono, got.ClockSnapshot.Mono) + } + } + if !reflect.DeepEqual(got.ExperimentalBatches, test.batches) { + t.Errorf("expected ExperimentalBatches to be %#v, got %#v", test.batches, got.ExperimentalBatches) + } + }) + } + }) + + t.Run("Task", func(t *testing.T) { + tests := []struct { + name string + kind EventKind + id TaskID + parent TaskID + typ string + valid bool + }{ + {name: "no task", kind: EventTaskBegin, id: NoTask, parent: 1, typ: "type-0", valid: false}, + {name: "invalid kind", kind: EventMetric, id: 1, parent: 2, typ: "type-1", valid: false}, + {name: "EvUserTaskBegin", kind: EventTaskBegin, id: 2, parent: 3, typ: "type-2", valid: true}, + {name: "EvUserTaskEnd", kind: EventTaskEnd, id: 3, parent: 4, typ: "type-3", valid: true}, + {name: "no parent", kind: EventTaskBegin, id: 4, parent: NoTask, typ: "type-4", valid: true}, + } + + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Task]{ + Kind: test.kind, + Time: Time(42 + i), + Details: Task{ID: test.id, Parent: test.parent, Type: test.typ}, + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + got := ev.Task() + if got.ID != test.id { + t.Errorf("expected ID to be %d, got %d", test.id, got.ID) + } + if got.Parent != test.parent { + t.Errorf("expected Parent to be %d, got %d", test.parent, got.Parent) + } + if got.Type != test.typ { + t.Errorf("expected Type to be %s, got %s", test.typ, got.Type) + } + }) + } + }) + + t.Run("Region", func(t *testing.T) { + tests := []struct { + name string + kind EventKind + task TaskID + typ string + valid bool + }{ + {name: "invalid kind", kind: EventMetric, task: 1, typ: "type-1", valid: false}, + {name: "EvUserRegionBegin", kind: EventRegionBegin, task: 2, typ: "type-2", valid: true}, + {name: "EvUserRegionEnd", kind: EventRegionEnd, task: 3, typ: "type-3", valid: true}, + } + + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Region]{ + Kind: test.kind, + Time: Time(42 + i), + Details: Region{Task: test.task, Type: test.typ}, + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + got := ev.Region() + if got.Task != test.task { + t.Errorf("expected Task to be %d, got %d", test.task, got.Task) + } + if got.Type != test.typ { + t.Errorf("expected Type to be %s, got %s", test.typ, got.Type) + } + }) + } + }) + + t.Run("Log", func(t *testing.T) { + tests := []struct { + name string + kind EventKind + task TaskID + category string + message string + valid bool + }{ + {name: "invalid kind", kind: EventMetric, task: 1, category: "category-1", message: "message-1", valid: false}, + {name: "basic", kind: EventLog, task: 2, category: "category-2", message: "message-2", valid: true}, + } + + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[Log]{ + Kind: test.kind, + Time: Time(42 + i), + Details: Log{Task: test.task, Category: test.category, Message: test.message}, + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + got := ev.Log() + if got.Task != test.task { + t.Errorf("expected Task to be %d, got %d", test.task, got.Task) + } + if got.Category != test.category { + t.Errorf("expected Category to be %s, got %s", test.category, got.Category) + } + if got.Message != test.message { + t.Errorf("expected Message to be %s, got %s", test.message, got.Message) + } + }) + } + + }) + + t.Run("StackSample", func(t *testing.T) { + tests := []struct { + name string + kind EventKind + stack Stack + valid bool + }{ + {name: "invalid kind", kind: EventMetric, stack: stk1, valid: false}, + {name: "basic", kind: EventStackSample, stack: stk1, valid: true}, + } + + for i, test := range tests { + t.Run(test.name, func(t *testing.T) { + ev, err := MakeEvent(EventConfig[StackSample]{ + Kind: test.kind, + Time: Time(42 + i), + Stack: test.stack, + // N.b. Details defaults to StackSample{}, so we can + // omit it here. + }) + if !checkValid(t, err, test.valid) { + return + } + checkTime(t, ev, Time(42+i)) + got := ev.Stack() + checkStack(t, got, test.stack, schedStack) + }) + } + + }) +} + +func TestMakeStack(t *testing.T) { + frames := []StackFrame{ + {PC: 1, Func: "foo", File: "foo.go", Line: 10}, + {PC: 2, Func: "bar", File: "bar.go", Line: 20}, + } + got := slices.Collect(MakeStack(frames).Frames()) + if len(got) != len(frames) { + t.Errorf("got=%d want=%d", len(got), len(frames)) + } + for i := range got { + if got[i] != frames[i] { + t.Errorf("got=%v want=%v", got[i], frames[i]) + } + } +} + +func TestPanicEvent(t *testing.T) { + // Use a sync event for this because it doesn't have any extra metadata. + ev := syncEvent(nil, 0, 0) + + mustPanic(t, func() { + _ = ev.Range() + }) + mustPanic(t, func() { + _ = ev.Metric() + }) + mustPanic(t, func() { + _ = ev.Log() + }) + mustPanic(t, func() { + _ = ev.Task() + }) + mustPanic(t, func() { + _ = ev.Region() + }) + mustPanic(t, func() { + _ = ev.Label() + }) + mustPanic(t, func() { + _ = ev.RangeAttributes() + }) +} + +func mustPanic(t *testing.T, f func()) { + defer func() { + if r := recover(); r == nil { + t.Fatal("failed to panic") + } + }() + f() +} diff --git a/go/src/internal/trace/export_reader_test.go b/go/src/internal/trace/export_reader_test.go new file mode 100644 index 0000000000000000000000000000000000000000..042c70864cf8a83efbeec11c70e5a95e59dc737e --- /dev/null +++ b/go/src/internal/trace/export_reader_test.go @@ -0,0 +1,12 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import "internal/trace/version" + +// GoVersion is the version set in the trace header. +func (r *Reader) GoVersion() version.Version { + return r.version +} diff --git a/go/src/internal/trace/export_test.go b/go/src/internal/trace/export_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4f494ee8cbad2d4dc628e750f27803ebab89dc80 --- /dev/null +++ b/go/src/internal/trace/export_test.go @@ -0,0 +1,7 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +var BandsPerSeries = bandsPerSeries diff --git a/go/src/internal/trace/gc.go b/go/src/internal/trace/gc.go new file mode 100644 index 0000000000000000000000000000000000000000..46890e784df24cf84e7584926c26c031ae0a5e53 --- /dev/null +++ b/go/src/internal/trace/gc.go @@ -0,0 +1,929 @@ +// 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 trace + +import ( + "container/heap" + "math" + "sort" + "strings" + "time" +) + +// MutatorUtil is a change in mutator utilization at a particular +// time. Mutator utilization functions are represented as a +// time-ordered []MutatorUtil. +type MutatorUtil struct { + Time int64 + // Util is the mean mutator utilization starting at Time. This + // is in the range [0, 1]. + Util float64 +} + +// UtilFlags controls the behavior of MutatorUtilization. +type UtilFlags int + +const ( + // UtilSTW means utilization should account for STW events. + // This includes non-GC STW events, which are typically user-requested. + UtilSTW UtilFlags = 1 << iota + // UtilBackground means utilization should account for + // background mark workers. + UtilBackground + // UtilAssist means utilization should account for mark + // assists. + UtilAssist + // UtilSweep means utilization should account for sweeping. + UtilSweep + + // UtilPerProc means each P should be given a separate + // utilization function. Otherwise, there is a single function + // and each P is given a fraction of the utilization. + UtilPerProc +) + +// MutatorUtilizationV2 returns a set of mutator utilization functions +// for the given v2 trace, passed as an io.Reader. Each function will +// always end with 0 utilization. The bounds of each function are implicit +// in the first and last event; outside of these bounds each function is +// undefined. +// +// If the UtilPerProc flag is not given, this always returns a single +// utilization function. Otherwise, it returns one function per P. +func MutatorUtilizationV2(events []Event, flags UtilFlags) [][]MutatorUtil { + // Set up a bunch of analysis state. + type perP struct { + // gc > 0 indicates that GC is active on this P. + gc int + // series the logical series number for this P. This + // is necessary because Ps may be removed and then + // re-added, and then the new P needs a new series. + series int + } + type procsCount struct { + // time at which procs changed. + time int64 + // n is the number of procs at that point. + n int + } + out := [][]MutatorUtil{} + stw := 0 + ps := []perP{} + inGC := make(map[GoID]bool) + states := make(map[GoID]GoState) + bgMark := make(map[GoID]bool) + procs := []procsCount{} + nSync := 0 + + // Helpers. + handleSTW := func(r Range) bool { + return flags&UtilSTW != 0 && isGCSTW(r) + } + handleMarkAssist := func(r Range) bool { + return flags&UtilAssist != 0 && isGCMarkAssist(r) + } + handleSweep := func(r Range) bool { + return flags&UtilSweep != 0 && isGCSweep(r) + } + + // Iterate through the trace, tracking mutator utilization. + var lastEv *Event + for i := range events { + ev := &events[i] + lastEv = ev + + // Process the event. + switch ev.Kind() { + case EventSync: + nSync = ev.Sync().N + case EventMetric: + m := ev.Metric() + if m.Name != "/sched/gomaxprocs:threads" { + break + } + gomaxprocs := int(m.Value.Uint64()) + if len(ps) > gomaxprocs { + if flags&UtilPerProc != 0 { + // End each P's series. + for _, p := range ps[gomaxprocs:] { + out[p.series] = addUtil(out[p.series], MutatorUtil{int64(ev.Time()), 0}) + } + } + ps = ps[:gomaxprocs] + } + for len(ps) < gomaxprocs { + // Start new P's series. + series := 0 + if flags&UtilPerProc != 0 || len(out) == 0 { + series = len(out) + out = append(out, []MutatorUtil{{int64(ev.Time()), 1}}) + } + ps = append(ps, perP{series: series}) + } + if len(procs) == 0 || gomaxprocs != procs[len(procs)-1].n { + procs = append(procs, procsCount{time: int64(ev.Time()), n: gomaxprocs}) + } + } + if len(ps) == 0 { + // We can't start doing any analysis until we see what GOMAXPROCS is. + // It will show up very early in the trace, but we need to be robust to + // something else being emitted beforehand. + continue + } + + switch ev.Kind() { + case EventRangeActive: + if nSync > 1 { + // If we've seen a full generation, then we can be sure we're not finding out + // about something late; we have complete information after that point, and these + // active events will just be redundant. + break + } + // This range is active back to the start of the trace. We're failing to account + // for this since we just found out about it now. Fix up the mutator utilization. + // + // N.B. A trace can't start during a STW, so we don't handle it here. + r := ev.Range() + switch { + case handleMarkAssist(r): + if !states[ev.Goroutine()].Executing() { + // If the goroutine isn't executing, then the fact that it was in mark + // assist doesn't actually count. + break + } + // This G has been in a mark assist *and running on its P* since the start + // of the trace. + fallthrough + case handleSweep(r): + // This P has been in sweep (or mark assist, from above) in the start of the trace. + // + // We don't need to do anything if UtilPerProc is set. If we get an event like + // this for a running P, it must show up the first time a P is mentioned. Therefore, + // this P won't actually have any MutatorUtils on its list yet. + // + // However, if UtilPerProc isn't set, then we probably have data from other procs + // and from previous events. We need to fix that up. + if flags&UtilPerProc != 0 { + break + } + // Subtract out 1/gomaxprocs mutator utilization for all time periods + // from the beginning of the trace until now. + mi, pi := 0, 0 + for mi < len(out[0]) { + if pi < len(procs)-1 && procs[pi+1].time < out[0][mi].Time { + pi++ + continue + } + out[0][mi].Util -= float64(1) / float64(procs[pi].n) + if out[0][mi].Util < 0 { + out[0][mi].Util = 0 + } + mi++ + } + } + // After accounting for the portion we missed, this just acts like the + // beginning of a new range. + fallthrough + case EventRangeBegin: + r := ev.Range() + if handleSTW(r) { + stw++ + } else if handleSweep(r) { + ps[ev.Proc()].gc++ + } else if handleMarkAssist(r) { + ps[ev.Proc()].gc++ + if g := r.Scope.Goroutine(); g != NoGoroutine { + inGC[g] = true + } + } + case EventRangeEnd: + r := ev.Range() + if handleSTW(r) { + stw-- + } else if handleSweep(r) { + ps[ev.Proc()].gc-- + } else if handleMarkAssist(r) { + ps[ev.Proc()].gc-- + if g := r.Scope.Goroutine(); g != NoGoroutine { + delete(inGC, g) + } + } + case EventStateTransition: + st := ev.StateTransition() + if st.Resource.Kind != ResourceGoroutine { + break + } + old, new := st.Goroutine() + g := st.Resource.Goroutine() + if inGC[g] || bgMark[g] { + if !old.Executing() && new.Executing() { + // Started running while doing GC things. + ps[ev.Proc()].gc++ + } else if old.Executing() && !new.Executing() { + // Stopped running while doing GC things. + ps[ev.Proc()].gc-- + } + } + states[g] = new + case EventLabel: + l := ev.Label() + if flags&UtilBackground != 0 && strings.HasPrefix(l.Label, "GC ") && l.Label != "GC (idle)" { + // Background mark worker. + // + // If we're in per-proc mode, we don't + // count dedicated workers because + // they kick all of the goroutines off + // that P, so don't directly + // contribute to goroutine latency. + if !(flags&UtilPerProc != 0 && l.Label == "GC (dedicated)") { + bgMark[ev.Goroutine()] = true + ps[ev.Proc()].gc++ + } + } + } + + if flags&UtilPerProc == 0 { + // Compute the current average utilization. + if len(ps) == 0 { + continue + } + gcPs := 0 + if stw > 0 { + gcPs = len(ps) + } else { + for i := range ps { + if ps[i].gc > 0 { + gcPs++ + } + } + } + mu := MutatorUtil{int64(ev.Time()), 1 - float64(gcPs)/float64(len(ps))} + + // Record the utilization change. (Since + // len(ps) == len(out), we know len(out) > 0.) + out[0] = addUtil(out[0], mu) + } else { + // Check for per-P utilization changes. + for i := range ps { + p := &ps[i] + util := 1.0 + if stw > 0 || p.gc > 0 { + util = 0.0 + } + out[p.series] = addUtil(out[p.series], MutatorUtil{int64(ev.Time()), util}) + } + } + } + + // No events in the stream. + if lastEv == nil { + return nil + } + + // Add final 0 utilization event to any remaining series. This + // is important to mark the end of the trace. The exact value + // shouldn't matter since no window should extend beyond this, + // but using 0 is symmetric with the start of the trace. + mu := MutatorUtil{int64(lastEv.Time()), 0} + for i := range ps { + out[ps[i].series] = addUtil(out[ps[i].series], mu) + } + return out +} + +func addUtil(util []MutatorUtil, mu MutatorUtil) []MutatorUtil { + if len(util) > 0 { + if mu.Util == util[len(util)-1].Util { + // No change. + return util + } + if mu.Time == util[len(util)-1].Time { + // Take the lowest utilization at a time stamp. + if mu.Util < util[len(util)-1].Util { + util[len(util)-1] = mu + } + return util + } + } + return append(util, mu) +} + +// totalUtil is total utilization, measured in nanoseconds. This is a +// separate type primarily to distinguish it from mean utilization, +// which is also a float64. +type totalUtil float64 + +func totalUtilOf(meanUtil float64, dur int64) totalUtil { + return totalUtil(meanUtil * float64(dur)) +} + +// mean returns the mean utilization over dur. +func (u totalUtil) mean(dur time.Duration) float64 { + return float64(u) / float64(dur) +} + +// An MMUCurve is the minimum mutator utilization curve across +// multiple window sizes. +type MMUCurve struct { + series []mmuSeries +} + +type mmuSeries struct { + util []MutatorUtil + // sums[j] is the cumulative sum of util[:j]. + sums []totalUtil + // bands summarizes util in non-overlapping bands of duration + // bandDur. + bands []mmuBand + // bandDur is the duration of each band. + bandDur int64 +} + +type mmuBand struct { + // minUtil is the minimum instantaneous mutator utilization in + // this band. + minUtil float64 + // cumUtil is the cumulative total mutator utilization between + // time 0 and the left edge of this band. + cumUtil totalUtil + + // integrator is the integrator for the left edge of this + // band. + integrator integrator +} + +// NewMMUCurve returns an MMU curve for the given mutator utilization +// function. +func NewMMUCurve(utils [][]MutatorUtil) *MMUCurve { + series := make([]mmuSeries, len(utils)) + for i, util := range utils { + series[i] = newMMUSeries(util) + } + return &MMUCurve{series} +} + +// bandsPerSeries is the number of bands to divide each series into. +// This is only changed by tests. +var bandsPerSeries = 1000 + +func newMMUSeries(util []MutatorUtil) mmuSeries { + // Compute cumulative sum. + sums := make([]totalUtil, len(util)) + var prev MutatorUtil + var sum totalUtil + for j, u := range util { + sum += totalUtilOf(prev.Util, u.Time-prev.Time) + sums[j] = sum + prev = u + } + + // Divide the utilization curve up into equal size + // non-overlapping "bands" and compute a summary for each of + // these bands. + // + // Compute the duration of each band. + numBands := bandsPerSeries + if numBands > len(util) { + // There's no point in having lots of bands if there + // aren't many events. + numBands = len(util) + } + dur := util[len(util)-1].Time - util[0].Time + bandDur := (dur + int64(numBands) - 1) / int64(numBands) + if bandDur < 1 { + bandDur = 1 + } + // Compute the bands. There are numBands+1 bands in order to + // record the final cumulative sum. + bands := make([]mmuBand, numBands+1) + s := mmuSeries{util, sums, bands, bandDur} + leftSum := integrator{&s, 0} + for i := range bands { + startTime, endTime := s.bandTime(i) + cumUtil := leftSum.advance(startTime) + predIdx := leftSum.pos + minUtil := 1.0 + for i := predIdx; i < len(util) && util[i].Time < endTime; i++ { + minUtil = math.Min(minUtil, util[i].Util) + } + bands[i] = mmuBand{minUtil, cumUtil, leftSum} + } + + return s +} + +func (s *mmuSeries) bandTime(i int) (start, end int64) { + start = int64(i)*s.bandDur + s.util[0].Time + end = start + s.bandDur + return +} + +type bandUtil struct { + // Utilization series index + series int + // Band index + i int + // Lower bound of mutator utilization for all windows + // with a left edge in this band. + utilBound float64 +} + +type bandUtilHeap []bandUtil + +func (h bandUtilHeap) Len() int { + return len(h) +} + +func (h bandUtilHeap) Less(i, j int) bool { + return h[i].utilBound < h[j].utilBound +} + +func (h bandUtilHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *bandUtilHeap) Push(x any) { + *h = append(*h, x.(bandUtil)) +} + +func (h *bandUtilHeap) Pop() any { + x := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return x +} + +// UtilWindow is a specific window at Time. +type UtilWindow struct { + Time int64 + // MutatorUtil is the mean mutator utilization in this window. + MutatorUtil float64 +} + +type utilHeap []UtilWindow + +func (h utilHeap) Len() int { + return len(h) +} + +func (h utilHeap) Less(i, j int) bool { + if h[i].MutatorUtil != h[j].MutatorUtil { + return h[i].MutatorUtil > h[j].MutatorUtil + } + return h[i].Time > h[j].Time +} + +func (h utilHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *utilHeap) Push(x any) { + *h = append(*h, x.(UtilWindow)) +} + +func (h *utilHeap) Pop() any { + x := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return x +} + +// An accumulator takes a windowed mutator utilization function and +// tracks various statistics for that function. +type accumulator struct { + mmu float64 + + // bound is the mutator utilization bound where adding any + // mutator utilization above this bound cannot affect the + // accumulated statistics. + bound float64 + + // Worst N window tracking + nWorst int + wHeap utilHeap + + // Mutator utilization distribution tracking + mud *mud + // preciseMass is the distribution mass that must be precise + // before accumulation is stopped. + preciseMass float64 + // lastTime and lastMU are the previous point added to the + // windowed mutator utilization function. + lastTime int64 + lastMU float64 +} + +// resetTime declares a discontinuity in the windowed mutator +// utilization function by resetting the current time. +func (acc *accumulator) resetTime() { + // This only matters for distribution collection, since that's + // the only thing that depends on the progression of the + // windowed mutator utilization function. + acc.lastTime = math.MaxInt64 +} + +// addMU adds a point to the windowed mutator utilization function at +// (time, mu). This must be called for monotonically increasing values +// of time. +// +// It returns true if further calls to addMU would be pointless. +func (acc *accumulator) addMU(time int64, mu float64, window time.Duration) bool { + if mu < acc.mmu { + acc.mmu = mu + } + acc.bound = acc.mmu + + if acc.nWorst == 0 { + // If the minimum has reached zero, it can't go any + // lower, so we can stop early. + return mu == 0 + } + + // Consider adding this window to the n worst. + if len(acc.wHeap) < acc.nWorst || mu < acc.wHeap[0].MutatorUtil { + // This window is lower than the K'th worst window. + // + // Check if there's any overlapping window + // already in the heap and keep whichever is + // worse. + for i, ui := range acc.wHeap { + if time+int64(window) > ui.Time && ui.Time+int64(window) > time { + if ui.MutatorUtil <= mu { + // Keep the first window. + goto keep + } else { + // Replace it with this window. + heap.Remove(&acc.wHeap, i) + break + } + } + } + + heap.Push(&acc.wHeap, UtilWindow{time, mu}) + if len(acc.wHeap) > acc.nWorst { + heap.Pop(&acc.wHeap) + } + keep: + } + + if len(acc.wHeap) < acc.nWorst { + // We don't have N windows yet, so keep accumulating. + acc.bound = 1.0 + } else { + // Anything above the least worst window has no effect. + acc.bound = math.Max(acc.bound, acc.wHeap[0].MutatorUtil) + } + + if acc.mud != nil { + if acc.lastTime != math.MaxInt64 { + // Update distribution. + acc.mud.add(acc.lastMU, mu, float64(time-acc.lastTime)) + } + acc.lastTime, acc.lastMU = time, mu + if _, mudBound, ok := acc.mud.approxInvCumulativeSum(); ok { + acc.bound = math.Max(acc.bound, mudBound) + } else { + // We haven't accumulated enough total precise + // mass yet to even reach our goal, so keep + // accumulating. + acc.bound = 1 + } + // It's not worth checking percentiles every time, so + // just keep accumulating this band. + return false + } + + // If we've found enough 0 utilizations, we can stop immediately. + return len(acc.wHeap) == acc.nWorst && acc.wHeap[0].MutatorUtil == 0 +} + +// MMU returns the minimum mutator utilization for the given time +// window. This is the minimum utilization for all windows of this +// duration across the execution. The returned value is in the range +// [0, 1]. +func (c *MMUCurve) MMU(window time.Duration) (mmu float64) { + acc := accumulator{mmu: 1.0, bound: 1.0} + c.mmu(window, &acc) + return acc.mmu +} + +// Examples returns n specific examples of the lowest mutator +// utilization for the given window size. The returned windows will be +// disjoint (otherwise there would be a huge number of +// mostly-overlapping windows at the single lowest point). There are +// no guarantees on which set of disjoint windows this returns. +func (c *MMUCurve) Examples(window time.Duration, n int) (worst []UtilWindow) { + acc := accumulator{mmu: 1.0, bound: 1.0, nWorst: n} + c.mmu(window, &acc) + sort.Sort(sort.Reverse(acc.wHeap)) + return ([]UtilWindow)(acc.wHeap) +} + +// MUD returns mutator utilization distribution quantiles for the +// given window size. +// +// The mutator utilization distribution is the distribution of mean +// mutator utilization across all windows of the given window size in +// the trace. +// +// The minimum mutator utilization is the minimum (0th percentile) of +// this distribution. (However, if only the minimum is desired, it's +// more efficient to use the MMU method.) +func (c *MMUCurve) MUD(window time.Duration, quantiles []float64) []float64 { + if len(quantiles) == 0 { + return []float64{} + } + + // Each unrefined band contributes a known total mass to the + // distribution (bandDur except at the end), but in an unknown + // way. However, we know that all the mass it contributes must + // be at or above its worst-case mean mutator utilization. + // + // Hence, we refine bands until the highest desired + // distribution quantile is less than the next worst-case mean + // mutator utilization. At this point, all further + // contributions to the distribution must be beyond the + // desired quantile and hence cannot affect it. + // + // First, find the highest desired distribution quantile. + maxQ := quantiles[0] + for _, q := range quantiles { + if q > maxQ { + maxQ = q + } + } + // The distribution's mass is in units of time (it's not + // normalized because this would make it more annoying to + // account for future contributions of unrefined bands). The + // total final mass will be the duration of the trace itself + // minus the window size. Using this, we can compute the mass + // corresponding to quantile maxQ. + var duration int64 + for _, s := range c.series { + duration1 := s.util[len(s.util)-1].Time - s.util[0].Time + if duration1 >= int64(window) { + duration += duration1 - int64(window) + } + } + qMass := float64(duration) * maxQ + + // Accumulate the MUD until we have precise information for + // everything to the left of qMass. + acc := accumulator{mmu: 1.0, bound: 1.0, preciseMass: qMass, mud: new(mud)} + acc.mud.setTrackMass(qMass) + c.mmu(window, &acc) + + // Evaluate the quantiles on the accumulated MUD. + out := make([]float64, len(quantiles)) + for i := range out { + mu, _ := acc.mud.invCumulativeSum(float64(duration) * quantiles[i]) + if math.IsNaN(mu) { + // There are a few legitimate ways this can + // happen: + // + // 1. If the window is the full trace + // duration, then the windowed MU function is + // only defined at a single point, so the MU + // distribution is not well-defined. + // + // 2. If there are no events, then the MU + // distribution has no mass. + // + // Either way, all of the quantiles will have + // converged toward the MMU at this point. + mu = acc.mmu + } + out[i] = mu + } + return out +} + +func (c *MMUCurve) mmu(window time.Duration, acc *accumulator) { + if window <= 0 { + acc.mmu = 0 + return + } + + var bandU bandUtilHeap + windows := make([]time.Duration, len(c.series)) + for i, s := range c.series { + windows[i] = window + if max := time.Duration(s.util[len(s.util)-1].Time - s.util[0].Time); window > max { + windows[i] = max + } + + bandU1 := bandUtilHeap(s.mkBandUtil(i, windows[i])) + if bandU == nil { + bandU = bandU1 + } else { + bandU = append(bandU, bandU1...) + } + } + + // Process bands from lowest utilization bound to highest. + heap.Init(&bandU) + + // Refine each band into a precise window and MMU until + // refining the next lowest band can no longer affect the MMU + // or windows. + for len(bandU) > 0 && bandU[0].utilBound < acc.bound { + i := bandU[0].series + c.series[i].bandMMU(bandU[0].i, windows[i], acc) + heap.Pop(&bandU) + } +} + +func (c *mmuSeries) mkBandUtil(series int, window time.Duration) []bandUtil { + // For each band, compute the worst-possible total mutator + // utilization for all windows that start in that band. + + // minBands is the minimum number of bands a window can span + // and maxBands is the maximum number of bands a window can + // span in any alignment. + minBands := int((int64(window) + c.bandDur - 1) / c.bandDur) + maxBands := int((int64(window) + 2*(c.bandDur-1)) / c.bandDur) + if window > 1 && maxBands < 2 { + panic("maxBands < 2") + } + tailDur := int64(window) % c.bandDur + nUtil := len(c.bands) - maxBands + 1 + if nUtil < 0 { + nUtil = 0 + } + bandU := make([]bandUtil, nUtil) + for i := range bandU { + // To compute the worst-case MU, we assume the minimum + // for any bands that are only partially overlapped by + // some window and the mean for any bands that are + // completely covered by all windows. + var util totalUtil + + // Find the lowest and second lowest of the partial + // bands. + l := c.bands[i].minUtil + r1 := c.bands[i+minBands-1].minUtil + r2 := c.bands[i+maxBands-1].minUtil + minBand := math.Min(l, math.Min(r1, r2)) + // Assume the worst window maximally overlaps the + // worst minimum and then the rest overlaps the second + // worst minimum. + if minBands == 1 { + util += totalUtilOf(minBand, int64(window)) + } else { + util += totalUtilOf(minBand, c.bandDur) + midBand := 0.0 + switch { + case minBand == l: + midBand = math.Min(r1, r2) + case minBand == r1: + midBand = math.Min(l, r2) + case minBand == r2: + midBand = math.Min(l, r1) + } + util += totalUtilOf(midBand, tailDur) + } + + // Add the total mean MU of bands that are completely + // overlapped by all windows. + if minBands > 2 { + util += c.bands[i+minBands-1].cumUtil - c.bands[i+1].cumUtil + } + + bandU[i] = bandUtil{series, i, util.mean(window)} + } + + return bandU +} + +// bandMMU computes the precise minimum mutator utilization for +// windows with a left edge in band bandIdx. +func (c *mmuSeries) bandMMU(bandIdx int, window time.Duration, acc *accumulator) { + util := c.util + + // We think of the mutator utilization over time as the + // box-filtered utilization function, which we call the + // "windowed mutator utilization function". The resulting + // function is continuous and piecewise linear (unless + // window==0, which we handle elsewhere), where the boundaries + // between segments occur when either edge of the window + // encounters a change in the instantaneous mutator + // utilization function. Hence, the minimum of this function + // will always occur when one of the edges of the window + // aligns with a utilization change, so these are the only + // points we need to consider. + // + // We compute the mutator utilization function incrementally + // by tracking the integral from t=0 to the left edge of the + // window and to the right edge of the window. + left := c.bands[bandIdx].integrator + right := left + time, endTime := c.bandTime(bandIdx) + if utilEnd := util[len(util)-1].Time - int64(window); utilEnd < endTime { + endTime = utilEnd + } + acc.resetTime() + for { + // Advance edges to time and time+window. + mu := (right.advance(time+int64(window)) - left.advance(time)).mean(window) + if acc.addMU(time, mu, window) { + break + } + if time == endTime { + break + } + + // The maximum slope of the windowed mutator + // utilization function is 1/window, so we can always + // advance the time by at least (mu - mmu) * window + // without dropping below mmu. + minTime := time + int64((mu-acc.bound)*float64(window)) + + // Advance the window to the next time where either + // the left or right edge of the window encounters a + // change in the utilization curve. + if t1, t2 := left.next(time), right.next(time+int64(window))-int64(window); t1 < t2 { + time = t1 + } else { + time = t2 + } + if time < minTime { + time = minTime + } + if time >= endTime { + // For MMUs we could stop here, but for MUDs + // it's important that we span the entire + // band. + time = endTime + } + } +} + +// An integrator tracks a position in a utilization function and +// integrates it. +type integrator struct { + u *mmuSeries + // pos is the index in u.util of the current time's non-strict + // predecessor. + pos int +} + +// advance returns the integral of the utilization function from 0 to +// time. advance must be called on monotonically increasing values of +// times. +func (in *integrator) advance(time int64) totalUtil { + util, pos := in.u.util, in.pos + // Advance pos until pos+1 is time's strict successor (making + // pos time's non-strict predecessor). + // + // Very often, this will be nearby, so we optimize that case, + // but it may be arbitrarily far away, so we handled that + // efficiently, too. + const maxSeq = 8 + if pos+maxSeq < len(util) && util[pos+maxSeq].Time > time { + // Nearby. Use a linear scan. + for pos+1 < len(util) && util[pos+1].Time <= time { + pos++ + } + } else { + // Far. Binary search for time's strict successor. + l, r := pos, len(util) + for l < r { + h := int(uint(l+r) >> 1) + if util[h].Time <= time { + l = h + 1 + } else { + r = h + } + } + pos = l - 1 // Non-strict predecessor. + } + in.pos = pos + var partial totalUtil + if time != util[pos].Time { + partial = totalUtilOf(util[pos].Util, time-util[pos].Time) + } + return in.u.sums[pos] + partial +} + +// next returns the smallest time t' > time of a change in the +// utilization function. +func (in *integrator) next(time int64) int64 { + for _, u := range in.u.util[in.pos:] { + if u.Time > time { + return u.Time + } + } + return 1<<63 - 1 +} + +func isGCSTW(r Range) bool { + return strings.HasPrefix(r.Name, "stop-the-world") && strings.Contains(r.Name, "GC") +} + +func isGCMarkAssist(r Range) bool { + return r.Name == "GC mark assist" +} + +func isGCSweep(r Range) bool { + return r.Name == "GC incremental sweep" +} diff --git a/go/src/internal/trace/gc_test.go b/go/src/internal/trace/gc_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9c6d0fcb0e56d89dfd936abaf10cf6a1c17c35f3 --- /dev/null +++ b/go/src/internal/trace/gc_test.go @@ -0,0 +1,195 @@ +// 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 trace_test + +import ( + "internal/trace" + "internal/trace/testtrace" + "io" + "math" + "testing" + "time" +) + +// aeq returns true if x and y are equal up to 8 digits (1 part in 100 +// million). +func aeq(x, y float64) bool { + if x < 0 && y < 0 { + x, y = -x, -y + } + const digits = 8 + factor := 1 - math.Pow(10, -digits+1) + return x*factor <= y && y*factor <= x +} + +func TestMMU(t *testing.T) { + t.Parallel() + + // MU + // 1.0 ***** ***** ***** + // 0.5 * * * * + // 0.0 ***** ***** + // 0 1 2 3 4 5 + util := [][]trace.MutatorUtil{{ + {0e9, 1}, + {1e9, 0}, + {2e9, 1}, + {3e9, 0}, + {4e9, 1}, + {5e9, 0}, + }} + mmuCurve := trace.NewMMUCurve(util) + + for _, test := range []struct { + window time.Duration + want float64 + worst []float64 + }{ + {0, 0, []float64{}}, + {time.Millisecond, 0, []float64{0, 0}}, + {time.Second, 0, []float64{0, 0}}, + {2 * time.Second, 0.5, []float64{0.5, 0.5}}, + {3 * time.Second, 1 / 3.0, []float64{1 / 3.0}}, + {4 * time.Second, 0.5, []float64{0.5}}, + {5 * time.Second, 3 / 5.0, []float64{3 / 5.0}}, + {6 * time.Second, 3 / 5.0, []float64{3 / 5.0}}, + } { + if got := mmuCurve.MMU(test.window); !aeq(test.want, got) { + t.Errorf("for %s window, want mu = %f, got %f", test.window, test.want, got) + } + worst := mmuCurve.Examples(test.window, 2) + // Which exact windows are returned is unspecified + // (and depends on the exact banding), so we just + // check that we got the right number with the right + // utilizations. + if len(worst) != len(test.worst) { + t.Errorf("for %s window, want worst %v, got %v", test.window, test.worst, worst) + } else { + for i := range worst { + if worst[i].MutatorUtil != test.worst[i] { + t.Errorf("for %s window, want worst %v, got %v", test.window, test.worst, worst) + break + } + } + } + } +} + +func TestMMUTrace(t *testing.T) { + // Can't be t.Parallel() because it modifies the + // testingOneBand package variable. + if testing.Short() { + // test input too big for all.bash + t.Skip("skipping in -short mode") + } + check := func(t *testing.T, mu [][]trace.MutatorUtil) { + mmuCurve := trace.NewMMUCurve(mu) + + // Test the optimized implementation against the "obviously + // correct" implementation. + for window := time.Nanosecond; window < 10*time.Second; window *= 10 { + want := mmuSlow(mu[0], window) + got := mmuCurve.MMU(window) + if !aeq(want, got) { + t.Errorf("want %f, got %f mutator utilization in window %s", want, got, window) + } + } + + // Test MUD with band optimization against MUD without band + // optimization. We don't have a simple testing implementation + // of MUDs (the simplest implementation is still quite + // complex), but this is still a pretty good test. + defer func(old int) { trace.BandsPerSeries = old }(trace.BandsPerSeries) + trace.BandsPerSeries = 1 + mmuCurve2 := trace.NewMMUCurve(mu) + quantiles := []float64{0, 1 - .999, 1 - .99} + for window := time.Microsecond; window < time.Second; window *= 10 { + mud1 := mmuCurve.MUD(window, quantiles) + mud2 := mmuCurve2.MUD(window, quantiles) + for i := range mud1 { + if !aeq(mud1[i], mud2[i]) { + t.Errorf("for quantiles %v at window %v, want %v, got %v", quantiles, window, mud2, mud1) + break + } + } + } + } + t.Run("V2", func(t *testing.T) { + testPath := "testdata/tests/go122-gc-stress.test" + r, _, _, err := testtrace.ParseFile(testPath) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + var events []trace.Event + tr, err := trace.NewReader(r) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + for { + ev, err := tr.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + events = append(events, ev) + } + // Pass the trace through MutatorUtilizationV2 and check it. + check(t, trace.MutatorUtilizationV2(events, trace.UtilSTW|trace.UtilBackground|trace.UtilAssist)) + }) +} + +func mmuSlow(util []trace.MutatorUtil, window time.Duration) (mmu float64) { + if max := time.Duration(util[len(util)-1].Time - util[0].Time); window > max { + window = max + } + + mmu = 1.0 + + // muInWindow returns the mean mutator utilization between + // util[0].Time and end. + muInWindow := func(util []trace.MutatorUtil, end int64) float64 { + total := 0.0 + var prevU trace.MutatorUtil + for _, u := range util { + if u.Time > end { + total += prevU.Util * float64(end-prevU.Time) + break + } + total += prevU.Util * float64(u.Time-prevU.Time) + prevU = u + } + return total / float64(end-util[0].Time) + } + update := func() { + for i, u := range util { + if u.Time+int64(window) > util[len(util)-1].Time { + break + } + mmu = math.Min(mmu, muInWindow(util[i:], u.Time+int64(window))) + } + } + + // Consider all left-aligned windows. + update() + // Reverse the trace. Slightly subtle because each MutatorUtil + // is a *change*. + rutil := make([]trace.MutatorUtil, len(util)) + if util[len(util)-1].Util != 0 { + panic("irreversible trace") + } + for i, u := range util { + util1 := 0.0 + if i != 0 { + util1 = util[i-1].Util + } + rutil[len(rutil)-i-1] = trace.MutatorUtil{Time: -u.Time, Util: util1} + } + util = rutil + // Consider all right-aligned windows. + update() + return +} diff --git a/go/src/internal/trace/generation.go b/go/src/internal/trace/generation.go new file mode 100644 index 0000000000000000000000000000000000000000..90ceef5f7488968791932468b30b13d3380d0b50 --- /dev/null +++ b/go/src/internal/trace/generation.go @@ -0,0 +1,603 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "bufio" + "bytes" + "cmp" + "encoding/binary" + "errors" + "fmt" + "io" + "slices" + "strings" + "time" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// generation contains all the trace data for a single +// trace generation. It is purely data: it does not +// track any parse state nor does it contain a cursor +// into the generation. +type generation struct { + gen uint64 + batches map[ThreadID][]batch + batchMs []ThreadID + cpuSamples []cpuSample + minTs timestamp + *evTable +} + +// readGeneration buffers and decodes the structural elements of a trace generation +// out of r. +func readGeneration(r *bufio.Reader, ver version.Version) (*generation, error) { + if ver < version.Go126 { + return nil, errors.New("internal error: readGeneration called for <1.26 trace") + } + g := &generation{ + evTable: &evTable{ + pcs: make(map[uint64]frame), + }, + batches: make(map[ThreadID][]batch), + } + + // Read batches one at a time until we either hit the next generation. + for { + b, gen, err := readBatch(r) + if err == io.EOF { + if len(g.batches) != 0 { + return nil, errors.New("incomplete generation found; trace likely truncated") + } + return nil, nil // All done. + } + if err != nil { + return nil, err + } + if g.gen == 0 { + // Initialize gen. + g.gen = gen + } + if b.isEndOfGeneration() { + break + } + if gen == 0 { + // 0 is a sentinel used by the runtime, so we'll never see it. + return nil, fmt.Errorf("invalid generation number %d", gen) + } + if gen != g.gen { + return nil, fmt.Errorf("broken trace: missing end-of-generation event, or generations are interleaved") + } + if g.minTs == 0 || b.time < g.minTs { + g.minTs = b.time + } + if err := processBatch(g, b, ver); err != nil { + return nil, err + } + } + + // Check some invariants. + if g.freq == 0 { + return nil, fmt.Errorf("no frequency event found") + } + if !g.hasClockSnapshot { + return nil, fmt.Errorf("no clock snapshot event found") + } + + // N.B. Trust that the batch order is correct. We can't validate the batch order + // by timestamp because the timestamps could just be plain wrong. The source of + // truth is the order things appear in the trace and the partial order sequence + // numbers on certain events. If it turns out the batch order is actually incorrect + // we'll very likely fail to advance a partial order from the frontier. + + // Compactify stacks and strings for better lookup performance later. + g.stacks.compactify() + g.strings.compactify() + + // Validate stacks. + if err := validateStackStrings(&g.stacks, &g.strings, g.pcs); err != nil { + return nil, err + } + + // Now that we have the frequency, fix up CPU samples. + fixUpCPUSamples(g.cpuSamples, g.freq) + return g, nil +} + +// spilledBatch represents a batch that was read out for the next generation, +// while reading the previous one. It's passed on when parsing the next +// generation. +// +// Used only for trace versions < Go126. +type spilledBatch struct { + gen uint64 + *batch +} + +// readGenerationWithSpill buffers and decodes the structural elements of a trace generation +// out of r. spill is the first batch of the new generation (already buffered and +// parsed from reading the last generation). Returns the generation and the first +// batch read of the next generation, if any. +// +// If gen is non-nil, it is valid and must be processed before handling the returned +// error. +func readGenerationWithSpill(r *bufio.Reader, spill *spilledBatch, ver version.Version) (*generation, *spilledBatch, error) { + if ver >= version.Go126 { + return nil, nil, errors.New("internal error: readGenerationWithSpill called for Go 1.26+ trace") + } + g := &generation{ + evTable: &evTable{ + pcs: make(map[uint64]frame), + }, + batches: make(map[ThreadID][]batch), + } + // Process the spilled batch. + if spill != nil { + // Process the spilled batch, which contains real data. + g.gen = spill.gen + g.minTs = spill.batch.time + if err := processBatch(g, *spill.batch, ver); err != nil { + return nil, nil, err + } + spill = nil + } + // Read batches one at a time until we either hit the next generation. + var spillErr error + for { + b, gen, err := readBatch(r) + if err == io.EOF { + break + } + if err != nil { + if g.gen != 0 { + // This may be an error reading the first batch of the next generation. + // This is fine. Let's forge ahead assuming that what we've got so + // far is fine. + spillErr = err + break + } + return nil, nil, err + } + if gen == 0 { + // 0 is a sentinel used by the runtime, so we'll never see it. + return nil, nil, fmt.Errorf("invalid generation number %d", gen) + } + if g.gen == 0 { + // Initialize gen. + g.gen = gen + } + if gen == g.gen+1 { + // TODO: Increment the generation with wraparound the same way the runtime does. + spill = &spilledBatch{gen: gen, batch: &b} + break + } + if gen != g.gen { + // N.B. Fail as fast as possible if we see this. At first it + // may seem prudent to be fault-tolerant and assume we have a + // complete generation, parsing and returning that first. However, + // if the batches are mixed across generations then it's likely + // we won't be able to parse this generation correctly at all. + // Rather than return a cryptic error in that case, indicate the + // problem as soon as we see it. + return nil, nil, fmt.Errorf("generations out of order") + } + if g.minTs == 0 || b.time < g.minTs { + g.minTs = b.time + } + if err := processBatch(g, b, ver); err != nil { + return nil, nil, err + } + } + + // Check some invariants. + if g.freq == 0 { + return nil, nil, fmt.Errorf("no frequency event found") + } + if ver >= version.Go125 && !g.hasClockSnapshot { + return nil, nil, fmt.Errorf("no clock snapshot event found") + } + + // N.B. Trust that the batch order is correct. We can't validate the batch order + // by timestamp because the timestamps could just be plain wrong. The source of + // truth is the order things appear in the trace and the partial order sequence + // numbers on certain events. If it turns out the batch order is actually incorrect + // we'll very likely fail to advance a partial order from the frontier. + + // Compactify stacks and strings for better lookup performance later. + g.stacks.compactify() + g.strings.compactify() + + // Validate stacks. + if err := validateStackStrings(&g.stacks, &g.strings, g.pcs); err != nil { + return nil, nil, err + } + + // Now that we have the frequency, fix up CPU samples. + fixUpCPUSamples(g.cpuSamples, g.freq) + return g, spill, spillErr +} + +// processBatch adds the batch to the generation. +func processBatch(g *generation, b batch, ver version.Version) error { + switch { + case b.isStringsBatch(): + if err := addStrings(&g.strings, b); err != nil { + return err + } + case b.isStacksBatch(): + if err := addStacks(&g.stacks, g.pcs, b); err != nil { + return err + } + case b.isCPUSamplesBatch(): + samples, err := addCPUSamples(g.cpuSamples, b) + if err != nil { + return err + } + g.cpuSamples = samples + case b.isSyncBatch(ver): + if err := setSyncBatch(&g.sync, b, ver); err != nil { + return err + } + case b.exp != tracev2.NoExperiment: + if g.expBatches == nil { + g.expBatches = make(map[tracev2.Experiment][]ExperimentalBatch) + } + if err := addExperimentalBatch(g.expBatches, b); err != nil { + return err + } + case b.isEndOfGeneration(): + return errors.New("internal error: unexpectedly processing EndOfGeneration; broken trace?") + default: + if _, ok := g.batches[b.m]; !ok { + g.batchMs = append(g.batchMs, b.m) + } + g.batches[b.m] = append(g.batches[b.m], b) + } + return nil +} + +// validateStackStrings makes sure all the string references in +// the stack table are present in the string table. +func validateStackStrings( + stacks *dataTable[stackID, stack], + strings *dataTable[stringID, string], + frames map[uint64]frame, +) error { + var err error + stacks.forEach(func(id stackID, stk stack) bool { + for _, pc := range stk.pcs { + frame, ok := frames[pc] + if !ok { + err = fmt.Errorf("found unknown pc %x for stack %d", pc, id) + return false + } + _, ok = strings.get(frame.funcID) + if !ok { + err = fmt.Errorf("found invalid func string ID %d for stack %d", frame.funcID, id) + return false + } + _, ok = strings.get(frame.fileID) + if !ok { + err = fmt.Errorf("found invalid file string ID %d for stack %d", frame.fileID, id) + return false + } + } + return true + }) + return err +} + +// addStrings takes a batch whose first byte is an EvStrings event +// (indicating that the batch contains only strings) and adds each +// string contained therein to the provided strings map. +func addStrings(stringTable *dataTable[stringID, string], b batch) error { + if !b.isStringsBatch() { + return fmt.Errorf("internal error: addStrings called on non-string batch") + } + r := bytes.NewReader(b.data) + hdr, err := r.ReadByte() // Consume the EvStrings byte. + if err != nil || tracev2.EventType(hdr) != tracev2.EvStrings { + return fmt.Errorf("missing strings batch header") + } + + var sb strings.Builder + for r.Len() != 0 { + // Read the header. + ev, err := r.ReadByte() + if err != nil { + return err + } + if tracev2.EventType(ev) != tracev2.EvString { + return fmt.Errorf("expected string event, got %d", ev) + } + + // Read the string's ID. + id, err := binary.ReadUvarint(r) + if err != nil { + return err + } + + // Read the string's length. + len, err := binary.ReadUvarint(r) + if err != nil { + return err + } + if len > tracev2.MaxEventTrailerDataSize { + return fmt.Errorf("invalid string size %d, maximum is %d", len, tracev2.MaxEventTrailerDataSize) + } + + // Copy out the string. + n, err := io.CopyN(&sb, r, int64(len)) + if n != int64(len) { + return fmt.Errorf("failed to read full string: read %d but wanted %d", n, len) + } + if err != nil { + return fmt.Errorf("copying string data: %w", err) + } + + // Add the string to the map. + s := sb.String() + sb.Reset() + if err := stringTable.insert(stringID(id), s); err != nil { + return err + } + } + return nil +} + +// addStacks takes a batch whose first byte is an EvStacks event +// (indicating that the batch contains only stacks) and adds each +// string contained therein to the provided stacks map. +func addStacks(stackTable *dataTable[stackID, stack], pcs map[uint64]frame, b batch) error { + if !b.isStacksBatch() { + return fmt.Errorf("internal error: addStacks called on non-stacks batch") + } + r := bytes.NewReader(b.data) + hdr, err := r.ReadByte() // Consume the EvStacks byte. + if err != nil || tracev2.EventType(hdr) != tracev2.EvStacks { + return fmt.Errorf("missing stacks batch header") + } + + for r.Len() != 0 { + // Read the header. + ev, err := r.ReadByte() + if err != nil { + return err + } + if tracev2.EventType(ev) != tracev2.EvStack { + return fmt.Errorf("expected stack event, got %d", ev) + } + + // Read the stack's ID. + id, err := binary.ReadUvarint(r) + if err != nil { + return err + } + + // Read how many frames are in each stack. + nFrames, err := binary.ReadUvarint(r) + if err != nil { + return err + } + if nFrames > tracev2.MaxFramesPerStack { + return fmt.Errorf("invalid stack size %d, maximum is %d", nFrames, tracev2.MaxFramesPerStack) + } + + // Each frame consists of 4 fields: pc, funcID (string), fileID (string), line. + frames := make([]uint64, 0, nFrames) + for i := uint64(0); i < nFrames; i++ { + // Read the frame data. + pc, err := binary.ReadUvarint(r) + if err != nil { + return fmt.Errorf("reading frame %d's PC for stack %d: %w", i+1, id, err) + } + funcID, err := binary.ReadUvarint(r) + if err != nil { + return fmt.Errorf("reading frame %d's funcID for stack %d: %w", i+1, id, err) + } + fileID, err := binary.ReadUvarint(r) + if err != nil { + return fmt.Errorf("reading frame %d's fileID for stack %d: %w", i+1, id, err) + } + line, err := binary.ReadUvarint(r) + if err != nil { + return fmt.Errorf("reading frame %d's line for stack %d: %w", i+1, id, err) + } + frames = append(frames, pc) + + if _, ok := pcs[pc]; !ok { + pcs[pc] = frame{ + pc: pc, + funcID: stringID(funcID), + fileID: stringID(fileID), + line: line, + } + } + } + + // Add the stack to the map. + if err := stackTable.insert(stackID(id), stack{pcs: frames}); err != nil { + return err + } + } + return nil +} + +// addCPUSamples takes a batch whose first byte is an EvCPUSamples event +// (indicating that the batch contains only CPU samples) and adds each +// sample contained therein to the provided samples list. +func addCPUSamples(samples []cpuSample, b batch) ([]cpuSample, error) { + if !b.isCPUSamplesBatch() { + return nil, fmt.Errorf("internal error: addCPUSamples called on non-CPU-sample batch") + } + r := bytes.NewReader(b.data) + hdr, err := r.ReadByte() // Consume the EvCPUSamples byte. + if err != nil || tracev2.EventType(hdr) != tracev2.EvCPUSamples { + return nil, fmt.Errorf("missing CPU samples batch header") + } + + for r.Len() != 0 { + // Read the header. + ev, err := r.ReadByte() + if err != nil { + return nil, err + } + if tracev2.EventType(ev) != tracev2.EvCPUSample { + return nil, fmt.Errorf("expected CPU sample event, got %d", ev) + } + + // Read the sample's timestamp. + ts, err := binary.ReadUvarint(r) + if err != nil { + return nil, err + } + + // Read the sample's M. + m, err := binary.ReadUvarint(r) + if err != nil { + return nil, err + } + mid := ThreadID(m) + + // Read the sample's P. + p, err := binary.ReadUvarint(r) + if err != nil { + return nil, err + } + pid := ProcID(p) + + // Read the sample's G. + g, err := binary.ReadUvarint(r) + if err != nil { + return nil, err + } + goid := GoID(g) + if g == 0 { + goid = NoGoroutine + } + + // Read the sample's stack. + s, err := binary.ReadUvarint(r) + if err != nil { + return nil, err + } + + // Add the sample to the slice. + samples = append(samples, cpuSample{ + schedCtx: schedCtx{ + M: mid, + P: pid, + G: goid, + }, + time: Time(ts), // N.B. this is really a "timestamp," not a Time. + stack: stackID(s), + }) + } + return samples, nil +} + +// sync holds the per-generation sync data. +type sync struct { + freq frequency + hasClockSnapshot bool + snapTime timestamp + snapMono uint64 + snapWall time.Time +} + +func setSyncBatch(s *sync, b batch, ver version.Version) error { + if !b.isSyncBatch(ver) { + return fmt.Errorf("internal error: setSyncBatch called on non-sync batch") + } + r := bytes.NewReader(b.data) + if ver >= version.Go125 { + hdr, err := r.ReadByte() // Consume the EvSync byte. + if err != nil || tracev2.EventType(hdr) != tracev2.EvSync { + return fmt.Errorf("missing sync batch header") + } + } + + lastTs := b.time + for r.Len() != 0 { + // Read the header + ev, err := r.ReadByte() + if err != nil { + return err + } + et := tracev2.EventType(ev) + switch { + case et == tracev2.EvFrequency: + if s.freq != 0 { + return fmt.Errorf("found multiple frequency events") + } + // Read the frequency. It'll come out as timestamp units per second. + f, err := binary.ReadUvarint(r) + if err != nil { + return err + } + // Convert to nanoseconds per timestamp unit. + s.freq = frequency(1.0 / (float64(f) / 1e9)) + case et == tracev2.EvClockSnapshot && ver >= version.Go125: + if s.hasClockSnapshot { + return fmt.Errorf("found multiple clock snapshot events") + } + s.hasClockSnapshot = true + // Read the EvClockSnapshot arguments. + tdiff, err := binary.ReadUvarint(r) + if err != nil { + return err + } + lastTs += timestamp(tdiff) + s.snapTime = lastTs + mono, err := binary.ReadUvarint(r) + if err != nil { + return err + } + s.snapMono = mono + sec, err := binary.ReadUvarint(r) + if err != nil { + return err + } + nsec, err := binary.ReadUvarint(r) + if err != nil { + return err + } + // TODO(felixge): In theory we could inject s.snapMono into the time + // value below to make it comparable. But there is no API for this + // in the time package right now. + s.snapWall = time.Unix(int64(sec), int64(nsec)) + default: + return fmt.Errorf("expected frequency or clock snapshot event, got %d", ev) + } + } + return nil +} + +// addExperimentalBatch takes an experimental batch and adds it to the list of experimental +// batches for the experiment its a part of. +func addExperimentalBatch(expBatches map[tracev2.Experiment][]ExperimentalBatch, b batch) error { + if b.exp == tracev2.NoExperiment { + return fmt.Errorf("internal error: addExperimentalBatch called on non-experimental batch") + } + expBatches[b.exp] = append(expBatches[b.exp], ExperimentalBatch{ + Thread: b.m, + Data: b.data, + }) + return nil +} + +func fixUpCPUSamples(samples []cpuSample, freq frequency) { + // Fix up the CPU sample timestamps. + for i := range samples { + s := &samples[i] + s.time = freq.mul(timestamp(s.time)) + } + // Sort the CPU samples. + slices.SortFunc(samples, func(a, b cpuSample) int { + return cmp.Compare(a.time, b.time) + }) +} diff --git a/go/src/internal/trace/internal/testgen/trace.go b/go/src/internal/trace/internal/testgen/trace.go new file mode 100644 index 0000000000000000000000000000000000000000..2eade48de70e00da8490024cd81be121437d38b4 --- /dev/null +++ b/go/src/internal/trace/internal/testgen/trace.go @@ -0,0 +1,459 @@ +// 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 testgen + +import ( + "bytes" + "encoding/binary" + "fmt" + "os" + "regexp" + "strings" + "time" + + "internal/trace" + "internal/trace/raw" + "internal/trace/tracev2" + "internal/trace/version" + "internal/txtar" +) + +func Main(ver version.Version, f func(*Trace)) { + // Create an output file. + out, err := os.Create(os.Args[1]) + if err != nil { + panic(err.Error()) + } + defer out.Close() + + // Create a new trace. + trace := NewTrace(ver) + + // Call the generator. + f(trace) + + // Write out the generator's state. + if _, err := out.Write(trace.Generate()); err != nil { + panic(err.Error()) + } +} + +// Trace represents an execution trace for testing. +// +// It does a little bit of work to ensure that the produced trace is valid, +// just for convenience. It mainly tracks batches and batch sizes (so they're +// trivially correct), tracks strings and stacks, and makes sure emitted string +// and stack batches are valid. That last part can be controlled by a few options. +// +// Otherwise, it performs no validation on the trace at all. +type Trace struct { + // Trace data state. + ver version.Version + names map[string]tracev2.EventType + specs []tracev2.EventSpec + events []raw.Event + gens []*Generation + validTimestamps bool + lastTs Time + + // Expectation state. + bad bool + badMatch *regexp.Regexp +} + +// NewTrace creates a new trace. +func NewTrace(ver version.Version) *Trace { + return &Trace{ + names: tracev2.EventNames(ver.Specs()), + specs: ver.Specs(), + ver: ver, + validTimestamps: true, + } +} + +// ExpectFailure writes down that the trace should be broken. The caller +// must provide a pattern matching the expected error produced by the parser. +func (t *Trace) ExpectFailure(pattern string) { + t.bad = true + t.badMatch = regexp.MustCompile(pattern) +} + +// ExpectSuccess writes down that the trace should successfully parse. +func (t *Trace) ExpectSuccess() { + t.bad = false +} + +// RawEvent emits an event into the trace. name must correspond to one +// of the names in Specs() result for the version that was passed to +// this trace. +func (t *Trace) RawEvent(typ tracev2.EventType, data []byte, args ...uint64) { + t.events = append(t.events, t.createEvent(typ, data, args...)) +} + +// DisableTimestamps makes the timestamps for all events generated after +// this call zero. Raw events are exempted from this because the caller +// has to pass their own timestamp into those events anyway. +func (t *Trace) DisableTimestamps() { + t.validTimestamps = false +} + +// Generation creates a new trace generation. +// +// This provides more structure than Event to allow for more easily +// creating complex traces that are mostly or completely correct. +func (t *Trace) Generation(gen uint64) *Generation { + g := &Generation{ + trace: t, + gen: gen, + strings: make(map[string]uint64), + stacks: make(map[stack]uint64), + sync: sync{freq: 15625000}, + } + t.gens = append(t.gens, g) + return g +} + +// Generate creates a test file for the trace. +func (t *Trace) Generate() []byte { + // Trace file contents. + var buf bytes.Buffer + tw, err := raw.NewTextWriter(&buf, t.ver) + if err != nil { + panic(err.Error()) + } + + // Write raw top-level events. + for _, e := range t.events { + tw.WriteEvent(e) + } + + // Write generations. + for _, g := range t.gens { + g.writeEventsTo(tw) + } + + // Expectation file contents. + expect := []byte("SUCCESS\n") + if t.bad { + expect = []byte(fmt.Sprintf("FAILURE %q\n", t.badMatch)) + } + + // Create the test file's contents. + return txtar.Format(&txtar.Archive{ + Files: []txtar.File{ + {Name: "expect", Data: expect}, + {Name: "trace", Data: buf.Bytes()}, + }, + }) +} + +func (t *Trace) createEvent(ev tracev2.EventType, data []byte, args ...uint64) raw.Event { + spec := t.specs[ev] + if ev != tracev2.EvStack { + if arity := len(spec.Args); len(args) != arity { + panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args))) + } + } + return raw.Event{ + Version: t.ver, + Ev: ev, + Args: args, + Data: data, + } +} + +type stack struct { + stk [32]trace.StackFrame + len int +} + +var ( + NoString = "" + NoStack = []trace.StackFrame{} +) + +// Generation represents a single generation in the trace. +type Generation struct { + trace *Trace + gen uint64 + batches []*Batch + strings map[string]uint64 + stacks map[stack]uint64 + sync sync + + // Options applied when Trace.Generate is called. + ignoreStringBatchSizeLimit bool + ignoreStackBatchSizeLimit bool +} + +// Batch starts a new event batch in the trace data. +// +// This is convenience function for generating correct batches. +func (g *Generation) Batch(thread trace.ThreadID, time Time) *Batch { + b := &Batch{ + gen: g, + thread: thread, + } + b.setTimestamp(time) + g.batches = append(g.batches, b) + return b +} + +// String registers a string with the trace. +// +// This is a convenience function for easily adding correct +// strings to traces. +func (g *Generation) String(s string) uint64 { + if len(s) == 0 { + return 0 + } + if id, ok := g.strings[s]; ok { + return id + } + id := uint64(len(g.strings) + 1) + g.strings[s] = id + return id +} + +// Stack registers a stack with the trace. +// +// This is a convenience function for easily adding correct +// stacks to traces. +func (g *Generation) Stack(stk []trace.StackFrame) uint64 { + if len(stk) == 0 { + return 0 + } + if len(stk) > 32 { + panic("stack too big for test") + } + var stkc stack + copy(stkc.stk[:], stk) + stkc.len = len(stk) + if id, ok := g.stacks[stkc]; ok { + return id + } + id := uint64(len(g.stacks) + 1) + g.stacks[stkc] = id + return id +} + +// Sync configures the sync batch for the generation. For go1.25 and later, +// the time value is the timestamp of the EvClockSnapshot event. For earlier +// version, the time value is the timestamp of the batch containing a lone +// EvFrequency event. +func (g *Generation) Sync(freq uint64, time Time, mono uint64, wall time.Time) { + if g.trace.ver < version.Go125 && (mono != 0 || !wall.IsZero()) { + panic(fmt.Sprintf("mono and wall args are not supported in go1.%d traces", g.trace.ver)) + } + g.sync = sync{ + freq: freq, + time: time, + mono: mono, + walltime: wall, + } +} + +type sync struct { + freq uint64 + time Time + mono uint64 + walltime time.Time +} + +// writeEventsTo emits event batches in the generation to tw. +func (g *Generation) writeEventsTo(tw *raw.TextWriter) { + // go1.25+ sync batches are emitted at the start of the generation. + if g.trace.ver >= version.Go125 { + b := g.newStructuralBatch() + // Arrange for EvClockSnapshot's ts to be exactly g.sync.time. + b.setTimestamp(g.sync.time - 1) + b.RawEvent(tracev2.EvSync, nil) + b.RawEvent(tracev2.EvFrequency, nil, g.sync.freq) + sec := uint64(g.sync.walltime.Unix()) + nsec := uint64(g.sync.walltime.Nanosecond()) + b.Event("ClockSnapshot", g.sync.mono, sec, nsec) + b.writeEventsTo(tw) + } + + // Write event batches for the generation. + for _, b := range g.batches { + b.writeEventsTo(tw) + } + + // Write lone EvFrequency sync batch for older traces. + if g.trace.ver < version.Go125 { + b := g.newStructuralBatch() + b.setTimestamp(g.sync.time) + b.RawEvent(tracev2.EvFrequency, nil, g.sync.freq) + b.writeEventsTo(tw) + } + + // Write stacks. + b := g.newStructuralBatch() + b.RawEvent(tracev2.EvStacks, nil) + for stk, id := range g.stacks { + stk := stk.stk[:stk.len] + args := []uint64{id, uint64(len(stk))} + for _, f := range stk { + args = append(args, f.PC, g.String(f.Func), g.String(f.File), f.Line) + } + b.RawEvent(tracev2.EvStack, nil, args...) + + // Flush the batch if necessary. + if !g.ignoreStackBatchSizeLimit && b.size > tracev2.MaxBatchSize/2 { + b.writeEventsTo(tw) + b = g.newStructuralBatch() + } + } + b.writeEventsTo(tw) + + // Write strings. + b = g.newStructuralBatch() + b.RawEvent(tracev2.EvStrings, nil) + for s, id := range g.strings { + b.RawEvent(tracev2.EvString, []byte(s), id) + + // Flush the batch if necessary. + if !g.ignoreStringBatchSizeLimit && b.size > tracev2.MaxBatchSize/2 { + b.writeEventsTo(tw) + b = g.newStructuralBatch() + } + } + b.writeEventsTo(tw) + + // Write end-of-generation event if necessary. + if g.trace.ver >= version.Go126 { + tw.WriteEvent(raw.Event{ + Version: g.trace.ver, + Ev: tracev2.EvEndOfGeneration, + }) + } +} + +func (g *Generation) newStructuralBatch() *Batch { + b := &Batch{gen: g, thread: trace.NoThread} + b.setTimestamp(g.trace.lastTs + 1) + return b +} + +// Batch represents an event batch. +type Batch struct { + gen *Generation + thread trace.ThreadID + timestamp Time + size uint64 + events []raw.Event +} + +// Event emits an event into a batch. name must correspond to one +// of the names in Specs() result for the version that was passed to +// this trace. Callers must omit the timestamp delta. +func (b *Batch) Event(name string, args ...any) { + ev, ok := b.gen.trace.names[name] + if !ok { + panic(fmt.Sprintf("invalid or unknown event %s", name)) + } + var uintArgs []uint64 + argOff := 0 + if b.gen.trace.specs[ev].IsTimedEvent { + if b.gen.trace.validTimestamps { + uintArgs = []uint64{1} + b.gen.trace.lastTs += 1 + } else { + uintArgs = []uint64{0} + } + argOff = 1 + } + spec := b.gen.trace.specs[ev] + if arity := len(spec.Args) - argOff; len(args) != arity { + panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args))) + } + for i, arg := range args { + uintArgs = append(uintArgs, b.uintArgFor(arg, spec.Args[i+argOff])) + } + b.RawEvent(ev, nil, uintArgs...) +} + +func (b *Batch) uintArgFor(arg any, argSpec string) uint64 { + components := strings.SplitN(argSpec, "_", 2) + typStr := components[0] + if len(components) == 2 { + typStr = components[1] + } + var u uint64 + switch typStr { + case "value", "mono", "sec", "nsec": + u = arg.(uint64) + case "stack": + u = b.gen.Stack(arg.([]trace.StackFrame)) + case "seq": + u = uint64(arg.(Seq)) + case "pstatus": + u = uint64(arg.(tracev2.ProcStatus)) + case "gstatus": + u = uint64(arg.(tracev2.GoStatus)) + case "g": + u = uint64(arg.(trace.GoID)) + case "m": + u = uint64(arg.(trace.ThreadID)) + case "p": + u = uint64(arg.(trace.ProcID)) + case "string": + u = b.gen.String(arg.(string)) + case "task": + u = uint64(arg.(trace.TaskID)) + default: + panic(fmt.Sprintf("unsupported arg type %q for spec %q", typStr, argSpec)) + } + return u +} + +// RawEvent emits an event into a batch. name must correspond to one +// of the names in Specs() result for the version that was passed to +// this trace. +func (b *Batch) RawEvent(typ tracev2.EventType, data []byte, args ...uint64) { + ev := b.gen.trace.createEvent(typ, data, args...) + + // Compute the size of the event and add it to the batch. + b.size += 1 // One byte for the event header. + var buf [binary.MaxVarintLen64]byte + for _, arg := range args { + b.size += uint64(binary.PutUvarint(buf[:], arg)) + } + if len(data) != 0 { + b.size += uint64(binary.PutUvarint(buf[:], uint64(len(data)))) + b.size += uint64(len(data)) + } + + // Add the event. + b.events = append(b.events, ev) +} + +// writeEventsTo emits events in the batch, including the batch header, to tw. +func (b *Batch) writeEventsTo(tw *raw.TextWriter) { + tw.WriteEvent(raw.Event{ + Version: b.gen.trace.ver, + Ev: tracev2.EvEventBatch, + Args: []uint64{b.gen.gen, uint64(b.thread), uint64(b.timestamp), b.size}, + }) + for _, e := range b.events { + tw.WriteEvent(e) + } +} + +// setTimestamp sets the timestamp for the batch. +func (b *Batch) setTimestamp(t Time) { + if b.gen.trace.validTimestamps { + b.timestamp = t + b.gen.trace.lastTs = t + } +} + +// Seq represents a sequence counter. +type Seq uint64 + +// Time represents a low-level trace timestamp (which does not necessarily +// correspond to nanoseconds, like trace.Time does). +type Time uint64 diff --git a/go/src/internal/trace/internal/tracev1/order.go b/go/src/internal/trace/internal/tracev1/order.go new file mode 100644 index 0000000000000000000000000000000000000000..683d7f03b47f2b0a168491f684edbefbc49d4a6d --- /dev/null +++ b/go/src/internal/trace/internal/tracev1/order.go @@ -0,0 +1,172 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package tracev1 + +import "errors" + +type orderEvent struct { + ev Event + proc *proc +} + +type gStatus int + +type gState struct { + seq uint64 + status gStatus +} + +const ( + gDead gStatus = iota + gRunnable + gRunning + gWaiting + + unordered = ^uint64(0) + garbage = ^uint64(0) - 1 + noseq = ^uint64(0) + seqinc = ^uint64(0) - 1 +) + +// stateTransition returns goroutine state (sequence and status) when the event +// becomes ready for merging (init) and the goroutine state after the event (next). +func stateTransition(ev *Event) (g uint64, init, next gState) { + // Note that we have an explicit return in each case, as that produces slightly better code (tested on Go 1.19). + + switch ev.Type { + case EvGoCreate: + g = ev.Args[0] + init = gState{0, gDead} + next = gState{1, gRunnable} + return + case EvGoWaiting, EvGoInSyscall: + g = ev.G + init = gState{1, gRunnable} + next = gState{2, gWaiting} + return + case EvGoStart, EvGoStartLabel: + g = ev.G + init = gState{ev.Args[1], gRunnable} + next = gState{ev.Args[1] + 1, gRunning} + return + case EvGoStartLocal: + // noseq means that this event is ready for merging as soon as + // frontier reaches it (EvGoStartLocal is emitted on the same P + // as the corresponding EvGoCreate/EvGoUnblock, and thus the latter + // is already merged). + // seqinc is a stub for cases when event increments g sequence, + // but since we don't know current seq we also don't know next seq. + g = ev.G + init = gState{noseq, gRunnable} + next = gState{seqinc, gRunning} + return + case EvGoBlock, EvGoBlockSend, EvGoBlockRecv, EvGoBlockSelect, + EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, EvGoSleep, + EvGoSysBlock, EvGoBlockGC: + g = ev.G + init = gState{noseq, gRunning} + next = gState{noseq, gWaiting} + return + case EvGoSched, EvGoPreempt: + g = ev.G + init = gState{noseq, gRunning} + next = gState{noseq, gRunnable} + return + case EvGoUnblock, EvGoSysExit: + g = ev.Args[0] + init = gState{ev.Args[1], gWaiting} + next = gState{ev.Args[1] + 1, gRunnable} + return + case EvGoUnblockLocal, EvGoSysExitLocal: + g = ev.Args[0] + init = gState{noseq, gWaiting} + next = gState{seqinc, gRunnable} + return + case EvGCStart: + g = garbage + init = gState{ev.Args[0], gDead} + next = gState{ev.Args[0] + 1, gDead} + return + default: + // no ordering requirements + g = unordered + return + } +} + +func transitionReady(g uint64, curr, init gState) bool { + return g == unordered || (init.seq == noseq || init.seq == curr.seq) && init.status == curr.status +} + +func transition(gs map[uint64]gState, g uint64, init, next gState) error { + if g == unordered { + return nil + } + curr := gs[g] + if !transitionReady(g, curr, init) { + // See comment near the call to transition, where we're building the frontier, for details on how this could + // possibly happen. + return errors.New("encountered impossible goroutine state transition") + } + switch next.seq { + case noseq: + next.seq = curr.seq + case seqinc: + next.seq = curr.seq + 1 + } + gs[g] = next + return nil +} + +type orderEventList []orderEvent + +func (l *orderEventList) Less(i, j int) bool { + return (*l)[i].ev.Ts < (*l)[j].ev.Ts +} + +func (h *orderEventList) Push(x orderEvent) { + *h = append(*h, x) + heapUp(h, len(*h)-1) +} + +func (h *orderEventList) Pop() orderEvent { + n := len(*h) - 1 + (*h)[0], (*h)[n] = (*h)[n], (*h)[0] + heapDown(h, 0, n) + x := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return x +} + +func heapUp(h *orderEventList, j int) { + for { + i := (j - 1) / 2 // parent + if i == j || !h.Less(j, i) { + break + } + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] + j = i + } +} + +func heapDown(h *orderEventList, i0, n int) bool { + i := i0 + for { + j1 := 2*i + 1 + if j1 >= n || j1 < 0 { // j1 < 0 after int overflow + break + } + j := j1 // left child + if j2 := j1 + 1; j2 < n && h.Less(j2, j1) { + j = j2 // = 2*i + 2 // right child + } + if !h.Less(j, i) { + break + } + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] + i = j + } + return i > i0 +} diff --git a/go/src/internal/trace/internal/tracev1/parser.go b/go/src/internal/trace/internal/tracev1/parser.go new file mode 100644 index 0000000000000000000000000000000000000000..d47de9088a992b302992ee1239bc9521b6793700 --- /dev/null +++ b/go/src/internal/trace/internal/tracev1/parser.go @@ -0,0 +1,1553 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package tracev1 implements a parser for Go execution traces from versions +// 1.11–1.21. +// +// The package started as a copy of Go 1.19's internal/trace, but has been +// optimized to be faster while using less memory and fewer allocations. It has +// been further modified for the specific purpose of converting traces to the +// new 1.22+ format. +package tracev1 + +import ( + "bytes" + "cmp" + "encoding/binary" + "errors" + "fmt" + "internal/trace/version" + "io" + "math" + "slices" + "sort" +) + +// Timestamp represents a count of nanoseconds since the beginning of the trace. +// They can only be meaningfully compared with other timestamps from the same +// trace. +type Timestamp int64 + +// Event describes one event in the trace. +type Event struct { + // The Event type is carefully laid out to optimize its size and to avoid + // pointers, the latter so that the garbage collector won't have to scan any + // memory of our millions of events. + + Ts Timestamp // timestamp in nanoseconds + G uint64 // G on which the event happened + Args [4]uint64 // event-type-specific arguments + StkID uint32 // unique stack ID + P int32 // P on which the event happened (can be a real P or one of TimerP, NetpollP, SyscallP) + Type EventType // one of Ev* +} + +// Frame is a frame in stack traces. +type Frame struct { + PC uint64 + // string ID of the function name + Fn uint64 + // string ID of the file name + File uint64 + Line int +} + +const ( + // Special P identifiers: + FakeP = 1000000 + iota + TimerP // contains timer unblocks + NetpollP // contains network unblocks + SyscallP // contains returns from syscalls + GCP // contains GC state + ProfileP // contains recording of CPU profile samples +) + +// Trace is the result of Parse. +type Trace struct { + Version version.Version + + // Events is the sorted list of Events in the trace. + Events Events + // Stacks is the stack traces (stored as slices of PCs), keyed by stack IDs + // from the trace. + Stacks map[uint32][]uint64 + PCs map[uint64]Frame + Strings map[uint64]string + InlineStrings []string +} + +// batchOffset records the byte offset of, and number of events in, a batch. A +// batch is a sequence of events emitted by a P. Events within a single batch +// are sorted by time. +type batchOffset struct { + offset int + numEvents int +} + +type parser struct { + ver version.Version + data []byte + off int + + strings map[uint64]string + inlineStrings []string + inlineStringsMapping map[string]int + // map from Ps to their batch offsets + batchOffsets map[int32][]batchOffset + stacks map[uint32][]uint64 + stacksData []uint64 + ticksPerSec int64 + pcs map[uint64]Frame + cpuSamples []Event + timerGoids map[uint64]bool + + // state for readRawEvent + args []uint64 + + // state for parseEvent + lastTs Timestamp + lastG uint64 + // map from Ps to the last Gs that ran on them + lastGs map[int32]uint64 + lastP int32 +} + +func (p *parser) discard(n uint64) bool { + if n > math.MaxInt { + return false + } + if noff := p.off + int(n); noff < p.off || noff > len(p.data) { + return false + } else { + p.off = noff + } + return true +} + +func newParser(r io.Reader, ver version.Version) (*parser, error) { + var buf []byte + if seeker, ok := r.(io.Seeker); ok { + // Determine the size of the reader so that we can allocate a buffer + // without having to grow it later. + cur, err := seeker.Seek(0, io.SeekCurrent) + if err != nil { + return nil, err + } + end, err := seeker.Seek(0, io.SeekEnd) + if err != nil { + return nil, err + } + _, err = seeker.Seek(cur, io.SeekStart) + if err != nil { + return nil, err + } + + buf = make([]byte, end-cur) + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, err + } + } else { + var err error + buf, err = io.ReadAll(r) + if err != nil { + return nil, err + } + } + return &parser{data: buf, ver: ver, timerGoids: make(map[uint64]bool)}, nil +} + +// Parse parses Go execution traces from versions 1.11–1.21. The provided reader +// will be read to completion and the entire trace will be materialized in +// memory. That is, this function does not allow incremental parsing. +// +// The reader has to be positioned just after the trace header and vers needs to +// be the version of the trace. This can be achieved by using +// version.ReadHeader. +func Parse(r io.Reader, vers version.Version) (Trace, error) { + // We accept the version as an argument because internal/trace will have + // already read the version to determine which parser to use. + p, err := newParser(r, vers) + if err != nil { + return Trace{}, err + } + return p.parse() +} + +// parse parses, post-processes and verifies the trace. +func (p *parser) parse() (Trace, error) { + defer func() { + p.data = nil + }() + + // We parse a trace by running the following steps in order: + // + // 1. In the initial pass we collect information about batches (their + // locations and sizes.) We also parse CPU profiling samples in this + // step, simply to reduce the number of full passes that we need. + // + // 2. In the second pass we parse batches and merge them into a globally + // ordered event stream. This uses the batch information from the first + // pass to quickly find batches. + // + // 3. After all events have been parsed we convert their timestamps from CPU + // ticks to wall time. Furthermore we move timers and syscalls to + // dedicated, fake Ps. + // + // 4. Finally, we validate the trace. + + p.strings = make(map[uint64]string) + p.batchOffsets = make(map[int32][]batchOffset) + p.lastGs = make(map[int32]uint64) + p.stacks = make(map[uint32][]uint64) + p.pcs = make(map[uint64]Frame) + p.inlineStringsMapping = make(map[string]int) + + if err := p.collectBatchesAndCPUSamples(); err != nil { + return Trace{}, err + } + + events, err := p.parseEventBatches() + if err != nil { + return Trace{}, err + } + + if p.ticksPerSec == 0 { + return Trace{}, errors.New("no EvFrequency event") + } + + if events.Len() > 0 { + // Translate cpu ticks to real time. + minTs := events.Ptr(0).Ts + // Use floating point to avoid integer overflows. + freq := 1e9 / float64(p.ticksPerSec) + for i := 0; i < events.Len(); i++ { + ev := events.Ptr(i) + ev.Ts = Timestamp(float64(ev.Ts-minTs) * freq) + // Move timers and syscalls to separate fake Ps. + if p.timerGoids[ev.G] && ev.Type == EvGoUnblock { + ev.P = TimerP + } + if ev.Type == EvGoSysExit { + ev.P = SyscallP + } + } + } + + if err := p.postProcessTrace(events); err != nil { + return Trace{}, err + } + + res := Trace{ + Version: p.ver, + Events: events, + Stacks: p.stacks, + Strings: p.strings, + InlineStrings: p.inlineStrings, + PCs: p.pcs, + } + return res, nil +} + +// rawEvent is a helper type used during parsing. +type rawEvent struct { + typ EventType + args []uint64 + sargs []string + + // if typ == EvBatch, these fields describe the batch. + batchPid int32 + batchOffset int +} + +type proc struct { + pid int32 + // the remaining events in the current batch + events []Event + // buffer for reading batches into, aliased by proc.events + buf []Event + + // there are no more batches left + done bool +} + +const eventsBucketSize = 524288 // 32 MiB of events + +type Events struct { + // Events is a slice of slices that grows one slice of size eventsBucketSize + // at a time. This avoids the O(n) cost of slice growth in append, and + // additionally allows consumers to drop references to parts of the data, + // freeing memory piecewise. + n int + buckets []*[eventsBucketSize]Event + off int +} + +// grow grows the slice by one and returns a pointer to the new element, without +// overwriting it. +func (l *Events) grow() *Event { + a, b := l.index(l.n) + if a >= len(l.buckets) { + l.buckets = append(l.buckets, new([eventsBucketSize]Event)) + } + ptr := &l.buckets[a][b] + l.n++ + return ptr +} + +// append appends v to the slice and returns a pointer to the new element. +func (l *Events) append(v Event) *Event { + ptr := l.grow() + *ptr = v + return ptr +} + +func (l *Events) Ptr(i int) *Event { + a, b := l.index(i + l.off) + return &l.buckets[a][b] +} + +func (l *Events) index(i int) (int, int) { + // Doing the division on uint instead of int compiles this function to a + // shift and an AND (for power of 2 bucket sizes), versus a whole bunch of + // instructions for int. + return int(uint(i) / eventsBucketSize), int(uint(i) % eventsBucketSize) +} + +func (l *Events) Len() int { + return l.n - l.off +} + +func (l *Events) Less(i, j int) bool { + return l.Ptr(i).Ts < l.Ptr(j).Ts +} + +func (l *Events) Swap(i, j int) { + *l.Ptr(i), *l.Ptr(j) = *l.Ptr(j), *l.Ptr(i) +} + +func (l *Events) Pop() (*Event, bool) { + if l.off == l.n { + return nil, false + } + a, b := l.index(l.off) + ptr := &l.buckets[a][b] + l.off++ + if b == eventsBucketSize-1 || l.off == l.n { + // We've consumed the last event from the bucket, so drop the bucket and + // allow GC to collect it. + l.buckets[a] = nil + } + return ptr, true +} + +func (l *Events) Peek() (*Event, bool) { + if l.off == l.n { + return nil, false + } + a, b := l.index(l.off) + return &l.buckets[a][b], true +} + +func (l *Events) All() func(yield func(ev *Event) bool) { + return func(yield func(ev *Event) bool) { + for i := 0; i < l.Len(); i++ { + a, b := l.index(i + l.off) + ptr := &l.buckets[a][b] + if !yield(ptr) { + return + } + } + } +} + +// parseEventBatches reads per-P event batches and merges them into a single, consistent +// stream. The high level idea is as follows. Events within an individual batch +// are in correct order, because they are emitted by a single P. So we need to +// produce a correct interleaving of the batches. To do this we take first +// unmerged event from each batch (frontier). Then choose subset that is "ready" +// to be merged, that is, events for which all dependencies are already merged. +// Then we choose event with the lowest timestamp from the subset, merge it and +// repeat. This approach ensures that we form a consistent stream even if +// timestamps are incorrect (condition observed on some machines). +func (p *parser) parseEventBatches() (Events, error) { + // The ordering of CPU profile sample events in the data stream is based on + // when each run of the signal handler was able to acquire the spinlock, + // with original timestamps corresponding to when ReadTrace pulled the data + // off of the profBuf queue. Re-sort them by the timestamp we captured + // inside the signal handler. + slices.SortFunc(p.cpuSamples, func(a, b Event) int { + return cmp.Compare(a.Ts, b.Ts) + }) + + allProcs := make([]proc, 0, len(p.batchOffsets)) + for pid := range p.batchOffsets { + allProcs = append(allProcs, proc{pid: pid}) + } + allProcs = append(allProcs, proc{pid: ProfileP, events: p.cpuSamples}) + + events := Events{} + + // Merge events as long as at least one P has more events + gs := make(map[uint64]gState) + // Note: technically we don't need a priority queue here. We're only ever + // interested in the earliest eligible event, which means we just have to + // track the smallest element. However, in practice, the priority queue + // performs better, because for each event we only have to compute its state + // transition once, not on each iteration. If it was eligible before, it'll + // already be in the queue. Furthermore, on average, we only have one P to + // look at in each iteration, because all other Ps are already in the queue. + var frontier orderEventList + + availableProcs := make([]*proc, len(allProcs)) + for i := range allProcs { + availableProcs[i] = &allProcs[i] + } + for { + pidLoop: + for i := 0; i < len(availableProcs); i++ { + proc := availableProcs[i] + + for len(proc.events) == 0 { + // Call loadBatch in a loop because sometimes batches are empty + evs, err := p.loadBatch(proc.pid, proc.buf[:0]) + proc.buf = evs[:0] + if err == io.EOF { + // This P has no more events + proc.done = true + availableProcs[i], availableProcs[len(availableProcs)-1] = availableProcs[len(availableProcs)-1], availableProcs[i] + availableProcs = availableProcs[:len(availableProcs)-1] + // We swapped the element at i with another proc, so look at + // the index again + i-- + continue pidLoop + } else if err != nil { + return Events{}, err + } else { + proc.events = evs + } + } + + ev := &proc.events[0] + g, init, _ := stateTransition(ev) + + // TODO(dh): This implementation matches the behavior of the + // upstream 'go tool trace', and works in practice, but has run into + // the following inconsistency during fuzzing: what happens if + // multiple Ps have events for the same G? While building the + // frontier we will check all of the events against the current + // state of the G. However, when we process the frontier, the state + // of the G changes, and a transition that was valid while building + // the frontier may no longer be valid when processing the frontier. + // Is this something that can happen for real, valid traces, or is + // this only possible with corrupt data? + if !transitionReady(g, gs[g], init) { + continue + } + proc.events = proc.events[1:] + availableProcs[i], availableProcs[len(availableProcs)-1] = availableProcs[len(availableProcs)-1], availableProcs[i] + availableProcs = availableProcs[:len(availableProcs)-1] + frontier.Push(orderEvent{*ev, proc}) + + // We swapped the element at i with another proc, so look at the + // index again + i-- + } + + if len(frontier) == 0 { + for i := range allProcs { + if !allProcs[i].done { + return Events{}, fmt.Errorf("no consistent ordering of events possible") + } + } + break + } + f := frontier.Pop() + + // We're computing the state transition twice, once when computing the + // frontier, and now to apply the transition. This is fine because + // stateTransition is a pure function. Computing it again is cheaper + // than storing large items in the frontier. + g, init, next := stateTransition(&f.ev) + + // Get rid of "Local" events, they are intended merely for ordering. + switch f.ev.Type { + case EvGoStartLocal: + f.ev.Type = EvGoStart + case EvGoUnblockLocal: + f.ev.Type = EvGoUnblock + case EvGoSysExitLocal: + f.ev.Type = EvGoSysExit + } + events.append(f.ev) + + if err := transition(gs, g, init, next); err != nil { + return Events{}, err + } + availableProcs = append(availableProcs, f.proc) + } + + // At this point we have a consistent stream of events. Make sure time + // stamps respect the ordering. The tests will skip (not fail) the test case + // if they see this error. + if !sort.IsSorted(&events) { + return Events{}, ErrTimeOrder + } + + // The last part is giving correct timestamps to EvGoSysExit events. The + // problem with EvGoSysExit is that actual syscall exit timestamp + // (ev.Args[2]) is potentially acquired long before event emission. So far + // we've used timestamp of event emission (ev.Ts). We could not set ev.Ts = + // ev.Args[2] earlier, because it would produce seemingly broken timestamps + // (misplaced event). We also can't simply update the timestamp and resort + // events, because if timestamps are broken we will misplace the event and + // later report logically broken trace (instead of reporting broken + // timestamps). + lastSysBlock := make(map[uint64]Timestamp) + for i := 0; i < events.Len(); i++ { + ev := events.Ptr(i) + switch ev.Type { + case EvGoSysBlock, EvGoInSyscall: + lastSysBlock[ev.G] = ev.Ts + case EvGoSysExit: + ts := Timestamp(ev.Args[2]) + if ts == 0 { + continue + } + block := lastSysBlock[ev.G] + if block == 0 { + return Events{}, fmt.Errorf("stray syscall exit") + } + if ts < block { + return Events{}, ErrTimeOrder + } + ev.Ts = ts + } + } + sort.Stable(&events) + + return events, nil +} + +// collectBatchesAndCPUSamples records the offsets of batches and parses CPU samples. +func (p *parser) collectBatchesAndCPUSamples() error { + // Read events. + var raw rawEvent + var curP int32 + for n := uint64(0); ; n++ { + err := p.readRawEvent(skipArgs|skipStrings, &raw) + if err == io.EOF { + break + } + if err != nil { + return err + } + if raw.typ == EvNone { + continue + } + + if raw.typ == EvBatch { + bo := batchOffset{offset: raw.batchOffset} + p.batchOffsets[raw.batchPid] = append(p.batchOffsets[raw.batchPid], bo) + curP = raw.batchPid + } + + batches := p.batchOffsets[curP] + if len(batches) == 0 { + return fmt.Errorf("read event %d with current P of %d, but P has no batches yet", + raw.typ, curP) + } + batches[len(batches)-1].numEvents++ + + if raw.typ == EvCPUSample { + e := Event{Type: raw.typ} + + argOffset := 1 + narg := raw.argNum() + if len(raw.args) != narg { + return fmt.Errorf("CPU sample has wrong number of arguments: want %d, got %d", narg, len(raw.args)) + } + for i := argOffset; i < narg; i++ { + if i == narg-1 { + e.StkID = uint32(raw.args[i]) + } else { + e.Args[i-argOffset] = raw.args[i] + } + } + + e.Ts = Timestamp(e.Args[0]) + e.P = int32(e.Args[1]) + e.G = e.Args[2] + e.Args[0] = 0 + + // Most events are written out by the active P at the exact moment + // they describe. CPU profile samples are different because they're + // written to the tracing log after some delay, by a separate worker + // goroutine, into a separate buffer. + // + // We keep these in their own batch until all of the batches are + // merged in timestamp order. We also (right before the merge) + // re-sort these events by the timestamp captured in the profiling + // signal handler. + // + // Note that we're not concerned about the memory usage of storing + // all CPU samples during the indexing phase. There are orders of + // magnitude fewer CPU samples than runtime events. + p.cpuSamples = append(p.cpuSamples, e) + } + } + + return nil +} + +const ( + skipArgs = 1 << iota + skipStrings +) + +func (p *parser) readByte() (byte, bool) { + if p.off < len(p.data) && p.off >= 0 { + b := p.data[p.off] + p.off++ + return b, true + } else { + return 0, false + } +} + +func (p *parser) readFull(n int) ([]byte, error) { + if p.off >= len(p.data) || p.off < 0 || p.off+n > len(p.data) { + // p.off < 0 is impossible but makes BCE happy. + // + // We do fail outright if there's not enough data, we don't care about + // partial results. + return nil, io.ErrUnexpectedEOF + } + buf := p.data[p.off : p.off+n] + p.off += n + return buf, nil +} + +// readRawEvent reads a raw event into ev. The slices in ev are only valid until +// the next call to readRawEvent, even when storing to a different location. +func (p *parser) readRawEvent(flags uint, ev *rawEvent) error { + // The number of arguments is encoded using two bits and can thus only + // represent the values 0–3. The value 3 (on the wire) indicates that + // arguments are prefixed by their byte length, to encode >=3 arguments. + const inlineArgs = 3 + + // Read event type and number of arguments (1 byte). + b, ok := p.readByte() + if !ok { + return io.EOF + } + typ := EventType(b << 2 >> 2) + // Most events have a timestamp before the actual arguments, so we add 1 and + // parse it like it's the first argument. EvString has a special format and + // the number of arguments doesn't matter. EvBatch writes '1' as the number + // of arguments, but actually has two: a pid and a timestamp, but here the + // timestamp is the second argument, not the first; adding 1 happens to come + // up with the correct number, but it doesn't matter, because EvBatch has + // custom logic for parsing. + // + // Note that because we're adding 1, inlineArgs == 3 describes the largest + // number of logical arguments that isn't length-prefixed, even though the + // value 3 on the wire indicates length-prefixing. For us, that becomes narg + // == 4. + narg := b>>6 + 1 + if typ == EvNone || typ >= EvCount || EventDescriptions[typ].minVersion > p.ver { + return fmt.Errorf("unknown event type %d", typ) + } + + switch typ { + case EvString: + if flags&skipStrings != 0 { + // String dictionary entry [ID, length, string]. + if _, err := p.readVal(); err != nil { + return errMalformedVarint + } + ln, err := p.readVal() + if err != nil { + return err + } + if !p.discard(ln) { + return fmt.Errorf("failed to read trace: %w", io.EOF) + } + } else { + // String dictionary entry [ID, length, string]. + id, err := p.readVal() + if err != nil { + return err + } + if id == 0 { + return errors.New("string has invalid id 0") + } + if p.strings[id] != "" { + return fmt.Errorf("string has duplicate id %d", id) + } + var ln uint64 + ln, err = p.readVal() + if err != nil { + return err + } + if ln == 0 { + return errors.New("string has invalid length 0") + } + if ln > 1e6 { + return fmt.Errorf("string has too large length %d", ln) + } + buf, err := p.readFull(int(ln)) + if err != nil { + return fmt.Errorf("failed to read trace: %w", err) + } + p.strings[id] = string(buf) + } + + ev.typ = EvNone + return nil + case EvBatch: + if want := byte(2); narg != want { + return fmt.Errorf("EvBatch has wrong number of arguments: got %d, want %d", narg, want) + } + + // -1 because we've already read the first byte of the batch + off := p.off - 1 + + pid, err := p.readVal() + if err != nil { + return err + } + if pid != math.MaxUint64 && pid > math.MaxInt32 { + return fmt.Errorf("processor ID %d is larger than maximum of %d", pid, uint64(math.MaxUint)) + } + + var pid32 int32 + if pid == math.MaxUint64 { + pid32 = -1 + } else { + pid32 = int32(pid) + } + + v, err := p.readVal() + if err != nil { + return err + } + + *ev = rawEvent{ + typ: EvBatch, + args: p.args[:0], + batchPid: pid32, + batchOffset: off, + } + ev.args = append(ev.args, pid, v) + return nil + default: + *ev = rawEvent{typ: typ, args: p.args[:0]} + if narg <= inlineArgs { + if flags&skipArgs == 0 { + for i := 0; i < int(narg); i++ { + v, err := p.readVal() + if err != nil { + return fmt.Errorf("failed to read event %d argument: %w", typ, err) + } + ev.args = append(ev.args, v) + } + } else { + for i := 0; i < int(narg); i++ { + if _, err := p.readVal(); err != nil { + return fmt.Errorf("failed to read event %d argument: %w", typ, errMalformedVarint) + } + } + } + } else { + // More than inlineArgs args, the first value is length of the event + // in bytes. + v, err := p.readVal() + if err != nil { + return fmt.Errorf("failed to read event %d argument: %w", typ, err) + } + + if limit := uint64(2048); v > limit { + // At the time of Go 1.19, v seems to be at most 128. Set 2048 + // as a generous upper limit and guard against malformed traces. + return fmt.Errorf("failed to read event %d argument: length-prefixed argument too big: %d bytes, limit is %d", typ, v, limit) + } + + if flags&skipArgs == 0 || typ == EvCPUSample { + buf, err := p.readFull(int(v)) + if err != nil { + return fmt.Errorf("failed to read trace: %w", err) + } + for len(buf) > 0 { + var v uint64 + v, buf, err = readValFrom(buf) + if err != nil { + return err + } + ev.args = append(ev.args, v) + } + } else { + // Skip over arguments + if !p.discard(v) { + return fmt.Errorf("failed to read trace: %w", io.EOF) + } + } + if typ == EvUserLog { + // EvUserLog records are followed by a value string + if flags&skipArgs == 0 { + // Read string + s, err := p.readStr() + if err != nil { + return err + } + ev.sargs = append(ev.sargs, s) + } else { + // Skip string + v, err := p.readVal() + if err != nil { + return err + } + if !p.discard(v) { + return io.EOF + } + } + } + } + + p.args = ev.args[:0] + return nil + } +} + +// loadBatch loads the next batch for pid and appends its contents to events. +func (p *parser) loadBatch(pid int32, events []Event) ([]Event, error) { + offsets := p.batchOffsets[pid] + if len(offsets) == 0 { + return nil, io.EOF + } + n := offsets[0].numEvents + offset := offsets[0].offset + offsets = offsets[1:] + p.batchOffsets[pid] = offsets + + p.off = offset + + if cap(events) < n { + events = make([]Event, 0, n) + } + + gotHeader := false + var raw rawEvent + var ev Event + for { + err := p.readRawEvent(0, &raw) + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + if raw.typ == EvNone || raw.typ == EvCPUSample { + continue + } + if raw.typ == EvBatch { + if gotHeader { + break + } else { + gotHeader = true + } + } + + err = p.parseEvent(&raw, &ev) + if err != nil { + return nil, err + } + if ev.Type != EvNone { + events = append(events, ev) + } + } + + return events, nil +} + +func (p *parser) readStr() (s string, err error) { + sz, err := p.readVal() + if err != nil { + return "", err + } + if sz == 0 { + return "", nil + } + if sz > 1e6 { + return "", fmt.Errorf("string is too large (len=%d)", sz) + } + buf, err := p.readFull(int(sz)) + if err != nil { + return "", fmt.Errorf("failed to read trace: %w", err) + } + return string(buf), nil +} + +// parseEvent transforms raw events into events. +// It does analyze and verify per-event-type arguments. +func (p *parser) parseEvent(raw *rawEvent, ev *Event) error { + desc := &EventDescriptions[raw.typ] + if desc.Name == "" { + return fmt.Errorf("missing description for event type %d", raw.typ) + } + narg := raw.argNum() + if len(raw.args) != narg { + return fmt.Errorf("%s has wrong number of arguments: want %d, got %d", desc.Name, narg, len(raw.args)) + } + switch raw.typ { + case EvBatch: + p.lastGs[p.lastP] = p.lastG + if raw.args[0] != math.MaxUint64 && raw.args[0] > math.MaxInt32 { + return fmt.Errorf("processor ID %d is larger than maximum of %d", raw.args[0], uint64(math.MaxInt32)) + } + if raw.args[0] == math.MaxUint64 { + p.lastP = -1 + } else { + p.lastP = int32(raw.args[0]) + } + p.lastG = p.lastGs[p.lastP] + p.lastTs = Timestamp(raw.args[1]) + case EvFrequency: + p.ticksPerSec = int64(raw.args[0]) + if p.ticksPerSec <= 0 { + // The most likely cause for this is tick skew on different CPUs. + // For example, solaris/amd64 seems to have wildly different + // ticks on different CPUs. + return ErrTimeOrder + } + case EvTimerGoroutine: + p.timerGoids[raw.args[0]] = true + case EvStack: + if len(raw.args) < 2 { + return fmt.Errorf("EvStack has wrong number of arguments: want at least 2, got %d", len(raw.args)) + } + size := raw.args[1] + if size > 1000 { + return fmt.Errorf("EvStack has bad number of frames: %d", size) + } + want := 2 + 4*size + if uint64(len(raw.args)) != want { + return fmt.Errorf("EvStack has wrong number of arguments: want %d, got %d", want, len(raw.args)) + } + id := uint32(raw.args[0]) + if id != 0 && size > 0 { + stk := p.allocateStack(size) + for i := 0; i < int(size); i++ { + pc := raw.args[2+i*4+0] + fn := raw.args[2+i*4+1] + file := raw.args[2+i*4+2] + line := raw.args[2+i*4+3] + stk[i] = pc + + if _, ok := p.pcs[pc]; !ok { + p.pcs[pc] = Frame{PC: pc, Fn: fn, File: file, Line: int(line)} + } + } + p.stacks[id] = stk + } + case EvCPUSample: + // These events get parsed during the indexing step and don't strictly + // belong to the batch. + default: + *ev = Event{Type: raw.typ, P: p.lastP, G: p.lastG} + var argOffset int + ev.Ts = p.lastTs + Timestamp(raw.args[0]) + argOffset = 1 + p.lastTs = ev.Ts + for i := argOffset; i < narg; i++ { + if i == narg-1 && desc.Stack { + ev.StkID = uint32(raw.args[i]) + } else { + ev.Args[i-argOffset] = raw.args[i] + } + } + switch raw.typ { + case EvGoStart, EvGoStartLocal, EvGoStartLabel: + p.lastG = ev.Args[0] + ev.G = p.lastG + case EvGoEnd, EvGoStop, EvGoSched, EvGoPreempt, + EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv, + EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, + EvGoSysBlock, EvGoBlockGC: + p.lastG = 0 + case EvGoSysExit, EvGoWaiting, EvGoInSyscall: + ev.G = ev.Args[0] + case EvUserTaskCreate: + // e.Args 0: taskID, 1:parentID, 2:nameID + case EvUserRegion: + // e.Args 0: taskID, 1: mode, 2:nameID + case EvUserLog: + // e.Args 0: taskID, 1:keyID, 2: stackID, 3: messageID + // raw.sargs 0: message + + if id, ok := p.inlineStringsMapping[raw.sargs[0]]; ok { + ev.Args[3] = uint64(id) + } else { + id := len(p.inlineStrings) + p.inlineStringsMapping[raw.sargs[0]] = id + p.inlineStrings = append(p.inlineStrings, raw.sargs[0]) + ev.Args[3] = uint64(id) + } + } + + return nil + } + + ev.Type = EvNone + return nil +} + +// ErrTimeOrder is returned by Parse when the trace contains +// time stamps that do not respect actual event ordering. +var ErrTimeOrder = errors.New("time stamps out of order") + +// postProcessTrace does inter-event verification and information restoration. +// The resulting trace is guaranteed to be consistent +// (for example, a P does not run two Gs at the same time, or a G is indeed +// blocked before an unblock event). +func (p *parser) postProcessTrace(events Events) error { + const ( + gDead = iota + gRunnable + gRunning + gWaiting + ) + type gdesc struct { + state int + ev *Event + evStart *Event + evCreate *Event + evMarkAssist *Event + } + type pdesc struct { + running bool + g uint64 + evSweep *Event + } + + gs := make(map[uint64]gdesc) + ps := make(map[int32]pdesc) + tasks := make(map[uint64]*Event) // task id to task creation events + activeRegions := make(map[uint64][]*Event) // goroutine id to stack of regions + gs[0] = gdesc{state: gRunning} + var evGC, evSTW *Event + + checkRunning := func(p pdesc, g gdesc, ev *Event, allowG0 bool) error { + name := EventDescriptions[ev.Type].Name + if g.state != gRunning { + return fmt.Errorf("g %d is not running while %s (time %d)", ev.G, name, ev.Ts) + } + if p.g != ev.G { + return fmt.Errorf("p %d is not running g %d while %s (time %d)", ev.P, ev.G, name, ev.Ts) + } + if !allowG0 && ev.G == 0 { + return fmt.Errorf("g 0 did %s (time %d)", name, ev.Ts) + } + return nil + } + + for evIdx := 0; evIdx < events.Len(); evIdx++ { + ev := events.Ptr(evIdx) + + switch ev.Type { + case EvProcStart: + p := ps[ev.P] + if p.running { + return fmt.Errorf("p %d is running before start (time %d)", ev.P, ev.Ts) + } + p.running = true + + ps[ev.P] = p + case EvProcStop: + p := ps[ev.P] + if !p.running { + return fmt.Errorf("p %d is not running before stop (time %d)", ev.P, ev.Ts) + } + if p.g != 0 { + return fmt.Errorf("p %d is running a goroutine %d during stop (time %d)", ev.P, p.g, ev.Ts) + } + p.running = false + + ps[ev.P] = p + case EvGCStart: + if evGC != nil { + return fmt.Errorf("previous GC is not ended before a new one (time %d)", ev.Ts) + } + evGC = ev + // Attribute this to the global GC state. + ev.P = GCP + case EvGCDone: + if evGC == nil { + return fmt.Errorf("bogus GC end (time %d)", ev.Ts) + } + evGC = nil + case EvSTWStart: + evp := &evSTW + if *evp != nil { + return fmt.Errorf("previous STW is not ended before a new one (time %d)", ev.Ts) + } + *evp = ev + case EvSTWDone: + evp := &evSTW + if *evp == nil { + return fmt.Errorf("bogus STW end (time %d)", ev.Ts) + } + *evp = nil + case EvGCSweepStart: + p := ps[ev.P] + if p.evSweep != nil { + return fmt.Errorf("previous sweeping is not ended before a new one (time %d)", ev.Ts) + } + p.evSweep = ev + + ps[ev.P] = p + case EvGCMarkAssistStart: + g := gs[ev.G] + if g.evMarkAssist != nil { + return fmt.Errorf("previous mark assist is not ended before a new one (time %d)", ev.Ts) + } + g.evMarkAssist = ev + + gs[ev.G] = g + case EvGCMarkAssistDone: + // Unlike most events, mark assists can be in progress when a + // goroutine starts tracing, so we can't report an error here. + g := gs[ev.G] + if g.evMarkAssist != nil { + g.evMarkAssist = nil + } + + gs[ev.G] = g + case EvGCSweepDone: + p := ps[ev.P] + if p.evSweep == nil { + return fmt.Errorf("bogus sweeping end (time %d)", ev.Ts) + } + p.evSweep = nil + + ps[ev.P] = p + case EvGoWaiting: + g := gs[ev.G] + if g.state != gRunnable { + return fmt.Errorf("g %d is not runnable before EvGoWaiting (time %d)", ev.G, ev.Ts) + } + g.state = gWaiting + g.ev = ev + + gs[ev.G] = g + case EvGoInSyscall: + g := gs[ev.G] + if g.state != gRunnable { + return fmt.Errorf("g %d is not runnable before EvGoInSyscall (time %d)", ev.G, ev.Ts) + } + g.state = gWaiting + g.ev = ev + + gs[ev.G] = g + case EvGoCreate: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, true); err != nil { + return err + } + if _, ok := gs[ev.Args[0]]; ok { + return fmt.Errorf("g %d already exists (time %d)", ev.Args[0], ev.Ts) + } + gs[ev.Args[0]] = gdesc{state: gRunnable, ev: ev, evCreate: ev} + + case EvGoStart, EvGoStartLabel: + g := gs[ev.G] + p := ps[ev.P] + if g.state != gRunnable { + return fmt.Errorf("g %d is not runnable before start (time %d)", ev.G, ev.Ts) + } + if p.g != 0 { + return fmt.Errorf("p %d is already running g %d while start g %d (time %d)", ev.P, p.g, ev.G, ev.Ts) + } + g.state = gRunning + g.evStart = ev + p.g = ev.G + if g.evCreate != nil { + ev.StkID = uint32(g.evCreate.Args[1]) + g.evCreate = nil + } + + if g.ev != nil { + g.ev = nil + } + + gs[ev.G] = g + ps[ev.P] = p + case EvGoEnd, EvGoStop: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, false); err != nil { + return err + } + g.evStart = nil + g.state = gDead + p.g = 0 + + if ev.Type == EvGoEnd { // flush all active regions + delete(activeRegions, ev.G) + } + + gs[ev.G] = g + ps[ev.P] = p + case EvGoSched, EvGoPreempt: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, false); err != nil { + return err + } + g.state = gRunnable + g.evStart = nil + p.g = 0 + g.ev = ev + + gs[ev.G] = g + ps[ev.P] = p + case EvGoUnblock: + g := gs[ev.G] + p := ps[ev.P] + if g.state != gRunning { + return fmt.Errorf("g %d is not running while unpark (time %d)", ev.G, ev.Ts) + } + if ev.P != TimerP && p.g != ev.G { + return fmt.Errorf("p %d is not running g %d while unpark (time %d)", ev.P, ev.G, ev.Ts) + } + g1 := gs[ev.Args[0]] + if g1.state != gWaiting { + return fmt.Errorf("g %d is not waiting before unpark (time %d)", ev.Args[0], ev.Ts) + } + if g1.ev != nil && g1.ev.Type == EvGoBlockNet { + ev.P = NetpollP + } + g1.state = gRunnable + g1.ev = ev + gs[ev.Args[0]] = g1 + + case EvGoSysCall: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, false); err != nil { + return err + } + g.ev = ev + + gs[ev.G] = g + case EvGoSysBlock: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, false); err != nil { + return err + } + g.state = gWaiting + g.evStart = nil + p.g = 0 + + gs[ev.G] = g + ps[ev.P] = p + case EvGoSysExit: + g := gs[ev.G] + if g.state != gWaiting { + return fmt.Errorf("g %d is not waiting during syscall exit (time %d)", ev.G, ev.Ts) + } + g.state = gRunnable + g.ev = ev + + gs[ev.G] = g + case EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv, + EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, EvGoBlockGC: + g := gs[ev.G] + p := ps[ev.P] + if err := checkRunning(p, g, ev, false); err != nil { + return err + } + g.state = gWaiting + g.ev = ev + g.evStart = nil + p.g = 0 + + gs[ev.G] = g + ps[ev.P] = p + case EvUserTaskCreate: + taskid := ev.Args[0] + if prevEv, ok := tasks[taskid]; ok { + return fmt.Errorf("task id conflicts (id:%d), %q vs %q", taskid, ev, prevEv) + } + tasks[ev.Args[0]] = ev + + case EvUserTaskEnd: + taskid := ev.Args[0] + delete(tasks, taskid) + + case EvUserRegion: + mode := ev.Args[1] + regions := activeRegions[ev.G] + if mode == 0 { // region start + activeRegions[ev.G] = append(regions, ev) // push + } else if mode == 1 { // region end + n := len(regions) + if n > 0 { // matching region start event is in the trace. + s := regions[n-1] + if s.Args[0] != ev.Args[0] || s.Args[2] != ev.Args[2] { // task id, region name mismatch + return fmt.Errorf("misuse of region in goroutine %d: span end %q when the inner-most active span start event is %q", ev.G, ev, s) + } + + if n > 1 { + activeRegions[ev.G] = regions[:n-1] + } else { + delete(activeRegions, ev.G) + } + } + } else { + return fmt.Errorf("invalid user region mode: %q", ev) + } + } + + if ev.StkID != 0 && len(p.stacks[ev.StkID]) == 0 { + // Make sure events don't refer to stacks that don't exist or to + // stacks with zero frames. Neither of these should be possible, but + // better be safe than sorry. + + ev.StkID = 0 + } + + } + + // TODO(mknyszek): restore stacks for EvGoStart events. + return nil +} + +var errMalformedVarint = errors.New("malformatted base-128 varint") + +// readVal reads unsigned base-128 value from r. +func (p *parser) readVal() (uint64, error) { + v, n := binary.Uvarint(p.data[p.off:]) + if n <= 0 { + return 0, errMalformedVarint + } + p.off += n + return v, nil +} + +func readValFrom(buf []byte) (v uint64, rem []byte, err error) { + v, n := binary.Uvarint(buf) + if n <= 0 { + return 0, nil, errMalformedVarint + } + return v, buf[n:], nil +} + +func (ev *Event) String() string { + desc := &EventDescriptions[ev.Type] + w := new(bytes.Buffer) + fmt.Fprintf(w, "%d %s p=%d g=%d stk=%d", ev.Ts, desc.Name, ev.P, ev.G, ev.StkID) + for i, a := range desc.Args { + fmt.Fprintf(w, " %s=%d", a, ev.Args[i]) + } + return w.String() +} + +// argNum returns total number of args for the event accounting for timestamps, +// sequence numbers and differences between trace format versions. +func (raw *rawEvent) argNum() int { + desc := &EventDescriptions[raw.typ] + if raw.typ == EvStack { + return len(raw.args) + } + narg := len(desc.Args) + if desc.Stack { + narg++ + } + switch raw.typ { + case EvBatch, EvFrequency, EvTimerGoroutine: + return narg + } + narg++ // timestamp + return narg +} + +type EventType uint8 + +// Event types in the trace. +// Verbatim copy from src/runtime/trace.go with the "trace" prefix removed. +const ( + EvNone EventType = 0 // unused + EvBatch EventType = 1 // start of per-P batch of events [pid, timestamp] + EvFrequency EventType = 2 // contains tracer timer frequency [frequency (ticks per second)] + EvStack EventType = 3 // stack [stack id, number of PCs, array of {PC, func string ID, file string ID, line}] + EvGomaxprocs EventType = 4 // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id] + EvProcStart EventType = 5 // start of P [timestamp, thread id] + EvProcStop EventType = 6 // stop of P [timestamp] + EvGCStart EventType = 7 // GC start [timestamp, seq, stack id] + EvGCDone EventType = 8 // GC done [timestamp] + EvSTWStart EventType = 9 // GC mark termination start [timestamp, kind] + EvSTWDone EventType = 10 // GC mark termination done [timestamp] + EvGCSweepStart EventType = 11 // GC sweep start [timestamp, stack id] + EvGCSweepDone EventType = 12 // GC sweep done [timestamp, swept, reclaimed] + EvGoCreate EventType = 13 // goroutine creation [timestamp, new goroutine id, new stack id, stack id] + EvGoStart EventType = 14 // goroutine starts running [timestamp, goroutine id, seq] + EvGoEnd EventType = 15 // goroutine ends [timestamp] + EvGoStop EventType = 16 // goroutine stops (like in select{}) [timestamp, stack] + EvGoSched EventType = 17 // goroutine calls Gosched [timestamp, stack] + EvGoPreempt EventType = 18 // goroutine is preempted [timestamp, stack] + EvGoSleep EventType = 19 // goroutine calls Sleep [timestamp, stack] + EvGoBlock EventType = 20 // goroutine blocks [timestamp, stack] + EvGoUnblock EventType = 21 // goroutine is unblocked [timestamp, goroutine id, seq, stack] + EvGoBlockSend EventType = 22 // goroutine blocks on chan send [timestamp, stack] + EvGoBlockRecv EventType = 23 // goroutine blocks on chan recv [timestamp, stack] + EvGoBlockSelect EventType = 24 // goroutine blocks on select [timestamp, stack] + EvGoBlockSync EventType = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack] + EvGoBlockCond EventType = 26 // goroutine blocks on Cond [timestamp, stack] + EvGoBlockNet EventType = 27 // goroutine blocks on network [timestamp, stack] + EvGoSysCall EventType = 28 // syscall enter [timestamp, stack] + EvGoSysExit EventType = 29 // syscall exit [timestamp, goroutine id, seq, real timestamp] + EvGoSysBlock EventType = 30 // syscall blocks [timestamp] + EvGoWaiting EventType = 31 // denotes that goroutine is blocked when tracing starts [timestamp, goroutine id] + EvGoInSyscall EventType = 32 // denotes that goroutine is in syscall when tracing starts [timestamp, goroutine id] + EvHeapAlloc EventType = 33 // gcController.heapLive change [timestamp, heap live bytes] + EvHeapGoal EventType = 34 // gcController.heapGoal change [timestamp, heap goal bytes] + EvTimerGoroutine EventType = 35 // denotes timer goroutine [timer goroutine id] + EvFutileWakeup EventType = 36 // denotes that the previous wakeup of this goroutine was futile [timestamp] + EvString EventType = 37 // string dictionary entry [ID, length, string] + EvGoStartLocal EventType = 38 // goroutine starts running on the same P as the last event [timestamp, goroutine id] + EvGoUnblockLocal EventType = 39 // goroutine is unblocked on the same P as the last event [timestamp, goroutine id, stack] + EvGoSysExitLocal EventType = 40 // syscall exit on the same P as the last event [timestamp, goroutine id, real timestamp] + EvGoStartLabel EventType = 41 // goroutine starts running with label [timestamp, goroutine id, seq, label string id] + EvGoBlockGC EventType = 42 // goroutine blocks on GC assist [timestamp, stack] + EvGCMarkAssistStart EventType = 43 // GC mark assist start [timestamp, stack] + EvGCMarkAssistDone EventType = 44 // GC mark assist done [timestamp] + EvUserTaskCreate EventType = 45 // trace.NewTask [timestamp, internal task id, internal parent id, stack, name string] + EvUserTaskEnd EventType = 46 // end of task [timestamp, internal task id, stack] + EvUserRegion EventType = 47 // trace.WithRegion [timestamp, internal task id, mode(0:start, 1:end), name string] + EvUserLog EventType = 48 // trace.Log [timestamp, internal id, key string id, stack, value string] + EvCPUSample EventType = 49 // CPU profiling sample [timestamp, stack, real timestamp, real P id (-1 when absent), goroutine id] + EvCount EventType = 50 +) + +var EventDescriptions = [256]struct { + Name string + minVersion version.Version + Stack bool + Args []string + SArgs []string // string arguments +}{ + EvNone: {"None", 5, false, []string{}, nil}, + EvBatch: {"Batch", 5, false, []string{"p", "ticks"}, nil}, // in 1.5 format it was {"p", "seq", "ticks"} + EvFrequency: {"Frequency", 5, false, []string{"freq"}, nil}, // in 1.5 format it was {"freq", "unused"} + EvStack: {"Stack", 5, false, []string{"id", "siz"}, nil}, + EvGomaxprocs: {"Gomaxprocs", 5, true, []string{"procs"}, nil}, + EvProcStart: {"ProcStart", 5, false, []string{"thread"}, nil}, + EvProcStop: {"ProcStop", 5, false, []string{}, nil}, + EvGCStart: {"GCStart", 5, true, []string{"seq"}, nil}, // in 1.5 format it was {} + EvGCDone: {"GCDone", 5, false, []string{}, nil}, + EvSTWStart: {"GCSTWStart", 5, false, []string{"kindid"}, []string{"kind"}}, // <= 1.9, args was {} (implicitly {0}) + EvSTWDone: {"GCSTWDone", 5, false, []string{}, nil}, + EvGCSweepStart: {"GCSweepStart", 5, true, []string{}, nil}, + EvGCSweepDone: {"GCSweepDone", 5, false, []string{"swept", "reclaimed"}, nil}, // before 1.9, format was {} + EvGoCreate: {"GoCreate", 5, true, []string{"g", "stack"}, nil}, + EvGoStart: {"GoStart", 5, false, []string{"g", "seq"}, nil}, // in 1.5 format it was {"g"} + EvGoEnd: {"GoEnd", 5, false, []string{}, nil}, + EvGoStop: {"GoStop", 5, true, []string{}, nil}, + EvGoSched: {"GoSched", 5, true, []string{}, nil}, + EvGoPreempt: {"GoPreempt", 5, true, []string{}, nil}, + EvGoSleep: {"GoSleep", 5, true, []string{}, nil}, + EvGoBlock: {"GoBlock", 5, true, []string{}, nil}, + EvGoUnblock: {"GoUnblock", 5, true, []string{"g", "seq"}, nil}, // in 1.5 format it was {"g"} + EvGoBlockSend: {"GoBlockSend", 5, true, []string{}, nil}, + EvGoBlockRecv: {"GoBlockRecv", 5, true, []string{}, nil}, + EvGoBlockSelect: {"GoBlockSelect", 5, true, []string{}, nil}, + EvGoBlockSync: {"GoBlockSync", 5, true, []string{}, nil}, + EvGoBlockCond: {"GoBlockCond", 5, true, []string{}, nil}, + EvGoBlockNet: {"GoBlockNet", 5, true, []string{}, nil}, + EvGoSysCall: {"GoSysCall", 5, true, []string{}, nil}, + EvGoSysExit: {"GoSysExit", 5, false, []string{"g", "seq", "ts"}, nil}, + EvGoSysBlock: {"GoSysBlock", 5, false, []string{}, nil}, + EvGoWaiting: {"GoWaiting", 5, false, []string{"g"}, nil}, + EvGoInSyscall: {"GoInSyscall", 5, false, []string{"g"}, nil}, + EvHeapAlloc: {"HeapAlloc", 5, false, []string{"mem"}, nil}, + EvHeapGoal: {"HeapGoal", 5, false, []string{"mem"}, nil}, + EvTimerGoroutine: {"TimerGoroutine", 5, false, []string{"g"}, nil}, // in 1.5 format it was {"g", "unused"} + EvFutileWakeup: {"FutileWakeup", 5, false, []string{}, nil}, + EvString: {"String", 7, false, []string{}, nil}, + EvGoStartLocal: {"GoStartLocal", 7, false, []string{"g"}, nil}, + EvGoUnblockLocal: {"GoUnblockLocal", 7, true, []string{"g"}, nil}, + EvGoSysExitLocal: {"GoSysExitLocal", 7, false, []string{"g", "ts"}, nil}, + EvGoStartLabel: {"GoStartLabel", 8, false, []string{"g", "seq", "labelid"}, []string{"label"}}, + EvGoBlockGC: {"GoBlockGC", 8, true, []string{}, nil}, + EvGCMarkAssistStart: {"GCMarkAssistStart", 9, true, []string{}, nil}, + EvGCMarkAssistDone: {"GCMarkAssistDone", 9, false, []string{}, nil}, + EvUserTaskCreate: {"UserTaskCreate", 11, true, []string{"taskid", "pid", "typeid"}, []string{"name"}}, + EvUserTaskEnd: {"UserTaskEnd", 11, true, []string{"taskid"}, nil}, + EvUserRegion: {"UserRegion", 11, true, []string{"taskid", "mode", "typeid"}, []string{"name"}}, + EvUserLog: {"UserLog", 11, true, []string{"id", "keyid"}, []string{"category", "message"}}, + EvCPUSample: {"CPUSample", 19, true, []string{"ts", "p", "g"}, nil}, +} + +//gcassert:inline +func (p *parser) allocateStack(size uint64) []uint64 { + if size == 0 { + return nil + } + + // Stacks are plentiful but small. For our "Staticcheck on std" trace with + // 11e6 events, we have roughly 500,000 stacks, using 200 MiB of memory. To + // avoid making 500,000 small allocations we allocate backing arrays 1 MiB + // at a time. + out := p.stacksData + if uint64(len(out)) < size { + out = make([]uint64, 1024*128) + } + p.stacksData = out[size:] + return out[:size:size] +} + +func (tr *Trace) STWReason(kindID uint64) STWReason { + if tr.Version < 21 { + if kindID == 0 || kindID == 1 { + return STWReason(kindID + 1) + } else { + return STWUnknown + } + } else if tr.Version == 21 { + if kindID < NumSTWReasons { + return STWReason(kindID) + } else { + return STWUnknown + } + } else { + return STWUnknown + } +} + +type STWReason int + +const ( + STWUnknown STWReason = 0 + STWGCMarkTermination STWReason = 1 + STWGCSweepTermination STWReason = 2 + STWWriteHeapDump STWReason = 3 + STWGoroutineProfile STWReason = 4 + STWGoroutineProfileCleanup STWReason = 5 + STWAllGoroutinesStackTrace STWReason = 6 + STWReadMemStats STWReason = 7 + STWAllThreadsSyscall STWReason = 8 + STWGOMAXPROCS STWReason = 9 + STWStartTrace STWReason = 10 + STWStopTrace STWReason = 11 + STWCountPagesInUse STWReason = 12 + STWReadMetricsSlow STWReason = 13 + STWReadMemStatsSlow STWReason = 14 + STWPageCachePagesLeaked STWReason = 15 + STWResetDebugLog STWReason = 16 + + NumSTWReasons = 17 +) diff --git a/go/src/internal/trace/internal/tracev1/parser_test.go b/go/src/internal/trace/internal/tracev1/parser_test.go new file mode 100644 index 0000000000000000000000000000000000000000..af6d8db2340eabc8eba6494c364c01e15b66aa1b --- /dev/null +++ b/go/src/internal/trace/internal/tracev1/parser_test.go @@ -0,0 +1,151 @@ +// 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 tracev1 + +import ( + "bytes" + "internal/trace/version" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCorruptedInputs(t *testing.T) { + // These inputs crashed parser previously. + tests := []string{ + "gotrace\x00\x020", + "gotrace\x00Q00\x020", + "gotrace\x00T00\x020", + "gotrace\x00\xc3\x0200", + "go 1.5 trace\x00\x00\x00\x00\x020", + "go 1.5 trace\x00\x00\x00\x00Q00\x020", + "go 1.5 trace\x00\x00\x00\x00T00\x020", + "go 1.5 trace\x00\x00\x00\x00\xc3\x0200", + } + for _, data := range tests { + res, err := Parse(strings.NewReader(data), 5) + if err == nil || res.Events.Len() != 0 || res.Stacks != nil { + t.Fatalf("no error on input: %q", data) + } + } +} + +func TestParseCanned(t *testing.T) { + files, err := os.ReadDir("./testdata") + if err != nil { + t.Fatalf("failed to read ./testdata: %v", err) + } + for _, f := range files { + info, err := f.Info() + if err != nil { + t.Fatal(err) + } + if testing.Short() && info.Size() > 10000 { + continue + } + name := filepath.Join("./testdata", f.Name()) + data, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + r := bytes.NewReader(data) + v, err := version.ReadHeader(r) + if err != nil { + t.Errorf("failed to parse good trace %s: %s", f.Name(), err) + } + trace, err := Parse(r, v) + switch { + case strings.HasSuffix(f.Name(), "_good"): + if err != nil { + t.Errorf("failed to parse good trace %v: %v", f.Name(), err) + } + checkTrace(t, int(v), trace) + case strings.HasSuffix(f.Name(), "_unordered"): + if err != ErrTimeOrder { + t.Errorf("unordered trace is not detected %v: %v", f.Name(), err) + } + default: + t.Errorf("unknown input file suffix: %v", f.Name()) + } + } +} + +// checkTrace walks over a good trace and makes a bunch of additional checks +// that may not cause the parser to outright fail. +func checkTrace(t *testing.T, ver int, res Trace) { + for i := 0; i < res.Events.Len(); i++ { + ev := res.Events.Ptr(i) + if ver >= 21 { + if ev.Type == EvSTWStart && res.Strings[ev.Args[0]] == "unknown" { + t.Errorf("found unknown STW event; update stwReasonStrings?") + } + } + } +} + +func TestBuckets(t *testing.T) { + var evs Events + + const N = eventsBucketSize*3 + 123 + for i := 0; i < N; i++ { + evs.append(Event{Ts: Timestamp(i)}) + } + + if n := len(evs.buckets); n != 4 { + t.Fatalf("got %d buckets, want %d", n, 4) + } + + if n := evs.Len(); n != N { + t.Fatalf("got %d events, want %d", n, N) + } + + var n int + evs.All()(func(ev *Event) bool { + n++ + return true + }) + if n != N { + t.Fatalf("iterated over %d events, expected %d", n, N) + } + + const consume = eventsBucketSize + 50 + for i := 0; i < consume; i++ { + if _, ok := evs.Pop(); !ok { + t.Fatalf("iteration failed after %d events", i) + } + } + + if evs.buckets[0] != nil { + t.Fatalf("expected first bucket to have been dropped") + } + for i, b := range evs.buckets[1:] { + if b == nil { + t.Fatalf("expected bucket %d to be non-nil", i+1) + } + } + + if n := evs.Len(); n != N-consume { + t.Fatalf("got %d remaining elements, expected %d", n, N-consume) + } + + ev := evs.Ptr(0) + if ev.Ts != consume { + t.Fatalf("got event %d, expected %d", int(ev.Ts), consume) + } + + for { + _, ok := evs.Pop() + if !ok { + break + } + } + + for i, b := range evs.buckets { + if b != nil { + t.Fatalf("expected bucket %d to be nil", i) + } + } +} diff --git a/go/src/internal/trace/internal/tracev1/testdata/fmt_1_21_pprof_good b/go/src/internal/trace/internal/tracev1/testdata/fmt_1_21_pprof_good new file mode 100644 index 0000000000000000000000000000000000000000..f3ea402fdb33b68b3a7c52a465c88e8e4424e074 Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/fmt_1_21_pprof_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/http_1_19_good b/go/src/internal/trace/internal/tracev1/testdata/http_1_19_good new file mode 100644 index 0000000000000000000000000000000000000000..c1d519e7d5da8d3b32eac715a32871c78bd619db Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/http_1_19_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/http_1_21_good b/go/src/internal/trace/internal/tracev1/testdata/http_1_21_good new file mode 100644 index 0000000000000000000000000000000000000000..b3295f9e5d760cb78cd0f574a764f5c207a489ed Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/http_1_21_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_11_good b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_11_good new file mode 100644 index 0000000000000000000000000000000000000000..457f01a6cdec08a1ab02e3fb486ee0534140d467 Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_11_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_19_good b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_19_good new file mode 100644 index 0000000000000000000000000000000000000000..92d92789c4f2562ecf94b816af5a0232bc88c5b6 Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_19_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_21_good b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_21_good new file mode 100644 index 0000000000000000000000000000000000000000..fff46a9a071b7727a0f2585c776b13d2e290c3da Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/stress_start_stop_1_21_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_11_good b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_11_good new file mode 100644 index 0000000000000000000000000000000000000000..f4edb67e6565dc62f6d9ab8968f0aa1124255132 Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_11_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_19_good b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_19_good new file mode 100644 index 0000000000000000000000000000000000000000..1daa3b25a6c64d8620c85fedb1fb46d287e72882 Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_19_good differ diff --git a/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_21_good b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_21_good new file mode 100644 index 0000000000000000000000000000000000000000..5c01a6405d8da87275b38ff777523fd56a66fc5c Binary files /dev/null and b/go/src/internal/trace/internal/tracev1/testdata/user_task_region_1_21_good differ diff --git a/go/src/internal/trace/mud.go b/go/src/internal/trace/mud.go new file mode 100644 index 0000000000000000000000000000000000000000..5292de364ef8a345d1db2b675d3cd4e14842bb71 --- /dev/null +++ b/go/src/internal/trace/mud.go @@ -0,0 +1,224 @@ +// 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 trace + +import ( + "cmp" + "math" + "slices" +) + +// mud is an updatable mutator utilization distribution. +// +// This is a continuous distribution of duration over mutator +// utilization. For example, the integral from mutator utilization a +// to b is the total duration during which the mutator utilization was +// in the range [a, b]. +// +// This distribution is *not* normalized (it is not a probability +// distribution). This makes it easier to work with as it's being +// updated. +// +// It is represented as the sum of scaled uniform distribution +// functions and Dirac delta functions (which are treated as +// degenerate uniform distributions). +type mud struct { + sorted, unsorted []edge + + // trackMass is the inverse cumulative sum to track as the + // distribution is updated. + trackMass float64 + // trackBucket is the bucket in which trackMass falls. If the + // total mass of the distribution is < trackMass, this is + // len(hist). + trackBucket int + // trackSum is the cumulative sum of hist[:trackBucket]. Once + // trackSum >= trackMass, trackBucket must be recomputed. + trackSum float64 + + // hist is a hierarchical histogram of distribution mass. + hist [mudDegree]float64 +} + +const ( + // mudDegree is the number of buckets in the MUD summary + // histogram. + mudDegree = 1024 +) + +type edge struct { + // At x, the function increases by y. + x, delta float64 + // Additionally at x is a Dirac delta function with area dirac. + dirac float64 +} + +// add adds a uniform function over [l, r] scaled so the total weight +// of the uniform is area. If l==r, this adds a Dirac delta function. +func (d *mud) add(l, r, area float64) { + if area == 0 { + return + } + + if r < l { + l, r = r, l + } + + // Add the edges. + if l == r { + d.unsorted = append(d.unsorted, edge{l, 0, area}) + } else { + delta := area / (r - l) + d.unsorted = append(d.unsorted, edge{l, delta, 0}, edge{r, -delta, 0}) + } + + // Update the histogram. + h := &d.hist + lbFloat, lf := math.Modf(l * mudDegree) + lb := int(lbFloat) + if lb >= mudDegree { + lb, lf = mudDegree-1, 1 + } + if l == r { + h[lb] += area + } else { + rbFloat, rf := math.Modf(r * mudDegree) + rb := int(rbFloat) + if rb >= mudDegree { + rb, rf = mudDegree-1, 1 + } + if lb == rb { + h[lb] += area + } else { + perBucket := area / (r - l) / mudDegree + h[lb] += perBucket * (1 - lf) + h[rb] += perBucket * rf + for i := lb + 1; i < rb; i++ { + h[i] += perBucket + } + } + } + + // Update mass tracking. + if thresh := float64(d.trackBucket) / mudDegree; l < thresh { + if r < thresh { + d.trackSum += area + } else { + d.trackSum += area * (thresh - l) / (r - l) + } + if d.trackSum >= d.trackMass { + // The tracked mass now falls in a different + // bucket. Recompute the inverse cumulative sum. + d.setTrackMass(d.trackMass) + } + } +} + +// setTrackMass sets the mass to track the inverse cumulative sum for. +// +// Specifically, mass is a cumulative duration, and the mutator +// utilization bounds for this duration can be queried using +// approxInvCumulativeSum. +func (d *mud) setTrackMass(mass float64) { + d.trackMass = mass + + // Find the bucket currently containing trackMass by computing + // the cumulative sum. + sum := 0.0 + for i, val := range d.hist[:] { + newSum := sum + val + if newSum > mass { + // mass falls in bucket i. + d.trackBucket = i + d.trackSum = sum + return + } + sum = newSum + } + d.trackBucket = len(d.hist) + d.trackSum = sum +} + +// approxInvCumulativeSum is like invCumulativeSum, but specifically +// operates on the tracked mass and returns an upper and lower bound +// approximation of the inverse cumulative sum. +// +// The true inverse cumulative sum will be in the range [lower, upper). +func (d *mud) approxInvCumulativeSum() (float64, float64, bool) { + if d.trackBucket == len(d.hist) { + return math.NaN(), math.NaN(), false + } + return float64(d.trackBucket) / mudDegree, float64(d.trackBucket+1) / mudDegree, true +} + +// invCumulativeSum returns x such that the integral of d from -∞ to x +// is y. If the total weight of d is less than y, it returns the +// maximum of the distribution and false. +// +// Specifically, y is a cumulative duration, and invCumulativeSum +// returns the mutator utilization x such that at least y time has +// been spent with mutator utilization <= x. +func (d *mud) invCumulativeSum(y float64) (float64, bool) { + if len(d.sorted) == 0 && len(d.unsorted) == 0 { + return math.NaN(), false + } + + // Sort edges. + edges := d.unsorted + slices.SortFunc(edges, func(a, b edge) int { + return cmp.Compare(a.x, b.x) + }) + // Merge with sorted edges. + d.unsorted = nil + if d.sorted == nil { + d.sorted = edges + } else { + oldSorted := d.sorted + newSorted := make([]edge, len(oldSorted)+len(edges)) + i, j := 0, 0 + for o := range newSorted { + if i >= len(oldSorted) { + copy(newSorted[o:], edges[j:]) + break + } else if j >= len(edges) { + copy(newSorted[o:], oldSorted[i:]) + break + } else if oldSorted[i].x < edges[j].x { + newSorted[o] = oldSorted[i] + i++ + } else { + newSorted[o] = edges[j] + j++ + } + } + d.sorted = newSorted + } + + // Traverse edges in order computing a cumulative sum. + csum, rate, prevX := 0.0, 0.0, 0.0 + for _, e := range d.sorted { + newCsum := csum + (e.x-prevX)*rate + if newCsum >= y { + // y was exceeded between the previous edge + // and this one. + if rate == 0 { + // Anywhere between prevX and + // e.x will do. We return e.x + // because that takes care of + // the y==0 case naturally. + return e.x, true + } + return (y-csum)/rate + prevX, true + } + newCsum += e.dirac + if newCsum >= y { + // y was exceeded by the Dirac delta at e.x. + return e.x, true + } + csum, prevX = newCsum, e.x + rate += e.delta + } + return prevX, false +} diff --git a/go/src/internal/trace/mud_test.go b/go/src/internal/trace/mud_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9856442cffbd070c45c87f7251138f9670722c54 --- /dev/null +++ b/go/src/internal/trace/mud_test.go @@ -0,0 +1,100 @@ +// 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 trace + +import ( + "math" + "math/rand" + "testing" +) + +func TestMUD(t *testing.T) { + // Insert random uniforms and check histogram mass and + // cumulative sum approximations. + rnd := rand.New(rand.NewSource(42)) + mass := 0.0 + var mud mud + for i := 0; i < 100; i++ { + area, l, r := rnd.Float64(), rnd.Float64(), rnd.Float64() + if rnd.Intn(10) == 0 { + r = l + } + t.Log(l, r, area) + mud.add(l, r, area) + mass += area + + // Check total histogram weight. + hmass := 0.0 + for _, val := range mud.hist { + hmass += val + } + if !aeq(mass, hmass) { + t.Fatalf("want mass %g, got %g", mass, hmass) + } + + // Check inverse cumulative sum approximations. + for j := 0.0; j < mass; j += mass * 0.099 { + mud.setTrackMass(j) + l, u, ok := mud.approxInvCumulativeSum() + inv, ok2 := mud.invCumulativeSum(j) + if !ok || !ok2 { + t.Fatalf("inverse cumulative sum failed: approx %v, exact %v", ok, ok2) + } + if !(l <= inv && inv < u) { + t.Fatalf("inverse(%g) = %g, not ∈ [%g, %g)", j, inv, l, u) + } + } + } +} + +func TestMUDTracking(t *testing.T) { + // Test that the tracked mass is tracked correctly across + // updates. + rnd := rand.New(rand.NewSource(42)) + const uniforms = 100 + for trackMass := 0.0; trackMass < uniforms; trackMass += uniforms / 50 { + var mud mud + mass := 0.0 + mud.setTrackMass(trackMass) + for i := 0; i < uniforms; i++ { + area, l, r := rnd.Float64(), rnd.Float64(), rnd.Float64() + mud.add(l, r, area) + mass += area + l, u, ok := mud.approxInvCumulativeSum() + inv, ok2 := mud.invCumulativeSum(trackMass) + + if mass < trackMass { + if ok { + t.Errorf("approx(%g) = [%g, %g), but mass = %g", trackMass, l, u, mass) + } + if ok2 { + t.Errorf("exact(%g) = %g, but mass = %g", trackMass, inv, mass) + } + } else { + if !ok { + t.Errorf("approx(%g) failed, but mass = %g", trackMass, mass) + } + if !ok2 { + t.Errorf("exact(%g) failed, but mass = %g", trackMass, mass) + } + if ok && ok2 && !(l <= inv && inv < u) { + t.Errorf("inverse(%g) = %g, not ∈ [%g, %g)", trackMass, inv, l, u) + } + } + } + } +} + +// aeq returns true if x and y are equal up to 8 digits (1 part in 100 +// million). +// TODO(amedee) dup of gc_test.go +func aeq(x, y float64) bool { + if x < 0 && y < 0 { + x, y = -x, -y + } + const digits = 8 + factor := 1 - math.Pow(10, -digits+1) + return x*factor <= y && y*factor <= x +} diff --git a/go/src/internal/trace/order.go b/go/src/internal/trace/order.go new file mode 100644 index 0000000000000000000000000000000000000000..7b6075d56377320a0ad3060874976a84e2b38b22 --- /dev/null +++ b/go/src/internal/trace/order.go @@ -0,0 +1,1420 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "fmt" + "slices" + "strings" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// ordering emulates Go scheduler state for both validation and +// for putting events in the right order. +// +// The interface to ordering consists of two methods: Advance +// and Next. Advance is called to try and advance an event and +// add completed events to the ordering. Next is used to pick +// off events in the ordering. +type ordering struct { + traceVer version.Version + gStates map[GoID]*gState + pStates map[ProcID]*pState // TODO: The keys are dense, so this can be a slice. + mStates map[ThreadID]*mState + activeTasks map[TaskID]taskState + gcSeq uint64 + gcState gcState + initialGen uint64 + queue queue[Event] +} + +// Advance checks if it's valid to proceed with ev which came from thread m. +// +// It assumes the gen value passed to it is monotonically increasing across calls. +// +// If any error is returned, then the trace is broken and trace parsing must cease. +// If it's not valid to advance with ev, but no error was encountered, the caller +// should attempt to advance with other candidate events from other threads. If the +// caller runs out of candidates, the trace is invalid. +// +// If this returns true, Next is guaranteed to return a complete event. However, +// multiple events may be added to the ordering, so the caller should (but is not +// required to) continue to call Next until it is exhausted. +func (o *ordering) Advance(ev *baseEvent, evt *evTable, m ThreadID, gen uint64) (bool, error) { + if o.initialGen == 0 { + // Set the initial gen if necessary. + o.initialGen = gen + } + + var curCtx, newCtx schedCtx + curCtx.M = m + newCtx.M = m + + var ms *mState + if m == NoThread { + curCtx.P = NoProc + curCtx.G = NoGoroutine + newCtx = curCtx + } else { + // Pull out or create the mState for this event. + var ok bool + ms, ok = o.mStates[m] + if !ok { + ms = &mState{ + g: NoGoroutine, + p: NoProc, + } + o.mStates[m] = ms + } + curCtx.P = ms.p + curCtx.G = ms.g + newCtx = curCtx + } + + f := orderingDispatch[ev.typ] + if f == nil { + return false, fmt.Errorf("bad event type found while ordering: %v", ev.typ) + } + newCtx, ok, err := f(o, ev, evt, m, gen, curCtx) + if err == nil && ok && ms != nil { + // Update the mState for this event. + ms.p = newCtx.P + ms.g = newCtx.G + } + return ok, err +} + +func (o *ordering) evName(typ tracev2.EventType) string { + return o.traceVer.EventName(typ) +} + +type orderingHandleFunc func(o *ordering, ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) + +var orderingDispatch = [256]orderingHandleFunc{ + // Procs. + tracev2.EvProcsChange: (*ordering).advanceAnnotation, + tracev2.EvProcStart: (*ordering).advanceProcStart, + tracev2.EvProcStop: (*ordering).advanceProcStop, + tracev2.EvProcSteal: (*ordering).advanceProcSteal, + tracev2.EvProcStatus: (*ordering).advanceProcStatus, + + // Goroutines. + tracev2.EvGoCreate: (*ordering).advanceGoCreate, + tracev2.EvGoCreateSyscall: (*ordering).advanceGoCreateSyscall, + tracev2.EvGoStart: (*ordering).advanceGoStart, + tracev2.EvGoDestroy: (*ordering).advanceGoStopExec, + tracev2.EvGoDestroySyscall: (*ordering).advanceGoDestroySyscall, + tracev2.EvGoStop: (*ordering).advanceGoStopExec, + tracev2.EvGoBlock: (*ordering).advanceGoStopExec, + tracev2.EvGoUnblock: (*ordering).advanceGoUnblock, + tracev2.EvGoSyscallBegin: (*ordering).advanceGoSyscallBegin, + tracev2.EvGoSyscallEnd: (*ordering).advanceGoSyscallEnd, + tracev2.EvGoSyscallEndBlocked: (*ordering).advanceGoSyscallEndBlocked, + tracev2.EvGoStatus: (*ordering).advanceGoStatus, + + // STW. + tracev2.EvSTWBegin: (*ordering).advanceGoRangeBegin, + tracev2.EvSTWEnd: (*ordering).advanceGoRangeEnd, + + // GC events. + tracev2.EvGCActive: (*ordering).advanceGCActive, + tracev2.EvGCBegin: (*ordering).advanceGCBegin, + tracev2.EvGCEnd: (*ordering).advanceGCEnd, + tracev2.EvGCSweepActive: (*ordering).advanceGCSweepActive, + tracev2.EvGCSweepBegin: (*ordering).advanceGCSweepBegin, + tracev2.EvGCSweepEnd: (*ordering).advanceGCSweepEnd, + tracev2.EvGCMarkAssistActive: (*ordering).advanceGoRangeActive, + tracev2.EvGCMarkAssistBegin: (*ordering).advanceGoRangeBegin, + tracev2.EvGCMarkAssistEnd: (*ordering).advanceGoRangeEnd, + tracev2.EvHeapAlloc: (*ordering).advanceHeapMetric, + tracev2.EvHeapGoal: (*ordering).advanceHeapMetric, + + // Annotations. + tracev2.EvGoLabel: (*ordering).advanceAnnotation, + tracev2.EvUserTaskBegin: (*ordering).advanceUserTaskBegin, + tracev2.EvUserTaskEnd: (*ordering).advanceUserTaskEnd, + tracev2.EvUserRegionBegin: (*ordering).advanceUserRegionBegin, + tracev2.EvUserRegionEnd: (*ordering).advanceUserRegionEnd, + tracev2.EvUserLog: (*ordering).advanceAnnotation, + + // Coroutines. Added in Go 1.23. + tracev2.EvGoSwitch: (*ordering).advanceGoSwitch, + tracev2.EvGoSwitchDestroy: (*ordering).advanceGoSwitch, + tracev2.EvGoCreateBlocked: (*ordering).advanceGoCreate, + + // GoStatus event with a stack. Added in Go 1.23. + tracev2.EvGoStatusStack: (*ordering).advanceGoStatus, + + // Experimental events. + + // Experimental heap span events. Added in Go 1.23. + tracev2.EvSpan: (*ordering).advanceAllocFree, + tracev2.EvSpanAlloc: (*ordering).advanceAllocFree, + tracev2.EvSpanFree: (*ordering).advanceAllocFree, + + // Experimental heap object events. Added in Go 1.23. + tracev2.EvHeapObject: (*ordering).advanceAllocFree, + tracev2.EvHeapObjectAlloc: (*ordering).advanceAllocFree, + tracev2.EvHeapObjectFree: (*ordering).advanceAllocFree, + + // Experimental goroutine stack events. Added in Go 1.23. + tracev2.EvGoroutineStack: (*ordering).advanceAllocFree, + tracev2.EvGoroutineStackAlloc: (*ordering).advanceAllocFree, + tracev2.EvGoroutineStackFree: (*ordering).advanceAllocFree, +} + +func (o *ordering) advanceProcStatus(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + pid := ProcID(ev.args[0]) + status := tracev2.ProcStatus(ev.args[1]) + if int(status) >= len(tracev2ProcStatus2ProcState) { + return curCtx, false, fmt.Errorf("invalid status for proc %d: %d", pid, status) + } + oldState := tracev2ProcStatus2ProcState[status] + if s, ok := o.pStates[pid]; ok { + if status == tracev2.ProcSyscallAbandoned && s.status == tracev2.ProcSyscall { + // ProcSyscallAbandoned is a special case of ProcSyscall. It indicates a + // potential loss of information, but if we're already in ProcSyscall, + // we haven't lost the relevant information. Promote the status and advance. + oldState = ProcRunning + ev.args[1] = uint64(tracev2.ProcSyscall) + } else if status == tracev2.ProcSyscallAbandoned && s.status == tracev2.ProcSyscallAbandoned { + // If we're passing through ProcSyscallAbandoned, then there's no promotion + // to do. We've lost the M that this P is associated with. However it got there, + // it's going to appear as idle in the API, so pass through as idle. + oldState = ProcIdle + ev.args[1] = uint64(tracev2.ProcSyscallAbandoned) + } else if s.status != status { + return curCtx, false, fmt.Errorf("inconsistent status for proc %d: old %v vs. new %v", pid, s.status, status) + } + s.seq = makeSeq(gen, 0) // Reset seq. + } else { + o.pStates[pid] = &pState{id: pid, status: status, seq: makeSeq(gen, 0)} + if gen == o.initialGen { + oldState = ProcUndetermined + } else { + oldState = ProcNotExist + } + } + ev.extra(version.Go122)[0] = uint64(oldState) // Smuggle in the old state for StateTransition. + + // Bind the proc to the new context, if it's running. + newCtx := curCtx + if status == tracev2.ProcRunning || status == tracev2.ProcSyscall { + newCtx.P = pid + } + // If we're advancing through ProcSyscallAbandoned *but* oldState is running then we've + // promoted it to ProcSyscall. However, because it's ProcSyscallAbandoned, we know this + // P is about to get stolen and its status very likely isn't being emitted by the same + // thread it was bound to. Since this status is Running -> Running and Running is binding, + // we need to make sure we emit it in the right context: the context to which it is bound. + // Find it, and set our current context to it. + if status == tracev2.ProcSyscallAbandoned && oldState == ProcRunning { + // N.B. This is slow but it should be fairly rare. + found := false + for mid, ms := range o.mStates { + if ms.p == pid { + curCtx.M = mid + curCtx.P = pid + curCtx.G = ms.g + found = true + } + } + if !found { + return curCtx, false, fmt.Errorf("failed to find sched context for proc %d that's about to be stolen", pid) + } + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceProcStart(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + pid := ProcID(ev.args[0]) + seq := makeSeq(gen, ev.args[1]) + + // Try to advance. We might fail here due to sequencing, because the P hasn't + // had a status emitted, or because we already have a P and we're in a syscall, + // and we haven't observed that it was stolen from us yet. + state, ok := o.pStates[pid] + if !ok || state.status != tracev2.ProcIdle || !seq.succeeds(state.seq) || curCtx.P != NoProc { + // We can't make an inference as to whether this is bad. We could just be seeing + // a ProcStart on a different M before the proc's state was emitted, or before we + // got to the right point in the trace. + // + // Note that we also don't advance here if we have a P and we're in a syscall. + return curCtx, false, nil + } + // We can advance this P. Check some invariants. + // + // We might have a goroutine if a goroutine is exiting a syscall. + reqs := schedReqs{M: mustHave, P: mustNotHave, G: mayHave} + if err := validateCtx(curCtx, reqs); err != nil { + return curCtx, false, err + } + state.status = tracev2.ProcRunning + state.seq = seq + newCtx := curCtx + newCtx.P = pid + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceProcStop(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // We must be able to advance this P. + // + // There are 2 ways a P can stop: ProcStop and ProcSteal. ProcStop is used when the P + // is stopped by the same M that started it, while ProcSteal is used when another M + // steals the P by stopping it from a distance. + // + // Since a P is bound to an M, and we're stopping on the same M we started, it must + // always be possible to advance the current M's P from a ProcStop. This is also why + // ProcStop doesn't need a sequence number. + state, ok := o.pStates[curCtx.P] + if !ok { + return curCtx, false, fmt.Errorf("event %s for proc (%v) that doesn't exist", o.evName(ev.typ), curCtx.P) + } + if state.status != tracev2.ProcRunning && state.status != tracev2.ProcSyscall { + return curCtx, false, fmt.Errorf("%s event for proc that's not %s or %s", o.evName(ev.typ), tracev2.ProcRunning, tracev2.ProcSyscall) + } + reqs := schedReqs{M: mustHave, P: mustHave, G: mayHave} + if err := validateCtx(curCtx, reqs); err != nil { + return curCtx, false, err + } + state.status = tracev2.ProcIdle + newCtx := curCtx + newCtx.P = NoProc + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceProcSteal(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + pid := ProcID(ev.args[0]) + seq := makeSeq(gen, ev.args[1]) + state, ok := o.pStates[pid] + if !ok || (state.status != tracev2.ProcSyscall && state.status != tracev2.ProcSyscallAbandoned) || !seq.succeeds(state.seq) { + // We can't make an inference as to whether this is bad. We could just be seeing + // a ProcStart on a different M before the proc's state was emitted, or before we + // got to the right point in the trace. + return curCtx, false, nil + } + // We can advance this P. Check some invariants. + reqs := schedReqs{M: mustHave, P: mayHave, G: mayHave} + if err := validateCtx(curCtx, reqs); err != nil { + return curCtx, false, err + } + // Smuggle in the P state that let us advance so we can surface information to the event. + // Specifically, we need to make sure that the event is interpreted not as a transition of + // ProcRunning -> ProcIdle but ProcIdle -> ProcIdle instead. + // + // ProcRunning is binding, but we may be running with a P on the current M and we can't + // bind another P. This P is about to go ProcIdle anyway. + oldStatus := state.status + ev.extra(version.Go122)[0] = uint64(oldStatus) + + // Update the P's status and sequence number. + state.status = tracev2.ProcIdle + state.seq = seq + + // If we've lost information then don't try to do anything with the M. + // It may have moved on and we can't be sure. + if oldStatus == tracev2.ProcSyscallAbandoned { + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil + } + + // Validate that the M we're stealing from is what we expect. + mid := ThreadID(ev.args[2]) // The M we're stealing from. + + newCtx := curCtx + if mid == curCtx.M { + // We're stealing from ourselves. This behaves like a ProcStop. + if curCtx.P != pid { + return curCtx, false, fmt.Errorf("tried to self-steal proc %d (thread %d), but got proc %d instead", pid, mid, curCtx.P) + } + newCtx.P = NoProc + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil + } + + // We're stealing from some other M. + mState, ok := o.mStates[mid] + if !ok { + return curCtx, false, fmt.Errorf("stole proc from non-existent thread %d", mid) + } + + // Make sure we're actually stealing the right P. + if mState.p != pid { + return curCtx, false, fmt.Errorf("tried to steal proc %d from thread %d, but got proc %d instead", pid, mid, mState.p) + } + + // Tell the M it has no P so it can proceed. + // + // This is safe because we know the P was in a syscall and + // the other M must be trying to get out of the syscall. + // GoSyscallEndBlocked cannot advance until the corresponding + // M loses its P. + mState.p = NoProc + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoStatus(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + gid := GoID(ev.args[0]) + mid := ThreadID(ev.args[1]) + status := tracev2.GoStatus(ev.args[2]) + + if int(status) >= len(tracev2GoStatus2GoState) { + return curCtx, false, fmt.Errorf("invalid status for goroutine %d: %d", gid, status) + } + oldState := tracev2GoStatus2GoState[status] + if s, ok := o.gStates[gid]; ok { + if s.status != status { + return curCtx, false, fmt.Errorf("inconsistent status for goroutine %d: old %v vs. new %v", gid, s.status, status) + } + s.seq = makeSeq(gen, 0) // Reset seq. + } else if gen == o.initialGen { + // Set the state. + o.gStates[gid] = &gState{id: gid, status: status, seq: makeSeq(gen, 0)} + oldState = GoUndetermined + } else { + return curCtx, false, fmt.Errorf("found goroutine status for new goroutine after the first generation: id=%v status=%v", gid, status) + } + ev.args[2] = uint64(oldState)<<32 | uint64(status) // Smuggle in the old state for StateTransition. + + newCtx := curCtx + switch status { + case tracev2.GoRunning: + // Bind the goroutine to the new context, since it's running. + newCtx.G = gid + case tracev2.GoSyscall: + if mid == NoThread { + return curCtx, false, fmt.Errorf("found goroutine %d in syscall without a thread", gid) + } + // Is the syscall on this thread? If so, bind it to the context. + // Otherwise, we're talking about a G sitting in a syscall on an M. + // Validate the named M. + if mid == curCtx.M { + if gen != o.initialGen && curCtx.G != gid { + // If this isn't the first generation, we *must* have seen this + // binding occur already. Even if the G was blocked in a syscall + // for multiple generations since trace start, we would have seen + // a previous GoStatus event that bound the goroutine to an M. + return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, curCtx.G) + } + newCtx.G = gid + break + } + // Now we're talking about a thread and goroutine that have been + // blocked on a syscall for the entire generation. This case must + // not have a P; the runtime makes sure that all Ps are traced at + // the beginning of a generation, which involves taking a P back + // from every thread. + ms, ok := o.mStates[mid] + if ok { + // This M has been seen. That means we must have seen this + // goroutine go into a syscall on this thread at some point. + if ms.g != gid { + // But the G on the M doesn't match. Something's wrong. + return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, ms.g) + } + // This case is just a Syscall->Syscall event, which needs to + // appear as having the G currently bound to this M. + curCtx.G = ms.g + } else if !ok { + // The M hasn't been seen yet. That means this goroutine + // has just been sitting in a syscall on this M. Create + // a state for it. + o.mStates[mid] = &mState{g: gid, p: NoProc} + // Don't set curCtx.G in this case because this event is the + // binding event (and curCtx represents the "before" state). + } + // Update the current context to the M we're talking about. + curCtx.M = mid + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoCreate(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Goroutines must be created on a running P, but may or may not be created + // by a running goroutine. + reqs := schedReqs{M: mustHave, P: mustHave, G: mayHave} + if err := validateCtx(curCtx, reqs); err != nil { + return curCtx, false, err + } + // If we have a goroutine, it must be running. + if state, ok := o.gStates[curCtx.G]; ok && state.status != tracev2.GoRunning { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + // This goroutine created another. Add a state for it. + newgid := GoID(ev.args[0]) + if _, ok := o.gStates[newgid]; ok { + return curCtx, false, fmt.Errorf("tried to create goroutine (%v) that already exists", newgid) + } + status := tracev2.GoRunnable + if ev.typ == tracev2.EvGoCreateBlocked { + status = tracev2.GoWaiting + } + o.gStates[newgid] = &gState{id: newgid, status: status, seq: makeSeq(gen, 0)} + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoStopExec(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // These are goroutine events that all require an active running + // goroutine on some thread. They must *always* be advance-able, + // since running goroutines are bound to their M. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + state, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if state.status != tracev2.GoRunning { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + // Handle each case slightly differently; we just group them together + // because they have shared preconditions. + newCtx := curCtx + switch ev.typ { + case tracev2.EvGoDestroy: + // This goroutine is exiting itself. + delete(o.gStates, curCtx.G) + newCtx.G = NoGoroutine + case tracev2.EvGoStop: + // Goroutine stopped (yielded). It's runnable but not running on this M. + state.status = tracev2.GoRunnable + newCtx.G = NoGoroutine + case tracev2.EvGoBlock: + // Goroutine blocked. It's waiting now and not running on this M. + state.status = tracev2.GoWaiting + newCtx.G = NoGoroutine + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoStart(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + gid := GoID(ev.args[0]) + seq := makeSeq(gen, ev.args[1]) + state, ok := o.gStates[gid] + if !ok || state.status != tracev2.GoRunnable || !seq.succeeds(state.seq) { + // We can't make an inference as to whether this is bad. We could just be seeing + // a GoStart on a different M before the goroutine was created, before it had its + // state emitted, or before we got to the right point in the trace yet. + return curCtx, false, nil + } + // We can advance this goroutine. Check some invariants. + reqs := schedReqs{M: mustHave, P: mustHave, G: mustNotHave} + if err := validateCtx(curCtx, reqs); err != nil { + return curCtx, false, err + } + state.status = tracev2.GoRunning + state.seq = seq + newCtx := curCtx + newCtx.G = gid + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoUnblock(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // N.B. These both reference the goroutine to unblock, not the current goroutine. + gid := GoID(ev.args[0]) + seq := makeSeq(gen, ev.args[1]) + state, ok := o.gStates[gid] + if !ok || state.status != tracev2.GoWaiting || !seq.succeeds(state.seq) { + // We can't make an inference as to whether this is bad. We could just be seeing + // a GoUnblock on a different M before the goroutine was created and blocked itself, + // before it had its state emitted, or before we got to the right point in the trace yet. + return curCtx, false, nil + } + state.status = tracev2.GoRunnable + state.seq = seq + // N.B. No context to validate. Basically anything can unblock + // a goroutine (e.g. sysmon). + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoSwitch(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // GoSwitch and GoSwitchDestroy represent a trio of events: + // - Unblock of the goroutine to switch to. + // - Block or destroy of the current goroutine. + // - Start executing the next goroutine. + // + // Because it acts like a GoStart for the next goroutine, we can + // only advance it if the sequence numbers line up. + // + // The current goroutine on the thread must be actively running. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + curGState, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if curGState.status != tracev2.GoRunning { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + nextg := GoID(ev.args[0]) + seq := makeSeq(gen, ev.args[1]) // seq is for nextg, not curCtx.G. + nextGState, ok := o.gStates[nextg] + if !ok || nextGState.status != tracev2.GoWaiting || !seq.succeeds(nextGState.seq) { + // We can't make an inference as to whether this is bad. We could just be seeing + // a GoSwitch on a different M before the goroutine was created, before it had its + // state emitted, or before we got to the right point in the trace yet. + return curCtx, false, nil + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + + // Update the state of the executing goroutine and emit an event for it + // (GoSwitch and GoSwitchDestroy will be interpreted as GoUnblock events + // for nextg). + switch ev.typ { + case tracev2.EvGoSwitch: + // Goroutine blocked. It's waiting now and not running on this M. + curGState.status = tracev2.GoWaiting + + // Emit a GoBlock event. + // TODO(mknyszek): Emit a reason. + o.queue.push(makeEvent(evt, curCtx, tracev2.EvGoBlock, ev.time, 0 /* no reason */, 0 /* no stack */)) + case tracev2.EvGoSwitchDestroy: + // This goroutine is exiting itself. + delete(o.gStates, curCtx.G) + + // Emit a GoDestroy event. + o.queue.push(makeEvent(evt, curCtx, tracev2.EvGoDestroy, ev.time)) + } + // Update the state of the next goroutine. + nextGState.status = tracev2.GoRunning + nextGState.seq = seq + newCtx := curCtx + newCtx.G = nextg + + // Queue an event for the next goroutine starting to run. + startCtx := curCtx + startCtx.G = NoGoroutine + o.queue.push(makeEvent(evt, startCtx, tracev2.EvGoStart, ev.time, uint64(nextg), ev.args[1])) + return newCtx, true, nil +} + +func (o *ordering) advanceGoSyscallBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Entering a syscall requires an active running goroutine with a + // proc on some thread. It is always advancable. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + state, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if state.status != tracev2.GoRunning { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + // Goroutine entered a syscall. It's still running on this P and M. + state.status = tracev2.GoSyscall + pState, ok := o.pStates[curCtx.P] + if !ok { + return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ)) + } + pState.status = tracev2.ProcSyscall + // Validate the P sequence number on the event and advance it. + // + // We have a P sequence number for what is supposed to be a goroutine event + // so that we can correctly model P stealing. Without this sequence number here, + // the syscall from which a ProcSteal event is stealing can be ambiguous in the + // face of broken timestamps. See the go122-syscall-steal-proc-ambiguous test for + // more details. + // + // Note that because this sequence number only exists as a tool for disambiguation, + // we can enforce that we have the right sequence number at this point; we don't need + // to back off and see if any other events will advance. This is a running P. + pSeq := makeSeq(gen, ev.args[0]) + if !pSeq.succeeds(pState.seq) { + return curCtx, false, fmt.Errorf("failed to advance %s: can't make sequence: %s -> %s", o.evName(ev.typ), pState.seq, pSeq) + } + pState.seq = pSeq + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoSyscallEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // This event is always advance-able because it happens on the same + // thread that EvGoSyscallStart happened, and the goroutine can't leave + // that thread until its done. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + state, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if state.status != tracev2.GoSyscall { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + state.status = tracev2.GoRunning + + // Transfer the P back to running from syscall. + pState, ok := o.pStates[curCtx.P] + if !ok { + return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ)) + } + if pState.status != tracev2.ProcSyscall { + return curCtx, false, fmt.Errorf("expected proc %d in state %v, but got %v instead", curCtx.P, tracev2.ProcSyscall, pState.status) + } + pState.status = tracev2.ProcRunning + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoSyscallEndBlocked(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // This event becomes advanceable when its P is not in a syscall state + // (lack of a P altogether is also acceptable for advancing). + // The transfer out of ProcSyscall can happen either voluntarily via + // ProcStop or involuntarily via ProcSteal. We may also acquire a new P + // before we get here (after the transfer out) but that's OK: that new + // P won't be in the ProcSyscall state anymore. + // + // Basically: while we have a preemptible P, don't advance, because we + // *know* from the event that we're going to lose it at some point during + // the syscall. We shouldn't advance until that happens. + if curCtx.P != NoProc { + pState, ok := o.pStates[curCtx.P] + if !ok { + return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ)) + } + if pState.status == tracev2.ProcSyscall { + return curCtx, false, nil + } + } + // As mentioned above, we may have a P here if we ProcStart + // before this event. + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustHave}); err != nil { + return curCtx, false, err + } + state, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if state.status != tracev2.GoSyscall { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning) + } + newCtx := curCtx + newCtx.G = NoGoroutine + state.status = tracev2.GoRunnable + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoCreateSyscall(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // This event indicates that a goroutine is effectively + // being created out of a cgo callback. Such a goroutine + // is 'created' in the syscall state. + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustNotHave}); err != nil { + return curCtx, false, err + } + // This goroutine is effectively being created. Add a state for it. + newgid := GoID(ev.args[0]) + if _, ok := o.gStates[newgid]; ok { + return curCtx, false, fmt.Errorf("tried to create goroutine (%v) in syscall that already exists", newgid) + } + o.gStates[newgid] = &gState{id: newgid, status: tracev2.GoSyscall, seq: makeSeq(gen, 0)} + // Goroutine is executing. Bind it to the context. + newCtx := curCtx + newCtx.G = newgid + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceGoDestroySyscall(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // This event indicates that a goroutine created for a + // cgo callback is disappearing, either because the callback + // ending or the C thread that called it is being destroyed. + // + // Also, treat this as if we lost our P too. + // The thread ID may be reused by the platform and we'll get + // really confused if we try to steal the P is this is running + // with later. The new M with the same ID could even try to + // steal back this P from itself! + // + // The runtime is careful to make sure that any GoCreateSyscall + // event will enter the runtime emitting events for reacquiring a P. + // + // Note: we might have a P here. The P might not be released + // eagerly by the runtime, and it might get stolen back later + // (or never again, if the program is going to exit). + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustHave}); err != nil { + return curCtx, false, err + } + // Check to make sure the goroutine exists in the right state. + state, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G) + } + if state.status != tracev2.GoSyscall { + return curCtx, false, fmt.Errorf("%s event for goroutine that's not %v", o.evName(ev.typ), GoSyscall) + } + // This goroutine is exiting itself. + delete(o.gStates, curCtx.G) + newCtx := curCtx + newCtx.G = NoGoroutine + + // If we have a proc, then we're dissociating from it now. See the comment at the top of the case. + if curCtx.P != NoProc { + pState, ok := o.pStates[curCtx.P] + if !ok { + return curCtx, false, fmt.Errorf("found invalid proc %d during %s", curCtx.P, o.evName(ev.typ)) + } + if pState.status != tracev2.ProcSyscall { + return curCtx, false, fmt.Errorf("proc %d in unexpected state %s during %s", curCtx.P, pState.status, o.evName(ev.typ)) + } + // See the go122-create-syscall-reuse-thread-id test case for more details. + pState.status = tracev2.ProcSyscallAbandoned + newCtx.P = NoProc + + // Queue an extra self-ProcSteal event. + extra := makeEvent(evt, curCtx, tracev2.EvProcSteal, ev.time, uint64(curCtx.P)) + extra.base.extra(version.Go122)[0] = uint64(tracev2.ProcSyscall) + o.queue.push(extra) + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return newCtx, true, nil +} + +func (o *ordering) advanceUserTaskBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle tasks. Tasks are interesting because: + // - There's no Begin event required to reference a task. + // - End for a particular task ID can appear multiple times. + // As a result, there's very little to validate. The only + // thing we have to be sure of is that a task didn't begin + // after it had already begun. Task IDs are allowed to be + // reused, so we don't care about a Begin after an End. + id := TaskID(ev.args[0]) + if _, ok := o.activeTasks[id]; ok { + return curCtx, false, fmt.Errorf("task ID conflict: %d", id) + } + // Get the parent ID, but don't validate it. There's no guarantee + // we actually have information on whether it's active. + parentID := TaskID(ev.args[1]) + if parentID == BackgroundTask { + // Note: a value of 0 here actually means no parent, *not* the + // background task. Automatic background task attachment only + // applies to regions. + parentID = NoTask + ev.args[1] = uint64(NoTask) + } + + // Validate the name and record it. We'll need to pass it through to + // EvUserTaskEnd. + nameID := stringID(ev.args[2]) + name, ok := evt.strings.get(nameID) + if !ok { + return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ) + } + o.activeTasks[id] = taskState{name: name, parentID: parentID} + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceUserTaskEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + id := TaskID(ev.args[0]) + if ts, ok := o.activeTasks[id]; ok { + // Smuggle the task info. This may happen in a different generation, + // which may not have the name in its string table. Add it to the extra + // strings table so we can look it up later. + ev.extra(version.Go122)[0] = uint64(ts.parentID) + ev.extra(version.Go122)[1] = uint64(evt.addExtraString(ts.name)) + delete(o.activeTasks, id) + } else { + // Explicitly clear the task info. + ev.extra(version.Go122)[0] = uint64(NoTask) + ev.extra(version.Go122)[1] = uint64(evt.addExtraString("")) + } + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceUserRegionBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + tid := TaskID(ev.args[0]) + nameID := stringID(ev.args[1]) + name, ok := evt.strings.get(nameID) + if !ok { + return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ) + } + gState, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("encountered EvUserRegionBegin without known state for current goroutine %d", curCtx.G) + } + if err := gState.beginRegion(userRegion{tid, name}); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceUserRegionEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + tid := TaskID(ev.args[0]) + nameID := stringID(ev.args[1]) + name, ok := evt.strings.get(nameID) + if !ok { + return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ) + } + gState, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("encountered EvUserRegionEnd without known state for current goroutine %d", curCtx.G) + } + if err := gState.endRegion(userRegion{tid, name}); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +// Handle the GC mark phase. +// +// We have sequence numbers for both start and end because they +// can happen on completely different threads. We want an explicit +// partial order edge between start and end here, otherwise we're +// relying entirely on timestamps to make sure we don't advance a +// GCEnd for a _different_ GC cycle if timestamps are wildly broken. +func (o *ordering) advanceGCActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + seq := ev.args[0] + if gen == o.initialGen { + if o.gcState != gcUndetermined { + return curCtx, false, fmt.Errorf("GCActive in the first generation isn't first GC event") + } + o.gcSeq = seq + o.gcState = gcRunning + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil + } + if seq != o.gcSeq+1 { + // This is not the right GC cycle. + return curCtx, false, nil + } + if o.gcState != gcRunning { + return curCtx, false, fmt.Errorf("encountered GCActive while GC was not in progress") + } + o.gcSeq = seq + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGCBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + seq := ev.args[0] + if o.gcState == gcUndetermined { + o.gcSeq = seq + o.gcState = gcRunning + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil + } + if seq != o.gcSeq+1 { + // This is not the right GC cycle. + return curCtx, false, nil + } + if o.gcState == gcRunning { + return curCtx, false, fmt.Errorf("encountered GCBegin while GC was already in progress") + } + o.gcSeq = seq + o.gcState = gcRunning + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGCEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + seq := ev.args[0] + if seq != o.gcSeq+1 { + // This is not the right GC cycle. + return curCtx, false, nil + } + if o.gcState == gcNotRunning { + return curCtx, false, fmt.Errorf("encountered GCEnd when GC was not in progress") + } + if o.gcState == gcUndetermined { + return curCtx, false, fmt.Errorf("encountered GCEnd when GC was in an undetermined state") + } + o.gcSeq = seq + o.gcState = gcNotRunning + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceAnnotation(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle simple instantaneous events that require a G. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceHeapMetric(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle allocation metrics, which don't require a G. + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGCSweepBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle sweep, which is bound to a P and doesn't require a G. + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil { + return curCtx, false, err + } + if err := o.pStates[curCtx.P].beginRange(makeRangeType(ev.typ, 0)); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGCSweepActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + pid := ProcID(ev.args[0]) + // N.B. In practice Ps can't block while they're sweeping, so this can only + // ever reference curCtx.P. However, be lenient about this like we are with + // GCMarkAssistActive; there's no reason the runtime couldn't change to block + // in the middle of a sweep. + pState, ok := o.pStates[pid] + if !ok { + return curCtx, false, fmt.Errorf("encountered GCSweepActive for unknown proc %d", pid) + } + if err := pState.activeRange(makeRangeType(ev.typ, 0), gen == o.initialGen); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGCSweepEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil { + return curCtx, false, err + } + _, err := o.pStates[curCtx.P].endRange(ev.typ) + if err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoRangeBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle special goroutine-bound event ranges. + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + desc := stringID(0) + if ev.typ == tracev2.EvSTWBegin { + desc = stringID(ev.args[0]) + } + gState, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", ev.typ, curCtx.G) + } + if err := gState.beginRange(makeRangeType(ev.typ, desc)); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoRangeActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + gid := GoID(ev.args[0]) + // N.B. Like GoStatus, this can happen at any time, because it can + // reference a non-running goroutine. Don't check anything about the + // current scheduler context. + gState, ok := o.gStates[gid] + if !ok { + return curCtx, false, fmt.Errorf("uninitialized goroutine %d found during %s", gid, o.evName(ev.typ)) + } + if err := gState.activeRange(makeRangeType(ev.typ, 0), gen == o.initialGen); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceGoRangeEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + if err := validateCtx(curCtx, userGoReqs); err != nil { + return curCtx, false, err + } + gState, ok := o.gStates[curCtx.G] + if !ok { + return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", ev.typ, curCtx.G) + } + desc, err := gState.endRange(ev.typ) + if err != nil { + return curCtx, false, err + } + if ev.typ == tracev2.EvSTWEnd { + // Smuggle the kind into the event. + // Don't use ev.extra here so we have symmetry with STWBegin. + ev.args[0] = uint64(desc) + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +func (o *ordering) advanceAllocFree(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) { + // Handle simple instantaneous events that may or may not have a P. + if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mayHave}); err != nil { + return curCtx, false, err + } + o.queue.push(Event{table: evt, ctx: curCtx, base: *ev}) + return curCtx, true, nil +} + +// Next returns the next event in the ordering. +func (o *ordering) Next() (Event, bool) { + return o.queue.pop() +} + +// schedCtx represents the scheduling resources associated with an event. +type schedCtx struct { + G GoID + P ProcID + M ThreadID +} + +// validateCtx ensures that ctx conforms to some reqs, returning an error if +// it doesn't. +func validateCtx(ctx schedCtx, reqs schedReqs) error { + // Check thread requirements. + if reqs.M == mustHave && ctx.M == NoThread { + return fmt.Errorf("expected a thread but didn't have one") + } else if reqs.M == mustNotHave && ctx.M != NoThread { + return fmt.Errorf("expected no thread but had one") + } + + // Check proc requirements. + if reqs.P == mustHave && ctx.P == NoProc { + return fmt.Errorf("expected a proc but didn't have one") + } else if reqs.P == mustNotHave && ctx.P != NoProc { + return fmt.Errorf("expected no proc but had one") + } + + // Check goroutine requirements. + if reqs.G == mustHave && ctx.G == NoGoroutine { + return fmt.Errorf("expected a goroutine but didn't have one") + } else if reqs.G == mustNotHave && ctx.G != NoGoroutine { + return fmt.Errorf("expected no goroutine but had one") + } + return nil +} + +// gcState is a trinary variable for the current state of the GC. +// +// The third state besides "enabled" and "disabled" is "undetermined." +type gcState uint8 + +const ( + gcUndetermined gcState = iota + gcNotRunning + gcRunning +) + +// String returns a human-readable string for the GC state. +func (s gcState) String() string { + switch s { + case gcUndetermined: + return "Undetermined" + case gcNotRunning: + return "NotRunning" + case gcRunning: + return "Running" + } + return "Bad" +} + +// userRegion represents a unique user region when attached to some gState. +type userRegion struct { + // name must be a resolved string because the string ID for the same + // string may change across generations, but we care about checking + // the value itself. + taskID TaskID + name string +} + +// rangeType is a way to classify special ranges of time. +// +// These typically correspond 1:1 with "Begin" events, but +// they may have an optional subtype that describes the range +// in more detail. +type rangeType struct { + typ tracev2.EventType // "Begin" event. + desc stringID // Optional subtype. +} + +// makeRangeType constructs a new rangeType. +func makeRangeType(typ tracev2.EventType, desc stringID) rangeType { + if styp := tracev2.Specs()[typ].StartEv; styp != tracev2.EvNone { + typ = styp + } + return rangeType{typ, desc} +} + +// gState is the state of a goroutine at a point in the trace. +type gState struct { + id GoID + status tracev2.GoStatus + seq seqCounter + + // regions are the active user regions for this goroutine. + regions []userRegion + + // rangeState is the state of special time ranges bound to this goroutine. + rangeState +} + +// beginRegion starts a user region on the goroutine. +func (s *gState) beginRegion(r userRegion) error { + s.regions = append(s.regions, r) + return nil +} + +// endRegion ends a user region on the goroutine. +func (s *gState) endRegion(r userRegion) error { + if len(s.regions) == 0 { + // We do not know about regions that began before tracing started. + return nil + } + if next := s.regions[len(s.regions)-1]; next != r { + return fmt.Errorf("misuse of region in goroutine %v: region end %v when the inner-most active region start event is %v", s.id, r, next) + } + s.regions = s.regions[:len(s.regions)-1] + return nil +} + +// pState is the state of a proc at a point in the trace. +type pState struct { + id ProcID + status tracev2.ProcStatus + seq seqCounter + + // rangeState is the state of special time ranges bound to this proc. + rangeState +} + +// mState is the state of a thread at a point in the trace. +type mState struct { + g GoID // Goroutine bound to this M. (The goroutine's state is Executing.) + p ProcID // Proc bound to this M. (The proc's state is Executing.) +} + +// rangeState represents the state of special time ranges. +type rangeState struct { + // inFlight contains the rangeTypes of any ranges bound to a resource. + inFlight []rangeType +} + +// beginRange begins a special range in time on the goroutine. +// +// Returns an error if the range is already in progress. +func (s *rangeState) beginRange(typ rangeType) error { + if s.hasRange(typ) { + return fmt.Errorf("discovered event already in-flight for when starting event %v", tracev2.Specs()[typ.typ].Name) + } + s.inFlight = append(s.inFlight, typ) + return nil +} + +// activeRange marks special range in time on the goroutine as active in the +// initial generation, or confirms that it is indeed active in later generations. +func (s *rangeState) activeRange(typ rangeType, isInitialGen bool) error { + if isInitialGen { + if s.hasRange(typ) { + return fmt.Errorf("found named active range already in first gen: %v", typ) + } + s.inFlight = append(s.inFlight, typ) + } else if !s.hasRange(typ) { + return fmt.Errorf("resource is missing active range: %v %v", tracev2.Specs()[typ.typ].Name, s.inFlight) + } + return nil +} + +// hasRange returns true if a special time range on the goroutine as in progress. +func (s *rangeState) hasRange(typ rangeType) bool { + return slices.Contains(s.inFlight, typ) +} + +// endRange ends a special range in time on the goroutine. +// +// This must line up with the start event type of the range the goroutine is currently in. +func (s *rangeState) endRange(typ tracev2.EventType) (stringID, error) { + st := tracev2.Specs()[typ].StartEv + idx := -1 + for i, r := range s.inFlight { + if r.typ == st { + idx = i + break + } + } + if idx < 0 { + return 0, fmt.Errorf("tried to end event %v, but not in-flight", tracev2.Specs()[st].Name) + } + // Swap remove. + desc := s.inFlight[idx].desc + s.inFlight[idx], s.inFlight[len(s.inFlight)-1] = s.inFlight[len(s.inFlight)-1], s.inFlight[idx] + s.inFlight = s.inFlight[:len(s.inFlight)-1] + return desc, nil +} + +// seqCounter represents a global sequence counter for a resource. +type seqCounter struct { + gen uint64 // The generation for the local sequence counter seq. + seq uint64 // The sequence number local to the generation. +} + +// makeSeq creates a new seqCounter. +func makeSeq(gen, seq uint64) seqCounter { + return seqCounter{gen: gen, seq: seq} +} + +// succeeds returns true if a is the immediate successor of b. +func (a seqCounter) succeeds(b seqCounter) bool { + return a.gen == b.gen && a.seq == b.seq+1 +} + +// String returns a debug string representation of the seqCounter. +func (c seqCounter) String() string { + return fmt.Sprintf("%d (gen=%d)", c.seq, c.gen) +} + +func dumpOrdering(order *ordering) string { + var sb strings.Builder + for id, state := range order.gStates { + fmt.Fprintf(&sb, "G %d [status=%s seq=%s]\n", id, state.status, state.seq) + } + fmt.Fprintln(&sb) + for id, state := range order.pStates { + fmt.Fprintf(&sb, "P %d [status=%s seq=%s]\n", id, state.status, state.seq) + } + fmt.Fprintln(&sb) + for id, state := range order.mStates { + fmt.Fprintf(&sb, "M %d [g=%d p=%d]\n", id, state.g, state.p) + } + fmt.Fprintln(&sb) + fmt.Fprintf(&sb, "GC %d %s\n", order.gcSeq, order.gcState) + return sb.String() +} + +// taskState represents an active task. +type taskState struct { + // name is the type of the active task. + name string + + // parentID is the parent ID of the active task. + parentID TaskID +} + +// queue implements a growable ring buffer with a queue API. +type queue[T any] struct { + start, end int + buf []T +} + +// push adds a new event to the back of the queue. +func (q *queue[T]) push(value T) { + if q.end-q.start == len(q.buf) { + q.grow() + } + q.buf[q.end%len(q.buf)] = value + q.end++ +} + +// grow increases the size of the queue. +func (q *queue[T]) grow() { + if len(q.buf) == 0 { + q.buf = make([]T, 2) + return + } + + // Create new buf and copy data over. + newBuf := make([]T, len(q.buf)*2) + pivot := q.start % len(q.buf) + first, last := q.buf[pivot:], q.buf[:pivot] + copy(newBuf[:len(first)], first) + copy(newBuf[len(first):], last) + + // Update the queue state. + q.start = 0 + q.end = len(q.buf) + q.buf = newBuf +} + +// pop removes an event from the front of the queue. If the +// queue is empty, it returns an EventBad event. +func (q *queue[T]) pop() (T, bool) { + if q.end-q.start == 0 { + return *new(T), false + } + elem := &q.buf[q.start%len(q.buf)] + value := *elem + *elem = *new(T) // Clear the entry before returning, so we don't hold onto old tables. + q.start++ + return value, true +} + +// makeEvent creates an Event from the provided information. +// +// It's just a convenience function; it's always OK to construct +// an Event manually if this isn't quite the right way to express +// the contents of the event. +func makeEvent(table *evTable, ctx schedCtx, typ tracev2.EventType, time Time, args ...uint64) Event { + ev := Event{ + table: table, + ctx: ctx, + base: baseEvent{ + typ: typ, + time: time, + }, + } + copy(ev.base.args[:], args) + return ev +} + +// schedReqs is a set of constraints on what the scheduling +// context must look like. +type schedReqs struct { + M constraint + P constraint + G constraint +} + +// constraint represents a various presence requirements. +type constraint uint8 + +const ( + mustNotHave constraint = iota + mayHave + mustHave +) + +// userGoReqs is a common requirement among events that are running +// or are close to running user code. +var userGoReqs = schedReqs{M: mustHave, P: mustHave, G: mustHave} diff --git a/go/src/internal/trace/order_test.go b/go/src/internal/trace/order_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e267512a5356091771bfadc00354182dd6f22531 --- /dev/null +++ b/go/src/internal/trace/order_test.go @@ -0,0 +1,34 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import "testing" + +func TestQueue(t *testing.T) { + var q queue[int] + check := func(name string, exp []int) { + for _, v := range exp { + q.push(v) + } + for i, want := range exp { + if got, ok := q.pop(); !ok { + t.Fatalf("check %q: expected to be able to pop after %d pops", name, i+1) + } else if got != want { + t.Fatalf("check %q: expected value %d after on pop %d, got %d", name, want, i+1, got) + } + } + if _, ok := q.pop(); ok { + t.Fatalf("check %q: did not expect to be able to pop more values", name) + } + if _, ok := q.pop(); ok { + t.Fatalf("check %q: did not expect to be able to pop more values a second time", name) + } + } + check("one element", []int{4}) + check("two elements", []int{64, 12}) + check("six elements", []int{55, 16423, 2352, 644, 12874, 9372}) + check("one element again", []int{7}) + check("two elements again", []int{77, 6336}) +} diff --git a/go/src/internal/trace/raw/doc.go b/go/src/internal/trace/raw/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..53487372b75e084b9aeb4de8218a5a2d2cdaf769 --- /dev/null +++ b/go/src/internal/trace/raw/doc.go @@ -0,0 +1,66 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package raw provides an interface to interpret and emit Go execution traces. +It can interpret and emit execution traces in its wire format as well as a +bespoke but simple text format. + +The readers and writers in this package perform no validation on or ordering of +the input, and so are generally unsuitable for analysis. However, they're very +useful for testing and debugging the tracer in the runtime and more sophisticated +trace parsers. + +# Text format specification + +The trace text format produced and consumed by this package is a line-oriented +format. + +The first line in each text trace is the header line. + + Trace Go1.XX + +Following that is a series of event lines. Each event begins with an +event name, followed by zero or more named unsigned integer arguments. +Names are separated from their integer values by an '=' sign. Names can +consist of any UTF-8 character except '='. + +For example: + + EventName arg1=23 arg2=55 arg3=53 + +Any amount of whitespace is allowed to separate each token. Whitespace +is identified via unicode.IsSpace. + +Some events have additional data on following lines. There are two such +special cases. + +The first special case consists of events with trailing byte-oriented data. +The trailer begins on the following line from the event. That line consists +of a single argument 'data' and a Go-quoted string representing the byte data +within. Note: an explicit argument for the length is elided, because it's +just the length of the unquoted string. + +For example: + + String id=5 + data="hello world\x00" + +These events are identified in their spec by the HasData flag. + +The second special case consists of stack events. These events are identified +by the IsStack flag. These events also have a trailing unsigned integer argument +describing the number of stack frame descriptors that follow. Each stack frame +descriptor is on its own line following the event, consisting of four signed +integer arguments: the PC, an integer describing the function name, an integer +describing the file name, and the line number in that file that function was at +at the time the stack trace was taken. + +For example: + + Stack id=5 n=2 + pc=1241251 func=3 file=6 line=124 + pc=7534345 func=6 file=3 line=64 +*/ +package raw diff --git a/go/src/internal/trace/raw/event.go b/go/src/internal/trace/raw/event.go new file mode 100644 index 0000000000000000000000000000000000000000..9042d3f2151eb49b6adc4e4904eca8284f4edb78 --- /dev/null +++ b/go/src/internal/trace/raw/event.go @@ -0,0 +1,76 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package raw + +import ( + "encoding/binary" + "strconv" + "strings" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// Event is a simple representation of a trace event. +// +// Note that this typically includes much more than just +// timestamped events, and it also represents parts of the +// trace format's framing. (But not interpreted.) +type Event struct { + Version version.Version + Ev tracev2.EventType + Args []uint64 + Data []byte +} + +// String returns the canonical string representation of the event. +// +// This format is the same format that is parsed by the TextReader +// and emitted by the TextWriter. +func (e *Event) String() string { + spec := e.Version.Specs()[e.Ev] + + var s strings.Builder + s.WriteString(spec.Name) + for i := range spec.Args { + s.WriteString(" ") + s.WriteString(spec.Args[i]) + s.WriteString("=") + s.WriteString(strconv.FormatUint(e.Args[i], 10)) + } + if spec.IsStack { + frames := e.Args[len(spec.Args):] + for i := 0; i < len(frames); i++ { + if i%4 == 0 { + s.WriteString("\n\t") + } else { + s.WriteString(" ") + } + s.WriteString(frameFields[i%4]) + s.WriteString("=") + s.WriteString(strconv.FormatUint(frames[i], 10)) + } + } + if e.Data != nil { + s.WriteString("\n\tdata=") + s.WriteString(strconv.Quote(string(e.Data))) + } + return s.String() +} + +// EncodedSize returns the canonical encoded size of an event. +func (e *Event) EncodedSize() int { + size := 1 + var buf [binary.MaxVarintLen64]byte + for _, arg := range e.Args { + size += binary.PutUvarint(buf[:], arg) + } + spec := e.Version.Specs()[e.Ev] + if spec.HasData { + size += binary.PutUvarint(buf[:], uint64(len(e.Data))) + size += len(e.Data) + } + return size +} diff --git a/go/src/internal/trace/raw/reader.go b/go/src/internal/trace/raw/reader.go new file mode 100644 index 0000000000000000000000000000000000000000..af5dfac0e77a72b87c8124868afb73f2270e6a4c --- /dev/null +++ b/go/src/internal/trace/raw/reader.go @@ -0,0 +1,110 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package raw + +import ( + "bufio" + "encoding/binary" + "fmt" + "io" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// Reader parses trace bytes with only very basic validation +// into an event stream. +type Reader struct { + r *bufio.Reader + v version.Version + specs []tracev2.EventSpec +} + +// NewReader creates a new reader for the trace wire format. +func NewReader(r io.Reader) (*Reader, error) { + br := bufio.NewReader(r) + v, err := version.ReadHeader(br) + if err != nil { + return nil, err + } + return &Reader{r: br, v: v, specs: v.Specs()}, nil +} + +// Version returns the version of the trace that we're reading. +func (r *Reader) Version() version.Version { + return r.v +} + +// ReadEvent reads and returns the next trace event in the byte stream. +func (r *Reader) ReadEvent() (Event, error) { + evb, err := r.r.ReadByte() + if err == io.EOF { + return Event{}, io.EOF + } + if err != nil { + return Event{}, err + } + if int(evb) >= len(r.specs) || evb == 0 { + return Event{}, fmt.Errorf("invalid event type: %d", evb) + } + ev := tracev2.EventType(evb) + spec := r.specs[ev] + args, err := r.readArgs(len(spec.Args)) + if err != nil { + return Event{}, err + } + if spec.IsStack { + len := int(args[1]) + for i := 0; i < len; i++ { + // Each stack frame has four args: pc, func ID, file ID, line number. + frame, err := r.readArgs(4) + if err != nil { + return Event{}, err + } + args = append(args, frame...) + } + } + var data []byte + if spec.HasData { + data, err = r.readData() + if err != nil { + return Event{}, err + } + } + return Event{ + Version: r.v, + Ev: ev, + Args: args, + Data: data, + }, nil +} + +func (r *Reader) readArgs(n int) ([]uint64, error) { + var args []uint64 + for i := 0; i < n; i++ { + val, err := binary.ReadUvarint(r.r) + if err != nil { + return nil, err + } + args = append(args, val) + } + return args, nil +} + +func (r *Reader) readData() ([]byte, error) { + len, err := binary.ReadUvarint(r.r) + if err != nil { + return nil, err + } + var data []byte + for i := 0; i < int(len); i++ { + b, err := r.r.ReadByte() + if err != nil { + return nil, err + } + data = append(data, b) + } + return data, nil +} diff --git a/go/src/internal/trace/raw/textreader.go b/go/src/internal/trace/raw/textreader.go new file mode 100644 index 0000000000000000000000000000000000000000..f1544a7052c56f2a29427f6a1a633923472c7154 --- /dev/null +++ b/go/src/internal/trace/raw/textreader.go @@ -0,0 +1,216 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package raw + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" + "unicode" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// TextReader parses a text format trace with only very basic validation +// into an event stream. +type TextReader struct { + v version.Version + specs []tracev2.EventSpec + names map[string]tracev2.EventType + s *bufio.Scanner +} + +// NewTextReader creates a new reader for the trace text format. +func NewTextReader(r io.Reader) (*TextReader, error) { + tr := &TextReader{s: bufio.NewScanner(r)} + line, err := tr.nextLine() + if err != nil { + return nil, err + } + trace, line := readToken(line) + if trace != "Trace" { + return nil, fmt.Errorf("failed to parse header") + } + gover, line := readToken(line) + if !strings.HasPrefix(gover, "Go1.") { + return nil, fmt.Errorf("failed to parse header Go version") + } + rawv, err := strconv.ParseUint(gover[len("Go1."):], 10, 64) + if err != nil { + return nil, fmt.Errorf("failed to parse header Go version: %v", err) + } + v := version.Version(rawv) + if !v.Valid() { + return nil, fmt.Errorf("unknown or unsupported Go version 1.%d", v) + } + tr.v = v + tr.specs = v.Specs() + tr.names = tracev2.EventNames(tr.specs) + for _, r := range line { + if !unicode.IsSpace(r) { + return nil, fmt.Errorf("encountered unexpected non-space at the end of the header: %q", line) + } + } + return tr, nil +} + +// Version returns the version of the trace that we're reading. +func (r *TextReader) Version() version.Version { + return r.v +} + +// ReadEvent reads and returns the next trace event in the text stream. +func (r *TextReader) ReadEvent() (Event, error) { + line, err := r.nextLine() + if err != nil { + return Event{}, err + } + evStr, line := readToken(line) + ev, ok := r.names[evStr] + if !ok { + return Event{}, fmt.Errorf("unidentified event: %s", evStr) + } + spec := r.specs[ev] + args, err := readArgs(line, spec.Args) + if err != nil { + return Event{}, fmt.Errorf("reading args for %s: %v", evStr, err) + } + if spec.IsStack { + len := int(args[1]) + for i := 0; i < len; i++ { + line, err := r.nextLine() + if err == io.EOF { + return Event{}, fmt.Errorf("unexpected EOF while reading stack: args=%v", args) + } + if err != nil { + return Event{}, err + } + frame, err := readArgs(line, frameFields) + if err != nil { + return Event{}, err + } + args = append(args, frame...) + } + } + var data []byte + if spec.HasData { + line, err := r.nextLine() + if err == io.EOF { + return Event{}, fmt.Errorf("unexpected EOF while reading data for %s: args=%v", evStr, args) + } + if err != nil { + return Event{}, err + } + data, err = readData(line) + if err != nil { + return Event{}, err + } + } + return Event{ + Version: r.v, + Ev: ev, + Args: args, + Data: data, + }, nil +} + +func (r *TextReader) nextLine() (string, error) { + for { + if !r.s.Scan() { + if err := r.s.Err(); err != nil { + return "", err + } + return "", io.EOF + } + txt := r.s.Text() + tok, _ := readToken(txt) + if tok == "" { + continue // Empty line or comment. + } + return txt, nil + } +} + +var frameFields = []string{"pc", "func", "file", "line"} + +func readArgs(s string, names []string) ([]uint64, error) { + var args []uint64 + for _, name := range names { + arg, value, rest, err := readArg(s) + if err != nil { + return nil, err + } + if arg != name { + return nil, fmt.Errorf("expected argument %q, but got %q", name, arg) + } + args = append(args, value) + s = rest + } + for _, r := range s { + if !unicode.IsSpace(r) { + return nil, fmt.Errorf("encountered unexpected non-space at the end of an event: %q", s) + } + } + return args, nil +} + +func readArg(s string) (arg string, value uint64, rest string, err error) { + var tok string + tok, rest = readToken(s) + if len(tok) == 0 { + return "", 0, s, fmt.Errorf("no argument") + } + arg, val, found := strings.Cut(tok, "=") + if !found { + return "", 0, s, fmt.Errorf("malformed argument: %q", tok) + } + value, err = strconv.ParseUint(val, 10, 64) + if err != nil { + return arg, value, s, fmt.Errorf("failed to parse argument value %q for arg %q", val, arg) + } + return +} + +func readToken(s string) (token, rest string) { + tkStart := -1 + for i, r := range s { + if r == '#' { + return "", "" + } + if !unicode.IsSpace(r) { + tkStart = i + break + } + } + if tkStart < 0 { + return "", "" + } + tkEnd := -1 + for i, r := range s[tkStart:] { + if unicode.IsSpace(r) || r == '#' { + tkEnd = i + tkStart + break + } + } + if tkEnd < 0 { + return s[tkStart:], "" + } + return s[tkStart:tkEnd], s[tkEnd:] +} + +func readData(line string) ([]byte, error) { + dk, dv, found := strings.Cut(line, "=") + if !found || strings.TrimSpace(dk) != "data" { + return nil, fmt.Errorf("malformed data: %q", line) + } + data, err := strconv.Unquote(strings.TrimSpace(dv)) + if err != nil { + return nil, fmt.Errorf("failed to parse data: %q: %v", line, err) + } + return []byte(data), nil +} diff --git a/go/src/internal/trace/raw/textwriter.go b/go/src/internal/trace/raw/textwriter.go new file mode 100644 index 0000000000000000000000000000000000000000..b9f25923cbf2fc03baa45587d6af5d656924f942 --- /dev/null +++ b/go/src/internal/trace/raw/textwriter.go @@ -0,0 +1,39 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package raw + +import ( + "fmt" + "io" + + "internal/trace/version" +) + +// TextWriter emits the text format of a trace. +type TextWriter struct { + w io.Writer + v version.Version +} + +// NewTextWriter creates a new write for the trace text format. +func NewTextWriter(w io.Writer, v version.Version) (*TextWriter, error) { + _, err := fmt.Fprintf(w, "Trace Go1.%d\n", v) + if err != nil { + return nil, err + } + return &TextWriter{w: w, v: v}, nil +} + +// WriteEvent writes a single event to the stream. +func (w *TextWriter) WriteEvent(e Event) error { + // Check version. + if e.Version != w.v { + return fmt.Errorf("mismatched version between writer (go 1.%d) and event (go 1.%d)", w.v, e.Version) + } + + // Write event. + _, err := fmt.Fprintln(w.w, e.String()) + return err +} diff --git a/go/src/internal/trace/raw/writer.go b/go/src/internal/trace/raw/writer.go new file mode 100644 index 0000000000000000000000000000000000000000..6b7042cf2af101d399c58ba8e0abb2e665d8178b --- /dev/null +++ b/go/src/internal/trace/raw/writer.go @@ -0,0 +1,75 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package raw + +import ( + "encoding/binary" + "fmt" + "io" + + "internal/trace/tracev2" + "internal/trace/version" +) + +// Writer emits the wire format of a trace. +// +// It may not produce a byte-for-byte compatible trace from what is +// produced by the runtime, because it may be missing extra padding +// in the LEB128 encoding that the runtime adds but isn't necessary +// when you know the data up-front. +type Writer struct { + w io.Writer + buf []byte + v version.Version + specs []tracev2.EventSpec +} + +// NewWriter creates a new byte format writer. +func NewWriter(w io.Writer, v version.Version) (*Writer, error) { + _, err := version.WriteHeader(w, v) + return &Writer{w: w, v: v, specs: v.Specs()}, err +} + +// WriteEvent writes a single event to the trace wire format stream. +func (w *Writer) WriteEvent(e Event) error { + // Check version. + if e.Version != w.v { + return fmt.Errorf("mismatched version between writer (go 1.%d) and event (go 1.%d)", w.v, e.Version) + } + + // Write event header byte. + w.buf = append(w.buf, uint8(e.Ev)) + + // Write out all arguments. + spec := w.specs[e.Ev] + for _, arg := range e.Args[:len(spec.Args)] { + w.buf = binary.AppendUvarint(w.buf, arg) + } + if spec.IsStack { + frameArgs := e.Args[len(spec.Args):] + for i := 0; i < len(frameArgs); i++ { + w.buf = binary.AppendUvarint(w.buf, frameArgs[i]) + } + } + + // Write out the length of the data. + if spec.HasData { + w.buf = binary.AppendUvarint(w.buf, uint64(len(e.Data))) + } + + // Write out varint events. + _, err := w.w.Write(w.buf) + w.buf = w.buf[:0] + if err != nil { + return err + } + + // Write out data. + if spec.HasData { + _, err := w.w.Write(e.Data) + return err + } + return nil +} diff --git a/go/src/internal/trace/reader.go b/go/src/internal/trace/reader.go new file mode 100644 index 0000000000000000000000000000000000000000..bb9cc280f5c981921165aa96001dc62f47444559 --- /dev/null +++ b/go/src/internal/trace/reader.go @@ -0,0 +1,320 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "bufio" + "errors" + "fmt" + "io" + "slices" + "strings" + + "internal/trace/internal/tracev1" + "internal/trace/tracev2" + "internal/trace/version" +) + +// Reader reads a byte stream, validates it, and produces trace events. +// +// Provided the trace is non-empty the Reader always produces a Sync +// event as the first event, and a Sync event as the last event. +// (There may also be any number of Sync events in the middle, too.) +type Reader struct { + version version.Version + r *bufio.Reader + lastTs Time + gen *generation + frontier []*batchCursor + cpuSamples []cpuSample + order ordering + syncs int + readGenErr error + done bool + + // Spill state. + // + // Traces before Go 1.26 had no explicit end-of-generation signal, and + // so the first batch of the next generation needed to be parsed to identify + // a new generation. This batch is the "spilled" so we don't lose track + // of it when parsing the next generation. + // + // This is unnecessary after Go 1.26 because of an explicit end-of-generation + // signal. + spill *spilledBatch + spillErr error // error from reading spill + spillErrSync bool // whether we emitted a Sync before reporting spillErr + + v1Events *traceV1Converter +} + +// NewReader creates a new trace reader. +func NewReader(r io.Reader) (*Reader, error) { + br := bufio.NewReader(r) + v, err := version.ReadHeader(br) + if err != nil { + return nil, err + } + switch v { + case version.Go111, version.Go119, version.Go121: + tr, err := tracev1.Parse(br, v) + if err != nil { + return nil, err + } + return &Reader{ + v1Events: convertV1Trace(tr), + }, nil + case version.Go122, version.Go123, version.Go125, version.Go126: + return &Reader{ + version: v, + r: br, + order: ordering{ + traceVer: v, + mStates: make(map[ThreadID]*mState), + pStates: make(map[ProcID]*pState), + gStates: make(map[GoID]*gState), + activeTasks: make(map[TaskID]taskState), + }, + }, nil + default: + return nil, fmt.Errorf("unknown or unsupported version go 1.%d", v) + } +} + +// ReadEvent reads a single event from the stream. +// +// If the stream has been exhausted, it returns an invalid event and io.EOF. +func (r *Reader) ReadEvent() (e Event, err error) { + // Return only io.EOF if we're done. + if r.done { + return Event{}, io.EOF + } + + // Handle v1 execution traces. + if r.v1Events != nil { + if r.syncs == 0 { + // Always emit a sync event first, if we have any events at all. + ev, ok := r.v1Events.events.Peek() + if ok { + r.syncs++ + return syncEvent(r.v1Events.evt, Time(ev.Ts-1), r.syncs), nil + } + } + ev, err := r.v1Events.next() + if err == io.EOF { + // Always emit a sync event at the end. + r.done = true + r.syncs++ + return syncEvent(nil, r.v1Events.lastTs+1, r.syncs), nil + } else if err != nil { + return Event{}, err + } + return ev, nil + } + + // Trace v2 parsing algorithm. + // + // (1) Read in all the batches for the next generation from the stream. + // (a) Use the size field in the header to quickly find all batches. + // (2) Parse out the strings, stacks, CPU samples, and timestamp conversion data. + // (3) Group each event batch by M, sorted by timestamp. (batchCursor contains the groups.) + // (4) Organize batchCursors in a min-heap, ordered by the timestamp of the next event for each M. + // (5) Try to advance the next event for the M at the top of the min-heap. + // (a) On success, select that M. + // (b) On failure, sort the min-heap and try to advance other Ms. Select the first M that advances. + // (c) If there's nothing left to advance, goto (1). + // (6) Select the latest event for the selected M and get it ready to be returned. + // (7) Read the next event for the selected M and update the min-heap. + // (8) Return the selected event, goto (5) on the next call. + + // Set us up to track the last timestamp and fix up + // the timestamp of any event that comes through. + defer func() { + if err != nil { + return + } + if err = e.validateTableIDs(); err != nil { + return + } + if e.base.time <= r.lastTs { + e.base.time = r.lastTs + 1 + } + r.lastTs = e.base.time + }() + + // Consume any events in the ordering first. + if ev, ok := r.order.Next(); ok { + return ev, nil + } + + // Check if we need to refresh the generation. + if len(r.frontier) == 0 && len(r.cpuSamples) == 0 { + if r.version < version.Go126 { + return r.nextGenWithSpill() + } + if r.readGenErr != nil { + return Event{}, r.readGenErr + } + gen, err := readGeneration(r.r, r.version) + if err != nil { + // Before returning an error, emit the sync event + // for the current generation and queue up the error + // for the next call. + r.readGenErr = err + r.gen = nil + r.syncs++ + return syncEvent(nil, r.lastTs, r.syncs), nil + } + return r.installGen(gen) + } + tryAdvance := func(i int) (bool, error) { + bc := r.frontier[i] + + if ok, err := r.order.Advance(&bc.ev, r.gen.evTable, bc.m, r.gen.gen); !ok || err != nil { + return ok, err + } + + // Refresh the cursor's event. + ok, err := bc.nextEvent(r.gen.batches[bc.m], r.gen.freq) + if err != nil { + return false, err + } + if ok { + // If we successfully refreshed, update the heap. + heapUpdate(r.frontier, i) + } else { + // There's nothing else to read. Delete this cursor from the frontier. + r.frontier = heapRemove(r.frontier, i) + } + return true, nil + } + // Inject a CPU sample if it comes next. + if len(r.cpuSamples) != 0 { + if len(r.frontier) == 0 || r.cpuSamples[0].time < r.frontier[0].ev.time { + e := r.cpuSamples[0].asEvent(r.gen.evTable) + r.cpuSamples = r.cpuSamples[1:] + return e, nil + } + } + // Try to advance the head of the frontier, which should have the minimum timestamp. + // This should be by far the most common case + if len(r.frontier) == 0 { + return Event{}, fmt.Errorf("broken trace: frontier is empty:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order)) + } + if ok, err := tryAdvance(0); err != nil { + return Event{}, err + } else if !ok { + // Try to advance the rest of the frontier, in timestamp order. + // + // To do this, sort the min-heap. A sorted min-heap is still a + // min-heap, but now we can iterate over the rest and try to + // advance in order. This path should be rare. + slices.SortFunc(r.frontier, (*batchCursor).compare) + success := false + for i := 1; i < len(r.frontier); i++ { + if ok, err = tryAdvance(i); err != nil { + return Event{}, err + } else if ok { + success = true + break + } + } + if !success { + return Event{}, fmt.Errorf("broken trace: failed to advance: frontier:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order)) + } + } + + // Pick off the next event on the queue. At this point, one must exist. + ev, ok := r.order.Next() + if !ok { + panic("invariant violation: advance successful, but queue is empty") + } + return ev, nil +} + +// nextGenWithSpill reads the generation and calls nextGen while +// also handling any spilled batches. +func (r *Reader) nextGenWithSpill() (Event, error) { + if r.version >= version.Go126 { + return Event{}, errors.New("internal error: nextGenWithSpill called for Go 1.26+ trace") + } + if r.spillErr != nil { + if r.spillErrSync { + return Event{}, r.spillErr + } + r.spillErrSync = true + r.syncs++ + return syncEvent(nil, r.lastTs, r.syncs), nil + } + if r.gen != nil && r.spill == nil { + // If we have a generation from the last read, + // and there's nothing left in the frontier, and + // there's no spilled batch, indicating that there's + // no further generation, it means we're done. + // Emit the final sync event. + r.done = true + r.syncs++ + return syncEvent(nil, r.lastTs, r.syncs), nil + } + + // Read the next generation. + var gen *generation + gen, r.spill, r.spillErr = readGenerationWithSpill(r.r, r.spill, r.version) + if gen == nil { + r.gen = nil + r.spillErrSync = true + r.syncs++ + return syncEvent(nil, r.lastTs, r.syncs), nil + } + return r.installGen(gen) +} + +// installGen installs the new generation into the Reader and returns +// a Sync event for the new generation. +func (r *Reader) installGen(gen *generation) (Event, error) { + if gen == nil { + // Emit the final sync event. + r.gen = nil + r.done = true + r.syncs++ + return syncEvent(nil, r.lastTs, r.syncs), nil + } + r.gen = gen + + // Reset CPU samples cursor. + r.cpuSamples = r.gen.cpuSamples + + // Reset frontier. + for _, m := range r.gen.batchMs { + batches := r.gen.batches[m] + bc := &batchCursor{m: m} + ok, err := bc.nextEvent(batches, r.gen.freq) + if err != nil { + return Event{}, err + } + if !ok { + // Turns out there aren't actually any events in these batches. + continue + } + r.frontier = heapInsert(r.frontier, bc) + } + r.syncs++ + + // Always emit a sync event at the beginning of the generation. + return syncEvent(r.gen.evTable, r.gen.freq.mul(r.gen.minTs), r.syncs), nil +} + +func dumpFrontier(frontier []*batchCursor) string { + var sb strings.Builder + for _, bc := range frontier { + spec := tracev2.Specs()[bc.ev.typ] + fmt.Fprintf(&sb, "M %d [%s time=%d", bc.m, spec.Name, bc.ev.time) + for i, arg := range spec.Args[1:] { + fmt.Fprintf(&sb, " %s=%d", arg, bc.ev.args[i]) + } + fmt.Fprintf(&sb, "]\n") + } + return sb.String() +} diff --git a/go/src/internal/trace/reader_test.go b/go/src/internal/trace/reader_test.go new file mode 100644 index 0000000000000000000000000000000000000000..264cc51569605f3ba315165d917e223187c21552 --- /dev/null +++ b/go/src/internal/trace/reader_test.go @@ -0,0 +1,201 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace_test + +import ( + "bytes" + "flag" + "io" + "path/filepath" + "runtime" + "testing" + "time" + + "internal/trace" + "internal/trace/testtrace" +) + +var ( + logEvents = flag.Bool("log-events", false, "whether to log high-level events; significantly slows down tests") + dumpTraces = flag.Bool("dump-traces", false, "dump traces even on success") + allocFree = flag.Bool("alloc-free", false, "run alloc/free trace experiment tests") +) + +func TestReaderGolden(t *testing.T) { + matches, err := filepath.Glob("./testdata/tests/*.test") + if err != nil { + t.Fatalf("failed to glob for tests: %v", err) + } + for _, testPath := range matches { + testName, err := filepath.Rel("./testdata", testPath) + if err != nil { + t.Fatalf("failed to relativize testdata path: %v", err) + } + t.Run(testName, func(t *testing.T) { + tr, ver, exp, err := testtrace.ParseFile(testPath) + if err != nil { + t.Fatalf("failed to parse test file at %s: %v", testPath, err) + } + v := testtrace.NewValidator() + v.GoVersion = ver + testReader(t, tr, v, exp) + }) + } +} + +func FuzzReader(f *testing.F) { + // Currently disabled because the parser doesn't do much validation and most + // getters can be made to panic. Turn this on once the parser is meant to + // reject invalid traces. + const testGetters = false + + f.Fuzz(func(t *testing.T, b []byte) { + r, err := trace.NewReader(bytes.NewReader(b)) + if err != nil { + return + } + for { + ev, err := r.ReadEvent() + if err != nil { + break + } + + if !testGetters { + continue + } + // Make sure getters don't do anything that panics + switch ev.Kind() { + case trace.EventLabel: + ev.Label() + case trace.EventLog: + ev.Log() + case trace.EventMetric: + ev.Metric() + case trace.EventRangeActive, trace.EventRangeBegin: + ev.Range() + case trace.EventRangeEnd: + ev.Range() + ev.RangeAttributes() + case trace.EventStateTransition: + ev.StateTransition() + case trace.EventRegionBegin, trace.EventRegionEnd: + ev.Region() + case trace.EventTaskBegin, trace.EventTaskEnd: + ev.Task() + case trace.EventSync: + case trace.EventStackSample: + case trace.EventBad: + } + } + }) +} + +func testReader(t *testing.T, tr io.Reader, v *testtrace.Validator, exp *testtrace.Expectation) { + r, err := trace.NewReader(tr) + if err != nil { + if err := exp.Check(err); err != nil { + t.Error(err) + } + return + } + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + v.GoVersion = r.GoVersion() + if runtime.GOOS == "windows" || runtime.GOARCH == "wasm" { + v.SkipClockSnapshotChecks() + } + if err != nil { + if err := exp.Check(err); err != nil { + t.Error(err) + } + return + } + if *logEvents { + t.Log(ev.String()) + } + if err := v.Event(ev); err != nil { + t.Error(err) + } + } + if err := exp.Check(nil); err != nil { + t.Error(err) + } +} + +func TestTraceGenSync(t *testing.T) { + type sync struct { + Time trace.Time + ClockSnapshot *trace.ClockSnapshot + } + runTest := func(testName string, wantSyncs []sync) { + t.Run(testName, func(t *testing.T) { + testPath := "testdata/tests/" + testName + r, _, _, err := testtrace.ParseFile(testPath) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + tr, err := trace.NewReader(r) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + var syncEvents []trace.Event + for { + ev, err := tr.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + if ev.Kind() == trace.EventSync { + syncEvents = append(syncEvents, ev) + } + } + + if got, want := len(syncEvents), len(wantSyncs); got != want { + t.Errorf("got %d sync events, want %d", got, want) + } + + for i, want := range wantSyncs { + got := syncEvents[i] + gotSync := syncEvents[i].Sync() + if got.Time() != want.Time { + t.Errorf("sync=%d got time %d, want %d", i+1, got.Time(), want.Time) + } + if gotSync.ClockSnapshot == nil && want.ClockSnapshot == nil { + continue + } + if gotSync.ClockSnapshot.Trace != want.ClockSnapshot.Trace { + t.Errorf("sync=%d got trace time %d, want %d", i+1, gotSync.ClockSnapshot.Trace, want.ClockSnapshot.Trace) + } + if !gotSync.ClockSnapshot.Wall.Equal(want.ClockSnapshot.Wall) { + t.Errorf("sync=%d got wall time %s, want %s", i+1, gotSync.ClockSnapshot.Wall, want.ClockSnapshot.Wall) + } + if gotSync.ClockSnapshot.Mono != want.ClockSnapshot.Mono { + t.Errorf("sync=%d got mono time %d, want %d", i+1, gotSync.ClockSnapshot.Mono, want.ClockSnapshot.Mono) + } + } + }) + } + + runTest("go123-sync.test", []sync{ + {10, nil}, + {40, nil}, + // The EvFrequency batch for generation 3 is emitted at trace.Time(80), + // but 60 is the minTs of the generation, see b30 in the go generator. + {60, nil}, + {63, nil}, + }) + + runTest("go125-sync.test", []sync{ + {9, &trace.ClockSnapshot{Trace: 10, Mono: 99, Wall: time.Date(2025, 2, 28, 15, 4, 9, 123, time.UTC)}}, + {38, &trace.ClockSnapshot{Trace: 40, Mono: 199, Wall: time.Date(2025, 2, 28, 15, 4, 10, 123, time.UTC)}}, + {58, &trace.ClockSnapshot{Trace: 60, Mono: 299, Wall: time.Date(2025, 2, 28, 15, 4, 11, 123, time.UTC)}}, + {83, nil}, + }) +} diff --git a/go/src/internal/trace/resources.go b/go/src/internal/trace/resources.go new file mode 100644 index 0000000000000000000000000000000000000000..951159ddbdcac5e0e25ef0ae1d7c86f4a56393de --- /dev/null +++ b/go/src/internal/trace/resources.go @@ -0,0 +1,275 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import "fmt" + +// ThreadID is the runtime-internal M structure's ID. This is unique +// for each OS thread. +type ThreadID int64 + +// NoThread indicates that the relevant events don't correspond to any +// thread in particular. +const NoThread = ThreadID(-1) + +// ProcID is the runtime-internal G structure's id field. This is unique +// for each P. +type ProcID int64 + +// NoProc indicates that the relevant events don't correspond to any +// P in particular. +const NoProc = ProcID(-1) + +// GoID is the runtime-internal G structure's goid field. This is unique +// for each goroutine. +type GoID int64 + +// NoGoroutine indicates that the relevant events don't correspond to any +// goroutine in particular. +const NoGoroutine = GoID(-1) + +// GoState represents the state of a goroutine. +// +// New GoStates may be added in the future. Users of this type must be robust +// to that possibility. +type GoState uint8 + +const ( + GoUndetermined GoState = iota // No information is known about the goroutine. + GoNotExist // Goroutine does not exist. + GoRunnable // Goroutine is runnable but not running. + GoRunning // Goroutine is running. + GoWaiting // Goroutine is waiting on something to happen. + GoSyscall // Goroutine is in a system call. +) + +// Executing returns true if the state indicates that the goroutine is executing +// and bound to its thread. +func (s GoState) Executing() bool { + return s == GoRunning || s == GoSyscall +} + +// String returns a human-readable representation of a GoState. +// +// The format of the returned string is for debugging purposes and is subject to change. +func (s GoState) String() string { + switch s { + case GoUndetermined: + return "Undetermined" + case GoNotExist: + return "NotExist" + case GoRunnable: + return "Runnable" + case GoRunning: + return "Running" + case GoWaiting: + return "Waiting" + case GoSyscall: + return "Syscall" + } + return "Bad" +} + +// ProcState represents the state of a proc. +// +// New ProcStates may be added in the future. Users of this type must be robust +// to that possibility. +type ProcState uint8 + +const ( + ProcUndetermined ProcState = iota // No information is known about the proc. + ProcNotExist // Proc does not exist. + ProcRunning // Proc is running. + ProcIdle // Proc is idle. +) + +// Executing returns true if the state indicates that the proc is executing +// and bound to its thread. +func (s ProcState) Executing() bool { + return s == ProcRunning +} + +// String returns a human-readable representation of a ProcState. +// +// The format of the returned string is for debugging purposes and is subject to change. +func (s ProcState) String() string { + switch s { + case ProcUndetermined: + return "Undetermined" + case ProcNotExist: + return "NotExist" + case ProcRunning: + return "Running" + case ProcIdle: + return "Idle" + } + return "Bad" +} + +// ResourceKind indicates a kind of resource that has a state machine. +// +// New ResourceKinds may be added in the future. Users of this type must be robust +// to that possibility. +type ResourceKind uint8 + +const ( + ResourceNone ResourceKind = iota // No resource. + ResourceGoroutine // Goroutine. + ResourceProc // Proc. + ResourceThread // Thread. +) + +// String returns a human-readable representation of a ResourceKind. +// +// The format of the returned string is for debugging purposes and is subject to change. +func (r ResourceKind) String() string { + switch r { + case ResourceNone: + return "None" + case ResourceGoroutine: + return "Goroutine" + case ResourceProc: + return "Proc" + case ResourceThread: + return "Thread" + } + return "Bad" +} + +// ResourceID represents a generic resource ID. +type ResourceID struct { + // Kind is the kind of resource this ID is for. + Kind ResourceKind + id int64 +} + +// MakeResourceID creates a general resource ID from a specific resource's ID. +func MakeResourceID[T interface{ GoID | ProcID | ThreadID }](id T) ResourceID { + var rd ResourceID + var a any = id + switch a.(type) { + case GoID: + rd.Kind = ResourceGoroutine + case ProcID: + rd.Kind = ResourceProc + case ThreadID: + rd.Kind = ResourceThread + } + rd.id = int64(id) + return rd +} + +// Goroutine obtains a GoID from the resource ID. +// +// r.Kind must be ResourceGoroutine or this function will panic. +func (r ResourceID) Goroutine() GoID { + if r.Kind != ResourceGoroutine { + panic(fmt.Sprintf("attempted to get GoID from %s resource ID", r.Kind)) + } + return GoID(r.id) +} + +// Proc obtains a ProcID from the resource ID. +// +// r.Kind must be ResourceProc or this function will panic. +func (r ResourceID) Proc() ProcID { + if r.Kind != ResourceProc { + panic(fmt.Sprintf("attempted to get ProcID from %s resource ID", r.Kind)) + } + return ProcID(r.id) +} + +// Thread obtains a ThreadID from the resource ID. +// +// r.Kind must be ResourceThread or this function will panic. +func (r ResourceID) Thread() ThreadID { + if r.Kind != ResourceThread { + panic(fmt.Sprintf("attempted to get ThreadID from %s resource ID", r.Kind)) + } + return ThreadID(r.id) +} + +// String returns a human-readable string representation of the ResourceID. +// +// This representation is subject to change and is intended primarily for debugging. +func (r ResourceID) String() string { + if r.Kind == ResourceNone { + return r.Kind.String() + } + return fmt.Sprintf("%s(%d)", r.Kind, r.id) +} + +// StateTransition provides details about a StateTransition event. +type StateTransition struct { + // Resource is the resource this state transition is for. + Resource ResourceID + + // Reason is a human-readable reason for the state transition. + Reason string + + // Stack is the stack trace of the resource making the state transition. + // + // This is distinct from the result (Event).Stack because it pertains to + // the transitioning resource, not any of the ones executing the event + // this StateTransition came from. + // + // An example of this difference is the NotExist -> Runnable transition for + // goroutines, which indicates goroutine creation. In this particular case, + // a Stack here would refer to the starting stack of the new goroutine, and + // an (Event).Stack would refer to the stack trace of whoever created the + // goroutine. + Stack Stack + + // The actual transition data. Stored in a neutral form so that + // we don't need fields for every kind of resource. + oldState uint8 + newState uint8 +} + +// MakeGoStateTransition creates a goroutine state transition. +func MakeGoStateTransition(id GoID, from, to GoState) StateTransition { + return StateTransition{ + Resource: ResourceID{Kind: ResourceGoroutine, id: int64(id)}, + oldState: uint8(from), + newState: uint8(to), + } +} + +// MakeProcStateTransition creates a proc state transition. +func MakeProcStateTransition(id ProcID, from, to ProcState) StateTransition { + return StateTransition{ + Resource: ResourceID{Kind: ResourceProc, id: int64(id)}, + oldState: uint8(from), + newState: uint8(to), + } +} + +// Goroutine returns the state transition for a goroutine. +// +// Transitions to and from states that are Executing are special in that +// they change the future execution context. In other words, future events +// on the same thread will feature the same goroutine until it stops running. +// +// Panics if d.Resource.Kind is not ResourceGoroutine. +func (d StateTransition) Goroutine() (from, to GoState) { + if d.Resource.Kind != ResourceGoroutine { + panic("Goroutine called on non-Goroutine state transition") + } + return GoState(d.oldState), GoState(d.newState) +} + +// Proc returns the state transition for a proc. +// +// Transitions to and from states that are Executing are special in that +// they change the future execution context. In other words, future events +// on the same thread will feature the same goroutine until it stops running. +// +// Panics if d.Resource.Kind is not ResourceProc. +func (d StateTransition) Proc() (from, to ProcState) { + if d.Resource.Kind != ResourceProc { + panic("Proc called on non-Proc state transition") + } + return ProcState(d.oldState), ProcState(d.newState) +} diff --git a/go/src/internal/trace/summary.go b/go/src/internal/trace/summary.go new file mode 100644 index 0000000000000000000000000000000000000000..68a924e6b9a89200d07fc1cbf63d79d23e281b98 --- /dev/null +++ b/go/src/internal/trace/summary.go @@ -0,0 +1,699 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "cmp" + "slices" + "strings" + "time" +) + +// Summary is the analysis result produced by the summarizer. +type Summary struct { + Goroutines map[GoID]*GoroutineSummary + Tasks map[TaskID]*UserTaskSummary +} + +// GoroutineSummary contains statistics and execution details of a single goroutine. +// (For v2 traces.) +type GoroutineSummary struct { + ID GoID + Name string // A non-unique human-friendly identifier for the goroutine. + PC uint64 // The first PC we saw for the entry function of the goroutine + CreationTime Time // Timestamp of the first appearance in the trace. + StartTime Time // Timestamp of the first time it started running. 0 if the goroutine never ran. + EndTime Time // Timestamp of when the goroutine exited. 0 if the goroutine never exited. + + // List of regions in the goroutine, sorted based on the start time. + Regions []*UserRegionSummary + + // Statistics of execution time during the goroutine execution. + GoroutineExecStats + + // goroutineSummary is state used just for computing this structure. + // It's dropped before being returned to the caller. + // + // More specifically, if it's nil, it indicates that this summary has + // already been finalized. + *goroutineSummary +} + +// UserTaskSummary represents a task in the trace. +type UserTaskSummary struct { + ID TaskID + Name string + Parent *UserTaskSummary // nil if the parent is unknown. + Children []*UserTaskSummary + + // Task begin event. An EventTaskBegin event or nil. + Start *Event + + // End end event. Normally EventTaskEnd event or nil. + End *Event + + // Logs is a list of EventLog events associated with the task. + Logs []*Event + + // List of regions in the task, sorted based on the start time. + Regions []*UserRegionSummary + + // Goroutines is the set of goroutines associated with this task. + Goroutines map[GoID]*GoroutineSummary +} + +// Complete returns true if we have complete information about the task +// from the trace: both a start and an end. +func (s *UserTaskSummary) Complete() bool { + return s.Start != nil && s.End != nil +} + +// Descendents returns a slice consisting of itself (always the first task returned), +// and the transitive closure of all of its children. +func (s *UserTaskSummary) Descendents() []*UserTaskSummary { + descendents := []*UserTaskSummary{s} + for _, child := range s.Children { + descendents = append(descendents, child.Descendents()...) + } + return descendents +} + +// UserRegionSummary represents a region and goroutine execution stats +// while the region was active. (For v2 traces.) +type UserRegionSummary struct { + TaskID TaskID + Name string + + // Region start event. Normally EventRegionBegin event or nil, + // but can be a state transition event from NotExist or Undetermined + // if the region is a synthetic region representing task inheritance + // from the parent goroutine. + Start *Event + + // Region end event. Normally EventRegionEnd event or nil, + // but can be a state transition event to NotExist if the goroutine + // terminated without explicitly ending the region. + End *Event + + GoroutineExecStats +} + +// GoroutineExecStats contains statistics about a goroutine's execution +// during a period of time. +type GoroutineExecStats struct { + // These stats are all non-overlapping. + ExecTime time.Duration + SchedWaitTime time.Duration + BlockTimeByReason map[string]time.Duration + SyscallTime time.Duration + SyscallBlockTime time.Duration + + // TotalTime is the duration of the goroutine's presence in the trace. + // Necessarily overlaps with other stats. + TotalTime time.Duration + + // Total time the goroutine spent in certain ranges; may overlap + // with other stats. + RangeTime map[string]time.Duration +} + +func (s GoroutineExecStats) NonOverlappingStats() map[string]time.Duration { + stats := map[string]time.Duration{ + "Execution time": s.ExecTime, + "Sched wait time": s.SchedWaitTime, + "Syscall execution time": s.SyscallTime, + "Block time (syscall)": s.SyscallBlockTime, + "Unknown time": s.UnknownTime(), + } + for reason, dt := range s.BlockTimeByReason { + stats["Block time ("+reason+")"] += dt + } + // N.B. Don't include RangeTime or TotalTime; they overlap with these other + // stats. + return stats +} + +// UnknownTime returns whatever isn't accounted for in TotalTime. +func (s GoroutineExecStats) UnknownTime() time.Duration { + sum := s.ExecTime + s.SchedWaitTime + s.SyscallTime + + s.SyscallBlockTime + for _, dt := range s.BlockTimeByReason { + sum += dt + } + // N.B. Don't include range time. Ranges overlap with + // other stats, whereas these stats are non-overlapping. + if sum < s.TotalTime { + return s.TotalTime - sum + } + return 0 +} + +// sub returns the stats v-s. +func (s GoroutineExecStats) sub(v GoroutineExecStats) (r GoroutineExecStats) { + r = s.clone() + r.ExecTime -= v.ExecTime + r.SchedWaitTime -= v.SchedWaitTime + for reason := range s.BlockTimeByReason { + r.BlockTimeByReason[reason] -= v.BlockTimeByReason[reason] + } + r.SyscallTime -= v.SyscallTime + r.SyscallBlockTime -= v.SyscallBlockTime + r.TotalTime -= v.TotalTime + for name := range s.RangeTime { + r.RangeTime[name] -= v.RangeTime[name] + } + return r +} + +func (s GoroutineExecStats) clone() (r GoroutineExecStats) { + r = s + r.BlockTimeByReason = make(map[string]time.Duration) + for reason, dt := range s.BlockTimeByReason { + r.BlockTimeByReason[reason] = dt + } + r.RangeTime = make(map[string]time.Duration) + for name, dt := range s.RangeTime { + r.RangeTime[name] = dt + } + return r +} + +// snapshotStat returns the snapshot of the goroutine execution statistics. +// This is called as we process the ordered trace event stream. lastTs is used +// to process pending statistics if this is called before any goroutine end event. +func (g *GoroutineSummary) snapshotStat(lastTs Time) (ret GoroutineExecStats) { + ret = g.GoroutineExecStats.clone() + + if g.goroutineSummary == nil { + return ret // Already finalized; no pending state. + } + + // Set the total time if necessary. + if g.TotalTime == 0 { + ret.TotalTime = lastTs.Sub(g.CreationTime) + } + + // Add in time since lastTs. + if g.lastStartTime != 0 { + ret.ExecTime += lastTs.Sub(g.lastStartTime) + } + if g.lastRunnableTime != 0 { + ret.SchedWaitTime += lastTs.Sub(g.lastRunnableTime) + } + if g.lastBlockTime != 0 { + ret.BlockTimeByReason[g.lastBlockReason] += lastTs.Sub(g.lastBlockTime) + } + if g.lastSyscallTime != 0 { + ret.SyscallTime += lastTs.Sub(g.lastSyscallTime) + } + if g.lastSyscallBlockTime != 0 { + ret.SchedWaitTime += lastTs.Sub(g.lastSyscallBlockTime) + } + for name, ts := range g.lastRangeTime { + ret.RangeTime[name] += lastTs.Sub(ts) + } + return ret +} + +// finalize is called when processing a goroutine end event or at +// the end of trace processing. This finalizes the execution stat +// and any active regions in the goroutine, in which case trigger is nil. +func (g *GoroutineSummary) finalize(lastTs Time, trigger *Event) { + if trigger != nil { + g.EndTime = trigger.Time() + } + finalStat := g.snapshotStat(lastTs) + + g.GoroutineExecStats = finalStat + + // System goroutines are never part of regions, even though they + // "inherit" a task due to creation (EvGoCreate) from within a region. + // This may happen e.g. if the first GC is triggered within a region, + // starting the GC worker goroutines. + if !IsSystemGoroutine(g.Name) { + for _, s := range g.activeRegions { + s.End = trigger + s.GoroutineExecStats = finalStat.sub(s.GoroutineExecStats) + g.Regions = append(g.Regions, s) + } + } + *(g.goroutineSummary) = goroutineSummary{} +} + +// goroutineSummary is a private part of GoroutineSummary that is required only during analysis. +type goroutineSummary struct { + lastStartTime Time + lastRunnableTime Time + lastBlockTime Time + lastBlockReason string + lastSyscallTime Time + lastSyscallBlockTime Time + lastRangeTime map[string]Time + activeRegions []*UserRegionSummary // stack of active regions +} + +// Summarizer constructs per-goroutine time statistics for v2 traces. +type Summarizer struct { + // gs contains the map of goroutine summaries we're building up to return to the caller. + gs map[GoID]*GoroutineSummary + + // tasks contains the map of task summaries we're building up to return to the caller. + tasks map[TaskID]*UserTaskSummary + + // syscallingP and syscallingG represent a binding between a P and G in a syscall. + // Used to correctly identify and clean up after syscalls (blocking or otherwise). + syscallingP map[ProcID]GoID + syscallingG map[GoID]ProcID + + // rangesP is used for optimistic tracking of P-based ranges for goroutines. + // + // It's a best-effort mapping of an active range on a P to the goroutine we think + // is associated with it. + rangesP map[rangeP]GoID + + lastTs Time // timestamp of the last event processed. + syncTs Time // timestamp of the last sync event processed (or the first timestamp in the trace). +} + +// NewSummarizer creates a new struct to build goroutine stats from a trace. +func NewSummarizer() *Summarizer { + return &Summarizer{ + gs: make(map[GoID]*GoroutineSummary), + tasks: make(map[TaskID]*UserTaskSummary), + syscallingP: make(map[ProcID]GoID), + syscallingG: make(map[GoID]ProcID), + rangesP: make(map[rangeP]GoID), + } +} + +type rangeP struct { + id ProcID + name string +} + +// Event feeds a single event into the stats summarizer. +func (s *Summarizer) Event(ev *Event) { + if s.syncTs == 0 { + s.syncTs = ev.Time() + } + s.lastTs = ev.Time() + + switch ev.Kind() { + // Record sync time for the RangeActive events. + case EventSync: + s.syncTs = ev.Time() + + // Handle state transitions. + case EventStateTransition: + st := ev.StateTransition() + switch st.Resource.Kind { + // Handle goroutine transitions, which are the meat of this computation. + case ResourceGoroutine: + id := st.Resource.Goroutine() + old, new := st.Goroutine() + if old == new { + // Skip these events; they're not telling us anything new. + break + } + + // Handle transition out. + g := s.gs[id] + switch old { + case GoUndetermined: + g = &GoroutineSummary{ID: id, goroutineSummary: &goroutineSummary{}} + + // The goroutine is being named for the first time. + // If we're coming out of GoUndetermined, then the creation time is the + // time of the last sync. + g.CreationTime = s.syncTs + g.lastRangeTime = make(map[string]Time) + g.BlockTimeByReason = make(map[string]time.Duration) + g.RangeTime = make(map[string]time.Duration) + + // Accumulate all the time we spent in new as if it was old. + // + // Note that we still handle "new" again below because the time until + // the *next* event still needs to be accumulated (even though it's + // probably going to come immediately after this event). + stateTime := ev.Time().Sub(s.syncTs) + switch new { + case GoRunning: + g.ExecTime += stateTime + case GoWaiting: + g.BlockTimeByReason[st.Reason] += stateTime + case GoRunnable: + g.SchedWaitTime += stateTime + case GoSyscall: + // For a syscall, we're not going to be 'naming' this P from afar. + // It's "executing" somewhere. If we've got a P, then that means + // we've had that P since the start, so this is regular syscall time. + // Otherwise, this is syscall block time (no P). + if ev.Proc() == NoProc { + g.SyscallBlockTime += stateTime + } else { + g.SyscallTime += stateTime + } + } + s.gs[g.ID] = g + case GoNotExist: + g = &GoroutineSummary{ID: id, goroutineSummary: &goroutineSummary{}} + + // The goroutine is being created. + g.CreationTime = ev.Time() + g.lastRangeTime = make(map[string]Time) + g.BlockTimeByReason = make(map[string]time.Duration) + g.RangeTime = make(map[string]time.Duration) + + // When a goroutine is newly created, inherit the task + // of the active region. For ease handling of this + // case, we create a fake region description with the + // task id. This isn't strictly necessary as this + // goroutine may not be associated with the task, but + // it can be convenient to see all children created + // during a region. + // + // N.B. ev.Goroutine() will always be NoGoroutine for the + // Undetermined case, so this is will simply not fire. + if creatorG := s.gs[ev.Goroutine()]; creatorG != nil && len(creatorG.activeRegions) > 0 { + regions := creatorG.activeRegions + s := regions[len(regions)-1] + g.activeRegions = []*UserRegionSummary{{TaskID: s.TaskID, Start: ev}} + } + s.gs[g.ID] = g + case GoRunning: + // Record execution time as we transition out of running + g.ExecTime += ev.Time().Sub(g.lastStartTime) + g.lastStartTime = 0 + case GoWaiting: + // Record block time as we transition out of waiting. + if g.lastBlockTime != 0 { + g.BlockTimeByReason[g.lastBlockReason] += ev.Time().Sub(g.lastBlockTime) + g.lastBlockTime = 0 + } + case GoRunnable: + // Record sched latency time as we transition out of runnable. + if g.lastRunnableTime != 0 { + g.SchedWaitTime += ev.Time().Sub(g.lastRunnableTime) + g.lastRunnableTime = 0 + } + case GoSyscall: + // Record syscall execution time and syscall block time as we transition out of syscall. + if g.lastSyscallTime != 0 { + if g.lastSyscallBlockTime != 0 { + g.SyscallBlockTime += ev.Time().Sub(g.lastSyscallBlockTime) + g.SyscallTime += g.lastSyscallBlockTime.Sub(g.lastSyscallTime) + } else { + g.SyscallTime += ev.Time().Sub(g.lastSyscallTime) + } + g.lastSyscallTime = 0 + g.lastSyscallBlockTime = 0 + + // Clear the syscall map. + delete(s.syscallingP, s.syscallingG[id]) + delete(s.syscallingG, id) + } + } + + // The goroutine hasn't been identified yet. Take the transition stack + // and identify the goroutine by the root frame of that stack. + // This root frame will be identical for all transitions on this + // goroutine, because it represents its immutable start point. + if g.Name == "" { + for frame := range st.Stack.Frames() { + // NB: this PC won't actually be consistent for + // goroutines which existed at the start of the + // trace. The UI doesn't use it directly; this + // mainly serves as an indication that we + // actually saw a call stack for the goroutine + g.PC = frame.PC + g.Name = frame.Func + } + } + + // Handle transition in. + switch new { + case GoRunning: + // We started running. Record it. + g.lastStartTime = ev.Time() + if g.StartTime == 0 { + g.StartTime = ev.Time() + } + case GoRunnable: + g.lastRunnableTime = ev.Time() + case GoWaiting: + if st.Reason != "forever" { + g.lastBlockTime = ev.Time() + g.lastBlockReason = st.Reason + break + } + // "Forever" is like goroutine death. + fallthrough + case GoNotExist: + g.finalize(ev.Time(), ev) + case GoSyscall: + s.syscallingP[ev.Proc()] = id + s.syscallingG[id] = ev.Proc() + g.lastSyscallTime = ev.Time() + } + + // Handle procs to detect syscall blocking, which si identifiable as a + // proc going idle while the goroutine it was attached to is in a syscall. + case ResourceProc: + id := st.Resource.Proc() + old, new := st.Proc() + if old != new && new == ProcIdle { + if goid, ok := s.syscallingP[id]; ok { + g := s.gs[goid] + g.lastSyscallBlockTime = ev.Time() + delete(s.syscallingP, id) + } + } + } + + // Handle ranges of all kinds. + case EventRangeBegin, EventRangeActive: + r := ev.Range() + var g *GoroutineSummary + switch r.Scope.Kind { + case ResourceGoroutine: + // Simple goroutine range. We attribute the entire range regardless of + // goroutine stats. Lots of situations are still identifiable, e.g. a + // goroutine blocked often in mark assist will have both high mark assist + // and high block times. Those interested in a deeper view can look at the + // trace viewer. + g = s.gs[r.Scope.Goroutine()] + case ResourceProc: + // N.B. These ranges are not actually bound to the goroutine, they're + // bound to the P. But if we happen to be on the P the whole time, let's + // try to attribute it to the goroutine. (e.g. GC sweeps are here.) + g = s.gs[ev.Goroutine()] + if g != nil { + s.rangesP[rangeP{id: r.Scope.Proc(), name: r.Name}] = ev.Goroutine() + } + } + if g == nil { + break + } + if ev.Kind() == EventRangeActive { + if ts := g.lastRangeTime[r.Name]; ts != 0 { + g.RangeTime[r.Name] += s.syncTs.Sub(ts) + } + g.lastRangeTime[r.Name] = s.syncTs + } else { + g.lastRangeTime[r.Name] = ev.Time() + } + case EventRangeEnd: + r := ev.Range() + var g *GoroutineSummary + switch r.Scope.Kind { + case ResourceGoroutine: + g = s.gs[r.Scope.Goroutine()] + case ResourceProc: + rp := rangeP{id: r.Scope.Proc(), name: r.Name} + if goid, ok := s.rangesP[rp]; ok { + if goid == ev.Goroutine() { + // As the comment in the RangeBegin case states, this is only OK + // if we finish on the same goroutine we started on. + g = s.gs[goid] + } + delete(s.rangesP, rp) + } + } + if g == nil { + break + } + ts := g.lastRangeTime[r.Name] + if ts == 0 { + break + } + g.RangeTime[r.Name] += ev.Time().Sub(ts) + delete(g.lastRangeTime, r.Name) + + // Handle user-defined regions. + case EventRegionBegin: + g := s.gs[ev.Goroutine()] + r := ev.Region() + region := &UserRegionSummary{ + Name: r.Type, + TaskID: r.Task, + Start: ev, + GoroutineExecStats: g.snapshotStat(ev.Time()), + } + g.activeRegions = append(g.activeRegions, region) + // Associate the region and current goroutine to the task. + task := s.getOrAddTask(r.Task) + task.Regions = append(task.Regions, region) + task.Goroutines[g.ID] = g + case EventRegionEnd: + g := s.gs[ev.Goroutine()] + r := ev.Region() + var sd *UserRegionSummary + if regionStk := g.activeRegions; len(regionStk) > 0 { + // Pop the top region from the stack since that's what must have ended. + n := len(regionStk) + sd = regionStk[n-1] + regionStk = regionStk[:n-1] + g.activeRegions = regionStk + // N.B. No need to add the region to a task; the EventRegionBegin already handled it. + } else { + // This is an "end" without a start. Just fabricate the region now. + sd = &UserRegionSummary{Name: r.Type, TaskID: r.Task} + // Associate the region and current goroutine to the task. + task := s.getOrAddTask(r.Task) + task.Goroutines[g.ID] = g + task.Regions = append(task.Regions, sd) + } + sd.GoroutineExecStats = g.snapshotStat(ev.Time()).sub(sd.GoroutineExecStats) + sd.End = ev + g.Regions = append(g.Regions, sd) + + // Handle tasks and logs. + case EventTaskBegin, EventTaskEnd: + // Initialize the task. + t := ev.Task() + task := s.getOrAddTask(t.ID) + task.Name = t.Type + task.Goroutines[ev.Goroutine()] = s.gs[ev.Goroutine()] + if ev.Kind() == EventTaskBegin { + task.Start = ev + } else { + task.End = ev + } + // Initialize the parent, if one exists and it hasn't been done yet. + // We need to avoid doing it twice, otherwise we could appear twice + // in the parent's Children list. + if t.Parent != NoTask && task.Parent == nil { + parent := s.getOrAddTask(t.Parent) + task.Parent = parent + parent.Children = append(parent.Children, task) + } + case EventLog: + log := ev.Log() + // Just add the log to the task. We'll create the task if it + // doesn't exist (it's just been mentioned now). + task := s.getOrAddTask(log.Task) + task.Goroutines[ev.Goroutine()] = s.gs[ev.Goroutine()] + task.Logs = append(task.Logs, ev) + } +} + +func (s *Summarizer) getOrAddTask(id TaskID) *UserTaskSummary { + task := s.tasks[id] + if task == nil { + task = &UserTaskSummary{ID: id, Goroutines: make(map[GoID]*GoroutineSummary)} + s.tasks[id] = task + } + return task +} + +// Finalize indicates to the summarizer that we're done processing the trace. +// It cleans up any remaining state and returns the full summary. +func (s *Summarizer) Finalize() *Summary { + for _, g := range s.gs { + g.finalize(s.lastTs, nil) + + // Sort based on region start time. + slices.SortFunc(g.Regions, func(a, b *UserRegionSummary) int { + x := a.Start + y := b.Start + if x == nil { + if y == nil { + return 0 + } + return -1 + } + if y == nil { + return +1 + } + return cmp.Compare(x.Time(), y.Time()) + }) + g.goroutineSummary = nil + } + return &Summary{ + Goroutines: s.gs, + Tasks: s.tasks, + } +} + +// RelatedGoroutinesV2 finds a set of goroutines related to goroutine goid for v2 traces. +// The association is based on whether they have synchronized with each other in the Go +// scheduler (one has unblocked another). +func RelatedGoroutinesV2(events []Event, goid GoID) map[GoID]struct{} { + // Process all the events, looking for transitions of goroutines + // out of GoWaiting. If there was an active goroutine when this + // happened, then we know that active goroutine unblocked another. + // Scribble all these down so we can process them. + type unblockEdge struct { + operator GoID + operand GoID + } + var unblockEdges []unblockEdge + for _, ev := range events { + if ev.Goroutine() == NoGoroutine { + continue + } + if ev.Kind() != EventStateTransition { + continue + } + st := ev.StateTransition() + if st.Resource.Kind != ResourceGoroutine { + continue + } + id := st.Resource.Goroutine() + old, new := st.Goroutine() + if old == new || old != GoWaiting { + continue + } + unblockEdges = append(unblockEdges, unblockEdge{ + operator: ev.Goroutine(), + operand: id, + }) + } + // Compute the transitive closure of depth 2 of goroutines that have unblocked each other + // (starting from goid). + gmap := make(map[GoID]struct{}) + gmap[goid] = struct{}{} + for i := 0; i < 2; i++ { + // Copy the map. + gmap1 := make(map[GoID]struct{}) + for g := range gmap { + gmap1[g] = struct{}{} + } + for _, edge := range unblockEdges { + if _, ok := gmap[edge.operand]; ok { + gmap1[edge.operator] = struct{}{} + } + } + gmap = gmap1 + } + return gmap +} + +func IsSystemGoroutine(entryFn string) bool { + // This mimics runtime.isSystemGoroutine as closely as + // possible. + // Also, locked g in extra M (with empty entryFn) is system goroutine. + return entryFn == "" || entryFn != "runtime.main" && strings.HasPrefix(entryFn, "runtime.") +} diff --git a/go/src/internal/trace/summary_test.go b/go/src/internal/trace/summary_test.go new file mode 100644 index 0000000000000000000000000000000000000000..74bffefd70844a6089d89115d74cdee388aab0b1 --- /dev/null +++ b/go/src/internal/trace/summary_test.go @@ -0,0 +1,441 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace_test + +import ( + "internal/trace" + "internal/trace/testtrace" + "io" + "testing" +) + +func TestSummarizeGoroutinesTrace(t *testing.T) { + summaries := summarizeTraceTest(t, "testdata/tests/go122-gc-stress.test").Goroutines + var ( + hasSchedWaitTime bool + hasSyncBlockTime bool + hasGCMarkAssistTime bool + hasUnknownTime bool + ) + + assertContainsGoroutine(t, summaries, "runtime.gcBgMarkWorker") + assertContainsGoroutine(t, summaries, "main.main.func1") + + for _, summary := range summaries { + basicGoroutineSummaryChecks(t, summary) + hasSchedWaitTime = hasSchedWaitTime || summary.SchedWaitTime > 0 + if dt, ok := summary.BlockTimeByReason["sync"]; ok && dt > 0 { + hasSyncBlockTime = true + } + if dt, ok := summary.RangeTime["GC mark assist"]; ok && dt > 0 { + hasGCMarkAssistTime = true + } + hasUnknownTime = hasUnknownTime || summary.UnknownTime() > 0 + } + if !hasSchedWaitTime { + t.Error("missing sched wait time") + } + if !hasSyncBlockTime { + t.Error("missing sync block time") + } + if !hasGCMarkAssistTime { + t.Error("missing GC mark assist time") + } + if hasUnknownTime { + t.Error("has time that is unaccounted for") + } +} + +func TestSummarizeGoroutinesRegionsTrace(t *testing.T) { + summaries := summarizeTraceTest(t, "testdata/tests/go122-annotations.test").Goroutines + type region struct { + startKind trace.EventKind + endKind trace.EventKind + } + wantRegions := map[string]region{ + // N.B. "pre-existing region" never even makes it into the trace. + // + // TODO(mknyszek): Add test case for end-without-a-start, which can happen at + // a generation split only. + "": {trace.EventStateTransition, trace.EventStateTransition}, // Task inheritance marker. + "task0 region": {trace.EventRegionBegin, trace.EventBad}, + "region0": {trace.EventRegionBegin, trace.EventRegionEnd}, + "region1": {trace.EventRegionBegin, trace.EventRegionEnd}, + "unended region": {trace.EventRegionBegin, trace.EventStateTransition}, + "post-existing region": {trace.EventRegionBegin, trace.EventBad}, + } + for _, summary := range summaries { + basicGoroutineSummaryChecks(t, summary) + for _, region := range summary.Regions { + want, ok := wantRegions[region.Name] + if !ok { + continue + } + checkRegionEvents(t, want.startKind, want.endKind, summary.ID, region) + delete(wantRegions, region.Name) + } + } + if len(wantRegions) != 0 { + t.Errorf("failed to find regions: %#v", wantRegions) + } +} + +func TestSummarizeTasksTrace(t *testing.T) { + summaries := summarizeTraceTest(t, "testdata/tests/go122-annotations-stress.test").Tasks + type task struct { + name string + parent *trace.TaskID + children []trace.TaskID + logs []trace.Log + goroutines []trace.GoID + } + parent := func(id trace.TaskID) *trace.TaskID { + p := new(trace.TaskID) + *p = id + return p + } + wantTasks := map[trace.TaskID]task{ + trace.BackgroundTask: { + // The background task (0) is never any task's parent. + logs: []trace.Log{ + {Task: trace.BackgroundTask, Category: "log", Message: "before do"}, + {Task: trace.BackgroundTask, Category: "log", Message: "before do"}, + }, + goroutines: []trace.GoID{1}, + }, + 1: { + // This started before tracing started and has no parents. + // Task 2 is technically a child, but we lost that information. + children: []trace.TaskID{3, 7, 16}, + logs: []trace.Log{ + {Task: 1, Category: "log", Message: "before do"}, + {Task: 1, Category: "log", Message: "before do"}, + }, + goroutines: []trace.GoID{1}, + }, + 2: { + // This started before tracing started and its parent is technically (1), but that information was lost. + children: []trace.TaskID{8, 17}, + logs: []trace.Log{ + {Task: 2, Category: "log", Message: "before do"}, + {Task: 2, Category: "log", Message: "before do"}, + }, + goroutines: []trace.GoID{1}, + }, + 3: { + parent: parent(1), + children: []trace.TaskID{10, 19}, + logs: []trace.Log{ + {Task: 3, Category: "log", Message: "before do"}, + {Task: 3, Category: "log", Message: "before do"}, + }, + goroutines: []trace.GoID{1}, + }, + 4: { + // Explicitly, no parent. + children: []trace.TaskID{12, 21}, + logs: []trace.Log{ + {Task: 4, Category: "log", Message: "before do"}, + {Task: 4, Category: "log", Message: "before do"}, + }, + goroutines: []trace.GoID{1}, + }, + 12: { + parent: parent(4), + children: []trace.TaskID{13}, + logs: []trace.Log{ + // TODO(mknyszek): This is computed asynchronously in the trace, + // which makes regenerating this test very annoying, since it will + // likely break this test. Resolve this by making the order not matter. + {Task: 12, Category: "log2", Message: "do"}, + {Task: 12, Category: "log", Message: "fanout region4"}, + {Task: 12, Category: "log", Message: "fanout region0"}, + {Task: 12, Category: "log", Message: "fanout region1"}, + {Task: 12, Category: "log", Message: "fanout region2"}, + {Task: 12, Category: "log", Message: "before do"}, + {Task: 12, Category: "log", Message: "fanout region3"}, + }, + goroutines: []trace.GoID{1, 5, 6, 7, 8, 9}, + }, + 13: { + // Explicitly, no children. + parent: parent(12), + logs: []trace.Log{ + {Task: 13, Category: "log2", Message: "do"}, + }, + goroutines: []trace.GoID{7}, + }, + } + for id, summary := range summaries { + want, ok := wantTasks[id] + if !ok { + continue + } + if id != summary.ID { + t.Errorf("ambiguous task %d (or %d?): field likely set incorrectly", id, summary.ID) + } + + // Check parent. + if want.parent != nil { + if summary.Parent == nil { + t.Errorf("expected parent %d for task %d without a parent", *want.parent, id) + } else if summary.Parent.ID != *want.parent { + t.Errorf("bad parent for task %d: want %d, got %d", id, *want.parent, summary.Parent.ID) + } + } else if summary.Parent != nil { + t.Errorf("unexpected parent %d for task %d", summary.Parent.ID, id) + } + + // Check children. + gotChildren := make(map[trace.TaskID]struct{}) + for _, child := range summary.Children { + gotChildren[child.ID] = struct{}{} + } + for _, wantChild := range want.children { + if _, ok := gotChildren[wantChild]; ok { + delete(gotChildren, wantChild) + } else { + t.Errorf("expected child task %d for task %d not found", wantChild, id) + } + } + if len(gotChildren) != 0 { + for child := range gotChildren { + t.Errorf("unexpected child task %d for task %d", child, id) + } + } + + // Check logs. + if len(want.logs) != len(summary.Logs) { + t.Errorf("wanted %d logs for task %d, got %d logs instead", len(want.logs), id, len(summary.Logs)) + } else { + for i := range want.logs { + if want.logs[i] != summary.Logs[i].Log() { + t.Errorf("log mismatch: want %#v, got %#v", want.logs[i], summary.Logs[i].Log()) + } + } + } + + // Check goroutines. + if len(want.goroutines) != len(summary.Goroutines) { + t.Errorf("wanted %d goroutines for task %d, got %d goroutines instead", len(want.goroutines), id, len(summary.Goroutines)) + } else { + for _, goid := range want.goroutines { + g, ok := summary.Goroutines[goid] + if !ok { + t.Errorf("want goroutine %d for task %d, not found", goid, id) + continue + } + if g.ID != goid { + t.Errorf("goroutine summary for %d does not match task %d listing of %d", g.ID, id, goid) + } + } + } + + // Marked as seen. + delete(wantTasks, id) + } + if len(wantTasks) != 0 { + t.Errorf("failed to find tasks: %#v", wantTasks) + } +} + +func assertContainsGoroutine(t *testing.T, summaries map[trace.GoID]*trace.GoroutineSummary, name string) { + for _, summary := range summaries { + if summary.Name == name { + return + } + } + t.Errorf("missing goroutine %s", name) +} + +func basicGoroutineSummaryChecks(t *testing.T, summary *trace.GoroutineSummary) { + if summary.ID == trace.NoGoroutine { + t.Error("summary found for no goroutine") + return + } + if (summary.StartTime != 0 && summary.CreationTime > summary.StartTime) || + (summary.StartTime != 0 && summary.EndTime != 0 && summary.StartTime > summary.EndTime) { + t.Errorf("bad summary creation/start/end times for G %d: creation=%d start=%d end=%d", summary.ID, summary.CreationTime, summary.StartTime, summary.EndTime) + } + if (summary.PC != 0 && summary.Name == "") || (summary.PC == 0 && summary.Name != "") { + t.Errorf("bad name and/or PC for G %d: pc=0x%x name=%q", summary.ID, summary.PC, summary.Name) + } + basicGoroutineExecStatsChecks(t, &summary.GoroutineExecStats) + for _, region := range summary.Regions { + basicGoroutineExecStatsChecks(t, ®ion.GoroutineExecStats) + } +} + +func summarizeTraceTest(t *testing.T, testPath string) *trace.Summary { + trc, _, _, err := testtrace.ParseFile(testPath) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + // Create the analysis state. + s := trace.NewSummarizer() + + // Create a reader. + r, err := trace.NewReader(trc) + if err != nil { + t.Fatalf("failed to create trace reader for %s: %v", testPath, err) + } + // Process the trace. + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("failed to process trace %s: %v", testPath, err) + } + s.Event(&ev) + } + return s.Finalize() +} + +func checkRegionEvents(t *testing.T, wantStart, wantEnd trace.EventKind, goid trace.GoID, region *trace.UserRegionSummary) { + switch wantStart { + case trace.EventBad: + if region.Start != nil { + t.Errorf("expected nil region start event, got\n%s", region.Start.String()) + } + case trace.EventStateTransition, trace.EventRegionBegin: + if region.Start == nil { + t.Error("expected non-nil region start event, got nil") + } + kind := region.Start.Kind() + if kind != wantStart { + t.Errorf("wanted region start event %s, got %s", wantStart, kind) + } + if kind == trace.EventRegionBegin { + if region.Start.Region().Type != region.Name { + t.Errorf("region name mismatch: event has %s, summary has %s", region.Start.Region().Type, region.Name) + } + } else { + st := region.Start.StateTransition() + if st.Resource.Kind != trace.ResourceGoroutine { + t.Errorf("found region start event for the wrong resource: %s", st.Resource) + } + if st.Resource.Goroutine() != goid { + t.Errorf("found region start event for the wrong resource: wanted goroutine %d, got %s", goid, st.Resource) + } + if old, _ := st.Goroutine(); old != trace.GoNotExist && old != trace.GoUndetermined { + t.Errorf("expected transition from GoNotExist or GoUndetermined, got transition from %s instead", old) + } + } + default: + t.Errorf("unexpected want start event type: %s", wantStart) + } + + switch wantEnd { + case trace.EventBad: + if region.End != nil { + t.Errorf("expected nil region end event, got\n%s", region.End.String()) + } + case trace.EventStateTransition, trace.EventRegionEnd: + if region.End == nil { + t.Error("expected non-nil region end event, got nil") + } + kind := region.End.Kind() + if kind != wantEnd { + t.Errorf("wanted region end event %s, got %s", wantEnd, kind) + } + if kind == trace.EventRegionEnd { + if region.End.Region().Type != region.Name { + t.Errorf("region name mismatch: event has %s, summary has %s", region.End.Region().Type, region.Name) + } + } else { + st := region.End.StateTransition() + if st.Resource.Kind != trace.ResourceGoroutine { + t.Errorf("found region end event for the wrong resource: %s", st.Resource) + } + if st.Resource.Goroutine() != goid { + t.Errorf("found region end event for the wrong resource: wanted goroutine %d, got %s", goid, st.Resource) + } + if _, new := st.Goroutine(); new != trace.GoNotExist { + t.Errorf("expected transition to GoNotExist, got transition to %s instead", new) + } + } + default: + t.Errorf("unexpected want end event type: %s", wantEnd) + } +} + +func basicGoroutineExecStatsChecks(t *testing.T, stats *trace.GoroutineExecStats) { + if stats.ExecTime < 0 { + t.Error("found negative ExecTime") + } + if stats.SchedWaitTime < 0 { + t.Error("found negative SchedWaitTime") + } + if stats.SyscallTime < 0 { + t.Error("found negative SyscallTime") + } + if stats.SyscallBlockTime < 0 { + t.Error("found negative SyscallBlockTime") + } + if stats.TotalTime < 0 { + t.Error("found negative TotalTime") + } + for reason, dt := range stats.BlockTimeByReason { + if dt < 0 { + t.Errorf("found negative BlockTimeByReason for %s", reason) + } + } + for name, dt := range stats.RangeTime { + if dt < 0 { + t.Errorf("found negative RangeTime for range %s", name) + } + } +} + +func TestRelatedGoroutinesV2Trace(t *testing.T) { + testPath := "testdata/tests/go122-gc-stress.test" + trc, _, _, err := testtrace.ParseFile(testPath) + if err != nil { + t.Fatalf("malformed test %s: bad trace file: %v", testPath, err) + } + + // Create a reader. + r, err := trace.NewReader(trc) + if err != nil { + t.Fatalf("failed to create trace reader for %s: %v", testPath, err) + } + + // Collect all the events. + var events []trace.Event + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("failed to process trace %s: %v", testPath, err) + } + events = append(events, ev) + } + + // Test the function. + targetg := trace.GoID(86) + got := trace.RelatedGoroutinesV2(events, targetg) + want := map[trace.GoID]struct{}{ + trace.GoID(86): {}, // N.B. Result includes target. + trace.GoID(71): {}, + trace.GoID(25): {}, + trace.GoID(122): {}, + } + for goid := range got { + if _, ok := want[goid]; ok { + delete(want, goid) + } else { + t.Errorf("unexpected goroutine %d found in related goroutines for %d in test %s", goid, targetg, testPath) + } + } + if len(want) != 0 { + for goid := range want { + t.Errorf("failed to find related goroutine %d for goroutine %d in test %s", goid, targetg, testPath) + } + } +} diff --git a/go/src/internal/trace/testdata/README.md b/go/src/internal/trace/testdata/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0fae9caf3711eada6856a795ab7178070abf4d00 --- /dev/null +++ b/go/src/internal/trace/testdata/README.md @@ -0,0 +1,38 @@ +# Trace test data + +## Trace golden tests + +Trace tests can be generated by running + +``` +go generate . +``` + +with the relevant toolchain in this directory. + +This will put the tests into a `tests` directory where the trace reader +tests will find them. + +A subset of tests can be regenerated by specifying a regexp pattern for +the names of tests to generate in the `GOTRACETEST` environment +variable. +Test names are defined as the name of the `.go` file that generates the +trace, but with the `.go` extension removed. + +## Trace test programs + +The trace test programs in the `testprog` directory generate traces to +stdout. +Otherwise they're just normal programs. + +## Trace debug commands + +The `cmd` directory contains helpful tools for debugging traces. + +* `gotraceraw` parses traces without validation. + It can produce a text version of the trace wire format, or convert + the text format back into bytes. +* `gotracevalidate` parses traces and validates them. + It performs more rigorous checks than the parser does on its own, + which helps for debugging the parser as well. + In fact, it performs the exact same checks that the tests do. diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/0cb1786dee0f090b b/go/src/internal/trace/testdata/fuzz/FuzzReader/0cb1786dee0f090b new file mode 100644 index 0000000000000000000000000000000000000000..326ebe1c6e59bc49d8ebf139b7ea520d24c95f2c --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/0cb1786dee0f090b @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x190000\x01\x0100\x88\x00\b0000000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/1e45307d5b2ec36d b/go/src/internal/trace/testdata/fuzz/FuzzReader/1e45307d5b2ec36d new file mode 100644 index 0000000000000000000000000000000000000000..406af9caa6b37e5959bad4978f4cb90230a0b692 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/1e45307d5b2ec36d @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01000\x85\x00\b0001") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/2b05796f9b2fc48d b/go/src/internal/trace/testdata/fuzz/FuzzReader/2b05796f9b2fc48d new file mode 100644 index 0000000000000000000000000000000000000000..50fdccda6b228954c54c158b7536bd3f49620cc2 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/2b05796f9b2fc48d @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00-0000\x01\x0100\x88\x00\b0000000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/2b9be9aebe08d511 b/go/src/internal/trace/testdata/fuzz/FuzzReader/2b9be9aebe08d511 new file mode 100644 index 0000000000000000000000000000000000000000..6bcb99adfc639a34d47e1a39f681a7dd2ff71db6 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/2b9be9aebe08d511 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x0f00\x120\x01\x0100\x88\x00\b0000000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/344331b314da0b08 b/go/src/internal/trace/testdata/fuzz/FuzzReader/344331b314da0b08 new file mode 100644 index 0000000000000000000000000000000000000000..de6e4694be8bca95e35adc94bc2d7752c9daad4e --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/344331b314da0b08 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\b0000\x01\x01\xff00\xb8\x00\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1901\xff\xff\xff\xff\xff\xff\xff\xff0\x800") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/365d7b5b633b3f97 b/go/src/internal/trace/testdata/fuzz/FuzzReader/365d7b5b633b3f97 new file mode 100644 index 0000000000000000000000000000000000000000..8dc370f383c22549750a05244c9fc57380c41d48 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/365d7b5b633b3f97 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x0100\x8c0\x85\x00\b0000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/4055b17cae1a3443 b/go/src/internal/trace/testdata/fuzz/FuzzReader/4055b17cae1a3443 new file mode 100644 index 0000000000000000000000000000000000000000..ea5417c78a0afa334bfab4330c50e171759204d7 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/4055b17cae1a3443 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.11 trace\x00\x00\x00A00\x020$0") diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/4d9ddc909984e871 b/go/src/internal/trace/testdata/fuzz/FuzzReader/4d9ddc909984e871 new file mode 100644 index 0000000000000000000000000000000000000000..040b2a4cae3f2eecd30f092b7ebca1dd04055a52 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/4d9ddc909984e871 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x11\r\xa700\x01\x19000\x02$000000\x01\x0100\x05\b0000\x01\x0110\x11\r\xa700\x01\x19 00\x02\x110 0000") diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/56f073e57903588c b/go/src/internal/trace/testdata/fuzz/FuzzReader/56f073e57903588c new file mode 100644 index 0000000000000000000000000000000000000000..d34fe3f06c800f1a46c300ece073d492d188484b --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/56f073e57903588c @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x1f0000\x01\x0100\x88\x00\b0000000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566 b/go/src/internal/trace/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566 new file mode 100644 index 0000000000000000000000000000000000000000..56772611555a7e27e7d57f1ebb8c9fa9743066ba --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x11\r\xa700\x01\x19000\x02#000000\x01\x0100\x05\b0000\x01\x0110\x11\r\xa700\x01\x19 00\x02\x110 0000") diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/aeb749b6bc317b66 b/go/src/internal/trace/testdata/fuzz/FuzzReader/aeb749b6bc317b66 new file mode 100644 index 0000000000000000000000000000000000000000..f93b5a90dad804a64d1002c76df65fc403636079 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/aeb749b6bc317b66 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01000\x85\x00\b0000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/closing-unknown-region b/go/src/internal/trace/testdata/fuzz/FuzzReader/closing-unknown-region new file mode 100644 index 0000000000000000000000000000000000000000..743321403038a25732ef8ba70ff0c105b7f3d3cd --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/closing-unknown-region @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xf6\x9f\n\x9fÕ\xb4\x99\xb2\x06\x11\r\xa7\x02\x00\x01\x19\x05\x01\xf6\x9f\n\x02+\x04\x01\x00\x00") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/d478e18d2d6756b7 b/go/src/internal/trace/testdata/fuzz/FuzzReader/d478e18d2d6756b7 new file mode 100644 index 0000000000000000000000000000000000000000..3e5fda833a93f1ab150098f6cedf40d408235d9c --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/d478e18d2d6756b7 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\"0000\x01\x0100\x88\x00\b0000000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/d91203cd397aa0bc b/go/src/internal/trace/testdata/fuzz/FuzzReader/d91203cd397aa0bc new file mode 100644 index 0000000000000000000000000000000000000000..d24b94ac9778aa1ee1e43d4b9b01d7170580ea55 --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/d91203cd397aa0bc @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01001\x85\x00\b0000") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/invalid-proc-state b/go/src/internal/trace/testdata/fuzz/FuzzReader/invalid-proc-state new file mode 100644 index 0000000000000000000000000000000000000000..e5d3258111361dc30b31466720ea1a68a045727e --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/invalid-proc-state @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x94镴\x99\xb2\x06\x05\r\xa7\x02\x00E") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/large-id b/go/src/internal/trace/testdata/fuzz/FuzzReader/large-id new file mode 100644 index 0000000000000000000000000000000000000000..0fb6273b443fab77d511874404d0f88c7cb37c4b --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/large-id @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x94镴\x99\xb2\x06\f\x02\x03\xff\xff\xff\xff\xff\xff\xff\x9f\x1d\x00") \ No newline at end of file diff --git a/go/src/internal/trace/testdata/fuzz/FuzzReader/malformed-timestamp b/go/src/internal/trace/testdata/fuzz/FuzzReader/malformed-timestamp new file mode 100644 index 0000000000000000000000000000000000000000..850ca50f87f35c999566f4c136ab2aba82bd777f --- /dev/null +++ b/go/src/internal/trace/testdata/fuzz/FuzzReader/malformed-timestamp @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xfa\x9f\n\xa5ѕ\xb4\x99\xb2\x06\x0e\n\x97\x96\x96\x96\x96\x96\x96\x96\x96\x96\x01\x01\x01") diff --git a/go/src/internal/trace/testdata/generate.go b/go/src/internal/trace/testdata/generate.go new file mode 100644 index 0000000000000000000000000000000000000000..c0658b2329667c3c341cad241403543cf2e6fa41 --- /dev/null +++ b/go/src/internal/trace/testdata/generate.go @@ -0,0 +1,6 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:generate go run mktests.go +package testdata diff --git a/go/src/internal/trace/testdata/generators/go122-confuse-seq-across-generations.go b/go/src/internal/trace/testdata/generators/go122-confuse-seq-across-generations.go new file mode 100644 index 0000000000000000000000000000000000000000..9b98723c4de8b124d4f856ae9ad238525bceae84 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-confuse-seq-across-generations.go @@ -0,0 +1,63 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Regression test for an issue found in development. +// +// The core of the issue is that if generation counters +// aren't considered as part of sequence numbers, then +// it's possible to accidentally advance without a +// GoStatus event. +// +// The situation is one in which it just so happens that +// an event on the frontier for a following generation +// has a sequence number exactly one higher than the last +// sequence number for e.g. a goroutine in the previous +// generation. The parser should wait to find a GoStatus +// event before advancing into the next generation at all. +// It turns out this situation is pretty rare; the GoStatus +// event almost always shows up first in practice. But it +// can and did happen. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g1 := t.Generation(1) + + // A running goroutine blocks. + b10 := g1.Batch(trace.ThreadID(0), 0) + b10.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b10.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b10.Event("GoStop", "whatever", testgen.NoStack) + + // The running goroutine gets unblocked. + b11 := g1.Batch(trace.ThreadID(1), 0) + b11.Event("ProcStatus", trace.ProcID(1), tracev2.ProcRunning) + b11.Event("GoStart", trace.GoID(1), testgen.Seq(1)) + b11.Event("GoStop", "whatever", testgen.NoStack) + + g2 := t.Generation(2) + + // Start running the goroutine, but later. + b21 := g2.Batch(trace.ThreadID(1), 3) + b21.Event("ProcStatus", trace.ProcID(1), tracev2.ProcRunning) + b21.Event("GoStart", trace.GoID(1), testgen.Seq(2)) + + // The goroutine starts running, then stops, then starts again. + b20 := g2.Batch(trace.ThreadID(0), 5) + b20.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b20.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunnable) + b20.Event("GoStart", trace.GoID(1), testgen.Seq(1)) + b20.Event("GoStop", "whatever", testgen.NoStack) +} diff --git a/go/src/internal/trace/testdata/generators/go122-create-syscall-reuse-thread-id.go b/go/src/internal/trace/testdata/generators/go122-create-syscall-reuse-thread-id.go new file mode 100644 index 0000000000000000000000000000000000000000..dc5c4a52572caf578684b8591b0c143bc933b3b1 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-create-syscall-reuse-thread-id.go @@ -0,0 +1,62 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a G being created from within a syscall. +// +// Specifically, it tests a scenario wherein a C +// thread is calling into Go, creating a goroutine in +// a syscall (in the tracer's model). The system is free +// to reuse thread IDs, so first a thread ID is used to +// call into Go, and then is used for a Go-created thread. +// +// This is a regression test. The trace parser didn't correctly +// model GoDestroySyscall as dropping its P (even if the runtime +// did). It turns out this is actually fine if all the threads +// in the trace have unique IDs, since the P just stays associated +// with an eternally dead thread, and it's stolen by some other +// thread later. But if thread IDs are reused, then the tracer +// gets confused when trying to advance events on the new thread. +// The now-dead thread which exited on a GoDestroySyscall still has +// its P associated and this transfers to the newly-live thread +// in the parser's state because they share a thread ID. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // A C thread calls into Go and acquires a P. It returns + // back to C, destroying the G. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("GoCreateSyscall", trace.GoID(4)) + b0.Event("GoSyscallEndBlocked") + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcIdle) + b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(1)) + b0.Event("GoStatus", trace.GoID(4), trace.NoThread, tracev2.GoRunnable) + b0.Event("GoStart", trace.GoID(4), testgen.Seq(1)) + b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack) + b0.Event("GoDestroySyscall") + + // A new Go-created thread with the same ID appears and + // starts running, then tries to steal the P from the + // first thread. The stealing is interesting because if + // the parser handles GoDestroySyscall wrong, then we + // have a self-steal here potentially that doesn't make + // sense. + b1 := g.Batch(trace.ThreadID(0), 0) + b1.Event("ProcStatus", trace.ProcID(1), tracev2.ProcIdle) + b1.Event("ProcStart", trace.ProcID(1), testgen.Seq(1)) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(3), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-create-syscall-with-p.go b/go/src/internal/trace/testdata/generators/go122-create-syscall-with-p.go new file mode 100644 index 0000000000000000000000000000000000000000..90729d7c528881690223e6ef7e7ff32cd734da21 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-create-syscall-with-p.go @@ -0,0 +1,53 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a G being created from within a syscall. +// +// Specifically, it tests a scenario wherein a C +// thread is calling into Go, creating a goroutine in +// a syscall (in the tracer's model). Because the actual +// m can be reused, it's possible for that m to have never +// had its P (in _Psyscall) stolen if the runtime doesn't +// model the scenario correctly. Make sure we reject such +// traces. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + t.ExpectFailure(".*expected a proc but didn't have one.*") + + g := t.Generation(1) + + // A C thread calls into Go and acquires a P. It returns + // back to C, destroying the G. It then comes back to Go + // on the same thread and again returns to C. + // + // Note: on pthread platforms this can't happen on the + // same thread because the m is stashed in TLS between + // calls into Go, until the thread dies. This is still + // possible on other platforms, however. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("GoCreateSyscall", trace.GoID(4)) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcIdle) + b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(1)) + b0.Event("GoSyscallEndBlocked") + b0.Event("GoStart", trace.GoID(4), testgen.Seq(1)) + b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack) + b0.Event("GoDestroySyscall") + b0.Event("GoCreateSyscall", trace.GoID(4)) + b0.Event("GoSyscallEnd") + b0.Event("GoSyscallBegin", testgen.Seq(3), testgen.NoStack) + b0.Event("GoDestroySyscall") +} diff --git a/go/src/internal/trace/testdata/generators/go122-fail-first-gen-first.go b/go/src/internal/trace/testdata/generators/go122-fail-first-gen-first.go new file mode 100644 index 0000000000000000000000000000000000000000..c8ead6772c0dcb68c651add421dd37753e7df9f7 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-fail-first-gen-first.go @@ -0,0 +1,45 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Regression test for #55160. +// +// The issue is that the parser reads ahead to the first batch of the +// next generation to find generation boundaries, but if it finds an +// error, it needs to delay handling that error until later. Previously +// it would handle that error immediately and a totally valid generation +// would be skipped for parsing and rejected because of an error in a +// batch in the following generation. +// +// This test captures this behavior by making both the first generation +// and second generation bad. It requires that the issue in the first +// generation, which is caught when actually ordering events, be reported +// instead of the second one. + +package main + +import ( + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + // A running goroutine emits a task begin. + t.RawEvent(tracev2.EvEventBatch, nil, 1 /*gen*/, 0 /*thread ID*/, 0 /*timestamp*/, 5 /*batch length*/) + t.RawEvent(tracev2.EvFrequency, nil, 15625000) + + // A running goroutine emits a task begin. + t.RawEvent(tracev2.EvEventBatch, nil, 1 /*gen*/, 0 /*thread ID*/, 0 /*timestamp*/, 5 /*batch length*/) + t.RawEvent(tracev2.EvGoCreate, nil, 0 /*timestamp delta*/, 1 /*go ID*/, 0, 0) + + // Write an invalid batch event for the next generation. + t.RawEvent(tracev2.EvEventBatch, nil, 2 /*gen*/, 0 /*thread ID*/, 0 /*timestamp*/, 50 /*batch length (invalid)*/) + + // We should fail at the first issue, not the second one. + t.ExpectFailure("expected a proc but didn't have one") +} diff --git a/go/src/internal/trace/testdata/generators/go122-go-create-without-running-g.go b/go/src/internal/trace/testdata/generators/go122-go-create-without-running-g.go new file mode 100644 index 0000000000000000000000000000000000000000..2e9b571d46eccab3e78932f9507a021c1b79678c --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-go-create-without-running-g.go @@ -0,0 +1,34 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Regression test for an issue found in development. +// +// GoCreate events can happen on bare Ps in a variety of situations and +// and earlier version of the parser assumed this wasn't possible. At +// the time of writing, one such example is goroutines created by expiring +// timers. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g1 := t.Generation(1) + + // A goroutine gets created on a running P, then starts running. + b0 := g1.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoCreate", trace.GoID(5), testgen.NoStack, testgen.NoStack) + b0.Event("GoStart", trace.GoID(5), testgen.Seq(1)) + b0.Event("GoStop", "whatever", testgen.NoStack) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-ambiguous.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-ambiguous.go new file mode 100644 index 0000000000000000000000000000000000000000..28d187c37e4782de202ab4df0135a36072488194 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-ambiguous.go @@ -0,0 +1,47 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. +// +// Specifically, it tests a scenario wherein, without a +// P sequence number of GoSyscallBegin, the syscall that +// a ProcSteal applies to is ambiguous. This only happens in +// practice when the events aren't already properly ordered +// by timestamp, since the ProcSteal won't be seen until after +// the correct GoSyscallBegin appears on the frontier. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + t.DisableTimestamps() + + g := t.Generation(1) + + // One goroutine does a syscall without blocking, then another one where + // it's P gets stolen. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("GoSyscallEnd") + b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack) + b0.Event("GoSyscallEndBlocked") + + // A running goroutine steals proc 0. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(2), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), tracev2.GoRunning) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(3), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go new file mode 100644 index 0000000000000000000000000000000000000000..5350b197404fe1851f1bd28485e21eed876946b0 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go @@ -0,0 +1,34 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing at a generation boundary. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine is exiting with a syscall. It already + // acquired a new P. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoSyscall) + b0.Event("GoSyscallEndBlocked") + + // A bare M stole the goroutine's P at the generation boundary. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(0), tracev2.ProcSyscallAbandoned) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go new file mode 100644 index 0000000000000000000000000000000000000000..f7611c5c0824c54e21fe6a456a342330351e416d --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go @@ -0,0 +1,35 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing at a generation boundary. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine is exiting with a syscall. It already + // acquired a new P. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoSyscall) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcIdle) + b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1)) + b0.Event("GoSyscallEndBlocked") + + // A bare M stole the goroutine's P at the generation boundary. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(0), tracev2.ProcSyscallAbandoned) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go new file mode 100644 index 0000000000000000000000000000000000000000..521363b0942b9998810000ad8d6bb76bf46a900f --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go @@ -0,0 +1,37 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing at a generation boundary. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine is exiting with a syscall. It already + // acquired a new P. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoSyscall) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcIdle) + b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1)) + b0.Event("GoSyscallEndBlocked") + + // A running goroutine stole P0 at the generation boundary. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(2), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), tracev2.GoRunning) + b1.Event("ProcStatus", trace.ProcID(0), tracev2.ProcSyscallAbandoned) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary.go new file mode 100644 index 0000000000000000000000000000000000000000..6c171c9cd1f89e3019e900f88adabf3536ed12bc --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary.go @@ -0,0 +1,36 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing at a generation boundary. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine is exiting with a syscall. It already + // acquired a new P. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoSyscall) + b0.Event("GoSyscallEndBlocked") + + // A running goroutine stole P0 at the generation boundary. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(2), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), tracev2.GoRunning) + b1.Event("ProcStatus", trace.ProcID(0), tracev2.ProcSyscallAbandoned) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go new file mode 100644 index 0000000000000000000000000000000000000000..18493dd5c383aa0eae6d196249a5fcf0fdc2f7f0 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go @@ -0,0 +1,35 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine enters a syscall, grabs a P, and starts running. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcIdle) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1)) + b0.Event("GoSyscallEndBlocked") + + // A bare M steals the goroutine's P. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go new file mode 100644 index 0000000000000000000000000000000000000000..d4e6ed3e2a2ed4d5cff2c20b655798390a6b5dd7 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go @@ -0,0 +1,37 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine enters a syscall, grabs a P, and starts running. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(1), tracev2.ProcIdle) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1)) + b0.Event("GoSyscallEndBlocked") + + // A running goroutine steals proc 0. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(2), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), tracev2.GoRunning) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-self.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-self.go new file mode 100644 index 0000000000000000000000000000000000000000..6dfb465b0a1819c8da04e884a752428b59edb30e --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-self.go @@ -0,0 +1,38 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. +// +// Specifically, it tests a scenario where a thread 'steals' +// a P from itself. It's just a ProcStop with extra steps when +// it happens on the same P. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + t.DisableTimestamps() + + g := t.Generation(1) + + // A goroutine execute a syscall and steals its own P, then starts running + // on that P. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0)) + b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(3)) + b0.Event("GoSyscallEndBlocked") +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go new file mode 100644 index 0000000000000000000000000000000000000000..ac314a6647804987d7fee36333d303d72ca404c3 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go @@ -0,0 +1,33 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine enters a syscall. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("GoSyscallEndBlocked") + + // A bare M steals the goroutine's P. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple.go new file mode 100644 index 0000000000000000000000000000000000000000..010272e5523c178d9eb4badaa3d90f2786b0c782 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-simple.go @@ -0,0 +1,35 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // One goroutine enters a syscall. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack) + b0.Event("GoSyscallEndBlocked") + + // A running goroutine steals proc 0. + b1 := g.Batch(trace.ThreadID(1), 0) + b1.Event("ProcStatus", trace.ProcID(2), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), tracev2.GoRunning) + b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0)) +} diff --git a/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go new file mode 100644 index 0000000000000000000000000000000000000000..410f9b7a089be88dd16bd3a912ab56b1dd43066f --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go @@ -0,0 +1,33 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests syscall P stealing from a goroutine and thread +// that have been in a syscall the entire generation. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g := t.Generation(1) + + // Steal proc from a goroutine that's been blocked + // in a syscall the entire generation. + b0 := g.Batch(trace.ThreadID(0), 0) + b0.Event("ProcStatus", trace.ProcID(0), tracev2.ProcSyscallAbandoned) + b0.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(1)) + + // Status event for a goroutine blocked in a syscall for the entire generation. + bz := g.Batch(trace.NoThread, 0) + bz.Event("GoStatus", trace.GoID(1), trace.ThreadID(1), tracev2.GoSyscall) +} diff --git a/go/src/internal/trace/testdata/generators/go122-task-across-generations.go b/go/src/internal/trace/testdata/generators/go122-task-across-generations.go new file mode 100644 index 0000000000000000000000000000000000000000..e8def318b403c5973f77c1e201a4328f47319ce8 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go122-task-across-generations.go @@ -0,0 +1,42 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Regression test for an issue found in development. +// +// The issue is that EvUserTaskEnd events don't carry the +// task type with them, so the parser needs to track that +// information. But if the parser just tracks the string ID +// and not the string itself, that string ID may not be valid +// for use in future generations. + +package main + +import ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" +) + +func main() { + testgen.Main(version.Go122, gen) +} + +func gen(t *testgen.Trace) { + g1 := t.Generation(1) + + // A running goroutine emits a task begin. + b1 := g1.Batch(trace.ThreadID(0), 0) + b1.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b1.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b1.Event("UserTaskBegin", trace.TaskID(2), trace.TaskID(0) /* 0 means no parent, not background */, "my task", testgen.NoStack) + + g2 := t.Generation(2) + + // That same goroutine emits a task end in the following generation. + b2 := g2.Batch(trace.ThreadID(0), 5) + b2.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + b2.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), tracev2.GoRunning) + b2.Event("UserTaskEnd", trace.TaskID(2), testgen.NoStack) +} diff --git a/go/src/internal/trace/testdata/generators/go123-sync.go b/go/src/internal/trace/testdata/generators/go123-sync.go new file mode 100644 index 0000000000000000000000000000000000000000..257581c7ea034c58507ef7d75dbf5f45603641cb --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go123-sync.go @@ -0,0 +1,30 @@ +// Copyright 2025 The Go Authors. 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 ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" + "time" +) + +func main() { + testgen.Main(version.Go123, gen) +} + +func gen(t *testgen.Trace) { + g1 := t.Generation(1) + g1.Sync(1000000000, 10, 0, time.Time{}) + b10 := g1.Batch(1, 15) + b10.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + g2 := t.Generation(2) + g2.Sync(500000000, 20, 0, time.Time{}) + g3 := t.Generation(3) + b30 := g3.Batch(1, 30) + b30.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + g3.Sync(500000000, 40, 0, time.Time{}) +} diff --git a/go/src/internal/trace/testdata/generators/go125-sync.go b/go/src/internal/trace/testdata/generators/go125-sync.go new file mode 100644 index 0000000000000000000000000000000000000000..30ebf6717a7629871cf8e082727e87ab77e4c170 --- /dev/null +++ b/go/src/internal/trace/testdata/generators/go125-sync.go @@ -0,0 +1,31 @@ +// Copyright 2025 The Go Authors. 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 ( + "internal/trace" + "internal/trace/internal/testgen" + "internal/trace/tracev2" + "internal/trace/version" + "time" +) + +func main() { + testgen.Main(version.Go125, gen) +} + +func gen(t *testgen.Trace) { + start := time.Date(2025, 2, 28, 15, 4, 9, 123, time.UTC) + g1 := t.Generation(1) + g1.Sync(1000000000, 10, 99, start) + b10 := g1.Batch(1, 15) + b10.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) + g2 := t.Generation(2) + g2.Sync(500000000, 20, 199, start.Add(1*time.Second)) + g3 := t.Generation(3) + g3.Sync(500000000, 30, 299, start.Add(2*time.Second)) + b30 := g3.Batch(1, 40) + b30.Event("ProcStatus", trace.ProcID(0), tracev2.ProcRunning) +} diff --git a/go/src/internal/trace/testdata/mktests.go b/go/src/internal/trace/testdata/mktests.go new file mode 100644 index 0000000000000000000000000000000000000000..d8d2e9065d3ec1ca52c6eb41619371c54887b8b6 --- /dev/null +++ b/go/src/internal/trace/testdata/mktests.go @@ -0,0 +1,160 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ignore + +package main + +import ( + "bytes" + "fmt" + "internal/trace/raw" + "internal/trace/version" + "internal/txtar" + "io" + "log" + "os" + "os/exec" + "path/filepath" + "regexp" +) + +func main() { + log.SetFlags(0) + ctx, err := newContext() + if err != nil { + log.Fatal(err) + } + if err := ctx.runGenerators(); err != nil { + log.Fatal(err) + } + if err := ctx.runTestProg("./testprog/annotations.go"); err != nil { + log.Fatal(err) + } + if err := ctx.runTestProg("./testprog/annotations-stress.go"); err != nil { + log.Fatal(err) + } +} + +type context struct { + testNames map[string]struct{} + filter *regexp.Regexp +} + +func newContext() (*context, error) { + var filter *regexp.Regexp + var err error + if pattern := os.Getenv("GOTRACETEST"); pattern != "" { + filter, err = regexp.Compile(pattern) + if err != nil { + return nil, fmt.Errorf("compiling regexp %q for GOTRACETEST: %v", pattern, err) + } + } + return &context{ + testNames: make(map[string]struct{}), + filter: filter, + }, nil +} + +func (ctx *context) register(testName string) (skip bool, err error) { + if _, ok := ctx.testNames[testName]; ok { + return true, fmt.Errorf("duplicate test %s found", testName) + } + if ctx.filter != nil { + return !ctx.filter.MatchString(testName), nil + } + return false, nil +} + +func (ctx *context) runGenerators() error { + generators, err := filepath.Glob("./generators/*.go") + if err != nil { + return fmt.Errorf("reading generators: %v", err) + } + genroot := "./tests" + + if err := os.MkdirAll(genroot, 0777); err != nil { + return fmt.Errorf("creating generated root: %v", err) + } + for _, path := range generators { + name := filepath.Base(path) + name = name[:len(name)-len(filepath.Ext(name))] + + // Skip if we have a pattern and this test doesn't match. + skip, err := ctx.register(name) + if err != nil { + return err + } + if skip { + continue + } + + fmt.Fprintf(os.Stderr, "generating %s... ", name) + + // Get the test path. + testPath := filepath.Join(genroot, fmt.Sprintf("%s.test", name)) + + // Run generator. + cmd := exec.Command("go", "run", path, testPath) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("running generator %s: %v:\n%s", name, err, out) + } + fmt.Fprintln(os.Stderr) + } + return nil +} + +func (ctx *context) runTestProg(progPath string) error { + name := filepath.Base(progPath) + name = name[:len(name)-len(filepath.Ext(name))] + name = fmt.Sprintf("go1%d-%s", version.Current, name) + + // Skip if we have a pattern and this test doesn't match. + skip, err := ctx.register(name) + if err != nil { + return err + } + if skip { + return nil + } + + // Create command. + var trace, stderr bytes.Buffer + cmd := exec.Command("go", "run", progPath) + cmd.Stdout = &trace + cmd.Stderr = &stderr + + // Run trace program; the trace will appear in stdout. + fmt.Fprintf(os.Stderr, "running trace program %s...\n", name) + if err := cmd.Run(); err != nil { + log.Fatalf("running trace program: %v:\n%s", err, stderr.String()) + } + + // Write out the trace. + var textTrace bytes.Buffer + r, err := raw.NewReader(&trace) + if err != nil { + log.Fatalf("reading trace: %v", err) + } + w, err := raw.NewTextWriter(&textTrace, version.Current) + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + log.Fatalf("reading trace: %v", err) + } + if err := w.WriteEvent(ev); err != nil { + log.Fatalf("writing trace: %v", err) + } + } + testData := txtar.Format(&txtar.Archive{ + Files: []txtar.File{ + {Name: "expect", Data: []byte("SUCCESS")}, + {Name: "trace", Data: textTrace.Bytes()}, + }, + }) + return os.WriteFile(fmt.Sprintf("./tests/%s.test", name), testData, 0o664) +} diff --git a/go/src/internal/trace/testdata/testprog/annotations-stress.go b/go/src/internal/trace/testdata/testprog/annotations-stress.go new file mode 100644 index 0000000000000000000000000000000000000000..511d6ed890b25c0e19e67e6425813ef4bea618a7 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/annotations-stress.go @@ -0,0 +1,84 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests user tasks, regions, and logging. + +//go:build ignore + +package main + +import ( + "context" + "fmt" + "log" + "os" + "runtime/trace" + "time" +) + +func main() { + baseCtx := context.Background() + + // Create a task that starts and ends entirely outside of the trace. + ctx0, t0 := trace.NewTask(baseCtx, "parent") + + // Create a task that starts before the trace and ends during the trace. + ctx1, t1 := trace.NewTask(ctx0, "type1") + + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + t1.End() + + // Create a task that starts during the trace and ends after. + ctx2, t2 := trace.NewTask(ctx0, "type2") + + // Create a task that starts and ends during the trace. + ctx3, t3 := trace.NewTask(baseCtx, "type3") + + // Generate some events. + for i := 0; i < 2; i++ { + do(baseCtx, 4) + do(ctx0, 2) + do(ctx1, 3) + do(ctx2, 6) + do(ctx3, 5) + } + + // Finish up tasks according to their lifetime relative to the trace. + t3.End() + trace.Stop() + t2.End() + t0.End() +} + +func do(ctx context.Context, k int) { + trace.Log(ctx, "log", "before do") + + var t *trace.Task + ctx, t = trace.NewTask(ctx, "do") + defer t.End() + + trace.Log(ctx, "log2", "do") + + // Create a region and spawn more tasks and more workers. + trace.WithRegion(ctx, "fanout", func() { + for i := 0; i < k; i++ { + go func(i int) { + trace.WithRegion(ctx, fmt.Sprintf("region%d", i), func() { + trace.Logf(ctx, "log", "fanout region%d", i) + if i == 2 { + do(ctx, 0) + return + } + }) + }(i) + } + }) + + // Sleep to let things happen, but also increase the chance that we + // advance a generation. + time.Sleep(10 * time.Millisecond) +} diff --git a/go/src/internal/trace/testdata/testprog/annotations.go b/go/src/internal/trace/testdata/testprog/annotations.go new file mode 100644 index 0000000000000000000000000000000000000000..2507bc4d3890d1f7a1cbb8c99106b3ecce8595f7 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/annotations.go @@ -0,0 +1,60 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests user tasks, regions, and logging. + +//go:build ignore + +package main + +import ( + "context" + "log" + "os" + "runtime/trace" + "sync" +) + +func main() { + bgctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Create a pre-existing region. This won't end up in the trace. + preExistingRegion := trace.StartRegion(bgctx, "pre-existing region") + + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + // Beginning of traced execution. + var wg sync.WaitGroup + ctx, task := trace.NewTask(bgctx, "task0") // EvUserTaskCreate("task0") + trace.StartRegion(ctx, "task0 region") + + wg.Add(1) + go func() { + defer wg.Done() + defer task.End() // EvUserTaskEnd("task0") + + trace.StartRegion(ctx, "unended region") + + trace.WithRegion(ctx, "region0", func() { + // EvUserRegionBegin("region0", start) + trace.WithRegion(ctx, "region1", func() { + trace.Log(ctx, "key0", "0123456789abcdef") // EvUserLog("task0", "key0", "0....f") + }) + // EvUserRegionEnd("region0", end) + }) + }() + wg.Wait() + + preExistingRegion.End() + postExistingRegion := trace.StartRegion(bgctx, "post-existing region") + + // End of traced execution. + trace.Stop() + + postExistingRegion.End() +} diff --git a/go/src/internal/trace/testdata/testprog/cgo-callback.go b/go/src/internal/trace/testdata/testprog/cgo-callback.go new file mode 100644 index 0000000000000000000000000000000000000000..d63650047e584f50bf493c54669d1945dce7fb48 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/cgo-callback.go @@ -0,0 +1,80 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests CPU profiling. + +//go:build ignore + +package main + +/* +#include + +void go_callback(); +void go_callback2(); + +static void *thr(void *arg) { + go_callback(); + return 0; +} + +static void foo() { + pthread_t th; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, 256 << 10); + pthread_create(&th, &attr, thr, 0); + pthread_join(th, 0); +} + +static void bar() { + go_callback2(); +} +*/ +import "C" + +import ( + "log" + "os" + "runtime" + "runtime/trace" +) + +//export go_callback +func go_callback() { + // Do another call into C, just to test that path too. + C.bar() +} + +//export go_callback2 +func go_callback2() { + runtime.GC() +} + +func main() { + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + // Do a whole bunch of cgocallbacks. + const n = 10 + done := make(chan bool) + for i := 0; i < n; i++ { + go func() { + C.foo() + done <- true + }() + } + for i := 0; i < n; i++ { + <-done + } + + // Do something to steal back any Ps from the Ms, just + // for coverage. + runtime.GC() + + // End of traced execution. + trace.Stop() +} diff --git a/go/src/internal/trace/testdata/testprog/cpu-profile.go b/go/src/internal/trace/testdata/testprog/cpu-profile.go new file mode 100644 index 0000000000000000000000000000000000000000..293a2acac8a2bf2434b868fbb68c4f28cacb6f6a --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/cpu-profile.go @@ -0,0 +1,137 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests CPU profiling. + +//go:build ignore + +package main + +import ( + "bytes" + "context" + "fmt" + "internal/profile" + "log" + "os" + "runtime" + "runtime/pprof" + "runtime/trace" + "strings" + "time" +) + +func main() { + cpuBuf := new(bytes.Buffer) + if err := pprof.StartCPUProfile(cpuBuf); err != nil { + log.Fatalf("failed to start CPU profile: %v", err) + } + + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + dur := 100 * time.Millisecond + func() { + // Create a region in the execution trace. Set and clear goroutine + // labels fully within that region, so we know that any CPU profile + // sample with the label must also be eligible for inclusion in the + // execution trace. + ctx := context.Background() + defer trace.StartRegion(ctx, "cpuHogger").End() + pprof.Do(ctx, pprof.Labels("tracing", "on"), func(ctx context.Context) { + cpuHogger(cpuHog1, &salt1, dur) + }) + // Be sure the execution trace's view, when filtered to this goroutine + // via the explicit goroutine ID in each event, gets many more samples + // than the CPU profiler when filtered to this goroutine via labels. + cpuHogger(cpuHog1, &salt1, dur) + }() + + trace.Stop() + pprof.StopCPUProfile() + + // Summarize the CPU profile to stderr so the test can check against it. + + prof, err := profile.Parse(cpuBuf) + if err != nil { + log.Fatalf("failed to parse CPU profile: %v", err) + } + // Examine the CPU profiler's view. Filter it to only include samples from + // the single test goroutine. Use labels to execute that filter: they should + // apply to all work done while that goroutine is getg().m.curg, and they + // should apply to no other goroutines. + pprofStacks := make(map[string]int) + for _, s := range prof.Sample { + if s.Label["tracing"] != nil { + var fns []string + var leaf string + for _, loc := range s.Location { + for _, line := range loc.Line { + fns = append(fns, fmt.Sprintf("%s:%d", line.Function.Name, line.Line)) + leaf = line.Function.Name + } + } + // runtime.sigprof synthesizes call stacks when "normal traceback is + // impossible or has failed", using particular placeholder functions + // to represent common failure cases. Look for those functions in + // the leaf position as a sign that the call stack and its + // symbolization are more complex than this test can handle. + // + // TODO: Make the symbolization done by the execution tracer and CPU + // profiler match up even in these harder cases. See #53378. + switch leaf { + case "runtime._System", "runtime._GC", "runtime._ExternalCode", "runtime._VDSO": + continue + } + stack := strings.Join(fns, "|") + samples := int(s.Value[0]) + pprofStacks[stack] += samples + } + } + for stack, samples := range pprofStacks { + fmt.Fprintf(os.Stderr, "%s\t%d\n", stack, samples) + } +} + +func cpuHogger(f func(x int) int, y *int, dur time.Duration) { + // We only need to get one 100 Hz clock tick, so we've got + // a large safety buffer. + // But do at least 500 iterations (which should take about 100ms), + // otherwise TestCPUProfileMultithreaded can fail if only one + // thread is scheduled during the testing period. + t0 := time.Now() + accum := *y + for i := 0; i < 500 || time.Since(t0) < dur; i++ { + accum = f(accum) + } + *y = accum +} + +var ( + salt1 = 0 +) + +// The actual CPU hogging function. +// Must not call other functions nor access heap/globals in the loop, +// otherwise under race detector the samples will be in the race runtime. +func cpuHog1(x int) int { + return cpuHog0(x, 1e5) +} + +func cpuHog0(x, n int) int { + foo := x + for i := 0; i < n; i++ { + if i%1000 == 0 { + // Spend time in mcall, stored as gp.m.curg, with g0 running + runtime.Gosched() + } + if foo > 0 { + foo *= foo + } else { + foo *= foo + 1 + } + } + return foo +} diff --git a/go/src/internal/trace/testdata/testprog/futile-wakeup.go b/go/src/internal/trace/testdata/testprog/futile-wakeup.go new file mode 100644 index 0000000000000000000000000000000000000000..cc489818fc9fcb5bf98d15b705198c0450bff15f --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/futile-wakeup.go @@ -0,0 +1,84 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests to make sure the runtime doesn't generate futile wakeups. For example, +// it makes sure that a block on a channel send that unblocks briefly only to +// immediately go back to sleep (in such a way that doesn't reveal any useful +// information, and is purely an artifact of the runtime implementation) doesn't +// make it into the trace. + +//go:build ignore + +package main + +import ( + "context" + "log" + "os" + "runtime" + "runtime/trace" + "sync" +) + +func main() { + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8)) + c0 := make(chan int, 1) + c1 := make(chan int, 1) + c2 := make(chan int, 1) + const procs = 2 + var done sync.WaitGroup + done.Add(4 * procs) + for p := 0; p < procs; p++ { + const iters = 1e3 + go func() { + trace.WithRegion(context.Background(), "special", func() { + for i := 0; i < iters; i++ { + runtime.Gosched() + c0 <- 0 + } + done.Done() + }) + }() + go func() { + trace.WithRegion(context.Background(), "special", func() { + for i := 0; i < iters; i++ { + runtime.Gosched() + <-c0 + } + done.Done() + }) + }() + go func() { + trace.WithRegion(context.Background(), "special", func() { + for i := 0; i < iters; i++ { + runtime.Gosched() + select { + case c1 <- 0: + case c2 <- 0: + } + } + done.Done() + }) + }() + go func() { + trace.WithRegion(context.Background(), "special", func() { + for i := 0; i < iters; i++ { + runtime.Gosched() + select { + case <-c1: + case <-c2: + } + } + done.Done() + }) + }() + } + done.Wait() + + trace.Stop() +} diff --git a/go/src/internal/trace/testdata/testprog/gc-stress.go b/go/src/internal/trace/testdata/testprog/gc-stress.go new file mode 100644 index 0000000000000000000000000000000000000000..74b63606d5e6199f53438ea67676a0dd674ee012 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/gc-stress.go @@ -0,0 +1,99 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a GC-heavy program. This is useful for shaking out +// all sorts of corner cases about GC-related ranges. + +//go:build ignore + +package main + +import ( + "log" + "os" + "runtime" + "runtime/debug" + "runtime/trace" + "time" +) + +type node struct { + children [4]*node + data [128]byte +} + +func makeTree(depth int) *node { + if depth == 0 { + return new(node) + } + return &node{ + children: [4]*node{ + makeTree(depth - 1), + makeTree(depth - 1), + makeTree(depth - 1), + makeTree(depth - 1), + }, + } +} + +func initTree(n *node) { + if n == nil { + return + } + for i := range n.data { + n.data[i] = 'a' + } + for i := range n.children { + initTree(n.children[i]) + } +} + +var trees [16]*node +var ballast *[16]*[1024]*node +var sink []*node + +func main() { + debug.SetMemoryLimit(50 << 20) + + for i := range trees { + trees[i] = makeTree(6) + } + ballast = new([16]*[1024]*node) + for i := range ballast { + ballast[i] = new([1024]*node) + for j := range ballast[i] { + ballast[i][j] = &node{ + data: [128]byte{1, 2, 3, 4}, + } + } + } + + procs := runtime.GOMAXPROCS(-1) + sink = make([]*node, procs) + + for i := 0; i < procs; i++ { + i := i + go func() { + for { + sink[i] = makeTree(3) + for range 5 { + initTree(sink[i]) + runtime.Gosched() + } + } + }() + } + // Increase the chance that we end up starting and stopping + // mid-GC by only starting to trace after a few milliseconds. + time.Sleep(5 * time.Millisecond) + + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + defer trace.Stop() + + // Let the tracing happen for a bit. + time.Sleep(400 * time.Millisecond) +} diff --git a/go/src/internal/trace/testdata/testprog/gomaxprocs.go b/go/src/internal/trace/testdata/testprog/gomaxprocs.go new file mode 100644 index 0000000000000000000000000000000000000000..265120767d6771f45edce77f15c4e8d4d3caf87f --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/gomaxprocs.go @@ -0,0 +1,46 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests increasing and decreasing GOMAXPROCS to try and +// catch issues with stale proc state. + +//go:build ignore + +package main + +import ( + "log" + "os" + "runtime" + "runtime/trace" + "time" +) + +func main() { + // Start a goroutine that calls runtime.GC to try and + // introduce some interesting events in between the + // GOMAXPROCS calls. + go func() { + for { + runtime.GC() + time.Sleep(1 * time.Millisecond) + } + }() + + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + // Run GOMAXPROCS a bunch of times, up and down. + for i := 1; i <= 16; i *= 2 { + runtime.GOMAXPROCS(i) + time.Sleep(1 * time.Millisecond) + } + for i := 16; i >= 1; i /= 2 { + runtime.GOMAXPROCS(i) + time.Sleep(1 * time.Millisecond) + } + // Stop tracing. + trace.Stop() +} diff --git a/go/src/internal/trace/testdata/testprog/iter-pull.go b/go/src/internal/trace/testdata/testprog/iter-pull.go new file mode 100644 index 0000000000000000000000000000000000000000..ba8f41365e3fe28d526fa7d99a721bfc96e26b9c --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/iter-pull.go @@ -0,0 +1,85 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests coroutine switches. + +//go:build ignore + +package main + +import ( + "iter" + "log" + "os" + "runtime/trace" + "sync" +) + +func main() { + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + // Try simple pull iteration. + i := pullRange(100) + for { + _, ok := i.next() + if !ok { + break + } + } + + // Try bouncing the pull iterator between two goroutines. + var wg sync.WaitGroup + var iterChans [2]chan intIter + wg.Add(2) + iterChans[0] = make(chan intIter) + iterChans[1] = make(chan intIter) + go func() { + defer wg.Done() + + iter := pullRange(100) + iterChans[1] <- iter + + for i := range iterChans[0] { + _, ok := i.next() + if !ok { + close(iterChans[1]) + break + } + iterChans[1] <- i + } + }() + go func() { + defer wg.Done() + + for i := range iterChans[1] { + _, ok := i.next() + if !ok { + close(iterChans[0]) + break + } + iterChans[0] <- i + } + }() + wg.Wait() + + // End of traced execution. + trace.Stop() +} + +func pullRange(n int) intIter { + next, stop := iter.Pull(func(yield func(v int) bool) { + for i := range n { + yield(i) + } + }) + return intIter{next: next, stop: stop} +} + +type intIter struct { + next func() (int, bool) + stop func() +} diff --git a/go/src/internal/trace/testdata/testprog/many-start-stop.go b/go/src/internal/trace/testdata/testprog/many-start-stop.go new file mode 100644 index 0000000000000000000000000000000000000000..2d5d0634f0f7ba5fc59630f1c5c419e71db329d8 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/many-start-stop.go @@ -0,0 +1,38 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests simply starting and stopping tracing multiple times. +// +// This is useful for finding bugs in trace state reset. + +//go:build ignore + +package main + +import ( + "bytes" + "log" + "os" + "runtime" + "runtime/trace" +) + +func main() { + // Trace a few times. + for i := 0; i < 10; i++ { + var buf bytes.Buffer + if err := trace.Start(&buf); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + runtime.GC() + trace.Stop() + } + + // Start tracing again, this time writing out the result. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + runtime.GC() + trace.Stop() +} diff --git a/go/src/internal/trace/testdata/testprog/stacks.go b/go/src/internal/trace/testdata/testprog/stacks.go new file mode 100644 index 0000000000000000000000000000000000000000..478daa0d941b2bc4a8b0336e108b9fd9835ad780 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/stacks.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. + +// Tests stack symbolization. + +//go:build ignore + +package main + +import ( + "log" + "net" + "os" + "runtime" + "runtime/trace" + "sync" + "time" +) + +func main() { + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + defer trace.Stop() // in case of early return + + // Now we will do a bunch of things for which we verify stacks later. + // It is impossible to ensure that a goroutine has actually blocked + // on a channel, in a select or otherwise. So we kick off goroutines + // that need to block first in the hope that while we are executing + // the rest of the test, they will block. + go func() { // func1 + select {} + }() + go func() { // func2 + var c chan int + c <- 0 + }() + go func() { // func3 + var c chan int + <-c + }() + done1 := make(chan bool) + go func() { // func4 + <-done1 + }() + done2 := make(chan bool) + go func() { // func5 + done2 <- true + }() + c1 := make(chan int) + c2 := make(chan int) + go func() { // func6 + select { + case <-c1: + case <-c2: + } + }() + var mu sync.Mutex + mu.Lock() + go func() { // func7 + mu.Lock() + mu.Unlock() + }() + var wg sync.WaitGroup + wg.Add(1) + go func() { // func8 + wg.Wait() + }() + cv := sync.NewCond(&sync.Mutex{}) + go func() { // func9 + cv.L.Lock() + cv.Wait() + cv.L.Unlock() + }() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + go func() { // func10 + c, err := ln.Accept() + if err != nil { + log.Printf("failed to accept: %v", err) + return + } + c.Close() + }() + rp, wp, err := os.Pipe() + if err != nil { + log.Fatalf("failed to create a pipe: %v", err) + } + defer rp.Close() + defer wp.Close() + pipeReadDone := make(chan bool) + go func() { // func11 + var data [1]byte + rp.Read(data[:]) + pipeReadDone <- true + }() + go func() { // func12 + for { + syncPreemptPoint() + } + }() + + time.Sleep(100 * time.Millisecond) + runtime.GC() + runtime.Gosched() + time.Sleep(100 * time.Millisecond) // the last chance for the goroutines above to block + done1 <- true + <-done2 + select { + case c1 <- 0: + case c2 <- 0: + } + mu.Unlock() + wg.Done() + cv.Signal() + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + log.Fatalf("failed to dial: %v", err) + } + c.Close() + var data [1]byte + wp.Write(data[:]) + <-pipeReadDone + + oldGoMaxProcs := runtime.GOMAXPROCS(0) + runtime.GOMAXPROCS(oldGoMaxProcs + 1) + + trace.Stop() + + runtime.GOMAXPROCS(oldGoMaxProcs) +} + +//go:noinline +func syncPreemptPoint() { + if never { + syncPreemptPoint() + } +} + +var never bool diff --git a/go/src/internal/trace/testdata/testprog/stress-start-stop.go b/go/src/internal/trace/testdata/testprog/stress-start-stop.go new file mode 100644 index 0000000000000000000000000000000000000000..72c1c5941711e4bc711a4584b4dcc4d23f573ca0 --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/stress-start-stop.go @@ -0,0 +1,166 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a many interesting cases (network, syscalls, a little GC, busy goroutines, +// blocked goroutines, LockOSThread, pipes, and GOMAXPROCS). + +//go:build ignore + +package main + +import ( + "bytes" + "io" + "log" + "net" + "os" + "runtime" + "runtime/trace" + "sync" + "time" +) + +func main() { + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8)) + outerDone := make(chan bool) + + go func() { + defer func() { + outerDone <- true + }() + + var wg sync.WaitGroup + done := make(chan bool) + + wg.Add(1) + go func() { + <-done + wg.Done() + }() + + rp, wp, err := os.Pipe() + if err != nil { + log.Fatalf("failed to create pipe: %v", err) + return + } + defer func() { + rp.Close() + wp.Close() + }() + wg.Add(1) + go func() { + var tmp [1]byte + rp.Read(tmp[:]) + <-done + wg.Done() + }() + time.Sleep(time.Millisecond) + + go func() { + runtime.LockOSThread() + for { + select { + case <-done: + return + default: + runtime.Gosched() + } + } + }() + + runtime.GC() + // Trigger GC from malloc. + n := 512 + for i := 0; i < n; i++ { + _ = make([]byte, 1<<20) + } + + // Create a bunch of busy goroutines to load all Ps. + for p := 0; p < 10; p++ { + wg.Add(1) + go func() { + // Do something useful. + tmp := make([]byte, 1<<16) + for i := range tmp { + tmp[i]++ + } + _ = tmp + <-done + wg.Done() + }() + } + + // Block in syscall. + wg.Add(1) + go func() { + var tmp [1]byte + rp.Read(tmp[:]) + <-done + wg.Done() + }() + + runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + + // Test timers. + timerDone := make(chan bool) + go func() { + time.Sleep(time.Millisecond) + timerDone <- true + }() + <-timerDone + + // A bit of network. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + log.Fatalf("listen failed: %v", err) + return + } + defer ln.Close() + go func() { + c, err := ln.Accept() + if err != nil { + return + } + time.Sleep(time.Millisecond) + var buf [1]byte + c.Write(buf[:]) + c.Close() + }() + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + log.Fatalf("dial failed: %v", err) + return + } + var tmp [1]byte + c.Read(tmp[:]) + c.Close() + + go func() { + runtime.Gosched() + select {} + }() + + // Unblock helper goroutines and wait them to finish. + wp.Write(tmp[:]) + wp.Write(tmp[:]) + close(done) + wg.Wait() + }() + + const iters = 5 + for i := 0; i < iters; i++ { + var w io.Writer + if i == iters-1 { + w = os.Stdout + } else { + w = new(bytes.Buffer) + } + if err := trace.Start(w); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + time.Sleep(time.Millisecond) + trace.Stop() + } + <-outerDone +} diff --git a/go/src/internal/trace/testdata/testprog/stress.go b/go/src/internal/trace/testdata/testprog/stress.go new file mode 100644 index 0000000000000000000000000000000000000000..99696d17569a45bb5da10122d22262afdf54c6ef --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/stress.go @@ -0,0 +1,146 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a many interesting cases (network, syscalls, a little GC, busy goroutines, +// blocked goroutines, LockOSThread, pipes, and GOMAXPROCS). + +//go:build ignore + +package main + +import ( + "log" + "net" + "os" + "runtime" + "runtime/trace" + "sync" + "time" +) + +func main() { + var wg sync.WaitGroup + done := make(chan bool) + + // Create a goroutine blocked before tracing. + wg.Add(1) + go func() { + <-done + wg.Done() + }() + + // Create a goroutine blocked in syscall before tracing. + rp, wp, err := os.Pipe() + if err != nil { + log.Fatalf("failed to create pipe: %v", err) + } + defer func() { + rp.Close() + wp.Close() + }() + wg.Add(1) + go func() { + var tmp [1]byte + rp.Read(tmp[:]) + <-done + wg.Done() + }() + time.Sleep(time.Millisecond) // give the goroutine above time to block + + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + defer trace.Stop() + + procs := runtime.GOMAXPROCS(10) + time.Sleep(50 * time.Millisecond) // test proc stop/start events + + go func() { + runtime.LockOSThread() + for { + select { + case <-done: + return + default: + runtime.Gosched() + } + } + }() + + runtime.GC() + // Trigger GC from malloc. + n := 512 + for i := 0; i < n; i++ { + _ = make([]byte, 1<<20) + } + + // Create a bunch of busy goroutines to load all Ps. + for p := 0; p < 10; p++ { + wg.Add(1) + go func() { + // Do something useful. + tmp := make([]byte, 1<<16) + for i := range tmp { + tmp[i]++ + } + _ = tmp + <-done + wg.Done() + }() + } + + // Block in syscall. + wg.Add(1) + go func() { + var tmp [1]byte + rp.Read(tmp[:]) + <-done + wg.Done() + }() + + // Test timers. + timerDone := make(chan bool) + go func() { + time.Sleep(time.Millisecond) + timerDone <- true + }() + <-timerDone + + // A bit of network. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + log.Fatalf("listen failed: %v", err) + } + defer ln.Close() + go func() { + c, err := ln.Accept() + if err != nil { + return + } + time.Sleep(time.Millisecond) + var buf [1]byte + c.Write(buf[:]) + c.Close() + }() + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + log.Fatalf("dial failed: %v", err) + } + var tmp [1]byte + c.Read(tmp[:]) + c.Close() + + go func() { + runtime.Gosched() + select {} + }() + + // Unblock helper goroutines and wait them to finish. + wp.Write(tmp[:]) + wp.Write(tmp[:]) + close(done) + wg.Wait() + + runtime.GOMAXPROCS(procs) +} diff --git a/go/src/internal/trace/testdata/testprog/wait-on-pipe.go b/go/src/internal/trace/testdata/testprog/wait-on-pipe.go new file mode 100644 index 0000000000000000000000000000000000000000..912f5dd3bcae62a97532039bc8140356b62dfc3d --- /dev/null +++ b/go/src/internal/trace/testdata/testprog/wait-on-pipe.go @@ -0,0 +1,66 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Tests a goroutine sitting blocked in a syscall for +// an entire generation. This is a regression test for +// #65196. + +//go:build ignore + +package main + +import ( + "log" + "os" + "runtime/trace" + "syscall" + "time" +) + +func main() { + // Create a pipe to block on. + var p [2]int + if err := syscall.Pipe(p[:]); err != nil { + log.Fatalf("failed to create pipe: %v", err) + } + rfd, wfd := p[0], p[1] + + // Create a goroutine that blocks on the pipe. + done := make(chan struct{}) + go func() { + var data [1]byte + _, err := syscall.Read(rfd, data[:]) + if err != nil { + log.Fatalf("failed to read from pipe: %v", err) + } + done <- struct{}{} + }() + + // Give the goroutine ample chance to block on the pipe. + time.Sleep(10 * time.Millisecond) + + // Start tracing. + if err := trace.Start(os.Stdout); err != nil { + log.Fatalf("failed to start tracing: %v", err) + } + + // This isn't enough to have a full generation pass by default, + // but it is generally enough in stress mode. + time.Sleep(100 * time.Millisecond) + + // Write to the pipe to unblock it. + if _, err := syscall.Write(wfd, []byte{10}); err != nil { + log.Fatalf("failed to write to pipe: %v", err) + } + + // Wait for the goroutine to unblock and start running. + // This is helpful to catch incorrect information written + // down for the syscall-blocked goroutine, since it'll start + // executing, and that execution information will be + // inconsistent. + <-done + + // Stop tracing. + trace.Stop() +} diff --git a/go/src/internal/trace/testdata/tests/go122-annotations-stress.test b/go/src/internal/trace/testdata/tests/go122-annotations-stress.test new file mode 100644 index 0000000000000000000000000000000000000000..8da8c0f318a56506de800b527ad8037d888c3e01 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-annotations-stress.test @@ -0,0 +1,1179 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=18446744073709551615 time=2753926854385 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=1986497 time=2753925247434 size=1430 +ProcStart dt=336 p=2 p_seq=1 +GoStart dt=191 g=19 g_seq=1 +HeapAlloc dt=389 heapalloc_value=1622016 +HeapAlloc dt=4453 heapalloc_value=1662976 +GoBlock dt=572 reason_string=12 stack=29 +ProcStop dt=26 +ProcStart dt=160734 p=2 p_seq=2 +ProcStop dt=21 +ProcStart dt=159292 p=0 p_seq=7 +GoStart dt=299 g=49 g_seq=1 +UserRegionBegin dt=183 task=8 name_string=33 stack=26 +UserLog dt=26 task=8 key_string=24 value_string=49 stack=27 +UserRegionEnd dt=8 task=8 name_string=33 stack=28 +GoDestroy dt=3 +GoStart dt=20 g=50 g_seq=1 +UserRegionBegin dt=40 task=8 name_string=35 stack=26 +UserLog dt=9 task=8 key_string=24 value_string=50 stack=27 +UserRegionEnd dt=2 task=8 name_string=35 stack=28 +GoDestroy dt=1 +ProcStop dt=18 +ProcStart dt=141801 p=4 p_seq=5 +ProcStop dt=18 +ProcStart dt=16860 p=4 p_seq=6 +GoUnblock dt=53 g=1 g_seq=5 stack=0 +GoUnblock dt=9 g=51 g_seq=3 stack=0 +GoStart dt=162 g=51 g_seq=4 +UserTaskEnd dt=35 task=9 stack=36 +UserRegionEnd dt=16 task=8 name_string=31 stack=28 +GoDestroy dt=2 +GoStart dt=20 g=1 g_seq=6 +UserTaskEnd dt=14 task=8 stack=54 +UserLog dt=26 task=3 key_string=24 value_string=51 stack=55 +UserTaskBegin dt=14 task=10 parent_task=3 name_string=26 stack=56 +UserLog dt=42 task=10 key_string=27 value_string=52 stack=57 +UserRegionBegin dt=12 task=10 name_string=29 stack=58 +GoCreate dt=36 new_g=35 new_stack=17 stack=59 +GoCreate dt=11 new_g=36 new_stack=17 stack=59 +GoCreate dt=18 new_g=37 new_stack=17 stack=59 +GoCreate dt=10 new_g=38 new_stack=17 stack=59 +GoCreate dt=6 new_g=39 new_stack=17 stack=59 +GoCreate dt=8 new_g=40 new_stack=17 stack=59 +UserRegionEnd dt=7 task=10 name_string=29 stack=60 +GoBlock dt=9 reason_string=19 stack=61 +GoStart dt=15 g=40 g_seq=1 +UserRegionBegin dt=110 task=10 name_string=53 stack=26 +UserLog dt=16 task=10 key_string=24 value_string=54 stack=27 +UserRegionEnd dt=2 task=10 name_string=53 stack=28 +GoDestroy dt=2 +GoStart dt=6 g=38 g_seq=1 +UserRegionBegin dt=31 task=10 name_string=30 stack=26 +UserLog dt=5 task=10 key_string=24 value_string=55 stack=27 +UserRegionEnd dt=2 task=10 name_string=30 stack=28 +GoDestroy dt=1 +GoStart dt=2 g=39 g_seq=1 +UserRegionBegin dt=23 task=10 name_string=56 stack=26 +UserLog dt=6 task=10 key_string=24 value_string=57 stack=27 +UserRegionEnd dt=1 task=10 name_string=56 stack=28 +GoDestroy dt=1 +GoStart dt=8 g=35 g_seq=1 +UserRegionBegin dt=17 task=10 name_string=33 stack=26 +UserLog dt=4 task=10 key_string=24 value_string=58 stack=27 +UserRegionEnd dt=2 task=10 name_string=33 stack=28 +GoDestroy dt=1 +GoStart dt=3 g=36 g_seq=1 +UserRegionBegin dt=19 task=10 name_string=35 stack=26 +UserLog dt=4 task=10 key_string=24 value_string=59 stack=27 +UserRegionEnd dt=2 task=10 name_string=35 stack=28 +GoDestroy dt=1 +ProcStop dt=11 +ProcStart dt=142205 p=0 p_seq=9 +ProcStop dt=19 +ProcStart dt=16811 p=0 p_seq=10 +GoUnblock dt=26 g=1 g_seq=7 stack=0 +GoStart dt=201 g=1 g_seq=8 +UserTaskEnd dt=24 task=10 stack=62 +UserLog dt=18 task=4 key_string=24 value_string=63 stack=63 +UserTaskBegin dt=11 task=12 parent_task=4 name_string=26 stack=64 +UserLog dt=21 task=12 key_string=27 value_string=64 stack=65 +UserRegionBegin dt=7 task=12 name_string=29 stack=66 +GoCreate dt=33 new_g=5 new_stack=17 stack=67 +GoCreate dt=12 new_g=6 new_stack=17 stack=67 +GoCreate dt=9 new_g=7 new_stack=17 stack=67 +GoCreate dt=8 new_g=8 new_stack=17 stack=67 +GoCreate dt=19 new_g=9 new_stack=17 stack=67 +UserRegionEnd dt=14 task=12 name_string=29 stack=68 +GoBlock dt=11 reason_string=19 stack=69 +GoStart dt=13 g=9 g_seq=1 +UserRegionBegin dt=70 task=12 name_string=56 stack=26 +UserLog dt=11 task=12 key_string=24 value_string=65 stack=27 +UserRegionEnd dt=3 task=12 name_string=56 stack=28 +GoDestroy dt=2 +GoStart dt=7 g=5 g_seq=1 +UserRegionBegin dt=24 task=12 name_string=33 stack=26 +UserLog dt=5 task=12 key_string=24 value_string=66 stack=27 +UserRegionEnd dt=2 task=12 name_string=33 stack=28 +GoDestroy dt=2 +GoStart dt=8 g=6 g_seq=1 +UserRegionBegin dt=15 task=12 name_string=35 stack=26 +UserLog dt=7 task=12 key_string=24 value_string=67 stack=27 +UserRegionEnd dt=2 task=12 name_string=35 stack=28 +GoDestroy dt=1 +GoStart dt=2 g=7 g_seq=1 +UserRegionBegin dt=13 task=12 name_string=31 stack=26 +UserLog dt=5 task=12 key_string=24 value_string=68 stack=27 +UserLog dt=6 task=12 key_string=24 value_string=69 stack=30 +UserTaskBegin dt=5 task=13 parent_task=12 name_string=26 stack=31 +UserLog dt=7 task=13 key_string=27 value_string=70 stack=32 +UserRegionBegin dt=4 task=13 name_string=29 stack=33 +UserRegionEnd dt=6 task=13 name_string=29 stack=34 +GoBlock dt=18 reason_string=19 stack=35 +GoStart dt=12 g=8 g_seq=1 +UserRegionBegin dt=22 task=12 name_string=30 stack=26 +UserLog dt=5 task=12 key_string=24 value_string=71 stack=27 +UserRegionEnd dt=2 task=12 name_string=30 stack=28 +GoDestroy dt=1 +ProcStop dt=20 +ProcStart dt=141838 p=4 p_seq=8 +ProcStop dt=16 +ProcStart dt=17652 p=4 p_seq=9 +GoUnblock dt=48 g=1 g_seq=9 stack=0 +GoUnblock dt=8 g=7 g_seq=2 stack=0 +GoStart dt=271 g=7 g_seq=3 +UserTaskEnd dt=25 task=13 stack=36 +UserRegionEnd dt=15 task=12 name_string=31 stack=28 +GoDestroy dt=4 +GoStart dt=19 g=1 g_seq=10 +UserTaskEnd dt=19 task=12 stack=70 +UserLog dt=21 task=0 key_string=24 value_string=72 stack=13 +UserTaskBegin dt=19 task=14 parent_task=0 name_string=26 stack=14 +UserLog dt=37 task=14 key_string=27 value_string=73 stack=15 +UserRegionBegin dt=6 task=14 name_string=29 stack=16 +GoCreate dt=28 new_g=41 new_stack=17 stack=18 +GoCreate dt=14 new_g=42 new_stack=17 stack=18 +GoCreate dt=12 new_g=43 new_stack=17 stack=18 +GoCreate dt=10 new_g=44 new_stack=17 stack=18 +UserRegionEnd dt=5 task=14 name_string=29 stack=19 +GoBlock dt=9 reason_string=19 stack=20 +GoStart dt=16 g=44 g_seq=1 +UserRegionBegin dt=107 task=14 name_string=30 stack=26 +UserLog dt=16 task=14 key_string=24 value_string=74 stack=27 +UserRegionEnd dt=3 task=14 name_string=30 stack=28 +GoDestroy dt=2 +GoStart dt=7 g=41 g_seq=1 +UserRegionBegin dt=30 task=14 name_string=33 stack=26 +UserLog dt=7 task=14 key_string=24 value_string=75 stack=27 +UserRegionEnd dt=2 task=14 name_string=33 stack=28 +GoDestroy dt=2 +GoStart dt=7 g=42 g_seq=1 +UserRegionBegin dt=27 task=14 name_string=35 stack=26 +UserLog dt=7 task=14 key_string=24 value_string=76 stack=27 +UserRegionEnd dt=2 task=14 name_string=35 stack=28 +GoDestroy dt=2 +ProcStop dt=28 +ProcStart dt=141923 p=0 p_seq=12 +ProcStop dt=19 +ProcStart dt=16780 p=0 p_seq=13 +GoUnblock dt=22 g=43 g_seq=2 stack=0 +GoStart dt=162 g=43 g_seq=3 +UserTaskEnd dt=16 task=15 stack=36 +UserRegionEnd dt=12 task=14 name_string=31 stack=28 +GoDestroy dt=2 +ProcStop dt=8 +ProcStart dt=1532 p=2 p_seq=9 +ProcStop dt=12 +ProcStart dt=141906 p=4 p_seq=11 +ProcStop dt=16 +ProcStart dt=16784 p=4 p_seq=12 +GoUnblock dt=20 g=1 g_seq=13 stack=0 +GoStart dt=191 g=1 g_seq=14 +UserTaskEnd dt=15 task=16 stack=45 +UserLog dt=17 task=2 key_string=24 value_string=84 stack=46 +UserTaskBegin dt=8 task=17 parent_task=2 name_string=26 stack=47 +UserLog dt=20 task=17 key_string=27 value_string=85 stack=48 +UserRegionBegin dt=6 task=17 name_string=29 stack=49 +GoCreate dt=28 new_g=45 new_stack=17 stack=50 +GoCreate dt=9 new_g=46 new_stack=17 stack=50 +GoCreate dt=10 new_g=47 new_stack=17 stack=50 +UserRegionEnd dt=5 task=17 name_string=29 stack=51 +GoBlock dt=6 reason_string=19 stack=52 +GoStart dt=10 g=47 g_seq=1 +UserRegionBegin dt=69 task=17 name_string=31 stack=26 +UserLog dt=11 task=17 key_string=24 value_string=86 stack=27 +UserLog dt=7 task=17 key_string=24 value_string=87 stack=30 +UserTaskBegin dt=5 task=18 parent_task=17 name_string=26 stack=31 +UserLog dt=7 task=18 key_string=27 value_string=88 stack=32 +UserRegionBegin dt=5 task=18 name_string=29 stack=33 +UserRegionEnd dt=4 task=18 name_string=29 stack=34 +HeapAlloc dt=35 heapalloc_value=1818624 +GoBlock dt=14 reason_string=19 stack=35 +HeapAlloc dt=11 heapalloc_value=1826816 +GoStart dt=10 g=45 g_seq=1 +UserRegionBegin dt=29 task=17 name_string=33 stack=26 +UserLog dt=9 task=17 key_string=24 value_string=89 stack=27 +UserRegionEnd dt=3 task=17 name_string=33 stack=28 +GoDestroy dt=1 +GoStart dt=5 g=46 g_seq=1 +UserRegionBegin dt=15 task=17 name_string=35 stack=26 +UserLog dt=8 task=17 key_string=24 value_string=90 stack=27 +UserRegionEnd dt=2 task=17 name_string=35 stack=28 +GoDestroy dt=1 +ProcStop dt=3 +ProcStart dt=141981 p=0 p_seq=16 +ProcStop dt=19 +ProcStart dt=17153 p=0 p_seq=17 +GoUnblock dt=44 g=1 g_seq=15 stack=0 +GoUnblock dt=11 g=47 g_seq=2 stack=0 +GoStart dt=215 g=47 g_seq=3 +UserTaskEnd dt=22 task=18 stack=36 +UserRegionEnd dt=9 task=17 name_string=31 stack=28 +GoDestroy dt=3 +GoStart dt=19 g=1 g_seq=16 +UserTaskEnd dt=13 task=17 stack=54 +UserLog dt=18 task=3 key_string=24 value_string=91 stack=55 +UserTaskBegin dt=7 task=19 parent_task=3 name_string=26 stack=56 +UserLog dt=27 task=19 key_string=27 value_string=92 stack=57 +UserRegionBegin dt=8 task=19 name_string=29 stack=58 +GoCreate dt=30 new_g=10 new_stack=17 stack=59 +GoCreate dt=9 new_g=11 new_stack=17 stack=59 +GoCreate dt=11 new_g=12 new_stack=17 stack=59 +GoCreate dt=7 new_g=13 new_stack=17 stack=59 +GoCreate dt=7 new_g=14 new_stack=17 stack=59 +GoCreate dt=9 new_g=15 new_stack=17 stack=59 +UserRegionEnd dt=5 task=19 name_string=29 stack=60 +GoBlock dt=7 reason_string=19 stack=61 +GoStart dt=17 g=15 g_seq=1 +UserRegionBegin dt=61 task=19 name_string=53 stack=26 +UserLog dt=10 task=19 key_string=24 value_string=93 stack=27 +UserRegionEnd dt=3 task=19 name_string=53 stack=28 +GoDestroy dt=1 +GoStart dt=4 g=10 g_seq=1 +UserRegionBegin dt=26 task=19 name_string=33 stack=26 +UserLog dt=7 task=19 key_string=24 value_string=94 stack=27 +UserRegionEnd dt=2 task=19 name_string=33 stack=28 +GoDestroy dt=1 +GoStart dt=4 g=11 g_seq=1 +UserRegionBegin dt=20 task=19 name_string=35 stack=26 +UserLog dt=5 task=19 key_string=24 value_string=95 stack=27 +UserRegionEnd dt=2 task=19 name_string=35 stack=28 +GoDestroy dt=1 +GoStart dt=7 g=12 g_seq=1 +UserRegionBegin dt=14 task=19 name_string=31 stack=26 +UserLog dt=4 task=19 key_string=24 value_string=96 stack=27 +UserLog dt=4 task=19 key_string=24 value_string=97 stack=30 +UserTaskBegin dt=7 task=20 parent_task=19 name_string=26 stack=31 +UserLog dt=5 task=20 key_string=27 value_string=98 stack=32 +UserRegionBegin dt=4 task=20 name_string=29 stack=33 +UserRegionEnd dt=5 task=20 name_string=29 stack=34 +GoBlock dt=9 reason_string=19 stack=35 +GoStart dt=9 g=14 g_seq=1 +UserRegionBegin dt=28 task=19 name_string=56 stack=26 +UserLog dt=7 task=19 key_string=24 value_string=99 stack=27 +UserRegionEnd dt=2 task=19 name_string=56 stack=28 +GoDestroy dt=2 +ProcStop dt=17 +ProcStart dt=141933 p=2 p_seq=11 +ProcStop dt=13 +ProcStart dt=16744 p=2 p_seq=12 +GoUnblock dt=29 g=1 g_seq=17 stack=0 +GoUnblock dt=7 g=12 g_seq=2 stack=0 +GoStart dt=172 g=12 g_seq=3 +UserTaskEnd dt=15 task=20 stack=36 +UserRegionEnd dt=8 task=19 name_string=31 stack=28 +GoDestroy dt=2 +GoStart dt=11 g=1 g_seq=18 +UserTaskEnd dt=14 task=19 stack=62 +UserLog dt=16 task=4 key_string=24 value_string=101 stack=63 +UserTaskBegin dt=6 task=21 parent_task=4 name_string=26 stack=64 +UserLog dt=25 task=21 key_string=27 value_string=102 stack=65 +UserRegionBegin dt=7 task=21 name_string=29 stack=66 +GoCreate dt=23 new_g=54 new_stack=17 stack=67 +GoCreate dt=8 new_g=55 new_stack=17 stack=67 +GoCreate dt=17 new_g=56 new_stack=17 stack=67 +GoCreate dt=8 new_g=57 new_stack=17 stack=67 +GoCreate dt=7 new_g=58 new_stack=17 stack=67 +UserRegionEnd dt=4 task=21 name_string=29 stack=68 +GoBlock dt=9 reason_string=19 stack=69 +GoStart dt=7 g=58 g_seq=1 +UserRegionBegin dt=46 task=21 name_string=56 stack=26 +UserLog dt=8 task=21 key_string=24 value_string=103 stack=27 +UserRegionEnd dt=4 task=21 name_string=56 stack=28 +GoDestroy dt=1 +GoStart dt=3 g=54 g_seq=1 +UserRegionBegin dt=19 task=21 name_string=33 stack=26 +UserLog dt=7 task=21 key_string=24 value_string=104 stack=27 +UserRegionEnd dt=2 task=21 name_string=33 stack=28 +GoDestroy dt=1 +GoStart dt=2 g=55 g_seq=1 +UserRegionBegin dt=17 task=21 name_string=35 stack=26 +UserLog dt=4 task=21 key_string=24 value_string=105 stack=27 +UserRegionEnd dt=2 task=21 name_string=35 stack=28 +GoDestroy dt=1 +GoStart dt=5 g=56 g_seq=1 +UserRegionBegin dt=16 task=21 name_string=31 stack=26 +UserLog dt=4 task=21 key_string=24 value_string=106 stack=27 +UserLog dt=3 task=21 key_string=24 value_string=107 stack=30 +UserTaskBegin dt=4 task=22 parent_task=21 name_string=26 stack=31 +UserLog dt=6 task=22 key_string=27 value_string=108 stack=32 +UserRegionBegin dt=4 task=22 name_string=29 stack=33 +UserRegionEnd dt=7 task=22 name_string=29 stack=34 +GoBlock dt=14 reason_string=19 stack=35 +GoStart dt=3 g=57 g_seq=1 +UserRegionBegin dt=22 task=21 name_string=30 stack=26 +UserLog dt=6 task=21 key_string=24 value_string=109 stack=27 +UserRegionEnd dt=2 task=21 name_string=30 stack=28 +GoDestroy dt=2 +ProcStop dt=10 +ProcStart dt=128031 p=4 p_seq=15 +ProcStop dt=16 +ProcStart dt=33758 p=2 p_seq=15 +ProcStop dt=18 +EventBatch gen=1 m=1986496 time=2753925246280 size=267 +ProcStart dt=549 p=0 p_seq=1 +GoStart dt=211 g=18 g_seq=1 +GoBlock dt=3533 reason_string=12 stack=21 +GoStart dt=41 g=21 g_seq=1 +GoBlock dt=150 reason_string=10 stack=22 +GoStart dt=93 g=20 g_seq=1 +GoSyscallBegin dt=51 p_seq=2 stack=23 +GoSyscallEnd dt=400 +GoBlock dt=582 reason_string=15 stack=25 +GoStart dt=26 g=23 g_seq=1 +HeapAlloc dt=50 heapalloc_value=1646592 +UserRegionBegin dt=2921 task=5 name_string=31 stack=26 +UserLog dt=28 task=5 key_string=24 value_string=37 stack=27 +UserLog dt=13 task=5 key_string=24 value_string=38 stack=30 +UserTaskBegin dt=15 task=6 parent_task=5 name_string=26 stack=31 +HeapAlloc dt=26 heapalloc_value=1687552 +UserLog dt=14 task=6 key_string=27 value_string=39 stack=32 +UserRegionBegin dt=9 task=6 name_string=29 stack=33 +UserRegionEnd dt=6 task=6 name_string=29 stack=34 +GoBlock dt=15 reason_string=19 stack=35 +ProcStop dt=30 +ProcStart dt=156949 p=4 p_seq=2 +GoUnblock dt=46 g=1 g_seq=1 stack=0 +GoStart dt=253 g=1 g_seq=2 +UserTaskEnd dt=27 task=5 stack=37 +UserLog dt=23 task=1 key_string=24 value_string=40 stack=38 +UserTaskBegin dt=14 task=7 parent_task=1 name_string=26 stack=39 +HeapAlloc dt=596 heapalloc_value=1695744 +HeapAlloc dt=18 heapalloc_value=1703936 +UserLog dt=17 task=7 key_string=27 value_string=41 stack=40 +UserRegionBegin dt=14 task=7 name_string=29 stack=41 +HeapAlloc dt=10 heapalloc_value=1712128 +HeapAlloc dt=17 heapalloc_value=1720320 +GoCreate dt=44 new_g=33 new_stack=17 stack=42 +GoCreate dt=175 new_g=34 new_stack=17 stack=42 +UserRegionEnd dt=50 task=7 name_string=29 stack=43 +GoBlock dt=9 reason_string=19 stack=44 +HeapAlloc dt=16 heapalloc_value=1728512 +GoStart dt=239 g=34 g_seq=1 +HeapAlloc dt=21 heapalloc_value=1736704 +UserRegionBegin dt=92 task=7 name_string=35 stack=26 +UserLog dt=15 task=7 key_string=24 value_string=42 stack=27 +UserRegionEnd dt=4 task=7 name_string=35 stack=28 +GoDestroy dt=2 +ProcStop dt=21 +ProcStart dt=800974 p=4 p_seq=10 +ProcStop dt=39 +ProcStart dt=158775 p=0 p_seq=15 +ProcStop dt=24 +ProcStart dt=159722 p=4 p_seq=13 +GoStart dt=254 g=13 g_seq=1 +UserRegionBegin dt=239 task=19 name_string=30 stack=26 +UserLog dt=23 task=19 key_string=24 value_string=100 stack=27 +UserRegionEnd dt=6 task=19 name_string=30 stack=28 +GoDestroy dt=7 +ProcStop dt=22 +EventBatch gen=1 m=1986495 time=2753925251756 size=320 +ProcStart dt=705 p=4 p_seq=1 +ProcStop dt=1279 +ProcStart dt=158975 p=0 p_seq=5 +ProcStop dt=23 +ProcStart dt=792 p=0 p_seq=6 +GoStart dt=187 g=33 g_seq=1 +UserRegionBegin dt=244 task=7 name_string=33 stack=26 +UserLog dt=32 task=7 key_string=24 value_string=43 stack=27 +UserRegionEnd dt=7 task=7 name_string=33 stack=28 +GoDestroy dt=5 +ProcStop dt=24 +ProcStart dt=160255 p=4 p_seq=4 +ProcStop dt=27 +ProcStart dt=159067 p=2 p_seq=5 +GoStart dt=222 g=37 g_seq=1 +UserRegionBegin dt=114 task=10 name_string=31 stack=26 +UserLog dt=16 task=10 key_string=24 value_string=60 stack=27 +UserLog dt=8 task=10 key_string=24 value_string=61 stack=30 +UserTaskBegin dt=8 task=11 parent_task=10 name_string=26 stack=31 +UserLog dt=19 task=11 key_string=27 value_string=62 stack=32 +UserRegionBegin dt=6 task=11 name_string=29 stack=33 +UserRegionEnd dt=7 task=11 name_string=29 stack=34 +GoBlock dt=15 reason_string=19 stack=35 +ProcStop dt=11 +ProcStart dt=160101 p=4 p_seq=7 +ProcStop dt=21 +ProcStart dt=159647 p=2 p_seq=7 +GoStart dt=277 g=43 g_seq=1 +UserRegionBegin dt=126 task=14 name_string=31 stack=26 +UserLog dt=21 task=14 key_string=24 value_string=77 stack=27 +UserLog dt=9 task=14 key_string=24 value_string=78 stack=30 +UserTaskBegin dt=8 task=15 parent_task=14 name_string=26 stack=31 +UserLog dt=17 task=15 key_string=27 value_string=79 stack=32 +UserRegionBegin dt=6 task=15 name_string=29 stack=33 +UserRegionEnd dt=8 task=15 name_string=29 stack=34 +GoBlock dt=23 reason_string=19 stack=35 +ProcStop dt=17 +ProcStart dt=159706 p=0 p_seq=14 +GoStart dt=229 g=52 g_seq=1 +UserRegionBegin dt=103 task=16 name_string=33 stack=26 +UserLog dt=20 task=16 key_string=24 value_string=83 stack=27 +UserRegionEnd dt=4 task=16 name_string=33 stack=28 +GoDestroy dt=3 +ProcStop dt=17 +ProcStart dt=319699 p=2 p_seq=10 +ProcStop dt=20 +ProcStart dt=158728 p=4 p_seq=14 +ProcStop dt=17 +ProcStart dt=110606 p=2 p_seq=13 +ProcStop dt=10 +ProcStart dt=16732 p=2 p_seq=14 +GoUnblock dt=45 g=18 g_seq=2 stack=0 +GoStart dt=184 g=18 g_seq=3 +GoBlock dt=114 reason_string=12 stack=21 +ProcStop dt=8 +ProcStart dt=16779 p=4 p_seq=16 +ProcStop dt=11 +ProcStart dt=16790 p=4 p_seq=17 +GoUnblock dt=23 g=1 g_seq=19 stack=0 +GoUnblock dt=8 g=56 g_seq=2 stack=0 +GoStart dt=142 g=56 g_seq=3 +UserTaskEnd dt=14 task=22 stack=36 +UserRegionEnd dt=8 task=21 name_string=31 stack=28 +GoDestroy dt=5 +GoStart dt=18 g=1 g_seq=20 +UserTaskEnd dt=17 task=21 stack=70 +UserTaskEnd dt=12 task=4 stack=71 +HeapAlloc dt=802 heapalloc_value=1835008 +HeapAlloc dt=41 heapalloc_value=1843200 +HeapAlloc dt=13 heapalloc_value=1851392 +EventBatch gen=1 m=1986494 time=2753925248778 size=47 +ProcStart dt=390 p=3 p_seq=1 +GoStart dt=1718 g=22 g_seq=1 +HeapAlloc dt=1807 heapalloc_value=1654784 +HeapAlloc dt=406 heapalloc_value=1671168 +HeapAlloc dt=15 heapalloc_value=1679360 +UserRegionBegin dt=49 task=5 name_string=35 stack=26 +UserLog dt=30 task=5 key_string=24 value_string=36 stack=27 +UserRegionEnd dt=5 task=5 name_string=35 stack=28 +GoDestroy dt=5 +ProcStop dt=42 +EventBatch gen=1 m=1986492 time=2753925244400 size=582 +ProcStatus dt=67 p=1 pstatus=1 +GoStatus dt=4 g=1 m=1986492 gstatus=2 +ProcsChange dt=220 procs_value=8 stack=1 +STWBegin dt=127 kind_string=21 stack=2 +HeapGoal dt=3 heapgoal_value=4194304 +ProcStatus dt=2 p=0 pstatus=2 +ProcStatus dt=2 p=2 pstatus=2 +ProcStatus dt=1 p=3 pstatus=2 +ProcStatus dt=1 p=4 pstatus=2 +ProcStatus dt=1 p=5 pstatus=2 +ProcStatus dt=1 p=6 pstatus=2 +ProcStatus dt=1 p=7 pstatus=2 +ProcsChange dt=353 procs_value=8 stack=3 +STWEnd dt=277 +HeapAlloc dt=243 heapalloc_value=1605632 +HeapAlloc dt=24 heapalloc_value=1613824 +GoCreate dt=209 new_g=18 new_stack=4 stack=5 +GoCreate dt=561 new_g=19 new_stack=6 stack=7 +GoCreate dt=25 new_g=20 new_stack=8 stack=9 +UserTaskEnd dt=309 task=2 stack=10 +UserTaskBegin dt=26 task=3 parent_task=1 name_string=22 stack=11 +UserTaskBegin dt=918 task=4 parent_task=0 name_string=23 stack=12 +UserLog dt=461 task=0 key_string=24 value_string=25 stack=13 +UserTaskBegin dt=420 task=5 parent_task=0 name_string=26 stack=14 +UserLog dt=673 task=5 key_string=27 value_string=28 stack=15 +UserRegionBegin dt=15 task=5 name_string=29 stack=16 +HeapAlloc dt=51 heapalloc_value=1630208 +GoCreate dt=24 new_g=21 new_stack=17 stack=18 +GoCreate dt=17 new_g=22 new_stack=17 stack=18 +GoCreate dt=10 new_g=23 new_stack=17 stack=18 +GoCreate dt=9 new_g=24 new_stack=17 stack=18 +UserRegionEnd dt=549 task=5 name_string=29 stack=19 +GoBlock dt=14 reason_string=19 stack=20 +GoStart dt=378 g=24 g_seq=1 +HeapAlloc dt=65 heapalloc_value=1638400 +GoUnblock dt=559 g=21 g_seq=2 stack=24 +UserRegionBegin dt=1498 task=5 name_string=30 stack=26 +UserLog dt=35 task=5 key_string=24 value_string=32 stack=27 +UserRegionEnd dt=8 task=5 name_string=30 stack=28 +GoDestroy dt=5 +GoStart dt=24 g=21 g_seq=3 +UserRegionBegin dt=60 task=5 name_string=33 stack=26 +UserLog dt=7 task=5 key_string=24 value_string=34 stack=27 +UserRegionEnd dt=2 task=5 name_string=33 stack=28 +GoDestroy dt=2 +ProcStop dt=34 +ProcStart dt=141874 p=0 p_seq=3 +ProcStop dt=21 +ProcStart dt=16770 p=0 p_seq=4 +GoUnblock dt=29 g=23 g_seq=2 stack=0 +GoStart dt=176 g=23 g_seq=3 +UserTaskEnd dt=19 task=6 stack=36 +UserRegionEnd dt=14 task=5 name_string=31 stack=28 +GoDestroy dt=2 +ProcStop dt=12 +ProcStart dt=2251 p=4 p_seq=3 +ProcStop dt=22 +ProcStart dt=141952 p=2 p_seq=3 +ProcStop dt=27 +ProcStart dt=16789 p=2 p_seq=4 +GoUnblock dt=35 g=1 g_seq=3 stack=0 +GoStart dt=214 g=1 g_seq=4 +UserTaskEnd dt=26 task=7 stack=45 +UserLog dt=27 task=2 key_string=24 value_string=44 stack=46 +UserTaskBegin dt=10 task=8 parent_task=2 name_string=26 stack=47 +HeapAlloc dt=52 heapalloc_value=1744896 +HeapAlloc dt=22 heapalloc_value=1753088 +UserLog dt=13 task=8 key_string=27 value_string=45 stack=48 +UserRegionBegin dt=11 task=8 name_string=29 stack=49 +HeapAlloc dt=7 heapalloc_value=1761280 +HeapAlloc dt=18 heapalloc_value=1769472 +GoCreate dt=52 new_g=49 new_stack=17 stack=50 +GoCreate dt=12 new_g=50 new_stack=17 stack=50 +HeapAlloc dt=11 heapalloc_value=1777664 +GoCreate dt=9 new_g=51 new_stack=17 stack=50 +UserRegionEnd dt=9 task=8 name_string=29 stack=51 +GoBlock dt=11 reason_string=19 stack=52 +HeapAlloc dt=12 heapalloc_value=1785856 +GoStart dt=14 g=51 g_seq=1 +HeapAlloc dt=18 heapalloc_value=1794048 +UserRegionBegin dt=95 task=8 name_string=31 stack=26 +UserLog dt=22 task=8 key_string=24 value_string=46 stack=27 +UserLog dt=8 task=8 key_string=24 value_string=47 stack=30 +UserTaskBegin dt=5 task=9 parent_task=8 name_string=26 stack=31 +UserLog dt=7 task=9 key_string=27 value_string=48 stack=32 +UserRegionBegin dt=4 task=9 name_string=29 stack=33 +UserRegionEnd dt=7 task=9 name_string=29 stack=34 +HeapAlloc dt=11 heapalloc_value=1802240 +GoStop dt=674 reason_string=16 stack=53 +GoStart dt=12 g=51 g_seq=2 +GoBlock dt=8 reason_string=19 stack=35 +HeapAlloc dt=16 heapalloc_value=1810432 +ProcStop dt=8 +ProcStart dt=159907 p=0 p_seq=8 +ProcStop dt=25 +ProcStart dt=159186 p=2 p_seq=6 +GoUnblock dt=22 g=37 g_seq=2 stack=0 +GoStart dt=217 g=37 g_seq=3 +UserTaskEnd dt=19 task=11 stack=36 +UserRegionEnd dt=15 task=10 name_string=31 stack=28 +GoDestroy dt=5 +ProcStop dt=16 +ProcStart dt=160988 p=0 p_seq=11 +ProcStop dt=29 +ProcStart dt=158554 p=2 p_seq=8 +GoUnblock dt=38 g=1 g_seq=11 stack=0 +GoStart dt=240 g=1 g_seq=12 +UserTaskEnd dt=25 task=14 stack=37 +UserLog dt=23 task=1 key_string=24 value_string=80 stack=38 +UserTaskBegin dt=11 task=16 parent_task=1 name_string=26 stack=39 +UserLog dt=36 task=16 key_string=27 value_string=81 stack=40 +UserRegionBegin dt=13 task=16 name_string=29 stack=41 +GoCreate dt=39 new_g=52 new_stack=17 stack=42 +GoCreate dt=23 new_g=53 new_stack=17 stack=42 +UserRegionEnd dt=11 task=16 name_string=29 stack=43 +GoBlock dt=9 reason_string=19 stack=44 +GoStart dt=244 g=53 g_seq=1 +UserRegionBegin dt=101 task=16 name_string=35 stack=26 +UserLog dt=17 task=16 key_string=24 value_string=82 stack=27 +UserRegionEnd dt=4 task=16 name_string=35 stack=28 +GoDestroy dt=3 +ProcStop dt=28 +EventBatch gen=1 m=18446744073709551615 time=2753926855140 size=56 +GoStatus dt=74 g=2 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=3 m=18446744073709551615 gstatus=4 +GoStatus dt=1 g=4 m=18446744073709551615 gstatus=4 +GoStatus dt=1 g=17 m=18446744073709551615 gstatus=4 +EventBatch gen=1 m=18446744073709551615 time=2753926855560 size=1759 +Stacks +Stack id=45 nframes=3 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4803566 func=114 file=113 line=44 +Stack id=22 nframes=7 + pc=4633935 func=115 file=116 line=90 + pc=4633896 func=117 file=118 line=223 + pc=4633765 func=119 file=118 line=216 + pc=4633083 func=120 file=118 line=131 + pc=4764601 func=121 file=122 line=152 + pc=4765335 func=123 file=122 line=238 + pc=4804612 func=124 file=113 line=70 +Stack id=9 nframes=2 + pc=4802543 func=125 file=126 line=128 + pc=4803332 func=114 file=113 line=30 +Stack id=71 nframes=2 + pc=4803671 func=110 file=111 line=80 + pc=4803666 func=114 file=113 line=51 +Stack id=10 nframes=2 + pc=4803415 func=110 file=111 line=80 + pc=4803410 func=114 file=113 line=33 +Stack id=18 nframes=4 + pc=4804196 func=127 file=113 line=69 + pc=4802140 func=128 file=111 line=141 + pc=4804022 func=112 file=113 line=67 + pc=4803543 func=114 file=113 line=43 +Stack id=37 nframes=3 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4803543 func=114 file=113 line=43 +Stack id=31 nframes=4 + pc=4803865 func=112 file=113 line=61 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=55 nframes=2 + pc=4803832 func=112 file=113 line=58 + pc=4803609 func=114 file=113 line=46 +Stack id=47 nframes=2 + pc=4803865 func=112 file=113 line=61 + pc=4803589 func=114 file=113 line=45 +Stack id=38 nframes=2 + pc=4803832 func=112 file=113 line=58 + pc=4803566 func=114 file=113 line=44 +Stack id=56 nframes=2 + pc=4803865 func=112 file=113 line=61 + pc=4803609 func=114 file=113 line=46 +Stack id=33 nframes=4 + pc=4804022 func=112 file=113 line=67 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=44 nframes=3 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4803566 func=114 file=113 line=44 +Stack id=3 nframes=4 + pc=4421707 func=132 file=133 line=1382 + pc=4533555 func=134 file=135 line=255 + pc=4802469 func=125 file=126 line=125 + pc=4803332 func=114 file=113 line=30 +Stack id=6 nframes=1 + pc=4539520 func=136 file=135 line=868 +Stack id=58 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803609 func=114 file=113 line=46 +Stack id=64 nframes=2 + pc=4803865 func=112 file=113 line=61 + pc=4803629 func=114 file=113 line=47 +Stack id=62 nframes=3 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4803609 func=114 file=113 line=46 +Stack id=34 nframes=4 + pc=4804022 func=112 file=113 line=67 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=30 nframes=4 + pc=4803832 func=112 file=113 line=58 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=32 nframes=4 + pc=4803943 func=112 file=113 line=64 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=26 nframes=1 + pc=4804691 func=124 file=113 line=70 +Stack id=46 nframes=2 + pc=4803832 func=112 file=113 line=58 + pc=4803589 func=114 file=113 line=45 +Stack id=50 nframes=4 + pc=4804196 func=127 file=113 line=69 + pc=4802140 func=128 file=111 line=141 + pc=4804022 func=112 file=113 line=67 + pc=4803589 func=114 file=113 line=45 +Stack id=59 nframes=4 + pc=4804196 func=127 file=113 line=69 + pc=4802140 func=128 file=111 line=141 + pc=4804022 func=112 file=113 line=67 + pc=4803609 func=114 file=113 line=46 +Stack id=7 nframes=4 + pc=4539492 func=137 file=135 line=868 + pc=4533572 func=134 file=135 line=258 + pc=4802469 func=125 file=126 line=125 + pc=4803332 func=114 file=113 line=30 +Stack id=17 nframes=1 + pc=4804512 func=124 file=113 line=69 +Stack id=57 nframes=2 + pc=4803943 func=112 file=113 line=64 + pc=4803609 func=114 file=113 line=46 +Stack id=41 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803566 func=114 file=113 line=44 +Stack id=63 nframes=2 + pc=4803832 func=112 file=113 line=58 + pc=4803629 func=114 file=113 line=47 +Stack id=60 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803609 func=114 file=113 line=46 +Stack id=5 nframes=4 + pc=4542549 func=138 file=139 line=42 + pc=4533560 func=134 file=135 line=257 + pc=4802469 func=125 file=126 line=125 + pc=4803332 func=114 file=113 line=30 +Stack id=40 nframes=2 + pc=4803943 func=112 file=113 line=64 + pc=4803566 func=114 file=113 line=44 +Stack id=21 nframes=3 + pc=4217905 func=140 file=141 line=442 + pc=4539946 func=142 file=135 line=928 + pc=4542714 func=143 file=139 line=54 +Stack id=2 nframes=3 + pc=4533284 func=134 file=135 line=238 + pc=4802469 func=125 file=126 line=125 + pc=4803332 func=114 file=113 line=30 +Stack id=53 nframes=6 + pc=4247492 func=144 file=145 line=1374 + pc=4599676 func=130 file=131 line=186 + pc=4804036 func=112 file=113 line=83 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=20 nframes=3 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4803543 func=114 file=113 line=43 +Stack id=70 nframes=3 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4803629 func=114 file=113 line=47 +Stack id=15 nframes=2 + pc=4803943 func=112 file=113 line=64 + pc=4803543 func=114 file=113 line=43 +Stack id=65 nframes=2 + pc=4803943 func=112 file=113 line=64 + pc=4803629 func=114 file=113 line=47 +Stack id=28 nframes=1 + pc=4804691 func=124 file=113 line=70 +Stack id=48 nframes=2 + pc=4803943 func=112 file=113 line=64 + pc=4803589 func=114 file=113 line=45 +Stack id=61 nframes=3 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4803609 func=114 file=113 line=46 +Stack id=13 nframes=2 + pc=4803832 func=112 file=113 line=58 + pc=4803543 func=114 file=113 line=43 +Stack id=29 nframes=3 + pc=4217905 func=140 file=141 line=442 + pc=4539946 func=142 file=135 line=928 + pc=4539559 func=136 file=135 line=871 +Stack id=51 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803589 func=114 file=113 line=45 +Stack id=42 nframes=4 + pc=4804196 func=127 file=113 line=69 + pc=4802140 func=128 file=111 line=141 + pc=4804022 func=112 file=113 line=67 + pc=4803566 func=114 file=113 line=44 +Stack id=14 nframes=2 + pc=4803865 func=112 file=113 line=61 + pc=4803543 func=114 file=113 line=43 +Stack id=39 nframes=2 + pc=4803865 func=112 file=113 line=61 + pc=4803566 func=114 file=113 line=44 +Stack id=49 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803589 func=114 file=113 line=45 +Stack id=52 nframes=3 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4803589 func=114 file=113 line=45 +Stack id=24 nframes=7 + pc=4634510 func=146 file=116 line=223 + pc=4634311 func=117 file=118 line=240 + pc=4633765 func=119 file=118 line=216 + pc=4633083 func=120 file=118 line=131 + pc=4764601 func=121 file=122 line=152 + pc=4765335 func=123 file=122 line=238 + pc=4804612 func=124 file=113 line=70 +Stack id=43 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803566 func=114 file=113 line=44 +Stack id=19 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803543 func=114 file=113 line=43 +Stack id=69 nframes=3 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4803629 func=114 file=113 line=47 +Stack id=16 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803543 func=114 file=113 line=43 +Stack id=54 nframes=3 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4803589 func=114 file=113 line=45 +Stack id=35 nframes=5 + pc=4599892 func=130 file=131 line=195 + pc=4804036 func=112 file=113 line=83 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=27 nframes=3 + pc=4804862 func=129 file=113 line=71 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=4 nframes=1 + pc=4542656 func=143 file=139 line=42 +Stack id=8 nframes=1 + pc=4802720 func=147 file=126 line=128 +Stack id=66 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803629 func=114 file=113 line=47 +Stack id=1 nframes=4 + pc=4548715 func=148 file=149 line=255 + pc=4533263 func=134 file=135 line=237 + pc=4802469 func=125 file=126 line=125 + pc=4803332 func=114 file=113 line=30 +Stack id=67 nframes=4 + pc=4804196 func=127 file=113 line=69 + pc=4802140 func=128 file=111 line=141 + pc=4804022 func=112 file=113 line=67 + pc=4803629 func=114 file=113 line=47 +Stack id=23 nframes=7 + pc=4641050 func=150 file=151 line=964 + pc=4751591 func=152 file=153 line=209 + pc=4751583 func=154 file=155 line=736 + pc=4751136 func=156 file=155 line=380 + pc=4753008 func=157 file=158 line=46 + pc=4753000 func=159 file=160 line=183 + pc=4802778 func=147 file=126 line=134 +Stack id=11 nframes=1 + pc=4803445 func=114 file=113 line=36 +Stack id=68 nframes=2 + pc=4804022 func=112 file=113 line=67 + pc=4803629 func=114 file=113 line=47 +Stack id=36 nframes=5 + pc=4804964 func=110 file=111 line=80 + pc=4804052 func=112 file=113 line=84 + pc=4804890 func=129 file=113 line=73 + pc=4802140 func=128 file=111 line=141 + pc=4804691 func=124 file=113 line=70 +Stack id=12 nframes=1 + pc=4803492 func=114 file=113 line=39 +Stack id=25 nframes=1 + pc=4802788 func=147 file=126 line=130 +EventBatch gen=1 m=18446744073709551615 time=2753925243266 size=3466 +Strings +String id=1 + data="Not worker" +String id=2 + data="GC (dedicated)" +String id=3 + data="GC (fractional)" +String id=4 + data="GC (idle)" +String id=5 + data="unspecified" +String id=6 + data="forever" +String id=7 + data="network" +String id=8 + data="select" +String id=9 + data="sync.(*Cond).Wait" +String id=10 + data="sync" +String id=11 + data="chan send" +String id=12 + data="chan receive" +String id=13 + data="GC mark assist wait for work" +String id=14 + data="GC background sweeper wait" +String id=15 + data="system goroutine wait" +String id=16 + data="preempted" +String id=17 + data="wait for debug call" +String id=18 + data="wait until GC ends" +String id=19 + data="sleep" +String id=20 + data="runtime.Gosched" +String id=21 + data="start trace" +String id=22 + data="type2" +String id=23 + data="type3" +String id=24 + data="log" +String id=25 + data="before do" +String id=26 + data="do" +String id=27 + data="log2" +String id=28 + data="do" +String id=29 + data="fanout" +String id=30 + data="region3" +String id=31 + data="region2" +String id=32 + data="fanout region3" +String id=33 + data="region0" +String id=34 + data="fanout region0" +String id=35 + data="region1" +String id=36 + data="fanout region1" +String id=37 + data="fanout region2" +String id=38 + data="before do" +String id=39 + data="do" +String id=40 + data="before do" +String id=41 + data="do" +String id=42 + data="fanout region1" +String id=43 + data="fanout region0" +String id=44 + data="before do" +String id=45 + data="do" +String id=46 + data="fanout region2" +String id=47 + data="before do" +String id=48 + data="do" +String id=49 + data="fanout region0" +String id=50 + data="fanout region1" +String id=51 + data="before do" +String id=52 + data="do" +String id=53 + data="region5" +String id=54 + data="fanout region5" +String id=55 + data="fanout region3" +String id=56 + data="region4" +String id=57 + data="fanout region4" +String id=58 + data="fanout region0" +String id=59 + data="fanout region1" +String id=60 + data="fanout region2" +String id=61 + data="before do" +String id=62 + data="do" +String id=63 + data="before do" +String id=64 + data="do" +String id=65 + data="fanout region4" +String id=66 + data="fanout region0" +String id=67 + data="fanout region1" +String id=68 + data="fanout region2" +String id=69 + data="before do" +String id=70 + data="do" +String id=71 + data="fanout region3" +String id=72 + data="before do" +String id=73 + data="do" +String id=74 + data="fanout region3" +String id=75 + data="fanout region0" +String id=76 + data="fanout region1" +String id=77 + data="fanout region2" +String id=78 + data="before do" +String id=79 + data="do" +String id=80 + data="before do" +String id=81 + data="do" +String id=82 + data="fanout region1" +String id=83 + data="fanout region0" +String id=84 + data="before do" +String id=85 + data="do" +String id=86 + data="fanout region2" +String id=87 + data="before do" +String id=88 + data="do" +String id=89 + data="fanout region0" +String id=90 + data="fanout region1" +String id=91 + data="before do" +String id=92 + data="do" +String id=93 + data="fanout region5" +String id=94 + data="fanout region0" +String id=95 + data="fanout region1" +String id=96 + data="fanout region2" +String id=97 + data="before do" +String id=98 + data="do" +String id=99 + data="fanout region4" +String id=100 + data="fanout region3" +String id=101 + data="before do" +String id=102 + data="do" +String id=103 + data="fanout region4" +String id=104 + data="fanout region0" +String id=105 + data="fanout region1" +String id=106 + data="fanout region2" +String id=107 + data="before do" +String id=108 + data="do" +String id=109 + data="fanout region3" +String id=110 + data="runtime/trace.(*Task).End" +String id=111 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/annotation.go" +String id=112 + data="main.do" +String id=113 + data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/annotations-stress.go" +String id=114 + data="main.main" +String id=115 + data="sync.(*Mutex).Lock" +String id=116 + data="/usr/local/google/home/mknyszek/work/go-1/src/sync/mutex.go" +String id=117 + data="sync.(*Pool).pinSlow" +String id=118 + data="/usr/local/google/home/mknyszek/work/go-1/src/sync/pool.go" +String id=119 + data="sync.(*Pool).pin" +String id=120 + data="sync.(*Pool).Get" +String id=121 + data="fmt.newPrinter" +String id=122 + data="/usr/local/google/home/mknyszek/work/go-1/src/fmt/print.go" +String id=123 + data="fmt.Sprintf" +String id=124 + data="main.do.func1.1" +String id=125 + data="runtime/trace.Start" +String id=126 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go" +String id=127 + data="main.do.func1" +String id=128 + data="runtime/trace.WithRegion" +String id=129 + data="main.do.func1.1.1" +String id=130 + data="time.Sleep" +String id=131 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/time.go" +String id=132 + data="runtime.startTheWorld" +String id=133 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go" +String id=134 + data="runtime.StartTrace" +String id=135 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go" +String id=136 + data="runtime.(*traceAdvancerState).start.func1" +String id=137 + data="runtime.(*traceAdvancerState).start" +String id=138 + data="runtime.traceStartReadCPU" +String id=139 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2cpu.go" +String id=140 + data="runtime.chanrecv1" +String id=141 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go" +String id=142 + data="runtime.(*wakeableSleep).sleep" +String id=143 + data="runtime.traceStartReadCPU.func1" +String id=144 + data="runtime.newobject" +String id=145 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/malloc.go" +String id=146 + data="sync.(*Mutex).Unlock" +String id=147 + data="runtime/trace.Start.func1" +String id=148 + data="runtime.traceLocker.Gomaxprocs" +String id=149 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go" +String id=150 + data="syscall.write" +String id=151 + data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/zsyscall_linux_amd64.go" +String id=152 + data="syscall.Write" +String id=153 + data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/syscall_unix.go" +String id=154 + data="internal/poll.ignoringEINTRIO" +String id=155 + data="/usr/local/google/home/mknyszek/work/go-1/src/internal/poll/fd_unix.go" +String id=156 + data="internal/poll.(*FD).Write" +String id=157 + data="os.(*File).write" +String id=158 + data="/usr/local/google/home/mknyszek/work/go-1/src/os/file_posix.go" +String id=159 + data="os.(*File).Write" +String id=160 + data="/usr/local/google/home/mknyszek/work/go-1/src/os/file.go" diff --git a/go/src/internal/trace/testdata/tests/go122-annotations.test b/go/src/internal/trace/testdata/tests/go122-annotations.test new file mode 100644 index 0000000000000000000000000000000000000000..e4686734973d314bcee472fb98c89f4cd1271664 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-annotations.test @@ -0,0 +1,299 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=18446744073709551615 time=28113086279559 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=167930 time=28113086277797 size=41 +ProcStart dt=505 p=1 p_seq=1 +GoStart dt=303 g=7 g_seq=1 +HeapAlloc dt=646 heapalloc_value=1892352 +HeapAlloc dt=149 heapalloc_value=1900544 +GoBlock dt=146 reason_string=12 stack=24 +GoStart dt=14 g=6 g_seq=1 +HeapAlloc dt=16 heapalloc_value=1908736 +GoBlock dt=347 reason_string=12 stack=25 +EventBatch gen=1 m=167928 time=28113086279032 size=10 +ProcStart dt=451 p=2 p_seq=1 +GoStart dt=188 g=8 g_seq=1 +EventBatch gen=1 m=167926 time=28113086275999 size=324 +ProcStatus dt=295 p=0 pstatus=1 +GoStatus dt=5 g=1 m=167926 gstatus=2 +ProcsChange dt=405 procs_value=48 stack=1 +STWBegin dt=65 kind_string=21 stack=2 +HeapGoal dt=2 heapgoal_value=4194304 +ProcStatus dt=4 p=1 pstatus=2 +ProcStatus dt=1 p=2 pstatus=2 +ProcStatus dt=1 p=3 pstatus=2 +ProcStatus dt=1 p=4 pstatus=2 +ProcStatus dt=1 p=5 pstatus=2 +ProcStatus dt=1 p=6 pstatus=2 +ProcStatus dt=1 p=7 pstatus=2 +ProcStatus dt=1 p=8 pstatus=2 +ProcStatus dt=1 p=9 pstatus=2 +ProcStatus dt=1 p=10 pstatus=2 +ProcStatus dt=1 p=11 pstatus=2 +ProcStatus dt=1 p=12 pstatus=2 +ProcStatus dt=1 p=13 pstatus=2 +ProcStatus dt=1 p=14 pstatus=2 +ProcStatus dt=1 p=15 pstatus=2 +ProcStatus dt=1 p=16 pstatus=2 +ProcStatus dt=1 p=17 pstatus=2 +ProcStatus dt=1 p=18 pstatus=2 +ProcStatus dt=1 p=19 pstatus=2 +ProcStatus dt=1 p=20 pstatus=2 +ProcStatus dt=1 p=21 pstatus=2 +ProcStatus dt=1 p=22 pstatus=2 +ProcStatus dt=1 p=23 pstatus=2 +ProcStatus dt=1 p=24 pstatus=2 +ProcStatus dt=1 p=25 pstatus=2 +ProcStatus dt=1 p=26 pstatus=2 +ProcStatus dt=1 p=27 pstatus=2 +ProcStatus dt=1 p=28 pstatus=2 +ProcStatus dt=1 p=29 pstatus=2 +ProcStatus dt=1 p=30 pstatus=2 +ProcStatus dt=1 p=31 pstatus=2 +ProcStatus dt=1 p=32 pstatus=2 +ProcStatus dt=1 p=33 pstatus=2 +ProcStatus dt=1 p=34 pstatus=2 +ProcStatus dt=1 p=35 pstatus=2 +ProcStatus dt=1 p=36 pstatus=2 +ProcStatus dt=1 p=37 pstatus=2 +ProcStatus dt=1 p=38 pstatus=2 +ProcStatus dt=1 p=39 pstatus=2 +ProcStatus dt=1 p=40 pstatus=2 +ProcStatus dt=1 p=41 pstatus=2 +ProcStatus dt=1 p=42 pstatus=2 +ProcStatus dt=1 p=43 pstatus=2 +ProcStatus dt=1 p=44 pstatus=2 +ProcStatus dt=1 p=45 pstatus=2 +ProcStatus dt=1 p=46 pstatus=2 +ProcStatus dt=1 p=47 pstatus=2 +ProcsChange dt=1 procs_value=48 stack=3 +STWEnd dt=184 +GoCreate dt=252 new_g=6 new_stack=4 stack=5 +GoCreate dt=78 new_g=7 new_stack=6 stack=7 +GoCreate dt=73 new_g=8 new_stack=8 stack=9 +UserTaskBegin dt=71 task=1 parent_task=0 name_string=22 stack=10 +UserRegionBegin dt=535 task=1 name_string=23 stack=11 +HeapAlloc dt=26 heapalloc_value=1884160 +GoCreate dt=8 new_g=9 new_stack=12 stack=13 +GoBlock dt=249 reason_string=10 stack=14 +GoStart dt=8 g=9 g_seq=1 +UserRegionBegin dt=286 task=1 name_string=24 stack=15 +UserRegionBegin dt=244 task=1 name_string=25 stack=16 +UserRegionBegin dt=6 task=1 name_string=26 stack=17 +UserLog dt=6 task=1 key_string=27 value_string=28 stack=18 +UserRegionEnd dt=4 task=1 name_string=26 stack=19 +UserRegionEnd dt=315 task=1 name_string=25 stack=20 +UserTaskEnd dt=5 task=1 stack=21 +GoUnblock dt=11 g=1 g_seq=1 stack=22 +GoDestroy dt=6 +GoStart dt=10 g=1 g_seq=2 +UserRegionBegin dt=278 task=0 name_string=29 stack=23 +EventBatch gen=1 m=18446744073709551615 time=28113086280061 size=57 +GoStatus dt=318 g=2 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=3 m=18446744073709551615 gstatus=4 +GoStatus dt=1 g=4 m=18446744073709551615 gstatus=4 +GoStatus dt=1 g=5 m=18446744073709551615 gstatus=4 +EventBatch gen=1 m=18446744073709551615 time=28113086280852 size=488 +Stacks +Stack id=17 nframes=3 + pc=4816080 func=30 file=31 line=45 + pc=4813660 func=32 file=33 line=141 + pc=4815908 func=34 file=31 line=43 +Stack id=8 nframes=1 + pc=4814528 func=35 file=36 line=128 +Stack id=9 nframes=2 + pc=4814351 func=37 file=36 line=128 + pc=4815228 func=38 file=31 line=27 +Stack id=24 nframes=3 + pc=4217457 func=39 file=40 line=442 + pc=4544973 func=41 file=42 line=918 + pc=4544806 func=43 file=42 line=871 +Stack id=7 nframes=4 + pc=4544740 func=44 file=42 line=868 + pc=4538792 func=45 file=42 line=258 + pc=4814277 func=37 file=36 line=125 + pc=4815228 func=38 file=31 line=27 +Stack id=22 nframes=3 + pc=4642148 func=46 file=47 line=81 + pc=4816326 func=48 file=47 line=87 + pc=4815941 func=34 file=31 line=50 +Stack id=11 nframes=1 + pc=4815364 func=38 file=31 line=34 +Stack id=5 nframes=4 + pc=4547349 func=49 file=50 line=42 + pc=4538780 func=45 file=42 line=257 + pc=4814277 func=37 file=36 line=125 + pc=4815228 func=38 file=31 line=27 +Stack id=23 nframes=1 + pc=4815568 func=38 file=31 line=54 +Stack id=3 nframes=4 + pc=4421860 func=51 file=52 line=1360 + pc=4538775 func=45 file=42 line=255 + pc=4814277 func=37 file=36 line=125 + pc=4815228 func=38 file=31 line=27 +Stack id=21 nframes=2 + pc=4816228 func=53 file=33 line=80 + pc=4815926 func=34 file=31 line=50 +Stack id=1 nframes=4 + pc=4553515 func=54 file=55 line=255 + pc=4538503 func=45 file=42 line=237 + pc=4814277 func=37 file=36 line=125 + pc=4815228 func=38 file=31 line=27 +Stack id=12 nframes=1 + pc=4815680 func=34 file=31 line=37 +Stack id=6 nframes=1 + pc=4544768 func=43 file=42 line=868 +Stack id=2 nframes=3 + pc=4538523 func=45 file=42 line=238 + pc=4814277 func=37 file=36 line=125 + pc=4815228 func=38 file=31 line=27 +Stack id=13 nframes=1 + pc=4815492 func=38 file=31 line=37 +Stack id=4 nframes=1 + pc=4547456 func=56 file=50 line=42 +Stack id=14 nframes=2 + pc=4642407 func=57 file=47 line=116 + pc=4815502 func=38 file=31 line=51 +Stack id=18 nframes=5 + pc=4816147 func=58 file=31 line=46 + pc=4813660 func=32 file=33 line=141 + pc=4816080 func=30 file=31 line=45 + pc=4813660 func=32 file=33 line=141 + pc=4815908 func=34 file=31 line=43 +Stack id=20 nframes=1 + pc=4815908 func=34 file=31 line=43 +Stack id=25 nframes=3 + pc=4217457 func=39 file=40 line=442 + pc=4544973 func=41 file=42 line=918 + pc=4547514 func=56 file=50 line=54 +Stack id=16 nframes=1 + pc=4815908 func=34 file=31 line=43 +Stack id=15 nframes=1 + pc=4815838 func=34 file=31 line=41 +Stack id=19 nframes=3 + pc=4816080 func=30 file=31 line=45 + pc=4813660 func=32 file=33 line=141 + pc=4815908 func=34 file=31 line=43 +Stack id=10 nframes=1 + pc=4815332 func=38 file=31 line=33 +EventBatch gen=1 m=18446744073709551615 time=28113086274600 size=1620 +Strings +String id=1 + data="Not worker" +String id=2 + data="GC (dedicated)" +String id=3 + data="GC (fractional)" +String id=4 + data="GC (idle)" +String id=5 + data="unspecified" +String id=6 + data="forever" +String id=7 + data="network" +String id=8 + data="select" +String id=9 + data="sync.(*Cond).Wait" +String id=10 + data="sync" +String id=11 + data="chan send" +String id=12 + data="chan receive" +String id=13 + data="GC mark assist wait for work" +String id=14 + data="GC background sweeper wait" +String id=15 + data="system goroutine wait" +String id=16 + data="preempted" +String id=17 + data="wait for debug call" +String id=18 + data="wait until GC ends" +String id=19 + data="sleep" +String id=20 + data="runtime.Gosched" +String id=21 + data="start trace" +String id=22 + data="task0" +String id=23 + data="task0 region" +String id=24 + data="unended region" +String id=25 + data="region0" +String id=26 + data="region1" +String id=27 + data="key0" +String id=28 + data="0123456789abcdef" +String id=29 + data="post-existing region" +String id=30 + data="main.main.func1.1" +String id=31 + data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/annotations.go" +String id=32 + data="runtime/trace.WithRegion" +String id=33 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/annotation.go" +String id=34 + data="main.main.func1" +String id=35 + data="runtime/trace.Start.func1" +String id=36 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go" +String id=37 + data="runtime/trace.Start" +String id=38 + data="main.main" +String id=39 + data="runtime.chanrecv1" +String id=40 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go" +String id=41 + data="runtime.(*wakeableSleep).sleep" +String id=42 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go" +String id=43 + data="runtime.(*traceAdvancerState).start.func1" +String id=44 + data="runtime.(*traceAdvancerState).start" +String id=45 + data="runtime.StartTrace" +String id=46 + data="sync.(*WaitGroup).Add" +String id=47 + data="/usr/local/google/home/mknyszek/work/go-1/src/sync/waitgroup.go" +String id=48 + data="sync.(*WaitGroup).Done" +String id=49 + data="runtime.traceStartReadCPU" +String id=50 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2cpu.go" +String id=51 + data="runtime.startTheWorld" +String id=52 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go" +String id=53 + data="runtime/trace.(*Task).End" +String id=54 + data="runtime.traceLocker.Gomaxprocs" +String id=55 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go" +String id=56 + data="runtime.traceStartReadCPU.func1" +String id=57 + data="sync.(*WaitGroup).Wait" +String id=58 + data="main.main.func1.1.1" diff --git a/go/src/internal/trace/testdata/tests/go122-confuse-seq-across-generations.test b/go/src/internal/trace/testdata/tests/go122-confuse-seq-across-generations.test new file mode 100644 index 0000000000000000000000000000000000000000..c0d6f0d3dd310140ee029cbf4177774e9f4891e4 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-confuse-seq-across-generations.test @@ -0,0 +1,36 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=13 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +GoStop dt=1 reason_string=1 stack=0 +EventBatch gen=1 m=1 time=0 size=12 +ProcStatus dt=1 p=1 pstatus=1 +GoStart dt=1 g=1 g_seq=1 +GoStop dt=1 reason_string=1 stack=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=12 +Strings +String id=1 + data="whatever" +EventBatch gen=2 m=1 time=3 size=8 +ProcStatus dt=1 p=1 pstatus=1 +GoStart dt=1 g=1 g_seq=2 +EventBatch gen=2 m=0 time=5 size=17 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=1 +GoStart dt=1 g=1 g_seq=1 +GoStop dt=1 reason_string=1 stack=0 +EventBatch gen=2 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=2 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=2 m=18446744073709551615 time=0 size=12 +Strings +String id=1 + data="whatever" diff --git a/go/src/internal/trace/testdata/tests/go122-create-syscall-reuse-thread-id.test b/go/src/internal/trace/testdata/tests/go122-create-syscall-reuse-thread-id.test new file mode 100644 index 0000000000000000000000000000000000000000..182073838493c367f3dd38ef5bb83c0a8d0ea3ee --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-create-syscall-reuse-thread-id.test @@ -0,0 +1,23 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=37 +GoCreateSyscall dt=1 new_g=4 +GoSyscallEndBlocked dt=1 +ProcStatus dt=1 p=0 pstatus=2 +ProcStart dt=1 p=0 p_seq=1 +GoStatus dt=1 g=4 m=18446744073709551615 gstatus=1 +GoStart dt=1 g=4 g_seq=1 +GoSyscallBegin dt=1 p_seq=2 stack=0 +GoDestroySyscall dt=1 +EventBatch gen=1 m=0 time=0 size=13 +ProcStatus dt=1 p=1 pstatus=2 +ProcStart dt=1 p=1 p_seq=1 +ProcSteal dt=1 p=0 p_seq=3 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-create-syscall-with-p.test b/go/src/internal/trace/testdata/tests/go122-create-syscall-with-p.test new file mode 100644 index 0000000000000000000000000000000000000000..9b329b8bae953948e1324558ab8c160bede056bb --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-create-syscall-with-p.test @@ -0,0 +1,22 @@ +-- expect -- +FAILURE ".*expected a proc but didn't have one.*" +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=34 +GoCreateSyscall dt=1 new_g=4 +ProcStatus dt=1 p=0 pstatus=2 +ProcStart dt=1 p=0 p_seq=1 +GoSyscallEndBlocked dt=1 +GoStart dt=1 g=4 g_seq=1 +GoSyscallBegin dt=1 p_seq=2 stack=0 +GoDestroySyscall dt=1 +GoCreateSyscall dt=1 new_g=4 +GoSyscallEnd dt=1 +GoSyscallBegin dt=1 p_seq=3 stack=0 +GoDestroySyscall dt=1 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-fail-first-gen-first.test b/go/src/internal/trace/testdata/tests/go122-fail-first-gen-first.test new file mode 100644 index 0000000000000000000000000000000000000000..cc4240de40dbe56327be2e0d8356ba384b003826 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-fail-first-gen-first.test @@ -0,0 +1,9 @@ +-- expect -- +FAILURE "expected a proc but didn't have one" +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=0 time=0 size=5 +GoCreate dt=0 new_g=1 new_stack=0 stack=0 +EventBatch gen=2 m=0 time=0 size=50 diff --git a/go/src/internal/trace/testdata/tests/go122-gc-stress.test b/go/src/internal/trace/testdata/tests/go122-gc-stress.test new file mode 100644 index 0000000000000000000000000000000000000000..d5e7266f1e4b2eae68555d4db13518c1801e41cf --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-gc-stress.test @@ -0,0 +1,4207 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=3 m=18446744073709551615 time=28114950954550 size=5 +Frequency freq=15625000 +EventBatch gen=3 m=169438 time=28114950899454 size=615 +ProcStatus dt=2 p=47 pstatus=1 +GoStatus dt=1 g=111 m=169438 gstatus=2 +GCMarkAssistActive dt=1 g=111 +GCMarkAssistEnd dt=1 +HeapAlloc dt=38 heapalloc_value=191159744 +HeapAlloc dt=134 heapalloc_value=191192512 +GCMarkAssistBegin dt=60 stack=3 +GoStop dt=2288 reason_string=20 stack=9 +GoStart dt=15 g=111 g_seq=1 +GCMarkAssistEnd dt=1860 +HeapAlloc dt=46 heapalloc_value=191585728 +GCMarkAssistBegin dt=35 stack=3 +GoBlock dt=32 reason_string=13 stack=11 +GoUnblock dt=14 g=57 g_seq=5 stack=0 +GoStart dt=9 g=57 g_seq=6 +GoLabel dt=3 label_string=2 +GoBlock dt=2925 reason_string=15 stack=5 +GoUnblock dt=12 g=57 g_seq=7 stack=0 +GoStart dt=5 g=57 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=391 reason_string=15 stack=5 +GoUnblock dt=15 g=57 g_seq=9 stack=0 +GoStart dt=7 g=57 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=307 reason_string=15 stack=5 +GoUnblock dt=7 g=57 g_seq=11 stack=0 +GoStart dt=3 g=57 g_seq=12 +GoLabel dt=2 label_string=2 +GoBlock dt=1049 reason_string=15 stack=5 +GoUnblock dt=23 g=58 g_seq=7 stack=0 +GoStart dt=8 g=58 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=1126 reason_string=15 stack=5 +GoUnblock dt=12 g=53 g_seq=3 stack=0 +GoStart dt=5 g=53 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=1751 reason_string=15 stack=5 +GoUnblock dt=12 g=53 g_seq=5 stack=0 +GoStart dt=6 g=53 g_seq=6 +GoLabel dt=3 label_string=2 +GoBlock dt=119 reason_string=15 stack=5 +GoStart dt=15 g=88 g_seq=4 +GoBlock dt=50 reason_string=13 stack=11 +GoUnblock dt=1212 g=54 g_seq=15 stack=0 +GoStart dt=6 g=54 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=2984 reason_string=15 stack=5 +GoUnblock dt=2696 g=52 g_seq=21 stack=0 +GoStart dt=3 g=52 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=2013 reason_string=15 stack=5 +GoStart dt=18 g=98 g_seq=6 +GCMarkAssistEnd dt=6 +HeapAlloc dt=44 heapalloc_value=192003520 +GCMarkAssistBegin dt=54 stack=3 +GoBlock dt=481 reason_string=13 stack=11 +GoUnblock dt=51 g=14 g_seq=17 stack=0 +GoStart dt=4 g=14 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=3954 reason_string=15 stack=5 +GoUnblock dt=59 g=57 g_seq=41 stack=0 +GoStart dt=8 g=57 g_seq=42 +GoLabel dt=1 label_string=4 +GoBlock dt=63 reason_string=15 stack=5 +GoUnblock dt=11 g=57 g_seq=43 stack=0 +GoStart dt=4 g=57 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=3186 reason_string=15 stack=5 +GoUnblock dt=11 g=57 g_seq=45 stack=0 +GoStart dt=3 g=57 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +ProcStop dt=60 +ProcStart dt=50 p=47 p_seq=1 +GoUnblock dt=9 g=22 g_seq=33 stack=0 +GoStart dt=4 g=22 g_seq=34 +GoLabel dt=1 label_string=4 +GoBlock dt=97 reason_string=15 stack=5 +GoUnblock dt=9 g=22 g_seq=35 stack=0 +GoStart dt=5 g=22 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=2605 reason_string=15 stack=5 +GoUnblock dt=10 g=22 g_seq=37 stack=0 +GoStart dt=4 g=22 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=13 reason_string=15 stack=5 +ProcStop dt=37 +ProcStart dt=582 p=47 p_seq=2 +GoStart dt=504 g=97 g_seq=4 +GCMarkAssistEnd dt=5 +GCMarkAssistBegin dt=34 stack=3 +GoBlock dt=279 reason_string=13 stack=11 +ProcStop dt=30 +ProcStart dt=3780 p=47 p_seq=3 +GoUnblock dt=9 g=71 g_seq=25 stack=0 +GoStart dt=128 g=71 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=210 reason_string=15 stack=5 +GoUnblock dt=8 g=71 g_seq=27 stack=0 +GoStart dt=1 g=71 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=1627 reason_string=15 stack=5 +GoStart dt=27 g=105 g_seq=6 +GCMarkAssistEnd dt=3 +HeapAlloc dt=44 heapalloc_value=192477912 +GCMarkAssistBegin dt=77 stack=3 +GoStop dt=873 reason_string=20 stack=9 +GoUnblock dt=12 g=23 g_seq=47 stack=0 +GoStart dt=3 g=23 g_seq=48 +GoLabel dt=1 label_string=2 +GoBlock dt=36 reason_string=15 stack=5 +GoUnblock dt=6 g=23 g_seq=49 stack=0 +GoStart dt=1 g=23 g_seq=50 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +GoUnblock dt=8 g=23 g_seq=51 stack=0 +GoStart dt=3 g=23 g_seq=52 +GoLabel dt=1 label_string=2 +GoBlock dt=15 reason_string=15 stack=5 +GoStart dt=10 g=105 g_seq=7 +GoStop dt=16 reason_string=20 stack=9 +GoUnblock dt=7 g=23 g_seq=53 stack=0 +GoStart dt=3 g=23 g_seq=54 +GoLabel dt=1 label_string=2 +GoBlock dt=10 reason_string=15 stack=5 +GoUnblock dt=12 g=23 g_seq=55 stack=0 +GoStart dt=3 g=23 g_seq=56 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +GoUnblock dt=4 g=23 g_seq=57 stack=0 +GoStart dt=1 g=23 g_seq=58 +GoLabel dt=1 label_string=2 +GoBlock dt=4554 reason_string=15 stack=5 +GoStart dt=14 g=105 g_seq=10 +GCMarkAssistEnd dt=5 +HeapAlloc dt=65 heapalloc_value=193682136 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=44 reason_string=13 stack=11 +GoStart dt=15 g=83 g_seq=8 +HeapAlloc dt=221 heapalloc_value=194173656 +HeapAlloc dt=1927 heapalloc_value=195443416 +GoStop dt=5838 reason_string=16 stack=6 +GoStart dt=51 g=83 g_seq=9 +GCMarkAssistBegin dt=12 stack=3 +GoBlock dt=35 reason_string=10 stack=18 +GoStart dt=70 g=87 g_seq=6 +GCMarkAssistBegin dt=14 stack=3 +GoBlock dt=35 reason_string=13 stack=11 +ProcStop dt=77 +EventBatch gen=3 m=169436 time=28114950894898 size=160 +ProcStatus dt=2 p=34 pstatus=1 +GoStatus dt=3 g=107 m=169436 gstatus=2 +GCMarkAssistBegin dt=15 stack=3 +GoBlock dt=4050 reason_string=13 stack=11 +GoStatus dt=20 g=23 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=23 g_seq=1 stack=0 +GoStart dt=8 g=23 g_seq=2 +GoLabel dt=1 label_string=2 +GoUnblock dt=2316 g=81 g_seq=1 stack=12 +GoBlock dt=626 reason_string=15 stack=5 +GoUnblock dt=9 g=23 g_seq=3 stack=0 +GoStart dt=9 g=23 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=3975 reason_string=15 stack=5 +GoUnblock dt=35 g=23 g_seq=5 stack=0 +GoStart dt=6 g=23 g_seq=6 +GoLabel dt=1 label_string=2 +GoBlock dt=142 reason_string=15 stack=5 +GoUnblock dt=9 g=23 g_seq=7 stack=0 +GoStart dt=4 g=23 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=3815 reason_string=15 stack=5 +GoUnblock dt=10 g=23 g_seq=9 stack=0 +GoStart dt=6 g=23 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=3560 reason_string=15 stack=5 +GoUnblock dt=8 g=23 g_seq=11 stack=0 +GoStart dt=4 g=23 g_seq=12 +GoLabel dt=3 label_string=2 +GoBlock dt=2781 reason_string=15 stack=5 +GoUnblock dt=13 g=23 g_seq=13 stack=0 +GoStart dt=4 g=23 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=1277 reason_string=15 stack=5 +ProcStop dt=16 +EventBatch gen=3 m=169435 time=28114950897148 size=522 +ProcStatus dt=2 p=24 pstatus=1 +GoStatus dt=2 g=122 m=169435 gstatus=2 +GCMarkAssistActive dt=1 g=122 +GCMarkAssistEnd dt=3 +HeapAlloc dt=24 heapalloc_value=190602688 +GCMarkAssistBegin dt=95 stack=3 +GCMarkAssistEnd dt=4651 +GCMarkAssistBegin dt=50 stack=3 +GoBlock dt=2931 reason_string=13 stack=11 +ProcStop dt=1401 +ProcStart dt=18 p=24 p_seq=1 +GoUnblock dt=3524 g=28 g_seq=5 stack=0 +GoStart dt=10 g=28 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=42 reason_string=15 stack=5 +GoUnblock dt=1162 g=24 g_seq=11 stack=0 +GoStart dt=7 g=24 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=3050 reason_string=15 stack=5 +GoUnblock dt=5301 g=67 g_seq=15 stack=0 +GoStart dt=4 g=67 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=40 reason_string=15 stack=5 +ProcStop dt=64 +ProcStart dt=841 p=24 p_seq=2 +GoStatus dt=58 g=16 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=16 g_seq=1 stack=0 +GoStart dt=273 g=16 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=139 reason_string=15 stack=5 +ProcStop dt=52 +ProcStart dt=97 p=24 p_seq=3 +GoUnblock dt=5 g=16 g_seq=3 stack=0 +GoStart dt=2 g=16 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=471 reason_string=15 stack=5 +GoUnblock dt=58 g=16 g_seq=5 stack=0 +GoStart dt=6 g=16 g_seq=6 +GoLabel dt=3 label_string=4 +GoBlock dt=912 reason_string=15 stack=5 +GoUnblock dt=9 g=16 g_seq=7 stack=0 +GoStart dt=6 g=16 g_seq=8 +GoLabel dt=1 label_string=2 +GoUnblock dt=6571 g=113 g_seq=5 stack=12 +GoBlock dt=22 reason_string=15 stack=5 +ProcStop dt=73 +ProcStart dt=22914 p=30 p_seq=16 +GoStart dt=342 g=117 g_seq=4 +GCMarkAssistEnd dt=8 +HeapAlloc dt=67 heapalloc_value=196467152 +GoStop dt=5253 reason_string=16 stack=6 +GoStart dt=44 g=128 g_seq=7 +GCMarkAssistBegin dt=21 stack=3 +GoBlock dt=37 reason_string=10 stack=18 +GoStart dt=7 g=130 g_seq=5 +GoBlock dt=182 reason_string=10 stack=20 +ProcStop dt=81 +ProcStart dt=8287 p=2 p_seq=2 +GoStart dt=164 g=82 g_seq=11 +GCMarkAssistEnd dt=8 +HeapAlloc dt=169 heapalloc_value=104038048 +HeapAlloc dt=135 heapalloc_value=104189856 +HeapAlloc dt=126 heapalloc_value=104287136 +HeapAlloc dt=24 heapalloc_value=104308256 +HeapAlloc dt=28 heapalloc_value=104313888 +HeapAlloc dt=14 heapalloc_value=104399904 +GCSweepBegin dt=43 stack=28 +GCSweepEnd dt=8 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=4 heapalloc_value=104473632 +HeapAlloc dt=58 heapalloc_value=104510496 +HeapAlloc dt=22 heapalloc_value=104534432 +HeapAlloc dt=51 heapalloc_value=104654624 +GCSweepBegin dt=146 stack=28 +GCSweepEnd dt=8 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=4 heapalloc_value=104878624 +HeapAlloc dt=42 heapalloc_value=105007648 +HeapAlloc dt=29 heapalloc_value=105077280 +HeapAlloc dt=36 heapalloc_value=105105952 +HeapAlloc dt=44 heapalloc_value=105242784 +HeapAlloc dt=58 heapalloc_value=105431200 +HeapAlloc dt=128 heapalloc_value=105593760 +HeapAlloc dt=199 heapalloc_value=106209440 +GCSweepBegin dt=155 stack=28 +GCSweepEnd dt=13 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=106666272 +HeapAlloc dt=77 heapalloc_value=106901152 +HeapAlloc dt=64 heapalloc_value=107211808 +HeapAlloc dt=133 heapalloc_value=107661088 +HeapAlloc dt=34 heapalloc_value=107722528 +HeapAlloc dt=108 heapalloc_value=108207392 +GCSweepBegin dt=202 stack=28 +GCSweepEnd dt=13 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=108742816 +HeapAlloc dt=112 heapalloc_value=109093664 +HeapAlloc dt=207 heapalloc_value=109913120 +HeapAlloc dt=271 heapalloc_value=110834560 +HeapAlloc dt=212 heapalloc_value=111566720 +HeapAlloc dt=148 heapalloc_value=112190720 +HeapAlloc dt=74 heapalloc_value=112528128 +HeapAlloc dt=143 heapalloc_value=113050240 +HeapAlloc dt=19 heapalloc_value=113194368 +HeapAlloc dt=135 heapalloc_value=113615232 +GCSweepBegin dt=251 stack=27 +EventBatch gen=3 m=169434 time=28114950909315 size=660 +ProcStatus dt=2 p=7 pstatus=1 +GoStatus dt=2 g=71 m=169434 gstatus=2 +GoBlock dt=6 reason_string=15 stack=5 +GoUnblock dt=2633 g=53 g_seq=7 stack=0 +GoStart dt=7 g=53 g_seq=8 +GoLabel dt=3 label_string=4 +GoBlock dt=127 reason_string=15 stack=5 +GoUnblock dt=1358 g=52 g_seq=15 stack=0 +GoStart dt=7 g=52 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=27 reason_string=15 stack=5 +GoStart dt=1150 g=93 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=39 heapalloc_value=191897024 +GCMarkAssistBegin dt=27 stack=3 +GoStop dt=894 reason_string=20 stack=9 +GoStart dt=13 g=93 g_seq=5 +GoBlock dt=150 reason_string=13 stack=11 +ProcStop dt=57 +ProcStart dt=14 p=7 p_seq=1 +ProcStop dt=4205 +ProcStart dt=18 p=7 p_seq=2 +GoUnblock dt=4 g=22 g_seq=17 stack=0 +GoStart dt=172 g=22 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=1298 reason_string=15 stack=5 +GoUnblock dt=12 g=22 g_seq=19 stack=0 +GoStart dt=7 g=22 g_seq=20 +GoLabel dt=1 label_string=2 +GoBlock dt=108 reason_string=15 stack=5 +GoUnblock dt=9 g=22 g_seq=21 stack=0 +GoStart dt=4 g=22 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=309 reason_string=15 stack=5 +GoUnblock dt=19 g=57 g_seq=35 stack=0 +GoStart dt=6 g=57 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=26 reason_string=15 stack=5 +GoUnblock dt=12 g=30 g_seq=15 stack=0 +GoStart dt=4 g=30 g_seq=16 +GoLabel dt=1 label_string=2 +GoBlock dt=410 reason_string=15 stack=5 +GoUnblock dt=2384 g=23 g_seq=37 stack=0 +GoStart dt=7 g=23 g_seq=38 +GoLabel dt=1 label_string=4 +GoBlock dt=119 reason_string=15 stack=5 +GoUnblock dt=58 g=25 g_seq=21 stack=0 +GoStart dt=4 g=25 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=1875 reason_string=15 stack=5 +GoUnblock dt=53 g=29 g_seq=15 stack=0 +GoStart dt=3 g=29 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=133 reason_string=15 stack=5 +GoUnblock dt=51 g=25 g_seq=25 stack=0 +GoStart dt=5 g=25 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=14 reason_string=15 stack=5 +GoUnblock dt=42 g=25 g_seq=27 stack=0 +GoStart dt=3 g=25 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=56 reason_string=15 stack=5 +GoUnblock dt=1741 g=24 g_seq=41 stack=0 +GoStart dt=4 g=24 g_seq=42 +GoLabel dt=3 label_string=2 +GoBlock dt=15 reason_string=15 stack=5 +GoUnblock dt=26 g=25 g_seq=31 stack=0 +GoStart dt=4 g=25 g_seq=32 +GoLabel dt=1 label_string=2 +GoBlock dt=2653 reason_string=15 stack=5 +GoUnblock dt=10 g=25 g_seq=33 stack=0 +GoStart dt=6 g=25 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=151 reason_string=15 stack=5 +GoUnblock dt=37 g=25 g_seq=35 stack=0 +GoStart dt=3 g=25 g_seq=36 +GoLabel dt=1 label_string=4 +GoBlock dt=12 reason_string=15 stack=5 +GoUnblock dt=8 g=25 g_seq=37 stack=0 +GoStart dt=3 g=25 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=1197 reason_string=15 stack=5 +GoUnblock dt=38 g=22 g_seq=43 stack=0 +GoStart dt=7 g=22 g_seq=44 +GoLabel dt=1 label_string=4 +GoBlock dt=16 reason_string=15 stack=5 +ProcStop dt=28 +ProcStart dt=2728 p=7 p_seq=3 +GoUnblock dt=10 g=25 g_seq=39 stack=0 +GoStart dt=162 g=25 g_seq=40 +GoLabel dt=2 label_string=2 +GoBlock dt=36 reason_string=15 stack=5 +GoUnblock dt=10 g=25 g_seq=41 stack=0 +GoStart dt=4 g=25 g_seq=42 +GoLabel dt=1 label_string=2 +GoBlock dt=19 reason_string=15 stack=5 +GoUnblock dt=7 g=25 g_seq=43 stack=0 +GoStart dt=1 g=25 g_seq=44 +GoLabel dt=1 label_string=2 +GoUnblock dt=616 g=81 g_seq=6 stack=12 +GoBlock dt=1549 reason_string=15 stack=5 +GoStart dt=12 g=112 g_seq=5 +GoBlock dt=22 reason_string=13 stack=11 +GoStart dt=8 g=90 g_seq=4 +GCMarkAssistEnd dt=3 +HeapAlloc dt=2613 heapalloc_value=192625368 +GoStop dt=48 reason_string=16 stack=6 +GoUnblock dt=13 g=54 g_seq=35 stack=0 +GoStart dt=4 g=54 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=269 reason_string=15 stack=5 +GoUnblock dt=6 g=54 g_seq=37 stack=0 +GoStart dt=5 g=54 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=856 reason_string=15 stack=5 +GoUnblock dt=23 g=52 g_seq=61 stack=0 +GoStart dt=4 g=52 g_seq=62 +GoLabel dt=1 label_string=2 +GoBlock dt=33 reason_string=15 stack=5 +GoUnblock dt=13 g=52 g_seq=63 stack=0 +GoStart dt=2 g=52 g_seq=64 +GoLabel dt=1 label_string=2 +GoBlock dt=38 reason_string=15 stack=5 +GoUnblock dt=17 g=52 g_seq=65 stack=0 +GoStart dt=3 g=52 g_seq=66 +GoLabel dt=1 label_string=2 +GoBlock dt=37 reason_string=15 stack=5 +GoUnblock dt=11 g=52 g_seq=67 stack=0 +GoStart dt=4 g=52 g_seq=68 +GoLabel dt=1 label_string=2 +GoBlock dt=2457 reason_string=15 stack=5 +GoUnblock dt=11 g=52 g_seq=69 stack=0 +GoStart dt=4 g=52 g_seq=70 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +GoStart dt=23 g=114 g_seq=4 +GCMarkAssistEnd dt=457 +HeapAlloc dt=223 heapalloc_value=194968280 +GoStop dt=6900 reason_string=16 stack=4 +GoStart dt=24 g=114 g_seq=5 +GCMarkAssistBegin dt=86 stack=3 +GoBlock dt=43 reason_string=10 stack=18 +ProcStop dt=49 +ProcStart dt=475 p=7 p_seq=4 +ProcStop dt=40 +ProcStart dt=1388 p=7 p_seq=5 +GoUnblock dt=9 g=131 g_seq=8 stack=0 +GoStart dt=169 g=131 g_seq=9 +GoSyscallBegin dt=24 p_seq=6 stack=7 +GoSyscallEnd dt=184 +GoBlock dt=11 reason_string=15 stack=2 +ProcStop dt=42 +ProcStart dt=18109 p=16 p_seq=2 +GoStart dt=176 g=91 g_seq=4 +GCMarkAssistEnd dt=8 +HeapAlloc dt=22 heapalloc_value=114837120 +HeapAlloc dt=88 heapalloc_value=114853504 +GCSweepBegin dt=145 stack=27 +EventBatch gen=3 m=169433 time=28114950897465 size=806 +ProcStatus dt=2 p=2 pstatus=1 +GoStatus dt=1 g=24 m=169433 gstatus=2 +GoBlock dt=9 reason_string=15 stack=5 +GoUnblock dt=19 g=24 g_seq=1 stack=0 +GoStart dt=5 g=24 g_seq=2 +GoLabel dt=2 label_string=2 +GoBlock dt=4044 reason_string=15 stack=5 +GoUnblock dt=17 g=24 g_seq=3 stack=0 +GoStart dt=4 g=24 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=4262 reason_string=15 stack=5 +GoUnblock dt=19 g=28 g_seq=3 stack=0 +GoStart dt=4 g=28 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=461 reason_string=15 stack=5 +GoUnblock dt=4544 g=72 g_seq=15 stack=0 +GoStart dt=9 g=72 g_seq=16 +GoLabel dt=3 label_string=4 +GoBlock dt=32 reason_string=15 stack=5 +GoUnblock dt=9 g=72 g_seq=17 stack=0 +GoStart dt=2 g=72 g_seq=18 +GoLabel dt=2 label_string=2 +GoBlock dt=13 reason_string=15 stack=5 +GoUnblock dt=3 g=72 g_seq=19 stack=0 +GoStart dt=1 g=72 g_seq=20 +GoLabel dt=1 label_string=2 +GoBlock dt=237 reason_string=15 stack=5 +GoUnblock dt=8 g=72 g_seq=21 stack=0 +GoStart dt=3 g=72 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=151 reason_string=15 stack=5 +GoUnblock dt=11 g=72 g_seq=23 stack=0 +GoStart dt=6 g=72 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=3418 reason_string=15 stack=5 +ProcStop dt=1573 +ProcStart dt=17 p=2 p_seq=1 +ProcStop dt=1102 +ProcStart dt=21668 p=19 p_seq=4 +GoUnblock dt=16 g=51 g_seq=47 stack=0 +GoStart dt=7 g=51 g_seq=48 +GoLabel dt=1 label_string=2 +GoBlock dt=60 reason_string=15 stack=5 +GoUnblock dt=6 g=51 g_seq=49 stack=0 +GoStart dt=1 g=51 g_seq=50 +GoLabel dt=3 label_string=2 +GoBlock dt=5166 reason_string=15 stack=5 +GoStart dt=18 g=106 g_seq=5 +GCMarkAssistEnd dt=10 +HeapAlloc dt=56 heapalloc_value=193452760 +GCMarkAssistBegin dt=116 stack=3 +GCMarkAssistEnd dt=58 +HeapAlloc dt=47 heapalloc_value=193714904 +GoStop dt=54 reason_string=16 stack=6 +GoUnblock dt=18 g=54 g_seq=41 stack=0 +GoStart dt=4 g=54 g_seq=42 +GoLabel dt=2 label_string=2 +GoUnblock dt=16 g=105 g_seq=11 stack=12 +GoBlock dt=21 reason_string=15 stack=5 +GoStart dt=8 g=105 g_seq=12 +GCMarkAssistEnd dt=7 +HeapAlloc dt=33 heapalloc_value=193919704 +GCMarkAssistBegin dt=13 stack=3 +GCMarkAssistEnd dt=91 +HeapAlloc dt=173 heapalloc_value=194378456 +GCMarkAssistBegin dt=26 stack=3 +GoBlock dt=37 reason_string=13 stack=11 +GoStart dt=33 g=104 g_seq=2 +GCMarkAssistEnd dt=5 +HeapAlloc dt=81 heapalloc_value=194673368 +GoStop dt=2248 reason_string=16 stack=6 +GoStart dt=2855 g=104 g_seq=3 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=27 reason_string=10 stack=18 +GoStart dt=16 g=103 g_seq=5 +GCMarkAssistEnd dt=6 +HeapAlloc dt=6180 heapalloc_value=196655568 +GoStop dt=14 reason_string=16 stack=6 +GoStart dt=146 g=102 g_seq=5 +GCMarkAssistBegin dt=10 stack=3 +HeapAlloc dt=38 heapalloc_value=196663760 +GoBlock dt=16 reason_string=10 stack=18 +ProcStop dt=41 +ProcStart dt=1317 p=19 p_seq=5 +ProcStop dt=24 +ProcStart dt=2117 p=0 p_seq=5 +GoStart dt=5190 g=115 g_seq=10 +GCMarkAssistEnd dt=6 +GCSweepBegin dt=22 stack=27 +GCSweepEnd dt=727 swept_value=71303168 reclaimed_value=1302272 +HeapAlloc dt=37 heapalloc_value=103898784 +HeapAlloc dt=200 heapalloc_value=103947936 +HeapAlloc dt=63 heapalloc_value=103960224 +HeapAlloc dt=27 heapalloc_value=103997088 +HeapAlloc dt=65 heapalloc_value=104103584 +HeapAlloc dt=87 heapalloc_value=104132512 +HeapAlloc dt=63 heapalloc_value=104255392 +HeapAlloc dt=87 heapalloc_value=104267680 +HeapAlloc dt=73 heapalloc_value=104379424 +HeapAlloc dt=79 heapalloc_value=104494112 +GCSweepBegin dt=40 stack=28 +GCSweepEnd dt=7 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=8 heapalloc_value=104526880 +HeapAlloc dt=27 heapalloc_value=104589088 +HeapAlloc dt=42 heapalloc_value=104711968 +HeapAlloc dt=83 heapalloc_value=104821280 +GCSweepBegin dt=21 stack=28 +GCSweepEnd dt=4 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=2 heapalloc_value=104854048 +HeapAlloc dt=105 heapalloc_value=105064992 +GCSweepBegin dt=94 stack=28 +GCSweepEnd dt=9 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=4 heapalloc_value=105250976 +GCSweepBegin dt=29 stack=28 +GCSweepEnd dt=10 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=4 heapalloc_value=105447584 +HeapAlloc dt=30 heapalloc_value=105476256 +HeapAlloc dt=57 heapalloc_value=105566368 +GCSweepBegin dt=74 stack=28 +GCSweepEnd dt=5 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=105741216 +HeapAlloc dt=77 heapalloc_value=105921440 +HeapAlloc dt=76 heapalloc_value=106143904 +HeapAlloc dt=50 heapalloc_value=106274976 +HeapAlloc dt=113 heapalloc_value=106633504 +HeapAlloc dt=110 heapalloc_value=107036320 +HeapAlloc dt=95 heapalloc_value=107351072 +HeapAlloc dt=80 heapalloc_value=107702048 +GCSweepBegin dt=78 stack=28 +GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=2 heapalloc_value=107835936 +HeapAlloc dt=39 heapalloc_value=107904288 +HeapAlloc dt=82 heapalloc_value=108390432 +HeapAlloc dt=230 heapalloc_value=108955808 +HeapAlloc dt=126 heapalloc_value=109421344 +GCSweepBegin dt=131 stack=28 +GCSweepEnd dt=5 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=3 heapalloc_value=109929504 +GCSweepBegin dt=29 stack=28 +GCSweepEnd dt=4 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=3 heapalloc_value=110038816 +HeapAlloc dt=28 heapalloc_value=110109472 +HeapAlloc dt=93 heapalloc_value=110412672 +HeapAlloc dt=33 heapalloc_value=110547840 +HeapAlloc dt=123 heapalloc_value=111070848 +GCSweepBegin dt=155 stack=28 +GCSweepEnd dt=10 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=3 heapalloc_value=111648640 +GCSweepBegin dt=61 stack=28 +GCSweepEnd dt=8 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=111996800 +GCSweepBegin dt=37 stack=28 +GCSweepEnd dt=5 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=8 heapalloc_value=112149760 +HeapAlloc dt=32 heapalloc_value=112342272 +GCSweepBegin dt=75 stack=28 +GCSweepEnd dt=7 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=5 heapalloc_value=112601856 +HeapAlloc dt=61 heapalloc_value=112923264 +HeapAlloc dt=90 heapalloc_value=113262720 +HeapAlloc dt=88 heapalloc_value=113522304 +HeapAlloc dt=119 heapalloc_value=113967488 +HeapAlloc dt=59 heapalloc_value=114201216 +GCSweepBegin dt=130 stack=27 +EventBatch gen=3 m=169431 time=28114950897743 size=407 +ProcStatus dt=2 p=11 pstatus=1 +GoStatus dt=4 g=51 m=169431 gstatus=2 +GoBlock dt=6 reason_string=15 stack=5 +GoUnblock dt=13 g=51 g_seq=1 stack=0 +GoStart dt=6 g=51 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=4143 reason_string=15 stack=5 +GoStatus dt=1425 g=28 m=18446744073709551615 gstatus=4 +GoUnblock dt=2 g=28 g_seq=1 stack=0 +GoStart dt=7 g=28 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=1758 reason_string=15 stack=5 +GoUnblock dt=3904 g=25 g_seq=9 stack=0 +GoStart dt=9 g=25 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=41 reason_string=15 stack=5 +ProcStop dt=1189 +ProcStart dt=16 p=11 p_seq=1 +GoUnblock dt=1157 g=57 g_seq=21 stack=0 +GoStart dt=6 g=57 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=25 reason_string=15 stack=5 +GoUnblock dt=1614 g=52 g_seq=13 stack=0 +GoStart dt=11 g=52 g_seq=14 +GoLabel dt=4 label_string=4 +GoBlock dt=86 reason_string=15 stack=5 +GoUnblock dt=4771 g=22 g_seq=11 stack=0 +GoStart dt=12 g=22 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=1413 reason_string=15 stack=5 +GoUnblock dt=10 g=22 g_seq=13 stack=0 +GoStart dt=4 g=22 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=39 reason_string=15 stack=5 +ProcStop dt=67 +ProcStart dt=2286 p=11 p_seq=2 +ProcStop dt=95 +ProcStart dt=53 p=0 p_seq=2 +GoUnblock dt=9 g=57 g_seq=33 stack=0 +GoStart dt=8 g=57 g_seq=34 +GoLabel dt=1 label_string=4 +GoBlock dt=37 reason_string=15 stack=5 +GoUnblock dt=20 g=22 g_seq=23 stack=0 +GoStart dt=3 g=22 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=1036 reason_string=15 stack=5 +GoUnblock dt=11 g=22 g_seq=25 stack=0 +GoStart dt=6 g=22 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=2130 reason_string=15 stack=5 +GoUnblock dt=11 g=22 g_seq=27 stack=0 +GoStart dt=7 g=22 g_seq=28 +GoLabel dt=2 label_string=2 +GoBlock dt=1227 reason_string=15 stack=5 +GoUnblock dt=12 g=22 g_seq=29 stack=0 +GoStart dt=6 g=22 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=31 reason_string=15 stack=5 +GoUnblock dt=7 g=22 g_seq=31 stack=0 +GoStart dt=2 g=22 g_seq=32 +GoLabel dt=1 label_string=2 +GoBlock dt=2282 reason_string=15 stack=5 +GoUnblock dt=71 g=29 g_seq=33 stack=0 +GoStart dt=4 g=29 g_seq=34 +GoLabel dt=1 label_string=4 +GoBlock dt=1234 reason_string=15 stack=5 +GoUnblock dt=8 g=29 g_seq=35 stack=0 +GoStart dt=8 g=29 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=18 reason_string=15 stack=5 +ProcStop dt=49 +ProcStart dt=10623 p=11 p_seq=5 +ProcStop dt=54 +ProcStart dt=686 p=11 p_seq=6 +GoStart dt=185 g=127 g_seq=5 +GCMarkAssistBegin dt=71 stack=3 +GoStop dt=67 reason_string=20 stack=9 +GoUnblock dt=15 g=53 g_seq=47 stack=0 +GoStart dt=3 g=53 g_seq=48 +GoLabel dt=1 label_string=2 +GoUnblock dt=661 g=121 g_seq=10 stack=12 +GoUnblock dt=7 g=88 g_seq=5 stack=12 +GoUnblock dt=8 g=87 g_seq=4 stack=12 +GoUnblock dt=2751 g=94 g_seq=10 stack=12 +GoUnblock dt=8 g=106 g_seq=7 stack=12 +GoUnblock dt=8 g=98 g_seq=9 stack=12 +GoBlock dt=18 reason_string=15 stack=5 +GoStart dt=17 g=87 g_seq=5 +GCMarkAssistEnd dt=5 +HeapAlloc dt=202 heapalloc_value=194796248 +GoStop dt=7327 reason_string=16 stack=6 +GoStart dt=68 g=84 g_seq=8 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=29 reason_string=13 stack=11 +ProcStop dt=88 +EventBatch gen=3 m=169428 time=28114950899204 size=756 +ProcStatus dt=2 p=31 pstatus=1 +GoStatus dt=5 g=104 m=169428 gstatus=2 +GCMarkAssistActive dt=1 g=104 +GCMarkAssistEnd dt=2 +HeapAlloc dt=37 heapalloc_value=191110592 +GCMarkAssistBegin dt=21 stack=3 +GoBlock dt=2670 reason_string=13 stack=11 +GoStatus dt=1400 g=22 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=22 g_seq=1 stack=0 +GoStart dt=7 g=22 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=43 reason_string=15 stack=5 +GoUnblock dt=2567 g=70 g_seq=3 stack=0 +GoStart dt=9 g=70 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=329 reason_string=15 stack=5 +GoUnblock dt=97 g=70 g_seq=5 stack=0 +GoStart dt=5 g=70 g_seq=6 +GoLabel dt=3 label_string=2 +GoUnblock dt=1728 g=84 g_seq=3 stack=12 +GoBlock dt=3527 reason_string=15 stack=5 +GoStart dt=4132 g=114 g_seq=2 +GoStatus dt=28 g=115 m=18446744073709551615 gstatus=4 +GoUnblock dt=8 g=115 g_seq=1 stack=10 +GCMarkAssistBegin dt=18 stack=3 +GoBlock dt=196 reason_string=13 stack=11 +GoStart dt=14 g=115 g_seq=2 +GoStatus dt=18 g=102 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=102 g_seq=1 stack=10 +GCMarkAssistBegin dt=13 stack=3 +GoBlock dt=371 reason_string=13 stack=11 +GoUnblock dt=9 g=30 g_seq=11 stack=0 +GoStart dt=6 g=30 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=5520 reason_string=15 stack=5 +GoUnblock dt=8 g=30 g_seq=13 stack=0 +GoStart dt=4 g=30 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=28 reason_string=15 stack=5 +GoUnblock dt=10 g=57 g_seq=37 stack=0 +GoStart dt=3 g=57 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=157 reason_string=15 stack=5 +GoUnblock dt=7 g=57 g_seq=39 stack=0 +GoStart dt=4 g=57 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=140 reason_string=15 stack=5 +GoUnblock dt=10 g=53 g_seq=25 stack=0 +GoStart dt=3 g=53 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=90 reason_string=15 stack=5 +GoUnblock dt=62 g=53 g_seq=27 stack=0 +GoStart dt=4 g=53 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=11 reason_string=15 stack=5 +GoUnblock dt=46 g=53 g_seq=29 stack=0 +GoStart dt=7 g=53 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=51 reason_string=15 stack=5 +ProcStop dt=2236 +ProcStart dt=966 p=35 p_seq=2 +GoStart dt=19 g=81 g_seq=5 +GCMarkAssistEnd dt=7 +HeapAlloc dt=67 heapalloc_value=192133920 +GCMarkAssistBegin dt=46 stack=3 +GoBlock dt=32 reason_string=13 stack=11 +ProcStop dt=57 +ProcStart dt=15 p=35 p_seq=3 +GoUnblock dt=2 g=69 g_seq=23 stack=0 +GoStart dt=2 g=69 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=224 reason_string=15 stack=5 +GoUnblock dt=52 g=69 g_seq=25 stack=0 +GoStart dt=3 g=69 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=289 reason_string=15 stack=5 +GoStart dt=23 g=118 g_seq=2 +GCMarkAssistEnd dt=7 +HeapAlloc dt=21 heapalloc_value=192207648 +GCMarkAssistBegin dt=103 stack=3 +GoBlock dt=18 reason_string=13 stack=11 +GoUnblock dt=48 g=29 g_seq=13 stack=0 +GoStart dt=1 g=29 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=19 reason_string=15 stack=5 +GoUnblock dt=44 g=25 g_seq=23 stack=0 +GoStart dt=6 g=25 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=144 reason_string=15 stack=5 +GoUnblock dt=49 g=29 g_seq=17 stack=0 +GoStart dt=1 g=29 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=777 reason_string=15 stack=5 +GoUnblock dt=56 g=52 g_seq=31 stack=0 +GoStart dt=3 g=52 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=27 g=51 g_seq=33 stack=0 +GoStart dt=5 g=51 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=12 reason_string=15 stack=5 +GoUnblock dt=13 g=51 g_seq=35 stack=0 +GoStart dt=4 g=51 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=226 reason_string=15 stack=5 +GoUnblock dt=7 g=51 g_seq=37 stack=0 +GoStart dt=4 g=51 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=3928 reason_string=15 stack=5 +GoUnblock dt=14 g=51 g_seq=39 stack=0 +GoStart dt=3 g=51 g_seq=40 +GoLabel dt=3 label_string=2 +GoBlock dt=214 reason_string=15 stack=5 +GoUnblock dt=5 g=51 g_seq=41 stack=0 +GoStart dt=1 g=51 g_seq=42 +GoLabel dt=1 label_string=2 +GoBlock dt=305 reason_string=15 stack=5 +GoUnblock dt=8 g=51 g_seq=43 stack=0 +GoStart dt=5 g=51 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +ProcStop dt=47 +ProcStart dt=5058 p=35 p_seq=4 +GoUnblock dt=20 g=52 g_seq=51 stack=0 +GoStart dt=188 g=52 g_seq=52 +GoLabel dt=1 label_string=2 +GoBlock dt=33 reason_string=15 stack=5 +GoUnblock dt=9 g=52 g_seq=53 stack=0 +GoStart dt=4 g=52 g_seq=54 +GoLabel dt=1 label_string=2 +GoBlock dt=12 reason_string=15 stack=5 +GoStart dt=14 g=126 g_seq=3 +GCMarkAssistEnd dt=7 +HeapAlloc dt=2068 heapalloc_value=192592600 +GoStop dt=31 reason_string=16 stack=4 +GoUnblock dt=10 g=30 g_seq=39 stack=0 +GoStart dt=4 g=30 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=54 reason_string=15 stack=5 +GoStart dt=708 g=121 g_seq=9 +GoBlock dt=49 reason_string=13 stack=11 +GoStart dt=18 g=90 g_seq=5 +GCMarkAssistBegin dt=12 stack=3 +GoBlock dt=39 reason_string=13 stack=11 +GoUnblock dt=15 g=71 g_seq=31 stack=0 +GoStart dt=4 g=71 g_seq=32 +GoLabel dt=2 label_string=2 +GoBlock dt=1101 reason_string=15 stack=5 +GoUnblock dt=13 g=71 g_seq=33 stack=0 +GoStart dt=4 g=71 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=27 reason_string=15 stack=5 +GoUnblock dt=18 g=14 g_seq=54 stack=0 +GoStart dt=4 g=14 g_seq=55 +GoLabel dt=2 label_string=2 +GoUnblock dt=2171 g=94 g_seq=8 stack=12 +GoBlock dt=28 reason_string=15 stack=5 +GoStart dt=11 g=94 g_seq=9 +GCMarkAssistEnd dt=6 +HeapAlloc dt=42 heapalloc_value=193665752 +GCMarkAssistBegin dt=100 stack=3 +GoBlock dt=30 reason_string=13 stack=11 +GoStart dt=13 g=106 g_seq=6 +HeapAlloc dt=99 heapalloc_value=193977048 +GCMarkAssistBegin dt=21 stack=3 +GoBlock dt=30 reason_string=13 stack=11 +GoStart dt=16 g=92 g_seq=4 +GCMarkAssistEnd dt=6 +HeapAlloc dt=884 heapalloc_value=195205848 +GoStop dt=3270 reason_string=16 stack=4 +GoStart dt=29 g=97 g_seq=6 +GCMarkAssistEnd dt=6 +HeapAlloc dt=42 heapalloc_value=195795408 +GCMarkAssistBegin dt=3026 stack=3 +GoBlock dt=85 reason_string=10 stack=18 +ProcStop dt=99 +EventBatch gen=3 m=169426 time=28114950897488 size=116 +ProcStatus dt=1 p=32 pstatus=1 +GoStatus dt=2 g=90 m=169426 gstatus=2 +GCMarkAssistActive dt=1 g=90 +GCMarkAssistEnd dt=3 +HeapAlloc dt=47 heapalloc_value=190627264 +GCMarkAssistBegin dt=51 stack=3 +GoBlock dt=2393 reason_string=13 stack=11 +GoStart dt=1449 g=125 g_seq=2 +GoStatus dt=26 g=127 m=18446744073709551615 gstatus=4 +GoUnblock dt=16 g=127 g_seq=1 stack=10 +GCMarkAssistBegin dt=17 stack=3 +GoStop dt=6909 reason_string=20 stack=9 +GoStart dt=20 g=125 g_seq=3 +GoBlock dt=2101 reason_string=13 stack=11 +GoUnblock dt=2575 g=71 g_seq=11 stack=0 +GoStart dt=8 g=71 g_seq=12 +GoLabel dt=3 label_string=4 +GoBlock dt=44 reason_string=15 stack=5 +GoStart dt=20 g=82 g_seq=7 +GoBlock dt=367 reason_string=13 stack=11 +GoUnblock dt=11 g=22 g_seq=9 stack=0 +GoStart dt=4 g=22 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=3492 reason_string=15 stack=5 +ProcStop dt=9 +EventBatch gen=3 m=169425 time=28114950900302 size=349 +ProcStatus dt=2 p=10 pstatus=1 +GoStatus dt=2 g=70 m=169425 gstatus=2 +GoBlock dt=8 reason_string=15 stack=5 +GoUnblock dt=15 g=70 g_seq=1 stack=0 +GoStart dt=5 g=70 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=5604 reason_string=15 stack=5 +GoUnblock dt=33 g=29 g_seq=3 stack=0 +GoStart dt=5 g=29 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=1191 reason_string=15 stack=5 +GoUnblock dt=9 g=29 g_seq=5 stack=0 +GoStart dt=5 g=29 g_seq=6 +GoLabel dt=2 label_string=2 +GoBlock dt=1935 reason_string=15 stack=5 +GoUnblock dt=15 g=51 g_seq=11 stack=0 +GoStart dt=5 g=51 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=307 reason_string=15 stack=5 +ProcStop dt=4189 +ProcStart dt=15 p=10 p_seq=1 +GoUnblock dt=10 g=69 g_seq=17 stack=0 +GoStart dt=4 g=69 g_seq=18 +GoLabel dt=1 label_string=2 +GoUnblock dt=780 g=93 g_seq=3 stack=12 +GoBlock dt=6076 reason_string=15 stack=5 +GoUnblock dt=11 g=69 g_seq=19 stack=0 +GoStart dt=4 g=69 g_seq=20 +GoLabel dt=3 label_string=2 +GoUnblock dt=93 g=98 g_seq=5 stack=12 +GoBlock dt=5034 reason_string=15 stack=5 +GoUnblock dt=14 g=58 g_seq=25 stack=0 +GoStart dt=5 g=58 g_seq=26 +GoLabel dt=2 label_string=2 +GoBlock dt=1253 reason_string=15 stack=5 +GoUnblock dt=6 g=58 g_seq=27 stack=0 +GoStart dt=4 g=58 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=1031 reason_string=15 stack=5 +GoUnblock dt=6 g=58 g_seq=29 stack=0 +GoStart dt=4 g=58 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=17 reason_string=15 stack=5 +GoUnblock dt=24 g=52 g_seq=33 stack=0 +GoStart dt=6 g=52 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=321 reason_string=15 stack=5 +GoUnblock dt=75 g=29 g_seq=27 stack=0 +GoStart dt=4 g=29 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=248 reason_string=15 stack=5 +GoUnblock dt=61 g=57 g_seq=47 stack=0 +GoStart dt=4 g=57 g_seq=48 +GoLabel dt=1 label_string=4 +GoBlock dt=794 reason_string=15 stack=5 +ProcStop dt=41 +ProcStart dt=15678 p=21 p_seq=3 +GoStart dt=22 g=88 g_seq=6 +GCMarkAssistEnd dt=9 +HeapAlloc dt=84 heapalloc_value=194730712 +GoStop dt=2177 reason_string=16 stack=6 +GoStart dt=2495 g=88 g_seq=7 +GCMarkAssistBegin dt=19 stack=3 +GoBlock dt=37 reason_string=10 stack=18 +GoStart dt=15 g=126 g_seq=6 +GCMarkAssistEnd dt=5 +HeapAlloc dt=27 heapalloc_value=196114896 +GCMarkAssistBegin dt=18 stack=3 +GoBlock dt=30 reason_string=10 stack=18 +GoStart dt=15 g=98 g_seq=10 +GCMarkAssistEnd dt=6 +HeapAlloc dt=48 heapalloc_value=196155856 +GoStop dt=6168 reason_string=16 stack=6 +GoStart dt=156 g=98 g_seq=11 +GCMarkAssistBegin dt=9 stack=3 +GoBlock dt=27 reason_string=10 stack=18 +GoStart dt=27 g=94 g_seq=12 +GCMarkAssistBegin dt=13 stack=3 +GoBlock dt=35 reason_string=10 stack=18 +ProcStop dt=55 +ProcStart dt=14725 p=13 p_seq=1 +GoStart dt=171 g=112 g_seq=9 +GCMarkAssistEnd dt=6 +GCSweepBegin dt=222 stack=27 +EventBatch gen=3 m=169424 time=28114950894869 size=176 +ProcStatus dt=1 p=23 pstatus=3 +GoStatus dt=2 g=131 m=169424 gstatus=3 +GoSyscallEnd dt=1 +GoBlock dt=64 reason_string=15 stack=2 +GoUnblock dt=2260 g=67 g_seq=1 stack=0 +GoStart dt=6 g=67 g_seq=2 +GoLabel dt=2 label_string=4 +GoBlock dt=530 reason_string=15 stack=5 +GoUnblock dt=12 g=69 g_seq=3 stack=0 +GoStart dt=5 g=69 g_seq=4 +GoLabel dt=1 label_string=2 +GoUnblock dt=2455 g=90 g_seq=1 stack=12 +GoBlock dt=20 reason_string=15 stack=5 +GoUnblock dt=16 g=69 g_seq=5 stack=0 +GoStart dt=7 g=69 g_seq=6 +GoLabel dt=1 label_string=2 +GoUnblock dt=493 g=120 g_seq=2 stack=12 +GoBlock dt=1777 reason_string=15 stack=5 +GoUnblock dt=832 g=69 g_seq=7 stack=0 +GoStart dt=9 g=69 g_seq=8 +GoLabel dt=2 label_string=2 +GoBlock dt=5425 reason_string=15 stack=5 +GoUnblock dt=15 g=69 g_seq=9 stack=0 +GoStart dt=4 g=69 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=1370 reason_string=15 stack=5 +ProcStop dt=2533 +ProcStart dt=11 p=23 p_seq=1 +GoUnblock dt=3354 g=54 g_seq=17 stack=0 +GoStart dt=7 g=54 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=29 reason_string=15 stack=5 +GoUnblock dt=25 g=54 g_seq=19 stack=0 +GoStart dt=5 g=54 g_seq=20 +GoLabel dt=2 label_string=2 +GoBlock dt=232 reason_string=15 stack=5 +GoUnblock dt=11 g=54 g_seq=21 stack=0 +GoStart dt=7 g=54 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=293 reason_string=15 stack=5 +ProcStop dt=11 +EventBatch gen=3 m=169423 time=28114950894865 size=525 +ProcStatus dt=2 p=30 pstatus=1 +GoStatus dt=4 g=87 m=169423 gstatus=2 +GCMarkAssistActive dt=1 g=87 +GCMarkAssistEnd dt=2 +HeapAlloc dt=98 heapalloc_value=189963712 +GoStop dt=56 reason_string=16 stack=6 +GoUnblock dt=20 g=131 g_seq=1 stack=0 +GoStart dt=7 g=131 g_seq=2 +GoSyscallBegin dt=39 p_seq=1 stack=7 +GoSyscallEnd dt=304 +GoSyscallBegin dt=19 p_seq=2 stack=7 +GoSyscallEnd dt=59 +GoSyscallBegin dt=15 p_seq=3 stack=7 +GoSyscallEnd dt=52 +GoSyscallBegin dt=11 p_seq=4 stack=7 +GoSyscallEnd dt=50 +GoSyscallBegin dt=8 p_seq=5 stack=7 +GoSyscallEnd dt=48 +GoSyscallBegin dt=10 p_seq=6 stack=7 +GoSyscallEnd dt=54 +GoSyscallBegin dt=13 p_seq=7 stack=7 +GoSyscallEnd dt=51 +GoSyscallBegin dt=12 p_seq=8 stack=7 +GoSyscallEnd dt=49 +GoSyscallBegin dt=16 p_seq=9 stack=7 +GoSyscallEnd dt=245 +GoSyscallBegin dt=12 p_seq=10 stack=7 +GoSyscallEnd dt=49 +GoSyscallBegin dt=10 p_seq=11 stack=7 +GoSyscallEnd dt=49 +GoSyscallBegin dt=10 p_seq=12 stack=7 +GoSyscallEnd dt=48 +GoSyscallBegin dt=6 p_seq=13 stack=7 +GoSyscallEnd dt=52 +GoStop dt=24 reason_string=16 stack=8 +GoUnblock dt=9 g=14 g_seq=1 stack=0 +GoStart dt=5 g=14 g_seq=2 +GoLabel dt=1 label_string=2 +GoUnblock dt=2948 g=107 g_seq=1 stack=12 +GoBlock dt=2891 reason_string=15 stack=5 +GoUnblock dt=11 g=14 g_seq=3 stack=0 +GoStart dt=5 g=14 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=1138 reason_string=15 stack=5 +GoUnblock dt=22 g=51 g_seq=5 stack=0 +GoStart dt=5 g=51 g_seq=6 +GoLabel dt=1 label_string=2 +GoUnblock dt=451 g=82 g_seq=3 stack=12 +GoBlock dt=460 reason_string=15 stack=5 +GoUnblock dt=4052 g=54 g_seq=5 stack=0 +GoStart dt=11 g=54 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=72 reason_string=15 stack=5 +GoUnblock dt=1333 g=57 g_seq=15 stack=0 +GoStart dt=8 g=57 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=283 reason_string=15 stack=5 +GoUnblock dt=1185 g=57 g_seq=19 stack=0 +GoStart dt=7 g=57 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=134 reason_string=15 stack=5 +GoUnblock dt=1144 g=53 g_seq=11 stack=0 +GoStart dt=6 g=53 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=372 reason_string=15 stack=5 +GoUnblock dt=16 g=53 g_seq=13 stack=0 +GoStart dt=7 g=53 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=8581 reason_string=15 stack=5 +ProcStop dt=76 +ProcStart dt=22 p=30 p_seq=14 +GoUnblock dt=3 g=72 g_seq=31 stack=0 +GoStart dt=7 g=72 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=46 reason_string=15 stack=5 +GoUnblock dt=63 g=23 g_seq=31 stack=0 +GoStart dt=7 g=23 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=34 reason_string=15 stack=5 +GoUnblock dt=14 g=23 g_seq=33 stack=0 +GoStart dt=4 g=23 g_seq=34 +GoLabel dt=2 label_string=2 +GoBlock dt=47 reason_string=15 stack=5 +GoUnblock dt=74 g=53 g_seq=19 stack=0 +GoStart dt=6 g=53 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=154 reason_string=15 stack=5 +GoStatus dt=91 g=56 m=18446744073709551615 gstatus=4 +GoUnblock dt=2 g=56 g_seq=1 stack=0 +GoStart dt=43 g=56 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=45 reason_string=15 stack=5 +GoUnblock dt=65 g=53 g_seq=23 stack=0 +GoStart dt=8 g=53 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=16 reason_string=15 stack=5 +ProcStop dt=2526 +ProcStart dt=208 p=30 p_seq=15 +GoUnblock dt=8 g=53 g_seq=37 stack=0 +GoStart dt=5 g=53 g_seq=38 +GoLabel dt=1 label_string=4 +GoBlock dt=694 reason_string=15 stack=5 +GoUnblock dt=14 g=53 g_seq=39 stack=0 +GoStart dt=4 g=53 g_seq=40 +GoLabel dt=3 label_string=2 +GoBlock dt=336 reason_string=15 stack=5 +GoUnblock dt=52 g=53 g_seq=41 stack=0 +GoStart dt=4 g=53 g_seq=42 +GoLabel dt=1 label_string=4 +GoUnblock dt=449 g=118 g_seq=1 stack=12 +GoBlock dt=17 reason_string=15 stack=5 +GoUnblock dt=65 g=24 g_seq=31 stack=0 +GoStart dt=6 g=24 g_seq=32 +GoLabel dt=2 label_string=4 +GoBlock dt=56 reason_string=15 stack=5 +GoUnblock dt=54 g=24 g_seq=33 stack=0 +GoStart dt=5 g=24 g_seq=34 +GoLabel dt=1 label_string=4 +GoBlock dt=489 reason_string=15 stack=5 +GoUnblock dt=9 g=24 g_seq=35 stack=0 +GoStart dt=4 g=24 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=1307 reason_string=15 stack=5 +ProcStop dt=84 +ProcStart dt=23944 p=15 p_seq=1 +GoStart dt=174 g=108 g_seq=3 +GCMarkAssistBegin dt=25 stack=3 +GoBlock dt=59 reason_string=10 stack=18 +ProcStop dt=71 +EventBatch gen=3 m=169421 time=28114950900230 size=330 +ProcStatus dt=1 p=33 pstatus=1 +GoStatus dt=5 g=81 m=169421 gstatus=2 +GCMarkAssistActive dt=3 g=81 +GoBlock dt=7 reason_string=13 stack=11 +GoStatus dt=1543 g=57 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=57 g_seq=1 stack=0 +GoStart dt=10 g=57 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=123 reason_string=15 stack=5 +GoStatus dt=1345 g=58 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=58 g_seq=1 stack=0 +GoStart dt=5 g=58 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=154 reason_string=15 stack=5 +GoUnblock dt=5938 g=54 g_seq=7 stack=0 +GoStart dt=7 g=54 g_seq=8 +GoLabel dt=1 label_string=4 +GoBlock dt=93 reason_string=15 stack=5 +GoStart dt=1331 g=97 g_seq=2 +GoStatus dt=26 g=93 m=18446744073709551615 gstatus=4 +GoUnblock dt=6 g=93 g_seq=1 stack=10 +GCMarkAssistBegin dt=18 stack=3 +GCMarkAssistEnd dt=1894 +HeapAlloc dt=57 heapalloc_value=191872448 +GCMarkAssistBegin dt=26 stack=3 +GoBlock dt=46 reason_string=13 stack=11 +GoUnblock dt=2442 g=52 g_seq=19 stack=0 +GoStart dt=14 g=52 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=767 reason_string=15 stack=5 +ProcStop dt=2248 +ProcStart dt=24 p=33 p_seq=1 +GoUnblock dt=8 g=72 g_seq=27 stack=0 +GoStart dt=7 g=72 g_seq=28 +GoLabel dt=1 label_string=4 +GoUnblock dt=172 g=119 g_seq=3 stack=12 +GoBlock dt=1629 reason_string=15 stack=5 +GoUnblock dt=71 g=28 g_seq=9 stack=0 +GoStart dt=7 g=28 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=276 reason_string=15 stack=5 +GoUnblock dt=72 g=28 g_seq=11 stack=0 +GoStart dt=4 g=28 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=2016 reason_string=15 stack=5 +GoUnblock dt=16 g=28 g_seq=13 stack=0 +GoStart dt=7 g=28 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=6712 reason_string=15 stack=5 +ProcStop dt=63 +ProcStart dt=20808 p=14 p_seq=1 +GoStart dt=205 g=89 g_seq=7 +GCMarkAssistEnd dt=10 +HeapAlloc dt=64 heapalloc_value=196245968 +GoStop dt=6073 reason_string=16 stack=6 +GoStart dt=21 g=89 g_seq=8 +GCMarkAssistBegin dt=15 stack=3 +GoBlock dt=38 reason_string=10 stack=18 +ProcStop dt=129 +ProcStart dt=13557 p=11 p_seq=7 +GoStart dt=202 g=116 g_seq=12 +GCMarkAssistEnd dt=10 +GCSweepBegin dt=25 stack=28 +GCSweepEnd dt=12 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=114760576 +GCSweepBegin dt=70 stack=28 +GCSweepEnd dt=5 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=1 heapalloc_value=114785152 +GCSweepBegin dt=353 stack=27 +EventBatch gen=3 m=169420 time=28114950896337 size=112 +ProcStatus dt=2 p=17 pstatus=1 +GoStatus dt=1 g=84 m=169420 gstatus=2 +GCMarkAssistActive dt=1 g=84 +GCMarkAssistEnd dt=3 +HeapAlloc dt=20 heapalloc_value=190365120 +GCMarkAssistBegin dt=42 stack=3 +GoStop dt=861 reason_string=20 stack=9 +GoStart dt=142 g=126 g_seq=1 +GoBlock dt=2538 reason_string=13 stack=11 +GoUnblock dt=1653 g=30 g_seq=1 stack=0 +GoStart dt=7 g=30 g_seq=2 +GoLabel dt=2 label_string=4 +GoBlock dt=6064 reason_string=15 stack=5 +GoUnblock dt=1633 g=25 g_seq=11 stack=0 +GoStart dt=8 g=25 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=4927 reason_string=15 stack=5 +GoUnblock dt=3569 g=67 g_seq=11 stack=0 +GoStart dt=7 g=67 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=1289 reason_string=15 stack=5 +GoUnblock dt=73 g=67 g_seq=13 stack=0 +GoStart dt=4 g=67 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=46 reason_string=15 stack=5 +ProcStop dt=52 +EventBatch gen=3 m=169419 time=28114950898971 size=132 +ProcStatus dt=2 p=13 pstatus=1 +GoStatus dt=2 g=30 m=169419 gstatus=2 +GoBlock dt=7 reason_string=15 stack=5 +GoUnblock dt=2697 g=72 g_seq=1 stack=0 +GoStart dt=8 g=72 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=969 reason_string=15 stack=5 +GoStart dt=2978 g=95 g_seq=2 +GoStatus dt=32 g=88 m=18446744073709551615 gstatus=4 +GoUnblock dt=7 g=88 g_seq=1 stack=10 +GCMarkAssistBegin dt=18 stack=3 +GoStop dt=1258 reason_string=20 stack=9 +GoStart dt=17 g=88 g_seq=2 +GoStatus dt=27 g=113 m=18446744073709551615 gstatus=4 +GoUnblock dt=5 g=113 g_seq=1 stack=10 +GCMarkAssistBegin dt=12 stack=3 +GoStop dt=1797 reason_string=20 stack=9 +GoStart dt=18 g=88 g_seq=3 +GoStop dt=2883 reason_string=20 stack=9 +GoUnblock dt=14 g=70 g_seq=7 stack=0 +GoStart dt=5 g=70 g_seq=8 +GoLabel dt=3 label_string=2 +GoBlock dt=5294 reason_string=15 stack=5 +GoStart dt=14 g=123 g_seq=5 +GoBlock dt=18 reason_string=13 stack=11 +ProcStop dt=16 +EventBatch gen=3 m=169418 time=28114950895095 size=398 +ProcStatus dt=1 p=35 pstatus=2 +ProcStart dt=2 p=35 p_seq=1 +GoStart dt=38 g=87 g_seq=1 +HeapAlloc dt=103 heapalloc_value=190086592 +GCMarkAssistBegin dt=64 stack=3 +GCMarkAssistEnd dt=3228 +HeapAlloc dt=76 heapalloc_value=190995904 +GCMarkAssistBegin dt=149 stack=3 +GoBlock dt=3823 reason_string=13 stack=11 +GoStart dt=1406 g=82 g_seq=4 +GCMarkAssistEnd dt=12 +HeapAlloc dt=82 heapalloc_value=191618496 +GCMarkAssistBegin dt=75 stack=3 +GoStop dt=4342 reason_string=20 stack=9 +GoStart dt=17 g=82 g_seq=5 +GoStop dt=987 reason_string=20 stack=9 +GoStart dt=26 g=82 g_seq=6 +GoStop dt=3601 reason_string=20 stack=9 +GoUnblock dt=14 g=58 g_seq=17 stack=0 +GoStart dt=3 g=58 g_seq=18 +GoLabel dt=3 label_string=2 +GoBlock dt=1524 reason_string=15 stack=5 +GoUnblock dt=23 g=25 g_seq=15 stack=0 +GoStart dt=8 g=25 g_seq=16 +GoLabel dt=3 label_string=2 +GoBlock dt=7942 reason_string=15 stack=5 +ProcStop dt=2920 +ProcStart dt=69 p=31 p_seq=1 +GoUnblock dt=7 g=67 g_seq=25 stack=0 +GoStart dt=5 g=67 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=1990 reason_string=15 stack=5 +GoUnblock dt=110 g=67 g_seq=29 stack=0 +GoStart dt=6 g=67 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=39 reason_string=15 stack=5 +GoUnblock dt=64 g=52 g_seq=29 stack=0 +GoStart dt=1 g=52 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=40 reason_string=15 stack=5 +GoUnblock dt=72 g=29 g_seq=19 stack=0 +GoStart dt=7 g=29 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=65 reason_string=15 stack=5 +GoUnblock dt=1007 g=23 g_seq=43 stack=0 +GoStart dt=8 g=23 g_seq=44 +GoLabel dt=1 label_string=4 +GoBlock dt=1633 reason_string=15 stack=5 +GoUnblock dt=7 g=23 g_seq=45 stack=0 +GoStart dt=160 g=23 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=16 reason_string=15 stack=5 +ProcStop dt=31 +ProcStart dt=8279 p=26 p_seq=2 +GoStart dt=216 g=103 g_seq=3 +GCMarkAssistBegin dt=19 stack=3 +GoBlock dt=41 reason_string=13 stack=11 +GoUnblock dt=11 g=25 g_seq=47 stack=0 +GoStart dt=3 g=25 g_seq=48 +GoLabel dt=1 label_string=2 +GoBlock dt=1274 reason_string=15 stack=5 +ProcStop dt=46 +ProcStart dt=1294 p=26 p_seq=3 +GoStart dt=164 g=127 g_seq=6 +GoStop dt=45 reason_string=20 stack=9 +GoStart dt=17 g=127 g_seq=7 +GCMarkAssistEnd dt=1921 +GoStop dt=49 reason_string=16 stack=17 +GoUnblock dt=17 g=22 g_seq=59 stack=0 +GoStart dt=8 g=22 g_seq=60 +GoLabel dt=1 label_string=2 +GoBlock dt=75 reason_string=15 stack=5 +GoStart dt=44 g=83 g_seq=7 +GCMarkAssistEnd dt=4 +GCMarkAssistBegin dt=50 stack=3 +GCMarkAssistEnd dt=27 +HeapAlloc dt=55 heapalloc_value=193551064 +GoStop dt=47 reason_string=16 stack=4 +GoStart dt=30 g=84 g_seq=7 +HeapAlloc dt=82 heapalloc_value=193772248 +HeapAlloc dt=291 heapalloc_value=194239192 +HeapAlloc dt=198 heapalloc_value=194493144 +HeapAlloc dt=7678 heapalloc_value=196524496 +GoStop dt=18 reason_string=16 stack=6 +ProcStop dt=218 +ProcStart dt=2082 p=26 p_seq=4 +ProcStop dt=68 +ProcStart dt=16818 p=14 p_seq=2 +GoStart dt=242 g=118 g_seq=7 +GCMarkAssistEnd dt=8 +GCSweepBegin dt=32 stack=28 +GCSweepEnd dt=11 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=114809728 +GCSweepBegin dt=279 stack=27 +EventBatch gen=3 m=169417 time=28114950894785 size=650 +ProcStatus dt=2 p=18 pstatus=1 +GoStatus dt=2 g=120 m=169417 gstatus=2 +GCMarkAssistActive dt=1 g=120 +GCMarkAssistEnd dt=2 +HeapAlloc dt=26 heapalloc_value=189767104 +GoStop dt=131 reason_string=16 stack=4 +GoStart dt=59 g=120 g_seq=1 +HeapAlloc dt=138 heapalloc_value=190045632 +GCMarkAssistBegin dt=31 stack=3 +GCMarkAssistEnd dt=3339 +HeapAlloc dt=63 heapalloc_value=190938560 +GCMarkAssistBegin dt=150 stack=3 +GoBlock dt=270 reason_string=13 stack=11 +GoUnblock dt=4058 g=57 g_seq=3 stack=0 +GoStart dt=7 g=57 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=902 reason_string=15 stack=5 +GoUnblock dt=4049 g=30 g_seq=3 stack=0 +GoStart dt=8 g=30 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=521 reason_string=15 stack=5 +GoUnblock dt=1581 g=57 g_seq=17 stack=0 +GoStart dt=11 g=57 g_seq=18 +GoLabel dt=3 label_string=4 +GoBlock dt=37 reason_string=15 stack=5 +GoUnblock dt=14 g=69 g_seq=11 stack=0 +GoStart dt=4 g=69 g_seq=12 +GoLabel dt=3 label_string=2 +GoBlock dt=543 reason_string=15 stack=5 +GoUnblock dt=10 g=69 g_seq=13 stack=0 +GoStart dt=6 g=69 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=1813 reason_string=15 stack=5 +ProcStop dt=2875 +ProcStart dt=28 p=18 p_seq=1 +GoUnblock dt=1296 g=54 g_seq=23 stack=0 +GoStart dt=7 g=54 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=1516 reason_string=15 stack=5 +GoUnblock dt=7 g=54 g_seq=25 stack=0 +GoStart dt=5 g=54 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=6851 reason_string=15 stack=5 +GoUnblock dt=71 g=72 g_seq=41 stack=0 +GoStart dt=5 g=72 g_seq=42 +GoLabel dt=1 label_string=4 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=5 g=72 g_seq=43 stack=0 +GoStart dt=3 g=72 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=62 reason_string=15 stack=5 +GoUnblock dt=19 g=72 g_seq=45 stack=0 +GoStart dt=4 g=72 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=3727 reason_string=15 stack=5 +ProcStop dt=69 +ProcStart dt=21 p=18 p_seq=2 +GoUnblock dt=10 g=70 g_seq=15 stack=0 +GoStart dt=3 g=70 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=14 reason_string=15 stack=5 +GoUnblock dt=49 g=70 g_seq=17 stack=0 +GoStart dt=3 g=70 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=2314 reason_string=15 stack=5 +ProcStop dt=46 +ProcStart dt=1398 p=18 p_seq=3 +ProcStop dt=38 +ProcStart dt=4183 p=18 p_seq=4 +GoStart dt=183 g=96 g_seq=4 +GCMarkAssistEnd dt=9 +HeapAlloc dt=36 heapalloc_value=192305952 +GCMarkAssistBegin dt=28 stack=3 +GoBlock dt=1320 reason_string=13 stack=11 +GoUnblock dt=15 g=25 g_seq=45 stack=0 +GoStart dt=7 g=25 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=600 reason_string=15 stack=5 +GoStart dt=13 g=89 g_seq=5 +GCMarkAssistBegin dt=11 stack=3 +GoBlock dt=112 reason_string=13 stack=11 +GoStart dt=14 g=121 g_seq=8 +GoStop dt=1488 reason_string=20 stack=9 +GoUnblock dt=16 g=25 g_seq=49 stack=0 +GoStart dt=7 g=25 g_seq=50 +GoLabel dt=2 label_string=2 +GoUnblock dt=1803 g=115 g_seq=6 stack=12 +GoUnblock dt=5 g=93 g_seq=6 stack=12 +GoUnblock dt=6 g=85 g_seq=5 stack=12 +GoUnblock dt=3 g=104 g_seq=1 stack=12 +GoUnblock dt=6 g=108 g_seq=1 stack=12 +GoUnblock dt=4 g=120 g_seq=4 stack=12 +GoUnblock dt=4 g=126 g_seq=5 stack=12 +GoUnblock dt=7 g=114 g_seq=3 stack=12 +GoUnblock dt=5 g=86 g_seq=4 stack=12 +GoUnblock dt=4 g=110 g_seq=3 stack=12 +GoBlock dt=14 reason_string=15 stack=5 +GoUnblock dt=7 g=25 g_seq=51 stack=0 +GoStart dt=1 g=25 g_seq=52 +GoLabel dt=1 label_string=2 +GoBlock dt=12 reason_string=15 stack=5 +GoStart dt=8 g=115 g_seq=7 +GCMarkAssistEnd dt=6 +HeapAlloc dt=32 heapalloc_value=192838360 +GCMarkAssistBegin dt=55 stack=3 +GoStop dt=1501 reason_string=20 stack=9 +GoUnblock dt=18 g=51 g_seq=51 stack=0 +GoStart dt=6 g=51 g_seq=52 +GoLabel dt=1 label_string=2 +GoUnblock dt=1117 g=105 g_seq=13 stack=12 +GoBlock dt=8 reason_string=15 stack=5 +GoStart dt=8 g=105 g_seq=14 +GCMarkAssistEnd dt=6 +GCMarkAssistBegin dt=27 stack=3 +GoBlock dt=13 reason_string=13 stack=11 +GoStart dt=7 g=86 g_seq=5 +GCMarkAssistEnd dt=6 +HeapAlloc dt=12 heapalloc_value=195148504 +GCMarkAssistBegin dt=65 stack=3 +HeapAlloc dt=22 heapalloc_value=195214040 +GoBlock dt=17 reason_string=10 stack=18 +GoStart dt=2881 g=124 g_seq=5 +HeapAlloc dt=35 heapalloc_value=195517144 +HeapAlloc dt=15 heapalloc_value=195566296 +HeapAlloc dt=61 heapalloc_value=195574224 +HeapAlloc dt=16 heapalloc_value=195631568 +GCMarkAssistBegin dt=23 stack=3 +GoBlock dt=34 reason_string=10 stack=18 +GoStart dt=14 g=90 g_seq=7 +GCMarkAssistEnd dt=5 +HeapAlloc dt=4 heapalloc_value=195697104 +GCMarkAssistBegin dt=58 stack=3 +GoBlock dt=15 reason_string=10 stack=18 +GoStart dt=10 g=96 g_seq=6 +GCMarkAssistEnd dt=3 +GCMarkAssistBegin dt=37 stack=3 +GoBlock dt=16 reason_string=13 stack=11 +GoStart dt=14 g=92 g_seq=5 +GCMarkAssistBegin dt=75 stack=3 +GoBlock dt=25 reason_string=10 stack=18 +GoStart dt=9 g=119 g_seq=6 +GCMarkAssistEnd dt=5 +HeapAlloc dt=20 heapalloc_value=195926480 +GCMarkAssistBegin dt=19 stack=3 +GoBlock dt=14 reason_string=10 stack=18 +GoStart dt=9 g=85 g_seq=6 +GCMarkAssistEnd dt=3 +HeapAlloc dt=38 heapalloc_value=195983824 +GoStop dt=5763 reason_string=16 stack=6 +GoStart dt=15 g=85 g_seq=7 +GCMarkAssistBegin dt=6 stack=3 +GoBlock dt=21 reason_string=10 stack=18 +ProcStop dt=46 +ProcStart dt=17429 p=15 p_seq=2 +GoStart dt=180 g=3 g_seq=2 +EventBatch gen=3 m=169416 time=28114950894874 size=516 +ProcStatus dt=2 p=26 pstatus=1 +GoStatus dt=1 g=98 m=169416 gstatus=2 +GCMarkAssistActive dt=1 g=98 +GCMarkAssistEnd dt=2 +HeapAlloc dt=136 heapalloc_value=190004672 +GoStop dt=29 reason_string=16 stack=4 +GoStart dt=29 g=86 g_seq=1 +GCMarkAssistBegin dt=75 stack=3 +GCMarkAssistEnd dt=8456 +HeapAlloc dt=48 heapalloc_value=191569344 +GoStop dt=32 reason_string=16 stack=4 +GoStart dt=19 g=86 g_seq=2 +GCMarkAssistBegin dt=73 stack=3 +GoStop dt=324 reason_string=20 stack=9 +GoStart dt=11 g=116 g_seq=3 +GoStop dt=270 reason_string=20 stack=9 +GoUnblock dt=14 g=51 g_seq=7 stack=0 +GoStart dt=4 g=51 g_seq=8 +GoLabel dt=3 label_string=2 +GoBlock dt=4139 reason_string=15 stack=5 +GoUnblock dt=9 g=51 g_seq=9 stack=0 +GoStart dt=6 g=51 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=564 reason_string=15 stack=5 +GoUnblock dt=12 g=29 g_seq=7 stack=0 +GoStart dt=4 g=29 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=13475 reason_string=15 stack=5 +ProcStop dt=61 +ProcStart dt=17 p=26 p_seq=1 +GoUnblock dt=6 g=53 g_seq=31 stack=0 +GoStart dt=3 g=53 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=18 reason_string=15 stack=5 +GoUnblock dt=6 g=53 g_seq=33 stack=0 +GoStart dt=4 g=53 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=2291 reason_string=15 stack=5 +GoUnblock dt=8 g=53 g_seq=35 stack=0 +GoStart dt=4 g=53 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=32 reason_string=15 stack=5 +GoUnblock dt=68 g=29 g_seq=9 stack=0 +GoStart dt=4 g=29 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=796 reason_string=15 stack=5 +GoUnblock dt=60 g=29 g_seq=11 stack=0 +GoStart dt=4 g=29 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=643 reason_string=15 stack=5 +GoUnblock dt=61 g=53 g_seq=43 stack=0 +GoStart dt=4 g=53 g_seq=44 +GoLabel dt=1 label_string=4 +GoBlock dt=3485 reason_string=15 stack=5 +GoUnblock dt=10 g=53 g_seq=45 stack=0 +GoStart dt=5 g=53 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=14 reason_string=15 stack=5 +ProcStop dt=38 +ProcStart dt=9443 p=0 p_seq=3 +GoStart dt=226 g=115 g_seq=5 +GoBlock dt=168 reason_string=13 stack=11 +GoUnblock dt=11 g=30 g_seq=37 stack=0 +GoStart dt=6 g=30 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=67 reason_string=15 stack=5 +ProcStop dt=46 +ProcStart dt=1842 p=25 p_seq=6 +GoUnblock dt=12 g=29 g_seq=37 stack=0 +GoStart dt=5 g=29 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=2260 reason_string=15 stack=5 +GoUnblock dt=16 g=29 g_seq=39 stack=0 +GoStart dt=4 g=29 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=19 reason_string=15 stack=5 +GoStart dt=34 g=99 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=55 heapalloc_value=193501912 +GoStop dt=29 reason_string=16 stack=4 +GoUnblock dt=18 g=29 g_seq=41 stack=0 +GoStart dt=7 g=29 g_seq=42 +GoLabel dt=1 label_string=2 +GoBlock dt=10 reason_string=15 stack=5 +GoUnblock dt=14 g=29 g_seq=43 stack=0 +GoStart dt=4 g=29 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=40 reason_string=15 stack=5 +GoStart dt=16 g=111 g_seq=6 +GoBlock dt=37 reason_string=13 stack=11 +GoStart dt=13 g=125 g_seq=6 +GCMarkAssistBegin dt=13 stack=3 +GoBlock dt=34 reason_string=13 stack=11 +GoStart dt=23 g=115 g_seq=8 +GoBlock dt=61 reason_string=13 stack=11 +GoStart dt=27 g=120 g_seq=5 +GCMarkAssistEnd dt=12 +HeapAlloc dt=82 heapalloc_value=194067160 +GoStop dt=22 reason_string=16 stack=4 +GoStart dt=10 g=93 g_seq=7 +GCMarkAssistEnd dt=4 +HeapAlloc dt=663 heapalloc_value=194992856 +GCMarkAssistBegin dt=23 stack=3 +GoBlock dt=12 reason_string=13 stack=11 +GoStart dt=11 g=99 g_seq=7 +GCMarkAssistEnd dt=5 +HeapAlloc dt=4741 heapalloc_value=196180432 +GoStop dt=10 reason_string=16 stack=6 +GoStart dt=19 g=99 g_seq=8 +GCMarkAssistBegin dt=8 stack=3 +GoBlock dt=18 reason_string=10 stack=18 +GoStart dt=9 g=100 g_seq=4 +GCMarkAssistEnd dt=5 +HeapAlloc dt=101 heapalloc_value=196295120 +GoStop dt=6074 reason_string=16 stack=6 +GoStart dt=49 g=100 g_seq=5 +GCMarkAssistBegin dt=10 stack=3 +GoBlock dt=32 reason_string=13 stack=11 +ProcStop dt=67 +ProcStart dt=12947 p=10 p_seq=3 +GoStart dt=200 g=86 g_seq=7 +GoUnblock dt=38 g=124 g_seq=6 stack=30 +GCMarkAssistEnd dt=5 +HeapAlloc dt=90 heapalloc_value=113809792 +HeapAlloc dt=112 heapalloc_value=114160256 +GCSweepBegin dt=694 stack=31 +EventBatch gen=3 m=169415 time=28114950903030 size=633 +ProcStatus dt=1 p=28 pstatus=1 +GoStatus dt=3 g=91 m=169415 gstatus=2 +GCMarkAssistActive dt=1 g=91 +GCMarkAssistEnd dt=2 +HeapAlloc dt=29 heapalloc_value=191479232 +GCMarkAssistBegin dt=84 stack=3 +GoBlock dt=82 reason_string=13 stack=11 +GoStart dt=4920 g=113 g_seq=2 +GoStatus dt=31 g=123 m=18446744073709551615 gstatus=4 +GoUnblock dt=10 g=123 g_seq=1 stack=10 +GCMarkAssistBegin dt=14 stack=3 +GoStop dt=1855 reason_string=20 stack=9 +GoStart dt=15 g=113 g_seq=3 +GoStop dt=352 reason_string=20 stack=9 +GoStart dt=13 g=113 g_seq=4 +GoBlock dt=261 reason_string=13 stack=11 +GoUnblock dt=3404 g=52 g_seq=17 stack=0 +GoStart dt=7 g=52 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=1025 reason_string=15 stack=5 +GoUnblock dt=4703 g=67 g_seq=17 stack=0 +GoStart dt=8 g=67 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=1418 reason_string=15 stack=5 +GoUnblock dt=72 g=23 g_seq=29 stack=0 +GoStart dt=4 g=23 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=307 reason_string=15 stack=5 +GoUnblock dt=85 g=72 g_seq=33 stack=0 +GoStart dt=5 g=72 g_seq=34 +GoLabel dt=3 label_string=4 +GoBlock dt=30 reason_string=15 stack=5 +GoStatus dt=168 g=68 m=18446744073709551615 gstatus=4 +GoUnblock dt=2 g=68 g_seq=1 stack=0 +GoStart dt=64 g=68 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=55 reason_string=15 stack=5 +GoUnblock dt=10 g=68 g_seq=3 stack=0 +GoStart dt=3 g=68 g_seq=4 +GoLabel dt=2 label_string=2 +GoBlock dt=327 reason_string=15 stack=5 +ProcStop dt=80 +ProcStart dt=25 p=28 p_seq=1 +GoUnblock dt=7 g=30 g_seq=17 stack=0 +GoStart dt=4 g=30 g_seq=18 +GoLabel dt=3 label_string=4 +GoBlock dt=2630 reason_string=15 stack=5 +GoUnblock dt=28 g=72 g_seq=39 stack=0 +GoStart dt=12 g=72 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=77 g=30 g_seq=19 stack=0 +GoStart dt=10 g=30 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=3781 reason_string=15 stack=5 +GoUnblock dt=15 g=30 g_seq=21 stack=0 +GoStart dt=5 g=30 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=2537 reason_string=15 stack=5 +GoUnblock dt=55 g=30 g_seq=23 stack=0 +GoStart dt=5 g=30 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=478 reason_string=15 stack=5 +GoUnblock dt=8 g=30 g_seq=25 stack=0 +GoStart dt=4 g=30 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=1039 reason_string=15 stack=5 +GoStart dt=26 g=14 g_seq=37 +GoBlock dt=1631 reason_string=15 stack=5 +GoUnblock dt=22 g=52 g_seq=43 stack=0 +GoStart dt=8 g=52 g_seq=44 +GoLabel dt=3 label_string=2 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=9 g=52 g_seq=45 stack=0 +GoStart dt=3 g=52 g_seq=46 +GoLabel dt=1 label_string=2 +GoBlock dt=17 reason_string=15 stack=5 +GoUnblock dt=6 g=52 g_seq=47 stack=0 +GoStart dt=3 g=52 g_seq=48 +GoLabel dt=1 label_string=2 +GoUnblock dt=217 g=112 g_seq=3 stack=12 +GoBlock dt=298 reason_string=15 stack=5 +GoUnblock dt=8 g=52 g_seq=49 stack=0 +GoStart dt=3 g=52 g_seq=50 +GoLabel dt=1 label_string=2 +GoBlock dt=1919 reason_string=15 stack=5 +GoStart dt=16 g=121 g_seq=6 +GCMarkAssistEnd dt=6 +HeapAlloc dt=1354 heapalloc_value=192363224 +GoStop dt=25 reason_string=16 stack=4 +GoStart dt=16 g=121 g_seq=7 +GCMarkAssistBegin dt=74 stack=3 +GoStop dt=496 reason_string=20 stack=9 +GoUnblock dt=11 g=52 g_seq=55 stack=0 +GoStart dt=4 g=52 g_seq=56 +GoLabel dt=1 label_string=2 +GoUnblock dt=1666 g=94 g_seq=5 stack=12 +GoBlock dt=18 reason_string=15 stack=5 +GoUnblock dt=18 g=30 g_seq=41 stack=0 +GoStart dt=4 g=30 g_seq=42 +GoLabel dt=1 label_string=2 +GoUnblock dt=1362 g=84 g_seq=5 stack=12 +GoUnblock dt=6 g=125 g_seq=4 stack=12 +GoUnblock dt=5 g=118 g_seq=3 stack=12 +GoBlock dt=9 reason_string=15 stack=5 +GoUnblock dt=10 g=30 g_seq=43 stack=0 +GoStart dt=3 g=30 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +GoStart dt=6 g=84 g_seq=6 +GCMarkAssistEnd dt=5 +HeapAlloc dt=24 heapalloc_value=192748248 +GCMarkAssistBegin dt=83 stack=3 +GCMarkAssistEnd dt=1516 +HeapAlloc dt=28 heapalloc_value=193231576 +GoStop dt=27 reason_string=16 stack=6 +GoUnblock dt=14 g=22 g_seq=57 stack=0 +GoStart dt=3 g=22 g_seq=58 +GoLabel dt=1 label_string=2 +GoUnblock dt=16 g=81 g_seq=8 stack=12 +GoBlock dt=10 reason_string=15 stack=5 +GoStart dt=11 g=125 g_seq=5 +GCMarkAssistEnd dt=5 +HeapAlloc dt=16 heapalloc_value=193354456 +GoStop dt=95 reason_string=16 stack=6 +GoUnblock dt=34 g=22 g_seq=61 stack=0 +GoStart dt=1 g=22 g_seq=62 +GoLabel dt=1 label_string=2 +GoUnblock dt=1090 g=99 g_seq=6 stack=12 +GoBlock dt=10 reason_string=15 stack=5 +GoStart dt=8 g=81 g_seq=9 +GCMarkAssistEnd dt=5 +HeapAlloc dt=3528 heapalloc_value=195729872 +GoStop dt=10 reason_string=16 stack=6 +GoStart dt=17 g=81 g_seq=10 +GCMarkAssistBegin dt=9 stack=3 +GoBlock dt=34 reason_string=10 stack=18 +GoStart dt=20 g=121 g_seq=11 +GCMarkAssistEnd dt=4 +HeapAlloc dt=44 heapalloc_value=195852752 +GoStop dt=7425 reason_string=16 stack=6 +ProcStop dt=134 +ProcStart dt=14156 p=12 p_seq=2 +GoStart dt=200 g=84 g_seq=10 +GCMarkAssistEnd dt=6 +GCSweepBegin dt=35 stack=27 +EventBatch gen=3 m=169414 time=28114950903409 size=415 +ProcStatus dt=1 p=19 pstatus=1 +GoStatus dt=1 g=54 m=169414 gstatus=2 +GoBlock dt=7 reason_string=15 stack=5 +GoUnblock dt=2586 g=25 g_seq=5 stack=0 +GoStart dt=8 g=25 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=2605 reason_string=15 stack=5 +GoUnblock dt=1216 g=71 g_seq=3 stack=0 +GoStart dt=7 g=71 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=672 reason_string=15 stack=5 +GoUnblock dt=7231 g=23 g_seq=15 stack=0 +GoStart dt=8 g=23 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=1212 reason_string=15 stack=5 +GoUnblock dt=11 g=23 g_seq=17 stack=0 +GoStart dt=7 g=23 g_seq=18 +GoLabel dt=3 label_string=2 +GoBlock dt=82 reason_string=15 stack=5 +GoUnblock dt=9 g=23 g_seq=19 stack=0 +GoStart dt=6 g=23 g_seq=20 +GoLabel dt=1 label_string=2 +GoBlock dt=162 reason_string=15 stack=5 +ProcStop dt=99 +ProcStart dt=3257 p=19 p_seq=1 +GoUnblock dt=13 g=68 g_seq=5 stack=0 +GoStart dt=10 g=68 g_seq=6 +GoLabel dt=1 label_string=2 +GoBlock dt=43 reason_string=15 stack=5 +GoUnblock dt=12 g=68 g_seq=7 stack=0 +GoStart dt=2 g=68 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=133 reason_string=15 stack=5 +GoUnblock dt=23 g=58 g_seq=23 stack=0 +GoStart dt=6 g=58 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=2822 reason_string=15 stack=5 +GoUnblock dt=11 g=69 g_seq=21 stack=0 +GoStart dt=7 g=69 g_seq=22 +GoLabel dt=2 label_string=2 +GoBlock dt=25 reason_string=15 stack=5 +GoUnblock dt=2937 g=58 g_seq=31 stack=0 +GoStart dt=6 g=58 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=20 reason_string=15 stack=5 +ProcStop dt=60 +ProcStart dt=31 p=19 p_seq=2 +GoUnblock dt=9 g=56 g_seq=7 stack=0 +GoStart dt=6 g=56 g_seq=8 +GoLabel dt=3 label_string=4 +GoBlock dt=949 reason_string=15 stack=5 +ProcStop dt=41 +ProcStart dt=433 p=19 p_seq=3 +ProcStop dt=43 +ProcStart dt=9942 p=11 p_seq=4 +ProcStop dt=50 +ProcStart dt=2351 p=22 p_seq=6 +GoUnblock dt=15 g=30 g_seq=45 stack=0 +GoStart dt=205 g=30 g_seq=46 +GoLabel dt=1 label_string=2 +GoUnblock dt=145 g=113 g_seq=7 stack=12 +GoBlock dt=21 reason_string=15 stack=5 +GoStart dt=10 g=113 g_seq=8 +GCMarkAssistEnd dt=8 +HeapAlloc dt=48 heapalloc_value=192895704 +GCMarkAssistBegin dt=118 stack=3 +GCMarkAssistEnd dt=272 +HeapAlloc dt=20 heapalloc_value=192936664 +HeapAlloc dt=89 heapalloc_value=192953048 +HeapAlloc dt=41 heapalloc_value=192994008 +HeapAlloc dt=92 heapalloc_value=193059544 +HeapAlloc dt=102 heapalloc_value=193108696 +HeapAlloc dt=94 heapalloc_value=193133272 +HeapAlloc dt=42 heapalloc_value=193141464 +HeapAlloc dt=31 heapalloc_value=193207000 +GCMarkAssistBegin dt=142 stack=3 +GoBlock dt=114 reason_string=13 stack=11 +GoStart dt=179 g=109 g_seq=5 +GCMarkAssistEnd dt=8 +GCMarkAssistBegin dt=54 stack=3 +GCMarkAssistEnd dt=720 +HeapAlloc dt=23 heapalloc_value=194427608 +HeapAlloc dt=456 heapalloc_value=195001048 +GCMarkAssistBegin dt=18 stack=3 +GoBlock dt=22 reason_string=13 stack=11 +GoStart dt=23 g=113 g_seq=10 +GCMarkAssistEnd dt=3 +HeapAlloc dt=54 heapalloc_value=195099352 +GoStop dt=6390 reason_string=16 stack=6 +GoStart dt=23 g=113 g_seq=11 +GCMarkAssistBegin dt=6 stack=3 +GoBlock dt=21 reason_string=10 stack=18 +GoStart dt=33 g=101 g_seq=6 +GCMarkAssistEnd dt=6 +HeapAlloc dt=29 heapalloc_value=196409808 +GCMarkAssistBegin dt=22 stack=3 +GoBlock dt=52 reason_string=10 stack=18 +ProcStop dt=102 +EventBatch gen=3 m=169413 time=28114950897164 size=752 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=6 g=67 m=169413 gstatus=2 +GoBlock dt=11 reason_string=15 stack=5 +GoUnblock dt=18 g=25 g_seq=1 stack=0 +GoStart dt=7 g=25 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=1315 reason_string=15 stack=5 +GoUnblock dt=11 g=25 g_seq=3 stack=0 +GoStart dt=6 g=25 g_seq=4 +GoLabel dt=1 label_string=2 +GoUnblock dt=4173 g=106 g_seq=1 stack=12 +GoBlock dt=1258 reason_string=15 stack=5 +GoUnblock dt=4804 g=30 g_seq=5 stack=0 +GoStart dt=7 g=30 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=541 reason_string=15 stack=5 +GoUnblock dt=30 g=30 g_seq=7 stack=0 +GoStart dt=6 g=30 g_seq=8 +GoLabel dt=3 label_string=2 +GoBlock dt=3873 reason_string=15 stack=5 +GoUnblock dt=10 g=30 g_seq=9 stack=0 +GoStart dt=5 g=30 g_seq=10 +GoLabel dt=3 label_string=2 +GoBlock dt=3107 reason_string=15 stack=5 +GoUnblock dt=3672 g=14 g_seq=15 stack=0 +GoStart dt=6 g=14 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=442 reason_string=15 stack=5 +GoStart dt=32 g=83 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=49 heapalloc_value=191962560 +GCMarkAssistBegin dt=108 stack=3 +GoStop dt=885 reason_string=20 stack=9 +GoStart dt=14 g=83 g_seq=5 +GoBlock dt=21 reason_string=13 stack=11 +ProcStop dt=93 +ProcStart dt=38 p=0 p_seq=1 +GoUnblock dt=7 g=53 g_seq=17 stack=0 +GoStart dt=2 g=53 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=31 reason_string=15 stack=5 +ProcStop dt=89 +ProcStart dt=45 p=11 p_seq=3 +GoUnblock dt=6 g=23 g_seq=35 stack=0 +GoStart dt=14 g=23 g_seq=36 +GoLabel dt=3 label_string=4 +GoBlock dt=2881 reason_string=15 stack=5 +GoUnblock dt=72 g=25 g_seq=17 stack=0 +GoStart dt=6 g=25 g_seq=18 +GoLabel dt=1 label_string=4 +GoBlock dt=19 reason_string=15 stack=5 +GoUnblock dt=58 g=25 g_seq=19 stack=0 +GoStart dt=3 g=25 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=13 reason_string=15 stack=5 +GoStart dt=16 g=94 g_seq=4 +GoBlock dt=356 reason_string=13 stack=11 +GoUnblock dt=80 g=52 g_seq=27 stack=0 +GoStart dt=9 g=52 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=2325 reason_string=15 stack=5 +GoUnblock dt=57 g=67 g_seq=31 stack=0 +GoStart dt=4 g=67 g_seq=32 +GoLabel dt=1 label_string=4 +GoBlock dt=2043 reason_string=15 stack=5 +GoUnblock dt=9 g=67 g_seq=33 stack=0 +GoStart dt=171 g=67 g_seq=34 +GoLabel dt=5 label_string=2 +GoBlock dt=21 reason_string=15 stack=5 +ProcStop dt=60 +ProcStart dt=1735 p=25 p_seq=4 +GoUnblock dt=61 g=22 g_seq=39 stack=0 +GoStart dt=178 g=22 g_seq=40 +GoLabel dt=1 label_string=4 +GoBlock dt=66 reason_string=15 stack=5 +GoUnblock dt=8 g=22 g_seq=41 stack=0 +GoStart dt=4 g=22 g_seq=42 +GoLabel dt=1 label_string=2 +GoBlock dt=975 reason_string=15 stack=5 +ProcStop dt=1192 +ProcStart dt=347 p=25 p_seq=5 +GoUnblock dt=11 g=131 g_seq=6 stack=0 +GoStart dt=145 g=131 g_seq=7 +GoBlock dt=21 reason_string=15 stack=2 +GoUnblock dt=30 g=14 g_seq=38 stack=0 +GoStart dt=4 g=14 g_seq=39 +GoLabel dt=1 label_string=2 +GoBlock dt=65 reason_string=15 stack=5 +GoStart dt=26 g=130 g_seq=1 +ProcStatus dt=380 p=38 pstatus=2 +ProcStatus dt=4 p=39 pstatus=2 +ProcStatus dt=4 p=40 pstatus=2 +ProcStatus dt=3 p=41 pstatus=2 +ProcStatus dt=5 p=42 pstatus=2 +ProcStatus dt=5 p=43 pstatus=2 +ProcStatus dt=2 p=44 pstatus=2 +ProcStatus dt=3 p=45 pstatus=2 +ProcStatus dt=4 p=46 pstatus=2 +GoStop dt=1488 reason_string=16 stack=15 +GoUnblock dt=17 g=51 g_seq=45 stack=0 +GoStart dt=3 g=51 g_seq=46 +GoLabel dt=3 label_string=2 +GoBlock dt=1337 reason_string=15 stack=5 +GoStart dt=13 g=81 g_seq=7 +GCMarkAssistEnd dt=6 +GCMarkAssistBegin dt=31 stack=3 +GoBlock dt=20 reason_string=13 stack=11 +GoStart dt=5 g=130 g_seq=2 +HeapAlloc dt=98 heapalloc_value=192314072 +GoBlock dt=348 reason_string=12 stack=16 +GoStart dt=31 g=103 g_seq=2 +GCMarkAssistEnd dt=7 +HeapAlloc dt=53 heapalloc_value=192428760 +GoStop dt=173 reason_string=16 stack=6 +GoUnblock dt=18 g=71 g_seq=29 stack=0 +GoStart dt=4 g=71 g_seq=30 +GoLabel dt=3 label_string=2 +GoBlock dt=1289 reason_string=15 stack=5 +GoStart dt=17 g=126 g_seq=4 +GCMarkAssistBegin dt=125 stack=3 +GoBlock dt=23 reason_string=13 stack=11 +ProcStop dt=76 +ProcStart dt=2523 p=0 p_seq=4 +GoUnblock dt=16 g=30 g_seq=47 stack=0 +GoStart dt=196 g=30 g_seq=48 +GoLabel dt=2 label_string=2 +GoUnblock dt=1834 g=125 g_seq=7 stack=12 +GoBlock dt=17 reason_string=15 stack=5 +GoStart dt=14 g=125 g_seq=8 +GCMarkAssistEnd dt=5 +HeapAlloc dt=69 heapalloc_value=194566872 +GoStop dt=2253 reason_string=16 stack=6 +GoStart dt=2080 g=125 g_seq=9 +GCMarkAssistBegin dt=14 stack=3 +GoBlock dt=41 reason_string=10 stack=18 +GoStart dt=13 g=106 g_seq=8 +GCMarkAssistEnd dt=6 +HeapAlloc dt=53 heapalloc_value=196106704 +GoStop dt=6900 reason_string=16 stack=6 +GoStart dt=57 g=121 g_seq=12 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=47 reason_string=10 stack=18 +ProcStop dt=83 +ProcStart dt=11930 p=7 p_seq=7 +GoStart dt=191 g=96 g_seq=8 +GCMarkAssistEnd dt=10 +HeapAlloc dt=59 heapalloc_value=109727392 +HeapAlloc dt=159 heapalloc_value=110336128 +HeapAlloc dt=109 heapalloc_value=110662528 +GCSweepBegin dt=144 stack=28 +GCSweepEnd dt=18 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=3 heapalloc_value=111288448 +GCSweepBegin dt=49 stack=28 +GCSweepEnd dt=14 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=5 heapalloc_value=111591296 +HeapAlloc dt=65 heapalloc_value=111888256 +HeapAlloc dt=228 heapalloc_value=112797056 +HeapAlloc dt=134 heapalloc_value=113322880 +HeapAlloc dt=83 heapalloc_value=113549696 +GCSweepBegin dt=35 stack=28 +GCSweepEnd dt=16 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=113842560 +HeapAlloc dt=75 heapalloc_value=114080128 +HeapAlloc dt=64 heapalloc_value=114307712 +HeapAlloc dt=134 heapalloc_value=114580608 +HeapAlloc dt=77 heapalloc_value=114670464 +GCSweepBegin dt=33 stack=28 +GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=114727808 +GCSweepBegin dt=90 stack=27 +EventBatch gen=3 m=169412 time=28114950898429 size=583 +ProcStatus dt=1 p=36 pstatus=2 +ProcStart dt=2 p=36 p_seq=1 +GoStart dt=401 g=83 g_seq=2 +GoBlock dt=1477 reason_string=13 stack=11 +GoStart dt=1208 g=81 g_seq=2 +GCMarkAssistEnd dt=9 +HeapAlloc dt=57 heapalloc_value=191348160 +GoStop dt=42 reason_string=16 stack=4 +GoStart dt=25 g=81 g_seq=3 +GCMarkAssistBegin dt=394 stack=3 +GoBlock dt=1177 reason_string=13 stack=11 +GoStart dt=28 g=106 g_seq=2 +GCMarkAssistEnd dt=10 +HeapAlloc dt=52 heapalloc_value=191503808 +GCMarkAssistBegin dt=52 stack=3 +GoStop dt=60 reason_string=20 stack=9 +GoUnblock dt=73 g=58 g_seq=3 stack=0 +GoStart dt=6 g=58 g_seq=4 +GoLabel dt=3 label_string=4 +GoBlock dt=2860 reason_string=15 stack=5 +GoUnblock dt=3777 g=24 g_seq=9 stack=0 +GoStart dt=6 g=24 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=41 reason_string=15 stack=5 +GoUnblock dt=1167 g=71 g_seq=9 stack=0 +GoStart dt=7 g=71 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=1396 reason_string=15 stack=5 +GoUnblock dt=1371 g=57 g_seq=23 stack=0 +GoStart dt=7 g=57 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=584 reason_string=15 stack=5 +GoUnblock dt=4657 g=23 g_seq=23 stack=0 +GoStart dt=7 g=23 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=40 reason_string=15 stack=5 +ProcStop dt=82 +ProcStart dt=1505 p=36 p_seq=2 +ProcStop dt=74 +ProcStart dt=19 p=36 p_seq=3 +GoUnblock dt=7 g=23 g_seq=27 stack=0 +GoStart dt=7 g=23 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=122 reason_string=15 stack=5 +GoUnblock dt=58 g=52 g_seq=25 stack=0 +GoStart dt=6 g=52 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=4034 reason_string=15 stack=5 +GoUnblock dt=75 g=14 g_seq=19 stack=0 +GoStart dt=6 g=14 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=2059 reason_string=15 stack=5 +GoUnblock dt=63 g=14 g_seq=21 stack=0 +GoStart dt=4 g=14 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=56 reason_string=15 stack=5 +ProcStop dt=49 +ProcStart dt=20 p=36 p_seq=4 +GoUnblock dt=6 g=67 g_seq=27 stack=0 +GoStart dt=2 g=67 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=13 reason_string=15 stack=5 +ProcStop dt=1721 +ProcStart dt=20316 p=36 p_seq=5 +GoStart dt=197 g=94 g_seq=11 +GCMarkAssistEnd dt=7 +HeapAlloc dt=6672 heapalloc_value=196598224 +GoStop dt=15 reason_string=16 stack=6 +GoStart dt=54 g=106 g_seq=9 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=32 reason_string=10 stack=18 +GoStart dt=41 g=103 g_seq=6 +GCMarkAssistBegin dt=15 stack=3 +GoBlock dt=84 reason_string=10 stack=18 +ProcStop dt=43 +ProcStart dt=10888 p=5 p_seq=1 +GoStart dt=189 g=120 g_seq=8 +GCMarkAssistEnd dt=7 +HeapAlloc dt=54 heapalloc_value=106433440 +HeapAlloc dt=94 heapalloc_value=106861728 +GCSweepBegin dt=92 stack=28 +GCSweepEnd dt=13 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=4 heapalloc_value=107301920 +HeapAlloc dt=65 heapalloc_value=107394848 +GCSweepBegin dt=32 stack=28 +GCSweepEnd dt=11 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=2 heapalloc_value=107616032 +HeapAlloc dt=60 heapalloc_value=107763488 +HeapAlloc dt=78 heapalloc_value=107953440 +HeapAlloc dt=65 heapalloc_value=108333088 +GCSweepBegin dt=38 stack=28 +GCSweepEnd dt=5 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=1 heapalloc_value=108423200 +GCSweepBegin dt=80 stack=28 +GCSweepEnd dt=9 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=108682656 +GCSweepBegin dt=61 stack=28 +GCSweepEnd dt=10 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=4 heapalloc_value=108816544 +HeapAlloc dt=32 heapalloc_value=108994080 +HeapAlloc dt=50 heapalloc_value=109290272 +HeapAlloc dt=112 heapalloc_value=109566240 +HeapAlloc dt=104 heapalloc_value=109973280 +GCSweepBegin dt=66 stack=29 +GCSweepEnd dt=17 swept_value=8192 reclaimed_value=0 +HeapAlloc dt=3 heapalloc_value=110183040 +HeapAlloc dt=86 heapalloc_value=110506880 +HeapAlloc dt=149 heapalloc_value=111151232 +HeapAlloc dt=24 heapalloc_value=111272064 +HeapAlloc dt=53 heapalloc_value=111368064 +HeapAlloc dt=68 heapalloc_value=111632256 +HeapAlloc dt=103 heapalloc_value=112078720 +GCSweepBegin dt=120 stack=28 +GCSweepEnd dt=7 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=112585472 +HeapAlloc dt=34 heapalloc_value=112616832 +HeapAlloc dt=39 heapalloc_value=112882304 +HeapAlloc dt=141 heapalloc_value=113391232 +HeapAlloc dt=80 heapalloc_value=113664384 +HeapAlloc dt=152 heapalloc_value=114242176 +HeapAlloc dt=104 heapalloc_value=114415616 +HeapAlloc dt=38 heapalloc_value=114527360 +HeapAlloc dt=28 heapalloc_value=114592896 +GCSweepBegin dt=227 stack=27 +EventBatch gen=3 m=169411 time=28114950895719 size=370 +ProcStatus dt=1 p=21 pstatus=1 +GoStatus dt=5 g=85 m=169411 gstatus=2 +GCMarkAssistActive dt=1 g=85 +GCMarkAssistEnd dt=3 +HeapAlloc dt=44 heapalloc_value=190299584 +GoStop dt=38 reason_string=16 stack=4 +GoStart dt=20 g=85 g_seq=1 +GCMarkAssistBegin dt=119 stack=3 +GoStop dt=4468 reason_string=20 stack=9 +GoStart dt=15 g=85 g_seq=2 +GoStop dt=1589 reason_string=20 stack=9 +GoStart dt=8 g=85 g_seq=3 +GCMarkAssistEnd dt=2892 +HeapAlloc dt=33 heapalloc_value=191733184 +GCMarkAssistBegin dt=98 stack=3 +GoStop dt=2309 reason_string=20 stack=9 +GoStart dt=10 g=95 g_seq=3 +GoBlock dt=153 reason_string=13 stack=11 +GoStart dt=5 g=85 g_seq=4 +GoBlock dt=18 reason_string=13 stack=11 +GoUnblock dt=3925 g=58 g_seq=13 stack=0 +GoStart dt=8 g=58 g_seq=14 +GoLabel dt=3 label_string=4 +GoBlock dt=106 reason_string=15 stack=5 +ProcStop dt=1275 +ProcStart dt=21 p=21 p_seq=1 +ProcStop dt=1335 +ProcStart dt=14 p=21 p_seq=2 +GoUnblock dt=1349 g=14 g_seq=9 stack=0 +GoStart dt=8 g=14 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=255 reason_string=15 stack=5 +GoUnblock dt=2226 g=70 g_seq=9 stack=0 +GoStart dt=8 g=70 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=398 reason_string=15 stack=5 +GoUnblock dt=8 g=70 g_seq=11 stack=0 +GoStart dt=6 g=70 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=8210 reason_string=15 stack=5 +GoUnblock dt=12 g=70 g_seq=13 stack=0 +GoStart dt=5 g=70 g_seq=14 +GoLabel dt=2 label_string=2 +GoBlock dt=2354 reason_string=15 stack=5 +GoUnblock dt=93 g=72 g_seq=47 stack=0 +GoStart dt=9 g=72 g_seq=48 +GoLabel dt=1 label_string=4 +GoBlock dt=27 reason_string=15 stack=5 +GoUnblock dt=220 g=72 g_seq=49 stack=0 +GoStart dt=7 g=72 g_seq=50 +GoLabel dt=1 label_string=2 +GoBlock dt=20 reason_string=15 stack=5 +ProcStop dt=61 +ProcStart dt=16474 p=33 p_seq=2 +GoStart dt=3475 g=107 g_seq=4 +GCMarkAssistEnd dt=9 +HeapAlloc dt=52 heapalloc_value=196041168 +GoStop dt=5585 reason_string=16 stack=6 +GoStart dt=15 g=107 g_seq=5 +GCMarkAssistBegin dt=91 stack=3 +GoBlock dt=34 reason_string=10 stack=18 +ProcStop dt=55 +ProcStart dt=1514 p=33 p_seq=3 +ProcStop dt=41 +ProcStart dt=12390 p=8 p_seq=1 +GoStart dt=166 g=100 g_seq=7 +GCMarkAssistEnd dt=5 +HeapAlloc dt=51 heapalloc_value=111353984 +GCSweepBegin dt=133 stack=28 +GCSweepEnd dt=18 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=112029568 +HeapAlloc dt=68 heapalloc_value=112301312 +HeapAlloc dt=120 heapalloc_value=112739712 +HeapAlloc dt=116 heapalloc_value=113221760 +HeapAlloc dt=53 heapalloc_value=113380224 +HeapAlloc dt=115 heapalloc_value=113768832 +HeapAlloc dt=66 heapalloc_value=114026880 +HeapAlloc dt=127 heapalloc_value=114403328 +GCSweepBegin dt=47 stack=28 +GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=114503936 +HeapAlloc dt=67 heapalloc_value=114651264 +GCSweepBegin dt=299 stack=27 +EventBatch gen=3 m=169409 time=28114950894853 size=224 +ProcStatus dt=2 p=29 pstatus=1 +GoStatus dt=3 g=126 m=169409 gstatus=2 +HeapAlloc dt=3 heapalloc_value=189824448 +GCMarkAssistBegin dt=163 stack=3 +GoStop dt=1609 reason_string=20 stack=9 +GoStart dt=26 g=98 g_seq=2 +GCMarkAssistBegin dt=17 stack=3 +GCMarkAssistEnd dt=7751 +HeapAlloc dt=77 heapalloc_value=191675840 +GoStop dt=39 reason_string=16 stack=6 +GoStart dt=20 g=116 g_seq=4 +GoBlock dt=302 reason_string=13 stack=11 +GoUnblock dt=4886 g=51 g_seq=13 stack=0 +GoStart dt=8 g=51 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=2058 reason_string=15 stack=5 +GoUnblock dt=11 g=51 g_seq=15 stack=0 +GoStart dt=6 g=51 g_seq=16 +GoLabel dt=3 label_string=2 +GoBlock dt=2936 reason_string=15 stack=5 +GoUnblock dt=35 g=58 g_seq=21 stack=0 +GoStart dt=6 g=58 g_seq=22 +GoLabel dt=3 label_string=2 +GoBlock dt=7995 reason_string=15 stack=5 +GoUnblock dt=20 g=68 g_seq=9 stack=0 +GoStart dt=6 g=68 g_seq=10 +GoLabel dt=3 label_string=2 +GoBlock dt=92 reason_string=15 stack=5 +GoUnblock dt=8 g=68 g_seq=11 stack=0 +GoStart dt=1 g=68 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=7039 reason_string=15 stack=5 +ProcStop dt=54 +ProcStart dt=14204 p=3 p_seq=1 +GoStart dt=213 g=94 g_seq=7 +GCMarkAssistBegin dt=29 stack=3 +GoBlock dt=62 reason_string=13 stack=11 +GoStart dt=20 g=124 g_seq=4 +GCMarkAssistEnd dt=6 +GCMarkAssistBegin dt=38 stack=3 +GCMarkAssistEnd dt=98 +HeapAlloc dt=118 heapalloc_value=193911512 +HeapAlloc dt=123 heapalloc_value=194116312 +HeapAlloc dt=352 heapalloc_value=194616024 +GoStop dt=3095 reason_string=16 stack=6 +GoStart dt=26 g=110 g_seq=4 +GCMarkAssistEnd dt=6 +HeapAlloc dt=30 heapalloc_value=195508952 +GoStop dt=4300 reason_string=16 stack=6 +GoStart dt=65 g=110 g_seq=5 +GCMarkAssistBegin dt=10 stack=3 +GoBlock dt=46 reason_string=10 stack=18 +ProcStop dt=124 +EventBatch gen=3 m=169408 time=28114950896863 size=856 +ProcStatus dt=1 p=22 pstatus=1 +GoStatus dt=2 g=105 m=169408 gstatus=2 +GCMarkAssistActive dt=1 g=105 +GCMarkAssistEnd dt=2 +HeapAlloc dt=22 heapalloc_value=190512576 +HeapAlloc dt=94 heapalloc_value=190537152 +GCMarkAssistBegin dt=18 stack=3 +GCMarkAssistEnd dt=1243 +HeapAlloc dt=34 heapalloc_value=190741952 +GCMarkAssistBegin dt=36 stack=3 +GCMarkAssistEnd dt=4423 +HeapAlloc dt=22 heapalloc_value=191413696 +GoStop dt=23 reason_string=16 stack=4 +GoStart dt=15 g=105 g_seq=1 +GCMarkAssistBegin dt=57 stack=3 +GoStop dt=662 reason_string=20 stack=9 +GoStart dt=12 g=105 g_seq=2 +GoStop dt=4139 reason_string=20 stack=9 +GoStart dt=11 g=105 g_seq=3 +GoStop dt=4306 reason_string=20 stack=9 +GoStart dt=15 g=105 g_seq=4 +GoBlock dt=21 reason_string=13 stack=11 +GoUnblock dt=2669 g=58 g_seq=19 stack=0 +GoStart dt=5 g=58 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=90 reason_string=15 stack=5 +GoUnblock dt=28 g=51 g_seq=17 stack=0 +GoStart dt=5 g=51 g_seq=18 +GoLabel dt=1 label_string=2 +GoBlock dt=5245 reason_string=15 stack=5 +GoUnblock dt=68 g=51 g_seq=19 stack=0 +GoStart dt=8 g=51 g_seq=20 +GoLabel dt=1 label_string=4 +GoBlock dt=14 reason_string=15 stack=5 +GoUnblock dt=6 g=51 g_seq=21 stack=0 +GoStart dt=1 g=51 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=7035 reason_string=15 stack=5 +GoUnblock dt=13 g=51 g_seq=23 stack=0 +GoStart dt=4 g=51 g_seq=24 +GoLabel dt=2 label_string=2 +GoUnblock dt=188 g=116 g_seq=5 stack=12 +GoBlock dt=65 reason_string=15 stack=5 +GoUnblock dt=9 g=51 g_seq=25 stack=0 +GoStart dt=2 g=51 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=170 reason_string=15 stack=5 +GoUnblock dt=15 g=51 g_seq=27 stack=0 +GoStart dt=6 g=51 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=33 reason_string=15 stack=5 +GoUnblock dt=7 g=51 g_seq=29 stack=0 +GoStart dt=6 g=51 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=159 reason_string=15 stack=5 +GoUnblock dt=8 g=51 g_seq=31 stack=0 +GoStart dt=3 g=51 g_seq=32 +GoLabel dt=1 label_string=2 +GoBlock dt=124 reason_string=15 stack=5 +ProcStop dt=79 +ProcStart dt=18 p=22 p_seq=1 +GoUnblock dt=4 g=29 g_seq=21 stack=0 +GoStart dt=4 g=29 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=28 reason_string=15 stack=5 +ProcStop dt=45 +ProcStart dt=12 p=22 p_seq=2 +GoUnblock dt=2 g=29 g_seq=23 stack=0 +GoStart dt=1 g=29 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=19 reason_string=15 stack=5 +GoUnblock dt=45 g=29 g_seq=25 stack=0 +GoStart dt=1 g=29 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=151 reason_string=15 stack=5 +GoUnblock dt=14 g=52 g_seq=35 stack=0 +GoStart dt=6 g=52 g_seq=36 +GoLabel dt=1 label_string=2 +GoBlock dt=13 reason_string=15 stack=5 +GoUnblock dt=4 g=52 g_seq=37 stack=0 +GoStart dt=3 g=52 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=127 reason_string=15 stack=5 +GoUnblock dt=7 g=52 g_seq=39 stack=0 +GoStart dt=1 g=52 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=11 reason_string=15 stack=5 +GoUnblock dt=6 g=52 g_seq=41 stack=0 +GoStart dt=2 g=52 g_seq=42 +GoLabel dt=1 label_string=2 +GoBlock dt=4594 reason_string=15 stack=5 +ProcStop dt=42 +ProcStart dt=1703 p=27 p_seq=42 +GoUnblock dt=17 g=22 g_seq=45 stack=0 +GoStart dt=283 g=22 g_seq=46 +GoLabel dt=2 label_string=2 +GoUnblock dt=103 g=96 g_seq=3 stack=12 +GoUnblock dt=95 g=121 g_seq=5 stack=12 +GoUnblock dt=5 g=126 g_seq=2 stack=12 +GoUnblock dt=529 g=115 g_seq=3 stack=12 +GoBlock dt=552 reason_string=15 stack=5 +GoUnblock dt=31 g=22 g_seq=47 stack=0 +GoStart dt=4 g=22 g_seq=48 +GoLabel dt=1 label_string=2 +GoUnblock dt=763 g=90 g_seq=3 stack=12 +GoBlock dt=39 reason_string=15 stack=5 +GoUnblock dt=12 g=22 g_seq=49 stack=0 +GoStart dt=4 g=22 g_seq=50 +GoLabel dt=1 label_string=2 +GoBlock dt=806 reason_string=15 stack=5 +GoStart dt=18 g=115 g_seq=4 +GCMarkAssistEnd dt=8 +HeapAlloc dt=834 heapalloc_value=192494296 +GCMarkAssistBegin dt=33 stack=3 +GoStop dt=622 reason_string=20 stack=9 +GoUnblock dt=15 g=14 g_seq=44 stack=0 +GoStart dt=5 g=14 g_seq=45 +GoLabel dt=1 label_string=2 +GoBlock dt=1768 reason_string=15 stack=5 +GoUnblock dt=11 g=14 g_seq=46 stack=0 +GoStart dt=4 g=14 g_seq=47 +GoLabel dt=1 label_string=2 +GoBlock dt=20 reason_string=15 stack=5 +GoUnblock dt=10 g=14 g_seq=48 stack=0 +GoStart dt=636 g=14 g_seq=49 +GoLabel dt=1 label_string=2 +GoBlock dt=55 reason_string=15 stack=5 +GoUnblock dt=18 g=14 g_seq=50 stack=0 +GoStart dt=3 g=14 g_seq=51 +GoLabel dt=1 label_string=2 +GoBlock dt=46 reason_string=15 stack=5 +GoUnblock dt=15 g=14 g_seq=52 stack=0 +GoStart dt=4 g=14 g_seq=53 +GoLabel dt=1 label_string=2 +GoBlock dt=26 reason_string=15 stack=5 +GoUnblock dt=29 g=70 g_seq=23 stack=0 +GoStart dt=5 g=70 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=15 reason_string=15 stack=5 +GoStart dt=30 g=94 g_seq=6 +GCMarkAssistEnd dt=5 +HeapAlloc dt=37 heapalloc_value=192699096 +GoStop dt=34 reason_string=16 stack=6 +GoUnblock dt=9 g=70 g_seq=25 stack=0 +GoStart dt=3 g=70 g_seq=26 +GoLabel dt=1 label_string=2 +GoUnblock dt=190 g=98 g_seq=7 stack=12 +GoUnblock dt=6 g=91 g_seq=1 stack=12 +GoUnblock dt=7 g=123 g_seq=6 stack=12 +GoUnblock dt=5 g=100 g_seq=3 stack=12 +GoUnblock dt=3 g=102 g_seq=3 stack=12 +GoUnblock dt=3 g=103 g_seq=4 stack=12 +GoUnblock dt=5 g=117 g_seq=3 stack=12 +GoBlock dt=45 reason_string=15 stack=5 +GoUnblock dt=8 g=70 g_seq=27 stack=0 +GoStart dt=1 g=70 g_seq=28 +GoLabel dt=1 label_string=2 +GoUnblock dt=1939 g=111 g_seq=7 stack=12 +GoUnblock dt=10 g=101 g_seq=5 stack=12 +GoBlock dt=23 reason_string=15 stack=5 +GoStart dt=15 g=98 g_seq=8 +GCMarkAssistEnd dt=8 +HeapAlloc dt=57 heapalloc_value=193960664 +GCMarkAssistBegin dt=83 stack=3 +GoBlock dt=26 reason_string=13 stack=11 +GoStart dt=7 g=91 g_seq=2 +GCMarkAssistEnd dt=6 +HeapAlloc dt=47 heapalloc_value=194296536 +GCMarkAssistBegin dt=103 stack=3 +GoBlock dt=118 reason_string=13 stack=11 +GoStart dt=20 g=123 g_seq=7 +GCMarkAssistEnd dt=4 +HeapAlloc dt=448 heapalloc_value=195058392 +GoStop dt=6487 reason_string=16 stack=6 +GoStart dt=27 g=123 g_seq=8 +GCMarkAssistBegin dt=10 stack=3 +GoBlock dt=32 reason_string=10 stack=18 +ProcStop dt=78 +ProcStart dt=16845 p=9 p_seq=1 +GoStart dt=21 g=127 g_seq=10 +GCMarkAssistEnd dt=11 +GCSweepBegin dt=37 stack=28 +GCSweepEnd dt=17 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=7 heapalloc_value=110613376 +HeapAlloc dt=77 heapalloc_value=110956160 +HeapAlloc dt=127 heapalloc_value=111501184 +HeapAlloc dt=150 heapalloc_value=112133376 +HeapAlloc dt=103 heapalloc_value=112487168 +HeapAlloc dt=158 heapalloc_value=113166976 +GCSweepBegin dt=50 stack=28 +GCSweepEnd dt=32 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=6 heapalloc_value=113407616 +HeapAlloc dt=173 heapalloc_value=114067840 +HeapAlloc dt=153 heapalloc_value=114430208 +GCSweepBegin dt=35 stack=28 +GCSweepEnd dt=4 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=4 heapalloc_value=114551936 +GCSweepBegin dt=1034 stack=27 +EventBatch gen=3 m=169407 time=28114950901555 size=528 +ProcStatus dt=2 p=4 pstatus=1 +GoStatus dt=1 g=72 m=169407 gstatus=2 +GoBlock dt=7 reason_string=15 stack=5 +GoUnblock dt=1446 g=72 g_seq=3 stack=0 +GoStart dt=9 g=72 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=394 reason_string=15 stack=5 +GoStart dt=26 g=106 g_seq=3 +GoBlock dt=149 reason_string=13 stack=11 +GoUnblock dt=2557 g=72 g_seq=5 stack=0 +GoStart dt=8 g=72 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=44 reason_string=15 stack=5 +GoUnblock dt=13 g=72 g_seq=7 stack=0 +GoStart dt=6 g=72 g_seq=8 +GoLabel dt=5 label_string=2 +GoBlock dt=1622 reason_string=15 stack=5 +GoUnblock dt=9 g=72 g_seq=9 stack=0 +GoStart dt=6 g=72 g_seq=10 +GoLabel dt=1 label_string=2 +GoUnblock dt=165 g=87 g_seq=2 stack=12 +GoBlock dt=854 reason_string=15 stack=5 +GoUnblock dt=9 g=72 g_seq=11 stack=0 +GoStart dt=4 g=72 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=398 reason_string=15 stack=5 +GoUnblock dt=20 g=72 g_seq=13 stack=0 +GoStart dt=5 g=72 g_seq=14 +GoLabel dt=1 label_string=2 +GoBlock dt=1475 reason_string=15 stack=5 +GoStart dt=1158 g=93 g_seq=2 +GoStatus dt=24 g=94 m=18446744073709551615 gstatus=4 +GoUnblock dt=5 g=94 g_seq=1 stack=10 +GCMarkAssistBegin dt=19 stack=3 +GoBlock dt=235 reason_string=13 stack=11 +GoStart dt=9 g=94 g_seq=2 +GoStatus dt=18 g=100 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=100 g_seq=1 stack=10 +GCMarkAssistBegin dt=16 stack=3 +GoStop dt=7669 reason_string=20 stack=9 +GoStart dt=9 g=94 g_seq=3 +GoStop dt=5028 reason_string=20 stack=9 +GoUnblock dt=76 g=23 g_seq=39 stack=0 +GoStart dt=4 g=23 g_seq=40 +GoLabel dt=1 label_string=4 +GoBlock dt=464 reason_string=15 stack=5 +GoUnblock dt=67 g=23 g_seq=41 stack=0 +GoStart dt=151 g=23 g_seq=42 +GoLabel dt=2 label_string=4 +GoBlock dt=3280 reason_string=15 stack=5 +GoStart dt=35 g=113 g_seq=6 +GCMarkAssistEnd dt=7 +GCMarkAssistBegin dt=65 stack=3 +GoBlock dt=63 reason_string=13 stack=11 +ProcStop dt=162 +ProcStart dt=22113 p=24 p_seq=4 +GoStart dt=228 g=111 g_seq=8 +GCMarkAssistEnd dt=11 +HeapAlloc dt=64 heapalloc_value=196401616 +GoStop dt=6120 reason_string=16 stack=6 +GoStart dt=26 g=111 g_seq=9 +GCMarkAssistBegin dt=15 stack=3 +GoBlock dt=35 reason_string=10 stack=18 +ProcStop dt=128 +ProcStart dt=7783 p=1 p_seq=3 +GoStart dt=191 g=87 g_seq=8 +GCMarkAssistEnd dt=9 +GCSweepBegin dt=33 stack=28 +GCSweepEnd dt=16 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=4 heapalloc_value=103833248 +GCSweepBegin dt=56 stack=27 +GCSweepEnd dt=1508 swept_value=4194304 reclaimed_value=3072000 +HeapAlloc dt=33 heapalloc_value=105692064 +HeapAlloc dt=115 heapalloc_value=105976736 +HeapAlloc dt=44 heapalloc_value=106034080 +HeapAlloc dt=109 heapalloc_value=106332320 +HeapAlloc dt=95 heapalloc_value=106715424 +HeapAlloc dt=80 heapalloc_value=106958496 +HeapAlloc dt=97 heapalloc_value=107330592 +HeapAlloc dt=56 heapalloc_value=107460384 +HeapAlloc dt=117 heapalloc_value=107811360 +HeapAlloc dt=62 heapalloc_value=108141856 +HeapAlloc dt=115 heapalloc_value=108472352 +HeapAlloc dt=103 heapalloc_value=108710048 +GCSweepBegin dt=51 stack=28 +GCSweepEnd dt=11 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=4 heapalloc_value=108832928 +HeapAlloc dt=51 heapalloc_value=109134624 +HeapAlloc dt=100 heapalloc_value=109470496 +HeapAlloc dt=98 heapalloc_value=109831200 +HeapAlloc dt=69 heapalloc_value=110087968 +HeapAlloc dt=117 heapalloc_value=110388096 +HeapAlloc dt=150 heapalloc_value=111005312 +HeapAlloc dt=140 heapalloc_value=111509376 +HeapAlloc dt=55 heapalloc_value=111773568 +HeapAlloc dt=105 heapalloc_value=112162048 +GCSweepBegin dt=85 stack=28 +GCSweepEnd dt=8 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=112560896 +HeapAlloc dt=68 heapalloc_value=112816768 +HeapAlloc dt=47 heapalloc_value=112988800 +HeapAlloc dt=122 heapalloc_value=113464960 +HeapAlloc dt=150 heapalloc_value=114008448 +GCSweepBegin dt=885 stack=27 +EventBatch gen=3 m=169406 time=28114950897134 size=117 +ProcStatus dt=3 p=6 pstatus=1 +GoStatus dt=5 g=52 m=169406 gstatus=2 +GoBlock dt=14 reason_string=15 stack=5 +GoUnblock dt=16 g=52 g_seq=1 stack=0 +GoStart dt=5 g=52 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=3752 reason_string=15 stack=5 +GoUnblock dt=21 g=52 g_seq=3 stack=0 +GoStart dt=7 g=52 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=4444 reason_string=15 stack=5 +GoUnblock dt=12 g=52 g_seq=5 stack=0 +GoStart dt=7 g=52 g_seq=6 +GoLabel dt=1 label_string=2 +GoBlock dt=5071 reason_string=15 stack=5 +GoUnblock dt=15 g=52 g_seq=7 stack=0 +GoStart dt=6 g=52 g_seq=8 +GoLabel dt=2 label_string=2 +GoBlock dt=2302 reason_string=15 stack=5 +GoUnblock dt=14 g=52 g_seq=9 stack=0 +GoStart dt=6 g=52 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=32 reason_string=15 stack=5 +GoUnblock dt=9 g=52 g_seq=11 stack=0 +GoStart dt=6 g=52 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=22 reason_string=15 stack=5 +ProcStop dt=35 +EventBatch gen=3 m=169405 time=28114950903578 size=119 +ProcStatus dt=2 p=15 pstatus=1 +GoStatus dt=4 g=53 m=169405 gstatus=2 +GoBlock dt=8 reason_string=15 stack=5 +GoUnblock dt=5238 g=25 g_seq=7 stack=0 +GoStart dt=7 g=25 g_seq=8 +GoLabel dt=1 label_string=4 +GoBlock dt=49 reason_string=15 stack=5 +GoUnblock dt=1111 g=58 g_seq=11 stack=0 +GoStart dt=6 g=58 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=158 reason_string=15 stack=5 +GoStart dt=3143 g=100 g_seq=2 +GoStatus dt=20 g=109 m=18446744073709551615 gstatus=4 +GoUnblock dt=7 g=109 g_seq=1 stack=10 +GCMarkAssistBegin dt=17 stack=3 +GoBlock dt=2307 reason_string=13 stack=11 +GoUnblock dt=2192 g=14 g_seq=13 stack=0 +GoStart dt=4 g=14 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=1366 reason_string=15 stack=5 +GoUnblock dt=68 g=23 g_seq=21 stack=0 +GoStart dt=4 g=23 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=21 reason_string=15 stack=5 +ProcStop dt=3159 +EventBatch gen=3 m=169404 time=28114950896316 size=116 +ProcStatus dt=1 p=5 pstatus=1 +GoStatus dt=2 g=14 m=169404 gstatus=2 +GoBlock dt=5 reason_string=15 stack=5 +GoUnblock dt=1436 g=67 g_seq=3 stack=0 +GoStart dt=217 g=67 g_seq=4 +GoLabel dt=3 label_string=4 +GoBlock dt=1945 reason_string=15 stack=5 +GoStart dt=23 g=121 g_seq=3 +GoStop dt=570 reason_string=20 stack=9 +GoStart dt=14 g=121 g_seq=4 +GoBlock dt=1389 reason_string=13 stack=11 +GoUnblock dt=13 g=51 g_seq=3 stack=0 +GoStart dt=7 g=51 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=1439 reason_string=15 stack=5 +GoUnblock dt=17 g=14 g_seq=5 stack=0 +GoStart dt=5 g=14 g_seq=6 +GoLabel dt=2 label_string=2 +GoBlock dt=11474 reason_string=15 stack=5 +GoStart dt=4166 g=109 g_seq=3 +GoBlock dt=39 reason_string=13 stack=11 +GoStart dt=20 g=119 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=68 heapalloc_value=191921600 +GCMarkAssistBegin dt=69 stack=3 +GoBlock dt=23 reason_string=13 stack=11 +ProcStop dt=59 +EventBatch gen=3 m=169402 time=28114950895074 size=135 +ProcStatus dt=2 p=9 pstatus=1 +GoStatus dt=2 g=25 m=169402 gstatus=2 +GoBlock dt=14 reason_string=15 stack=5 +GoStart dt=54 g=98 g_seq=1 +GCMarkAssistBegin dt=99 stack=3 +GCMarkAssistEnd dt=1187 +HeapAlloc dt=68 heapalloc_value=190463424 +GoStop dt=53 reason_string=16 stack=6 +GoStart dt=10 g=82 g_seq=1 +GCMarkAssistBegin dt=82 stack=3 +GoStop dt=2699 reason_string=20 stack=9 +GoStart dt=13 g=107 g_seq=2 +GCMarkAssistEnd dt=7 +GCMarkAssistBegin dt=49 stack=3 +GoBlock dt=852 reason_string=13 stack=11 +GoStart dt=29 g=90 g_seq=2 +GCMarkAssistEnd dt=3 +HeapAlloc dt=36 heapalloc_value=191233472 +GCMarkAssistBegin dt=825 stack=3 +GoBlock dt=392 reason_string=13 stack=11 +GoUnblock dt=21 g=67 g_seq=5 stack=0 +GoStart dt=5 g=67 g_seq=6 +GoLabel dt=1 label_string=2 +GoBlock dt=8638 reason_string=15 stack=5 +GoUnblock dt=9 g=67 g_seq=7 stack=0 +GoStart dt=4 g=67 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=145 reason_string=15 stack=5 +GoUnblock dt=14 g=67 g_seq=9 stack=0 +GoStart dt=5 g=67 g_seq=10 +GoLabel dt=1 label_string=2 +GoBlock dt=7067 reason_string=15 stack=5 +ProcStop dt=23 +EventBatch gen=3 m=169401 time=28114950894770 size=505 +ProcStatus dt=1 p=8 pstatus=1 +GoStatus dt=1 g=130 m=169401 gstatus=2 +ProcsChange dt=124 procs_value=48 stack=1 +GCActive dt=3 gc_seq=4 +HeapAlloc dt=600 heapalloc_value=190152128 +HeapAlloc dt=16 heapalloc_value=190160320 +HeapAlloc dt=11095 heapalloc_value=191741376 +HeapAlloc dt=179 heapalloc_value=191749568 +HeapAlloc dt=14244 heapalloc_value=192011712 +HeapAlloc dt=292 heapalloc_value=192019904 +HeapAlloc dt=244 heapalloc_value=192028096 +HeapAlloc dt=3225 heapalloc_value=192036288 +HeapAlloc dt=39 heapalloc_value=192044192 +HeapAlloc dt=60 heapalloc_value=192052000 +HeapAlloc dt=462 heapalloc_value=192060192 +HeapAlloc dt=85 heapalloc_value=192068384 +HeapAlloc dt=341 heapalloc_value=192076576 +HeapAlloc dt=314 heapalloc_value=192142112 +GoStop dt=8367 reason_string=16 stack=14 +GoUnblock dt=274 g=30 g_seq=27 stack=0 +GoStart dt=6 g=30 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=312 reason_string=15 stack=5 +GoUnblock dt=403 g=30 g_seq=29 stack=0 +GoStart dt=4 g=30 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=773 reason_string=15 stack=5 +GoUnblock dt=7 g=30 g_seq=31 stack=0 +GoStart dt=3 g=30 g_seq=32 +GoLabel dt=1 label_string=2 +GoBlock dt=8 reason_string=15 stack=5 +GoStart dt=14 g=112 g_seq=4 +GCMarkAssistEnd dt=6 +HeapAlloc dt=45 heapalloc_value=192297760 +GCMarkAssistBegin dt=107 stack=3 +GoStop dt=897 reason_string=20 stack=9 +GoUnblock dt=15 g=70 g_seq=19 stack=0 +GoStart dt=5 g=70 g_seq=20 +GoLabel dt=1 label_string=2 +GoUnblock dt=1479 g=105 g_seq=5 stack=12 +GoBlock dt=2280 reason_string=15 stack=5 +GoUnblock dt=12 g=70 g_seq=21 stack=0 +GoStart dt=5 g=70 g_seq=22 +GoLabel dt=2 label_string=2 +GoBlock dt=1253 reason_string=15 stack=5 +GoUnblock dt=23 g=71 g_seq=35 stack=0 +GoStart dt=8 g=71 g_seq=36 +GoLabel dt=2 label_string=2 +GoBlock dt=26 reason_string=15 stack=5 +GoUnblock dt=6 g=71 g_seq=37 stack=0 +GoStart dt=3 g=71 g_seq=38 +GoLabel dt=1 label_string=2 +GoBlock dt=9 reason_string=15 stack=5 +GoUnblock dt=3 g=71 g_seq=39 stack=0 +GoStart dt=2 g=71 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=3 g=71 g_seq=41 stack=0 +GoStart dt=1 g=71 g_seq=42 +GoLabel dt=1 label_string=2 +GoUnblock dt=82 g=109 g_seq=4 stack=12 +GoUnblock dt=6 g=106 g_seq=4 stack=12 +GoUnblock dt=103 g=111 g_seq=4 stack=12 +GoUnblock dt=5 g=112 g_seq=6 stack=12 +GoUnblock dt=6 g=96 g_seq=5 stack=12 +GoUnblock dt=4 g=119 g_seq=5 stack=12 +GoUnblock dt=6 g=122 g_seq=1 stack=12 +GoUnblock dt=11 g=97 g_seq=5 stack=12 +GoUnblock dt=4 g=107 g_seq=3 stack=12 +GoUnblock dt=106 g=92 g_seq=3 stack=12 +GoUnblock dt=4 g=116 g_seq=9 stack=12 +GoUnblock dt=5 g=82 g_seq=8 stack=12 +GoBlock dt=9 reason_string=15 stack=5 +GoStart dt=12 g=111 g_seq=5 +GCMarkAssistEnd dt=5 +HeapAlloc dt=22 heapalloc_value=192797400 +GCMarkAssistBegin dt=75 stack=3 +GoStop dt=22 reason_string=20 stack=9 +GoUnblock dt=11 g=25 g_seq=53 stack=0 +GoStart dt=4 g=25 g_seq=54 +GoLabel dt=1 label_string=2 +GoUnblock dt=1354 g=95 g_seq=4 stack=12 +GoUnblock dt=9 g=90 g_seq=6 stack=12 +GoUnblock dt=6 g=113 g_seq=9 stack=12 +GoUnblock dt=3 g=89 g_seq=6 stack=12 +GoBlock dt=30 reason_string=15 stack=5 +GoStart dt=10 g=112 g_seq=7 +GCMarkAssistEnd dt=5 +GCMarkAssistBegin dt=28 stack=3 +GoBlock dt=587 reason_string=13 stack=11 +GoStart dt=6 g=116 g_seq=10 +GCMarkAssistEnd dt=5 +HeapAlloc dt=54 heapalloc_value=194337496 +GCMarkAssistBegin dt=51 stack=3 +GoBlock dt=21 reason_string=13 stack=11 +GoStart dt=8 g=82 g_seq=9 +GCMarkAssistEnd dt=6 +HeapAlloc dt=63 heapalloc_value=194525912 +GCMarkAssistBegin dt=51 stack=3 +GoBlock dt=45 reason_string=13 stack=11 +GoStart dt=22 g=95 g_seq=5 +GCMarkAssistEnd dt=6 +HeapAlloc dt=1508 heapalloc_value=195394264 +GoStop dt=6034 reason_string=16 stack=6 +GoStart dt=48 g=95 g_seq=6 +GCMarkAssistBegin dt=18 stack=3 +GoBlock dt=48 reason_string=10 stack=18 +ProcStop dt=85 +ProcStart dt=20619 p=17 p_seq=1 +GoStart dt=1507 g=130 g_seq=7 +EventBatch gen=3 m=169400 time=28114950894819 size=671 +ProcStatus dt=1 p=12 pstatus=1 +GoStatus dt=2 g=112 m=169400 gstatus=2 +GCMarkAssistBegin dt=120 stack=3 +GCMarkAssistEnd dt=3298 +HeapAlloc dt=41 heapalloc_value=190758336 +GCMarkAssistBegin dt=29 stack=3 +GoStop dt=2271 reason_string=20 stack=9 +GoStart dt=14 g=112 g_seq=1 +GoStop dt=569 reason_string=20 stack=9 +GoUnblock dt=2436 g=54 g_seq=1 stack=0 +GoStart dt=18 g=54 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=31 reason_string=15 stack=5 +GoUnblock dt=5090 g=57 g_seq=13 stack=0 +GoStart dt=6 g=57 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=734 reason_string=15 stack=5 +GoUnblock dt=4144 g=71 g_seq=15 stack=0 +GoStart dt=5 g=71 g_seq=16 +GoLabel dt=1 label_string=4 +GoUnblock dt=415 g=111 g_seq=2 stack=12 +GoBlock dt=5674 reason_string=15 stack=5 +GoUnblock dt=9 g=71 g_seq=17 stack=0 +GoStart dt=5 g=71 g_seq=18 +GoLabel dt=1 label_string=2 +GoUnblock dt=693 g=83 g_seq=3 stack=12 +GoBlock dt=4708 reason_string=15 stack=5 +GoUnblock dt=14 g=71 g_seq=19 stack=0 +GoStart dt=6 g=71 g_seq=20 +GoLabel dt=3 label_string=2 +GoBlock dt=1294 reason_string=15 stack=5 +GoUnblock dt=11 g=71 g_seq=21 stack=0 +GoStart dt=4 g=71 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=2434 reason_string=15 stack=5 +GoUnblock dt=8 g=71 g_seq=23 stack=0 +GoStart dt=3 g=71 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=4227 reason_string=15 stack=5 +ProcStop dt=41 +ProcStart dt=3260 p=12 p_seq=1 +GoUnblock dt=16 g=30 g_seq=33 stack=0 +GoStart dt=143 g=30 g_seq=34 +GoLabel dt=1 label_string=2 +GoUnblock dt=553 g=89 g_seq=3 stack=12 +GoUnblock dt=971 g=127 g_seq=3 stack=12 +GoBlock dt=39 reason_string=15 stack=5 +GoStart dt=21 g=89 g_seq=4 +GCMarkAssistEnd dt=10 +HeapAlloc dt=1100 heapalloc_value=192510680 +GoStop dt=24 reason_string=16 stack=6 +GoUnblock dt=12 g=22 g_seq=51 stack=0 +GoStart dt=5 g=22 g_seq=52 +GoLabel dt=3 label_string=2 +GoBlock dt=1678 reason_string=15 stack=5 +GoUnblock dt=13 g=22 g_seq=53 stack=0 +GoStart dt=277 g=22 g_seq=54 +GoLabel dt=3 label_string=2 +GoBlock dt=960 reason_string=15 stack=5 +GoUnblock dt=8 g=22 g_seq=55 stack=0 +GoStart dt=4 g=22 g_seq=56 +GoLabel dt=1 label_string=2 +GoUnblock dt=583 g=99 g_seq=3 stack=12 +GoUnblock dt=5 g=83 g_seq=6 stack=12 +GoUnblock dt=5 g=124 g_seq=3 stack=12 +GoUnblock dt=6 g=105 g_seq=9 stack=12 +GoUnblock dt=1280 g=128 g_seq=3 stack=12 +GoUnblock dt=8 g=101 g_seq=3 stack=12 +GoBlock dt=7 reason_string=15 stack=5 +GoStart dt=11 g=128 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=38 heapalloc_value=193297112 +GCMarkAssistBegin dt=118 stack=3 +GCMarkAssistEnd dt=44 +HeapAlloc dt=21 heapalloc_value=193403608 +GoStop dt=87 reason_string=16 stack=6 +GoStart dt=15 g=101 g_seq=4 +GCMarkAssistEnd dt=5 +HeapAlloc dt=58 heapalloc_value=193608408 +GCMarkAssistBegin dt=92 stack=3 +GoBlock dt=22 reason_string=13 stack=11 +GoStart dt=10 g=128 g_seq=5 +HeapAlloc dt=34 heapalloc_value=193829592 +HeapAlloc dt=166 heapalloc_value=194026200 +HeapAlloc dt=236 heapalloc_value=194419416 +HeapAlloc dt=885 heapalloc_value=195279576 +GoStop dt=6734 reason_string=16 stack=6 +GoUnblock dt=1628 g=130 g_seq=3 stack=0 +GoStart dt=136 g=130 g_seq=4 +HeapAlloc dt=62 heapalloc_value=196532688 +HeapAlloc dt=28 heapalloc_value=196540880 +HeapAlloc dt=22 heapalloc_value=196549072 +HeapAlloc dt=26 heapalloc_value=196557264 +HeapAlloc dt=38 heapalloc_value=196565456 +HeapAlloc dt=51 heapalloc_value=196573648 +GoStop dt=3032 reason_string=16 stack=19 +GoStart dt=10 g=117 g_seq=5 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=51 reason_string=10 stack=18 +ProcStop dt=29 +ProcStart dt=9381 p=4 p_seq=2 +GoStart dt=190 g=105 g_seq=16 +GCMarkAssistEnd dt=4 +HeapAlloc dt=76 heapalloc_value=105214112 +HeapAlloc dt=103 heapalloc_value=105517216 +HeapAlloc dt=84 heapalloc_value=105642912 +HeapAlloc dt=85 heapalloc_value=105864096 +GCSweepBegin dt=188 stack=28 +GCSweepEnd dt=17 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=2 heapalloc_value=106376096 +HeapAlloc dt=43 heapalloc_value=106518816 +HeapAlloc dt=43 heapalloc_value=106756384 +HeapAlloc dt=82 heapalloc_value=106978976 +HeapAlloc dt=42 heapalloc_value=107091616 +GCSweepBegin dt=23 stack=28 +GCSweepEnd dt=8 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=3 heapalloc_value=107310112 +HeapAlloc dt=35 heapalloc_value=107372960 +HeapAlloc dt=65 heapalloc_value=107583264 +HeapAlloc dt=141 heapalloc_value=108018976 +HeapAlloc dt=161 heapalloc_value=108567968 +GCSweepBegin dt=85 stack=28 +GCSweepEnd dt=9 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=4 heapalloc_value=108808352 +HeapAlloc dt=90 heapalloc_value=109241120 +HeapAlloc dt=139 heapalloc_value=109623584 +HeapAlloc dt=162 heapalloc_value=110175008 +HeapAlloc dt=164 heapalloc_value=110769024 +HeapAlloc dt=246 heapalloc_value=111705984 +HeapAlloc dt=187 heapalloc_value=112446208 +HeapAlloc dt=161 heapalloc_value=113148544 +HeapAlloc dt=295 heapalloc_value=114145664 +GCSweepBegin dt=159 stack=28 +GCSweepEnd dt=5 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=7 heapalloc_value=114588800 +GCSweepBegin dt=48 stack=27 +EventBatch gen=3 m=169398 time=28114950899192 size=165 +ProcStatus dt=1 p=37 pstatus=2 +ProcStart dt=2 p=37 p_seq=1 +GoStatus dt=3261 g=29 m=18446744073709551615 gstatus=4 +GoUnblock dt=6 g=29 g_seq=1 stack=0 +GoStart dt=10 g=29 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=1840 reason_string=15 stack=5 +GoStart dt=16 g=86 g_seq=3 +GoBlock dt=1090 reason_string=13 stack=11 +ProcStop dt=1389 +ProcStart dt=16 p=37 p_seq=2 +GoStart dt=1537 g=84 g_seq=4 +GCMarkAssistEnd dt=7 +HeapAlloc dt=55 heapalloc_value=191847872 +GCMarkAssistBegin dt=85 stack=3 +GoBlock dt=249 reason_string=13 stack=11 +GoUnblock dt=1134 g=58 g_seq=9 stack=0 +GoStart dt=7 g=58 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=27 reason_string=15 stack=5 +GoUnblock dt=2190 g=53 g_seq=9 stack=0 +GoStart dt=8 g=53 g_seq=10 +GoLabel dt=1 label_string=4 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=2156 g=25 g_seq=13 stack=0 +GoStart dt=4 g=25 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=20 reason_string=15 stack=5 +GoUnblock dt=1089 g=14 g_seq=7 stack=0 +GoStart dt=4 g=14 g_seq=8 +GoLabel dt=1 label_string=4 +GoBlock dt=107 reason_string=15 stack=5 +GoUnblock dt=1081 g=24 g_seq=15 stack=0 +GoStart dt=6 g=24 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=19 reason_string=15 stack=5 +ProcStop dt=1075 +EventBatch gen=3 m=169397 time=28114950897533 size=734 +ProcStatus dt=1 p=25 pstatus=1 +GoStatus dt=2 g=118 m=169397 gstatus=2 +GCMarkAssistActive dt=1 g=118 +GCMarkAssistEnd dt=2 +HeapAlloc dt=37 heapalloc_value=190684608 +GCMarkAssistBegin dt=79 stack=3 +GoBlock dt=1327 reason_string=13 stack=11 +ProcStop dt=4643 +ProcStart dt=23 p=25 p_seq=1 +GoUnblock dt=20 g=53 g_seq=1 stack=0 +GoStart dt=9 g=53 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=2529 reason_string=15 stack=5 +GoStart dt=3244 g=123 g_seq=2 +GoStatus dt=30 g=97 m=18446744073709551615 gstatus=4 +GoUnblock dt=13 g=97 g_seq=1 stack=10 +GCMarkAssistBegin dt=20 stack=3 +GoStop dt=1976 reason_string=20 stack=9 +GoStart dt=15 g=123 g_seq=3 +GoStop dt=2654 reason_string=20 stack=9 +GoStart dt=12 g=123 g_seq=4 +GoStop dt=2704 reason_string=20 stack=9 +GoUnblock dt=9 g=24 g_seq=17 stack=0 +GoStart dt=4 g=24 g_seq=18 +GoLabel dt=1 label_string=2 +GoBlock dt=4029 reason_string=15 stack=5 +GoUnblock dt=14 g=24 g_seq=19 stack=0 +GoStart dt=4 g=24 g_seq=20 +GoLabel dt=1 label_string=2 +GoBlock dt=534 reason_string=15 stack=5 +GoUnblock dt=4 g=24 g_seq=21 stack=0 +GoStart dt=4 g=24 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=250 reason_string=15 stack=5 +GoUnblock dt=12 g=24 g_seq=23 stack=0 +GoStart dt=4 g=24 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=22 reason_string=15 stack=5 +ProcStop dt=71 +ProcStart dt=244 p=25 p_seq=2 +ProcStop dt=54 +ProcStart dt=25 p=25 p_seq=3 +GoUnblock dt=8 g=53 g_seq=21 stack=0 +GoStart dt=7 g=53 g_seq=22 +GoLabel dt=1 label_string=4 +GoBlock dt=86 reason_string=15 stack=5 +GoUnblock dt=59 g=56 g_seq=3 stack=0 +GoStart dt=4 g=56 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=6219 reason_string=15 stack=5 +GoUnblock dt=52 g=56 g_seq=5 stack=0 +GoStart dt=4 g=56 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=98 reason_string=15 stack=5 +GoUnblock dt=61 g=14 g_seq=27 stack=0 +GoStart dt=4 g=14 g_seq=28 +GoLabel dt=1 label_string=4 +GoBlock dt=32 reason_string=15 stack=5 +GoUnblock dt=13 g=14 g_seq=29 stack=0 +GoStart dt=5 g=14 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=2423 reason_string=15 stack=5 +ProcStop dt=36 +ProcStart dt=7135 p=31 p_seq=2 +GoStart dt=228 g=127 g_seq=4 +GCMarkAssistEnd dt=9 +HeapAlloc dt=2440 heapalloc_value=192666328 +GoStop dt=28 reason_string=16 stack=4 +GoUnblock dt=19 g=52 g_seq=57 stack=0 +GoStart dt=6 g=52 g_seq=58 +GoLabel dt=1 label_string=2 +GoBlock dt=1072 reason_string=15 stack=5 +GoUnblock dt=16 g=52 g_seq=59 stack=0 +GoStart dt=6 g=52 g_seq=60 +GoLabel dt=1 label_string=2 +GoBlock dt=19 reason_string=15 stack=5 +GoUnblock dt=17 g=54 g_seq=39 stack=0 +GoStart dt=4 g=54 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=2352 reason_string=15 stack=5 +GoStart dt=22 g=127 g_seq=8 +GCMarkAssistBegin dt=127 stack=3 +GoBlock dt=42 reason_string=13 stack=11 +GoStart dt=766 g=122 g_seq=2 +GCMarkAssistEnd dt=2 +HeapAlloc dt=19 heapalloc_value=194902744 +GCMarkAssistBegin dt=66 stack=3 +STWBegin dt=12586 kind_string=21 stack=21 +GoUnblock dt=699 g=91 g_seq=3 stack=22 +GoUnblock dt=5 g=127 g_seq=9 stack=22 +GoUnblock dt=3 g=112 g_seq=8 stack=22 +GoUnblock dt=4 g=82 g_seq=10 stack=22 +GoUnblock dt=3 g=116 g_seq=11 stack=22 +GoUnblock dt=3 g=93 g_seq=8 stack=22 +GoUnblock dt=4 g=109 g_seq=6 stack=22 +GoUnblock dt=5 g=115 g_seq=9 stack=22 +GoUnblock dt=7 g=120 g_seq=7 stack=22 +GoUnblock dt=7 g=105 g_seq=15 stack=22 +GoUnblock dt=6 g=96 g_seq=7 stack=22 +GoUnblock dt=3 g=118 g_seq=6 stack=22 +GoUnblock dt=4 g=87 g_seq=7 stack=22 +GoUnblock dt=4 g=84 g_seq=9 stack=22 +GoUnblock dt=6 g=100 g_seq=6 stack=22 +GoUnblock dt=29 g=86 g_seq=6 stack=23 +HeapAlloc dt=53 heapalloc_value=103773088 +GoStatus dt=10 g=3 m=18446744073709551615 gstatus=4 +GoUnblock dt=7 g=3 g_seq=1 stack=24 +GCEnd dt=3 gc_seq=5 +HeapGoal dt=6 heapgoal_value=207987496 +ProcsChange dt=45 procs_value=48 stack=25 +STWEnd dt=399 +GoUnblock dt=5992 g=130 g_seq=6 stack=26 +GCMarkAssistEnd dt=9 +HeapAlloc dt=11 heapalloc_value=103816864 +GCSweepBegin dt=79 stack=27 +GCSweepEnd dt=1631 swept_value=8388608 reclaimed_value=3260416 +HeapAlloc dt=14 heapalloc_value=104810272 +HeapAlloc dt=104 heapalloc_value=105001504 +HeapAlloc dt=107 heapalloc_value=105164960 +HeapAlloc dt=55 heapalloc_value=105308320 +HeapAlloc dt=200 heapalloc_value=105798560 +HeapAlloc dt=119 heapalloc_value=106091424 +HeapAlloc dt=118 heapalloc_value=106359712 +HeapAlloc dt=47 heapalloc_value=106488096 +HeapAlloc dt=44 heapalloc_value=106763424 +HeapAlloc dt=26 heapalloc_value=106820768 +HeapAlloc dt=106 heapalloc_value=107277344 +HeapAlloc dt=131 heapalloc_value=107656992 +HeapAlloc dt=71 heapalloc_value=107790880 +GCSweepBegin dt=42 stack=28 +GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=107860512 +HeapAlloc dt=71 heapalloc_value=108305696 +HeapAlloc dt=113 heapalloc_value=108608928 +HeapAlloc dt=129 heapalloc_value=108890272 +HeapAlloc dt=147 heapalloc_value=109508896 +HeapAlloc dt=88 heapalloc_value=109776544 +HeapAlloc dt=140 heapalloc_value=110286976 +HeapAlloc dt=151 heapalloc_value=110900096 +HeapAlloc dt=152 heapalloc_value=111433600 +HeapAlloc dt=136 heapalloc_value=111931264 +HeapAlloc dt=67 heapalloc_value=112248064 +HeapAlloc dt=209 heapalloc_value=113046144 +HeapAlloc dt=213 heapalloc_value=113949056 +HeapAlloc dt=236 heapalloc_value=114471168 +HeapAlloc dt=90 heapalloc_value=114663552 +GCSweepBegin dt=45 stack=28 +GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=3 heapalloc_value=114703232 +GCSweepBegin dt=54 stack=27 +EventBatch gen=3 m=169396 time=28114950894859 size=148 +ProcStatus dt=2 p=1 pstatus=1 +GoStatus dt=4 g=86 m=169396 gstatus=2 +GCMarkAssistActive dt=2 g=86 +GCMarkAssistEnd dt=2 +HeapAlloc dt=42 heapalloc_value=189889984 +GoStop dt=32 reason_string=16 stack=4 +GoUnblock dt=117 g=69 g_seq=1 stack=0 +GoStart dt=6 g=69 g_seq=2 +GoLabel dt=1 label_string=2 +GoBlock dt=2672 reason_string=15 stack=5 +GoStart dt=16 g=84 g_seq=1 +GoStop dt=2565 reason_string=20 stack=9 +GoStart dt=17 g=84 g_seq=2 +GoBlock dt=886 reason_string=13 stack=11 +ProcStop dt=2581 +ProcStart dt=17 p=1 p_seq=1 +ProcStop dt=4400 +ProcStart dt=16 p=1 p_seq=2 +GoStart dt=24 g=87 g_seq=3 +GCMarkAssistEnd dt=8 +HeapAlloc dt=70 heapalloc_value=191782336 +GCMarkAssistBegin dt=85 stack=3 +GoBlock dt=1055 reason_string=13 stack=11 +GoUnblock dt=20 g=54 g_seq=9 stack=0 +GoStart dt=7 g=54 g_seq=10 +GoLabel dt=3 label_string=2 +GoBlock dt=230 reason_string=15 stack=5 +GoUnblock dt=12 g=54 g_seq=11 stack=0 +GoStart dt=6 g=54 g_seq=12 +GoLabel dt=1 label_string=2 +GoBlock dt=1754 reason_string=15 stack=5 +GoUnblock dt=12 g=54 g_seq=13 stack=0 +GoStart dt=8 g=54 g_seq=14 +GoLabel dt=3 label_string=2 +GoBlock dt=1379 reason_string=15 stack=5 +ProcStop dt=15 +EventBatch gen=3 m=169395 time=28114950898507 size=532 +ProcStatus dt=2 p=14 pstatus=1 +GoStatus dt=2 g=103 m=169395 gstatus=2 +GCMarkAssistActive dt=1 g=103 +GCMarkAssistEnd dt=3 +HeapAlloc dt=40 heapalloc_value=190873024 +HeapAlloc dt=75 heapalloc_value=191036864 +GCMarkAssistBegin dt=65 stack=3 +GoBlock dt=6142 reason_string=13 stack=11 +GoStart dt=19 g=98 g_seq=3 +GCMarkAssistBegin dt=20 stack=3 +GoStop dt=1738 reason_string=20 stack=9 +GoStart dt=16 g=98 g_seq=4 +GoBlock dt=2102 reason_string=13 stack=11 +GoUnblock dt=2317 g=71 g_seq=5 stack=0 +GoStart dt=5 g=71 g_seq=6 +GoLabel dt=2 label_string=4 +GoBlock dt=128 reason_string=15 stack=5 +GoUnblock dt=2283 g=71 g_seq=13 stack=0 +GoStart dt=7 g=71 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=97 reason_string=15 stack=5 +GoUnblock dt=1168 g=24 g_seq=13 stack=0 +GoStart dt=7 g=24 g_seq=14 +GoLabel dt=1 label_string=4 +GoBlock dt=1399 reason_string=15 stack=5 +GoUnblock dt=3752 g=23 g_seq=25 stack=0 +GoStart dt=6 g=23 g_seq=26 +GoLabel dt=3 label_string=4 +GoBlock dt=1167 reason_string=15 stack=5 +GoUnblock dt=99 g=52 g_seq=23 stack=0 +GoStart dt=35 g=52 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=47 reason_string=15 stack=5 +GoUnblock dt=81 g=67 g_seq=19 stack=0 +GoStart dt=8 g=67 g_seq=20 +GoLabel dt=3 label_string=4 +GoBlock dt=3975 reason_string=15 stack=5 +GoUnblock dt=18 g=67 g_seq=21 stack=0 +GoStart dt=6 g=67 g_seq=22 +GoLabel dt=1 label_string=2 +GoBlock dt=80 reason_string=15 stack=5 +GoUnblock dt=18 g=67 g_seq=23 stack=0 +GoStart dt=6 g=67 g_seq=24 +GoLabel dt=1 label_string=2 +GoBlock dt=22 reason_string=15 stack=5 +GoUnblock dt=3174 g=14 g_seq=23 stack=0 +GoStart dt=7 g=14 g_seq=24 +GoLabel dt=1 label_string=4 +GoBlock dt=22 reason_string=15 stack=5 +GoUnblock dt=9 g=14 g_seq=25 stack=0 +GoStart dt=2 g=14 g_seq=26 +GoLabel dt=1 label_string=2 +GoBlock dt=13 reason_string=15 stack=5 +GoUnblock dt=65 g=29 g_seq=29 stack=0 +GoStart dt=8 g=29 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=18 reason_string=15 stack=5 +GoUnblock dt=13 g=29 g_seq=31 stack=0 +GoStart dt=6 g=29 g_seq=32 +GoLabel dt=2 label_string=2 +GoBlock dt=21 reason_string=15 stack=5 +GoUnblock dt=19 g=24 g_seq=37 stack=0 +GoStart dt=4 g=24 g_seq=38 +GoLabel dt=2 label_string=2 +GoBlock dt=33 reason_string=15 stack=5 +GoUnblock dt=8 g=24 g_seq=39 stack=0 +GoStart dt=3 g=24 g_seq=40 +GoLabel dt=1 label_string=2 +GoBlock dt=32 reason_string=15 stack=5 +GoUnblock dt=80 g=25 g_seq=29 stack=0 +GoStart dt=9 g=25 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=20 reason_string=15 stack=5 +GoUnblock dt=27 g=24 g_seq=43 stack=0 +GoStart dt=6 g=24 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=185 reason_string=15 stack=5 +GoUnblock dt=9 g=24 g_seq=45 stack=0 +GoStart dt=6 g=24 g_seq=46 +GoLabel dt=3 label_string=2 +GoBlock dt=10 reason_string=15 stack=5 +GoUnblock dt=6 g=24 g_seq=47 stack=0 +GoStart dt=1 g=24 g_seq=48 +GoLabel dt=1 label_string=2 +GoBlock dt=41 reason_string=15 stack=5 +ProcStop dt=59 +ProcStart dt=21430 p=4 p_seq=1 +GoStart dt=238 g=102 g_seq=4 +GCMarkAssistEnd dt=10 +HeapAlloc dt=38 heapalloc_value=196352464 +GoStop dt=5526 reason_string=16 stack=6 +ProcStop dt=240 +ProcStart dt=11401 p=6 p_seq=1 +GoStart dt=196 g=109 g_seq=7 +GCMarkAssistEnd dt=5 +HeapAlloc dt=54 heapalloc_value=108264736 +HeapAlloc dt=117 heapalloc_value=108527008 +HeapAlloc dt=77 heapalloc_value=108783776 +HeapAlloc dt=90 heapalloc_value=109036320 +HeapAlloc dt=77 heapalloc_value=109355808 +HeapAlloc dt=106 heapalloc_value=109678240 +HeapAlloc dt=70 heapalloc_value=110030624 +HeapAlloc dt=90 heapalloc_value=110205056 +HeapAlloc dt=51 heapalloc_value=110347136 +HeapAlloc dt=63 heapalloc_value=110588800 +HeapAlloc dt=69 heapalloc_value=110912384 +HeapAlloc dt=42 heapalloc_value=111111808 +HeapAlloc dt=105 heapalloc_value=111452032 +HeapAlloc dt=89 heapalloc_value=111822720 +HeapAlloc dt=106 heapalloc_value=112260352 +HeapAlloc dt=55 heapalloc_value=112397056 +HeapAlloc dt=62 heapalloc_value=112682368 +HeapAlloc dt=137 heapalloc_value=113281920 +GCSweepBegin dt=50 stack=28 +GCSweepEnd dt=8 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=4 heapalloc_value=113424000 +HeapAlloc dt=92 heapalloc_value=113908096 +GCSweepBegin dt=145 stack=31 +EventBatch gen=3 m=169394 time=28114950898962 size=373 +ProcStatus dt=1 p=20 pstatus=1 +GoStatus dt=4 g=108 m=169394 gstatus=2 +GCMarkAssistActive dt=1 g=108 +GCMarkAssistEnd dt=2 +HeapAlloc dt=25 heapalloc_value=191102400 +GCMarkAssistBegin dt=104 stack=3 +GCMarkAssistEnd dt=2445 +HeapAlloc dt=47 heapalloc_value=191372736 +GCMarkAssistBegin dt=11 stack=3 +GoBlock dt=1789 reason_string=13 stack=11 +GoUnblock dt=19 g=22 g_seq=3 stack=0 +GoStart dt=7 g=22 g_seq=4 +GoLabel dt=1 label_string=2 +GoBlock dt=3342 reason_string=15 stack=5 +GoUnblock dt=2752 g=71 g_seq=1 stack=0 +GoStart dt=7 g=71 g_seq=2 +GoLabel dt=1 label_string=4 +GoBlock dt=269 reason_string=15 stack=5 +GoStart dt=4308 g=111 g_seq=3 +GCMarkAssistEnd dt=7 +HeapAlloc dt=58 heapalloc_value=191888832 +GCMarkAssistBegin dt=42 stack=3 +GoBlock dt=148 reason_string=13 stack=11 +GoUnblock dt=1120 g=72 g_seq=25 stack=0 +GoStart dt=5 g=72 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=640 reason_string=15 stack=5 +GoStart dt=1105 g=102 g_seq=2 +GoStatus dt=19 g=117 m=18446744073709551615 gstatus=4 +GoUnblock dt=4 g=117 g_seq=1 stack=10 +GCMarkAssistBegin dt=13 stack=3 +GoBlock dt=32 reason_string=13 stack=11 +GoStart dt=8 g=117 g_seq=2 +GoStatus dt=19 g=128 m=18446744073709551615 gstatus=4 +GoUnblock dt=2 g=128 g_seq=1 stack=10 +GCMarkAssistBegin dt=5 stack=3 +GoBlock dt=15 reason_string=13 stack=11 +GoStart dt=5 g=128 g_seq=2 +GoStatus dt=12 g=92 m=18446744073709551615 gstatus=4 +GoUnblock dt=1 g=92 g_seq=1 stack=10 +GCMarkAssistBegin dt=9 stack=3 +GoBlock dt=14 reason_string=13 stack=11 +GoStart dt=7 g=92 g_seq=2 +GoStatus dt=17 g=101 m=18446744073709551615 gstatus=4 +GoUnblock dt=1 g=101 g_seq=1 stack=10 +GCMarkAssistBegin dt=7 stack=3 +GoBlock dt=10 reason_string=13 stack=11 +GoStart dt=5 g=101 g_seq=2 +GoStatus dt=11 g=99 m=18446744073709551615 gstatus=4 +GoUnblock dt=1 g=99 g_seq=1 stack=10 +GCMarkAssistBegin dt=8 stack=3 +GoBlock dt=15 reason_string=13 stack=11 +GoStart dt=6 g=99 g_seq=2 +GoStatus dt=11 g=89 m=18446744073709551615 gstatus=4 +GoUnblock dt=1 g=89 g_seq=1 stack=10 +GCMarkAssistBegin dt=10 stack=3 +GoBlock dt=15 reason_string=13 stack=11 +GoStart dt=4 g=89 g_seq=2 +GoStatus dt=11 g=124 m=18446744073709551615 gstatus=4 +GoUnblock dt=2 g=124 g_seq=1 stack=10 +GCMarkAssistBegin dt=8 stack=3 +GoBlock dt=34 reason_string=13 stack=11 +GoStart dt=5 g=124 g_seq=2 +GoStatus dt=10 g=96 m=18446744073709551615 gstatus=4 +GoUnblock dt=1 g=96 g_seq=1 stack=10 +GCMarkAssistBegin dt=4 stack=3 +GoBlock dt=14 reason_string=13 stack=11 +GoStart dt=4 g=96 g_seq=2 +GCMarkAssistBegin dt=8 stack=3 +GoBlock dt=22 reason_string=13 stack=11 +ProcStop dt=16 +EventBatch gen=3 m=169393 time=28114950894837 size=271 +ProcStatus dt=2 p=16 pstatus=1 +GoStatus dt=2 g=69 m=169393 gstatus=2 +GoBlock dt=122 reason_string=15 stack=5 +GoStatus dt=2224 g=83 m=169393 gstatus=1 +GoStart dt=1 g=83 g_seq=1 +GoStatus dt=33 g=121 m=18446744073709551615 gstatus=4 +GoUnblock dt=10 g=121 g_seq=1 stack=10 +GCMarkAssistBegin dt=16 stack=3 +GoStop dt=620 reason_string=20 stack=9 +GoStart dt=11 g=121 g_seq=2 +GoStatus dt=18 g=110 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=110 g_seq=1 stack=10 +GCMarkAssistBegin dt=12 stack=3 +GoStop dt=1840 reason_string=20 stack=9 +GoStart dt=16 g=110 g_seq=2 +GoStatus dt=19 g=125 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=125 g_seq=1 stack=10 +GCMarkAssistBegin dt=10 stack=3 +GoBlock dt=1799 reason_string=13 stack=11 +GoStart dt=1317 g=127 g_seq=2 +GoStatus dt=21 g=116 m=18446744073709551615 gstatus=4 +GoUnblock dt=9 g=116 g_seq=1 stack=10 +GCMarkAssistBegin dt=16 stack=3 +GoBlock dt=473 reason_string=13 stack=11 +GoStart dt=28 g=116 g_seq=2 +GoStatus dt=14 g=119 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=119 g_seq=1 stack=10 +GCMarkAssistBegin dt=12 stack=3 +GoStop dt=570 reason_string=20 stack=9 +GoStart dt=24 g=119 g_seq=2 +GoStatus dt=18 g=95 m=18446744073709551615 gstatus=4 +GoUnblock dt=3 g=95 g_seq=1 stack=10 +GCMarkAssistBegin dt=11 stack=3 +GoBlock dt=5206 reason_string=13 stack=11 +ProcStop dt=2547 +ProcStart dt=26 p=16 p_seq=1 +GoUnblock dt=87 g=58 g_seq=15 stack=0 +GoStart dt=8 g=58 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=579 reason_string=15 stack=5 +GoUnblock dt=23 g=69 g_seq=15 stack=0 +GoStart dt=5 g=69 g_seq=16 +GoLabel dt=1 label_string=2 +GoBlock dt=1028 reason_string=15 stack=5 +GoUnblock dt=2356 g=14 g_seq=11 stack=0 +GoStart dt=6 g=14 g_seq=12 +GoLabel dt=1 label_string=4 +GoBlock dt=1282 reason_string=15 stack=5 +ProcStop dt=8 +EventBatch gen=3 m=169392 time=28114950898262 size=651 +ProcStatus dt=1 p=3 pstatus=1 +GoStatus dt=1 g=106 m=169392 gstatus=2 +GCMarkAssistActive dt=1 g=106 +GCMarkAssistEnd dt=3 +HeapAlloc dt=34 heapalloc_value=190807488 +HeapAlloc dt=125 heapalloc_value=190832064 +GCMarkAssistBegin dt=46 stack=3 +GoBlock dt=1002 reason_string=13 stack=11 +GoStart dt=28 g=82 g_seq=2 +GoBlock dt=1446 reason_string=13 stack=11 +GoStart dt=34 g=120 g_seq=3 +GCMarkAssistEnd dt=2 +HeapAlloc dt=32 heapalloc_value=191282624 +GCMarkAssistBegin dt=115 stack=3 +GoBlock dt=25 reason_string=13 stack=11 +GoStart dt=17 g=112 g_seq=2 +GoBlock dt=2074 reason_string=13 stack=11 +GoUnblock dt=2604 g=24 g_seq=5 stack=0 +GoStart dt=7 g=24 g_seq=6 +GoLabel dt=2 label_string=4 +GoBlock dt=278 reason_string=15 stack=5 +GoUnblock dt=2267 g=58 g_seq=5 stack=0 +GoStart dt=9 g=58 g_seq=6 +GoLabel dt=1 label_string=4 +GoBlock dt=316 reason_string=15 stack=5 +GoUnblock dt=1167 g=24 g_seq=7 stack=0 +GoStart dt=6 g=24 g_seq=8 +GoLabel dt=1 label_string=4 +GoBlock dt=171 reason_string=15 stack=5 +GoUnblock dt=1155 g=71 g_seq=7 stack=0 +GoStart dt=6 g=71 g_seq=8 +GoLabel dt=1 label_string=4 +GoBlock dt=32 reason_string=15 stack=5 +GoStart dt=3316 g=109 g_seq=2 +GoStatus dt=28 g=114 m=18446744073709551615 gstatus=4 +GoUnblock dt=8 g=114 g_seq=1 stack=10 +GCMarkAssistBegin dt=18 stack=3 +GoStop dt=3860 reason_string=20 stack=9 +GoUnblock dt=14 g=57 g_seq=31 stack=0 +GoStart dt=5 g=57 g_seq=32 +GoLabel dt=3 label_string=2 +GoBlock dt=3324 reason_string=15 stack=5 +GoUnblock dt=97 g=24 g_seq=25 stack=0 +GoStart dt=6 g=24 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=1146 reason_string=15 stack=5 +GoUnblock dt=73 g=24 g_seq=27 stack=0 +GoStart dt=4 g=24 g_seq=28 +GoLabel dt=1 label_string=4 +GoUnblock dt=2655 g=81 g_seq=4 stack=12 +GoBlock dt=402 reason_string=15 stack=5 +GoUnblock dt=9 g=24 g_seq=29 stack=0 +GoStart dt=7 g=24 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=492 reason_string=15 stack=5 +GoUnblock dt=21 g=69 g_seq=27 stack=0 +GoStart dt=6 g=69 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=20 reason_string=15 stack=5 +GoUnblock dt=11 g=69 g_seq=29 stack=0 +GoStart dt=3 g=69 g_seq=30 +GoLabel dt=1 label_string=2 +GoBlock dt=459 reason_string=15 stack=5 +GoStart dt=168 g=116 g_seq=6 +GCMarkAssistEnd dt=8 +HeapAlloc dt=61 heapalloc_value=192232224 +GCMarkAssistBegin dt=39 stack=3 +GoBlock dt=2360 reason_string=13 stack=11 +ProcStop dt=53 +ProcStart dt=14760 p=10 p_seq=2 +GoStart dt=211 g=99 g_seq=5 +GCMarkAssistBegin dt=93 stack=3 +GoBlock dt=33 reason_string=13 stack=11 +GoStart dt=9 g=120 g_seq=6 +GCMarkAssistBegin dt=78 stack=3 +GoBlock dt=102 reason_string=13 stack=11 +GoStart dt=31 g=108 g_seq=2 +GCMarkAssistEnd dt=6 +HeapAlloc dt=307 heapalloc_value=194853592 +GoStop dt=7166 reason_string=16 stack=6 +GoStart dt=86 g=128 g_seq=6 +HeapAlloc dt=4873 heapalloc_value=196688336 +GoStop dt=12 reason_string=16 stack=6 +ProcStop dt=395 +ProcStart dt=8670 p=3 p_seq=2 +GoStart dt=193 g=93 g_seq=9 +GCMarkAssistEnd dt=7 +HeapAlloc dt=78 heapalloc_value=104465440 +HeapAlloc dt=122 heapalloc_value=104583584 +HeapAlloc dt=92 heapalloc_value=104769312 +HeapAlloc dt=127 heapalloc_value=104935968 +GCSweepBegin dt=109 stack=28 +GCSweepEnd dt=9 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=2 heapalloc_value=105138720 +HeapAlloc dt=77 heapalloc_value=105373856 +GCSweepBegin dt=157 stack=28 +GCSweepEnd dt=8 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=3 heapalloc_value=105708448 +GCSweepBegin dt=56 stack=28 +GCSweepEnd dt=11 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=4 heapalloc_value=105880480 +GCSweepBegin dt=48 stack=28 +GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768 +HeapAlloc dt=4 heapalloc_value=106124192 +GCSweepBegin dt=79 stack=28 +GCSweepEnd dt=7 swept_value=8192 reclaimed_value=8192 +HeapAlloc dt=2 heapalloc_value=106283168 +HeapAlloc dt=98 heapalloc_value=106567968 +HeapAlloc dt=116 heapalloc_value=107070496 +HeapAlloc dt=30 heapalloc_value=107146272 +HeapAlloc dt=105 heapalloc_value=107517728 +HeapAlloc dt=169 heapalloc_value=108084512 +HeapAlloc dt=187 heapalloc_value=108649888 +HeapAlloc dt=158 heapalloc_value=109200160 +HeapAlloc dt=200 heapalloc_value=109872160 +GCSweepBegin dt=116 stack=28 +GCSweepEnd dt=9 swept_value=24576 reclaimed_value=24576 +HeapAlloc dt=3 heapalloc_value=110229632 +HeapAlloc dt=54 heapalloc_value=110441344 +HeapAlloc dt=76 heapalloc_value=110711680 +HeapAlloc dt=100 heapalloc_value=111216768 +HeapAlloc dt=156 heapalloc_value=111708032 +HeapAlloc dt=55 heapalloc_value=111972224 +HeapAlloc dt=122 heapalloc_value=112391424 +HeapAlloc dt=160 heapalloc_value=113099392 +HeapAlloc dt=191 heapalloc_value=113713536 +HeapAlloc dt=158 heapalloc_value=114362368 +GCSweepBegin dt=88 stack=28 +GCSweepEnd dt=14 swept_value=16384 reclaimed_value=16384 +HeapAlloc dt=9 heapalloc_value=114520320 +HeapAlloc dt=56 heapalloc_value=114636672 +GCSweepBegin dt=180 stack=27 +EventBatch gen=3 m=169390 time=28114950895313 size=834 +ProcStatus dt=1 p=27 pstatus=1 +GoStatus dt=3 g=82 m=169390 gstatus=2 +GCMarkAssistActive dt=1 g=82 +GCMarkAssistEnd dt=2 +HeapAlloc dt=28 heapalloc_value=190143936 +HeapAlloc dt=270 heapalloc_value=190201280 +HeapAlloc dt=96 heapalloc_value=190209472 +HeapAlloc dt=29 heapalloc_value=190258624 +HeapAlloc dt=107 heapalloc_value=190356928 +GCMarkAssistBegin dt=57 stack=3 +GCMarkAssistEnd dt=502 +HeapAlloc dt=27 heapalloc_value=190430656 +GoStop dt=26 reason_string=16 stack=4 +GoStart dt=12 g=131 g_seq=3 +GoSyscallBegin dt=17 p_seq=1 stack=7 +GoSyscallEnd dt=205 +GoSyscallBegin dt=19 p_seq=2 stack=7 +GoSyscallEnd dt=2580 +GoSyscallBegin dt=16 p_seq=3 stack=7 +GoSyscallEnd dt=71 +GoSyscallBegin dt=15 p_seq=4 stack=7 +GoSyscallEnd dt=72 +GoSyscallBegin dt=25 p_seq=5 stack=7 +GoSyscallEnd dt=76 +GoSyscallBegin dt=12 p_seq=6 stack=7 +GoSyscallEnd dt=69 +GoSyscallBegin dt=11 p_seq=7 stack=7 +GoSyscallEnd dt=62 +GoSyscallBegin dt=13 p_seq=8 stack=7 +GoSyscallEnd dt=67 +GoSyscallBegin dt=16 p_seq=9 stack=7 +GoSyscallEnd dt=64 +GoSyscallBegin dt=12 p_seq=10 stack=7 +GoSyscallEnd dt=65 +GoSyscallBegin dt=14 p_seq=11 stack=7 +GoSyscallEnd dt=226 +GoSyscallBegin dt=14 p_seq=12 stack=7 +GoSyscallEnd dt=69 +GoSyscallBegin dt=17 p_seq=13 stack=7 +GoSyscallEnd dt=72 +GoSyscallBegin dt=15 p_seq=14 stack=7 +GoSyscallEnd dt=66 +GoSyscallBegin dt=18 p_seq=15 stack=7 +GoSyscallEnd dt=63 +GoSyscallBegin dt=13 p_seq=16 stack=7 +GoSyscallEnd dt=69 +GoSyscallBegin dt=17 p_seq=17 stack=7 +GoSyscallEnd dt=66 +GoSyscallBegin dt=109 p_seq=18 stack=7 +GoSyscallEnd dt=73 +GoSyscallBegin dt=13 p_seq=19 stack=7 +GoSyscallEnd dt=68 +GoSyscallBegin dt=16 p_seq=20 stack=7 +GoSyscallEnd dt=63 +GoSyscallBegin dt=15 p_seq=21 stack=7 +GoSyscallEnd dt=82 +GoSyscallBegin dt=11 p_seq=22 stack=7 +GoSyscallEnd dt=177 +GoSyscallBegin dt=14 p_seq=23 stack=7 +GoSyscallEnd dt=62 +GoSyscallBegin dt=13 p_seq=24 stack=7 +GoSyscallEnd dt=90 +GoSyscallBegin dt=11 p_seq=25 stack=7 +GoSyscallEnd dt=69 +GoSyscallBegin dt=13 p_seq=26 stack=7 +GoSyscallEnd dt=65 +GoSyscallBegin dt=15 p_seq=27 stack=7 +GoSyscallEnd dt=72 +GoSyscallBegin dt=15 p_seq=28 stack=7 +GoSyscallEnd dt=73 +GoSyscallBegin dt=18 p_seq=29 stack=7 +GoSyscallEnd dt=80 +GoSyscallBegin dt=21 p_seq=30 stack=7 +GoSyscallEnd dt=72 +GoSyscallBegin dt=17 p_seq=31 stack=7 +GoSyscallEnd dt=67 +GoSyscallBegin dt=12 p_seq=32 stack=7 +GoSyscallEnd dt=171 +GoSyscallBegin dt=16 p_seq=33 stack=7 +GoSyscallEnd dt=76 +GoSyscallBegin dt=18 p_seq=34 stack=7 +GoSyscallEnd dt=78 +GoSyscallBegin dt=13 p_seq=35 stack=7 +GoSyscallEnd dt=77 +GoSyscallBegin dt=20 p_seq=36 stack=7 +GoSyscallEnd dt=77 +GoBlock dt=16 reason_string=15 stack=2 +GoUnblock dt=1400 g=54 g_seq=3 stack=0 +GoStart dt=8 g=54 g_seq=4 +GoLabel dt=1 label_string=4 +GoBlock dt=2659 reason_string=15 stack=5 +GoUnblock dt=13 g=22 g_seq=5 stack=0 +GoStart dt=5 g=22 g_seq=6 +GoLabel dt=1 label_string=2 +GoBlock dt=2498 reason_string=15 stack=5 +GoUnblock dt=10 g=22 g_seq=7 stack=0 +GoStart dt=7 g=22 g_seq=8 +GoLabel dt=2 label_string=2 +GoBlock dt=4213 reason_string=15 stack=5 +GoUnblock dt=1324 g=57 g_seq=25 stack=0 +GoStart dt=11 g=57 g_seq=26 +GoLabel dt=1 label_string=4 +GoBlock dt=256 reason_string=15 stack=5 +GoUnblock dt=8 g=57 g_seq=27 stack=0 +GoStart dt=5 g=57 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=485 reason_string=15 stack=5 +GoUnblock dt=8 g=57 g_seq=29 stack=0 +GoStart dt=6 g=57 g_seq=30 +GoLabel dt=3 label_string=2 +GoBlock dt=504 reason_string=15 stack=5 +ProcStop dt=3771 +ProcStart dt=29 p=27 p_seq=37 +GoUnblock dt=9 g=22 g_seq=15 stack=0 +GoStart dt=5 g=22 g_seq=16 +GoLabel dt=1 label_string=4 +GoBlock dt=123 reason_string=15 stack=5 +GoUnblock dt=19 g=28 g_seq=7 stack=0 +GoStart dt=2 g=28 g_seq=8 +GoLabel dt=1 label_string=2 +GoBlock dt=67 reason_string=15 stack=5 +GoUnblock dt=73 g=72 g_seq=29 stack=0 +GoStart dt=8 g=72 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=1357 reason_string=15 stack=5 +GoUnblock dt=71 g=53 g_seq=15 stack=0 +GoStart dt=5 g=53 g_seq=16 +GoLabel dt=2 label_string=4 +GoBlock dt=53 reason_string=15 stack=5 +ProcStop dt=61 +ProcStart dt=29 p=27 p_seq=38 +GoUnblock dt=4 g=72 g_seq=35 stack=0 +GoStart dt=4 g=72 g_seq=36 +GoLabel dt=1 label_string=4 +GoBlock dt=775 reason_string=15 stack=5 +GoUnblock dt=11 g=72 g_seq=37 stack=0 +GoStart dt=5 g=72 g_seq=38 +GoLabel dt=3 label_string=2 +GoBlock dt=2553 reason_string=15 stack=5 +GoUnblock dt=23 g=54 g_seq=27 stack=0 +GoStart dt=7 g=54 g_seq=28 +GoLabel dt=1 label_string=2 +GoBlock dt=5185 reason_string=15 stack=5 +ProcStop dt=46 +ProcStart dt=1102 p=27 p_seq=39 +GoUnblock dt=17 g=14 g_seq=31 stack=0 +GoStart dt=191 g=14 g_seq=32 +GoLabel dt=5 label_string=2 +GoBlock dt=26 reason_string=15 stack=5 +GoUnblock dt=7 g=14 g_seq=33 stack=0 +GoStart dt=2 g=14 g_seq=34 +GoLabel dt=1 label_string=2 +GoBlock dt=81 reason_string=15 stack=5 +GoUnblock dt=11 g=14 g_seq=35 stack=0 +GoStart dt=6 g=14 g_seq=36 +GoLabel dt=1 label_string=2 +GoUnblock dt=257 g=97 g_seq=3 stack=12 +GoStop dt=1123 reason_string=16 stack=13 +GoUnblock dt=612 g=131 g_seq=4 stack=0 +GoStart dt=5 g=131 g_seq=5 +GoSyscallBegin dt=23 p_seq=40 stack=7 +GoSyscallEnd dt=200 +GoSyscallBegin dt=13 p_seq=41 stack=7 +GoSyscallEnd dt=179 +GoBlock dt=6 reason_string=15 stack=2 +ProcStop dt=31 +ProcStart dt=1232 p=22 p_seq=3 +GoUnblock dt=16 g=14 g_seq=40 stack=0 +GoStart dt=157 g=14 g_seq=41 +GoLabel dt=2 label_string=2 +GoUnblock dt=343 g=103 g_seq=1 stack=12 +GoBlock dt=2805 reason_string=15 stack=5 +ProcStop dt=68 +ProcStart dt=17 p=22 p_seq=4 +GoUnblock dt=3 g=14 g_seq=42 stack=0 +GoStart dt=4 g=14 g_seq=43 +GoLabel dt=1 label_string=4 +GoUnblock dt=609 g=116 g_seq=7 stack=12 +GoBlock dt=9 reason_string=15 stack=5 +GoStart dt=10 g=116 g_seq=8 +GCMarkAssistEnd dt=7 +HeapAlloc dt=60 heapalloc_value=192527064 +GCMarkAssistBegin dt=41 stack=3 +GoBlock dt=47 reason_string=13 stack=11 +GoUnblock dt=13 g=30 g_seq=35 stack=0 +GoStart dt=4 g=30 g_seq=36 +GoLabel dt=2 label_string=2 +GoBlock dt=266 reason_string=15 stack=5 +GoStart dt=16 g=105 g_seq=8 +GoBlock dt=18 reason_string=13 stack=11 +GoUnblock dt=55 g=54 g_seq=29 stack=0 +GoStart dt=8 g=54 g_seq=30 +GoLabel dt=1 label_string=4 +GoBlock dt=13 reason_string=15 stack=5 +GoUnblock dt=10 g=54 g_seq=31 stack=0 +GoStart dt=1 g=54 g_seq=32 +GoLabel dt=1 label_string=2 +GoBlock dt=46 reason_string=15 stack=5 +ProcStop dt=57 +ProcStart dt=14 p=22 p_seq=5 +GoUnblock dt=4 g=54 g_seq=33 stack=0 +GoStart dt=159 g=54 g_seq=34 +GoLabel dt=1 label_string=4 +GoBlock dt=8 reason_string=15 stack=5 +ProcStop dt=32 +ProcStart dt=3156 p=29 p_seq=1 +GoUnblock dt=15 g=71 g_seq=43 stack=0 +GoStart dt=165 g=71 g_seq=44 +GoLabel dt=1 label_string=2 +GoBlock dt=1463 reason_string=15 stack=5 +GoStart dt=22 g=118 g_seq=4 +GCMarkAssistEnd dt=6 +HeapAlloc dt=903 heapalloc_value=195328728 +GoStop dt=6525 reason_string=16 stack=6 +GoStart dt=46 g=118 g_seq=5 +GCMarkAssistBegin dt=12 stack=3 +GoBlock dt=31 reason_string=13 stack=11 +ProcStop dt=194 +EventBatch gen=3 m=18446744073709551615 time=28114950975784 size=435 +GoStatus dt=1 g=1 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=2 m=18446744073709551615 gstatus=4 +GoStatus dt=6 g=4 m=18446744073709551615 gstatus=4 +GoStatus dt=5 g=5 m=18446744073709551615 gstatus=4 +GoStatus dt=4 g=6 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=7 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=17 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=33 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=8 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=9 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=10 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=18 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=11 m=18446744073709551615 gstatus=4 +GoStatus dt=4 g=34 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=19 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=12 m=18446744073709551615 gstatus=4 +GoStatus dt=2 g=20 m=18446744073709551615 gstatus=4 +GoStatus dt=4 g=35 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=13 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=21 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=36 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=49 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=50 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=15 m=18446744073709551615 gstatus=4 +GoStatus dt=4 g=65 m=18446744073709551615 gstatus=4 +GoStatus dt=2 g=66 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=26 m=18446744073709551615 gstatus=4 +GoStatus dt=4 g=55 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=27 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=37 m=18446744073709551615 gstatus=4 +GoStatus dt=3 g=129 m=18446744073709551615 gstatus=4 +EventBatch gen=3 m=18446744073709551615 time=28114950976078 size=1132 +Stacks +Stack id=20 nframes=2 + pc=4540421 func=22 file=23 line=363 + pc=4546157 func=24 file=23 line=874 +Stack id=21 nframes=5 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=18 nframes=6 + pc=4296626 func=34 file=35 line=807 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=26 nframes=7 + pc=4300939 func=36 file=35 line=1196 + pc=4297301 func=34 file=35 line=926 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=7 nframes=7 + pc=4709082 func=37 file=38 line=964 + pc=4738119 func=39 file=40 line=209 + pc=4738111 func=41 file=42 line=736 + pc=4737664 func=43 file=42 line=380 + pc=4739536 func=44 file=45 line=46 + pc=4739528 func=46 file=47 line=183 + pc=4803162 func=48 file=49 line=134 +Stack id=10 nframes=4 + pc=4295522 func=50 file=35 line=627 + pc=4246870 func=29 file=28 line=1288 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=29 nframes=8 + pc=4556437 func=51 file=52 line=352 + pc=4341796 func=53 file=54 line=521 + pc=4279859 func=55 file=56 line=127 + pc=4277746 func=57 file=58 line=182 + pc=4244580 func=59 file=28 line=944 + pc=4245653 func=29 file=28 line=1116 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=14 nframes=1 + pc=4546157 func=24 file=23 line=874 +Stack id=17 nframes=1 + pc=0 func=0 file=0 line=0 +Stack id=19 nframes=2 + pc=4540420 func=22 file=23 line=353 + pc=4546157 func=24 file=23 line=874 +Stack id=13 nframes=1 + pc=0 func=0 file=0 line=0 +Stack id=5 nframes=2 + pc=4418893 func=60 file=61 line=402 + pc=4301860 func=62 file=35 line=1297 +Stack id=25 nframes=7 + pc=4298957 func=36 file=35 line=1087 + pc=4297301 func=34 file=35 line=926 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=4 nframes=2 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=30 nframes=6 + pc=4297308 func=34 file=35 line=817 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=11 nframes=6 + pc=4314276 func=63 file=26 line=749 + pc=4312530 func=25 file=26 line=589 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=6 nframes=2 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=15 nframes=1 + pc=4546157 func=24 file=23 line=874 +Stack id=8 nframes=1 + pc=0 func=0 file=0 line=0 +Stack id=12 nframes=2 + pc=4614055 func=64 file=65 line=474 + pc=4302129 func=62 file=35 line=1357 +Stack id=3 nframes=6 + pc=4556897 func=66 file=52 line=378 + pc=4312252 func=25 file=26 line=536 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=9 nframes=5 + pc=4312495 func=25 file=26 line=576 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=24 nframes=8 + pc=4614055 func=64 file=65 line=474 + pc=4298031 func=36 file=35 line=964 + pc=4297301 func=34 file=35 line=926 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=23 nframes=6 + pc=4297239 func=34 file=35 line=914 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=2 nframes=1 + pc=4803172 func=48 file=49 line=130 +Stack id=28 nframes=8 + pc=4556437 func=51 file=52 line=352 + pc=4341796 func=53 file=54 line=521 + pc=4280028 func=55 file=56 line=147 + pc=4277746 func=57 file=58 line=182 + pc=4244580 func=59 file=28 line=944 + pc=4246070 func=29 file=28 line=1145 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=27 nframes=5 + pc=4353658 func=67 file=68 line=958 + pc=4278148 func=69 file=58 line=234 + pc=4246244 func=29 file=28 line=1160 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=16 nframes=3 + pc=4217457 func=70 file=71 line=442 + pc=4546317 func=72 file=23 line=918 + pc=4546150 func=24 file=23 line=871 +Stack id=31 nframes=8 + pc=4353658 func=67 file=68 line=958 + pc=4280657 func=73 file=56 line=254 + pc=4280247 func=55 file=56 line=170 + pc=4277746 func=57 file=58 line=182 + pc=4244580 func=59 file=28 line=944 + pc=4246070 func=29 file=28 line=1145 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +Stack id=1 nframes=3 + pc=4554859 func=74 file=52 line=255 + pc=4540633 func=22 file=23 line=391 + pc=4546157 func=24 file=23 line=874 +Stack id=22 nframes=10 + pc=4558967 func=75 file=76 line=166 + pc=4558898 func=77 file=52 line=445 + pc=4447453 func=78 file=61 line=3712 + pc=4314041 func=79 file=26 line=714 + pc=4297238 func=34 file=35 line=909 + pc=4312466 func=25 file=26 line=564 + pc=4247187 func=27 file=28 line=1333 + pc=4245160 func=29 file=28 line=1021 + pc=4502184 func=30 file=31 line=103 + pc=4804475 func=32 file=33 line=60 +EventBatch gen=3 m=18446744073709551615 time=28114950894688 size=2762 +Strings +String id=1 + data="Not worker" +String id=2 + data="GC (dedicated)" +String id=3 + data="GC (fractional)" +String id=4 + data="GC (idle)" +String id=5 + data="unspecified" +String id=6 + data="forever" +String id=7 + data="network" +String id=8 + data="select" +String id=9 + data="sync.(*Cond).Wait" +String id=10 + data="sync" +String id=11 + data="chan send" +String id=12 + data="chan receive" +String id=13 + data="GC mark assist wait for work" +String id=14 + data="GC background sweeper wait" +String id=15 + data="system goroutine wait" +String id=16 + data="preempted" +String id=17 + data="wait for debug call" +String id=18 + data="wait until GC ends" +String id=19 + data="sleep" +String id=20 + data="runtime.Gosched" +String id=21 + data="GC mark termination" +String id=22 + data="runtime.traceAdvance" +String id=23 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go" +String id=24 + data="runtime.(*traceAdvancerState).start.func1" +String id=25 + data="runtime.gcAssistAlloc" +String id=26 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgcmark.go" +String id=27 + data="runtime.deductAssistCredit" +String id=28 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/malloc.go" +String id=29 + data="runtime.mallocgc" +String id=30 + data="runtime.makeslice" +String id=31 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/slice.go" +String id=32 + data="main.main.func1" +String id=33 + data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/gc-stress.go" +String id=34 + data="runtime.gcMarkDone" +String id=35 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgc.go" +String id=36 + data="runtime.gcMarkTermination" +String id=37 + data="syscall.write" +String id=38 + data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/zsyscall_linux_amd64.go" +String id=39 + data="syscall.Write" +String id=40 + data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/syscall_unix.go" +String id=41 + data="internal/poll.ignoringEINTRIO" +String id=42 + data="/usr/local/google/home/mknyszek/work/go-1/src/internal/poll/fd_unix.go" +String id=43 + data="internal/poll.(*FD).Write" +String id=44 + data="os.(*File).write" +String id=45 + data="/usr/local/google/home/mknyszek/work/go-1/src/os/file_posix.go" +String id=46 + data="os.(*File).Write" +String id=47 + data="/usr/local/google/home/mknyszek/work/go-1/src/os/file.go" +String id=48 + data="runtime/trace.Start.func1" +String id=49 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go" +String id=50 + data="runtime.gcStart" +String id=51 + data="runtime.traceLocker.GCSweepSpan" +String id=52 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go" +String id=53 + data="runtime.(*sweepLocked).sweep" +String id=54 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgcsweep.go" +String id=55 + data="runtime.(*mcentral).cacheSpan" +String id=56 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mcentral.go" +String id=57 + data="runtime.(*mcache).refill" +String id=58 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mcache.go" +String id=59 + data="runtime.(*mcache).nextFree" +String id=60 + data="runtime.gopark" +String id=61 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go" +String id=62 + data="runtime.gcBgMarkWorker" +String id=63 + data="runtime.gcParkAssist" +String id=64 + data="runtime.systemstack_switch" +String id=65 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/asm_amd64.s" +String id=66 + data="runtime.traceLocker.GCMarkAssistStart" +String id=67 + data="runtime.(*mheap).alloc" +String id=68 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mheap.go" +String id=69 + data="runtime.(*mcache).allocLarge" +String id=70 + data="runtime.chanrecv1" +String id=71 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go" +String id=72 + data="runtime.(*wakeableSleep).sleep" +String id=73 + data="runtime.(*mcentral).grow" +String id=74 + data="runtime.traceLocker.Gomaxprocs" +String id=75 + data="runtime.traceLocker.stack" +String id=76 + data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2event.go" +String id=77 + data="runtime.traceLocker.GoUnpark" +String id=78 + data="runtime.injectglist" +String id=79 + data="runtime.gcWakeAllAssists" diff --git a/go/src/internal/trace/testdata/tests/go122-go-create-without-running-g.test b/go/src/internal/trace/testdata/tests/go122-go-create-without-running-g.test new file mode 100644 index 0000000000000000000000000000000000000000..494c444ca37eb20667f1628e5f21fa28ab94c2f0 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-go-create-without-running-g.test @@ -0,0 +1,17 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=17 +ProcStatus dt=1 p=0 pstatus=1 +GoCreate dt=1 new_g=5 new_stack=0 stack=0 +GoStart dt=1 g=5 g_seq=1 +GoStop dt=1 reason_string=1 stack=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=12 +Strings +String id=1 + data="whatever" diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-ambiguous.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-ambiguous.test new file mode 100644 index 0000000000000000000000000000000000000000..0d88af4d61467d290b604271df6ba3ecedffa586 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-ambiguous.test @@ -0,0 +1,21 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=21 +ProcStatus dt=0 p=0 pstatus=1 +GoStatus dt=0 g=1 m=0 gstatus=2 +GoSyscallBegin dt=0 p_seq=1 stack=0 +GoSyscallEnd dt=0 +GoSyscallBegin dt=0 p_seq=2 stack=0 +GoSyscallEndBlocked dt=0 +EventBatch gen=1 m=1 time=0 size=14 +ProcStatus dt=0 p=2 pstatus=1 +GoStatus dt=0 g=2 m=1 gstatus=2 +ProcSteal dt=0 p=0 p_seq=3 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test new file mode 100644 index 0000000000000000000000000000000000000000..bbfc9cc877eee4a3bd584fa8012742ea81800efc --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test @@ -0,0 +1,17 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=11 +ProcStatus dt=1 p=1 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=3 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=9 +ProcStatus dt=1 p=0 pstatus=4 +ProcSteal dt=1 p=0 p_seq=1 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test new file mode 100644 index 0000000000000000000000000000000000000000..8e291327cf0e27bce70646f56333f50f5b0c376f --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test @@ -0,0 +1,18 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=15 +GoStatus dt=1 g=1 m=0 gstatus=3 +ProcStatus dt=1 p=1 pstatus=2 +ProcStart dt=1 p=1 p_seq=1 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=9 +ProcStatus dt=1 p=0 pstatus=4 +ProcSteal dt=1 p=0 p_seq=1 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test new file mode 100644 index 0000000000000000000000000000000000000000..3b26e8f13f5498b3337a56da4133f9222ccd0f8a --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test @@ -0,0 +1,20 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=15 +GoStatus dt=1 g=1 m=0 gstatus=3 +ProcStatus dt=1 p=1 pstatus=2 +ProcStart dt=1 p=1 p_seq=1 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=18 +ProcStatus dt=1 p=2 pstatus=1 +GoStatus dt=1 g=2 m=1 gstatus=2 +ProcStatus dt=1 p=0 pstatus=4 +ProcSteal dt=1 p=0 p_seq=1 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary.test new file mode 100644 index 0000000000000000000000000000000000000000..133d8a5447c2aaaaa9462ee0fdc093105ba81a31 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-gen-boundary.test @@ -0,0 +1,19 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=11 +ProcStatus dt=1 p=1 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=3 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=18 +ProcStatus dt=1 p=2 pstatus=1 +GoStatus dt=1 g=2 m=1 gstatus=2 +ProcStatus dt=1 p=0 pstatus=4 +ProcSteal dt=1 p=0 p_seq=1 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test new file mode 100644 index 0000000000000000000000000000000000000000..fa68c824b91ce402d3d38c87bb62f7563359a04c --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test @@ -0,0 +1,19 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=23 +ProcStatus dt=1 p=1 pstatus=2 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +GoSyscallBegin dt=1 p_seq=1 stack=0 +ProcStart dt=1 p=1 p_seq=1 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=5 +ProcSteal dt=1 p=0 p_seq=2 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test new file mode 100644 index 0000000000000000000000000000000000000000..85c19fcf05d021b6b8790c5b0cf9857f41288d2d --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test @@ -0,0 +1,21 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=23 +ProcStatus dt=1 p=1 pstatus=2 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +GoSyscallBegin dt=1 p_seq=1 stack=0 +ProcStart dt=1 p=1 p_seq=1 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=14 +ProcStatus dt=1 p=2 pstatus=1 +GoStatus dt=1 g=2 m=1 gstatus=2 +ProcSteal dt=1 p=0 p_seq=2 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-self.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-self.test new file mode 100644 index 0000000000000000000000000000000000000000..6484eb6d35cca9c1445effb72e1ef91d621d2ca8 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-self.test @@ -0,0 +1,17 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=24 +ProcStatus dt=0 p=0 pstatus=1 +GoStatus dt=0 g=1 m=0 gstatus=2 +GoSyscallBegin dt=0 p_seq=1 stack=0 +ProcSteal dt=0 p=0 p_seq=2 m=0 +ProcStart dt=0 p=0 p_seq=3 +GoSyscallEndBlocked dt=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test new file mode 100644 index 0000000000000000000000000000000000000000..d33872287d5ed5bcfc3a949255173d2256d9ba54 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test @@ -0,0 +1,17 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=15 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +GoSyscallBegin dt=1 p_seq=1 stack=0 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=5 +ProcSteal dt=1 p=0 p_seq=2 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple.test new file mode 100644 index 0000000000000000000000000000000000000000..a1f9db41d4729f2f6416e793d6309f6e9793b266 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-simple.test @@ -0,0 +1,19 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=15 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +GoSyscallBegin dt=1 p_seq=1 stack=0 +GoSyscallEndBlocked dt=1 +EventBatch gen=1 m=1 time=0 size=14 +ProcStatus dt=1 p=2 pstatus=1 +GoStatus dt=1 g=2 m=1 gstatus=2 +ProcSteal dt=1 p=0 p_seq=2 m=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test new file mode 100644 index 0000000000000000000000000000000000000000..58c41c55491d059354cd11a7392af74fb67069b2 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test @@ -0,0 +1,15 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=9 +ProcStatus dt=1 p=0 pstatus=4 +ProcSteal dt=1 p=0 p_seq=1 m=1 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +GoStatus dt=1 g=1 m=1 gstatus=3 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go122-task-across-generations.test b/go/src/internal/trace/testdata/tests/go122-task-across-generations.test new file mode 100644 index 0000000000000000000000000000000000000000..0b8abd7346416b8843e1a4eeecc10124138608d6 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go122-task-across-generations.test @@ -0,0 +1,26 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.22 +EventBatch gen=1 m=0 time=0 size=15 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +UserTaskBegin dt=1 task=2 parent_task=0 name_string=1 stack=0 +EventBatch gen=1 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=1 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=0 size=11 +Strings +String id=1 + data="my task" +EventBatch gen=2 m=0 time=5 size=13 +ProcStatus dt=1 p=0 pstatus=1 +GoStatus dt=1 g=1 m=0 gstatus=2 +UserTaskEnd dt=1 task=2 stack=0 +EventBatch gen=2 m=18446744073709551615 time=0 size=5 +Frequency freq=15625000 +EventBatch gen=2 m=18446744073709551615 time=0 size=1 +Stacks +EventBatch gen=2 m=18446744073709551615 time=0 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go123-sync.test b/go/src/internal/trace/testdata/tests/go123-sync.test new file mode 100644 index 0000000000000000000000000000000000000000..44e98e6c959a11a8d12af340272ef4d91d7df659 --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go123-sync.test @@ -0,0 +1,26 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.23 +EventBatch gen=1 m=1 time=15 size=4 +ProcStatus dt=1 p=0 pstatus=1 +EventBatch gen=1 m=18446744073709551615 time=10 size=6 +Frequency freq=1000000000 +EventBatch gen=1 m=18446744073709551615 time=11 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=12 size=1 +Strings +EventBatch gen=2 m=18446744073709551615 time=20 size=6 +Frequency freq=500000000 +EventBatch gen=2 m=18446744073709551615 time=21 size=1 +Stacks +EventBatch gen=2 m=18446744073709551615 time=22 size=1 +Strings +EventBatch gen=3 m=1 time=30 size=4 +ProcStatus dt=1 p=0 pstatus=1 +EventBatch gen=3 m=18446744073709551615 time=40 size=6 +Frequency freq=500000000 +EventBatch gen=3 m=18446744073709551615 time=41 size=1 +Stacks +EventBatch gen=3 m=18446744073709551615 time=42 size=1 +Strings diff --git a/go/src/internal/trace/testdata/tests/go125-sync.test b/go/src/internal/trace/testdata/tests/go125-sync.test new file mode 100644 index 0000000000000000000000000000000000000000..dac3723b62f5a15619e77766d8dc501b46f4e65f --- /dev/null +++ b/go/src/internal/trace/testdata/tests/go125-sync.test @@ -0,0 +1,32 @@ +-- expect -- +SUCCESS +-- trace -- +Trace Go1.25 +EventBatch gen=1 m=18446744073709551615 time=9 size=16 +Sync +Frequency freq=1000000000 +ClockSnapshot dt=1 mono=99 sec=1740755049 nsec=123 +EventBatch gen=1 m=1 time=15 size=4 +ProcStatus dt=1 p=0 pstatus=1 +EventBatch gen=1 m=18446744073709551615 time=11 size=1 +Stacks +EventBatch gen=1 m=18446744073709551615 time=12 size=1 +Strings +EventBatch gen=2 m=18446744073709551615 time=19 size=17 +Sync +Frequency freq=500000000 +ClockSnapshot dt=1 mono=199 sec=1740755050 nsec=123 +EventBatch gen=2 m=18446744073709551615 time=21 size=1 +Stacks +EventBatch gen=2 m=18446744073709551615 time=22 size=1 +Strings +EventBatch gen=3 m=18446744073709551615 time=29 size=17 +Sync +Frequency freq=500000000 +ClockSnapshot dt=1 mono=299 sec=1740755051 nsec=123 +EventBatch gen=3 m=1 time=40 size=4 +ProcStatus dt=1 p=0 pstatus=1 +EventBatch gen=3 m=18446744073709551615 time=31 size=1 +Stacks +EventBatch gen=3 m=18446744073709551615 time=32 size=1 +Strings diff --git a/go/src/internal/trace/testtrace/expectation.go b/go/src/internal/trace/testtrace/expectation.go new file mode 100644 index 0000000000000000000000000000000000000000..3e5394a7e4e9f95a169191bca3cab9cfe56c4eb5 --- /dev/null +++ b/go/src/internal/trace/testtrace/expectation.go @@ -0,0 +1,81 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "bufio" + "bytes" + "fmt" + "regexp" + "strconv" + "strings" +) + +// Expectation represents the expected result of some operation. +type Expectation struct { + failure bool + errorMatcher *regexp.Regexp +} + +// ExpectSuccess returns an Expectation that trivially expects success. +func ExpectSuccess() *Expectation { + return new(Expectation) +} + +// Check validates whether err conforms to the expectation. Returns +// an error if it does not conform. +// +// Conformance means that if failure is true, then err must be non-nil. +// If err is non-nil, then it must match errorMatcher. +func (e *Expectation) Check(err error) error { + if !e.failure && err != nil { + return fmt.Errorf("unexpected error while reading the trace: %v", err) + } + if e.failure && err == nil { + return fmt.Errorf("expected error while reading the trace: want something matching %q, got none", e.errorMatcher) + } + if e.failure && err != nil && !e.errorMatcher.MatchString(err.Error()) { + return fmt.Errorf("unexpected error while reading the trace: want something matching %q, got %s", e.errorMatcher, err.Error()) + } + return nil +} + +// ParseExpectation parses the serialized form of an Expectation. +func ParseExpectation(data []byte) (*Expectation, error) { + exp := new(Expectation) + s := bufio.NewScanner(bytes.NewReader(data)) + if s.Scan() { + c := strings.SplitN(s.Text(), " ", 2) + switch c[0] { + case "SUCCESS": + case "FAILURE": + exp.failure = true + if len(c) != 2 { + return exp, fmt.Errorf("bad header line for FAILURE: %q", s.Text()) + } + matcher, err := parseMatcher(c[1]) + if err != nil { + return exp, err + } + exp.errorMatcher = matcher + default: + return exp, fmt.Errorf("bad header line: %q", s.Text()) + } + return exp, nil + } + return exp, s.Err() +} + +func parseMatcher(quoted string) (*regexp.Regexp, error) { + pattern, err := strconv.Unquote(quoted) + if err != nil { + return nil, fmt.Errorf("malformed pattern: not correctly quoted: %s: %v", quoted, err) + } + matcher, err := regexp.Compile(pattern) + if err != nil { + return nil, fmt.Errorf("malformed pattern: not a valid regexp: %s: %v", pattern, err) + } + return matcher, nil +} diff --git a/go/src/internal/trace/testtrace/format.go b/go/src/internal/trace/testtrace/format.go new file mode 100644 index 0000000000000000000000000000000000000000..5c3c64787d25827bd1c184e836c0106332cd40f0 --- /dev/null +++ b/go/src/internal/trace/testtrace/format.go @@ -0,0 +1,57 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "bytes" + "fmt" + "internal/trace/raw" + "internal/trace/version" + "internal/txtar" + "io" +) + +// ParseFile parses a test file generated by the testgen package. +func ParseFile(testPath string) (io.Reader, version.Version, *Expectation, error) { + ar, err := txtar.ParseFile(testPath) + if err != nil { + return nil, 0, nil, fmt.Errorf("failed to read test file for %s: %v", testPath, err) + } + if len(ar.Files) != 2 { + return nil, 0, nil, fmt.Errorf("malformed test %s: wrong number of files", testPath) + } + if ar.Files[0].Name != "expect" { + return nil, 0, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[0].Name) + } + if ar.Files[1].Name != "trace" { + return nil, 0, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[1].Name) + } + tr, err := raw.NewTextReader(bytes.NewReader(ar.Files[1].Data)) + if err != nil { + return nil, 0, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err) + } + var buf bytes.Buffer + tw, err := raw.NewWriter(&buf, tr.Version()) + if err != nil { + return nil, 0, nil, fmt.Errorf("failed to create trace byte writer: %v", err) + } + for { + ev, err := tr.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + return nil, 0, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err) + } + if err := tw.WriteEvent(ev); err != nil { + return nil, 0, nil, fmt.Errorf("internal error during %s: failed to write trace bytes: %v", testPath, err) + } + } + exp, err := ParseExpectation(ar.Files[0].Data) + if err != nil { + return nil, 0, nil, fmt.Errorf("internal error during %s: failed to parse expectation %q: %v", testPath, string(ar.Files[0].Data), err) + } + return &buf, tr.Version(), exp, nil +} diff --git a/go/src/internal/trace/testtrace/helpers.go b/go/src/internal/trace/testtrace/helpers.go new file mode 100644 index 0000000000000000000000000000000000000000..8a64d5c2ee19cfc33158883a230e47a2d151756e --- /dev/null +++ b/go/src/internal/trace/testtrace/helpers.go @@ -0,0 +1,87 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "bytes" + "fmt" + "internal/testenv" + "internal/trace/raw" + "internal/trace/version" + "io" + "os" + "strings" + "testing" +) + +// Dump saves the trace to a file or the test log. +func Dump(t *testing.T, testName string, traceBytes []byte, forceToFile bool) { + onBuilder := testenv.Builder() != "" + onOldBuilder := !strings.Contains(testenv.Builder(), "gotip") && !strings.Contains(testenv.Builder(), "go1") + + if onBuilder && !forceToFile { + // Dump directly to the test log on the builder, since this + // data is critical for debugging and this is the only way + // we can currently make sure it's retained. + s := dumpTraceToText(t, traceBytes) + if onOldBuilder && len(s) > 1<<20+512<<10 { + // The old build infrastructure truncates logs at ~2 MiB. + // Let's assume we're the only failure and give ourselves + // up to 1.5 MiB to dump the trace. + // + // TODO(mknyszek): Remove this when we've migrated off of + // the old infrastructure. + t.Logf("text trace too large to dump (%d bytes)", len(s)) + } else { + t.Log(s) + t.Log("Convert this to a raw trace with `go test internal/trace/testtrace -convert in.tracetxt -out out.trace`") + } + } else { + // We asked to dump the trace or failed. Write the trace to a file. + t.Logf("wrote trace to file: %s", dumpTraceToFile(t, testName, traceBytes)) + } +} + +func dumpTraceToText(t *testing.T, b []byte) string { + t.Helper() + + br, err := raw.NewReader(bytes.NewReader(b)) + if err != nil { + t.Fatalf("dumping trace: %v", err) + } + var sb strings.Builder + tw, err := raw.NewTextWriter(&sb, version.Current) + if err != nil { + t.Fatalf("dumping trace: %v", err) + } + for { + ev, err := br.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("dumping trace: %v", err) + } + if err := tw.WriteEvent(ev); err != nil { + t.Fatalf("dumping trace: %v", err) + } + } + return sb.String() +} + +func dumpTraceToFile(t *testing.T, testName string, b []byte) string { + t.Helper() + + name := fmt.Sprintf("%s.trace.", testName) + f, err := os.CreateTemp(t.ArtifactDir(), name) + if err != nil { + t.Fatalf("creating temp file: %v", err) + } + defer f.Close() + if _, err := io.Copy(f, bytes.NewReader(b)); err != nil { + t.Fatalf("writing trace dump to %q: %v", f.Name(), err) + } + return f.Name() +} diff --git a/go/src/internal/trace/testtrace/helpers_test.go b/go/src/internal/trace/testtrace/helpers_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2fd4eedafdfcc3f1c2f7b7a42a1c5c73326852ad --- /dev/null +++ b/go/src/internal/trace/testtrace/helpers_test.go @@ -0,0 +1,79 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "flag" + "fmt" + "internal/trace/raw" + "io" + "os" + "testing" +) + +var ( + convert = flag.String("convert", "", "Path to trace text file to convert to binary format") + output = flag.String("out", "", "Output path for converted trace") +) + +// TestConvertDump is not actually a test, it is a tool for converting trace +// text dumps generated by Dump into the binary trace format. Set -convert and +// -o to perform a converison. +// +// go test internal/trace/testtrace -convert in.tracetxt -out out.trace +// +// This would be cleaner as a dedicated internal command rather than a test, +// but cmd/dist does not handle internal (non-distributed) commands in std +// well. +func TestConvertDump(t *testing.T) { + if *convert == "" { + t.Skip("Set -convert to convert a trace text file") + } + if *output == "" { + t.Fatal("Set -out to specify conversion output") + } + + if err := convertDump(*convert, *output); err != nil { + t.Error(err) + } +} + +func convertDump(inPath, outPath string) error { + in, err := os.Open(inPath) + if err != nil { + return fmt.Errorf("error opening input: %v", err) + } + defer in.Close() + + out, err := os.Create(outPath) + if err != nil { + return fmt.Errorf("error creating output: %v", err) + } + defer out.Close() + + tr, err := raw.NewTextReader(in) + if err != nil { + return fmt.Errorf("error creating text reader: %v", err) + } + tw, err := raw.NewWriter(out, tr.Version()) + if err != nil { + return fmt.Errorf("error creating raw writer: %v", err) + } + + for { + ev, err := tr.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + return fmt.Errorf("bad trace file: %v", err) + } + if err := tw.WriteEvent(ev); err != nil { + return fmt.Errorf("failed to write trace bytes: %v", err) + } + } + + return nil +} diff --git a/go/src/internal/trace/testtrace/platforms.go b/go/src/internal/trace/testtrace/platforms.go new file mode 100644 index 0000000000000000000000000000000000000000..937a2dcc84190331dcb411431192a97c7d6d43f5 --- /dev/null +++ b/go/src/internal/trace/testtrace/platforms.go @@ -0,0 +1,32 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "runtime" + "testing" +) + +// MustHaveSyscallEvents skips the current test if the current +// platform does not support true system call events. +func MustHaveSyscallEvents(t *testing.T) { + if HasSyscallEvents() { + return + } + t.Skip("current platform has no true syscall events") +} + +// HasSyscallEvents returns true if the current platform +// has real syscall events available. +func HasSyscallEvents() bool { + switch runtime.GOOS { + case "js", "wasip1": + // js and wasip1 emulate system calls by blocking on channels + // while yielding back to the environment. They never actually + // call entersyscall/exitsyscall. + return false + } + return true +} diff --git a/go/src/internal/trace/testtrace/validation.go b/go/src/internal/trace/testtrace/validation.go new file mode 100644 index 0000000000000000000000000000000000000000..5edcf3a5b2dc0a4e18393a6bb85fb66e7e55e172 --- /dev/null +++ b/go/src/internal/trace/testtrace/validation.go @@ -0,0 +1,423 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testtrace + +import ( + "errors" + "fmt" + "internal/trace" + "internal/trace/version" + "slices" + "strings" +) + +// Validator is a type used for validating a stream of trace.Events. +type Validator struct { + lastTs trace.Time + gs map[trace.GoID]*goState + ps map[trace.ProcID]*procState + ms map[trace.ThreadID]*schedContext + ranges map[trace.ResourceID][]string + tasks map[trace.TaskID]string + lastSync trace.Sync + GoVersion version.Version + + // Flags to modify validation behavior. + skipClockSnapshotChecks bool // Some platforms can't guarantee a monotonically increasing clock reading. +} + +type schedContext struct { + M trace.ThreadID + P trace.ProcID + G trace.GoID +} + +type goState struct { + state trace.GoState + binding *schedContext +} + +type procState struct { + state trace.ProcState + binding *schedContext +} + +// NewValidator creates a new Validator. +func NewValidator() *Validator { + return &Validator{ + gs: make(map[trace.GoID]*goState), + ps: make(map[trace.ProcID]*procState), + ms: make(map[trace.ThreadID]*schedContext), + ranges: make(map[trace.ResourceID][]string), + tasks: make(map[trace.TaskID]string), + GoVersion: version.Current, + } +} + +// SkipClockSnapshotChecks causes the validator to skip checks on the clock snapshots. +// +// Some platforms like Windows, with a small enough trace period, are unable to produce +// monotonically increasing timestamps due to very coarse clock granularity. +func (v *Validator) SkipClockSnapshotChecks() { + v.skipClockSnapshotChecks = true +} + +// Event validates ev as the next event in a stream of trace.Events. +// +// Returns an error if validation fails. +func (v *Validator) Event(ev trace.Event) error { + e := new(errAccumulator) + + // Validate timestamp order. + if v.lastTs != 0 { + if ev.Time() <= v.lastTs { + e.Errorf("timestamp out-of-order (want > %v) for %+v", v.lastTs, ev) + } else { + v.lastTs = ev.Time() + } + } else { + v.lastTs = ev.Time() + } + + // Validate event stack. + checkStack(e, ev.Stack()) + + switch ev.Kind() { + case trace.EventSync: + s := ev.Sync() + if s.N != v.lastSync.N+1 { + e.Errorf("sync count is not sequential: expected %d, got %d", v.lastSync.N+1, s.N) + } + // The trace reader currently emits synthetic sync events at the end of + // a trace. Those don't contain clock snapshots data, so we don't try + // to validate them. + // + // TODO(felixge): Drop the synthetic syncs as discussed in CL 653576. + if v.GoVersion >= version.Go125 && !(s.N > 1 && s.ClockSnapshot == nil) { + if s.ClockSnapshot == nil { + e.Errorf("sync %d has no clock snapshot", s.N) + } else { + if s.ClockSnapshot.Wall.IsZero() { + e.Errorf("sync %d has zero wall time", s.N) + } + if s.ClockSnapshot.Mono == 0 { + e.Errorf("sync %d has zero mono time", s.N) + } + if s.ClockSnapshot.Trace == 0 { + e.Errorf("sync %d has zero trace time", s.N) + } + if !v.skipClockSnapshotChecks { + if s.N >= 2 && !s.ClockSnapshot.Wall.After(v.lastSync.ClockSnapshot.Wall) { + e.Errorf("sync %d has non-increasing wall time: %v vs %v", s.N, s.ClockSnapshot.Wall, v.lastSync.ClockSnapshot.Wall) + } + if s.N >= 2 && !(s.ClockSnapshot.Mono > v.lastSync.ClockSnapshot.Mono) { + e.Errorf("sync %d has non-increasing mono time: %v vs %v", s.N, s.ClockSnapshot.Mono, v.lastSync.ClockSnapshot.Mono) + } + if s.N >= 2 && !(s.ClockSnapshot.Trace > v.lastSync.ClockSnapshot.Trace) { + e.Errorf("sync %d has non-increasing trace time: %v vs %v", s.N, s.ClockSnapshot.Trace, v.lastSync.ClockSnapshot.Trace) + } + } + } + } + v.lastSync = s + case trace.EventMetric: + m := ev.Metric() + if !strings.Contains(m.Name, ":") { + // Should have a ":" as per runtime/metrics convention. + e.Errorf("invalid metric name %q", m.Name) + } + // Make sure the value is OK. + if m.Value.Kind() == trace.ValueBad { + e.Errorf("invalid value") + } + switch m.Value.Kind() { + case trace.ValueUint64: + // Just make sure it doesn't panic. + _ = m.Value.Uint64() + } + case trace.EventLabel: + l := ev.Label() + + // Check label. + if l.Label == "" { + e.Errorf("invalid label %q", l.Label) + } + + // Check label resource. + if l.Resource.Kind == trace.ResourceNone { + e.Errorf("label resource none") + } + switch l.Resource.Kind { + case trace.ResourceGoroutine: + id := l.Resource.Goroutine() + if _, ok := v.gs[id]; !ok { + e.Errorf("label for invalid goroutine %d", id) + } + case trace.ResourceProc: + id := l.Resource.Proc() + if _, ok := v.ps[id]; !ok { + e.Errorf("label for invalid proc %d", id) + } + case trace.ResourceThread: + id := l.Resource.Thread() + if _, ok := v.ms[id]; !ok { + e.Errorf("label for invalid thread %d", id) + } + } + case trace.EventStackSample: + // Not much to check here. It's basically a sched context and a stack. + // The sched context is also not guaranteed to align with other events. + // We already checked the stack above. + case trace.EventStateTransition: + // Validate state transitions. + // + // TODO(mknyszek): A lot of logic is duplicated between goroutines and procs. + // The two are intentionally handled identically; from the perspective of the + // API, resources all have the same general properties. Consider making this + // code generic over resources and implementing validation just once. + tr := ev.StateTransition() + checkStack(e, tr.Stack) + switch tr.Resource.Kind { + case trace.ResourceGoroutine: + // Basic state transition validation. + id := tr.Resource.Goroutine() + old, new := tr.Goroutine() + if new == trace.GoUndetermined { + e.Errorf("transition to undetermined state for goroutine %d", id) + } + if v.lastSync.N > 1 && old == trace.GoUndetermined { + e.Errorf("undetermined goroutine %d after first global sync", id) + } + if new == trace.GoNotExist && v.hasAnyRange(trace.MakeResourceID(id)) { + e.Errorf("goroutine %d died with active ranges", id) + } + state, ok := v.gs[id] + if ok { + if old != state.state { + e.Errorf("bad old state for goroutine %d: got %s, want %s", id, old, state.state) + } + state.state = new + } else { + if old != trace.GoUndetermined && old != trace.GoNotExist { + e.Errorf("bad old state for unregistered goroutine %d: %s", id, old) + } + state = &goState{state: new} + v.gs[id] = state + } + // Validate sched context. + if new.Executing() { + ctx := v.getOrCreateThread(e, ev, ev.Thread()) + if ctx != nil { + if ctx.G != trace.NoGoroutine && ctx.G != id { + e.Errorf("tried to run goroutine %d when one was already executing (%d) on thread %d", id, ctx.G, ev.Thread()) + } + ctx.G = id + state.binding = ctx + } + } else if old.Executing() && !new.Executing() { + if tr.Stack != ev.Stack() { + // This is a case where the transition is happening to a goroutine that is also executing, so + // these two stacks should always match. + e.Errorf("StateTransition.Stack doesn't match Event.Stack") + } + ctx := state.binding + if ctx != nil { + if ctx.G != id { + e.Errorf("tried to stop goroutine %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.G, ev.Thread()) + } + ctx.G = trace.NoGoroutine + state.binding = nil + } else { + e.Errorf("stopping goroutine %d not bound to any active context", id) + } + } + case trace.ResourceProc: + // Basic state transition validation. + id := tr.Resource.Proc() + old, new := tr.Proc() + if new == trace.ProcUndetermined { + e.Errorf("transition to undetermined state for proc %d", id) + } + if v.lastSync.N > 1 && old == trace.ProcUndetermined { + e.Errorf("undetermined proc %d after first global sync", id) + } + if new == trace.ProcNotExist && v.hasAnyRange(trace.MakeResourceID(id)) { + e.Errorf("proc %d died with active ranges", id) + } + state, ok := v.ps[id] + if ok { + if old != state.state { + e.Errorf("bad old state for proc %d: got %s, want %s", id, old, state.state) + } + state.state = new + } else { + if old != trace.ProcUndetermined && old != trace.ProcNotExist { + e.Errorf("bad old state for unregistered proc %d: %s", id, old) + } + state = &procState{state: new} + v.ps[id] = state + } + // Validate sched context. + if new.Executing() { + ctx := v.getOrCreateThread(e, ev, ev.Thread()) + if ctx != nil { + if ctx.P != trace.NoProc && ctx.P != id { + e.Errorf("tried to run proc %d when one was already executing (%d) on thread %d", id, ctx.P, ev.Thread()) + } + ctx.P = id + state.binding = ctx + } + } else if old.Executing() && !new.Executing() { + ctx := state.binding + if ctx != nil { + if ctx.P != id { + e.Errorf("tried to stop proc %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.P, ctx.M) + } + ctx.P = trace.NoProc + state.binding = nil + } else { + e.Errorf("stopping proc %d not bound to any active context", id) + } + } + } + case trace.EventRangeBegin, trace.EventRangeActive, trace.EventRangeEnd: + // Validate ranges. + r := ev.Range() + switch ev.Kind() { + case trace.EventRangeBegin: + if v.hasRange(r.Scope, r.Name) { + e.Errorf("already active range %q on %v begun again", r.Name, r.Scope) + } + v.addRange(r.Scope, r.Name) + case trace.EventRangeActive: + if !v.hasRange(r.Scope, r.Name) { + v.addRange(r.Scope, r.Name) + } + case trace.EventRangeEnd: + if !v.hasRange(r.Scope, r.Name) { + e.Errorf("inactive range %q on %v ended", r.Name, r.Scope) + } + v.deleteRange(r.Scope, r.Name) + } + case trace.EventTaskBegin: + // Validate task begin. + t := ev.Task() + if t.ID == trace.NoTask || t.ID == trace.BackgroundTask { + // The background task should never have an event emitted for it. + e.Errorf("found invalid task ID for task of type %s", t.Type) + } + if t.Parent == trace.BackgroundTask { + // It's not possible for a task to be a subtask of the background task. + e.Errorf("found background task as the parent for task of type %s", t.Type) + } + // N.B. Don't check the task type. Empty string is a valid task type. + v.tasks[t.ID] = t.Type + case trace.EventTaskEnd: + // Validate task end. + // We can see a task end without a begin, so ignore a task without information. + // Instead, if we've seen the task begin, just make sure the task end lines up. + t := ev.Task() + if typ, ok := v.tasks[t.ID]; ok { + if t.Type != typ { + e.Errorf("task end type %q doesn't match task start type %q for task %d", t.Type, typ, t.ID) + } + delete(v.tasks, t.ID) + } + case trace.EventLog: + // There's really not much here to check, except that we can + // generate a Log. The category and message are entirely user-created, + // so we can't make any assumptions as to what they are. We also + // can't validate the task, because proving the task's existence is very + // much best-effort. + _ = ev.Log() + } + return e.Errors() +} + +func (v *Validator) hasRange(r trace.ResourceID, name string) bool { + ranges, ok := v.ranges[r] + return ok && slices.Contains(ranges, name) +} + +func (v *Validator) addRange(r trace.ResourceID, name string) { + ranges, _ := v.ranges[r] + ranges = append(ranges, name) + v.ranges[r] = ranges +} + +func (v *Validator) hasAnyRange(r trace.ResourceID) bool { + ranges, ok := v.ranges[r] + return ok && len(ranges) != 0 +} + +func (v *Validator) deleteRange(r trace.ResourceID, name string) { + ranges, ok := v.ranges[r] + if !ok { + return + } + i := slices.Index(ranges, name) + if i < 0 { + return + } + v.ranges[r] = slices.Delete(ranges, i, i+1) +} + +func (v *Validator) getOrCreateThread(e *errAccumulator, ev trace.Event, m trace.ThreadID) *schedContext { + lenient := func() bool { + // Be lenient about GoUndetermined -> GoSyscall transitions if they + // originate from an old trace. These transitions lack thread + // information in trace formats older than 1.22. + if v.GoVersion >= version.Go122 { + return false + } + if ev.Kind() != trace.EventStateTransition { + return false + } + tr := ev.StateTransition() + if tr.Resource.Kind != trace.ResourceGoroutine { + return false + } + from, to := tr.Goroutine() + return from == trace.GoUndetermined && to == trace.GoSyscall + } + if m == trace.NoThread && !lenient() { + e.Errorf("must have thread, but thread ID is none") + return nil + } + s, ok := v.ms[m] + if !ok { + s = &schedContext{M: m, P: trace.NoProc, G: trace.NoGoroutine} + v.ms[m] = s + return s + } + return s +} + +func checkStack(e *errAccumulator, stk trace.Stack) { + // Check for non-empty values, but we also check for crashes due to incorrect validation. + for i, f := range slices.Collect(stk.Frames()) { + if i == 0 { + // Allow for one fully zero stack. + // + // TODO(mknyszek): Investigate why that happens. + continue + } + if f.Func == "" || f.File == "" || f.PC == 0 || f.Line == 0 { + e.Errorf("invalid stack frame %#v: missing information", f) + } + } +} + +type errAccumulator struct { + errs []error +} + +func (e *errAccumulator) Errorf(f string, args ...any) { + e.errs = append(e.errs, fmt.Errorf(f, args...)) +} + +func (e *errAccumulator) Errors() error { + return errors.Join(e.errs...) +} diff --git a/go/src/internal/trace/trace_test.go b/go/src/internal/trace/trace_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bfbd5315115305e58a9aa45a63968a5ce97ea5cf --- /dev/null +++ b/go/src/internal/trace/trace_test.go @@ -0,0 +1,708 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace_test + +import ( + "bufio" + "bytes" + "fmt" + "internal/race" + "internal/testenv" + "internal/trace" + "internal/trace/testtrace" + "internal/trace/version" + "io" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" +) + +func TestTraceAnnotations(t *testing.T) { + testTraceProg(t, "annotations.go", func(t *testing.T, tb, _ []byte, _ string) { + type evDesc struct { + kind trace.EventKind + task trace.TaskID + args []string + } + want := []evDesc{ + {trace.EventTaskBegin, trace.TaskID(1), []string{"task0"}}, + {trace.EventRegionBegin, trace.TaskID(1), []string{"region0"}}, + {trace.EventRegionBegin, trace.TaskID(1), []string{"region1"}}, + {trace.EventLog, trace.TaskID(1), []string{"key0", "0123456789abcdef"}}, + {trace.EventRegionEnd, trace.TaskID(1), []string{"region1"}}, + {trace.EventRegionEnd, trace.TaskID(1), []string{"region0"}}, + {trace.EventTaskEnd, trace.TaskID(1), []string{"task0"}}, + // Currently, pre-existing region is not recorded to avoid allocations. + {trace.EventRegionBegin, trace.BackgroundTask, []string{"post-existing region"}}, + } + r, err := trace.NewReader(bytes.NewReader(tb)) + if err != nil { + t.Error(err) + } + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + for i, wantEv := range want { + if wantEv.kind != ev.Kind() { + continue + } + match := false + switch ev.Kind() { + case trace.EventTaskBegin, trace.EventTaskEnd: + task := ev.Task() + match = task.ID == wantEv.task && task.Type == wantEv.args[0] + case trace.EventRegionBegin, trace.EventRegionEnd: + reg := ev.Region() + match = reg.Task == wantEv.task && reg.Type == wantEv.args[0] + case trace.EventLog: + log := ev.Log() + match = log.Task == wantEv.task && log.Category == wantEv.args[0] && log.Message == wantEv.args[1] + } + if match { + want[i] = want[len(want)-1] + want = want[:len(want)-1] + break + } + } + } + if len(want) != 0 { + for _, ev := range want { + t.Errorf("no match for %s TaskID=%d Args=%#v", ev.kind, ev.task, ev.args) + } + } + }) +} + +func TestTraceAnnotationsStress(t *testing.T) { + testTraceProg(t, "annotations-stress.go", nil) +} + +func TestTraceCgoCallback(t *testing.T) { + testenv.MustHaveCGO(t) + + switch runtime.GOOS { + case "plan9", "windows": + t.Skipf("cgo callback test requires pthreads and is not supported on %s", runtime.GOOS) + } + testTraceProg(t, "cgo-callback.go", nil) +} + +func TestTraceCPUProfile(t *testing.T) { + testTraceProg(t, "cpu-profile.go", func(t *testing.T, tb, stderr []byte, _ string) { + // Parse stderr which has a CPU profile summary, if everything went well. + // (If it didn't, we shouldn't even make it here.) + scanner := bufio.NewScanner(bytes.NewReader(stderr)) + pprofSamples := 0 + pprofStacks := make(map[string]int) + for scanner.Scan() { + var stack string + var samples int + _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &stack, &samples) + if err != nil { + t.Fatalf("failed to parse CPU profile summary in stderr: %s\n\tfull:\n%s", scanner.Text(), stderr) + } + pprofStacks[stack] = samples + pprofSamples += samples + } + if err := scanner.Err(); err != nil { + t.Fatalf("failed to parse CPU profile summary in stderr: %v", err) + } + if pprofSamples == 0 { + t.Skip("CPU profile did not include any samples while tracing was active") + } + + // Examine the execution tracer's view of the CPU profile samples. Filter it + // to only include samples from the single test goroutine. Use the goroutine + // ID that was recorded in the events: that should reflect getg().m.curg, + // same as the profiler's labels (even when the M is using its g0 stack). + totalTraceSamples := 0 + traceSamples := 0 + traceStacks := make(map[string]int) + r, err := trace.NewReader(bytes.NewReader(tb)) + if err != nil { + t.Error(err) + } + var hogRegion *trace.Event + var hogRegionClosed bool + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + if ev.Kind() == trace.EventRegionBegin && ev.Region().Type == "cpuHogger" { + hogRegion = &ev + } + if ev.Kind() == trace.EventStackSample { + totalTraceSamples++ + if hogRegion != nil && ev.Goroutine() == hogRegion.Goroutine() { + traceSamples++ + var fns []string + for frame := range ev.Stack().Frames() { + if frame.Func != "runtime.goexit" { + fns = append(fns, fmt.Sprintf("%s:%d", frame.Func, frame.Line)) + } + } + stack := strings.Join(fns, "|") + traceStacks[stack]++ + } + } + if ev.Kind() == trace.EventRegionEnd && ev.Region().Type == "cpuHogger" { + hogRegionClosed = true + } + } + if hogRegion == nil { + t.Fatalf("execution trace did not identify cpuHogger goroutine") + } else if !hogRegionClosed { + t.Fatalf("execution trace did not close cpuHogger region") + } + + // The execution trace may drop CPU profile samples if the profiling buffer + // overflows. Based on the size of profBufWordCount, that takes a bit over + // 1900 CPU samples or 19 thread-seconds at a 100 Hz sample rate. If we've + // hit that case, then we definitely have at least one full buffer's worth + // of CPU samples, so we'll call that success. + overflowed := totalTraceSamples >= 1900 + if traceSamples < pprofSamples { + t.Logf("execution trace did not include all CPU profile samples; %d in profile, %d in trace", pprofSamples, traceSamples) + if !overflowed { + t.Fail() + } + } + + for stack, traceSamples := range traceStacks { + pprofSamples := pprofStacks[stack] + delete(pprofStacks, stack) + if traceSamples < pprofSamples { + t.Logf("execution trace did not include all CPU profile samples for stack %q; %d in profile, %d in trace", + stack, pprofSamples, traceSamples) + if !overflowed { + t.Fail() + } + } + } + for stack, pprofSamples := range pprofStacks { + t.Logf("CPU profile included %d samples at stack %q not present in execution trace", pprofSamples, stack) + if !overflowed { + t.Fail() + } + } + + if t.Failed() { + t.Logf("execution trace CPU samples:") + for stack, samples := range traceStacks { + t.Logf("%d: %q", samples, stack) + } + t.Logf("CPU profile:\n%s", stderr) + } + }) +} + +func TestTraceFutileWakeup(t *testing.T) { + testTraceProg(t, "futile-wakeup.go", func(t *testing.T, tb, _ []byte, _ string) { + // Check to make sure that no goroutine in the "special" trace region + // ends up blocking, unblocking, then immediately blocking again. + // + // The goroutines are careful to call runtime.Gosched in between blocking, + // so there should never be a clean block/unblock on the goroutine unless + // the runtime was generating extraneous events. + const ( + entered = iota + blocked + runnable + running + ) + gs := make(map[trace.GoID]int) + seenSpecialGoroutines := false + r, err := trace.NewReader(bytes.NewReader(tb)) + if err != nil { + t.Error(err) + } + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + // Only track goroutines in the special region we control, so runtime + // goroutines don't interfere (it's totally valid in traces for a + // goroutine to block, run, and block again; that's not what we care about). + if ev.Kind() == trace.EventRegionBegin && ev.Region().Type == "special" { + seenSpecialGoroutines = true + gs[ev.Goroutine()] = entered + } + if ev.Kind() == trace.EventRegionEnd && ev.Region().Type == "special" { + delete(gs, ev.Goroutine()) + } + // Track state transitions for goroutines we care about. + // + // The goroutines we care about will advance through the state machine + // of entered -> blocked -> runnable -> running. If in the running state + // we block, then we have a futile wakeup. Because of the runtime.Gosched + // on these specially marked goroutines, we should end up back in runnable + // first. If at any point we go to a different state, switch back to entered + // and wait for the next time the goroutine blocks. + if ev.Kind() != trace.EventStateTransition { + continue + } + st := ev.StateTransition() + if st.Resource.Kind != trace.ResourceGoroutine { + continue + } + id := st.Resource.Goroutine() + state, ok := gs[id] + if !ok { + continue + } + _, new := st.Goroutine() + switch state { + case entered: + if new == trace.GoWaiting { + state = blocked + } else { + state = entered + } + case blocked: + if new == trace.GoRunnable { + state = runnable + } else { + state = entered + } + case runnable: + if new == trace.GoRunning { + state = running + } else { + state = entered + } + case running: + if new == trace.GoWaiting { + t.Fatalf("found futile wakeup on goroutine %d", id) + } else { + state = entered + } + } + gs[id] = state + } + if !seenSpecialGoroutines { + t.Fatal("did not see a goroutine in a the region 'special'") + } + }) +} + +func TestTraceGCStress(t *testing.T) { + testTraceProg(t, "gc-stress.go", nil) +} + +func TestTraceGOMAXPROCS(t *testing.T) { + testTraceProg(t, "gomaxprocs.go", nil) +} + +func TestTraceStacks(t *testing.T) { + testTraceProg(t, "stacks.go", func(t *testing.T, tb, _ []byte, godebug string) { + type frame struct { + fn string + line int + } + type evDesc struct { + kind trace.EventKind + match string + frames []frame + } + // mainLine is the line number of `func main()` in testprog/stacks.go. + const mainLine = 21 + want := []evDesc{ + {trace.EventStateTransition, "Goroutine Running->Runnable", []frame{ + {"runtime.Gosched", 0}, + {"main.main", mainLine + 87}, + }}, + {trace.EventStateTransition, "Goroutine NotExist->Runnable", []frame{ + {"main.main", mainLine + 11}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.block", 0}, + {"main.main.func1", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.chansend1", 0}, + {"main.main.func2", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.chanrecv1", 0}, + {"main.main.func3", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.chanrecv1", 0}, + {"main.main.func4", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"runtime.chansend1", 0}, + {"main.main", mainLine + 89}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.chansend1", 0}, + {"main.main.func5", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"runtime.chanrecv1", 0}, + {"main.main", mainLine + 90}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"runtime.selectgo", 0}, + {"main.main.func6", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"runtime.selectgo", 0}, + {"main.main", mainLine + 91}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"sync.(*Mutex).Lock", 0}, + {"main.main.func7", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"sync.(*Mutex).Unlock", 0}, + {"main.main", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"sync.(*WaitGroup).Wait", 0}, + {"main.main.func8", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"sync.(*WaitGroup).Add", 0}, + {"sync.(*WaitGroup).Done", 0}, + {"main.main", mainLine + 96}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"sync.(*Cond).Wait", 0}, + {"main.main.func9", 0}, + }}, + {trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{ + {"sync.(*Cond).Signal", 0}, + {"main.main", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"time.Sleep", 0}, + {"main.main", 0}, + }}, + {trace.EventMetric, "/sched/gomaxprocs:threads", []frame{ + {"runtime.startTheWorld", 0}, // this is when the current gomaxprocs is logged. + {"runtime.startTheWorldGC", 0}, + {"runtime.GOMAXPROCS", 0}, + {"main.main", 0}, + }}, + } + asyncPreemptOff := strings.Contains(godebug, "asyncpreemptoff=1") + if asyncPreemptOff { + // Only check for syncPreemptPoint if asynchronous preemption is disabled. + // Otherwise, the syncPreemptPoint goroutine might be exclusively async + // preempted, causing this test to flake. + syncPreemptEv := evDesc{trace.EventStateTransition, "Goroutine Running->Runnable", []frame{ + {"main.syncPreemptPoint", 0}, + {"main.main.func12", 0}, + }} + want = append(want, syncPreemptEv) + } + stress := strings.Contains(godebug, "traceadvanceperiod=0") + if !stress { + // Only check for this stack if !stress because traceAdvance alone could + // allocate enough memory to trigger a GC if called frequently enough. + // This might cause the runtime.GC call we're trying to match against to + // coalesce with an active GC triggered this by traceAdvance. In that case + // we won't have an EventRangeBegin event that matches the stace trace we're + // looking for, since runtime.GC will not have triggered the GC. + gcEv := evDesc{trace.EventRangeBegin, "GC concurrent mark phase", []frame{ + {"runtime.GC", 0}, + {"main.main", 0}, + }} + want = append(want, gcEv) + } + if runtime.GOOS != "windows" && runtime.GOOS != "plan9" { + want = append(want, []evDesc{ + {trace.EventStateTransition, "Goroutine Running->Waiting", []frame{ + {"internal/poll.(*FD).Accept", 0}, + {"net.(*netFD).accept", 0}, + {"net.(*TCPListener).accept", 0}, + {"net.(*TCPListener).Accept", 0}, + {"main.main.func10", 0}, + }}, + {trace.EventStateTransition, "Goroutine Running->Syscall", []frame{ + {"syscall.read", 0}, + {"syscall.Read", 0}, + {"internal/poll.ignoringEINTRIO", 0}, + {"internal/poll.(*FD).Read", 0}, + {"os.(*File).read", 0}, + {"os.(*File).Read", 0}, + {"main.main.func11", 0}, + }}, + }...) + if runtime.GOOS == "darwin" { + want[len(want)-1].frames = append([]frame{{"syscall.syscall", 0}}, want[len(want)-1].frames...) + } + } + stackMatches := func(stk trace.Stack, frames []frame) bool { + for i, f := range slices.Collect(stk.Frames()) { + if f.Func != frames[i].fn { + return false + } + if line := uint64(frames[i].line); line != 0 && line != f.Line { + return false + } + } + return true + } + r, err := trace.NewReader(bytes.NewReader(tb)) + if err != nil { + t.Error(err) + } + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + for i, wantEv := range want { + if wantEv.kind != ev.Kind() { + continue + } + match := false + switch ev.Kind() { + case trace.EventStateTransition: + st := ev.StateTransition() + str := "" + switch st.Resource.Kind { + case trace.ResourceGoroutine: + old, new := st.Goroutine() + str = fmt.Sprintf("%s %s->%s", st.Resource.Kind, old, new) + } + match = str == wantEv.match + case trace.EventRangeBegin: + rng := ev.Range() + match = rng.Name == wantEv.match + case trace.EventMetric: + metric := ev.Metric() + match = metric.Name == wantEv.match + } + match = match && stackMatches(ev.Stack(), wantEv.frames) + if match { + want[i] = want[len(want)-1] + want = want[:len(want)-1] + break + } + } + } + if len(want) != 0 { + for _, ev := range want { + t.Errorf("no match for %s Match=%s Stack=%#v", ev.kind, ev.match, ev.frames) + } + } + }) +} + +func TestTraceStress(t *testing.T) { + switch runtime.GOOS { + case "js", "wasip1": + t.Skip("no os.Pipe on " + runtime.GOOS) + } + testTraceProg(t, "stress.go", checkReaderDeterminism) +} + +func TestTraceStressStartStop(t *testing.T) { + switch runtime.GOOS { + case "js", "wasip1": + t.Skip("no os.Pipe on " + runtime.GOOS) + } + testTraceProg(t, "stress-start-stop.go", nil) +} + +func TestTraceManyStartStop(t *testing.T) { + testTraceProg(t, "many-start-stop.go", nil) +} + +func TestTraceWaitOnPipe(t *testing.T) { + switch runtime.GOOS { + case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris": + testTraceProg(t, "wait-on-pipe.go", nil) + return + } + t.Skip("no applicable syscall.Pipe on " + runtime.GOOS) +} + +func TestTraceIterPull(t *testing.T) { + testTraceProg(t, "iter-pull.go", nil) +} + +func checkReaderDeterminism(t *testing.T, tb, _ []byte, _ string) { + events := func() []trace.Event { + var evs []trace.Event + + r, err := trace.NewReader(bytes.NewReader(tb)) + if err != nil { + t.Error(err) + } + for { + ev, err := r.ReadEvent() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + evs = append(evs, ev) + } + + return evs + } + + evs1 := events() + evs2 := events() + + if l1, l2 := len(evs1), len(evs2); l1 != l2 { + t.Fatalf("re-reading trace gives different event count (%d != %d)", l1, l2) + } + for i, ev1 := range evs1 { + ev2 := evs2[i] + if s1, s2 := ev1.String(), ev2.String(); s1 != s2 { + t.Errorf("re-reading trace gives different event %d:\n%s\n%s\n", i, s1, s2) + break + } + } +} + +func testTraceProg(t *testing.T, progName string, extra func(t *testing.T, trace, stderr []byte, godebug string)) { + testenv.MustHaveGoRun(t) + + // Check if we're on a builder. + onBuilder := testenv.Builder() != "" + onOldBuilder := !strings.Contains(testenv.Builder(), "gotip") && !strings.Contains(testenv.Builder(), "go1") + + if progName == "cgo-callback.go" && onBuilder && !onOldBuilder && + runtime.GOOS == "freebsd" && runtime.GOARCH == "amd64" && race.Enabled { + t.Skip("test fails on freebsd-amd64-race in LUCI; see go.dev/issue/71556") + } + + testPath := filepath.Join("./testdata/testprog", progName) + testName := progName + runTest := func(t *testing.T, stress bool, extraGODEBUG string) { + // Build the program. + binFile, err := os.CreateTemp("", progName) + if err != nil { + t.Fatalf("failed to create temporary output file: %v", err) + } + bin := binFile.Name() + binFile.Close() + t.Cleanup(func() { + os.Remove(bin) + }) + buildCmd := testenv.CommandContext(t, t.Context(), testenv.GoToolPath(t), "build", "-o", bin) + if race.Enabled { + buildCmd.Args = append(buildCmd.Args, "-race") + } + buildCmd.Args = append(buildCmd.Args, testPath) + buildOutput, err := buildCmd.CombinedOutput() + if err != nil { + t.Fatalf("failed to build %s: %v: output:\n%s", testPath, err, buildOutput) + } + + // Run the program and capture the trace, which is always written to stdout. + cmd := testenv.CommandContext(t, t.Context(), bin) + + // Add a stack ownership check. This is cheap enough for testing. + godebug := "tracecheckstackownership=1" + if stress { + // Advance a generation constantly to stress the tracer. + godebug += ",traceadvanceperiod=0" + } + if extraGODEBUG != "" { + // Add extra GODEBUG flags. + godebug += "," + extraGODEBUG + } + cmd.Env = append(cmd.Env, "GODEBUG="+godebug) + if _, ok := os.LookupEnv("GOTRACEBACK"); !ok { + // Unless overriden, set GOTRACEBACK=crash. + cmd.Env = append(cmd.Env, "GOTRACEBACK=crash") + } + + // Capture stdout and stderr. + // + // The protocol for these programs is that stdout contains the trace data + // and stderr is an expectation in string format. + var traceBuf, errBuf bytes.Buffer + cmd.Stdout = &traceBuf + cmd.Stderr = &errBuf + // Run the program. + if err := cmd.Run(); err != nil { + if errBuf.Len() != 0 { + t.Logf("stderr: %s", string(errBuf.Bytes())) + } + t.Fatal(err) + } + tb := traceBuf.Bytes() + + // Test the trace and the parser. + v := testtrace.NewValidator() + v.GoVersion = version.Current + if runtime.GOOS == "windows" && stress { + // Under stress mode we're constantly advancing trace generations. + // Windows' clock granularity is too coarse to guarantee monotonic + // timestamps for monotonic and wall clock time in this case, so + // skip the checks. + v.SkipClockSnapshotChecks() + } + testReader(t, bytes.NewReader(tb), v, testtrace.ExpectSuccess()) + + // Run some extra validation. + if !t.Failed() && extra != nil { + extra(t, tb, errBuf.Bytes(), godebug) + } + + // Dump some more information on failure. + if t.Failed() || *dumpTraces { + suffix := func(stress bool) string { + if stress { + return "stress" + } + return "default" + } + testtrace.Dump(t, fmt.Sprintf("%s.%s", testName, suffix(stress)), tb, *dumpTraces) + } + } + t.Run("Default", func(t *testing.T) { + runTest(t, false, "") + }) + t.Run("AsyncPreemptOff", func(t *testing.T) { + if testing.Short() && runtime.NumCPU() < 2 { + t.Skip("skipping trace async preempt off tests in short mode") + } + runTest(t, false, "asyncpreemptoff=1") + }) + t.Run("Stress", func(t *testing.T) { + if testing.Short() { + t.Skip("skipping trace stress tests in short mode") + } + runTest(t, true, "") + }) + t.Run("AllocFree", func(t *testing.T) { + if !*allocFree { + t.Skip("skipping trace alloc/free tests by default; too flaky (see go.dev/issue/70838)") + } + if testing.Short() { + t.Skip("skipping trace alloc/free tests in short mode") + } + runTest(t, false, "traceallocfree=1") + }) +} diff --git a/go/src/internal/trace/tracev1.go b/go/src/internal/trace/tracev1.go new file mode 100644 index 0000000000000000000000000000000000000000..667d7be1cd1b4b5b0c4aa19f03f495066bba9b9b --- /dev/null +++ b/go/src/internal/trace/tracev1.go @@ -0,0 +1,567 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file implements conversion from v1 (Go 1.11–Go 1.21) traces to the v2 +// format (Go 1.22+). +// +// Most events have direct equivalents in v2, at worst requiring arguments to +// be reordered. Some events, such as GoWaiting need to look ahead for follow-up +// events to determine the correct translation. GoSyscall, which is an +// instantaneous event, gets turned into a 1 ns long pair of +// GoSyscallStart+GoSyscallEnd, unless we observe a GoSysBlock, in which case we +// emit a GoSyscallStart+GoSyscallEndBlocked pair with the correct duration +// (i.e. starting at the original GoSyscall). +// +// The resulting trace treats the trace v1 as a single, large generation, +// sharing a single evTable for all events. +// +// We use a new (compared to what was used for 'go tool trace' in earlier +// versions of Go) parser for v1 traces that is optimized for speed, low memory +// usage, and minimal GC pressure. It allocates events in batches so that even +// though we have to load the entire trace into memory, the conversion process +// shouldn't result in a doubling of memory usage, even if all converted events +// are kept alive, as we free batches once we're done with them. +// +// The conversion process is lossless. + +package trace + +import ( + "errors" + "fmt" + "internal/trace/internal/tracev1" + "internal/trace/tracev2" + "io" +) + +type traceV1Converter struct { + trace tracev1.Trace + evt *evTable + preInit bool + createdPreInit map[GoID]struct{} + events tracev1.Events + extra []Event + extraArr [3]Event + tasks map[TaskID]taskState + seenProcs map[ProcID]struct{} + lastTs Time + procMs map[ProcID]ThreadID + lastStwReason uint64 + + inlineToStringID []uint64 + builtinToStringID []uint64 +} + +const ( + // Block reasons + sForever = iota + sPreempted + sGosched + sSleep + sChanSend + sChanRecv + sNetwork + sSync + sSyncCond + sSelect + sEmpty + sMarkAssistWait + + // STW kinds + sSTWUnknown + sSTWGCMarkTermination + sSTWGCSweepTermination + sSTWWriteHeapDump + sSTWGoroutineProfile + sSTWGoroutineProfileCleanup + sSTWAllGoroutinesStackTrace + sSTWReadMemStats + sSTWAllThreadsSyscall + sSTWGOMAXPROCS + sSTWStartTrace + sSTWStopTrace + sSTWCountPagesInUse + sSTWReadMetricsSlow + sSTWReadMemStatsSlow + sSTWPageCachePagesLeaked + sSTWResetDebugLog + + sLast +) + +func (it *traceV1Converter) init(pr tracev1.Trace) error { + it.trace = pr + it.preInit = true + it.createdPreInit = make(map[GoID]struct{}) + it.evt = &evTable{pcs: make(map[uint64]frame)} + it.events = pr.Events + it.extra = it.extraArr[:0] + it.tasks = make(map[TaskID]taskState) + it.seenProcs = make(map[ProcID]struct{}) + it.procMs = make(map[ProcID]ThreadID) + it.lastTs = -1 + + evt := it.evt + + // Convert from trace v1's Strings map to our dataTable. + var max uint64 + for id, s := range pr.Strings { + evt.strings.insert(stringID(id), s) + if id > max { + max = id + } + } + pr.Strings = nil + + // Add all strings used for UserLog. In the trace v1 format, these were + // stored inline and didn't have IDs. We generate IDs for them. + if max+uint64(len(pr.InlineStrings)) < max { + return errors.New("trace contains too many strings") + } + var addErr error + add := func(id stringID, s string) { + if err := evt.strings.insert(id, s); err != nil && addErr == nil { + addErr = err + } + } + for id, s := range pr.InlineStrings { + nid := max + 1 + uint64(id) + it.inlineToStringID = append(it.inlineToStringID, nid) + add(stringID(nid), s) + } + max += uint64(len(pr.InlineStrings)) + pr.InlineStrings = nil + + // Add strings that the converter emits explicitly. + if max+uint64(sLast) < max { + return errors.New("trace contains too many strings") + } + it.builtinToStringID = make([]uint64, sLast) + addBuiltin := func(c int, s string) { + nid := max + 1 + uint64(c) + it.builtinToStringID[c] = nid + add(stringID(nid), s) + } + addBuiltin(sForever, "forever") + addBuiltin(sPreempted, "preempted") + addBuiltin(sGosched, "runtime.Gosched") + addBuiltin(sSleep, "sleep") + addBuiltin(sChanSend, "chan send") + addBuiltin(sChanRecv, "chan receive") + addBuiltin(sNetwork, "network") + addBuiltin(sSync, "sync") + addBuiltin(sSyncCond, "sync.(*Cond).Wait") + addBuiltin(sSelect, "select") + addBuiltin(sEmpty, "") + addBuiltin(sMarkAssistWait, "GC mark assist wait for work") + addBuiltin(sSTWUnknown, "") + addBuiltin(sSTWGCMarkTermination, "GC mark termination") + addBuiltin(sSTWGCSweepTermination, "GC sweep termination") + addBuiltin(sSTWWriteHeapDump, "write heap dump") + addBuiltin(sSTWGoroutineProfile, "goroutine profile") + addBuiltin(sSTWGoroutineProfileCleanup, "goroutine profile cleanup") + addBuiltin(sSTWAllGoroutinesStackTrace, "all goroutine stack trace") + addBuiltin(sSTWReadMemStats, "read mem stats") + addBuiltin(sSTWAllThreadsSyscall, "AllThreadsSyscall") + addBuiltin(sSTWGOMAXPROCS, "GOMAXPROCS") + addBuiltin(sSTWStartTrace, "start trace") + addBuiltin(sSTWStopTrace, "stop trace") + addBuiltin(sSTWCountPagesInUse, "CountPagesInUse (test)") + addBuiltin(sSTWReadMetricsSlow, "ReadMetricsSlow (test)") + addBuiltin(sSTWReadMemStatsSlow, "ReadMemStatsSlow (test)") + addBuiltin(sSTWPageCachePagesLeaked, "PageCachePagesLeaked (test)") + addBuiltin(sSTWResetDebugLog, "ResetDebugLog (test)") + + if addErr != nil { + // This should be impossible but let's be safe. + return fmt.Errorf("couldn't add strings: %w", addErr) + } + + it.evt.strings.compactify() + + // Convert stacks. + for id, stk := range pr.Stacks { + evt.stacks.insert(stackID(id), stack{pcs: stk}) + } + + // OPT(dh): if we could share the frame type between this package and + // tracev1 we wouldn't have to copy the map. + for pc, f := range pr.PCs { + evt.pcs[pc] = frame{ + pc: pc, + funcID: stringID(f.Fn), + fileID: stringID(f.File), + line: uint64(f.Line), + } + } + pr.Stacks = nil + pr.PCs = nil + evt.stacks.compactify() + return nil +} + +// next returns the next event, io.EOF if there are no more events, or a +// descriptive error for invalid events. +func (it *traceV1Converter) next() (Event, error) { + if len(it.extra) > 0 { + ev := it.extra[0] + it.extra = it.extra[1:] + + if len(it.extra) == 0 { + it.extra = it.extraArr[:0] + } + // Two events aren't allowed to fall on the same timestamp in the new API, + // but this may happen when we produce EvGoStatus events + if ev.base.time <= it.lastTs { + ev.base.time = it.lastTs + 1 + } + it.lastTs = ev.base.time + return ev, nil + } + + oev, ok := it.events.Pop() + if !ok { + return Event{}, io.EOF + } + + ev, err := it.convertEvent(oev) + + if err == errSkip { + return it.next() + } else if err != nil { + return Event{}, err + } + + // Two events aren't allowed to fall on the same timestamp in the new API, + // but this may happen when we produce EvGoStatus events + if ev.base.time <= it.lastTs { + ev.base.time = it.lastTs + 1 + } + it.lastTs = ev.base.time + return ev, nil +} + +var errSkip = errors.New("skip event") + +// convertEvent converts an event from the trace v1 format to zero or more +// events in the new format. Most events translate 1 to 1. Some events don't +// result in an event right away, in which case convertEvent returns errSkip. +// Some events result in more than one new event; in this case, convertEvent +// returns the first event and stores additional events in it.extra. When +// encountering events that tracev1 shouldn't be able to emit, ocnvertEvent +// returns a descriptive error. +func (it *traceV1Converter) convertEvent(ev *tracev1.Event) (OUT Event, ERR error) { + var mappedType tracev2.EventType + var mappedArgs timedEventArgs + copy(mappedArgs[:], ev.Args[:]) + + switch ev.Type { + case tracev1.EvGomaxprocs: + mappedType = tracev2.EvProcsChange + if it.preInit { + // The first EvGomaxprocs signals the end of trace initialization. At this point we've seen + // all goroutines that already existed at trace begin. + it.preInit = false + for gid := range it.createdPreInit { + // These are goroutines that already existed when tracing started but for which we + // received neither GoWaiting, GoInSyscall, or GoStart. These are goroutines that are in + // the states _Gidle or _Grunnable. + it.extra = append(it.extra, Event{ + ctx: schedCtx{ + // G: GoID(gid), + G: NoGoroutine, + P: NoProc, + M: NoThread, + }, + table: it.evt, + base: baseEvent{ + typ: tracev2.EvGoStatus, + time: Time(ev.Ts), + args: timedEventArgs{uint64(gid), ^uint64(0), uint64(tracev2.GoRunnable)}, + }, + }) + } + it.createdPreInit = nil + return Event{}, errSkip + } + case tracev1.EvProcStart: + it.procMs[ProcID(ev.P)] = ThreadID(ev.Args[0]) + if _, ok := it.seenProcs[ProcID(ev.P)]; ok { + mappedType = tracev2.EvProcStart + mappedArgs = timedEventArgs{uint64(ev.P)} + } else { + it.seenProcs[ProcID(ev.P)] = struct{}{} + mappedType = tracev2.EvProcStatus + mappedArgs = timedEventArgs{uint64(ev.P), uint64(tracev2.ProcRunning)} + } + case tracev1.EvProcStop: + if _, ok := it.seenProcs[ProcID(ev.P)]; ok { + mappedType = tracev2.EvProcStop + mappedArgs = timedEventArgs{uint64(ev.P)} + } else { + it.seenProcs[ProcID(ev.P)] = struct{}{} + mappedType = tracev2.EvProcStatus + mappedArgs = timedEventArgs{uint64(ev.P), uint64(tracev2.ProcIdle)} + } + case tracev1.EvGCStart: + mappedType = tracev2.EvGCBegin + case tracev1.EvGCDone: + mappedType = tracev2.EvGCEnd + case tracev1.EvSTWStart: + sid := it.builtinToStringID[sSTWUnknown+it.trace.STWReason(ev.Args[0])] + it.lastStwReason = sid + mappedType = tracev2.EvSTWBegin + mappedArgs = timedEventArgs{uint64(sid)} + case tracev1.EvSTWDone: + mappedType = tracev2.EvSTWEnd + mappedArgs = timedEventArgs{it.lastStwReason} + case tracev1.EvGCSweepStart: + mappedType = tracev2.EvGCSweepBegin + case tracev1.EvGCSweepDone: + mappedType = tracev2.EvGCSweepEnd + case tracev1.EvGoCreate: + if it.preInit { + it.createdPreInit[GoID(ev.Args[0])] = struct{}{} + return Event{}, errSkip + } + mappedType = tracev2.EvGoCreate + case tracev1.EvGoStart: + if it.preInit { + mappedType = tracev2.EvGoStatus + mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoRunning)} + delete(it.createdPreInit, GoID(ev.Args[0])) + } else { + mappedType = tracev2.EvGoStart + } + case tracev1.EvGoStartLabel: + it.extra = []Event{{ + ctx: schedCtx{ + G: GoID(ev.G), + P: ProcID(ev.P), + M: it.procMs[ProcID(ev.P)], + }, + table: it.evt, + base: baseEvent{ + typ: tracev2.EvGoLabel, + time: Time(ev.Ts), + args: timedEventArgs{ev.Args[2]}, + }, + }} + return Event{ + ctx: schedCtx{ + G: GoID(ev.G), + P: ProcID(ev.P), + M: it.procMs[ProcID(ev.P)], + }, + table: it.evt, + base: baseEvent{ + typ: tracev2.EvGoStart, + time: Time(ev.Ts), + args: mappedArgs, + }, + }, nil + case tracev1.EvGoEnd: + mappedType = tracev2.EvGoDestroy + case tracev1.EvGoStop: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sForever]), uint64(ev.StkID)} + case tracev1.EvGoSched: + mappedType = tracev2.EvGoStop + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sGosched]), uint64(ev.StkID)} + case tracev1.EvGoPreempt: + mappedType = tracev2.EvGoStop + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sPreempted]), uint64(ev.StkID)} + case tracev1.EvGoSleep: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSleep]), uint64(ev.StkID)} + case tracev1.EvGoBlock: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sEmpty]), uint64(ev.StkID)} + case tracev1.EvGoUnblock: + mappedType = tracev2.EvGoUnblock + case tracev1.EvGoBlockSend: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sChanSend]), uint64(ev.StkID)} + case tracev1.EvGoBlockRecv: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sChanRecv]), uint64(ev.StkID)} + case tracev1.EvGoBlockSelect: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSelect]), uint64(ev.StkID)} + case tracev1.EvGoBlockSync: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSync]), uint64(ev.StkID)} + case tracev1.EvGoBlockCond: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sSyncCond]), uint64(ev.StkID)} + case tracev1.EvGoBlockNet: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sNetwork]), uint64(ev.StkID)} + case tracev1.EvGoBlockGC: + mappedType = tracev2.EvGoBlock + mappedArgs = timedEventArgs{uint64(it.builtinToStringID[sMarkAssistWait]), uint64(ev.StkID)} + case tracev1.EvGoSysCall: + // Look for the next event for the same G to determine if the syscall + // blocked. + blocked := false + it.events.All()(func(nev *tracev1.Event) bool { + if nev.G != ev.G { + return true + } + // After an EvGoSysCall, the next event on the same G will either be + // EvGoSysBlock to denote a blocking syscall, or some other event + // (or the end of the trace) if the syscall didn't block. + if nev.Type == tracev1.EvGoSysBlock { + blocked = true + } + return false + }) + if blocked { + mappedType = tracev2.EvGoSyscallBegin + mappedArgs = timedEventArgs{1: uint64(ev.StkID)} + } else { + // Convert the old instantaneous syscall event to a pair of syscall + // begin and syscall end and give it the shortest possible duration, + // 1ns. + out1 := Event{ + ctx: schedCtx{ + G: GoID(ev.G), + P: ProcID(ev.P), + M: it.procMs[ProcID(ev.P)], + }, + table: it.evt, + base: baseEvent{ + typ: tracev2.EvGoSyscallBegin, + time: Time(ev.Ts), + args: timedEventArgs{1: uint64(ev.StkID)}, + }, + } + + out2 := Event{ + ctx: out1.ctx, + table: it.evt, + base: baseEvent{ + typ: tracev2.EvGoSyscallEnd, + time: Time(ev.Ts + 1), + args: timedEventArgs{}, + }, + } + + it.extra = append(it.extra, out2) + return out1, nil + } + + case tracev1.EvGoSysExit: + mappedType = tracev2.EvGoSyscallEndBlocked + case tracev1.EvGoSysBlock: + return Event{}, errSkip + case tracev1.EvGoWaiting: + mappedType = tracev2.EvGoStatus + mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoWaiting)} + delete(it.createdPreInit, GoID(ev.Args[0])) + case tracev1.EvGoInSyscall: + mappedType = tracev2.EvGoStatus + // In the new tracer, GoStatus with GoSyscall knows what thread the + // syscall is on. In trace v1, EvGoInSyscall doesn't contain that + // information and all we can do here is specify NoThread. + mappedArgs = timedEventArgs{ev.Args[0], ^uint64(0), uint64(tracev2.GoSyscall)} + delete(it.createdPreInit, GoID(ev.Args[0])) + case tracev1.EvHeapAlloc: + mappedType = tracev2.EvHeapAlloc + case tracev1.EvHeapGoal: + mappedType = tracev2.EvHeapGoal + case tracev1.EvGCMarkAssistStart: + mappedType = tracev2.EvGCMarkAssistBegin + case tracev1.EvGCMarkAssistDone: + mappedType = tracev2.EvGCMarkAssistEnd + case tracev1.EvUserTaskCreate: + mappedType = tracev2.EvUserTaskBegin + parent := ev.Args[1] + if parent == 0 { + parent = uint64(NoTask) + } + mappedArgs = timedEventArgs{ev.Args[0], parent, ev.Args[2], uint64(ev.StkID)} + name, _ := it.evt.strings.get(stringID(ev.Args[2])) + it.tasks[TaskID(ev.Args[0])] = taskState{name: name, parentID: TaskID(ev.Args[1])} + case tracev1.EvUserTaskEnd: + mappedType = tracev2.EvUserTaskEnd + // Event.Task expects the parent and name to be smuggled in extra args + // and as extra strings. + ts, ok := it.tasks[TaskID(ev.Args[0])] + if ok { + delete(it.tasks, TaskID(ev.Args[0])) + mappedArgs = timedEventArgs{ + ev.Args[0], + ev.Args[1], + uint64(ts.parentID), + uint64(it.evt.addExtraString(ts.name)), + } + } else { + mappedArgs = timedEventArgs{ev.Args[0], ev.Args[1], uint64(NoTask), uint64(it.evt.addExtraString(""))} + } + case tracev1.EvUserRegion: + switch ev.Args[1] { + case 0: // start + mappedType = tracev2.EvUserRegionBegin + case 1: // end + mappedType = tracev2.EvUserRegionEnd + } + mappedArgs = timedEventArgs{ev.Args[0], ev.Args[2], uint64(ev.StkID)} + case tracev1.EvUserLog: + mappedType = tracev2.EvUserLog + mappedArgs = timedEventArgs{ev.Args[0], ev.Args[1], it.inlineToStringID[ev.Args[3]], uint64(ev.StkID)} + case tracev1.EvCPUSample: + mappedType = tracev2.EvCPUSample + // When emitted by the Go 1.22 tracer, CPU samples have 5 arguments: + // timestamp, M, P, G, stack. However, after they get turned into Event, + // they have the arguments stack, M, P, G. + // + // In Go 1.21, CPU samples did not have Ms. + mappedArgs = timedEventArgs{uint64(ev.StkID), ^uint64(0), uint64(ev.P), ev.G} + default: + return Event{}, fmt.Errorf("unexpected event type %v", ev.Type) + } + + if tracev1.EventDescriptions[ev.Type].Stack { + if stackIDs := tracev2.Specs()[mappedType].StackIDs; len(stackIDs) > 0 { + mappedArgs[stackIDs[0]-1] = uint64(ev.StkID) + } + } + + m := NoThread + if ev.P != -1 && ev.Type != tracev1.EvCPUSample { + if t, ok := it.procMs[ProcID(ev.P)]; ok { + m = ThreadID(t) + } + } + if ev.Type == tracev1.EvProcStop { + delete(it.procMs, ProcID(ev.P)) + } + g := GoID(ev.G) + if g == 0 { + g = NoGoroutine + } + out := Event{ + ctx: schedCtx{ + G: GoID(g), + P: ProcID(ev.P), + M: m, + }, + table: it.evt, + base: baseEvent{ + typ: mappedType, + time: Time(ev.Ts), + args: mappedArgs, + }, + } + return out, nil +} + +// convertV1Trace takes a fully loaded trace in the v1 trace format and +// returns an iterator over events in the new format. +func convertV1Trace(pr tracev1.Trace) *traceV1Converter { + it := &traceV1Converter{} + it.init(pr) + return it +} diff --git a/go/src/internal/trace/tracev1_test.go b/go/src/internal/trace/tracev1_test.go new file mode 100644 index 0000000000000000000000000000000000000000..355a6ff529f2aefbc6361245e9c3c62c42be41bc --- /dev/null +++ b/go/src/internal/trace/tracev1_test.go @@ -0,0 +1,89 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace_test + +import ( + "internal/trace" + "internal/trace/testtrace" + "internal/trace/version" + "io" + "os" + "path/filepath" + "testing" +) + +func TestTraceV1(t *testing.T) { + traces, err := filepath.Glob("./internal/tracev1/testdata/*_good") + if err != nil { + t.Fatalf("failed to glob for tests: %s", err) + } + var testedUserRegions bool + for _, p := range traces { + testName, err := filepath.Rel("./internal/tracev1/testdata", p) + if err != nil { + t.Fatalf("failed to relativize testdata path: %s", err) + } + t.Run(testName, func(t *testing.T) { + f, err := os.Open(p) + if err != nil { + t.Fatalf("failed to open test %q: %s", p, err) + } + defer f.Close() + + tr, err := trace.NewReader(f) + if err != nil { + t.Fatalf("failed to create reader: %s", err) + } + + v := testtrace.NewValidator() + v.GoVersion = version.Go121 + for { + ev, err := tr.ReadEvent() + if err != nil { + if err == io.EOF { + break + } + t.Fatalf("couldn't read converted event: %s", err) + } + if err := v.Event(ev); err != nil { + t.Fatalf("converted event did not validate; event: \n%s\nerror: %s", ev, err) + } + + if testName == "user_task_region_1_21_good" { + testedUserRegions = true + validRegions := map[string]struct{}{ + "post-existing region": {}, + "region0": {}, + "region1": {}, + } + // Check that we correctly convert user regions. These + // strings were generated by + // runtime/trace.TestUserTaskRegion, which is the basis for + // the user_task_region_* test cases. We only check for the + // Go 1.21 traces because earlier traces used different + // strings. + switch ev.Kind() { + case trace.EventRegionBegin, trace.EventRegionEnd: + if _, ok := validRegions[ev.Region().Type]; !ok { + t.Fatalf("converted event has unexpected region type:\n%s", ev) + } + case trace.EventTaskBegin, trace.EventTaskEnd: + if ev.Task().Type != "task0" { + t.Fatalf("converted event has unexpected task type name:\n%s", ev) + } + case trace.EventLog: + l := ev.Log() + if l.Task != 1 || l.Category != "key0" || l.Message != "0123456789abcdef" { + t.Fatalf("converted event has unexpected user log:\n%s", ev) + } + } + } + } + }) + } + if !testedUserRegions { + t.Fatal("didn't see expected test case user_task_region_1_21_good") + } +} diff --git a/go/src/internal/trace/tracev2/EXPERIMENTS.md b/go/src/internal/trace/tracev2/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..fedf7bdbdc8db74f9f564bafe9708cfa563046e4 --- /dev/null +++ b/go/src/internal/trace/tracev2/EXPERIMENTS.md @@ -0,0 +1,101 @@ +# Trace experiments + +Execution traces allow for trialing new events on an experimental basis via +trace experiments. +This document is a guide that explains how you can define your own trace +experiments. + +Note that if you're just trying to do some debugging or perform some light +instrumentation, then a trace experiment is way overkill. +Use `runtime/trace.Log` instead. +Even if you're just trying to create a proof-of-concept for a low-frequency +event, `runtime/trace.Log` will probably be easier overall if you can make +it work. + +Consider a trace experiment if: +- The volume of new trace events will be relatively high, and so the events + would benefit from a more compact representation (creating new tables to + deduplicate data, taking advantage of the varint representation, etc.). +- It's not safe to call `runtime/trace.Log` (or its runtime equivalent) in + the contexts you want to generate an event (for example, for events about + timers). + +## Defining a new experiment + +To define a new experiment, modify `internal/trace/tracev2` to define a +new `Experiment` enum value. + +An experiment consists of two parts: timed events and experimental batches. +Timed events are events like any other and follow the same format. +They are easier to order and require less work to make use of. +Experimental batches are essentially bags of bytes that correspond to +an entire trace generation. +What they contain and how they're interpreted is totally up to you, but +they're most often useful for tables that your other events can refer into. +For example, the AllocFree experiment uses them to store type information +that allocation events can refer to. + +### Defining new events + +1. Define your new experiment event types (by convention, experimental events + types start at ID 127, so look for the `const` block defining events + starting there). +2. Describe your new events in `specs`. + Use the documentation for `Spec` to write your new specs, and check your + work by running the tests in the `internal/trace/tracev2` package. + If you wish for your event argument to be interpreted in a particular + way, follow the naming convention in + `src/internal/trace/tracev2/spec.go`. + For example, if you intend to emit a string argument, make sure the + argument name has the suffix `string`. +3. Add ordering and validation logic for your new events to + `src/internal/trace/order.go` by listing handlers for those events in + the `orderingDispatch` table. + If your events are always emitted in a regular user goroutine context, + then the handler should be trivial and just validate the scheduling + context to match userGoReqs. + If it's more complicated, see `(*ordering).advanceAllocFree` for a + slightly more complicated example that handles events from a larger + variety of execution environments. + If you need to encode a partial ordering, look toward the scheduler + events (names beginning with `Go`) or just ask someone for help. +4. Add your new events to the `tracev2Type2Kind` table in + `src/internal/trace/event.go`. + +## Emitting data + +### Emitting your new events + +1. Define helper methods on `runtime.traceEventWriter` for emitting your + events. +2. Instrument the runtime with calls to these helper methods. + Make sure to call `traceAcquire` and `traceRelease` around the operation + your event represents, otherwise it will not be emitted atomically with + that operation completing, resulting in a potentially misleading trace. + +### Emitting experimental batches + +To emit experimental batches, use the `runtime.unsafeTraceExpWriter` to +write experimental batches associated with your experiment. +Heed the warnings and make sure that while you write them, the trace +generation cannot advance. +Note that each experiment can only have one distinguishable set of +batches. + +## Recovering experimental data + +### Recovering experimental events from the trace + +Experimental events will appear in the event stream as an event with the +`EventExperimental` `Kind`. +Use the `Experimental` method to collect the raw data inserted into the +trace. +It's essentially up to you to interpret the event from here. +I recommend writing a thin wrapper API to present a cleaner interface if you +so desire. + +### Recovering experimental batches + +Parse out all the experimental batches from `Sync` events as they come. +These experimental batches are all for the same generation as all the +experimental events up until the next `Sync` event. diff --git a/go/src/internal/trace/tracev2/doc.go b/go/src/internal/trace/tracev2/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..725fc0821d0fd723a42d0293ce7f9112ebd1f4b4 --- /dev/null +++ b/go/src/internal/trace/tracev2/doc.go @@ -0,0 +1,11 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package tracev2 contains definitions for the v2 execution trace wire format. + +These definitions are shared between the trace parser and the runtime, so it +must not depend on any package that depends on the runtime (most packages). +*/ +package tracev2 diff --git a/go/src/internal/trace/tracev2/events.go b/go/src/internal/trace/tracev2/events.go new file mode 100644 index 0000000000000000000000000000000000000000..c5e3c94136946b0202340097f0eeb86f3b8f3aa9 --- /dev/null +++ b/go/src/internal/trace/tracev2/events.go @@ -0,0 +1,589 @@ +// 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 tracev2 + +// Event types in the trace, args are given in square brackets. +// +// Naming scheme: +// - Time range event pairs have suffixes "Begin" and "End". +// - "Start", "Stop", "Create", "Destroy", "Block", "Unblock" +// are suffixes reserved for scheduling resources. +// +// NOTE: If you add an event type, make sure you also update all +// tables in this file! +const ( + EvNone EventType = iota // unused + + // Structural events. + EvEventBatch // start of per-M batch of events [generation, M ID, timestamp, batch length] + EvStacks // start of a section of the stack table [...EvStack] + EvStack // stack table entry [ID, ...{PC, func string ID, file string ID, line #}] + EvStrings // start of a section of the string dictionary [...EvString] + EvString // string dictionary entry [ID, length, string] + EvCPUSamples // start of a section of CPU samples [...EvCPUSample] + EvCPUSample // CPU profiling sample [timestamp, M ID, P ID, goroutine ID, stack ID] + EvFrequency // timestamp units per sec [freq] + + // Procs. + EvProcsChange // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack ID] + EvProcStart // start of P [timestamp, P ID, P seq] + EvProcStop // stop of P [timestamp] + EvProcSteal // P was stolen [timestamp, P ID, P seq, M ID] + EvProcStatus // P status at the start of a generation [timestamp, P ID, status] + + // Goroutines. + EvGoCreate // goroutine creation [timestamp, new goroutine ID, new stack ID, stack ID] + EvGoCreateSyscall // goroutine appears in syscall (cgo callback) [timestamp, new goroutine ID] + EvGoStart // goroutine starts running [timestamp, goroutine ID, goroutine seq] + EvGoDestroy // goroutine ends [timestamp] + EvGoDestroySyscall // goroutine ends in syscall (cgo callback) [timestamp] + EvGoStop // goroutine yields its time, but is runnable [timestamp, reason, stack ID] + EvGoBlock // goroutine blocks [timestamp, reason, stack ID] + EvGoUnblock // goroutine is unblocked [timestamp, goroutine ID, goroutine seq, stack ID] + EvGoSyscallBegin // syscall enter [timestamp, P seq, stack ID] + EvGoSyscallEnd // syscall exit [timestamp] + EvGoSyscallEndBlocked // syscall exit and it blocked at some point [timestamp] + EvGoStatus // goroutine status at the start of a generation [timestamp, goroutine ID, M ID, status] + + // STW. + EvSTWBegin // STW start [timestamp, kind, stack ID] + EvSTWEnd // STW done [timestamp] + + // GC events. + EvGCActive // GC active [timestamp, seq] + EvGCBegin // GC start [timestamp, seq, stack ID] + EvGCEnd // GC done [timestamp, seq] + EvGCSweepActive // GC sweep active [timestamp, P ID] + EvGCSweepBegin // GC sweep start [timestamp, stack ID] + EvGCSweepEnd // GC sweep done [timestamp, swept bytes, reclaimed bytes] + EvGCMarkAssistActive // GC mark assist active [timestamp, goroutine ID] + EvGCMarkAssistBegin // GC mark assist start [timestamp, stack ID] + EvGCMarkAssistEnd // GC mark assist done [timestamp] + EvHeapAlloc // gcController.heapLive change [timestamp, heap alloc in bytes] + EvHeapGoal // gcController.heapGoal() change [timestamp, heap goal in bytes] + + // Annotations. + EvGoLabel // apply string label to current running goroutine [timestamp, label string ID] + EvUserTaskBegin // trace.NewTask [timestamp, internal task ID, internal parent task ID, name string ID, stack ID] + EvUserTaskEnd // end of a task [timestamp, internal task ID, stack ID] + EvUserRegionBegin // trace.{Start,With}Region [timestamp, internal task ID, name string ID, stack ID] + EvUserRegionEnd // trace.{End,With}Region [timestamp, internal task ID, name string ID, stack ID] + EvUserLog // trace.Log [timestamp, internal task ID, key string ID, value string ID, stack] + + // Coroutines. Added in Go 1.23. + EvGoSwitch // goroutine switch (coroswitch) [timestamp, goroutine ID, goroutine seq] + EvGoSwitchDestroy // goroutine switch and destroy [timestamp, goroutine ID, goroutine seq] + EvGoCreateBlocked // goroutine creation (starts blocked) [timestamp, new goroutine ID, new stack ID, stack ID] + + // GoStatus with stack. Added in Go 1.23. + EvGoStatusStack // goroutine status at the start of a generation, with a stack [timestamp, goroutine ID, M ID, status, stack ID] + + // Batch event for an experimental batch with a custom format. Added in Go 1.23. + EvExperimentalBatch // start of extra data [experiment ID, generation, M ID, timestamp, batch length, batch data...] + + // Sync batch. Added in Go 1.25. Previously a lone EvFrequency event. + EvSync // start of a sync batch [...EvFrequency|EvClockSnapshot] + EvClockSnapshot // snapshot of trace, mono and wall clocks [timestamp, mono, sec, nsec] + + // In-band end-of-generation signal. Added in Go 1.26. + // Used in Go 1.25 only internally. + EvEndOfGeneration + + NumEvents +) + +func (ev EventType) Experimental() bool { + return ev > MaxEvent && ev < MaxExperimentalEvent +} + +// Experiments. +const ( + // AllocFree is the alloc-free events experiment. + AllocFree Experiment = 1 + iota + + NumExperiments +) + +func Experiments() []string { + return experiments[:] +} + +var experiments = [...]string{ + NoExperiment: "None", + AllocFree: "AllocFree", +} + +// Experimental events. +const ( + MaxEvent EventType = 127 + iota + + // Experimental events for AllocFree. + + // Experimental heap span events. Added in Go 1.23. + EvSpan // heap span exists [timestamp, id, npages, type/class] + EvSpanAlloc // heap span alloc [timestamp, id, npages, type/class] + EvSpanFree // heap span free [timestamp, id] + + // Experimental heap object events. Added in Go 1.23. + EvHeapObject // heap object exists [timestamp, id, type] + EvHeapObjectAlloc // heap object alloc [timestamp, id, type] + EvHeapObjectFree // heap object free [timestamp, id] + + // Experimental goroutine stack events. Added in Go 1.23. + EvGoroutineStack // stack exists [timestamp, id, order] + EvGoroutineStackAlloc // stack alloc [timestamp, id, order] + EvGoroutineStackFree // stack free [timestamp, id] + + MaxExperimentalEvent +) + +const NumExperimentalEvents = MaxExperimentalEvent - MaxEvent + +// MaxTimedEventArgs is the maximum number of arguments for timed events. +const MaxTimedEventArgs = 5 + +func Specs() []EventSpec { + return specs[:] +} + +var specs = [...]EventSpec{ + // "Structural" Events. + EvEventBatch: { + Name: "EventBatch", + Args: []string{"gen", "m", "time", "size"}, + }, + EvStacks: { + Name: "Stacks", + }, + EvStack: { + Name: "Stack", + Args: []string{"id", "nframes"}, + IsStack: true, + }, + EvStrings: { + Name: "Strings", + }, + EvString: { + Name: "String", + Args: []string{"id"}, + HasData: true, + }, + EvCPUSamples: { + Name: "CPUSamples", + }, + EvCPUSample: { + Name: "CPUSample", + Args: []string{"time", "m", "p", "g", "stack"}, + // N.B. There's clearly a timestamp here, but these Events + // are special in that they don't appear in the regular + // M streams. + StackIDs: []int{4}, + }, + EvFrequency: { + Name: "Frequency", + Args: []string{"freq"}, + }, + EvExperimentalBatch: { + Name: "ExperimentalBatch", + Args: []string{"exp", "gen", "m", "time"}, + HasData: true, // Easier to represent for raw readers. + }, + EvSync: { + Name: "Sync", + }, + EvEndOfGeneration: { + Name: "EndOfGeneration", + }, + + // "Timed" Events. + EvProcsChange: { + Name: "ProcsChange", + Args: []string{"dt", "procs_value", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + }, + EvProcStart: { + Name: "ProcStart", + Args: []string{"dt", "p", "p_seq"}, + IsTimedEvent: true, + }, + EvProcStop: { + Name: "ProcStop", + Args: []string{"dt"}, + IsTimedEvent: true, + }, + EvProcSteal: { + Name: "ProcSteal", + Args: []string{"dt", "p", "p_seq", "m"}, + IsTimedEvent: true, + }, + EvProcStatus: { + Name: "ProcStatus", + Args: []string{"dt", "p", "pstatus"}, + IsTimedEvent: true, + }, + EvGoCreate: { + Name: "GoCreate", + Args: []string{"dt", "new_g", "new_stack", "stack"}, + IsTimedEvent: true, + StackIDs: []int{3, 2}, + }, + EvGoCreateSyscall: { + Name: "GoCreateSyscall", + Args: []string{"dt", "new_g"}, + IsTimedEvent: true, + }, + EvGoStart: { + Name: "GoStart", + Args: []string{"dt", "g", "g_seq"}, + IsTimedEvent: true, + }, + EvGoDestroy: { + Name: "GoDestroy", + Args: []string{"dt"}, + IsTimedEvent: true, + }, + EvGoDestroySyscall: { + Name: "GoDestroySyscall", + Args: []string{"dt"}, + IsTimedEvent: true, + }, + EvGoStop: { + Name: "GoStop", + Args: []string{"dt", "reason_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + StringIDs: []int{1}, + }, + EvGoBlock: { + Name: "GoBlock", + Args: []string{"dt", "reason_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + StringIDs: []int{1}, + }, + EvGoUnblock: { + Name: "GoUnblock", + Args: []string{"dt", "g", "g_seq", "stack"}, + IsTimedEvent: true, + StackIDs: []int{3}, + }, + EvGoSyscallBegin: { + Name: "GoSyscallBegin", + Args: []string{"dt", "p_seq", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + }, + EvGoSyscallEnd: { + Name: "GoSyscallEnd", + Args: []string{"dt"}, + StartEv: EvGoSyscallBegin, + IsTimedEvent: true, + }, + EvGoSyscallEndBlocked: { + Name: "GoSyscallEndBlocked", + Args: []string{"dt"}, + StartEv: EvGoSyscallBegin, + IsTimedEvent: true, + }, + EvGoStatus: { + Name: "GoStatus", + Args: []string{"dt", "g", "m", "gstatus"}, + IsTimedEvent: true, + }, + EvSTWBegin: { + Name: "STWBegin", + Args: []string{"dt", "kind_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + StringIDs: []int{1}, + }, + EvSTWEnd: { + Name: "STWEnd", + Args: []string{"dt"}, + StartEv: EvSTWBegin, + IsTimedEvent: true, + }, + EvGCActive: { + Name: "GCActive", + Args: []string{"dt", "gc_seq"}, + IsTimedEvent: true, + StartEv: EvGCBegin, + }, + EvGCBegin: { + Name: "GCBegin", + Args: []string{"dt", "gc_seq", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + }, + EvGCEnd: { + Name: "GCEnd", + Args: []string{"dt", "gc_seq"}, + StartEv: EvGCBegin, + IsTimedEvent: true, + }, + EvGCSweepActive: { + Name: "GCSweepActive", + Args: []string{"dt", "p"}, + StartEv: EvGCSweepBegin, + IsTimedEvent: true, + }, + EvGCSweepBegin: { + Name: "GCSweepBegin", + Args: []string{"dt", "stack"}, + IsTimedEvent: true, + StackIDs: []int{1}, + }, + EvGCSweepEnd: { + Name: "GCSweepEnd", + Args: []string{"dt", "swept_value", "reclaimed_value"}, + StartEv: EvGCSweepBegin, + IsTimedEvent: true, + }, + EvGCMarkAssistActive: { + Name: "GCMarkAssistActive", + Args: []string{"dt", "g"}, + StartEv: EvGCMarkAssistBegin, + IsTimedEvent: true, + }, + EvGCMarkAssistBegin: { + Name: "GCMarkAssistBegin", + Args: []string{"dt", "stack"}, + IsTimedEvent: true, + StackIDs: []int{1}, + }, + EvGCMarkAssistEnd: { + Name: "GCMarkAssistEnd", + Args: []string{"dt"}, + StartEv: EvGCMarkAssistBegin, + IsTimedEvent: true, + }, + EvHeapAlloc: { + Name: "HeapAlloc", + Args: []string{"dt", "heapalloc_value"}, + IsTimedEvent: true, + }, + EvHeapGoal: { + Name: "HeapGoal", + Args: []string{"dt", "heapgoal_value"}, + IsTimedEvent: true, + }, + EvGoLabel: { + Name: "GoLabel", + Args: []string{"dt", "label_string"}, + IsTimedEvent: true, + StringIDs: []int{1}, + }, + EvUserTaskBegin: { + Name: "UserTaskBegin", + Args: []string{"dt", "task", "parent_task", "name_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{4}, + StringIDs: []int{3}, + }, + EvUserTaskEnd: { + Name: "UserTaskEnd", + Args: []string{"dt", "task", "stack"}, + IsTimedEvent: true, + StackIDs: []int{2}, + }, + EvUserRegionBegin: { + Name: "UserRegionBegin", + Args: []string{"dt", "task", "name_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{3}, + StringIDs: []int{2}, + }, + EvUserRegionEnd: { + Name: "UserRegionEnd", + Args: []string{"dt", "task", "name_string", "stack"}, + StartEv: EvUserRegionBegin, + IsTimedEvent: true, + StackIDs: []int{3}, + StringIDs: []int{2}, + }, + EvUserLog: { + Name: "UserLog", + Args: []string{"dt", "task", "key_string", "value_string", "stack"}, + IsTimedEvent: true, + StackIDs: []int{4}, + StringIDs: []int{2, 3}, + }, + EvGoSwitch: { + Name: "GoSwitch", + Args: []string{"dt", "g", "g_seq"}, + IsTimedEvent: true, + }, + EvGoSwitchDestroy: { + Name: "GoSwitchDestroy", + Args: []string{"dt", "g", "g_seq"}, + IsTimedEvent: true, + }, + EvGoCreateBlocked: { + Name: "GoCreateBlocked", + Args: []string{"dt", "new_g", "new_stack", "stack"}, + IsTimedEvent: true, + StackIDs: []int{3, 2}, + }, + EvGoStatusStack: { + Name: "GoStatusStack", + Args: []string{"dt", "g", "m", "gstatus", "stack"}, + IsTimedEvent: true, + StackIDs: []int{4}, + }, + EvClockSnapshot: { + Name: "ClockSnapshot", + Args: []string{"dt", "mono", "sec", "nsec"}, + IsTimedEvent: true, + }, + + // Experimental events. + + EvSpan: { + Name: "Span", + Args: []string{"dt", "id", "npages_value", "kindclass"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvSpanAlloc: { + Name: "SpanAlloc", + Args: []string{"dt", "id", "npages_value", "kindclass"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvSpanFree: { + Name: "SpanFree", + Args: []string{"dt", "id"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvHeapObject: { + Name: "HeapObject", + Args: []string{"dt", "id", "type"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvHeapObjectAlloc: { + Name: "HeapObjectAlloc", + Args: []string{"dt", "id", "type"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvHeapObjectFree: { + Name: "HeapObjectFree", + Args: []string{"dt", "id"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvGoroutineStack: { + Name: "GoroutineStack", + Args: []string{"dt", "id", "order"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvGoroutineStackAlloc: { + Name: "GoroutineStackAlloc", + Args: []string{"dt", "id", "order"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, + EvGoroutineStackFree: { + Name: "GoroutineStackFree", + Args: []string{"dt", "id"}, + IsTimedEvent: true, + Experiment: AllocFree, + }, +} + +// GoStatus is the status of a goroutine. +// +// They correspond directly to the various goroutine states. +type GoStatus uint8 + +const ( + GoBad GoStatus = iota + GoRunnable + GoRunning + GoSyscall + GoWaiting +) + +func (s GoStatus) String() string { + switch s { + case GoRunnable: + return "Runnable" + case GoRunning: + return "Running" + case GoSyscall: + return "Syscall" + case GoWaiting: + return "Waiting" + } + return "Bad" +} + +// ProcStatus is the status of a P. +// +// They mostly correspond to the various P states. +type ProcStatus uint8 + +const ( + ProcBad ProcStatus = iota + ProcRunning + ProcIdle + ProcSyscall + + // ProcSyscallAbandoned is a special case of + // ProcSyscall. It's used in the very specific case + // where the first a P is mentioned in a generation is + // part of a ProcSteal event. If that's the first time + // it's mentioned, then there's no GoSyscallBegin to + // connect the P stealing back to at that point. This + // special state indicates this to the parser, so it + // doesn't try to find a GoSyscallEndBlocked that + // corresponds with the ProcSteal. + ProcSyscallAbandoned +) + +func (s ProcStatus) String() string { + switch s { + case ProcRunning: + return "Running" + case ProcIdle: + return "Idle" + case ProcSyscall: + return "Syscall" + } + return "Bad" +} + +const ( + // MaxBatchSize sets the maximum size that a batch can be. + // + // Directly controls the trace batch size in the runtime. + // + // NOTE: If this number decreases, the trace format version must change. + MaxBatchSize = 64 << 10 + + // Maximum number of PCs in a single stack trace. + // + // Since events contain only stack ID rather than whole stack trace, + // we can allow quite large values here. + // + // Directly controls the maximum number of frames per stack + // in the runtime. + // + // NOTE: If this number decreases, the trace format version must change. + MaxFramesPerStack = 128 + + // MaxEventTrailerDataSize controls the amount of trailer data that + // an event can have in bytes. Must be smaller than MaxBatchSize. + // Controls the maximum string size in the trace. + // + // Directly controls the maximum such value in the runtime. + // + // NOTE: If this number decreases, the trace format version must change. + MaxEventTrailerDataSize = 1 << 10 +) diff --git a/go/src/internal/trace/tracev2/events_test.go b/go/src/internal/trace/tracev2/events_test.go new file mode 100644 index 0000000000000000000000000000000000000000..60c4c08c34a1278acfe150fef90d9289e86aaa80 --- /dev/null +++ b/go/src/internal/trace/tracev2/events_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. + +package tracev2_test + +import ( + "internal/trace/tracev2" + "iter" + "regexp" + "slices" + "strings" + "testing" +) + +var argNameRegexp = regexp.MustCompile(`((?P[A-Za-z]+)_)?(?P[A-Za-z]+)`) + +func TestSpecs(t *testing.T) { + if tracev2.NumEvents <= 0 { + t.Fatalf("no trace events?") + } + if tracev2.MaxExperimentalEvent < tracev2.MaxEvent { + t.Fatalf("max experimental event (%d) is < max event (%d)", tracev2.MaxExperimentalEvent, tracev2.MaxEvent) + } + specs := tracev2.Specs() + for ev := range allEvents() { + spec := &specs[ev] + if spec.Name == "" { + t.Errorf("expected event %d to be defined in specs", ev) + continue + } + if spec.IsTimedEvent && spec.Args[0] != "dt" { + t.Errorf("%s is a timed event, but its first argument is not 'dt'", spec.Name) + } + if spec.HasData && spec.Name != "String" && spec.Name != "ExperimentalBatch" { + t.Errorf("%s has data, but is not a special kind of event (unsupported, but could be)", spec.Name) + } + if spec.IsStack && spec.Name != "Stack" { + t.Errorf("%s listed as being a stack, but is not the Stack event (unsupported)", spec.Name) + } + if spec.IsTimedEvent && len(spec.Args) > tracev2.MaxTimedEventArgs { + t.Errorf("%s has too many timed event args: have %d, want %d at most", spec.Name, len(spec.Args), tracev2.MaxTimedEventArgs) + } + if ev.Experimental() && spec.Experiment == tracev2.NoExperiment { + t.Errorf("experimental event %s must have an experiment", spec.Name) + } + + // Check arg types. + for _, arg := range spec.Args { + matches := argNameRegexp.FindStringSubmatch(arg) + if len(matches) == 0 { + t.Errorf("malformed argument %s for event %s", arg, spec.Name) + } + } + + // Check stacks. + for _, i := range spec.StackIDs { + if !strings.HasSuffix(spec.Args[i], "stack") { + t.Errorf("stack argument listed at %d in %s, but argument name %s does not imply stack type", i, spec.Name, spec.Args[i]) + } + } + for i, arg := range spec.Args { + if !strings.HasSuffix(spec.Args[i], "stack") { + continue + } + if !slices.Contains(spec.StackIDs, i) { + t.Errorf("found stack argument %s in %s at index %d not listed in StackIDs", arg, spec.Name, i) + } + } + + // Check strings. + for _, i := range spec.StringIDs { + if !strings.HasSuffix(spec.Args[i], "string") { + t.Errorf("string argument listed at %d in %s, but argument name %s does not imply string type", i, spec.Name, spec.Args[i]) + } + } + for i, arg := range spec.Args { + if !strings.HasSuffix(spec.Args[i], "string") { + continue + } + if !slices.Contains(spec.StringIDs, i) { + t.Errorf("found string argument %s in %s at index %d not listed in StringIDs", arg, spec.Name, i) + } + } + } +} + +func allEvents() iter.Seq[tracev2.EventType] { + return func(yield func(tracev2.EventType) bool) { + for ev := tracev2.EvNone + 1; ev < tracev2.NumEvents; ev++ { + if !yield(ev) { + return + } + } + for ev := tracev2.MaxEvent + 1; ev < tracev2.NumExperimentalEvents; ev++ { + if !yield(ev) { + return + } + } + } +} diff --git a/go/src/internal/trace/tracev2/spec.go b/go/src/internal/trace/tracev2/spec.go new file mode 100644 index 0000000000000000000000000000000000000000..6e54c399f49ddf4abc84d438cd9f94a0306f2e20 --- /dev/null +++ b/go/src/internal/trace/tracev2/spec.go @@ -0,0 +1,107 @@ +// 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 tracev2 + +// EventType indicates an event's type from which its arguments and semantics can be +// derived. Its representation matches the wire format's representation of the event +// types that precede all event data. +type EventType uint8 + +// EventSpec is a specification for a trace event. It contains sufficient information +// to perform basic parsing of any trace event for any version of Go. +type EventSpec struct { + // Name is the human-readable name of the trace event. + Name string + + // Args contains the names of each trace event's argument. + // Its length determines the number of arguments an event has. + // + // Argument names follow a certain structure and this structure + // is relied on by the testing framework to type-check arguments + // and to produce Values for experimental events. + // + // The structure is: + // + // (?P[A-Za-z]+)(_(?P[A-Za-z]+))? + // + // In sum, it's a name followed by an optional type. + // If the type is present, it is preceded with an underscore. + // Arguments without types will be interpreted as just raw uint64s. + // The valid argument types and the Go types they map to are listed + // in the ArgTypes variable. + Args []string + + // StringIDs indicates which of the arguments are string IDs. + StringIDs []int + + // StackIDs indicates which of the arguments are stack IDs. + // + // The list is not sorted. The first index always refers to + // the main stack for the current execution context of the event. + StackIDs []int + + // StartEv indicates the event type of the corresponding "start" + // event, if this event is an "end," for a pair of events that + // represent a time range. + StartEv EventType + + // IsTimedEvent indicates whether this is an event that both + // appears in the main event stream and is surfaced to the + // trace reader. + // + // Events that are not "timed" are considered "structural" + // since they either need significant reinterpretation or + // otherwise aren't actually surfaced by the trace reader. + IsTimedEvent bool + + // HasData is true if the event has trailer consisting of a + // varint length followed by unencoded bytes of some data. + // + // An event may not be both a timed event and have data. + HasData bool + + // IsStack indicates that the event represents a complete + // stack trace. Specifically, it means that after the arguments + // there's a varint length, followed by 4*length varints. Each + // group of 4 represents the PC, file ID, func ID, and line number + // in that order. + IsStack bool + + // Experiment indicates the ID of an experiment this event is associated + // with. If Experiment is not NoExperiment, then the event is experimental + // and will be exposed as an EventExperiment. + Experiment Experiment +} + +// EventArgTypes is a list of valid argument types for use in Args. +// +// See the documentation of Args for more details. +var EventArgTypes = [...]string{ + "seq", // sequence number + "pstatus", // P status + "gstatus", // G status + "g", // trace.GoID + "m", // trace.ThreadID + "p", // trace.ProcID + "string", // string ID + "stack", // stack ID + "value", // uint64 + "task", // trace.TaskID +} + +// EventNames is a helper that produces a mapping of event names to event types. +func EventNames(specs []EventSpec) map[string]EventType { + nameToType := make(map[string]EventType) + for i, spec := range specs { + nameToType[spec.Name] = EventType(byte(i)) + } + return nameToType +} + +// Experiment is an experiment ID that events may be associated with. +type Experiment uint + +// NoExperiment is the reserved ID 0 indicating no experiment. +const NoExperiment Experiment = 0 diff --git a/go/src/internal/trace/traceviewer/emitter.go b/go/src/internal/trace/traceviewer/emitter.go new file mode 100644 index 0000000000000000000000000000000000000000..9167ff81b45f8380e81c5c8158e17f06e341b80c --- /dev/null +++ b/go/src/internal/trace/traceviewer/emitter.go @@ -0,0 +1,813 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package traceviewer + +import ( + "encoding/json" + "fmt" + "internal/trace" + "internal/trace/traceviewer/format" + "io" + "strconv" + "time" +) + +type TraceConsumer struct { + ConsumeTimeUnit func(unit string) + ConsumeViewerEvent func(v *format.Event, required bool) + ConsumeViewerFrame func(key string, f format.Frame) + Flush func() +} + +// ViewerDataTraceConsumer returns a TraceConsumer that writes to w. The +// startIdx and endIdx are used for splitting large traces. They refer to +// indexes in the traceEvents output array, not the events in the trace input. +func ViewerDataTraceConsumer(w io.Writer, startIdx, endIdx int64) TraceConsumer { + allFrames := make(map[string]format.Frame) + requiredFrames := make(map[string]format.Frame) + enc := json.NewEncoder(w) + written := 0 + index := int64(-1) + + io.WriteString(w, "{") + return TraceConsumer{ + ConsumeTimeUnit: func(unit string) { + io.WriteString(w, `"displayTimeUnit":`) + enc.Encode(unit) + io.WriteString(w, ",") + }, + ConsumeViewerEvent: func(v *format.Event, required bool) { + index++ + if !required && (index < startIdx || index > endIdx) { + // not in the range. Skip! + return + } + WalkStackFrames(allFrames, v.Stack, func(id int) { + s := strconv.Itoa(id) + requiredFrames[s] = allFrames[s] + }) + WalkStackFrames(allFrames, v.EndStack, func(id int) { + s := strconv.Itoa(id) + requiredFrames[s] = allFrames[s] + }) + if written == 0 { + io.WriteString(w, `"traceEvents": [`) + } + if written > 0 { + io.WriteString(w, ",") + } + enc.Encode(v) + // TODO(mknyszek): get rid of the extra \n inserted by enc.Encode. + // Same should be applied to splittingTraceConsumer. + written++ + }, + ConsumeViewerFrame: func(k string, v format.Frame) { + allFrames[k] = v + }, + Flush: func() { + io.WriteString(w, `], "stackFrames":`) + enc.Encode(requiredFrames) + io.WriteString(w, `}`) + }, + } +} + +func SplittingTraceConsumer(max int) (*splitter, TraceConsumer) { + type eventSz struct { + Time float64 + Sz int + Frames []int + } + + var ( + // data.Frames contains only the frames for required events. + data = format.Data{Frames: make(map[string]format.Frame)} + + allFrames = make(map[string]format.Frame) + + sizes []eventSz + cw countingWriter + ) + + s := new(splitter) + + return s, TraceConsumer{ + ConsumeTimeUnit: func(unit string) { + data.TimeUnit = unit + }, + ConsumeViewerEvent: func(v *format.Event, required bool) { + if required { + // Store required events inside data so flush + // can include them in the required part of the + // trace. + data.Events = append(data.Events, v) + WalkStackFrames(allFrames, v.Stack, func(id int) { + s := strconv.Itoa(id) + data.Frames[s] = allFrames[s] + }) + WalkStackFrames(allFrames, v.EndStack, func(id int) { + s := strconv.Itoa(id) + data.Frames[s] = allFrames[s] + }) + return + } + enc := json.NewEncoder(&cw) + enc.Encode(v) + size := eventSz{Time: v.Time, Sz: cw.size + 1} // +1 for ",". + // Add referenced stack frames. Their size is computed + // in flush, where we can dedup across events. + WalkStackFrames(allFrames, v.Stack, func(id int) { + size.Frames = append(size.Frames, id) + }) + WalkStackFrames(allFrames, v.EndStack, func(id int) { + size.Frames = append(size.Frames, id) // This may add duplicates. We'll dedup later. + }) + sizes = append(sizes, size) + cw.size = 0 + }, + ConsumeViewerFrame: func(k string, v format.Frame) { + allFrames[k] = v + }, + Flush: func() { + // Calculate size of the mandatory part of the trace. + // This includes thread names and stack frames for + // required events. + cw.size = 0 + enc := json.NewEncoder(&cw) + enc.Encode(data) + requiredSize := cw.size + + // Then calculate size of each individual event and + // their stack frames, grouping them into ranges. We + // only include stack frames relevant to the events in + // the range to reduce overhead. + + var ( + start = 0 + + eventsSize = 0 + + frames = make(map[string]format.Frame) + framesSize = 0 + ) + for i, ev := range sizes { + eventsSize += ev.Sz + + // Add required stack frames. Note that they + // may already be in the map. + for _, id := range ev.Frames { + s := strconv.Itoa(id) + _, ok := frames[s] + if ok { + continue + } + f := allFrames[s] + frames[s] = f + framesSize += stackFrameEncodedSize(uint(id), f) + } + + total := requiredSize + framesSize + eventsSize + if total < max { + continue + } + + // Reached max size, commit this range and + // start a new range. + startTime := time.Duration(sizes[start].Time * 1000) + endTime := time.Duration(ev.Time * 1000) + s.Ranges = append(s.Ranges, Range{ + Name: fmt.Sprintf("%v-%v", startTime, endTime), + Start: start, + End: i + 1, + StartTime: int64(startTime), + EndTime: int64(endTime), + }) + start = i + 1 + frames = make(map[string]format.Frame) + framesSize = 0 + eventsSize = 0 + } + if len(s.Ranges) <= 1 { + s.Ranges = nil + return + } + + if end := len(sizes) - 1; start < end { + s.Ranges = append(s.Ranges, Range{ + Name: fmt.Sprintf("%v-%v", time.Duration(sizes[start].Time*1000), time.Duration(sizes[end].Time*1000)), + Start: start, + End: end, + StartTime: int64(sizes[start].Time * 1000), + EndTime: int64(sizes[end].Time * 1000), + }) + } + }, + } +} + +type splitter struct { + Ranges []Range +} + +type countingWriter struct { + size int +} + +func (cw *countingWriter) Write(data []byte) (int, error) { + cw.size += len(data) + return len(data), nil +} + +func stackFrameEncodedSize(id uint, f format.Frame) int { + // We want to know the marginal size of traceviewer.Data.Frames for + // each event. Running full JSON encoding of the map for each event is + // far too slow. + // + // Since the format is fixed, we can easily compute the size without + // encoding. + // + // A single entry looks like one of the following: + // + // "1":{"name":"main.main:30"}, + // "10":{"name":"pkg.NewSession:173","parent":9}, + // + // The parent is omitted if 0. The trailing comma is omitted from the + // last entry, but we don't need that much precision. + const ( + baseSize = len(`"`) + len(`":{"name":"`) + len(`"},`) + + // Don't count the trailing quote on the name, as that is + // counted in baseSize. + parentBaseSize = len(`,"parent":`) + ) + + size := baseSize + + size += len(f.Name) + + // Bytes for id (always positive). + for id > 0 { + size += 1 + id /= 10 + } + + if f.Parent > 0 { + size += parentBaseSize + // Bytes for parent (always positive). + for f.Parent > 0 { + size += 1 + f.Parent /= 10 + } + } + + return size +} + +// WalkStackFrames calls fn for id and all of its parent frames from allFrames. +func WalkStackFrames(allFrames map[string]format.Frame, id int, fn func(id int)) { + for id != 0 { + f, ok := allFrames[strconv.Itoa(id)] + if !ok { + break + } + fn(id) + id = f.Parent + } +} + +type Mode int + +const ( + ModeGoroutineOriented Mode = 1 << iota + ModeTaskOriented + ModeThreadOriented // Mutually exclusive with ModeGoroutineOriented. +) + +// NewEmitter returns a new Emitter that writes to c. The rangeStart and +// rangeEnd args are used for splitting large traces. +func NewEmitter(c TraceConsumer, rangeStart, rangeEnd time.Duration) *Emitter { + c.ConsumeTimeUnit("ns") + + return &Emitter{ + c: c, + rangeStart: rangeStart, + rangeEnd: rangeEnd, + frameTree: frameNode{children: make(map[uint64]frameNode)}, + resources: make(map[uint64]string), + tasks: make(map[uint64]task), + } +} + +type Emitter struct { + c TraceConsumer + rangeStart time.Duration + rangeEnd time.Duration + + heapStats, prevHeapStats heapStats + gstates, prevGstates [gStateCount]int64 + threadStats, prevThreadStats [threadStateCount]int64 + gomaxprocs uint64 + frameTree frameNode + frameSeq int + arrowSeq uint64 + filter func(uint64) bool + resourceType string + resources map[uint64]string + focusResource uint64 + tasks map[uint64]task + asyncSliceSeq uint64 +} + +type task struct { + name string + sortIndex int +} + +func (e *Emitter) Gomaxprocs(v uint64) { + if v > e.gomaxprocs { + e.gomaxprocs = v + } +} + +func (e *Emitter) Resource(id uint64, name string) { + if e.filter != nil && !e.filter(id) { + return + } + e.resources[id] = name +} + +func (e *Emitter) SetResourceType(name string) { + e.resourceType = name +} + +func (e *Emitter) SetResourceFilter(filter func(uint64) bool) { + e.filter = filter +} + +func (e *Emitter) Task(id uint64, name string, sortIndex int) { + e.tasks[id] = task{name, sortIndex} +} + +func (e *Emitter) Slice(s SliceEvent) { + if e.filter != nil && !e.filter(s.Resource) { + return + } + e.slice(s, format.ProcsSection, "") +} + +func (e *Emitter) TaskSlice(s SliceEvent) { + e.slice(s, format.TasksSection, pickTaskColor(s.Resource)) +} + +func (e *Emitter) slice(s SliceEvent, sectionID uint64, cname string) { + if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) { + return + } + e.OptionalEvent(&format.Event{ + Name: s.Name, + Phase: "X", + Time: viewerTime(s.Ts), + Dur: viewerTime(s.Dur), + PID: sectionID, + TID: s.Resource, + Stack: s.Stack, + EndStack: s.EndStack, + Arg: s.Arg, + Cname: cname, + }) +} + +type SliceEvent struct { + Name string + Ts time.Duration + Dur time.Duration + Resource uint64 + Stack int + EndStack int + Arg any +} + +func (e *Emitter) AsyncSlice(s AsyncSliceEvent) { + if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) { + return + } + if e.filter != nil && !e.filter(s.Resource) { + return + } + cname := "" + if s.TaskColorIndex != 0 { + cname = pickTaskColor(s.TaskColorIndex) + } + e.asyncSliceSeq++ + e.OptionalEvent(&format.Event{ + Category: s.Category, + Name: s.Name, + Phase: "b", + Time: viewerTime(s.Ts), + TID: s.Resource, + ID: e.asyncSliceSeq, + Scope: s.Scope, + Stack: s.Stack, + Cname: cname, + }) + e.OptionalEvent(&format.Event{ + Category: s.Category, + Name: s.Name, + Phase: "e", + Time: viewerTime(s.Ts + s.Dur), + TID: s.Resource, + ID: e.asyncSliceSeq, + Scope: s.Scope, + Stack: s.EndStack, + Arg: s.Arg, + Cname: cname, + }) +} + +type AsyncSliceEvent struct { + SliceEvent + Category string + Scope string + TaskColorIndex uint64 // Take on the same color as the task with this ID. +} + +func (e *Emitter) Instant(i InstantEvent) { + if !e.tsWithinRange(i.Ts) { + return + } + if e.filter != nil && !e.filter(i.Resource) { + return + } + cname := "" + e.OptionalEvent(&format.Event{ + Name: i.Name, + Category: i.Category, + Phase: "I", + Scope: "t", + Time: viewerTime(i.Ts), + PID: format.ProcsSection, + TID: i.Resource, + Stack: i.Stack, + Cname: cname, + Arg: i.Arg, + }) +} + +type InstantEvent struct { + Ts time.Duration + Name string + Category string + Resource uint64 + Stack int + Arg any +} + +func (e *Emitter) Arrow(a ArrowEvent) { + if e.filter != nil && (!e.filter(a.FromResource) || !e.filter(a.ToResource)) { + return + } + e.arrow(a, format.ProcsSection) +} + +func (e *Emitter) TaskArrow(a ArrowEvent) { + e.arrow(a, format.TasksSection) +} + +func (e *Emitter) arrow(a ArrowEvent, sectionID uint64) { + if !e.tsWithinRange(a.Start) || !e.tsWithinRange(a.End) { + return + } + e.arrowSeq++ + e.OptionalEvent(&format.Event{ + Name: a.Name, + Phase: "s", + TID: a.FromResource, + PID: sectionID, + ID: e.arrowSeq, + Time: viewerTime(a.Start), + Stack: a.FromStack, + }) + e.OptionalEvent(&format.Event{ + Name: a.Name, + Phase: "t", + TID: a.ToResource, + PID: sectionID, + ID: e.arrowSeq, + Time: viewerTime(a.End), + }) +} + +type ArrowEvent struct { + Name string + Start time.Duration + End time.Duration + FromResource uint64 + FromStack int + ToResource uint64 +} + +func (e *Emitter) Event(ev *format.Event) { + e.c.ConsumeViewerEvent(ev, true) +} + +func (e *Emitter) HeapAlloc(ts time.Duration, v uint64) { + e.heapStats.heapAlloc = v + e.emitHeapCounters(ts) +} + +func (e *Emitter) Focus(id uint64) { + e.focusResource = id +} + +func (e *Emitter) GoroutineTransition(ts time.Duration, from, to GState) { + e.gstates[from]-- + e.gstates[to]++ + if e.prevGstates == e.gstates { + return + } + if e.tsWithinRange(ts) { + e.OptionalEvent(&format.Event{ + Name: "Goroutines", + Phase: "C", + Time: viewerTime(ts), + PID: 1, + Arg: &format.GoroutineCountersArg{ + Running: uint64(e.gstates[GRunning]), + Runnable: uint64(e.gstates[GRunnable]), + GCWaiting: uint64(e.gstates[GWaitingGC]), + }, + }) + } + e.prevGstates = e.gstates +} + +func (e *Emitter) IncThreadStateCount(ts time.Duration, state ThreadState, delta int64) { + e.threadStats[state] += delta + if e.prevThreadStats == e.threadStats { + return + } + if e.tsWithinRange(ts) { + e.OptionalEvent(&format.Event{ + Name: "Threads", + Phase: "C", + Time: viewerTime(ts), + PID: 1, + Arg: &format.ThreadCountersArg{ + Running: int64(e.threadStats[ThreadStateRunning]), + InSyscall: int64(e.threadStats[ThreadStateInSyscall]), + // TODO(mknyszek): Why is InSyscallRuntime not included here? + }, + }) + } + e.prevThreadStats = e.threadStats +} + +func (e *Emitter) HeapGoal(ts time.Duration, v uint64) { + // This cutoff at 1 PiB is a Workaround for https://github.com/golang/go/issues/63864. + // + // TODO(mknyszek): Remove this once the problem has been fixed. + const PB = 1 << 50 + if v > PB { + v = 0 + } + e.heapStats.nextGC = v + e.emitHeapCounters(ts) +} + +func (e *Emitter) emitHeapCounters(ts time.Duration) { + if e.prevHeapStats == e.heapStats { + return + } + diff := uint64(0) + if e.heapStats.nextGC > e.heapStats.heapAlloc { + diff = e.heapStats.nextGC - e.heapStats.heapAlloc + } + if e.tsWithinRange(ts) { + e.OptionalEvent(&format.Event{ + Name: "Heap", + Phase: "C", + Time: viewerTime(ts), + PID: 1, + Arg: &format.HeapCountersArg{Allocated: e.heapStats.heapAlloc, NextGC: diff}, + }) + } + e.prevHeapStats = e.heapStats +} + +// Err returns an error if the emitter is in an invalid state. +func (e *Emitter) Err() error { + if e.gstates[GRunnable] < 0 || e.gstates[GRunning] < 0 || e.threadStats[ThreadStateInSyscall] < 0 || e.threadStats[ThreadStateInSyscallRuntime] < 0 { + return fmt.Errorf( + "runnable=%d running=%d insyscall=%d insyscallRuntime=%d", + e.gstates[GRunnable], + e.gstates[GRunning], + e.threadStats[ThreadStateInSyscall], + e.threadStats[ThreadStateInSyscallRuntime], + ) + } + return nil +} + +func (e *Emitter) tsWithinRange(ts time.Duration) bool { + return e.rangeStart <= ts && ts <= e.rangeEnd +} + +// OptionalEvent emits ev if it's within the time range of the consumer, i.e. +// the selected trace split range. +func (e *Emitter) OptionalEvent(ev *format.Event) { + e.c.ConsumeViewerEvent(ev, false) +} + +func (e *Emitter) Flush() { + e.processMeta(format.StatsSection, "STATS", 0) + + if len(e.tasks) != 0 { + e.processMeta(format.TasksSection, "TASKS", 1) + } + for id, task := range e.tasks { + e.threadMeta(format.TasksSection, id, task.name, task.sortIndex) + } + + e.processMeta(format.ProcsSection, e.resourceType, 2) + + e.threadMeta(format.ProcsSection, GCP, "GC", -6) + e.threadMeta(format.ProcsSection, NetpollP, "Network", -5) + e.threadMeta(format.ProcsSection, TimerP, "Timers", -4) + e.threadMeta(format.ProcsSection, SyscallP, "Syscalls", -3) + + for id, name := range e.resources { + priority := int(id) + if e.focusResource != 0 && id == e.focusResource { + // Put the focus goroutine on top. + priority = -2 + } + e.threadMeta(format.ProcsSection, id, name, priority) + } + + e.c.Flush() +} + +func (e *Emitter) threadMeta(sectionID, tid uint64, name string, priority int) { + e.Event(&format.Event{ + Name: "thread_name", + Phase: "M", + PID: sectionID, + TID: tid, + Arg: &format.NameArg{Name: name}, + }) + e.Event(&format.Event{ + Name: "thread_sort_index", + Phase: "M", + PID: sectionID, + TID: tid, + Arg: &format.SortIndexArg{Index: priority}, + }) +} + +func (e *Emitter) processMeta(sectionID uint64, name string, priority int) { + e.Event(&format.Event{ + Name: "process_name", + Phase: "M", + PID: sectionID, + Arg: &format.NameArg{Name: name}, + }) + e.Event(&format.Event{ + Name: "process_sort_index", + Phase: "M", + PID: sectionID, + Arg: &format.SortIndexArg{Index: priority}, + }) +} + +// Stack emits the given frames and returns a unique id for the stack. No +// pointers to the given data are being retained beyond the call to Stack. +func (e *Emitter) Stack(stk []trace.StackFrame) int { + return e.buildBranch(e.frameTree, stk) +} + +// buildBranch builds one branch in the prefix tree rooted at ctx.frameTree. +func (e *Emitter) buildBranch(parent frameNode, stk []trace.StackFrame) int { + if len(stk) == 0 { + return parent.id + } + last := len(stk) - 1 + frame := stk[last] + stk = stk[:last] + + node, ok := parent.children[frame.PC] + if !ok { + e.frameSeq++ + node.id = e.frameSeq + node.children = make(map[uint64]frameNode) + parent.children[frame.PC] = node + e.c.ConsumeViewerFrame(strconv.Itoa(node.id), format.Frame{Name: fmt.Sprintf("%v:%v", frame.Func, frame.Line), Parent: parent.id}) + } + return e.buildBranch(node, stk) +} + +type heapStats struct { + heapAlloc uint64 + nextGC uint64 +} + +func viewerTime(t time.Duration) float64 { + return float64(t) / float64(time.Microsecond) +} + +type GState int + +const ( + GDead GState = iota + GRunnable + GRunning + GWaiting + GWaitingGC + + gStateCount +) + +type ThreadState int + +const ( + ThreadStateInSyscall ThreadState = iota + ThreadStateInSyscallRuntime + ThreadStateRunning + + threadStateCount +) + +type frameNode struct { + id int + children map[uint64]frameNode +} + +// Mapping from more reasonable color names to the reserved color names in +// https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html#L50 +// The chrome trace viewer allows only those as cname values. +const ( + colorLightMauve = "thread_state_uninterruptible" // 182, 125, 143 + colorOrange = "thread_state_iowait" // 255, 140, 0 + colorSeafoamGreen = "thread_state_running" // 126, 200, 148 + colorVistaBlue = "thread_state_runnable" // 133, 160, 210 + colorTan = "thread_state_unknown" // 199, 155, 125 + colorIrisBlue = "background_memory_dump" // 0, 180, 180 + colorMidnightBlue = "light_memory_dump" // 0, 0, 180 + colorDeepMagenta = "detailed_memory_dump" // 180, 0, 180 + colorBlue = "vsync_highlight_color" // 0, 0, 255 + colorGrey = "generic_work" // 125, 125, 125 + colorGreen = "good" // 0, 125, 0 + colorDarkGoldenrod = "bad" // 180, 125, 0 + colorPeach = "terrible" // 180, 0, 0 + colorBlack = "black" // 0, 0, 0 + colorLightGrey = "grey" // 221, 221, 221 + colorWhite = "white" // 255, 255, 255 + colorYellow = "yellow" // 255, 255, 0 + colorOlive = "olive" // 100, 100, 0 + colorCornflowerBlue = "rail_response" // 67, 135, 253 + colorSunsetOrange = "rail_animation" // 244, 74, 63 + colorTangerine = "rail_idle" // 238, 142, 0 + colorShamrockGreen = "rail_load" // 13, 168, 97 + colorGreenishYellow = "startup" // 230, 230, 0 + colorDarkGrey = "heap_dump_stack_frame" // 128, 128, 128 + colorTawny = "heap_dump_child_node_arrow" // 204, 102, 0 + colorLemon = "cq_build_running" // 255, 255, 119 + colorLime = "cq_build_passed" // 153, 238, 102 + colorPink = "cq_build_failed" // 238, 136, 136 + colorSilver = "cq_build_abandoned" // 187, 187, 187 + colorManzGreen = "cq_build_attempt_runnig" // 222, 222, 75 + colorKellyGreen = "cq_build_attempt_passed" // 108, 218, 35 + colorAnotherGrey = "cq_build_attempt_failed" // 187, 187, 187 +) + +var colorForTask = []string{ + colorLightMauve, + colorOrange, + colorSeafoamGreen, + colorVistaBlue, + colorTan, + colorMidnightBlue, + colorIrisBlue, + colorDeepMagenta, + colorGreen, + colorDarkGoldenrod, + colorPeach, + colorOlive, + colorCornflowerBlue, + colorSunsetOrange, + colorTangerine, + colorShamrockGreen, + colorTawny, + colorLemon, + colorLime, + colorPink, + colorSilver, + colorManzGreen, + colorKellyGreen, +} + +func pickTaskColor(id uint64) string { + idx := id % uint64(len(colorForTask)) + return colorForTask[idx] +} diff --git a/go/src/internal/trace/traceviewer/fakep.go b/go/src/internal/trace/traceviewer/fakep.go new file mode 100644 index 0000000000000000000000000000000000000000..655938b213bc361855960463709f43c139767cef --- /dev/null +++ b/go/src/internal/trace/traceviewer/fakep.go @@ -0,0 +1,15 @@ +// 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 traceviewer + +const ( + // Special P identifiers: + FakeP = 1000000 + iota + TimerP // depicts timer unblocks + NetpollP // depicts network unblocks + SyscallP // depicts returns from syscalls + GCP // depicts GC state + ProfileP // depicts recording of CPU profile samples +) diff --git a/go/src/internal/trace/traceviewer/format/format.go b/go/src/internal/trace/traceviewer/format/format.go new file mode 100644 index 0000000000000000000000000000000000000000..2ec4dd4bdc1537ea5046af3a8af3444f726b05f1 --- /dev/null +++ b/go/src/internal/trace/traceviewer/format/format.go @@ -0,0 +1,80 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package traceviewer provides definitions of the JSON data structures +// used by the Chrome trace viewer. +// +// The official description of the format is in this file: +// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview +// +// Note: This can't be part of the parent traceviewer package as that would +// throw. go_bootstrap cannot depend on the cgo version of package net in ./make.bash. +package format + +type Data struct { + Events []*Event `json:"traceEvents"` + Frames map[string]Frame `json:"stackFrames"` + TimeUnit string `json:"displayTimeUnit"` +} + +type Event struct { + Name string `json:"name,omitempty"` + Phase string `json:"ph"` + Scope string `json:"s,omitempty"` + Time float64 `json:"ts"` + Dur float64 `json:"dur,omitempty"` + PID uint64 `json:"pid"` + TID uint64 `json:"tid"` + ID uint64 `json:"id,omitempty"` + BindPoint string `json:"bp,omitempty"` + Stack int `json:"sf,omitempty"` + EndStack int `json:"esf,omitempty"` + Arg any `json:"args,omitempty"` + Cname string `json:"cname,omitempty"` + Category string `json:"cat,omitempty"` +} + +type Frame struct { + Name string `json:"name"` + Parent int `json:"parent,omitempty"` +} + +type NameArg struct { + Name string `json:"name"` +} + +type BlockedArg struct { + Blocked string `json:"blocked"` +} + +type SortIndexArg struct { + Index int `json:"sort_index"` +} + +type HeapCountersArg struct { + Allocated uint64 + NextGC uint64 +} + +const ( + ProcsSection = 0 // where Goroutines or per-P timelines are presented. + StatsSection = 1 // where counters are presented. + TasksSection = 2 // where Task hierarchy & timeline is presented. +) + +type GoroutineCountersArg struct { + Running uint64 + Runnable uint64 + GCWaiting uint64 +} + +type ThreadCountersArg struct { + Running int64 + InSyscall int64 +} + +type SchedCtxArg struct { + ThreadID uint64 `json:"thread,omitempty"` + ProcID uint64 `json:"proc,omitempty"` +} diff --git a/go/src/internal/trace/traceviewer/histogram.go b/go/src/internal/trace/traceviewer/histogram.go new file mode 100644 index 0000000000000000000000000000000000000000..d4c8749dc9a87bc16ec7c1cd6e43c69292dd0d7b --- /dev/null +++ b/go/src/internal/trace/traceviewer/histogram.go @@ -0,0 +1,86 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package traceviewer + +import ( + "fmt" + "html/template" + "math" + "strings" + "time" +) + +// TimeHistogram is an high-dynamic-range histogram for durations. +type TimeHistogram struct { + Count int + Buckets []int + MinBucket, MaxBucket int +} + +// Five buckets for every power of 10. +var logDiv = math.Log(math.Pow(10, 1.0/5)) + +// Add adds a single sample to the histogram. +func (h *TimeHistogram) Add(d time.Duration) { + var bucket int + if d > 0 { + bucket = int(math.Log(float64(d)) / logDiv) + } + if len(h.Buckets) <= bucket { + h.Buckets = append(h.Buckets, make([]int, bucket-len(h.Buckets)+1)...) + h.Buckets = h.Buckets[:cap(h.Buckets)] + } + h.Buckets[bucket]++ + if bucket < h.MinBucket || h.MaxBucket == 0 { + h.MinBucket = bucket + } + if bucket > h.MaxBucket { + h.MaxBucket = bucket + } + h.Count++ +} + +// BucketMin returns the minimum duration value for a provided bucket. +func (h *TimeHistogram) BucketMin(bucket int) time.Duration { + return time.Duration(math.Exp(float64(bucket) * logDiv)) +} + +// ToHTML renders the histogram as HTML. +func (h *TimeHistogram) ToHTML(urlmaker func(min, max time.Duration) string) template.HTML { + if h == nil || h.Count == 0 { + return template.HTML("") + } + + const barWidth = 400 + + maxCount := 0 + for _, count := range h.Buckets { + if count > maxCount { + maxCount = count + } + } + + w := new(strings.Builder) + fmt.Fprintf(w, ``) + for i := h.MinBucket; i <= h.MaxBucket; i++ { + // Tick label. + if h.Buckets[i] > 0 { + fmt.Fprintf(w, ``, urlmaker(h.BucketMin(i), h.BucketMin(i+1)), h.BucketMin(i)) + } else { + fmt.Fprintf(w, ``, h.BucketMin(i)) + } + // Bucket bar. + width := h.Buckets[i] * barWidth / maxCount + fmt.Fprintf(w, ``, width) + // Bucket count. + fmt.Fprintf(w, ``, h.Buckets[i]) + fmt.Fprintf(w, "\n") + + } + // Final tick label. + fmt.Fprintf(w, ``, h.BucketMin(h.MaxBucket+1)) + fmt.Fprintf(w, `
%s
%s
 
%d
%s
`) + return template.HTML(w.String()) +} diff --git a/go/src/internal/trace/traceviewer/http.go b/go/src/internal/trace/traceviewer/http.go new file mode 100644 index 0000000000000000000000000000000000000000..5258db05d8ab1763ea87eaa09b9b68ea39bf3ab4 --- /dev/null +++ b/go/src/internal/trace/traceviewer/http.go @@ -0,0 +1,422 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package traceviewer + +import ( + "embed" + "fmt" + "html/template" + "net/http" + "strings" +) + +func MainHandler(views []View) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if err := templMain.Execute(w, views); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + }) +} + +const CommonStyle = ` +/* See https://github.com/golang/pkgsite/blob/master/static/shared/typography/typography.css */ +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji'; + font-size: 1rem; + line-height: normal; + max-width: 9in; + margin: 1em; +} +h1 { font-size: 1.5rem; } +h2 { font-size: 1.375rem; } +h1,h2 { + font-weight: 600; + line-height: 1.25em; + word-break: break-word; +} +p { color: grey85; font-size:85%; } +code, +pre, +textarea.code { + font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace; + font-size: 0.875rem; + line-height: 1.5em; +} + +pre, +textarea.code { + background-color: var(--color-background-accented); + border: var(--border); + border-radius: var(--border-radius); + color: var(--color-text); + overflow-x: auto; + padding: 0.625rem; + tab-size: 4; + white-space: pre; +} +` + +var templMain = template.Must(template.New("").Parse(` + + + +

cmd/trace: the Go trace event viewer

+

+ This web server provides various visualizations of an event log gathered during + the execution of a Go program that uses the runtime/trace package. +

+ +

Event timelines for running goroutines

+{{range $i, $view := $}} +{{if $view.Ranges}} +{{if eq $i 0}} +

+ Large traces are split into multiple sections of equal data size + (not duration) to avoid overwhelming the visualizer. +

+{{end}} + +{{else}} + +{{end}} +{{end}} +

+ This view displays a series of timelines for a type of resource. + The "by proc" view consists of a timeline for each of the GOMAXPROCS + logical processors, showing which goroutine (if any) was running on that + logical processor at each moment. + The "by thread" view (if available) consists of a similar timeline for each + OS thread. + + Each goroutine has an identifying number (e.g. G123), main function, + and color. + + A colored bar represents an uninterrupted span of execution. + + Execution of a goroutine may migrate from one logical processor to another, + causing a single colored bar to be horizontally continuous but + vertically displaced. +

+

+ Clicking on a span reveals information about it, such as its + duration, its causal predecessors and successors, and the stack trace + at the final moment when it yielded the logical processor, for example + because it made a system call or tried to acquire a mutex. + + Directly underneath each bar, a smaller bar or more commonly a fine + vertical line indicates an event occurring during its execution. + Some of these are related to garbage collection; most indicate that + a goroutine yielded its logical processor but then immediately resumed execution + on the same logical processor. Clicking on the event displays the stack trace + at the moment it occurred. +

+

+ The causal relationships between spans of goroutine execution + can be displayed by clicking the Flow Events button at the top. +

+

+ At the top ("STATS"), there are three additional timelines that + display statistical information. + + "Goroutines" is a time series of the count of existing goroutines; + clicking on it displays their breakdown by state at that moment: + running, runnable, or waiting. + + "Heap" is a time series of the amount of heap memory allocated (in orange) + and (in green) the allocation limit at which the next GC cycle will begin. + + "Threads" shows the number of kernel threads in existence: there is + always one kernel thread per logical processor, and additional threads + are created for calls to non-Go code such as a system call or a + function written in C. +

+

+ Above the event trace for the first logical processor are + traces for various runtime-internal events. + + The "GC" bar shows when the garbage collector is running, and in which stage. + Garbage collection may temporarily affect all the logical processors + and the other metrics. + + The "Network", "Timers", and "Syscalls" traces indicate events in + the runtime that cause goroutines to wake up. +

+

+ The visualization allows you to navigate events at scales ranging from several + seconds to a handful of nanoseconds. + + Consult the documentation for the Chromium Trace Event Profiling Tool + for help navigating the view. +

+ + +

+ This view displays information about each set of goroutines that + shares the same main function. + + Clicking on a main function shows links to the four types of + blocking profile (see below) applied to that subset of goroutines. + + It also shows a table of specific goroutine instances, with various + execution statistics and a link to the event timeline for each one. + + The timeline displays only the selected goroutine and any others it + interacts with via block/unblock events. (The timeline is + goroutine-oriented rather than logical processor-oriented.) +

+ +

Profiles

+

+ Each link below displays a global profile in zoomable graph form as + produced by pprof's "web" command. + + In addition there is a link to download the profile for offline + analysis with pprof. + + All four profiles represent causes of delay that prevent a goroutine + from running on a logical processor: because it was waiting for the network, + for a synchronization operation on a mutex or channel, for a system call, + or for a logical processor to become available. +

+ + +

User-defined tasks and regions

+

+ The trace API allows a target program to annotate a region of code + within a goroutine, such as a key function, so that its performance + can be analyzed. + + Log events may be + associated with a region to record progress and relevant values. + + The API also allows annotation of higher-level + tasks, + which may involve work across many goroutines. +

+

+ The links below display, for each region and task, a histogram of its execution times. + + Each histogram bucket contains a sample trace that records the + sequence of events such as goroutine creations, log events, and + subregion start/end times. + + For each task, you can click through to a logical-processor or + goroutine-oriented view showing the tasks and regions on the + timeline. + + Such information may help uncover which steps in a region are + unexpectedly slow, or reveal relationships between the data values + logged in a request and its running time. +

+ + +

Garbage collection metrics

+ +

+ This chart indicates the maximum GC pause time (the largest x value + for which y is zero), and more generally, the fraction of time that + the processors are available to application goroutines ("mutators"), + for any time window of a specified size, in the worst case. +

+ + +`)) + +type View struct { + Type ViewType + Ranges []Range +} + +type ViewType string + +const ( + ViewProc ViewType = "proc" + ViewThread ViewType = "thread" +) + +func (v View) URL(rangeIdx int) string { + if rangeIdx < 0 { + return fmt.Sprintf("/trace?view=%s", v.Type) + } + return v.Ranges[rangeIdx].URL(v.Type) +} + +type Range struct { + Name string + Start int + End int + StartTime int64 + EndTime int64 +} + +func (r Range) URL(viewType ViewType) string { + return fmt.Sprintf("/trace?view=%s&start=%d&end=%d", viewType, r.Start, r.End) +} + +func TraceHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + html := strings.ReplaceAll(templTrace, "{{PARAMS}}", r.Form.Encode()) + w.Write([]byte(html)) + }) +} + +// https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962/tracing/docs/embedding-trace-viewer.md +// This is almost verbatim copy of https://chromium-review.googlesource.com/c/catapult/+/2062938/2/tracing/bin/index.html +var templTrace = ` + + + + + + + + + + + + + +` + +//go:embed static/trace_viewer_full.html static/webcomponents.min.js +var staticContent embed.FS + +func StaticHandler() http.Handler { + return http.FileServer(http.FS(staticContent)) +} diff --git a/go/src/internal/trace/traceviewer/mmu.go b/go/src/internal/trace/traceviewer/mmu.go new file mode 100644 index 0000000000000000000000000000000000000000..190ce5afcad6e1dad688ff1e36072caffdd681fd --- /dev/null +++ b/go/src/internal/trace/traceviewer/mmu.go @@ -0,0 +1,414 @@ +// 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. + +// Minimum mutator utilization (MMU) graphing. + +// TODO: +// +// In worst window list, show break-down of GC utilization sources +// (STW, assist, etc). Probably requires a different MutatorUtil +// representation. +// +// When a window size is selected, show a second plot of the mutator +// utilization distribution for that window size. +// +// Render plot progressively so rough outline is visible quickly even +// for very complex MUTs. Start by computing just a few window sizes +// and then add more window sizes. +// +// Consider using sampling to compute an approximate MUT. This would +// work by sampling the mutator utilization at randomly selected +// points in time in the trace to build an empirical distribution. We +// could potentially put confidence intervals on these estimates and +// render this progressively as we refine the distributions. + +package traceviewer + +import ( + "encoding/json" + "fmt" + "internal/trace" + "log" + "math" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +type MutatorUtilFunc func(trace.UtilFlags) ([][]trace.MutatorUtil, error) + +func MMUHandlerFunc(ranges []Range, f MutatorUtilFunc) http.HandlerFunc { + mmu := &mmu{ + cache: make(map[trace.UtilFlags]*mmuCacheEntry), + f: f, + ranges: ranges, + } + return func(w http.ResponseWriter, r *http.Request) { + switch r.FormValue("mode") { + case "plot": + mmu.HandlePlot(w, r) + return + case "details": + mmu.HandleDetails(w, r) + return + } + http.ServeContent(w, r, "", time.Time{}, strings.NewReader(templMMU)) + } +} + +var utilFlagNames = map[string]trace.UtilFlags{ + "perProc": trace.UtilPerProc, + "stw": trace.UtilSTW, + "background": trace.UtilBackground, + "assist": trace.UtilAssist, + "sweep": trace.UtilSweep, +} + +func requestUtilFlags(r *http.Request) trace.UtilFlags { + var flags trace.UtilFlags + for flagStr := range strings.SplitSeq(r.FormValue("flags"), "|") { + flags |= utilFlagNames[flagStr] + } + return flags +} + +type mmuCacheEntry struct { + init sync.Once + util [][]trace.MutatorUtil + mmuCurve *trace.MMUCurve + err error +} + +type mmu struct { + mu sync.Mutex + cache map[trace.UtilFlags]*mmuCacheEntry + f MutatorUtilFunc + ranges []Range +} + +func (m *mmu) get(flags trace.UtilFlags) ([][]trace.MutatorUtil, *trace.MMUCurve, error) { + m.mu.Lock() + entry := m.cache[flags] + if entry == nil { + entry = new(mmuCacheEntry) + m.cache[flags] = entry + } + m.mu.Unlock() + + entry.init.Do(func() { + util, err := m.f(flags) + if err != nil { + entry.err = err + } else { + entry.util = util + entry.mmuCurve = trace.NewMMUCurve(util) + } + }) + return entry.util, entry.mmuCurve, entry.err +} + +// HandlePlot serves the JSON data for the MMU plot. +func (m *mmu) HandlePlot(w http.ResponseWriter, r *http.Request) { + mu, mmuCurve, err := m.get(requestUtilFlags(r)) + if err != nil { + http.Error(w, fmt.Sprintf("failed to produce MMU data: %v", err), http.StatusInternalServerError) + return + } + + var quantiles []float64 + for flagStr := range strings.SplitSeq(r.FormValue("flags"), "|") { + if flagStr == "mut" { + quantiles = []float64{0, 1 - .999, 1 - .99, 1 - .95} + break + } + } + + // Find a nice starting point for the plot. + xMin := time.Second + for xMin > 1 { + if mmu := mmuCurve.MMU(xMin); mmu < 0.0001 { + break + } + xMin /= 1000 + } + // Cover six orders of magnitude. + xMax := xMin * 1e6 + // But no more than the length of the trace. + minEvent, maxEvent := mu[0][0].Time, mu[0][len(mu[0])-1].Time + for _, mu1 := range mu[1:] { + if mu1[0].Time < minEvent { + minEvent = mu1[0].Time + } + if mu1[len(mu1)-1].Time > maxEvent { + maxEvent = mu1[len(mu1)-1].Time + } + } + if maxMax := time.Duration(maxEvent - minEvent); xMax > maxMax { + xMax = maxMax + } + // Compute MMU curve. + logMin, logMax := math.Log(float64(xMin)), math.Log(float64(xMax)) + const samples = 100 + plot := make([][]float64, samples) + for i := 0; i < samples; i++ { + window := time.Duration(math.Exp(float64(i)/(samples-1)*(logMax-logMin) + logMin)) + if quantiles == nil { + plot[i] = make([]float64, 2) + plot[i][1] = mmuCurve.MMU(window) + } else { + plot[i] = make([]float64, 1+len(quantiles)) + copy(plot[i][1:], mmuCurve.MUD(window, quantiles)) + } + plot[i][0] = float64(window) + } + + // Create JSON response. + err = json.NewEncoder(w).Encode(map[string]any{"xMin": int64(xMin), "xMax": int64(xMax), "quantiles": quantiles, "curve": plot}) + if err != nil { + log.Printf("failed to serialize response: %v", err) + return + } +} + +var templMMU = ` + + + + + + + + + +
+
Loading plot...
+
+

+ View
+ + ?Consider whole system utilization. For example, if one of four procs is available to the mutator, mutator utilization will be 0.25. This is the standard definition of an MMU.
+ + ?Consider per-goroutine utilization. When even one goroutine is interrupted by GC, mutator utilization is 0.
+

+

+ Include
+ + ?Stop-the-world stops all goroutines simultaneously.
+ + ?Background workers are GC-specific goroutines. 25% of the CPU is dedicated to background workers during GC.
+ + ?Mark assists are performed by allocation to prevent the mutator from outpacing GC.
+ + ?Sweep reclaims unused memory between GCs. (Enabling this may be very slow.).
+

+

+ Display
+ + ?Display percentile mutator utilization in addition to minimum. E.g., p99 MU drops the worst 1% of windows.
+

+
+
+
Select a point for details.
+ + +` + +// HandleDetails serves details of an MMU graph at a particular window. +func (m *mmu) HandleDetails(w http.ResponseWriter, r *http.Request) { + _, mmuCurve, err := m.get(requestUtilFlags(r)) + if err != nil { + http.Error(w, fmt.Sprintf("failed to produce MMU data: %v", err), http.StatusInternalServerError) + return + } + + windowStr := r.FormValue("window") + window, err := strconv.ParseUint(windowStr, 10, 64) + if err != nil { + http.Error(w, fmt.Sprintf("failed to parse window parameter %q: %v", windowStr, err), http.StatusBadRequest) + return + } + worst := mmuCurve.Examples(time.Duration(window), 10) + + // Construct a link for each window. + var links []linkedUtilWindow + for _, ui := range worst { + links = append(links, m.newLinkedUtilWindow(ui, time.Duration(window))) + } + + err = json.NewEncoder(w).Encode(links) + if err != nil { + log.Printf("failed to serialize trace: %v", err) + return + } +} + +type linkedUtilWindow struct { + trace.UtilWindow + URL string +} + +func (m *mmu) newLinkedUtilWindow(ui trace.UtilWindow, window time.Duration) linkedUtilWindow { + // Find the range containing this window. + var r Range + for _, r = range m.ranges { + if r.EndTime > ui.Time { + break + } + } + return linkedUtilWindow{ui, fmt.Sprintf("%s#%v:%v", r.URL(ViewProc), float64(ui.Time)/1e6, float64(ui.Time+int64(window))/1e6)} +} diff --git a/go/src/internal/trace/traceviewer/pprof.go b/go/src/internal/trace/traceviewer/pprof.go new file mode 100644 index 0000000000000000000000000000000000000000..141b2687b781acda195df2f46d071e9507d01eba --- /dev/null +++ b/go/src/internal/trace/traceviewer/pprof.go @@ -0,0 +1,150 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Serving of pprof-like profiles. + +package traceviewer + +import ( + "bufio" + "fmt" + "internal/profile" + "internal/trace" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "time" +) + +type ProfileFunc func(r *http.Request) ([]ProfileRecord, error) + +// SVGProfileHandlerFunc serves pprof-like profile generated by prof as svg. +func SVGProfileHandlerFunc(f ProfileFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.FormValue("raw") != "" { + w.Header().Set("Content-Type", "application/octet-stream") + + failf := func(s string, args ...any) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Header().Set("X-Go-Pprof", "1") + http.Error(w, fmt.Sprintf(s, args...), http.StatusInternalServerError) + } + records, err := f(r) + if err != nil { + failf("failed to get records: %v", err) + return + } + if err := BuildProfile(records).Write(w); err != nil { + failf("failed to write profile: %v", err) + return + } + return + } + + blockf, err := os.CreateTemp("", "block") + if err != nil { + http.Error(w, fmt.Sprintf("failed to create temp file: %v", err), http.StatusInternalServerError) + return + } + defer func() { + blockf.Close() + os.Remove(blockf.Name()) + }() + records, err := f(r) + if err != nil { + http.Error(w, fmt.Sprintf("failed to generate profile: %v", err), http.StatusInternalServerError) + } + blockb := bufio.NewWriter(blockf) + if err := BuildProfile(records).Write(blockb); err != nil { + http.Error(w, fmt.Sprintf("failed to write profile: %v", err), http.StatusInternalServerError) + return + } + if err := blockb.Flush(); err != nil { + http.Error(w, fmt.Sprintf("failed to flush temp file: %v", err), http.StatusInternalServerError) + return + } + if err := blockf.Close(); err != nil { + http.Error(w, fmt.Sprintf("failed to close temp file: %v", err), http.StatusInternalServerError) + return + } + svgFilename := blockf.Name() + ".svg" + if output, err := exec.Command(goCmd(), "tool", "pprof", "-svg", "-output", svgFilename, blockf.Name()).CombinedOutput(); err != nil { + http.Error(w, fmt.Sprintf("failed to execute go tool pprof: %v\n%s", err, output), http.StatusInternalServerError) + return + } + defer os.Remove(svgFilename) + w.Header().Set("Content-Type", "image/svg+xml") + http.ServeFile(w, r, svgFilename) + } +} + +type ProfileRecord struct { + Stack []trace.StackFrame + Count uint64 + Time time.Duration +} + +func BuildProfile(prof []ProfileRecord) *profile.Profile { + p := &profile.Profile{ + PeriodType: &profile.ValueType{Type: "trace", Unit: "count"}, + Period: 1, + SampleType: []*profile.ValueType{ + {Type: "contentions", Unit: "count"}, + {Type: "delay", Unit: "nanoseconds"}, + }, + } + locs := make(map[uint64]*profile.Location) + funcs := make(map[string]*profile.Function) + for _, rec := range prof { + var sloc []*profile.Location + for _, frame := range rec.Stack { + loc := locs[frame.PC] + if loc == nil { + fn := funcs[frame.File+frame.Func] + if fn == nil { + fn = &profile.Function{ + ID: uint64(len(p.Function) + 1), + Name: frame.Func, + SystemName: frame.Func, + Filename: frame.File, + } + p.Function = append(p.Function, fn) + funcs[frame.File+frame.Func] = fn + } + loc = &profile.Location{ + ID: uint64(len(p.Location) + 1), + Address: frame.PC, + Line: []profile.Line{ + { + Function: fn, + Line: int64(frame.Line), + }, + }, + } + p.Location = append(p.Location, loc) + locs[frame.PC] = loc + } + sloc = append(sloc, loc) + } + p.Sample = append(p.Sample, &profile.Sample{ + Value: []int64{int64(rec.Count), int64(rec.Time)}, + Location: sloc, + }) + } + return p +} + +func goCmd() string { + var exeSuffix string + if runtime.GOOS == "windows" { + exeSuffix = ".exe" + } + path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix) + if _, err := os.Stat(path); err == nil { + return path + } + return "go" +} diff --git a/go/src/internal/trace/traceviewer/static/README.md b/go/src/internal/trace/traceviewer/static/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b0ca86a39783c142d056c2a5114572828c8f6db2 --- /dev/null +++ b/go/src/internal/trace/traceviewer/static/README.md @@ -0,0 +1,106 @@ +## Resources for Go's trace viewer + +Go execution trace UI (`go tool trace`) embeds +Chrome's trace viewer (Catapult) following the +[instructions]( +https://chromium.googlesource.com/catapult/+/refs/heads/master/tracing/docs/embedding-trace-viewer.md). This directory contains +the helper files to embed Chrome's trace viewer. + +The current resources were generated/copied from +[`Catapult@9508452e18f130c98499cb4c4f1e1efaedee8962`]( +https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962). + +### Updating `trace_viewer_full.html` + +The file was generated by catapult's `vulcanize_trace_viewer` command. + +``` +$ git clone https://chromium.googlesource.com/catapult +$ cd catapult +$ ./tracing/bin/vulcanize_trace_viewer --config=full +$ cp tracing/bin/trace_viewer_full.html $GOROOT/src/cmd/trace/static/trace_viewer_full.html +``` + +We are supposed to use --config=lean (produces smaller html), +but it is broken at the moment: +https://github.com/catapult-project/catapult/issues/2247 + +### Updating `webcomponents.min.js` + +`webcomponents.min.js` is necessary to let the trace viewer page +to import the `trace_viewer_full.html`. +This is copied from the catapult repo. + +``` +$ cp third_party/polymer/components/webcomponentsjs/webcomponents.min.js $GOROOT/src/cmd/trace/static/webcomponents.min.js +``` + +## Licenses + +The license for trace-viewer is as follows: +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The license for webcomponents.min.js is as follows: + +/** + * @license + * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. + * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt + * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt + * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt + * Code distributed by Google as part of the polymer project is also + * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt + */ +// Copyright (c) 2014 The Polymer Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/go/src/internal/trace/traceviewer/static/trace_viewer_full.html b/go/src/internal/trace/traceviewer/static/trace_viewer_full.html new file mode 100644 index 0000000000000000000000000000000000000000..ae6e35fca22badf007ee2a735c2937ebb7eba138 --- /dev/null +++ b/go/src/internal/trace/traceviewer/static/trace_viewer_full.html @@ -0,0 +1,10441 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/go/src/internal/trace/traceviewer/static/webcomponents.min.js b/go/src/internal/trace/traceviewer/static/webcomponents.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ad8196bc301f81141937c10a3dd38c88c10a1e68 --- /dev/null +++ b/go/src/internal/trace/traceviewer/static/webcomponents.min.js @@ -0,0 +1,14 @@ +/** + * @license + * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. + * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt + * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt + * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt + * Code distributed by Google as part of the polymer project is also + * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt + */ +// @version 0.7.24 +!function(){window.WebComponents=window.WebComponents||{flags:{}};var e="webcomponents.js",t=document.querySelector('script[src*="'+e+'"]'),n={};if(!n.noOpts){if(location.search.slice(1).split("&").forEach(function(e){var t,r=e.split("=");r[0]&&(t=r[0].match(/wc-(.+)/))&&(n[t[1]]=r[1]||!0)}),t)for(var r,o=0;r=t.attributes[o];o++)"src"!==r.name&&(n[r.name]=r.value||!0);if(n.log&&n.log.split){var i=n.log.split(",");n.log={},i.forEach(function(e){n.log[e]=!0})}else n.log={}}n.shadow=n.shadow||n.shadowdom||n.polyfill,"native"===n.shadow?n.shadow=!1:n.shadow=n.shadow||!HTMLElement.prototype.createShadowRoot,n.register&&(window.CustomElements=window.CustomElements||{flags:{}},window.CustomElements.flags.register=n.register),WebComponents.flags=n}(),WebComponents.flags.shadow&&("undefined"==typeof WeakMap&&!function(){var e=Object.defineProperty,t=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+(t++ +"__")};n.prototype={set:function(t,n){var r=t[this.name];return r&&r[0]===t?r[1]=n:e(t,this.name,{value:[t,n],writable:!0}),this},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){var t=e[this.name];return!(!t||t[0]!==e)&&(t[0]=t[1]=void 0,!0)},has:function(e){var t=e[this.name];return!!t&&t[0]===e}},window.WeakMap=n}(),window.ShadowDOMPolyfill={},function(e){"use strict";function t(){if("undefined"!=typeof chrome&&chrome.app&&chrome.app.runtime)return!1;if(navigator.getDeviceStorage)return!1;try{var e=new Function("return true;");return e()}catch(t){return!1}}function n(e){if(!e)throw new Error("Assertion failed")}function r(e,t){for(var n=W(t),r=0;r0||n>0;)if(0!=t)if(0!=n){var l,u=e[t-1][n-1],d=e[t-1][n],p=e[t][n-1];l=d0){for(var u=0;u0&&r.length>0;){var i=n.pop(),a=r.pop();if(i!==a)break;o=i}return o}function u(e,t,n){t instanceof G.Window&&(t=t.document);var o,i=A(t),a=A(n),s=r(n,e),o=l(i,a);o||(o=a.root);for(var c=o;c;c=c.parent)for(var u=0;u0;i--)if(!g(t[i],e,o,t,r))return!1;return!0}function w(e,t,n,r){var o=ie,i=t[0]||n;return g(i,e,o,t,r)}function v(e,t,n,r){for(var o=ae,i=1;i0&&g(n,e,o,t,r)}function g(e,t,n,r,o){var i=z.get(e);if(!i)return!0;var a=o||s(r,e);if(a===e){if(n===oe)return!0;n===ae&&(n=ie)}else if(n===ae&&!t.bubbles)return!0;if("relatedTarget"in t){var c=B(t),l=c.relatedTarget;if(l){if(l instanceof Object&&l.addEventListener){var d=V(l),p=u(t,e,d);if(p===a)return!0}else p=null;Z.set(t,p)}}J.set(t,n);var h=t.type,f=!1;X.set(t,a),Y.set(t,e),i.depth++;for(var m=0,w=i.length;m=0;a--)e.removeChild(i[a]),i[a].parentNode_=t;U=!1;for(var a=0;a>>/g," ")}function r(e){return String(e).replace(/:host\(([^\s]+)\)/g,"$1").replace(/([^\s]):host/g,"$1").replace(":host","*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g," ")}function o(e,t){for(var n,r=e.firstElementChild;r;){if(r.matches(t))return r;if(n=o(r,t))return n;r=r.nextElementSibling}return null}function i(e,t){return e.matches(t)}function a(e,t,n){var r=e.localName;return r===t||r===n&&e.namespaceURI===j}function s(){return!0}function c(e,t,n){return e.localName===n}function l(e,t){return e.namespaceURI===t}function u(e,t,n){return e.namespaceURI===t&&e.localName===n}function d(e,t,n,r,o,i){for(var a=e.firstElementChild;a;)r(a,o,i)&&(n[t++]=a),t=d(a,t,n,r,o,i),a=a.nextElementSibling;return t}function p(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,null);if(c instanceof N)s=S.call(c,i);else{if(!(c instanceof C))return d(this,r,o,n,i,null);s=_.call(c,i)}return t(s,r,o,a)}function h(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=M.call(c,i,a);else{if(!(c instanceof C))return d(this,r,o,n,i,a);s=T.call(c,i,a)}return t(s,r,o,!1)}function f(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=L.call(c,i,a);else{if(!(c instanceof C))return d(this,r,o,n,i,a);s=O.call(c,i,a)}return t(s,r,o,!1)}var m=e.wrappers.HTMLCollection,w=e.wrappers.NodeList,v=e.getTreeScope,g=e.unsafeUnwrap,b=e.wrap,y=document.querySelector,E=document.documentElement.querySelector,_=document.querySelectorAll,S=document.documentElement.querySelectorAll,T=document.getElementsByTagName,M=document.documentElement.getElementsByTagName,O=document.getElementsByTagNameNS,L=document.documentElement.getElementsByTagNameNS,N=window.Element,C=window.HTMLDocument||window.Document,j="http://www.w3.org/1999/xhtml",D={ +querySelector:function(t){var r=n(t),i=r!==t;t=r;var a,s=g(this),c=v(this).root;if(c instanceof e.wrappers.ShadowRoot)return o(this,t);if(s instanceof N)a=b(E.call(s,t));else{if(!(s instanceof C))return o(this,t);a=b(y.call(s,t))}return a&&!i&&(c=v(a).root)&&c instanceof e.wrappers.ShadowRoot?o(this,t):a},querySelectorAll:function(e){var t=n(e),r=t!==e;e=t;var o=new w;return o.length=p.call(this,i,0,o,e,r),o}},H={matches:function(t){return t=r(t),e.originalMatches.call(g(this),t)}},x={getElementsByTagName:function(e){var t=new m,n="*"===e?s:a;return t.length=h.call(this,n,0,t,e,e.toLowerCase()),t},getElementsByClassName:function(e){return this.querySelectorAll("."+e)},getElementsByTagNameNS:function(e,t){var n=new m,r=null;return r="*"===e?"*"===t?s:c:"*"===t?l:u,n.length=f.call(this,r,0,n,e||null,t),n}};e.GetElementsByInterface=x,e.SelectorsInterface=D,e.MatchesInterface=H}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;return e}function n(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.previousSibling;return e}var r=e.wrappers.NodeList,o={get firstElementChild(){return t(this.firstChild)},get lastElementChild(){return n(this.lastChild)},get childElementCount(){for(var e=0,t=this.firstElementChild;t;t=t.nextElementSibling)e++;return e},get children(){for(var e=new r,t=0,n=this.firstElementChild;n;n=n.nextElementSibling)e[t++]=n;return e.length=t,e},remove:function(){var e=this.parentNode;e&&e.removeChild(this)}},i={get nextElementSibling(){return t(this.nextSibling)},get previousElementSibling(){return n(this.previousSibling)}},a={getElementById:function(e){return/[ \t\n\r\f]/.test(e)?null:this.querySelector('[id="'+e+'"]')}};e.ChildNodeInterface=i,e.NonElementParentNodeInterface=a,e.ParentNodeInterface=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}var n=e.ChildNodeInterface,r=e.wrappers.Node,o=e.enqueueMutation,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=window.CharacterData;t.prototype=Object.create(r.prototype),i(t.prototype,{get nodeValue(){return this.data},set nodeValue(e){this.data=e},get textContent(){return this.data},set textContent(e){this.data=e},get data(){return s(this).data},set data(e){var t=s(this).data;o(this,"characterData",{oldValue:t}),s(this).data=e}}),i(t.prototype,n),a(c,t,document.createTextNode("")),e.wrappers.CharacterData=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e>>>0}function n(e){r.call(this,e)}var r=e.wrappers.CharacterData,o=(e.enqueueMutation,e.mixin),i=e.registerWrapper,a=window.Text;n.prototype=Object.create(r.prototype),o(n.prototype,{splitText:function(e){e=t(e);var n=this.data;if(e>n.length)throw new Error("IndexSizeError");var r=n.slice(0,e),o=n.slice(e);this.data=r;var i=this.ownerDocument.createTextNode(o);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}}),i(a,n,document.createTextNode("")),e.wrappers.Text=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return i(e).getAttribute("class")}function n(e,t){a(e,"attributes",{name:"class",namespace:null,oldValue:t})}function r(t){e.invalidateRendererBasedOnAttribute(t,"class")}function o(e,o,i){var a=e.ownerElement_;if(null==a)return o.apply(e,i);var s=t(a),c=o.apply(e,i);return t(a)!==s&&(n(a,s),r(a)),c}if(!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH.");var i=e.unsafeUnwrap,a=e.enqueueMutation,s=DOMTokenList.prototype.add;DOMTokenList.prototype.add=function(){o(this,s,arguments)};var c=DOMTokenList.prototype.remove;DOMTokenList.prototype.remove=function(){o(this,c,arguments)};var l=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(){return o(this,l,arguments)}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n){var r=t.parentNode;if(r&&r.shadowRoot){var o=e.getRendererForHost(r);o.dependsOnAttribute(n)&&o.invalidate()}}function n(e,t,n){u(e,"attributes",{name:t,namespace:null,oldValue:n})}function r(e){a.call(this,e)}var o=e.ChildNodeInterface,i=e.GetElementsByInterface,a=e.wrappers.Node,s=e.ParentNodeInterface,c=e.SelectorsInterface,l=e.MatchesInterface,u=(e.addWrapNodeListMethod,e.enqueueMutation),d=e.mixin,p=(e.oneOf,e.registerWrapper),h=e.unsafeUnwrap,f=e.wrappers,m=window.Element,w=["matches","mozMatchesSelector","msMatchesSelector","webkitMatchesSelector"].filter(function(e){return m.prototype[e]}),v=w[0],g=m.prototype[v],b=new WeakMap;r.prototype=Object.create(a.prototype),d(r.prototype,{createShadowRoot:function(){var t=new f.ShadowRoot(this);h(this).polymerShadowRoot_=t;var n=e.getRendererForHost(this);return n.invalidate(),t},get shadowRoot(){return h(this).polymerShadowRoot_||null},setAttribute:function(e,r){var o=h(this).getAttribute(e);h(this).setAttribute(e,r),n(this,e,o),t(this,e)},removeAttribute:function(e){var r=h(this).getAttribute(e);h(this).removeAttribute(e),n(this,e,r),t(this,e)},get classList(){var e=b.get(this);if(!e){if(e=h(this).classList,!e)return;e.ownerElement_=this,b.set(this,e)}return e},get className(){return h(this).className},set className(e){this.setAttribute("class",e)},get id(){return h(this).id},set id(e){this.setAttribute("id",e)}}),w.forEach(function(e){"matches"!==e&&(r.prototype[e]=function(e){return this.matches(e)})}),m.prototype.webkitCreateShadowRoot&&(r.prototype.webkitCreateShadowRoot=r.prototype.createShadowRoot),d(r.prototype,o),d(r.prototype,i),d(r.prototype,s),d(r.prototype,c),d(r.prototype,l),p(m,r,document.createElementNS(null,"x")),e.invalidateRendererBasedOnAttribute=t,e.matchesNames=w,e.originalMatches=g,e.wrappers.Element=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case" ":return" "}}function n(e){return e.replace(L,t)}function r(e){return e.replace(N,t)}function o(e){for(var t={},n=0;n"):c+">"+s(e)+"";case Node.TEXT_NODE:var d=e.data;return t&&j[t.localName]?d:r(d);case Node.COMMENT_NODE:return"";default:throw console.error(e),new Error("not implemented")}}function s(e){e instanceof O.HTMLTemplateElement&&(e=e.content);for(var t="",n=e.firstChild;n;n=n.nextSibling)t+=a(n,e);return t}function c(e,t,n){var r=n||"div";e.textContent="";var o=T(e.ownerDocument.createElement(r));o.innerHTML=t;for(var i;i=o.firstChild;)e.appendChild(M(i))}function l(e){m.call(this,e)}function u(e,t){var n=T(e.cloneNode(!1));n.innerHTML=t;for(var r,o=T(document.createDocumentFragment());r=n.firstChild;)o.appendChild(r);return M(o)}function d(t){return function(){return e.renderAllPending(),S(this)[t]}}function p(e){w(l,e,d(e))}function h(t){Object.defineProperty(l.prototype,t,{get:d(t),set:function(n){e.renderAllPending(),S(this)[t]=n},configurable:!0,enumerable:!0})}function f(t){Object.defineProperty(l.prototype,t,{value:function(){return e.renderAllPending(),S(this)[t].apply(S(this),arguments)},configurable:!0,enumerable:!0})}var m=e.wrappers.Element,w=e.defineGetter,v=e.enqueueMutation,g=e.mixin,b=e.nodesWereAdded,y=e.nodesWereRemoved,E=e.registerWrapper,_=e.snapshotNodeList,S=e.unsafeUnwrap,T=e.unwrap,M=e.wrap,O=e.wrappers,L=/[&\u00A0"]/g,N=/[&\u00A0<>]/g,C=o(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),j=o(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]),D="http://www.w3.org/1999/xhtml",H=/MSIE/.test(navigator.userAgent),x=window.HTMLElement,R=window.HTMLTemplateElement;l.prototype=Object.create(m.prototype),g(l.prototype,{get innerHTML(){return s(this)},set innerHTML(e){if(H&&j[this.localName])return void(this.textContent=e);var t=_(this.childNodes);this.invalidateShadowRenderer()?this instanceof O.HTMLTemplateElement?c(this.content,e):c(this,e,this.tagName):!R&&this instanceof O.HTMLTemplateElement?c(this.content,e):S(this).innerHTML=e;var n=_(this.childNodes);v(this,"childList",{addedNodes:n,removedNodes:t}),y(t),b(n,this)},get outerHTML(){return a(this,this.parentNode)},set outerHTML(e){var t=this.parentNode;if(t){t.invalidateShadowRenderer();var n=u(t,e);t.replaceChild(n,this)}},insertAdjacentHTML:function(e,t){var n,r;switch(String(e).toLowerCase()){case"beforebegin":n=this.parentNode,r=this;break;case"afterend":n=this.parentNode,r=this.nextSibling;break;case"afterbegin":n=this,r=this.firstChild;break;case"beforeend":n=this,r=null;break;default:return}var o=u(n,t);n.insertBefore(o,r)},get hidden(){return this.hasAttribute("hidden")},set hidden(e){e?this.setAttribute("hidden",""):this.removeAttribute("hidden")}}),["clientHeight","clientLeft","clientTop","clientWidth","offsetHeight","offsetLeft","offsetTop","offsetWidth","scrollHeight","scrollWidth"].forEach(p),["scrollLeft","scrollTop"].forEach(h),["focus","getBoundingClientRect","getClientRects","scrollIntoView"].forEach(f),E(x,l,document.createElement("b")),e.wrappers.HTMLElement=l,e.getInnerHTML=s,e.setInnerHTML=c}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.HTMLCanvasElement;t.prototype=Object.create(n.prototype),r(t.prototype,{getContext:function(){var e=i(this).getContext.apply(i(this),arguments);return e&&a(e)}}),o(s,t,document.createElement("canvas")),e.wrappers.HTMLCanvasElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=window.HTMLContentElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get select(){return this.getAttribute("select")},set select(e){this.setAttribute("select",e)},setAttribute:function(e,t){n.prototype.setAttribute.call(this,e,t),"select"===String(e).toLowerCase()&&this.invalidateShadowRenderer(!0)}}),i&&o(i,t),e.wrappers.HTMLContentElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=window.HTMLFormElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get elements(){return i(a(this).elements)}}),o(s,t,document.createElement("form")),e.wrappers.HTMLFormElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e,t){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var o=i(document.createElement("img"));r.call(this,o),a(o,this),void 0!==e&&(o.width=e),void 0!==t&&(o.height=t)}var r=e.wrappers.HTMLElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLImageElement;t.prototype=Object.create(r.prototype),o(s,t,document.createElement("img")),n.prototype=t.prototype,e.wrappers.HTMLImageElement=t,e.wrappers.Image=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=(e.mixin,e.wrappers.NodeList,e.registerWrapper),o=window.HTMLShadowElement;t.prototype=Object.create(n.prototype),t.prototype.constructor=t,o&&r(o,t),e.wrappers.HTMLShadowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){if(!e.defaultView)return e;var t=d.get(e);if(!t){for(t=e.implementation.createHTMLDocument("");t.lastChild;)t.removeChild(t.lastChild);d.set(e,t)}return t}function n(e){for(var n,r=t(e.ownerDocument),o=c(r.createDocumentFragment());n=e.firstChild;)o.appendChild(n);return o}function r(e){if(o.call(this,e),!p){var t=n(e);u.set(this,l(t))}}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=e.unwrap,l=e.wrap,u=new WeakMap,d=new WeakMap,p=window.HTMLTemplateElement;r.prototype=Object.create(o.prototype),i(r.prototype,{constructor:r,get content(){return p?l(s(this).content):u.get(this)}}),p&&a(p,r),e.wrappers.HTMLTemplateElement=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.registerWrapper,o=window.HTMLMediaElement;o&&(t.prototype=Object.create(n.prototype),r(o,t,document.createElement("audio")),e.wrappers.HTMLMediaElement=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var t=i(document.createElement("audio"));r.call(this,t),a(t,this),t.setAttribute("preload","auto"),void 0!==e&&t.setAttribute("src",e)}var r=e.wrappers.HTMLMediaElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLAudioElement;s&&(t.prototype=Object.create(r.prototype),o(s,t,document.createElement("audio")),n.prototype=t.prototype,e.wrappers.HTMLAudioElement=t,e.wrappers.Audio=n)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e.replace(/\s+/g," ").trim()}function n(e){o.call(this,e)}function r(e,t,n,i){if(!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function.");var a=c(document.createElement("option"));o.call(this,a),s(a,this),void 0!==e&&(a.text=e),void 0!==t&&a.setAttribute("value",t),n===!0&&a.setAttribute("selected",""),a.selected=i===!0}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.rewrap,c=e.unwrap,l=e.wrap,u=window.HTMLOptionElement;n.prototype=Object.create(o.prototype),i(n.prototype,{get text(){return t(this.textContent)},set text(e){this.textContent=t(String(e))},get form(){return l(c(this).form)}}),a(u,n,document.createElement("option")),r.prototype=n.prototype,e.wrappers.HTMLOptionElement=n,e.wrappers.Option=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=window.HTMLSelectElement;t.prototype=Object.create(n.prototype),r(t.prototype,{add:function(e,t){"object"==typeof t&&(t=i(t)),i(this).add(i(e),t)},remove:function(e){return void 0===e?void n.prototype.remove.call(this):("object"==typeof e&&(e=i(e)),void i(this).remove(e))},get form(){return a(i(this).form)}}),o(s,t,document.createElement("select")),e.wrappers.HTMLSelectElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=e.wrapHTMLCollection,c=window.HTMLTableElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get caption(){return a(i(this).caption)},createCaption:function(){return a(i(this).createCaption())},get tHead(){return a(i(this).tHead)},createTHead:function(){return a(i(this).createTHead())},createTFoot:function(){return a(i(this).createTFoot())},get tFoot(){return a(i(this).tFoot)},get tBodies(){return s(i(this).tBodies)},createTBody:function(){return a(i(this).createTBody())},get rows(){return s(i(this).rows)},insertRow:function(e){return a(i(this).insertRow(e))}}),o(c,t,document.createElement("table")),e.wrappers.HTMLTableElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableSectionElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get rows(){return i(a(this).rows)},insertRow:function(e){return s(a(this).insertRow(e))}}),o(c,t,document.createElement("thead")),e.wrappers.HTMLTableSectionElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableRowElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get cells(){return i(a(this).cells)},insertCell:function(e){return s(a(this).insertCell(e))}}),o(c,t,document.createElement("tr")),e.wrappers.HTMLTableRowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e.localName){case"content":return new n(e);case"shadow":return new o(e);case"template":return new i(e)}r.call(this,e)}var n=e.wrappers.HTMLContentElement,r=e.wrappers.HTMLElement,o=e.wrappers.HTMLShadowElement,i=e.wrappers.HTMLTemplateElement,a=(e.mixin,e.registerWrapper),s=window.HTMLUnknownElement;t.prototype=Object.create(r.prototype),a(s,t),e.wrappers.HTMLUnknownElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Element,r=e.wrappers.HTMLElement,o=e.registerWrapper,i=(e.defineWrapGetter,e.unsafeUnwrap),a=e.wrap,s=e.mixin,c="http://www.w3.org/2000/svg",l=window.SVGElement,u=document.createElementNS(c,"title");if(!("classList"in u)){var d=Object.getOwnPropertyDescriptor(n.prototype,"classList");Object.defineProperty(r.prototype,"classList",d),delete n.prototype.classList}t.prototype=Object.create(n.prototype),s(t.prototype,{get ownerSVGElement(){return a(i(this).ownerSVGElement)}}),o(l,t,document.createElementNS(c,"title")),e.wrappers.SVGElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){p.call(this,e)}var n=e.mixin,r=e.registerWrapper,o=e.unwrap,i=e.wrap,a=window.SVGUseElement,s="http://www.w3.org/2000/svg",c=i(document.createElementNS(s,"g")),l=document.createElementNS(s,"use"),u=c.constructor,d=Object.getPrototypeOf(u.prototype),p=d.constructor;t.prototype=Object.create(d),"instanceRoot"in l&&n(t.prototype,{get instanceRoot(){return i(o(this).instanceRoot)},get animatedInstanceRoot(){return i(o(this).animatedInstanceRoot)}}),r(a,t,l),e.wrappers.SVGUseElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.SVGElementInstance;s&&(t.prototype=Object.create(n.prototype),r(t.prototype,{get correspondingElement(){return a(i(this).correspondingElement)},get correspondingUseElement(){return a(i(this).correspondingUseElement)},get parentNode(){return a(i(this).parentNode)},get childNodes(){throw new Error("Not implemented")},get firstChild(){return a(i(this).firstChild)},get lastChild(){return a(i(this).lastChild)},get previousSibling(){return a(i(this).previousSibling)},get nextSibling(){return a(i(this).nextSibling)}}),o(s,t),e.wrappers.SVGElementInstance=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){o(e,this)}var n=e.mixin,r=e.registerWrapper,o=e.setWrapper,i=e.unsafeUnwrap,a=e.unwrap,s=e.unwrapIfNeeded,c=e.wrap,l=window.CanvasRenderingContext2D;n(t.prototype,{get canvas(){return c(i(this).canvas)},drawImage:function(){arguments[0]=s(arguments[0]),i(this).drawImage.apply(i(this),arguments)},createPattern:function(){return arguments[0]=a(arguments[0]),i(this).createPattern.apply(i(this),arguments)}}),r(l,t,document.createElement("canvas").getContext("2d")),e.wrappers.CanvasRenderingContext2D=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){i(e,this)}var n=e.addForwardingProperties,r=e.mixin,o=e.registerWrapper,i=e.setWrapper,a=e.unsafeUnwrap,s=e.unwrapIfNeeded,c=e.wrap,l=window.WebGLRenderingContext;if(l){r(t.prototype,{get canvas(){return c(a(this).canvas)},texImage2D:function(){arguments[5]=s(arguments[5]),a(this).texImage2D.apply(a(this),arguments)},texSubImage2D:function(){arguments[6]=s(arguments[6]),a(this).texSubImage2D.apply(a(this),arguments)}});var u=Object.getPrototypeOf(l.prototype);u!==Object.prototype&&n(u,t.prototype);var d=/WebKit/.test(navigator.userAgent)?{drawingBufferHeight:null,drawingBufferWidth:null}:{};o(l,t,d),e.wrappers.WebGLRenderingContext=t}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Node,r=e.GetElementsByInterface,o=e.NonElementParentNodeInterface,i=e.ParentNodeInterface,a=e.SelectorsInterface,s=e.mixin,c=e.registerObject,l=e.registerWrapper,u=window.DocumentFragment;t.prototype=Object.create(n.prototype),s(t.prototype,i),s(t.prototype,a),s(t.prototype,r),s(t.prototype,o),l(u,t,document.createDocumentFragment()),e.wrappers.DocumentFragment=t;var d=c(document.createComment(""));e.wrappers.Comment=d}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(u(e).ownerDocument.createDocumentFragment());n.call(this,t),c(t,this);var o=e.shadowRoot;f.set(this,o),this.treeScope_=new r(this,a(o||e)),h.set(this,e)}var n=e.wrappers.DocumentFragment,r=e.TreeScope,o=e.elementFromPoint,i=e.getInnerHTML,a=e.getTreeScope,s=e.mixin,c=e.rewrap,l=e.setInnerHTML,u=e.unsafeUnwrap,d=e.unwrap,p=e.wrap,h=new WeakMap,f=new WeakMap;t.prototype=Object.create(n.prototype),s(t.prototype,{constructor:t,get innerHTML(){return i(this)},set innerHTML(e){l(this,e),this.invalidateShadowRenderer()},get olderShadowRoot(){return f.get(this)||null},get host(){return h.get(this)||null},invalidateShadowRenderer:function(){return h.get(this).invalidateShadowRenderer()},elementFromPoint:function(e,t){return o(this,this.ownerDocument,e,t)},getSelection:function(){return document.getSelection()},get activeElement(){var e=d(this).ownerDocument.activeElement;if(!e||!e.nodeType)return null;for(var t=p(e);!this.contains(t);){for(;t.parentNode;)t=t.parentNode;if(!t.host)return null;t=t.host}return t}}),e.wrappers.ShadowRoot=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(e).root;return t instanceof h?t.host:null}function n(t,n){if(t.shadowRoot){n=Math.min(t.childNodes.length-1,n);var r=t.childNodes[n];if(r){var o=e.getDestinationInsertionPoints(r);if(o.length>0){var i=o[0].parentNode;i.nodeType==Node.ELEMENT_NODE&&(t=i)}}}return t}function r(e){return e=u(e),t(e)||e}function o(e){a(e,this)}var i=e.registerWrapper,a=e.setWrapper,s=e.unsafeUnwrap,c=e.unwrap,l=e.unwrapIfNeeded,u=e.wrap,d=e.getTreeScope,p=window.Range,h=e.wrappers.ShadowRoot;o.prototype={get startContainer(){return r(s(this).startContainer)},get endContainer(){return r(s(this).endContainer)},get commonAncestorContainer(){return r(s(this).commonAncestorContainer)},setStart:function(e,t){e=n(e,t),s(this).setStart(l(e),t)},setEnd:function(e,t){e=n(e,t),s(this).setEnd(l(e),t)},setStartBefore:function(e){s(this).setStartBefore(l(e))},setStartAfter:function(e){s(this).setStartAfter(l(e))},setEndBefore:function(e){s(this).setEndBefore(l(e))},setEndAfter:function(e){s(this).setEndAfter(l(e))},selectNode:function(e){s(this).selectNode(l(e))},selectNodeContents:function(e){s(this).selectNodeContents(l(e))},compareBoundaryPoints:function(e,t){return s(this).compareBoundaryPoints(e,c(t))},extractContents:function(){return u(s(this).extractContents())},cloneContents:function(){return u(s(this).cloneContents())},insertNode:function(e){s(this).insertNode(l(e))},surroundContents:function(e){s(this).surroundContents(l(e))},cloneRange:function(){return u(s(this).cloneRange())},isPointInRange:function(e,t){return s(this).isPointInRange(l(e),t)},comparePoint:function(e,t){return s(this).comparePoint(l(e),t)},intersectsNode:function(e){return s(this).intersectsNode(l(e))},toString:function(){return s(this).toString()}},p.prototype.createContextualFragment&&(o.prototype.createContextualFragment=function(e){return u(s(this).createContextualFragment(e))}),i(window.Range,o,document.createRange()),e.wrappers.Range=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.previousSibling_=e.previousSibling,e.nextSibling_=e.nextSibling,e.parentNode_=e.parentNode}function n(n,o,i){var a=x(n),s=x(o),c=i?x(i):null;if(r(o),t(o),i)n.firstChild===i&&(n.firstChild_=i),i.previousSibling_=i.previousSibling;else{n.lastChild_=n.lastChild,n.lastChild===n.firstChild&&(n.firstChild_=n.firstChild);var l=R(a.lastChild);l&&(l.nextSibling_=l.nextSibling)}e.originalInsertBefore.call(a,s,c)}function r(n){var r=x(n),o=r.parentNode;if(o){var i=R(o);t(n),n.previousSibling&&(n.previousSibling.nextSibling_=n),n.nextSibling&&(n.nextSibling.previousSibling_=n),i.lastChild===n&&(i.lastChild_=n),i.firstChild===n&&(i.firstChild_=n),e.originalRemoveChild.call(o,r)}}function o(e){P.set(e,[])}function i(e){var t=P.get(e);return t||P.set(e,t=[]),t}function a(e){for(var t=[],n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t}function s(){for(var e=0;e=0;o--){var i=r[o],a=m(i);if(a){var s=i.olderShadowRoot;s&&(n=f(s));for(var c=0;c=0;u--)l=Object.create(l);["createdCallback","attachedCallback","detachedCallback","attributeChangedCallback"].forEach(function(e){var t=o[e];t&&(l[e]=function(){j(this)instanceof r||O(this),t.apply(j(this),arguments)})});var d={prototype:l};i&&(d["extends"]=i),r.prototype=o,r.prototype.constructor=r,e.constructorTable.set(l,r),e.nativePrototypeTable.set(o,l);k.call(C(this),t,d);return r},E([window.HTMLDocument||window.Document],["registerElement"])}E([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement,window.HTMLHtmlElement],["appendChild","compareDocumentPosition","contains","getElementsByClassName","getElementsByTagName","getElementsByTagNameNS","insertBefore","querySelector","querySelectorAll","removeChild","replaceChild"]),E([window.HTMLBodyElement,window.HTMLHeadElement,window.HTMLHtmlElement],_),E([window.HTMLDocument||window.Document],["adoptNode","importNode","contains","createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode","createTreeWalker","elementFromPoint","getElementById","getElementsByName","getSelection"]),S(t.prototype,l),S(t.prototype,d),S(t.prototype,f),S(t.prototype,p),S(t.prototype,{get implementation(){var e=H.get(this);return e?e:(e=new a(C(this).implementation),H.set(this,e),e)},get defaultView(){return j(C(this).defaultView)}}),T(window.Document,t,document.implementation.createHTMLDocument("")),window.HTMLDocument&&T(window.HTMLDocument,t),D([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement]);var A=document.implementation.createDocument;a.prototype.createDocument=function(){return arguments[2]=C(arguments[2]),j(A.apply(N(this),arguments))},s(a,"createDocumentType"),s(a,"createHTMLDocument"),c(a,"hasFeature"),T(window.DOMImplementation,a),E([window.DOMImplementation],["createDocument","createDocumentType","createHTMLDocument","hasFeature"]),e.adoptNodeNoRemove=r,e.wrappers.DOMImplementation=a,e.wrappers.Document=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.wrappers.Selection,o=e.mixin,i=e.registerWrapper,a=e.renderAllPending,s=e.unwrap,c=e.unwrapIfNeeded,l=e.wrap,u=window.Window,d=window.getComputedStyle,p=window.getDefaultComputedStyle,h=window.getSelection;t.prototype=Object.create(n.prototype),u.prototype.getComputedStyle=function(e,t){return l(this||window).getComputedStyle(c(e),t)},p&&(u.prototype.getDefaultComputedStyle=function(e,t){return l(this||window).getDefaultComputedStyle(c(e),t)}),u.prototype.getSelection=function(){return l(this||window).getSelection()},delete window.getComputedStyle,delete window.getDefaultComputedStyle,delete window.getSelection,["addEventListener","removeEventListener","dispatchEvent"].forEach(function(e){u.prototype[e]=function(){var t=l(this||window);return t[e].apply(t,arguments)},delete window[e]}),o(t.prototype,{getComputedStyle:function(e,t){return a(),d.call(s(this),c(e),t)},getSelection:function(){return a(),new r(h.call(s(this)))},get document(){return l(s(this).document)}}),p&&(t.prototype.getDefaultComputedStyle=function(e,t){return a(),p.call(s(this),c(e),t)}),i(u,t,window),e.wrappers.Window=t}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrap,n=window.DataTransfer||window.Clipboard,r=n.prototype.setDragImage;r&&(n.prototype.setDragImage=function(e,n,o){r.call(this,t(e),n,o)})}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t;t=e instanceof i?e:new i(e&&o(e)),r(t,this)}var n=e.registerWrapper,r=e.setWrapper,o=e.unwrap,i=window.FormData;i&&(n(i,t,new i),e.wrappers.FormData=t)}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrapIfNeeded,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.send=function(e){return n.call(this,t(e))}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=n[e],r=window[t];if(r){var o=document.createElement(e),i=o.constructor;window[t]=i}}var n=(e.isWrapperFor,{a:"HTMLAnchorElement",area:"HTMLAreaElement",audio:"HTMLAudioElement",base:"HTMLBaseElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",col:"HTMLTableColElement",content:"HTMLContentElement",data:"HTMLDataElement",datalist:"HTMLDataListElement",del:"HTMLModElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",embed:"HTMLEmbedElement",fieldset:"HTMLFieldSetElement",font:"HTMLFontElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",head:"HTMLHeadElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",marquee:"HTMLMarqueeElement",menu:"HTMLMenuElement",menuitem:"HTMLMenuItemElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",script:"HTMLScriptElement",select:"HTMLSelectElement",shadow:"HTMLShadowElement",source:"HTMLSourceElement",span:"HTMLSpanElement",style:"HTMLStyleElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",template:"HTMLTemplateElement",textarea:"HTMLTextAreaElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",ul:"HTMLUListElement",video:"HTMLVideoElement"});Object.keys(n).forEach(t),Object.getOwnPropertyNames(e.wrappers).forEach(function(t){window[t]=e.wrappers[t]})}(window.ShadowDOMPolyfill),function(e){function t(e,t){var n="";return Array.prototype.forEach.call(e,function(e){n+=e.textContent+"\n\n"}),t||(n=n.replace(d,"")),n}function n(e){var t=document.createElement("style");return t.textContent=e,t}function r(e){var t=n(e);document.head.appendChild(t);var r=[];if(t.sheet)try{r=t.sheet.cssRules}catch(o){}else console.warn("sheet not found",t);return t.parentNode.removeChild(t),r}function o(){C.initialized=!0,document.body.appendChild(C);var e=C.contentDocument,t=e.createElement("base");t.href=document.baseURI,e.head.appendChild(t)}function i(e){C.initialized||o(),document.body.appendChild(C),e(C.contentDocument),document.body.removeChild(C)}function a(e,t){if(t){var o;if(e.match("@import")&&D){var a=n(e);i(function(e){e.head.appendChild(a.impl),o=Array.prototype.slice.call(a.sheet.cssRules,0),t(o)})}else o=r(e),t(o)}}function s(e){e&&l().appendChild(document.createTextNode(e))}function c(e,t){var r=n(e);r.setAttribute(t,""),r.setAttribute(x,""),document.head.appendChild(r)}function l(){return j||(j=document.createElement("style"),j.setAttribute(x,""),j[x]=!0),j}var u={strictStyling:!1,registry:{},shimStyling:function(e,n,r){var o=this.prepareRoot(e,n,r),i=this.isTypeExtension(r),a=this.makeScopeSelector(n,i),s=t(o,!0);s=this.scopeCssText(s,a),e&&(e.shimmedStyle=s),this.addCssToDocument(s,n)},shimStyle:function(e,t){return this.shimCssText(e.textContent,t)},shimCssText:function(e,t){return e=this.insertDirectives(e),this.scopeCssText(e,t)},makeScopeSelector:function(e,t){return e?t?"[is="+e+"]":e:""},isTypeExtension:function(e){return e&&e.indexOf("-")<0},prepareRoot:function(e,t,n){var r=this.registerRoot(e,t,n);return this.replaceTextInStyles(r.rootStyles,this.insertDirectives),this.removeStyles(e,r.rootStyles),this.strictStyling&&this.applyScopeToContent(e,t),r.scopeStyles},removeStyles:function(e,t){for(var n,r=0,o=t.length;r","+","~"],r=e,o="["+t+"]";return n.forEach(function(e){var t=r.split(e);r=t.map(function(e){var t=e.trim().replace(L,"");return t&&n.indexOf(t)<0&&t.indexOf(o)<0&&(e=t.replace(/([^:]*)(:*)(.*)/,"$1"+o+"$2$3")),e}).join(e)}),r},insertPolyfillHostInCssText:function(e){return e.replace(M,b).replace(T,g)},propertiesFromRule:function(e){var t=e.style.cssText;e.style.content&&!e.style.content.match(/['"]+|attr/)&&(t=t.replace(/content:[^;]*;/g,"content: '"+e.style.content+"';"));var n=e.style;for(var r in n)"initial"===n[r]&&(t+=r+": initial; ");return t},replaceTextInStyles:function(e,t){e&&t&&(e instanceof Array||(e=[e]),Array.prototype.forEach.call(e,function(e){e.textContent=t.call(this,e.textContent)},this))},addCssToDocument:function(e,t){e.match("@import")?c(e,t):s(e)}},d=/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//gim,p=/\/\*\s*@polyfill ([^*]*\*+([^\/*][^*]*\*+)*\/)([^{]*?){/gim,h=/polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim,f=/\/\*\s@polyfill-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,m=/(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,w=/\/\*\s@polyfill-unscoped-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,v=/(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,g="-shadowcsshost",b="-shadowcsscontext",y=")(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)",E=new RegExp("("+g+y,"gim"),_=new RegExp("("+b+y,"gim"),S="([>\\s~+[.,{:][\\s\\S]*)?$",T=/\:host/gim,M=/\:host-context/gim,O=g+"-no-combinator",L=new RegExp(g,"gim"),N=(new RegExp(b,"gim"),[/>>>/g,/::shadow/g,/::content/g,/\/deep\//g,/\/shadow\//g,/\/shadow-deep\//g,/\^\^/g,/\^(?!=)/g]),C=document.createElement("iframe");C.style.display="none";var j,D=navigator.userAgent.match("Chrome"),H="shim-shadowdom",x="shim-shadowdom-css",R="no-shim";if(window.ShadowDOMPolyfill){s("style { display: none !important; }\n");var I=ShadowDOMPolyfill.wrap(document),P=I.querySelector("head");P.insertBefore(l(),P.childNodes[0]),document.addEventListener("DOMContentLoaded",function(){e.urlResolver;if(window.HTMLImports&&!HTMLImports.useNative){var t="link[rel=stylesheet]["+H+"]",n="style["+H+"]";HTMLImports.importer.documentPreloadSelectors+=","+t,HTMLImports.importer.importsPreloadSelectors+=","+t,HTMLImports.parser.documentSelectors=[HTMLImports.parser.documentSelectors,t,n].join(",");var r=HTMLImports.parser.parseGeneric;HTMLImports.parser.parseGeneric=function(e){if(!e[x]){var t=e.__importElement||e;if(!t.hasAttribute(H))return void r.call(this,e);e.__resource&&(t=e.ownerDocument.createElement("style"),t.textContent=e.__resource),HTMLImports.path.resolveUrlsInStyle(t,e.href),t.textContent=u.shimStyle(t),t.removeAttribute(H,""),t.setAttribute(x,""),t[x]=!0,t.parentNode!==P&&(e.parentNode===P?P.replaceChild(t,e):this.addElementToDocument(t)),t.__importParsed=!0,this.markParsingComplete(e),this.parseNext()}};var o=HTMLImports.parser.hasResource;HTMLImports.parser.hasResource=function(e){return"link"===e.localName&&"stylesheet"===e.rel&&e.hasAttribute(H)?e.__resource:o.call(this,e)}}})}e.ShadowCSS=u}(window.WebComponents)),function(e){window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}}(window.WebComponents),function(e){"use strict";function t(e){return void 0!==p[e]}function n(){s.call(this),this._isInvalid=!0}function r(e){return""==e&&n.call(this),e.toLowerCase()}function o(e){var t=e.charCodeAt(0);return t>32&&t<127&&[34,35,60,62,63,96].indexOf(t)==-1?e:encodeURIComponent(e)}function i(e){var t=e.charCodeAt(0);return t>32&&t<127&&[34,35,60,62,96].indexOf(t)==-1?e:encodeURIComponent(e)}function a(e,a,s){function c(e){b.push(e)}var l=a||"scheme start",u=0,d="",v=!1,g=!1,b=[];e:for(;(e[u-1]!=f||0==u)&&!this._isInvalid;){var y=e[u];switch(l){case"scheme start":if(!y||!m.test(y)){if(a){c("Invalid scheme.");break e}d="",l="no scheme";continue}d+=y.toLowerCase(),l="scheme";break;case"scheme":if(y&&w.test(y))d+=y.toLowerCase();else{if(":"!=y){if(a){if(f==y)break e;c("Code point not allowed in scheme: "+y);break e}d="",u=0,l="no scheme";continue}if(this._scheme=d,d="",a)break e;t(this._scheme)&&(this._isRelative=!0),l="file"==this._scheme?"relative":this._isRelative&&s&&s._scheme==this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"==y?(this._query="?",l="query"):"#"==y?(this._fragment="#",l="fragment"):f!=y&&"\t"!=y&&"\n"!=y&&"\r"!=y&&(this._schemeData+=o(y));break;case"no scheme":if(s&&t(s._scheme)){l="relative";continue}c("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!=y||"/"!=e[u+1]){c("Expected /, got: "+y),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!=this._scheme&&(this._scheme=s._scheme),f==y){this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._username=s._username,this._password=s._password;break e}if("/"==y||"\\"==y)"\\"==y&&c("\\ is an invalid code point."),l="relative slash";else if("?"==y)this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query="?",this._username=s._username,this._password=s._password,l="query";else{if("#"!=y){var E=e[u+1],_=e[u+2];("file"!=this._scheme||!m.test(y)||":"!=E&&"|"!=E||f!=_&&"/"!=_&&"\\"!=_&&"?"!=_&&"#"!=_)&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password,this._path=s._path.slice(),this._path.pop()),l="relative path";continue}this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._fragment="#",this._username=s._username,this._password=s._password,l="fragment"}break;case"relative slash":if("/"!=y&&"\\"!=y){"file"!=this._scheme&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password),l="relative path";continue}"\\"==y&&c("\\ is an invalid code point."),l="file"==this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!=y){c("Expected '/', got: "+y),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!=y){c("Expected '/', got: "+y);continue}break;case"authority ignore slashes":if("/"!=y&&"\\"!=y){l="authority";continue}c("Expected authority, got: "+y);break;case"authority":if("@"==y){v&&(c("@ already seen."),d+="%40"),v=!0;for(var S=0;S0){var o=n[r-1],i=h(o,e);if(i)return void(n[r-1]=i)}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=w.get(e);t||w.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=w.get(e),n=0;n=200&&e.status<300||304===e.status||0===e.status},load:function(n,r,o){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=null;try{var a=i.getResponseHeader("Location");a&&(n="/"===a.substr(0,1)?location.origin+a:a)}catch(e){console.error(e.message)}r.call(o,!t.ok(i)&&i,i.response||i.responseText,n)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),window.HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;n-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,o){this.receive(e,r,t,n,o)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,o){this.cache[e]=r;for(var i,a=this.pending[e],s=0,c=a.length;s=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(e["import"]=e.__doc,window.HTMLImports.__importsParsingHook&&window.HTMLImports.__importsParsingHook(e),e["import"]&&(e["import"].__importParsed=!0),this.markParsingComplete(e),e.__resource&&!e.__error?e.dispatchEvent(new CustomEvent("load",{bubbles:!1})):e.dispatchEvent(new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(o){e.removeEventListener("load",r),e.removeEventListener("error",r),t&&t(o),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),l&&"style"===e.localName){var o=!1;if(e.textContent.indexOf("@import")==-1)o=!0;else if(e.sheet){o=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,c=0;c=0},hasResource:function(e){return!t(e)||void 0!==e.__doc}};e.parser=p,e.IMPORT_SELECTOR=d}),window.HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function o(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var o=n.createElement("base");o.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(o),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,c=e.rootDocument,l=e.Loader,u=e.Observer,d=e.parser,p={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){h.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);h.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===c?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var c=this.documents[e];void 0===c&&(c=a?null:o(r,s||e),c&&(c.__importLink=n,this.bootDocument(c)),this.documents[e]=c),n.__doc=c}d.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),d.parseNext()},loadedAll:function(){d.parseNext()}},h=new l(p.loaded.bind(p),p.loadedAll.bind(p));if(p.observer=new u,!document.baseURI){var f={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",f),Object.defineProperty(c,"baseURI",f)}e.importer=p,e.importLoader=h}),window.HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,o,i,a,s=0,c=e.length;s=0)){n.push(e);for(var r,o=e.querySelectorAll("link[rel="+a+"]"),s=0,c=o.length;s=0&&b(r,HTMLElement),r)}function f(e,t){var n=e[t];e[t]=function(){var e=n.apply(this,arguments);return v(e),e}}var m,w=(e.isIE,e.upgradeDocumentTree),v=e.upgradeAll,g=e.upgradeWithDefinition,b=e.implementPrototype,y=e.useNative,E=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],_={},S="http://www.w3.org/1999/xhtml",T=document.createElement.bind(document),M=document.createElementNS.bind(document);m=Object.__proto__||y?function(e,t){return e instanceof t}:function(e,t){if(e instanceof t)return!0;for(var n=e;n;){if(n===t.prototype)return!0;n=n.__proto__}return!1},f(Node.prototype,"cloneNode"),f(document,"importNode"),document.registerElement=t,document.createElement=h,document.createElementNS=p,e.registry=_,e["instanceof"]=m,e.reservedTagList=E,e.getRegisteredDefinition=l,document.register=document.registerElement}),function(e){function t(){i(window.wrap(document)),window.CustomElements.ready=!0;var e=window.requestAnimationFrame||function(e){setTimeout(e,16)};e(function(){setTimeout(function(){window.CustomElements.readyTime=Date.now(),window.HTMLImports&&(window.CustomElements.elapsed=window.CustomElements.readyTime-window.HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})}var n=e.useNative,r=e.initializeModules;e.isIE;if(n){var o=function(){};e.watchShadow=o,e.upgrade=o,e.upgradeAll=o,e.upgradeDocumentTree=o,e.upgradeSubtree=o,e.takeRecords=o,e["instanceof"]=function(e,t){return e instanceof t}}else r();var i=e.upgradeDocumentTree,a=e.upgradeDocument;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=window.ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=window.ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}),window.HTMLImports&&(window.HTMLImports.__importsParsingHook=function(e){e["import"]&&a(wrap(e["import"]))}),"complete"===document.readyState||e.flags.eager)t();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var s=window.HTMLImports&&!window.HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(s,t)}else t()}(window.CustomElements),function(e){Function.prototype.bind||(Function.prototype.bind=function(e){var t=this,n=Array.prototype.slice.call(arguments,1);return function(){var r=n.slice();return r.push.apply(r,arguments),t.apply(e,r)}})}(window.WebComponents),function(e){var t=document.createElement("style");t.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var n=document.querySelector("head");n.insertBefore(t,n.firstChild)}(window.WebComponents),function(e){window.Platform=e}(window.WebComponents); \ No newline at end of file diff --git a/go/src/internal/trace/value.go b/go/src/internal/trace/value.go new file mode 100644 index 0000000000000000000000000000000000000000..41eeb50d87fe9a67d4b04864456c0d9d6bc019b6 --- /dev/null +++ b/go/src/internal/trace/value.go @@ -0,0 +1,69 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package trace + +import ( + "fmt" + "unsafe" +) + +// Value is a dynamically-typed value obtained from a trace. +type Value struct { + kind ValueKind + pointer unsafe.Pointer + scalar uint64 +} + +// ValueKind is the type of a dynamically-typed value from a trace. +type ValueKind uint8 + +const ( + ValueBad ValueKind = iota + ValueUint64 + ValueString +) + +// Kind returns the ValueKind of the value. +// +// It represents the underlying structure of the value. +// +// New ValueKinds may be added in the future. Users of this type must be robust +// to that possibility. +func (v Value) Kind() ValueKind { + return v.kind +} + +// Uint64 returns the uint64 value for a ValueUint64. +// +// Panics if this Value's Kind is not ValueUint64. +func (v Value) Uint64() uint64 { + if v.kind != ValueUint64 { + panic("Uint64 called on Value of a different Kind") + } + return v.scalar +} + +// String returns the string value for a ValueString, and otherwise +// a string representation of the value for other kinds of values. +func (v Value) String() string { + if v.kind == ValueString { + return unsafe.String((*byte)(v.pointer), int(v.scalar)) + } + switch v.kind { + case ValueUint64: + return fmt.Sprintf("Value{Uint64(%d)}", v.Uint64()) + } + return "Value{Bad}" +} + +// Uint64Value creates a value of kind ValueUint64. +func Uint64Value(x uint64) Value { + return Value{kind: ValueUint64, scalar: x} +} + +// StringValue creates a value of kind ValueString. +func StringValue(s string) Value { + return Value{kind: ValueString, scalar: uint64(len(s)), pointer: unsafe.Pointer(unsafe.StringData(s))} +} diff --git a/go/src/internal/trace/version/version.go b/go/src/internal/trace/version/version.go new file mode 100644 index 0000000000000000000000000000000000000000..328a261a93081f461253aa3e84e490792595e617 --- /dev/null +++ b/go/src/internal/trace/version/version.go @@ -0,0 +1,87 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package version + +import ( + "fmt" + "io" + + "internal/trace/tracev2" +) + +// Version represents the version of a trace file. +type Version uint32 + +const ( + Go111 Version = 11 // v1 + Go119 Version = 19 // v1 + Go121 Version = 21 // v1 + Go122 Version = 22 // v2 + Go123 Version = 23 // v2 + Go125 Version = 25 // v2 + Go126 Version = 26 // v2 + Current = Go126 +) + +var versions = map[Version][]tracev2.EventSpec{ + // Go 1.11–1.21 use a different parser and are only set here for the sake of + // Version.Valid. + Go111: nil, + Go119: nil, + Go121: nil, + + Go122: tracev2.Specs()[:tracev2.EvUserLog+1], // All events after are Go 1.23+. + Go123: tracev2.Specs()[:tracev2.EvExperimentalBatch+1], // All events after are Go 1.25+. + Go125: tracev2.Specs()[:tracev2.EvClockSnapshot+1], // All events after are Go 1.26+. + Go126: tracev2.Specs(), +} + +// Specs returns the set of event.Specs for this version. +func (v Version) Specs() []tracev2.EventSpec { + return versions[v] +} + +// EventName returns a string name of a wire format event +// for a particular trace version. +func (v Version) EventName(typ tracev2.EventType) string { + if !v.Valid() { + return "" + } + s := v.Specs() + if len(s) == 0 { + return "" + } + if int(typ) < len(s) && s[typ].Name != "" { + return s[typ].Name + } + return fmt.Sprintf("Invalid(%d)", typ) +} + +func (v Version) Valid() bool { + _, ok := versions[v] + return ok +} + +// headerFmt is the format of the header of all Go execution traces. +const headerFmt = "go 1.%d trace\x00\x00\x00" + +// ReadHeader reads the version of the trace out of the trace file's +// header, whose prefix must be present in v. +func ReadHeader(r io.Reader) (Version, error) { + var v Version + _, err := fmt.Fscanf(r, headerFmt, &v) + if err != nil { + return v, fmt.Errorf("bad file format: not a Go execution trace?") + } + if !v.Valid() { + return v, fmt.Errorf("unknown or unsupported trace version go 1.%d", v) + } + return v, nil +} + +// WriteHeader writes a header for a trace version v to w. +func WriteHeader(w io.Writer, v Version) (int, error) { + return fmt.Fprintf(w, headerFmt, v) +} diff --git a/go/src/internal/txtar/archive.go b/go/src/internal/txtar/archive.go new file mode 100644 index 0000000000000000000000000000000000000000..fd95f1e64a1b43f890b001e7e07d0d2e4abd12f3 --- /dev/null +++ b/go/src/internal/txtar/archive.go @@ -0,0 +1,140 @@ +// 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 txtar implements a trivial text-based file archive format. +// +// The goals for the format are: +// +// - be trivial enough to create and edit by hand. +// - be able to store trees of text files describing go command test cases. +// - diff nicely in git history and code reviews. +// +// Non-goals include being a completely general archive format, +// storing binary data, storing file modes, storing special files like +// symbolic links, and so on. +// +// # Txtar format +// +// A txtar archive is zero or more comment lines and then a sequence of file entries. +// Each file entry begins with a file marker line of the form "-- FILENAME --" +// and is followed by zero or more file content lines making up the file data. +// The comment or file content ends at the next file marker line. +// The file marker line must begin with the three-byte sequence "-- " +// and end with the three-byte sequence " --", but the enclosed +// file name can be surrounding by additional white space, +// all of which is stripped. +// +// If the txtar file is missing a trailing newline on the final line, +// parsers should consider a final newline to be present anyway. +// +// There are no possible syntax errors in a txtar archive. +package txtar + +import ( + "bytes" + "fmt" + "os" + "strings" +) + +// An Archive is a collection of files. +type Archive struct { + Comment []byte + Files []File +} + +// A File is a single file in an archive. +type File struct { + Name string // name of file ("foo/bar.txt") + Data []byte // text content of file +} + +// Format returns the serialized form of an Archive. +// It is assumed that the Archive data structure is well-formed: +// a.Comment and all a.File[i].Data contain no file marker lines, +// and all a.File[i].Name is non-empty. +func Format(a *Archive) []byte { + var buf bytes.Buffer + buf.Write(fixNL(a.Comment)) + for _, f := range a.Files { + fmt.Fprintf(&buf, "-- %s --\n", f.Name) + buf.Write(fixNL(f.Data)) + } + return buf.Bytes() +} + +// ParseFile parses the named file as an archive. +func ParseFile(file string) (*Archive, error) { + data, err := os.ReadFile(file) + if err != nil { + return nil, err + } + return Parse(data), nil +} + +// Parse parses the serialized form of an Archive. +// The returned Archive holds slices of data. +func Parse(data []byte) *Archive { + a := new(Archive) + var name string + a.Comment, name, data = findFileMarker(data) + for name != "" { + f := File{name, nil} + f.Data, name, data = findFileMarker(data) + a.Files = append(a.Files, f) + } + return a +} + +var ( + newlineMarker = []byte("\n-- ") + marker = []byte("-- ") + markerEnd = []byte(" --") +) + +// findFileMarker finds the next file marker in data, +// extracts the file name, and returns the data before the marker, +// the file name, and the data after the marker. +// If there is no next marker, findFileMarker returns before = fixNL(data), name = "", after = nil. +func findFileMarker(data []byte) (before []byte, name string, after []byte) { + var i int + for { + if name, after = isMarker(data[i:]); name != "" { + return data[:i], name, after + } + j := bytes.Index(data[i:], newlineMarker) + if j < 0 { + return fixNL(data), "", nil + } + i += j + 1 // positioned at start of new possible marker + } +} + +// isMarker checks whether data begins with a file marker line. +// If so, it returns the name from the line and the data after the line. +// Otherwise it returns name == "" with an unspecified after. +func isMarker(data []byte) (name string, after []byte) { + if !bytes.HasPrefix(data, marker) { + return "", nil + } + if i := bytes.IndexByte(data, '\n'); i >= 0 { + data, after = data[:i], data[i+1:] + } + if !(bytes.HasSuffix(data, markerEnd) && len(data) >= len(marker)+len(markerEnd)) { + return "", nil + } + return strings.TrimSpace(string(data[len(marker) : len(data)-len(markerEnd)])), after +} + +// If data is empty or ends in \n, fixNL returns data. +// Otherwise fixNL returns a new slice consisting of data with a final \n added. +func fixNL(data []byte) []byte { + if len(data) == 0 || data[len(data)-1] == '\n' { + return data + } + d := make([]byte, len(data)+1) + copy(d, data) + d[len(data)] = '\n' + return d +} diff --git a/go/src/internal/types/errors/code_string.go b/go/src/internal/types/errors/code_string.go new file mode 100644 index 0000000000000000000000000000000000000000..26d7b48ee78a6357a2d7388dbb2efa6b03a97b7c --- /dev/null +++ b/go/src/internal/types/errors/code_string.go @@ -0,0 +1,199 @@ +// Code generated by "stringer -type Code codes.go"; DO NOT EDIT. + +package errors + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[InvalidSyntaxTree - -1] + _ = x[Test-1] + _ = x[BlankPkgName-2] + _ = x[MismatchedPkgName-3] + _ = x[InvalidPkgUse-4] + _ = x[BadImportPath-5] + _ = x[BrokenImport-6] + _ = x[ImportCRenamed-7] + _ = x[UnusedImport-8] + _ = x[InvalidInitCycle-9] + _ = x[DuplicateDecl-10] + _ = x[InvalidDeclCycle-11] + _ = x[InvalidTypeCycle-12] + _ = x[InvalidConstInit-13] + _ = x[InvalidConstVal-14] + _ = x[InvalidConstType-15] + _ = x[UntypedNilUse-16] + _ = x[WrongAssignCount-17] + _ = x[UnassignableOperand-18] + _ = x[NoNewVar-19] + _ = x[MultiValAssignOp-20] + _ = x[InvalidIfaceAssign-21] + _ = x[InvalidChanAssign-22] + _ = x[IncompatibleAssign-23] + _ = x[UnaddressableFieldAssign-24] + _ = x[NotAType-25] + _ = x[InvalidArrayLen-26] + _ = x[BlankIfaceMethod-27] + _ = x[IncomparableMapKey-28] + _ = x[InvalidPtrEmbed-30] + _ = x[BadRecv-31] + _ = x[InvalidRecv-32] + _ = x[DuplicateFieldAndMethod-33] + _ = x[DuplicateMethod-34] + _ = x[InvalidBlank-35] + _ = x[InvalidIota-36] + _ = x[MissingInitBody-37] + _ = x[InvalidInitSig-38] + _ = x[InvalidInitDecl-39] + _ = x[InvalidMainDecl-40] + _ = x[TooManyValues-41] + _ = x[NotAnExpr-42] + _ = x[TruncatedFloat-43] + _ = x[NumericOverflow-44] + _ = x[UndefinedOp-45] + _ = x[MismatchedTypes-46] + _ = x[DivByZero-47] + _ = x[NonNumericIncDec-48] + _ = x[UnaddressableOperand-49] + _ = x[InvalidIndirection-50] + _ = x[NonIndexableOperand-51] + _ = x[InvalidIndex-52] + _ = x[SwappedSliceIndices-53] + _ = x[NonSliceableOperand-54] + _ = x[InvalidSliceExpr-55] + _ = x[InvalidShiftCount-56] + _ = x[InvalidShiftOperand-57] + _ = x[InvalidReceive-58] + _ = x[InvalidSend-59] + _ = x[DuplicateLitKey-60] + _ = x[MissingLitKey-61] + _ = x[InvalidLitIndex-62] + _ = x[OversizeArrayLit-63] + _ = x[MixedStructLit-64] + _ = x[InvalidStructLit-65] + _ = x[MissingLitField-66] + _ = x[DuplicateLitField-67] + _ = x[UnexportedLitField-68] + _ = x[InvalidLitField-69] + _ = x[UntypedLit-70] + _ = x[InvalidLit-71] + _ = x[AmbiguousSelector-72] + _ = x[UndeclaredImportedName-73] + _ = x[UnexportedName-74] + _ = x[UndeclaredName-75] + _ = x[MissingFieldOrMethod-76] + _ = x[BadDotDotDotSyntax-77] + _ = x[NonVariadicDotDotDot-78] + _ = x[InvalidDotDotDot-81] + _ = x[UncalledBuiltin-82] + _ = x[InvalidAppend-83] + _ = x[InvalidCap-84] + _ = x[InvalidClose-85] + _ = x[InvalidCopy-86] + _ = x[InvalidComplex-87] + _ = x[InvalidDelete-88] + _ = x[InvalidImag-89] + _ = x[InvalidLen-90] + _ = x[SwappedMakeArgs-91] + _ = x[InvalidMake-92] + _ = x[InvalidReal-93] + _ = x[InvalidAssert-94] + _ = x[ImpossibleAssert-95] + _ = x[InvalidConversion-96] + _ = x[InvalidUntypedConversion-97] + _ = x[BadOffsetofSyntax-98] + _ = x[InvalidOffsetof-99] + _ = x[UnusedExpr-100] + _ = x[UnusedVar-101] + _ = x[MissingReturn-102] + _ = x[WrongResultCount-103] + _ = x[OutOfScopeResult-104] + _ = x[InvalidCond-105] + _ = x[InvalidPostDecl-106] + _ = x[InvalidIterVar-108] + _ = x[InvalidRangeExpr-109] + _ = x[MisplacedBreak-110] + _ = x[MisplacedContinue-111] + _ = x[MisplacedFallthrough-112] + _ = x[DuplicateCase-113] + _ = x[DuplicateDefault-114] + _ = x[BadTypeKeyword-115] + _ = x[InvalidTypeSwitch-116] + _ = x[InvalidExprSwitch-117] + _ = x[InvalidSelectCase-118] + _ = x[UndeclaredLabel-119] + _ = x[DuplicateLabel-120] + _ = x[MisplacedLabel-121] + _ = x[UnusedLabel-122] + _ = x[JumpOverDecl-123] + _ = x[JumpIntoBlock-124] + _ = x[InvalidMethodExpr-125] + _ = x[WrongArgCount-126] + _ = x[InvalidCall-127] + _ = x[UnusedResults-128] + _ = x[InvalidDefer-129] + _ = x[InvalidGo-130] + _ = x[BadDecl-131] + _ = x[RepeatedDecl-132] + _ = x[InvalidUnsafeAdd-133] + _ = x[InvalidUnsafeSlice-134] + _ = x[UnsupportedFeature-135] + _ = x[NotAGenericType-136] + _ = x[WrongTypeArgCount-137] + _ = x[CannotInferTypeArgs-138] + _ = x[InvalidTypeArg-139] + _ = x[InvalidInstanceCycle-140] + _ = x[InvalidUnion-141] + _ = x[MisplacedConstraintIface-142] + _ = x[InvalidMethodTypeParams-143] + _ = x[MisplacedTypeParam-144] + _ = x[InvalidUnsafeSliceData-145] + _ = x[InvalidUnsafeString-146] + _ = x[InvalidClear-148] + _ = x[TypeTooLarge-149] + _ = x[InvalidMinMaxOperand-150] + _ = x[TooNew-151] +} + +const ( + _Code_name_0 = "InvalidSyntaxTree" + _Code_name_1 = "TestBlankPkgNameMismatchedPkgNameInvalidPkgUseBadImportPathBrokenImportImportCRenamedUnusedImportInvalidInitCycleDuplicateDeclInvalidDeclCycleInvalidTypeCycleInvalidConstInitInvalidConstValInvalidConstTypeUntypedNilUseWrongAssignCountUnassignableOperandNoNewVarMultiValAssignOpInvalidIfaceAssignInvalidChanAssignIncompatibleAssignUnaddressableFieldAssignNotATypeInvalidArrayLenBlankIfaceMethodIncomparableMapKey" + _Code_name_2 = "InvalidPtrEmbedBadRecvInvalidRecvDuplicateFieldAndMethodDuplicateMethodInvalidBlankInvalidIotaMissingInitBodyInvalidInitSigInvalidInitDeclInvalidMainDeclTooManyValuesNotAnExprTruncatedFloatNumericOverflowUndefinedOpMismatchedTypesDivByZeroNonNumericIncDecUnaddressableOperandInvalidIndirectionNonIndexableOperandInvalidIndexSwappedSliceIndicesNonSliceableOperandInvalidSliceExprInvalidShiftCountInvalidShiftOperandInvalidReceiveInvalidSendDuplicateLitKeyMissingLitKeyInvalidLitIndexOversizeArrayLitMixedStructLitInvalidStructLitMissingLitFieldDuplicateLitFieldUnexportedLitFieldInvalidLitFieldUntypedLitInvalidLitAmbiguousSelectorUndeclaredImportedNameUnexportedNameUndeclaredNameMissingFieldOrMethodBadDotDotDotSyntaxNonVariadicDotDotDot" + _Code_name_3 = "InvalidDotDotDotUncalledBuiltinInvalidAppendInvalidCapInvalidCloseInvalidCopyInvalidComplexInvalidDeleteInvalidImagInvalidLenSwappedMakeArgsInvalidMakeInvalidRealInvalidAssertImpossibleAssertInvalidConversionInvalidUntypedConversionBadOffsetofSyntaxInvalidOffsetofUnusedExprUnusedVarMissingReturnWrongResultCountOutOfScopeResultInvalidCondInvalidPostDecl" + _Code_name_4 = "InvalidIterVarInvalidRangeExprMisplacedBreakMisplacedContinueMisplacedFallthroughDuplicateCaseDuplicateDefaultBadTypeKeywordInvalidTypeSwitchInvalidExprSwitchInvalidSelectCaseUndeclaredLabelDuplicateLabelMisplacedLabelUnusedLabelJumpOverDeclJumpIntoBlockInvalidMethodExprWrongArgCountInvalidCallUnusedResultsInvalidDeferInvalidGoBadDeclRepeatedDeclInvalidUnsafeAddInvalidUnsafeSliceUnsupportedFeatureNotAGenericTypeWrongTypeArgCountCannotInferTypeArgsInvalidTypeArgInvalidInstanceCycleInvalidUnionMisplacedConstraintIfaceInvalidMethodTypeParamsMisplacedTypeParamInvalidUnsafeSliceDataInvalidUnsafeString" + _Code_name_5 = "InvalidClearTypeTooLargeInvalidMinMaxOperandTooNew" +) + +var ( + _Code_index_1 = [...]uint16{0, 4, 16, 33, 46, 59, 71, 85, 97, 113, 126, 142, 158, 174, 189, 205, 218, 234, 253, 261, 277, 295, 312, 330, 354, 362, 377, 393, 411} + _Code_index_2 = [...]uint16{0, 15, 22, 33, 56, 71, 83, 94, 109, 123, 138, 153, 166, 175, 189, 204, 215, 230, 239, 255, 275, 293, 312, 324, 343, 362, 378, 395, 414, 428, 439, 454, 467, 482, 498, 512, 528, 543, 560, 578, 593, 603, 613, 630, 652, 666, 680, 700, 718, 738} + _Code_index_3 = [...]uint16{0, 16, 31, 44, 54, 66, 77, 91, 104, 115, 125, 140, 151, 162, 175, 191, 208, 232, 249, 264, 274, 283, 296, 312, 328, 339, 354} + _Code_index_4 = [...]uint16{0, 14, 30, 44, 61, 81, 94, 110, 124, 141, 158, 175, 190, 204, 218, 229, 241, 254, 271, 284, 295, 308, 320, 329, 336, 348, 364, 382, 400, 415, 432, 451, 465, 485, 497, 521, 544, 562, 584, 603} + _Code_index_5 = [...]uint8{0, 12, 24, 44, 50} +) + +func (i Code) String() string { + switch { + case i == -1: + return _Code_name_0 + case 1 <= i && i <= 28: + i -= 1 + return _Code_name_1[_Code_index_1[i]:_Code_index_1[i+1]] + case 30 <= i && i <= 78: + i -= 30 + return _Code_name_2[_Code_index_2[i]:_Code_index_2[i+1]] + case 81 <= i && i <= 106: + i -= 81 + return _Code_name_3[_Code_index_3[i]:_Code_index_3[i+1]] + case 108 <= i && i <= 146: + i -= 108 + return _Code_name_4[_Code_index_4[i]:_Code_index_4[i+1]] + case 148 <= i && i <= 151: + i -= 148 + return _Code_name_5[_Code_index_5[i]:_Code_index_5[i+1]] + default: + return "Code(" + strconv.FormatInt(int64(i), 10) + ")" + } +} diff --git a/go/src/internal/types/errors/codes.go b/go/src/internal/types/errors/codes.go new file mode 100644 index 0000000000000000000000000000000000000000..5b68cc3af7a57e2751d2c485bdd6cb201e5ecfc9 --- /dev/null +++ b/go/src/internal/types/errors/codes.go @@ -0,0 +1,1485 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors + +//go:generate go run golang.org/x/tools/cmd/stringer@latest -type Code codes.go + +type Code int + +// This file defines the error codes that can be produced during type-checking. +// Collectively, these codes provide an identifier that may be used to +// implement special handling for certain types of errors. +// +// Error code values should not be changed: add new codes at the end. +// +// Error codes should be fine-grained enough that the exact nature of the error +// can be easily determined, but coarse enough that they are not an +// implementation detail of the type checking algorithm. As a rule-of-thumb, +// errors should be considered equivalent if there is a theoretical refactoring +// of the type checker in which they are emitted in exactly one place. For +// example, the type checker emits different error messages for "too many +// arguments" and "too few arguments", but one can imagine an alternative type +// checker where this check instead just emits a single "wrong number of +// arguments", so these errors should have the same code. +// +// Error code names should be as brief as possible while retaining accuracy and +// distinctiveness. In most cases names should start with an adjective +// describing the nature of the error (e.g. "invalid", "unused", "misplaced"), +// and end with a noun identifying the relevant language object. For example, +// "_DuplicateDecl" or "_InvalidSliceExpr". For brevity, naming follows the +// convention that "bad" implies a problem with syntax, and "invalid" implies a +// problem with types. + +const ( + // InvalidSyntaxTree occurs if an invalid syntax tree is provided + // to the type checker. It should never happen. + InvalidSyntaxTree Code = -1 +) + +const ( + // The zero Code value indicates an unset (invalid) error code. + _ Code = iota + + // Test is reserved for errors that only apply while in self-test mode. + Test + + // BlankPkgName occurs when a package name is the blank identifier "_". + // + // Per the spec: + // "The PackageName must not be the blank identifier." + // + // Example: + // package _ + BlankPkgName + + // MismatchedPkgName occurs when a file's package name doesn't match the + // package name already established by other files. + MismatchedPkgName + + // InvalidPkgUse occurs when a package identifier is used outside of a + // selector expression. + // + // Example: + // import "fmt" + // + // var _ = fmt + InvalidPkgUse + + // BadImportPath occurs when an import path is not valid. + BadImportPath + + // BrokenImport occurs when importing a package fails. + // + // Example: + // import "amissingpackage" + BrokenImport + + // ImportCRenamed occurs when the special import "C" is renamed. "C" is a + // pseudo-package, and must not be renamed. + // + // Example: + // import _ "C" + ImportCRenamed + + // UnusedImport occurs when an import is unused. + // + // Example: + // import "fmt" + // + // func main() {} + UnusedImport + + // InvalidInitCycle occurs when an invalid cycle is detected within the + // initialization graph. + // + // Example: + // var x int = f() + // + // func f() int { return x } + InvalidInitCycle + + // DuplicateDecl occurs when an identifier is declared multiple times. + // + // Example: + // var x = 1 + // var x = 2 + DuplicateDecl + + // InvalidDeclCycle occurs when a declaration cycle is not valid. + // + // Example: + // type S struct { + // S + // } + // + // Example: + // import "unsafe" + // + // type T [unsafe.Sizeof(T{})]int + InvalidDeclCycle + + // TODO(markfreeman): Retire InvalidTypeCycle, as it's never emitted. + + // InvalidTypeCycle occurs when a cycle in type definitions results in a + // type that is not well-defined. + InvalidTypeCycle + + // InvalidConstInit occurs when a const declaration has a non-constant + // initializer. + // + // Example: + // var x int + // const _ = x + InvalidConstInit + + // InvalidConstVal occurs when a const value cannot be converted to its + // target type. + // + // TODO(findleyr): this error code and example are not very clear. Consider + // removing it. + // + // Example: + // const _ = 1 << "hello" + InvalidConstVal + + // InvalidConstType occurs when the underlying type in a const declaration + // is not a valid constant type. + // + // Example: + // const c *int = 4 + InvalidConstType + + // UntypedNilUse occurs when the predeclared (untyped) value nil is used to + // initialize a variable declared without an explicit type. + // + // Example: + // var x = nil + UntypedNilUse + + // WrongAssignCount occurs when the number of values on the right-hand side + // of an assignment or initialization expression does not match the number + // of variables on the left-hand side. + // + // Example: + // var x = 1, 2 + WrongAssignCount + + // UnassignableOperand occurs when the left-hand side of an assignment is + // not assignable. + // + // Example: + // func f() { + // const c = 1 + // c = 2 + // } + UnassignableOperand + + // NoNewVar occurs when a short variable declaration (':=') does not declare + // new variables. + // + // Example: + // func f() { + // x := 1 + // x := 2 + // } + NoNewVar + + // MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does + // not have single-valued left-hand or right-hand side. + // + // Per the spec: + // "In assignment operations, both the left- and right-hand expression lists + // must contain exactly one single-valued expression" + // + // Example: + // func f() int { + // x, y := 1, 2 + // x, y += 1 + // return x + y + // } + MultiValAssignOp + + // InvalidIfaceAssign occurs when a value of type T is used as an + // interface, but T does not implement a method of the expected interface. + // + // Example: + // type I interface { + // f() + // } + // + // type T int + // + // var x I = T(1) + InvalidIfaceAssign + + // InvalidChanAssign occurs when a chan assignment is invalid. + // + // Per the spec, a value x is assignable to a channel type T if: + // "x is a bidirectional channel value, T is a channel type, x's type V and + // T have identical element types, and at least one of V or T is not a + // defined type." + // + // Example: + // type T1 chan int + // type T2 chan int + // + // var x T1 + // // Invalid assignment because both types are named + // var _ T2 = x + InvalidChanAssign + + // IncompatibleAssign occurs when the type of the right-hand side expression + // in an assignment cannot be assigned to the type of the variable being + // assigned. + // + // Example: + // var x []int + // var _ int = x + IncompatibleAssign + + // UnaddressableFieldAssign occurs when trying to assign to a struct field + // in a map value. + // + // Example: + // func f() { + // m := make(map[string]struct{i int}) + // m["foo"].i = 42 + // } + UnaddressableFieldAssign + + // NotAType occurs when the identifier used as the underlying type in a type + // declaration or the right-hand side of a type alias does not denote a type. + // + // Example: + // var S = 2 + // + // type T S + NotAType + + // InvalidArrayLen occurs when an array length is not a constant value. + // + // Example: + // var n = 3 + // var _ = [n]int{} + InvalidArrayLen + + // BlankIfaceMethod occurs when a method name is '_'. + // + // Per the spec: + // "The name of each explicitly specified method must be unique and not + // blank." + // + // Example: + // type T interface { + // _(int) + // } + BlankIfaceMethod + + // IncomparableMapKey occurs when a map key type does not support the == and + // != operators. + // + // Per the spec: + // "The comparison operators == and != must be fully defined for operands of + // the key type; thus the key type must not be a function, map, or slice." + // + // Example: + // var x map[T]int + // + // type T []int + IncomparableMapKey + + // InvalidIfaceEmbed occurs when a non-interface type is embedded in an + // interface (for go 1.17 or earlier). + _ // not used anymore + + // InvalidPtrEmbed occurs when an embedded field is of the pointer form *T, + // and T itself is itself a pointer, an unsafe.Pointer, or an interface. + // + // Per the spec: + // "An embedded field must be specified as a type name T or as a pointer to + // a non-interface type name *T, and T itself may not be a pointer type." + // + // Example: + // type T *int + // + // type S struct { + // *T + // } + InvalidPtrEmbed + + // BadRecv occurs when a method declaration does not have exactly one + // receiver parameter. + // + // Example: + // func () _() {} + BadRecv + + // InvalidRecv occurs when a receiver type expression is not of the form T + // or *T, or T is a pointer type. + // + // Example: + // type T struct {} + // + // func (**T) m() {} + InvalidRecv + + // DuplicateFieldAndMethod occurs when an identifier appears as both a field + // and method name. + // + // Example: + // type T struct { + // m int + // } + // + // func (T) m() {} + DuplicateFieldAndMethod + + // DuplicateMethod occurs when two methods on the same receiver type have + // the same name. + // + // Example: + // type T struct {} + // func (T) m() {} + // func (T) m(i int) int { return i } + DuplicateMethod + + // InvalidBlank occurs when a blank identifier is used as a value or type. + // + // Per the spec: + // "The blank identifier may appear as an operand only on the left-hand side + // of an assignment." + // + // Example: + // var x = _ + InvalidBlank + + // InvalidIota occurs when the predeclared identifier iota is used outside + // of a constant declaration. + // + // Example: + // var x = iota + InvalidIota + + // MissingInitBody occurs when an init function is missing its body. + // + // Example: + // func init() + MissingInitBody + + // InvalidInitSig occurs when an init function declares parameters or + // results. + // + // Deprecated: no longer emitted by the type checker. _InvalidInitDecl is + // used instead. + InvalidInitSig + + // InvalidInitDecl occurs when init is declared as anything other than a + // function. + // + // Example: + // var init = 1 + // + // Example: + // func init() int { return 1 } + InvalidInitDecl + + // InvalidMainDecl occurs when main is declared as anything other than a + // function, in a main package. + InvalidMainDecl + + // TooManyValues occurs when a function returns too many values for the + // expression context in which it is used. + // + // Example: + // func ReturnTwo() (int, int) { + // return 1, 2 + // } + // + // var x = ReturnTwo() + TooManyValues + + // NotAnExpr occurs when a type expression is used where a value expression + // is expected. + // + // Example: + // type T struct {} + // + // func f() { + // T + // } + NotAnExpr + + // TruncatedFloat occurs when a float constant is truncated to an integer + // value. + // + // Example: + // var _ int = 98.6 + TruncatedFloat + + // NumericOverflow occurs when a numeric constant overflows its target type. + // + // Example: + // var x int8 = 1000 + NumericOverflow + + // UndefinedOp occurs when an operator is not defined for the type(s) used + // in an operation. + // + // Example: + // var c = "a" - "b" + UndefinedOp + + // MismatchedTypes occurs when operand types are incompatible in a binary + // operation. + // + // Example: + // var a = "hello" + // var b = 1 + // var c = a - b + MismatchedTypes + + // DivByZero occurs when a division operation is provable at compile + // time to be a division by zero. + // + // Example: + // const divisor = 0 + // var x int = 1/divisor + DivByZero + + // NonNumericIncDec occurs when an increment or decrement operator is + // applied to a non-numeric value. + // + // Example: + // func f() { + // var c = "c" + // c++ + // } + NonNumericIncDec + + // UnaddressableOperand occurs when the & operator is applied to an + // unaddressable expression. + // + // Example: + // var x = &1 + UnaddressableOperand + + // InvalidIndirection occurs when a non-pointer value is indirected via the + // '*' operator. + // + // Example: + // var x int + // var y = *x + InvalidIndirection + + // NonIndexableOperand occurs when an index operation is applied to a value + // that cannot be indexed. + // + // Example: + // var x = 1 + // var y = x[1] + NonIndexableOperand + + // InvalidIndex occurs when an index argument is not of integer type, + // negative, or out-of-bounds. + // + // Example: + // var s = [...]int{1,2,3} + // var x = s[5] + // + // Example: + // var s = []int{1,2,3} + // var _ = s[-1] + // + // Example: + // var s = []int{1,2,3} + // var i string + // var _ = s[i] + InvalidIndex + + // SwappedSliceIndices occurs when constant indices in a slice expression + // are decreasing in value. + // + // Example: + // var _ = []int{1,2,3}[2:1] + SwappedSliceIndices + + // NonSliceableOperand occurs when a slice operation is applied to a value + // whose type is not sliceable, or is unaddressable. + // + // Example: + // var x = [...]int{1, 2, 3}[:1] + // + // Example: + // var x = 1 + // var y = 1[:1] + NonSliceableOperand + + // InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is + // applied to a string. + // + // Example: + // var s = "hello" + // var x = s[1:2:3] + InvalidSliceExpr + + // InvalidShiftCount occurs when the right-hand side of a shift operation is + // either non-integer, negative, or too large. + // + // Example: + // var ( + // x string + // y int = 1 << x + // ) + InvalidShiftCount + + // InvalidShiftOperand occurs when the shifted operand is not an integer. + // + // Example: + // var s = "hello" + // var x = s << 2 + InvalidShiftOperand + + // InvalidReceive occurs when there is a channel receive from a value that + // is either not a channel, or is a send-only channel. + // + // Example: + // func f() { + // var x = 1 + // <-x + // } + InvalidReceive + + // InvalidSend occurs when there is a channel send to a value that is not a + // channel, or is a receive-only channel. + // + // Example: + // func f() { + // var x = 1 + // x <- "hello!" + // } + InvalidSend + + // DuplicateLitKey occurs when an index is duplicated in a slice, array, or + // map literal. + // + // Example: + // var _ = []int{0:1, 0:2} + // + // Example: + // var _ = map[string]int{"a": 1, "a": 2} + DuplicateLitKey + + // MissingLitKey occurs when a map literal is missing a key expression. + // + // Example: + // var _ = map[string]int{1} + MissingLitKey + + // InvalidLitIndex occurs when the key in a key-value element of a slice or + // array literal is not an integer constant. + // + // Example: + // var i = 0 + // var x = []string{i: "world"} + InvalidLitIndex + + // OversizeArrayLit occurs when an array literal exceeds its length. + // + // Example: + // var _ = [2]int{1,2,3} + OversizeArrayLit + + // MixedStructLit occurs when a struct literal contains a mix of positional + // and named elements. + // + // Example: + // var _ = struct{i, j int}{i: 1, 2} + MixedStructLit + + // InvalidStructLit occurs when a positional struct literal has an incorrect + // number of values. + // + // Example: + // var _ = struct{i, j int}{1,2,3} + InvalidStructLit + + // MissingLitField occurs when a struct literal refers to a field that does + // not exist on the struct type. + // + // Example: + // var _ = struct{i int}{j: 2} + MissingLitField + + // DuplicateLitField occurs when a struct literal contains duplicated + // fields. + // + // Example: + // var _ = struct{i int}{i: 1, i: 2} + DuplicateLitField + + // UnexportedLitField occurs when a positional struct literal implicitly + // assigns an unexported field of an imported type. + UnexportedLitField + + // InvalidLitField occurs when a field name is not a valid identifier. + // + // Example: + // var _ = struct{i int}{1: 1} + InvalidLitField + + // UntypedLit occurs when a composite literal omits a required type + // identifier. + // + // Example: + // type outer struct{ + // inner struct { i int } + // } + // + // var _ = outer{inner: {1}} + UntypedLit + + // InvalidLit occurs when a composite literal expression does not match its + // type. + // + // Example: + // type P *struct{ + // x int + // } + // var _ = P {} + InvalidLit + + // AmbiguousSelector occurs when a selector is ambiguous. + // + // Example: + // type E1 struct { i int } + // type E2 struct { i int } + // type T struct { E1; E2 } + // + // var x T + // var _ = x.i + AmbiguousSelector + + // UndeclaredImportedName occurs when a package-qualified identifier is + // undeclared by the imported package. + // + // Example: + // import "go/types" + // + // var _ = types.NotAnActualIdentifier + UndeclaredImportedName + + // UnexportedName occurs when a selector refers to an unexported identifier + // of an imported package. + // + // Example: + // import "reflect" + // + // type _ reflect.flag + UnexportedName + + // UndeclaredName occurs when an identifier is not declared in the current + // scope. + // + // Example: + // var x T + UndeclaredName + + // MissingFieldOrMethod occurs when a selector references a field or method + // that does not exist. + // + // Example: + // type T struct {} + // + // var x = T{}.f + MissingFieldOrMethod + + // BadDotDotDotSyntax occurs when a "..." occurs in a context where it is + // not valid. + // + // Example: + // var _ = map[int][...]int{0: {}} + BadDotDotDotSyntax + + // NonVariadicDotDotDot occurs when a "..." is used on the final argument to + // a non-variadic function. + // + // Example: + // func printArgs(s []string) { + // for _, a := range s { + // println(a) + // } + // } + // + // func f() { + // s := []string{"a", "b", "c"} + // printArgs(s...) + // } + NonVariadicDotDotDot + + // MisplacedDotDotDot occurs when a "..." is used somewhere other than the + // final argument in a function declaration. + _ // not used anymore (error reported by parser) + + _ // InvalidDotDotDotOperand was removed. + + // InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in + // function. + // + // Example: + // var s = []int{1, 2, 3} + // var l = len(s...) + InvalidDotDotDot + + // UncalledBuiltin occurs when a built-in function is used as a + // function-valued expression, instead of being called. + // + // Per the spec: + // "The built-in functions do not have standard Go types, so they can only + // appear in call expressions; they cannot be used as function values." + // + // Example: + // var _ = copy + UncalledBuiltin + + // InvalidAppend occurs when append is called with a first argument that is + // not a slice. + // + // Example: + // var _ = append(1, 2) + InvalidAppend + + // InvalidCap occurs when an argument to the cap built-in function is not of + // supported type. + // + // See https://golang.org/ref/spec#Length_and_capacity for information on + // which underlying types are supported as arguments to cap and len. + // + // Example: + // var s = 2 + // var x = cap(s) + InvalidCap + + // InvalidClose occurs when close(...) is called with an argument that is + // not of channel type, or that is a receive-only channel. + // + // Example: + // func f() { + // var x int + // close(x) + // } + InvalidClose + + // InvalidCopy occurs when the arguments are not of slice type or do not + // have compatible type. + // + // See https://golang.org/ref/spec#Appending_and_copying_slices for more + // information on the type requirements for the copy built-in. + // + // Example: + // func f() { + // var x []int + // y := []int64{1,2,3} + // copy(x, y) + // } + InvalidCopy + + // InvalidComplex occurs when the complex built-in function is called with + // arguments with incompatible types. + // + // Example: + // var _ = complex(float32(1), float64(2)) + InvalidComplex + + // InvalidDelete occurs when the delete built-in function is called with a + // first argument that is not a map. + // + // Example: + // func f() { + // m := "hello" + // delete(m, "e") + // } + InvalidDelete + + // InvalidImag occurs when the imag built-in function is called with an + // argument that does not have complex type. + // + // Example: + // var _ = imag(int(1)) + InvalidImag + + // InvalidLen occurs when an argument to the len built-in function is not of + // supported type. + // + // See https://golang.org/ref/spec#Length_and_capacity for information on + // which underlying types are supported as arguments to cap and len. + // + // Example: + // var s = 2 + // var x = len(s) + InvalidLen + + // SwappedMakeArgs occurs when make is called with three arguments, and its + // length argument is larger than its capacity argument. + // + // Example: + // var x = make([]int, 3, 2) + SwappedMakeArgs + + // InvalidMake occurs when make is called with an unsupported type argument. + // + // See https://golang.org/ref/spec#Making_slices_maps_and_channels for + // information on the types that may be created using make. + // + // Example: + // var x = make(int) + InvalidMake + + // InvalidReal occurs when the real built-in function is called with an + // argument that does not have complex type. + // + // Example: + // var _ = real(int(1)) + InvalidReal + + // InvalidAssert occurs when a type assertion is applied to a + // value that is not of interface type. + // + // Example: + // var x = 1 + // var _ = x.(float64) + InvalidAssert + + // ImpossibleAssert occurs for a type assertion x.(T) when the value x of + // interface cannot have dynamic type T, due to a missing or mismatching + // method on T. + // + // Example: + // type T int + // + // func (t *T) m() int { return int(*t) } + // + // type I interface { m() int } + // + // var x I + // var _ = x.(T) + ImpossibleAssert + + // InvalidConversion occurs when the argument type cannot be converted to the + // target. + // + // See https://golang.org/ref/spec#Conversions for the rules of + // convertibility. + // + // Example: + // var x float64 + // var _ = string(x) + InvalidConversion + + // InvalidUntypedConversion occurs when there is no valid implicit + // conversion from an untyped value satisfying the type constraints of the + // context in which it is used. + // + // Example: + // func f[T ~int8 | ~int16 | ~int32 | ~int64](x T) T { + // return x + 1024 + // } + InvalidUntypedConversion + + // BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument + // that is not a selector expression. + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Offsetof(x) + BadOffsetofSyntax + + // InvalidOffsetof occurs when unsafe.Offsetof is called with a method + // selector, rather than a field selector, or when the field is embedded via + // a pointer. + // + // Per the spec: + // + // "If f is an embedded field, it must be reachable without pointer + // indirections through fields of the struct. " + // + // Example: + // import "unsafe" + // + // type T struct { f int } + // type S struct { *T } + // var s S + // var _ = unsafe.Offsetof(s.f) + // + // Example: + // import "unsafe" + // + // type S struct{} + // + // func (S) m() {} + // + // var s S + // var _ = unsafe.Offsetof(s.m) + InvalidOffsetof + + // UnusedExpr occurs when a side-effect free expression is used as a + // statement. Such a statement has no effect. + // + // Example: + // func f(i int) { + // i*i + // } + UnusedExpr + + // UnusedVar occurs when a variable is declared but unused. + // + // Example: + // func f() { + // x := 1 + // } + UnusedVar + + // MissingReturn occurs when a function with results is missing a return + // statement. + // + // Example: + // func f() int {} + MissingReturn + + // WrongResultCount occurs when a return statement returns an incorrect + // number of values. + // + // Example: + // func ReturnOne() int { + // return 1, 2 + // } + WrongResultCount + + // OutOfScopeResult occurs when the name of a value implicitly returned by + // an empty return statement is shadowed in a nested scope. + // + // Example: + // func factor(n int) (i int) { + // for i := 2; i < n; i++ { + // if n%i == 0 { + // return + // } + // } + // return 0 + // } + OutOfScopeResult + + // InvalidCond occurs when an if condition is not a boolean expression. + // + // Example: + // func checkReturn(i int) { + // if i { + // panic("non-zero return") + // } + // } + InvalidCond + + // InvalidPostDecl occurs when there is a declaration in a for-loop post + // statement. + // + // Example: + // func f() { + // for i := 0; i < 10; j := 0 {} + // } + InvalidPostDecl + + _ // InvalidChanRange was removed. + + // InvalidIterVar occurs when two iteration variables are used while ranging + // over a channel. + // + // Example: + // func f(c chan int) { + // for k, v := range c { + // println(k, v) + // } + // } + InvalidIterVar + + // InvalidRangeExpr occurs when the type of a range expression is not + // a valid type for use with a range loop. + // + // Example: + // func f(f float64) { + // for j := range f { + // println(j) + // } + // } + InvalidRangeExpr + + // MisplacedBreak occurs when a break statement is not within a for, switch, + // or select statement of the innermost function definition. + // + // Example: + // func f() { + // break + // } + MisplacedBreak + + // MisplacedContinue occurs when a continue statement is not within a for + // loop of the innermost function definition. + // + // Example: + // func sumeven(n int) int { + // proceed := func() { + // continue + // } + // sum := 0 + // for i := 1; i <= n; i++ { + // if i % 2 != 0 { + // proceed() + // } + // sum += i + // } + // return sum + // } + MisplacedContinue + + // MisplacedFallthrough occurs when a fallthrough statement is not within an + // expression switch. + // + // Example: + // func typename(i interface{}) string { + // switch i.(type) { + // case int64: + // fallthrough + // case int: + // return "int" + // } + // return "unsupported" + // } + MisplacedFallthrough + + // DuplicateCase occurs when a type or expression switch has duplicate + // cases. + // + // Example: + // func printInt(i int) { + // switch i { + // case 1: + // println("one") + // case 1: + // println("One") + // } + // } + DuplicateCase + + // DuplicateDefault occurs when a type or expression switch has multiple + // default clauses. + // + // Example: + // func printInt(i int) { + // switch i { + // case 1: + // println("one") + // default: + // println("One") + // default: + // println("1") + // } + // } + DuplicateDefault + + // BadTypeKeyword occurs when a .(type) expression is used anywhere other + // than a type switch. + // + // Example: + // type I interface { + // m() + // } + // var t I + // var _ = t.(type) + BadTypeKeyword + + // InvalidTypeSwitch occurs when .(type) is used on an expression that is + // not of interface type. + // + // Example: + // func f(i int) { + // switch x := i.(type) {} + // } + InvalidTypeSwitch + + // InvalidExprSwitch occurs when a switch expression is not comparable. + // + // Example: + // func _() { + // var a struct{ _ func() } + // switch a /* ERROR cannot switch on a */ { + // } + // } + InvalidExprSwitch + + // InvalidSelectCase occurs when a select case is not a channel send or + // receive. + // + // Example: + // func checkChan(c <-chan int) bool { + // select { + // case c: + // return true + // default: + // return false + // } + // } + InvalidSelectCase + + // UndeclaredLabel occurs when an undeclared label is jumped to. + // + // Example: + // func f() { + // goto L + // } + UndeclaredLabel + + // DuplicateLabel occurs when a label is declared more than once. + // + // Example: + // func f() int { + // L: + // L: + // return 1 + // } + DuplicateLabel + + // MisplacedLabel occurs when a break or continue label is not on a for, + // switch, or select statement. + // + // Example: + // func f() { + // L: + // a := []int{1,2,3} + // for _, e := range a { + // if e > 10 { + // break L + // } + // println(a) + // } + // } + MisplacedLabel + + // UnusedLabel occurs when a label is declared and not used. + // + // Example: + // func f() { + // L: + // } + UnusedLabel + + // JumpOverDecl occurs when a label jumps over a variable declaration. + // + // Example: + // func f() int { + // goto L + // x := 2 + // L: + // x++ + // return x + // } + JumpOverDecl + + // JumpIntoBlock occurs when a forward jump goes to a label inside a nested + // block. + // + // Example: + // func f(x int) { + // goto L + // if x > 0 { + // L: + // print("inside block") + // } + // } + JumpIntoBlock + + // InvalidMethodExpr occurs when a pointer method is called but the argument + // is not addressable. + // + // Example: + // type T struct {} + // + // func (*T) m() int { return 1 } + // + // var _ = T.m(T{}) + InvalidMethodExpr + + // WrongArgCount occurs when too few or too many arguments are passed by a + // function call. + // + // Example: + // func f(i int) {} + // var x = f() + WrongArgCount + + // InvalidCall occurs when an expression is called that is not of function + // type. + // + // Example: + // var x = "x" + // var y = x() + InvalidCall + + // UnusedResults occurs when a restricted expression-only built-in function + // is suspended via go or defer. Such a suspension discards the results of + // these side-effect free built-in functions, and therefore is ineffectual. + // + // Example: + // func f(a []int) int { + // defer len(a) + // return i + // } + UnusedResults + + // InvalidDefer occurs when a deferred expression is not a function call, + // for example if the expression is a type conversion. + // + // Example: + // func f(i int) int { + // defer int32(i) + // return i + // } + InvalidDefer + + // InvalidGo occurs when a go expression is not a function call, for example + // if the expression is a type conversion. + // + // Example: + // func f(i int) int { + // go int32(i) + // return i + // } + InvalidGo + + // All codes below were added in Go 1.17. + + // BadDecl occurs when a declaration has invalid syntax. + BadDecl + + // RepeatedDecl occurs when an identifier occurs more than once on the left + // hand side of a short variable declaration. + // + // Example: + // func _() { + // x, y, y := 1, 2, 3 + // } + RepeatedDecl + + // InvalidUnsafeAdd occurs when unsafe.Add is called with a + // length argument that is not of integer type. + // It also occurs if it is used in a package compiled for a + // language version before go1.17. + // + // Example: + // import "unsafe" + // + // var p unsafe.Pointer + // var _ = unsafe.Add(p, float64(1)) + InvalidUnsafeAdd + + // InvalidUnsafeSlice occurs when unsafe.Slice is called with a + // pointer argument that is not of pointer type or a length argument + // that is not of integer type, negative, or out of bounds. + // It also occurs if it is used in a package compiled for a language + // version before go1.17. + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Slice(x, 1) + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Slice(&x, float64(1)) + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Slice(&x, -1) + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Slice(&x, uint64(1) << 63) + InvalidUnsafeSlice + + // All codes below were added in Go 1.18. + + // UnsupportedFeature occurs when a language feature is used that is not + // supported at this Go version. + UnsupportedFeature + + // NotAGenericType occurs when a non-generic type is used where a generic + // type is expected: in type or function instantiation. + // + // Example: + // type T int + // + // var _ T[int] + NotAGenericType + + // WrongTypeArgCount occurs when a type or function is instantiated with an + // incorrect number of type arguments, including when a generic type or + // function is used without instantiation. + // + // Errors involving failed type inference are assigned other error codes. + // + // Example: + // type T[p any] int + // + // var _ T[int, string] + // + // Example: + // func f[T any]() {} + // + // var x = f + WrongTypeArgCount + + // CannotInferTypeArgs occurs when type or function type argument inference + // fails to infer all type arguments. + // + // Example: + // func f[T any]() {} + // + // func _() { + // f() + // } + CannotInferTypeArgs + + // InvalidTypeArg occurs when a type argument does not satisfy its + // corresponding type parameter constraints. + // + // Example: + // type T[P ~int] struct{} + // + // var _ T[string] + InvalidTypeArg // arguments? InferenceFailed + + // InvalidInstanceCycle occurs when an invalid cycle is detected + // within the instantiation graph. + // + // Example: + // func f[T any]() { f[*T]() } + InvalidInstanceCycle + + // InvalidUnion occurs when an embedded union or approximation element is + // not valid. + // + // Example: + // type _ interface { + // ~int | interface{ m() } + // } + InvalidUnion + + // MisplacedConstraintIface occurs when a constraint-type interface is used + // outside of constraint position. + // + // Example: + // type I interface { ~int } + // + // var _ I + MisplacedConstraintIface + + // InvalidMethodTypeParams occurs when methods have type parameters. + // + // It cannot be encountered with an AST parsed using go/parser. + InvalidMethodTypeParams + + // MisplacedTypeParam occurs when a type parameter is used in a place where + // it is not permitted. + // + // Example: + // type T[P any] P + // + // Example: + // type T[P any] struct{ *P } + MisplacedTypeParam + + // InvalidUnsafeSliceData occurs when unsafe.SliceData is called with + // an argument that is not of slice type. It also occurs if it is used + // in a package compiled for a language version before go1.20. + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.SliceData(x) + InvalidUnsafeSliceData + + // InvalidUnsafeString occurs when unsafe.String is called with + // a length argument that is not of integer type, negative, or + // out of bounds. It also occurs if it is used in a package + // compiled for a language version before go1.20. + // + // Example: + // import "unsafe" + // + // var b [10]byte + // var _ = unsafe.String(&b[0], -1) + InvalidUnsafeString + + // InvalidUnsafeStringData occurs if it is used in a package + // compiled for a language version before go1.20. + _ // not used anymore + + // InvalidClear occurs when clear is called with an argument + // that is not of map or slice type. + // + // Example: + // func _(x int) { + // clear(x) + // } + InvalidClear + + // TypeTooLarge occurs if unsafe.Sizeof or unsafe.Offsetof is + // called with an expression whose type is too large. + // + // Example: + // import "unsafe" + // + // type E [1 << 31 - 1]int + // var a [1 << 31]E + // var _ = unsafe.Sizeof(a) + // + // Example: + // import "unsafe" + // + // type E [1 << 31 - 1]int + // var s struct { + // _ [1 << 31]E + // x int + // } + // var _ = unsafe.Offsetof(s.x) + TypeTooLarge + + // InvalidMinMaxOperand occurs if min or max is called + // with an operand that cannot be ordered because it + // does not support the < operator. + // + // Example: + // const _ = min(true) + // + // Example: + // var s, t []byte + // var _ = max(s, t) + InvalidMinMaxOperand + + // TooNew indicates that, through build tags or a go.mod file, + // a source file requires a version of Go that is newer than + // the logic of the type checker. As a consequence, the type + // checker may produce spurious errors or fail to report real + // errors. The solution is to rebuild the application with a + // newer Go release. + TooNew +) diff --git a/go/src/internal/types/errors/codes_test.go b/go/src/internal/types/errors/codes_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2490ade5c369754bb5a879f8cb21de186027d65c --- /dev/null +++ b/go/src/internal/types/errors/codes_test.go @@ -0,0 +1,197 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors_test + +import ( + "fmt" + "go/ast" + "go/constant" + "go/importer" + "go/parser" + "go/token" + "internal/testenv" + "reflect" + "strings" + "testing" + + . "go/types" +) + +func TestErrorCodeExamples(t *testing.T) { + testenv.MustHaveGoBuild(t) // go command needed to resolve std .a files for importer.Default(). + + walkCodes(t, func(name string, value int, spec *ast.ValueSpec) { + t.Run(name, func(t *testing.T) { + doc := spec.Doc.Text() + examples := strings.Split(doc, "Example:") + for i := 1; i < len(examples); i++ { + example := strings.TrimSpace(examples[i]) + err := checkExample(t, example) + if err == nil { + t.Fatalf("no error in example #%d", i) + } + typerr, ok := err.(Error) + if !ok { + t.Fatalf("not a types.Error: %v", err) + } + if got := readCode(typerr); got != value { + t.Errorf("%s: example #%d returned code %d (%s), want %d", name, i, got, err, value) + } + } + }) + }) +} + +func walkCodes(t *testing.T, f func(string, int, *ast.ValueSpec)) { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "codes.go", nil, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + conf := Config{Importer: importer.Default()} + info := &Info{ + Types: make(map[ast.Expr]TypeAndValue), + Defs: make(map[*ast.Ident]Object), + Uses: make(map[*ast.Ident]Object), + } + _, err = conf.Check("types", fset, []*ast.File{file}, info) + if err != nil { + t.Fatal(err) + } + for _, decl := range file.Decls { + decl, ok := decl.(*ast.GenDecl) + if !ok || decl.Tok != token.CONST { + continue + } + for _, spec := range decl.Specs { + spec, ok := spec.(*ast.ValueSpec) + if !ok || len(spec.Names) == 0 { + continue + } + obj := info.ObjectOf(spec.Names[0]) + if named, ok := obj.Type().(*Named); ok && named.Obj().Name() == "Code" { + if len(spec.Names) != 1 { + t.Fatalf("bad Code declaration for %q: got %d names, want exactly 1", spec.Names[0].Name, len(spec.Names)) + } + codename := spec.Names[0].Name + value := int(constant.Val(obj.(*Const).Val()).(int64)) + f(codename, value, spec) + } + } + } +} + +func readCode(err Error) int { + v := reflect.ValueOf(err) + return int(v.FieldByName("go116code").Int()) +} + +func checkExample(t *testing.T, example string) error { + t.Helper() + fset := token.NewFileSet() + if !strings.HasPrefix(example, "package") { + example = "package p\n\n" + example + } + file, err := parser.ParseFile(fset, "example.go", example, 0) + if err != nil { + t.Fatal(err) + } + conf := Config{ + FakeImportC: true, + Importer: importer.Default(), + } + _, err = conf.Check("example", fset, []*ast.File{file}, nil) + return err +} + +func TestErrorCodeStyle(t *testing.T) { + // The set of error codes is large and intended to be self-documenting, so + // this test enforces some style conventions. + forbiddenInIdent := []string{ + // use invalid instead + "illegal", + // words with a common short-form + "argument", + "assertion", + "assignment", + "boolean", + "channel", + "condition", + "declaration", + "expression", + "function", + "initial", // use init for initializer, initialization, etc. + "integer", + "interface", + "iterat", // use iter for iterator, iteration, etc. + "literal", + "operation", + "package", + "pointer", + "receiver", + "signature", + "statement", + "variable", + } + forbiddenInComment := []string{ + // lhs and rhs should be spelled-out. + "lhs", "rhs", + // builtin should be hyphenated. + "builtin", + // Use dot-dot-dot. + "ellipsis", + } + nameHist := make(map[int]int) + longestName := "" + maxValue := 0 + + walkCodes(t, func(name string, value int, spec *ast.ValueSpec) { + if name == "_" { + return + } + nameHist[len(name)]++ + if value > maxValue { + maxValue = value + } + if len(name) > len(longestName) { + longestName = name + } + if !token.IsExported(name) { + t.Errorf("%q is not exported", name) + } + lower := strings.ToLower(name) + for _, bad := range forbiddenInIdent { + if strings.Contains(lower, bad) { + t.Errorf("%q contains forbidden word %q", name, bad) + } + } + doc := spec.Doc.Text() + if doc == "" { + t.Errorf("%q is undocumented", name) + } else if !strings.HasPrefix(doc, name) { + t.Errorf("doc for %q does not start with the error code name", name) + } + lowerComment := strings.ToLower(strings.TrimPrefix(doc, name)) + for _, bad := range forbiddenInComment { + if strings.Contains(lowerComment, bad) { + t.Errorf("doc for %q contains forbidden word %q", name, bad) + } + } + }) + + if testing.Verbose() { + var totChars, totCount int + for chars, count := range nameHist { + totChars += chars * count + totCount += count + } + avg := float64(totChars) / float64(totCount) + fmt.Println() + fmt.Printf("%d error codes\n", totCount) + fmt.Printf("average length: %.2f chars\n", avg) + fmt.Printf("max length: %d (%s)\n", len(longestName), longestName) + } +} diff --git a/go/src/internal/types/errors/generrordocs.go b/go/src/internal/types/errors/generrordocs.go new file mode 100644 index 0000000000000000000000000000000000000000..613c77426928dee4e8177abf68bb43413e7b06c3 --- /dev/null +++ b/go/src/internal/types/errors/generrordocs.go @@ -0,0 +1,117 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build ignore + +// generrordocs creates a Markdown file for each (compiler) error code +// and its associated documentation. +// Note: this program must be run in this directory. +// go run generrordocs.go + +//go:generate go run generrordocs.go errors_markdown + +package main + +import ( + "bytes" + "fmt" + "go/ast" + "go/importer" + "go/parser" + "go/token" + "log" + "os" + "path" + "strings" + "text/template" + + . "go/types" +) + +func main() { + if len(os.Args) != 2 { + log.Fatal("missing argument: generrordocs ") + } + outDir := os.Args[1] + if err := os.MkdirAll(outDir, 0755); err != nil { + log.Fatal("unable to create output directory: %s", err) + } + walkCodes(func(name string, vs *ast.ValueSpec) { + // ignore unused errors + if name == "_" { + return + } + // Ensure that < are represented correctly when its included in code + // blocks. The goldmark Markdown parser converts them to &lt; + // when not escaped. It is the only known string with this issue. + desc := strings.ReplaceAll(vs.Doc.Text(), "<", `{{raw "<"}}`) + e := struct { + Name string + Description string + }{ + Name: name, + Description: fmt.Sprintf("```\n%s```\n", desyc), + } + var buf bytes.Buffer + err := template.Must(template.New("eachError").Parse(markdownTemplate)).Execute(&buf, e) + if err != nil { + log.Fatalf("template.Must: %s", err) + } + if err := os.WriteFile(path.Join(outDir, name+".md"), buf.Bytes(), 0660); err != nil { + log.Fatalf("os.WriteFile: %s\n", err) + } + }) + log.Printf("output directory: %s\n", outDir) +} + +func walkCodes(f func(string, *ast.ValueSpec)) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "codes.go", nil, parser.ParseComments) + if err != nil { + log.Fatalf("ParseFile failed: %s", err) + } + conf := Config{Importer: importer.Default()} + info := &Info{ + Types: make(map[ast.Expr]TypeAndValue), + Defs: make(map[*ast.Ident]Object), + Uses: make(map[*ast.Ident]Object), + } + _, err = conf.Check("types", fset, []*ast.File{file}, info) + if err != nil { + log.Fatalf("Check failed: %s", err) + } + for _, decl := range file.Decls { + decl, ok := decl.(*ast.GenDecl) + if !ok || decl.Tok != token.CONST { + continue + } + for _, spec := range decl.Specs { + spec, ok := spec.(*ast.ValueSpec) + if !ok || len(spec.Names) == 0 { + continue + } + obj := info.ObjectOf(spec.Names[0]) + if named, ok := obj.Type().(*Named); ok && named.Obj().Name() == "Code" { + if len(spec.Names) != 1 { + log.Fatalf("bad Code declaration for %q: got %d names, want exactly 1", spec.Names[0].Name, len(spec.Names)) + } + codename := spec.Names[0].Name + f(codename, spec) + } + } + } +} + +const markdownTemplate = `--- +title: {{.Name}} +layout: article +--- + + + + +{{.Description}} +` diff --git a/go/src/internal/types/testdata/check/blank.go b/go/src/internal/types/testdata/check/blank.go new file mode 100644 index 0000000000000000000000000000000000000000..2bea11f53b7b08a6456e7066195fe90b501d2bf3 --- /dev/null +++ b/go/src/internal/types/testdata/check/blank.go @@ -0,0 +1,5 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package _ /* ERROR "invalid package name" */ diff --git a/go/src/internal/types/testdata/check/builtins0.go b/go/src/internal/types/testdata/check/builtins0.go new file mode 100644 index 0000000000000000000000000000000000000000..9b99a890acf996376e063288d6d27edebeefe995 --- /dev/null +++ b/go/src/internal/types/testdata/check/builtins0.go @@ -0,0 +1,1112 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// builtin calls + +package builtins + +import "unsafe" + +func f0() {} + +func append1() { + var b byte + var x int + var s []byte + _ = append() // ERROR "not enough arguments" + _ = append("foo" /* ERROR "must be a slice" */ ) + _ = append(nil /* ERROR "must be a slice" */ , s) + _ = append(x /* ERROR "must be a slice" */ , s) + _ = append(s) + _ = append(s, nil...) + append /* ERROR "not used" */ (s) + + _ = append(s, b) + _ = append(s, x /* ERROR "cannot use x" */ ) + _ = append(s, s /* ERROR "cannot use s" */ ) + _ = append(s...) /* ERROR "not enough arguments" */ + _ = append(s, b, s /* ERROR "too many arguments" */ ...) + _ = append(s, 1, 2, 3) + _ = append(s, 1, 2, 3, x /* ERROR "cannot use x" */ , 5, 6, 6) + _ = append(s, 1, 2 /* ERROR "too many arguments" */, s...) + _ = append([]interface{}(nil), 1, 2, "foo", x, 3.1425, false) + + type S []byte + type T string + var t T + _ = append(s, "foo" /* ERRORx `cannot use .* in argument to append` */ ) + _ = append(s, "foo"...) + _ = append(S(s), "foo" /* ERRORx `cannot use .* in argument to append` */ ) + _ = append(S(s), "foo"...) + _ = append(s, t /* ERROR "cannot use t" */ ) + _ = append(s, t...) + _ = append(s, T("foo")...) + _ = append(S(s), t /* ERROR "cannot use t" */ ) + _ = append(S(s), t...) + _ = append(S(s), T("foo")...) + _ = append([]string{}, t /* ERROR "cannot use t" */ , "foo") + _ = append([]T{}, t, "foo") +} + +// from the spec +func append2() { + s0 := []int{0, 0} + s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} + s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} + s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} + s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} + + var t []interface{} + t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"} + + var b []byte + b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } + + _ = s4 +} + +func append3() { + f1 := func() (s []int) { return } + f2 := func() (s []int, x int) { return } + f3 := func() (s []int, x, y int) { return } + f5 := func() (s []interface{}, x int, y float32, z string, b bool) { return } + ff := func() (int, float32) { return 0, 0 } + _ = append(f0 /* ERROR "used as value" */ ()) + _ = append(f1()) + _ = append(f2()) + _ = append(f3()) + _ = append(f5()) + _ = append(ff /* ERROR "must be a slice" */ ()) // TODO(gri) better error message +} + +func cap1() { + var a [10]bool + var p *[20]int + var c chan string + _ = cap() // ERROR "not enough arguments" + _ = cap(1, 2) // ERROR "too many arguments" + _ = cap(42 /* ERROR "invalid" */) + const _3 = cap(a) + assert(_3 == 10) + const _4 = cap(p) + assert(_4 == 20) + _ = cap(c) + cap /* ERROR "not used" */ (c) + + // issue 4744 + type T struct{ a [10]int } + const _ = cap(((*T)(nil)).a) + + var s [][]byte + _ = cap(s) + _ = cap(s... /* ERROR "invalid use of ... with built-in cap" */ ) + + var x int + _ = cap(x /* ERROR "invalid argument: x (variable of type int) for built-in cap" */ ) +} + +func cap2() { + f1a := func() (a [10]int) { return } + f1s := func() (s []int) { return } + f2 := func() (s []int, x int) { return } + _ = cap(f0 /* ERROR "used as value" */ ()) + _ = cap(f1a()) + _ = cap(f1s()) + _ = cap(f2()) // ERROR "too many arguments" +} + +// test cases for issue 7387 +func cap3() { + var f = func() int { return 0 } + var x = f() + const ( + _ = cap([4]int{}) + _ = cap([4]int{x}) + _ = cap /* ERROR "not constant" */ ([4]int{f()}) + _ = cap /* ERROR "not constant" */ ([4]int{cap([]int{})}) + _ = cap([4]int{cap([4]int{})}) + ) + var y float64 + var z complex128 + const ( + _ = cap([4]float64{}) + _ = cap([4]float64{y}) + _ = cap([4]float64{real(2i)}) + _ = cap /* ERROR "not constant" */ ([4]float64{real(z)}) + ) + var ch chan [10]int + const ( + _ = cap /* ERROR "not constant" */ (<-ch) + _ = cap /* ERROR "not constant" */ ([4]int{(<-ch)[0]}) + ) +} + +func clear1() { + var a [10]int + var m map[float64]string + var s []byte + clear(a /* ERROR "cannot clear a" */) + clear(&/* ERROR "cannot clear &a" */a) + clear(m) + clear(s) + clear([]int{}) +} + +func close1() { + var c chan int + var r <-chan int + close() // ERROR "not enough arguments" + close(1, 2) // ERROR "too many arguments" + close(42 /* ERROR "cannot close non-channel" */) + close(r /* ERROR "receive-only channel" */) + close(c) + _ = close /* ERROR "used as value" */ (c) + + var s []chan int + close(s... /* ERROR "invalid use of ..." */ ) +} + +func close2() { + f1 := func() (ch chan int) { return } + f2 := func() (ch chan int, x int) { return } + close(f0 /* ERROR "used as value" */ ()) + close(f1()) + close(f2()) // ERROR "too many arguments" +} + +func complex1() { + var i32 int32 + var f32 float32 + var f64 float64 + var c64 complex64 + var c128 complex128 + _ = complex() // ERROR "not enough arguments" + _ = complex(1) // ERROR "not enough arguments" + _ = complex(true /* ERROR "mismatched types" */ , 0) + _ = complex(i32 /* ERROR "expected floating-point" */ , 0) + _ = complex("foo" /* ERROR "mismatched types" */ , 0) + _ = complex(c64 /* ERROR "expected floating-point" */ , 0) + _ = complex(0 /* ERROR "mismatched types" */ , true) + _ = complex(0 /* ERROR "expected floating-point" */ , i32) + _ = complex(0 /* ERROR "mismatched types" */ , "foo") + _ = complex(0 /* ERROR "expected floating-point" */ , c64) + _ = complex(f32, f32) + _ = complex(f32, 1) + _ = complex(f32, 1.0) + _ = complex(f32, 'a') + _ = complex(f64, f64) + _ = complex(f64, 1) + _ = complex(f64, 1.0) + _ = complex(f64, 'a') + _ = complex(f32 /* ERROR "mismatched types" */ , f64) + _ = complex(f64 /* ERROR "mismatched types" */ , f32) + _ = complex(1, 1) + _ = complex(1, 1.1) + _ = complex(1, 'a') + complex /* ERROR "not used" */ (1, 2) + + var _ complex64 = complex(f32, f32) + var _ complex64 = complex /* ERRORx `cannot use .* in variable declaration` */ (f64, f64) + + var _ complex128 = complex /* ERRORx `cannot use .* in variable declaration` */ (f32, f32) + var _ complex128 = complex(f64, f64) + + // untyped constants + const _ int = complex(1, 0) + const _ float32 = complex(1, 0) + const _ complex64 = complex(1, 0) + const _ complex128 = complex(1, 0) + const _ = complex(0i, 0i) + const _ = complex(0i, 0) + const _ int = 1.0 + complex(1, 0i) + + const _ int = complex /* ERROR "int" */ (1.1, 0) + const _ float32 = complex /* ERROR "float32" */ (1, 2) + + // untyped values + var s uint + _ = complex(1 /* ERROR "integer" */ <>8&1 + mi>>16&1 + mi>>32&1) + logSizeofUint = uint(mu>>8&1 + mu>>16&1 + mu>>32&1) + logSizeofUintptr = uint(mp>>8&1 + mp>>16&1 + mp>>32&1) +) + +const ( + minInt8 = -1<<(8< 0) + _ = assert(smallestFloat64 > 0) +) + +const ( + maxFloat32 = 1<<127 * (1<<24 - 1) / (1.0<<23) + // TODO(gri) The compiler limits integers to 512 bit and thus + // we cannot compute the value 1<<1023 + // without overflow. For now we match the compiler. + // See also issue #44057. + // maxFloat64 = 1<<1023 * (1<<53 - 1) / (1.0<<52) + maxFloat64 = math.MaxFloat64 +) + +const ( + _ int8 = minInt8 /* ERROR "overflows" */ - 1 + _ int8 = minInt8 + _ int8 = maxInt8 + _ int8 = maxInt8 /* ERROR "overflows" */ + 1 + _ int8 = smallestFloat64 /* ERROR "truncated" */ + + _ = int8(minInt8 /* ERROR "overflows" */ - 1) + _ = int8(minInt8) + _ = int8(maxInt8) + _ = int8(maxInt8 /* ERROR "overflows" */ + 1) + _ = int8(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ int16 = minInt16 /* ERROR "overflows" */ - 1 + _ int16 = minInt16 + _ int16 = maxInt16 + _ int16 = maxInt16 /* ERROR "overflows" */ + 1 + _ int16 = smallestFloat64 /* ERROR "truncated" */ + + _ = int16(minInt16 /* ERROR "overflows" */ - 1) + _ = int16(minInt16) + _ = int16(maxInt16) + _ = int16(maxInt16 /* ERROR "overflows" */ + 1) + _ = int16(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ int32 = minInt32 /* ERROR "overflows" */ - 1 + _ int32 = minInt32 + _ int32 = maxInt32 + _ int32 = maxInt32 /* ERROR "overflows" */ + 1 + _ int32 = smallestFloat64 /* ERROR "truncated" */ + + _ = int32(minInt32 /* ERROR "overflows" */ - 1) + _ = int32(minInt32) + _ = int32(maxInt32) + _ = int32(maxInt32 /* ERROR "overflows" */ + 1) + _ = int32(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ int64 = minInt64 /* ERROR "overflows" */ - 1 + _ int64 = minInt64 + _ int64 = maxInt64 + _ int64 = maxInt64 /* ERROR "overflows" */ + 1 + _ int64 = smallestFloat64 /* ERROR "truncated" */ + + _ = int64(minInt64 /* ERROR "overflows" */ - 1) + _ = int64(minInt64) + _ = int64(maxInt64) + _ = int64(maxInt64 /* ERROR "overflows" */ + 1) + _ = int64(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ int = minInt /* ERROR "overflows" */ - 1 + _ int = minInt + _ int = maxInt + _ int = maxInt /* ERROR "overflows" */ + 1 + _ int = smallestFloat64 /* ERROR "truncated" */ + + _ = int(minInt /* ERROR "overflows" */ - 1) + _ = int(minInt) + _ = int(maxInt) + _ = int(maxInt /* ERROR "overflows" */ + 1) + _ = int(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uint8 = 0 /* ERROR "overflows" */ - 1 + _ uint8 = 0 + _ uint8 = maxUint8 + _ uint8 = maxUint8 /* ERROR "overflows" */ + 1 + _ uint8 = smallestFloat64 /* ERROR "truncated" */ + + _ = uint8(0 /* ERROR "overflows" */ - 1) + _ = uint8(0) + _ = uint8(maxUint8) + _ = uint8(maxUint8 /* ERROR "overflows" */ + 1) + _ = uint8(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uint16 = 0 /* ERROR "overflows" */ - 1 + _ uint16 = 0 + _ uint16 = maxUint16 + _ uint16 = maxUint16 /* ERROR "overflows" */ + 1 + _ uint16 = smallestFloat64 /* ERROR "truncated" */ + + _ = uint16(0 /* ERROR "overflows" */ - 1) + _ = uint16(0) + _ = uint16(maxUint16) + _ = uint16(maxUint16 /* ERROR "overflows" */ + 1) + _ = uint16(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uint32 = 0 /* ERROR "overflows" */ - 1 + _ uint32 = 0 + _ uint32 = maxUint32 + _ uint32 = maxUint32 /* ERROR "overflows" */ + 1 + _ uint32 = smallestFloat64 /* ERROR "truncated" */ + + _ = uint32(0 /* ERROR "overflows" */ - 1) + _ = uint32(0) + _ = uint32(maxUint32) + _ = uint32(maxUint32 /* ERROR "overflows" */ + 1) + _ = uint32(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uint64 = 0 /* ERROR "overflows" */ - 1 + _ uint64 = 0 + _ uint64 = maxUint64 + _ uint64 = maxUint64 /* ERROR "overflows" */ + 1 + _ uint64 = smallestFloat64 /* ERROR "truncated" */ + + _ = uint64(0 /* ERROR "overflows" */ - 1) + _ = uint64(0) + _ = uint64(maxUint64) + _ = uint64(maxUint64 /* ERROR "overflows" */ + 1) + _ = uint64(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uint = 0 /* ERROR "overflows" */ - 1 + _ uint = 0 + _ uint = maxUint + _ uint = maxUint /* ERROR "overflows" */ + 1 + _ uint = smallestFloat64 /* ERROR "truncated" */ + + _ = uint(0 /* ERROR "overflows" */ - 1) + _ = uint(0) + _ = uint(maxUint) + _ = uint(maxUint /* ERROR "overflows" */ + 1) + _ = uint(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ uintptr = 0 /* ERROR "overflows" */ - 1 + _ uintptr = 0 + _ uintptr = maxUintptr + _ uintptr = maxUintptr /* ERROR "overflows" */ + 1 + _ uintptr = smallestFloat64 /* ERROR "truncated" */ + + _ = uintptr(0 /* ERROR "overflows" */ - 1) + _ = uintptr(0) + _ = uintptr(maxUintptr) + _ = uintptr(maxUintptr /* ERROR "overflows" */ + 1) + _ = uintptr(smallestFloat64 /* ERROR "cannot convert" */) +) + +const ( + _ float32 = minInt64 + _ float64 = minInt64 + _ complex64 = minInt64 + _ complex128 = minInt64 + + _ = float32(minInt64) + _ = float64(minInt64) + _ = complex64(minInt64) + _ = complex128(minInt64) +) + +const ( + _ float32 = maxUint64 + _ float64 = maxUint64 + _ complex64 = maxUint64 + _ complex128 = maxUint64 + + _ = float32(maxUint64) + _ = float64(maxUint64) + _ = complex64(maxUint64) + _ = complex128(maxUint64) +) + +// TODO(gri) find smaller deltas below + +const delta32 = maxFloat32/(1 << 23) + +const ( + _ float32 = - /* ERROR "overflow" */ (maxFloat32 + delta32) + _ float32 = -maxFloat32 + _ float32 = maxFloat32 + _ float32 = maxFloat32 /* ERROR "overflow" */ + delta32 + + _ = float32(- /* ERROR "cannot convert" */ (maxFloat32 + delta32)) + _ = float32(-maxFloat32) + _ = float32(maxFloat32) + _ = float32(maxFloat32 /* ERROR "cannot convert" */ + delta32) + + _ = assert(float32(smallestFloat32) == smallestFloat32) + _ = assert(float32(smallestFloat32/2) == 0) + _ = assert(float32(smallestFloat64) == 0) + _ = assert(float32(smallestFloat64/2) == 0) +) + +const delta64 = maxFloat64/(1 << 52) + +const ( + _ float64 = - /* ERROR "overflow" */ (maxFloat64 + delta64) + _ float64 = -maxFloat64 + _ float64 = maxFloat64 + _ float64 = maxFloat64 /* ERROR "overflow" */ + delta64 + + _ = float64(- /* ERROR "cannot convert" */ (maxFloat64 + delta64)) + _ = float64(-maxFloat64) + _ = float64(maxFloat64) + _ = float64(maxFloat64 /* ERROR "cannot convert" */ + delta64) + + _ = assert(float64(smallestFloat32) == smallestFloat32) + _ = assert(float64(smallestFloat32/2) == smallestFloat32/2) + _ = assert(float64(smallestFloat64) == smallestFloat64) + _ = assert(float64(smallestFloat64/2) == 0) +) + +const ( + _ complex64 = - /* ERROR "overflow" */ (maxFloat32 + delta32) + _ complex64 = -maxFloat32 + _ complex64 = maxFloat32 + _ complex64 = maxFloat32 /* ERROR "overflow" */ + delta32 + + _ = complex64(- /* ERROR "cannot convert" */ (maxFloat32 + delta32)) + _ = complex64(-maxFloat32) + _ = complex64(maxFloat32) + _ = complex64(maxFloat32 /* ERROR "cannot convert" */ + delta32) +) + +const ( + _ complex128 = - /* ERROR "overflow" */ (maxFloat64 + delta64) + _ complex128 = -maxFloat64 + _ complex128 = maxFloat64 + _ complex128 = maxFloat64 /* ERROR "overflow" */ + delta64 + + _ = complex128(- /* ERROR "cannot convert" */ (maxFloat64 + delta64)) + _ = complex128(-maxFloat64) + _ = complex128(maxFloat64) + _ = complex128(maxFloat64 /* ERROR "cannot convert" */ + delta64) +) + +// Initialization of typed constant and conversion are the same: +const ( + f32 = 1 + smallestFloat32 + x32 float32 = f32 + y32 = float32(f32) + _ = assert(x32 - y32 == 0) +) + +const ( + f64 = 1 + smallestFloat64 + x64 float64 = f64 + y64 = float64(f64) + _ = assert(x64 - y64 == 0) +) + +const ( + _ = int8(-1) << 7 + _ = int8 /* ERROR "overflows" */ (-1) << 8 + + _ = uint32(1) << 31 + _ = uint32 /* ERROR "overflows" */ (1) << 32 +) diff --git a/go/src/internal/types/testdata/check/constdecl.go b/go/src/internal/types/testdata/check/constdecl.go new file mode 100644 index 0000000000000000000000000000000000000000..9ace419a61b1a3984923d5998f1528f65e175ffc --- /dev/null +++ b/go/src/internal/types/testdata/check/constdecl.go @@ -0,0 +1,160 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package constdecl + +import "math" +import "unsafe" + +var v int + +// Const decls must be initialized by constants. +const _ = v /* ERROR "not constant" */ +const _ = math /* ERROR "not constant" */ .Sin(0) +const _ = int /* ERROR "not an expression" */ + +func _() { + const _ = v /* ERROR "not constant" */ + const _ = math /* ERROR "not constant" */ .Sin(0) + const _ = int /* ERROR "not an expression" */ +} + +// Identifier and expression arity must match. +const _ /* ERROR "missing init expr for _" */ +const _ = 1, 2 /* ERROR "extra init expr 2" */ + +const _ /* ERROR "missing init expr for _" */ int +const _ int = 1, 2 /* ERROR "extra init expr 2" */ + +const ( + _ /* ERROR "missing init expr for _" */ + _ = 1, 2 /* ERROR "extra init expr 2" */ + + _ /* ERROR "missing init expr for _" */ int + _ int = 1, 2 /* ERROR "extra init expr 2" */ +) + +const ( + _ = 1 + _ + _, _ /* ERROR "missing init expr for _" */ + _ +) + +const ( + _, _ = 1, 2 + _, _ + _ /* ERROR "extra init expr at" */ + _, _ + _, _, _ /* ERROR "missing init expr for _" */ + _, _ +) + +func _() { + const _ /* ERROR "missing init expr for _" */ + const _ = 1, 2 /* ERROR "extra init expr 2" */ + + const _ /* ERROR "missing init expr for _" */ int + const _ int = 1, 2 /* ERROR "extra init expr 2" */ + + const ( + _ /* ERROR "missing init expr for _" */ + _ = 1, 2 /* ERROR "extra init expr 2" */ + + _ /* ERROR "missing init expr for _" */ int + _ int = 1, 2 /* ERROR "extra init expr 2" */ + ) + + const ( + _ = 1 + _ + _, _ /* ERROR "missing init expr for _" */ + _ + ) + + const ( + _, _ = 1, 2 + _, _ + _ /* ERROR "extra init expr at" */ + _, _ + _, _, _ /* ERROR "missing init expr for _" */ + _, _ + ) +} + +// Test case for constant with invalid initialization. +// Caused panic because the constant value was not set up (gri - 7/8/2014). +func _() { + const ( + x string = missing /* ERROR "undefined" */ + y = x + "" + ) +} + +// Test case for constants depending on function literals (see also #22992). +const A /* ERROR "initialization cycle" */ = unsafe.Sizeof(func() { _ = A }) + +func _() { + // The function literal below must not see a. + const a = unsafe.Sizeof(func() { _ = a /* ERROR "undefined" */ }) + const b = unsafe.Sizeof(func() { _ = a }) + + // The function literal below must not see x, y, or z. + const x, y, z = 0, 1, unsafe.Sizeof(func() { _ = x /* ERROR "undefined" */ + y /* ERROR "undefined" */ + z /* ERROR "undefined" */ }) +} + +// Test cases for errors in inherited constant initialization expressions. +// Errors related to inherited initialization expressions must appear at +// the constant identifier being declared, not at the original expression +// (issues #42991, #42992). +const ( + _ byte = 255 + iota + /* some gap */ + _ // ERROR "overflows" + /* some gap */ + /* some gap */ _ /* ERROR "overflows" */; _ /* ERROR "overflows" */ + /* some gap */ + _ = 255 + iota + _ = byte /* ERROR "overflows" */ (255) + iota + _ /* ERROR "overflows" */ +) + +// Test cases from issue. +const ( + ok = byte(iota + 253) + bad + barn + bard // ERROR "overflows" +) + +const ( + c = len([1 - iota]int{}) + d + e // ERROR "invalid array length" + f // ERROR "invalid array length" +) + +// Test that identifiers in implicit (omitted) RHS +// expressions of constant declarations are resolved +// in the correct context; see issues #49157, #53585. +const X = 2 + +func _() { + const ( + A = iota // 0 + iota = iota // 1 + B // 1 (iota is declared locally on prev. line) + C // 1 + ) + assert(A == 0 && B == 1 && C == 1) + + const ( + X = X + X + Y + Z = iota + ) + assert(X == 4 && Y == 8 && Z == 1) +} + +// TODO(gri) move extra tests from testdata/const0.src into here diff --git a/go/src/internal/types/testdata/check/conversions0.go b/go/src/internal/types/testdata/check/conversions0.go new file mode 100644 index 0000000000000000000000000000000000000000..e1336c0456adf7baada345f46f5da54d89c9b804 --- /dev/null +++ b/go/src/internal/types/testdata/check/conversions0.go @@ -0,0 +1,93 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// conversions + +package conversions + +import "unsafe" + +// argument count +var ( + _ = int() /* ERROR "missing argument" */ + _ = int(1, 2 /* ERROR "too many arguments" */ ) +) + +// numeric constant conversions are in const1.src. + +func string_conversions() { + const A = string(65) + assert(A == "A") + const E = string(-1) + assert(E == "\uFFFD") + assert(E == string(1234567890)) + + type myint int + assert(A == string(myint(65))) + + type mystring string + const _ mystring = mystring("foo") + + const _ = string(true /* ERROR "cannot convert" */ ) + const _ = string(1.2 /* ERROR "cannot convert" */ ) + const _ = string(nil /* ERROR "cannot convert" */ ) + + // issues 11357, 11353: argument must be of integer type + _ = string(0.0 /* ERROR "cannot convert" */ ) + _ = string(0i /* ERROR "cannot convert" */ ) + _ = string(1 /* ERROR "cannot convert" */ + 2i) +} + +func interface_conversions() { + type E interface{} + + type I1 interface{ + m1() + } + + type I2 interface{ + m1() + m2(x int) + } + + type I3 interface{ + m1() + m2() int + } + + var e E + var i1 I1 + var i2 I2 + var i3 I3 + + _ = E(0) + _ = E(nil) + _ = E(e) + _ = E(i1) + _ = E(i2) + + _ = I1(0 /* ERROR "cannot convert" */ ) + _ = I1(nil) + _ = I1(i1) + _ = I1(e /* ERROR "cannot convert" */ ) + _ = I1(i2) + + _ = I2(nil) + _ = I2(i1 /* ERROR "cannot convert" */ ) + _ = I2(i2) + _ = I2(i3 /* ERROR "cannot convert" */ ) + + _ = I3(nil) + _ = I3(i1 /* ERROR "cannot convert" */ ) + _ = I3(i2 /* ERROR "cannot convert" */ ) + _ = I3(i3) + + // TODO(gri) add more tests, improve error message +} + +func issue6326() { + type T unsafe.Pointer + var x T + _ = uintptr(x) // see issue 6326 +} diff --git a/go/src/internal/types/testdata/check/conversions1.go b/go/src/internal/types/testdata/check/conversions1.go new file mode 100644 index 0000000000000000000000000000000000000000..65aabde9105783518f4661f85245bcbd5142150d --- /dev/null +++ b/go/src/internal/types/testdata/check/conversions1.go @@ -0,0 +1,313 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test various valid and invalid struct assignments and conversions. +// Does not compile. + +package conversions2 + +type I interface { + m() +} + +// conversions between structs + +func _() { + type S struct{} + type T struct{} + var s S + var t T + var u struct{} + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u + s = S(s) + s = S(t) + s = S(u) + t = u + t = T(u) +} + +func _() { + type S struct{ x int } + type T struct { + x int "foo" + } + var s S + var t T + var u struct { + x int "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = S(s) + s = S(t) + s = S(u) + t = u // ERRORx `cannot use .* in assignment` + t = T(u) +} + +func _() { + type E struct{ x int } + type S struct{ x E } + type T struct { + x E "foo" + } + var s S + var t T + var u struct { + x E "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = S(s) + s = S(t) + s = S(u) + t = u // ERRORx `cannot use .* in assignment` + t = T(u) +} + +func _() { + type S struct { + x struct { + x int "foo" + } + } + type T struct { + x struct { + x int "bar" + } "foo" + } + var s S + var t T + var u struct { + x struct { + x int "bar" + } "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = S(s) + s = S(t) + s = S(u) + t = u // ERRORx `cannot use .* in assignment` + t = T(u) +} + +func _() { + type E1 struct { + x int "foo" + } + type E2 struct { + x int "bar" + } + type S struct{ x E1 } + type T struct { + x E2 "foo" + } + var s S + var t T + var u struct { + x E2 "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = S(s) + s = S(t /* ERROR "cannot convert" */ ) + s = S(u /* ERROR "cannot convert" */ ) + t = u // ERRORx `cannot use .* in assignment` + t = T(u) +} + +func _() { + type E struct{ x int } + type S struct { + f func(struct { + x int "foo" + }) + } + type T struct { + f func(struct { + x int "bar" + }) + } + var s S + var t T + var u struct{ f func(E) } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = S(s) + s = S(t) + s = S(u /* ERROR "cannot convert" */ ) + t = u // ERRORx `cannot use .* in assignment` + t = T(u /* ERROR "cannot convert" */ ) +} + +// conversions between pointers to structs + +func _() { + type S struct{} + type T struct{} + var s *S + var t *T + var u *struct{} + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u) +} + +func _() { + type S struct{ x int } + type T struct { + x int "foo" + } + var s *S + var t *T + var u *struct { + x int "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u) +} + +func _() { + type E struct{ x int } + type S struct{ x E } + type T struct { + x E "foo" + } + var s *S + var t *T + var u *struct { + x E "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u) +} + +func _() { + type S struct { + x struct { + x int "foo" + } + } + type T struct { + x struct { + x int "bar" + } "foo" + } + var s *S + var t *T + var u *struct { + x struct { + x int "bar" + } "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u) +} + +func _() { + type E1 struct { + x int "foo" + } + type E2 struct { + x int "bar" + } + type S struct{ x E1 } + type T struct { + x E2 "foo" + } + var s *S + var t *T + var u *struct { + x E2 "bar" + } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t /* ERROR "cannot convert" */ ) + s = (*S)(u /* ERROR "cannot convert" */ ) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u) +} + +func _() { + type E struct{ x int } + type S struct { + f func(struct { + x int "foo" + }) + } + type T struct { + f func(struct { + x int "bar" + }) + } + var s *S + var t *T + var u *struct{ f func(E) } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u /* ERROR "cannot convert" */ ) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u /* ERROR "cannot convert" */ ) +} + +func _() { + type E struct{ x int } + type S struct { + f func(*struct { + x int "foo" + }) + } + type T struct { + f func(*struct { + x int "bar" + }) + } + var s *S + var t *T + var u *struct{ f func(E) } + s = s + s = t // ERRORx `cannot use .* in assignment` + s = u // ERRORx `cannot use .* in assignment` + s = (*S)(s) + s = (*S)(t) + s = (*S)(u /* ERROR "cannot convert" */ ) + t = u // ERRORx `cannot use .* in assignment` + t = (*T)(u /* ERROR "cannot convert" */ ) +} diff --git a/go/src/internal/types/testdata/check/cycles0.go b/go/src/internal/types/testdata/check/cycles0.go new file mode 100644 index 0000000000000000000000000000000000000000..d13dc447dd57b87fedadcdf19205d948f9861e2b --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles0.go @@ -0,0 +1,175 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cycles + +import "unsafe" + +type ( + T0 int + T1 /* ERROR "invalid recursive type: T1 refers to itself" */ T1 + T2 *T2 + + T3 /* ERROR "invalid recursive type" */ T4 + T4 T5 + T5 T3 + + T6 T7 + T7 *T8 + T8 T6 + + // arrays + A0 /* ERROR "invalid recursive type" */ [10]A0 + A1 [10]*A1 + + A2 /* ERROR "invalid recursive type" */ [10]A3 + A3 [10]A4 + A4 A2 + + A5 [10]A6 + A6 *A5 + + // slices + L0 []L0 + + // structs + S0 /* ERROR "invalid recursive type: S0 refers to itself" */ struct{ _ S0 } + S1 /* ERROR "invalid recursive type: S1 refers to itself" */ struct{ S1 } + S2 struct{ _ *S2 } + S3 struct{ *S3 } + + S4 /* ERROR "invalid recursive type" */ struct{ S5 } + S5 struct{ S6 } + S6 S4 + + // pointers + P0 *P0 + PP /* ERROR "invalid recursive type" */ *struct{ PP.f } + + // functions + F0 func(F0) + F1 func() F1 + F2 func(F2) F2 + + // interfaces + I0 /* ERROR "invalid recursive type: I0 refers to itself" */ interface{ I0 } + + I1 /* ERROR "invalid recursive type" */ interface{ I2 } + I2 interface{ I3 } + I3 interface{ I1 } + + I4 interface{ f(I4) } + + // testcase for issue 5090 + I5 interface{ f(I6) } + I6 interface{ I5 } + + // maps + M0 map[M0 /* ERROR "invalid map key" */ ]M0 + + // channels + C0 chan C0 +) + +// test case for issue #34771 +type ( + AA /* ERROR "invalid recursive type" */ B + B C + C [10]D + D E + E AA +) + +func _() { + type ( + t1 /* ERROR "invalid recursive type: t1 refers to itself" */ t1 + t2 *t2 + + t3 t4 /* ERROR "undefined" */ + t4 t5 /* ERROR "undefined" */ + t5 t3 + + // arrays + a0 /* ERROR "invalid recursive type: a0 refers to itself" */ [10]a0 + a1 [10]*a1 + + // slices + l0 []l0 + + // structs + s0 /* ERROR "invalid recursive type: s0 refers to itself" */ struct{ _ s0 } + s1 /* ERROR "invalid recursive type: s1 refers to itself" */ struct{ s1 } + s2 struct{ _ *s2 } + s3 struct{ *s3 } + + // pointers + p0 *p0 + + // functions + f0 func(f0) + f1 func() f1 + f2 func(f2) f2 + + // interfaces + i0 /* ERROR "invalid recursive type: i0 refers to itself" */ interface{ i0 } + + // maps + m0 map[m0 /* ERROR "invalid map key" */ ]m0 + + // channels + c0 chan c0 + ) +} + +// test cases for issue 6667 + +type A [10]map[A /* ERROR "invalid map key" */ ]bool + +type S struct { + m map[S /* ERROR "invalid map key" */ ]bool +} + +// test cases for issue 7236 +// (cycle detection must not be dependent on starting point of resolution) + +type ( + P1 *T9 + T9 /* ERROR "invalid recursive type: T9 refers to itself" */ T9 + + T10 /* ERROR "invalid recursive type: T10 refers to itself" */ T10 + P2 *T10 +) + +func (T11) m() {} + +type T11 /* ERROR "invalid recursive type: T11 refers to itself" */ struct{ T11 } + +type T12 /* ERROR "invalid recursive type: T12 refers to itself" */ struct{ T12 } + +func (*T12) m() {} + +type ( + P3 *T13 + T13 /* ERROR "invalid recursive type" */ T13 +) + +// test cases for issue 18643 +// (type cycle detection when non-type expressions are involved) +type ( + T14 /* ERROR "invalid recursive type" */ [len(T14{})]int + T15 /* ERROR "invalid recursive type" */ [][len(T15{})]int + T16 /* ERROR "invalid recursive type" */ map[[len(T16{1:2})]int]int + T17 /* ERROR "invalid recursive type" */ map[int][len(T17{1:2})]int +) + +// Test case for types depending on function literals (see also #22992). +type T20 chan [unsafe.Sizeof(func(ch T20){ _ = <-ch })]byte +type T22 = chan [unsafe.Sizeof(func(ch T20){ _ = <-ch })]byte + +func _() { + type T0 func(T0) + type T1 /* ERROR "invalid recursive type" */ = func(T1) + type T2 chan [unsafe.Sizeof(func(ch T2){ _ = <-ch })]byte + type T3 /* ERROR "invalid recursive type" */ = chan [unsafe.Sizeof(func(ch T3){ _ = <-ch })]byte +} diff --git a/go/src/internal/types/testdata/check/cycles1.go b/go/src/internal/types/testdata/check/cycles1.go new file mode 100644 index 0000000000000000000000000000000000000000..ae2b38ebec21e36d5f2e5bdd360948e8cbba97ce --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles1.go @@ -0,0 +1,77 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + A interface { + a() interface { + ABC1 + } + } + B interface { + b() interface { + ABC2 + } + } + C interface { + c() interface { + ABC3 + } + } + + AB interface { + A + B + } + BC interface { + B + C + } + + ABC1 interface { + A + B + C + } + ABC2 interface { + AB + C + } + ABC3 interface { + A + BC + } +) + +var ( + x1 ABC1 + x2 ABC2 + x3 ABC3 +) + +func _() { + // all types have the same method set + x1 = x2 + x2 = x1 + + x1 = x3 + x3 = x1 + + x2 = x3 + x3 = x2 + + // all methods return the same type again + x1 = x1.a() + x1 = x1.b() + x1 = x1.c() + + x2 = x2.a() + x2 = x2.b() + x2 = x2.c() + + x3 = x3.a() + x3 = x3.b() + x3 = x3.c() +} diff --git a/go/src/internal/types/testdata/check/cycles2.go b/go/src/internal/types/testdata/check/cycles2.go new file mode 100644 index 0000000000000000000000000000000000000000..75016dbe8bc1e15008b5db1569165b3684b95264 --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles2.go @@ -0,0 +1,98 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// Test case for issue 5090 + +type t interface { + f(u) +} + +type u interface { + t +} + +func _() { + var t t + var u u + + t.f(t) + t.f(u) + + u.f(t) + u.f(u) +} + + +// Test case for issues #6589, #33656. + +type A interface { + a() interface { + AB + } +} + +type B interface { + b() interface { + AB + } +} + +type AB interface { + a() interface { + A + B + } + b() interface { + A + B + } +} + +var x AB +var y interface { + A + B +} + +var _ = x == y + + +// Test case for issue 6638. + +type T /* ERROR "invalid recursive type" */ interface { + m() [T(nil).m()[0]]int +} + +// Variations of this test case. + +type T1 /* ERROR "invalid recursive type" */ interface { + m() [x1.m()[0]]int +} + +var x1 T1 + +type T2 /* ERROR "invalid recursive type" */ interface { + m() [len(x2.m())]int +} + +var x2 T2 + +type T3 /* ERROR "invalid recursive type" */ interface { + m() [unsafe.Sizeof(x3.m)]int +} + +var x3 T3 + +type T4 /* ERROR "invalid recursive type" */ interface { + m() [unsafe.Sizeof(cast4(x4.m))]int // cast is invalid but we have a cycle, so all bets are off +} + +var x4 T4 +var _ = cast4(x4.m) + +type cast4 func() diff --git a/go/src/internal/types/testdata/check/cycles3.go b/go/src/internal/types/testdata/check/cycles3.go new file mode 100644 index 0000000000000000000000000000000000000000..3ed999cc3d12a2cf33046353c0051897a3ffe91c --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles3.go @@ -0,0 +1,60 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +var ( + _ A = A(nil).a().b().c().d().e().f() + _ A = A(nil).b().c().d().e().f() + _ A = A(nil).c().d().e().f() + _ A = A(nil).d().e().f() + _ A = A(nil).e().f() + _ A = A(nil).f() + _ A = A(nil) +) + +type ( + A interface { + a() B + B + } + + B interface { + b() C + C + } + + C interface { + c() D + D + } + + D interface { + d() E + E + } + + E interface { + e() F + F + } + + F interface { + f() A + } +) + +type ( + U /* ERROR "invalid recursive type" */ interface { + V + } + + V interface { + v() [unsafe.Sizeof(u)]int + } +) + +var u U diff --git a/go/src/internal/types/testdata/check/cycles4.go b/go/src/internal/types/testdata/check/cycles4.go new file mode 100644 index 0000000000000000000000000000000000000000..86f4f9aa034ade0c19405b76bf32927e45975cb7 --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles4.go @@ -0,0 +1,121 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// Check that all methods of T are collected before +// determining the result type of m (which embeds +// all methods of T). + +type T interface { + m() interface {T} + E +} + +var _ int = T.m(nil).m().e() + +type E interface { + e() int +} + +// Check that unresolved forward chains are followed +// (see also comment in resolver.go, checker.typeDecl). + +var _ int = C.m(nil).m().e() + +type A B + +type B interface { + m() interface{C} + E +} + +type C A + +// Check that interface type comparison for identity +// does not recur endlessly. + +type T1 interface { + m() interface{T1} +} + +type T2 interface { + m() interface{T2} +} + +func _(x T1, y T2) { + // Checking for assignability of interfaces must check + // if all methods of x are present in y, and that they + // have identical signatures. The signatures recur via + // the result type, which is an interface that embeds + // a single method m that refers to the very interface + // that contains it. This requires cycle detection in + // identity checks for interface types. + x = y +} + +type T3 interface { + m() interface{T4} +} + +type T4 interface { + m() interface{T3} +} + +func _(x T1, y T3) { + x = y +} + +// Check that interfaces are type-checked in order of +// (embedded interface) dependencies (was issue 7158). + +var x1 T5 = T7(nil) + +type T5 interface { + T6 +} + +type T6 interface { + m() T7 +} +type T7 interface { + T5 +} + +// Actual test case from issue 7158. + +func wrapNode() Node { + return wrapElement() +} + +func wrapElement() Element { + return nil +} + +type EventTarget interface { + AddEventListener(Event) +} + +type Node interface { + EventTarget +} + +type Element interface { + Node +} + +type Event interface { + Target() Element +} + +// Check that accessing an interface method too early doesn't lead +// to follow-on errors due to an incorrectly computed type set. + +type T8 /* ERROR "invalid recursive type" */ interface { + m() [unsafe.Sizeof(T8.m)]int +} + +var _ = T8.m // no error expected here diff --git a/go/src/internal/types/testdata/check/cycles5.go b/go/src/internal/types/testdata/check/cycles5.go new file mode 100644 index 0000000000000000000000000000000000000000..9605f8ded4489a595ffaaa2c1ba6e54ade46071f --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles5.go @@ -0,0 +1,202 @@ +// -gotypesalias=0 + +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// test case from issue #18395 + +type ( + A interface { B } + B interface { C } + C interface { D; F() A } + D interface { G() B } +) + +var _ = A(nil).G // G must be found + + +// test case from issue #21804 + +type sourceBridge interface { + listVersions() ([]Version, error) +} + +type Constraint interface { + copyTo(*ConstraintMsg) +} + +type ConstraintMsg struct{} + +func (m *ConstraintMsg) asUnpairedVersion() UnpairedVersion { + return nil +} + +type Version interface { + Constraint +} + +type UnpairedVersion interface { + Version +} + +var _ Constraint = UnpairedVersion(nil) + + +// derived test case from issue #21804 + +type ( + _ interface{ m(B1) } + A1 interface{ a(D1) } + B1 interface{ A1 } + C1 interface{ B1 } + D1 interface{ C1 } +) + +var _ A1 = C1(nil) + + +// derived test case from issue #22701 + +func F(x I4) interface{} { + return x.Method() +} + +type Unused interface { + RefersToI1(a I1) +} + +type I1 interface { + I2 + I3 +} + +type I2 interface { + RefersToI4() I4 +} + +type I3 interface { + Method() interface{} +} + +type I4 interface { + I1 +} + + +// check embedding of error interface + +type Error interface{ error } + +var err Error +var _ = err.Error() + + +// more esoteric cases + +type ( + T1 interface { T2 } + T2 /* ERROR "invalid recursive type" */ T2 +) + +type ( + T3 interface { T4 } + T4 /* ERROR "invalid recursive type" */ T5 + T5 = T6 + T6 = T7 + T7 = T4 +) + + +// arbitrary code may appear inside an interface + +const n = unsafe.Sizeof(func(){}) + +type I interface { + m([unsafe.Sizeof(func() { I.m(nil, [n]byte{}) })]byte) +} + + +// test cases for varias alias cycles + +type T10 /* ERROR "invalid recursive type" */ = *T10 // issue #25141 +type T11 /* ERROR "invalid recursive type" */ = interface{ f(T11) } // issue #23139 + +// issue #18640 +type ( + aa = bb + bb struct { + *aa + } +) + +type ( + a struct{ *b } + b = c + c struct{ *b /* ERROR "invalid use of type alias" */ } +) + +// issue #24939 +type ( + _ interface { + M(P) + } + + M interface { + F() P // ERROR "invalid use of type alias" + } + + P = interface { + I() M + } +) + +// issue #8699 +type T12 /* ERROR "invalid recursive type" */ [len(a12)]int +var a12 = makeArray() +func makeArray() (res T12) { return } + +// issue #20770 +var r = newReader() +func newReader() r // ERROR "r (package-level variable) is not a type" + +// variations of the theme of #8699 and #20770 +var arr /* ERROR "cycle" */ = f() +func f() [len(arr)]int + +// issue #25790 +func ff(ff /* ERROR "not a type" */ ) +func gg((gg /* ERROR "not a type" */ )) + +type T13 /* ERROR "invalid recursive type T13" */ [len(b13)]int +var b13 T13 + +func g1() [unsafe.Sizeof(g1)]int +func g2() [unsafe.Sizeof(x2)]int +var x2 = g2 + +// verify that we get the correct sizes for the functions above +// (note: assert is statically evaluated in go/types test mode) +func init() { + assert(unsafe.Sizeof(g1) == 8) + assert(unsafe.Sizeof(x2) == 8) +} + +func h() [h /* ERROR "no value" */ ()[0]]int { panic(0) } + +var c14 /* ERROR "cycle" */ T14 +type T14 [uintptr(unsafe.Sizeof(&c14))]byte + +// issue #34333 +type T15 /* ERROR "invalid recursive type T15" */ struct { + f func() T16 + b T16 +} + +type T16 struct { + T15 +} \ No newline at end of file diff --git a/go/src/internal/types/testdata/check/cycles5a.go b/go/src/internal/types/testdata/check/cycles5a.go new file mode 100644 index 0000000000000000000000000000000000000000..a8cad50243a727af9670b534fb54c3a7995f583e --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles5a.go @@ -0,0 +1,202 @@ +// -gotypesalias=1 + +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// test case from issue #18395 + +type ( + A interface { B } + B interface { C } + C interface { D; F() A } + D interface { G() B } +) + +var _ = A(nil).G // G must be found + + +// test case from issue #21804 + +type sourceBridge interface { + listVersions() ([]Version, error) +} + +type Constraint interface { + copyTo(*ConstraintMsg) +} + +type ConstraintMsg struct{} + +func (m *ConstraintMsg) asUnpairedVersion() UnpairedVersion { + return nil +} + +type Version interface { + Constraint +} + +type UnpairedVersion interface { + Version +} + +var _ Constraint = UnpairedVersion(nil) + + +// derived test case from issue #21804 + +type ( + _ interface{ m(B1) } + A1 interface{ a(D1) } + B1 interface{ A1 } + C1 interface{ B1 } + D1 interface{ C1 } +) + +var _ A1 = C1(nil) + + +// derived test case from issue #22701 + +func F(x I4) interface{} { + return x.Method() +} + +type Unused interface { + RefersToI1(a I1) +} + +type I1 interface { + I2 + I3 +} + +type I2 interface { + RefersToI4() I4 +} + +type I3 interface { + Method() interface{} +} + +type I4 interface { + I1 +} + + +// check embedding of error interface + +type Error interface{ error } + +var err Error +var _ = err.Error() + + +// more esoteric cases + +type ( + T1 interface { T2 } + T2 /* ERROR "invalid recursive type" */ T2 +) + +type ( + T3 interface { T4 } + T4 /* ERROR "invalid recursive type" */ T5 + T5 = T6 + T6 = T7 + T7 = T4 +) + + +// arbitrary code may appear inside an interface + +const n = unsafe.Sizeof(func(){}) + +type I interface { + m([unsafe.Sizeof(func() { I.m(nil, [n]byte{}) })]byte) +} + + +// test cases for varias alias cycles + +type T10 /* ERROR "invalid recursive type" */ = *T10 // issue #25141 +type T11 /* ERROR "invalid recursive type" */ = interface{ f(T11) } // issue #23139 + +// issue #18640 +type ( + aa = bb + bb struct { + *aa + } +) + +type ( + a struct{ *b } + b = c + c struct{ *b } +) + +// issue #24939 +type ( + _ interface { + M(P) + } + + M interface { + F() P + } + + P = interface { + I() M + } +) + +// issue #8699 +type T12 /* ERROR "invalid recursive type" */ [len(a12)]int +var a12 = makeArray() +func makeArray() (res T12) { return } + +// issue #20770 +var r = newReader() +func newReader() r // ERROR "r (package-level variable) is not a type" + +// variations of the theme of #8699 and #20770 +var arr /* ERROR "cycle" */ = f() +func f() [len(arr)]int + +// issue #25790 +func ff(ff /* ERROR "not a type" */ ) +func gg((gg /* ERROR "not a type" */ )) + +type T13 /* ERROR "invalid recursive type T13" */ [len(b13)]int +var b13 T13 + +func g1() [unsafe.Sizeof(g1)]int +func g2() [unsafe.Sizeof(x2)]int +var x2 = g2 + +// verify that we get the correct sizes for the functions above +// (note: assert is statically evaluated in go/types test mode) +func init() { + assert(unsafe.Sizeof(g1) == 8) + assert(unsafe.Sizeof(x2) == 8) +} + +func h() [h /* ERROR "no value" */ ()[0]]int { panic(0) } + +var c14 /* ERROR "cycle" */ T14 +type T14 [uintptr(unsafe.Sizeof(&c14))]byte + +// issue #34333 +type T15 /* ERROR "invalid recursive type T15" */ struct { + f func() T16 + b T16 +} + +type T16 struct { + T15 +} \ No newline at end of file diff --git a/go/src/internal/types/testdata/check/cycles6.go b/go/src/internal/types/testdata/check/cycles6.go new file mode 100644 index 0000000000000000000000000000000000000000..e5635ed4566c4ec460dddb92538cc0d366eae63d --- /dev/null +++ b/go/src/internal/types/testdata/check/cycles6.go @@ -0,0 +1,71 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// Below are the pieces of syntax corresponding to functions which can produce a +// type T without first having a value of type T. Notice that each causes a +// value of type T to be passed to unsafe.Sizeof while T is incomplete. + +// literal on type +type T0 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(T0{})]int +// literal on value (not applicable) +// literal on pointer (not applicable) + +// call on type +type T1 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(T1(42))]int +// call on value +func f2() T2 +type T2 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(f2())]int +// call on pointer (not applicable) + +// assert on type +var i3 interface{} +type T3 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(i3.(T3))]int +// assert on value (not applicable) +// assert on pointer (not applicable) + +// receive on type (not applicable) +// receive on value +func f4() <-chan T4 +type T4 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(<-f4())]int +// receive on pointer (not applicable) + +// star on type (not applicable) +// star on value (not applicable) +// star on pointer +func f5() *T5 +type T5 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(*f5())]int + +// Below is additional syntax which interacts with incomplete types. Notice that +// each of the below falls into 1 of 3 cases: +// 1. It cannot produce a value of (incomplete) type T. +// 2. It can, but only because it already has a value of type T. +// 3. It can, but only because it performs an implicit dereference. + +// select on type (case 1) +// select on value (case 2) +type T6 /* ERROR "invalid recursive type" */ struct { + f T7 +} +type T7 [unsafe.Sizeof(T6{}.f)]int +// select on pointer (case 3) +type T8 /* ERROR "invalid recursive type" */ struct { + f T9 +} +type T9 [unsafe.Sizeof(new(T8).f)]int + +// slice on type (not applicable) +// slice on value (case 2) +type T10 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(T10{}[:])]int +// slice on pointer (case 3) +type T11 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(new(T11)[:])]int + +// index on type (case 1) +// index on value (case 2) +type T12 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(T12{}[42])]int +// index on pointer (case 3) +type T13 /* ERROR "invalid recursive type" */ [unsafe.Sizeof(new(T13)[42])]int diff --git a/go/src/internal/types/testdata/check/decls0.go b/go/src/internal/types/testdata/check/decls0.go new file mode 100644 index 0000000000000000000000000000000000000000..f5345135db4193ea7369d4da9e77479008e9733d --- /dev/null +++ b/go/src/internal/types/testdata/check/decls0.go @@ -0,0 +1,210 @@ +// -lang=go1.17 + +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// type declarations + +package p // don't permit non-interface elements in interfaces + +import "unsafe" + +const pi = 3.1415 + +type ( + N undefined /* ERROR "undefined" */ + B bool + I int32 + A [10]P + T struct { + x, y P + } + P *T + R (*R) + F func(A) I + Y interface { + f(A) I + } + S [](((P))) + M map[I]F + C chan<- I + + // blank types must be typechecked + _ pi /* ERROR "not a type" */ + _ struct{} + _ struct{ pi /* ERROR "not a type" */ } +) + + +// declarations of init +const _, init /* ERROR "cannot declare init" */ , _ = 0, 1, 2 +type init /* ERROR "cannot declare init" */ struct{} +var _, init /* ERROR "cannot declare init" */ int + +func init() {} +func init /* ERROR "func init must have a body" */ () + +func _() { const init = 0 } +func _() { type init int } +func _() { var init int; _ = init } + +// invalid array types +type ( + iA0 [... /* ERROR "invalid use of [...] array" */ ]byte + // The error message below could be better. At the moment + // we believe an integer that is too large is not an integer. + // But at least we get an error. + iA1 [1 /* ERROR "invalid array length" */ <<100]int + iA2 [- /* ERROR "invalid array length" */ 1]complex128 + iA3 ["foo" /* ERROR "must be integer" */ ]string + iA4 [float64 /* ERROR "must be integer" */ (0)]int +) + + +type ( + p1 pi.foo /* ERROR "pi.foo is not a type" */ + p2 unsafe.Pointer +) + + +type ( + Pi pi /* ERROR "not a type" */ + + a /* ERROR "invalid recursive type" */ a + a /* ERROR "redeclared" */ int + + b /* ERROR "invalid recursive type" */ c + c d + d e + e b + + t *t + + U V + V *W + W U + + P1 *S2 + P2 P1 + + S0 struct { + } + S1 struct { + a, b, c int + u, v, a /* ERROR "redeclared" */ float32 + } + S2 struct { + S0 // embedded field + S0 /* ERROR "redeclared" */ int + } + S3 struct { + x S2 + } + S4/* ERROR "invalid recursive type" */ struct { + S4 + } + S5 /* ERROR "invalid recursive type" */ struct { + S6 + } + S6 struct { + field S7 + } + S7 struct { + S5 + } + + L1 []L1 + L2 []int + + A1 [10.0]int + A2 /* ERROR "invalid recursive type" */ [10]A2 + A3 /* ERROR "invalid recursive type" */ [10]struct { + x A4 + } + A4 [10]A3 + + F1 func() + F2 func(x, y, z float32) + F3 func(x, y, x /* ERROR "redeclared" */ float32) + F4 func() (x, y, x /* ERROR "redeclared" */ float32) + F5 func(x int) (x /* ERROR "redeclared" */ float32) + F6 func(x ...int) + + I1 interface{} + I2 interface { + m1() + } + I3 interface { + m1() + m1 /* ERROR "duplicate method m1" */ () + } + I4 interface { + m1(x, y, x /* ERROR "redeclared" */ float32) + m2() (x, y, x /* ERROR "redeclared" */ float32) + m3(x int) (x /* ERROR "redeclared" */ float32) + } + I5 interface { + m1(I5) + } + I6 interface { + S0 /* ERROR "non-interface type S0" */ + } + I7 interface { + I1 + I1 + } + I8 /* ERROR "invalid recursive type" */ interface { + I8 + } + I9 /* ERROR "invalid recursive type" */ interface { + I10 + } + I10 interface { + I11 + } + I11 interface { + I9 + } + + C1 chan int + C2 <-chan int + C3 chan<- C3 + C4 chan C5 + C5 chan C6 + C6 chan C4 + + M1 map[Last]string + M2 map[string]M2 + + Last int +) + +// cycles in function/method declarations +// (test cases for issues #5217, #25790 and variants) +func f1(x f1 /* ERROR "not a type" */ ) {} +func f2(x *f2 /* ERROR "not a type" */ ) {} +func f3() (x f3 /* ERROR "not a type" */ ) { return } +func f4() (x *f4 /* ERROR "not a type" */ ) { return } +// TODO(#43215) this should be detected as a cycle error +func f5([unsafe.Sizeof(f5)]int) {} + +func (S0) m1 (x S0.m1 /* ERROR "S0.m1 is not a type" */ ) {} +func (S0) m2 (x *S0.m2 /* ERROR "S0.m2 is not a type" */ ) {} +func (S0) m3 () (x S0.m3 /* ERROR "S0.m3 is not a type" */ ) { return } +func (S0) m4 () (x *S0.m4 /* ERROR "S0.m4 is not a type" */ ) { return } + +// interfaces may not have any blank methods +type BlankI interface { + _ /* ERROR "methods must have a unique non-blank name" */ () + _ /* ERROR "methods must have a unique non-blank name" */ (float32) int + m() +} + +// non-interface types may have multiple blank methods +type BlankT struct{} + +func (BlankT) _() {} +func (BlankT) _(int) {} +func (BlankT) _() int { return 0 } +func (BlankT) _(int) int { return 0} diff --git a/go/src/internal/types/testdata/check/decls1.go b/go/src/internal/types/testdata/check/decls1.go new file mode 100644 index 0000000000000000000000000000000000000000..5e4ba86cb080d6ff1ee1b661b81e41da4b5724de --- /dev/null +++ b/go/src/internal/types/testdata/check/decls1.go @@ -0,0 +1,153 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// variable declarations + +package decls1 + +import ( + "math" +) + +// Global variables without initialization +var ( + a, b bool + c byte + d uint8 + r rune + i int + j, k, l int + x, y float32 + xx, yy float64 + u, v complex64 + uu, vv complex128 + s, t string + array []byte + iface interface{} + + blank _ /* ERROR "cannot use _" */ +) + +// Global variables with initialization +var ( + s1 = i + j + s2 = i /* ERROR "mismatched types" */ + x + s3 = c + d + s4 = s + t + s5 = s /* ERROR "invalid operation" */ / t + s6 = array[t1] + s7 = array[x /* ERROR "integer" */] + s8 = &a + s10 = &42 /* ERROR "cannot take address" */ + s11 = &v + s12 = -(u + *t11) / *&v + s13 = a /* ERROR "shifted operand" */ << d + s14 = i << j + s18 = math.Pi * 10.0 + s19 = s1 /* ERROR "cannot call" */ () + s20 = f0 /* ERROR "no value" */ () + s21 = f6(1, s1, i) + s22 = f6(1, s1, uu /* ERRORx `cannot use .* in argument` */ ) + + t1 int = i + j + t2 int = i /* ERROR "mismatched types" */ + x + t3 int = c /* ERRORx `cannot use .* variable declaration` */ + d + t4 string = s + t + t5 string = s /* ERROR "invalid operation" */ / t + t6 byte = array[t1] + t7 byte = array[x /* ERROR "must be integer" */] + t8 *int = & /* ERRORx `cannot use .* variable declaration` */ a + t10 *int = &42 /* ERROR "cannot take address" */ + t11 *complex64 = &v + t12 complex64 = -(u + *t11) / *&v + t13 int = a /* ERROR "shifted operand" */ << d + t14 int = i << j + t15 math /* ERROR "math (package name) is not a type" */ + t16 math.xxx /* ERROR "undefined" */ + t17 math /* ERROR "not a type" */ .Pi + t18 float64 = math.Pi * 10.0 + t19 int = t1 /* ERROR "cannot call" */ () + t20 int = f0 /* ERROR "no value" */ () + t21 int = a /* ERRORx `cannot use .* variable declaration` */ +) + +// Various more complex expressions +var ( + u1 = x /* ERROR "not an interface" */ .(int) + u2 = iface.([]int) + u3 = iface.(a /* ERROR "not a type" */ ) + u4, ok = iface.(int) + u5, ok2, ok3 = iface /* ERROR "assignment mismatch" */ .(int) +) + +// Constant expression initializations +var ( + v1 = 1 /* ERROR "mismatched types untyped int and untyped string" */ + "foo" + v2 = c + 255 + v3 = c + 256 /* ERROR "overflows" */ + v4 = r + 2147483647 + v5 = r + 2147483648 /* ERROR "overflows" */ + v6 = 42 + v7 = v6 + 9223372036854775807 + v8 = v6 + 9223372036854775808 /* ERROR "overflows" */ + v9 = i + 1 << 10 + v10 byte = 1024 /* ERROR "overflows" */ + v11 = xx/yy*yy - xx + v12 = true && false + v13 = nil /* ERROR "use of untyped nil" */ + v14 string = 257 // ERRORx `cannot use 257 .* as string value in variable declaration$` + v15 int8 = 257 // ERRORx `cannot use 257 .* as int8 value in variable declaration .*overflows` +) + +// Multiple assignment expressions +var ( + m1a, m1b = 1, 2 + m2a, m2b, m2c /* ERROR "missing init expr for m2c" */ = 1, 2 + m3a, m3b = 1, 2, 3 /* ERROR "extra init expr 3" */ +) + +func _() { + var ( + m1a, m1b = 1, 2 + m2a, m2b, m2c /* ERROR "missing init expr for m2c" */ = 1, 2 + m3a, m3b = 1, 2, 3 /* ERROR "extra init expr 3" */ + ) + + _, _ = m1a, m1b + _, _, _ = m2a, m2b, m2c + _, _ = m3a, m3b +} + +// Declaration of parameters and results +func f0() {} +func f1(a /* ERROR "not a type" */) {} +func f2(a, b, c d /* ERROR "not a type" */) {} + +func f3() int { return 0 } +func f4() a /* ERROR "not a type" */ { return 0 } +func f5() (a, b, c d /* ERROR "not a type" */) { return } + +func f6(a, b, c int) complex128 { return 0 } + +// Declaration of receivers +type T struct{} + +func (T) m0() {} +func (*T) m1() {} +func (x T) m2() {} +func (x *T) m3() {} + +// Initialization functions +func init() {} +func init /* ERROR "no arguments and no return values" */ (int) {} +func init /* ERROR "no arguments and no return values" */ () int { return 0 } +func init /* ERROR "no arguments and no return values" */ (int) int { return 0 } +func (T) init(int) int { return 0 } + +func _() { + var error error + var _ error /* ERROR "error (local variable) is not a type" */ + _ = error +} + diff --git a/go/src/internal/types/testdata/check/decls2/decls2a.go b/go/src/internal/types/testdata/check/decls2/decls2a.go new file mode 100644 index 0000000000000000000000000000000000000000..58fdbfe1321f762e89999a44cd90ac7e0360b5d8 --- /dev/null +++ b/go/src/internal/types/testdata/check/decls2/decls2a.go @@ -0,0 +1,111 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// method declarations + +package decls2 + +import "time" +import "unsafe" + +// T1 declared before its methods. +type T1 struct{ + f int +} + +func (T1) m() {} +func (T1) m /* ERROR "already declared" */ () {} +func (x *T1) f /* ERROR "field and method with the same name f" */ () {} + +// Conflict between embedded field and method name, +// with the embedded field being a basic type. +type T1b struct { + int +} + +func (T1b) int /* ERROR "field and method" */ () {} + +type T1c struct { + time.Time +} + +func (T1c) Time /* ERROR "field and method with the same name Time" */ () int { return 0 } + +// Disabled for now: LookupFieldOrMethod will find Pointer even though +// it's double-declared (it would cost extra in the common case to verify +// this). But the MethodSet computation will not find it due to the name +// collision caused by the double-declaration, leading to an internal +// inconsistency while we are verifying one computation against the other. +// var _ = T1c{}.Pointer + +// T2's method declared before the type. +func (*T2) f /* ERROR "field and method" */ () {} + +type T2 struct { + f int +} + +// Methods declared without a declared type. +func (undefined /* ERROR "undefined" */) m() {} +func (x *undefined /* ERROR "undefined" */) m() {} + +func (pi /* ERROR "not a type" */) m1() {} +func (x pi /* ERROR "not a type" */) m2() {} +func (x *pi /* ERROR "not a type" */ ) m3() {} + +// Blank types. +type _ struct { m int } +type _ struct { m int } + +func (_ /* ERROR "cannot use _" */) m() {} +func m(_ /* ERROR "cannot use _" */) {} + +// Methods with receiver base type declared in another file. +func (T3) m1() {} +func (*T3) m2() {} +func (x T3) m3() {} +func (x *T3) f /* ERROR "field and method" */ () {} + +// Methods of non-struct type. +type T4 func() + +func (self T4) m() func() { return self } + +// Methods associated with an interface. +type T5 interface { + m() int +} + +func (T5 /* ERROR "invalid receiver" */ ) m1() {} +func (T5 /* ERROR "invalid receiver" */ ) m2() {} + +// Methods associated with a named pointer type. +type ptr *int +func (ptr /* ERROR "invalid receiver" */ ) _() {} +func (*ptr /* ERROR "invalid receiver" */ ) _() {} + +// Methods with zero or multiple receivers. +func ( /* ERROR "method has no receiver" */ ) _() {} +func (T3, * /* ERROR "method has multiple receivers" */ T3) _() {} +func (T3, T3, T3 /* ERROR "method has multiple receivers" */ ) _() {} +func (a, b /* ERROR "method has multiple receivers" */ T3) _() {} +func (a, b, c /* ERROR "method has multiple receivers" */ T3) _() {} + +// Methods associated with non-local or unnamed types. +func (int /* ERROR "cannot define new methods on non-local type int" */ ) m() {} +func ([ /* ERROR "invalid receiver" */ ]int) m() {} +func (time /* ERROR "cannot define new methods on non-local type time.Time" */ .Time) m() {} +func (*time /* ERROR "cannot define new methods on non-local type time.Time" */ .Time) m() {} +func (x any /* ERROR "invalid receiver" */ ) m() {} + +// Unsafe.Pointer is treated like a pointer when used as receiver type. +type UP unsafe.Pointer +func (UP /* ERROR "invalid" */ ) m1() {} +func (*UP /* ERROR "invalid" */ ) m2() {} + +// Double declarations across package files +const c_double = 0 +type t_double int +var v_double int +func f_double() {} diff --git a/go/src/internal/types/testdata/check/decls2/decls2b.go b/go/src/internal/types/testdata/check/decls2/decls2b.go new file mode 100644 index 0000000000000000000000000000000000000000..dd6cd44d99265b1b8bd80098c9cb5ade14fab0d7 --- /dev/null +++ b/go/src/internal/types/testdata/check/decls2/decls2b.go @@ -0,0 +1,75 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// method declarations + +package decls2 + +import "io" + +const pi = 3.1415 + +func (T1) m /* ERROR "already declared" */ () {} +func (T2) m(io.Writer) {} + +type T3 struct { + f *T3 +} + +type T6 struct { + x int +} + +func (t *T6) m1() int { + return t.x +} + +func f() { + var t *T6 + t.m1() +} + +// Double declarations across package files +const c_double /* ERROR "redeclared" */ = 0 +type t_double /* ERROR "redeclared" */ int +var v_double /* ERROR "redeclared" */ int +func f_double /* ERROR "redeclared" */ () {} + +// Blank methods need to be type-checked. +// Verify by checking that errors are reported. +func (T /* ERROR "undefined" */ ) _() {} +func (T1) _(undefined /* ERROR "undefined" */ ) {} +func (T1) _() int { return "foo" /* ERRORx "cannot use .* in return statement" */ } + +// Methods with undefined receiver type can still be checked. +// Verify by checking that errors are reported. +func (Foo /* ERROR "undefined" */ ) m() {} +func (Foo /* ERROR "undefined" */ ) m(undefined /* ERROR "undefined" */ ) {} +func (Foo /* ERRORx `undefined` */ ) m() int { return "foo" /* ERRORx "cannot use .* in return statement" */ } + +func (Foo /* ERROR "undefined" */ ) _() {} +func (Foo /* ERROR "undefined" */ ) _(undefined /* ERROR "undefined" */ ) {} +func (Foo /* ERROR "undefined" */ ) _() int { return "foo" /* ERRORx "cannot use .* in return statement" */ } + +// Receiver declarations are regular parameter lists; +// receiver types may use parentheses, and the list +// may have a trailing comma. +type T7 struct {} + +func (T7) m1() {} +func ((T7)) m2() {} +func ((*T7)) m3() {} +func (x *(T7),) m4() {} +func (x (*(T7)),) m5() {} +func (x ((*((T7)))),) m6() {} + +// Check that methods with parenthesized receiver are actually present (issue #23130). +var ( + _ = T7.m1 + _ = T7.m2 + _ = (*T7).m3 + _ = (*T7).m4 + _ = (*T7).m5 + _ = (*T7).m6 +) diff --git a/go/src/internal/types/testdata/check/decls3.go b/go/src/internal/types/testdata/check/decls3.go new file mode 100644 index 0000000000000000000000000000000000000000..3d00a580ab922caa9f29c0c92e9637a758e617b9 --- /dev/null +++ b/go/src/internal/types/testdata/check/decls3.go @@ -0,0 +1,309 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// embedded types + +package decls3 + +import "unsafe" +import "fmt" + +// fields with the same name at the same level cancel each other out + +func _() { + type ( + T1 struct { X int } + T2 struct { X int } + T3 struct { T1; T2 } // X is embedded twice at the same level via T1->X, T2->X + ) + + var t T3 + _ = t.X /* ERROR "ambiguous selector t.X" */ +} + +func _() { + type ( + T1 struct { X int } + T2 struct { T1 } + T3 struct { T1 } + T4 struct { T2; T3 } // X is embedded twice at the same level via T2->T1->X, T3->T1->X + ) + + var t T4 + _ = t.X /* ERROR "ambiguous selector t.X" */ +} + +func issue4355() { + type ( + T1 struct {X int} + T2 struct {T1} + T3 struct {T2} + T4 struct {T2} + T5 struct {T3; T4} // X is embedded twice at the same level via T3->T2->T1->X, T4->T2->T1->X + ) + + var t T5 + _ = t.X /* ERROR "ambiguous selector t.X" */ +} + +func _() { + type State int + type A struct{ State } + type B struct{ fmt.State } + type T struct{ A; B } + + var t T + _ = t.State /* ERROR "ambiguous selector t.State" */ +} + +// Embedded fields can be predeclared types. + +func _() { + type T0 struct{ + int + float32 + f int + } + var x T0 + _ = x.int + _ = x.float32 + _ = x.f + + type T1 struct{ + T0 + } + var y T1 + _ = y.int + _ = y.float32 + _ = y.f +} + +// Restrictions on embedded field types. + +func _() { + type I1 interface{} + type I2 interface{} + type P1 *int + type P2 *int + type UP unsafe.Pointer + + type T1 struct { + I1 + * /* ERROR "cannot be a pointer to an interface" */ I2 + * /* ERROR "cannot be a pointer to an interface" */ error + P1 /* ERROR "cannot be a pointer" */ + * /* ERROR "cannot be a pointer" */ P2 + } + + // unsafe.Pointers are treated like regular pointers when embedded + type T2 struct { + unsafe /* ERROR "cannot be unsafe.Pointer" */ .Pointer + */* ERROR "cannot be unsafe.Pointer" */ unsafe.Pointer /* ERROR "Pointer redeclared" */ + UP /* ERROR "cannot be unsafe.Pointer" */ + * /* ERROR "cannot be unsafe.Pointer" */ UP /* ERROR "UP redeclared" */ + } +} + +// Named types that are pointers. + +type S struct{ x int } +func (*S) m() {} +type P *S + +func _() { + var s *S + _ = s.x + _ = s.m + + var p P + _ = p.x + _ = p.m /* ERROR "no field or method" */ + _ = P.m /* ERROR "no field or method" */ +} + +// Borrowed from the FieldByName test cases in reflect/all_test.go. + +type D1 struct { + d int +} +type D2 struct { + d int +} + +type S0 struct { + A, B, C int + D1 + D2 +} + +type S1 struct { + B int + S0 +} + +type S2 struct { + A int + *S1 +} + +type S1x struct { + S1 +} + +type S1y struct { + S1 +} + +type S3 struct { + S1x + S2 + D, E int + *S1y +} + +type S4 struct { + *S4 + A int +} + +// The X in S6 and S7 annihilate, but they also block the X in S8.S9. +type S5 struct { + S6 + S7 + S8 +} + +type S6 struct { + X int +} + +type S7 S6 + +type S8 struct { + S9 +} + +type S9 struct { + X int + Y int +} + +// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. +type S10 struct { + S11 + S12 + S13 +} + +type S11 struct { + S6 +} + +type S12 struct { + S6 +} + +type S13 struct { + S8 +} + +func _() { + _ = struct{}{}.Foo /* ERROR "no field or method" */ + _ = S0{}.A + _ = S0{}.D /* ERROR "no field or method" */ + _ = S1{}.A + _ = S1{}.B + _ = S1{}.S0 + _ = S1{}.C + _ = S2{}.A + _ = S2{}.S1 + _ = S2{}.B + _ = S2{}.C + _ = S2{}.D /* ERROR "no field or method" */ + _ = S3{}.S1 /* ERROR "ambiguous selector S3{}.S1" */ + _ = S3{}.A + _ = S3{}.B /* ERROR "ambiguous selector S3{}.B" */ + _ = S3{}.D + _ = S3{}.E + _ = S4{}.A + _ = S4{}.B /* ERROR "no field or method" */ + _ = S5{}.X /* ERROR "ambiguous selector S5{}.X" */ + _ = S5{}.Y + _ = S10{}.X /* ERROR "ambiguous selector S10{}.X" */ + _ = S10{}.Y +} + +// Borrowed from the FieldByName benchmark in reflect/all_test.go. + +type R0 struct { + *R1 + *R2 + *R3 + *R4 +} + +type R1 struct { + *R5 + *R6 + *R7 + *R8 +} + +type R2 R1 +type R3 R1 +type R4 R1 + +type R5 struct { + *R9 + *R10 + *R11 + *R12 +} + +type R6 R5 +type R7 R5 +type R8 R5 + +type R9 struct { + *R13 + *R14 + *R15 + *R16 +} + +type R10 R9 +type R11 R9 +type R12 R9 + +type R13 struct { + *R17 + *R18 + *R19 + *R20 +} + +type R14 R13 +type R15 R13 +type R16 R13 + +type R17 struct { + *R21 + *R22 + *R23 + *R24 +} + +type R18 R17 +type R19 R17 +type R20 R17 + +type R21 struct { + X int +} + +type R22 R21 +type R23 R21 +type R24 R21 + +var _ = R0{}.X /* ERROR "ambiguous selector R0{}.X" */ \ No newline at end of file diff --git a/go/src/internal/types/testdata/check/decls4.go b/go/src/internal/types/testdata/check/decls4.go new file mode 100644 index 0000000000000000000000000000000000000000..7c063904c8a0d9dec9868e1b4ab23b952790eab7 --- /dev/null +++ b/go/src/internal/types/testdata/check/decls4.go @@ -0,0 +1,199 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// type aliases + +package decls4 + +type ( + T0 [10]int + T1 []byte + T2 struct { + x int + } + T3 interface{ + m() T2 + } + T4 func(int, T0) chan T2 +) + +type ( + Ai = int + A0 = T0 + A1 = T1 + A2 = T2 + A3 = T3 + A4 = T4 + + A10 = [10]int + A11 = []byte + A12 = struct { + x int + } + A13 = interface{ + m() A2 + } + A14 = func(int, A0) chan A2 +) + +// check assignment compatibility due to equality of types +var ( + xi_ int + ai Ai = xi_ + + x0 T0 + a0 A0 = x0 + + x1 T1 + a1 A1 = x1 + + x2 T2 + a2 A2 = x2 + + x3 T3 + a3 A3 = x3 + + x4 T4 + a4 A4 = x4 +) + +// alias receiver types +func (Ai /* ERRORx "cannot define new methods on non-local type (int|Ai)" */) m1() {} +func (T0) m1() {} +func (A0) m1 /* ERROR "already declared" */ () {} +func (A0) m2 () {} +func (A3 /* ERROR "invalid receiver" */ ) m1 () {} +func (A10 /* ERROR "invalid receiver" */ ) m1() {} + +// x0 has methods m1, m2 declared via receiver type names T0 and A0 +var _ interface{ m1(); m2() } = x0 + +// alias receiver types (test case for issue #23042) +type T struct{} + +var ( + _ = T.m + _ = T{}.m + _ interface{m()} = T{} +) + +var ( + _ = T.n + _ = T{}.n + _ interface{m(); n()} = T{} +) + +type U = T +func (U) m() {} + +// alias receiver types (long type declaration chains) +type ( + V0 = V1 + V1 = (V2) + V2 = ((V3)) + V3 = T +) + +func (V0) m /* ERROR "already declared" */ () {} +func (V1) n() {} + +// alias receiver types (invalid due to cycles) +type ( + W0 /* ERROR "invalid recursive type" */ = W1 + W1 = (W2) + W2 = ((W0)) +) + +func (W0) m() {} // no error expected (due to above cycle error) +func (W1) n() {} + +// alias receiver types (invalid due to builtin underlying type) +type ( + B0 = B1 + B1 = B2 + B2 = int +) + +func (B0 /* ERRORx "cannot define new methods on non-local type (int|B)" */ ) m() {} +func (B1 /* ERRORx "cannot define new methods on non-local type (int|B)" */ ) n() {} + +// cycles +type ( + C2 /* ERROR "invalid recursive type" */ = C2 + C3 /* ERROR "invalid recursive type" */ = C4 + C4 = C3 + C5 struct { + f *C6 + } + C6 = C5 + C7 /* ERROR "invalid recursive type" */ struct { + f C8 + } + C8 = C7 +) + +// embedded fields +var ( + s0 struct { T0 } + s1 struct { A0 } = s0 /* ERROR "cannot use" */ // embedded field names are different +) + +// embedding and lookup of fields and methods +func _(s struct{A0}) { s.A0 = x0 } + +type eX struct{xf int} + +func (eX) xm() + +type eY = struct{eX} // field/method set of eY includes xf, xm + +type eZ = *struct{eX} // field/method set of eZ includes xf, xm + +type eA struct { + eX // eX contributes xf, xm to eA +} + +type eA2 struct { + *eX // *eX contributes xf, xm to eA +} + +type eB struct { + eY // eY contributes xf, xm to eB +} + +type eB2 struct { + *eY // *eY contributes xf, xm to eB +} + +type eC struct { + eZ // eZ contributes xf, xm to eC +} + +var ( + _ = eA{}.xf + _ = eA{}.xm + _ = eA2{}.xf + _ = eA2{}.xm + _ = eB{}.xf + _ = eB{}.xm + _ = eB2{}.xf + _ = eB2{}.xm + _ = eC{}.xf + _ = eC{}.xm +) + +// ambiguous selectors due to embedding via type aliases +type eD struct { + eY + eZ +} + +var ( + _ = eD{}.xf /* ERROR "ambiguous selector eD{}.xf" */ + _ = eD{}.xm /* ERROR "ambiguous selector eD{}.xm" */ +) + +var ( + _ interface{ xm() } = eD /* ERROR "ambiguous selector eD.xm" */ {} +) \ No newline at end of file diff --git a/go/src/internal/types/testdata/check/decls5.go b/go/src/internal/types/testdata/check/decls5.go new file mode 100644 index 0000000000000000000000000000000000000000..88d31946da44b7c832f84611648c894f31a8d451 --- /dev/null +++ b/go/src/internal/types/testdata/check/decls5.go @@ -0,0 +1,10 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// declarations of main +const _, main /* ERROR "cannot declare main" */ , _ = 0, 1, 2 +type main /* ERROR "cannot declare main" */ struct{} +var _, main /* ERROR "cannot declare main" */ int diff --git a/go/src/internal/types/testdata/check/doubled_labels.go b/go/src/internal/types/testdata/check/doubled_labels.go new file mode 100644 index 0000000000000000000000000000000000000000..f3de27020ba35b2288dba76ffcd7e1ff3f830658 --- /dev/null +++ b/go/src/internal/types/testdata/check/doubled_labels.go @@ -0,0 +1,26 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { +outer: +inner: + for { + continue inner + break inner + } + goto outer +} + +func _() { +outer: +inner: + for { + continue inner + continue outer /* ERROR "invalid continue label outer" */ + break outer /* ERROR "invalid break label outer" */ + } + goto outer +} diff --git a/go/src/internal/types/testdata/check/errors.go b/go/src/internal/types/testdata/check/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..615cf862d1b89d9e9acd0ef8acd610dc3cba3c9e --- /dev/null +++ b/go/src/internal/types/testdata/check/errors.go @@ -0,0 +1,66 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors + +// Testing precise operand formatting in error messages +// (matching messages are regular expressions, hence the \'s). +func f(x int, m map[string]int) { + // no values + _ = f /* ERROR "f(0, m) (no value) used as value" */ (0, m) + + // built-ins + _ = println // ERROR "println (built-in) must be called" + + // types + _ = complex128 // ERROR "complex128 (type) is not an expression" + + // constants + const c1 = 991 + const c2 float32 = 0.5 + const c3 = "foo" + 0 // ERROR "0 (untyped int constant) is not used" + 0.5 // ERROR "0.5 (untyped float constant) is not used" + "foo" // ERROR `"foo" (untyped string constant) is not used` + c1 // ERROR "c1 (untyped int constant 991) is not used" + c2 // ERROR "c2 (constant 0.5 of type float32) is not used" + c1 /* ERROR "c1 + c2 (constant 991.5 of type float32) is not used" */ + c2 + c3 // ERROR `c3 (untyped string constant "foo") is not used` + + // variables + x // ERROR "x (variable of type int) is not used" + + // values + nil // ERROR "nil is not used" + ( /* ERROR "(*int)(nil) (value of type *int) is not used" */ *int)(nil) + x /* ERROR "x != x (untyped bool value) is not used" */ != x + x /* ERROR "x + x (value of type int) is not used" */ + x + + // value, ok's + const s = "foo" + m /* ERROR "m[s] (map index expression of type int) is not used" */ [s] +} + +// Valid ERROR comments can have a variety of forms. +func _() { + 0 /* ERRORx "0 .* is not used" */ + 0 /* ERRORx "0 .* is not used" */ + 0 // ERRORx "0 .* is not used" + 0 // ERRORx "0 .* is not used" +} + +// Don't report spurious errors as a consequence of earlier errors. +// Add more tests as needed. +func _() { + if err := foo /* ERROR "undefined" */ (); err != nil /* "no error here" */ {} +} + +// Use unqualified names for package-local objects. +type T struct{} +var _ int = T /* ERROR "value of struct type T" */ {} // use T in error message rather than errors.T + +// Don't report errors containing "invalid type" (issue #24182). +func _(x *missing /* ERROR "undefined: missing" */ ) { + x.m() // there shouldn't be an error here referring to *invalid type +} diff --git a/go/src/internal/types/testdata/check/expr0.go b/go/src/internal/types/testdata/check/expr0.go new file mode 100644 index 0000000000000000000000000000000000000000..26dc58958fe7ad858b3f7af8561960e6b1cce90e --- /dev/null +++ b/go/src/internal/types/testdata/check/expr0.go @@ -0,0 +1,196 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// unary expressions + +package expr0 + +type mybool bool + +var ( + // bool + b0 = true + b1 bool = b0 + b2 = !true + b3 = !b1 + b4 bool = !true + b5 bool = !b4 + b6 = +b0 /* ERROR "not defined" */ + b7 = -b0 /* ERROR "not defined" */ + b8 = ^b0 /* ERROR "not defined" */ + b9 = *b0 /* ERROR "cannot indirect" */ + b10 = &true /* ERROR "cannot take address" */ + b11 = &b0 + b12 = <-b0 /* ERROR "cannot receive" */ + b13 = & & /* ERROR "cannot take address" */ b0 + b14 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ b0 + + // byte + _ = byte(0) + _ = byte(- /* ERROR "overflows" */ 1) + _ = - /* ERROR "-byte(1) (constant -1 of type byte) overflows byte" */ byte(1) // test for issue 11367 + _ = byte /* ERROR "overflows byte" */ (0) - byte(1) + _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ byte(0) + + // int + i0 = 1 + i1 int = i0 + i2 = +1 + i3 = +i0 + i4 int = +1 + i5 int = +i4 + i6 = -1 + i7 = -i0 + i8 int = -1 + i9 int = -i4 + i10 = !i0 /* ERROR "not defined" */ + i11 = ^1 + i12 = ^i0 + i13 int = ^1 + i14 int = ^i4 + i15 = *i0 /* ERROR "cannot indirect" */ + i16 = &i0 + i17 = *i16 + i18 = <-i16 /* ERROR "cannot receive" */ + i19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ i0 + + // uint + u0 = uint(1) + u1 uint = u0 + u2 = +1 + u3 = +u0 + u4 uint = +1 + u5 uint = +u4 + u6 = -1 + u7 = -u0 + u8 uint = - /* ERROR "overflows" */ 1 + u9 uint = -u4 + u10 = !u0 /* ERROR "not defined" */ + u11 = ^1 + u12 = ^i0 + u13 uint = ^ /* ERROR "overflows" */ 1 + u14 uint = ^u4 + u15 = *u0 /* ERROR "cannot indirect" */ + u16 = &u0 + u17 = *u16 + u18 = <-u16 /* ERROR "cannot receive" */ + u19 = ^uint(0) + u20 = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ u0 + + // float64 + f0 = float64(1) + f1 float64 = f0 + f2 = +1 + f3 = +f0 + f4 float64 = +1 + f5 float64 = +f4 + f6 = -1 + f7 = -f0 + f8 float64 = -1 + f9 float64 = -f4 + f10 = !f0 /* ERROR "not defined" */ + f11 = ^1 + f12 = ^i0 + f13 float64 = ^1 + f14 float64 = ^f4 /* ERROR "not defined" */ + f15 = *f0 /* ERROR "cannot indirect" */ + f16 = &f0 + f17 = *u16 + f18 = <-u16 /* ERROR "cannot receive" */ + f19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ f0 + + // complex128 + c0 = complex128(1) + c1 complex128 = c0 + c2 = +1 + c3 = +c0 + c4 complex128 = +1 + c5 complex128 = +c4 + c6 = -1 + c7 = -c0 + c8 complex128 = -1 + c9 complex128 = -c4 + c10 = !c0 /* ERROR "not defined" */ + c11 = ^1 + c12 = ^i0 + c13 complex128 = ^1 + c14 complex128 = ^c4 /* ERROR "not defined" */ + c15 = *c0 /* ERROR "cannot indirect" */ + c16 = &c0 + c17 = *u16 + c18 = <-u16 /* ERROR "cannot receive" */ + c19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ c0 + + // string + s0 = "foo" + s1 = +"foo" /* ERROR "not defined" */ + s2 = -s0 /* ERROR "not defined" */ + s3 = !s0 /* ERROR "not defined" */ + s4 = ^s0 /* ERROR "not defined" */ + s5 = *s4 + s6 = &s4 + s7 = *s6 + s8 = <-s7 + s9 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ s0 + + // channel + ch chan int + rc <-chan float64 + sc chan <- string + ch0 = +ch /* ERROR "not defined" */ + ch1 = -ch /* ERROR "not defined" */ + ch2 = !ch /* ERROR "not defined" */ + ch3 = ^ch /* ERROR "not defined" */ + ch4 = *ch /* ERROR "cannot indirect" */ + ch5 = &ch + ch6 = *ch5 + ch7 = <-ch + ch8 = <-rc + ch9 = <-sc /* ERROR "cannot receive" */ + ch10, ok = <-ch + // ok is of type bool + ch11, myok = <-ch + _ mybool = myok /* ERRORx `cannot use .* in variable declaration` */ + ch12 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ ch + +) + +// address of composite literals +type T struct{x, y int} + +func f() T { return T{} } + +var ( + _ = &T{1, 2} + _ = &[...]int{} + _ = &[]int{} + _ = &[]int{} + _ = &map[string]T{} + _ = &(T{1, 2}) + _ = &((((T{1, 2})))) + _ = &f /* ERROR "cannot take address" */ () +) + +// recursive pointer types +type P *P + +var ( + p1 P = new(P) + p2 P = *p1 + p3 P = &p2 +) + +func g() (a, b int) { return } + +func _() { + _ = -g /* ERROR "multiple-value g" */ () + _ = <-g /* ERROR "multiple-value g" */ () +} + +// ~ is accepted as unary operator only permitted in interface type elements +var ( + _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ 0 + _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ "foo" + _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ i0 +) diff --git a/go/src/internal/types/testdata/check/expr1.go b/go/src/internal/types/testdata/check/expr1.go new file mode 100644 index 0000000000000000000000000000000000000000..1c04c8fb6e8938dae4f9c44b2d7609d218d2d285 --- /dev/null +++ b/go/src/internal/types/testdata/check/expr1.go @@ -0,0 +1,127 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// binary expressions + +package expr1 + +type mybool bool + +func _(x, y bool, z mybool) { + x = x || y + x = x || true + x = x || false + x = x && y + x = x && true + x = x && false + + z = z /* ERROR "mismatched types" */ || y + z = z || true + z = z || false + z = z /* ERROR "mismatched types" */ && y + z = z && true + z = z && false +} + +type myint int + +func _(x, y int, z myint) { + x = x + 1 + x = x + 1.0 + x = x + 1.1 // ERROR "truncated to int" + x = x + y + x = x - y + x = x * y + x = x / y + x = x % y + x = x << y + x = x >> y + + z = z + 1 + z = z + 1.0 + z = z + 1.1 // ERROR "truncated to int" + z = z /* ERROR "mismatched types" */ + y + z = z /* ERROR "mismatched types" */ - y + z = z /* ERROR "mismatched types" */ * y + z = z /* ERROR "mismatched types" */ / y + z = z /* ERROR "mismatched types" */ % y + z = z << y + z = z >> y +} + +type myuint uint + +func _(x, y uint, z myuint) { + x = x + 1 + x = x + - /* ERROR "overflows uint" */ 1 + x = x + 1.0 + x = x + 1.1 // ERROR "truncated to uint" + x = x + y + x = x - y + x = x * y + x = x / y + x = x % y + x = x << y + x = x >> y + + z = z + 1 + z = x + - /* ERROR "overflows uint" */ 1 + z = z + 1.0 + z = z + 1.1 // ERROR "truncated to uint" + z = z /* ERROR "mismatched types" */ + y + z = z /* ERROR "mismatched types" */ - y + z = z /* ERROR "mismatched types" */ * y + z = z /* ERROR "mismatched types" */ / y + z = z /* ERROR "mismatched types" */ % y + z = z << y + z = z >> y +} + +type myfloat64 float64 + +func _(x, y float64, z myfloat64) { + x = x + 1 + x = x + -1 + x = x + 1.0 + x = x + 1.1 + x = x + y + x = x - y + x = x * y + x = x / y + x = x /* ERROR "not defined" */ % y + x = x /* ERRORx `operand x .* must be integer` */ << y + x = x /* ERRORx `operand x .* must be integer` */ >> y + + z = z + 1 + z = z + -1 + z = z + 1.0 + z = z + 1.1 + z = z /* ERROR "mismatched types" */ + y + z = z /* ERROR "mismatched types" */ - y + z = z /* ERROR "mismatched types" */ * y + z = z /* ERROR "mismatched types" */ / y + z = z /* ERROR "mismatched types" */ % y + z = z /* ERRORx `operand z .* must be integer` */ << y + z = z /* ERRORx `operand z .* must be integer` */ >> y +} + +type mystring string + +func _(x, y string, z mystring) { + x = x + "foo" + x = x /* ERROR "not defined" */ - "foo" + x = x /* ERROR "mismatched types string and untyped int" */ + 1 + x = x + y + x = x /* ERROR "not defined" */ - y + x = x /* ERROR "mismatched types string and untyped int" */* 10 +} + +func f() (a, b int) { return } + +func _(x int) { + _ = f /* ERROR "multiple-value f" */ () + 1 + _ = x + f /* ERROR "multiple-value f" */ () + _ = f /* ERROR "multiple-value f" */ () + f + _ = f /* ERROR "multiple-value f" */ () + f /* ERROR "multiple-value f" */ () +} diff --git a/go/src/internal/types/testdata/check/expr2.go b/go/src/internal/types/testdata/check/expr2.go new file mode 100644 index 0000000000000000000000000000000000000000..603f5ae190734f7de548f0c1227eda0e1e60b8c9 --- /dev/null +++ b/go/src/internal/types/testdata/check/expr2.go @@ -0,0 +1,260 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// comparisons + +package expr2 + +func _bool() { + const t = true == true + const f = true == false + _ = t /* ERRORx `operator .* not defined` */ < f + _ = 0 == t /* ERROR "mismatched types untyped int and untyped bool" */ + var b bool + var x, y float32 + b = x < y + _ = b + _ = struct{b bool}{x < y} +} + +// corner cases +var ( + v0 = nil == nil // ERROR "operator == not defined on untyped nil" +) + +func arrays() { + // basics + var a, b [10]int + _ = a == b + _ = a != b + _ = a /* ERROR "< not defined" */ < b + _ = a == nil /* ERROR "mismatched types" */ + + type C [10]int + var c C + _ = a == c + + type D [10]int + var d D + _ = c == d /* ERROR "mismatched types" */ + + var e [10]func() int + _ = e /* ERROR "[10]func() int cannot be compared" */ == e +} + +func structs() { + // basics + var s, t struct { + x int + a [10]float32 + _ bool + } + _ = s == t + _ = s != t + _ = s /* ERROR "< not defined" */ < t + _ = s == nil /* ERROR "mismatched types" */ + + type S struct { + x int + a [10]float32 + _ bool + } + type T struct { + x int + a [10]float32 + _ bool + } + var ss S + var tt T + _ = s == ss + _ = ss == tt /* ERROR "mismatched types" */ + + var u struct { + x int + a [10]map[string]int + } + _ = u /* ERROR "cannot be compared" */ == u +} + +func pointers() { + // nil + _ = nil == nil // ERROR "operator == not defined on untyped nil" + _ = nil != nil // ERROR "operator != not defined on untyped nil" + _ = nil /* ERROR "< not defined" */ < nil + _ = nil /* ERROR "<= not defined" */ <= nil + _ = nil /* ERROR "> not defined" */ > nil + _ = nil /* ERROR ">= not defined" */ >= nil + + // basics + var p, q *int + _ = p == q + _ = p != q + + _ = p == nil + _ = p != nil + _ = nil == q + _ = nil != q + + _ = p /* ERROR "< not defined" */ < q + _ = p /* ERROR "<= not defined" */ <= q + _ = p /* ERROR "> not defined" */ > q + _ = p /* ERROR ">= not defined" */ >= q + + // various element types + type ( + S1 struct{} + S2 struct{} + P1 *S1 + P2 *S2 + ) + var ( + ps1 *S1 + ps2 *S2 + p1 P1 + p2 P2 + ) + _ = ps1 == ps1 + _ = ps1 == ps2 /* ERROR "mismatched types" */ + _ = ps2 == ps1 /* ERROR "mismatched types" */ + + _ = p1 == p1 + _ = p1 == p2 /* ERROR "mismatched types" */ + + _ = p1 == ps1 +} + +func channels() { + // basics + var c, d chan int + _ = c == d + _ = c != d + _ = c == nil + _ = c /* ERROR "< not defined" */ < d + + // various element types (named types) + type ( + C1 chan int + C1r <-chan int + C1s chan<- int + C2 chan float32 + ) + var ( + c1 C1 + c1r C1r + c1s C1s + c1a chan int + c2 C2 + ) + _ = c1 == c1 + _ = c1 == c1r /* ERROR "mismatched types" */ + _ = c1 == c1s /* ERROR "mismatched types" */ + _ = c1r == c1s /* ERROR "mismatched types" */ + _ = c1 == c1a + _ = c1a == c1 + _ = c1 == c2 /* ERROR "mismatched types" */ + _ = c1a == c2 /* ERROR "mismatched types" */ + + // various element types (unnamed types) + var ( + d1 chan int + d1r <-chan int + d1s chan<- int + d1a chan<- int + d2 chan float32 + ) + _ = d1 == d1 + _ = d1 == d1r + _ = d1 == d1s + _ = d1r == d1s /* ERROR "mismatched types" */ + _ = d1 == d1a + _ = d1a == d1 + _ = d1 == d2 /* ERROR "mismatched types" */ + _ = d1a == d2 /* ERROR "mismatched types" */ +} + +// for interfaces test +type S1 struct{} +type S11 struct{} +type S2 struct{} +func (*S1) m() int +func (*S11) m() int +func (*S11) n() +func (*S2) m() float32 + +func interfaces() { + // basics + var i, j interface{ m() int } + _ = i == j + _ = i != j + _ = i == nil + _ = i /* ERROR "< not defined" */ < j + + // various interfaces + var ii interface { m() int; n() } + var k interface { m() float32 } + _ = i == ii + _ = i == k /* ERROR "mismatched types" */ + + // interfaces vs values + var s1 S1 + var s11 S11 + var s2 S2 + + _ = i == 0 /* ERROR "invalid operation: i == 0 (mismatched types interface{m() int} and untyped int)" */ + _ = i == s1 /* ERROR "mismatched types" */ + _ = i == &s1 + _ = i == &s11 + + _ = i == s2 /* ERROR "mismatched types" */ + _ = i == & /* ERROR "mismatched types" */ s2 + + // issue #28164 + // testcase from issue + _ = interface{}(nil) == [ /* ERROR "slice can only be compared to nil" */ ]int(nil) + + // related cases + var e interface{} + var s []int + var x int + _ = e == s // ERROR "slice can only be compared to nil" + _ = s /* ERROR "slice can only be compared to nil" */ == e + _ = e /* ERROR "operator < not defined on interface" */ < x + _ = x < e // ERROR "operator < not defined on interface" +} + +func slices() { + // basics + var s []int + _ = s == nil + _ = s != nil + _ = s /* ERROR "< not defined" */ < nil + + // slices are not otherwise comparable + _ = s /* ERROR "slice can only be compared to nil" */ == s + _ = s /* ERROR "< not defined" */ < s +} + +func maps() { + // basics + var m map[string]int + _ = m == nil + _ = m != nil + _ = m /* ERROR "< not defined" */ < nil + + // maps are not otherwise comparable + _ = m /* ERROR "map can only be compared to nil" */ == m + _ = m /* ERROR "< not defined" */ < m +} + +func funcs() { + // basics + var f func(int) float32 + _ = f == nil + _ = f != nil + _ = f /* ERROR "< not defined" */ < nil + + // funcs are not otherwise comparable + _ = f /* ERROR "func can only be compared to nil" */ == f + _ = f /* ERROR "< not defined" */ < f +} diff --git a/go/src/internal/types/testdata/check/expr3.go b/go/src/internal/types/testdata/check/expr3.go new file mode 100644 index 0000000000000000000000000000000000000000..91534cdd629b4007ce0241b7563223eddfdc7332 --- /dev/null +++ b/go/src/internal/types/testdata/check/expr3.go @@ -0,0 +1,564 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package expr3 + +import "time" + +func indexes() { + _ = 1 /* ERROR "cannot index" */ [0] + _ = indexes /* ERROR "cannot index" */ [0] + _ = ( /* ERROR "cannot slice" */ 12 + 3)[1:2] + + var a [10]int + _ = a[true /* ERROR "cannot convert" */ ] + _ = a["foo" /* ERROR "cannot convert" */ ] + _ = a[1.1 /* ERROR "truncated" */ ] + _ = a[1.0] + _ = a[- /* ERROR "negative" */ 1] + _ = a[- /* ERROR "negative" */ 1 :] + _ = a[: - /* ERROR "negative" */ 1] + _ = a[: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ] + _ = a[0: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ] + _ = a[0: /* ERROR "middle index required" */ :10] + _ = a[:10:10] + + var a0 int + a0 = a[0] + _ = a0 + var a1 int32 + a1 = a /* ERRORx `cannot use .* in assignment` */ [1] + _ = a1 + + _ = a[9] + _ = a[10 /* ERRORx `index .* out of bounds` */ ] + _ = a[1 /* ERROR "overflows" */ <<100] + _ = a[1<< /* ERROR "constant shift overflow" */ 1000] // no out-of-bounds follow-on error + _ = a[10:] + _ = a[:10] + _ = a[10:10] + _ = a[11 /* ERRORx `index .* out of bounds` */ :] + _ = a[: 11 /* ERRORx `index .* out of bounds` */ ] + _ = a[: 1 /* ERROR "overflows" */ <<100] + _ = a[:10:10] + _ = a[:11 /* ERRORx `index .* out of bounds` */ :10] + _ = a[:10:11 /* ERRORx `index .* out of bounds` */ ] + _ = a[10:0 /* ERROR "invalid slice indices" */ :10] + _ = a[0:10:0 /* ERROR "invalid slice indices" */ ] + _ = a[10:0 /* ERROR "invalid slice indices" */:0] + _ = &a /* ERROR "cannot take address" */ [:10] + + pa := &a + _ = pa[9] + _ = pa[10 /* ERRORx `index .* out of bounds` */ ] + _ = pa[1 /* ERROR "overflows" */ <<100] + _ = pa[10:] + _ = pa[:10] + _ = pa[10:10] + _ = pa[11 /* ERRORx `index .* out of bounds` */ :] + _ = pa[: 11 /* ERRORx `index .* out of bounds` */ ] + _ = pa[: 1 /* ERROR "overflows" */ <<100] + _ = pa[:10:10] + _ = pa[:11 /* ERRORx `index .* out of bounds` */ :10] + _ = pa[:10:11 /* ERRORx `index .* out of bounds` */ ] + _ = pa[10:0 /* ERROR "invalid slice indices" */ :10] + _ = pa[0:10:0 /* ERROR "invalid slice indices" */ ] + _ = pa[10:0 /* ERROR "invalid slice indices" */ :0] + _ = &pa /* ERROR "cannot take address" */ [:10] + + var b [0]int + _ = b[0 /* ERRORx `index .* out of bounds` */ ] + _ = b[:] + _ = b[0:] + _ = b[:0] + _ = b[0:0] + _ = b[0:0:0] + _ = b[1 /* ERRORx `index .* out of bounds` */ :0:0] + + var s []int + _ = s[- /* ERROR "negative" */ 1] + _ = s[- /* ERROR "negative" */ 1 :] + _ = s[: - /* ERROR "negative" */ 1] + _ = s[0] + _ = s[1:2] + _ = s[2:1 /* ERROR "invalid slice indices" */ ] + _ = s[2:] + _ = s[: 1 /* ERROR "overflows" */ <<100] + _ = s[1 /* ERROR "overflows" */ <<100 :] + _ = s[1 /* ERROR "overflows" */ <<100 : 1 /* ERROR "overflows" */ <<100] + _ = s[: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ] + _ = s[:10:10] + _ = s[10:0 /* ERROR "invalid slice indices" */ :10] + _ = s[0:10:0 /* ERROR "invalid slice indices" */ ] + _ = s[10:0 /* ERROR "invalid slice indices" */ :0] + _ = &s /* ERROR "cannot take address" */ [:10] + + var m map[string]int + _ = m[0 /* ERRORx `cannot use .* in map index` */ ] + _ = m /* ERROR "cannot slice" */ ["foo" : "bar"] + _ = m["foo"] + // ok is of type bool + type mybool bool + var ok mybool + _, ok = m["bar"] + _ = ok + _ = m/* ERROR "mismatched types int and untyped string" */[0 /* ERROR "cannot use 0" */ ] + "foo" + + var t string + _ = t[- /* ERROR "negative" */ 1] + _ = t[- /* ERROR "negative" */ 1 :] + _ = t[: - /* ERROR "negative" */ 1] + _ = t[1:2:3 /* ERROR "3-index slice of string" */ ] + _ = "foo"[1:2:3 /* ERROR "3-index slice of string" */ ] + var t0 byte + t0 = t[0] + _ = t0 + var t1 rune + t1 = t /* ERRORx `cannot use .* in assignment` */ [2] + _ = t1 + _ = ("foo" + "bar")[5] + _ = ("foo" + "bar")[6 /* ERRORx `index .* out of bounds` */ ] + + const c = "foo" + _ = c[- /* ERROR "negative" */ 1] + _ = c[- /* ERROR "negative" */ 1 :] + _ = c[: - /* ERROR "negative" */ 1] + var c0 byte + c0 = c[0] + _ = c0 + var c2 float32 + c2 = c /* ERRORx `cannot use .* in assignment` */ [2] + _ = c[3 /* ERRORx `index .* out of bounds` */ ] + _ = ""[0 /* ERRORx `index .* out of bounds` */ ] + _ = c2 + + _ = s[1<<30] // no compile-time error here + + // issue 4913 + type mystring string + var ss string + var ms mystring + var i, j int + ss = "foo"[1:2] + ss = "foo"[i:j] + ms = "foo" /* ERRORx `cannot use .* in assignment` */ [1:2] + ms = "foo" /* ERRORx `cannot use .* in assignment` */ [i:j] + _, _ = ss, ms +} + +type T struct { + x int + y func() +} + +func (*T) m() {} + +func method_expressions() { + _ = T.a /* ERROR "no field or method" */ + _ = T.x /* ERROR "has no method" */ + _ = T.m /* ERROR "invalid method expression T.m (needs pointer receiver (*T).m)" */ + _ = (*T).m + + var f func(*T) = T.m /* ERROR "invalid method expression T.m (needs pointer receiver (*T).m)" */ + var g func(*T) = (*T).m + _, _ = f, g + + _ = T.y /* ERROR "has no method" */ + _ = (*T).y /* ERROR "has no method" */ +} + +func struct_literals() { + type T0 struct { + a, b, c int + } + + type T1 struct { + T0 + a, b int + u float64 + s string + } + + // keyed elements + _ = T1{} + _ = T1{a: 0, 1 /* ERRORx `mixture of .* elements` */ } + _ = T1{aa /* ERROR "unknown field" */ : 0} + _ = T1{1 /* ERROR "invalid field name" */ : 0} + _ = T1{a: 0, s: "foo", u: 0, a /* ERROR "duplicate field" */: 10} + _ = T1{a: "foo" /* ERRORx `cannot use .* in struct literal` */ } + _ = T1{c /* ERROR "unknown field" */ : 0} + _ = T1{T0: { /* ERROR "missing type" */ }} // struct literal element type may not be elided + _ = T1{T0: T0{}} + _ = T1{T0 /* ERROR "invalid field name" */ .a: 0} + + // unkeyed elements + _ = T0{1, 2, 3} + _ = T0{1, b /* ERROR "mixture" */ : 2, 3} + _ = T0{1, 2} /* ERROR "too few values" */ + _ = T0{1, 2, 3, 4 /* ERROR "too many values" */ } + _ = T0{1, "foo" /* ERRORx `cannot use .* in struct literal` */, 3.4 /* ERRORx `cannot use .*\(truncated\)` */} + + // invalid type + type P *struct{ + x int + } + _ = P /* ERROR "invalid composite literal type" */ {} + + // unexported fields + _ = time.Time{} + _ = time.Time{sec /* ERROR "unknown field" */ : 0} + _ = time.Time{ + 0 /* ERROR "implicit assignment to unexported field wall in struct literal" */, + 0 /* ERROR "implicit assignment" */ , + nil /* ERROR "implicit assignment" */ , + } +} + +func array_literals() { + type A0 [0]int + _ = A0{} + _ = A0{0 /* ERRORx `index .* out of bounds` */} + _ = A0{0 /* ERRORx `index .* out of bounds` */ : 0} + + type A1 [10]int + _ = A1{} + _ = A1{0, 1, 2} + _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /* ERRORx `index .* out of bounds` */ } + _ = A1{- /* ERROR "negative" */ 1: 0} + _ = A1{8: 8, 9} + _ = A1{8: 8, 9, 10 /* ERRORx `index .* out of bounds` */ } + _ = A1{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} + _ = A1{5: 5, 6, 7, 3: 3, 4} + _ = A1{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ } + _ = A1{10 /* ERRORx `index .* out of bounds` */ : 10, 10 /* ERRORx `index .* out of bounds` */ : 10} + _ = A1{5: 5, 6, 7, 3: 3, 1 /* ERROR "overflows" */ <<100: 4, 5 /* ERROR "duplicate index" */ } + _ = A1{5: 5, 6, 7, 4: 4, 1 /* ERROR "overflows" */ <<100: 4} + _ = A1{2.0} + _ = A1{2.1 /* ERROR "truncated" */ } + _ = A1{"foo" /* ERRORx `cannot use .* in array or slice literal` */ } + + // indices must be integer constants + i := 1 + const f = 2.1 + const s = "foo" + _ = A1{i /* ERROR "index i must be integer constant" */ : 0} + _ = A1{f /* ERROR "truncated" */ : 0} + _ = A1{s /* ERROR "cannot convert" */ : 0} + + a0 := [...]int{} + assert(len(a0) == 0) + + a1 := [...]int{0, 1, 2} + assert(len(a1) == 3) + var a13 [3]int + var a14 [4]int + a13 = a1 + a14 = a1 /* ERRORx `cannot use .* in assignment` */ + _, _ = a13, a14 + + a2 := [...]int{- /* ERROR "negative" */ 1: 0} + _ = a2 + + a3 := [...]int{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} + assert(len(a3) == 5) // somewhat arbitrary + + a4 := [...]complex128{0, 1, 2, 1<<10-2: -1i, 1i, 400: 10, 12, 14} + assert(len(a4) == 1024) + + // composite literal element types may be elided + type T []int + _ = [10]T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}} + a6 := [...]T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}} + assert(len(a6) == 8) + + // recursively so + _ = [10][10]T{{}, [10]T{{}}, {{1, 2, 3}}} + + // from the spec + type Point struct { x, y float32 } + _ = [...]Point{Point{1.5, -3.5}, Point{0, 0}} + _ = [...]Point{{1.5, -3.5}, {0, 0}} + _ = [][]int{[]int{1, 2, 3}, []int{4, 5}} + _ = [][]int{{1, 2, 3}, {4, 5}} + _ = [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}} + _ = [...]*Point{{1.5, -3.5}, {0, 0}} +} + +func slice_literals() { + type S0 []int + _ = S0{} + _ = S0{0, 1, 2} + _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + _ = S0{- /* ERROR "negative" */ 1: 0} + _ = S0{8: 8, 9} + _ = S0{8: 8, 9, 10} + _ = S0{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4} + _ = S0{5: 5, 6, 7, 3: 3, 4} + _ = S0{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ } + _ = S0{10: 10, 10 /* ERROR "duplicate index" */ : 10} + _ = S0{5: 5, 6, 7, 3: 3, 1 /* ERROR "overflows" */ <<100: 4, 5 /* ERROR "duplicate index" */ } + _ = S0{5: 5, 6, 7, 4: 4, 1 /* ERROR "overflows" */ <<100: 4} + _ = S0{2.0} + _ = S0{2.1 /* ERROR "truncated" */ } + _ = S0{"foo" /* ERRORx `cannot use .* in array or slice literal` */ } + + // indices must be resolved correctly + const index1 = 1 + _ = S0{index1: 1} + _ = S0{index2: 2} + _ = S0{index3 /* ERROR "undefined" */ : 3} + + // indices must be integer constants + i := 1 + const f = 2.1 + const s = "foo" + _ = S0{i /* ERROR "index i must be integer constant" */ : 0} + _ = S0{f /* ERROR "truncated" */ : 0} + _ = S0{s /* ERROR "cannot convert" */ : 0} + + // composite literal element types may be elided + type T []int + _ = []T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}} + _ = [][]int{{1, 2, 3}, {4, 5}} + + // recursively so + _ = [][]T{{}, []T{{}}, {{1, 2, 3}}} + + // issue 17954 + type T0 *struct { s string } + _ = []T0{{}} + _ = []T0{{"foo"}} + + type T1 *struct{ int } + _ = []T1{} + _ = []T1{{0}, {1}, {2}} + + type T2 T1 + _ = []T2{} + _ = []T2{{0}, {1}, {2}} + + _ = map[T0]T2{} + _ = map[T0]T2{{}: {}} +} + +const index2 int = 2 + +type N int +func (N) f() {} + +func map_literals() { + type M0 map[string]int + type M1 map[bool]int + type M2 map[*int]int + + _ = M0{} + _ = M0{1 /* ERROR "missing key" */ } + _ = M0{1 /* ERRORx `cannot use .* in map literal` */ : 2} + _ = M0{"foo": "bar" /* ERRORx `cannot use .* in map literal` */ } + _ = M0{"foo": 1, "bar": 2, "foo" /* ERROR "duplicate key" */ : 3 } + + _ = map[interface{}]int{2: 1, 2 /* ERROR "duplicate key" */ : 1} + _ = map[interface{}]int{int(2): 1, int16(2): 1} + _ = map[interface{}]int{int16(2): 1, int16 /* ERROR "duplicate key" */ (2): 1} + + type S string + + _ = map[interface{}]int{"a": 1, "a" /* ERROR "duplicate key" */ : 1} + _ = map[interface{}]int{"a": 1, S("a"): 1} + _ = map[interface{}]int{S("a"): 1, S /* ERROR "duplicate key" */ ("a"): 1} + _ = map[interface{}]int{1.0: 1, 1.0 /* ERROR "duplicate key" */: 1} + _ = map[interface{}]int{int64(-1): 1, int64 /* ERROR "duplicate key" */ (-1) : 1} + _ = map[interface{}]int{^uint64(0): 1, ^ /* ERROR "duplicate key" */ uint64(0): 1} + _ = map[interface{}]int{complex(1,2): 1, complex /* ERROR "duplicate key" */ (1,2) : 1} + + type I interface { + f() + } + + _ = map[I]int{N(0): 1, N(2): 1} + _ = map[I]int{N(2): 1, N /* ERROR "duplicate key" */ (2): 1} + + // map keys must be resolved correctly + key1 := "foo" + _ = M0{key1: 1} + _ = M0{key2: 2} + _ = M0{key3 /* ERROR "undefined" */ : 2} + + var value int + _ = M1{true: 1, false: 0} + _ = M2{nil: 0, &value: 1} + + // composite literal element types may be elided + type T [2]int + _ = map[int]T{0: T{3, 4}, 1: {5, 6}} + + // recursively so + _ = map[int][]T{0: {}, 1: {{}, T{1, 2}}} + + // composite literal key types may be elided + _ = map[T]int{T{3, 4}: 0, {5, 6}: 1} + + // recursively so + _ = map[[2]T]int{{}: 0, {{}}: 1, [2]T{{}}: 2, {T{1, 2}}: 3} + + // composite literal element and key types may be elided + _ = map[T]T{{}: {}, {1, 2}: T{3, 4}, T{4, 5}: {}} + _ = map[T]M0{{} : {}, T{1, 2}: M0{"foo": 0}, {1, 3}: {"foo": 1}} + + // recursively so + _ = map[[2]T][]T{{}: {}, {{}}: {{}, T{1, 2}}, [2]T{{}}: nil, {T{1, 2}}: {{}, {}}} + + // from the spec + type Point struct { x, y float32 } + _ = map[string]Point{"orig": {0, 0}} + _ = map[*Point]string{{0, 0}: "orig"} + + // issue 17954 + type T0 *struct{ s string } + type T1 *struct{ int } + type T2 T1 + + _ = map[T0]T2{} + _ = map[T0]T2{{}: {}} +} + +var key2 string = "bar" + +type I interface { + m() +} + +type I2 interface { + m(int) +} + +type T1 struct{} +type T2 struct{} + +func (T2) m(int) {} + +type mybool bool + +func type_asserts() { + var x int + _ = x /* ERROR "not an interface" */ .(int) + + var e interface{} + var ok bool + x, ok = e.(int) + _ = ok + + // ok value is of type bool + var myok mybool + _, myok = e.(int) + _ = myok + + var t I + _ = t /* ERRORx `use of .* outside type switch` */ .(type) + _ = t /* ERROR "m has pointer receiver" */ .(T) + _ = t.(*T) + _ = t /* ERROR "missing method m" */ .(T1) + _ = t /* ERROR "wrong type for method m" */ .(T2) + _ = t /* STRICT "wrong type for method m" */ .(I2) // only an error in strict mode (issue 8561) + + // e doesn't statically have an m, but may have one dynamically. + _ = e.(I2) +} + +func f0() {} +func f1(x int) {} +func f2(u float32, s string) {} +func fs(s []byte) {} +func fv(x ...int) {} +func fi(x ... interface{}) {} +func (T) fm(x ...int) + +func g0() {} +func g1() int { return 0} +func g2() (u float32, s string) { return } +func gs() []byte { return nil } + +func _calls() { + var x int + var y float32 + var s []int + + f0() + _ = f0 /* ERROR "used as value" */ () + f0(g0 /* ERROR "too many arguments" */ ) + + f1(0) + f1(x) + f1(10.0) + f1() /* ERROR "not enough arguments in call to f1\n\thave ()\n\twant (int)" */ + f1(x, y /* ERROR "too many arguments in call to f1\n\thave (int, float32)\n\twant (int)" */ ) + f1(s /* ERRORx `cannot use .* in argument` */ ) + f1(x ... /* ERROR "cannot use ..." */ ) + f1(g0 /* ERROR "used as value" */ ()) + f1(g1()) + f1(g2 /* ERROR "too many arguments in call to f1\n\thave (float32, string)\n\twant (int)" */ ()) + + f2() /* ERROR "not enough arguments in call to f2\n\thave ()\n\twant (float32, string)" */ + f2(3.14) /* ERROR "not enough arguments in call to f2\n\thave (number)\n\twant (float32, string)" */ + f2(3.14, "foo") + f2(x /* ERRORx `cannot use .* in argument` */ , "foo") + f2(g0 /* ERROR "used as value" */ ()) /* ERROR "not enough arguments in call to f2\n\thave (func())\n\twant (float32, string)" */ + f2(g1()) /* ERROR "not enough arguments in call to f2\n\thave (int)\n\twant (float32, string)" */ + f2(g2()) + + fs() /* ERROR "not enough arguments" */ + fs(g0 /* ERROR "used as value" */ ()) + fs(g1 /* ERRORx `cannot use .* in argument` */ ()) + fs(g2 /* ERROR "too many arguments" */ ()) + fs(gs()) + + fv() + fv(1, 2.0, x) + fv(s /* ERRORx `cannot use .* in argument` */ ) + fv(s...) + fv(x /* ERROR "cannot use" */ ...) + fv(1, s /* ERROR "too many arguments" */ ...) + fv(gs /* ERRORx `cannot use .* in argument` */ ()) + fv(gs /* ERRORx `cannot use .* in argument` */ ()...) + + var t T + t.fm() + t.fm(1, 2.0, x) + t.fm(s /* ERRORx `cannot use .* in argument` */ ) + t.fm(g1()) + t.fm(1, s /* ERROR "too many arguments" */ ...) + t.fm(gs /* ERRORx `cannot use .* in argument` */ ()) + t.fm(gs /* ERRORx `cannot use .* in argument` */ ()...) + + T.fm(t, ) + T.fm(t, 1, 2.0, x) + T.fm(t, s /* ERRORx `cannot use .* in argument` */ ) + T.fm(t, g1()) + T.fm(t, 1, s /* ERROR "too many arguments" */ ...) + T.fm(t, gs /* ERRORx `cannot use .* in argument` */ ()) + T.fm(t, gs /* ERRORx `cannot use .* in argument` */ ()...) + + var i interface{ fm(x ...int) } = t + i.fm() + i.fm(1, 2.0, x) + i.fm(s /* ERRORx `cannot use .* in argument` */ ) + i.fm(g1()) + i.fm(1, s /* ERROR "too many arguments" */ ...) + i.fm(gs /* ERRORx `cannot use .* in argument` */ ()) + i.fm(gs /* ERRORx `cannot use .* in argument` */ ()...) + + fi() + fi(1, 2.0, x, 3.14, "foo") + fi(g2()) + fi(0, g2) + fi(0, g2 /* ERROR "multiple-value g2" */ ()) +} + +func issue6344() { + type T []interface{} + var x T + fi(x...) // ... applies also to named slices +} diff --git a/go/src/internal/types/testdata/check/funcinference.go b/go/src/internal/types/testdata/check/funcinference.go new file mode 100644 index 0000000000000000000000000000000000000000..e0e978f25a331dcd994dfb2eab6ad4e17055593e --- /dev/null +++ b/go/src/internal/types/testdata/check/funcinference.go @@ -0,0 +1,112 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package funcInference + +import "strconv" + +type any interface{} + +func f0[A any, B interface{*C}, C interface{*D}, D interface{*A}](A, B, C, D) {} +func _() { + f := f0[string] + f("a", nil, nil, nil) + f0("a", nil, nil, nil) +} + +func f1[A any, B interface{*A}](A, B) {} +func _() { + f := f1[int] + f(int(0), new(int)) + f1(int(0), new(int)) +} + +func f2[A any, B interface{[]A}](A, B) {} +func _() { + f := f2[byte] + f(byte(0), []byte{}) + f2(byte(0), []byte{}) +} + +// Embedding stand-alone type parameters is not permitted for now. Disabled. +// func f3[A any, B interface{~C}, C interface{~*A}](A, B, C) +// func _() { +// f := f3[int] +// var x int +// f(x, &x, &x) +// f3(x, &x, &x) +// } + +func f4[A any, B interface{[]C}, C interface{*A}](A, B, C) {} +func _() { + f := f4[int] + var x int + f(x, []*int{}, &x) + f4(x, []*int{}, &x) +} + +func f5[A interface{struct{b B; c C}}, B any, C interface{*B}](x B) A { panic(0) } +func _() { + x := f5(1.2) + var _ float64 = x.b + var _ float64 = *x.c +} + +func f6[A any, B interface{~struct{f []A}}](B) A { panic(0) } +func _() { + x := f6(struct{f []string}{}) + var _ string = x +} + +func f7[A interface{*B}, B interface{~*A}]() {} + +// More realistic examples + +func Double[S interface{ ~[]E }, E interface{ ~int | ~int8 | ~int16 | ~int32 | ~int64 }](s S) S { + r := make(S, len(s)) + for i, v := range s { + r[i] = v + v + } + return r +} + +type MySlice []int + +var _ = Double(MySlice{1}) + +// From the draft design. + +type Setter[B any] interface { + Set(string) + *B +} + +func FromStrings[T interface{}, PT Setter[T]](s []string) []T { + result := make([]T, len(s)) + for i, v := range s { + // The type of &result[i] is *T which is in the type set + // of Setter, so we can convert it to PT. + p := PT(&result[i]) + // PT has a Set method. + p.Set(v) + } + return result +} + +type Settable int + +func (p *Settable) Set(s string) { + i, _ := strconv.Atoi(s) // real code should not ignore the error + *p = Settable(i) +} + +var _ = FromStrings[Settable]([]string{"1", "2"}) + +// Suitable error message when the type parameter is provided (rather than inferred). + +func f8[P, Q any](P, Q) {} + +func _(s string) { + f8[int](s /* ERROR "cannot use s (variable of type string) as int value in argument to f8[int]" */ , s) +} diff --git a/go/src/internal/types/testdata/check/go1_12.go b/go/src/internal/types/testdata/check/go1_12.go new file mode 100644 index 0000000000000000000000000000000000000000..f1266c23cc25789907962b8716edcc19ff3b3e07 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_12.go @@ -0,0 +1,36 @@ +// -lang=go1.12 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +package p + +// numeric literals +const ( + _ = 1_000 // ERROR "underscore in numeric literal requires go1.13 or later" + _ = 0b111 // ERROR "binary literal requires go1.13 or later" + _ = 0o567 // ERROR "0o/0O-style octal literal requires go1.13 or later" + _ = 0xabc // ok + _ = 0x0p1 // ERROR "hexadecimal floating-point literal requires go1.13 or later" + + _ = 0b111 // ERROR "binary" + _ = 0o567 // ERROR "octal" + _ = 0xabc // ok + _ = 0x0p1 // ERROR "hexadecimal floating-point" + + _ = 1_000i // ERROR "underscore" + _ = 0b111i // ERROR "binary" + _ = 0o567i // ERROR "octal" + _ = 0xabci // ERROR "hexadecimal floating-point" + _ = 0x0p1i // ERROR "hexadecimal floating-point" +) + +// signed shift counts +var ( + s int + _ = 1 << s // ERROR "invalid operation: signed shift count s (variable of type int) requires go1.13 or later" + _ = 1 >> s // ERROR "signed shift count" +) diff --git a/go/src/internal/types/testdata/check/go1_13.go b/go/src/internal/types/testdata/check/go1_13.go new file mode 100644 index 0000000000000000000000000000000000000000..cc7861d616100222ffddabec24b6cc75d2e4dadc --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_13.go @@ -0,0 +1,23 @@ +// -lang=go1.13 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +package p + +// interface embedding + +type I interface { m() } + +type _ interface { + m() + I // ERROR "duplicate method m" +} + +type _ interface { + I + I // ERROR "duplicate method m" +} diff --git a/go/src/internal/types/testdata/check/go1_16.go b/go/src/internal/types/testdata/check/go1_16.go new file mode 100644 index 0000000000000000000000000000000000000000..9675b292b627f3a980f8efdd1aa4c47ac433da78 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_16.go @@ -0,0 +1,15 @@ +// -lang=go1.16 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (*Array)(s /* ERROR "requires go1.17 or later" */ ) diff --git a/go/src/internal/types/testdata/check/go1_19.go b/go/src/internal/types/testdata/check/go1_19.go new file mode 100644 index 0000000000000000000000000000000000000000..b6cff4f4653071aff0f031a52c64297591862387 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_19.go @@ -0,0 +1,15 @@ +// -lang=go1.19 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (Array)(s /* ERROR "requires go1.20 or later" */) diff --git a/go/src/internal/types/testdata/check/go1_19_20.go b/go/src/internal/types/testdata/check/go1_19_20.go new file mode 100644 index 0000000000000000000000000000000000000000..52e5dfdc4a7786399a30ac299cb4f5f6171c1855 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_19_20.go @@ -0,0 +1,17 @@ +// -lang=go1.19 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.20 + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (Array)(s /* ok */) diff --git a/go/src/internal/types/testdata/check/go1_20_19.go b/go/src/internal/types/testdata/check/go1_20_19.go new file mode 100644 index 0000000000000000000000000000000000000000..892179c72fc02f01da5d32a3d30fabf7f0903f86 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_20_19.go @@ -0,0 +1,17 @@ +// -lang=go1.20 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.19 + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (Array)(s /* ok because file versions below go1.21 set the language version to go1.21 */) diff --git a/go/src/internal/types/testdata/check/go1_21_19.go b/go/src/internal/types/testdata/check/go1_21_19.go new file mode 100644 index 0000000000000000000000000000000000000000..febf653cb1b49cb96b9576c54921c402b913c9bf --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_21_19.go @@ -0,0 +1,17 @@ +// -lang=go1.21 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.19 + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (Array)(s /* ok because file versions below go1.21 set the language version to go1.21 */) diff --git a/go/src/internal/types/testdata/check/go1_21_22.go b/go/src/internal/types/testdata/check/go1_21_22.go new file mode 100644 index 0000000000000000000000000000000000000000..3939b7b1d868c0518edf9aa5dc53897099ad0cd1 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_21_22.go @@ -0,0 +1,16 @@ +// -lang=go1.21 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.22 + +package p + +func f() { + for _ = range /* ok because of upgrade to 1.22 */ 10 { + } +} diff --git a/go/src/internal/types/testdata/check/go1_22_21.go b/go/src/internal/types/testdata/check/go1_22_21.go new file mode 100644 index 0000000000000000000000000000000000000000..f910ecb59cbc7812df00e91c8d1db8b320cb2616 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_22_21.go @@ -0,0 +1,16 @@ +// -lang=go1.22 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.21 + +package p + +func f() { + for _ = range 10 /* ERROR "requires go1.22 or later" */ { + } +} diff --git a/go/src/internal/types/testdata/check/go1_25.go b/go/src/internal/types/testdata/check/go1_25.go new file mode 100644 index 0000000000000000000000000000000000000000..3799bc02b46466a1ffd6dc162a8db4a329a83d5c --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_25.go @@ -0,0 +1,18 @@ +// -lang=go1.25 + +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.25 + +package p + +func f(x int) { + _ = new /* ERROR "new(123) requires go1.26 or later" */ (123) + _ = new /* ERROR "new(x) requires go1.26 or later" */ (x) + _ = new /* ERROR "new(f) requires go1.26 or later" */ (f) + _ = new /* ERROR "new(1 < 2) requires go1.26 or later" */ (1 < 2) +} diff --git a/go/src/internal/types/testdata/check/go1_8.go b/go/src/internal/types/testdata/check/go1_8.go new file mode 100644 index 0000000000000000000000000000000000000000..d386d5e60b88ef2dffdfe9a83c4e2f8f5be3fbd2 --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_8.go @@ -0,0 +1,12 @@ +// -lang=go1.8 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +package p + +// type alias declarations +type any = /* ERROR "type alias requires go1.9 or later" */ interface{} diff --git a/go/src/internal/types/testdata/check/go1_xx_19.go b/go/src/internal/types/testdata/check/go1_xx_19.go new file mode 100644 index 0000000000000000000000000000000000000000..01f6b7d2ebb3a23438fa41bc04be9c4dc3f58abe --- /dev/null +++ b/go/src/internal/types/testdata/check/go1_xx_19.go @@ -0,0 +1,15 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check Go language version-specific errors. + +//go:build go1.19 + +package p + +type Slice []byte +type Array [8]byte + +var s Slice +var p = (Array)(s /* ok because Go 1.X prior to Go 1.21 ignored the //go:build go1.19 */) diff --git a/go/src/internal/types/testdata/check/gotos.go b/go/src/internal/types/testdata/check/gotos.go new file mode 100644 index 0000000000000000000000000000000000000000..069a94bbbf42f930a972e260702b942ef61bb665 --- /dev/null +++ b/go/src/internal/types/testdata/check/gotos.go @@ -0,0 +1,560 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a modified copy of $GOROOT/test/goto.go. + +package gotos + +var ( + i, n int + x []int + c chan int + m map[int]int + s string +) + +// goto after declaration okay +func _() { + x := 1 + goto L +L: + _ = x +} + +// goto before declaration okay +func _() { + goto L +L: + x := 1 + _ = x +} + +// goto across declaration not okay +func _() { + goto L /* ERROR "goto L jumps over variable declaration at line 36" */ + x := 1 + _ = x +L: +} + +// goto across declaration in inner scope okay +func _() { + goto L + { + x := 1 + _ = x + } +L: +} + +// goto across declaration after inner scope not okay +func _() { + goto L /* ERROR "goto L jumps over variable declaration at line 58" */ + { + x := 1 + _ = x + } + x := 1 + _ = x +L: +} + +// goto across declaration in reverse okay +func _() { +L: + x := 1 + _ = x + goto L +} + +func _() { +L: L1: + x := 1 + _ = x + goto L + goto L1 +} + +// error shows first offending variable +func _() { + goto L /* ERROR "goto L jumps over variable declaration at line 84" */ + x := 1 + _ = x + y := 1 + _ = y +L: +} + +// goto not okay even if code path is dead +func _() { + goto L /* ERROR "goto L jumps over variable declaration" */ + x := 1 + _ = x + y := 1 + _ = y + return +L: +} + +// goto into outer block okay +func _() { + { + goto L + } +L: +} + +func _() { + { + goto L + goto L1 + } +L: L1: +} + +// goto backward into outer block okay +func _() { +L: + { + goto L + } +} + +func _() { +L: L1: + { + goto L + goto L1 + } +} + +// goto into inner block not okay +func _() { + goto L /* ERROR "goto L jumps into block" */ + { + L: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + goto L1 /* ERROR "goto L1 jumps into block" */ + { + L: L1: + } +} + +// goto backward into inner block still not okay +func _() { + { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + { + L: L1: + } + goto L /* ERROR "goto L jumps into block" */ + goto L1 /* ERROR "goto L1 jumps into block" */ +} + +// error shows first (outermost) offending block +func _() { + goto L /* ERROR "goto L jumps into block" */ + { + { + { + L: + } + } + } +} + +// error prefers block diagnostic over declaration diagnostic +func _() { + goto L /* ERROR "goto L jumps into block" */ + x := 1 + _ = x + { + L: + } +} + +// many kinds of blocks, all invalid to jump into or among, +// but valid to jump out of + +// if + +func _() { +L: + if true { + goto L + } +} + +func _() { +L: + if true { + goto L + } else { + } +} + +func _() { +L: + if false { + } else { + goto L + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + if true { + L: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + if true { + L: + } else { + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + if true { + } else { + L: + } +} + +func _() { + if false { + L: + } else { + goto L /* ERROR "goto L jumps into block" */ + } +} + +func _() { + if true { + goto L /* ERROR "goto L jumps into block" */ + } else { + L: + } +} + +func _() { + if true { + goto L /* ERROR "goto L jumps into block" */ + } else if false { + L: + } +} + +func _() { + if true { + goto L /* ERROR "goto L jumps into block" */ + } else if false { + L: + } else { + } +} + +func _() { + if true { + goto L /* ERROR "goto L jumps into block" */ + } else if false { + } else { + L: + } +} + +func _() { + if true { + goto L /* ERROR "goto L jumps into block" */ + } else { + L: + } +} + +func _() { + if true { + L: + } else { + goto L /* ERROR "goto L jumps into block" */ + } +} + +// for + +func _() { + for { + goto L + } +L: +} + +func _() { + for { + goto L + L: + } +} + +func _() { + for { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for { + goto L + L1: + } +L: + goto L1 /* ERROR "goto L1 jumps into block" */ +} + +func _() { + for i < n { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for i = 0; i < n; i++ { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for i = range x { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for i = range c { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for i = range m { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +func _() { + for i = range s { + L: + } + goto L /* ERROR "goto L jumps into block" */ +} + +// switch + +func _() { +L: + switch i { + case 0: + goto L + } +} + +func _() { +L: + switch i { + case 0: + + default: + goto L + } +} + +func _() { + switch i { + case 0: + + default: + L: + goto L + } +} + +func _() { + switch i { + case 0: + + default: + goto L + L: + } +} + +func _() { + switch i { + case 0: + goto L + L: + ; + default: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + switch i { + case 0: + L: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + switch i { + case 0: + L: + ; + default: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + switch i { + case 0: + default: + L: + } +} + +func _() { + switch i { + default: + goto L /* ERROR "goto L jumps into block" */ + case 0: + L: + } +} + +func _() { + switch i { + case 0: + L: + ; + default: + goto L /* ERROR "goto L jumps into block" */ + } +} + +// select +// different from switch. the statement has no implicit block around it. + +func _() { +L: + select { + case <-c: + goto L + } +} + +func _() { +L: + select { + case c <- 1: + + default: + goto L + } +} + +func _() { + select { + case <-c: + + default: + L: + goto L + } +} + +func _() { + select { + case c <- 1: + + default: + goto L + L: + } +} + +func _() { + select { + case <-c: + goto L + L: + ; + default: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + select { + case c <- 1: + L: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + select { + case c <- 1: + L: + ; + default: + } +} + +func _() { + goto L /* ERROR "goto L jumps into block" */ + select { + case <-c: + default: + L: + } +} + +func _() { + select { + default: + goto L /* ERROR "goto L jumps into block" */ + case <-c: + L: + } +} + +func _() { + select { + case <-c: + L: + ; + default: + goto L /* ERROR "goto L jumps into block" */ + } +} diff --git a/go/src/internal/types/testdata/check/importC.go b/go/src/internal/types/testdata/check/importC.go new file mode 100644 index 0000000000000000000000000000000000000000..2cdf383a08840e41c7a6fadc01a801f4d616ed16 --- /dev/null +++ b/go/src/internal/types/testdata/check/importC.go @@ -0,0 +1,56 @@ +// -fakeImportC + +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package importC + +import "C" +import _ /* ERROR `cannot rename import "C"` */ "C" +import foo /* ERROR `cannot rename import "C"` */ "C" +import . /* ERROR `cannot rename import "C"` */ "C" + +// Test cases extracted from issue #22090. + +import "unsafe" + +const _ C.int = 0xff // no error due to invalid constant type + +type T struct { + Name string + Ordinal int +} + +func _(args []T) { + var s string + for i, v := range args { + cname := C.CString(v.Name) + args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s, cname)) // no error due to i not being "used" + C.free(unsafe.Pointer(cname)) + } +} + +type CType C.Type + +const _ CType = C.X // no error due to invalid constant type +const _ = C.X + +// Test cases extracted from issue #23712. + +func _() { + var a [C.ArrayLength]byte + _ = a[0] // no index out of bounds error here +} + +// Additional tests to verify fix for #23712. + +func _() { + var a [C.ArrayLength1]byte + _ = 1 / len(a) // no division by zero error here and below + _ = 1 / cap(a) + _ = uint(unsafe.Sizeof(a)) // must not be negative + + var b [C.ArrayLength2]byte + a = b // should be valid +} diff --git a/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go b/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go new file mode 100644 index 0000000000000000000000000000000000000000..4bfb61e5b4e43e6cd4af7347fb808ca4305ab012 --- /dev/null +++ b/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go @@ -0,0 +1,53 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package importdecl0 + +import () + +import ( + // we can have multiple blank imports (was bug) + _ "math" + _ "net/rpc" + init /* ERROR "cannot import package as init" */ "fmt" + // reflect defines a type "flag" which shows up in the gc export data + "reflect" + . /* ERROR "imported and not used" */ "reflect" +) + +import "math" /* ERROR "imported and not used" */ +import m /* ERROR "imported as m and not used" */ "math" +import _ "math" + +import ( + "math/big" /* ERROR "imported and not used" */ + b /* ERROR "imported as b and not used" */ "math/big" + _ "math/big" +) + +import "fmt" +import f1 "fmt" +import f2 "fmt" + +// reflect.flag must not be visible in this package +type flag int +type _ reflect.flag /* ERROR "name flag not exported by package reflect" */ + +// imported package name may conflict with local objects +type reflect /* ERROR "reflect already declared" */ int + +// dot-imported exported objects may conflict with local objects +type Value /* ERROR "Value already declared through dot-import of package reflect" */ struct{} + +var _ = fmt.Println // use "fmt" + +func _() { + f1.Println() // use "fmt" +} + +func _() { + _ = func() { + f2.Println() // use "fmt" + } +} diff --git a/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go b/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go new file mode 100644 index 0000000000000000000000000000000000000000..99e1d1ebdf7ce82db18b3630c80538880c4215ef --- /dev/null +++ b/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go @@ -0,0 +1,30 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package importdecl0 + +import "math" +import m "math" + +import . "testing" // declares T in file scope +import . /* ERRORx `.unsafe. imported and not used` */ "unsafe" +import . "fmt" // declares Println in file scope + +import ( + "" /* ERROR "invalid import path" */ + "a!b" /* ERROR "invalid import path" */ + "abc\xffdef" /* ERROR "invalid import path" */ +) + +// using "math" in this file doesn't affect its use in other files +const Pi0 = math.Pi +const Pi1 = m.Pi + +type _ T // use "testing" + +func _() func() interface{} { + return func() interface{} { + return Println // use "fmt" + } +} diff --git a/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go b/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go new file mode 100644 index 0000000000000000000000000000000000000000..d377c01638a534a111d1c93833c2b05cc3627330 --- /dev/null +++ b/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go @@ -0,0 +1,22 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test case for issue 8969. + +package importdecl1 + +import "go/ast" +import . "unsafe" + +var _ Pointer // use dot-imported package unsafe + +// Test cases for issue 23914. + +type A interface { + // Methods m1, m2 must be type-checked in this file scope + // even when embedded in an interface in a different + // file of the same package. + m1() ast.Node + m2() Pointer +} diff --git a/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go b/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go new file mode 100644 index 0000000000000000000000000000000000000000..49ac2d53e66fd3df3288cdfba10935b4cf931454 --- /dev/null +++ b/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go @@ -0,0 +1,11 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package importdecl1 + +import . /* ERRORx ".unsafe. imported and not used" */ "unsafe" + +type B interface { + A +} diff --git a/go/src/internal/types/testdata/check/init0.go b/go/src/internal/types/testdata/check/init0.go new file mode 100644 index 0000000000000000000000000000000000000000..ee2175e2c7a96520f86d5b4509679b28c82890c9 --- /dev/null +++ b/go/src/internal/types/testdata/check/init0.go @@ -0,0 +1,106 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// initialization cycles + +package init0 + +// initialization cycles (we don't know the types) +const ( + s0 /* ERROR "initialization cycle: s0 refers to itself" */ = s0 + + x0 /* ERROR "initialization cycle for x0" */ = y0 + y0 = x0 + + a0 = b0 + b0 /* ERROR "initialization cycle for b0" */ = c0 + c0 = d0 + d0 = b0 +) + +var ( + s1 /* ERROR "initialization cycle: s1 refers to itself" */ = s1 + + x1 /* ERROR "initialization cycle for x1" */ = y1 + y1 = x1 + + a1 = b1 + b1 /* ERROR "initialization cycle for b1" */ = c1 + c1 = d1 + d1 = b1 +) + +// initialization cycles (we know the types) +const ( + s2 /* ERROR "initialization cycle: s2 refers to itself" */ int = s2 + + x2 /* ERROR "initialization cycle for x2" */ int = y2 + y2 = x2 + + a2 = b2 + b2 /* ERROR "initialization cycle for b2" */ int = c2 + c2 = d2 + d2 = b2 +) + +var ( + s3 /* ERROR "initialization cycle: s3 refers to itself" */ int = s3 + + x3 /* ERROR "initialization cycle for x3" */ int = y3 + y3 = x3 + + a3 = b3 + b3 /* ERROR "initialization cycle for b3" */ int = c3 + c3 = d3 + d3 = b3 +) + +// cycles via struct fields + +type S1 struct { + f int +} +const cx3 S1 /* ERROR "invalid constant type" */ = S1{cx3.f} +var vx3 /* ERROR "initialization cycle: vx3 refers to itself" */ S1 = S1{vx3.f} + +// cycles via functions + +var x4 = x5 +var x5 /* ERROR "initialization cycle for x5" */ = f1() +func f1() int { return x5*10 } + +var x6, x7 /* ERROR "initialization cycle" */ = f2() +var x8 = x7 +func f2() (int, int) { return f3() + f3(), 0 } +func f3() int { return x8 } + +// cycles via function literals + +var x9 /* ERROR "initialization cycle: x9 refers to itself" */ = func() int { return x9 }() + +var x10 /* ERROR "initialization cycle for x10" */ = f4() + +func f4() int { + _ = func() { + _ = x10 + } + return 0 +} + +// cycles via method expressions + +type T1 struct{} + +func (T1) m() bool { _ = x11; return false } + +var x11 /* ERROR "initialization cycle for x11" */ = T1.m(T1{}) + +// cycles via method values + +type T2 struct{} + +func (T2) m() bool { _ = x12; return false } + +var t1 T2 +var x12 /* ERROR "initialization cycle for x12" */ = t1.m diff --git a/go/src/internal/types/testdata/check/init1.go b/go/src/internal/types/testdata/check/init1.go new file mode 100644 index 0000000000000000000000000000000000000000..c89032ad6244c2dbba8633c0ea48202852ccc713 --- /dev/null +++ b/go/src/internal/types/testdata/check/init1.go @@ -0,0 +1,97 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// initialization cycles + +package init1 + +// issue 6683 (marked as WorkingAsIntended) + +type T0 struct{} + +func (T0) m() int { return y0 } + +var x0 = T0{} + +var y0 /* ERROR "initialization cycle" */ = x0.m() + +type T1 struct{} + +func (T1) m() int { return y1 } + +var x1 interface { + m() int +} = T1{} + +var y1 = x1.m() // no cycle reported, x1 is of interface type + +// issue 6703 (modified) + +var x2 /* ERROR "initialization cycle" */ = T2.m + +var y2 = x2 + +type T2 struct{} + +func (T2) m() int { + _ = y2 + return 0 +} + +var x3 /* ERROR "initialization cycle" */ = T3.m(T3{}) // <<<< added (T3{}) + +var y3 = x3 + +type T3 struct{} + +func (T3) m() int { + _ = y3 + return 0 +} + +var x4 /* ERROR "initialization cycle" */ = T4{}.m // <<<< added {} + +var y4 = x4 + +type T4 struct{} + +func (T4) m() int { + _ = y4 + return 0 +} + +var x5 /* ERROR "initialization cycle" */ = T5{}.m() // <<<< added () + +var y5 = x5 + +type T5 struct{} + +func (T5) m() int { + _ = y5 + return 0 +} + +// issue 4847 +// simplified test case + +var x6 = f6 +var y6 /* ERROR "initialization cycle" */ = f6 +func f6() { _ = y6 } + +// full test case + +type ( + E int + S int +) + +type matcher func(s *S) E + +func matchList(s *S) E { return matcher(matchAnyFn)(s) } + +var foo = matcher(matchList) + +var matchAny /* ERROR "initialization cycle" */ = matcher(matchList) + +func matchAnyFn(s *S) (err E) { return matchAny(s) } \ No newline at end of file diff --git a/go/src/internal/types/testdata/check/init2.go b/go/src/internal/types/testdata/check/init2.go new file mode 100644 index 0000000000000000000000000000000000000000..24e9277122cb922ab76c6d01b904f5336c67d542 --- /dev/null +++ b/go/src/internal/types/testdata/check/init2.go @@ -0,0 +1,139 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// initialization cycles + +package init2 + +// cycles through functions + +func f1() int { _ = x1; return 0 } +var x1 /* ERROR "initialization cycle" */ = f1 + +func f2() int { _ = x2; return 0 } +var x2 /* ERROR "initialization cycle" */ = f2() + +// cycles through method expressions + +type T3 int +func (T3) m() int { _ = x3; return 0 } +var x3 /* ERROR "initialization cycle" */ = T3.m + +type T4 int +func (T4) m() int { _ = x4; return 0 } +var x4 /* ERROR "initialization cycle" */ = T4.m(0) + +type T3p int +func (*T3p) m() int { _ = x3p; return 0 } +var x3p /* ERROR "initialization cycle" */ = (*T3p).m + +type T4p int +func (*T4p) m() int { _ = x4p; return 0 } +var x4p /* ERROR "initialization cycle" */ = (*T4p).m(nil) + +// cycles through method expressions of embedded methods + +type T5 struct { E5 } +type E5 int +func (E5) m() int { _ = x5; return 0 } +var x5 /* ERROR "initialization cycle" */ = T5.m + +type T6 struct { E6 } +type E6 int +func (E6) m() int { _ = x6; return 0 } +var x6 /* ERROR "initialization cycle" */ = T6.m(T6{0}) + +type T5p struct { E5p } +type E5p int +func (*E5p) m() int { _ = x5p; return 0 } +var x5p /* ERROR "initialization cycle" */ = (*T5p).m + +type T6p struct { E6p } +type E6p int +func (*E6p) m() int { _ = x6p; return 0 } +var x6p /* ERROR "initialization cycle" */ = (*T6p).m(nil) + +// cycles through method values + +type T7 int +func (T7) m() int { _ = x7; return 0 } +var x7 /* ERROR "initialization cycle" */ = T7(0).m + +type T8 int +func (T8) m() int { _ = x8; return 0 } +var x8 /* ERROR "initialization cycle" */ = T8(0).m() + +type T7p int +func (*T7p) m() int { _ = x7p; return 0 } +var x7p /* ERROR "initialization cycle" */ = new(T7p).m + +type T8p int +func (*T8p) m() int { _ = x8p; return 0 } +var x8p /* ERROR "initialization cycle" */ = new(T8p).m() + +type T7v int +func (T7v) m() int { _ = x7v; return 0 } +var x7var T7v +var x7v /* ERROR "initialization cycle" */ = x7var.m + +type T8v int +func (T8v) m() int { _ = x8v; return 0 } +var x8var T8v +var x8v /* ERROR "initialization cycle" */ = x8var.m() + +type T7pv int +func (*T7pv) m() int { _ = x7pv; return 0 } +var x7pvar *T7pv +var x7pv /* ERROR "initialization cycle" */ = x7pvar.m + +type T8pv int +func (*T8pv) m() int { _ = x8pv; return 0 } +var x8pvar *T8pv +var x8pv /* ERROR "initialization cycle" */ = x8pvar.m() + +// cycles through method values of embedded methods + +type T9 struct { E9 } +type E9 int +func (E9) m() int { _ = x9; return 0 } +var x9 /* ERROR "initialization cycle" */ = T9{0}.m + +type T10 struct { E10 } +type E10 int +func (E10) m() int { _ = x10; return 0 } +var x10 /* ERROR "initialization cycle" */ = T10{0}.m() + +type T9p struct { E9p } +type E9p int +func (*E9p) m() int { _ = x9p; return 0 } +var x9p /* ERROR "initialization cycle" */ = new(T9p).m + +type T10p struct { E10p } +type E10p int +func (*E10p) m() int { _ = x10p; return 0 } +var x10p /* ERROR "initialization cycle" */ = new(T10p).m() + +type T9v struct { E9v } +type E9v int +func (E9v) m() int { _ = x9v; return 0 } +var x9var T9v +var x9v /* ERROR "initialization cycle" */ = x9var.m + +type T10v struct { E10v } +type E10v int +func (E10v) m() int { _ = x10v; return 0 } +var x10var T10v +var x10v /* ERROR "initialization cycle" */ = x10var.m() + +type T9pv struct { E9pv } +type E9pv int +func (*E9pv) m() int { _ = x9pv; return 0 } +var x9pvar *T9pv +var x9pv /* ERROR "initialization cycle" */ = x9pvar.m + +type T10pv struct { E10pv } +type E10pv int +func (*E10pv) m() int { _ = x10pv; return 0 } +var x10pvar *T10pv +var x10pv /* ERROR "initialization cycle" */ = x10pvar.m() diff --git a/go/src/internal/types/testdata/check/issue25008/issue25008a.go b/go/src/internal/types/testdata/check/issue25008/issue25008a.go new file mode 100644 index 0000000000000000000000000000000000000000..cf71ca10e48c771f3ed8a931ae45ff33e2d6efbd --- /dev/null +++ b/go/src/internal/types/testdata/check/issue25008/issue25008a.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "io" + +type A interface { + io.Reader +} + +func f(a A) { + a.Read(nil) +} diff --git a/go/src/internal/types/testdata/check/issue25008/issue25008b.go b/go/src/internal/types/testdata/check/issue25008/issue25008b.go new file mode 100644 index 0000000000000000000000000000000000000000..f132b7fab3fb348eba2b5ca2046824fb46b0f554 --- /dev/null +++ b/go/src/internal/types/testdata/check/issue25008/issue25008b.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type B interface { + A +} diff --git a/go/src/internal/types/testdata/check/issue70974.go b/go/src/internal/types/testdata/check/issue70974.go new file mode 100644 index 0000000000000000000000000000000000000000..59b11653cee18ffe731b74d4c55ffad84a36ac42 --- /dev/null +++ b/go/src/internal/types/testdata/check/issue70974.go @@ -0,0 +1,27 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { +outer: + for { + break outer + } + + for { + break outer /* ERROR "invalid break label outer" */ + } +} + +func _() { +outer: + for { + continue outer + } + + for { + continue outer /* ERROR "invalid continue label outer" */ + } +} diff --git a/go/src/internal/types/testdata/check/issues0.go b/go/src/internal/types/testdata/check/issues0.go new file mode 100644 index 0000000000000000000000000000000000000000..fb4e1282f920afed68eebd5faa9174755406efe8 --- /dev/null +++ b/go/src/internal/types/testdata/check/issues0.go @@ -0,0 +1,373 @@ +// -lang=go1.17 + +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p // don't permit non-interface elements in interfaces + +import ( + "fmt" + syn "regexp/syntax" + t1 "text/template" + t2 "html/template" +) + +func issue7035() { + type T struct{ X int } + _ = func() { + fmt.Println() // must refer to imported fmt rather than the fmt below + } + fmt := new(T) + _ = fmt.X +} + +func issue8066() { + const ( + _ = float32(340282356779733661637539395458142568447) + _ = float32(340282356779733661637539395458142568448 /* ERROR "cannot convert" */ ) + ) +} + +// Check that a missing identifier doesn't lead to a spurious error cascade. +func issue8799a() { + x, ok := missing /* ERROR "undefined" */ () + _ = !ok + _ = x +} + +func issue8799b(x int, ok bool) { + x, ok = missing /* ERROR "undefined" */ () + _ = !ok + _ = x +} + +func issue9182() { + type Point C /* ERROR "undefined" */ .Point + // no error for composite literal based on unknown type + _ = Point{x: 1, y: 2} +} + +func f0() (a []int) { return } +func f1() (a []int, b int) { return } +func f2() (a, b []int) { return } + +func append_([]int, ...int) {} + +func issue9473(a []int, b ...int) { + // variadic builtin function + _ = append(f0()) + _ = append(f0(), f0()...) + _ = append(f1()) + _ = append(f2 /* ERRORx `cannot use .* in argument` */ ()) + _ = append(f2()... /* ERROR "cannot use ..." */ ) + _ = append(f0(), f1 /* ERROR "multiple-value f1" */ ()) + _ = append(f0(), f2 /* ERROR "multiple-value f2" */ ()) + _ = append(f0(), f1 /* ERROR "multiple-value f1" */ ()...) + _ = append(f0(), f2 /* ERROR "multiple-value f2" */ ()...) + + // variadic user-defined function + append_(f0()) + append_(f0(), f0()...) + append_(f1()) + append_(f2 /* ERRORx `cannot use .* in argument` */ ()) + append_(f2()... /* ERROR "cannot use ..." */ ) + append_(f0(), f1 /* ERROR "multiple-value f1" */ ()) + append_(f0(), f2 /* ERROR "multiple-value f2" */ ()) + append_(f0(), f1 /* ERROR "multiple-value f1" */ ()...) + append_(f0(), f2 /* ERROR "multiple-value f2" */ ()...) +} + +// Check that embedding a non-interface type in an interface results in a good error message. +func issue10979() { + type _ interface { + int /* ERROR "non-interface type int" */ + } + type T struct{} + type _ interface { + T /* ERROR "non-interface type T" */ + } + type _ interface { + nosuchtype /* ERROR "undefined: nosuchtype" */ + } + type _ interface { + fmt.Nosuchtype /* ERROR "undefined: fmt.Nosuchtype" */ + } + type _ interface { + nosuchpkg /* ERROR "undefined: nosuchpkg" */ .Nosuchtype + } + type I /* ERROR "invalid recursive type" */ interface { + I.m + m() + } +} + +// issue11347 +// These should not crash. +var a1, b1, c1 /* ERROR "cycle" */ b1 /* ERROR "b1 (package-level variable) is not a type" */ = 0 > 0<<""[""[c1]]>c1 +var a2, b2 /* ERROR "cycle" */ = 0 /* ERROR "assignment mismatch" */ /* ERROR "assignment mismatch" */ > 0<<""[b2] +var a3, b3 /* ERROR "cycle" */ = int /* ERROR "assignment mismatch" */ /* ERROR "assignment mismatch" */ (1<<""[b3]) + +// issue10260 +// Check that error messages explain reason for interface assignment failures. +type ( + I0 interface{} + I1 interface{ foo() } + I2 interface{ foo(x int) } + T0 struct{} + T1 struct{} + T2 struct{} +) + +func (*T1) foo() {} +func (*T2) foo(x int) {} + +func issue10260() { + var ( + i0 I0 + i1 I1 + i2 I2 + t0 *T0 + t1 *T1 + t2 *T2 + ) + + var x I1 + x = T1 /* ERRORx `cannot use T1{} .* as I1 value in assignment: T1 does not implement I1 \(method foo has pointer receiver\)` */ {} + _ = x /* ERROR "impossible type assertion: x.(T1)\n\tT1 does not implement I1 (method foo has pointer receiver)" */ .(T1) + + T1{}.foo /* ERROR "cannot call pointer method foo on T1" */ () + x.Foo /* ERROR "x.Foo undefined (type I1 has no field or method Foo, but does have method foo)" */ () + + _ = i2 /* ERROR "impossible type assertion: i2.(*T1)\n\t*T1 does not implement I2 (wrong type for method foo)\n\t\thave foo()\n\t\twant foo(int)" */ .(*T1) + + i1 = i0 /* ERRORx `cannot use i0 .* as I1 value in assignment: I0 does not implement I1 \(missing method foo\)` */ + i1 = t0 /* ERRORx `.* t0 .* as I1 .*: \*T0 does not implement I1 \(missing method foo\)` */ + i1 = i2 /* ERRORx `.* i2 .* as I1 .*: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ + i1 = t2 /* ERRORx `.* t2 .* as I1 .*: \*T2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ + i2 = i1 /* ERRORx `.* i1 .* as I2 .*: I1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ + i2 = t1 /* ERRORx `.* t1 .* as I2 .*: \*T1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ + + _ = func() I1 { return i0 /* ERRORx `cannot use i0 .* as I1 value in return statement: I0 does not implement I1 \(missing method foo\)` */ } + _ = func() I1 { return t0 /* ERRORx `.* t0 .* as I1 .*: \*T0 does not implement I1 \(missing method foo\)` */ } + _ = func() I1 { return i2 /* ERRORx `.* i2 .* as I1 .*: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ } + _ = func() I1 { return t2 /* ERRORx `.* t2 .* as I1 .*: \*T2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ } + _ = func() I2 { return i1 /* ERRORx `.* i1 .* as I2 .*: I1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ } + _ = func() I2 { return t1 /* ERRORx `.* t1 .* as I2 .*: \*T1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ } + + // a few more - less exhaustive now + + f := func(I1, I2){} + f(i0 /* ERROR "missing method foo" */ , i1 /* ERROR "wrong type for method foo" */ ) + + _ = [...]I1{i0 /* ERRORx `cannot use i0 .* as I1 value in array or slice literal: I0 does not implement I1 \(missing method foo\)` */ } + _ = [...]I1{i2 /* ERRORx `cannot use i2 .* as I1 value in array or slice literal: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ } + _ = []I1{i0 /* ERROR "missing method foo" */ } + _ = []I1{i2 /* ERROR "wrong type for method foo" */ } + _ = map[int]I1{0: i0 /* ERROR "missing method foo" */ } + _ = map[int]I1{0: i2 /* ERROR "wrong type for method foo" */ } + + make(chan I1) <- i0 /* ERROR "missing method foo" */ + make(chan I1) <- i2 /* ERROR "wrong type for method foo" */ +} + +// Check that constants representable as integers are in integer form +// before being used in operations that are only defined on integers. +func issue14229() { + // from the issue + const _ = int64(-1<<63) % 1e6 + + // related + const ( + a int = 3 + b = 4.0 + _ = a / b + _ = a % b + _ = b / a + _ = b % a + ) +} + +// Check that in a n:1 variable declaration with type and initialization +// expression the type is distributed to all variables of the lhs before +// the initialization expression assignment is checked. +func issue15755() { + // from issue + var i interface{} + type b bool + var x, y b = i.(b) + _ = x == y + + // related: we should see an error since the result of f1 is ([]int, int) + var u, v []int = f1 /* ERROR "cannot use f1" */ () + _ = u + _ = v +} + +// Test that we don't get "declared and not used" +// errors in the context of invalid/C objects. +func issue20358() { + var F C /* ERROR "undefined" */ .F + var A C /* ERROR "undefined" */ .A + var S C /* ERROR "undefined" */ .S + type T C /* ERROR "undefined" */ .T + type P C /* ERROR "undefined" */ .P + + // these variables must be "used" even though + // the LHS expressions/types below in which + // context they are used are unknown/invalid + var f, a, s1, s2, s3, t, p int + + _ = F(f) + _ = A[a] + _ = S[s1:s2:s3] + _ = T{t} + _ = P{f: p} +} + +// Test that we don't declare lhs variables in short variable +// declarations before we type-check function literals on the +// rhs. +func issue24026() { + f := func() int { f(0) /* must refer to outer f */; return 0 } + _ = f + + _ = func() { + f := func() { _ = f() /* must refer to outer f */ } + _ = f + } + + // b and c must not be visible inside function literal + a := 0 + a, b, c := func() (int, int, int) { + return a, b /* ERROR "undefined" */ , c /* ERROR "undefined" */ + }() + _, _ = b, c +} + +func f(int) {} // for issue24026 + +// Test that we don't report a "missing return statement" error +// (due to incorrect context when type-checking interfaces). +func issue24140(x interface{}) int { + switch x.(type) { + case interface{}: + return 0 + default: + panic(0) + } +} + +// Test that we don't crash when the 'if' condition is missing. +func issue25438() { + if { /* ERROR "missing condition" */ } + if x := 0; /* ERROR "missing condition" */ { _ = x } + if + { /* ERROR "missing condition" */ } +} + +// Test that we can embed alias type names in interfaces. +type issue25301 interface { + E +} + +type E = interface { + m() +} + +// Test case from issue. +// cmd/compile reports a cycle as well. +type issue25301b /* ERROR "invalid recursive type" */ = interface { + m() interface{ issue25301b } +} + +type issue25301c interface { + notE // ERRORx "non-interface type (struct{}|notE)" +} + +type notE = struct{} + +// Test that method declarations don't introduce artificial cycles +// (issue #26124). +const CC TT = 1 +type TT int +func (TT) MM() [CC]TT + +// Reduced test case from issue #26124. +const preloadLimit LNumber = 128 +type LNumber float64 +func (LNumber) assertFunction() *LFunction +type LFunction struct { + GFunction LGFunction +} +type LGFunction func(*LState) +type LState struct { + reg *registry +} +type registry struct { + alloc *allocator +} +type allocator struct { + _ [int(preloadLimit)]int +} + +// Test that we don't crash when type-checking composite literals +// containing errors in the type. +var issue27346 = [][n /* ERROR "undefined" */ ]int{ + 0: {}, +} + +var issue22467 = map[int][... /* ERROR "invalid use of [...] array" */ ]int{0: {}} + +// Test that invalid use of ... in parameter lists is recognized +// (issue #28281). +func issue28281a(int, int, ...int) +func issue28281b(a, b int, c ...int) +func issue28281c(a, b, c ... /* ERROR "can only use ... with final parameter" */ int) +func issue28281d(... /* ERROR "can only use ... with final parameter" */ int, int) +func issue28281e(a, b, c ... /* ERROR "can only use ... with final parameter" */ int, d int) +func issue28281f(... /* ERROR "can only use ... with final parameter" */ int, ... int, int) +func (... /* ERROR "invalid use of ..." */ TT) f() +func issue28281g() (... /* ERROR "invalid use of ..." */ TT) + +// Issue #26234: Make various field/method lookup errors easier to read by matching cmd/compile's output +func issue26234a(f *syn.Prog) { + // The error message below should refer to the actual package name (syntax) + // not the local package name (syn). + f.foo /* ERROR "f.foo undefined (type *syntax.Prog has no field or method foo)" */ +} + +type T struct { + x int + E1 + E2 +} + +type E1 struct{ f int } +type E2 struct{ f int } + +func issue26234b(x T) { + _ = x.f /* ERROR "ambiguous selector x.f" */ +} + +func issue26234c() { + T.x /* ERROR "T.x undefined (type T has no method x)" */ () +} + +func issue35895() { + // T is defined in this package, don't qualify its name with the package name. + var _ T = 0 // ERROR "cannot use 0 (untyped int constant) as T" + + // There is only one package with name syntax imported, only use the (global) package name in error messages. + var _ *syn.Prog = 0 // ERROR "cannot use 0 (untyped int constant) as *syntax.Prog" + + // Because both t1 and t2 have the same global package name (template), + // qualify packages with full path name in this case. + var _ t1.Template = t2 /* ERRORx `cannot use .* \(value of struct type .html/template.\.Template\) as .text/template.\.Template` */ .Template{} +} + +func issue42989(s uint) { + var m map[int]string + delete(m, 1< 10: + if x == 11 { + break L3 + } + if x == 12 { + continue L3 /* ERROR "invalid continue label L3" */ + } + goto L3 + } + +L4: + if true { + if x == 13 { + break L4 /* ERROR "invalid break label L4" */ + } + if x == 14 { + continue L4 /* ERROR "invalid continue label L4" */ + } + if x == 15 { + goto L4 + } + } + +L5: + f1() + if x == 16 { + break L5 /* ERROR "invalid break label L5" */ + } + if x == 17 { + continue L5 /* ERROR "invalid continue label L5" */ + } + if x == 18 { + goto L5 + } + + for { + if x == 19 { + break L1 /* ERROR "invalid break label L1" */ + } + if x == 20 { + continue L1 /* ERROR "invalid continue label L1" */ + } + if x == 21 { + goto L1 + } + } +} + +// Additional tests not in the original files. + +func f2() { +L1 /* ERROR "label L1 declared and not used" */ : + if x == 0 { + for { + continue L1 /* ERROR "invalid continue label L1" */ + } + } +} + +func f3() { +L1: +L2: +L3: + for { + break L1 /* ERROR "invalid break label L1" */ + break L2 /* ERROR "invalid break label L2" */ + break L3 + continue L1 /* ERROR "invalid continue label L1" */ + continue L2 /* ERROR "invalid continue label L2" */ + continue L3 + goto L1 + goto L2 + goto L3 + } +} + +// Blank labels are never declared. + +func f4() { +_: +_: // multiple blank labels are ok + goto _ /* ERROR "label _ not declared" */ +} + +func f5() { +_: + for { + break _ /* ERROR "invalid break label _" */ + continue _ /* ERROR "invalid continue label _" */ + } +} + +func f6() { +_: + switch { + default: + break _ /* ERROR "invalid break label _" */ + } +} diff --git a/go/src/internal/types/testdata/check/linalg.go b/go/src/internal/types/testdata/check/linalg.go new file mode 100644 index 0000000000000000000000000000000000000000..f02e773dbeeeebbafde08ab38ac4cef93f11897a --- /dev/null +++ b/go/src/internal/types/testdata/check/linalg.go @@ -0,0 +1,82 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package linalg + +// Numeric is type bound that matches any numeric type. +// It would likely be in a constraints package in the standard library. +type Numeric interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 | + ~complex64 | ~complex128 +} + +func DotProduct[T Numeric](s1, s2 []T) T { + if len(s1) != len(s2) { + panic("DotProduct: slices of unequal length") + } + var r T + for i := range s1 { + r += s1[i] * s2[i] + } + return r +} + +// NumericAbs matches numeric types with an Abs method. +type NumericAbs[T any] interface { + Numeric + + Abs() T +} + +// AbsDifference computes the absolute value of the difference of +// a and b, where the absolute value is determined by the Abs method. +func AbsDifference[T NumericAbs[T]](a, b T) T { + d := a - b + return d.Abs() +} + +// OrderedNumeric is a type bound that matches numeric types that support the < operator. +type OrderedNumeric interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 +} + +// Complex is a type bound that matches the two complex types, which do not have a < operator. +type Complex interface { + ~complex64 | ~complex128 +} + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// // OrderedAbs is a helper type that defines an Abs method for +// // ordered numeric types. +// type OrderedAbs[T OrderedNumeric] T +// +// func (a OrderedAbs[T]) Abs() OrderedAbs[T] { +// if a < 0 { +// return -a +// } +// return a +// } +// +// // ComplexAbs is a helper type that defines an Abs method for +// // complex types. +// type ComplexAbs[T Complex] T +// +// func (a ComplexAbs[T]) Abs() ComplexAbs[T] { +// r := float64(real(a)) +// i := float64(imag(a)) +// d := math.Sqrt(r * r + i * i) +// return ComplexAbs[T](complex(d, 0)) +// } +// +// func OrderedAbsDifference[T OrderedNumeric](a, b T) T { +// return T(AbsDifference(OrderedAbs[T](a), OrderedAbs[T](b))) +// } +// +// func ComplexAbsDifference[T Complex](a, b T) T { +// return T(AbsDifference(ComplexAbs[T](a), ComplexAbs[T](b))) +// } diff --git a/go/src/internal/types/testdata/check/literals.go b/go/src/internal/types/testdata/check/literals.go new file mode 100644 index 0000000000000000000000000000000000000000..494a465f48756717dc04153a2d27d294d60392a0 --- /dev/null +++ b/go/src/internal/types/testdata/check/literals.go @@ -0,0 +1,111 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests various representations of literals +// and compares them with literals or constant expressions +// of equal values. + +package literals + +func _() { + // 0-octals + assert(0_123 == 0123) + assert(0123_456 == 0123456) + + // decimals + assert(1_234 == 1234) + assert(1_234_567 == 1234567) + + // hexadecimals + assert(0X_0 == 0) + assert(0X_1234 == 0x1234) + assert(0X_CAFE_f00d == 0xcafef00d) + + // octals + assert(0o0 == 0) + assert(0o1234 == 01234) + assert(0o01234567 == 01234567) + + assert(0O0 == 0) + assert(0O1234 == 01234) + assert(0O01234567 == 01234567) + + assert(0o_0 == 0) + assert(0o_1234 == 01234) + assert(0o0123_4567 == 01234567) + + assert(0O_0 == 0) + assert(0O_1234 == 01234) + assert(0O0123_4567 == 01234567) + + // binaries + assert(0b0 == 0) + assert(0b1011 == 0xb) + assert(0b00101101 == 0x2d) + + assert(0B0 == 0) + assert(0B1011 == 0xb) + assert(0B00101101 == 0x2d) + + assert(0b_0 == 0) + assert(0b10_11 == 0xb) + assert(0b_0010_1101 == 0x2d) + + // decimal floats + assert(1_2_3. == 123.) + assert(0_123. == 123.) + + assert(0_0e0 == 0.) + assert(1_2_3e0 == 123.) + assert(0_123e0 == 123.) + + assert(0e-0_0 == 0.) + assert(1_2_3E+0 == 123.) + assert(0123E1_2_3 == 123e123) + + assert(0.e+1 == 0.) + assert(123.E-1_0 == 123e-10) + assert(01_23.e123 == 123e123) + + assert(.0e-1 == .0) + assert(.123E+10 == .123e10) + assert(.0123E123 == .0123e123) + + assert(1_2_3.123 == 123.123) + assert(0123.01_23 == 123.0123) + + // hexadecimal floats + assert(0x0.p+0 == 0.) + assert(0Xdeadcafe.p-10 == 0xdeadcafe/1024.0) + assert(0x1234.P84 == 0x1234000000000000000000000) + + assert(0x.1p-0 == 1./16) + assert(0X.deadcafep4 == 1.0*0xdeadcafe/0x10000000) + assert(0x.1234P+12 == 1.0*0x1234/0x10) + + assert(0x0p0 == 0.) + assert(0Xdeadcafep+1 == 0x1bd5b95fc) + assert(0x1234P-10 == 0x1234/1024.0) + + assert(0x0.0p0 == 0.) + assert(0Xdead.cafep+1 == 1.0*0x1bd5b95fc/0x10000) + assert(0x12.34P-10 == 1.0*0x1234/0x40000) + + assert(0Xdead_cafep+1 == 0xdeadcafep+1) + assert(0x_1234P-10 == 0x1234p-10) + + assert(0X_dead_cafe.p-10 == 0xdeadcafe.p-10) + assert(0x12_34.P1_2_3 == 0x1234.p123) + + assert(1_234i == 1234i) + assert(1_234_567i == 1234567i) + + assert(0.i == 0i) + assert(123.i == 123i) + assert(0123.i == 123i) + + assert(0.e+1i == 0i) + assert(123.E-1_0i == 123e-10i) + assert(01_23.e123i == 123e123i) +} diff --git a/go/src/internal/types/testdata/check/lookup1.go b/go/src/internal/types/testdata/check/lookup1.go new file mode 100644 index 0000000000000000000000000000000000000000..669767b27876dcaa3489dc4acfaa9bc5d4c15f95 --- /dev/null +++ b/go/src/internal/types/testdata/check/lookup1.go @@ -0,0 +1,85 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package lookup + +import "math/big" // provides big.Float struct with unexported fields and methods + +func _() { + var s struct { + x, aBc int + } + _ = s.x + _ = s /* ERROR "invalid operation: cannot call s.x (variable of type int): int is not a function" */ .x() + _ = s.X // ERROR "s.X undefined (type struct{x int; aBc int} has no field or method X, but does have field x)" + _ = s.X /* ERROR "s.X undefined (type struct{x int; aBc int} has no field or method X, but does have field x)" */ () + + _ = s.aBc + _ = s.abc // ERROR "s.abc undefined (type struct{x int; aBc int} has no field or method abc, but does have field aBc)" + _ = s.ABC // ERROR "s.ABC undefined (type struct{x int; aBc int} has no field or method ABC, but does have field aBc)" +} + +func _() { + type S struct { + x int + } + var s S + _ = s.x + _ = s /* ERROR "invalid operation: cannot call s.x (variable of type int): int is not a function" */ .x() + _ = s.X // ERROR "s.X undefined (type S has no field or method X, but does have field x)" + _ = s.X /* ERROR "s.X undefined (type S has no field or method X, but does have field x)" */ () +} + +type S struct { + x int +} + +func (S) m() {} +func (S) aBc() {} + +func _() { + var s S + _ = s.m + s.m() + _ = s.M // ERROR "s.M undefined (type S has no field or method M, but does have method m)" + s.M /* ERROR "s.M undefined (type S has no field or method M, but does have method m)" */ () + + _ = s.aBc + _ = s.abc // ERROR "s.abc undefined (type S has no field or method abc, but does have method aBc)" + _ = s.ABC // ERROR "s.ABC undefined (type S has no field or method ABC, but does have method aBc)" +} + +func _() { + type P *S + var s P + _ = s.m // ERROR "s.m undefined (type P has no field or method m)" + _ = s.M // ERROR "s.M undefined (type P has no field or method M)" + _ = s.x + _ = s.X // ERROR "s.X undefined (type P has no field or method X, but does have field x)" +} + +func _() { + var x big.Float + _ = x.neg // ERROR "x.neg undefined (type big.Float has no field or method neg, but does have method Neg)" + _ = x.nEg // ERROR "x.nEg undefined (type big.Float has no field or method nEg)" + _ = x.Neg + _ = x.NEg // ERROR "x.NEg undefined (type big.Float has no field or method NEg, but does have method Neg)" + + _ = x.form // ERROR "x.form undefined (cannot refer to unexported field form)" + _ = x.fOrm // ERROR "x.fOrm undefined (type big.Float has no field or method fOrm)" + _ = x.Form // ERROR "x.Form undefined (type big.Float has no field or method Form, but does have unexported field form)" + _ = x.FOrm // ERROR "x.FOrm undefined (type big.Float has no field or method FOrm)" +} + +func _[P any](x P) { + x /* ERROR "cannot call x (variable of type P constrained by any): no specific type" */ () +} + +func _[P int](x P) { + x /* ERROR "cannot call x (variable of type P constrained by int): int is not a function" */ () +} + +func _[P int | string](x P) { + x /* ERROR "cannot call x (variable of type P constrained by int | string): int is not a function" */ () +} diff --git a/go/src/internal/types/testdata/check/lookup2.go b/go/src/internal/types/testdata/check/lookup2.go new file mode 100644 index 0000000000000000000000000000000000000000..a274da1ddc5335bf0c2aaa51280725691ec8f3bd --- /dev/null +++ b/go/src/internal/types/testdata/check/lookup2.go @@ -0,0 +1,94 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "go/ast" + "math/big" +) + +// case sel pkg have message (examples for general lookup) +// --------------------------------------------------------------------------------------------------------- +// ok x.Foo == Foo +// misspelled x.Foo == FoO type X has no field or method Foo, but does have field FoO +// misspelled x.Foo == foo type X has no field or method Foo, but does have field foo +// misspelled x.Foo == foO type X has no field or method Foo, but does have field foO +// +// misspelled x.foo == Foo type X has no field or method foo, but does have field Foo +// misspelled x.foo == FoO type X has no field or method foo, but does have field FoO +// ok x.foo == foo +// misspelled x.foo == foO type X has no field or method foo, but does have field foO +// +// ok x.Foo != Foo +// misspelled x.Foo != FoO type X has no field or method Foo, but does have field FoO +// unexported x.Foo != foo type X has no field or method Foo, but does have unexported field foo +// missing x.Foo != foO type X has no field or method Foo +// +// misspelled x.foo != Foo type X has no field or method foo, but does have field Foo +// missing x.foo != FoO type X has no field or method foo +// inaccessible x.foo != foo cannot refer to unexported field foo +// missing x.foo != foO type X has no field or method foo + +type S struct { + Foo1 int + FoO2 int + foo3 int + foO4 int +} + +func _() { + var x S + _ = x.Foo1 // OK + _ = x.Foo2 // ERROR "x.Foo2 undefined (type S has no field or method Foo2, but does have field FoO2)" + _ = x.Foo3 // ERROR "x.Foo3 undefined (type S has no field or method Foo3, but does have field foo3)" + _ = x.Foo4 // ERROR "x.Foo4 undefined (type S has no field or method Foo4, but does have field foO4)" + + _ = x.foo1 // ERROR "x.foo1 undefined (type S has no field or method foo1, but does have field Foo1)" + _ = x.foo2 // ERROR "x.foo2 undefined (type S has no field or method foo2, but does have field FoO2)" + _ = x.foo3 // OK + _ = x.foo4 // ERROR "x.foo4 undefined (type S has no field or method foo4, but does have field foO4)" +} + +func _() { + _ = S{Foo1: 0} // OK + _ = S{Foo2 /* ERROR "unknown field Foo2 in struct literal of type S, but does have FoO2" */ : 0} + _ = S{Foo3 /* ERROR "unknown field Foo3 in struct literal of type S, but does have foo3" */ : 0} + _ = S{Foo4 /* ERROR "unknown field Foo4 in struct literal of type S, but does have foO4" */ : 0} + + _ = S{foo1 /* ERROR "unknown field foo1 in struct literal of type S, but does have Foo1" */ : 0} + _ = S{foo2 /* ERROR "unknown field foo2 in struct literal of type S, but does have FoO2" */ : 0} + _ = S{foo3: 0} // OK + _ = S{foo4 /* ERROR "unknown field foo4 in struct literal of type S, but does have foO4" */ : 0} +} + +// The following tests follow the same pattern as above but operate on an imported type instead of S. +// Currently our testing framework doesn't make it easy to define an imported package for testing, so +// instead we use the big.Float and ast.File types as they provide a suitable mix of exported and un- +// exported fields and methods. + +func _() { + var x *big.Float + _ = x.Neg // OK + _ = x.NeG // ERROR "x.NeG undefined (type *big.Float has no field or method NeG, but does have method Neg)" + _ = x.Form // ERROR "x.Form undefined (type *big.Float has no field or method Form, but does have unexported field form)" + _ = x.ForM // ERROR "x.ForM undefined (type *big.Float has no field or method ForM)" + + _ = x.abs // ERROR "x.abs undefined (type *big.Float has no field or method abs, but does have method Abs)" + _ = x.abS // ERROR "x.abS undefined (type *big.Float has no field or method abS)" + _ = x.form // ERROR "x.form undefined (cannot refer to unexported field form)" + _ = x.forM // ERROR "x.forM undefined (type *big.Float has no field or method forM)" +} + +func _() { + _ = ast.File{Name: nil} // OK + _ = ast.File{NamE /* ERROR "unknown field NamE in struct literal of type ast.File, but does have Name" */ : nil} + _ = big.Float{Form /* ERROR "unknown field Form in struct literal of type big.Float, but does have unexported form" */ : 0} + _ = big.Float{ForM /* ERROR "unknown field ForM in struct literal of type big.Float" */ : 0} + + _ = ast.File{name /* ERROR "unknown field name in struct literal of type ast.File, but does have Name" */ : nil} + _ = ast.File{namE /* ERROR "unknown field namE in struct literal of type ast.File" */ : nil} + _ = big.Float{form /* ERROR "cannot refer to unexported field form in struct literal of type big.Float" */ : 0} + _ = big.Float{forM /* ERROR "unknown field forM in struct literal of type big.Float" */ : 0} +} diff --git a/go/src/internal/types/testdata/check/main0.go b/go/src/internal/types/testdata/check/main0.go new file mode 100644 index 0000000000000000000000000000000000000000..95a8ed1d6d0a2b25e50a94b40889f0dee6b2e66b --- /dev/null +++ b/go/src/internal/types/testdata/check/main0.go @@ -0,0 +1,9 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func main() +func main /* ERROR "no arguments and no return values" */ /* ERROR "redeclared" */ (int) +func main /* ERROR "no arguments and no return values" */ /* ERROR "redeclared" */ () int diff --git a/go/src/internal/types/testdata/check/main1.go b/go/src/internal/types/testdata/check/main1.go new file mode 100644 index 0000000000000000000000000000000000000000..fb567a07d085a32493b7126995a13b1a0a39962f --- /dev/null +++ b/go/src/internal/types/testdata/check/main1.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func main[T /* ERROR "func main must have no type parameters" */ any]() {} diff --git a/go/src/internal/types/testdata/check/map0.go b/go/src/internal/types/testdata/check/map0.go new file mode 100644 index 0000000000000000000000000000000000000000..21c989cc9d2c248f10493bcd50089b6ecd015e06 --- /dev/null +++ b/go/src/internal/types/testdata/check/map0.go @@ -0,0 +1,113 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package orderedmap provides an ordered map, implemented as a binary tree. +package orderedmap + +// TODO(gri) fix imports for tests +import "chans" // ERROR "could not import" + +// Map is an ordered map. +type Map[K, V any] struct { + root *node[K, V] + compare func(K, K) int +} + +// node is the type of a node in the binary tree. +type node[K, V any] struct { + key K + val V + left, right *node[K, V] +} + +// New returns a new map. +func New[K, V any](compare func(K, K) int) *Map[K, V] { + return &Map[K, V]{compare: compare} +} + +// find looks up key in the map, and returns either a pointer +// to the node holding key, or a pointer to the location where +// such a node would go. +func (m *Map[K, V]) find(key K) **node[K, V] { + pn := &m.root + for *pn != nil { + switch cmp := m.compare(key, (*pn).key); { + case cmp < 0: + pn = &(*pn).left + case cmp > 0: + pn = &(*pn).right + default: + return pn + } + } + return pn +} + +// Insert inserts a new key/value into the map. +// If the key is already present, the value is replaced. +// Returns true if this is a new key, false if already present. +func (m *Map[K, V]) Insert(key K, val V) bool { + pn := m.find(key) + if *pn != nil { + (*pn).val = val + return false + } + *pn = &node[K, V]{key: key, val: val} + return true +} + +// Find returns the value associated with a key, or zero if not present. +// The found result reports whether the key was found. +func (m *Map[K, V]) Find(key K) (V, bool) { + pn := m.find(key) + if *pn == nil { + var zero V // see the discussion of zero values, above + return zero, false + } + return (*pn).val, true +} + +// keyValue is a pair of key and value used when iterating. +type keyValue[K, V any] struct { + key K + val V +} + +// InOrder returns an iterator that does an in-order traversal of the map. +func (m *Map[K, V]) InOrder() *Iterator[K, V] { + sender, receiver := chans.Ranger[keyValue[K, V]]() + var f func(*node[K, V]) bool + f = func(n *node[K, V]) bool { + if n == nil { + return true + } + // Stop sending values if sender.Send returns false, + // meaning that nothing is listening at the receiver end. + return f(n.left) && + sender.Send(keyValue[K, V]{n.key, n.val}) && + f(n.right) + } + go func() { + f(m.root) + sender.Close() + }() + return &Iterator[K, V]{receiver} +} + +// Iterator is used to iterate over the map. +type Iterator[K, V any] struct { + r *chans.Receiver[keyValue[K, V]] +} + +// Next returns the next key and value pair, and a boolean indicating +// whether they are valid or whether we have reached the end. +func (it *Iterator[K, V]) Next() (K, V, bool) { + keyval, ok := it.r.Next() + if !ok { + var zerok K + var zerov V + return zerok, zerov, false + } + return keyval.key, keyval.val, true +} diff --git a/go/src/internal/types/testdata/check/map1.go b/go/src/internal/types/testdata/check/map1.go new file mode 100644 index 0000000000000000000000000000000000000000..e13bf33feda9edb1f87910f9bda04d4f7908bd9e --- /dev/null +++ b/go/src/internal/types/testdata/check/map1.go @@ -0,0 +1,146 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is like map.go2, but instead if importing chans, it contains +// the necessary functionality at the end of the file. + +// Package orderedmap provides an ordered map, implemented as a binary tree. +package orderedmap + +// Map is an ordered map. +type Map[K, V any] struct { + root *node[K, V] + compare func(K, K) int +} + +// node is the type of a node in the binary tree. +type node[K, V any] struct { + key K + val V + left, right *node[K, V] +} + +// New returns a new map. +func New[K, V any](compare func(K, K) int) *Map[K, V] { + return &Map[K, V]{compare: compare} +} + +// find looks up key in the map, and returns either a pointer +// to the node holding key, or a pointer to the location where +// such a node would go. +func (m *Map[K, V]) find(key K) **node[K, V] { + pn := &m.root + for *pn != nil { + switch cmp := m.compare(key, (*pn).key); { + case cmp < 0: + pn = &(*pn).left + case cmp > 0: + pn = &(*pn).right + default: + return pn + } + } + return pn +} + +// Insert inserts a new key/value into the map. +// If the key is already present, the value is replaced. +// Returns true if this is a new key, false if already present. +func (m *Map[K, V]) Insert(key K, val V) bool { + pn := m.find(key) + if *pn != nil { + (*pn).val = val + return false + } + *pn = &node[K, V]{key: key, val: val} + return true +} + +// Find returns the value associated with a key, or zero if not present. +// The found result reports whether the key was found. +func (m *Map[K, V]) Find(key K) (V, bool) { + pn := m.find(key) + if *pn == nil { + var zero V // see the discussion of zero values, above + return zero, false + } + return (*pn).val, true +} + +// keyValue is a pair of key and value used when iterating. +type keyValue[K, V any] struct { + key K + val V +} + +// InOrder returns an iterator that does an in-order traversal of the map. +func (m *Map[K, V]) InOrder() *Iterator[K, V] { + sender, receiver := chans_Ranger[keyValue[K, V]]() + var f func(*node[K, V]) bool + f = func(n *node[K, V]) bool { + if n == nil { + return true + } + // Stop sending values if sender.Send returns false, + // meaning that nothing is listening at the receiver end. + return f(n.left) && + sender.Send(keyValue[K, V]{n.key, n.val}) && + f(n.right) + } + go func() { + f(m.root) + sender.Close() + }() + return &Iterator[K, V]{receiver} +} + +// Iterator is used to iterate over the map. +type Iterator[K, V any] struct { + r *chans_Receiver[keyValue[K, V]] +} + +// Next returns the next key and value pair, and a boolean indicating +// whether they are valid or whether we have reached the end. +func (it *Iterator[K, V]) Next() (K, V, bool) { + keyval, ok := it.r.Next() + if !ok { + var zerok K + var zerov V + return zerok, zerov, false + } + return keyval.key, keyval.val, true +} + +// chans + +func chans_Ranger[T any]() (*chans_Sender[T], *chans_Receiver[T]) { panic(0) } + +// A sender is used to send values to a Receiver. +type chans_Sender[T any] struct { + values chan<- T + done <-chan bool +} + +func (s *chans_Sender[T]) Send(v T) bool { + select { + case s.values <- v: + return true + case <-s.done: + return false + } +} + +func (s *chans_Sender[T]) Close() { + close(s.values) +} + +type chans_Receiver[T any] struct { + values <-chan T + done chan<- bool +} + +func (r *chans_Receiver[T]) Next() (T, bool) { + v, ok := <-r.values + return v, ok +} diff --git a/go/src/internal/types/testdata/check/methodsets.go b/go/src/internal/types/testdata/check/methodsets.go new file mode 100644 index 0000000000000000000000000000000000000000..5b3e4a296ca8c3b93f29bd80b205b4447babae1b --- /dev/null +++ b/go/src/internal/types/testdata/check/methodsets.go @@ -0,0 +1,214 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package methodsets + +type T0 struct {} + +func (T0) v0() {} +func (*T0) p0() {} + +type T1 struct {} // like T0 with different method names + +func (T1) v1() {} +func (*T1) p1() {} + +type T2 interface { + v2() + p2() +} + +type T3 struct { + T0 + *T1 + T2 +} + +// Method expressions +func _() { + var ( + _ func(T0) = T0.v0 + _ = T0.p0 /* ERROR "invalid method expression T0.p0 (needs pointer receiver (*T0).p0)" */ + + _ func (*T0) = (*T0).v0 + _ func (*T0) = (*T0).p0 + + // T1 is like T0 + + _ func(T2) = T2.v2 + _ func(T2) = T2.p2 + + _ func(T3) = T3.v0 + _ func(T3) = T3.p0 /* ERROR "invalid method expression T3.p0 (needs pointer receiver (*T3).p0)" */ + _ func(T3) = T3.v1 + _ func(T3) = T3.p1 + _ func(T3) = T3.v2 + _ func(T3) = T3.p2 + + _ func(*T3) = (*T3).v0 + _ func(*T3) = (*T3).p0 + _ func(*T3) = (*T3).v1 + _ func(*T3) = (*T3).p1 + _ func(*T3) = (*T3).v2 + _ func(*T3) = (*T3).p2 + ) +} + +// Method values with addressable receivers +func _() { + var ( + v0 T0 + _ func() = v0.v0 + _ func() = v0.p0 + ) + + var ( + p0 *T0 + _ func() = p0.v0 + _ func() = p0.p0 + ) + + // T1 is like T0 + + var ( + v2 T2 + _ func() = v2.v2 + _ func() = v2.p2 + ) + + var ( + v4 T3 + _ func() = v4.v0 + _ func() = v4.p0 + _ func() = v4.v1 + _ func() = v4.p1 + _ func() = v4.v2 + _ func() = v4.p2 + ) + + var ( + p4 *T3 + _ func() = p4.v0 + _ func() = p4.p0 + _ func() = p4.v1 + _ func() = p4.p1 + _ func() = p4.v2 + _ func() = p4.p2 + ) +} + +// Method calls with addressable receivers +func _() { + var v0 T0 + v0.v0() + v0.p0() + + var p0 *T0 + p0.v0() + p0.p0() + + // T1 is like T0 + + var v2 T2 + v2.v2() + v2.p2() + + var v4 T3 + v4.v0() + v4.p0() + v4.v1() + v4.p1() + v4.v2() + v4.p2() + + var p4 *T3 + p4.v0() + p4.p0() + p4.v1() + p4.p1() + p4.v2() + p4.p2() +} + +// Method values with value receivers +func _() { + var ( + _ func() = T0{}.v0 + _ func() = T0{}.p0 /* ERROR "cannot call pointer method p0 on T0" */ + + _ func() = (&T0{}).v0 + _ func() = (&T0{}).p0 + + // T1 is like T0 + + // no values for T2 + + _ func() = T3{}.v0 + _ func() = T3{}.p0 /* ERROR "cannot call pointer method p0 on T3" */ + _ func() = T3{}.v1 + _ func() = T3{}.p1 + _ func() = T3{}.v2 + _ func() = T3{}.p2 + + _ func() = (&T3{}).v0 + _ func() = (&T3{}).p0 + _ func() = (&T3{}).v1 + _ func() = (&T3{}).p1 + _ func() = (&T3{}).v2 + _ func() = (&T3{}).p2 + ) +} + +// Method calls with value receivers +func _() { + T0{}.v0() + T0{}.p0 /* ERROR "cannot call pointer method p0 on T0" */ () + + (&T0{}).v0() + (&T0{}).p0() + + // T1 is like T0 + + // no values for T2 + + T3{}.v0() + T3{}.p0 /* ERROR "cannot call pointer method p0 on T3" */ () + T3{}.v1() + T3{}.p1() + T3{}.v2() + T3{}.p2() + + (&T3{}).v0() + (&T3{}).p0() + (&T3{}).v1() + (&T3{}).p1() + (&T3{}).v2() + (&T3{}).p2() +} + +// *T has no methods if T is an interface type +func issue5918() { + var ( + err error + _ = err.Error() + _ func() string = err.Error + _ func(error) string = error.Error + + perr = &err + _ = perr.Error /* ERROR "type *error is pointer to interface, not interface" */ () + _ func() string = perr.Error /* ERROR "type *error is pointer to interface, not interface" */ + _ func(*error) string = (*error).Error /* ERROR "type *error is pointer to interface, not interface" */ + ) + + type T *interface{ m() int } + var ( + x T + _ = (*x).m() + _ = (*x).m + + _ = x.m /* ERROR "type T is pointer to interface, not interface" */ () + _ = x.m /* ERROR "type T is pointer to interface, not interface" */ + _ = T.m /* ERROR "type T is pointer to interface, not interface" */ + ) +} diff --git a/go/src/internal/types/testdata/check/shifts.go b/go/src/internal/types/testdata/check/shifts.go new file mode 100644 index 0000000000000000000000000000000000000000..6ae3985aba4b7bd2197356b29767b92601ef3931 --- /dev/null +++ b/go/src/internal/types/testdata/check/shifts.go @@ -0,0 +1,399 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package shifts + +func shifts0() { + // basic constant shifts + const ( + s = 10 + _ = 0<<0 + _ = 1<> s) + _, _, _ = u, v, x +} + +func shifts4() { + // shifts in comparisons w/ untyped operands + var s uint + + _ = 1<> 1.1 /* ERROR "truncated to uint" */ // example from issue 11325 + _ = 0 >> 1.1 /* ERROR "truncated to uint" */ + _ = 0 << 1.1 /* ERROR "truncated to uint" */ + _ = 0 >> 1. + _ = 1 >> 1.1 /* ERROR "truncated to uint" */ + _ = 1 >> 1. + _ = 1. >> 1 + _ = 1. >> 1. + _ = 1.1 /* ERROR "must be integer" */ >> 1 +} + +func issue11594() { + var _ = complex64 /* ERROR "must be integer" */ (1) << 2 // example from issue 11594 + _ = float32 /* ERROR "must be integer" */ (0) << 1 + _ = float64 /* ERROR "must be integer" */ (0) >> 2 + _ = complex64 /* ERROR "must be integer" */ (0) << 3 + _ = complex64 /* ERROR "must be integer" */ (0) >> 4 +} + +func issue21727() { + var s uint + var a = make([]int, 1< 255: + return 255 + } +} + +var input = []int{-4, 68954, 7, 44, 0, -555, 6945} +var limited1 = Map[int, byte](input, limiter) +var limited2 = Map(input, limiter) // using type inference + +func reducer(x float64, y int) float64 { + return x + float64(y) +} + +var reduced1 = Reduce[int, float64](input, 0, reducer) +var reduced2 = Reduce(input, 1i /* ERROR "overflows" */, reducer) // using type inference +var reduced3 = Reduce(input, 1, reducer) // using type inference + +func filter(x int) bool { + return x&1 != 0 +} + +var filtered1 = Filter[int](input, filter) +var filtered2 = Filter(input, filter) // using type inference + diff --git a/go/src/internal/types/testdata/check/stmt0.go b/go/src/internal/types/testdata/check/stmt0.go new file mode 100644 index 0000000000000000000000000000000000000000..e17dd650cdae627777b5a9fb169b75dcda07fc66 --- /dev/null +++ b/go/src/internal/types/testdata/check/stmt0.go @@ -0,0 +1,994 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// statements + +package stmt0 + +func assignments0() (int, int) { + var a, b, c int + var ch chan int + f0 := func() {} + f1 := func() int { return 1 } + f2 := func() (int, int) { return 1, 2 } + f3 := func() (int, int, int) { return 1, 2, 3 } + + a, b, c = 1, 2, 3 + a, b, c = 1 /* ERROR "assignment mismatch: 3 variables but 2 values" */ , 2 + a, b, c = 1 /* ERROR "assignment mismatch: 3 variables but 4 values" */ , 2, 3, 4 + _, _, _ = a, b, c + + a = f0 /* ERROR "used as value" */ () + a = f1() + a = f2 /* ERROR "assignment mismatch: 1 variable but f2 returns 2 values" */ () + a, b = f2() + a, b, c = f2 /* ERROR "assignment mismatch: 3 variables but f2 returns 2 values" */ () + a, b, c = f3() + a, b = f3 /* ERROR "assignment mismatch: 2 variables but f3 returns 3 values" */ () + + a, b, c = <- /* ERROR "assignment mismatch: 3 variables but 1 value" */ ch + + return /* ERROR "not enough return values\n\thave ()\n\twant (int, int)" */ + return 1 /* ERROR "not enough return values\n\thave (number)\n\twant (int, int)" */ + return 1, 2 + return 1, 2, 3 /* ERROR "too many return values\n\thave (number, number, number)\n\twant (int, int)" */ +} + +func assignments1() { + b, i, f, c, s := false, 1, 1.0, 1i, "foo" + b = i /* ERRORx `cannot use .* in assignment` */ + i = f /* ERRORx `cannot use .* in assignment` */ + f = c /* ERRORx `cannot use .* in assignment` */ + c = s /* ERRORx `cannot use .* in assignment` */ + s = b /* ERRORx `cannot use .* in assignment` */ + + v0, v1, v2 := 1 /* ERROR "assignment mismatch" */ , 2, 3, 4 + _, _, _ = v0, v1, v2 + + b = true + + i += 1 + i /* ERROR "mismatched types int and untyped string" */+= "foo" + + f -= 1 + f /= 0 + f = float32(0)/0 /* ERROR "division by zero" */ + f /* ERROR "mismatched types float64 and untyped string" */-= "foo" + + c *= 1 + c /= 0 + + s += "bar" + s /* ERROR "mismatched types string and untyped int" */+= 1 + + var u64 uint64 + u64 += 1< 0 { + return l[0], true + } + return +} + +// A test case for instantiating types with other types (extracted from map.go2) + +type Pair[K any] struct { + key K +} + +type Receiver[T any] struct { + values T +} + +type Iterator[K any] struct { + r Receiver[Pair[K]] +} + +func Values [T any] (r Receiver[T]) T { + return r.values +} + +func (it Iterator[K]) Next() K { + return Values[Pair[K]](it.r).key +} + +// A more complex test case testing type bounds (extracted from linalg.go2 and reduced to essence) + +type NumericAbs[T any] interface { + Abs() T +} + +func AbsDifference[T NumericAbs[T]](x T) { panic(0) } + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type OrderedAbs[T any] T +// +// func (a OrderedAbs[T]) Abs() OrderedAbs[T] +// +// func OrderedAbsDifference[T any](x T) { +// AbsDifference(OrderedAbs[T](x)) +// } + +// same code, reduced to essence + +func g[P interface{ m() P }](x P) { panic(0) } + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type T4[P any] P +// +// func (_ T4[P]) m() T4[P] +// +// func _[Q any](x Q) { +// g(T4[Q](x)) +// } + +// Another test case that caused problems in the past + +type T5[_ interface { a() }, _ interface{}] struct{} + +type A[P any] struct{ x P } + +func (_ A[P]) a() {} + +var _ T5[A[int], int] + +// Invoking methods with parameterized receiver types uses +// type inference to determine the actual type arguments matching +// the receiver type parameters from the actual receiver argument. +// Go does implicit address-taking and dereferenciation depending +// on the actual receiver and the method's receiver type. To make +// type inference work, the type-checker matches "pointer-ness" +// of the actual receiver and the method's receiver type. +// The following code tests this mechanism. + +type R1[A any] struct{} +func (_ R1[A]) vm() +func (_ *R1[A]) pm() + +func _[T any](r R1[T], p *R1[T]) { + r.vm() + r.pm() + p.vm() + p.pm() +} + +type R2[A, B any] struct{} +func (_ R2[A, B]) vm() +func (_ *R2[A, B]) pm() + +func _[T any](r R2[T, int], p *R2[string, T]) { + r.vm() + r.pm() + p.vm() + p.pm() +} + +// It is ok to have multiple embedded unions. +type _ interface { + m0() + ~int | ~string | ~bool + ~float32 | ~float64 + m1() + m2() + ~complex64 | ~complex128 + ~rune +} + +// Type sets may contain each type at most once. +type _ interface { + ~int|~ /* ERROR "overlapping terms ~int" */ int + ~int|int /* ERROR "overlapping terms int" */ + int|int /* ERROR "overlapping terms int" */ +} + +type _ interface { + ~struct{f int} | ~struct{g int} | ~ /* ERROR "overlapping terms" */ struct{f int} +} + +// Interface term lists can contain any type, incl. *Named types. +// Verify that we use the underlying type(s) of the type(s) in the +// term list when determining if an operation is permitted. + +type MyInt int +func add1[T interface{MyInt}](x T) T { + return x + 1 +} + +type MyString string +func double[T interface{MyInt|MyString}](x T) T { + return x + x +} + +// Embedding of interfaces with term lists leads to interfaces +// with term lists that are the intersection of the embedded +// term lists. + +type E0 interface { + ~int | ~bool | ~string +} + +type E1 interface { + ~int | ~float64 | ~string +} + +type E2 interface { + ~float64 +} + +type I0 interface { + E0 +} + +func f0[T I0]() {} +var _ = f0[int] +var _ = f0[bool] +var _ = f0[string] +var _ = f0[float64 /* ERROR "does not satisfy I0" */ ] + +type I01 interface { + E0 + E1 +} + +func f01[T I01]() {} +var _ = f01[int] +var _ = f01[bool /* ERROR "does not satisfy I0" */ ] +var _ = f01[string] +var _ = f01[float64 /* ERROR "does not satisfy I0" */ ] + +type I012 interface { + E0 + E1 + E2 +} + +func f012[T I012]() {} +var _ = f012[int /* ERRORx `cannot satisfy I012.*empty type set` */ ] +var _ = f012[bool /* ERRORx `cannot satisfy I012.*empty type set` */ ] +var _ = f012[string /* ERRORx `cannot satisfy I012.*empty type set` */ ] +var _ = f012[float64 /* ERRORx `cannot satisfy I012.*empty type set` */ ] + +type I12 interface { + E1 + E2 +} + +func f12[T I12]() {} +var _ = f12[int /* ERROR "does not satisfy I12" */ ] +var _ = f12[bool /* ERROR "does not satisfy I12" */ ] +var _ = f12[string /* ERROR "does not satisfy I12" */ ] +var _ = f12[float64] + +type I0_ interface { + E0 + ~int +} + +func f0_[T I0_]() {} +var _ = f0_[int] +var _ = f0_[bool /* ERROR "does not satisfy I0_" */ ] +var _ = f0_[string /* ERROR "does not satisfy I0_" */ ] +var _ = f0_[float64 /* ERROR "does not satisfy I0_" */ ] + +// Using a function instance as a type is an error. +var _ f0 // ERROR "not a type" +var _ f0 /* ERROR "not a type" */ [int] + +// Empty type sets can only be satisfied by empty type sets. +type none interface { + // force an empty type set + int + string +} + +func ff[T none]() {} +func gg[T any]() {} +func hh[T ~int]() {} + +func _[T none]() { + _ = ff[int /* ERROR "cannot satisfy none (empty type set)" */ ] + _ = ff[T] // pathological but ok because T's type set is empty, too + _ = gg[int] + _ = gg[T] + _ = hh[int] + _ = hh[T] +} diff --git a/go/src/internal/types/testdata/check/typeinstcycles.go b/go/src/internal/types/testdata/check/typeinstcycles.go new file mode 100644 index 0000000000000000000000000000000000000000..74fe19195a8e5e6cc4227c2ba897ff452df56295 --- /dev/null +++ b/go/src/internal/types/testdata/check/typeinstcycles.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +func F1[T any](_ [unsafe.Sizeof(F1[int])]T) (res T) { return } +func F2[T any](_ T) (res [unsafe.Sizeof(F2[string])]int) { return } +func F3[T any](_ [unsafe.Sizeof(F1[string])]int) {} diff --git a/go/src/internal/types/testdata/check/typeparams.go b/go/src/internal/types/testdata/check/typeparams.go new file mode 100644 index 0000000000000000000000000000000000000000..b73f1fee6d51daeee16b678add4ee24fc93ac52f --- /dev/null +++ b/go/src/internal/types/testdata/check/typeparams.go @@ -0,0 +1,508 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// import "io" // for type assertion tests + +var _ any // ok to use any anywhere +func _[_ any, _ interface{any}](any) { + var _ any +} + +func identity[T any](x T) T { return x } + +func _[_ any](x int) int { panic(0) } +func _[T any](T /* ERROR "redeclared" */ T)() {} +func _[T, T /* ERROR "redeclared" */ any]() {} + +// Constraints (incl. any) may be parenthesized. +func _[_ (any)]() {} +func _[_ (interface{})]() {} + +func reverse[T any](list []T) []T { + rlist := make([]T, len(list)) + i := len(list) + for _, x := range list { + i-- + rlist[i] = x + } + return rlist +} + +var _ = reverse /* ERROR "cannot use generic function reverse" */ +var _ = reverse[int, float32 /* ERROR "got 2 type arguments" */ ] ([]int{1, 2, 3}) +var _ = reverse[int]([ /* ERROR "cannot use" */ ]float32{1, 2, 3}) +var f = reverse[chan int] +var _ = f(0 /* ERRORx `cannot use 0 .* as \[\]chan int` */ ) + +func swap[A, B any](a A, b B) (B, A) { return b, a } + +var _ = swap /* ERROR "multiple-value" */ [int, float32](1, 2) +var f32, i = swap[int, float32](swap[float32, int](1, 2)) +var _ float32 = f32 +var _ int = i + +func swapswap[A, B any](a A, b B) (A, B) { + return swap[B, A](b, a) +} + +type F[A, B any] func(A, B) (B, A) + +func min[T interface{ ~int }](x, y T) T { + if x < y { + return x + } + return y +} + +func _[T interface{~int | ~float32}](x, y T) bool { return x < y } +func _[T any](x, y T) bool { return x /* ERROR "type parameter T cannot use operator <" */ < y } +func _[T interface{~int | ~float32 | ~bool}](x, y T) bool { return x /* ERROR "type parameter T cannot use operator <" */ < y } + +func _[T C1[T]](x, y T) bool { return x /* ERROR "type parameter T cannot use operator <" */ < y } +func _[T C2[T]](x, y T) bool { return x < y } + +type C1[T any] interface{} +type C2[T any] interface{ ~int | ~float32 } + +func new[T any]() *T { + var x T + return &x +} + +var _ = new /* ERROR "cannot use generic function new" */ +var _ *int = new[int]() + +func _[T any](map[T /* ERROR "invalid map key type T (missing comparable constraint)" */]int) {} // w/o constraint we don't know if T is comparable + +func f1[T1 any](struct{T1 /* ERRORx `cannot be a .* type parameter` */ }) int { panic(0) } +var _ = f1[int](struct{T1}{}) +type T1 = int + +func f2[t1 any](struct{t1 /* ERRORx `cannot be a .* type parameter` */ ; x float32}) int { panic(0) } +var _ = f2[t1](struct{t1; x float32}{}) +type t1 = int + + +func f3[A, B, C any](A, struct{x B}, func(A, struct{x B}, *C)) int { panic(0) } + +var _ = f3[int, rune, bool](1, struct{x rune}{}, nil) + +// indexing + +func _[T any] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } +func _[T interface{ ~int }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } +func _[T interface{ ~string }] (x T, i int) { _ = x[i] } +func _[T interface{ ~[]int }] (x T, i int) { _ = x[i] } +func _[T interface{ ~[10]int | ~*[20]int | ~map[int]int }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types +func _[T interface{ ~string | ~[]byte }] (x T, i int) { _ = x[i] } +func _[T interface{ ~[]int | ~[1]rune }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } +func _[T interface{ ~string | ~[]rune }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } + +// indexing with various combinations of map types in type sets (see issue #42616) +func _[T interface{ ~[]E | ~map[int]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types +func _[T interface{ ~[]E }, E any](x T, i int) { _ = &x[i] } +func _[T interface{ ~map[int]E }, E any](x T, i int) { _, _ = x[i] } // comma-ok permitted +func _[T interface{ ~map[int]E }, E any](x T, i int) { _ = &x /* ERROR "cannot take address" */ [i] } +func _[T interface{ ~map[int]E | ~map[uint]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // different map element types +func _[T interface{ ~[]E | ~map[string]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types + +// indexing with various combinations of array and other types in type sets +func _[T interface{ [10]int }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] } +func _[T interface{ [10]byte | string }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] } +func _[T interface{ [10]int | *[20]int | []int }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] } + +// indexing with strings and non-variable arrays (assignment not permitted) +func _[T string](x T) { _ = x[0]; x /* ERROR "cannot assign" */ [0] = 0 } +func _[T []byte | string](x T) { x /* ERROR "cannot assign" */ [0] = 0 } +func _[T [10]byte]() { f := func() (x T) { return }; f /* ERROR "cannot assign" */ ()[0] = 0 } +func _[T [10]byte]() { f := func() (x *T) { return }; f /* ERROR "cannot index" */ ()[0] = 0 } +func _[T [10]byte]() { f := func() (x *T) { return }; (*f())[0] = 0 } +func _[T *[10]byte]() { f := func() (x T) { return }; f()[0] = 0 } + +// slicing + +func _[T interface{ ~[10]E }, E any] (x T, i, j, k int) { var _ []E = x[i:j] } +func _[T interface{ ~[10]E }, E any] (x T, i, j, k int) { var _ []E = x[i:j:k] } +func _[T interface{ ~[]byte }] (x T, i, j, k int) { var _ T = x[i:j] } +func _[T interface{ ~[]byte }] (x T, i, j, k int) { var _ T = x[i:j:k] } +func _[T interface{ ~string }] (x T, i, j, k int) { var _ T = x[i:j] } +func _[T interface{ ~string }] (x T, i, j, k int) { var _ T = x[i:j:k /* ERROR "3-index slice of string" */ ] } + +type myByte1 []byte +type myByte2 []byte +func _[T interface{ []byte | myByte1 | myByte2 }] (x T, i, j, k int) { var _ T = x[i:j:k] } +func _[T interface{ []byte | myByte1 | []int }] (x T, i, j, k int) { var _ T = x /* ERROR "[]byte and []int have different underlying types" */ [i:j:k] } + +func _[T interface{ []byte | myByte1 | myByte2 | string }] (x T, i, j, k int) { var _ T = x[i:j] } +func _[T interface{ []byte | myByte1 | myByte2 | string }] (x T, i, j, k int) { var _ T = x[i:j:k /* ERROR "3-index slice of string" */ ] } +func _[T interface{ []byte | myByte1 | []int | string }] (x T, i, j, k int) { var _ T = x /* ERROR "[]byte and []int have different underlying types" */ [i:j] } + +// len/cap built-ins + +func _[T any](x T) { _ = len(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~int }](x T) { _ = len(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~string | ~[]byte | ~int }](x T) { _ = len(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~string }](x T) { _ = len(x) } +func _[T interface{ ~[10]int }](x T) { _ = len(x) } +func _[T interface{ ~[]byte }](x T) { _ = len(x) } +func _[T interface{ ~map[int]int }](x T) { _ = len(x) } +func _[T interface{ ~chan int }](x T) { _ = len(x) } +func _[T interface{ ~string | ~[]byte | ~chan int }](x T) { _ = len(x) } + +func _[T any](x T) { _ = cap(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~string | ~[]byte | ~int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~string }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~[10]int }](x T) { _ = cap(x) } +func _[T interface{ ~[]byte }](x T) { _ = cap(x) } +func _[T interface{ ~map[int]int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) } +func _[T interface{ ~chan int }](x T) { _ = cap(x) } +func _[T interface{ ~[]byte | ~chan int }](x T) { _ = cap(x) } + +// range iteration + +func _[T interface{}](x T) { + for range x /* ERROR "cannot range" */ {} +} + +type myString string + +func _[ + B1 interface{ string }, + B2 interface{ string | myString }, + + C1 interface{ chan int }, + C2 interface{ chan int | <-chan int }, + C3 interface{ chan<- int }, + + S1 interface{ []int }, + S2 interface{ []int | [10]int }, + + A1 interface{ [10]int }, + A2 interface{ [10]int | []int }, + + P1 interface{ *[10]int }, + P2 interface{ *[10]int | *[]int }, + + M1 interface{ map[string]int }, + M2 interface{ map[string]int | map[string]string }, +]() { + var b0 string + for range b0 {} + for _ = range b0 {} + for _, _ = range b0 {} + + var b1 B1 + for range b1 {} + for _ = range b1 {} + for _, _ = range b1 {} + + var b2 B2 + for range b2 {} + + var c0 chan int + for range c0 {} + for _ = range c0 {} + for _, _ /* ERROR "permits only one iteration variable" */ = range c0 {} + + var c1 C1 + for range c1 {} + for _ = range c1 {} + for _, _ /* ERROR "permits only one iteration variable" */ = range c1 {} + + var c2 C2 + for range c2 {} + + var c3 C3 + for range c3 /* ERROR "receive from send-only channel" */ {} + + var s0 []int + for range s0 {} + for _ = range s0 {} + for _, _ = range s0 {} + + var s1 S1 + for range s1 {} + for _ = range s1 {} + for _, _ = range s1 {} + + var s2 S2 + for range s2 /* ERRORx `cannot range over s2.*\[\]int and \[10\]int have different underlying types` */ {} + + var a0 []int + for range a0 {} + for _ = range a0 {} + for _, _ = range a0 {} + + var a1 A1 + for range a1 {} + for _ = range a1 {} + for _, _ = range a1 {} + + var a2 A2 + for range a2 /* ERRORx `cannot range over a2.*\[10\]int and \[\]int have different underlying types` */ {} + + var p0 *[10]int + for range p0 {} + for _ = range p0 {} + for _, _ = range p0 {} + + var p1 P1 + for range p1 {} + for _ = range p1 {} + for _, _ = range p1 {} + + var p2 P2 + for range p2 /* ERRORx `cannot range over p2.*\*\[10\]int and \*\[\]int have different underlying types` */ {} + + var m0 map[string]int + for range m0 {} + for _ = range m0 {} + for _, _ = range m0 {} + + var m1 M1 + for range m1 {} + for _ = range m1 {} + for _, _ = range m1 {} + + var m2 M2 + for range m2 /* ERRORx `cannot range over m2.*map\[string\]int and map\[string\]string` */ {} +} + +// type inference checks + +var _ = new /* ERROR "cannot infer T" */ () + +func f4[A, B, C any](A, B) C { panic(0) } + +var _ = f4 /* ERROR "cannot infer C" */ (1, 2) +var _ = f4[int, float32, complex128](1, 2) + +func f5[A, B, C any](A, []*B, struct{f []C}) int { panic(0) } + +var _ = f5[int, float32, complex128](0, nil, struct{f []complex128}{}) +var _ = f5 /* ERROR "cannot infer" */ (0, nil, struct{f []complex128}{}) +var _ = f5(0, []*float32{new[float32]()}, struct{f []complex128}{}) + +func f6[A any](A, []A) int { panic(0) } + +var _ = f6(0, nil) + +func f6nil[A any](A) int { panic(0) } + +var _ = f6nil /* ERROR "cannot infer" */ (nil) + +// type inference with variadic functions + +func f7[T any](...T) T { panic(0) } + +var _ int = f7 /* ERROR "cannot infer T" */ () +var _ int = f7(1) +var _ int = f7(1, 2) +var _ int = f7([]int{}...) +var _ int = f7 /* ERROR "cannot use" */ ([]float64{}...) +var _ float64 = f7([]float64{}...) +var _ = f7[float64](1, 2.3) +var _ = f7(float64(1), 2.3) +var _ = f7(1, 2.3) +var _ = f7(1.2, 3) + +func f8[A, B any](A, B, ...B) int { panic(0) } + +var _ = f8(1) /* ERROR "not enough arguments" */ +var _ = f8(1, 2.3) +var _ = f8(1, 2.3, 3.4, 4.5) +var _ = f8(1, 2.3, 3.4, 4) +var _ = f8[int, float64](1, 2.3, 3.4, 4) + +var _ = f8[int, float64](0, 0, nil...) // test case for #18268 + +// init functions cannot have type parameters + +func init() {} +func init[_ /* ERROR "func init must have no type parameters" */ any]() {} +func init[P /* ERROR "func init must have no type parameters" */ any]() {} + +type T struct {} + +func (T) m1() {} +func (T) m2[ /* ERROR "method must have no type parameters" */ _ any]() {} +func (T) m3[ /* ERROR "method must have no type parameters" */ P any]() {} + +// type inference across parameterized types + +type S1[P any] struct { f P } + +func f9[P any](x S1[P]) {} + +func _() { + f9[int](S1[int]{42}) + f9(S1[int]{42}) +} + +type S2[A, B, C any] struct{} + +func f10[X, Y, Z any](a S2[X, int, Z], b S2[X, Y, bool]) {} + +func _[P any]() { + f10[int, float32, string](S2[int, int, string]{}, S2[int, float32, bool]{}) + f10(S2[int, int, string]{}, S2[int, float32, bool]{}) + f10(S2[P, int, P]{}, S2[P, float32, bool]{}) +} + +// corner case for type inference +// (was bug: after instantiating f11, the type-checker didn't mark f11 as non-generic) + +func f11[T any]() {} + +func _() { + f11[int]() +} + +// the previous example was extracted from + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// func f12[T interface{m() T}]() {} +// +// type A[T any] T +// +// func (a A[T]) m() A[T] +// +// func _[T any]() { +// f12[A[T]]() +// } + +// method expressions + +func (_ S1[P]) m() + +func _() { + m := S1[int].m + m(struct { f int }{42}) +} + +func _[T any] (x T) { + m := S1[T].m + m(S1[T]{x}) +} + +type I1[A any] interface { + m1(A) +} + +var _ I1[int] = r1[int]{} + +type r1[T any] struct{} + +func (_ r1[T]) m1(T) + +type I2[A, B any] interface { + m1(A) + m2(A) B +} + +var _ I2[int, float32] = R2[int, float32]{} + +type R2[P, Q any] struct{} + +func (_ R2[X, Y]) m1(X) +func (_ R2[X, Y]) m2(X) Y + +// type assertions and type switches over generic types +// NOTE: These are currently disabled because it's unclear what the correct +// approach is, and one can always work around by assigning the variable to +// an interface first. + +// // ReadByte1 corresponds to the ReadByte example in the draft design. +// func ReadByte1[T io.Reader](r T) (byte, error) { +// if br, ok := r.(io.ByteReader); ok { +// return br.ReadByte() +// } +// var b [1]byte +// _, err := r.Read(b[:]) +// return b[0], err +// } +// +// // ReadBytes2 is like ReadByte1 but uses a type switch instead. +// func ReadByte2[T io.Reader](r T) (byte, error) { +// switch br := r.(type) { +// case io.ByteReader: +// return br.ReadByte() +// } +// var b [1]byte +// _, err := r.Read(b[:]) +// return b[0], err +// } +// +// // type assertions and type switches over generic types are strict +// type I3 interface { +// m(int) +// } +// +// type I4 interface { +// m() int // different signature from I3.m +// } +// +// func _[T I3](x I3, p T) { +// // type assertions and type switches over interfaces are not strict +// _ = x.(I4) +// switch x.(type) { +// case I4: +// } +// +// // type assertions and type switches over generic types are strict +// _ = p /* ERROR "cannot have dynamic type I4" */.(I4) +// switch p.(type) { +// case I4 /* ERROR "cannot have dynamic type I4" */ : +// } +// } + +// type assertions and type switches over generic types lead to errors for now + +func _[T any](x T) { + _ = x /* ERROR "cannot use type assertion" */ .(int) + switch x /* ERROR "cannot use type switch" */ .(type) { + } + + // work-around + var t interface{} = x + _ = t.(int) + switch t.(type) { + } +} + +func _[T interface{~int}](x T) { + _ = x /* ERROR "cannot use type assertion" */ .(int) + switch x /* ERROR "cannot use type switch" */ .(type) { + } + + // work-around + var t interface{} = x + _ = t.(int) + switch t.(type) { + } +} + +// error messages related to type bounds mention those bounds +type C[P any] interface{} + +func _[P C[P]] (x P) { + x.m /* ERROR "x.m undefined" */ () +} + +type I interface {} + +func _[P I] (x P) { + x.m /* ERROR "type P has no field or method m" */ () +} + +func _[P interface{}] (x P) { + x.m /* ERROR "type P has no field or method m" */ () +} + +func _[P any] (x P) { + x.m /* ERROR "type P has no field or method m" */ () +} diff --git a/go/src/internal/types/testdata/check/unions.go b/go/src/internal/types/testdata/check/unions.go new file mode 100644 index 0000000000000000000000000000000000000000..5a3a9edd356ab64e33b14e05f8bc004c12177f9d --- /dev/null +++ b/go/src/internal/types/testdata/check/unions.go @@ -0,0 +1,66 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check that overlong unions don't bog down type checking. +// Disallow them for now. + +package p + +type t int + +type ( + t00 t; t01 t; t02 t; t03 t; t04 t; t05 t; t06 t; t07 t; t08 t; t09 t + t10 t; t11 t; t12 t; t13 t; t14 t; t15 t; t16 t; t17 t; t18 t; t19 t + t20 t; t21 t; t22 t; t23 t; t24 t; t25 t; t26 t; t27 t; t28 t; t29 t + t30 t; t31 t; t32 t; t33 t; t34 t; t35 t; t36 t; t37 t; t38 t; t39 t + t40 t; t41 t; t42 t; t43 t; t44 t; t45 t; t46 t; t47 t; t48 t; t49 t + t50 t; t51 t; t52 t; t53 t; t54 t; t55 t; t56 t; t57 t; t58 t; t59 t + t60 t; t61 t; t62 t; t63 t; t64 t; t65 t; t66 t; t67 t; t68 t; t69 t + t70 t; t71 t; t72 t; t73 t; t74 t; t75 t; t76 t; t77 t; t78 t; t79 t + t80 t; t81 t; t82 t; t83 t; t84 t; t85 t; t86 t; t87 t; t88 t; t89 t + t90 t; t91 t; t92 t; t93 t; t94 t; t95 t; t96 t; t97 t; t98 t; t99 t +) + +type u99 interface { + t00|t01|t02|t03|t04|t05|t06|t07|t08|t09| + t10|t11|t12|t13|t14|t15|t16|t17|t18|t19| + t20|t21|t22|t23|t24|t25|t26|t27|t28|t29| + t30|t31|t32|t33|t34|t35|t36|t37|t38|t39| + t40|t41|t42|t43|t44|t45|t46|t47|t48|t49| + t50|t51|t52|t53|t54|t55|t56|t57|t58|t59| + t60|t61|t62|t63|t64|t65|t66|t67|t68|t69| + t70|t71|t72|t73|t74|t75|t76|t77|t78|t79| + t80|t81|t82|t83|t84|t85|t86|t87|t88|t89| + t90|t91|t92|t93|t94|t95|t96|t97|t98 +} + +type u100a interface { + u99|float32 +} + +type u100b interface { + u99|float64 +} + +type u101 interface { + t00|t01|t02|t03|t04|t05|t06|t07|t08|t09| + t10|t11|t12|t13|t14|t15|t16|t17|t18|t19| + t20|t21|t22|t23|t24|t25|t26|t27|t28|t29| + t30|t31|t32|t33|t34|t35|t36|t37|t38|t39| + t40|t41|t42|t43|t44|t45|t46|t47|t48|t49| + t50|t51|t52|t53|t54|t55|t56|t57|t58|t59| + t60|t61|t62|t63|t64|t65|t66|t67|t68|t69| + t70|t71|t72|t73|t74|t75|t76|t77|t78|t79| + t80|t81|t82|t83|t84|t85|t86|t87|t88|t89| + t90|t91|t92|t93|t94|t95|t96|t97|t98|t99| + int // ERROR "cannot handle more than 100 union terms" +} + +type u102 interface { + int /* ERROR "cannot handle more than 100 union terms" */ |string|u100a +} + +type u200 interface { + u100a /* ERROR "cannot handle more than 100 union terms" */ |u100b +} diff --git a/go/src/internal/types/testdata/check/vardecl.go b/go/src/internal/types/testdata/check/vardecl.go new file mode 100644 index 0000000000000000000000000000000000000000..726b619361fab764755c8a7bc1e5e7a7fb86c21a --- /dev/null +++ b/go/src/internal/types/testdata/check/vardecl.go @@ -0,0 +1,215 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vardecl + +// Prerequisites. +import "math" +func f() {} +func g() (x, y int) { return } +var m map[string]int + +// Var decls must have a type or an initializer. +var _ int +var _, _ int + +var _; /* ERROR "expected type" */ +var _, _; /* ERROR "expected type" */ +var _, _, _; /* ERROR "expected type" */ + +// The initializer must be an expression. +var _ = int /* ERROR "not an expression" */ +var _ = f /* ERROR "used as value" */ () + +// Identifier and expression arity must match. +var _, _ = 1, 2 +var _ = 1, 2 /* ERROR "extra init expr 2" */ +var _, _ = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ +var _, _, _ /* ERROR "missing init expr for _" */ = 1, 2 + +var _ = g /* ERROR "multiple-value g" */ () +var _, _ = g() +var _, _, _ = g /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ () + +var _ = m["foo"] +var _, _ = m["foo"] +var _, _, _ = m /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ["foo"] + +var _, _ int = 1, 2 +var _ int = 1, 2 /* ERROR "extra init expr 2" */ +var _, _ int = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ +var _, _, _ /* ERROR "missing init expr for _" */ int = 1, 2 + +var ( + _, _ = 1, 2 + _ = 1, 2 /* ERROR "extra init expr 2" */ + _, _ = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ + _, _, _ /* ERROR "missing init expr for _" */ = 1, 2 + + _ = g /* ERROR "multiple-value g" */ () + _, _ = g() + _, _, _ = g /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ () + + _ = m["foo"] + _, _ = m["foo"] + _, _, _ = m /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ["foo"] + + _, _ int = 1, 2 + _ int = 1, 2 /* ERROR "extra init expr 2" */ + _, _ int = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ + _, _, _ /* ERROR "missing init expr for _" */ int = 1, 2 +) + +// Variables declared in function bodies must be 'used'. +type T struct{} +func (r T) _(a, b, c int) (u, v, w int) { + var x1 /* ERROR "declared and not used" */ int + var x2 /* ERROR "declared and not used" */ int + x1 = 1 + (x2) = 2 + + y1 /* ERROR "declared and not used" */ := 1 + y2 /* ERROR "declared and not used" */ := 2 + y1 = 1 + (y1) = 2 + + { + var x1 /* ERROR "declared and not used" */ int + var x2 /* ERROR "declared and not used" */ int + x1 = 1 + (x2) = 2 + + y1 /* ERROR "declared and not used" */ := 1 + y2 /* ERROR "declared and not used" */ := 2 + y1 = 1 + (y1) = 2 + } + + if x /* ERROR "declared and not used" */ := 0; a < b {} + + switch x /* ERROR "declared and not used" */, y := 0, 1; a { + case 0: + _ = y + case 1: + x /* ERROR "declared and not used" */ := 0 + } + + var t interface{} + switch t /* ERROR "declared and not used" */ := t.(type) {} + + switch t /* ERROR "declared and not used" */ := t.(type) { + case int: + } + + switch t /* ERROR "declared and not used" */ := t.(type) { + case int: + case float32, complex64: + t = nil + } + + switch t := t.(type) { + case int: + case float32, complex64: + _ = t + } + + switch t := t.(type) { + case int: + case float32: + case string: + _ = func() string { + return t + } + } + + switch t := t; t /* ERROR "declared and not used" */ := t.(type) {} + + var z1 /* ERROR "declared and not used" */ int + var z2 int + _ = func(a, b, c int) (u, v, w int) { + z1 = a + (z1) = b + a = z2 + return + } + + var s []int + var i /* ERROR "declared and not used" */ , j int + for i, j = range s { + _ = j + } + + for i, j /* ERROR "declared and not used" */ := range s { + _ = func() int { + return i + } + } + return +} + +// Unused variables in function literals must lead to only one error (issue #22524). +func _() { + _ = func() { + var x /* ERROR "declared and not used" */ int + } +} + +// Invalid variable declarations must not lead to "declared and not used errors". +// TODO(gri) enable these tests once go/types follows types2 logic for declared and not used variables +// func _() { +// var a x // DISABLED_ERROR undefined: x +// var b = x // DISABLED_ERROR undefined: x +// var c int = x // DISABLED_ERROR undefined: x +// var d, e, f x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ +// var g, h, i = x, x, x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ +// var j, k, l float32 = x, x, x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ +// // but no "declared and not used" errors +// } + +// Invalid (unused) expressions must not lead to spurious "declared and not used errors". +func _() { + var a, b, c int + var x, y int + x, y = a /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ , b, c + _ = x + _ = y +} + +func _() { + var x int + return x /* ERROR "too many return values" */ + return math /* ERROR "too many return values" */ .Sin(0) +} + +func _() int { + var x, y int + return x, y /* ERROR "too many return values" */ +} + +// Short variable declarations must declare at least one new non-blank variable. +func _() { + _ := /* ERROR "no new variables" */ 0 + _, a := 0, 1 + _, a := /* ERROR "no new variables" */ 0, 1 + _, a, b := 0, 1, 2 + _, _, _ := /* ERROR "no new variables" */ 0, 1, 2 + + _ = a + _ = b +} + +// Test case for variables depending on function literals (see also #22992). +var A /* ERROR "initialization cycle" */ = func() int { return A }() + +func _() { + // The function literal below must not see a. + var a = func() int { return a /* ERROR "undefined" */ }() + var _ = func() int { return a }() + + // The function literal below must not see x, y, or z. + var x, y, z = 0, 1, func() int { return x /* ERROR "undefined" */ + y /* ERROR "undefined" */ + z /* ERROR "undefined" */ }() + _, _, _ = x, y, z +} + +// TODO(gri) consolidate other var decl checks in this file \ No newline at end of file diff --git a/go/src/internal/types/testdata/examples/constraints.go b/go/src/internal/types/testdata/examples/constraints.go new file mode 100644 index 0000000000000000000000000000000000000000..4c97a400977ced6c06e8344dc397daafc348fbdc --- /dev/null +++ b/go/src/internal/types/testdata/examples/constraints.go @@ -0,0 +1,80 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of generic constraint interfaces. + +package p + +type MyInt int + +type ( + // Arbitrary types may be embedded like interfaces. + _ interface{int} + _ interface{~int} + + // Types may be combined into a union. + union interface{int|~string} + + // Union terms must describe disjoint (non-overlapping) type sets. + _ interface{int|int /* ERROR "overlapping terms int" */ } + _ interface{int|~ /* ERROR "overlapping terms ~int" */ int } + _ interface{~int|~ /* ERROR "overlapping terms ~int" */ int } + _ interface{~int|MyInt /* ERROR "overlapping terms p.MyInt and ~int" */ } + _ interface{int|any} + _ interface{int|~string|union} + _ interface{int|~string|interface{int}} + _ interface{union|int} // interfaces (here: union) are ignored when checking for overlap + _ interface{union|union} // ditto + + // For now we do not permit interfaces with methods in unions. + _ interface{~ /* ERROR "invalid use of ~" */ any} + _ interface{int|interface /* ERRORx `cannot use .* in union` */ { m() }} +) + +type ( + // Tilde is not permitted on defined types or interfaces. + foo int + bar any + _ interface{foo} + _ interface{~ /* ERROR "invalid use of ~" */ foo } + _ interface{~ /* ERROR "invalid use of ~" */ bar } +) + +// Stand-alone type parameters are not permitted as elements or terms in unions. +type ( + _[T interface{ *T } ] struct{} // ok + _[T interface{ int | *T } ] struct{} // ok + _[T interface{ T /* ERROR "term cannot be a type parameter" */ } ] struct{} + _[T interface{ ~T /* ERROR "type in term ~T cannot be a type parameter" */ } ] struct{} + _[T interface{ int|T /* ERROR "term cannot be a type parameter" */ }] struct{} +) + +// Multiple embedded union elements are intersected. The order in which they +// appear in the interface doesn't matter since intersection is a symmetric +// operation. + +type myInt1 int +type myInt2 int + +func _[T interface{ myInt1|myInt2; ~int }]() T { return T(0) } +func _[T interface{ ~int; myInt1|myInt2 }]() T { return T(0) } + +// Here the intersections are empty - there's no type that's in the type set of T. +func _[T interface{ myInt1|myInt2; int }]() T { return T(0 /* ERROR "cannot convert" */ ) } +func _[T interface{ int; myInt1|myInt2 }]() T { return T(0 /* ERROR "cannot convert" */ ) } + +// Union elements may be interfaces as long as they don't define +// any methods or embed comparable. + +type ( + Integer interface{ ~int|~int8|~int16|~int32|~int64 } + Unsigned interface{ ~uint|~uint8|~uint16|~uint32|~uint64 } + Floats interface{ ~float32|~float64 } + Complex interface{ ~complex64|~complex128 } + Number interface{ Integer|Unsigned|Floats|Complex } + Ordered interface{ Integer|Unsigned|Floats|~string } + + _ interface{ Number | error /* ERROR "cannot use error in union" */ } + _ interface{ Ordered | comparable /* ERROR "cannot use comparable in union" */ } +) diff --git a/go/src/internal/types/testdata/examples/functions.go b/go/src/internal/types/testdata/examples/functions.go new file mode 100644 index 0000000000000000000000000000000000000000..fdc67e7162af555a82c218360b142d434191b3f5 --- /dev/null +++ b/go/src/internal/types/testdata/examples/functions.go @@ -0,0 +1,219 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of type-parameterized functions. + +package p + +// Reverse is a generic function that takes a []T argument and +// reverses that slice in place. +func Reverse[T any](list []T) { + i := 0 + j := len(list)-1 + for i < j { + list[i], list[j] = list[j], list[i] + i++ + j-- + } +} + +func _() { + // Reverse can be called with an explicit type argument. + Reverse[int](nil) + Reverse[string]([]string{"foo", "bar"}) + Reverse[struct{x, y int}]([]struct{x, y int}{{1, 2}, {2, 3}, {3, 4}}) + + // Since the type parameter is used for an incoming argument, + // it can be inferred from the provided argument's type. + Reverse([]string{"foo", "bar"}) + Reverse([]struct{x, y int}{{1, 2}, {2, 3}, {3, 4}}) + + // But the incoming argument must have a type, even if it's a + // default type. An untyped nil won't work. + // Reverse(nil) // this won't type-check + + // A typed nil will work, though. + Reverse([]int(nil)) +} + +// Certain functions, such as the built-in `new` could be written using +// type parameters. +func new[T any]() *T { + var x T + return &x +} + +// When calling our own `new`, we need to pass the type parameter +// explicitly since there is no (value) argument from which the +// result type could be inferred. We don't try to infer the +// result type from the assignment to keep things simple and +// easy to understand. +var _ = new[int]() +var _ *float64 = new[float64]() // the result type is indeed *float64 + +// A function may have multiple type parameters, of course. +func foo[A, B, C any](a A, b []B, c *C) B { + // do something here + return b[0] +} + +// As before, we can pass type parameters explicitly. +var s = foo[int, string, float64](1, []string{"first"}, new[float64]()) + +// Or we can use type inference. +var _ float64 = foo(42, []float64{1.0}, &s) + +// Type inference works in a straight-forward manner even +// for variadic functions. +func variadic[A, B any](A, B, ...B) int { panic(0) } + +// var _ = variadic(1) // ERROR "not enough arguments" +var _ = variadic(1, 2.3) +var _ = variadic(1, 2.3, 3.4, 4.5) +var _ = variadic[int, float64](1, 2.3, 3.4, 4) + +// Type inference also works in recursive function calls where +// the inferred type is the type parameter of the caller. +func f1[T any](x T) { + f1(x) +} + +func f2a[T any](x, y T) { + f2a(x, y) +} + +func f2b[T any](x, y T) { + f2b(y, x) +} + +func g2a[P, Q any](x P, y Q) { + g2a(x, y) +} + +func g2b[P, Q any](x P, y Q) { + g2b(y, x) +} + +// Here's an example of a recursive function call with variadic +// arguments and type inference inferring the type parameter of +// the caller (i.e., itself). +func max[T interface{ ~int }](x ...T) T { + var x0 T + if len(x) > 0 { + x0 = x[0] + } + if len(x) > 1 { + x1 := max(x[1:]...) + if x1 > x0 { + return x1 + } + } + return x0 +} + +// When inferring channel types, the channel direction is ignored +// for the purpose of type inference. Once the type has been in- +// fered, the usual parameter passing rules are applied. +// Thus even if a type can be inferred successfully, the function +// call may not be valid. + +func fboth[T any](chan T) {} +func frecv[T any](<-chan T) {} +func fsend[T any](chan<- T) {} + +func _() { + var both chan int + var recv <-chan int + var send chan<-int + + fboth(both) + fboth(recv /* ERROR "cannot use" */ ) + fboth(send /* ERROR "cannot use" */ ) + + frecv(both) + frecv(recv) + frecv(send /* ERROR "cannot use" */ ) + + fsend(both) + fsend(recv /* ERROR "cannot use" */) + fsend(send) +} + +func ffboth[T any](func(chan T)) {} +func ffrecv[T any](func(<-chan T)) {} +func ffsend[T any](func(chan<- T)) {} + +func _() { + var both func(chan int) + var recv func(<-chan int) + var send func(chan<- int) + + ffboth(both) + ffboth(recv /* ERROR "does not match" */ ) + ffboth(send /* ERROR "does not match" */ ) + + ffrecv(both /* ERROR "does not match" */ ) + ffrecv(recv) + ffrecv(send /* ERROR "does not match" */ ) + + ffsend(both /* ERROR "does not match" */ ) + ffsend(recv /* ERROR "does not match" */ ) + ffsend(send) +} + +// When inferring elements of unnamed composite parameter types, +// if the arguments are defined types, use their underlying types. +// Even though the matching types are not exactly structurally the +// same (one is a type literal, the other a named type), because +// assignment is permitted, parameter passing is permitted as well, +// so type inference should be able to handle these cases well. + +func g1[T any]([]T) {} +func g2[T any]([]T, T) {} +func g3[T any](*T, ...T) {} + +func _() { + type intSlice []int + g1([]int{}) + g1(intSlice{}) + g2(nil, 0) + + type myString string + var s1 string + g3(nil, "1", myString("2"), "3") + g3(& /* ERROR "cannot use &s1 (value of type *string) as *myString value in argument to g3" */ s1, "1", myString("2"), "3") + _ = s1 + + type myStruct struct{x int} + var s2 myStruct + g3(nil, struct{x int}{}, myStruct{}) + g3(&s2, struct{x int}{}, myStruct{}) + g3(nil, myStruct{}, struct{x int}{}) + g3(&s2, myStruct{}, struct{x int}{}) +} + +// Here's a realistic example. + +func append[T any](s []T, t ...T) []T { panic(0) } + +func _() { + var f func() + type Funcs []func() + var funcs Funcs + _ = append(funcs, f) +} + +// Generic type declarations cannot have empty type parameter lists +// (that would indicate a slice type). Thus, generic functions cannot +// have empty type parameter lists, either. This is a syntax error. + +func h[] /* ERROR "empty type parameter list" */ () {} + +func _() { + h /* ERROR "cannot index" */ [] /* ERROR "operand" */ () +} + +// Generic functions must have a function body. + +func _ /* ERROR "generic function is missing function body" */ [P any]() diff --git a/go/src/internal/types/testdata/examples/inference.go b/go/src/internal/types/testdata/examples/inference.go new file mode 100644 index 0000000000000000000000000000000000000000..0aaaa8278c1478fa472383dfa5dd9ec5badb8ebc --- /dev/null +++ b/go/src/internal/types/testdata/examples/inference.go @@ -0,0 +1,163 @@ +// -lang=go1.20 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of type inference. + +package p + +type Ordered interface { + ~int | ~float64 | ~string +} + +func min[T Ordered](x, y T) T { panic(0) } + +func _() { + // min can be called with explicit instantiation. + _ = min[int](1, 2) + + // Alternatively, the type argument can be inferred from + // one of the arguments. Untyped arguments will be considered + // last. + var x int + _ = min(x, x) + _ = min(x, 1) + _ = min(x, 1.0) + _ = min(1, 2) + _ = min(1, 2.3) + + var y float64 + _ = min(1, y) + _ = min(1.2, y) + _ = min(1.2, 3.4) + _ = min(1.2, 3) + + var s string + _ = min(s, "foo") + _ = min("foo", "bar") +} + +func mixed[T1, T2, T3 any](T1, T2, T3) {} + +func _() { + // mixed can be called with explicit instantiation. + mixed[int, string, bool](0, "", false) + + // Alternatively, partial type arguments may be provided + // (from left to right), and the other may be inferred. + mixed[int, string](0, "", false) + mixed[int](0, "", false) + mixed(0, "", false) + + // Provided type arguments always take precedence over + // inferred types. + mixed[int, string](1.1 /* ERROR "cannot use 1.1" */, "", false) +} + +func related1[Slice interface{ ~[]Elem }, Elem any](s Slice, e Elem) {} + +func _() { + // related1 can be called with explicit instantiation. + var si []int + related1[[]int, int](si, 0) + + // Alternatively, the 2nd type argument can be inferred + // from the first one through constraint type inference. + var ss []string + _ = related1[[]string] + related1[[]string](ss, "foo") + + // A type argument inferred from another explicitly provided + // type argument overrides whatever value argument type is given. + related1[[]string](ss, 0 /* ERROR "cannot use 0" */) + + // A type argument may be inferred from a value argument + // and then help infer another type argument via constraint + // type inference. + related1(si, 0) + related1(si, "foo" /* ERROR `cannot use "foo"` */) +} + +func related2[Elem any, Slice interface{ []Elem }](e Elem, s Slice) {} + +func _() { + // related2 can be called with explicit instantiation. + var si []int + related2[int, []int](0, si) + + // Alternatively, the 2nd type argument can be inferred + // from the first one through constraint type inference. + var ss []string + _ = related2[string] + related2[string]("foo", ss) + + // A type argument may be inferred from a value argument + // and then help infer another type argument via constraint + // type inference. Untyped arguments are always considered + // last. + related2(1.2, []float64{}) + related2(1.0, []int{}) + related2 /* ERROR "Slice (type []int) does not satisfy interface{[]Elem}" */ (float64(1.0), []int{}) // TODO(gri) better error message +} + +type List[P any] []P + +func related3[Elem any, Slice []Elem | List[Elem]]() Slice { return nil } + +func _() { + // related3 can be instantiated explicitly + related3[int, []int]() + related3[byte, List[byte]]() + + // The 2nd type argument cannot be inferred from the first + // one because there's two possible choices: []Elem and + // List[Elem]. + related3 /* ERROR "cannot infer Slice" */ [int]() +} + +func wantsMethods[P interface { + m1(Q) + m2() R +}, Q, R any](P) { +} + +type hasMethods1 struct{} + +func (hasMethods1) m1(int) +func (hasMethods1) m2() string + +type hasMethods2 struct{} + +func (*hasMethods2) m1(int) +func (*hasMethods2) m2() string + +type hasMethods3 interface { + m1(float64) + m2() complex128 +} + +type hasMethods4 interface { + m1() +} + +func _() { + // wantsMethod can be called with arguments that have the relevant methods + // and wantsMethod's type arguments are inferred from those types' method + // signatures. + wantsMethods(hasMethods1{}) + wantsMethods(&hasMethods1{}) + wantsMethods /* ERROR "P (type hasMethods2) does not satisfy interface{m1(Q); m2() R} (method m1 has pointer receiver)" */ (hasMethods2{}) + wantsMethods(&hasMethods2{}) + wantsMethods(hasMethods3(nil)) + wantsMethods /* ERROR "P (type any) does not satisfy interface{m1(Q); m2() R} (missing method m1)" */ (any(nil)) + wantsMethods /* ERROR "P (type hasMethods4) does not satisfy interface{m1(Q); m2() R} (wrong type for method m1)" */ (hasMethods4(nil)) +} + +// "Reverse" type inference is not yet permitted. + +func f[P any](P) {} + +// This must not crash. +var _ func(int) = f // ERROR "implicitly instantiated function in assignment requires go1.21 or later" diff --git a/go/src/internal/types/testdata/examples/inference2.go b/go/src/internal/types/testdata/examples/inference2.go new file mode 100644 index 0000000000000000000000000000000000000000..91f9df1d840d0460846f9f98f47306f6ce5a6332 --- /dev/null +++ b/go/src/internal/types/testdata/examples/inference2.go @@ -0,0 +1,104 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of "reverse" type inference +// where the type arguments for generic functions are determined +// from assigning the functions. + +package p + +func f1[P any](P) {} +func f2[P any]() P { var x P; return x } +func f3[P, Q any](P) Q { var x Q; return x } +func f4[P any](P, P) {} +func f5[P any](P) []P { return nil } +func f6[P any](int) P { var x P; return x } +func f7[P any](P) string { return "" } + +// initialization expressions +var ( + v1 = f1 // ERROR "cannot use generic function f1 without instantiation" + v2 func(int) = f2 // ERROR "cannot infer P" + + v3 func(int) = f1 + v4 func() int = f2 + v5 func(int) int = f3 + _ func(int) int = f3[int] + + v6 func(int, int) = f4 + v7 func(int, string) = f4 // ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of v7" + v8 func(int) []int = f5 + v9 func(string) []int = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of v9" + + _, _ func(int) = f1, f1 + _, _ func(int) = f1, f2 // ERROR "cannot infer P" +) + +// Regular assignments +func _() { + v1 = f1 // no error here because v1 is invalid (we don't know its type) due to the error above + var v1_ func() int + _ = v1_ + v1_ = f1 // ERROR "cannot infer P" + v2 = f2 // ERROR "cannot infer P" + + v3 = f1 + v4 = f2 + v5 = f3 + v5 = f3[int] + + v6 = f4 + v7 = f4 // ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of v7" + v8 = f5 + v9 = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of v9" + + // non-trivial LHS + var a [2]func(string) []int + a[0] = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of a[0]" +} + +// Return statements +func _() func(int) { return f1 } +func _() func() int { return f2 } +func _() func(int) int { return f3 } +func _() func(int) int { return f3[int] } + +func _() func(int, int) { return f4 } +func _() func(int, string) { + return f4 /* ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of result variable" */ +} +func _() func(int) []int { return f5 } +func _() func(string) []int { + return f5 /* ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of result variable" */ +} + +func _() (_, _ func(int)) { return f1, f1 } +func _() (_, _ func(int)) { return f1, f2 /* ERROR "cannot infer P" */ } + +// Argument passing +func g1(func(int)) {} +func g2(func(int, int)) {} +func g3(func(int) string) {} +func g4[P any](func(P) string) {} +func g5[P, Q any](func(P) string, func(P) Q) {} +func g6(func(int), func(string)) {} + +func _() { + g1(f1) + g1(f2 /* ERROR "cannot infer P" */) + g2(f4) + g4(f6) + g5(f6, f7) + g6(f1, f1) +} + +// Argument passing of partially instantiated functions +func h(func(int, string), func(string, int)) {} + +func p[P, Q any](P, Q) {} + +func _() { + h(p, p) + h(p[int], p[string]) +} diff --git a/go/src/internal/types/testdata/examples/methods.go b/go/src/internal/types/testdata/examples/methods.go new file mode 100644 index 0000000000000000000000000000000000000000..e92dc5028bb3ae14a48298a2ebf811a1bec5dbf6 --- /dev/null +++ b/go/src/internal/types/testdata/examples/methods.go @@ -0,0 +1,112 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of methods on type-parameterized types. + +package p + +// Parameterized types may have methods. +type T1[A any] struct{ a A } + +// When declaring a method for a parameterized type, the "instantiated" +// receiver type acts as an implicit declaration of the type parameters +// for the receiver type. In the example below, method m1 on type T1 has +// the receiver type T1[A] which declares the type parameter A for use +// with this method. That is, within the method m1, A stands for the +// actual type argument provided to an instantiated T1. +func (t T1[A]) m1() A { return t.a } + +// For instance, if T1 is instantiated with the type int, the type +// parameter A in m1 assumes that type (int) as well and we can write +// code like this: +var x T1[int] +var _ int = x.m1() + +// Because the type parameter provided to a parameterized receiver type +// is declared through that receiver declaration, it must be an identifier. +// It cannot possibly be some other type because the receiver type is not +// instantiated with concrete types, it is standing for the parameterized +// receiver type. +func (t T1[[ /* ERROR "must be an identifier" */ ]int]) m2() {} + +// Note that using what looks like a predeclared identifier, say int, +// as type parameter in this situation is deceptive and considered bad +// style. In m3 below, int is the name of the local receiver type parameter +// and it shadows the predeclared identifier int which then cannot be used +// anymore as expected. +// This is no different from locally re-declaring a predeclared identifier +// and usually should be avoided. There are some notable exceptions; e.g., +// sometimes it makes sense to use the identifier "copy" which happens to +// also be the name of a predeclared built-in function. +func (t T1[int]) m3() { var _ int = 42 /* ERRORx `cannot use 42 .* as int` */ } + +// The names of the type parameters used in a parameterized receiver +// type don't have to match the type parameter names in the declaration +// of the type used for the receiver. In our example, even though T1 is +// declared with type parameter named A, methods using that receiver type +// are free to use their own name for that type parameter. That is, the +// name of type parameters is always local to the declaration where they +// are introduced. In our example we can write a method m2 and use the +// name X instead of A for the type parameter w/o any difference. +func (t T1[X]) m4() X { return t.a } + +// If the receiver type is parameterized, type parameters must always be +// provided: this simply follows from the general rule that a parameterized +// type must be instantiated before it can be used. A method receiver +// declaration using a parameterized receiver type is no exception. It is +// simply that such receiver type expressions perform two tasks simultaneously: +// they declare the (local) type parameters and then use them to instantiate +// the receiver type. Forgetting to provide a type parameter leads to an error. +func (t T1 /* ERRORx `generic type .* without instantiation` */ ) m5() {} + +// However, sometimes we don't need the type parameter, and thus it is +// inconvenient to have to choose a name. Since the receiver type expression +// serves as a declaration for its type parameters, we are free to choose the +// blank identifier: +func (t T1[_]) m6() {} + +// Naturally, these rules apply to any number of type parameters on the receiver +// type. Here are some more complex examples. +type T2[A, B, C any] struct { + a A + b B + c C +} + +// Naming of the type parameters is local and has no semantic impact: +func (t T2[A, B, C]) m1() (A, B, C) { return t.a, t.b, t.c } +func (t T2[C, B, A]) m2() (C, B, A) { return t.a, t.b, t.c } +func (t T2[X, Y, Z]) m3() (X, Y, Z) { return t.a, t.b, t.c } + +// Type parameters may be left blank if they are not needed: +func (t T2[A, _, C]) m4() (A, C) { return t.a, t.c } +func (t T2[_, _, X]) m5() X { return t.c } +func (t T2[_, _, _]) m6() {} + +// As usual, blank names may be used for any object which we don't care about +// using later. For instance, we may write an unnamed method with a receiver +// that cannot be accessed: +func (_ T2[_, _, _]) _() int { return 42 } + +// Because a receiver parameter list is simply a parameter list, we can +// leave the receiver argument away for receiver types. +type T0 struct{} +func (T0) _() {} +func (T1[A]) _() {} + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// // A generic receiver type may constrain its type parameter such +// // that it must be a pointer type. Such receiver types are not +// // permitted. +// type T3a[P interface{ ~int | ~string | ~float64 }] P +// +// func (T3a[_]) m() {} // this is ok +// +// type T3b[P interface{ ~unsafe.Pointer }] P +// +// func (T3b /* ERROR "invalid receiver" */ [_]) m() {} +// +// type T3c[P interface{ *int | *string }] P +// +// func (T3c /* ERROR "invalid receiver" */ [_]) m() {} diff --git a/go/src/internal/types/testdata/examples/operations.go b/go/src/internal/types/testdata/examples/operations.go new file mode 100644 index 0000000000000000000000000000000000000000..9fb95d0b2b05ad14923a8e6a9b1eb286bcbf1774 --- /dev/null +++ b/go/src/internal/types/testdata/examples/operations.go @@ -0,0 +1,29 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// indirection + +func _[P any](p P) { + _ = *p // ERROR "cannot indirect p" +} + +func _[P interface{ int }](p P) { + _ = *p // ERROR "cannot indirect p" +} + +func _[P interface{ *int }](p P) { + _ = *p +} + +func _[P interface{ *int | *string }](p P) { + _ = *p // ERROR "must have identical base types" +} + +type intPtr *int + +func _[P interface{ *int | intPtr } ](p P) { + var _ int = *p +} diff --git a/go/src/internal/types/testdata/examples/types.go b/go/src/internal/types/testdata/examples/types.go new file mode 100644 index 0000000000000000000000000000000000000000..d6da2c5f6f9f9fa8247964d25d46371366796b07 --- /dev/null +++ b/go/src/internal/types/testdata/examples/types.go @@ -0,0 +1,315 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of generic types. + +package p + +// List is just what it says - a slice of E elements. +type List[E any] []E + +// A generic (parameterized) type must always be instantiated +// before it can be used to designate the type of a variable +// (including a struct field, or function parameter); though +// for the latter cases, the provided type may be another type +// parameter. So: +var _ List[byte] = []byte{} + +// A generic binary tree might be declared as follows. +type Tree[E any] struct { + left, right *Tree[E] + payload E +} + +// A simple instantiation of Tree: +var root1 Tree[int] + +// The actual type parameter provided may be a generic type itself: +var root2 Tree[List[int]] + +// A couple of more complex examples. +// We don't need extra parentheses around the element type of the slices on +// the right (unlike when we use ()'s rather than []'s for type parameters). +var _ List[List[int]] = []List[int]{} +var _ List[List[List[Tree[int]]]] = []List[List[Tree[int]]]{} + +// Type parameters act like type aliases when used in generic types +// in the sense that we can "emulate" a specific type instantiation +// with type aliases. +type T1[P any] struct { + f P +} + +type T2[P any] struct { + f struct { + g P + } +} + +var x1 T1[struct{ g int }] +var x2 T2[int] + +func _() { + // This assignment is invalid because the types of x1, x2 are T1(...) + // and T2(...) respectively, which are two different defined types. + x1 = x2 // ERROR "assignment" + + // This assignment is valid because the types of x1.f and x2.f are + // both struct { g int }; the type parameters act like type aliases + // and their actual names don't come into play here. + x1.f = x2.f +} + +// We can verify this behavior using type aliases instead: +type T1a struct { + f A1 +} +type A1 = struct { g int } + +type T2a struct { + f struct { + g A2 + } +} +type A2 = int + +var x1a T1a +var x2a T2a + +func _() { + x1a = x2a // ERROR "assignment" + x1a.f = x2a.f +} + +// Another interesting corner case are generic types that don't use +// their type arguments. For instance: +type T[P any] struct{} + +var xint T[int] +var xbool T[bool] + +// Are these two variables of the same type? After all, their underlying +// types are identical. We consider them to be different because each type +// instantiation creates a new named type, in this case T and T +// even if their underlying types are identical. This is sensible because +// we might still have methods that have different signatures or behave +// differently depending on the type arguments, and thus we can't possibly +// consider such types identical. Consequently: +func _() { + xint = xbool // ERROR "assignment" +} + +// Generic types cannot be used without instantiation. +var _ T // ERROR "cannot use generic type T" +var _ = T /* ERROR "cannot use generic type T" */ (0) + +// In type context, generic (parameterized) types cannot be parenthesized before +// being instantiated. See also NOTES entry from 12/4/2019. +var _ (T /* ERROR "cannot use generic type T" */ )[ /* ERRORx `unexpected \[|expected ';'` */ int] + +// All types may be parameterized, including interfaces. +type I1[T any] interface{ + m1(T) +} + +// There is no such thing as a variadic generic type. +type _[T ... /* ERROR "invalid use of ..." */ any] struct{} + +// Generic interfaces may be embedded as one would expect. +type I2 interface { + I1(int) // method! + I1[string] // embedded I1 +} + +func _() { + var x I2 + x.I1(0) + x.m1("foo") +} + +type I0 interface { + m0() +} + +type I3 interface { + I0 + I1[bool] + m(string) +} + +func _() { + var x I3 + x.m0() + x.m1(true) + x.m("foo") +} + +type _ struct { + ( /* ERROR "cannot parenthesize" */ int8) + ( /* ERROR "cannot parenthesize" */ *int16) + *( /* ERROR "cannot parenthesize" */ int32) + List[int] + + int8 /* ERROR "int8 redeclared" */ + *int16 /* ERROR "int16 redeclared" */ + List /* ERROR "List redeclared" */ [int] +} + +// Issue #45639: We don't allow this anymore. Keep this code +// in case we decide to revisit this decision. +// +// It's possible to declare local types whose underlying types +// are type parameters. As with ordinary type definitions, the +// types underlying properties are "inherited" but the methods +// are not. +// func _[T interface{ m(); ~int }]() { +// type L T +// var x L +// +// // m is not defined on L (it is not "inherited" from +// // its underlying type). +// x.m /* ERROR "x.m undefined" */ () +// +// // But the properties of T, such that as that it supports +// // the operations of the types given by its type bound, +// // are also the properties of L. +// x++ +// _ = x - x +// +// // On the other hand, if we define a local alias for T, +// // that alias stands for T as expected. +// type A = T +// var y A +// y.m() +// _ = y < 0 +// } + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// // It is not permitted to declare a local type whose underlying +// // type is a type parameter not declared by that type declaration. +// func _[T any]() { +// type _ T // ERROR "cannot use function type parameter T as RHS in type declaration" +// type _ [_ any] T // ERROR "cannot use function type parameter T as RHS in type declaration" +// } + +// As a special case, an explicit type argument may be omitted +// from a type parameter bound if the type bound expects exactly +// one type argument. In that case, the type argument is the +// respective type parameter to which the type bound applies. +// Note: We may not permit this syntactic sugar at first. +// Note: This is now disabled. All examples below are adjusted. +type Adder[T any] interface { + Add(T) T +} + +// We don't need to explicitly instantiate the Adder bound +// if we have exactly one type parameter. +func Sum[T Adder[T]](list []T) T { + var sum T + for _, x := range list { + sum = sum.Add(x) + } + return sum +} + +// Valid and invalid variations. +type B0 any +type B1[_ any] any +type B2[_, _ any] any + +func _[T1 B0]() {} +func _[T1 B1[T1]]() {} +func _[T1 B2 /* ERRORx `cannot use generic type .* without instantiation` */ ]() {} + +func _[T1, T2 B0]() {} +func _[T1 B1[T1], T2 B1[T2]]() {} +func _[T1, T2 B2 /* ERRORx `cannot use generic type .* without instantiation` */ ]() {} + +func _[T1 B0, T2 B1[T2]]() {} // here B1 applies to T2 + +// When the type argument is left away, the type bound is +// instantiated for each type parameter with that type +// parameter. +// Note: We may not permit this syntactic sugar at first. +func _[A Adder[A], B Adder[B], C Adder[A]]() { + var a A // A's type bound is Adder[A] + a = a.Add(a) + var b B // B's type bound is Adder[B] + b = b.Add(b) + var c C // C's type bound is Adder[A] + a = c.Add(a) +} + +// The type of variables (incl. parameters and return values) cannot +// be an interface with type constraints or be/embed comparable. +type I interface { + ~int +} + +var ( + _ interface /* ERROR "contains type constraints" */ {~int} + _ I /* ERROR "contains type constraints" */ +) + +func _(I /* ERROR "contains type constraints" */ ) +func _(x, y, z I /* ERROR "contains type constraints" */ ) +func _() I /* ERROR "contains type constraints" */ + +func _() { + var _ I /* ERROR "contains type constraints" */ +} + +type C interface { + comparable +} + +var _ comparable /* ERROR "comparable" */ +var _ C /* ERROR "comparable" */ + +func _(_ comparable /* ERROR "comparable" */ , _ C /* ERROR "comparable" */ ) + +func _() { + var _ comparable /* ERROR "comparable" */ + var _ C /* ERROR "comparable" */ +} + +// Type parameters are never const types, i.e., it's +// not possible to declare a constant of type parameter type. +// (If a type set contains just a single const type, we could +// allow it, but such type sets don't make much sense in the +// first place.) +func _[T interface{~int|~float64}]() { + // not valid + const _ = T /* ERROR "not constant" */ (0) + const _ T /* ERROR "invalid constant type T" */ = 1 + + // valid + var _ = T(0) + var _ T = 1 + _ = T(0) +} + +// It is possible to create composite literals of type parameter +// type as long as it's possible to create a composite literal +// of the core type of the type parameter's constraint. +func _[P interface{ ~[]int }]() P { + return P{} + return P{1, 2, 3} +} + +func _[P interface{ ~[]E }, E interface{ map[string]P } ]() P { + x := P{} + return P{{}} + return P{E{}} + return P{E{"foo": x}} + return P{{"foo": x}, {}} +} + +// This is a degenerate case with a singleton type set, but we can create +// composite literals even if the core type is a defined type. +type MyInts []int + +func _[P MyInts]() P { + return P{} +} diff --git a/go/src/internal/types/testdata/examples/typesets.go b/go/src/internal/types/testdata/examples/typesets.go new file mode 100644 index 0000000000000000000000000000000000000000..93eada730a31ce13c5b87900a6b6c43ff999b9da --- /dev/null +++ b/go/src/internal/types/testdata/examples/typesets.go @@ -0,0 +1,59 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file shows some examples of constraint literals with elided interfaces. +// These examples are permitted if proposal issue #48424 is accepted. + +package p + +// Constraint type sets of the form T, ~T, or A|B may omit the interface. +type ( + _[T int] struct{} + _[T ~int] struct{} + _[T int | string] struct{} + _[T ~int | ~string] struct{} +) + +func min[T int | string](x, y T) T { + if x < y { + return x + } + return y +} + +func lookup[M ~map[K]V, K comparable, V any](m M, k K) V { + return m[k] +} + +func deref[P ~*E, E any](p P) E { + return *p +} + +func _() int { + p := new(int) + return deref(p) +} + +func addrOfCopy[V any, P *V](v V) P { + return &v +} + +func _() *int { + return addrOfCopy(0) +} + +// A type parameter may not be embedded in an interface; +// so it can also not be used as a constraint. +func _[A any, B A /* ERROR "cannot use a type parameter as constraint" */]() {} +func _[A any, B, C A /* ERROR "cannot use a type parameter as constraint" */]() {} + +// Error messages refer to the type constraint as it appears in the source. +// (No implicit interface should be exposed.) +func _[T string](x T) T { + return x /* ERROR "constrained by string" */ * x +} + +func _[T int | string](x T) T { + return x /* ERROR "constrained by int | string" */ * x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue20583.go b/go/src/internal/types/testdata/fixedbugs/issue20583.go new file mode 100644 index 0000000000000000000000000000000000000000..55cbd9417562de62f650780daf63e22b5b18b115 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue20583.go @@ -0,0 +1,14 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue20583 + +const ( + _ = 6e886451608 /* ERROR "malformed constant" */ /2 + _ = 6e886451608i /* ERROR "malformed constant" */ /2 + _ = 0 * 1e+1000000000 // ERROR "malformed constant" + + x = 1e100000000 + _ = x*x*x*x*x*x* /* ERROR "not representable" */ x +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue23203a.go b/go/src/internal/types/testdata/fixedbugs/issue23203a.go new file mode 100644 index 0000000000000000000000000000000000000000..48cb5889cd90ef1fcf0dfbc6fee261b571c72a0d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue23203a.go @@ -0,0 +1,14 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "unsafe" + +type T struct{} + +func (T) m1() {} +func (T) m2([unsafe.Sizeof(T.m1)]int) {} + +func main() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue23203b.go b/go/src/internal/types/testdata/fixedbugs/issue23203b.go new file mode 100644 index 0000000000000000000000000000000000000000..638ec6c5ce34c5d0dd974e11fc0655b038f851b0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue23203b.go @@ -0,0 +1,14 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "unsafe" + +type T struct{} + +func (T) m2([unsafe.Sizeof(T.m1)]int) {} +func (T) m1() {} + +func main() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue25838.go b/go/src/internal/types/testdata/fixedbugs/issue25838.go new file mode 100644 index 0000000000000000000000000000000000000000..b0ea98ee89609f97bda9d7a0da0a26ccabfb5b72 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue25838.go @@ -0,0 +1,40 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// examples from the issue + +type ( + e = f + f = g + g = []h + h i + i = j + j = e +) + +type ( + e1 = []h1 + h1 e1 +) + +type ( + P = *T + T P +) + +func newA(c funcAlias) A { + return A{c: c} +} + +type B struct { + a *A +} + +type A struct { + c funcAlias +} + +type funcAlias = func(B) diff --git a/go/src/internal/types/testdata/fixedbugs/issue26390.go b/go/src/internal/types/testdata/fixedbugs/issue26390.go new file mode 100644 index 0000000000000000000000000000000000000000..9e0101f5819b9c4fbbee387d56408a7a8f51e073 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue26390.go @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// stand-alone test to ensure case is triggered + +package issue26390 + +type A = T + +func (t *T) m() *A { return t } + +type T struct{} diff --git a/go/src/internal/types/testdata/fixedbugs/issue28251.go b/go/src/internal/types/testdata/fixedbugs/issue28251.go new file mode 100644 index 0000000000000000000000000000000000000000..71e727e2ac64152ee484586f0b500ed123cc4f71 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue28251.go @@ -0,0 +1,65 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains test cases for various forms of +// method receiver declarations, per the spec clarification +// https://golang.org/cl/142757. + +package issue28251 + +// test case from issue28251 +type T struct{} + +type T0 = *T + +func (T0) m() {} + +func _() { (&T{}).m() } + +// various alternative forms +type ( + T1 = (((T))) +) + +func ((*(T1))) m1() {} +func _() { (T{}).m2() } +func _() { (&T{}).m2() } + +type ( + T2 = (((T3))) + T3 = T +) + +func (T2) m2() {} +func _() { (T{}).m2() } +func _() { (&T{}).m2() } + +type ( + T4 = ((*(T5))) + T5 = T +) + +func (T4) m4() {} +func _() { (T{}).m4 /* ERROR "cannot call pointer method m4 on T" */ () } +func _() { (&T{}).m4() } + +type ( + T6 = (((T7))) + T7 = (*(T8)) + T8 = T +) + +func (T6) m6() {} +func _() { (T{}).m6 /* ERROR "cannot call pointer method m6 on T" */ () } +func _() { (&T{}).m6() } + +type ( + T9 = *T10 + T10 = *T11 + T11 = T +) + +func (T9 /* ERRORx `invalid receiver type (\*\*T|T9)` */ ) m9() {} +func _() { (T{}).m9 /* ERROR "has no field or method m9" */ () } +func _() { (&T{}).m9 /* ERROR "has no field or method m9" */ () } diff --git a/go/src/internal/types/testdata/fixedbugs/issue3117.go b/go/src/internal/types/testdata/fixedbugs/issue3117.go new file mode 100644 index 0000000000000000000000000000000000000000..16c0afce81d13b8d6b1a2c1e7b80eed1356f59ba --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue3117.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S struct { + a [1]int +} + +func _(m map[int]S, key int) { + m /* ERROR "cannot assign to m[key].a[0] (neither addressable nor a map index expression)" */ [key].a[0] = 0 +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39634.go b/go/src/internal/types/testdata/fixedbugs/issue39634.go new file mode 100644 index 0000000000000000000000000000000000000000..5392f903c2b8686e9d43ffb786139e72c8631586 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39634.go @@ -0,0 +1,94 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Examples from the issue adjusted to match new [T any] syntax for type parameters. +// Also, previously permitted empty type parameter lists and instantiations +// are now syntax errors. +// +// The primary concern here is that these tests shouldn't crash the type checker. +// The quality of the error messages is secondary as these are all pretty esoteric +// or artificial test cases. + +package p + +// crash 1 +type nt1[_ any]interface{g /* ERROR "undefined" */ } +type ph1[e nt1[e],g(d /* ERROR "undefined" */ )]s /* ERROR "undefined" */ +func(*ph1[e,e /* ERROR "redeclared" */ ])h(d /* ERROR "undefined" */ ) + +// crash 2 +// Disabled: empty []'s are now syntax errors. This example leads to too many follow-on errors. +// type Numeric2 interface{t2 /* ERROR "not a type" */ } +// func t2[T Numeric2](s[]T){0 /* ERROR "not a type */ []{s /* ERROR cannot index" */ [0][0]}} + +// crash 3 +type t3 /* ERROR "invalid recursive type" */ *interface{ t3.p } + +// crash 4 +type Numeric4 interface{t4 /* ERROR "not a type" */ } +func t4[T Numeric4](s[]T){if( /* ERROR "non-boolean" */ 0){*s /* ERROR "cannot indirect" */ [0]}} + +// crash 7 +type foo7 interface { bar() } +type x7[A any] struct{ foo7 } +func main7() { var _ foo7 = x7[int]{} } + +// crash 8 +type foo8[A any] interface { ~A /* ERROR "cannot be a type parameter" */ } +func bar8[A foo8[A]](a A) {} + +// crash 9 +type foo9[A any] interface { foo9 /* ERROR "invalid recursive type" */ [A] } +func _() { var _ = new(foo9[int]) } + +// crash 12 +var u, i [func /* ERROR "used as value" */ /* ERROR "used as value" */ (u /* ERROR "u (package-level variable) is not a type" */ /* ERROR "u (package-level variable) is not a type" */ , c /* ERROR "undefined" */ /* ERROR "undefined" */ ) {}(0, len /* ERROR "must be called" */ /* ERROR "must be called" */ )]c /* ERROR "undefined" */ /* ERROR "undefined" */ + +// crash 15 +func y15() { var a /* ERROR "declared and not used" */ interface{ p() } = G15[string]{} } +type G15[X any] s /* ERROR "undefined" */ +func (G15 /* ERRORx `generic type .* without instantiation` */ ) p() + +// crash 16 +type Foo16[T any] r16 /* ERROR "not a type" */ +func r16[T any]() Foo16[Foo16[T]] { panic(0) } + +// crash 17 +type Y17 interface{ c() } +type Z17 interface { + c() Y17 + Y17 /* ERROR "duplicate method" */ +} +func F17[T Z17](T) {} + +// crash 18 +type o18[T any] []func(_ o18[[]_ /* ERROR "cannot use _" */ ]) + +// crash 19 +type Z19 /* ERROR "invalid recursive type: Z19 refers to itself" */ [][[]Z19{}[0][0]]int + +// crash 20 +type Z20 /* ERROR "invalid recursive type" */ interface{ Z20 } +func F20[t Z20]() { F20(t /* ERROR "invalid composite literal type" */ /* ERROR "too many arguments in call to F20\n\thave (unknown type)\n\twant ()" */ {}) } + +// crash 21 +type Z21 /* ERROR "invalid recursive type" */ interface{ Z21 } +func F21[T Z21]() { ( /* ERROR "not used" */ F21[Z21]) } + +// crash 24 +type T24[P any] P // ERROR "cannot use a type parameter as RHS in type declaration" +func (r T24[P]) m() { T24 /* ERROR "without instantiation" */ .m() } + +// crash 25 +type T25[A any] int +func (t T25[A]) m1() {} +var x T25 /* ERROR "without instantiation" */ .m1 + +// crash 26 +type T26 = interface{ F26[ /* ERROR "interface method must have no type parameters" */ Z any]() } +func F26[Z any]() T26 { return F26[] /* ERROR "operand" */ } + +// crash 27 +func e27[T any]() interface{ x27 /* ERROR "not a type" */ } { panic(0) } +func x27() { e27 /* ERROR "cannot infer T" */ () } diff --git a/go/src/internal/types/testdata/fixedbugs/issue39664.go b/go/src/internal/types/testdata/fixedbugs/issue39664.go new file mode 100644 index 0000000000000000000000000000000000000000..a8148c6e9e3aec342fb4a678ba7541663c0c93c0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39664.go @@ -0,0 +1,15 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[_ any] struct {} + +func (T /* ERROR "instantiation" */ ) m() + +func _() { + var x interface { m() } + x = T[int]{} + _ = x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39680.go b/go/src/internal/types/testdata/fixedbugs/issue39680.go new file mode 100644 index 0000000000000000000000000000000000000000..e56bc3547582d190f110b6f70a231e9e38012572 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39680.go @@ -0,0 +1,31 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Embedding stand-alone type parameters is not permitted for now. Disabled. + +/* +import "fmt" + +// Minimal test case. +func _[T interface{~T}](x T) T{ + return x +} + +// Test case from issue. +type constr[T any] interface { + ~T +} + +func Print[T constr[T]](s []T) { + for _, v := range s { + fmt.Print(v) + } +} + +func f() { + Print([]string{"Hello, ", "playground\n"}) +} +*/ diff --git a/go/src/internal/types/testdata/fixedbugs/issue39693.go b/go/src/internal/types/testdata/fixedbugs/issue39693.go new file mode 100644 index 0000000000000000000000000000000000000000..03f27895d8b643d81f14f9ef7544d3928eddda25 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39693.go @@ -0,0 +1,23 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Number1 interface { + // embedding non-interface types is permitted + int + float64 +} + +func Add1[T Number1](a, b T) T { + return a /* ERROR "not defined" */ + b +} + +type Number2 interface { + int | float64 +} + +func Add2[T Number2](a, b T) T { + return a + b +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39699.go b/go/src/internal/types/testdata/fixedbugs/issue39699.go new file mode 100644 index 0000000000000000000000000000000000000000..73ba0c4cd618d0b554525a947c489f5b905c9dcb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39699.go @@ -0,0 +1,29 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T0 interface{ +} + +type T1 interface{ + ~int +} + +type T2 interface{ + comparable +} + +type T3 interface { + T0 + T1 + T2 +} + +func _() { + _ = T0(0) + _ = T1 /* ERROR "cannot use interface T1 in conversion" */ (1) + _ = T2 /* ERROR "cannot use interface T2 in conversion" */ (2) + _ = T3 /* ERROR "cannot use interface T3 in conversion" */ (3) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39711.go b/go/src/internal/types/testdata/fixedbugs/issue39711.go new file mode 100644 index 0000000000000000000000000000000000000000..d85fa03fc433bc77d34c4e16f4fbb923cfee8d32 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39711.go @@ -0,0 +1,13 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Do not report a duplicate type error for this term list. +// (Check types after interfaces have been completed.) +type _ interface { + // TODO(rfindley) Once we have full type sets we can enable this again. + // Fow now we don't permit interfaces in term lists. + // type interface{ Error() string }, interface{ String() string } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39723.go b/go/src/internal/types/testdata/fixedbugs/issue39723.go new file mode 100644 index 0000000000000000000000000000000000000000..19e5e80393987f95976081d28d2d94a4fd9336df --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39723.go @@ -0,0 +1,9 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// A constraint must be an interface; it cannot +// be a type parameter, for instance. +func _[A interface{ ~int }, B A /* ERROR "cannot use a type parameter as constraint" */ ]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39725.go b/go/src/internal/types/testdata/fixedbugs/issue39725.go new file mode 100644 index 0000000000000000000000000000000000000000..0145667e0de323a45eabde8d3d5c8b903cc83260 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39725.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[T1, T2 any](T1, T2, struct{a T1; b T2}) {} +func _() { + f1(42, string("foo"), struct /* ERROR "does not match inferred type struct{a int; b string}" */ {a, b int}{}) +} + +// simplified test case from issue +func f2[T any](_ []T, _ func(T)) {} +func _() { + f2([]string{}, func /* ERROR "does not match inferred type func(string)" */ (f []byte) {}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39754.go b/go/src/internal/types/testdata/fixedbugs/issue39754.go new file mode 100644 index 0000000000000000000000000000000000000000..a1bd5bafddae764d9a5908a8f6a3cc46c60d0422 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39754.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Optional[T any] struct {} + +func (_ Optional[T]) Val() (T, bool) + +type Box[T any] interface { + Val() (T, bool) +} + +func f[V interface{}, A, B Box[V]]() {} + +func _() { + f[int, Optional[int], Optional[int]]() + _ = f[int, Optional[int], Optional /* ERROR "does not satisfy Box" */ [string]] + _ = f[int, Optional[int], Optional /* ERRORx "Optional.* does not satisfy Box.*" */ [string]] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39755.go b/go/src/internal/types/testdata/fixedbugs/issue39755.go new file mode 100644 index 0000000000000000000000000000000000000000..257b73a2fbeff15a934f4daf4798952578bad9d5 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39755.go @@ -0,0 +1,23 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T interface{~map[string]int}](x T) { + _ = x == nil +} + +// simplified test case from issue + +type PathParamsConstraint interface { + ~map[string]string | ~[]struct{key, value string} +} + +type PathParams[T PathParamsConstraint] struct { + t T +} + +func (pp *PathParams[T]) IsNil() bool { + return pp.t == nil // this must succeed +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39768.go b/go/src/internal/types/testdata/fixedbugs/issue39768.go new file mode 100644 index 0000000000000000000000000000000000000000..51a417759a27807076f21153bb4e007ceaf0e8cc --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39768.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type T[P any] P +// type A = T // ERROR "cannot use generic type" +// var x A[int] +// var _ A +// +// type B = T[int] +// var y B = x +// var _ B /* ERROR "not a generic type" */ [int] + +// test case from issue + +type Vector[T any] []T +type VectorAlias = Vector // ERROR "cannot use generic type" +var v Vector[int] diff --git a/go/src/internal/types/testdata/fixedbugs/issue39938.go b/go/src/internal/types/testdata/fixedbugs/issue39938.go new file mode 100644 index 0000000000000000000000000000000000000000..bd5bdcae07cb4736f9b325619c5493269218b7e8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39938.go @@ -0,0 +1,54 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// All but E2 and E5 provide an "indirection" and break infinite expansion of a type. +type E0[P any] []P +type E1[P any] *P +type E2[P any] struct{ _ P } +type E3[P any] struct{ _ *P } +type E5[P any] struct{ _ [10]P } + +type T0 struct { + _ E0[T0] +} + +type T0_ struct { + E0[T0_] +} + +type T1 struct { + _ E1[T1] +} + +type T2 /* ERROR "invalid recursive type" */ struct { + _ E2[T2] +} + +type T3 struct { + _ E3[T3] +} + +type T4 /* ERROR "invalid recursive type" */ [10]E5[T4] + +type T5 struct { + _ E0[E2[T5]] +} + +type T6 struct { + _ E0[E2[E0[E1[E2[[10]T6]]]]] +} + +type T7 struct { + _ E0[[10]E2[E0[E2[E2[T7]]]]] +} + +type T8 struct { + _ E0[[]E2[E0[E2[E2[T8]]]]] +} + +type T9 /* ERROR "invalid recursive type" */ [10]E2[E5[E2[T9]]] + +type T10 [10]E2[E5[E2[func(T10)]]] diff --git a/go/src/internal/types/testdata/fixedbugs/issue39948.go b/go/src/internal/types/testdata/fixedbugs/issue39948.go new file mode 100644 index 0000000000000000000000000000000000000000..e4430cfc4af96a0a30815c394a541ced373afb01 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39948.go @@ -0,0 +1,9 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] interface{ + P // ERROR "term cannot be a type parameter" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39976.go b/go/src/internal/types/testdata/fixedbugs/issue39976.go new file mode 100644 index 0000000000000000000000000000000000000000..b622cd92874c114e9a42280e2bb5628348db1f2b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39976.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type policy[K, V any] interface{} +type LRU[K, V any] struct{} + +func NewCache[K, V any](p policy[K, V]) {} + +func _() { + var lru LRU[int, string] + NewCache[int, string](&lru) + NewCache /* ERROR "cannot infer K" */ (&lru) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue39982.go b/go/src/internal/types/testdata/fixedbugs/issue39982.go new file mode 100644 index 0000000000000000000000000000000000000000..9810b6386a9a9e847617ac0915f28dd42e8374d7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue39982.go @@ -0,0 +1,36 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + T[_ any] struct{} + S[_ any] struct { + data T[*T[int]] + } +) + +func _() { + _ = S[int]{ + data: T[*T[int]]{}, + } +} + +// full test case from issue + +type ( + Element[TElem any] struct{} + + entry[K comparable] struct{} + + Cache[K comparable] struct { + data map[K]*Element[*entry[K]] + } +) + +func _() { + _ = Cache[int]{ + data: make(map[int](*Element[*entry[int]])), + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue40038.go b/go/src/internal/types/testdata/fixedbugs/issue40038.go new file mode 100644 index 0000000000000000000000000000000000000000..5f81fcbfaa7236bfcdd58114ac74847f9e709555 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40038.go @@ -0,0 +1,15 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[T any] int + +func (A[T]) m(A[T]) + +func f[P interface{m(P)}]() {} + +func _() { + _ = f[A[int]] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue40056.go b/go/src/internal/types/testdata/fixedbugs/issue40056.go new file mode 100644 index 0000000000000000000000000000000000000000..ce882e7f2255e220a41ddf8c750cddea1d31c7dd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40056.go @@ -0,0 +1,15 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + NewS /* ERROR "cannot infer T" */ ().M() +} + +type S struct {} + +func NewS[T any]() *S { panic(0) } + +func (_ *S /* ERROR "S is not a generic type" */ [T]) M() diff --git a/go/src/internal/types/testdata/fixedbugs/issue40057.go b/go/src/internal/types/testdata/fixedbugs/issue40057.go new file mode 100644 index 0000000000000000000000000000000000000000..2996d398e7d732eae38eae55c6937773bc2ffc4b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40057.go @@ -0,0 +1,17 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + var x interface{} + switch t := x.(type) { + case S /* ERROR "cannot use generic type" */ : + t.m() + } +} + +type S[T any] struct {} + +func (_ S[T]) m() diff --git a/go/src/internal/types/testdata/fixedbugs/issue40301.go b/go/src/internal/types/testdata/fixedbugs/issue40301.go new file mode 100644 index 0000000000000000000000000000000000000000..c78f9a1fa040892e7ebec27753100db2867752b2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40301.go @@ -0,0 +1,12 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +func _[T any](x T) { + _ = unsafe.Alignof(x) + _ = unsafe.Sizeof(x) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue40350.go b/go/src/internal/types/testdata/fixedbugs/issue40350.go new file mode 100644 index 0000000000000000000000000000000000000000..b7ceb33918e35e59e6eb0f40739c11595122bea2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40350.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type number interface { + ~float64 | ~int | ~int32 + float64 | ~int32 +} + +func f[T number]() {} + +func _() { + _ = f[int /* ERROR "int does not satisfy number (number mentions int, but int is not in the type set of number)" */] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue40684.go b/go/src/internal/types/testdata/fixedbugs/issue40684.go new file mode 100644 index 0000000000000000000000000000000000000000..48051841600df1a688cfce3543dea4600898c679 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40684.go @@ -0,0 +1,15 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[_ any] int + +func f[_ any]() {} +func g[_, _ any]() {} + +func _() { + _ = f[T /* ERROR "without instantiation" */ ] + _ = g[T /* ERROR "without instantiation" */ , T /* ERROR "without instantiation" */ ] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue40789.go b/go/src/internal/types/testdata/fixedbugs/issue40789.go new file mode 100644 index 0000000000000000000000000000000000000000..9eea4ad60a6647380606f70fd998febab618db8c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue40789.go @@ -0,0 +1,37 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "fmt" + +func main() { + m := map[string]int{ + "a": 6, + "b": 7, + } + fmt.Println(copyMap[map[string]int, string, int](m)) +} + +type Map[K comparable, V any] interface { + map[K] V +} + +func copyMap[M Map[K, V], K comparable, V any](m M) M { + m1 := make(M) + for k, v := range m { + m1[k] = v + } + return m1 +} + +// simpler test case from the same issue + +type A[X comparable] interface { + []X +} + +func f[B A[X], X comparable]() B { + return nil +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue41124.go b/go/src/internal/types/testdata/fixedbugs/issue41124.go new file mode 100644 index 0000000000000000000000000000000000000000..0f828dc502a5f95254b398a2f24cdf8a59ee91f3 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue41124.go @@ -0,0 +1,91 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Test case from issue. + +type Nat /* ERROR "invalid recursive type" */ interface { + Zero|Succ +} + +type Zero struct{} +type Succ struct{ + Nat // Nat contains type constraints but is invalid, so no error +} + +// Struct tests. + +type I1 interface { + comparable +} + +type I2 interface { + ~int +} + +type I3 interface { + I1 + I2 +} + +type _ struct { + f I1 // ERRORx `interface is .* comparable` +} + +type _ struct { + comparable // ERRORx `interface is .* comparable` +} + +type _ struct{ + I1 // ERRORx `interface is .* comparable` +} + +type _ struct{ + I2 // ERROR "interface contains type constraints" +} + +type _ struct{ + I3 // ERROR "interface contains type constraints" +} + +// General composite types. + +type ( + _ [10]I1 // ERRORx `interface is .* comparable` + _ [10]I2 // ERROR "interface contains type constraints" + + _ []I1 // ERRORx `interface is .* comparable` + _ []I2 // ERROR "interface contains type constraints" + + _ *I3 // ERROR "interface contains type constraints" + _ map[I1 /* ERRORx `interface is .* comparable` */ ]I2 // ERROR "interface contains type constraints" + _ chan I3 // ERROR "interface contains type constraints" + _ func(I1 /* ERRORx `interface is .* comparable` */ ) + _ func() I2 // ERROR "interface contains type constraints" +) + +// Other cases. + +var _ = [...]I3 /* ERROR "interface contains type constraints" */ {} + +func _(x interface{}) { + _ = x.(I3 /* ERROR "interface contains type constraints" */ ) +} + +type T1[_ any] struct{} +type T3[_, _, _ any] struct{} +var _ T1[I2 /* ERROR "interface contains type constraints" */ ] +var _ T3[int, I2 /* ERROR "interface contains type constraints" */ , float32] + +func f1[_ any]() int { panic(0) } +var _ = f1[I2 /* ERROR "interface contains type constraints" */ ]() +func f3[_, _, _ any]() int { panic(0) } +var _ = f3[int, I2 /* ERROR "interface contains type constraints" */ , float32]() + +func _(x interface{}) { + switch x.(type) { + case I2 /* ERROR "interface contains type constraints" */ : + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue41176.go b/go/src/internal/types/testdata/fixedbugs/issue41176.go new file mode 100644 index 0000000000000000000000000000000000000000..755e83a6327464460bf4657ced9368162885780c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue41176.go @@ -0,0 +1,21 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S struct{} + +func (S) M() byte { + return 0 +} + +type I[T any] interface { + M() T +} + +func f[T any](x I[T]) {} + +func _() { + f(S{}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue42695.go b/go/src/internal/types/testdata/fixedbugs/issue42695.go new file mode 100644 index 0000000000000000000000000000000000000000..4551e9f03bb3a66c68229b5e07d0eff440450847 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue42695.go @@ -0,0 +1,17 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue42695 + +const _ = 6e5518446744 // ERROR "malformed constant" +const _ uint8 = 6e5518446744 // ERROR "malformed constant" + +var _ = 6e5518446744 // ERROR "malformed constant" +var _ uint8 = 6e5518446744 // ERROR "malformed constant" + +func f(x int) int { + return x + 6e5518446744 // ERROR "malformed constant" +} + +var _ = f(6e5518446744 /* ERROR "malformed constant" */ ) diff --git a/go/src/internal/types/testdata/fixedbugs/issue42758.go b/go/src/internal/types/testdata/fixedbugs/issue42758.go new file mode 100644 index 0000000000000000000000000000000000000000..4e1df340da1d9b2f1851d186e59ddbbb7a8374ce --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue42758.go @@ -0,0 +1,33 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T any](x interface{}){ + switch x.(type) { + case T: // ok to use a type parameter + case int: + } + + switch x.(type) { + case T: + case T /* ERROR "duplicate case" */ : + } +} + +type constraint interface { + ~int +} + +func _[T constraint](x interface{}){ + switch x.(type) { + case T: // ok to use a type parameter even if type set contains int + case int: + } +} + +func _(x constraint /* ERROR "contains type constraints" */ ) { + switch x.(type) { // no need to report another error + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue42881.go b/go/src/internal/types/testdata/fixedbugs/issue42881.go new file mode 100644 index 0000000000000000000000000000000000000000..b766b5e5bd3b6c06f685f66f3c43b89b5ab9d816 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue42881.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + T1 interface{ comparable } + T2 interface{ int } +) + +var ( + _ comparable // ERROR "cannot use type comparable outside a type constraint: interface is (or embeds) comparable" + _ T1 // ERROR "cannot use type T1 outside a type constraint: interface is (or embeds) comparable" + _ T2 // ERROR "cannot use type T2 outside a type constraint: interface contains type constraints" +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue42987.go b/go/src/internal/types/testdata/fixedbugs/issue42987.go new file mode 100644 index 0000000000000000000000000000000000000000..21c14c1fbdd802cf77cb71726994b782b79aa3de --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue42987.go @@ -0,0 +1,8 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Check that there is only one error (no follow-on errors). + +package p +var _ = [ ... /* ERROR "invalid use of [...] array" */ ]byte("foo") \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue43056.go b/go/src/internal/types/testdata/fixedbugs/issue43056.go new file mode 100644 index 0000000000000000000000000000000000000000..8ff4e7f9b4d8f763d25edbb024ab6dbeeb1e0336 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43056.go @@ -0,0 +1,31 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// simplified example +func f[T ~func(T)](a, b T) {} + +type F func(F) + +func _() { + var i F + var j func(F) + + f(i, j) + f(j, i) +} + +// example from issue +func g[T interface{ Equal(T) bool }](a, b T) {} + +type I interface{ Equal(I) bool } + +func _() { + var i I + var j interface{ Equal(I) bool } + + g(i, j) + g(j, i) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue43087.go b/go/src/internal/types/testdata/fixedbugs/issue43087.go new file mode 100644 index 0000000000000000000000000000000000000000..222fac823cdd5253664e0629fb813b4b258206b1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43087.go @@ -0,0 +1,43 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + a, b, b /* ERROR "b repeated on left side of :=" */ := 1, 2, 3 + _ = a + _ = b +} + +func _() { + a, _, _ := 1, 2, 3 // multiple _'s ok + _ = a +} + +func _() { + var b int + a, b, b /* ERROR "b repeated on left side of :=" */ := 1, 2, 3 + _ = a + _ = b +} + +func _() { + var a []int + a /* ERRORx `non-name .* on left side of :=` */ [0], b := 1, 2 + _ = a + _ = b +} + +func _() { + var a int + a, a /* ERROR "a repeated on left side of :=" */ := 1, 2 + _ = a +} + +func _() { + var a, b int + a, b := /* ERROR "no new variables on left side of :=" */ 1, 2 + _ = a + _ = b +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue43109.go b/go/src/internal/types/testdata/fixedbugs/issue43109.go new file mode 100644 index 0000000000000000000000000000000000000000..5d21a568dbbe8f6a8db7a31e3ba6576d05bb7d6f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43109.go @@ -0,0 +1,10 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Ensure there is no "imported and not used" error +// if a package wasn't imported in the first place. + +package p + +import . "/foo" // ERROR "could not import /foo" diff --git a/go/src/internal/types/testdata/fixedbugs/issue43110.go b/go/src/internal/types/testdata/fixedbugs/issue43110.go new file mode 100644 index 0000000000000000000000000000000000000000..1e850226119a4ac3b5bafaae334f3f056a5d5d2f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43110.go @@ -0,0 +1,43 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type P *struct{} + +func _() { + // want an error even if the switch is empty + var a struct{ _ func() } + switch a /* ERROR "cannot switch on a" */ { + } + + switch a /* ERROR "cannot switch on a" */ { + case a: // no follow-on error here + } + + // this is ok because f can be compared to nil + var f func() + switch f { + } + + switch f { + case nil: + } + + switch (func())(nil) { + case nil: + } + + switch (func())(nil) { + case f /* ERRORx `invalid case f in switch on .* \(func can only be compared to nil\)` */ : + } + + switch nil /* ERROR "use of untyped nil in switch expression" */ { + } + + // this is ok + switch P(nil) { + case P(nil): + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue43124.go b/go/src/internal/types/testdata/fixedbugs/issue43124.go new file mode 100644 index 0000000000000000000000000000000000000000..ce26ae1703cc15e08df384ccda1f747106a14bf1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43124.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var _ = int(0 /* ERROR "invalid use of ... in conversion to int" */ ...) + +// test case from issue + +type M []string + +var ( + x = []string{"a", "b"} + _ = M(x /* ERROR "invalid use of ... in conversion to M" */ ...) +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue43190.go b/go/src/internal/types/testdata/fixedbugs/issue43190.go new file mode 100644 index 0000000000000000000000000000000000000000..b4d1fa463074310353dcfd908362933667da32ac --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43190.go @@ -0,0 +1,31 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The errors below are produced by the parser, but we check +// them here for consistency with the types2 tests. + +package p + +import ; // ERROR "missing import path" +import "" // ERROR "invalid import path (empty string)" +import +var /* ERROR "missing import path" */ _ int +import .; // ERROR "missing import path" +import 'x' // ERROR "import path must be a string" +var _ int +import /* ERROR "imports must appear before other declarations" */ _ "math" + +// Don't repeat previous error for each immediately following import ... +import () +import (.) // ERROR "missing import path" +import ( + "fmt" + . +) // ERROR "missing import path" + +// ... but remind with error again if we start a new import section after +// other declarations +var _ = fmt.Println +import /* ERROR "imports must appear before other declarations" */ _ "math" +import _ "math" diff --git a/go/src/internal/types/testdata/fixedbugs/issue43527.go b/go/src/internal/types/testdata/fixedbugs/issue43527.go new file mode 100644 index 0000000000000000000000000000000000000000..473ab96f56d0bb6304d7ba522624edeb2e84ed1e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43527.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +const L = 10 + +type ( + _ [L]struct{} + _ [A /* ERROR "undefined array length A or missing type constraint" */ ]struct{} + _ [B /* ERROR "invalid array length B" */ ]struct{} + _[A any] struct{} + + B int +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue43671.go b/go/src/internal/types/testdata/fixedbugs/issue43671.go new file mode 100644 index 0000000000000000000000000000000000000000..5b44682a7accd70390969c80ba60c9540eab245e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue43671.go @@ -0,0 +1,58 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type C0 interface{ int } +type C1 interface{ chan int } +type C2 interface{ chan int | <-chan int } +type C3 interface{ chan int | chan float32 } +type C4 interface{ chan int | chan<- int } +type C5[T any] interface{ ~chan T | <-chan T } + +func _[T any](ch T) { + <-ch // ERRORx `cannot receive from ch .*: no specific channel type` +} + +func _[T C0](ch T) { + <-ch // ERRORx `cannot receive from ch .*: non-channel int` +} + +func _[T C1](ch T) { + <-ch +} + +func _[T C2](ch T) { + <-ch +} + +func _[T C3](ch T) { + <-ch // ERRORx `cannot receive from ch .*: channels chan int and chan float32 have different element types` +} + +func _[T C4](ch T) { + <-ch // ERRORx `cannot receive from ch .*: send-only channel chan<- int` +} + +func _[T C5[X], X any](ch T, x X) { + x = <-ch +} + +// test case from issue, slightly modified +type RecvChan[T any] interface { + ~chan T | ~<-chan T +} + +func _[T any, C RecvChan[T]](ch C) T { + return <-ch +} + +func f[T any, C interface{ chan T }](ch C) T { + return <-ch +} + +func _(ch chan int) { + var x int = f(ch) // test constraint type inference for this case + _ = x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue44688.go b/go/src/internal/types/testdata/fixedbugs/issue44688.go new file mode 100644 index 0000000000000000000000000000000000000000..512bfcc9223c824c84f960b9de2fb78286bab1d8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue44688.go @@ -0,0 +1,83 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package P + +type A1[T any] struct{} + +func (*A1[T]) m1(T) {} + +type A2[T any] interface { + m2(T) +} + +type B1[T any] struct { + filler int + *A1[T] + A2[T] +} + +type B2[T any] interface { + A2[T] +} + +type C[T any] struct { + filler1 int + filler2 int + B1[T] +} + +type D[T any] struct { + filler1 int + filler2 int + filler3 int + C[T] +} + +func _() { + // calling embedded methods + var b1 B1[string] + + b1.A1.m1("") + b1.m1("") + + b1.A2.m2("") + b1.m2("") + + var b2 B2[string] + b2.m2("") + + // a deeper nesting + var d D[string] + d.m1("") + d.m2("") + + // calling method expressions + m1x := B1[string].m1 + m1x(b1, "") + m2x := B2[string].m2 + m2x(b2, "") + + // calling method values + m1v := b1.m1 + m1v("") + m2v := b1.m2 + m2v("") + b2v := b2.m2 + b2v("") +} + +// actual test case from issue + +type A[T any] struct{} + +func (*A[T]) f(T) {} + +type B[T any] struct{ A[T] } + +func _() { + var b B[string] + b.A.f("") + b.f("") +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue44799.go b/go/src/internal/types/testdata/fixedbugs/issue44799.go new file mode 100644 index 0000000000000000000000000000000000000000..9e528a7475b30e02792def3c31274c37e852e618 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue44799.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func Map[F, T any](s []F, f func(F) T) []T { return nil } + +func Reduce[Elem1, Elem2 any](s []Elem1, initializer Elem2, f func(Elem2, Elem1) Elem2) Elem2 { var x Elem2; return x } + +func main() { + var s []int + var f1 func(int) float64 + var f2 func(float64, int) float64 + _ = Map[int](s, f1) + _ = Map(s, f1) + _ = Reduce[int](s, 0, f2) + _ = Reduce(s, 0, f2) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue45114.go b/go/src/internal/types/testdata/fixedbugs/issue45114.go new file mode 100644 index 0000000000000000000000000000000000000000..e51b3f711ba19b68ac960d9ebd3ae7d17f5ba594 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45114.go @@ -0,0 +1,8 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var s uint +var _ = string(1 /* ERRORx `shifted operand 1 .* must be integer` */ << s) diff --git a/go/src/internal/types/testdata/fixedbugs/issue45548.go b/go/src/internal/types/testdata/fixedbugs/issue45548.go new file mode 100644 index 0000000000000000000000000000000000000000..01c9672745a600b10d78c9e110437a06460a7d16 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45548.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[F interface{*Q}, G interface{*R}, Q, R any](q Q, r R) {} + +func _() { + f[*float64, *int](1, 2) + f[*float64](1, 2) + f(1, 2) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue45550.go b/go/src/internal/types/testdata/fixedbugs/issue45550.go new file mode 100644 index 0000000000000000000000000000000000000000..32fdde6740c7a55cf3893115fb8abe9386183ff9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45550.go @@ -0,0 +1,10 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Builder[T ~struct{ Builder[T] }] struct{} +type myBuilder struct { + Builder[myBuilder] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue45635.go b/go/src/internal/types/testdata/fixedbugs/issue45635.go new file mode 100644 index 0000000000000000000000000000000000000000..b83d4774fe935126b8ae53fc9afcf3e54fe7fb03 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45635.go @@ -0,0 +1,31 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +func main() { + some /* ERROR "undefined" */ [int, int]() +} + +type N[T any] struct{} + +var _ N [] // ERROR "expected type argument list" + +type I interface { + ~[]int +} + +func _[T I](i, j int) { + var m map[int]int + _ = m[i, j /* ERROR "more than one index" */ ] + + var a [3]int + _ = a[i, j /* ERROR "more than one index" */ ] + + var s []int + _ = s[i, j /* ERROR "more than one index" */ ] + + var t T + _ = t[i, j /* ERROR "more than one index" */ ] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue45639.go b/go/src/internal/types/testdata/fixedbugs/issue45639.go new file mode 100644 index 0000000000000000000000000000000000000000..a224aedcb68e10d056c35ad04c450fcf70a9ac86 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45639.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package P + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// // It is not permitted to declare a local type whose underlying +// // type is a type parameters not declared by that type declaration. +// func _[T any]() { +// type _ T // ERROR "cannot use function type parameter T as RHS in type declaration" +// type _ [_ any] T // ERROR "cannot use function type parameter T as RHS in type declaration" +// } diff --git a/go/src/internal/types/testdata/fixedbugs/issue45920.go b/go/src/internal/types/testdata/fixedbugs/issue45920.go new file mode 100644 index 0000000000000000000000000000000000000000..716abb17680d5e787f01da34ee41d3ff1cf693e7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45920.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[T any, C chan T | <-chan T](ch C) {} + +func _(ch chan int) { f1(ch) } +func _(ch <-chan int) { f1(ch) } +func _(ch chan<- int) { f1 /* ERROR "chan<- int does not satisfy chan int | <-chan int" */ (ch) } + +func f2[T any, C chan T | chan<- T](ch C) {} + +func _(ch chan int) { f2(ch) } +func _(ch <-chan int) { f2 /* ERROR "<-chan int does not satisfy chan int | chan<- int" */ (ch) } +func _(ch chan<- int) { f2(ch) } diff --git a/go/src/internal/types/testdata/fixedbugs/issue45985.go b/go/src/internal/types/testdata/fixedbugs/issue45985.go new file mode 100644 index 0000000000000000000000000000000000000000..c486150cb39f24c8a3e8083f28d17d8c46baae52 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue45985.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue45985 + +func app[S interface{ ~[]T }, T any](s S, e T) S { + return append(s, e) +} + +func _() { + _ = app /* ERROR "S (type int) does not satisfy interface{~[]T}" */ [int] // TODO(gri) better error message +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue46090.go b/go/src/internal/types/testdata/fixedbugs/issue46090.go new file mode 100644 index 0000000000000000000000000000000000000000..59670da7fa416cb2b60c295e84a0c2e1778a436d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46090.go @@ -0,0 +1,11 @@ +// -lang=go1.17 + +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The predeclared type comparable is not visible before Go 1.18. + +package p + +type _ comparable // ERROR "predeclared comparable" diff --git a/go/src/internal/types/testdata/fixedbugs/issue46275.go b/go/src/internal/types/testdata/fixedbugs/issue46275.go new file mode 100644 index 0000000000000000000000000000000000000000..0862d5bb5a0ef6dac4311b39757ef8b952d8d5fe --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46275.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue46275 + +type N[T any] struct { + *N[T] + t T +} + +func (n *N[T]) Elem() T { + return n.t +} + +type I interface { + Elem() string +} + +func _() { + var n1 *N[string] + var _ I = n1 + type NS N[string] + var n2 *NS + var _ I = n2 +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue46403.go b/go/src/internal/types/testdata/fixedbugs/issue46403.go new file mode 100644 index 0000000000000000000000000000000000000000..fc60340a2102cf132f9f2e1d569217ca3e840fa9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46403.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue46403 + +func _() { + // a should be used, despite the parser error below. + var a []int + var _ = a[] // ERROR "expected operand" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue46404.go b/go/src/internal/types/testdata/fixedbugs/issue46404.go new file mode 100644 index 0000000000000000000000000000000000000000..e3c93f66a85938999e65dbdd0d80be83533aa75b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46404.go @@ -0,0 +1,10 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue46404 + +// TODO(gri) re-enable this test with matching errors +// between go/types and types2 +// Check that we don't type check t[_] as an instantiation. +// type t [t /* type parameters must be named */ /* not a generic type */ [_]]_ // cannot use diff --git a/go/src/internal/types/testdata/fixedbugs/issue46461.go b/go/src/internal/types/testdata/fixedbugs/issue46461.go new file mode 100644 index 0000000000000000000000000000000000000000..454f7e836537c6c533509e6b8bdbc84daa5b93b9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46461.go @@ -0,0 +1,22 @@ +// -gotypesalias=0 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// test case 1 +type T[U interface{ M() T[U] }] int + +type X int + +func (X) M() T[X] { return 0 } + +// test case 2 +type A[T interface{ A[T] }] interface{} + +// test case 3 +type A2[U interface{ A2[U] }] interface{ M() A2[U] } + +type I interface{ A2[I]; M() A2[I] } diff --git a/go/src/internal/types/testdata/fixedbugs/issue46461a.go b/go/src/internal/types/testdata/fixedbugs/issue46461a.go new file mode 100644 index 0000000000000000000000000000000000000000..74ed6c4882719cc65be11157c540f68ff3550f8d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46461a.go @@ -0,0 +1,22 @@ +// -gotypesalias=1 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// test case 1 +type T[U interface{ M() T[U] }] int + +type X int + +func (X) M() T[X] { return 0 } + +// test case 2 +type A[T interface{ A[T] }] interface{} + +// test case 3 +type A2[U interface{ A2[U] }] interface{ M() A2[U] } + +type I interface{ A2[I]; M() A2[I] } diff --git a/go/src/internal/types/testdata/fixedbugs/issue46583.go b/go/src/internal/types/testdata/fixedbugs/issue46583.go new file mode 100644 index 0000000000000000000000000000000000000000..1901bff31e8f323885fb6ff784c9d6eeae149073 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue46583.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T1 struct{} +func (t T1) m(int) {} +var f1 func(T1) + +type T2 struct{} +func (t T2) m(x int) {} +var f2 func(T2) + +type T3 struct{} +func (T3) m(int) {} +var f3 func(T3) + +type T4 struct{} +func (T4) m(x int) {} +var f4 func(T4) + +func _() { + f1 = T1 /* ERROR "func(T1, int)" */ .m + f2 = T2 /* ERROR "func(t T2, x int)" */ .m + f3 = T3 /* ERROR "func(T3, int)" */ .m + f4 = T4 /* ERROR "func(_ T4, x int)" */ .m +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47031.go b/go/src/internal/types/testdata/fixedbugs/issue47031.go new file mode 100644 index 0000000000000000000000000000000000000000..23a9c55a1106883e18643c128c87d16adacbab67 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47031.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Mer interface { M() } + +func F[T Mer](p *T) { + p.M /* ERROR "p.M undefined" */ () +} + +type MyMer int + +func (MyMer) M() {} + +func _() { + F(new(MyMer)) + F[Mer](nil) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47115.go b/go/src/internal/types/testdata/fixedbugs/issue47115.go new file mode 100644 index 0000000000000000000000000000000000000000..58b668ce4f1cdb4e616278196ded8d12fa8fbfb7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47115.go @@ -0,0 +1,40 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type C0 interface{ int } +type C1 interface{ chan int } +type C2 interface{ chan int | <-chan int } +type C3 interface{ chan int | chan float32 } +type C4 interface{ chan int | chan<- int } +type C5[T any] interface{ ~chan T | chan<- T } + +func _[T any](ch T) { + ch <- /* ERRORx `cannot send to ch .*: no specific channel type` */ 0 +} + +func _[T C0](ch T) { + ch <- /* ERRORx `cannot send to ch .*: non-channel int` */ 0 +} + +func _[T C1](ch T) { + ch <- 0 +} + +func _[T C2](ch T) { + ch <- /* ERRORx `cannot send to ch .*: receive-only channel <-chan int` */ 0 +} + +func _[T C3](ch T) { + ch <- /* ERRORx `cannot send to ch .*: channels chan int and chan float32 have different element types` */ 0 +} + +func _[T C4](ch T) { + ch <- 0 +} + +func _[T C5[X], X any](ch T, x X) { + ch <- x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47127.go b/go/src/internal/types/testdata/fixedbugs/issue47127.go new file mode 100644 index 0000000000000000000000000000000000000000..b6639387ea460e46d480bbe2f6b64e376d3c62fd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47127.go @@ -0,0 +1,37 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Embedding of stand-alone type parameters is not permitted. + +package p + +type ( + _[P any] interface{ *P | []P | chan P | map[string]P } + _[P any] interface{ P /* ERROR "term cannot be a type parameter" */ } + _[P any] interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ } + _[P any] interface{ int | P /* ERROR "term cannot be a type parameter" */ } + _[P any] interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ } +) + +func _[P any]() { + type ( + _[P any] interface{ *P | []P | chan P | map[string]P } + _[P any] interface{ P /* ERROR "term cannot be a type parameter" */ } + _[P any] interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ } + _[P any] interface{ int | P /* ERROR "term cannot be a type parameter" */ } + _[P any] interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ } + + _ interface{ *P | []P | chan P | map[string]P } + _ interface{ P /* ERROR "term cannot be a type parameter" */ } + _ interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ } + _ interface{ int | P /* ERROR "term cannot be a type parameter" */ } + _ interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ } + ) +} + +func _[P any, Q interface{ *P | []P | chan P | map[string]P }]() {} +func _[P any, Q interface{ P /* ERROR "term cannot be a type parameter" */ }]() {} +func _[P any, Q interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ }]() {} +func _[P any, Q interface{ int | P /* ERROR "term cannot be a type parameter" */ }]() {} +func _[P any, Q interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ }]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47411.go b/go/src/internal/types/testdata/fixedbugs/issue47411.go new file mode 100644 index 0000000000000000000000000000000000000000..97b5942ff05ed1ef3e9a6ec976ed0d2f88a3faa5 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47411.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[_ comparable]() {} +func g[_ interface{interface{comparable; ~int|~string}}]() {} + +func _[P comparable, + Q interface{ comparable; ~int|~string }, + R any, // not comparable + S interface{ comparable; ~func() }, // not comparable +]() { + _ = f[int] + _ = f[P] + _ = f[Q] + _ = f[func /* ERROR "does not satisfy comparable" */ ()] + _ = f[R /* ERROR "R does not satisfy comparable" */ ] + + _ = g[int] + _ = g[P /* ERROR "P does not satisfy interface{interface{comparable; ~int | ~string}" */ ] + _ = g[Q] + _ = g[func /* ERROR "func() does not satisfy interface{interface{comparable; ~int | ~string}}" */ ()] + _ = g[R /* ERROR "R does not satisfy interface{interface{comparable; ~int | ~string}" */ ] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47747.go b/go/src/internal/types/testdata/fixedbugs/issue47747.go new file mode 100644 index 0000000000000000000000000000000000000000..34c78d3b49c02f6629982c047d289eb55c5510f1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47747.go @@ -0,0 +1,71 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type T1[P any] P +// +// func (T1[_]) m() {} +// +// func _[P any](x *T1[P]) { +// // x.m exists because x is of type *T1 where T1 is a defined type +// // (even though under(T1) is a type parameter) +// x.m() +// } + + +func _[P interface{ m() }](x P) { + x.m() + // (&x).m doesn't exist because &x is of type *P + // and pointers to type parameters don't have methods + (&x).m /* ERROR "type *P is pointer to type parameter, not type parameter" */ () +} + + +type T2 interface{ m() } + +func _(x *T2) { + // x.m doesn't exists because x is of type *T2 + // and pointers to interfaces don't have methods + x.m /* ERROR "type *T2 is pointer to interface, not interface" */() +} + +// Test case 1 from issue + +type Fooer1[t any] interface { + Foo(Barer[t]) +} +type Barer[t any] interface { + Bar(t) +} + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type Foo1[t any] t +// type Bar[t any] t +// +// func (l Foo1[t]) Foo(v Barer[t]) { v.Bar(t(l)) } +// func (b *Bar[t]) Bar(l t) { *b = Bar[t](l) } +// +// func _[t any](f Fooer1[t]) t { +// var b Bar[t] +// f.Foo(&b) +// return t(b) +// } + +// Test case 2 from issue + +// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639). +// type Fooer2[t any] interface { +// Foo() +// } +// +// type Foo2[t any] t +// +// func (f *Foo2[t]) Foo() {} +// +// func _[t any](v t) { +// var f = Foo2[t](v) +// _ = Fooer2[t](&f) +// } diff --git a/go/src/internal/types/testdata/fixedbugs/issue47796.go b/go/src/internal/types/testdata/fixedbugs/issue47796.go new file mode 100644 index 0000000000000000000000000000000000000000..b07cdddababf67b55ca7587f628e2f32283a12bd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47796.go @@ -0,0 +1,33 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// parameterized types with self-recursive constraints +type ( + T1[P T1[P]] interface{} + T2[P, Q T2[P, Q]] interface{} + T3[P T2[P, Q], Q interface{ ~string }] interface{} + + T4a[P T4a[P]] interface{ ~int } + T4b[P T4b[int]] interface{ ~int } + T4c[P T4c[string /* ERROR "string does not satisfy T4c[string]" */]] interface{ ~int } + + // mutually recursive constraints + T5[P T6[P]] interface{ int } + T6[P T5[P]] interface{ int } +) + +// verify that constraints are checked as expected +var ( + _ T1[int] + _ T2[int, string] + _ T3[int, string] +) + +// test case from issue + +type Eq[a Eq[a]] interface { + Equal(that a) bool +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue47818.go b/go/src/internal/types/testdata/fixedbugs/issue47818.go new file mode 100644 index 0000000000000000000000000000000000000000..4750a4fd0404a897f0afe171a43a64e85b39ba77 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47818.go @@ -0,0 +1,61 @@ +// -lang=go1.17 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Parser accepts type parameters but the type checker +// needs to report any operations that are not permitted +// before Go 1.18. + +package p + +type T[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */] struct{} + +// for init (and main, but we're not in package main) we should only get one error +func init[P /* ERROR "func init must have no type parameters" */ any /* ERROR "predeclared any requires go1.18 or later" */]() { +} +func main[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */]() { +} + +func f[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */](x P) { + var _ T[ /* ERROR "type instantiation requires go1.18 or later" */ int] + var _ (T[ /* ERROR "type instantiation requires go1.18 or later" */ int]) + _ = T[ /* ERROR "type instantiation requires go1.18 or later" */ int]{} + _ = T[ /* ERROR "type instantiation requires go1.18 or later" */ int](struct{}{}) +} + +func (T /* ERROR "type instantiation requires go1.18 or later" */ [P]) g(x int) { + f[ /* ERROR "function instantiation requires go1.18 or later" */ int](0) // explicit instantiation + (f[ /* ERROR "function instantiation requires go1.18 or later" */ int])(0) // parentheses (different code path) + f( /* ERROR "implicit function instantiation requires go1.18 or later" */ x) // implicit instantiation +} + +type C1 interface { + comparable // ERROR "predeclared comparable requires go1.18 or later" +} + +type C2 interface { + comparable // ERROR "predeclared comparable requires go1.18 or later" + int // ERROR "embedding non-interface type int requires go1.18 or later" + ~ /* ERROR "embedding interface element ~int requires go1.18 or later" */ int + int /* ERROR "embedding interface element int | ~string requires go1.18 or later" */ | ~string +} + +type _ interface { + // errors for these were reported with their declaration + C1 + C2 +} + +type ( + _ comparable // ERROR "predeclared comparable requires go1.18 or later" + // errors for these were reported with their declaration + _ C1 + _ C2 + + _ = comparable // ERROR "predeclared comparable requires go1.18 or later" + // errors for these were reported with their declaration + _ = C1 + _ = C2 +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue47887.go b/go/src/internal/types/testdata/fixedbugs/issue47887.go new file mode 100644 index 0000000000000000000000000000000000000000..4c4fc2fda8f8a3140ae9f9b540eb5b7a0781f2e2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47887.go @@ -0,0 +1,28 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Fooer[t any] interface { + foo(Barer[t]) +} +type Barer[t any] interface { + bar(Bazer[t]) +} +type Bazer[t any] interface { + Fooer[t] + baz(t) +} + +type Int int + +func (n Int) baz(int) {} +func (n Int) foo(b Barer[int]) { b.bar(n) } + +type F[t any] interface { f(G[t]) } +type G[t any] interface { g(H[t]) } +type H[t any] interface { F[t] } + +type T struct{} +func (n T) f(b G[T]) { b.g(n) } diff --git a/go/src/internal/types/testdata/fixedbugs/issue47968.go b/go/src/internal/types/testdata/fixedbugs/issue47968.go new file mode 100644 index 0000000000000000000000000000000000000000..e260c63a76da0d1340be7153c12bd57a4f763ab0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue47968.go @@ -0,0 +1,23 @@ +// -gotypesalias=1 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] struct{} + +func (T[P]) m1() + +type A1 = T // ERROR "cannot use generic type" + +func (A1[P]) m2() {} // don't report a follow-on error on A1 + +type A2 = T[int] + +func (A2 /* ERROR "cannot define new methods on instantiated type T[int]" */) m3() {} +func (_ A2 /* ERROR "cannot define new methods on instantiated type T[int]" */) m4() {} + +func (T[int]) m5() {} // int is the type parameter name, not an instantiation +func (T[* /* ERROR "must be an identifier" */ int]) m6() {} // syntax error diff --git a/go/src/internal/types/testdata/fixedbugs/issue48008.go b/go/src/internal/types/testdata/fixedbugs/issue48008.go new file mode 100644 index 0000000000000000000000000000000000000000..8d0c640c3cecd1f88022489e9f3cb70646031641 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48008.go @@ -0,0 +1,60 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] struct{} + +func _(x interface{}) { + switch x.(type) { + case nil: + case int: + + case T[int]: + case []T[int]: + case [10]T[int]: + case struct{T[int]}: + case *T[int]: + case func(T[int]): + case interface{m(T[int])}: + case map[T[int]] string: + case chan T[int]: + + case T /* ERROR "cannot use generic type T[P any] without instantiation" */ : + case []T /* ERROR "cannot use generic type" */ : + case [10]T /* ERROR "cannot use generic type" */ : + case struct{T /* ERROR "cannot use generic type" */ }: + case *T /* ERROR "cannot use generic type" */ : + case func(T /* ERROR "cannot use generic type" */ ): + case interface{m(T /* ERROR "cannot use generic type" */ )}: + case map[T /* ERROR "cannot use generic type" */ ] string: + case chan T /* ERROR "cannot use generic type" */ : + + case T /* ERROR "cannot use generic type" */ , *T /* ERROR "cannot use generic type" */ : + } +} + +// Make sure a parenthesized nil is ok. + +func _(x interface{}) { + switch x.(type) { + case ((nil)), int: + } +} + +// Make sure we look for the predeclared nil. + +func _(x interface{}) { + type nil int + switch x.(type) { + case nil: // ok - this is the type nil + } +} + +func _(x interface{}) { + var nil int + switch x.(type) { + case nil /* ERROR "not a type" */ : // not ok - this is the variable nil + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48018.go b/go/src/internal/types/testdata/fixedbugs/issue48018.go new file mode 100644 index 0000000000000000000000000000000000000000..3df908acb58ab817235adc893b95e546d10d1b91 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48018.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +type Box[A any] struct { + value A +} + +func Nest[A /* ERROR "instantiation cycle" */ any](b Box[A], n int) interface{} { + if n == 0 { + return b + } + return Nest(Box[Box[A]]{b}, n-1) +} + +func main() { + Nest(Box[int]{0}, 10) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48048.go b/go/src/internal/types/testdata/fixedbugs/issue48048.go new file mode 100644 index 0000000000000000000000000000000000000000..98a03eabdf0c82ee9cf3d47c7d18df27f7998ab9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48048.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] struct{} + +func (T[_]) A() {} + +var _ = (T[int]).A +var _ = (*T[int]).A + +var _ = (T /* ERROR "cannot use generic type" */).A +var _ = (*T /* ERROR "cannot use generic type" */).A diff --git a/go/src/internal/types/testdata/fixedbugs/issue48082.go b/go/src/internal/types/testdata/fixedbugs/issue48082.go new file mode 100644 index 0000000000000000000000000000000000000000..648c512ea22ae2c4d91ad239137254d4f9c9f3e7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48082.go @@ -0,0 +1,7 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue48082 + +import "init" /* ERROR "init must be a func" */ /* ERROR "could not import init" */ diff --git a/go/src/internal/types/testdata/fixedbugs/issue48083.go b/go/src/internal/types/testdata/fixedbugs/issue48083.go new file mode 100644 index 0000000000000000000000000000000000000000..15e9b70d1d9d5eb2d1fa90988928798b78a86e62 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48083.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] struct{} + +type _ interface{ int | T /* ERROR "cannot use generic type" */ } \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue48136.go b/go/src/internal/types/testdata/fixedbugs/issue48136.go new file mode 100644 index 0000000000000000000000000000000000000000..b76322e8554ac2c904f730352699e86a5cbd7519 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48136.go @@ -0,0 +1,36 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[P interface{ *P }]() {} +func f2[P interface{ func(P) }]() {} +func f3[P, Q interface{ func(Q) P }]() {} +func f4[P interface{ *Q }, Q interface{ func(P) }]() {} +func f5[P interface{ func(P) }]() {} +func f6[P interface { *Tree[P] }, Q any ]() {} + +func _() { + f1 /* ERROR "cannot infer P" */ () + f2 /* ERROR "cannot infer P" */ () + f3 /* ERROR "cannot infer P" */ () + f4 /* ERROR "cannot infer P" */ () + f5 /* ERROR "cannot infer P" */ () + f6 /* ERROR "cannot infer P" */ () +} + +type Tree[P any] struct { + left, right *Tree[P] + data P +} + +// test case from issue + +func foo[Src interface { func() Src }]() Src { + return foo[Src] +} + +func _() { + foo /* ERROR "cannot infer Src" */ () +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48234.go b/go/src/internal/types/testdata/fixedbugs/issue48234.go new file mode 100644 index 0000000000000000000000000000000000000000..e069930c42d99c3caa36a9acff90d60cf6031fa4 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48234.go @@ -0,0 +1,10 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var _ = interface{ + m() + m /* ERROR "duplicate method" */ () +}(nil) diff --git a/go/src/internal/types/testdata/fixedbugs/issue48312.go b/go/src/internal/types/testdata/fixedbugs/issue48312.go new file mode 100644 index 0000000000000000000000000000000000000000..708201b415fe07d4e9ada1c16cb13c8e8a4ff25c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48312.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T interface{ m() } +type P *T + +func _(p *T) { + p.m /* ERROR "type *T is pointer to interface, not interface" */ () +} + +func _(p P) { + p.m /* ERROR "type P is pointer to interface, not interface" */ () +} + +func _[P T](p *P) { + p.m /* ERROR "type *P is pointer to type parameter, not type parameter" */ () +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48472.go b/go/src/internal/types/testdata/fixedbugs/issue48472.go new file mode 100644 index 0000000000000000000000000000000000000000..169ab0da9e054c6e4ebc34def9371b8a6428ad7f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48472.go @@ -0,0 +1,16 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func g() { + var s string + var i int + _ = s /* ERROR "invalid operation: s + i (mismatched types string and int)" */ + i +} + +func f(i int) int { + i /* ERROR `invalid operation: i += "1" (mismatched types int and untyped string)` */ += "1" + return i +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48529.go b/go/src/internal/types/testdata/fixedbugs/issue48529.go new file mode 100644 index 0000000000000000000000000000000000000000..eca1da89232b08bf399f2e659fd4509d5263ec8f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48529.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[U interface{ M() T /* ERROR "too many type arguments for type T" */ [U, int] }] int + +type X int + +func (X) M() T[X] { return 0 } diff --git a/go/src/internal/types/testdata/fixedbugs/issue48582.go b/go/src/internal/types/testdata/fixedbugs/issue48582.go new file mode 100644 index 0000000000000000000000000000000000000000..8ffcd5a8c2e02a65cdca0c2194cce93298f23ca7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48582.go @@ -0,0 +1,29 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type N /* ERROR "invalid recursive type" */ interface { + int | N +} + +type A /* ERROR "invalid recursive type" */ interface { + int | B +} + +type B interface { + int | A +} + +type S /* ERROR "invalid recursive type" */ struct { + I // ERROR "interface contains type constraints" +} + +type I interface { + int | S +} + +type P interface { + *P // ERROR "interface contains type constraints" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48619.go b/go/src/internal/types/testdata/fixedbugs/issue48619.go new file mode 100644 index 0000000000000000000000000000000000000000..fc5dce0ad5620f3856e19d46b77df23fa6d43645 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48619.go @@ -0,0 +1,22 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P any](a, _ P) { + var x int + // TODO(gri) these error messages, while correct, could be better + f(a, x /* ERROR "type int of x does not match inferred type P for P" */) + f(x, a /* ERROR "type P of a does not match inferred type int for P" */) +} + +func g[P any](a, b P) { + g(a, b) + g(&a, &b) + g([]P{}, []P{}) + + // work-around: provide type argument explicitly + g[*P](&a, &b) + g[[]P]([]P{}, []P{}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48656.go b/go/src/internal/types/testdata/fixedbugs/issue48656.go new file mode 100644 index 0000000000000000000000000000000000000000..f77e08a4c116a33559c66a6fe2e7542305cf1a45 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48656.go @@ -0,0 +1,13 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P *Q, Q any](P, Q) { + _ = f[P] +} + +func f2[P /* ERROR "instantiation cycle" */ *Q, Q any](P, Q) { + _ = f2[*P] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48695.go b/go/src/internal/types/testdata/fixedbugs/issue48695.go new file mode 100644 index 0000000000000000000000000000000000000000..9f4a76851d5dad0ec983630cbb97abf263011f88 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48695.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func g[P ~func(T) P, T any](P) {} + +func _() { + type F func(int) F + var f F + g(f) + _ = g[F] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48703.go b/go/src/internal/types/testdata/fixedbugs/issue48703.go new file mode 100644 index 0000000000000000000000000000000000000000..89c667b2e9ca7744982605d41cdb18f3faa8fab6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48703.go @@ -0,0 +1,27 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +// The actual example from the issue. +type List[P any] struct{} + +func (_ List[P]) m() (_ List[List[P]]) { return } + +// Other types of recursion through methods. +type R[P any] int + +func (*R[R /* ERROR "must be an identifier" */ [int]]) m0() {} +func (R[P]) m1(R[R[P]]) {} +func (R[P]) m2(R[*P]) {} +func (R[P]) m3([unsafe.Sizeof(new(R[P]))]int) {} +func (R[P]) m4([unsafe.Sizeof(new(R[R[P]]))]int) {} + +// Mutual recursion +type M[P any] int + +func (R[P]) m5(M[M[P]]) {} +func (M[P]) m(R[R[P]]) {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48712.go b/go/src/internal/types/testdata/fixedbugs/issue48712.go new file mode 100644 index 0000000000000000000000000000000000000000..028660fb1e30bcea50298442ec2a658b137c8eb7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48712.go @@ -0,0 +1,41 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P comparable](x, y P) { + _ = x == x + _ = x == y + _ = y == x + _ = y == y + + _ = x /* ERROR "type parameter P cannot use operator <" */ < y +} + +func _[P comparable](x P, y any) { + _ = x == x + _ = x == y + _ = y == x + _ = y == y + + _ = x /* ERROR "type parameter P cannot use operator <" */ < y +} + +func _[P any](x, y P) { + _ = x /* ERROR "incomparable types in type set" */ == x + _ = x /* ERROR "incomparable types in type set" */ == y + _ = y /* ERROR "incomparable types in type set" */ == x + _ = y /* ERROR "incomparable types in type set" */ == y + + _ = x /* ERROR "type parameter P cannot use operator <" */ < y +} + +func _[P any](x P, y any) { + _ = x /* ERROR "incomparable types in type set" */ == x + _ = x /* ERROR "incomparable types in type set" */ == y + _ = y == x // ERROR "incomparable types in type set" + _ = y == y + + _ = x /* ERROR "type parameter P cannot use operator <" */ < y +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48819.go b/go/src/internal/types/testdata/fixedbugs/issue48819.go new file mode 100644 index 0000000000000000000000000000000000000000..916faaffef5496c172587e4d7b1928213ce50835 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48819.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type T /* ERROR "invalid recursive type: T refers to itself" */ struct { + T +} + +func _(t T) { + _ = unsafe.Sizeof(t) // should not go into infinite recursion here +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48827.go b/go/src/internal/types/testdata/fixedbugs/issue48827.go new file mode 100644 index 0000000000000000000000000000000000000000..bd08835e9159614698a684b47527dcbbbeba90ff --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48827.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type G[P any] int + +type ( + _ G[int] + _ G[G /* ERRORx `cannot use.*without instantiation` */] + _ bool /* ERROR "invalid operation: bool[int] (bool is not a generic type)" */ [int] + _ bool /* ERROR "invalid operation: bool[G] (bool is not a generic type)" */[G] +) + +// The example from the issue. +func _() { + _ = &([10]bool /* ERRORx `invalid operation.*bool is not a generic type` */ [1 /* ERROR "expected type" */ ]{}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48951.go b/go/src/internal/types/testdata/fixedbugs/issue48951.go new file mode 100644 index 0000000000000000000000000000000000000000..8d6f8500e4259638a2c8739218f78853a229c015 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48951.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + A1[P any] [10]A1 /* ERROR "invalid recursive type" */ [P] + A2[P any] [10]A2 /* ERROR "invalid recursive type" */ [*P] + A3[P any] [10]*A3[P] + + L1[P any] []L1[P] + + S1[P any] struct{ f S1 /* ERROR "invalid recursive type" */ [P] } + S2[P any] struct{ f S2 /* ERROR "invalid recursive type" */ [*P] } // like example in issue + S3[P any] struct{ f *S3[P] } + + I1[P any] interface{ I1 /* ERROR "invalid recursive type" */ [P] } + I2[P any] interface{ I2 /* ERROR "invalid recursive type" */ [*P] } + I3[P any] interface{ *I3 /* ERROR "interface contains type constraints" */ [P] } +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue48962.go b/go/src/internal/types/testdata/fixedbugs/issue48962.go new file mode 100644 index 0000000000000000000000000000000000000000..4294cf08619ee211943be2bd5bd5f4b5553d6853 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48962.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T0[P any] struct { + f P +} + +type T1 /* ERROR "invalid recursive type" */ struct { + _ T0[T1] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue48974.go b/go/src/internal/types/testdata/fixedbugs/issue48974.go new file mode 100644 index 0000000000000000000000000000000000000000..08d8656a061c036000bdaa802f54292eb28e68e4 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue48974.go @@ -0,0 +1,22 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Fooer interface { + Foo() +} + +type Fooable[F /* ERROR "instantiation cycle" */ Fooer] struct { + ptr F +} + +func (f *Fooable[F]) Adapter() *Fooable[*FooerImpl[F]] { + return &Fooable[*FooerImpl[F]]{&FooerImpl[F]{}} +} + +type FooerImpl[F Fooer] struct { +} + +func (fi *FooerImpl[F]) Foo() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49003.go b/go/src/internal/types/testdata/fixedbugs/issue49003.go new file mode 100644 index 0000000000000000000000000000000000000000..bf2e6c4d113cb0bb9e40a6d13987c5eba7c9edab --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49003.go @@ -0,0 +1,10 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f(s string) int { + for range s { + } +} // ERROR "missing return" diff --git a/go/src/internal/types/testdata/fixedbugs/issue49005.go b/go/src/internal/types/testdata/fixedbugs/issue49005.go new file mode 100644 index 0000000000000000000000000000000000000000..6ec926ec6163dc9823486281598f090552a15bf3 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49005.go @@ -0,0 +1,31 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T1 interface{ M() } + +func F1() T1 + +var _ = F1().(*X1 /* ERROR "undefined: X1" */) + +func _() { + switch F1().(type) { + case *X1 /* ERROR "undefined: X1" */ : + } +} + +type T2 interface{ M() } + +func F2() T2 + +var _ = F2 /* ERROR "impossible type assertion: F2().(*X2)\n\t*X2 does not implement T2 (missing method M)" */ ().(*X2) + +type X2 struct{} + +func _() { + switch F2().(type) { + case * /* ERROR "impossible type switch case: *X2\n\tF2() (value of interface type T2) cannot have dynamic type *X2 (missing method M)" */ X2: + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49043.go b/go/src/internal/types/testdata/fixedbugs/issue49043.go new file mode 100644 index 0000000000000000000000000000000000000000..7594b3277cbce5e1341e945e99766f36e979f7c0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49043.go @@ -0,0 +1,24 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// The example from the issue. +type ( + N[P any] M /* ERROR "invalid recursive type" */ [P] + M[P any] N[P] +) + +// A slightly more complicated case. +type ( + A[P any] B /* ERROR "invalid recursive type" */ [P] + B[P any] C[P] + C[P any] A[P] +) + +// Confusing but valid (note that `type T *T` is valid). +type ( + N1[P any] *M1[P] + M1[P any] *N1[P] +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue49112.go b/go/src/internal/types/testdata/fixedbugs/issue49112.go new file mode 100644 index 0000000000000000000000000000000000000000..e87d1c07dcfb4dc774fe060dd43a5a9b56433a02 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49112.go @@ -0,0 +1,15 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P int](P) {} + +func _() { + _ = f[int] + _ = f[[ /* ERROR "[]int does not satisfy int ([]int missing in int)" */ ]int] + + f(0) + f /* ERROR "P (type []int) does not satisfy int" */ ([]int{}) // TODO(gri) better error message +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49179.go b/go/src/internal/types/testdata/fixedbugs/issue49179.go new file mode 100644 index 0000000000000000000000000000000000000000..1f8da295959207d768665f321f651ade4769beb7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49179.go @@ -0,0 +1,37 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[P int | string]() {} +func f2[P ~int | string | float64]() {} +func f3[P int](x P) {} + +type myInt int +type myFloat float64 + +func _() { + _ = f1[int] + _ = f1[myInt /* ERROR "possibly missing ~ for int in int | string" */] + _ = f2[myInt] + _ = f2[myFloat /* ERROR "possibly missing ~ for float64 in ~int | string | float64" */] + var x myInt + f3 /* ERROR "myInt does not satisfy int (possibly missing ~ for int in int)" */ (x) +} + +// test case from the issue + +type SliceConstraint[T any] interface { + []T +} + +func Map[S SliceConstraint[E], E any](s S, f func(E) E) S { + return s +} + +type MySlice []int + +func f(s MySlice) { + Map[MySlice /* ERROR "MySlice does not satisfy SliceConstraint[int] (possibly missing ~ for []int in SliceConstraint[int])" */, int](s, nil) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49242.go b/go/src/internal/types/testdata/fixedbugs/issue49242.go new file mode 100644 index 0000000000000000000000000000000000000000..0415bf692ea3b92f729dfeb3754b806f11b3f3fd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49242.go @@ -0,0 +1,27 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P int](x P) int { + return x // ERRORx `cannot use x .* as int value in return statement` +} + +func _[P int]() int { + return P /* ERRORx `cannot use P\(1\) .* as int value in return statement` */ (1) +} + +func _[P int](x int) P { + return x // ERRORx `cannot use x .* as P value in return statement` +} + +func _[P, Q any](x P) Q { + return x // ERRORx `cannot use x .* as Q value in return statement` +} + +// test case from issue +func F[G interface{ uint }]() int { + f := func(uint) int { return 0 } + return f(G /* ERRORx `cannot use G\(1\) .* as uint value in argument to f` */ (1)) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49247.go b/go/src/internal/types/testdata/fixedbugs/issue49247.go new file mode 100644 index 0000000000000000000000000000000000000000..0ad2e29d9c5f8114487b72e2c860d87231c19ef8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49247.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type integer interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +func Add1024[T integer](s []T) { + for i, v := range s { + s[i] = v + 1024 // ERROR "cannot convert 1024 (untyped int constant) to type T" + } +} + +func f[T interface{ int8 }]() { + println(T(1024 /* ERROR "cannot convert 1024 (untyped int value) to type T" */)) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49276.go b/go/src/internal/types/testdata/fixedbugs/issue49276.go new file mode 100644 index 0000000000000000000000000000000000000000..00da1a72cf44458f38c731a14eeff832c60bfc69 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49276.go @@ -0,0 +1,46 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type S /* ERROR "invalid recursive type S" */ struct { + _ [unsafe.Sizeof(s)]byte +} + +var s S + +// Since f is a pointer, this case could be valid. +// But it's pathological and not worth the expense. +type T /* ERROR "invalid recursive type" */ struct { + f *[unsafe.Sizeof(T{})]int +} + +// a mutually recursive case using unsafe.Sizeof +type ( + A1/* ERROR "invalid recursive type" */ struct { + _ [unsafe.Sizeof(B1{})]int + } + + B1 struct { + _ [unsafe.Sizeof(A1{})]int + } +) + +// a mutually recursive case using len +type ( + A2/* ERROR "invalid recursive type" */ struct { + f [len(B2{}.f)]int + } + + B2 struct { + f [len(A2{}.f)]int + } +) + +// test case from issue +type a /* ERROR "invalid recursive type" */ struct { + _ [42 - unsafe.Sizeof(a{})]byte +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49296.go b/go/src/internal/types/testdata/fixedbugs/issue49296.go new file mode 100644 index 0000000000000000000000000000000000000000..c8c520873676b99ba9696597b55b020e5205fc4c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49296.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[ + T0 any, + T1 []int, + T2 ~float64 | ~complex128 | chan int, +]() { + _ = T0(nil /* ERROR "cannot convert nil to type T0" */ ) + _ = T1(1 /* ERRORx `cannot convert 1 .* to type T1` */ ) + _ = T2(2 /* ERRORx `cannot convert 2 .* to type T2` */ ) +} + +// test case from issue +func f[T interface{[]int}]() { + _ = T(1 /* ERROR "cannot convert" */ ) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49439.go b/go/src/internal/types/testdata/fixedbugs/issue49439.go new file mode 100644 index 0000000000000000000000000000000000000000..63bedf61911914f99de3b34d555f8dcfd77387b8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49439.go @@ -0,0 +1,26 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type T0[P T0[P]] struct{} + +type T1[P T2[P /* ERROR "P does not satisfy T1[P]" */]] struct{} +type T2[P T1[P /* ERROR "P does not satisfy T2[P]" */]] struct{} + +type T3[P interface{ ~struct{ f T3[int /* ERROR "int does not satisfy" */ ] } }] struct{} + +// valid cycle in M +type N[P M[P]] struct{} +type M[Q any] struct{ F *M[Q] } + +// "crazy" case +type TC[P [unsafe.Sizeof(func() { + type T[P [unsafe.Sizeof(func() {})]byte] struct{} +})]byte] struct{} + +// test case from issue +type X[T any, PT X /* ERROR "not enough type arguments for type X" */ [T]] interface{} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49482.go b/go/src/internal/types/testdata/fixedbugs/issue49482.go new file mode 100644 index 0000000000000000000000000000000000000000..bc6b60099cf5aee1919cccd5f1809c4a7c06c484 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49482.go @@ -0,0 +1,26 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// The following is OK, per the special handling for type literals discussed in issue #49482. +type _[P *struct{}] struct{} +type _[P *int,] int +type _[P (*int),] int + +const P = 2 // declare P to avoid noisy 'undefined' errors below. + +// The following parse as invalid array types due to parsing ambiguitiues. +type _ [P *int /* ERROR "int (type) is not an expression" */ ]int +type _ [P /* ERROR "cannot call P (untyped int constant 2): untyped int is not a function" */ (*int)]int + +// Adding a trailing comma or an enclosing interface resolves the ambiguity. +type _[P *int,] int +type _[P (*int),] int +type _[P interface{*int}] int +type _[P interface{(*int)}] int + +// The following parse correctly as valid generic types. +type _[P *struct{} | int] struct{} +type _[P *struct{} | ~int] struct{} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49541.go b/go/src/internal/types/testdata/fixedbugs/issue49541.go new file mode 100644 index 0000000000000000000000000000000000000000..665ed1da7c7a1f17f5c764fcc082843476c859cf --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49541.go @@ -0,0 +1,45 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S[A, B any] struct { + f int +} + +func (S[A, B]) m() {} + +// TODO(gri): with type-type inference enabled we should only report one error +// below. See issue #50588. + +func _[A any](s S /* ERROR "not enough type arguments for type S: have 1, want 2" */ [A]) { + // we should see no follow-on errors below + s.f = 1 + s.m() +} + +// another test case from the issue + +func _() { + X /* ERROR "cannot infer Q" */ (Interface[*F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [string]](Impl{})) +} + +func X[Q Qer](fs Interface[Q]) { +} + +type Impl struct{} + +func (Impl) M() {} + +type Interface[Q Qer] interface { + M() +} + +type Qer interface { + Q() +} + +type F[A, B any] struct{} + +func (f *F[A, B]) Q() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49579.go b/go/src/internal/types/testdata/fixedbugs/issue49579.go new file mode 100644 index 0000000000000000000000000000000000000000..780859c50962ba3b0670f4d9abe0dc03194a83e6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49579.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type I[F any] interface { + Q(*F) +} + +func G[F any]() I[any] { + return g /* ERRORx `cannot use g\[F\]{} .* as I\[any\] value in return statement: g\[F\] does not implement I\[any\] \(method Q has pointer receiver\)` */ [F]{} +} + +type g[F any] struct{} + +func (*g[F]) Q(*any) {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49592.go b/go/src/internal/types/testdata/fixedbugs/issue49592.go new file mode 100644 index 0000000000000000000000000000000000000000..846deaa89aac62bf1d7b404ca8e78d01965587f9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49592.go @@ -0,0 +1,11 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + var x *interface{} + var y interface{} + _ = x == y +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49602.go b/go/src/internal/types/testdata/fixedbugs/issue49602.go new file mode 100644 index 0000000000000000000000000000000000000000..09cc96963ba311fd65ea38ea303b10684e8dd7a6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49602.go @@ -0,0 +1,19 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type M interface { + m() +} + +type C interface { + comparable +} + +type _ interface { + int | M // ERROR "cannot use p.M in union (p.M contains methods)" + int | comparable // ERROR "cannot use comparable in union" + int | C // ERROR "cannot use p.C in union (p.C embeds comparable)" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49705.go b/go/src/internal/types/testdata/fixedbugs/issue49705.go new file mode 100644 index 0000000000000000000000000000000000000000..5b5fba2a1dc661a76f1f0fe1b98174cb28896ed2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49705.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Integer interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +func shl[I Integer](n int) I { + return 1 << n +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49735.go b/go/src/internal/types/testdata/fixedbugs/issue49735.go new file mode 100644 index 0000000000000000000000000000000000000000..b719e1353f0e928fb992888af37dd2cedb5c2e0e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49735.go @@ -0,0 +1,12 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P1 any, P2 ~byte, P3 []int | []byte](s1 P1, s2 P2, s3 P3) { + _ = append(nil /* ERROR "invalid append: argument must be a slice; have untyped nil" */, 0) + _ = append(s1 /* ERROR "invalid append: argument must be a slice; have s1 (variable of type P1 constrained by any)" */, 0) + _ = append(s2 /* ERROR "invalid append: argument must be a slice; have s2 (variable of type P2 constrained by ~byte)" */, 0) + _ = append(s3 /* ERROR "invalid append: mismatched slice element types int and byte in s3 (variable of type P3 constrained by []int | []byte)" */, 0) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49736.go b/go/src/internal/types/testdata/fixedbugs/issue49736.go new file mode 100644 index 0000000000000000000000000000000000000000..83e53a4937f9c9ee6d0f660bde04a5d2e690bf95 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49736.go @@ -0,0 +1,17 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "math/big" + +// From go.dev/issue/18419 +func _(x *big.Float) { + x.form /* ERROR "x.form undefined (cannot refer to unexported field form)" */ () +} + +// From go.dev/issue/31053 +func _() { + _ = big.Float{form /* ERROR "cannot refer to unexported field form in struct literal of type big.Float" */ : 0} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49739.go b/go/src/internal/types/testdata/fixedbugs/issue49739.go new file mode 100644 index 0000000000000000000000000000000000000000..73825f440dd41505a6857ea10d95db39b8945409 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49739.go @@ -0,0 +1,23 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Verify that we get an empty type set (not just an error) +// when using an invalid ~A. + +package p + +type A int +type C interface { + ~ /* ERROR "invalid use of ~" */ A +} + +func f[_ C]() {} +func g[_ interface{ C }]() {} +func h[_ C | int]() {} + +func _() { + _ = f[int /* ERROR "cannot satisfy C (empty type set)" */] + _ = g[int /* ERROR "cannot satisfy interface{C} (empty type set)" */] + _ = h[int] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue49864.go b/go/src/internal/types/testdata/fixedbugs/issue49864.go new file mode 100644 index 0000000000000000000000000000000000000000..8ccd77cfea07bb97e4b913e7f07efbc23dde49a2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue49864.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P ~int, Q any](p P) { + _ = Q(p /* ERROR "cannot convert" */ ) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50259.go b/go/src/internal/types/testdata/fixedbugs/issue50259.go new file mode 100644 index 0000000000000000000000000000000000000000..6df8c64524324c68f800d3a412374bad6f4b7d18 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50259.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var x T[B] + +type T[_ any] struct{} +type A T[B] +type B = T[A] + +// test case from issue + +var v Box[Step] +type Box[T any] struct{} +type Step = Box[StepBox] +type StepBox Box[Step] diff --git a/go/src/internal/types/testdata/fixedbugs/issue50276.go b/go/src/internal/types/testdata/fixedbugs/issue50276.go new file mode 100644 index 0000000000000000000000000000000000000000..97e477e6fa32108152e3658e0708fa2c537520d2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50276.go @@ -0,0 +1,39 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// simplified test case + +type transform[T any] struct{} +type pair[S any] struct {} + +var _ transform[step] + +type box transform[step] +type step = pair[box] + +// test case from issue + +type Transform[T any] struct{ hold T } +type Pair[S, T any] struct { + First S + Second T +} + +var first Transform[Step] + +// This line doesn't use the Step alias, and it compiles fine if you uncomment it. +var second Transform[Pair[Box, interface{}]] + +type Box *Transform[Step] + +// This line is the same as the `first` line, but it comes after the Box declaration and +// does not break the compile. +var third Transform[Step] + +type Step = Pair[Box, interface{}] + +// This line also does not break the compile +var fourth Transform[Step] diff --git a/go/src/internal/types/testdata/fixedbugs/issue50281.go b/go/src/internal/types/testdata/fixedbugs/issue50281.go new file mode 100644 index 0000000000000000000000000000000000000000..f333e81a7054f8105224001ef30d7b443aaa7445 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50281.go @@ -0,0 +1,26 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[S string | []byte](s S) { + var buf []byte + _ = append(buf, s...) +} + +func _[S ~string | ~[]byte](s S) { + var buf []byte + _ = append(buf, s...) +} + +// test case from issue + +type byteseq interface { + string | []byte +} + +// This should allow to eliminate the two functions above. +func AppendByteString[source byteseq](buf []byte, s source) []byte { + return append(buf, s[1:6]...) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50321.go b/go/src/internal/types/testdata/fixedbugs/issue50321.go new file mode 100644 index 0000000000000000000000000000000000000000..ab2a31b7ebdbb5630758baf87f71b0c58999b3ed --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50321.go @@ -0,0 +1,8 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func Ln[A A /* ERROR "cannot use a type parameter as constraint" */ ](p A) { +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50372.go b/go/src/internal/types/testdata/fixedbugs/issue50372.go new file mode 100644 index 0000000000000000000000000000000000000000..10d2a24a28cb9df5c5f270d1fbf8fe37439fa4a6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50372.go @@ -0,0 +1,27 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(s []int) { + var i, j, k, l int + _, _, _, _ = i, j, k, l + + for range s {} + for i = range s {} + for i, j = range s {} + for i, j, k /* ERRORx "range clause permits at most two iteration variables|at most 2 expressions" */ = range s {} + for i, j, k, l /* ERRORx "range clause permits at most two iteration variables|at most 2 expressions" */ = range s {} +} + +func _(s chan int) { + var i, j, k, l int + _, _, _, _ = i, j, k, l + + for range s {} + for i = range s {} + for i, j /* ERRORx `range over .* permits only one iteration variable` */ = range s {} + for i, j, k /* ERRORx `range over .* permits only one iteration variable|at most 2 expressions` */ = range s {} + for i, j, k, l /* ERRORx `range over .* permits only one iteration variable|at most 2 expressions` */ = range s {} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50417.go b/go/src/internal/types/testdata/fixedbugs/issue50417.go new file mode 100644 index 0000000000000000000000000000000000000000..c70898e2a87bf21b4463cf4d5c30e7d67c7456f5 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50417.go @@ -0,0 +1,68 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Field accesses through type parameters are disabled +// until we have a more thorough understanding of the +// implications on the spec. See issue #51576. + +package p + +type Sf struct { + f int +} + +func f0[P Sf](p P) { + _ = p.f // ERROR "p.f undefined" + p.f /* ERROR "p.f undefined" */ = 0 +} + +func f0t[P ~struct{f int}](p P) { + _ = p.f // ERROR "p.f undefined" + p.f /* ERROR "p.f undefined" */ = 0 +} + +var _ = f0[Sf] +var _ = f0t[Sf] + +var _ = f0[Sm /* ERROR "does not satisfy" */ ] +var _ = f0t[Sm /* ERROR "does not satisfy" */ ] + +func f1[P interface{ Sf; m() }](p P) { + _ = p.f // ERROR "p.f undefined" + p.f /* ERROR "p.f undefined" */ = 0 + p.m() +} + +var _ = f1[Sf /* ERROR "missing method m" */ ] +var _ = f1[Sm /* ERROR "does not satisfy" */ ] + +type Sm struct {} + +func (Sm) m() {} + +type Sfm struct { + f int +} + +func (Sfm) m() {} + +func f2[P interface{ Sfm; m() }](p P) { + _ = p.f // ERROR "p.f undefined" + p.f /* ERROR "p.f undefined" */ = 0 + p.m() +} + +var _ = f2[Sfm] + +// special case: core type is a named pointer type + +type PSfm *Sfm + +func f3[P interface{ PSfm }](p P) { + _ = p.f // ERROR "p.f undefined" + p.f /* ERROR "p.f undefined" */ = 0 + p.m /* ERROR "type P has no field or method m" */ () +} + +var _ = f3[PSfm] diff --git a/go/src/internal/types/testdata/fixedbugs/issue50426.go b/go/src/internal/types/testdata/fixedbugs/issue50426.go new file mode 100644 index 0000000000000000000000000000000000000000..17ec0ce529688bae5e8c27ce7a1024fe4d3388ed --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50426.go @@ -0,0 +1,44 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A1 [2]uint64 +type A2 [2]uint64 + +func (a A1) m() A1 { return a } +func (a A2) m() A2 { return a } + +func f[B any, T interface { + A1 | A2 + m() T +}](v T) { +} + +func _() { + var v A2 + // Use function type inference to infer type A2 for T. + // Don't use constraint type inference before function + // type inference for typed arguments, otherwise it would + // infer type [2]uint64 for T which doesn't have method m + // (was the bug). + f[int](v) +} + +// Keep using constraint type inference before function type +// inference for untyped arguments so we infer type float64 +// for E below, and not int (which would not work). +func g[S ~[]E, E any](S, E) {} + +func _() { + var s []float64 + g[[]float64](s, 0) +} + +// Keep using constraint type inference after function +// type inference for untyped arguments so we infer +// missing type arguments for which we only have the +// untyped arguments as starting point. +func h[E any, R []E](v E) R { return R{v} } +func _() []int { return h(0) } diff --git a/go/src/internal/types/testdata/fixedbugs/issue50427.go b/go/src/internal/types/testdata/fixedbugs/issue50427.go new file mode 100644 index 0000000000000000000000000000000000000000..d89d63e3087d966361570416ddc52101651c9730 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50427.go @@ -0,0 +1,23 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// The parser no longer parses type parameters for methods. +// In the past, type checking the code below led to a crash (#50427). + +type T interface{ m[ /* ERROR "must have no type parameters" */ P any]() } + +func _(t T) { + var _ interface{ m[ /* ERROR "must have no type parameters" */ P any](); n() } = t /* ERROR "does not implement" */ +} + +type S struct{} + +func (S) m[ /* ERROR "must have no type parameters" */ P any]() {} + +func _(s S) { + var _ interface{ m[ /* ERROR "must have no type parameters" */ P any](); n() } = s /* ERROR "does not implement" */ + +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50450.go b/go/src/internal/types/testdata/fixedbugs/issue50450.go new file mode 100644 index 0000000000000000000000000000000000000000..bae311157860558829538bd5ff5719c7a633068e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50450.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S struct{} + +func f[P S]() {} + +var _ = f[S] diff --git a/go/src/internal/types/testdata/fixedbugs/issue50516.go b/go/src/internal/types/testdata/fixedbugs/issue50516.go new file mode 100644 index 0000000000000000000000000000000000000000..fcaefedc45a18eec372816ec854cf2a98d22292d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50516.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P struct{ f int }](x P) { + _ = x.g // ERROR "type P has no field or method g" +} + +func _[P struct{ f int } | struct{ g int }](x P) { + _ = x.g // ERROR "type P has no field or method g" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50646.go b/go/src/internal/types/testdata/fixedbugs/issue50646.go new file mode 100644 index 0000000000000000000000000000000000000000..2c16cfcda46f012f17622975c6edef55338fe582 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50646.go @@ -0,0 +1,26 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[_ comparable]() {} +func f2[_ interface{ comparable }]() {} + +type T interface{ m() } + +func _[P comparable, Q ~int, R any]() { + _ = f1[int] + _ = f1[T] + _ = f1[any] + _ = f1[P] + _ = f1[Q] + _ = f1[R /* ERROR "R does not satisfy comparable" */] + + _ = f2[int] + _ = f2[T] + _ = f2[any] + _ = f2[P] + _ = f2[Q] + _ = f2[R /* ERROR "R does not satisfy comparable" */] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50729.go b/go/src/internal/types/testdata/fixedbugs/issue50729.go new file mode 100644 index 0000000000000000000000000000000000000000..fe19fdfa6884630a8299c145d18e6fd707366513 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50729.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// version 1 +var x1 T1[B1] + +type T1[_ any] struct{} +type A1 T1[B1] +type B1 = T1[A1] + +// version 2 +type T2[_ any] struct{} +type A2 T2[B2] +type B2 = T2[A2] + +var x2 T2[B2] diff --git a/go/src/internal/types/testdata/fixedbugs/issue50729b.go b/go/src/internal/types/testdata/fixedbugs/issue50729b.go new file mode 100644 index 0000000000000000000000000000000000000000..bc1f4406e5227f5f621e27f1507acda87d3e1533 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50729b.go @@ -0,0 +1,15 @@ +// -gotypesalias=1 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type d[T any] struct{} +type ( + b d[a] +) + +type a = func(c) +type c struct{ a } diff --git a/go/src/internal/types/testdata/fixedbugs/issue50755.go b/go/src/internal/types/testdata/fixedbugs/issue50755.go new file mode 100644 index 0000000000000000000000000000000000000000..afc7b2414cb37ca8fe633fc8058bb3d7541cebc5 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50755.go @@ -0,0 +1,47 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// The core type of M2 unifies with the type of m1 +// during function argument type inference. +// M2's constraint is unnamed. +func f1[K1 comparable, E1 any](m1 map[K1]E1) {} + +func f2[M2 map[string]int](m2 M2) { + f1(m2) +} + +// The core type of M3 unifies with the type of m1 +// during function argument type inference. +// M3's constraint is named. +type Map3 map[string]int + +func f3[M3 Map3](m3 M3) { + f1(m3) +} + +// The core type of M5 unifies with the core type of M4 +// during constraint type inference. +func f4[M4 map[K4]int, K4 comparable](m4 M4) {} + +func f5[M5 map[K5]int, K5 comparable](m5 M5) { + f4(m5) +} + +// test case from issue + +func Copy[MC ~map[KC]VC, KC comparable, VC any](dst, src MC) { + for k, v := range src { + dst[k] = v + } +} + +func Merge[MM ~map[KM]VM, KM comparable, VM any](ms ...MM) MM { + result := MM{} + for _, m := range ms { + Copy(result, m) + } + return result +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50779.go b/go/src/internal/types/testdata/fixedbugs/issue50779.go new file mode 100644 index 0000000000000000000000000000000000000000..59c0f2d6a015750eb73237450dcf459c06374c27 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50779.go @@ -0,0 +1,25 @@ +// -gotypesalias=0 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type AC interface { + C +} + +type ST []int + +type R[S any, P any] struct{} + +type SR = R[SS, ST] + +type SS interface { + NSR(any) *SR // ERROR "invalid use of type alias SR in recursive type" +} + +type C interface { + NSR(any) *SR +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50779a.go b/go/src/internal/types/testdata/fixedbugs/issue50779a.go new file mode 100644 index 0000000000000000000000000000000000000000..d0e99058b7ede98bdf6a3d5d0d6252290b2ee4eb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50779a.go @@ -0,0 +1,25 @@ +// -gotypesalias=1 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type AC interface { + C +} + +type ST []int + +type R[S any, P any] struct{} + +type SR = R[SS, ST] + +type SS interface { + NSR(any) *SR +} + +type C interface { + NSR(any) *SR +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50782.go b/go/src/internal/types/testdata/fixedbugs/issue50782.go new file mode 100644 index 0000000000000000000000000000000000000000..97e8f6cdff4db34b4e741ab5f089b4421f884583 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50782.go @@ -0,0 +1,47 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Field accesses through type parameters are disabled +// until we have a more thorough understanding of the +// implications on the spec. See issue #51576. + +package p + +// The first example from the issue. +type Numeric interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// numericAbs matches numeric types with an Abs method. +type numericAbs[T Numeric] interface { + ~struct{ Value T } + Abs() T +} + +// AbsDifference computes the absolute value of the difference of +// a and b, where the absolute value is determined by the Abs method. +func absDifference[T numericAbs[T /* ERROR "T does not satisfy Numeric" */]](a, b T) T { + // Field accesses are not permitted for now. Keep an error so + // we can find and fix this code once the situation changes. + return a.Value // ERROR "a.Value undefined" + // TODO: The error below should probably be positioned on the '-'. + // d := a /* ERROR "invalid operation: operator - not defined" */ .Value - b.Value + // return d.Abs() +} + +// The second example from the issue. +type T[P int] struct{ f P } + +func _[P T[P /* ERROR "P does not satisfy int" */ ]]() {} + +// Additional tests +func _[P T[T /* ERROR "T[P] does not satisfy int" */ [P /* ERROR "P does not satisfy int" */ ]]]() {} +func _[P T[Q /* ERROR "Q does not satisfy int" */ ], Q T[P /* ERROR "P does not satisfy int" */ ]]() {} +func _[P T[Q], Q int]() {} + +type C[P comparable] struct{ f P } +func _[P C[C[P]]]() {} +func _[P C[C /* ERROR "C[Q] does not satisfy comparable" */ [Q /* ERROR "Q does not satisfy comparable" */]], Q func()]() {} +func _[P [10]C[P]]() {} +func _[P struct{ f C[C[P]]}]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50816.go b/go/src/internal/types/testdata/fixedbugs/issue50816.go new file mode 100644 index 0000000000000000000000000000000000000000..b7c28cdffd824104e103899898ba8dbc01fe7e86 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50816.go @@ -0,0 +1,23 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkg + +type I interface { + Foo() +} + +type T1 struct{} + +func (T1) foo() {} + +type T2 struct{} + +func (T2) foo() string { return "" } + +func _() { + var i I + _ = i /* ERROR "impossible type assertion: i.(T1)\n\tT1 does not implement I (missing method Foo)\n\t\thave foo()\n\t\twant Foo()" */ .(T1) + _ = i /* ERROR "impossible type assertion: i.(T2)\n\tT2 does not implement I (missing method Foo)\n\t\thave foo() string\n\t\twant Foo()" */ .(T2) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50833.go b/go/src/internal/types/testdata/fixedbugs/issue50833.go new file mode 100644 index 0000000000000000000000000000000000000000..e912e4d67dfe8a46049b495374ce28db354db08e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50833.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + S struct{ f int } + PS *S +) + +func a() []*S { return []*S{{f: 1}} } +func b() []PS { return []PS{{f: 1}} } + +func c[P *S]() []P { return []P{{f: 1}} } +func d[P PS]() []P { return []P{{f: 1}} } diff --git a/go/src/internal/types/testdata/fixedbugs/issue50912.go b/go/src/internal/types/testdata/fixedbugs/issue50912.go new file mode 100644 index 0000000000000000000000000000000000000000..a99fa7bfeaeb49c6681920736ce0ce1ebcc0be84 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50912.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func Real[P ~complex128](x P) { + _ = real(x /* ERROR "not supported" */ ) +} + +func Imag[P ~complex128](x P) { + _ = imag(x /* ERROR "not supported" */ ) +} + +func Complex[P ~float64](x P) { + _ = complex(x /* ERROR "not supported" */ , 0) + _ = complex(0 /* ERROR "not supported" */ , x) + _ = complex(x /* ERROR "not supported" */ , x) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50918.go b/go/src/internal/types/testdata/fixedbugs/issue50918.go new file mode 100644 index 0000000000000000000000000000000000000000..5744fa810d34eebf91558a1aeed42f777643ad2c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50918.go @@ -0,0 +1,21 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type thing1 struct { + things []string +} + +type thing2 struct { + things []thing1 +} + +func _() { + var a1, b1 thing1 + _ = a1 /* ERROR "struct containing []string cannot be compared" */ == b1 + + var a2, b2 thing2 + _ = a2 /* ERROR "struct containing []thing1 cannot be compared" */ == b2 +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50929.go b/go/src/internal/types/testdata/fixedbugs/issue50929.go new file mode 100644 index 0000000000000000000000000000000000000000..a665e229be0627d1e14bd7bc8fd4ff46a7bcd792 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50929.go @@ -0,0 +1,68 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is tested when running "go test -run Manual" +// without source arguments. Use for one-off debugging. + +package p + +import "fmt" + +type F[A, B any] int + +func G[A, B any](F[A, B]) { +} + +func _() { + // TODO(gri) only report one error below (issue #50932) + var x F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [int] + G(x /* ERROR "does not match" */) +} + +// test case from issue +// (lots of errors but doesn't crash anymore) + +type RC[G any, RG any] interface { + ~[]RG +} + +type RG[G any] struct{} + +type RSC[G any] []*RG[G] + +type M[Rc RC[G, RG], G any, RG any] struct { + Fn func(Rc) +} + +type NFn[Rc RC[G, RG], G any, RG any] func(Rc) + +func NC[Rc RC[G, RG], G any, RG any](nFn NFn[Rc, G, RG]) { + var empty Rc + nFn(empty) +} + +func NSG[G any](c RSC[G]) { + fmt.Println(c) +} + +func MMD[Rc RC /* ERROR "not enough type arguments for type RC: have 1, want 2" */ [RG], RG any, G any]() M /* ERROR "not enough type arguments for type" */ [Rc, RG] { + + var nFn NFn /* ERROR "not enough type arguments for type NFn: have 2, want 3" */ [Rc, RG] + + var empty Rc + switch any(empty).(type) { + case BC /* ERROR "undefined: BC" */ : + + case RSC[G]: + nFn = NSG /* ERROR "cannot use NSG[G]" */ [G] + } + + return M /* ERROR "not enough type arguments for type M: have 2, want 3" */ [Rc, RG]{ + Fn: func(rc Rc) { + NC(nFn /* ERROR "does not match" */) + }, + } + + return M /* ERROR "not enough type arguments for type M: have 2, want 3" */ [Rc, RG]{} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue50965.go b/go/src/internal/types/testdata/fixedbugs/issue50965.go new file mode 100644 index 0000000000000000000000000000000000000000..79059e96731dd55f6c36350c70e7bdc2f566d87f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue50965.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(x int, c string) { + switch x { + case c /* ERROR "invalid case c in switch on x (mismatched types string and int)" */ : + } +} + +func _(x, c []int) { + switch x { + case c /* ERROR "invalid case c in switch on x (slice can only be compared to nil)" */ : + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51025.go b/go/src/internal/types/testdata/fixedbugs/issue51025.go new file mode 100644 index 0000000000000000000000000000000000000000..caaabd583eabf8c579ea02689444b76551ec0a26 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51025.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var _ interface{ m() } = struct /* ERROR "m is a field, not a method" */ { + m func() +}{} + +var _ interface{ m() } = & /* ERROR "m is a field, not a method" */ struct { + m func() +}{} + +var _ interface{ M() } = struct /* ERROR "missing method M" */ { + m func() +}{} + +var _ interface{ M() } = & /* ERROR "missing method M" */ struct { + m func() +}{} + +// test case from issue +type I interface{ m() } +type T struct{ m func() } +type M struct{} + +func (M) m() {} + +func _() { + var t T + var m M + var i I + + i = m + i = t // ERROR "m is a field, not a method" + _ = i +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51048.go b/go/src/internal/types/testdata/fixedbugs/issue51048.go new file mode 100644 index 0000000000000000000000000000000000000000..58308370ea54b75c07798c43846c7962942115bd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51048.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P int]() { + _ = f[P] +} + +func f[T int]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51139.go b/go/src/internal/types/testdata/fixedbugs/issue51139.go new file mode 100644 index 0000000000000000000000000000000000000000..4c460d4ff8ee9110215f3affb895bbf3fded1f77 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51139.go @@ -0,0 +1,26 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[S []T, T any](S, T) {} + +func _() { + type L chan int + f([]L{}, make(chan int)) + f([]L{}, make(L)) + f([]chan int{}, make(chan int)) + f /* ERROR "[]chan int does not satisfy []L ([]chan int missing in []p.L)" */ ([]chan int{}, make(L)) +} + +// test case from issue + +func Append[S ~[]T, T any](s S, x ...T) S { /* implementation of append */ return s } + +func _() { + type MyPtr *int + var x []MyPtr + _ = append(x, new(int)) + _ = Append(x, new(int)) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51145.go b/go/src/internal/types/testdata/fixedbugs/issue51145.go new file mode 100644 index 0000000000000000000000000000000000000000..1f970d9bb07476c3bccd86ee759c54d24b9fe85a --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51145.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "fmt" + +type ( + _ [fmt /* ERROR "invalid array length fmt" */ ]int + _ [float64 /* ERROR "invalid array length float64" */ ]int + _ [f /* ERROR "invalid array length f" */ ]int + _ [nil /* ERROR "invalid array length nil" */ ]int +) + +func f() + +var _ fmt.Stringer // use fmt diff --git a/go/src/internal/types/testdata/fixedbugs/issue51158.go b/go/src/internal/types/testdata/fixedbugs/issue51158.go new file mode 100644 index 0000000000000000000000000000000000000000..3edc50538206ed45562af0ada88abf9db88a15af --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51158.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Type checking the following code should not cause an infinite recursion. +func f[M map[K]int, K comparable](m M) { + f(m) +} + +// Equivalent code using mutual recursion. +func f1[M map[K]int, K comparable](m M) { + f2(m) +} +func f2[M map[K]int, K comparable](m M) { + f1(m) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51229.go b/go/src/internal/types/testdata/fixedbugs/issue51229.go new file mode 100644 index 0000000000000000000000000000000000000000..22a91135dfd9b6769999bc4154256074beac226c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51229.go @@ -0,0 +1,164 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Constraint type inference should be independent of the +// ordering of the type parameter declarations. Try all +// permutations in the test case below. +// Permutations produced by https://go.dev/play/p/PHcZNGJTEBZ. + +func f00[S1 ~[]E1, S2 ~[]E2, E1 ~byte, E2 ~byte](S1, S2) {} +func f01[S2 ~[]E2, S1 ~[]E1, E1 ~byte, E2 ~byte](S1, S2) {} +func f02[E1 ~byte, S1 ~[]E1, S2 ~[]E2, E2 ~byte](S1, S2) {} +func f03[S1 ~[]E1, E1 ~byte, S2 ~[]E2, E2 ~byte](S1, S2) {} +func f04[S2 ~[]E2, E1 ~byte, S1 ~[]E1, E2 ~byte](S1, S2) {} +func f05[E1 ~byte, S2 ~[]E2, S1 ~[]E1, E2 ~byte](S1, S2) {} +func f06[E2 ~byte, S2 ~[]E2, S1 ~[]E1, E1 ~byte](S1, S2) {} +func f07[S2 ~[]E2, E2 ~byte, S1 ~[]E1, E1 ~byte](S1, S2) {} +func f08[S1 ~[]E1, E2 ~byte, S2 ~[]E2, E1 ~byte](S1, S2) {} +func f09[E2 ~byte, S1 ~[]E1, S2 ~[]E2, E1 ~byte](S1, S2) {} +func f10[S2 ~[]E2, S1 ~[]E1, E2 ~byte, E1 ~byte](S1, S2) {} +func f11[S1 ~[]E1, S2 ~[]E2, E2 ~byte, E1 ~byte](S1, S2) {} +func f12[S1 ~[]E1, E1 ~byte, E2 ~byte, S2 ~[]E2](S1, S2) {} +func f13[E1 ~byte, S1 ~[]E1, E2 ~byte, S2 ~[]E2](S1, S2) {} +func f14[E2 ~byte, S1 ~[]E1, E1 ~byte, S2 ~[]E2](S1, S2) {} +func f15[S1 ~[]E1, E2 ~byte, E1 ~byte, S2 ~[]E2](S1, S2) {} +func f16[E1 ~byte, E2 ~byte, S1 ~[]E1, S2 ~[]E2](S1, S2) {} +func f17[E2 ~byte, E1 ~byte, S1 ~[]E1, S2 ~[]E2](S1, S2) {} +func f18[E2 ~byte, E1 ~byte, S2 ~[]E2, S1 ~[]E1](S1, S2) {} +func f19[E1 ~byte, E2 ~byte, S2 ~[]E2, S1 ~[]E1](S1, S2) {} +func f20[S2 ~[]E2, E2 ~byte, E1 ~byte, S1 ~[]E1](S1, S2) {} +func f21[E2 ~byte, S2 ~[]E2, E1 ~byte, S1 ~[]E1](S1, S2) {} +func f22[E1 ~byte, S2 ~[]E2, E2 ~byte, S1 ~[]E1](S1, S2) {} +func f23[S2 ~[]E2, E1 ~byte, E2 ~byte, S1 ~[]E1](S1, S2) {} + +type myByte byte + +func _(a []byte, b []myByte) { + f00(a, b) + f01(a, b) + f02(a, b) + f03(a, b) + f04(a, b) + f05(a, b) + f06(a, b) + f07(a, b) + f08(a, b) + f09(a, b) + f10(a, b) + f11(a, b) + f12(a, b) + f13(a, b) + f14(a, b) + f15(a, b) + f16(a, b) + f17(a, b) + f18(a, b) + f19(a, b) + f20(a, b) + f21(a, b) + f22(a, b) + f23(a, b) +} + +// Constraint type inference may have to iterate. +// Again, the order of the type parameters shouldn't matter. + +func g0[S ~[]E, M ~map[string]S, E any](m M) {} +func g1[M ~map[string]S, S ~[]E, E any](m M) {} +func g2[E any, S ~[]E, M ~map[string]S](m M) {} +func g3[S ~[]E, E any, M ~map[string]S](m M) {} +func g4[M ~map[string]S, E any, S ~[]E](m M) {} +func g5[E any, M ~map[string]S, S ~[]E](m M) {} + +func _(m map[string][]byte) { + g0(m) + g1(m) + g2(m) + g3(m) + g4(m) + g5(m) +} + +// Worst-case scenario. +// There are 10 unknown type parameters. In each iteration of +// constraint type inference we infer one more, from right to left. +// Each iteration looks repeatedly at all 11 type parameters, +// requiring a total of 10*11 = 110 iterations with the current +// implementation. Pathological case. + +func h[K any, J ~*K, I ~*J, H ~*I, G ~*H, F ~*G, E ~*F, D ~*E, C ~*D, B ~*C, A ~*B](x A) {} + +func _(x **********int) { + h(x) +} + +// Examples with channel constraints and tilde. + +func ch1[P chan<- int]() (_ P) { return } // core(P) == chan<- int (single type, no tilde) +func ch2[P ~chan int]() { return } // core(P) == ~chan<- int (tilde) +func ch3[P chan E, E any](E) { return } // core(P) == chan<- E (single type, no tilde) +func ch4[P chan E | ~chan<- E, E any](E) { return } // core(P) == ~chan<- E (tilde) +func ch5[P chan int | chan<- int]() { return } // core(P) == chan<- int (not a single type) + +func _() { + // P can be inferred as there's a single specific type and no tilde. + var _ chan int = ch1 /* ERRORx `cannot use ch1.*value of type chan<- int` */ () + var _ chan<- int = ch1() + + // P cannot be inferred as there's a tilde. + ch2 /* ERROR "cannot infer P" */ () + type myChan chan int + ch2[myChan]() + + // P can be inferred as there's a single specific type and no tilde. + var e int + ch3(e) + + // P cannot be inferred as there's more than one specific type and a tilde. + ch4 /* ERROR "cannot infer P" */ (e) + _ = ch4[chan int] + + // P cannot be inferred as there's more than one specific type. + ch5 /* ERROR "cannot infer P" */ () + ch5[chan<- int]() +} + +// test case from issue + +func equal[M1 ~map[K1]V1, M2 ~map[K2]V2, K1, K2 ~uint32, V1, V2 ~string](m1 M1, m2 M2) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[K2(k)]; !ok || V2(v1) != v2 { + return false + } + } + return true +} + +func equalFixed[K1, K2 ~uint32, V1, V2 ~string](m1 map[K1]V1, m2 map[K2]V2) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[K2(k)]; !ok || v1 != V1(v2) { + return false + } + } + return true +} + +type ( + someNumericID uint32 + someStringID string +) + +func _() { + foo := map[uint32]string{10: "bar"} + bar := map[someNumericID]someStringID{10: "bar"} + equal(foo, bar) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51232.go b/go/src/internal/types/testdata/fixedbugs/issue51232.go new file mode 100644 index 0000000000000000000000000000000000000000..c5832d2976914c7c9edbab6c7e8663f93f9ea699 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51232.go @@ -0,0 +1,30 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type RC[RG any] interface { + ~[]RG +} + +type Fn[RCT RC[RG], RG any] func(RCT) + +type F[RCT RC[RG], RG any] interface { + Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] +} + +type concreteF[RCT RC[RG], RG any] struct { + makeFn func() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] +} + +func (c *concreteF[RCT, RG]) Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] { + return c.makeFn() +} + +func NewConcrete[RCT RC[RG], RG any](Rc RCT) F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [RCT] { + // TODO(rfindley): eliminate the duplicate error below. + return & /* ERRORx `cannot use .* as F\[RCT\]` */ concreteF /* ERROR "not enough type arguments for type concreteF: have 1, want 2" */ [RCT]{ + makeFn: nil, + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51233.go b/go/src/internal/types/testdata/fixedbugs/issue51233.go new file mode 100644 index 0000000000000000000000000000000000000000..d96d3d1aa07fb2d10451b11cd305c1ad13201a85 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51233.go @@ -0,0 +1,27 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// As of issue #51527, type-type inference has been disabled. + +type RC[RG any] interface { + ~[]RG +} + +type Fn[RCT RC[RG], RG any] func(RCT) + +type FFn[RCT RC[RG], RG any] func() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] + +type F[RCT RC[RG], RG any] interface { + Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] +} + +type concreteF[RCT RC[RG], RG any] struct { + makeFn FFn /* ERROR "not enough type arguments for type FFn: have 1, want 2" */ [RCT] +} + +func (c *concreteF[RCT, RG]) Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] { + return c.makeFn() +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51257.go b/go/src/internal/types/testdata/fixedbugs/issue51257.go new file mode 100644 index 0000000000000000000000000000000000000000..828612b4283f2b605b17e06831d055637cf7334a --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51257.go @@ -0,0 +1,46 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[_ comparable]() {} + +type S1 struct{ x int } +type S2 struct{ x any } +type S3 struct{ x [10]interface{ m() } } + +func _[P1 comparable, P2 S2]() { + _ = f[S1] + _ = f[S2] + _ = f[S3] + + type L1 struct { x P1 } + type L2 struct { x P2 } + _ = f[L1] + _ = f[L2 /* ERROR "L2 does not satisfy comparable" */ ] +} + + +// example from issue + +type Set[T comparable] map[T]struct{} + +func NewSetFromSlice[T comparable](items []T) *Set[T] { + s := Set[T]{} + + for _, item := range items { + s[item] = struct{}{} + } + + return &s +} + +type T struct{ x any } + +func main() { + NewSetFromSlice([]T{ + {"foo"}, + {5}, + }) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51335.go b/go/src/internal/types/testdata/fixedbugs/issue51335.go new file mode 100644 index 0000000000000000000000000000000000000000..5eb52138430ab508c561ea3bf65c3f33937ec50f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51335.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S1 struct{} +type S2 struct{} + +func _[P *S1|*S2]() { + _= []P{{ /* ERROR "invalid composite literal element type P (no common underlying type)" */ }} +} + +func _[P *S1|S1]() { + _= []P{{ /* ERROR "invalid composite literal element type P (no common underlying type)" */ }} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51339.go b/go/src/internal/types/testdata/fixedbugs/issue51339.go new file mode 100644 index 0000000000000000000000000000000000000000..933e426715d0578080d9bfc4dae0ba5503fd48ee --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51339.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is tested when running "go test -run Manual" +// without source arguments. Use for one-off debugging. + +package p + +type T[P any, B *P] struct{} + +func (T /* ERROR "cannot use generic type" */) m0() {} + +func (T /* ERROR "receiver declares 1 type parameter, but receiver base type declares 2" */ [_]) m1() { +} +func (T[_, _]) m2() {} + +// TODO(gri) this error is unfortunate (issue #51343) +func (T /* ERROR "receiver declares 3 type parameters, but receiver base type declares 2" */ [_, _, _]) m3() { +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51360.go b/go/src/internal/types/testdata/fixedbugs/issue51360.go new file mode 100644 index 0000000000000000000000000000000000000000..1798a4ab2fd3f8b96e91386b58711c054af18739 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51360.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + len.Println /* ERROR "invalid use of len (built-in) in selector expression" */ + len.Println /* ERROR "invalid use of len (built-in) in selector expression" */ () + _ = len.Println /* ERROR "invalid use of len (built-in) in selector expression" */ + _ = len /* ERROR "cannot index len" */ [0] + _ = *len /* ERROR "cannot indirect len" */ +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51376.go b/go/src/internal/types/testdata/fixedbugs/issue51376.go new file mode 100644 index 0000000000000000000000000000000000000000..0f2ab8ea2242f4dbb0c43f976b6a550d957a6214 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51376.go @@ -0,0 +1,24 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Map map[string]int + +func f[M ~map[K]V, K comparable, V any](M) {} +func g[M map[K]V, K comparable, V any](M) {} + +func _[M1 ~map[K]V, M2 map[K]V, K comparable, V any]() { + var m1 M1 + f(m1) + g /* ERROR "M1 does not satisfy map[K]V" */ (m1) // M1 has tilde + + var m2 M2 + f(m2) + g(m2) // M1 does not have tilde + + var m3 Map + f(m3) + g /* ERROR "Map does not satisfy map[string]int" */ (m3) // M in g does not have tilde +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51386.go b/go/src/internal/types/testdata/fixedbugs/issue51386.go new file mode 100644 index 0000000000000000000000000000000000000000..ef6223927a21f41c6ba52cfc649574cec11e4500 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51386.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type myString string + +func _[P ~string | ~[]byte | ~[]rune]() { + _ = P("") + const s myString = "" + _ = P(s) +} + +func _[P myString]() { + _ = P("") +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51437.go b/go/src/internal/types/testdata/fixedbugs/issue51437.go new file mode 100644 index 0000000000000000000000000000000000000000..376261516eec92a8fb40d1f7d0ffbc552df55ef8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51437.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T struct{} + +func (T) m() []int { return nil } + +func f(x T) { + for _, x := range func() []int { + return x.m() // x declared in parameter list of f + }() { + _ = x // x declared by range clause + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51472.go b/go/src/internal/types/testdata/fixedbugs/issue51472.go new file mode 100644 index 0000000000000000000000000000000000000000..6dfff05395979ce22b3a08e369dfbb8653b60b59 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51472.go @@ -0,0 +1,54 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T comparable](x T) { + _ = x == x +} + +func _[T interface{interface{comparable}}](x T) { + _ = x == x +} + +func _[T interface{comparable; interface{comparable}}](x T) { + _ = x == x +} + +func _[T interface{comparable; ~int}](x T) { + _ = x == x +} + +func _[T interface{comparable; ~[]byte}](x T) { + _ = x /* ERROR "empty type set" */ == x +} + +// TODO(gri) The error message here should be better. See issue #51525. +func _[T interface{comparable; ~int; ~string}](x T) { + _ = x /* ERROR "empty type set" */ == x +} + +// TODO(gri) The error message here should be better. See issue #51525. +func _[T interface{~int; ~string}](x T) { + _ = x /* ERROR "empty type set" */ == x +} + +func _[T interface{comparable; interface{~int}; interface{int|float64}}](x T) { + _ = x == x +} + +func _[T interface{interface{comparable; ~int}; interface{~float64; comparable; m()}}](x T) { + _ = x /* ERROR "empty type set" */ == x +} + +// test case from issue + +func f[T interface{comparable; []byte|string}](x T) { + _ = x == x +} + +func _(s []byte) { + f /* ERROR "T (type []byte) does not satisfy interface{comparable; []byte | string}" */ (s) // TODO(gri) better error message (T's type set only contains string!) + _ = f[[ /* ERROR "does not satisfy" */ ]byte] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51503.go b/go/src/internal/types/testdata/fixedbugs/issue51503.go new file mode 100644 index 0000000000000000000000000000000000000000..90a4256229a3b81d1bb1114601ce2f1567ba69d7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51503.go @@ -0,0 +1,31 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[T any] struct{} + +// The inner T in T[T] must not conflict with the receiver base type T. +func (T[T]) m1() {} + +// The receiver parameter r is declared after the receiver type parameter +// r in T[r]. An error is expected for the receiver parameter. +func (r /* ERROR "r redeclared" */ T[r]) m2() {} + +type C any + +// The scope of type parameter C starts after the type name (_) +// because we want to be able to use type parameters in the type +// parameter list. Hence, the 2nd C in the type parameter list below +// refers to the first C. Since constraints cannot be type parameters +// this is an error. +type _[C C /* ERROR "cannot use a type parameter as constraint" */] struct{} + +// Same issue here. +func _[C C /* ERROR "cannot use a type parameter as constraint" */]() {} + +// The scope of ordinary parameter C starts after the function signature. +// Therefore, the 2nd C in the parameter list below refers to the type C. +// This code is correct. +func _(C C) {} // okay diff --git a/go/src/internal/types/testdata/fixedbugs/issue51509.go b/go/src/internal/types/testdata/fixedbugs/issue51509.go new file mode 100644 index 0000000000000000000000000000000000000000..4737a825056d761471b0d37e92e0429d28efc132 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51509.go @@ -0,0 +1,7 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T /* ERROR "invalid recursive type" */ T.x diff --git a/go/src/internal/types/testdata/fixedbugs/issue51525.go b/go/src/internal/types/testdata/fixedbugs/issue51525.go new file mode 100644 index 0000000000000000000000000000000000000000..af569c854359d0096b575a0f3506cc011eb1ebcb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51525.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T interface { + int + string +}](x T) { + _ = x /* ERROR "empty type set" */ == x + _ = x /* ERROR "empty type set" */ + x + <-x /* ERROR "empty type set" */ + x <- /* ERROR "empty type set" */ 0 + close(x /* ERROR "empty type set" */) +} + +func _[T interface{ int | []byte }](x T) { + _ = x /* ERROR "incomparable types in type set" */ == x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51533.go b/go/src/internal/types/testdata/fixedbugs/issue51533.go new file mode 100644 index 0000000000000000000000000000000000000000..166e5fe64ad3dc11b82b522626c88cd086aa03c3 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51533.go @@ -0,0 +1,20 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(x any) { + switch x { + case 0: + fallthrough // ERROR "fallthrough statement out of place" + _ = x + default: + } + + switch x.(type) { + case int: + fallthrough // ERROR "cannot fallthrough in type switch" + default: + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51578.go b/go/src/internal/types/testdata/fixedbugs/issue51578.go new file mode 100644 index 0000000000000000000000000000000000000000..d2e8a2855080e6895b2ef59f538ad89d7273a358 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51578.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var _ = (*interface /* ERROR "interface contains type constraints" */ {int})(nil) + +// abbreviated test case from issue + +type TypeSet interface{ int | string } + +func _() { + f((*TypeSet /* ERROR "interface contains type constraints" */)(nil)) +} + +func f(any) {} \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue51593.go b/go/src/internal/types/testdata/fixedbugs/issue51593.go new file mode 100644 index 0000000000000000000000000000000000000000..62b0a5625ad9219590dd2ecd3d0e3d6bd6c465fb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51593.go @@ -0,0 +1,13 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P interface{ m(R) }, R any]() {} + +type T = interface { m(int) } + +func _() { + _ = f[T] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51607.go b/go/src/internal/types/testdata/fixedbugs/issue51607.go new file mode 100644 index 0000000000000000000000000000000000000000..298adade4b9a0088ee9f15b18b6006fb1198fd88 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51607.go @@ -0,0 +1,65 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Interface types must be ignored during overlap test. + +type ( + T1 interface{int} + T2 interface{~int} + T3 interface{T1 | bool | string} + T4 interface{T2 | ~bool | ~string} +) + +type ( + // overlap errors for non-interface terms + // (like the interface terms, but explicitly inlined) + _ interface{int | int /* ERROR "overlapping terms int and int" */ } + _ interface{int | ~ /* ERROR "overlapping terms ~int and int" */ int} + _ interface{~int | int /* ERROR "overlapping terms int and ~int" */ } + _ interface{~int | ~ /* ERROR "overlapping terms ~int and ~int" */ int} + + _ interface{T1 | bool | string | T1 | bool /* ERROR "overlapping terms bool and bool" */ | string /* ERROR "overlapping terms string and string" */ } + _ interface{T1 | bool | string | T2 | ~ /* ERROR "overlapping terms ~bool and bool" */ bool | ~ /* ERROR "overlapping terms ~string and string" */ string} + + // no errors for interface terms + _ interface{T1 | T1} + _ interface{T1 | T2} + _ interface{T2 | T1} + _ interface{T2 | T2} + + _ interface{T3 | T3 | int} + _ interface{T3 | T4 | bool } + _ interface{T4 | T3 | string } + _ interface{T4 | T4 | float64 } +) + +func _[_ T1 | bool | string | T1 | bool /* ERROR "overlapping terms" */ ]() {} +func _[_ T1 | bool | string | T2 | ~ /* ERROR "overlapping terms" */ bool ]() {} +func _[_ T2 | ~bool | ~string | T1 | bool /* ERROR "overlapping terms" */ ]() {} +func _[_ T2 | ~bool | ~string | T2 | ~ /* ERROR "overlapping terms" */ bool ]() {} + +func _[_ T3 | T3 | int]() {} +func _[_ T3 | T4 | bool]() {} +func _[_ T4 | T3 | string]() {} +func _[_ T4 | T4 | float64]() {} + +// test cases from issue + +type _ interface { + interface {bool | int} | interface {bool | string} +} + +type _ interface { + interface {bool | int} ; interface {bool | string} +} + +type _ interface { + interface {bool; int} ; interface {bool; string} +} + +type _ interface { + interface {bool; int} | interface {bool; string} +} \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue51610.go b/go/src/internal/types/testdata/fixedbugs/issue51610.go new file mode 100644 index 0000000000000000000000000000000000000000..d0bc1ace9bf2ed3a54b00b26a972b166c071b728 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51610.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P int | float64 | complex128]() { + _ = map[P]int{1: 1, 1.0 /* ERROR "duplicate key 1" */ : 2, 1 /* ERROR "duplicate key (1 + 0i)" */ + 0i: 3} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51616.go b/go/src/internal/types/testdata/fixedbugs/issue51616.go new file mode 100644 index 0000000000000000000000000000000000000000..e0efc9e620ece2f84b42f3c21bbe62c7f2d59bd2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51616.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + C[T any] interface{~int; M() T} + + _ C[bool] + _ comparable + _ interface {~[]byte | ~string} + + // Alias type declarations may refer to "constraint" types + // like ordinary type declarations. + _ = C[bool] + _ = comparable + _ = interface {~[]byte | ~string} +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue51658.go b/go/src/internal/types/testdata/fixedbugs/issue51658.go new file mode 100644 index 0000000000000000000000000000000000000000..36e2fdd37f2090107091c0e187b899d070521a64 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51658.go @@ -0,0 +1,43 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This test checks syntax errors which differ between +// go/parser and the syntax package. +// TODO: consolidate eventually + +package p + +type F { // ERRORx "expected type|type declaration" + float64 +} // ERRORx "expected declaration|non-declaration statement" + +func _[T F | int](x T) { + _ = x == 0 // don't crash when recording type of 0 +} + +// test case from issue + +type FloatType { // ERRORx "expected type|type declaration" + float32 | float64 +} // ERRORx "expected declaration|non-declaration statement" + +type IntegerType interface { + int8 | int16 | int32 | int64 | int | + uint8 | uint16 | uint32 | uint64 | uint +} + +type ComplexType interface { + complex64 | complex128 +} + +type Number interface { + FloatType | IntegerType | ComplexType +} + +func GetDefaultNumber[T Number](value, defaultValue T) T { + if value == 0 { + return defaultValue + } + return value +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue51877.go b/go/src/internal/types/testdata/fixedbugs/issue51877.go new file mode 100644 index 0000000000000000000000000000000000000000..4b0e5bcd1fa7bcd7c51ab3ea9964a170ed548c1f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue51877.go @@ -0,0 +1,18 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S struct { + f1 int + f2 bool +} + +var ( + _ = S{0} /* ERROR "too few values in struct literal" */ + _ = struct{ f1, f2 int }{0} /* ERROR "too few values in struct literal" */ + + _ = S{0, true, "foo" /* ERROR "too many values in struct literal" */} + _ = struct{ f1, f2 int }{0, 1, 2 /* ERROR "too many values in struct literal" */} +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue52031.go b/go/src/internal/types/testdata/fixedbugs/issue52031.go new file mode 100644 index 0000000000000000000000000000000000000000..5b75b75c0cc58326fcd8190eb78f6ce9e567818b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue52031.go @@ -0,0 +1,33 @@ +// -lang=go1.12 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type resultFlags uint + +// Example from #52031. +// +// The following shifts should not produce errors on Go < 1.13, as their +// untyped constant operands are representable by type uint. +const ( + _ resultFlags = (1 << iota) / 2 + + reportEqual + reportUnequal + reportByIgnore + reportByMethod + reportByFunc + reportByCycle +) + +// Invalid cases. +var x int = 1 +var _ = (8 << x /* ERRORx `signed shift count .* requires go1.13 or later` */) + +const _ = (1 << 1.2 /* ERROR "truncated to uint" */) + +var y float64 +var _ = (1 << y /* ERROR "must be integer" */) diff --git a/go/src/internal/types/testdata/fixedbugs/issue52401.go b/go/src/internal/types/testdata/fixedbugs/issue52401.go new file mode 100644 index 0000000000000000000000000000000000000000..ccc32d3b1ba534b261cc570f4797a1aa8bcfd1dc --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue52401.go @@ -0,0 +1,11 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + const x = 0 + x /* ERROR "cannot assign to x" */ += 1 + x /* ERROR "cannot assign to x" */ ++ +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue52529.go b/go/src/internal/types/testdata/fixedbugs/issue52529.go new file mode 100644 index 0000000000000000000000000000000000000000..de7b2964b0ce1fc4dc94347c04f201d34964f851 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue52529.go @@ -0,0 +1,15 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Foo[P any] struct { + _ *Bar[P] +} + +type Bar[Q any] Foo[Q] + +func (v *Bar[R]) M() { + _ = (*Foo[R])(v) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue52698.go b/go/src/internal/types/testdata/fixedbugs/issue52698.go new file mode 100644 index 0000000000000000000000000000000000000000..20f24f09ffd96e56843f51403c9078941366b03e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue52698.go @@ -0,0 +1,62 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// correctness check: ensure that cycles through generic instantiations are detected +type T[P any] struct { + _ P +} + +type S /* ERROR "invalid recursive type" */ struct { + _ T[S] +} + +// simplified test 1 + +var _ A1[A1[string]] + +type A1[P any] struct { + _ B1[P] +} + +type B1[P any] struct { + _ P +} + +// simplified test 2 +var _ B2[A2] + +type A2 struct { + _ B2[string] +} + +type B2[P any] struct { + _ C2[P] +} + +type C2[P any] struct { + _ P +} + +// test case from issue +type T23 interface { + ~struct { + Field0 T13[T15] + } +} + +type T1[P1 interface { +}] struct { + Field2 P1 +} + +type T13[P2 interface { +}] struct { + Field2 T1[P2] +} + +type T15 struct { + Field0 T13[string] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue52915.go b/go/src/internal/types/testdata/fixedbugs/issue52915.go new file mode 100644 index 0000000000000000000000000000000000000000..e60c1767e98aefc6a8831913eac08d0dc60f9332 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue52915.go @@ -0,0 +1,21 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type T[P any] struct { + T /* ERROR "invalid recursive type" */ [P] +} + +func _[P any]() { + _ = unsafe.Sizeof(T[int]{}) + _ = unsafe.Sizeof(struct{ T[int] }{}) + + _ = unsafe.Sizeof(T[P]{}) + _ = unsafe.Sizeof(struct{ T[P] }{}) +} + +const _ = unsafe.Sizeof(T /* ERROR "invalid recursive type" */ [int]{}) diff --git a/go/src/internal/types/testdata/fixedbugs/issue53358.go b/go/src/internal/types/testdata/fixedbugs/issue53358.go new file mode 100644 index 0000000000000000000000000000000000000000..67c095c2833e4c04a011a0a770ef083899874a92 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue53358.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A struct{} + +func (*A) m() int { return 0 } + +var _ = A.m /* ERROR "invalid method expression A.m (needs pointer receiver (*A).m)" */ () +var _ = (*A).m(nil) + +type B struct{ A } + +var _ = B.m // ERROR "invalid method expression B.m (needs pointer receiver (*B).m)" +var _ = (*B).m + +var _ = struct{ A }.m // ERROR "invalid method expression struct{A}.m (needs pointer receiver (*struct{A}).m)" diff --git a/go/src/internal/types/testdata/fixedbugs/issue53535.go b/go/src/internal/types/testdata/fixedbugs/issue53535.go new file mode 100644 index 0000000000000000000000000000000000000000..127b8a8b452d352456c7ae2d87a5c7e7836a0c8b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue53535.go @@ -0,0 +1,35 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "io" + +// test using struct with invalid embedded field +var _ io.Writer = W{} // no error expected here because W has invalid embedded field + +type W struct { + *bufio /* ERROR "undefined: bufio" */ .Writer +} + +// test using an invalid type +var _ interface{ m() } = &M{} // no error expected here because M is invalid + +type M undefined // ERROR "undefined: undefined" + +// test using struct with invalid embedded field and containing a self-reference (cycle) +var _ interface{ m() } = &S{} // no error expected here because S is invalid + +type S struct { + *S + undefined // ERROR "undefined: undefined" +} + +// test using a generic struct with invalid embedded field and containing a self-reference (cycle) +var _ interface{ m() } = &G[int]{} // no error expected here because S is invalid + +type G[P any] struct { + *G[P] + undefined // ERROR "undefined: undefined" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue53650.go b/go/src/internal/types/testdata/fixedbugs/issue53650.go new file mode 100644 index 0000000000000000000000000000000000000000..4bba59efbfaa9f8c2a5138b5c3049227860806fd --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue53650.go @@ -0,0 +1,59 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "reflect" + "testing" +) + +type T1 int +type T2 int + +func f[P T1 | T2, _ []P]() {} + +var _ = f[T1] + +// test case from issue + +type BaseT interface { + Type1 | Type2 +} +type BaseType int +type Type1 BaseType +type Type2 BaseType // float64 + +type ValueT[T BaseT] struct { + A1 T +} + +func NewType1() *ValueT[Type1] { + r := NewT[Type1]() + return r +} +func NewType2() *ValueT[Type2] { + r := NewT[Type2]() + return r +} + +func NewT[TBase BaseT, TVal ValueT[TBase]]() *TVal { + ret := TVal{} + return &ret +} +func TestGoType(t *testing.T) { + r1 := NewType1() + r2 := NewType2() + t.Log(r1, r2) + t.Log(reflect.TypeOf(r1), reflect.TypeOf(r2)) + fooT1(r1.A1) + fooT2(r2.A1) +} + +func fooT1(t1 Type1) { + +} +func fooT2(t2 Type2) { + +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue53692.go b/go/src/internal/types/testdata/fixedbugs/issue53692.go new file mode 100644 index 0000000000000000000000000000000000000000..dc1a76c723f675deb97925eca4e1b47b03e7c6e1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue53692.go @@ -0,0 +1,15 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Cache[K comparable, V any] interface{} + +type LRU[K comparable, V any] struct{} + +func WithLocking2[K comparable, V any](Cache[K, V]) {} + +func _() { + WithLocking2 /* ERROR "cannot infer V" */ [string](LRU[string, int]{}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue54280.go b/go/src/internal/types/testdata/fixedbugs/issue54280.go new file mode 100644 index 0000000000000000000000000000000000000000..9465894aed0b59168b275bdd8291c29f68f7f6ea --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue54280.go @@ -0,0 +1,7 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +const C = 912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912 // ERROR "constant overflow" diff --git a/go/src/internal/types/testdata/fixedbugs/issue54405.go b/go/src/internal/types/testdata/fixedbugs/issue54405.go new file mode 100644 index 0000000000000000000000000000000000000000..688fee1f9e55551e70f3f9e5ada3440b6aa60320 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue54405.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that we don't see spurious errors for == +// for values with invalid types due to prior errors. + +package p + +var x struct { + f *NotAType /* ERROR "undefined" */ +} +var _ = x.f == nil // no error expected here + +var y *NotAType /* ERROR "undefined" */ +var _ = y == nil // no error expected here diff --git a/go/src/internal/types/testdata/fixedbugs/issue54424.go b/go/src/internal/types/testdata/fixedbugs/issue54424.go new file mode 100644 index 0000000000000000000000000000000000000000..ebfb83db09963ac24bee8590d36c5311fd8d762e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue54424.go @@ -0,0 +1,12 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P ~*T, T any]() { + var p P + var tp *T + tp = p // this assignment is valid + _ = tp +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue54942.go b/go/src/internal/types/testdata/fixedbugs/issue54942.go new file mode 100644 index 0000000000000000000000000000000000000000..b9a5cce4783cead8889d07abe5db9681423f459a --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue54942.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "context" + "database/sql" +) + +type I interface { + m(int, int, *int, int) +} + +type T struct{} + +func (_ *T) m(a, b, c, d int) {} + +var _ I = new /* ERROR "have m(int, int, int, int)\n\t\twant m(int, int, *int, int)" */ (T) + +// (slightly modified) test case from issue + +type Result struct { + Value string +} + +type Executor interface { + Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (Result, error) +} + +type myExecutor struct{} + +func (_ *myExecutor) Execute(ctx context.Context, stmt sql.Stmt, maxrows int, args []sql.NamedArg, urgency int) (*Result, error) { + return &Result{}, nil +} + +var ex Executor = new /* ERROR "have Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (*Result, error)\n\t\twant Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (Result, error)" */ (myExecutor) diff --git a/go/src/internal/types/testdata/fixedbugs/issue56351.go b/go/src/internal/types/testdata/fixedbugs/issue56351.go new file mode 100644 index 0000000000000000000000000000000000000000..eee142c9938085d0a7a33fcf40b3a0ffaf80e769 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue56351.go @@ -0,0 +1,11 @@ +// -lang=go1.20 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(s []int) { + clear /* ERROR "clear requires go1.21 or later" */ (s) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue56425.go b/go/src/internal/types/testdata/fixedbugs/issue56425.go new file mode 100644 index 0000000000000000000000000000000000000000..d85733faaac01db25db15935b32e857d0bfb4f9c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue56425.go @@ -0,0 +1,8 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +const s float32 = 0 +var _ = 0 << s diff --git a/go/src/internal/types/testdata/fixedbugs/issue56665.go b/go/src/internal/types/testdata/fixedbugs/issue56665.go new file mode 100644 index 0000000000000000000000000000000000000000..1f787d0bbc88554e3830e945e399494b651f2568 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue56665.go @@ -0,0 +1,30 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Example from the issue: +type A[T any] interface { + *T +} + +type B[T any] interface { + B /* ERROR "invalid recursive type" */ [*T] +} + +type C[T any, U B[U]] interface { + *T +} + +// Simplified reproducer: +type X[T any] interface { + X /* ERROR "invalid recursive type" */ [*T] +} + +var _ X[int] + +// A related example that doesn't go through interfaces. +type A2[P any] [10]A2 /* ERROR "invalid recursive type" */ [*P] + +var _ A2[int] diff --git a/go/src/internal/types/testdata/fixedbugs/issue57155.go b/go/src/internal/types/testdata/fixedbugs/issue57155.go new file mode 100644 index 0000000000000000000000000000000000000000..ec9fb2bad3ff57381c0c6c9df3a6a973b4837e21 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57155.go @@ -0,0 +1,14 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P *Q, Q any](p P, q Q) { + func() { + _ = f[P] + f(p, q) + f[P](p, q) + f[P, Q](p, q) + }() +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57160.go b/go/src/internal/types/testdata/fixedbugs/issue57160.go new file mode 100644 index 0000000000000000000000000000000000000000..446d019900c2a6c7fdf7a818790aa0286e8c98c8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57160.go @@ -0,0 +1,10 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(x *int) { + _ = 0 < x // ERROR "invalid operation" + _ = x < 0 // ERROR "invalid operation" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57192.go b/go/src/internal/types/testdata/fixedbugs/issue57192.go new file mode 100644 index 0000000000000000000000000000000000000000..6c7894ac0f1e7efdab00593254c74f344fc69aec --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57192.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type I1[T any] interface { + m1(T) +} +type I2[T any] interface { + I1[T] + m2(T) +} + +var V1 I1[int] +var V2 I2[int] + +func g[T any](I1[T]) {} +func _() { + g(V1) + g(V2) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57352.go b/go/src/internal/types/testdata/fixedbugs/issue57352.go new file mode 100644 index 0000000000000000000000000000000000000000..2b3170033785800a93abfc222520ddc315757e2b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57352.go @@ -0,0 +1,21 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A interface { + a() +} + +type AB interface { + A + b() +} + +type AAB struct { + A + AB +} + +var _ AB = AAB /* ERROR "ambiguous selector AAB.a" */ {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57486.go b/go/src/internal/types/testdata/fixedbugs/issue57486.go new file mode 100644 index 0000000000000000000000000000000000000000..933eeb4cf9a1a288de1f39b9afd85a12ed47bb41 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57486.go @@ -0,0 +1,29 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type C1 interface { + comparable +} + +type C2 interface { + comparable + [2]any | int +} + +func G1[T C1](t T) { _ = t == t } +func G2[T C2](t T) { _ = t == t } + +func F1[V [2]any](v V) { + _ = G1[V /* ERROR "V does not satisfy comparable" */] + _ = G1[[2]any] + _ = G1[int] +} + +func F2[V [2]any](v V) { + _ = G2[V /* ERROR "V does not satisfy C2" */] + _ = G2[[ /* ERROR "[2]any does not satisfy C2 (C2 mentions [2]any, but [2]any is not in the type set of C2)" */ 2]any] + _ = G2[int] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57500.go b/go/src/internal/types/testdata/fixedbugs/issue57500.go new file mode 100644 index 0000000000000000000000000000000000000000..4a90d47618fe9f071c2c7e2d5e7e010daa18c0f7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57500.go @@ -0,0 +1,16 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type C interface { + comparable + [2]any | int +} + +func f[T C]() {} + +func _() { + _ = f[[ /* ERROR "[2]any does not satisfy C (C mentions [2]any, but [2]any is not in the type set of C)" */ 2]any] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue57522.go b/go/src/internal/types/testdata/fixedbugs/issue57522.go new file mode 100644 index 0000000000000000000000000000000000000000..d83e5b2443e1aa14fa99911606f4836d179f3ce5 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue57522.go @@ -0,0 +1,24 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// A simplified version of the code in the original report. +type S[T any] struct{} +var V = S[any]{} +func (fs *S[T]) M(V.M /* ERROR "V.M is not a type" */) {} + +// Other minimal reproducers. +type S1[T any] V1.M /* ERROR "V1.M is not a type" */ +type V1 = S1[any] + +type S2[T any] struct{} +type V2 = S2[any] +func (fs *S2[T]) M(x V2.M /* ERROR "V2.M is not a type" */ ) {} + +// The following still panics, as the selector is reached from check.expr +// rather than check.typexpr. TODO(rfindley): fix this. +// type X[T any] int +// func (X[T]) M(x [X[int].M]int) {} + diff --git a/go/src/internal/types/testdata/fixedbugs/issue58611.go b/go/src/internal/types/testdata/fixedbugs/issue58611.go new file mode 100644 index 0000000000000000000000000000000000000000..1ff30f74fa024ba1d94a6334b963ffd5505055f7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue58611.go @@ -0,0 +1,27 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "sort" + "strings" +) + +func f[int any](x int) { + x = 0 /* ERRORx "cannot use 0.*(as int.*with int declared at|type parameter)" */ +} + +// test case from issue + +type Set[T comparable] map[T]struct{} + +func (s *Set[string]) String() string { + keys := make([]string, 0, len(*s)) + for k := range *s { + keys = append(keys, k) + } + sort.Strings(keys /* ERRORx "cannot use keys.*with string declared at.*|type parameter" */ ) + return strings /* ERROR "cannot use strings.Join" */ .Join(keys /* ERRORx "cannot use keys.*with string declared at.*|type parameter" */ , ",") +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue58612.go b/go/src/internal/types/testdata/fixedbugs/issue58612.go new file mode 100644 index 0000000000000000000000000000000000000000..db6a62d24721fd1f54fc5cb10c6e310b93abe176 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue58612.go @@ -0,0 +1,14 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + var x = new(T) + f[x /* ERROR "not a type" */ /* ERROR "use of .(type) outside type switch" */ .(type)]() +} + +type T struct{} + +func f[_ any]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue58671.go b/go/src/internal/types/testdata/fixedbugs/issue58671.go new file mode 100644 index 0000000000000000000000000000000000000000..fa964aa5fd2e812e5289ac49c927c2878ee111fe --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue58671.go @@ -0,0 +1,20 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func g[P any](...P) P { var x P; return x } + +func _() { + var ( + _ int = g(1, 2) + _ rune = g(1, 'a') + _ float64 = g(1, 'a', 2.3) + _ float64 = g('a', 2.3) + _ complex128 = g(2.3, 'a', 1i) + ) + g(true, 'a' /* ERROR "mismatched types untyped bool and untyped rune (cannot infer P)" */) + g(1, "foo" /* ERROR "mismatched types untyped int and untyped string (cannot infer P)" */) + g(1, 2.3, "bar" /* ERROR "mismatched types untyped float and untyped string (cannot infer P)" */) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue58742.go b/go/src/internal/types/testdata/fixedbugs/issue58742.go new file mode 100644 index 0000000000000000000000000000000000000000..b649a497747a1ec100060835672e231d9862a94f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue58742.go @@ -0,0 +1,18 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() (int, UndefinedType /* ERROR "undefined: UndefinedType" */ , string) { + return 0 // ERROR "not enough return values\n\thave (number)\n\twant (int, unknown type, string)" +} + +func _() (int, UndefinedType /* ERROR "undefined: UndefinedType" */ ) { + return 0, 1, 2 // ERROR "too many return values\n\thave (number, number, number)\n\twant (int, unknown type)" +} + +// test case from issue +func _() UndefinedType /* ERROR "undefined: UndefinedType" */ { + return // ERROR "not enough return values\n\thave ()\n\twant (unknown type)" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59190.go b/go/src/internal/types/testdata/fixedbugs/issue59190.go new file mode 100644 index 0000000000000000000000000000000000000000..fd08303303d5a500a1fdf627c35d22701fb26496 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59190.go @@ -0,0 +1,36 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type E [1 << 30]complex128 +var a [1 << 30]E +var _ = unsafe.Sizeof(a /* ERROR "too large" */ ) + +var s struct { + _ [1 << 30]E + x int +} +var _ = unsafe.Offsetof(s /* ERROR "too large" */ .x) + +// Test case from issue (modified so it also triggers on 32-bit platforms). + +type A [1]int +type S struct { + x A + y [1 << 30]A + z [1 << 30]struct{} +} +type T [1 << 30][1 << 30]S + +func _() { + var a A + var s S + var t T + _ = unsafe.Sizeof(a) + _ = unsafe.Sizeof(s) + _ = unsafe.Sizeof(t /* ERROR "too large" */ ) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59207.go b/go/src/internal/types/testdata/fixedbugs/issue59207.go new file mode 100644 index 0000000000000000000000000000000000000000..59b36e243dfb4d20e039278fc363ae138c568d70 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59207.go @@ -0,0 +1,12 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type E [1 << 32]byte + +var a [1 << 32]E // size of a must not overflow to 0 +var _ = unsafe.Sizeof(a /* ERROR "too large" */ ) diff --git a/go/src/internal/types/testdata/fixedbugs/issue59209.go b/go/src/internal/types/testdata/fixedbugs/issue59209.go new file mode 100644 index 0000000000000000000000000000000000000000..870ae528647c905b968dedf55f2cc76110f5ff38 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59209.go @@ -0,0 +1,11 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type ( + _ [1 /* ERROR "invalid array length" */ << 100]int + _ [1.0]int + _ [1.1 /* ERROR "must be integer" */ ]int +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue59338a.go b/go/src/internal/types/testdata/fixedbugs/issue59338a.go new file mode 100644 index 0000000000000000000000000000000000000000..34864dcd30bbcd718375e5da99fcfb8fdc68fc20 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59338a.go @@ -0,0 +1,21 @@ +// -lang=go1.20 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func g[P any](P) {} +func h[P, Q any](P) Q { panic(0) } + +var _ func(int) = g /* ERROR "implicitly instantiated function in assignment requires go1.21 or later" */ +var _ func(int) string = h[ /* ERROR "partially instantiated function in assignment requires go1.21 or later" */ int] + +func f1(func(int)) {} +func f2(int, func(int)) {} + +func _() { + f1(g /* ERROR "implicitly instantiated function as argument requires go1.21 or later" */) + f2(0, g /* ERROR "implicitly instantiated function as argument requires go1.21 or later" */) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59338b.go b/go/src/internal/types/testdata/fixedbugs/issue59338b.go new file mode 100644 index 0000000000000000000000000000000000000000..1a5530aeaefd5bda5741313552acd1bd631ad408 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59338b.go @@ -0,0 +1,19 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func g[P any](P) {} +func h[P, Q any](P) Q { panic(0) } + +var _ func(int) = g +var _ func(int) string = h[int] + +func f1(func(int)) {} +func f2(int, func(int)) {} + +func _() { + f1(g) + f2(0, g) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59371.go b/go/src/internal/types/testdata/fixedbugs/issue59371.go new file mode 100644 index 0000000000000000000000000000000000000000..d5b4db6a858325aae24c645b0db6312af5d650b6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59371.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var m map[int]int + +func _() { + _, ok /* ERROR "undefined: ok" */ = m[0] // must not crash +} + +func _() { + var ok = undef /* ERROR "undefined: undef" */ + x, ok := m[0] // must not crash + _, _ = x, ok +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59639.go b/go/src/internal/types/testdata/fixedbugs/issue59639.go new file mode 100644 index 0000000000000000000000000000000000000000..1117668e98852c90e895cde7bed499b15590dc8f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59639.go @@ -0,0 +1,11 @@ +// -lang=go1.17 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P /* ERROR "requires go1.18" */ interface{}](P) {} + +var v func(int) = f /* ERROR "requires go1.18" */ diff --git a/go/src/internal/types/testdata/fixedbugs/issue59740.go b/go/src/internal/types/testdata/fixedbugs/issue59740.go new file mode 100644 index 0000000000000000000000000000000000000000..31cd03b3af161fd8ad0cc1eff1127f1907a21b24 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59740.go @@ -0,0 +1,25 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type F[T any] func(func(F[T])) + +func f(F[int]) {} +func g[T any](F[T]) {} + +func _() { + g(f /* ERROR "type func(F[int]) of f does not match F[T] (cannot infer T)" */) // type inference/unification must not panic +} + +// original test case from issue + +type List[T any] func(T, func(T, List[T]) T) T + +func nil[T any](n T, _ List[T]) T { return n } +func cons[T any](h T, t List[T]) List[T] { return func(n T, f func(T, List[T]) T) T { return f(h, t) } } + +func nums[T any](t T) List[T] { + return cons(t, cons(t, nil /* ERROR "type func(n T, _ List[T]) T of nil[T] does not match inferred type List[T] for List[T]" */ [T])) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59848.go b/go/src/internal/types/testdata/fixedbugs/issue59848.go new file mode 100644 index 0000000000000000000000000000000000000000..51da7475e5203101751b0b7a14e1f8a0654cce31 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59848.go @@ -0,0 +1,10 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T struct{} +type I interface{ M() } +var _ I = T /* ERROR "missing method M" */ {} // must not crash +func (T) m() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59890.go b/go/src/internal/types/testdata/fixedbugs/issue59890.go new file mode 100644 index 0000000000000000000000000000000000000000..ed7afd939aacf71859dad5ab2a2033884338ebce --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59890.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { g /* ERROR "cannot infer T" */ () } + +func g[T any]() (_ /* ERROR "cannot use _ as value or type" */, int) { panic(0) } + +// test case from issue + +var _ = append(f /* ERROR "cannot infer T" */ ()()) + +func f[T any]() (_ /* ERROR "cannot use _" */, _ /* ERROR "cannot use _" */, int) { + panic("not implemented") +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59953.go b/go/src/internal/types/testdata/fixedbugs/issue59953.go new file mode 100644 index 0000000000000000000000000000000000000000..b10ced749b4a6a580ee925dfc7d6aa73921bcfd4 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59953.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { f(g) } +func f[P any](P) {} +func g[Q int](Q) {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59956.go b/go/src/internal/types/testdata/fixedbugs/issue59956.go new file mode 100644 index 0000000000000000000000000000000000000000..646b50e7716e7b06689cb3bd4a91d729d97def6e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59956.go @@ -0,0 +1,47 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1(func(int)) +func f2(func(int), func(string)) +func f3(func(int), func(string), func(float32)) + +func g1[P any](P) {} + +func _() { + f1(g1) + f2(g1, g1) + f3(g1, g1, g1) +} + +// More complex examples + +func g2[P any](P, P) {} +func h3[P any](func(P), func(P), func() P) {} +func h4[P, Q any](func(P), func(P, Q), func() Q, func(P, Q)) {} + +func r1() int { return 0 } + +func _() { + h3(g1, g1, r1) + h4(g1, g2, r1, g2) +} + +// Variadic cases + +func f(func(int)) +func g[P any](P) {} + +func d[P any](...func(P)) {} + +func _() { + d /* ERROR "cannot infer P" */ () + d(f) + d(f, g) + d(f, g, g) + d /* ERROR "cannot infer P" */ (g, g, g) + d(g, g, f) + d(g, f, g, f) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue59958.go b/go/src/internal/types/testdata/fixedbugs/issue59958.go new file mode 100644 index 0000000000000000000000000000000000000000..4a4b4dc921d5f7fce1e356d376b34cee4b7f6f84 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue59958.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f(func(int) string) {} + +func g2[P, Q any](P) Q { var q Q; return q } +func g3[P, Q, R any](P) R { var r R; return r } + +func _() { + f(g2) + f(g2[int]) + f(g2[int, string]) + + f(g3[int, bool]) + f(g3[int, bool, string]) + + var _ func(int) string = g2 + var _ func(int) string = g2[int] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60346.go b/go/src/internal/types/testdata/fixedbugs/issue60346.go new file mode 100644 index 0000000000000000000000000000000000000000..6dc057b178454b2529997908135002aca9f55e0d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60346.go @@ -0,0 +1,17 @@ +// -lang=go1.20 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func F[P any, Q *P](p P) {} + +var _ = F[int] + +func G[R any](func(R)) {} + +func _() { + G(F[int]) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60377.go b/go/src/internal/types/testdata/fixedbugs/issue60377.go new file mode 100644 index 0000000000000000000000000000000000000000..17a9deb6d170106b067e132887fc64bdf0cfc1b2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60377.go @@ -0,0 +1,88 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// The type parameter P is not used in interface T1. +// T1 is a defined parameterized interface type which +// can be assigned to any other interface with the same +// methods. We cannot infer a type argument in this case +// because any type would do. + +type T1[P any] interface{ m() } + +func g[P any](T1[P]) {} + +func _() { + var x T1[int] + g /* ERROR "cannot infer P" */ (x) + g[int](x) // int is ok for P + g[string](x) // string is also ok for P! +} + +// This is analogous to the above example, +// but uses two interface types of the same structure. + +type T2[P any] interface{ m() } + +func _() { + var x T2[int] + g /* ERROR "cannot infer P" */ (x) + g[int](x) // int is ok for P + g[string](x) // string is also ok for P! +} + +// Analogous to the T2 example but using an unparameterized interface T3. + +type T3 interface{ m() } + +func _() { + var x T3 + g /* ERROR "cannot infer P" */ (x) + g[int](x) // int is ok for P + g[string](x) // string is also ok for P! +} + +// The type parameter P is not used in struct S. +// S is a defined parameterized (non-interface) type which can only +// be assigned to another type S with the same type argument. +// Therefore we can infer a type argument in this case. + +type S[P any] struct{} + +func g4[P any](S[P]) {} + +func _() { + var x S[int] + g4(x) // we can infer int for P + g4[int](x) // int is the correct type argument + g4[string](x /* ERROR "cannot use x (variable of struct type S[int]) as S[string] value in argument to g4[string]" */) +} + +// This is similar to the first example but here T1 is a component +// of a func type. In this case types must match exactly: P must +// match int. + +func g5[P any](func(T1[P])) {} + +func _() { + var f func(T1[int]) + g5(f) + g5[int](f) + g5[string](f /* ERROR "cannot use f (variable of type func(T1[int])) as func(T1[string]) value in argument to g5[string]" */) +} + +// This example would fail if we were to infer the type argument int for P +// exactly because any type argument would be ok for the first argument. +// Choosing the wrong type would cause the second argument to not match. + +type T[P any] interface{} + +func g6[P any](T[P], P) {} + +func _() { + var x T[int] + g6(x, 1.2) + g6(x, "") +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60434.go b/go/src/internal/types/testdata/fixedbugs/issue60434.go new file mode 100644 index 0000000000000000000000000000000000000000..68aa7c2fdfd11bc39161918af40b4a457f638547 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60434.go @@ -0,0 +1,17 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that there are no type inference errors +// if function arguments are invalid. + +package p + +func f[S any](S) {} + +var s struct{ x int } + +func _() { + f(s.y /* ERROR "s.y undefined" */) + f(1 /* ERROR "invalid operation: 1 / s (mismatched types untyped int and struct{x int})" */ / s) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60460.go b/go/src/internal/types/testdata/fixedbugs/issue60460.go new file mode 100644 index 0000000000000000000000000000000000000000..a9cb3d91e735ae5bd201d7f860177e1b26db7533 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60460.go @@ -0,0 +1,88 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// Simplified (representative) test case. + +func _() { + f(R1{}) +} + +func f[T any](R[T]) {} + +type R[T any] interface { + m(R[T]) +} + +type R1 struct{} + +func (R1) m(R[int]) {} + +// Test case from issue. + +func _() { + r := newTestRules() + NewSet(r) + r2 := newTestRules2() + NewSet(r2) +} + +type Set[T any] struct { + rules Rules[T] +} + +func NewSet[T any](rules Rules[T]) Set[T] { + return Set[T]{ + rules: rules, + } +} + +func (s Set[T]) Copy() Set[T] { + return NewSet(s.rules) +} + +type Rules[T any] interface { + Hash(T) int + Equivalent(T, T) bool + SameRules(Rules[T]) bool +} + +type testRules struct{} + +func newTestRules() Rules[int] { + return testRules{} +} + +func (r testRules) Hash(val int) int { + return val % 16 +} + +func (r testRules) Equivalent(val1 int, val2 int) bool { + return val1 == val2 +} + +func (r testRules) SameRules(other Rules[int]) bool { + _, ok := other.(testRules) + return ok +} + +type testRules2 struct{} + +func newTestRules2() Rules[string] { + return testRules2{} +} + +func (r testRules2) Hash(val string) int { + return 16 +} + +func (r testRules2) Equivalent(val1 string, val2 string) bool { + return val1 == val2 +} + +func (r testRules2) SameRules(other Rules[string]) bool { + _, ok := other.(testRules2) + return ok +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60500.go b/go/src/internal/types/testdata/fixedbugs/issue60500.go new file mode 100644 index 0000000000000000000000000000000000000000..be8ccaf94f615ed7112a95040521dde465adf56d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60500.go @@ -0,0 +1,11 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + log("This is a test %v" /* ERROR "cannot use \"This is a test %v\" (untyped string constant) as bool value in argument to log" */, "foo") +} + +func log(enabled bool, format string, args ...any) diff --git a/go/src/internal/types/testdata/fixedbugs/issue60542.go b/go/src/internal/types/testdata/fixedbugs/issue60542.go new file mode 100644 index 0000000000000000000000000000000000000000..b617c2b57e46d43367be32a2c5f387be0daef0eb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60542.go @@ -0,0 +1,12 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func Clip[S ~[]E, E any](s S) S { + return s +} + +var versions func() +var _ = Clip /* ERROR "in call to Clip, S (type func()) does not satisfy ~[]E" */ (versions) diff --git a/go/src/internal/types/testdata/fixedbugs/issue60556.go b/go/src/internal/types/testdata/fixedbugs/issue60556.go new file mode 100644 index 0000000000000000000000000000000000000000..77e5034730cf51cd259bdcda6f8f3fa76d62af5c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60556.go @@ -0,0 +1,19 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type I[T any] interface { + m(I[T]) +} + +type S[T any] struct{} + +func (S[T]) m(I[T]) {} + +func f[T I[E], E any](T) {} + +func _() { + f(S[int]{}) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60562.go b/go/src/internal/types/testdata/fixedbugs/issue60562.go new file mode 100644 index 0000000000000000000000000000000000000000..c08bbf34fe51b3028f7266c8250a5147b877be21 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60562.go @@ -0,0 +1,61 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S[T any] struct{} + +func (S[T]) m(T) {} + +func f0[T any](chan S[T]) {} + +func _() { + var x chan interface{ m(int) } + f0(x /* ERROR "type chan interface{m(int)} of x does not match chan S[T] (cannot infer T)" */) +} + +// variants of the theme + +func f1[T any]([]S[T]) {} + +func _() { + var x []interface{ m(int) } + f1(x /* ERROR "type []interface{m(int)} of x does not match []S[T] (cannot infer T)" */) +} + +type I[T any] interface { + m(T) +} + +func f2[T any](func(I[T])) {} + +func _() { + var x func(interface{ m(int) }) + f2(x /* ERROR "type func(interface{m(int)}) of x does not match func(I[T]) (cannot infer T)" */) +} + +func f3[T any](func(I[T])) {} + +func _() { + var x func(I[int]) + f3(x) // but this is correct: I[T] and I[int] can be made identical with T == int +} + +func f4[T any]([10]I[T]) {} + +func _() { + var x [10]interface{ I[int] } + f4(x /* ERROR "type [10]interface{I[int]} of x does not match [10]I[T] (cannot infer T)" */) +} + +func f5[T any](I[T]) {} + +func _() { + var x interface { + m(int) + n() + } + f5(x) + f5[int](x) // ok +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60688.go b/go/src/internal/types/testdata/fixedbugs/issue60688.go new file mode 100644 index 0000000000000000000000000000000000000000..61b9f915106db8bc09dde61d89d851a795f3515e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60688.go @@ -0,0 +1,16 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type String string + +func g[P any](P, string) {} + +// String and string are not identical and thus must not unify +// (they are element types of the func type and therefore must +// be identical to match). +// The result is an error from type inference, rather than an +// error from an assignment mismatch. +var f func(int, String) = g // ERROR "inferred type func(int, string) for func(P, string) does not match type func(int, String) of f" diff --git a/go/src/internal/types/testdata/fixedbugs/issue60747.go b/go/src/internal/types/testdata/fixedbugs/issue60747.go new file mode 100644 index 0000000000000000000000000000000000000000..6587a4e55788e129a61fc1c93a5438f9981044b6 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60747.go @@ -0,0 +1,13 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P any](P) P { panic(0) } + +var v func(string) int = f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of v" + +func _() func(string) int { + return f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of result variable" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60906.go b/go/src/internal/types/testdata/fixedbugs/issue60906.go new file mode 100644 index 0000000000000000000000000000000000000000..2744e894555fac684a52f5dd86d7b470314c9ce7 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60906.go @@ -0,0 +1,11 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + var x int + var f func() []int + _ = f /* ERROR "cannot index f" */ [x] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue60933.go b/go/src/internal/types/testdata/fixedbugs/issue60933.go new file mode 100644 index 0000000000000000000000000000000000000000..9b10237e5dc474d05ac2345cde929fc524bdf32c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60933.go @@ -0,0 +1,67 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import ( + "io" + "os" +) + +func g[T any](...T) {} + +// Interface and non-interface types do not match. +func _() { + var file *os.File + g(file, io /* ERROR "type io.Writer of io.Discard does not match inferred type *os.File for T" */ .Discard) + g(file, os.Stdout) +} + +func _() { + var a *os.File + var b any + g(a, a) + g(a, b /* ERROR "type any of b does not match inferred type *os.File for T" */) +} + +var writer interface { + Write(p []byte) (n int, err error) +} + +func _() { + var file *os.File + g(file, writer /* ERROR "type interface{Write(p []byte) (n int, err error)} of writer does not match inferred type *os.File for T" */) + g(writer, file /* ERROR "type *os.File of file does not match inferred type interface{Write(p []byte) (n int, err error)} for T" */) +} + +// Different named interface types do not match. +func _() { + g(io.ReadWriter(nil), io.ReadWriter(nil)) + g(io.ReadWriter(nil), io /* ERROR "does not match" */ .Writer(nil)) + g(io.Writer(nil), io /* ERROR "does not match" */ .ReadWriter(nil)) +} + +// Named and unnamed interface types match if they have the same methods. +func _() { + g(io.Writer(nil), writer) + g(io.ReadWriter(nil), writer /* ERROR "does not match" */ ) +} + +// There must be no order dependency for named and unnamed interfaces. +func f[T interface{ m(T) }](a, b T) {} + +type F interface { + m(F) +} + +func _() { + var i F + var j interface { + m(F) + } + + // order doesn't matter + f(i, j) + f(j, i) +} \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue60946.go b/go/src/internal/types/testdata/fixedbugs/issue60946.go new file mode 100644 index 0000000000000000000000000000000000000000..a66254b6d05d30ac7a88cba7a0b1a92efdf24e5f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue60946.go @@ -0,0 +1,38 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type Tn interface{ m() } +type T1 struct{} +type T2 struct{} + +func (*T1) m() {} +func (*T2) m() {} + +func g[P any](...P) {} + +func _() { + var t interface{ m() } + var tn Tn + var t1 *T1 + var t2 *T2 + + // these are ok (interface types only) + g(t, t) + g(t, tn) + g(tn, t) + g(tn, tn) + + // these are not ok (interface and non-interface types) + g(t, t1 /* ERROR "does not match" */) + g(t1, t /* ERROR "does not match" */) + g(tn, t1 /* ERROR "does not match" */) + g(t1, tn /* ERROR "does not match" */) + + g(t, t1 /* ERROR "does not match" */, t2) + g(t1, t2 /* ERROR "does not match" */, t) + g(tn, t1 /* ERROR "does not match" */, t2) + g(t1, t2 /* ERROR "does not match" */, tn) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue61486.go b/go/src/internal/types/testdata/fixedbugs/issue61486.go new file mode 100644 index 0000000000000000000000000000000000000000..b12a800f0d9e84003e265fb158a432c08646d8e9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue61486.go @@ -0,0 +1,9 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _(s uint) { + _ = min(1 << s) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue61685.go b/go/src/internal/types/testdata/fixedbugs/issue61685.go new file mode 100644 index 0000000000000000000000000000000000000000..b88b222eb9e5d196c37bed9454a7e99e63541213 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue61685.go @@ -0,0 +1,15 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T any](x any) { + f /* ERROR "T (type I[T]) does not satisfy I[T] (wrong type for method m)" */ (x.(I[T])) +} + +func f[T I[T]](T) {} + +type I[T any] interface { + m(T) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue61822.go b/go/src/internal/types/testdata/fixedbugs/issue61822.go new file mode 100644 index 0000000000000000000000000000000000000000..0a91ebb7b25c66f7f69ba8ad96ee97f809706b9c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue61822.go @@ -0,0 +1,19 @@ +// -lang=go1.19 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.20 + +package p + +type I[P any] interface { + ~string | ~int + Error() P +} + +func _[P I[string]]() { + var x P + var _ error = x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue61879.go b/go/src/internal/types/testdata/fixedbugs/issue61879.go new file mode 100644 index 0000000000000000000000000000000000000000..542bc2d68a1643ec00c8caa8d2372773265a0ed9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue61879.go @@ -0,0 +1,57 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "fmt" + +type Interface[T any] interface { + m(Interface[T]) +} + +func f[S []Interface[T], T any](S) {} + +func _() { + var s []Interface[int] + f(s) // panic here +} + +// Larger example from issue + +type InterfaceA[T comparable] interface { + setData(string) InterfaceA[T] +} + +type ImplA[T comparable] struct { + data string + args []any +} + +func NewInterfaceA[T comparable](args ...any) InterfaceA[T] { + return &ImplA[T]{ + data: fmt.Sprintf("%v", args...), + args: args, + } +} + +func (k *ImplA[T]) setData(data string) InterfaceA[T] { + k.data = data + return k +} + +func Foo[M ~map[InterfaceA[T]]V, T comparable, V any](m M) { + // DO SOMETHING HERE + return +} + +func Bar() { + keys := make([]InterfaceA[int], 0, 10) + m := make(map[InterfaceA[int]]int) + for i := 0; i < 10; i++ { + keys = append(keys, NewInterfaceA[int](i)) + m[keys[i]] = i + } + + Foo(m) // panic here +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue61903.go b/go/src/internal/types/testdata/fixedbugs/issue61903.go new file mode 100644 index 0000000000000000000000000000000000000000..8a6fcd9529193554715c54608f05d56f95c78c5c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue61903.go @@ -0,0 +1,20 @@ +// -lang=go1.20 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] interface{} + +func f1[P any](T[P]) {} +func f2[P any](T[P], P) {} + +func _() { + var t T[int] + f1(t) + + var s string + f2(t, s /* ERROR "type string of s does not match inferred type int for P" */) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue62157.go b/go/src/internal/types/testdata/fixedbugs/issue62157.go new file mode 100644 index 0000000000000000000000000000000000000000..67a110df3176049b81ed61eb62c6bb2094949aed --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue62157.go @@ -0,0 +1,128 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[T any](...T) T { var x T; return x } + +// Test case 1 + +func _() { + var a chan string + var b <-chan string + f(a, b) + f(b, a) +} + +// Test case 2 + +type F[T any] func(T) bool + +func g[T any](T) F[<-chan T] { return nil } + +func f1[T any](T, F[T]) {} +func f2[T any](F[T], T) {} + +func _() { + var ch chan string + f1(ch, g("")) + f2(g(""), ch) +} + +// Test case 3: named and directional types combined + +func _() { + type namedA chan int + type namedB chan<- int + + var a chan int + var A namedA + var b chan<- int + var B namedB + + // Defined types win over channel types irrespective of channel direction. + f(A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */) + f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A) + + f(a, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A) + f(a, A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */) + f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A, a) + f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, a, A) + f(A, a, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */) + f(A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, a) + + // Unnamed directed channels win over bidirectional channels. + b = f(a, b) + b = f(b, a) + + // Defined directed channels win over defined bidirectional channels. + A = f(A, a) + A = f(a, A) + B = f(B, b) + B = f(b, B) + + f(a, b, B) + f(a, B, b) + f(b, B, a) + f(b, a, B) + f(B, a, b) + f(B, b, a) + + // Differently named channel types conflict irrespective of channel direction. + f(A, B /* ERROR "type namedB of B does not match inferred type namedA for T" */) + f(B, A /* ERROR "type namedA of A does not match inferred type namedB for T" */) + + // Ensure that all combinations of directional and + // bidirectional channels with a named directional + // channel lead to the correct (named) directional + // channel. + B = f(a, b) + B = f(a, B) + B = f(b, a) + B = f(B, a) + + B = f(a, b, B) + B = f(a, B, b) + B = f(b, B, a) + B = f(b, a, B) + B = f(B, a, b) + B = f(B, b, a) + + // verify type error + A = f /* ERROR "cannot use f(B, b, a) (value of chan type namedB) as namedA value in assignment" */ (B, b, a) +} + +// Test case 4: some more combinations + +func _() { + type A chan int + type B chan int + type C = chan int + type D = chan<- int + + var a A + var b B + var c C + var d D + + f(a, b /* ERROR "type B of b does not match inferred type A for T" */, c) + f(c, a, b /* ERROR "type B of b does not match inferred type A for T" */) + f(a, b /* ERROR "type B of b does not match inferred type A for T" */, d) + f(d, a, b /* ERROR "type B of b does not match inferred type A for T" */) +} + +// Simplified test case from issue + +type Matcher[T any] func(T) bool + +func Produces[T any](T) Matcher[<-chan T] { return nil } + +func Assert1[T any](Matcher[T], T) {} +func Assert2[T any](T, Matcher[T]) {} + +func _() { + var ch chan string + Assert1(Produces(""), ch) + Assert2(ch, Produces("")) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue63563.go b/go/src/internal/types/testdata/fixedbugs/issue63563.go new file mode 100644 index 0000000000000000000000000000000000000000..b8134852765b5e057b79680b1b51247b6999eddf --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue63563.go @@ -0,0 +1,37 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +var ( + _ = int8(1 /* ERROR "constant 255 overflows int8" */ <<8 - 1) + _ = int16(1 /* ERROR "constant 65535 overflows int16" */ <<16 - 1) + _ = int32(1 /* ERROR "constant 4294967295 overflows int32" */ <<32 - 1) + _ = int64(1 /* ERROR "constant 18446744073709551615 overflows int64" */ <<64 - 1) + + _ = uint8(1 /* ERROR "constant 256 overflows uint8" */ << 8) + _ = uint16(1 /* ERROR "constant 65536 overflows uint16" */ << 16) + _ = uint32(1 /* ERROR "constant 4294967296 overflows uint32" */ << 32) + _ = uint64(1 /* ERROR "constant 18446744073709551616 overflows uint64" */ << 64) +) + +func _[P int8 | uint8]() { + _ = P(0) + _ = P(1 /* ERROR "constant 255 overflows int8 (in P)" */ <<8 - 1) +} + +func _[P int16 | uint16]() { + _ = P(0) + _ = P(1 /* ERROR "constant 65535 overflows int16 (in P)" */ <<16 - 1) +} + +func _[P int32 | uint32]() { + _ = P(0) + _ = P(1 /* ERROR "constant 4294967295 overflows int32 (in P)" */ <<32 - 1) +} + +func _[P int64 | uint64]() { + _ = P(0) + _ = P(1 /* ERROR "constant 18446744073709551615 overflows int64 (in P)" */ <<64 - 1) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue64406.go b/go/src/internal/types/testdata/fixedbugs/issue64406.go new file mode 100644 index 0000000000000000000000000000000000000000..54b959dbba83be01af23546308ec42c3491da919 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue64406.go @@ -0,0 +1,23 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package issue64406 + +import ( + "unsafe" +) + +func sliceData[E any, S ~[]E](s S) *E { + return unsafe.SliceData(s) +} + +func slice[E any, S ~*E](s S) []E { + return unsafe.Slice(s, 0) +} + +func f() { + s := []uint32{0} + _ = sliceData(s) + _ = slice(&s) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue64704.go b/go/src/internal/types/testdata/fixedbugs/issue64704.go new file mode 100644 index 0000000000000000000000000000000000000000..c8e9056cdd5251a7580dc6e67ac330f66821ee08 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue64704.go @@ -0,0 +1,12 @@ +// -lang=go1.21 + +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + for range 10 /* ERROR "cannot range over 10 (untyped int constant): requires go1.22 or later" */ { + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue65344.go b/go/src/internal/types/testdata/fixedbugs/issue65344.go new file mode 100644 index 0000000000000000000000000000000000000000..4db97c04ffb372c89a3879500698c0dde5bf81c0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue65344.go @@ -0,0 +1,19 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T1 C /* ERROR "C (constant) is not a type" */ + +// TODO(gri) try to avoid this follow-on error +const C = T1(0 /* ERROR "cannot convert 0 (untyped int constant) to type T1" */) + +type T2 V /* ERROR "V (package-level variable) is not a type" */ + +var V T2 + +func _() { + // don't produce errors here + _ = C + V +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue65711.go b/go/src/internal/types/testdata/fixedbugs/issue65711.go new file mode 100644 index 0000000000000000000000000000000000000000..2c26a9208b2848122bc05117f39735b1d17bf262 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue65711.go @@ -0,0 +1,25 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[P any] [1]P + +type B[P any] A[P] + +type C /* ERROR "invalid recursive type" */ B[C] + +// test case from issue + +type Foo[T any] struct { + baz T +} + +type Bar[T any] struct { + foo Foo[T] +} + +type Baz /* ERROR "invalid recursive type" */ struct { + bar Bar[Baz] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue65854.go b/go/src/internal/types/testdata/fixedbugs/issue65854.go new file mode 100644 index 0000000000000000000000000000000000000000..744777a94f84575a0800c0089d3882c0f95b9c38 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue65854.go @@ -0,0 +1,13 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A = int + +type T[P any] *A + +var _ T[int] diff --git a/go/src/internal/types/testdata/fixedbugs/issue66064.go b/go/src/internal/types/testdata/fixedbugs/issue66064.go new file mode 100644 index 0000000000000000000000000000000000000000..d4a361754be80d6acba88824318be9e79f340fae --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue66064.go @@ -0,0 +1,15 @@ +// -lang=go1.16 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.21 + +package main + +import "slices" + +func main() { + _ = slices.Clone([]string{}) // no error should be reported here +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue66285.go b/go/src/internal/types/testdata/fixedbugs/issue66285.go new file mode 100644 index 0000000000000000000000000000000000000000..4af76f05da8e41a53fed50217f4af57eb83c447f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue66285.go @@ -0,0 +1,32 @@ +// -lang=go1.13 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "io" + +// A "duplicate method" error should be reported for +// all these interfaces, irrespective of which package +// the embedded Reader is coming from. + +type _ interface { + Reader + Reader // ERROR "duplicate method Read" +} + +type Reader interface { + Read(p []byte) (n int, err error) +} + +type _ interface { + io.Reader + Reader // ERROR "duplicate method Read" +} + +type _ interface { + io.Reader + io /* ERROR "duplicate method Read" */ .Reader +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue66323.go b/go/src/internal/types/testdata/fixedbugs/issue66323.go new file mode 100644 index 0000000000000000000000000000000000000000..482c094ddeea31b0eec4bfeb57a8023decdf1b1b --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue66323.go @@ -0,0 +1,17 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "time" + +// This type declaration must not cause problems with +// the type validity checker. + +type S[T any] struct { + a T + b time.Time +} + +var _ S[time.Time] diff --git a/go/src/internal/types/testdata/fixedbugs/issue66751.go b/go/src/internal/types/testdata/fixedbugs/issue66751.go new file mode 100644 index 0000000000000000000000000000000000000000..5a64b4dcc172224f97516a35a908ec9662599ef9 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue66751.go @@ -0,0 +1,62 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type S struct{} + +func (*S) m(int) {} + +func f[A interface { + ~*B + m(C) +}, B, C any]() { +} + +var _ = f[*S] // must be able to infer all remaining type arguments + +// original test case from issue + +type ptrTo[A any] interface{ ~*A } +type hasFoo[A any] interface{ foo(A) } +type both[A, B any] interface { + ptrTo[A] + hasFoo[B] +} + +type fooer[A any] struct{} + +func (f *fooer[A]) foo(A) {} + +func withPtr[A ptrTo[B], B any]() {} +func withFoo[A hasFoo[B], B any]() {} +func withBoth[A both[B, C], B, C any]() {} + +func _() { + withPtr[*fooer[int]]() // ok + withFoo[*fooer[int]]() // ok + withBoth[*fooer[int]]() // should be able to infer C +} + +// related test case reported in issue + +type X struct{} + +func (x X) M() int { return 42 } + +func CallM1[T interface{ M() R }, R any](t T) R { + return t.M() +} + +func CallM2[T interface { + X + M() R +}, R any](t T) R { + return t.M() +} + +func _() { + CallM1(X{}) // ok + CallM2(X{}) // should be able to infer R +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue66878.go b/go/src/internal/types/testdata/fixedbugs/issue66878.go new file mode 100644 index 0000000000000000000000000000000000000000..bd6315f9c38255512e5de98feee5164064779395 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue66878.go @@ -0,0 +1,21 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[T bool](ch chan T) { + var _, _ T = <-ch +} + +// offending code snippets from issue + +func _[T ~bool](ch <-chan T) { + var x, ok T = <-ch + println(x, ok) +} + +func _[T ~bool](m map[int]T) { + var x, ok T = m[0] + println(x, ok) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue67547.go b/go/src/internal/types/testdata/fixedbugs/issue67547.go new file mode 100644 index 0000000000000000000000000000000000000000..1c2f66b6b99172a791ca80d1a143643acc64595a --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue67547.go @@ -0,0 +1,96 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P int]() { + type A = P + _ = A(0) // don't crash with this conversion +} + +func _[P []int]() { + type A = P + _ = make(A, 10) // don't report an error for A +} + +func _[P string]() { + var t []byte + type A = P + var s A + copy(t, s) // don't report an error for s +} + +func _[P map[int]int]() { + type A = P + var m A + clear(m) // don't report an error for m +} + +type S1 struct { + x int "S1.x" +} + +type S2 struct { + x int "S2.x" +} + +func _[P1 S1, P2 S2]() { + type A = P1 + var p A + _ = P2(p) // conversion must be valid +} + +func _[P1 S1, P2 S2]() { + var p P1 + type A = P2 + _ = A(p) // conversion must be valid +} + +func _[P int | string]() { + var p P + type A = int + // preserve target type name A in error messages when using Alias types + // (test are run with and without Alias types enabled, so we need to + // keep both A and int in the error message) + _ = A(p /* ERRORx `cannot convert string \(in P\) to type (A|int)` */) +} + +func _[P struct{ x int }]() { + var x struct{ x int } + type A = P + var _ A = x // assignment must be valid +} + +func _[P struct{ x int }]() { + type A = P + var x A + var _ struct{ x int } = x // assignment must be valid +} + +func _[P []int | struct{}]() { + type A = []int + var a A + var p P + // preserve target type name A in error messages when using Alias types + a = p // ERRORx `cannot assign struct{} \(in P\) to (A|\[\]int)` + _ = a +} + +func _[P any]() { + type A = P + var x A + // keep "constrained by" for aliased type parameters in error messages + var _ int = x // ERRORx `cannot use x \(variable of type (A|P) constrained by any\) as int value in variable declaration` +} + +// Test case for go.dev/issue/67540. +func _() { + type ( + S struct{} + A = *S + T S + ) + var p A + _ = (*T)(p) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue67628.go b/go/src/internal/types/testdata/fixedbugs/issue67628.go new file mode 100644 index 0000000000000000000000000000000000000000..dff1bee4a0242c56d62c6ed078843f89c1958282 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue67628.go @@ -0,0 +1,17 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f[P any](x P) P { return x } + +func _() { + type A = int + var a A + b := f(a) // type of b is A + // error should report type of b as A, not int + _ = b /* ERROR "mismatched types A and untyped string" */ + "foo" +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue67683.go b/go/src/internal/types/testdata/fixedbugs/issue67683.go new file mode 100644 index 0000000000000000000000000000000000000000..c9ad5f6788bec418c648939d90164cb4fc873671 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue67683.go @@ -0,0 +1,19 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[P any] func() + +// alias signature types +type B[P any] = func() +type C[P any] = B[P] + +var _ = A /* ERROR "cannot use generic type A without instantiation" */ (nil) + +// generic alias signature types must be instantiated before use +var _ = B /* ERROR "cannot use generic type B without instantiation" */ (nil) +var _ = C /* ERROR "cannot use generic type C without instantiation" */ (nil) diff --git a/go/src/internal/types/testdata/fixedbugs/issue67872.go b/go/src/internal/types/testdata/fixedbugs/issue67872.go new file mode 100644 index 0000000000000000000000000000000000000000..3d96613142b113afbec12595a8d93f423125cfe1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue67872.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A = uint8 +type E uint8 + +func f[P ~A](P) {} + +func g(e E) { + f(e) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue67962.go b/go/src/internal/types/testdata/fixedbugs/issue67962.go new file mode 100644 index 0000000000000000000000000000000000000000..4dbcd31288c51addfdc1ea365f6494f193551b76 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue67962.go @@ -0,0 +1,26 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +// No `"fmt" imported and not used` error below. +// The switch cases must be typechecked even +// though the switch expression is invalid. + +import "fmt" + +func _() { + x := 1 + for e := range x.m /* ERROR "x.m undefined (type int has no field or method m)" */ () { + switch e.(type) { + case int: + fmt.Println() + } + } + + switch t := x /* ERROR "not an interface" */ .(type) { + case int, string: + _ = t + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue68162.go b/go/src/internal/types/testdata/fixedbugs/issue68162.go new file mode 100644 index 0000000000000000000000000000000000000000..8efd8a66dff4be89d6bad68a5ea534d55cdb622c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue68162.go @@ -0,0 +1,24 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +type N[B N[B]] interface { + Add(B) B +} + +func Add[P N[P]](x, y P) P { + return x.Add(y) +} + +type MyInt int + +func (x MyInt) Add(y MyInt) MyInt { + return x + y +} + +func main() { + var x, y MyInt = 2, 3 + println(Add(x, y)) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue68184.go b/go/src/internal/types/testdata/fixedbugs/issue68184.go new file mode 100644 index 0000000000000000000000000000000000000000..9c77365aa9a527ac2c0be6b1f4ea2341da599c6d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue68184.go @@ -0,0 +1,38 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type VeryLongStruct struct { + A1 int + A2 int + A3 int + A4 int + A5 int + A6 int + A7 int + A8 int + A9 int + A10 int + A11 int + A12 int + A13 int + A14 int + A15 int + A16 int + A17 int + A18 int + A19 int + A20 int +} + +func _() { + // The error messages in both these cases should print the + // struct name rather than the struct's underlying type. + + var x VeryLongStruct + x.B2 /* ERROR "x.B2 undefined (type VeryLongStruct has no field or method B2)" */ = false + + _ = []VeryLongStruct{{B2 /* ERROR "unknown field B2 in struct literal of type VeryLongStruct" */ : false}} +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue68903.go b/go/src/internal/types/testdata/fixedbugs/issue68903.go new file mode 100644 index 0000000000000000000000000000000000000000..b1369aa0f6faa78c8b188fd5be357e1ef42d703f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue68903.go @@ -0,0 +1,24 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A = [4]int +type B = map[string]interface{} + +func _[T ~A](x T) { + _ = len(x) +} + +func _[U ~A](x U) { + _ = cap(x) +} + +func _[V ~A]() { + _ = V{} +} + +func _[W ~B](a interface{}) { + _ = a.(W)["key"] +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue68935.go b/go/src/internal/types/testdata/fixedbugs/issue68935.go new file mode 100644 index 0000000000000000000000000000000000000000..2e72468f05eb0cbb5aa8e047e6ee5d8c89e3e27f --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue68935.go @@ -0,0 +1,26 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A = struct { + F string + G int +} + +func Make[T ~A]() T { + return T{ + F: "blah", + G: 1234, + } +} + +type N struct { + F string + G int +} + +func _() { + _ = Make[N]() +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue69576.go b/go/src/internal/types/testdata/fixedbugs/issue69576.go new file mode 100644 index 0000000000000000000000000000000000000000..fc436bbfd38424e79a57ab6c52b4ae19353353b4 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue69576.go @@ -0,0 +1,11 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[P int] = struct{} + +var _ A[string /* ERROR "string does not satisfy int (string missing in int)" */] diff --git a/go/src/internal/types/testdata/fixedbugs/issue6977.go b/go/src/internal/types/testdata/fixedbugs/issue6977.go new file mode 100644 index 0000000000000000000000000000000000000000..ffe4a7464b62190701b7ec8768154e06e3154ef0 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue6977.go @@ -0,0 +1,85 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "io" + +// Alan's initial report. + +type I interface { f(); String() string } +type J interface { g(); String() string } + +type IJ1 = interface { I; J } +type IJ2 = interface { f(); g(); String() string } + +var _ = (*IJ1)(nil) == (*IJ2)(nil) // static assert that IJ1 and IJ2 are identical types + +// The canonical example. + +type ReadWriteCloser interface { io.ReadCloser; io.WriteCloser } + +// Some more cases. + +type M interface { m() } +type M32 interface { m() int32 } +type M64 interface { m() int64 } + +type U1 interface { m() } +type U2 interface { m(); M } +type U3 interface { M; m() } +type U4 interface { M; M; M } +type U5 interface { U1; U2; U3; U4 } + +type U6 interface { m(); m /* ERROR "duplicate method" */ () } +type U7 interface { M32 /* ERROR "duplicate method" */ ; m() } +type U8 interface { m(); M32 /* ERROR "duplicate method" */ } +type U9 interface { M32; M64 /* ERROR "duplicate method" */ } + +// Verify that repeated embedding of the same interface(s) +// eliminates duplicate methods early (rather than at the +// end) to prevent exponential memory and time use. +// Without early elimination, computing T29 may take dozens +// of minutes. +type ( + T0 interface { m() } + T1 interface { T0; T0 } + T2 interface { T1; T1 } + T3 interface { T2; T2 } + T4 interface { T3; T3 } + T5 interface { T4; T4 } + T6 interface { T5; T5 } + T7 interface { T6; T6 } + T8 interface { T7; T7 } + T9 interface { T8; T8 } + + // TODO(gri) Enable this longer test once we have found a solution + // for the incorrect optimization in the validType check + // (see TODO in validtype.go). + // T10 interface { T9; T9 } + // T11 interface { T10; T10 } + // T12 interface { T11; T11 } + // T13 interface { T12; T12 } + // T14 interface { T13; T13 } + // T15 interface { T14; T14 } + // T16 interface { T15; T15 } + // T17 interface { T16; T16 } + // T18 interface { T17; T17 } + // T19 interface { T18; T18 } + + // T20 interface { T19; T19 } + // T21 interface { T20; T20 } + // T22 interface { T21; T21 } + // T23 interface { T22; T22 } + // T24 interface { T23; T23 } + // T25 interface { T24; T24 } + // T26 interface { T25; T25 } + // T27 interface { T26; T26 } + // T28 interface { T27; T27 } + // T29 interface { T28; T28 } +) + +// Verify that m is present. +var x T9 // T29 +var _ = x.m diff --git a/go/src/internal/types/testdata/fixedbugs/issue69955.go b/go/src/internal/types/testdata/fixedbugs/issue69955.go new file mode 100644 index 0000000000000000000000000000000000000000..68ddf4108ce8ce41162a4669e4c6d241e09ef93c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue69955.go @@ -0,0 +1,42 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "math/big" + +type ( + S struct{} + N int + + A = S + B = int + C = N +) + +var ( + i int + s S + n N + a A + b B + c C + w big.Word +) + +const ( + _ = i // ERROR "i (variable of type int) is not constant" + _ = s // ERROR "s (variable of struct type S) is not constant" + _ = struct /* ERROR "struct{}{} (value of type struct{}) is not constant" */ {}{} + _ = n // ERROR "n (variable of int type N) is not constant" + + _ = a // ERROR "a (variable of struct type A) is not constant" + _ = b // ERROR "b (variable of int type B) is not constant" + _ = c // ERROR "c (variable of int type C) is not constant" + _ = w // ERROR "w (variable of uint type big.Word) is not constant" +) + +var _ int = w /* ERROR "cannot use w + 1 (value of uint type big.Word) as int value in variable declaration" */ + 1 diff --git a/go/src/internal/types/testdata/fixedbugs/issue70150.go b/go/src/internal/types/testdata/fixedbugs/issue70150.go new file mode 100644 index 0000000000000000000000000000000000000000..5baf4a66306b05be6fbff1edc98b9a5500af9388 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue70150.go @@ -0,0 +1,15 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + var values []int + vf(values /* ERROR "(variable of type []int) as string value" */) + vf(values...) /* ERROR "have ([]int...)\n\twant (string, ...int)" */ + vf("ab", "cd", values /* ERROR "have (string, string, []int...)\n\twant (string, ...int)" */ ...) +} + +func vf(method string, values ...int) { +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue70417.go b/go/src/internal/types/testdata/fixedbugs/issue70417.go new file mode 100644 index 0000000000000000000000000000000000000000..74bdea3b8a4156d00bb1633562e494dd589771cc --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue70417.go @@ -0,0 +1,58 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type T[P any] struct{} + +// A0 +type A0 = T[int] +type B0 = *T[int] + +func (A0 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} +func (*A0 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} +func (B0 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} + +// A1 +type A1[P any] = T[P] +type B1[P any] = *T[P] + +func (A1 /* ERROR "cannot define new methods on generic alias type A1[P any]" */ [P]) m() {} +func (*A1 /* ERROR "cannot define new methods on generic alias type A1[P any]" */ [P]) m() {} +func (B1 /* ERROR "cannot define new methods on generic alias type B1[P any]" */ [P]) m() {} + +// A2 +type A2[P any] = T[int] +type B2[P any] = *T[int] + +func (A2 /* ERROR "cannot define new methods on generic alias type A2[P any]" */ [P]) m() {} +func (*A2 /* ERROR "cannot define new methods on generic alias type A2[P any]" */ [P]) m() {} +func (B2 /* ERROR "cannot define new methods on generic alias type B2[P any]" */ [P]) m() {} + +// A3 +type A3 = T[int] +type B3 = *T[int] + +func (A3 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} +func (*A3 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} +func (B3 /* ERROR "cannot define new methods on instantiated type T[int]" */) m() {} + +// A4 +type A4 = T // ERROR "cannot use generic type T[P any] without instantiation" +type B4 = *T // ERROR "cannot use generic type T[P any] without instantiation" + +func (A4[P]) m1() {} // don't report a follow-on error on A4 +func (*A4[P]) m2() {} // don't report a follow-on error on A4 +func (B4[P]) m3() {} // don't report a follow-on error on B4 + +// instantiation in the middle of an alias chain +type S struct{} +type C0 = S +type C1[P any] = C0 +type C2 = *C1[int] + +func (C2 /* ERROR "cannot define new methods on instantiated type C1[int]" */) m() {} +func (*C2 /* ERROR "cannot define new methods on instantiated type C1[int]" */) m() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue70526.go b/go/src/internal/types/testdata/fixedbugs/issue70526.go new file mode 100644 index 0000000000000000000000000000000000000000..56b20bfc3cbe6b2f2661ddbdc573e1dde47f2420 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue70526.go @@ -0,0 +1,13 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f(...any) + +func _(x int, s []int) { + f(0, x /* ERROR "have (number, int...)\n\twant (...any)" */ ...) + f(0, s /* ERROR "have (number, []int...)\n\twant (...any)" */ ...) + f(0, 0 /* ERROR "have (number, number...)\n\twant (...any)" */ ...) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue70549.go b/go/src/internal/types/testdata/fixedbugs/issue70549.go new file mode 100644 index 0000000000000000000000000000000000000000..fa54b458eed36018c420e0951860c7c5ae52288e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue70549.go @@ -0,0 +1,15 @@ +// Copyright 2025 The Go Authors. 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 "math" + +var ( + _ = math.Sqrt + _ = math.SQrt /* ERROR "undefined: math.SQrt (but have Sqrt)" */ + _ = math.sqrt /* ERROR "name sqrt not exported by package math" */ + _ = math.Foo /* ERROR "undefined: math.Foo" */ + _ = math.foo /* ERROR "undefined: math.foo" */ +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue71131.go b/go/src/internal/types/testdata/fixedbugs/issue71131.go new file mode 100644 index 0000000000000000000000000000000000000000..8e7575b02828ded3f25ebbf1f1f63a2abb90a155 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue71131.go @@ -0,0 +1,15 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + type Bool bool + for range func /* ERROR "yield func returns user-defined boolean, not bool" */ (func() Bool) {} { + } + for range func /* ERROR "yield func returns user-defined boolean, not bool" */ (func(int) Bool) {} { + } + for range func /* ERROR "yield func returns user-defined boolean, not bool" */ (func(int, string) Bool) {} { + } +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue71198.go b/go/src/internal/types/testdata/fixedbugs/issue71198.go new file mode 100644 index 0000000000000000000000000000000000000000..479f8e2b0c4e64e6c729df370feba36d121857be --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue71198.go @@ -0,0 +1,16 @@ +// -gotypesalias=1 + +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[_ any] = any + +// This must not panic; also the error message must match the style for non-alias types, below. +func _[_ A /* ERROR "too many type arguments for type A: have 2, want 1" */ [int, string]]() {} + +type T[_ any] any + +func _[_ T /* ERROR "too many type arguments for type T: have 2, want 1" */ [int, string]]() {} diff --git a/go/src/internal/types/testdata/fixedbugs/issue71284.go b/go/src/internal/types/testdata/fixedbugs/issue71284.go new file mode 100644 index 0000000000000000000000000000000000000000..4b73087a78a19131ba355971b93d98adf3b84380 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue71284.go @@ -0,0 +1,10 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package A + +type ( + _ = A + A /* ERROR "invalid recursive type: A refers to itself" */ = A +) diff --git a/go/src/internal/types/testdata/fixedbugs/issue72936.go b/go/src/internal/types/testdata/fixedbugs/issue72936.go new file mode 100644 index 0000000000000000000000000000000000000000..eb4942c0d94fa0dca25480d175f1543742581e6e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue72936.go @@ -0,0 +1,23 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[C chan<- int | chan int](c C) { c <- 0 } +func _[C chan int | chan<- int](c C) { c <- 0 } +func _[C <-chan int | chan<- int](c C) { c <- /* ERROR "receive-only channel <-chan int" */ 0 } + +func _[C <-chan int | chan int](c C) { <-c } +func _[C chan int | <-chan int](c C) { <-c } +func _[C chan<- int | <-chan int](c C) { <-c /* ERROR "send-only channel chan<- int" */ } + +// from issue report + +func send[C interface{ ~chan<- V | ~chan V }, V any](c C, v V) { + c <- v +} + +func receive[C interface{ ~<-chan V | ~chan V }, V any](c C) V { + return <-c +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue73428.go b/go/src/internal/types/testdata/fixedbugs/issue73428.go new file mode 100644 index 0000000000000000000000000000000000000000..b452b90fe350ad1b6abc9dcf692ac7d5e2a6e94e --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue73428.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f() {} + +const c = 0 + +var v int +var _ = f < c // ERROR "invalid operation: f < c (mismatched types func() and untyped int)" +var _ = f < v // ERROR "invalid operation: f < v (mismatched types func() and int)" diff --git a/go/src/internal/types/testdata/fixedbugs/issue75194.go b/go/src/internal/types/testdata/fixedbugs/issue75194.go new file mode 100644 index 0000000000000000000000000000000000000000..ec2f9249ec9247c0420e78d8362b0d8ce63e648c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue75194.go @@ -0,0 +1,14 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A /* ERROR "invalid recursive type: A refers to itself" */ struct { + a A +} + +type B /* ERROR "invalid recursive type: B refers to itself" */ struct { + a A + b B +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue75883.go b/go/src/internal/types/testdata/fixedbugs/issue75883.go new file mode 100644 index 0000000000000000000000000000000000000000..33b23505f4342d6e51fbd56b40a66d2f561cb647 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue75883.go @@ -0,0 +1,20 @@ +// Copyright 2025 The Go 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 cases that were invalid because of cycles before the respective language change. +// Some are still invalid, but not because of cycles. + +package p + +type T1[P T1[P]] struct{} +type T2[P interface { + T2[int /* ERROR "int does not satisfy interface{T2[int]}" */] +}] struct{} +type T3[P interface { + m(T3[int /* ERROR "int does not satisfy interface{m(T3[int])}" */]) +}] struct{} +type T4[P T5[P /* ERROR "P does not satisfy T4[P]" */]] struct{} +type T5[P T4[P /* ERROR "P does not satisfy T5[P]" */]] struct{} + +type T6[P int] struct{ f *T6[P] } diff --git a/go/src/internal/types/testdata/fixedbugs/issue75885.go b/go/src/internal/types/testdata/fixedbugs/issue75885.go new file mode 100644 index 0000000000000000000000000000000000000000..f0cf4a65ed7e946dff33934b0cd25ec8c9b4f1fb --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue75885.go @@ -0,0 +1,15 @@ +// -gotypesalias=1 + +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type A[P any] = P // ERROR "cannot use type parameter declared in alias declaration as RHS" + +func _[P any]() { + type A[P any] = P // ERROR "cannot use type parameter declared in alias declaration as RHS" + type B = P + type C[Q any] = P +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue75918.go b/go/src/internal/types/testdata/fixedbugs/issue75918.go new file mode 100644 index 0000000000000000000000000000000000000000..373db4a21bb16f2a0ee1f441985246deee1dfde1 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue75918.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type A /* ERROR "invalid recursive type" */ [unsafe.Sizeof(S{})]byte + +type S struct { + a A +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue75986.go b/go/src/internal/types/testdata/fixedbugs/issue75986.go new file mode 100644 index 0000000000000000000000000000000000000000..b2b1509e03babe254660ed3b3d5f3ce7eec49979 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue75986.go @@ -0,0 +1,28 @@ +// -lang=go1.25 + +// Copyright 2025 The Go Authors. 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 "strings" + +type T int +type G[P any] struct{} + +var x T + +// Verify that we don't get a version error when there's another error present in new(expr). + +func f() { + _ = new(U /* ERROR "undefined: U" */) + _ = new(strings.BUILDER /* ERROR "undefined: strings.BUILDER (but have Builder)" */) + _ = new(T) // ok + _ = new(G[int]) // ok + _ = new(G /* ERROR "cannot use generic type G without instantiation" */) + _ = new(nil /* ERROR "use of untyped nil in argument to new" */) + _ = new(comparable /* ERROR "cannot use type comparable outside a type constraint" */) + _ = new(new /* ERROR "new (built-in) must be called" */) + _ = new(panic /* ERROR "panic(0) (no value) used as value or type" */ (0)) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue76103.go b/go/src/internal/types/testdata/fixedbugs/issue76103.go new file mode 100644 index 0000000000000000000000000000000000000000..6ba0d3c67765c47ec586288af32d405c6cdc34c2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76103.go @@ -0,0 +1,29 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + f(foo /* ERROR "undefined: foo" */) // ERROR "not enough arguments in call to f\n\thave (unknown type)\n\twant (int, int)" +} + +func f(_, _ int) {} + +// test case from issue + +type S struct{} + +func (S) G() {} + +func main() { + var s S + _ = must(s.F /* ERROR "s.F undefined" */ ()) // ERROR "not enough arguments in call to must\n\thave (unknown type)\n\twant (T, error)" +} + +func must[T any](x T, err error) T { + if err != nil { + panic(err) + } + return x +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue76220.go b/go/src/internal/types/testdata/fixedbugs/issue76220.go new file mode 100644 index 0000000000000000000000000000000000000000..ad465010a05159a0562fa1831925db693084d7af --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76220.go @@ -0,0 +1,17 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + append(nil /* ERROR "argument must be a slice; have untyped nil" */, ""...) +} + +// test case from issue + +func main() { + s := "hello" + msg := append(nil /* ERROR "argument must be a slice; have untyped nil" */, s...) + print(msg) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue76366.go b/go/src/internal/types/testdata/fixedbugs/issue76366.go new file mode 100644 index 0000000000000000000000000000000000000000..b78aa4463f805f36860ba62149ea16f6ec0b2d5d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76366.go @@ -0,0 +1,12 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _() { + type ( + A = int + B = []A + ) +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue76383.go b/go/src/internal/types/testdata/fixedbugs/issue76383.go new file mode 100644 index 0000000000000000000000000000000000000000..519174ab2872904470750ddccce22dfce4058fd8 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76383.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +var v any = 42 + +type T /* ERROR "invalid recursive type" */ struct { + f [unsafe.Sizeof(v.(T))]int +} diff --git a/go/src/internal/types/testdata/fixedbugs/issue76384.go b/go/src/internal/types/testdata/fixedbugs/issue76384.go new file mode 100644 index 0000000000000000000000000000000000000000..0737eb9e1a7e9bae4e822e015b3a4077cbc6812d --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76384.go @@ -0,0 +1,13 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type T /* ERROR "invalid recursive type" */ [unsafe.Sizeof(f())]int + +func f() T { + return T{} +} \ No newline at end of file diff --git a/go/src/internal/types/testdata/fixedbugs/issue76478.go b/go/src/internal/types/testdata/fixedbugs/issue76478.go new file mode 100644 index 0000000000000000000000000000000000000000..f16b40e04ea1c4775c91a0c55971e8c9860e422c --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue76478.go @@ -0,0 +1,25 @@ +// Copyright 2025 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +import "unsafe" + +type A /* ERROR "invalid recursive type" */ [unsafe.Sizeof(B{})]int +type B A + +type C /* ERROR "invalid recursive type" */ [unsafe.Sizeof(f())]int +func f() D { + return D{} +} +type D C + +type E /* ERROR "invalid recursive type" */ [unsafe.Sizeof(g[F]())]int +func g[P any]() P { + panic(0) +} +type F struct { + f E +} + diff --git a/go/src/internal/types/testdata/fixedbugs/issue78163.go b/go/src/internal/types/testdata/fixedbugs/issue78163.go new file mode 100644 index 0000000000000000000000000000000000000000..a697181f809c4b4cfbd7e0f1196b7366eec821f2 --- /dev/null +++ b/go/src/internal/types/testdata/fixedbugs/issue78163.go @@ -0,0 +1,11 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func _[P any](x P) { + var s []byte + _ = append(s, x /* ERROR "cannot use x (variable of type P constrained by any) as []byte value in argument to append" */ ...) + copy(s, x /* ERROR "invalid copy: argument must be a slice; have x (variable of type P constrained by any)" */) +} diff --git a/go/src/internal/types/testdata/spec/assignability.go b/go/src/internal/types/testdata/spec/assignability.go new file mode 100644 index 0000000000000000000000000000000000000000..2ce9a4a150134f03556d9ebca7f98c7d69cee795 --- /dev/null +++ b/go/src/internal/types/testdata/spec/assignability.go @@ -0,0 +1,264 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package assignability + +// See the end of this package for the declarations +// of the types and variables used in these tests. + +// "x's type is identical to T" +func _[TP any](X TP) { + b = b + a = a + l = l + s = s + p = p + f = f + i = i + m = m + c = c + d = d + + B = B + A = A + L = L + S = S + P = P + F = F + I = I + M = M + C = C + D = D + X = X +} + +// "x's type V and T have identical underlying types +// and at least one of V or T is not a named type." +// (here a named type is a type with a name) +func _[TP1, TP2 Interface](X1 TP1, X2 TP2) { + b = B // ERRORx `cannot use B .* as (int|_Basic.*) value` + a = A + l = L + s = S + p = P + f = F + i = I + m = M + c = C + d = D + + B = b // ERRORx `cannot use b .* as Basic value` + A = a + L = l + S = s + P = p + F = f + I = i + M = m + C = c + D = d + X1 = i // ERRORx `cannot use i .* as TP1 value` + X1 = X2 // ERRORx `cannot use X2 .* as TP1 value` +} + +// "T is an interface type and x implements T and T is not a type parameter" +func _[TP Interface](X TP) { + i = d // ERROR "missing method m" + i = D + i = X + X = i // ERRORx `cannot use i .* as TP value` +} + +// "x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type" +// (here a named type is a type with a name) +type ( + _SendChan = chan<- int + _RecvChan = <-chan int + + SendChan _SendChan + RecvChan _RecvChan +) + +func _[ + _CC ~_Chan, + _SC ~_SendChan, + _RC ~_RecvChan, + + CC Chan, + SC SendChan, + RC RecvChan, +]() { + var ( + _ _SendChan = c + _ _RecvChan = c + _ _Chan = c + + _ _SendChan = C + _ _RecvChan = C + _ _Chan = C + + _ SendChan = c + _ RecvChan = c + _ Chan = c + + _ SendChan = C // ERRORx `cannot use C .* as SendChan value` + _ RecvChan = C // ERRORx `cannot use C .* as RecvChan value` + _ Chan = C + _ Chan = make /* ERRORx `cannot use make\(chan Basic\) .* as Chan value` */ (chan Basic) + ) + + var ( + _ _CC = C // ERRORx `cannot use C .* as _CC value` + _ _SC = C // ERRORx `cannot use C .* as _SC value` + _ _RC = C // ERRORx `cannot use C .* as _RC value` + + _ CC = _CC /* ERRORx `cannot use _CC\(nil\) .* as CC value` */ (nil) + _ SC = _CC /* ERRORx `cannot use _CC\(nil\) .* as SC value` */ (nil) + _ RC = _CC /* ERRORx `cannot use _CC\(nil\) .* as RC value` */ (nil) + + _ CC = C // ERRORx `cannot use C .* as CC value` + _ SC = C // ERRORx `cannot use C .* as SC value` + _ RC = C // ERRORx `cannot use C .* as RC value` + ) +} + +// "x's type V is not a named type and T is a type parameter, and x is assignable to each specific type in T's type set." +func _[ + TP0 any, + TP1 ~_Chan, + TP2 ~chan int | ~chan byte, +]() { + var ( + _ TP0 = c // ERRORx `cannot use c .* as TP0 value` + _ TP0 = C // ERRORx `cannot use C .* as TP0 value` + _ TP1 = c + _ TP1 = C // ERRORx `cannot use C .* as TP1 value` + _ TP2 = c // ERRORx `.* cannot assign (chan int|_Chan.*) to chan byte` + ) +} + +// "x's type V is a type parameter and T is not a named type, and values x' of each specific type in V's type set are assignable to T." +func _[ + TP0 Interface, + TP1 ~_Chan, + TP2 ~chan int | ~chan byte, +](X0 TP0, X1 TP1, X2 TP2) { + i = X0 + I = X0 + c = X1 + C = X1 // ERRORx `cannot use X1 .* as Chan value` + c = X2 // ERRORx `.* cannot assign chan byte \(in TP2\) to (chan int|_Chan.*)` +} + +// "x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type" +func _[TP Interface](X TP) { + b = nil // ERROR "cannot use nil" + a = nil // ERROR "cannot use nil" + l = nil + s = nil // ERROR "cannot use nil" + p = nil + f = nil + i = nil + m = nil + c = nil + d = nil // ERROR "cannot use nil" + + B = nil // ERROR "cannot use nil" + A = nil // ERROR "cannot use nil" + L = nil + S = nil // ERROR "cannot use nil" + P = nil + F = nil + I = nil + M = nil + C = nil + D = nil // ERROR "cannot use nil" + X = nil // ERROR "cannot use nil" +} + +// "x is an untyped constant representable by a value of type T" +func _[ + Int8 ~int8, + Int16 ~int16, + Int32 ~int32, + Int64 ~int64, + Int8_16 ~int8 | ~int16, +]( + i8 Int8, + i16 Int16, + i32 Int32, + i64 Int64, + i8_16 Int8_16, +) { + b = 42 + b = 42.0 + // etc. + + i8 = -1 << 7 + i8 = 1<<7 - 1 + i16 = -1 << 15 + i16 = 1<<15 - 1 + i32 = -1 << 31 + i32 = 1<<31 - 1 + i64 = -1 << 63 + i64 = 1<<63 - 1 + + i8_16 = -1 << 7 + i8_16 = 1<<7 - 1 + i8_16 = - /* ERRORx `cannot use .* as Int8_16` */ 1 << 15 + i8_16 = 1 /* ERRORx `cannot use .* as Int8_16` */ <<15 - 1 +} + +// proto-types for tests + +type ( + _Basic = int + _Array = [10]int + _Slice = []int + _Struct = struct{ f int } + _Pointer = *int + _Func = func(x int) string + _Interface = interface{ m() int } + _Map = map[string]int + _Chan = chan int + + Basic _Basic + Array _Array + Slice _Slice + Struct _Struct + Pointer _Pointer + Func _Func + Interface _Interface + Map _Map + Chan _Chan + Defined _Struct +) + +func (Defined) m() int + +// proto-variables for tests + +var ( + b _Basic + a _Array + l _Slice + s _Struct + p _Pointer + f _Func + i _Interface + m _Map + c _Chan + d _Struct + + B Basic + A Array + L Slice + S Struct + P Pointer + F Func + I Interface + M Map + C Chan + D Defined +) diff --git a/go/src/internal/types/testdata/spec/comparable.go b/go/src/internal/types/testdata/spec/comparable.go new file mode 100644 index 0000000000000000000000000000000000000000..211fa119a858b475b53c75fd7fc1ebc4836fa02c --- /dev/null +++ b/go/src/internal/types/testdata/spec/comparable.go @@ -0,0 +1,26 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[_ comparable]() {} +func f2[_ interface{ comparable }]() {} + +type T interface{ m() } + +func _[P comparable, Q ~int, R any]() { + _ = f1[int] + _ = f1[T /* T does satisfy comparable */] + _ = f1[any /* any does satisfy comparable */] + _ = f1[P] + _ = f1[Q] + _ = f1[R /* ERROR "R does not satisfy comparable" */] + + _ = f2[int] + _ = f2[T /* T does satisfy comparable */] + _ = f2[any /* any does satisfy comparable */] + _ = f2[P] + _ = f2[Q] + _ = f2[R /* ERROR "R does not satisfy comparable" */] +} diff --git a/go/src/internal/types/testdata/spec/comparable1.19.go b/go/src/internal/types/testdata/spec/comparable1.19.go new file mode 100644 index 0000000000000000000000000000000000000000..7a4b2a0cfa497942c215e305c43a2f5b234372d2 --- /dev/null +++ b/go/src/internal/types/testdata/spec/comparable1.19.go @@ -0,0 +1,28 @@ +// -lang=go1.19 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +func f1[_ comparable]() {} +func f2[_ interface{ comparable }]() {} + +type T interface{ m() } + +func _[P comparable, Q ~int, R any]() { + _ = f1[int] + _ = f1[T /* ERROR "T to satisfy comparable requires go1.20 or later" */] + _ = f1[any /* ERROR "any to satisfy comparable requires go1.20 or later" */] + _ = f1[P] + _ = f1[Q] + _ = f1[R /* ERROR "R does not satisfy comparable" */] + + _ = f2[int] + _ = f2[T /* ERROR "T to satisfy comparable requires go1.20 or later" */] + _ = f2[any /* ERROR "any to satisfy comparable requires go1.20 or later" */] + _ = f2[P] + _ = f2[Q] + _ = f2[R /* ERROR "R does not satisfy comparable" */] +} diff --git a/go/src/internal/types/testdata/spec/comparisons.go b/go/src/internal/types/testdata/spec/comparisons.go new file mode 100644 index 0000000000000000000000000000000000000000..9f2b247b8089c32fd6c52e58ec632d1ce0eac36f --- /dev/null +++ b/go/src/internal/types/testdata/spec/comparisons.go @@ -0,0 +1,120 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package comparisons + +type ( + B int // basic type representative + A [10]func() + L []byte + S struct{ f []byte } + P *S + F func() + I interface{} + M map[string]int + C chan int +) + +var ( + b B + a A + l L + s S + p P + f F + i I + m M + c C +) + +func _() { + _ = nil == nil // ERROR "operator == not defined on untyped nil" + _ = b == b + _ = a /* ERROR "A cannot be compared" */ == a + _ = l /* ERROR "slice can only be compared to nil" */ == l + _ = s /* ERROR "struct containing []byte cannot be compared" */ == s + _ = p == p + _ = f /* ERROR "func can only be compared to nil" */ == f + _ = i == i + _ = m /* ERROR "map can only be compared to nil" */ == m + _ = c == c + + _ = b == nil /* ERROR "mismatched types" */ + _ = a == nil /* ERROR "mismatched types" */ + _ = l == nil + _ = s == nil /* ERROR "mismatched types" */ + _ = p == nil + _ = f == nil + _ = i == nil + _ = m == nil + _ = c == nil + + _ = nil /* ERROR "operator < not defined on untyped nil" */ < nil + _ = b < b + _ = a /* ERROR "operator < not defined on array" */ < a + _ = l /* ERROR "operator < not defined on slice" */ < l + _ = s /* ERROR "operator < not defined on struct" */ < s + _ = p /* ERROR "operator < not defined on pointer" */ < p + _ = f /* ERROR "operator < not defined on func" */ < f + _ = i /* ERROR "operator < not defined on interface" */ < i + _ = m /* ERROR "operator < not defined on map" */ < m + _ = c /* ERROR "operator < not defined on chan" */ < c +} + +func _[ + B int, + A [10]func(), + L []byte, + S struct{ f []byte }, + P *S, + F func(), + I interface{}, + J comparable, + M map[string]int, + C chan int, +]( + b B, + a A, + l L, + s S, + p P, + f F, + i I, + j J, + m M, + c C, +) { + _ = b == b + _ = a /* ERROR "incomparable types in type set" */ == a + _ = l /* ERROR "incomparable types in type set" */ == l + _ = s /* ERROR "incomparable types in type set" */ == s + _ = p == p + _ = f /* ERROR "incomparable types in type set" */ == f + _ = i /* ERROR "incomparable types in type set" */ == i + _ = j == j + _ = m /* ERROR "incomparable types in type set" */ == m + _ = c == c + + _ = b == nil /* ERROR "mismatched types" */ + _ = a == nil /* ERROR "mismatched types" */ + _ = l == nil + _ = s == nil /* ERROR "mismatched types" */ + _ = p == nil + _ = f == nil + _ = i == nil /* ERROR "mismatched types" */ + _ = j == nil /* ERROR "mismatched types" */ + _ = m == nil + _ = c == nil + + _ = b < b + _ = a /* ERROR "type parameter A cannot use operator <" */ < a + _ = l /* ERROR "type parameter L cannot use operator <" */ < l + _ = s /* ERROR "type parameter S cannot use operator <" */ < s + _ = p /* ERROR "type parameter P cannot use operator <" */ < p + _ = f /* ERROR "type parameter F cannot use operator <" */ < f + _ = i /* ERROR "type parameter I cannot use operator <" */ < i + _ = j /* ERROR "type parameter J cannot use operator <" */ < j + _ = m /* ERROR "type parameter M cannot use operator <" */ < m + _ = c /* ERROR "type parameter C cannot use operator <" */ < c +} diff --git a/go/src/internal/types/testdata/spec/conversions.go b/go/src/internal/types/testdata/spec/conversions.go new file mode 100644 index 0000000000000000000000000000000000000000..081439e3f200f051ef545f7cf888ebfa5373270a --- /dev/null +++ b/go/src/internal/types/testdata/spec/conversions.go @@ -0,0 +1,208 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package conversions + +import "unsafe" + +// constant conversions + +func _[T ~byte]() T { return 255 } +func _[T ~byte]() T { return 256 /* ERRORx `cannot use 256 .* as T value` */ } + +func _[T ~byte]() { + const _ = T /* ERRORx `T\(0\) .* is not constant` */ (0) + var _ T = 255 + var _ T = 256 // ERRORx `cannot use 256 .* as T value` +} + +func _[T ~string]() T { return T('a') } +func _[T ~int | ~string]() T { return T('a') } +func _[T ~byte | ~int | ~string]() T { return T(256 /* ERRORx `cannot convert 256 .* to type T` */) } + +// implicit conversions never convert to string +func _[T ~string]() { + var _ string = 0 // ERRORx `cannot use .* as string value` + var _ T = 0 // ERRORx `cannot use .* as T value` +} + +// failing const conversions of constants to type parameters report a cause +func _[ + T1 any, + T2 interface{ m() }, + T3 ~int | ~float64 | ~bool, + T4 ~int | ~string, +]() { + _ = T1(0 /* ERRORx `cannot convert 0 .* to type T1: T1 does not contain specific types` */) + _ = T2(1 /* ERRORx `cannot convert 1 .* to type T2: T2 does not contain specific types` */) + _ = T3(2 /* ERRORx `cannot convert 2 .* to type T3: cannot convert 2 .* to type bool \(in T3\)` */) + _ = T4(3.14 /* ERRORx `cannot convert 3.14 .* to type T4: cannot convert 3.14 .* to type int \(in T4\)` */) +} + +// "x is assignable to T" +// - tested via assignability tests + +// "x's type and T have identical underlying types if tags are ignored" + +func _[X ~int, T ~int](x X) T { return T(x) } +func _[X struct { + f int "foo" +}, T struct { + f int "bar" +}](x X) T { + return T(x) +} + +type Foo struct { + f int "foo" +} +type Bar struct { + f int "bar" +} +type Far struct{ f float64 } + +func _[X Foo, T Bar](x X) T { return T(x) } +func _[X Foo | Bar, T Bar](x X) T { return T(x) } +func _[X Foo, T Foo | Bar](x X) T { return T(x) } +func _[X Foo, T Far](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by Foo) to type T: cannot convert Foo (in X) to type Far (in T)" */) +} + +// "x's type and T are unnamed pointer types and their pointer base types +// have identical underlying types if tags are ignored" + +func _[X ~*Foo, T ~*Bar](x X) T { return T(x) } +func _[X ~*Foo | ~*Bar, T ~*Bar](x X) T { return T(x) } +func _[X ~*Foo, T ~*Foo | ~*Bar](x X) T { return T(x) } +func _[X ~*Foo, T ~*Far](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by ~*Foo) to type T: cannot convert *Foo (in X) to type *Far (in T)" */) +} + +// Verify that the defined types in constraints are considered for the rule above. + +type ( + B int + C int + X0 *B + T0 *C +) + +func _(x X0) T0 { return T0(x /* ERROR "cannot convert" */) } // non-generic reference +func _[X X0, T T0](x X) T { return T(x /* ERROR "cannot convert" */) } +func _[T T0](x X0) T { return T(x /* ERROR "cannot convert" */) } +func _[X X0](x X) T0 { return T0(x /* ERROR "cannot convert" */) } + +// "x's type and T are both integer or floating point types" + +func _[X Integer, T Integer](x X) T { return T(x) } +func _[X Unsigned, T Integer](x X) T { return T(x) } +func _[X Float, T Integer](x X) T { return T(x) } + +func _[X Integer, T Unsigned](x X) T { return T(x) } +func _[X Unsigned, T Unsigned](x X) T { return T(x) } +func _[X Float, T Unsigned](x X) T { return T(x) } + +func _[X Integer, T Float](x X) T { return T(x) } +func _[X Unsigned, T Float](x X) T { return T(x) } +func _[X Float, T Float](x X) T { return T(x) } + +func _[X, T Integer | Unsigned | Float](x X) T { return T(x) } +func _[X, T Integer | ~string](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by Integer | ~string) to type T: cannot convert string (in X) to type int (in T)" */) +} + +// "x's type and T are both complex types" + +func _[X, T Complex](x X) T { return T(x) } +func _[X, T Float | Complex](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by Float | Complex) to type T: cannot convert float32 (in X) to type complex64 (in T)" */) +} + +// "x is an integer or a slice of bytes or runes and T is a string type" + +type myInt int +type myString string + +func _[T ~string](x int) T { return T(x) } +func _[T ~string](x myInt) T { return T(x) } +func _[X Integer](x X) string { return string(x) } +func _[X Integer](x X) myString { return myString(x) } +func _[X Integer](x X) *string { + return (*string)(x /* ERROR "cannot convert x (variable of type X constrained by Integer) to type *string: cannot convert int (in X) to type *string" */) +} + +func _[T ~string](x []byte) T { return T(x) } +func _[T ~string](x []rune) T { return T(x) } +func _[X ~[]byte, T ~string](x X) T { return T(x) } +func _[X ~[]rune, T ~string](x X) T { return T(x) } +func _[X Integer | ~[]byte | ~[]rune, T ~string](x X) T { return T(x) } +func _[X Integer | ~[]byte | ~[]rune, T ~*string](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by Integer | ~[]byte | ~[]rune) to type T: cannot convert int (in X) to type *string (in T)" */) +} + +// "x is a string and T is a slice of bytes or runes" + +func _[T ~[]byte](x string) T { return T(x) } +func _[T ~[]rune](x string) T { return T(x) } +func _[T ~[]rune](x *string) T { + return T(x /* ERROR "cannot convert x (variable of type *string) to type T: cannot convert *string to type []rune (in T)" */) +} + +func _[X ~string, T ~[]byte](x X) T { return T(x) } +func _[X ~string, T ~[]rune](x X) T { return T(x) } +func _[X ~string, T ~[]byte | ~[]rune](x X) T { return T(x) } +func _[X ~*string, T ~[]byte | ~[]rune](x X) T { + return T(x /* ERROR "cannot convert x (variable of type X constrained by ~*string) to type T: cannot convert *string (in X) to type []byte (in T)" */) +} + +// package unsafe: +// "any pointer or value of underlying type uintptr can be converted into a unsafe.Pointer" + +type myUintptr uintptr + +func _[X ~uintptr](x X) unsafe.Pointer { return unsafe.Pointer(x) } +func _[T unsafe.Pointer](x myUintptr) T { return T(x) } +func _[T unsafe.Pointer](x int64) T { + return T(x /* ERROR "cannot convert x (variable of type int64) to type T: cannot convert int64 to type unsafe.Pointer (in T)" */) +} + +// "and vice versa" + +func _[T ~uintptr](x unsafe.Pointer) T { return T(x) } +func _[X unsafe.Pointer](x X) uintptr { return uintptr(x) } +func _[X unsafe.Pointer](x X) myUintptr { return myUintptr(x) } +func _[X unsafe.Pointer](x X) int64 { + return int64(x /* ERROR "cannot convert x (variable of type X constrained by unsafe.Pointer) to type int64: cannot convert unsafe.Pointer (in X) to type int64" */) +} + +// "x is a slice, T is an array or pointer-to-array type, +// and the slice and array types have identical element types." + +func _[X ~[]E, T ~[10]E, E any](x X) T { return T(x) } +func _[X ~[]E, T ~*[10]E, E any](x X) T { return T(x) } + +// ---------------------------------------------------------------------------- +// The following declarations can be replaced by the exported types of the +// constraints package once all builders support importing interfaces with +// type constraints. + +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +type Integer interface { + Signed | Unsigned +} + +type Float interface { + ~float32 | ~float64 +} + +type Complex interface { + ~complex64 | ~complex128 +} diff --git a/go/src/internal/types/testdata/spec/range.go b/go/src/internal/types/testdata/spec/range.go new file mode 100644 index 0000000000000000000000000000000000000000..d77511ece0575474446dabc837fa5e3718c262a1 --- /dev/null +++ b/go/src/internal/types/testdata/spec/range.go @@ -0,0 +1,200 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package p + +type MyInt int32 +type MyBool = bool // TODO(gri) remove alias declaration - see go.dev/issues/71131, go.dev/issues/71164 +type MyString string +type MyFunc1 func(func(int) bool) +type MyFunc2 func(int) bool +type MyFunc3 func(MyFunc2) + +type T struct{} + +func (*T) PM() {} +func (T) M() {} + +func f1() {} +func f2(func()) {} +func f4(func(int) bool) {} +func f5(func(int, string) bool) {} +func f7(func(int) MyBool) {} +func f8(func(MyInt, MyString) MyBool) {} + +func test() { + // TODO: Would be nice to test 'for range T.M' and 'for range (*T).PM' directly, + // but there is no gofmt-friendly way to write the error pattern in the right place. + m1 := T.M + for range m1 /* ERROR "cannot range over m1 (variable of type func(T)): func must be func(yield func(...) bool): argument is not func" */ { + } + m2 := (*T).PM + for range m2 /* ERROR "cannot range over m2 (variable of type func(*T)): func must be func(yield func(...) bool): argument is not func" */ { + } + for range f1 /* ERROR "cannot range over f1 (value of type func()): func must be func(yield func(...) bool): wrong argument count" */ { + } + for range f2 /* ERROR "cannot range over f2 (value of type func(func())): func must be func(yield func(...) bool): yield func does not return bool" */ { + } + for range f4 { + } + for _ = range f4 { + } + for _, _ = range f5 { + } + for _ = range f7 { + } + for _, _ = range f8 { + } + for range 1 { + } + for range uint8(1) { + } + for range int64(1) { + } + for range MyInt(1) { + } + for range 'x' { + } + for range 1.0 /* ERROR "cannot range over 1.0 (untyped float constant 1)" */ { + } + for _ = range MyFunc1(nil) { + } + for _ = range MyFunc3(nil) { + } + for _ = range (func(MyFunc2))(nil) { + } + + var i int + var s string + var mi MyInt + var ms MyString + for i := range f4 { + _ = i + } + for i = range f4 { + _ = i + } + for i, s := range f5 { + _, _ = i, s + } + for i, s = range f5 { + _, _ = i, s + } + for i, _ := range f5 { + _ = i + } + for i, _ = range f5 { + _ = i + } + for i := range f7 { + _ = i + } + for i = range f7 { + _ = i + } + for mi, _ := range f8 { + _ = mi + } + for mi, _ = range f8 { + _ = mi + } + for mi, ms := range f8 { + _, _ = mi, ms + } + for i /* ERROR "cannot use i (value of int32 type MyInt) as int value in assignment" */, s /* ERROR "cannot use s (value of string type MyString) as string value in assignment" */ = range f8 { + _, _ = mi, ms + } + for mi, ms := range f8 { + i, s = mi /* ERROR "cannot use mi (variable of int32 type MyInt) as int value in assignment" */, ms /* ERROR "cannot use ms (variable of string type MyString) as string value in assignment" */ + } + for mi, ms = range f8 { + _, _ = mi, ms + } + + for i := range 10 { + _ = i + } + for i = range 10 { + _ = i + } + for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ := range 10 { + _, _ = i, j + } + for mi := range MyInt(10) { + _ = mi + } + for mi = range MyInt(10) { + _ = mi + } +} + +func _[T any](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by any): no specific type" */ { + } +} + +func _[T interface{int; string}](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by interface{int; string} with empty type set): no specific type" */ { + } +} + +func _[T int | string](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by int | string): int and string have different underlying types" */ { + } +} + +func _[T int | int64](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by int | int64): int and int64 have different underlying types" */ { + } +} + +func _[T ~int](x T) { + for range x { // ok + } +} + +func _[T any](x func(func(T) bool)) { + for _ = range x { // ok + } +} + +func _[T ~func(func(int) bool)](x T) { + for _ = range x { // ok + } +} + +func _[T func() bool | func(int) bool]() { + for range func /* ERROR "func must be func(yield func(...) bool): in yield type, func() bool and func(int) bool have different underlying types" */ (T) {} { + } +} + +// go.dev/issue/65236 + +func seq0(func() bool) {} +func seq1(func(int) bool) {} +func seq2(func(int, int) bool) {} + +func _() { + for range seq0 { + } + for _ /* ERROR "range over seq0 (value of type func(func() bool)) permits no iteration variables" */ = range seq0 { + } + + for range seq1 { + } + for _ = range seq1 { + } + for _, _ /* ERROR "range over seq1 (value of type func(func(int) bool)) permits only one iteration variable" */ = range seq1 { + } + + for range seq2 { + } + for _ = range seq2 { + } + for _, _ = range seq2 { + } + // Note: go/types reports a parser error in this case, hence the different error messages. + for _, _, _ /* ERRORx "(range clause permits at most two iteration variables|expected at most 2 expressions)" */ = range seq2 { + } +} diff --git a/go/src/internal/types/testdata/spec/range_int.go b/go/src/internal/types/testdata/spec/range_int.go new file mode 100644 index 0000000000000000000000000000000000000000..81b8ed62290d82aa7989ccf94b5b7bf5096d2f22 --- /dev/null +++ b/go/src/internal/types/testdata/spec/range_int.go @@ -0,0 +1,190 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This is a subset of the tests in range.go for range over integers, +// with extra tests, and without the need for -goexperiment=range. + +package p + +// test framework assumes 64-bit int/uint sizes by default +const ( + maxInt = 1<<63 - 1 + maxUint = 1<<64 - 1 +) + +type MyInt int32 + +func _() { + for range -1 { + } + for range 0 { + } + for range 1 { + } + for range uint8(1) { + } + for range int64(1) { + } + for range MyInt(1) { + } + for range 'x' { + } + for range 1.0 /* ERROR "cannot range over 1.0 (untyped float constant 1)" */ { + } + + var i int + var mi MyInt + for i := range 10 { + _ = i + } + for i = range 10 { + _ = i + } + for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ := range 10 { + _, _ = i, j + } + for i = range MyInt /* ERROR "cannot use MyInt(10) (constant 10 of int32 type MyInt) as int value in range clause" */ (10) { + _ = i + } + for mi := range MyInt(10) { + _ = mi + } + for mi = range MyInt(10) { + _ = mi + } +} + +func _[T int | string](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by int | string): int and string have different underlying types" */ { + } +} + +func _[T int | int64](x T) { + for range x /* ERROR "cannot range over x (variable of type T constrained by int | int64): int and int64 have different underlying types" */ { + } +} + +func _[T ~int](x T) { + for range x { // ok + } +} + +func issue65133() { + for range maxInt { + } + for range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 { + } + for range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ { + } + + for i := range maxInt { + _ = i + } + for i := range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 { + _ = i + } + for i := range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ { + _ = i + } + + var i int + _ = i + for i = range maxInt { + } + for i = range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 { + } + for i = range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ { + } + + var j uint + _ = j + for j = range maxInt { + } + for j = range maxInt + 1 { + } + for j = range maxUint { + } + for j = range maxUint /* ERROR "cannot use maxUint + 1 (untyped int constant 18446744073709551616) as uint value in range clause (overflows)" */ + 1 { + } + + for range 256 { + } + for _ = range 256 { + } + for i = range 256 { + } + for i := range 256 { + _ = i + } + + var u8 uint8 + _ = u8 + for u8 = range - /* ERROR "cannot use -1 (untyped int constant) as uint8 value in range clause (overflows)" */ 1 { + } + for u8 = range 0 { + } + for u8 = range 255 { + } + for u8 = range 256 /* ERROR "cannot use 256 (untyped int constant) as uint8 value in range clause (overflows)" */ { + } +} + +func issue64471() { + for i := range 'a' { + var _ *rune = &i // ensure i has type rune + } +} + +func issue66561() { + for range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ { + } + for range 1e3 /* ERROR "cannot range over 1e3 (untyped float constant 1000)" */ { + } + for range 1 /* ERROR "cannot range over 1 + 0i (untyped complex constant (1 + 0i))" */ + 0i { + } + + for range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ { + } + for range 1i /* ERROR "cannot range over 1i (untyped complex constant (0 + 1i))" */ { + } + + for i := range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ { + _ = i + } + for i := range 1e3 /* ERROR "cannot range over 1e3 (untyped float constant 1000)" */ { + _ = i + } + for i := range 1 /* ERROR "cannot range over 1 + 0i (untyped complex constant (1 + 0i))" */ + 0i { + _ = i + } + + for i := range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ { + _ = i + } + for i := range 1i /* ERROR "cannot range over 1i (untyped complex constant (0 + 1i))" */ { + _ = i + } + + var j float64 + _ = j + for j /* ERROR "cannot use iteration variable of type float64" */ = range 1 { + } + for j = range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ { + } + for j = range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ { + } + + // There shouldn't be assignment errors if there are more iteration variables than permitted. + var i int + _ = i + for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ = range 10 { + } +} + +func issue67027() { + var i float64 + _ = i + for i /* ERROR "cannot use iteration variable of type float64" */ = range 10 { + } +} diff --git a/go/src/internal/types/testdata/spec/receivers.go b/go/src/internal/types/testdata/spec/receivers.go new file mode 100644 index 0000000000000000000000000000000000000000..010c5511c1d0dce10e35f688003f269b82784068 --- /dev/null +++ b/go/src/internal/types/testdata/spec/receivers.go @@ -0,0 +1,14 @@ +// -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package receivers + +// TODO(gri) add more tests checking the various restrictions on receivers + +type G[P any] struct{} +type A[P any] = G[P] + +func (a A /* ERROR "cannot define new methods on generic alias type A[P any]" */ [P]) m() {} diff --git a/go/src/internal/types/testdata/spec/typeAliases1.22.go b/go/src/internal/types/testdata/spec/typeAliases1.22.go new file mode 100644 index 0000000000000000000000000000000000000000..4b7beeed4907f05f9dcdf6275a14fbe150921499 --- /dev/null +++ b/go/src/internal/types/testdata/spec/typeAliases1.22.go @@ -0,0 +1,10 @@ +// -lang=go1.22 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aliasTypes + +type _ = int +type _[P /* ERROR "generic type alias requires go1.23 or later" */ any] = int diff --git a/go/src/internal/types/testdata/spec/typeAliases1.23a.go b/go/src/internal/types/testdata/spec/typeAliases1.23a.go new file mode 100644 index 0000000000000000000000000000000000000000..0ea21a4e32784ef8ff42bbbf477366879bd35eb1 --- /dev/null +++ b/go/src/internal/types/testdata/spec/typeAliases1.23a.go @@ -0,0 +1,10 @@ +// -lang=go1.23 -gotypesalias=0 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aliasTypes + +type _ = int +type _ /* ERROR "generic type alias requires GODEBUG=gotypesalias=1" */ [P any] = int diff --git a/go/src/internal/types/testdata/spec/typeAliases1.23b.go b/go/src/internal/types/testdata/spec/typeAliases1.23b.go new file mode 100644 index 0000000000000000000000000000000000000000..8a09899066fe18f8dd11fe2ab8be7377815af750 --- /dev/null +++ b/go/src/internal/types/testdata/spec/typeAliases1.23b.go @@ -0,0 +1,47 @@ +// -lang=go1.23 -gotypesalias=1 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aliasTypes + +type _ = int +type _[P any] = int + +// A type alias may have fewer type parameters than its RHS. +type RHS[P any, Q ~int] struct { + p P + q Q +} + +type _[P any] = RHS[P, int] + +// Or it may have more type parameters than its RHS. +type _[P any, Q ~int, R comparable] = RHS[P, Q] + +// The type parameters of a type alias must implement the +// corresponding type constraints of the type parameters +// on the RHS (if any) +type _[P any, Q ~int] = RHS[P, Q] +type _[P any, Q int] = RHS[P, Q] +type _[P int | float64] = RHS[P, int] +type _[P, Q any] = RHS[P, Q /* ERROR "Q does not satisfy ~int" */] + +// A generic type alias may be used like any other generic type. +type A[P any] = RHS[P, int] + +func _(a A[string]) { + a.p = "foo" + a.q = 42 +} + +// A generic alias may refer to another generic alias. +type B[P any] = A[P] + +func _(a B[string]) { + a.p = "foo" + a.q = 42 + // error messages print the instantiated alias type + a.r /* ERROR "a.r undefined (type B[string] has no field or method r)" */ = 0 +} diff --git a/go/src/internal/types/testdata/spec/typeAliases1.8.go b/go/src/internal/types/testdata/spec/typeAliases1.8.go new file mode 100644 index 0000000000000000000000000000000000000000..ecc01bbc344642b7a71aa1f3840f0df0c6729141 --- /dev/null +++ b/go/src/internal/types/testdata/spec/typeAliases1.8.go @@ -0,0 +1,10 @@ +// -lang=go1.8 + +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aliasTypes + +type _ = /* ERROR "type alias requires go1.9 or later" */ int +type _[P /* ERROR "generic type alias requires go1.23 or later" */ interface{}] = int diff --git a/go/src/internal/unsafeheader/unsafeheader.go b/go/src/internal/unsafeheader/unsafeheader.go new file mode 100644 index 0000000000000000000000000000000000000000..6d092c629a24869ea71dfbbedea8c25bd63e6f26 --- /dev/null +++ b/go/src/internal/unsafeheader/unsafeheader.go @@ -0,0 +1,37 @@ +// 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 unsafeheader contains header declarations for the Go runtime's slice +// and string implementations. +// +// This package allows packages that cannot import "reflect" to use types that +// are tested to be equivalent to reflect.SliceHeader and reflect.StringHeader. +package unsafeheader + +import ( + "unsafe" +) + +// Slice is the runtime representation of a slice. +// It cannot be used safely or portably and its representation may +// change in a later release. +// +// Unlike reflect.SliceHeader, its Data field is sufficient to guarantee the +// data it references will not be garbage collected. +type Slice struct { + Data unsafe.Pointer + Len int + Cap int +} + +// String is the runtime representation of a string. +// It cannot be used safely or portably and its representation may +// change in a later release. +// +// Unlike reflect.StringHeader, its Data field is sufficient to guarantee the +// data it references will not be garbage collected. +type String struct { + Data unsafe.Pointer + Len int +} diff --git a/go/src/internal/unsafeheader/unsafeheader_test.go b/go/src/internal/unsafeheader/unsafeheader_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f3d1a9bb68882f93709663e36e6880f3abbf6052 --- /dev/null +++ b/go/src/internal/unsafeheader/unsafeheader_test.go @@ -0,0 +1,100 @@ +// 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 unsafeheader_test + +import ( + "bytes" + "internal/unsafeheader" + "reflect" + "testing" + "unsafe" +) + +// TestTypeMatchesReflectType ensures that the name and layout of the +// unsafeheader types matches the corresponding Header types in the reflect +// package. +func TestTypeMatchesReflectType(t *testing.T) { + t.Run("Slice", func(t *testing.T) { + testHeaderMatchesReflect(t, unsafeheader.Slice{}, reflect.SliceHeader{}) + }) + + t.Run("String", func(t *testing.T) { + testHeaderMatchesReflect(t, unsafeheader.String{}, reflect.StringHeader{}) + }) +} + +func testHeaderMatchesReflect(t *testing.T, header, reflectHeader any) { + h := reflect.TypeOf(header) + rh := reflect.TypeOf(reflectHeader) + + for i := 0; i < h.NumField(); i++ { + f := h.Field(i) + rf, ok := rh.FieldByName(f.Name) + if !ok { + t.Errorf("Field %d of %v is named %s, but no such field exists in %v", i, h, f.Name, rh) + continue + } + if !typeCompatible(f.Type, rf.Type) { + t.Errorf("%v.%s has type %v, but %v.%s has type %v", h, f.Name, f.Type, rh, rf.Name, rf.Type) + } + if f.Offset != rf.Offset { + t.Errorf("%v.%s has offset %d, but %v.%s has offset %d", h, f.Name, f.Offset, rh, rf.Name, rf.Offset) + } + } + + if h.NumField() != rh.NumField() { + t.Errorf("%v has %d fields, but %v has %d", h, h.NumField(), rh, rh.NumField()) + } + if h.Align() != rh.Align() { + t.Errorf("%v has alignment %d, but %v has alignment %d", h, h.Align(), rh, rh.Align()) + } +} + +var ( + unsafePointerType = reflect.TypeOf(unsafe.Pointer(nil)) + uintptrType = reflect.TypeOf(uintptr(0)) +) + +func typeCompatible(t, rt reflect.Type) bool { + return t == rt || (t == unsafePointerType && rt == uintptrType) +} + +// TestWriteThroughHeader ensures that the headers in the unsafeheader package +// can successfully mutate variables of the corresponding built-in types. +// +// This test is expected to fail under -race (which implicitly enables +// -d=checkptr) if the runtime views the header types as incompatible with the +// underlying built-in types. +func TestWriteThroughHeader(t *testing.T) { + t.Run("Slice", func(t *testing.T) { + s := []byte("Hello, checkptr!")[:5] + + var alias []byte + hdr := (*unsafeheader.Slice)(unsafe.Pointer(&alias)) + hdr.Data = unsafe.Pointer(&s[0]) + hdr.Cap = cap(s) + hdr.Len = len(s) + + if !bytes.Equal(alias, s) { + t.Errorf("alias of %T(%q) constructed via Slice = %T(%q)", s, s, alias, alias) + } + if cap(alias) != cap(s) { + t.Errorf("alias of %T with cap %d has cap %d", s, cap(s), cap(alias)) + } + }) + + t.Run("String", func(t *testing.T) { + s := "Hello, checkptr!" + + var alias string + hdr := (*unsafeheader.String)(unsafe.Pointer(&alias)) + hdr.Data = (*unsafeheader.String)(unsafe.Pointer(&s)).Data + hdr.Len = len(s) + + if alias != s { + t.Errorf("alias of %q constructed via String = %q", s, alias) + } + }) +} diff --git a/go/src/internal/xcoff/ar.go b/go/src/internal/xcoff/ar.go new file mode 100644 index 0000000000000000000000000000000000000000..e616f377a3cf192063a1f01554a9d9465d36f3bd --- /dev/null +++ b/go/src/internal/xcoff/ar.go @@ -0,0 +1,226 @@ +// 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 xcoff + +import ( + "encoding/binary" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +const ( + SAIAMAG = 0x8 + AIAFMAG = "`\n" + AIAMAG = "\n" + AIAMAGBIG = "\n" + + // Sizeof + FL_HSZ_BIG = 0x80 + AR_HSZ_BIG = 0x70 +) + +type bigarFileHeader struct { + Flmagic [SAIAMAG]byte // Archive magic string + Flmemoff [20]byte // Member table offset + Flgstoff [20]byte // 32-bits global symtab offset + Flgst64off [20]byte // 64-bits global symtab offset + Flfstmoff [20]byte // First member offset + Fllstmoff [20]byte // Last member offset + Flfreeoff [20]byte // First member on free list offset +} + +type bigarMemberHeader struct { + Arsize [20]byte // File member size + Arnxtmem [20]byte // Next member pointer + Arprvmem [20]byte // Previous member pointer + Ardate [12]byte // File member date + Aruid [12]byte // File member uid + Argid [12]byte // File member gid + Armode [12]byte // File member mode (octal) + Arnamlen [4]byte // File member name length + // _ar_nam is removed because it's easier to get name without it. +} + +// Archive represents an open AIX big archive. +type Archive struct { + ArchiveHeader + Members []*Member + + closer io.Closer +} + +// ArchiveHeader holds information about a big archive file header +type ArchiveHeader struct { + magic string +} + +// Member represents a member of an AIX big archive. +type Member struct { + MemberHeader + sr *io.SectionReader +} + +// MemberHeader holds information about a big archive member +type MemberHeader struct { + Name string + Size uint64 +} + +// OpenArchive opens the named archive using os.Open and prepares it for use +// as an AIX big archive. +func OpenArchive(name string) (*Archive, error) { + f, err := os.Open(name) + if err != nil { + return nil, err + } + arch, err := NewArchive(f) + if err != nil { + f.Close() + return nil, err + } + arch.closer = f + return arch, nil +} + +// Close closes the Archive. +// If the Archive was created using NewArchive directly instead of OpenArchive, +// Close has no effect. +func (a *Archive) Close() error { + var err error + if a.closer != nil { + err = a.closer.Close() + a.closer = nil + } + return err +} + +// NewArchive creates a new Archive for accessing an AIX big archive in an underlying reader. +func NewArchive(r io.ReaderAt) (*Archive, error) { + parseDecimalBytes := func(b []byte) (int64, error) { + return strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64) + } + sr := io.NewSectionReader(r, 0, 1<<63-1) + + // Read File Header + var magic [SAIAMAG]byte + if _, err := sr.ReadAt(magic[:], 0); err != nil { + return nil, err + } + + arch := new(Archive) + switch string(magic[:]) { + case AIAMAGBIG: + arch.magic = string(magic[:]) + case AIAMAG: + return nil, fmt.Errorf("small AIX archive not supported") + default: + return nil, fmt.Errorf("unrecognised archive magic: 0x%x", magic) + } + + var fhdr bigarFileHeader + if _, err := sr.Seek(0, io.SeekStart); err != nil { + return nil, err + } + if err := binary.Read(sr, binary.BigEndian, &fhdr); err != nil { + return nil, err + } + + off, err := parseDecimalBytes(fhdr.Flfstmoff[:]) + if err != nil { + return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) + } + + if off == 0 { + // Occurs if the archive is empty. + return arch, nil + } + + lastoff, err := parseDecimalBytes(fhdr.Fllstmoff[:]) + if err != nil { + return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) + } + + // Read members + for { + // Read Member Header + // The member header is normally 2 bytes larger. But it's easier + // to read the name if the header is read without _ar_nam. + // However, AIAFMAG must be read afterward. + if _, err := sr.Seek(off, io.SeekStart); err != nil { + return nil, err + } + + var mhdr bigarMemberHeader + if err := binary.Read(sr, binary.BigEndian, &mhdr); err != nil { + return nil, err + } + + member := new(Member) + arch.Members = append(arch.Members, member) + + size, err := parseDecimalBytes(mhdr.Arsize[:]) + if err != nil { + return nil, fmt.Errorf("error parsing size in member header(%q); %v", mhdr, err) + } + member.Size = uint64(size) + + // Read name + namlen, err := parseDecimalBytes(mhdr.Arnamlen[:]) + if err != nil { + return nil, fmt.Errorf("error parsing name length in member header(%q); %v", mhdr, err) + } + name := make([]byte, namlen) + if err := binary.Read(sr, binary.BigEndian, name); err != nil { + return nil, err + } + member.Name = string(name) + + fileoff := off + AR_HSZ_BIG + namlen + if fileoff&1 != 0 { + fileoff++ + if _, err := sr.Seek(1, io.SeekCurrent); err != nil { + return nil, err + } + } + + // Read AIAFMAG string + var fmag [2]byte + if err := binary.Read(sr, binary.BigEndian, &fmag); err != nil { + return nil, err + } + if string(fmag[:]) != AIAFMAG { + return nil, fmt.Errorf("AIAFMAG not found after member header") + } + + fileoff += 2 // Add the two bytes of AIAFMAG + member.sr = io.NewSectionReader(sr, fileoff, size) + + if off == lastoff { + break + } + off, err = parseDecimalBytes(mhdr.Arnxtmem[:]) + if err != nil { + return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) + } + + } + + return arch, nil +} + +// GetFile returns the XCOFF file defined by member name. +// FIXME: This doesn't work if an archive has two members with the same +// name which can occur if an archive has both 32-bits and 64-bits files. +func (arch *Archive) GetFile(name string) (*File, error) { + for _, mem := range arch.Members { + if mem.Name == name { + return NewFile(mem.sr) + } + } + return nil, fmt.Errorf("unknown member %s in archive", name) +} diff --git a/go/src/internal/xcoff/ar_test.go b/go/src/internal/xcoff/ar_test.go new file mode 100644 index 0000000000000000000000000000000000000000..83333d6d0e523d4f66abc0c796d52280562793d8 --- /dev/null +++ b/go/src/internal/xcoff/ar_test.go @@ -0,0 +1,79 @@ +// 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 xcoff + +import ( + "reflect" + "testing" +) + +type archiveTest struct { + file string + hdr ArchiveHeader + members []*MemberHeader + membersFileHeader []FileHeader +} + +var archTest = []archiveTest{ + { + "testdata/bigar-ppc64", + ArchiveHeader{AIAMAGBIG}, + []*MemberHeader{ + {"printbye.o", 836}, + {"printhello.o", 860}, + }, + []FileHeader{ + {U64_TOCMAGIC}, + {U64_TOCMAGIC}, + }, + }, + { + "testdata/bigar-empty", + ArchiveHeader{AIAMAGBIG}, + []*MemberHeader{}, + []FileHeader{}, + }, +} + +func TestOpenArchive(t *testing.T) { + for i := range archTest { + tt := &archTest[i] + arch, err := OpenArchive(tt.file) + if err != nil { + t.Error(err) + continue + } + if !reflect.DeepEqual(arch.ArchiveHeader, tt.hdr) { + t.Errorf("open archive %s:\n\thave %#v\n\twant %#v\n", tt.file, arch.ArchiveHeader, tt.hdr) + continue + } + + for i, mem := range arch.Members { + if i >= len(tt.members) { + break + } + have := &mem.MemberHeader + want := tt.members[i] + if !reflect.DeepEqual(have, want) { + t.Errorf("open %s, member %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) + } + + f, err := arch.GetFile(mem.Name) + if err != nil { + t.Error(err) + continue + } + if !reflect.DeepEqual(f.FileHeader, tt.membersFileHeader[i]) { + t.Errorf("open %s, member file header %d:\n\thave %#v\n\twant %#v\n", tt.file, i, f.FileHeader, tt.membersFileHeader[i]) + } + } + tn := len(tt.members) + an := len(arch.Members) + if tn != an { + t.Errorf("open %s: len(Members) = %d, want %d", tt.file, an, tn) + } + + } +} diff --git a/go/src/internal/xcoff/file.go b/go/src/internal/xcoff/file.go new file mode 100644 index 0000000000000000000000000000000000000000..9b9627a74a54687ebc8d34b63bb1ca66dde5652d --- /dev/null +++ b/go/src/internal/xcoff/file.go @@ -0,0 +1,693 @@ +// 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 xcoff implements access to XCOFF (Extended Common Object File Format) files. +package xcoff + +import ( + "debug/dwarf" + "encoding/binary" + "errors" + "fmt" + "internal/saferio" + "io" + "os" + "strings" +) + +// SectionHeader holds information about an XCOFF section header. +type SectionHeader struct { + Name string + VirtualAddress uint64 + Size uint64 + Type uint32 + Relptr uint64 + Nreloc uint32 +} + +type Section struct { + SectionHeader + Relocs []Reloc + io.ReaderAt + sr *io.SectionReader +} + +// AuxiliaryCSect holds information about an XCOFF symbol in an AUX_CSECT entry. +type AuxiliaryCSect struct { + Length int64 + StorageMappingClass int + SymbolType int +} + +// AuxiliaryFcn holds information about an XCOFF symbol in an AUX_FCN entry. +type AuxiliaryFcn struct { + Size int64 +} + +type Symbol struct { + Name string + Value uint64 + SectionNumber int + StorageClass int + AuxFcn AuxiliaryFcn + AuxCSect AuxiliaryCSect +} + +type Reloc struct { + VirtualAddress uint64 + Symbol *Symbol + Signed bool + InstructionFixed bool + Length uint8 + Type uint8 +} + +// ImportedSymbol holds information about an imported XCOFF symbol. +type ImportedSymbol struct { + Name string + Library string +} + +// FileHeader holds information about an XCOFF file header. +type FileHeader struct { + TargetMachine uint16 +} + +// A File represents an open XCOFF file. +type File struct { + FileHeader + Sections []*Section + Symbols []*Symbol + StringTable []byte + LibraryPaths []string + + closer io.Closer +} + +// Open opens the named file using os.Open and prepares it for use as an XCOFF binary. +func Open(name string) (*File, error) { + f, err := os.Open(name) + if err != nil { + return nil, err + } + ff, err := NewFile(f) + if err != nil { + f.Close() + return nil, err + } + ff.closer = f + return ff, nil +} + +// Close closes the File. +// If the File was created using NewFile directly instead of Open, +// Close has no effect. +func (f *File) Close() error { + var err error + if f.closer != nil { + err = f.closer.Close() + f.closer = nil + } + return err +} + +// Section returns the first section with the given name, or nil if no such +// section exists. +// Xcoff have section's name limited to 8 bytes. Some sections like .gosymtab +// can be trunked but this method will still find them. +func (f *File) Section(name string) *Section { + for _, s := range f.Sections { + if s.Name == name || (len(name) > 8 && s.Name == name[:8]) { + return s + } + } + return nil +} + +// SectionByType returns the first section in f with the +// given type, or nil if there is no such section. +func (f *File) SectionByType(typ uint32) *Section { + for _, s := range f.Sections { + if s.Type == typ { + return s + } + } + return nil +} + +// cstring converts ASCII byte sequence b to string. +// It stops once it finds 0 or reaches end of b. +func cstring(b []byte) string { + var i int + for i = 0; i < len(b) && b[i] != 0; i++ { + } + return string(b[:i]) +} + +// getString extracts a string from an XCOFF string table. +func getString(st []byte, offset uint32) (string, bool) { + if offset < 4 || int(offset) >= len(st) { + return "", false + } + return cstring(st[offset:]), true +} + +// NewFile creates a new File for accessing an XCOFF binary in an underlying reader. +func NewFile(r io.ReaderAt) (*File, error) { + sr := io.NewSectionReader(r, 0, 1<<63-1) + // Read XCOFF target machine + var magic uint16 + if err := binary.Read(sr, binary.BigEndian, &magic); err != nil { + return nil, err + } + if magic != U802TOCMAGIC && magic != U64_TOCMAGIC { + return nil, fmt.Errorf("unrecognised XCOFF magic: 0x%x", magic) + } + + f := new(File) + f.TargetMachine = magic + + // Read XCOFF file header + if _, err := sr.Seek(0, io.SeekStart); err != nil { + return nil, err + } + var nscns uint16 + var symptr uint64 + var nsyms uint32 + var opthdr uint16 + var hdrsz int + switch f.TargetMachine { + case U802TOCMAGIC: + fhdr := new(FileHeader32) + if err := binary.Read(sr, binary.BigEndian, fhdr); err != nil { + return nil, err + } + nscns = fhdr.Fnscns + symptr = uint64(fhdr.Fsymptr) + nsyms = fhdr.Fnsyms + opthdr = fhdr.Fopthdr + hdrsz = FILHSZ_32 + case U64_TOCMAGIC: + fhdr := new(FileHeader64) + if err := binary.Read(sr, binary.BigEndian, fhdr); err != nil { + return nil, err + } + nscns = fhdr.Fnscns + symptr = fhdr.Fsymptr + nsyms = fhdr.Fnsyms + opthdr = fhdr.Fopthdr + hdrsz = FILHSZ_64 + } + + if symptr == 0 || nsyms <= 0 { + return nil, fmt.Errorf("no symbol table") + } + + // Read string table (located right after symbol table). + offset := symptr + uint64(nsyms)*SYMESZ + if _, err := sr.Seek(int64(offset), io.SeekStart); err != nil { + return nil, err + } + // The first 4 bytes contain the length (in bytes). + var l uint32 + if err := binary.Read(sr, binary.BigEndian, &l); err != nil { + return nil, err + } + if l > 4 { + st, err := saferio.ReadDataAt(sr, uint64(l), int64(offset)) + if err != nil { + return nil, err + } + f.StringTable = st + } + + // Read section headers + if _, err := sr.Seek(int64(hdrsz)+int64(opthdr), io.SeekStart); err != nil { + return nil, err + } + c := saferio.SliceCap[*Section](uint64(nscns)) + if c < 0 { + return nil, fmt.Errorf("too many XCOFF sections (%d)", nscns) + } + f.Sections = make([]*Section, 0, c) + for i := 0; i < int(nscns); i++ { + var scnptr uint64 + s := new(Section) + switch f.TargetMachine { + case U802TOCMAGIC: + shdr := new(SectionHeader32) + if err := binary.Read(sr, binary.BigEndian, shdr); err != nil { + return nil, err + } + s.Name = cstring(shdr.Sname[:]) + s.VirtualAddress = uint64(shdr.Svaddr) + s.Size = uint64(shdr.Ssize) + scnptr = uint64(shdr.Sscnptr) + s.Type = shdr.Sflags + s.Relptr = uint64(shdr.Srelptr) + s.Nreloc = uint32(shdr.Snreloc) + case U64_TOCMAGIC: + shdr := new(SectionHeader64) + if err := binary.Read(sr, binary.BigEndian, shdr); err != nil { + return nil, err + } + s.Name = cstring(shdr.Sname[:]) + s.VirtualAddress = shdr.Svaddr + s.Size = shdr.Ssize + scnptr = shdr.Sscnptr + s.Type = shdr.Sflags + s.Relptr = shdr.Srelptr + s.Nreloc = shdr.Snreloc + } + r2 := r + if scnptr == 0 { // .bss must have all 0s + r2 = &nobitsSectionReader{} + } + s.sr = io.NewSectionReader(r2, int64(scnptr), int64(s.Size)) + s.ReaderAt = s.sr + f.Sections = append(f.Sections, s) + } + + // Symbol map needed by relocation + var idxToSym = make(map[int]*Symbol) + + // Read symbol table + if _, err := sr.Seek(int64(symptr), io.SeekStart); err != nil { + return nil, err + } + f.Symbols = make([]*Symbol, 0) + for i := 0; i < int(nsyms); i++ { + var numaux int + var ok, needAuxFcn bool + sym := new(Symbol) + switch f.TargetMachine { + case U802TOCMAGIC: + se := new(SymEnt32) + if err := binary.Read(sr, binary.BigEndian, se); err != nil { + return nil, err + } + numaux = int(se.Nnumaux) + sym.SectionNumber = int(se.Nscnum) + sym.StorageClass = int(se.Nsclass) + sym.Value = uint64(se.Nvalue) + needAuxFcn = se.Ntype&SYM_TYPE_FUNC != 0 && numaux > 1 + zeroes := binary.BigEndian.Uint32(se.Nname[:4]) + if zeroes != 0 { + sym.Name = cstring(se.Nname[:]) + } else { + offset := binary.BigEndian.Uint32(se.Nname[4:]) + sym.Name, ok = getString(f.StringTable, offset) + if !ok { + goto skip + } + } + case U64_TOCMAGIC: + se := new(SymEnt64) + if err := binary.Read(sr, binary.BigEndian, se); err != nil { + return nil, err + } + numaux = int(se.Nnumaux) + sym.SectionNumber = int(se.Nscnum) + sym.StorageClass = int(se.Nsclass) + sym.Value = se.Nvalue + needAuxFcn = se.Ntype&SYM_TYPE_FUNC != 0 && numaux > 1 + sym.Name, ok = getString(f.StringTable, se.Noffset) + if !ok { + goto skip + } + } + if sym.StorageClass != C_EXT && sym.StorageClass != C_WEAKEXT && sym.StorageClass != C_HIDEXT { + goto skip + } + // Must have at least one csect auxiliary entry. + if numaux < 1 || i+numaux >= int(nsyms) { + goto skip + } + + if sym.SectionNumber > int(nscns) { + goto skip + } + if sym.SectionNumber == 0 { + sym.Value = 0 + } else { + sym.Value -= f.Sections[sym.SectionNumber-1].VirtualAddress + } + + idxToSym[i] = sym + + // If this symbol is a function, it must retrieve its size from + // its AUX_FCN entry. + // It can happen that a function symbol doesn't have any AUX_FCN. + // In this case, needAuxFcn is false and their size will be set to 0. + if needAuxFcn { + switch f.TargetMachine { + case U802TOCMAGIC: + aux := new(AuxFcn32) + if err := binary.Read(sr, binary.BigEndian, aux); err != nil { + return nil, err + } + sym.AuxFcn.Size = int64(aux.Xfsize) + case U64_TOCMAGIC: + aux := new(AuxFcn64) + if err := binary.Read(sr, binary.BigEndian, aux); err != nil { + return nil, err + } + sym.AuxFcn.Size = int64(aux.Xfsize) + } + } + + // Read csect auxiliary entry (by convention, it is the last). + if !needAuxFcn { + if _, err := sr.Seek(int64(numaux-1)*SYMESZ, io.SeekCurrent); err != nil { + return nil, err + } + } + i += numaux + numaux = 0 + switch f.TargetMachine { + case U802TOCMAGIC: + aux := new(AuxCSect32) + if err := binary.Read(sr, binary.BigEndian, aux); err != nil { + return nil, err + } + sym.AuxCSect.SymbolType = int(aux.Xsmtyp & 0x7) + sym.AuxCSect.StorageMappingClass = int(aux.Xsmclas) + sym.AuxCSect.Length = int64(aux.Xscnlen) + case U64_TOCMAGIC: + aux := new(AuxCSect64) + if err := binary.Read(sr, binary.BigEndian, aux); err != nil { + return nil, err + } + sym.AuxCSect.SymbolType = int(aux.Xsmtyp & 0x7) + sym.AuxCSect.StorageMappingClass = int(aux.Xsmclas) + sym.AuxCSect.Length = int64(aux.Xscnlenhi)<<32 | int64(aux.Xscnlenlo) + } + f.Symbols = append(f.Symbols, sym) + skip: + i += numaux // Skip auxiliary entries + if _, err := sr.Seek(int64(numaux)*SYMESZ, io.SeekCurrent); err != nil { + return nil, err + } + } + + // Read relocations + // Only for .data or .text section + for sectNum, sect := range f.Sections { + if sect.Type != STYP_TEXT && sect.Type != STYP_DATA { + continue + } + if sect.Relptr == 0 { + continue + } + c := saferio.SliceCap[Reloc](uint64(sect.Nreloc)) + if c < 0 { + return nil, fmt.Errorf("too many relocs (%d) for section %d", sect.Nreloc, sectNum) + } + sect.Relocs = make([]Reloc, 0, c) + if _, err := sr.Seek(int64(sect.Relptr), io.SeekStart); err != nil { + return nil, err + } + for i := uint32(0); i < sect.Nreloc; i++ { + var reloc Reloc + switch f.TargetMachine { + case U802TOCMAGIC: + rel := new(Reloc32) + if err := binary.Read(sr, binary.BigEndian, rel); err != nil { + return nil, err + } + reloc.VirtualAddress = uint64(rel.Rvaddr) + reloc.Symbol = idxToSym[int(rel.Rsymndx)] + reloc.Type = rel.Rtype + reloc.Length = rel.Rsize&0x3F + 1 + + if rel.Rsize&0x80 != 0 { + reloc.Signed = true + } + if rel.Rsize&0x40 != 0 { + reloc.InstructionFixed = true + } + + case U64_TOCMAGIC: + rel := new(Reloc64) + if err := binary.Read(sr, binary.BigEndian, rel); err != nil { + return nil, err + } + reloc.VirtualAddress = rel.Rvaddr + reloc.Symbol = idxToSym[int(rel.Rsymndx)] + reloc.Type = rel.Rtype + reloc.Length = rel.Rsize&0x3F + 1 + if rel.Rsize&0x80 != 0 { + reloc.Signed = true + } + if rel.Rsize&0x40 != 0 { + reloc.InstructionFixed = true + } + } + + sect.Relocs = append(sect.Relocs, reloc) + } + } + + return f, nil +} + +type nobitsSectionReader struct{} + +func (*nobitsSectionReader) ReadAt(p []byte, off int64) (n int, err error) { + return 0, errors.New("unexpected read from section with uninitialized data") +} + +// Data reads and returns the contents of the XCOFF section s. +func (s *Section) Data() ([]byte, error) { + dat := make([]byte, s.sr.Size()) + n, err := s.sr.ReadAt(dat, 0) + if n == len(dat) { + err = nil + } + return dat[:n], err +} + +// CSect reads and returns the contents of a csect. +func (f *File) CSect(name string) []byte { + for _, sym := range f.Symbols { + if sym.Name == name && sym.AuxCSect.SymbolType == XTY_SD { + if i := sym.SectionNumber - 1; 0 <= i && i < len(f.Sections) { + s := f.Sections[i] + if sym.Value+uint64(sym.AuxCSect.Length) <= s.Size { + dat := make([]byte, sym.AuxCSect.Length) + _, err := s.sr.ReadAt(dat, int64(sym.Value)) + if err != nil { + return nil + } + return dat + } + } + break + } + } + return nil +} + +func (f *File) DWARF() (*dwarf.Data, error) { + // There are many other DWARF sections, but these + // are the ones the debug/dwarf package uses. + // Don't bother loading others. + var subtypes = [...]uint32{SSUBTYP_DWABREV, SSUBTYP_DWINFO, SSUBTYP_DWLINE, SSUBTYP_DWRNGES, SSUBTYP_DWSTR} + var dat [len(subtypes)][]byte + for i, subtype := range subtypes { + s := f.SectionByType(STYP_DWARF | subtype) + if s != nil { + b, err := s.Data() + if err != nil && uint64(len(b)) < s.Size { + return nil, err + } + dat[i] = b + } + } + + abbrev, info, line, ranges, str := dat[0], dat[1], dat[2], dat[3], dat[4] + return dwarf.New(abbrev, nil, nil, info, line, nil, ranges, str) +} + +// readImportID returns the import file IDs stored inside the .loader section. +// Library name pattern is either path/base/member or base/member +func (f *File) readImportIDs(s *Section) ([]string, error) { + // Read loader header + if _, err := s.sr.Seek(0, io.SeekStart); err != nil { + return nil, err + } + var istlen uint32 + var nimpid uint32 + var impoff uint64 + switch f.TargetMachine { + case U802TOCMAGIC: + lhdr := new(LoaderHeader32) + if err := binary.Read(s.sr, binary.BigEndian, lhdr); err != nil { + return nil, err + } + istlen = lhdr.Listlen + nimpid = lhdr.Lnimpid + impoff = uint64(lhdr.Limpoff) + case U64_TOCMAGIC: + lhdr := new(LoaderHeader64) + if err := binary.Read(s.sr, binary.BigEndian, lhdr); err != nil { + return nil, err + } + istlen = lhdr.Listlen + nimpid = lhdr.Lnimpid + impoff = lhdr.Limpoff + } + + // Read loader import file ID table + if _, err := s.sr.Seek(int64(impoff), io.SeekStart); err != nil { + return nil, err + } + table := make([]byte, istlen) + if _, err := io.ReadFull(s.sr, table); err != nil { + return nil, err + } + + offset := 0 + // First import file ID is the default LIBPATH value + libpath := cstring(table[offset:]) + f.LibraryPaths = strings.Split(libpath, ":") + offset += len(libpath) + 3 // 3 null bytes + all := make([]string, 0) + for i := 1; i < int(nimpid); i++ { + impidpath := cstring(table[offset:]) + offset += len(impidpath) + 1 + impidbase := cstring(table[offset:]) + offset += len(impidbase) + 1 + impidmem := cstring(table[offset:]) + offset += len(impidmem) + 1 + var path string + if len(impidpath) > 0 { + path = impidpath + "/" + impidbase + "/" + impidmem + } else { + path = impidbase + "/" + impidmem + } + all = append(all, path) + } + + return all, nil +} + +// ImportedSymbols returns the names of all symbols +// referred to by the binary f that are expected to be +// satisfied by other libraries at dynamic load time. +// It does not return weak symbols. +func (f *File) ImportedSymbols() ([]ImportedSymbol, error) { + s := f.SectionByType(STYP_LOADER) + if s == nil { + return nil, nil + } + // Read loader header + if _, err := s.sr.Seek(0, io.SeekStart); err != nil { + return nil, err + } + var stlen uint32 + var stoff uint64 + var nsyms uint32 + var symoff uint64 + switch f.TargetMachine { + case U802TOCMAGIC: + lhdr := new(LoaderHeader32) + if err := binary.Read(s.sr, binary.BigEndian, lhdr); err != nil { + return nil, err + } + stlen = lhdr.Lstlen + stoff = uint64(lhdr.Lstoff) + nsyms = lhdr.Lnsyms + symoff = LDHDRSZ_32 + case U64_TOCMAGIC: + lhdr := new(LoaderHeader64) + if err := binary.Read(s.sr, binary.BigEndian, lhdr); err != nil { + return nil, err + } + stlen = lhdr.Lstlen + stoff = lhdr.Lstoff + nsyms = lhdr.Lnsyms + symoff = lhdr.Lsymoff + } + + // Read loader section string table + if _, err := s.sr.Seek(int64(stoff), io.SeekStart); err != nil { + return nil, err + } + st := make([]byte, stlen) + if _, err := io.ReadFull(s.sr, st); err != nil { + return nil, err + } + + // Read imported libraries + libs, err := f.readImportIDs(s) + if err != nil { + return nil, err + } + + // Read loader symbol table + if _, err := s.sr.Seek(int64(symoff), io.SeekStart); err != nil { + return nil, err + } + all := make([]ImportedSymbol, 0) + for i := 0; i < int(nsyms); i++ { + var name string + var ifile uint32 + var ok bool + switch f.TargetMachine { + case U802TOCMAGIC: + ldsym := new(LoaderSymbol32) + if err := binary.Read(s.sr, binary.BigEndian, ldsym); err != nil { + return nil, err + } + if ldsym.Lsmtype&0x40 == 0 { + continue // Imported symbols only + } + zeroes := binary.BigEndian.Uint32(ldsym.Lname[:4]) + if zeroes != 0 { + name = cstring(ldsym.Lname[:]) + } else { + offset := binary.BigEndian.Uint32(ldsym.Lname[4:]) + name, ok = getString(st, offset) + if !ok { + continue + } + } + ifile = ldsym.Lifile + case U64_TOCMAGIC: + ldsym := new(LoaderSymbol64) + if err := binary.Read(s.sr, binary.BigEndian, ldsym); err != nil { + return nil, err + } + if ldsym.Lsmtype&0x40 == 0 { + continue // Imported symbols only + } + name, ok = getString(st, ldsym.Loffset) + if !ok { + continue + } + ifile = ldsym.Lifile + } + var sym ImportedSymbol + sym.Name = name + if ifile >= 1 && int(ifile) <= len(libs) { + sym.Library = libs[ifile-1] + } + all = append(all, sym) + } + + return all, nil +} + +// ImportedLibraries returns the names of all libraries +// referred to by the binary f that are expected to be +// linked with the binary at dynamic link time. +func (f *File) ImportedLibraries() ([]string, error) { + s := f.SectionByType(STYP_LOADER) + if s == nil { + return nil, nil + } + all, err := f.readImportIDs(s) + return all, err +} diff --git a/go/src/internal/xcoff/file_test.go b/go/src/internal/xcoff/file_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d1f10d6bf1f7a3787c944689402ffebb17237278 --- /dev/null +++ b/go/src/internal/xcoff/file_test.go @@ -0,0 +1,103 @@ +// 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 xcoff + +import ( + "reflect" + "slices" + "testing" +) + +type fileTest struct { + file string + hdr FileHeader + sections []*SectionHeader + needed []string +} + +var fileTests = []fileTest{ + { + "testdata/gcc-ppc32-aix-dwarf2-exec", + FileHeader{U802TOCMAGIC}, + []*SectionHeader{ + {".text", 0x10000290, 0x00000bbd, STYP_TEXT, 0x7ae6, 0x36}, + {".data", 0x20000e4d, 0x00000437, STYP_DATA, 0x7d02, 0x2b}, + {".bss", 0x20001284, 0x0000021c, STYP_BSS, 0, 0}, + {".loader", 0x00000000, 0x000004b3, STYP_LOADER, 0, 0}, + {".dwline", 0x00000000, 0x000000df, STYP_DWARF | SSUBTYP_DWLINE, 0x7eb0, 0x7}, + {".dwinfo", 0x00000000, 0x00000314, STYP_DWARF | SSUBTYP_DWINFO, 0x7ef6, 0xa}, + {".dwabrev", 0x00000000, 0x000000d6, STYP_DWARF | SSUBTYP_DWABREV, 0, 0}, + {".dwarnge", 0x00000000, 0x00000020, STYP_DWARF | SSUBTYP_DWARNGE, 0x7f5a, 0x2}, + {".dwloc", 0x00000000, 0x00000074, STYP_DWARF | SSUBTYP_DWLOC, 0, 0}, + {".debug", 0x00000000, 0x00005e4f, STYP_DEBUG, 0, 0}, + }, + []string{"libc.a/shr.o"}, + }, + { + "testdata/gcc-ppc64-aix-dwarf2-exec", + FileHeader{U64_TOCMAGIC}, + []*SectionHeader{ + {".text", 0x10000480, 0x00000afd, STYP_TEXT, 0x8322, 0x34}, + {".data", 0x20000f7d, 0x000002f3, STYP_DATA, 0x85fa, 0x25}, + {".bss", 0x20001270, 0x00000428, STYP_BSS, 0, 0}, + {".loader", 0x00000000, 0x00000535, STYP_LOADER, 0, 0}, + {".dwline", 0x00000000, 0x000000b4, STYP_DWARF | SSUBTYP_DWLINE, 0x8800, 0x4}, + {".dwinfo", 0x00000000, 0x0000036a, STYP_DWARF | SSUBTYP_DWINFO, 0x8838, 0x7}, + {".dwabrev", 0x00000000, 0x000000b5, STYP_DWARF | SSUBTYP_DWABREV, 0, 0}, + {".dwarnge", 0x00000000, 0x00000040, STYP_DWARF | SSUBTYP_DWARNGE, 0x889a, 0x2}, + {".dwloc", 0x00000000, 0x00000062, STYP_DWARF | SSUBTYP_DWLOC, 0, 0}, + {".debug", 0x00000000, 0x00006605, STYP_DEBUG, 0, 0}, + }, + []string{"libc.a/shr_64.o"}, + }, +} + +func TestOpen(t *testing.T) { + for i := range fileTests { + tt := &fileTests[i] + + f, err := Open(tt.file) + if err != nil { + t.Error(err) + continue + } + if !reflect.DeepEqual(f.FileHeader, tt.hdr) { + t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.FileHeader, tt.hdr) + continue + } + + for i, sh := range f.Sections { + if i >= len(tt.sections) { + break + } + have := &sh.SectionHeader + want := tt.sections[i] + if !reflect.DeepEqual(have, want) { + t.Errorf("open %s, section %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) + } + } + tn := len(tt.sections) + fn := len(f.Sections) + if tn != fn { + t.Errorf("open %s: len(Sections) = %d, want %d", tt.file, fn, tn) + } + tl := tt.needed + fl, err := f.ImportedLibraries() + if err != nil { + t.Error(err) + } + if !slices.Equal(tl, fl) { + t.Errorf("open %s: loader import = %v, want %v", tt.file, tl, fl) + } + } +} + +func TestOpenFailure(t *testing.T) { + filename := "file.go" // not an XCOFF object file + _, err := Open(filename) // don't crash + if err == nil { + t.Errorf("open %s: succeeded unexpectedly", filename) + } +} diff --git a/go/src/internal/xcoff/testdata/bigar-empty b/go/src/internal/xcoff/testdata/bigar-empty new file mode 100644 index 0000000000000000000000000000000000000000..851ccc51236947fa0fe8527ea14204f1566ee171 --- /dev/null +++ b/go/src/internal/xcoff/testdata/bigar-empty @@ -0,0 +1,2 @@ + +0 0 0 0 0 0 \ No newline at end of file diff --git a/go/src/internal/xcoff/testdata/bigar-ppc64 b/go/src/internal/xcoff/testdata/bigar-ppc64 new file mode 100644 index 0000000000000000000000000000000000000000..a8d4979d121f71266b57bc33c0e55e2b8a679cbb Binary files /dev/null and b/go/src/internal/xcoff/testdata/bigar-ppc64 differ diff --git a/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec b/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec new file mode 100644 index 0000000000000000000000000000000000000000..810e21a0dfc78b29f2dfc5afe2bc588763177ea6 Binary files /dev/null and b/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec differ diff --git a/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec b/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec new file mode 100644 index 0000000000000000000000000000000000000000..707d01ebd43487081a620250a213dcdba7a80379 Binary files /dev/null and b/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec differ diff --git a/go/src/internal/xcoff/testdata/hello.c b/go/src/internal/xcoff/testdata/hello.c new file mode 100644 index 0000000000000000000000000000000000000000..34d9ee79234ef29ea03feeb69d220b0796295636 --- /dev/null +++ b/go/src/internal/xcoff/testdata/hello.c @@ -0,0 +1,7 @@ +#include + +void +main(int argc, char *argv[]) +{ + printf("hello, world\n"); +} diff --git a/go/src/internal/xcoff/testdata/printbye.c b/go/src/internal/xcoff/testdata/printbye.c new file mode 100644 index 0000000000000000000000000000000000000000..904507998ab1b9948129a3b74a285ed43e6320ec --- /dev/null +++ b/go/src/internal/xcoff/testdata/printbye.c @@ -0,0 +1,5 @@ +#include + +void printbye(){ + printf("Goodbye\n"); +} diff --git a/go/src/internal/xcoff/testdata/printhello.c b/go/src/internal/xcoff/testdata/printhello.c new file mode 100644 index 0000000000000000000000000000000000000000..182aa09728abc457d8eab9c25ccb481a0f0649ff --- /dev/null +++ b/go/src/internal/xcoff/testdata/printhello.c @@ -0,0 +1,5 @@ +#include + +void printhello(){ + printf("Helloworld\n"); +} diff --git a/go/src/internal/xcoff/xcoff.go b/go/src/internal/xcoff/xcoff.go new file mode 100644 index 0000000000000000000000000000000000000000..db81542ed39bb5842c5e49cc7f294b6bce748257 --- /dev/null +++ b/go/src/internal/xcoff/xcoff.go @@ -0,0 +1,367 @@ +// 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 xcoff + +// File Header. +type FileHeader32 struct { + Fmagic uint16 // Target machine + Fnscns uint16 // Number of sections + Ftimedat uint32 // Time and date of file creation + Fsymptr uint32 // Byte offset to symbol table start + Fnsyms uint32 // Number of entries in symbol table + Fopthdr uint16 // Number of bytes in optional header + Fflags uint16 // Flags +} + +type FileHeader64 struct { + Fmagic uint16 // Target machine + Fnscns uint16 // Number of sections + Ftimedat uint32 // Time and date of file creation + Fsymptr uint64 // Byte offset to symbol table start + Fopthdr uint16 // Number of bytes in optional header + Fflags uint16 // Flags + Fnsyms uint32 // Number of entries in symbol table +} + +const ( + FILHSZ_32 = 20 + FILHSZ_64 = 24 +) +const ( + U802TOCMAGIC = 0737 // AIX 32-bit XCOFF + U64_TOCMAGIC = 0767 // AIX 64-bit XCOFF +) + +// Flags that describe the type of the object file. +const ( + F_RELFLG = 0x0001 + F_EXEC = 0x0002 + F_LNNO = 0x0004 + F_FDPR_PROF = 0x0010 + F_FDPR_OPTI = 0x0020 + F_DSA = 0x0040 + F_VARPG = 0x0100 + F_DYNLOAD = 0x1000 + F_SHROBJ = 0x2000 + F_LOADONLY = 0x4000 +) + +// Section Header. +type SectionHeader32 struct { + Sname [8]byte // Section name + Spaddr uint32 // Physical address + Svaddr uint32 // Virtual address + Ssize uint32 // Section size + Sscnptr uint32 // Offset in file to raw data for section + Srelptr uint32 // Offset in file to relocation entries for section + Slnnoptr uint32 // Offset in file to line number entries for section + Snreloc uint16 // Number of relocation entries + Snlnno uint16 // Number of line number entries + Sflags uint32 // Flags to define the section type +} + +type SectionHeader64 struct { + Sname [8]byte // Section name + Spaddr uint64 // Physical address + Svaddr uint64 // Virtual address + Ssize uint64 // Section size + Sscnptr uint64 // Offset in file to raw data for section + Srelptr uint64 // Offset in file to relocation entries for section + Slnnoptr uint64 // Offset in file to line number entries for section + Snreloc uint32 // Number of relocation entries + Snlnno uint32 // Number of line number entries + Sflags uint32 // Flags to define the section type + Spad uint32 // Needs to be 72 bytes long +} + +// Flags defining the section type. +const ( + STYP_DWARF = 0x0010 + STYP_TEXT = 0x0020 + STYP_DATA = 0x0040 + STYP_BSS = 0x0080 + STYP_EXCEPT = 0x0100 + STYP_INFO = 0x0200 + STYP_TDATA = 0x0400 + STYP_TBSS = 0x0800 + STYP_LOADER = 0x1000 + STYP_DEBUG = 0x2000 + STYP_TYPCHK = 0x4000 + STYP_OVRFLO = 0x8000 +) +const ( + SSUBTYP_DWINFO = 0x10000 // DWARF info section + SSUBTYP_DWLINE = 0x20000 // DWARF line-number section + SSUBTYP_DWPBNMS = 0x30000 // DWARF public names section + SSUBTYP_DWPBTYP = 0x40000 // DWARF public types section + SSUBTYP_DWARNGE = 0x50000 // DWARF aranges section + SSUBTYP_DWABREV = 0x60000 // DWARF abbreviation section + SSUBTYP_DWSTR = 0x70000 // DWARF strings section + SSUBTYP_DWRNGES = 0x80000 // DWARF ranges section + SSUBTYP_DWLOC = 0x90000 // DWARF location lists section + SSUBTYP_DWFRAME = 0xA0000 // DWARF frames section + SSUBTYP_DWMAC = 0xB0000 // DWARF macros section +) + +// Symbol Table Entry. +type SymEnt32 struct { + Nname [8]byte // Symbol name + Nvalue uint32 // Symbol value + Nscnum uint16 // Section number of symbol + Ntype uint16 // Basic and derived type specification + Nsclass uint8 // Storage class of symbol + Nnumaux uint8 // Number of auxiliary entries +} + +type SymEnt64 struct { + Nvalue uint64 // Symbol value + Noffset uint32 // Offset of the name in string table or .debug section + Nscnum uint16 // Section number of symbol + Ntype uint16 // Basic and derived type specification + Nsclass uint8 // Storage class of symbol + Nnumaux uint8 // Number of auxiliary entries +} + +const SYMESZ = 18 + +const ( + // Nscnum + N_DEBUG = -2 + N_ABS = -1 + N_UNDEF = 0 + + //Ntype + SYM_V_INTERNAL = 0x1000 + SYM_V_HIDDEN = 0x2000 + SYM_V_PROTECTED = 0x3000 + SYM_V_EXPORTED = 0x4000 + SYM_TYPE_FUNC = 0x0020 // is function +) + +// Storage Class. +const ( + C_NULL = 0 // Symbol table entry marked for deletion + C_EXT = 2 // External symbol + C_STAT = 3 // Static symbol + C_BLOCK = 100 // Beginning or end of inner block + C_FCN = 101 // Beginning or end of function + C_FILE = 103 // Source file name and compiler information + C_HIDEXT = 107 // Unnamed external symbol + C_BINCL = 108 // Beginning of include file + C_EINCL = 109 // End of include file + C_WEAKEXT = 111 // Weak external symbol + C_DWARF = 112 // DWARF symbol + C_GSYM = 128 // Global variable + C_LSYM = 129 // Automatic variable allocated on stack + C_PSYM = 130 // Argument to subroutine allocated on stack + C_RSYM = 131 // Register variable + C_RPSYM = 132 // Argument to function or procedure stored in register + C_STSYM = 133 // Statically allocated symbol + C_BCOMM = 135 // Beginning of common block + C_ECOML = 136 // Local member of common block + C_ECOMM = 137 // End of common block + C_DECL = 140 // Declaration of object + C_ENTRY = 141 // Alternate entry + C_FUN = 142 // Function or procedure + C_BSTAT = 143 // Beginning of static block + C_ESTAT = 144 // End of static block + C_GTLS = 145 // Global thread-local variable + C_STTLS = 146 // Static thread-local variable +) + +// File Auxiliary Entry +type AuxFile64 struct { + Xfname [8]byte // Name or offset inside string table + Xftype uint8 // Source file string type + Xauxtype uint8 // Type of auxiliary entry +} + +// Function Auxiliary Entry +type AuxFcn32 struct { + Xexptr uint32 // File offset to exception table entry + Xfsize uint32 // Size of function in bytes + Xlnnoptr uint32 // File pointer to line number + Xendndx uint32 // Symbol table index of next entry + Xpad uint16 // Unused +} +type AuxFcn64 struct { + Xlnnoptr uint64 // File pointer to line number + Xfsize uint32 // Size of function in bytes + Xendndx uint32 // Symbol table index of next entry + Xpad uint8 // Unused + Xauxtype uint8 // Type of auxiliary entry +} + +type AuxSect64 struct { + Xscnlen uint64 // section length + Xnreloc uint64 // Num RLDs + pad uint8 + Xauxtype uint8 // Type of auxiliary entry +} + +// csect Auxiliary Entry. +type AuxCSect32 struct { + Xscnlen uint32 // Length or symbol table index + Xparmhash uint32 // Offset of parameter type-check string + Xsnhash uint16 // .typchk section number + Xsmtyp uint8 // Symbol alignment and type + Xsmclas uint8 // Storage-mapping class + Xstab uint32 // Reserved + Xsnstab uint16 // Reserved +} + +type AuxCSect64 struct { + Xscnlenlo uint32 // Lower 4 bytes of length or symbol table index + Xparmhash uint32 // Offset of parameter type-check string + Xsnhash uint16 // .typchk section number + Xsmtyp uint8 // Symbol alignment and type + Xsmclas uint8 // Storage-mapping class + Xscnlenhi uint32 // Upper 4 bytes of length or symbol table index + Xpad uint8 // Unused + Xauxtype uint8 // Type of auxiliary entry +} + +// Auxiliary type +const ( + _AUX_EXCEPT = 255 + _AUX_FCN = 254 + _AUX_SYM = 253 + _AUX_FILE = 252 + _AUX_CSECT = 251 + _AUX_SECT = 250 +) + +// Symbol type field. +const ( + XTY_ER = 0 // External reference + XTY_SD = 1 // Section definition + XTY_LD = 2 // Label definition + XTY_CM = 3 // Common csect definition +) + +// Defines for File auxiliary definitions: x_ftype field of x_file +const ( + XFT_FN = 0 // Source File Name + XFT_CT = 1 // Compile Time Stamp + XFT_CV = 2 // Compiler Version Number + XFT_CD = 128 // Compiler Defined Information +) + +// Storage-mapping class. +const ( + XMC_PR = 0 // Program code + XMC_RO = 1 // Read-only constant + XMC_DB = 2 // Debug dictionary table + XMC_TC = 3 // TOC entry + XMC_UA = 4 // Unclassified + XMC_RW = 5 // Read/Write data + XMC_GL = 6 // Global linkage + XMC_XO = 7 // Extended operation + XMC_SV = 8 // 32-bit supervisor call descriptor + XMC_BS = 9 // BSS class + XMC_DS = 10 // Function descriptor + XMC_UC = 11 // Unnamed FORTRAN common + XMC_TC0 = 15 // TOC anchor + XMC_TD = 16 // Scalar data entry in the TOC + XMC_SV64 = 17 // 64-bit supervisor call descriptor + XMC_SV3264 = 18 // Supervisor call descriptor for both 32-bit and 64-bit + XMC_TL = 20 // Read/Write thread-local data + XMC_UL = 21 // Read/Write thread-local data (.tbss) + XMC_TE = 22 // TOC entry +) + +// Loader Header. +type LoaderHeader32 struct { + Lversion uint32 // Loader section version number + Lnsyms uint32 // Number of symbol table entries + Lnreloc uint32 // Number of relocation table entries + Listlen uint32 // Length of import file ID string table + Lnimpid uint32 // Number of import file IDs + Limpoff uint32 // Offset to start of import file IDs + Lstlen uint32 // Length of string table + Lstoff uint32 // Offset to start of string table +} + +type LoaderHeader64 struct { + Lversion uint32 // Loader section version number + Lnsyms uint32 // Number of symbol table entries + Lnreloc uint32 // Number of relocation table entries + Listlen uint32 // Length of import file ID string table + Lnimpid uint32 // Number of import file IDs + Lstlen uint32 // Length of string table + Limpoff uint64 // Offset to start of import file IDs + Lstoff uint64 // Offset to start of string table + Lsymoff uint64 // Offset to start of symbol table + Lrldoff uint64 // Offset to start of relocation entries +} + +const ( + LDHDRSZ_32 = 32 + LDHDRSZ_64 = 56 +) + +// Loader Symbol. +type LoaderSymbol32 struct { + Lname [8]byte // Symbol name or byte offset into string table + Lvalue uint32 // Address field + Lscnum uint16 // Section number containing symbol + Lsmtype uint8 // Symbol type, export, import flags + Lsmclas uint8 // Symbol storage class + Lifile uint32 // Import file ID; ordinal of import file IDs + Lparm uint32 // Parameter type-check field +} + +type LoaderSymbol64 struct { + Lvalue uint64 // Address field + Loffset uint32 // Byte offset into string table of symbol name + Lscnum uint16 // Section number containing symbol + Lsmtype uint8 // Symbol type, export, import flags + Lsmclas uint8 // Symbol storage class + Lifile uint32 // Import file ID; ordinal of import file IDs + Lparm uint32 // Parameter type-check field +} + +type Reloc32 struct { + Rvaddr uint32 // (virtual) address of reference + Rsymndx uint32 // Index into symbol table + Rsize uint8 // Sign and reloc bit len + Rtype uint8 // Toc relocation type +} + +type Reloc64 struct { + Rvaddr uint64 // (virtual) address of reference + Rsymndx uint32 // Index into symbol table + Rsize uint8 // Sign and reloc bit len + Rtype uint8 // Toc relocation type +} + +const ( + R_POS = 0x00 // A(sym) Positive Relocation + R_NEG = 0x01 // -A(sym) Negative Relocation + R_REL = 0x02 // A(sym-*) Relative to self + R_TOC = 0x03 // A(sym-TOC) Relative to TOC + R_TRL = 0x12 // A(sym-TOC) TOC Relative indirect load. + + R_TRLA = 0x13 // A(sym-TOC) TOC Rel load address. modifiable inst + R_GL = 0x05 // A(external TOC of sym) Global Linkage + R_TCL = 0x06 // A(local TOC of sym) Local object TOC address + R_RL = 0x0C // A(sym) Pos indirect load. modifiable instruction + R_RLA = 0x0D // A(sym) Pos Load Address. modifiable instruction + R_REF = 0x0F // AL0(sym) Non relocating ref. No garbage collect + R_BA = 0x08 // A(sym) Branch absolute. Cannot modify instruction + R_RBA = 0x18 // A(sym) Branch absolute. modifiable instruction + R_BR = 0x0A // A(sym-*) Branch rel to self. non modifiable + R_RBR = 0x1A // A(sym-*) Branch rel to self. modifiable instr + + R_TLS = 0x20 // General-dynamic reference to TLS symbol + R_TLS_IE = 0x21 // Initial-exec reference to TLS symbol + R_TLS_LD = 0x22 // Local-dynamic reference to TLS symbol + R_TLS_LE = 0x23 // Local-exec reference to TLS symbol + R_TLSM = 0x24 // Module reference to TLS symbol + R_TLSML = 0x25 // Module reference to local (own) module + + R_TOCU = 0x30 // Relative to TOC - high order bits + R_TOCL = 0x31 // Relative to TOC - low order bits +) diff --git a/go/src/internal/zstd/bits.go b/go/src/internal/zstd/bits.go new file mode 100644 index 0000000000000000000000000000000000000000..c9a2f708023444553dae2910a2c77e30efcd4427 --- /dev/null +++ b/go/src/internal/zstd/bits.go @@ -0,0 +1,130 @@ +// 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 zstd + +import ( + "math/bits" +) + +// block is the data for a single compressed block. +// The data starts immediately after the 3 byte block header, +// and is Block_Size bytes long. +type block []byte + +// bitReader reads a bit stream going forward. +type bitReader struct { + r *Reader // for error reporting + data block // the bits to read + off uint32 // current offset into data + bits uint32 // bits ready to be returned + cnt uint32 // number of valid bits in the bits field +} + +// makeBitReader makes a bit reader starting at off. +func (r *Reader) makeBitReader(data block, off int) bitReader { + return bitReader{ + r: r, + data: data, + off: uint32(off), + } +} + +// moreBits is called to read more bits. +// This ensures that at least 16 bits are available. +func (br *bitReader) moreBits() error { + for br.cnt < 16 { + if br.off >= uint32(len(br.data)) { + return br.r.makeEOFError(int(br.off)) + } + c := br.data[br.off] + br.off++ + br.bits |= uint32(c) << br.cnt + br.cnt += 8 + } + return nil +} + +// val is called to fetch a value of b bits. +func (br *bitReader) val(b uint8) uint32 { + r := br.bits & ((1 << b) - 1) + br.bits >>= b + br.cnt -= uint32(b) + return r +} + +// backup steps back to the last byte we used. +func (br *bitReader) backup() { + for br.cnt >= 8 { + br.off-- + br.cnt -= 8 + } +} + +// makeError returns an error at the current offset wrapping a string. +func (br *bitReader) makeError(msg string) error { + return br.r.makeError(int(br.off), msg) +} + +// reverseBitReader reads a bit stream in reverse. +type reverseBitReader struct { + r *Reader // for error reporting + data block // the bits to read + off uint32 // current offset into data + start uint32 // start in data; we read backward to start + bits uint32 // bits ready to be returned + cnt uint32 // number of valid bits in bits field +} + +// makeReverseBitReader makes a reverseBitReader reading backward +// from off to start. The bitstream starts with a 1 bit in the last +// byte, at off. +func (r *Reader) makeReverseBitReader(data block, off, start int) (reverseBitReader, error) { + streamStart := data[off] + if streamStart == 0 { + return reverseBitReader{}, r.makeError(off, "zero byte at reverse bit stream start") + } + rbr := reverseBitReader{ + r: r, + data: data, + off: uint32(off), + start: uint32(start), + bits: uint32(streamStart), + cnt: uint32(7 - bits.LeadingZeros8(streamStart)), + } + return rbr, nil +} + +// val is called to fetch a value of b bits. +func (rbr *reverseBitReader) val(b uint8) (uint32, error) { + if !rbr.fetch(b) { + return 0, rbr.r.makeEOFError(int(rbr.off)) + } + + rbr.cnt -= uint32(b) + v := (rbr.bits >> rbr.cnt) & ((1 << b) - 1) + return v, nil +} + +// fetch is called to ensure that at least b bits are available. +// It reports false if this can't be done, +// in which case only rbr.cnt bits are available. +func (rbr *reverseBitReader) fetch(b uint8) bool { + for rbr.cnt < uint32(b) { + if rbr.off <= rbr.start { + return false + } + rbr.off-- + c := rbr.data[rbr.off] + rbr.bits <<= 8 + rbr.bits |= uint32(c) + rbr.cnt += 8 + } + return true +} + +// makeError returns an error at the current offset wrapping a string. +func (rbr *reverseBitReader) makeError(msg string) error { + return rbr.r.makeError(int(rbr.off), msg) +} diff --git a/go/src/internal/zstd/block.go b/go/src/internal/zstd/block.go new file mode 100644 index 0000000000000000000000000000000000000000..11a99cd778e834c5d8afe9c34cfc46c8667546ff --- /dev/null +++ b/go/src/internal/zstd/block.go @@ -0,0 +1,425 @@ +// 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 zstd + +import ( + "io" +) + +// debug can be set in the source to print debug info using println. +const debug = false + +// compressedBlock decompresses a compressed block, storing the decompressed +// data in r.buffer. The blockSize argument is the compressed size. +// RFC 3.1.1.3. +func (r *Reader) compressedBlock(blockSize int) error { + if len(r.compressedBuf) >= blockSize { + r.compressedBuf = r.compressedBuf[:blockSize] + } else { + // We know that blockSize <= 128K, + // so this won't allocate an enormous amount. + need := blockSize - len(r.compressedBuf) + r.compressedBuf = append(r.compressedBuf, make([]byte, need)...) + } + + if _, err := io.ReadFull(r.r, r.compressedBuf); err != nil { + return r.wrapNonEOFError(0, err) + } + + data := block(r.compressedBuf) + off := 0 + r.buffer = r.buffer[:0] + + litoff, litbuf, err := r.readLiterals(data, off, r.literals[:0]) + if err != nil { + return err + } + r.literals = litbuf + + off = litoff + + seqCount, off, err := r.initSeqs(data, off) + if err != nil { + return err + } + + if seqCount == 0 { + // No sequences, just literals. + if off < len(data) { + return r.makeError(off, "extraneous data after no sequences") + } + + r.buffer = append(r.buffer, litbuf...) + + return nil + } + + return r.execSeqs(data, off, litbuf, seqCount) +} + +// seqCode is the kind of sequence codes we have to handle. +type seqCode int + +const ( + seqLiteral seqCode = iota + seqOffset + seqMatch +) + +// seqCodeInfoData is the information needed to set up seqTables and +// seqTableBits for a particular kind of sequence code. +type seqCodeInfoData struct { + predefTable []fseBaselineEntry // predefined FSE + predefTableBits int // number of bits in predefTable + maxSym int // max symbol value in FSE + maxBits int // max bits for FSE + + // toBaseline converts from an FSE table to an FSE baseline table. + toBaseline func(*Reader, int, []fseEntry, []fseBaselineEntry) error +} + +// seqCodeInfo is the seqCodeInfoData for each kind of sequence code. +var seqCodeInfo = [3]seqCodeInfoData{ + seqLiteral: { + predefTable: predefinedLiteralTable[:], + predefTableBits: 6, + maxSym: 35, + maxBits: 9, + toBaseline: (*Reader).makeLiteralBaselineFSE, + }, + seqOffset: { + predefTable: predefinedOffsetTable[:], + predefTableBits: 5, + maxSym: 31, + maxBits: 8, + toBaseline: (*Reader).makeOffsetBaselineFSE, + }, + seqMatch: { + predefTable: predefinedMatchTable[:], + predefTableBits: 6, + maxSym: 52, + maxBits: 9, + toBaseline: (*Reader).makeMatchBaselineFSE, + }, +} + +// initSeqs reads the Sequences_Section_Header and sets up the FSE +// tables used to read the sequence codes. It returns the number of +// sequences and the new offset. RFC 3.1.1.3.2.1. +func (r *Reader) initSeqs(data block, off int) (int, int, error) { + if off >= len(data) { + return 0, 0, r.makeEOFError(off) + } + + seqHdr := data[off] + off++ + if seqHdr == 0 { + return 0, off, nil + } + + var seqCount int + if seqHdr < 128 { + seqCount = int(seqHdr) + } else if seqHdr < 255 { + if off >= len(data) { + return 0, 0, r.makeEOFError(off) + } + seqCount = ((int(seqHdr) - 128) << 8) + int(data[off]) + off++ + } else { + if off+1 >= len(data) { + return 0, 0, r.makeEOFError(off) + } + seqCount = int(data[off]) + (int(data[off+1]) << 8) + 0x7f00 + off += 2 + } + + // Read the Symbol_Compression_Modes byte. + + if off >= len(data) { + return 0, 0, r.makeEOFError(off) + } + symMode := data[off] + if symMode&3 != 0 { + return 0, 0, r.makeError(off, "invalid symbol compression mode") + } + off++ + + // Set up the FSE tables used to decode the sequence codes. + + var err error + off, err = r.setSeqTable(data, off, seqLiteral, (symMode>>6)&3) + if err != nil { + return 0, 0, err + } + + off, err = r.setSeqTable(data, off, seqOffset, (symMode>>4)&3) + if err != nil { + return 0, 0, err + } + + off, err = r.setSeqTable(data, off, seqMatch, (symMode>>2)&3) + if err != nil { + return 0, 0, err + } + + return seqCount, off, nil +} + +// setSeqTable uses the Compression_Mode in mode to set up r.seqTables and +// r.seqTableBits for kind. We store these in the Reader because one of +// the modes simply reuses the value from the last block in the frame. +func (r *Reader) setSeqTable(data block, off int, kind seqCode, mode byte) (int, error) { + info := &seqCodeInfo[kind] + switch mode { + case 0: + // Predefined_Mode + r.seqTables[kind] = info.predefTable + r.seqTableBits[kind] = uint8(info.predefTableBits) + return off, nil + + case 1: + // RLE_Mode + if off >= len(data) { + return 0, r.makeEOFError(off) + } + rle := data[off] + off++ + + // Build a simple baseline table that always returns rle. + + entry := []fseEntry{ + { + sym: rle, + bits: 0, + base: 0, + }, + } + if cap(r.seqTableBuffers[kind]) == 0 { + r.seqTableBuffers[kind] = make([]fseBaselineEntry, 1< 128<<10 { + return rbr.makeError("uncompressed size too big") + } + + ptoffset := &r.seqTables[seqOffset][offsetState] + ptmatch := &r.seqTables[seqMatch][matchState] + ptliteral := &r.seqTables[seqLiteral][literalState] + + add, err := rbr.val(ptoffset.basebits) + if err != nil { + return err + } + offset := ptoffset.baseline + add + + add, err = rbr.val(ptmatch.basebits) + if err != nil { + return err + } + match := ptmatch.baseline + add + + add, err = rbr.val(ptliteral.basebits) + if err != nil { + return err + } + literal := ptliteral.baseline + add + + // Handle repeat offsets. RFC 3.1.1.5. + // See the comment in makeOffsetBaselineFSE. + if ptoffset.basebits > 1 { + r.repeatedOffset3 = r.repeatedOffset2 + r.repeatedOffset2 = r.repeatedOffset1 + r.repeatedOffset1 = offset + } else { + if literal == 0 { + offset++ + } + switch offset { + case 1: + offset = r.repeatedOffset1 + case 2: + offset = r.repeatedOffset2 + r.repeatedOffset2 = r.repeatedOffset1 + r.repeatedOffset1 = offset + case 3: + offset = r.repeatedOffset3 + r.repeatedOffset3 = r.repeatedOffset2 + r.repeatedOffset2 = r.repeatedOffset1 + r.repeatedOffset1 = offset + case 4: + offset = r.repeatedOffset1 - 1 + r.repeatedOffset3 = r.repeatedOffset2 + r.repeatedOffset2 = r.repeatedOffset1 + r.repeatedOffset1 = offset + } + } + + seq++ + if seq < seqCount { + // Update the states. + add, err = rbr.val(ptliteral.bits) + if err != nil { + return err + } + literalState = uint32(ptliteral.base) + add + + add, err = rbr.val(ptmatch.bits) + if err != nil { + return err + } + matchState = uint32(ptmatch.base) + add + + add, err = rbr.val(ptoffset.bits) + if err != nil { + return err + } + offsetState = uint32(ptoffset.base) + add + } + + // The next sequence is now in literal, offset, match. + + if debug { + println("literal", literal, "offset", offset, "match", match) + } + + // Copy literal bytes from litbuf. + if literal > uint32(len(litbuf)) { + return rbr.makeError("literal byte overflow") + } + if literal > 0 { + r.buffer = append(r.buffer, litbuf[:literal]...) + litbuf = litbuf[literal:] + } + + if match > 0 { + if err := r.copyFromWindow(&rbr, offset, match); err != nil { + return err + } + } + } + + r.buffer = append(r.buffer, litbuf...) + + if rbr.cnt != 0 { + return r.makeError(off, "extraneous data after sequences") + } + + return nil +} + +// Copy match bytes from the decoded output, or the window, at offset. +func (r *Reader) copyFromWindow(rbr *reverseBitReader, offset, match uint32) error { + if offset == 0 { + return rbr.makeError("invalid zero offset") + } + + // Offset may point into the buffer or the window and + // match may extend past the end of the initial buffer. + // |--r.window--|--r.buffer--| + // |<-----offset------| + // |------match----------->| + bufferOffset := uint32(0) + lenBlock := uint32(len(r.buffer)) + if lenBlock < offset { + lenWindow := r.window.len() + copy := offset - lenBlock + if copy > lenWindow { + return rbr.makeError("offset past window") + } + windowOffset := lenWindow - copy + if copy > match { + copy = match + } + r.buffer = r.window.appendTo(r.buffer, windowOffset, windowOffset+copy) + match -= copy + } else { + bufferOffset = lenBlock - offset + } + + // We are being asked to copy data that we are adding to the + // buffer in the same copy. + for match > 0 { + copy := uint32(len(r.buffer)) - bufferOffset + if copy > match { + copy = match + } + r.buffer = append(r.buffer, r.buffer[bufferOffset:bufferOffset+copy]...) + match -= copy + } + return nil +} diff --git a/go/src/internal/zstd/fse.go b/go/src/internal/zstd/fse.go new file mode 100644 index 0000000000000000000000000000000000000000..f03a792edebbf36e3dd9ce3f8d3c55f307548a1f --- /dev/null +++ b/go/src/internal/zstd/fse.go @@ -0,0 +1,437 @@ +// 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 zstd + +import ( + "math/bits" +) + +// fseEntry is one entry in an FSE table. +type fseEntry struct { + sym uint8 // value that this entry records + bits uint8 // number of bits to read to determine next state + base uint16 // add those bits to this state to get the next state +} + +// readFSE reads an FSE table from data starting at off. +// maxSym is the maximum symbol value. +// maxBits is the maximum number of bits permitted for symbols in the table. +// The FSE is written into table, which must be at least 1< maxBits { + return 0, 0, br.makeError("FSE accuracy log too large") + } + + // The number of remaining probabilities, plus 1. + // This determines the number of bits to be read for the next value. + remaining := (1 << accuracyLog) + 1 + + // The current difference between small and large values, + // which depends on the number of remaining values. + // Small values use 1 less bit. + threshold := 1 << accuracyLog + + // The number of bits needed to compute threshold. + bitsNeeded := accuracyLog + 1 + + // The next character value. + sym := 0 + + // Whether the last count was 0. + prev0 := false + + var norm [256]int16 + + for remaining > 1 && sym <= maxSym { + if err := br.moreBits(); err != nil { + return 0, 0, err + } + + if prev0 { + // Previous count was 0, so there is a 2-bit + // repeat flag. If the 2-bit flag is 0b11, + // it adds 3 and then there is another repeat flag. + zsym := sym + for (br.bits & 0xfff) == 0xfff { + zsym += 3 * 6 + br.bits >>= 12 + br.cnt -= 12 + if err := br.moreBits(); err != nil { + return 0, 0, err + } + } + for (br.bits & 3) == 3 { + zsym += 3 + br.bits >>= 2 + br.cnt -= 2 + if err := br.moreBits(); err != nil { + return 0, 0, err + } + } + + // We have at least 14 bits here, + // no need to call moreBits + + zsym += int(br.val(2)) + + if zsym > maxSym { + return 0, 0, br.makeError("FSE symbol index overflow") + } + + for ; sym < zsym; sym++ { + norm[uint8(sym)] = 0 + } + + prev0 = false + continue + } + + max := (2*threshold - 1) - remaining + var count int + if int(br.bits&uint32(threshold-1)) < max { + // A small value. + count = int(br.bits & uint32((threshold - 1))) + br.bits >>= bitsNeeded - 1 + br.cnt -= uint32(bitsNeeded - 1) + } else { + // A large value. + count = int(br.bits & uint32((2*threshold - 1))) + if count >= threshold { + count -= max + } + br.bits >>= bitsNeeded + br.cnt -= uint32(bitsNeeded) + } + + count-- + if count >= 0 { + remaining -= count + } else { + remaining-- + } + if sym >= 256 { + return 0, 0, br.makeError("FSE sym overflow") + } + norm[uint8(sym)] = int16(count) + sym++ + + prev0 = count == 0 + + for remaining < threshold { + bitsNeeded-- + threshold >>= 1 + } + } + + if remaining != 1 { + return 0, 0, br.makeError("too many symbols in FSE table") + } + + for ; sym <= maxSym; sym++ { + norm[uint8(sym)] = 0 + } + + br.backup() + + if err := r.buildFSE(off, norm[:maxSym+1], table, accuracyLog); err != nil { + return 0, 0, err + } + + return accuracyLog, int(br.off), nil +} + +// buildFSE builds an FSE decoding table from a list of probabilities. +// The probabilities are in norm. next is scratch space. The number of bits +// in the table is tableBits. +func (r *Reader) buildFSE(off int, norm []int16, table []fseEntry, tableBits int) error { + tableSize := 1 << tableBits + highThreshold := tableSize - 1 + + var next [256]uint16 + + for i, n := range norm { + if n >= 0 { + next[uint8(i)] = uint16(n) + } else { + table[highThreshold].sym = uint8(i) + highThreshold-- + next[uint8(i)] = 1 + } + } + + pos := 0 + step := (tableSize >> 1) + (tableSize >> 3) + 3 + mask := tableSize - 1 + for i, n := range norm { + for j := 0; j < int(n); j++ { + table[pos].sym = uint8(i) + pos = (pos + step) & mask + for pos > highThreshold { + pos = (pos + step) & mask + } + } + } + if pos != 0 { + return r.makeError(off, "FSE count error") + } + + for i := 0; i < tableSize; i++ { + sym := table[i].sym + nextState := next[sym] + next[sym]++ + + if nextState == 0 { + return r.makeError(off, "FSE state error") + } + + highBit := 15 - bits.LeadingZeros16(nextState) + + bits := tableBits - highBit + table[i].bits = uint8(bits) + table[i].base = (nextState << bits) - uint16(tableSize) + } + + return nil +} + +// fseBaselineEntry is an entry in an FSE baseline table. +// We use these for literal/match/length values. +// Those require mapping the symbol to a baseline value, +// and then reading zero or more bits and adding the value to the baseline. +// Rather than looking these up in separate tables, +// we convert the FSE table to an FSE baseline table. +type fseBaselineEntry struct { + baseline uint32 // baseline for value that this entry represents + basebits uint8 // number of bits to read to add to baseline + bits uint8 // number of bits to read to determine next state + base uint16 // add the bits to this base to get the next state +} + +// Given a literal length code, we need to read a number of bits and +// add that to a baseline. For states 0 to 15 the baseline is the +// state and the number of bits is zero. RFC 3.1.1.3.2.1.1. + +const literalLengthOffset = 16 + +var literalLengthBase = []uint32{ + 16 | (1 << 24), + 18 | (1 << 24), + 20 | (1 << 24), + 22 | (1 << 24), + 24 | (2 << 24), + 28 | (2 << 24), + 32 | (3 << 24), + 40 | (3 << 24), + 48 | (4 << 24), + 64 | (6 << 24), + 128 | (7 << 24), + 256 | (8 << 24), + 512 | (9 << 24), + 1024 | (10 << 24), + 2048 | (11 << 24), + 4096 | (12 << 24), + 8192 | (13 << 24), + 16384 | (14 << 24), + 32768 | (15 << 24), + 65536 | (16 << 24), +} + +// makeLiteralBaselineFSE converts the literal length fseTable to baselineTable. +func (r *Reader) makeLiteralBaselineFSE(off int, fseTable []fseEntry, baselineTable []fseBaselineEntry) error { + for i, e := range fseTable { + be := fseBaselineEntry{ + bits: e.bits, + base: e.base, + } + if e.sym < literalLengthOffset { + be.baseline = uint32(e.sym) + be.basebits = 0 + } else { + if e.sym > 35 { + return r.makeError(off, "FSE baseline symbol overflow") + } + idx := e.sym - literalLengthOffset + basebits := literalLengthBase[idx] + be.baseline = basebits & 0xffffff + be.basebits = uint8(basebits >> 24) + } + baselineTable[i] = be + } + return nil +} + +// makeOffsetBaselineFSE converts the offset length fseTable to baselineTable. +func (r *Reader) makeOffsetBaselineFSE(off int, fseTable []fseEntry, baselineTable []fseBaselineEntry) error { + for i, e := range fseTable { + be := fseBaselineEntry{ + bits: e.bits, + base: e.base, + } + if e.sym > 31 { + return r.makeError(off, "FSE offset symbol overflow") + } + + // The simple way to write this is + // be.baseline = 1 << e.sym + // be.basebits = e.sym + // That would give us an offset value that corresponds to + // the one described in the RFC. However, for offsets > 3 + // we have to subtract 3. And for offset values 1, 2, 3 + // we use a repeated offset. + // + // The baseline is always a power of 2, and is never 0, + // so for those low values we will see one entry that is + // baseline 1, basebits 0, and one entry that is baseline 2, + // basebits 1. All other entries will have baseline >= 4 + // basebits >= 2. + // + // So we can check for RFC offset <= 3 by checking for + // basebits <= 1. That means that we can subtract 3 here + // and not worry about doing it in the hot loop. + + be.baseline = 1 << e.sym + if e.sym >= 2 { + be.baseline -= 3 + } + be.basebits = e.sym + baselineTable[i] = be + } + return nil +} + +// Given a match length code, we need to read a number of bits and add +// that to a baseline. For states 0 to 31 the baseline is state+3 and +// the number of bits is zero. RFC 3.1.1.3.2.1.1. + +const matchLengthOffset = 32 + +var matchLengthBase = []uint32{ + 35 | (1 << 24), + 37 | (1 << 24), + 39 | (1 << 24), + 41 | (1 << 24), + 43 | (2 << 24), + 47 | (2 << 24), + 51 | (3 << 24), + 59 | (3 << 24), + 67 | (4 << 24), + 83 | (4 << 24), + 99 | (5 << 24), + 131 | (7 << 24), + 259 | (8 << 24), + 515 | (9 << 24), + 1027 | (10 << 24), + 2051 | (11 << 24), + 4099 | (12 << 24), + 8195 | (13 << 24), + 16387 | (14 << 24), + 32771 | (15 << 24), + 65539 | (16 << 24), +} + +// makeMatchBaselineFSE converts the match length fseTable to baselineTable. +func (r *Reader) makeMatchBaselineFSE(off int, fseTable []fseEntry, baselineTable []fseBaselineEntry) error { + for i, e := range fseTable { + be := fseBaselineEntry{ + bits: e.bits, + base: e.base, + } + if e.sym < matchLengthOffset { + be.baseline = uint32(e.sym) + 3 + be.basebits = 0 + } else { + if e.sym > 52 { + return r.makeError(off, "FSE baseline symbol overflow") + } + idx := e.sym - matchLengthOffset + basebits := matchLengthBase[idx] + be.baseline = basebits & 0xffffff + be.basebits = uint8(basebits >> 24) + } + baselineTable[i] = be + } + return nil +} + +// predefinedLiteralTable is the predefined table to use for literal lengths. +// Generated from table in RFC 3.1.1.3.2.2.1. +// Checked by TestPredefinedTables. +var predefinedLiteralTable = [...]fseBaselineEntry{ + {0, 0, 4, 0}, {0, 0, 4, 16}, {1, 0, 5, 32}, + {3, 0, 5, 0}, {4, 0, 5, 0}, {6, 0, 5, 0}, + {7, 0, 5, 0}, {9, 0, 5, 0}, {10, 0, 5, 0}, + {12, 0, 5, 0}, {14, 0, 6, 0}, {16, 1, 5, 0}, + {20, 1, 5, 0}, {22, 1, 5, 0}, {28, 2, 5, 0}, + {32, 3, 5, 0}, {48, 4, 5, 0}, {64, 6, 5, 32}, + {128, 7, 5, 0}, {256, 8, 6, 0}, {1024, 10, 6, 0}, + {4096, 12, 6, 0}, {0, 0, 4, 32}, {1, 0, 4, 0}, + {2, 0, 5, 0}, {4, 0, 5, 32}, {5, 0, 5, 0}, + {7, 0, 5, 32}, {8, 0, 5, 0}, {10, 0, 5, 32}, + {11, 0, 5, 0}, {13, 0, 6, 0}, {16, 1, 5, 32}, + {18, 1, 5, 0}, {22, 1, 5, 32}, {24, 2, 5, 0}, + {32, 3, 5, 32}, {40, 3, 5, 0}, {64, 6, 4, 0}, + {64, 6, 4, 16}, {128, 7, 5, 32}, {512, 9, 6, 0}, + {2048, 11, 6, 0}, {0, 0, 4, 48}, {1, 0, 4, 16}, + {2, 0, 5, 32}, {3, 0, 5, 32}, {5, 0, 5, 32}, + {6, 0, 5, 32}, {8, 0, 5, 32}, {9, 0, 5, 32}, + {11, 0, 5, 32}, {12, 0, 5, 32}, {15, 0, 6, 0}, + {18, 1, 5, 32}, {20, 1, 5, 32}, {24, 2, 5, 32}, + {28, 2, 5, 32}, {40, 3, 5, 32}, {48, 4, 5, 32}, + {65536, 16, 6, 0}, {32768, 15, 6, 0}, {16384, 14, 6, 0}, + {8192, 13, 6, 0}, +} + +// predefinedOffsetTable is the predefined table to use for offsets. +// Generated from table in RFC 3.1.1.3.2.2.3. +// Checked by TestPredefinedTables. +var predefinedOffsetTable = [...]fseBaselineEntry{ + {1, 0, 5, 0}, {61, 6, 4, 0}, {509, 9, 5, 0}, + {32765, 15, 5, 0}, {2097149, 21, 5, 0}, {5, 3, 5, 0}, + {125, 7, 4, 0}, {4093, 12, 5, 0}, {262141, 18, 5, 0}, + {8388605, 23, 5, 0}, {29, 5, 5, 0}, {253, 8, 4, 0}, + {16381, 14, 5, 0}, {1048573, 20, 5, 0}, {1, 2, 5, 0}, + {125, 7, 4, 16}, {2045, 11, 5, 0}, {131069, 17, 5, 0}, + {4194301, 22, 5, 0}, {13, 4, 5, 0}, {253, 8, 4, 16}, + {8189, 13, 5, 0}, {524285, 19, 5, 0}, {2, 1, 5, 0}, + {61, 6, 4, 16}, {1021, 10, 5, 0}, {65533, 16, 5, 0}, + {268435453, 28, 5, 0}, {134217725, 27, 5, 0}, {67108861, 26, 5, 0}, + {33554429, 25, 5, 0}, {16777213, 24, 5, 0}, +} + +// predefinedMatchTable is the predefined table to use for match lengths. +// Generated from table in RFC 3.1.1.3.2.2.2. +// Checked by TestPredefinedTables. +var predefinedMatchTable = [...]fseBaselineEntry{ + {3, 0, 6, 0}, {4, 0, 4, 0}, {5, 0, 5, 32}, + {6, 0, 5, 0}, {8, 0, 5, 0}, {9, 0, 5, 0}, + {11, 0, 5, 0}, {13, 0, 6, 0}, {16, 0, 6, 0}, + {19, 0, 6, 0}, {22, 0, 6, 0}, {25, 0, 6, 0}, + {28, 0, 6, 0}, {31, 0, 6, 0}, {34, 0, 6, 0}, + {37, 1, 6, 0}, {41, 1, 6, 0}, {47, 2, 6, 0}, + {59, 3, 6, 0}, {83, 4, 6, 0}, {131, 7, 6, 0}, + {515, 9, 6, 0}, {4, 0, 4, 16}, {5, 0, 4, 0}, + {6, 0, 5, 32}, {7, 0, 5, 0}, {9, 0, 5, 32}, + {10, 0, 5, 0}, {12, 0, 6, 0}, {15, 0, 6, 0}, + {18, 0, 6, 0}, {21, 0, 6, 0}, {24, 0, 6, 0}, + {27, 0, 6, 0}, {30, 0, 6, 0}, {33, 0, 6, 0}, + {35, 1, 6, 0}, {39, 1, 6, 0}, {43, 2, 6, 0}, + {51, 3, 6, 0}, {67, 4, 6, 0}, {99, 5, 6, 0}, + {259, 8, 6, 0}, {4, 0, 4, 32}, {4, 0, 4, 48}, + {5, 0, 4, 16}, {7, 0, 5, 32}, {8, 0, 5, 32}, + {10, 0, 5, 32}, {11, 0, 5, 32}, {14, 0, 6, 0}, + {17, 0, 6, 0}, {20, 0, 6, 0}, {23, 0, 6, 0}, + {26, 0, 6, 0}, {29, 0, 6, 0}, {32, 0, 6, 0}, + {65539, 16, 6, 0}, {32771, 15, 6, 0}, {16387, 14, 6, 0}, + {8195, 13, 6, 0}, {4099, 12, 6, 0}, {2051, 11, 6, 0}, + {1027, 10, 6, 0}, +} diff --git a/go/src/internal/zstd/fse_test.go b/go/src/internal/zstd/fse_test.go new file mode 100644 index 0000000000000000000000000000000000000000..20365745a5402e3d4c2f46b65f1c1535d0b7237c --- /dev/null +++ b/go/src/internal/zstd/fse_test.go @@ -0,0 +1,88 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package zstd + +import ( + "slices" + "testing" +) + +// literalPredefinedDistribution is the predefined distribution table +// for literal lengths. RFC 3.1.1.3.2.2.1. +var literalPredefinedDistribution = []int16{ + 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, + -1, -1, -1, -1, +} + +// offsetPredefinedDistribution is the predefined distribution table +// for offsets. RFC 3.1.1.3.2.2.3. +var offsetPredefinedDistribution = []int16{ + 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, +} + +// matchPredefinedDistribution is the predefined distribution table +// for match lengths. RFC 3.1.1.3.2.2.2. +var matchPredefinedDistribution = []int16{ + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, + -1, -1, -1, -1, -1, +} + +// TestPredefinedTables verifies that we can generate the predefined +// literal/offset/match tables from the input data in RFC 8878. +// This serves as a test of the predefined tables, and also of buildFSE +// and the functions that make baseline FSE tables. +func TestPredefinedTables(t *testing.T) { + tests := []struct { + name string + distribution []int16 + tableBits int + toBaseline func(*Reader, int, []fseEntry, []fseBaselineEntry) error + predef []fseBaselineEntry + }{ + { + name: "literal", + distribution: literalPredefinedDistribution, + tableBits: 6, + toBaseline: (*Reader).makeLiteralBaselineFSE, + predef: predefinedLiteralTable[:], + }, + { + name: "offset", + distribution: offsetPredefinedDistribution, + tableBits: 5, + toBaseline: (*Reader).makeOffsetBaselineFSE, + predef: predefinedOffsetTable[:], + }, + { + name: "match", + distribution: matchPredefinedDistribution, + tableBits: 6, + toBaseline: (*Reader).makeMatchBaselineFSE, + predef: predefinedMatchTable[:], + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var r Reader + table := make([]fseEntry, 1< len(zstdExp) { + c = len(zstdExp) + } + goExp = goExp[:c] + zstdExp = zstdExp[:c] + if !bytes.Equal(goExp, zstdExp) { + t.Error("byte mismatch after error") + t.Logf("Go error: %v\n", goErr) + t.Logf("zstd error: %v\n", zstdErr) + showDiffs(t, zstdExp, goExp) + } + } + }) +} diff --git a/go/src/internal/zstd/huff.go b/go/src/internal/zstd/huff.go new file mode 100644 index 0000000000000000000000000000000000000000..452e24b760c3e5276a5fdf013a938ab3522e342c --- /dev/null +++ b/go/src/internal/zstd/huff.go @@ -0,0 +1,204 @@ +// 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 zstd + +import ( + "io" + "math/bits" +) + +// maxHuffmanBits is the largest possible Huffman table bits. +const maxHuffmanBits = 11 + +// readHuff reads Huffman table from data starting at off into table. +// Each entry in a Huffman table is a pair of bytes. +// The high byte is the encoded value. The low byte is the number +// of bits used to encode that value. We index into the table +// with a value of size tableBits. A value that requires fewer bits +// appear in the table multiple times. +// This returns the number of bits in the Huffman table and the new offset. +// RFC 4.2.1. +func (r *Reader) readHuff(data block, off int, table []uint16) (tableBits, roff int, err error) { + if off >= len(data) { + return 0, 0, r.makeEOFError(off) + } + + hdr := data[off] + off++ + + var weights [256]uint8 + var count int + if hdr < 128 { + // The table is compressed using an FSE. RFC 4.2.1.2. + if len(r.fseScratch) < 1<<6 { + r.fseScratch = make([]fseEntry, 1<<6) + } + fseBits, noff, err := r.readFSE(data, off, 255, 6, r.fseScratch) + if err != nil { + return 0, 0, err + } + fseTable := r.fseScratch + + if off+int(hdr) > len(data) { + return 0, 0, r.makeEOFError(off) + } + + rbr, err := r.makeReverseBitReader(data, off+int(hdr)-1, noff) + if err != nil { + return 0, 0, err + } + + state1, err := rbr.val(uint8(fseBits)) + if err != nil { + return 0, 0, err + } + + state2, err := rbr.val(uint8(fseBits)) + if err != nil { + return 0, 0, err + } + + // There are two independent FSE streams, tracked by + // state1 and state2. We decode them alternately. + + for { + pt := &fseTable[state1] + if !rbr.fetch(pt.bits) { + if count >= 254 { + return 0, 0, rbr.makeError("Huffman count overflow") + } + weights[count] = pt.sym + weights[count+1] = fseTable[state2].sym + count += 2 + break + } + + v, err := rbr.val(pt.bits) + if err != nil { + return 0, 0, err + } + state1 = uint32(pt.base) + v + + if count >= 255 { + return 0, 0, rbr.makeError("Huffman count overflow") + } + + weights[count] = pt.sym + count++ + + pt = &fseTable[state2] + + if !rbr.fetch(pt.bits) { + if count >= 254 { + return 0, 0, rbr.makeError("Huffman count overflow") + } + weights[count] = pt.sym + weights[count+1] = fseTable[state1].sym + count += 2 + break + } + + v, err = rbr.val(pt.bits) + if err != nil { + return 0, 0, err + } + state2 = uint32(pt.base) + v + + if count >= 255 { + return 0, 0, rbr.makeError("Huffman count overflow") + } + + weights[count] = pt.sym + count++ + } + + off += int(hdr) + } else { + // The table is not compressed. Each weight is 4 bits. + + count = int(hdr) - 127 + if off+((count+1)/2) >= len(data) { + return 0, 0, io.ErrUnexpectedEOF + } + for i := 0; i < count; i += 2 { + b := data[off] + off++ + weights[i] = b >> 4 + weights[i+1] = b & 0xf + } + } + + // RFC 4.2.1.3. + + var weightMark [13]uint32 + weightMask := uint32(0) + for _, w := range weights[:count] { + if w > 12 { + return 0, 0, r.makeError(off, "Huffman weight overflow") + } + weightMark[w]++ + if w > 0 { + weightMask += 1 << (w - 1) + } + } + if weightMask == 0 { + return 0, 0, r.makeError(off, "bad Huffman weights") + } + + tableBits = 32 - bits.LeadingZeros32(weightMask) + if tableBits > maxHuffmanBits { + return 0, 0, r.makeError(off, "bad Huffman weights") + } + + if len(table) < 1<= 256 { + return 0, 0, r.makeError(off, "Huffman weight overflow") + } + weights[count] = uint8(highBit + 1) + count++ + weightMark[highBit+1]++ + + if weightMark[1] < 2 || weightMark[1]&1 != 0 { + return 0, 0, r.makeError(off, "bad Huffman weights") + } + + // Change weightMark from a count of weights to the index of + // the first symbol for that weight. We shift the indexes to + // also store how many we have seen so far, + next := uint32(0) + for i := 0; i < tableBits; i++ { + cur := next + next += weightMark[i+1] << i + weightMark[i+1] = cur + } + + for i, w := range weights[:count] { + if w == 0 { + continue + } + length := uint32(1) << (w - 1) + tval := uint16(i)<<8 | (uint16(tableBits) + 1 - uint16(w)) + start := weightMark[w] + for j := uint32(0); j < length; j++ { + table[start+j] = tval + } + weightMark[w] += length + } + + return tableBits, off, nil +} diff --git a/go/src/internal/zstd/literals.go b/go/src/internal/zstd/literals.go new file mode 100644 index 0000000000000000000000000000000000000000..11ef859f149673611ec8ab219f22b716badfe67f --- /dev/null +++ b/go/src/internal/zstd/literals.go @@ -0,0 +1,336 @@ +// 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 zstd + +import ( + "encoding/binary" +) + +// readLiterals reads and decompresses the literals from data at off. +// The literals are appended to outbuf, which is returned. +// Also returns the new input offset. RFC 3.1.1.3.1. +func (r *Reader) readLiterals(data block, off int, outbuf []byte) (int, []byte, error) { + if off >= len(data) { + return 0, nil, r.makeEOFError(off) + } + + // Literals section header. RFC 3.1.1.3.1.1. + hdr := data[off] + off++ + + if (hdr&3) == 0 || (hdr&3) == 1 { + return r.readRawRLELiterals(data, off, hdr, outbuf) + } else { + return r.readHuffLiterals(data, off, hdr, outbuf) + } +} + +// readRawRLELiterals reads and decompresses a Raw_Literals_Block or +// a RLE_Literals_Block. RFC 3.1.1.3.1.1. +func (r *Reader) readRawRLELiterals(data block, off int, hdr byte, outbuf []byte) (int, []byte, error) { + raw := (hdr & 3) == 0 + + var regeneratedSize int + switch (hdr >> 2) & 3 { + case 0, 2: + regeneratedSize = int(hdr >> 3) + case 1: + if off >= len(data) { + return 0, nil, r.makeEOFError(off) + } + regeneratedSize = int(hdr>>4) + (int(data[off]) << 4) + off++ + case 3: + if off+1 >= len(data) { + return 0, nil, r.makeEOFError(off) + } + regeneratedSize = int(hdr>>4) + (int(data[off]) << 4) + (int(data[off+1]) << 12) + off += 2 + } + + // We are going to use the entire literal block in the output. + // The maximum size of one decompressed block is 128K, + // so we can't have more literals than that. + if regeneratedSize > 128<<10 { + return 0, nil, r.makeError(off, "literal size too large") + } + + if raw { + // RFC 3.1.1.3.1.2. + if off+regeneratedSize > len(data) { + return 0, nil, r.makeError(off, "raw literal size too large") + } + outbuf = append(outbuf, data[off:off+regeneratedSize]...) + off += regeneratedSize + } else { + // RFC 3.1.1.3.1.3. + if off >= len(data) { + return 0, nil, r.makeError(off, "RLE literal missing") + } + rle := data[off] + off++ + for i := 0; i < regeneratedSize; i++ { + outbuf = append(outbuf, rle) + } + } + + return off, outbuf, nil +} + +// readHuffLiterals reads and decompresses a Compressed_Literals_Block or +// a Treeless_Literals_Block. RFC 3.1.1.3.1.4. +func (r *Reader) readHuffLiterals(data block, off int, hdr byte, outbuf []byte) (int, []byte, error) { + var ( + regeneratedSize int + compressedSize int + streams int + ) + switch (hdr >> 2) & 3 { + case 0, 1: + if off+1 >= len(data) { + return 0, nil, r.makeEOFError(off) + } + regeneratedSize = (int(hdr) >> 4) | ((int(data[off]) & 0x3f) << 4) + compressedSize = (int(data[off]) >> 6) | (int(data[off+1]) << 2) + off += 2 + if ((hdr >> 2) & 3) == 0 { + streams = 1 + } else { + streams = 4 + } + case 2: + if off+2 >= len(data) { + return 0, nil, r.makeEOFError(off) + } + regeneratedSize = (int(hdr) >> 4) | (int(data[off]) << 4) | ((int(data[off+1]) & 3) << 12) + compressedSize = (int(data[off+1]) >> 2) | (int(data[off+2]) << 6) + off += 3 + streams = 4 + case 3: + if off+3 >= len(data) { + return 0, nil, r.makeEOFError(off) + } + regeneratedSize = (int(hdr) >> 4) | (int(data[off]) << 4) | ((int(data[off+1]) & 0x3f) << 12) + compressedSize = (int(data[off+1]) >> 6) | (int(data[off+2]) << 2) | (int(data[off+3]) << 10) + off += 4 + streams = 4 + } + + // We are going to use the entire literal block in the output. + // The maximum size of one decompressed block is 128K, + // so we can't have more literals than that. + if regeneratedSize > 128<<10 { + return 0, nil, r.makeError(off, "literal size too large") + } + + roff := off + compressedSize + if roff > len(data) || roff < 0 { + return 0, nil, r.makeEOFError(off) + } + + totalStreamsSize := compressedSize + if (hdr & 3) == 2 { + // Compressed_Literals_Block. + // Read new huffman tree. + + if len(r.huffmanTable) < 1<> (rbr.cnt - huffBits)) & huffMask + t = huffTable[idx] + outbuf = append(outbuf, byte(t>>8)) + rbr.cnt -= uint32(t & 0xff) + } + + return outbuf, nil +} + +// readLiteralsFourStreams reads four interleaved streams of +// compressed literals. +func (r *Reader) readLiteralsFourStreams(data block, off, totalStreamsSize, regeneratedSize int, outbuf []byte) ([]byte, error) { + // Read the jump table to find out where the streams are. + // RFC 3.1.1.3.1.6. + if off+5 >= len(data) { + return nil, r.makeEOFError(off) + } + if totalStreamsSize < 6 { + return nil, r.makeError(off, "total streams size too small for jump table") + } + // RFC 3.1.1.3.1.6. + // "The decompressed size of each stream is equal to (Regenerated_Size+3)/4, + // except for the last stream, which may be up to 3 bytes smaller, + // to reach a total decompressed size as specified in Regenerated_Size." + regeneratedStreamSize := (regeneratedSize + 3) / 4 + if regeneratedSize < regeneratedStreamSize*3 { + return nil, r.makeError(off, "regenerated size too small to decode streams") + } + + streamSize1 := binary.LittleEndian.Uint16(data[off:]) + streamSize2 := binary.LittleEndian.Uint16(data[off+2:]) + streamSize3 := binary.LittleEndian.Uint16(data[off+4:]) + off += 6 + + tot := uint64(streamSize1) + uint64(streamSize2) + uint64(streamSize3) + if tot > uint64(totalStreamsSize)-6 { + return nil, r.makeEOFError(off) + } + streamSize4 := uint32(totalStreamsSize) - 6 - uint32(tot) + + off-- + off1 := off + int(streamSize1) + start1 := off + 1 + + off2 := off1 + int(streamSize2) + start2 := off1 + 1 + + off3 := off2 + int(streamSize3) + start3 := off2 + 1 + + off4 := off3 + int(streamSize4) + start4 := off3 + 1 + + // We let the reverse bit readers read earlier bytes, + // because the Huffman tables ignore bits that they don't need. + + rbr1, err := r.makeReverseBitReader(data, off1, start1-2) + if err != nil { + return nil, err + } + + rbr2, err := r.makeReverseBitReader(data, off2, start2-2) + if err != nil { + return nil, err + } + + rbr3, err := r.makeReverseBitReader(data, off3, start3-2) + if err != nil { + return nil, err + } + + rbr4, err := r.makeReverseBitReader(data, off4, start4-2) + if err != nil { + return nil, err + } + + out1 := len(outbuf) + out2 := out1 + regeneratedStreamSize + out3 := out2 + regeneratedStreamSize + out4 := out3 + regeneratedStreamSize + + regeneratedStreamSize4 := regeneratedSize - regeneratedStreamSize*3 + + outbuf = append(outbuf, make([]byte, regeneratedSize)...) + + huffTable := r.huffmanTable + huffBits := uint32(r.huffmanTableBits) + huffMask := (uint32(1) << huffBits) - 1 + + for i := 0; i < regeneratedStreamSize; i++ { + use4 := i < regeneratedStreamSize4 + + fetchHuff := func(rbr *reverseBitReader) (uint16, error) { + if !rbr.fetch(uint8(huffBits)) { + return 0, rbr.makeError("literals Huffman stream out of bits") + } + idx := (rbr.bits >> (rbr.cnt - huffBits)) & huffMask + return huffTable[idx], nil + } + + t1, err := fetchHuff(&rbr1) + if err != nil { + return nil, err + } + + t2, err := fetchHuff(&rbr2) + if err != nil { + return nil, err + } + + t3, err := fetchHuff(&rbr3) + if err != nil { + return nil, err + } + + if use4 { + t4, err := fetchHuff(&rbr4) + if err != nil { + return nil, err + } + outbuf[out4] = byte(t4 >> 8) + out4++ + rbr4.cnt -= uint32(t4 & 0xff) + } + + outbuf[out1] = byte(t1 >> 8) + out1++ + rbr1.cnt -= uint32(t1 & 0xff) + + outbuf[out2] = byte(t2 >> 8) + out2++ + rbr2.cnt -= uint32(t2 & 0xff) + + outbuf[out3] = byte(t3 >> 8) + out3++ + rbr3.cnt -= uint32(t3 & 0xff) + } + + return outbuf, nil +} diff --git a/go/src/internal/zstd/testdata/README b/go/src/internal/zstd/testdata/README new file mode 100644 index 0000000000000000000000000000000000000000..1a6dbb3a8f8c5c3fec7be52f7023cc1c1654182e --- /dev/null +++ b/go/src/internal/zstd/testdata/README @@ -0,0 +1,10 @@ +This directory holds files for testing zstd.NewReader. + +Each one is a Zstandard compressed file named as hash.arbitrary-name.zst, +where hash is the first eight hexadecimal digits of the SHA256 hash +of the expected uncompressed content: + + zstd -d < 1890a371.gettysburg.txt-100x.zst | sha256sum | head -c 8 + 1890a371 + +The test uses hash value to verify decompression result. diff --git a/go/src/internal/zstd/window.go b/go/src/internal/zstd/window.go new file mode 100644 index 0000000000000000000000000000000000000000..11596df3c70975ef80af2901311e9cbb19a3f210 --- /dev/null +++ b/go/src/internal/zstd/window.go @@ -0,0 +1,94 @@ +// 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 zstd + +// window stores up to size bytes of data. +// It is implemented as a circular buffer: +// sequential save calls append to the data slice until +// its length reaches configured size and after that, +// save calls overwrite previously saved data at off +// and update off such that it always points at +// the byte stored before others. +type window struct { + size int + data []byte + off int +} + +// reset clears stored data and configures window size. +func (w *window) reset(size int) { + b := w.data[:0] + if cap(b) < size { + b = make([]byte, 0, size) + } + w.data = b + w.off = 0 + w.size = size +} + +// len returns the number of stored bytes. +func (w *window) len() uint32 { + return uint32(len(w.data)) +} + +// save stores up to size last bytes from the buf. +func (w *window) save(buf []byte) { + if w.size == 0 { + return + } + if len(buf) == 0 { + return + } + + if len(buf) >= w.size { + from := len(buf) - w.size + w.data = append(w.data[:0], buf[from:]...) + w.off = 0 + return + } + + // Update off to point to the oldest remaining byte. + free := w.size - len(w.data) + if free == 0 { + n := copy(w.data[w.off:], buf) + if n == len(buf) { + w.off += n + } else { + w.off = copy(w.data, buf[n:]) + } + } else { + if free >= len(buf) { + w.data = append(w.data, buf...) + } else { + w.data = append(w.data, buf[:free]...) + w.off = copy(w.data, buf[free:]) + } + } +} + +// appendTo appends stored bytes between from and to indices to the buf. +// Index from must be less or equal to index to and to must be less or equal to w.len(). +func (w *window) appendTo(buf []byte, from, to uint32) []byte { + dataLen := uint32(len(w.data)) + from += uint32(w.off) + to += uint32(w.off) + + wrap := false + if from > dataLen { + from -= dataLen + wrap = !wrap + } + if to > dataLen { + to -= dataLen + wrap = !wrap + } + + if wrap { + buf = append(buf, w.data[from:]...) + return append(buf, w.data[:to]...) + } else { + return append(buf, w.data[from:to]...) + } +} diff --git a/go/src/internal/zstd/window_test.go b/go/src/internal/zstd/window_test.go new file mode 100644 index 0000000000000000000000000000000000000000..afa2eefc1a67fc1d0b12ff9f360a4e17f3e188fe --- /dev/null +++ b/go/src/internal/zstd/window_test.go @@ -0,0 +1,72 @@ +// 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 zstd + +import ( + "bytes" + "fmt" + "testing" +) + +func makeSequence(start, n int) (seq []byte) { + for i := 0; i < n; i++ { + seq = append(seq, byte(start+i)) + } + return +} + +func TestWindow(t *testing.T) { + for size := 0; size <= 3; size++ { + for i := 0; i <= 2*size; i++ { + a := makeSequence('a', i) + for j := 0; j <= 2*size; j++ { + b := makeSequence('a'+i, j) + for k := 0; k <= 2*size; k++ { + c := makeSequence('a'+i+j, k) + + t.Run(fmt.Sprintf("%d-%d-%d-%d", size, i, j, k), func(t *testing.T) { + testWindow(t, size, a, b, c) + }) + } + } + } + } +} + +// testWindow tests window by saving three sequences of bytes to it. +// Third sequence tests read offset that can become non-zero only after second save. +func testWindow(t *testing.T, size int, a, b, c []byte) { + var w window + w.reset(size) + + w.save(a) + w.save(b) + w.save(c) + + var tail []byte + tail = append(tail, a...) + tail = append(tail, b...) + tail = append(tail, c...) + + if len(tail) > size { + tail = tail[len(tail)-size:] + } + + if w.len() != uint32(len(tail)) { + t.Errorf("wrong data length: got: %d, want: %d", w.len(), len(tail)) + } + + var from, to uint32 + for from = 0; from <= uint32(len(tail)); from++ { + for to = from; to <= uint32(len(tail)); to++ { + got := w.appendTo(nil, from, to) + want := tail[from:to] + + if !bytes.Equal(got, want) { + t.Errorf("wrong data at [%d:%d]: got %q, want %q", from, to, got, want) + } + } + } +} diff --git a/go/src/internal/zstd/xxhash.go b/go/src/internal/zstd/xxhash.go new file mode 100644 index 0000000000000000000000000000000000000000..51d5ff89603460443a3bf43ee0aeed3bbe585f8e --- /dev/null +++ b/go/src/internal/zstd/xxhash.go @@ -0,0 +1,146 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package zstd + +import ( + "encoding/binary" + "math/bits" +) + +const ( + xxhPrime64c1 = 0x9e3779b185ebca87 + xxhPrime64c2 = 0xc2b2ae3d27d4eb4f + xxhPrime64c3 = 0x165667b19e3779f9 + xxhPrime64c4 = 0x85ebca77c2b2ae63 + xxhPrime64c5 = 0x27d4eb2f165667c5 +) + +// xxhash64 is the state of a xxHash-64 checksum. +type xxhash64 struct { + len uint64 // total length hashed + v [4]uint64 // accumulators + buf [32]byte // buffer + cnt int // number of bytes in buffer +} + +// reset discards the current state and prepares to compute a new hash. +// We assume a seed of 0 since that is what zstd uses. +func (xh *xxhash64) reset() { + xh.len = 0 + + // Separate addition for awkward constant overflow. + xh.v[0] = xxhPrime64c1 + xh.v[0] += xxhPrime64c2 + + xh.v[1] = xxhPrime64c2 + xh.v[2] = 0 + + // Separate negation for awkward constant overflow. + xh.v[3] = xxhPrime64c1 + xh.v[3] = -xh.v[3] + + clear(xh.buf[:]) + xh.cnt = 0 +} + +// update adds a buffer to the has. +func (xh *xxhash64) update(b []byte) { + xh.len += uint64(len(b)) + + if xh.cnt+len(b) < len(xh.buf) { + copy(xh.buf[xh.cnt:], b) + xh.cnt += len(b) + return + } + + if xh.cnt > 0 { + n := copy(xh.buf[xh.cnt:], b) + b = b[n:] + xh.v[0] = xh.round(xh.v[0], binary.LittleEndian.Uint64(xh.buf[:])) + xh.v[1] = xh.round(xh.v[1], binary.LittleEndian.Uint64(xh.buf[8:])) + xh.v[2] = xh.round(xh.v[2], binary.LittleEndian.Uint64(xh.buf[16:])) + xh.v[3] = xh.round(xh.v[3], binary.LittleEndian.Uint64(xh.buf[24:])) + xh.cnt = 0 + } + + for len(b) >= 32 { + xh.v[0] = xh.round(xh.v[0], binary.LittleEndian.Uint64(b)) + xh.v[1] = xh.round(xh.v[1], binary.LittleEndian.Uint64(b[8:])) + xh.v[2] = xh.round(xh.v[2], binary.LittleEndian.Uint64(b[16:])) + xh.v[3] = xh.round(xh.v[3], binary.LittleEndian.Uint64(b[24:])) + b = b[32:] + } + + if len(b) > 0 { + copy(xh.buf[:], b) + xh.cnt = len(b) + } +} + +// digest returns the final hash value. +func (xh *xxhash64) digest() uint64 { + var h64 uint64 + if xh.len < 32 { + h64 = xh.v[2] + xxhPrime64c5 + } else { + h64 = bits.RotateLeft64(xh.v[0], 1) + + bits.RotateLeft64(xh.v[1], 7) + + bits.RotateLeft64(xh.v[2], 12) + + bits.RotateLeft64(xh.v[3], 18) + h64 = xh.mergeRound(h64, xh.v[0]) + h64 = xh.mergeRound(h64, xh.v[1]) + h64 = xh.mergeRound(h64, xh.v[2]) + h64 = xh.mergeRound(h64, xh.v[3]) + } + + h64 += xh.len + + len := xh.len + len &= 31 + buf := xh.buf[:] + for len >= 8 { + k1 := xh.round(0, binary.LittleEndian.Uint64(buf)) + buf = buf[8:] + h64 ^= k1 + h64 = bits.RotateLeft64(h64, 27)*xxhPrime64c1 + xxhPrime64c4 + len -= 8 + } + if len >= 4 { + h64 ^= uint64(binary.LittleEndian.Uint32(buf)) * xxhPrime64c1 + buf = buf[4:] + h64 = bits.RotateLeft64(h64, 23)*xxhPrime64c2 + xxhPrime64c3 + len -= 4 + } + for len > 0 { + h64 ^= uint64(buf[0]) * xxhPrime64c5 + buf = buf[1:] + h64 = bits.RotateLeft64(h64, 11) * xxhPrime64c1 + len-- + } + + h64 ^= h64 >> 33 + h64 *= xxhPrime64c2 + h64 ^= h64 >> 29 + h64 *= xxhPrime64c3 + h64 ^= h64 >> 32 + + return h64 +} + +// round updates a value. +func (xh *xxhash64) round(v, n uint64) uint64 { + v += n * xxhPrime64c2 + v = bits.RotateLeft64(v, 31) + v *= xxhPrime64c1 + return v +} + +// mergeRound updates a value in the final round. +func (xh *xxhash64) mergeRound(v, n uint64) uint64 { + n = xh.round(0, n) + v ^= n + v = v*xxhPrime64c1 + xxhPrime64c4 + return v +} diff --git a/go/src/internal/zstd/xxhash_test.go b/go/src/internal/zstd/xxhash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..68ca558c5fd9fe17ab7d9706b419d4bd25479f40 --- /dev/null +++ b/go/src/internal/zstd/xxhash_test.go @@ -0,0 +1,115 @@ +// 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 zstd + +import ( + "bytes" + "os" + "os/exec" + "strconv" + "testing" +) + +var xxHashTests = []struct { + data string + hash uint64 +}{ + { + "hello, world", + 0xb33a384e6d1b1242, + }, + { + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$", + 0x1032d841e824f998, + }, +} + +func TestXXHash(t *testing.T) { + var xh xxhash64 + for i, test := range xxHashTests { + xh.reset() + xh.update([]byte(test.data)) + if got := xh.digest(); got != test.hash { + t.Errorf("#%d: got %#x want %#x", i, got, test.hash) + } + } +} + +func TestLargeXXHash(t *testing.T) { + if testing.Short() { + t.Skip("skipping expensive test in short mode") + } + + data, err := os.ReadFile("../../testdata/Isaac.Newton-Opticks.txt") + if err != nil { + t.Fatal(err) + } + + var xh xxhash64 + xh.reset() + i := 0 + for i < len(data) { + // Write varying amounts to test buffering. + c := i%4094 + 1 + if i+c > len(data) { + c = len(data) - i + } + xh.update(data[i : i+c]) + i += c + } + + got := xh.digest() + want := uint64(0xf0dd39fd7e063f82) + if got != want { + t.Errorf("got %#x want %#x", got, want) + } +} + +func findXxhsum(t testing.TB) string { + xxhsum, err := exec.LookPath("xxhsum") + if err != nil { + t.Skip("skipping because xxhsum not found") + } + return xxhsum +} + +func FuzzXXHash(f *testing.F) { + xxhsum := findXxhsum(f) + + for _, test := range xxHashTests { + f.Add([]byte(test.data)) + } + f.Add(bytes.Repeat([]byte("abcdefghijklmnop"), 256)) + var buf bytes.Buffer + for i := 0; i < 256; i++ { + buf.WriteByte(byte(i)) + } + f.Add(bytes.Repeat(buf.Bytes(), 64)) + f.Add(bigData(f)) + + f.Fuzz(func(t *testing.T, b []byte) { + cmd := exec.Command(xxhsum, "-H64") + cmd.Stdin = bytes.NewReader(b) + var hhsumHash bytes.Buffer + cmd.Stdout = &hhsumHash + if err := cmd.Run(); err != nil { + t.Fatalf("running hhsum failed: %v", err) + } + hhHashBytes := bytes.Fields(bytes.TrimSpace(hhsumHash.Bytes()))[0] + hhHash, err := strconv.ParseUint(string(hhHashBytes), 16, 64) + if err != nil { + t.Fatalf("could not parse hash %q: %v", hhHashBytes, err) + } + + var xh xxhash64 + xh.reset() + xh.update(b) + goHash := xh.digest() + + if goHash != hhHash { + t.Errorf("Go hash %#x != xxhsum hash %#x", goHash, hhHash) + } + }) +} diff --git a/go/src/internal/zstd/zstd.go b/go/src/internal/zstd/zstd.go new file mode 100644 index 0000000000000000000000000000000000000000..d4eac399aff0be616afe5e92f9e67db29a2abff2 --- /dev/null +++ b/go/src/internal/zstd/zstd.go @@ -0,0 +1,505 @@ +// 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 zstd provides a decompressor for zstd streams, +// described in RFC 8878. It does not support dictionaries. +package zstd + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +// fuzzing is a fuzzer hook set to true when fuzzing. +// This is used to reject cases where we don't match zstd. +var fuzzing = false + +// Reader implements [io.Reader] to read a zstd compressed stream. +type Reader struct { + // The underlying Reader. + r io.Reader + + // Whether we have read the frame header. + // This is of interest when buffer is empty. + // If true we expect to see a new block. + sawFrameHeader bool + + // Whether the current frame expects a checksum. + hasChecksum bool + + // Whether we have read at least one frame. + readOneFrame bool + + // True if the frame size is not known. + frameSizeUnknown bool + + // The number of uncompressed bytes remaining in the current frame. + // If frameSizeUnknown is true, this is not valid. + remainingFrameSize uint64 + + // The number of bytes read from r up to the start of the current + // block, for error reporting. + blockOffset int64 + + // Buffered decompressed data. + buffer []byte + // Current read offset in buffer. + off int + + // The current repeated offsets. + repeatedOffset1 uint32 + repeatedOffset2 uint32 + repeatedOffset3 uint32 + + // The current Huffman tree used for compressing literals. + huffmanTable []uint16 + huffmanTableBits int + + // The window for back references. + window window + + // A buffer available to hold a compressed block. + compressedBuf []byte + + // A buffer for literals. + literals []byte + + // Sequence decode FSE tables. + seqTables [3][]fseBaselineEntry + seqTableBits [3]uint8 + + // Buffers for sequence decode FSE tables. + seqTableBuffers [3][]fseBaselineEntry + + // Scratch space used for small reads, to avoid allocation. + scratch [16]byte + + // A scratch table for reading an FSE. Only temporarily valid. + fseScratch []fseEntry + + // For checksum computation. + checksum xxhash64 +} + +// NewReader creates a new Reader that decompresses data from the given reader. +func NewReader(input io.Reader) *Reader { + r := new(Reader) + r.Reset(input) + return r +} + +// Reset discards the current state and starts reading a new stream from r. +// This permits reusing a Reader rather than allocating a new one. +func (r *Reader) Reset(input io.Reader) { + r.r = input + + // Several fields are preserved to avoid allocation. + // Others are always set before they are used. + r.sawFrameHeader = false + r.hasChecksum = false + r.readOneFrame = false + r.frameSizeUnknown = false + r.remainingFrameSize = 0 + r.blockOffset = 0 + r.buffer = r.buffer[:0] + r.off = 0 + // repeatedOffset1 + // repeatedOffset2 + // repeatedOffset3 + // huffmanTable + // huffmanTableBits + // window + // compressedBuf + // literals + // seqTables + // seqTableBits + // seqTableBuffers + // scratch + // fseScratch +} + +// Read implements [io.Reader]. +func (r *Reader) Read(p []byte) (int, error) { + if err := r.refillIfNeeded(); err != nil { + return 0, err + } + n := copy(p, r.buffer[r.off:]) + r.off += n + return n, nil +} + +// ReadByte implements [io.ByteReader]. +func (r *Reader) ReadByte() (byte, error) { + if err := r.refillIfNeeded(); err != nil { + return 0, err + } + ret := r.buffer[r.off] + r.off++ + return ret, nil +} + +// refillIfNeeded reads the next block if necessary. +func (r *Reader) refillIfNeeded() error { + for r.off >= len(r.buffer) { + if err := r.refill(); err != nil { + return err + } + r.off = 0 + } + return nil +} + +// refill reads and decompresses the next block. +func (r *Reader) refill() error { + if !r.sawFrameHeader { + if err := r.readFrameHeader(); err != nil { + return err + } + } + return r.readBlock() +} + +// readFrameHeader reads the frame header and prepares to read a block. +func (r *Reader) readFrameHeader() error { +retry: + relativeOffset := 0 + + // Read magic number. RFC 3.1.1. + if _, err := io.ReadFull(r.r, r.scratch[:4]); err != nil { + // We require that the stream contains at least one frame. + if err == io.EOF && !r.readOneFrame { + err = io.ErrUnexpectedEOF + } + return r.wrapError(relativeOffset, err) + } + + if magic := binary.LittleEndian.Uint32(r.scratch[:4]); magic != 0xfd2fb528 { + if magic >= 0x184d2a50 && magic <= 0x184d2a5f { + // This is a skippable frame. + r.blockOffset += int64(relativeOffset) + 4 + if err := r.skipFrame(); err != nil { + return err + } + r.readOneFrame = true + goto retry + } + + return r.makeError(relativeOffset, "invalid magic number") + } + + relativeOffset += 4 + + // Read Frame_Header_Descriptor. RFC 3.1.1.1.1. + if _, err := io.ReadFull(r.r, r.scratch[:1]); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + descriptor := r.scratch[0] + + singleSegment := descriptor&(1<<5) != 0 + + fcsFieldSize := 1 << (descriptor >> 6) + if fcsFieldSize == 1 && !singleSegment { + fcsFieldSize = 0 + } + + var windowDescriptorSize int + if singleSegment { + windowDescriptorSize = 0 + } else { + windowDescriptorSize = 1 + } + + if descriptor&(1<<3) != 0 { + return r.makeError(relativeOffset, "reserved bit set in frame header descriptor") + } + + r.hasChecksum = descriptor&(1<<2) != 0 + if r.hasChecksum { + r.checksum.reset() + } + + // Dictionary_ID_Flag. RFC 3.1.1.1.1.6. + dictionaryIdSize := 0 + if dictIdFlag := descriptor & 3; dictIdFlag != 0 { + dictionaryIdSize = 1 << (dictIdFlag - 1) + } + + relativeOffset++ + + headerSize := windowDescriptorSize + dictionaryIdSize + fcsFieldSize + + if _, err := io.ReadFull(r.r, r.scratch[:headerSize]); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + + // Figure out the maximum amount of data we need to retain + // for backreferences. + var windowSize uint64 + if !singleSegment { + // Window descriptor. RFC 3.1.1.1.2. + windowDescriptor := r.scratch[0] + exponent := uint64(windowDescriptor >> 3) + mantissa := uint64(windowDescriptor & 7) + windowLog := exponent + 10 + windowBase := uint64(1) << windowLog + windowAdd := (windowBase / 8) * mantissa + windowSize = windowBase + windowAdd + + // Default zstd sets limits on the window size. + if fuzzing && (windowLog > 31 || windowSize > 1<<27) { + return r.makeError(relativeOffset, "windowSize too large") + } + } + + // Dictionary_ID. RFC 3.1.1.1.3. + if dictionaryIdSize != 0 { + dictionaryId := r.scratch[windowDescriptorSize : windowDescriptorSize+dictionaryIdSize] + // Allow only zero Dictionary ID. + for _, b := range dictionaryId { + if b != 0 { + return r.makeError(relativeOffset, "dictionaries are not supported") + } + } + } + + // Frame_Content_Size. RFC 3.1.1.1.4. + r.frameSizeUnknown = false + r.remainingFrameSize = 0 + fb := r.scratch[windowDescriptorSize+dictionaryIdSize:] + switch fcsFieldSize { + case 0: + r.frameSizeUnknown = true + case 1: + r.remainingFrameSize = uint64(fb[0]) + case 2: + r.remainingFrameSize = 256 + uint64(binary.LittleEndian.Uint16(fb)) + case 4: + r.remainingFrameSize = uint64(binary.LittleEndian.Uint32(fb)) + case 8: + r.remainingFrameSize = binary.LittleEndian.Uint64(fb) + default: + panic("unreachable") + } + + // RFC 3.1.1.1.2. + // When Single_Segment_Flag is set, Window_Descriptor is not present. + // In this case, Window_Size is Frame_Content_Size. + if singleSegment { + windowSize = r.remainingFrameSize + } + + // RFC 8878 3.1.1.1.1.2. permits us to set an 8M max on window size. + const maxWindowSize = 8 << 20 + if windowSize > maxWindowSize { + windowSize = maxWindowSize + } + + relativeOffset += headerSize + + r.sawFrameHeader = true + r.readOneFrame = true + r.blockOffset += int64(relativeOffset) + + // Prepare to read blocks from the frame. + r.repeatedOffset1 = 1 + r.repeatedOffset2 = 4 + r.repeatedOffset3 = 8 + r.huffmanTableBits = 0 + r.window.reset(int(windowSize)) + r.seqTables[0] = nil + r.seqTables[1] = nil + r.seqTables[2] = nil + + return nil +} + +// skipFrame skips a skippable frame. RFC 3.1.2. +func (r *Reader) skipFrame() error { + relativeOffset := 0 + + if _, err := io.ReadFull(r.r, r.scratch[:4]); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + + relativeOffset += 4 + + size := binary.LittleEndian.Uint32(r.scratch[:4]) + if size == 0 { + r.blockOffset += int64(relativeOffset) + return nil + } + + if seeker, ok := r.r.(io.Seeker); ok { + r.blockOffset += int64(relativeOffset) + // Implementations of Seeker do not always detect invalid offsets, + // so check that the new offset is valid by comparing to the end. + prev, err := seeker.Seek(0, io.SeekCurrent) + if err != nil { + return r.wrapError(0, err) + } + end, err := seeker.Seek(0, io.SeekEnd) + if err != nil { + return r.wrapError(0, err) + } + if prev > end-int64(size) { + r.blockOffset += end - prev + return r.makeEOFError(0) + } + + // The new offset is valid, so seek to it. + _, err = seeker.Seek(prev+int64(size), io.SeekStart) + if err != nil { + return r.wrapError(0, err) + } + r.blockOffset += int64(size) + return nil + } + + n, err := io.CopyN(io.Discard, r.r, int64(size)) + relativeOffset += int(n) + if err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + r.blockOffset += int64(relativeOffset) + return nil +} + +// readBlock reads the next block from a frame. +func (r *Reader) readBlock() error { + relativeOffset := 0 + + // Read Block_Header. RFC 3.1.1.2. + if _, err := io.ReadFull(r.r, r.scratch[:3]); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + + relativeOffset += 3 + + header := uint32(r.scratch[0]) | (uint32(r.scratch[1]) << 8) | (uint32(r.scratch[2]) << 16) + + lastBlock := header&1 != 0 + blockType := (header >> 1) & 3 + blockSize := int(header >> 3) + + // Maximum block size is smaller of window size and 128K. + // We don't record the window size for a single segment frame, + // so just use 128K. RFC 3.1.1.2.3, 3.1.1.2.4. + if blockSize > 128<<10 || (r.window.size > 0 && blockSize > r.window.size) { + return r.makeError(relativeOffset, "block size too large") + } + + // Handle different block types. RFC 3.1.1.2.2. + switch blockType { + case 0: + r.setBufferSize(blockSize) + if _, err := io.ReadFull(r.r, r.buffer); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + relativeOffset += blockSize + r.blockOffset += int64(relativeOffset) + case 1: + r.setBufferSize(blockSize) + if _, err := io.ReadFull(r.r, r.scratch[:1]); err != nil { + return r.wrapNonEOFError(relativeOffset, err) + } + relativeOffset++ + v := r.scratch[0] + for i := range r.buffer { + r.buffer[i] = v + } + r.blockOffset += int64(relativeOffset) + case 2: + r.blockOffset += int64(relativeOffset) + if err := r.compressedBlock(blockSize); err != nil { + return err + } + r.blockOffset += int64(blockSize) + case 3: + return r.makeError(relativeOffset, "invalid block type") + } + + if !r.frameSizeUnknown { + if uint64(len(r.buffer)) > r.remainingFrameSize { + return r.makeError(relativeOffset, "too many uncompressed bytes in frame") + } + r.remainingFrameSize -= uint64(len(r.buffer)) + } + + if r.hasChecksum { + r.checksum.update(r.buffer) + } + + if !lastBlock { + r.window.save(r.buffer) + } else { + if !r.frameSizeUnknown && r.remainingFrameSize != 0 { + return r.makeError(relativeOffset, "not enough uncompressed bytes for frame") + } + // Check for checksum at end of frame. RFC 3.1.1. + if r.hasChecksum { + if _, err := io.ReadFull(r.r, r.scratch[:4]); err != nil { + return r.wrapNonEOFError(0, err) + } + + inputChecksum := binary.LittleEndian.Uint32(r.scratch[:4]) + dataChecksum := uint32(r.checksum.digest()) + if inputChecksum != dataChecksum { + return r.wrapError(0, fmt.Errorf("invalid checksum: got %#x want %#x", dataChecksum, inputChecksum)) + } + + r.blockOffset += 4 + } + r.sawFrameHeader = false + } + + return nil +} + +// setBufferSize sets the decompressed buffer size. +// When this is called the buffer is empty. +func (r *Reader) setBufferSize(size int) { + if cap(r.buffer) < size { + need := size - cap(r.buffer) + r.buffer = append(r.buffer[:cap(r.buffer)], make([]byte, need)...) + } + r.buffer = r.buffer[:size] +} + +// zstdError is an error while decompressing. +type zstdError struct { + offset int64 + err error +} + +func (ze *zstdError) Error() string { + return fmt.Sprintf("zstd decompression error at %d: %v", ze.offset, ze.err) +} + +func (ze *zstdError) Unwrap() error { + return ze.err +} + +func (r *Reader) makeEOFError(off int) error { + return r.wrapError(off, io.ErrUnexpectedEOF) +} + +func (r *Reader) wrapNonEOFError(off int, err error) error { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return r.wrapError(off, err) +} + +func (r *Reader) makeError(off int, msg string) error { + return r.wrapError(off, errors.New(msg)) +} + +func (r *Reader) wrapError(off int, err error) error { + if err == io.EOF { + return err + } + return &zstdError{r.blockOffset + int64(off), err} +} diff --git a/go/src/internal/zstd/zstd_test.go b/go/src/internal/zstd/zstd_test.go new file mode 100644 index 0000000000000000000000000000000000000000..eb06af8a14b324d3c7c87029f3bee93c4645a0e6 --- /dev/null +++ b/go/src/internal/zstd/zstd_test.go @@ -0,0 +1,333 @@ +// 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 zstd + +import ( + "bytes" + "crypto/sha256" + "fmt" + "internal/race" + "internal/testenv" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" +) + +// tests holds some simple test cases, including some found by fuzzing. +var tests = []struct { + name, uncompressed, compressed string +}{ + { + "hello", + "hello, world\n", + "\x28\xb5\x2f\xfd\x24\x0d\x69\x00\x00\x68\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x0a\x4c\x1f\xf9\xf1", + }, + { + // a small compressed .debug_ranges section. + "ranges", + "\xcc\x11\x00\x00\x00\x00\x00\x00\xd5\x13\x00\x00\x00\x00\x00\x00" + + "\x1c\x14\x00\x00\x00\x00\x00\x00\x72\x14\x00\x00\x00\x00\x00\x00" + + "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\xfb\x12\x00\x00\x00\x00\x00\x00\x09\x13\x00\x00\x00\x00\x00\x00" + + "\x0c\x13\x00\x00\x00\x00\x00\x00\xcb\x13\x00\x00\x00\x00\x00\x00" + + "\x29\x14\x00\x00\x00\x00\x00\x00\x4e\x14\x00\x00\x00\x00\x00\x00" + + "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\xfb\x12\x00\x00\x00\x00\x00\x00\x09\x13\x00\x00\x00\x00\x00\x00" + + "\x67\x13\x00\x00\x00\x00\x00\x00\xcb\x13\x00\x00\x00\x00\x00\x00" + + "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\x5f\x0b\x00\x00\x00\x00\x00\x00\x6c\x0b\x00\x00\x00\x00\x00\x00" + + "\x7d\x0b\x00\x00\x00\x00\x00\x00\x7e\x0c\x00\x00\x00\x00\x00\x00" + + "\x38\x0f\x00\x00\x00\x00\x00\x00\x5c\x0f\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\x83\x0c\x00\x00\x00\x00\x00\x00\xfa\x0c\x00\x00\x00\x00\x00\x00" + + "\xfd\x0d\x00\x00\x00\x00\x00\x00\xef\x0e\x00\x00\x00\x00\x00\x00" + + "\x14\x0f\x00\x00\x00\x00\x00\x00\x38\x0f\x00\x00\x00\x00\x00\x00" + + "\x9f\x0f\x00\x00\x00\x00\x00\x00\xac\x0f\x00\x00\x00\x00\x00\x00" + + "\xdb\x0f\x00\x00\x00\x00\x00\x00\xff\x0f\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\xfd\x0d\x00\x00\x00\x00\x00\x00\xd8\x0e\x00\x00\x00\x00\x00\x00" + + "\x9f\x0f\x00\x00\x00\x00\x00\x00\xac\x0f\x00\x00\x00\x00\x00\x00" + + "\xdb\x0f\x00\x00\x00\x00\x00\x00\xff\x0f\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\xfa\x0c\x00\x00\x00\x00\x00\x00\xea\x0d\x00\x00\x00\x00\x00\x00" + + "\xef\x0e\x00\x00\x00\x00\x00\x00\x14\x0f\x00\x00\x00\x00\x00\x00" + + "\x5c\x0f\x00\x00\x00\x00\x00\x00\x9f\x0f\x00\x00\x00\x00\x00\x00" + + "\xac\x0f\x00\x00\x00\x00\x00\x00\xdb\x0f\x00\x00\x00\x00\x00\x00" + + "\xff\x0f\x00\x00\x00\x00\x00\x00\x2c\x10\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\x60\x11\x00\x00\x00\x00\x00\x00\xd1\x16\x00\x00\x00\x00\x00\x00" + + "\x40\x0b\x00\x00\x00\x00\x00\x00\x2c\x10\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\x7a\x00\x00\x00\x00\x00\x00\x00\xb6\x00\x00\x00\x00\x00\x00\x00" + + "\x9f\x01\x00\x00\x00\x00\x00\x00\xa7\x01\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + "\x7a\x00\x00\x00\x00\x00\x00\x00\xa9\x00\x00\x00\x00\x00\x00\x00" + + "\x9f\x01\x00\x00\x00\x00\x00\x00\xa7\x01\x00\x00\x00\x00\x00\x00" + + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", + + "\x28\xb5\x2f\xfd\x64\xa0\x01\x2d\x05\x00\xc4\x04\xcc\x11\x00\xd5" + + "\x13\x00\x1c\x14\x00\x72\x9d\xd5\xfb\x12\x00\x09\x0c\x13\xcb\x13" + + "\x29\x4e\x67\x5f\x0b\x6c\x0b\x7d\x0b\x7e\x0c\x38\x0f\x5c\x0f\x83" + + "\x0c\xfa\x0c\xfd\x0d\xef\x0e\x14\x38\x9f\x0f\xac\x0f\xdb\x0f\xff" + + "\x0f\xd8\x9f\xac\xdb\xff\xea\x5c\x2c\x10\x60\xd1\x16\x40\x0b\x7a" + + "\x00\xb6\x00\x9f\x01\xa7\x01\xa9\x36\x20\xa0\x83\x14\x34\x63\x4a" + + "\x21\x70\x8c\x07\x46\x03\x4e\x10\x62\x3c\x06\x4e\xc8\x8c\xb0\x32" + + "\x2a\x59\xad\xb2\xf1\x02\x82\x7c\x33\xcb\x92\x6f\x32\x4f\x9b\xb0" + + "\xa2\x30\xf0\xc0\x06\x1e\x98\x99\x2c\x06\x1e\xd8\xc0\x03\x56\xd8" + + "\xc0\x03\x0f\x6c\xe0\x01\xf1\xf0\xee\x9a\xc6\xc8\x97\x99\xd1\x6c" + + "\xb4\x21\x45\x3b\x10\xe4\x7b\x99\x4d\x8a\x36\x64\x5c\x77\x08\x02" + + "\xcb\xe0\xce", + }, + { + "fuzz1", + "0\x00\x00\x00\x00\x000\x00\x00\x00\x00\x001\x00\x00\x00\x00\x000000", + "(\xb5/\xfd\x04X\x8d\x00\x00P0\x000\x001\x000000\x03T\x02\x00\x01\x01m\xf9\xb7G", + }, + { + "empty block", + "", + "\x28\xb5\x2f\xfd\x00\x00\x15\x00\x00\x00\x00", + }, + { + "single skippable frame", + "", + "\x50\x2a\x4d\x18\x00\x00\x00\x00", + }, + { + "two skippable frames", + "", + "\x50\x2a\x4d\x18\x00\x00\x00\x00" + + "\x50\x2a\x4d\x18\x00\x00\x00\x00", + }, +} + +func TestSamples(t *testing.T) { + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + r := NewReader(strings.NewReader(test.compressed)) + got, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + gotstr := string(got) + if gotstr != test.uncompressed { + t.Errorf("got %q want %q", gotstr, test.uncompressed) + } + }) + } +} + +func TestReset(t *testing.T) { + input := strings.NewReader("") + r := NewReader(input) + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + input.Reset(test.compressed) + r.Reset(input) + got, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + gotstr := string(got) + if gotstr != test.uncompressed { + t.Errorf("got %q want %q", gotstr, test.uncompressed) + } + }) + } +} + +var ( + bigDataOnce sync.Once + bigDataBytes []byte + bigDataErr error +) + +// bigData returns the contents of our large test file repeated multiple times. +func bigData(t testing.TB) []byte { + bigDataOnce.Do(func() { + bigDataBytes, bigDataErr = os.ReadFile("../../testdata/Isaac.Newton-Opticks.txt") + if bigDataErr == nil { + bigDataBytes = bytes.Repeat(bigDataBytes, 20) + } + }) + if bigDataErr != nil { + t.Fatal(bigDataErr) + } + return bigDataBytes +} + +func findZstd(t testing.TB) string { + zstd, err := exec.LookPath("zstd") + if err != nil { + t.Skip("skipping because zstd not found") + } + return zstd +} + +var ( + zstdBigOnce sync.Once + zstdBigBytes []byte + zstdBigErr error +) + +// zstdBigData returns the compressed contents of our large test file. +// This will only run on Unix systems with zstd installed. +// That's OK as the package is GOOS-independent. +func zstdBigData(t testing.TB) []byte { + input := bigData(t) + + zstd := findZstd(t) + + zstdBigOnce.Do(func() { + cmd := exec.Command(zstd, "-z") + cmd.Stdin = bytes.NewReader(input) + var compressed bytes.Buffer + cmd.Stdout = &compressed + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + zstdBigErr = fmt.Errorf("running zstd failed: %v", err) + return + } + + zstdBigBytes = compressed.Bytes() + }) + if zstdBigErr != nil { + t.Fatal(zstdBigErr) + } + return zstdBigBytes +} + +// Test decompressing a large file. We don't have a compressor, +// so this test only runs on systems with zstd installed. +func TestLarge(t *testing.T) { + if testing.Short() { + t.Skip("skipping expensive test in short mode") + } + + data := bigData(t) + compressed := zstdBigData(t) + + t.Logf("zstd compressed %d bytes to %d", len(data), len(compressed)) + + r := NewReader(bytes.NewReader(compressed)) + got, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + + if !bytes.Equal(got, data) { + showDiffs(t, got, data) + } +} + +// showDiffs reports the first few differences in two []byte. +func showDiffs(t *testing.T, got, want []byte) { + t.Error("data mismatch") + if len(got) != len(want) { + t.Errorf("got data length %d, want %d", len(got), len(want)) + } + diffs := 0 + for i, b := range got { + if i >= len(want) { + break + } + if b != want[i] { + diffs++ + if diffs > 20 { + break + } + t.Logf("%d: %#x != %#x", i, b, want[i]) + } + } +} + +func TestAlloc(t *testing.T) { + testenv.SkipIfOptimizationOff(t) + if race.Enabled { + t.Skip("skipping allocation test under race detector") + } + + compressed := zstdBigData(t) + input := bytes.NewReader(compressed) + r := NewReader(input) + c := testing.AllocsPerRun(10, func() { + input.Reset(compressed) + r.Reset(input) + io.Copy(io.Discard, r) + }) + if c != 0 { + t.Errorf("got %v allocs, want 0", c) + } +} + +func TestFileSamples(t *testing.T) { + samples, err := os.ReadDir("testdata") + if err != nil { + t.Fatal(err) + } + + for _, sample := range samples { + name := sample.Name() + if !strings.HasSuffix(name, ".zst") { + continue + } + + t.Run(name, func(t *testing.T) { + f, err := os.Open(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + + r := NewReader(f) + h := sha256.New() + if _, err := io.Copy(h, r); err != nil { + t.Fatal(err) + } + got := fmt.Sprintf("%x", h.Sum(nil))[:8] + + want, _, _ := strings.Cut(name, ".") + if got != want { + t.Errorf("Wrong uncompressed content hash: got %s, want %s", got, want) + } + }) + } +} + +func TestReaderBad(t *testing.T) { + for i, s := range badStrings { + t.Run(fmt.Sprintf("badStrings#%d", i), func(t *testing.T) { + _, err := io.Copy(io.Discard, NewReader(strings.NewReader(s))) + if err == nil { + t.Error("expected error") + } + }) + } +} + +func BenchmarkLarge(b *testing.B) { + b.StopTimer() + b.ReportAllocs() + + compressed := zstdBigData(b) + + b.SetBytes(int64(len(compressed))) + + input := bytes.NewReader(compressed) + r := NewReader(input) + + b.StartTimer() + for i := 0; i < b.N; i++ { + input.Reset(compressed) + r.Reset(input) + io.Copy(io.Discard, r) + } +}