codekingpro commited on
Commit
13c2bf6
·
verified ·
1 Parent(s): de452ad

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. go/src/internal/cpu/cpu_arm64_other.go +13 -0
  2. go/src/internal/cpu/cpu_darwin.go +72 -0
  3. go/src/internal/cpu/cpu_loong64.go +55 -0
  4. go/src/internal/cpu/cpu_loong64.s +12 -0
  5. go/src/internal/cpu/cpu_loong64_hwcap.go +28 -0
  6. go/src/internal/cpu/cpu_loong64_linux.go +11 -0
  7. go/src/internal/cpu/cpu_mips.go +10 -0
  8. go/src/internal/cpu/cpu_mips64x.go +32 -0
  9. go/src/internal/cpu/cpu_mipsle.go +10 -0
  10. go/src/internal/cpu/cpu_no_name.go +18 -0
  11. go/src/internal/cpu/cpu_ppc64x.go +35 -0
  12. go/src/internal/cpu/cpu_ppc64x_aix.go +25 -0
  13. go/src/internal/cpu/cpu_ppc64x_linux.go +33 -0
  14. go/src/internal/cpu/cpu_ppc64x_other.go +13 -0
  15. go/src/internal/cpu/cpu_riscv64.go +22 -0
  16. go/src/internal/cpu/cpu_riscv64_linux.go +93 -0
  17. go/src/internal/cpu/cpu_riscv64_other.go +11 -0
  18. go/src/internal/cpu/cpu_s390x.go +205 -0
  19. go/src/internal/cpu/cpu_s390x.s +63 -0
  20. go/src/internal/cpu/cpu_s390x_test.go +63 -0
  21. go/src/internal/cpu/cpu_test.go +61 -0
  22. go/src/internal/cpu/cpu_wasm.go +10 -0
  23. go/src/internal/cpu/cpu_x86.go +279 -0
  24. go/src/internal/cpu/cpu_x86.s +43 -0
  25. go/src/internal/cpu/cpu_x86_darwin.go +23 -0
  26. go/src/internal/cpu/cpu_x86_other.go +9 -0
  27. go/src/internal/cpu/cpu_x86_test.go +57 -0
  28. go/src/internal/cpu/datacache_unsupported.go +11 -0
  29. go/src/internal/cpu/datacache_x86.go +121 -0
  30. go/src/internal/cpu/datacache_x86_test.go +26 -0
  31. go/src/internal/cpu/export_test.go +9 -0
  32. go/src/internal/cpu/export_x86_test.go +11 -0
  33. go/src/internal/dag/alg.go +63 -0
  34. go/src/internal/dag/alg_test.go +46 -0
  35. go/src/internal/dag/parse.go +317 -0
  36. go/src/internal/dag/parse_test.go +61 -0
  37. go/src/internal/diff/diff.go +261 -0
  38. go/src/internal/diff/diff_test.go +43 -0
  39. go/src/internal/exportdata/exportdata.go +355 -0
  40. go/src/internal/exportdata/support.go +32 -0
  41. go/src/internal/filepathlite/path.go +274 -0
  42. go/src/internal/filepathlite/path_nonwindows.go +9 -0
  43. go/src/internal/filepathlite/path_plan9.go +41 -0
  44. go/src/internal/filepathlite/path_unix.go +43 -0
  45. go/src/internal/filepathlite/path_windows.go +326 -0
  46. go/src/internal/fmtsort/export_test.go +11 -0
  47. go/src/internal/fmtsort/sort.go +154 -0
  48. go/src/internal/fmtsort/sort_test.go +280 -0
  49. go/src/internal/fuzz/counters_supported.go +21 -0
  50. go/src/internal/fuzz/counters_unsupported.go +24 -0
go/src/internal/cpu/cpu_arm64_other.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build arm64 && !linux && !freebsd && !android && (!darwin || ios) && !openbsd
6
+
7
+ package cpu
8
+
9
+ func osInit() {
10
+ // Other operating systems do not support reading HWCap from auxiliary vector,
11
+ // reading privileged aarch64 system registers or sysctl in user space to detect
12
+ // CPU features at runtime.
13
+ }
go/src/internal/cpu/cpu_darwin.go ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build darwin && !ios
6
+
7
+ package cpu
8
+
9
+ import _ "unsafe" // for linkname
10
+
11
+ // Pushed from runtime.
12
+ //
13
+ //go:noescape
14
+ func sysctlbynameInt32(name []byte) (int32, int32)
15
+
16
+ // Pushed from runtime.
17
+ //
18
+ //go:noescape
19
+ func sysctlbynameBytes(name, out []byte) int32
20
+
21
+ // sysctlEnabled should be an internal detail,
22
+ // but widely used packages access it using linkname.
23
+ // Notable members of the hall of shame include:
24
+ // - github.com/bytedance/gopkg
25
+ // - github.com/songzhibin97/gkit
26
+ //
27
+ // Do not remove or change the type signature.
28
+ // See go.dev/issue/67401.
29
+ //
30
+ //go:linkname sysctlEnabled
31
+ func sysctlEnabled(name []byte) bool {
32
+ ret, value := sysctlbynameInt32(name)
33
+ if ret < 0 {
34
+ return false
35
+ }
36
+ return value > 0
37
+ }
38
+
39
+ // darwinKernelVersionCheck reports if Darwin kernel version is at
40
+ // least major.minor.patch.
41
+ //
42
+ // Code borrowed from x/sys/cpu.
43
+ func darwinKernelVersionCheck(major, minor, patch int) bool {
44
+ var release [256]byte
45
+ ret := sysctlbynameBytes([]byte("kern.osrelease\x00"), release[:])
46
+ if ret < 0 {
47
+ return false
48
+ }
49
+
50
+ var mmp [3]int
51
+ c := 0
52
+ Loop:
53
+ for _, b := range release[:] {
54
+ switch {
55
+ case b >= '0' && b <= '9':
56
+ mmp[c] = 10*mmp[c] + int(b-'0')
57
+ case b == '.':
58
+ c++
59
+ if c > 2 {
60
+ return false
61
+ }
62
+ case b == 0:
63
+ break Loop
64
+ default:
65
+ return false
66
+ }
67
+ }
68
+ if c != 2 {
69
+ return false
70
+ }
71
+ return mmp[0] > major || mmp[0] == major && (mmp[1] > minor || mmp[1] == minor && mmp[2] >= patch)
72
+ }
go/src/internal/cpu/cpu_loong64.go ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build loong64
6
+
7
+ package cpu
8
+
9
+ // CacheLinePadSize is used to prevent false sharing of cache lines.
10
+ // We choose 64 because Loongson 3A5000 the L1 Dcache is 4-way 256-line 64-byte-per-line.
11
+ const CacheLinePadSize = 64
12
+
13
+ // Bit fields for CPUCFG registers, Related reference documents:
14
+ // https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html#_cpucfg
15
+ const (
16
+ // CPUCFG1 bits
17
+ cpucfg1_CRC32 = 1 << 25
18
+
19
+ // CPUCFG2 bits
20
+ cpucfg2_LAM_BH = 1 << 27
21
+ cpucfg2_LAMCAS = 1 << 28
22
+ )
23
+
24
+ // get_cpucfg is implemented in cpu_loong64.s.
25
+ func get_cpucfg(reg uint32) uint32
26
+
27
+ func doinit() {
28
+ options = []option{
29
+ {Name: "lsx", Feature: &Loong64.HasLSX},
30
+ {Name: "lasx", Feature: &Loong64.HasLASX},
31
+ {Name: "crc32", Feature: &Loong64.HasCRC32},
32
+ {Name: "lamcas", Feature: &Loong64.HasLAMCAS},
33
+ {Name: "lam_bh", Feature: &Loong64.HasLAM_BH},
34
+ }
35
+
36
+ // The CPUCFG data on Loong64 only reflects the hardware capabilities,
37
+ // not the kernel support status, so features such as LSX and LASX that
38
+ // require kernel support cannot be obtained from the CPUCFG data.
39
+ //
40
+ // These features only require hardware capability support and do not
41
+ // require kernel specific support, so they can be obtained directly
42
+ // through CPUCFG
43
+ cfg1 := get_cpucfg(1)
44
+ cfg2 := get_cpucfg(2)
45
+
46
+ Loong64.HasCRC32 = cfgIsSet(cfg1, cpucfg1_CRC32)
47
+ Loong64.HasLAMCAS = cfgIsSet(cfg2, cpucfg2_LAMCAS)
48
+ Loong64.HasLAM_BH = cfgIsSet(cfg2, cpucfg2_LAM_BH)
49
+
50
+ osInit()
51
+ }
52
+
53
+ func cfgIsSet(cfg uint32, val uint32) bool {
54
+ return cfg&val != 0
55
+ }
go/src/internal/cpu/cpu_loong64.s ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ #include "textflag.h"
6
+
7
+ // func get_cpucfg(reg uint32) uint32
8
+ TEXT ·get_cpucfg(SB), NOSPLIT|NOFRAME, $0-12
9
+ MOVW reg+0(FP), R5
10
+ CPUCFG R5, R4
11
+ MOVW R4, ret+8(FP)
12
+ RET
go/src/internal/cpu/cpu_loong64_hwcap.go ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build loong64 && linux
6
+
7
+ package cpu
8
+
9
+ // This is initialized by archauxv and should not be changed after it is
10
+ // initialized.
11
+ var HWCap uint
12
+
13
+ // HWCAP bits. These are exposed by the Linux kernel.
14
+ const (
15
+ hwcap_LOONGARCH_LSX = 1 << 4
16
+ hwcap_LOONGARCH_LASX = 1 << 5
17
+ )
18
+
19
+ func hwcapInit() {
20
+ // TODO: Features that require kernel support like LSX and LASX can
21
+ // be detected here once needed in std library or by the compiler.
22
+ Loong64.HasLSX = hwcIsSet(HWCap, hwcap_LOONGARCH_LSX)
23
+ Loong64.HasLASX = hwcIsSet(HWCap, hwcap_LOONGARCH_LASX)
24
+ }
25
+
26
+ func hwcIsSet(hwc uint, val uint) bool {
27
+ return hwc&val != 0
28
+ }
go/src/internal/cpu/cpu_loong64_linux.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build loong64 && linux
6
+
7
+ package cpu
8
+
9
+ func osInit() {
10
+ hwcapInit()
11
+ }
go/src/internal/cpu/cpu_mips.go ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ const CacheLinePadSize = 32
8
+
9
+ func doinit() {
10
+ }
go/src/internal/cpu/cpu_mips64x.go ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2019 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build mips64 || mips64le
6
+
7
+ package cpu
8
+
9
+ const CacheLinePadSize = 32
10
+
11
+ // This is initialized by archauxv and should not be changed after it is
12
+ // initialized.
13
+ var HWCap uint
14
+
15
+ // HWCAP bits. These are exposed by the Linux kernel 5.4.
16
+ const (
17
+ // CPU features
18
+ hwcap_MIPS_MSA = 1 << 1
19
+ )
20
+
21
+ func doinit() {
22
+ options = []option{
23
+ {Name: "msa", Feature: &MIPS64X.HasMSA},
24
+ }
25
+
26
+ // HWCAP feature bits
27
+ MIPS64X.HasMSA = isSet(HWCap, hwcap_MIPS_MSA)
28
+ }
29
+
30
+ func isSet(hwc uint, value uint) bool {
31
+ return hwc&value != 0
32
+ }
go/src/internal/cpu/cpu_mipsle.go ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ const CacheLinePadSize = 32
8
+
9
+ func doinit() {
10
+ }
go/src/internal/cpu/cpu_no_name.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build !386 && !amd64 && !ppc64 && !ppc64le
6
+
7
+ package cpu
8
+
9
+ // Name returns the CPU name given by the vendor
10
+ // if it can be read directly from memory or by CPU instructions.
11
+ // If the CPU name can not be determined an empty string is returned.
12
+ //
13
+ // Implementations that use the Operating System (e.g. sysctl or /sys/)
14
+ // to gather CPU information for display should be placed in internal/sysinfo.
15
+ func Name() string {
16
+ // "A CPU has no name".
17
+ return ""
18
+ }
go/src/internal/cpu/cpu_ppc64x.go ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build ppc64 || ppc64le
6
+
7
+ package cpu
8
+
9
+ const CacheLinePadSize = 128
10
+
11
+ func doinit() {
12
+ options = []option{
13
+ {Name: "darn", Feature: &PPC64.HasDARN},
14
+ {Name: "scv", Feature: &PPC64.HasSCV},
15
+ {Name: "power9", Feature: &PPC64.IsPOWER9},
16
+ }
17
+
18
+ osinit()
19
+ }
20
+
21
+ func isSet(hwc uint, value uint) bool {
22
+ return hwc&value != 0
23
+ }
24
+
25
+ func Name() string {
26
+ switch {
27
+ case PPC64.IsPOWER10:
28
+ return "POWER10"
29
+ case PPC64.IsPOWER9:
30
+ return "POWER9"
31
+ case PPC64.IsPOWER8:
32
+ return "POWER8"
33
+ }
34
+ return ""
35
+ }
go/src/internal/cpu/cpu_ppc64x_aix.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build ppc64 || ppc64le
6
+
7
+ package cpu
8
+
9
+ const (
10
+ // getsystemcfg constants
11
+ _SC_IMPL = 2
12
+ _IMPL_POWER8 = 0x10000
13
+ _IMPL_POWER9 = 0x20000
14
+ _IMPL_POWER10 = 0x40000
15
+ )
16
+
17
+ func osinit() {
18
+ impl := getsystemcfg(_SC_IMPL)
19
+ PPC64.IsPOWER8 = isSet(impl, _IMPL_POWER8)
20
+ PPC64.IsPOWER9 = isSet(impl, _IMPL_POWER9)
21
+ PPC64.IsPOWER10 = isSet(impl, _IMPL_POWER10)
22
+ }
23
+
24
+ // getsystemcfg is defined in runtime/os2_aix.go
25
+ func getsystemcfg(label uint) uint
go/src/internal/cpu/cpu_ppc64x_linux.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build ppc64 || ppc64le
6
+
7
+ package cpu
8
+
9
+ // ppc64 doesn't have a 'cpuid' equivalent, so we rely on HWCAP/HWCAP2.
10
+ // These are initialized by archauxv and should not be changed after they are
11
+ // initialized.
12
+ var HWCap uint
13
+ var HWCap2 uint
14
+
15
+ // HWCAP bits. These are exposed by Linux.
16
+ const (
17
+ // ISA Level
18
+ hwcap2_ARCH_2_07 = 0x80000000
19
+ hwcap2_ARCH_3_00 = 0x00800000
20
+ hwcap2_ARCH_3_1 = 0x00040000
21
+
22
+ // CPU features
23
+ hwcap2_DARN = 0x00200000
24
+ hwcap2_SCV = 0x00100000
25
+ )
26
+
27
+ func osinit() {
28
+ PPC64.IsPOWER8 = isSet(HWCap2, hwcap2_ARCH_2_07)
29
+ PPC64.IsPOWER9 = isSet(HWCap2, hwcap2_ARCH_3_00)
30
+ PPC64.IsPOWER10 = isSet(HWCap2, hwcap2_ARCH_3_1)
31
+ PPC64.HasDARN = isSet(HWCap2, hwcap2_DARN)
32
+ PPC64.HasSCV = isSet(HWCap2, hwcap2_SCV)
33
+ }
go/src/internal/cpu/cpu_ppc64x_other.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build (ppc64 || ppc64le) && !aix && !linux
6
+
7
+ package cpu
8
+
9
+ func osinit() {
10
+ // Other operating systems do not support reading HWCap from auxiliary vector,
11
+ // reading privileged system registers or sysctl in user space to detect CPU
12
+ // features at runtime.
13
+ }
go/src/internal/cpu/cpu_riscv64.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2019 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ const CacheLinePadSize = 64
8
+
9
+ // RISC-V doesn't have a 'cpuid' equivalent. On Linux we rely on the riscv_hwprobe syscall.
10
+
11
+ func doinit() {
12
+ options = []option{
13
+ {Name: "fastmisaligned", Feature: &RISCV64.HasFastMisaligned},
14
+ {Name: "v", Feature: &RISCV64.HasV},
15
+ {Name: "zbb", Feature: &RISCV64.HasZbb},
16
+ }
17
+ osInit()
18
+ }
19
+
20
+ func isSet(hwc uint, value uint) bool {
21
+ return hwc&value != 0
22
+ }
go/src/internal/cpu/cpu_riscv64_linux.go ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build riscv64 && linux
6
+
7
+ package cpu
8
+
9
+ import _ "unsafe"
10
+
11
+ // RISC-V extension discovery code for Linux.
12
+ //
13
+ // A note on detection of the Vector extension using HWCAP.
14
+ //
15
+ // Support for the Vector extension version 1.0 was added to the Linux kernel in release 6.5.
16
+ // Support for the riscv_hwprobe syscall was added in 6.4. It follows that if the riscv_hwprobe
17
+ // syscall is not available then neither is the Vector extension (which needs kernel support).
18
+ // The riscv_hwprobe syscall should then be all we need to detect the Vector extension.
19
+ // However, some RISC-V board manufacturers ship boards with an older kernel on top of which
20
+ // they have back-ported various versions of the Vector extension patches but not the riscv_hwprobe
21
+ // patches. These kernels advertise support for the Vector extension using HWCAP. Falling
22
+ // back to HWCAP to detect the Vector extension, if riscv_hwprobe is not available, or simply not
23
+ // bothering with riscv_hwprobe at all and just using HWCAP may then seem like an attractive option.
24
+ //
25
+ // Unfortunately, simply checking the 'V' bit in AT_HWCAP will not work as this bit is used by
26
+ // RISC-V board and cloud instance providers to mean different things. The Lichee Pi 4A board
27
+ // and the Scaleway RV1 cloud instances use the 'V' bit to advertise their support for the unratified
28
+ // 0.7.1 version of the Vector Specification. The Banana Pi BPI-F3 and the CanMV-K230 board use
29
+ // it to advertise support for 1.0 of the Vector extension. Versions 0.7.1 and 1.0 of the Vector
30
+ // extension are binary incompatible. HWCAP can then not be used in isolation to populate the
31
+ // HasV field as this field indicates that the underlying CPU is compatible with RVV 1.0.
32
+ // Go will only support the ratified versions >= 1.0 and so any vector code it might generate
33
+ // would crash on a Scaleway RV1 instance or a Lichee Pi 4a, if allowed to run.
34
+ //
35
+ // There is a way at runtime to distinguish between versions 0.7.1 and 1.0 of the Vector
36
+ // specification by issuing a RVV 1.0 vsetvli instruction and checking the vill bit of the vtype
37
+ // register. This check would allow us to safely detect version 1.0 of the Vector extension
38
+ // with HWCAP, if riscv_hwprobe were not available. However, the check cannot
39
+ // be added until the assembler supports the Vector instructions.
40
+ //
41
+ // Note the riscv_hwprobe syscall does not suffer from these ambiguities by design as all of the
42
+ // extensions it advertises support for are explicitly versioned. It's also worth noting that
43
+ // the riscv_hwprobe syscall is the only way to detect multi-letter RISC-V extensions, e.g., Zvbb.
44
+ // These cannot be detected using HWCAP and so riscv_hwprobe must be used to detect the majority
45
+ // of RISC-V extensions.
46
+ //
47
+ // Please see https://docs.kernel.org/arch/riscv/hwprobe.html for more information.
48
+
49
+ const (
50
+ // Copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go.
51
+ riscv_HWPROBE_KEY_IMA_EXT_0 = 0x4
52
+ riscv_HWPROBE_IMA_V = 0x4
53
+ riscv_HWPROBE_EXT_ZBB = 0x10
54
+ riscv_HWPROBE_KEY_CPUPERF_0 = 0x5
55
+ riscv_HWPROBE_MISALIGNED_FAST = 0x3
56
+ riscv_HWPROBE_MISALIGNED_MASK = 0x7
57
+ )
58
+
59
+ // riscvHWProbePairs is copied from golang.org/x/sys/unix/ztypes_linux_riscv64.go.
60
+ type riscvHWProbePairs struct {
61
+ key int64
62
+ value uint64
63
+ }
64
+
65
+ //go:linkname riscvHWProbe
66
+ func riscvHWProbe(pairs []riscvHWProbePairs, flags uint) bool
67
+
68
+ func osInit() {
69
+ // A slice of key/value pair structures is passed to the RISCVHWProbe syscall. The key
70
+ // field should be initialised with one of the key constants defined above, e.g.,
71
+ // RISCV_HWPROBE_KEY_IMA_EXT_0. The syscall will set the value field to the appropriate value.
72
+ // If the kernel does not recognise a key it will set the key field to -1 and the value field to 0.
73
+
74
+ pairs := []riscvHWProbePairs{
75
+ {riscv_HWPROBE_KEY_IMA_EXT_0, 0},
76
+ {riscv_HWPROBE_KEY_CPUPERF_0, 0},
77
+ }
78
+
79
+ // This call only indicates that extensions are supported if they are implemented on all cores.
80
+ if !riscvHWProbe(pairs, 0) {
81
+ return
82
+ }
83
+
84
+ if pairs[0].key != -1 {
85
+ v := uint(pairs[0].value)
86
+ RISCV64.HasV = isSet(v, riscv_HWPROBE_IMA_V)
87
+ RISCV64.HasZbb = isSet(v, riscv_HWPROBE_EXT_ZBB)
88
+ }
89
+ if pairs[1].key != -1 {
90
+ v := pairs[1].value & riscv_HWPROBE_MISALIGNED_MASK
91
+ RISCV64.HasFastMisaligned = v == riscv_HWPROBE_MISALIGNED_FAST
92
+ }
93
+ }
go/src/internal/cpu/cpu_riscv64_other.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build riscv64 && !linux
6
+
7
+ package cpu
8
+
9
+ func osInit() {
10
+ // Other operating systems do not support the riscv_hwprobe syscall.
11
+ }
go/src/internal/cpu/cpu_s390x.go ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ const CacheLinePadSize = 256
8
+
9
+ var HWCap uint
10
+
11
+ // bitIsSet reports whether the bit at index is set. The bit index
12
+ // is in big endian order, so bit index 0 is the leftmost bit.
13
+ func bitIsSet(bits []uint64, index uint) bool {
14
+ return bits[index/64]&((1<<63)>>(index%64)) != 0
15
+ }
16
+
17
+ // function is the function code for the named function.
18
+ type function uint8
19
+
20
+ const (
21
+ // KM{,A,C,CTR} function codes
22
+ aes128 function = 18 // AES-128
23
+ aes192 function = 19 // AES-192
24
+ aes256 function = 20 // AES-256
25
+
26
+ // K{I,L}MD function codes
27
+ sha1 function = 1 // SHA-1
28
+ sha256 function = 2 // SHA-256
29
+ sha512 function = 3 // SHA-512
30
+ sha3_224 function = 32 // SHA3-224
31
+ sha3_256 function = 33 // SHA3-256
32
+ sha3_384 function = 34 // SHA3-384
33
+ sha3_512 function = 35 // SHA3-512
34
+ shake128 function = 36 // SHAKE-128
35
+ shake256 function = 37 // SHAKE-256
36
+
37
+ // KLMD function codes
38
+ ghash function = 65 // GHASH
39
+ )
40
+
41
+ const (
42
+ // KDSA function codes
43
+ ecdsaVerifyP256 function = 1 // NIST P256
44
+ ecdsaVerifyP384 function = 2 // NIST P384
45
+ ecdsaVerifyP521 function = 3 // NIST P521
46
+ ecdsaSignP256 function = 9 // NIST P256
47
+ ecdsaSignP384 function = 10 // NIST P384
48
+ ecdsaSignP521 function = 11 // NIST P521
49
+ eddsaVerifyEd25519 function = 32 // Curve25519
50
+ eddsaVerifyEd448 function = 36 // Curve448
51
+ eddsaSignEd25519 function = 40 // Curve25519
52
+ eddsaSignEd448 function = 44 // Curve448
53
+ )
54
+
55
+ // queryResult contains the result of a Query function
56
+ // call. Bits are numbered in big endian order so the
57
+ // leftmost bit (the MSB) is at index 0.
58
+ type queryResult struct {
59
+ bits [2]uint64
60
+ }
61
+
62
+ // Has reports whether the given functions are present.
63
+ func (q *queryResult) Has(fns ...function) bool {
64
+ if len(fns) == 0 {
65
+ panic("no function codes provided")
66
+ }
67
+ for _, f := range fns {
68
+ if !bitIsSet(q.bits[:], uint(f)) {
69
+ return false
70
+ }
71
+ }
72
+ return true
73
+ }
74
+
75
+ // facility is a bit index for the named facility.
76
+ type facility uint8
77
+
78
+ const (
79
+ // mandatory facilities
80
+ zarch facility = 1 // z architecture mode is active
81
+ stflef facility = 7 // store-facility-list-extended
82
+ ldisp facility = 18 // long-displacement
83
+ eimm facility = 21 // extended-immediate
84
+
85
+ // miscellaneous facilities
86
+ dfp facility = 42 // decimal-floating-point
87
+ etf3eh facility = 30 // extended-translation 3 enhancement
88
+
89
+ // cryptography facilities
90
+ msa facility = 17 // message-security-assist
91
+ msa3 facility = 76 // message-security-assist extension 3
92
+ msa4 facility = 77 // message-security-assist extension 4
93
+ msa5 facility = 57 // message-security-assist extension 5
94
+ msa8 facility = 146 // message-security-assist extension 8
95
+ msa9 facility = 155 // message-security-assist extension 9
96
+
97
+ // vector facilities
98
+ vxe facility = 135 // vector-enhancements 1
99
+
100
+ // Note: vx requires kernel support
101
+ // and so must be fetched from HWCAP.
102
+
103
+ hwcap_VX = 1 << 11 // vector facility
104
+ )
105
+
106
+ // facilityList contains the result of an STFLE call.
107
+ // Bits are numbered in big endian order so the
108
+ // leftmost bit (the MSB) is at index 0.
109
+ type facilityList struct {
110
+ bits [4]uint64
111
+ }
112
+
113
+ // Has reports whether the given facilities are present.
114
+ func (s *facilityList) Has(fs ...facility) bool {
115
+ if len(fs) == 0 {
116
+ panic("no facility bits provided")
117
+ }
118
+ for _, f := range fs {
119
+ if !bitIsSet(s.bits[:], uint(f)) {
120
+ return false
121
+ }
122
+ }
123
+ return true
124
+ }
125
+
126
+ // The following feature detection functions are defined in cpu_s390x.s.
127
+ // They are likely to be expensive to call so the results should be cached.
128
+ func stfle() facilityList
129
+ func kmQuery() queryResult
130
+ func kmcQuery() queryResult
131
+ func kmctrQuery() queryResult
132
+ func kmaQuery() queryResult
133
+ func kimdQuery() queryResult
134
+ func klmdQuery() queryResult
135
+ func kdsaQuery() queryResult
136
+
137
+ func doinit() {
138
+ options = []option{
139
+ {Name: "zarch", Feature: &S390X.HasZARCH},
140
+ {Name: "stfle", Feature: &S390X.HasSTFLE},
141
+ {Name: "ldisp", Feature: &S390X.HasLDISP},
142
+ {Name: "msa", Feature: &S390X.HasMSA},
143
+ {Name: "eimm", Feature: &S390X.HasEIMM},
144
+ {Name: "dfp", Feature: &S390X.HasDFP},
145
+ {Name: "etf3eh", Feature: &S390X.HasETF3EH},
146
+ {Name: "vx", Feature: &S390X.HasVX},
147
+ {Name: "vxe", Feature: &S390X.HasVXE},
148
+ {Name: "kdsa", Feature: &S390X.HasKDSA},
149
+ }
150
+
151
+ aes := []function{aes128, aes192, aes256}
152
+ facilities := stfle()
153
+
154
+ S390X.HasZARCH = facilities.Has(zarch)
155
+ S390X.HasSTFLE = facilities.Has(stflef)
156
+ S390X.HasLDISP = facilities.Has(ldisp)
157
+ S390X.HasEIMM = facilities.Has(eimm)
158
+ S390X.HasDFP = facilities.Has(dfp)
159
+ S390X.HasETF3EH = facilities.Has(etf3eh)
160
+ S390X.HasMSA = facilities.Has(msa)
161
+
162
+ if S390X.HasMSA {
163
+ // cipher message
164
+ km, kmc := kmQuery(), kmcQuery()
165
+ S390X.HasAES = km.Has(aes...)
166
+ S390X.HasAESCBC = kmc.Has(aes...)
167
+ if facilities.Has(msa4) {
168
+ kmctr := kmctrQuery()
169
+ S390X.HasAESCTR = kmctr.Has(aes...)
170
+ }
171
+ if facilities.Has(msa8) {
172
+ kma := kmaQuery()
173
+ S390X.HasAESGCM = kma.Has(aes...)
174
+ }
175
+
176
+ // compute message digest
177
+ kimd := kimdQuery() // intermediate (no padding)
178
+ klmd := klmdQuery() // last (padding)
179
+ S390X.HasSHA1 = kimd.Has(sha1) && klmd.Has(sha1)
180
+ S390X.HasSHA256 = kimd.Has(sha256) && klmd.Has(sha256)
181
+ S390X.HasSHA512 = kimd.Has(sha512) && klmd.Has(sha512)
182
+ S390X.HasGHASH = kimd.Has(ghash) // KLMD-GHASH does not exist
183
+ sha3 := []function{
184
+ sha3_224, sha3_256, sha3_384, sha3_512,
185
+ shake128, shake256,
186
+ }
187
+ S390X.HasSHA3 = kimd.Has(sha3...) && klmd.Has(sha3...)
188
+ S390X.HasKDSA = facilities.Has(msa9) // elliptic curves
189
+ if S390X.HasKDSA {
190
+ kdsa := kdsaQuery()
191
+ S390X.HasECDSA = kdsa.Has(ecdsaVerifyP256, ecdsaSignP256, ecdsaVerifyP384, ecdsaSignP384, ecdsaVerifyP521, ecdsaSignP521)
192
+ S390X.HasEDDSA = kdsa.Has(eddsaVerifyEd25519, eddsaSignEd25519, eddsaVerifyEd448, eddsaSignEd448)
193
+ }
194
+ }
195
+
196
+ S390X.HasVX = isSet(HWCap, hwcap_VX)
197
+
198
+ if S390X.HasVX {
199
+ S390X.HasVXE = facilities.Has(vxe)
200
+ }
201
+ }
202
+
203
+ func isSet(hwc uint, value uint) bool {
204
+ return hwc&value != 0
205
+ }
go/src/internal/cpu/cpu_s390x.s ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ #include "textflag.h"
6
+
7
+ // func stfle() facilityList
8
+ TEXT ·stfle(SB), NOSPLIT|NOFRAME, $0-32
9
+ MOVD $ret+0(FP), R1
10
+ MOVD $3, R0 // last doubleword index to store
11
+ XC $32, (R1), (R1) // clear 4 doublewords (32 bytes)
12
+ WORD $0xb2b01000 // store facility list extended (STFLE)
13
+ RET
14
+
15
+ // func kmQuery() queryResult
16
+ TEXT ·kmQuery(SB), NOSPLIT|NOFRAME, $0-16
17
+ MOVD $0, R0 // set function code to 0 (KM-Query)
18
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
19
+ KM R2, R4 // cipher message (KM)
20
+ RET
21
+
22
+ // func kmcQuery() queryResult
23
+ TEXT ·kmcQuery(SB), NOSPLIT|NOFRAME, $0-16
24
+ MOVD $0, R0 // set function code to 0 (KMC-Query)
25
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
26
+ KMC R2, R4 // cipher message with chaining (KMC)
27
+ RET
28
+
29
+ // func kmctrQuery() queryResult
30
+ TEXT ·kmctrQuery(SB), NOSPLIT|NOFRAME, $0-16
31
+ MOVD $0, R0 // set function code to 0 (KMCTR-Query)
32
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
33
+ KMCTR R2, R4, R4 // cipher message with counter (KMCTR)
34
+ RET
35
+
36
+ // func kmaQuery() queryResult
37
+ TEXT ·kmaQuery(SB), NOSPLIT|NOFRAME, $0-16
38
+ MOVD $0, R0 // set function code to 0 (KMA-Query)
39
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
40
+ KMA R2, R6, R4 // cipher message with authentication (KMA)
41
+ RET
42
+
43
+ // func kimdQuery() queryResult
44
+ TEXT ·kimdQuery(SB), NOSPLIT|NOFRAME, $0-16
45
+ MOVD $0, R0 // set function code to 0 (KIMD-Query)
46
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
47
+ KIMD R2, R4 // compute intermediate message digest (KIMD)
48
+ RET
49
+
50
+ // func klmdQuery() queryResult
51
+ TEXT ·klmdQuery(SB), NOSPLIT|NOFRAME, $0-16
52
+ MOVD $0, R0 // set function code to 0 (KLMD-Query)
53
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
54
+ KLMD R2, R4 // compute last message digest (KLMD)
55
+ RET
56
+
57
+ // func kdsaQuery() queryResult
58
+ TEXT ·kdsaQuery(SB), NOSPLIT|NOFRAME, $0-16
59
+ MOVD $0, R0 // set function code to 0 (KLMD-Query)
60
+ MOVD $ret+0(FP), R1 // address of 16-byte return value
61
+ KDSA R0, R4 // compute digital signature authentication
62
+ RET
63
+
go/src/internal/cpu/cpu_s390x_test.go ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu_test
6
+
7
+ import (
8
+ "errors"
9
+ . "internal/cpu"
10
+ "os"
11
+ "regexp"
12
+ "testing"
13
+ )
14
+
15
+ func getFeatureList() ([]string, error) {
16
+ cpuinfo, err := os.ReadFile("/proc/cpuinfo")
17
+ if err != nil {
18
+ return nil, err
19
+ }
20
+ r := regexp.MustCompile("features\\s*:\\s*(.*)")
21
+ b := r.FindSubmatch(cpuinfo)
22
+ if len(b) < 2 {
23
+ return nil, errors.New("no feature list in /proc/cpuinfo")
24
+ }
25
+ return regexp.MustCompile("\\s+").Split(string(b[1]), -1), nil
26
+ }
27
+
28
+ func TestS390XAgainstCPUInfo(t *testing.T) {
29
+ // mapping of linux feature strings to S390X fields
30
+ mapping := make(map[string]*bool)
31
+ for _, option := range Options {
32
+ mapping[option.Name] = option.Feature
33
+ }
34
+
35
+ // these must be true on the machines Go supports
36
+ mandatory := make(map[string]bool)
37
+ mandatory["zarch"] = false
38
+ mandatory["eimm"] = false
39
+ mandatory["ldisp"] = false
40
+ mandatory["stfle"] = false
41
+
42
+ features, err := getFeatureList()
43
+ if err != nil {
44
+ t.Error(err)
45
+ }
46
+ for _, feature := range features {
47
+ if _, ok := mandatory[feature]; ok {
48
+ mandatory[feature] = true
49
+ }
50
+ if flag, ok := mapping[feature]; ok {
51
+ if !*flag {
52
+ t.Errorf("feature '%v' not detected", feature)
53
+ }
54
+ } else {
55
+ t.Logf("no entry for '%v'", feature)
56
+ }
57
+ }
58
+ for k, v := range mandatory {
59
+ if !v {
60
+ t.Errorf("mandatory feature '%v' not detected", k)
61
+ }
62
+ }
63
+ }
go/src/internal/cpu/cpu_test.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu_test
6
+
7
+ import (
8
+ . "internal/cpu"
9
+ "internal/godebug"
10
+ "internal/testenv"
11
+ "os/exec"
12
+ "runtime"
13
+ "testing"
14
+ )
15
+
16
+ func MustHaveDebugOptionsSupport(t *testing.T) {
17
+ switch runtime.GOOS {
18
+ case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
19
+ default:
20
+ t.Skipf("skipping test: cpu feature options not supported by OS")
21
+ }
22
+ }
23
+
24
+ func MustSupportFeatureDetection(t *testing.T) {
25
+ // TODO: add platforms that do not have CPU feature detection support.
26
+ }
27
+
28
+ func runDebugOptionsTest(t *testing.T, test string, options string) {
29
+ MustHaveDebugOptionsSupport(t)
30
+
31
+ env := "GODEBUG=" + options
32
+
33
+ cmd := exec.Command(testenv.Executable(t), "-test.run=^"+test+"$")
34
+ cmd.Env = append(cmd.Env, env)
35
+
36
+ output, err := cmd.CombinedOutput()
37
+ if err != nil {
38
+ t.Fatalf("%s with %s: run failed: %v output:\n%s\n",
39
+ test, env, err, string(output))
40
+ }
41
+ }
42
+
43
+ func TestDisableAllCapabilities(t *testing.T) {
44
+ MustSupportFeatureDetection(t)
45
+ runDebugOptionsTest(t, "TestAllCapabilitiesDisabled", "cpu.all=off")
46
+ }
47
+
48
+ func TestAllCapabilitiesDisabled(t *testing.T) {
49
+ MustHaveDebugOptionsSupport(t)
50
+
51
+ if godebug.New("#cpu.all").Value() != "off" {
52
+ t.Skipf("skipping test: GODEBUG=cpu.all=off not set")
53
+ }
54
+
55
+ for _, o := range Options {
56
+ want := false
57
+ if got := *o.Feature; got != want {
58
+ t.Errorf("%v: expected %v, got %v", o.Name, want, got)
59
+ }
60
+ }
61
+ }
go/src/internal/cpu/cpu_wasm.go ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ const CacheLinePadSize = 64
8
+
9
+ func doinit() {
10
+ }
go/src/internal/cpu/cpu_x86.go ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ package cpu
8
+
9
+ const CacheLinePadSize = 64
10
+
11
+ // cpuid is implemented in cpu_x86.s.
12
+ func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32)
13
+
14
+ // xgetbv with ecx = 0 is implemented in cpu_x86.s.
15
+ func xgetbv() (eax, edx uint32)
16
+
17
+ // getGOAMD64level is implemented in cpu_x86.s. Returns number in [1,4].
18
+ func getGOAMD64level() int32
19
+
20
+ const (
21
+ // eax bits
22
+ cpuid_AVXVNNI = 1 << 4
23
+
24
+ // ecx bits
25
+ cpuid_SSE3 = 1 << 0
26
+ cpuid_PCLMULQDQ = 1 << 1
27
+ cpuid_AVX512VBMI = 1 << 1
28
+ cpuid_AVX512VBMI2 = 1 << 6
29
+ cpuid_SSSE3 = 1 << 9
30
+ cpuid_AVX512GFNI = 1 << 8
31
+ cpuid_VAES = 1 << 9
32
+ cpuid_AVX512VNNI = 1 << 11
33
+ cpuid_AVX512BITALG = 1 << 12
34
+ cpuid_FMA = 1 << 12
35
+ cpuid_AVX512VPOPCNTDQ = 1 << 14
36
+ cpuid_SSE41 = 1 << 19
37
+ cpuid_SSE42 = 1 << 20
38
+ cpuid_POPCNT = 1 << 23
39
+ cpuid_AES = 1 << 25
40
+ cpuid_OSXSAVE = 1 << 27
41
+ cpuid_AVX = 1 << 28
42
+
43
+ // "Extended Feature Flag" bits returned in EBX for CPUID EAX=0x7 ECX=0x0
44
+ cpuid_BMI1 = 1 << 3
45
+ cpuid_AVX2 = 1 << 5
46
+ cpuid_BMI2 = 1 << 8
47
+ cpuid_ERMS = 1 << 9
48
+ cpuid_AVX512F = 1 << 16
49
+ cpuid_AVX512DQ = 1 << 17
50
+ cpuid_ADX = 1 << 19
51
+ cpuid_AVX512CD = 1 << 28
52
+ cpuid_SHA = 1 << 29
53
+ cpuid_AVX512BW = 1 << 30
54
+ cpuid_AVX512VL = 1 << 31
55
+
56
+ // "Extended Feature Flag" bits returned in ECX for CPUID EAX=0x7 ECX=0x0
57
+ cpuid_AVX512_VBMI = 1 << 1
58
+ cpuid_AVX512_VBMI2 = 1 << 6
59
+ cpuid_GFNI = 1 << 8
60
+ cpuid_AVX512VPCLMULQDQ = 1 << 10
61
+ cpuid_AVX512_BITALG = 1 << 12
62
+
63
+ // edx bits
64
+ cpuid_FSRM = 1 << 4
65
+ // edx bits for CPUID 0x80000001
66
+ cpuid_RDTSCP = 1 << 27
67
+ )
68
+
69
+ var maxExtendedFunctionInformation uint32
70
+
71
+ func doinit() {
72
+ options = []option{
73
+ {Name: "adx", Feature: &X86.HasADX},
74
+ {Name: "aes", Feature: &X86.HasAES},
75
+ {Name: "erms", Feature: &X86.HasERMS},
76
+ {Name: "fsrm", Feature: &X86.HasFSRM},
77
+ {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ},
78
+ {Name: "rdtscp", Feature: &X86.HasRDTSCP},
79
+ {Name: "sha", Feature: &X86.HasSHA},
80
+ {Name: "vpclmulqdq", Feature: &X86.HasAVX512VPCLMULQDQ},
81
+ }
82
+ level := getGOAMD64level()
83
+ if level < 2 {
84
+ // These options are required at level 2. At lower levels
85
+ // they can be turned off.
86
+ options = append(options,
87
+ option{Name: "popcnt", Feature: &X86.HasPOPCNT},
88
+ option{Name: "sse3", Feature: &X86.HasSSE3},
89
+ option{Name: "sse41", Feature: &X86.HasSSE41},
90
+ option{Name: "sse42", Feature: &X86.HasSSE42},
91
+ option{Name: "ssse3", Feature: &X86.HasSSSE3})
92
+ }
93
+ if level < 3 {
94
+ // These options are required at level 3. At lower levels
95
+ // they can be turned off.
96
+ options = append(options,
97
+ option{Name: "avx", Feature: &X86.HasAVX},
98
+ option{Name: "avx2", Feature: &X86.HasAVX2},
99
+ option{Name: "bmi1", Feature: &X86.HasBMI1},
100
+ option{Name: "bmi2", Feature: &X86.HasBMI2},
101
+ option{Name: "fma", Feature: &X86.HasFMA})
102
+ }
103
+ if level < 4 {
104
+ // These options are required at level 4. At lower levels
105
+ // they can be turned off.
106
+ options = append(options,
107
+ option{Name: "avx512f", Feature: &X86.HasAVX512F},
108
+ option{Name: "avx512cd", Feature: &X86.HasAVX512CD},
109
+ option{Name: "avx512bw", Feature: &X86.HasAVX512BW},
110
+ option{Name: "avx512dq", Feature: &X86.HasAVX512DQ},
111
+ option{Name: "avx512vl", Feature: &X86.HasAVX512VL},
112
+ )
113
+ }
114
+
115
+ maxID, _, _, _ := cpuid(0, 0)
116
+
117
+ if maxID < 1 {
118
+ osInit()
119
+ return
120
+ }
121
+
122
+ maxExtendedFunctionInformation, _, _, _ = cpuid(0x80000000, 0)
123
+
124
+ _, _, ecx1, _ := cpuid(1, 0)
125
+
126
+ X86.HasSSE3 = isSet(ecx1, cpuid_SSE3)
127
+ X86.HasPCLMULQDQ = isSet(ecx1, cpuid_PCLMULQDQ)
128
+ X86.HasSSSE3 = isSet(ecx1, cpuid_SSSE3)
129
+ X86.HasSSE41 = isSet(ecx1, cpuid_SSE41)
130
+ X86.HasSSE42 = isSet(ecx1, cpuid_SSE42)
131
+ X86.HasPOPCNT = isSet(ecx1, cpuid_POPCNT)
132
+ X86.HasAES = isSet(ecx1, cpuid_AES)
133
+
134
+ // OSXSAVE can be false when using older Operating Systems
135
+ // or when explicitly disabled on newer Operating Systems by
136
+ // e.g. setting the xsavedisable boot option on Windows 10.
137
+ X86.HasOSXSAVE = isSet(ecx1, cpuid_OSXSAVE)
138
+
139
+ osSupportsAVX := false
140
+ osSupportsAVX512 := false
141
+ // For XGETBV, OSXSAVE bit is required and sufficient.
142
+ if X86.HasOSXSAVE {
143
+ eax, _ := xgetbv()
144
+ // Check if XMM and YMM registers have OS support.
145
+ osSupportsAVX = isSet(eax, 1<<1) && isSet(eax, 1<<2)
146
+
147
+ // AVX512 detection does not work on Darwin,
148
+ // see https://github.com/golang/go/issues/49233
149
+ //
150
+ // Check if opmask, ZMMhi256 and Hi16_ZMM have OS support.
151
+ osSupportsAVX512 = osSupportsAVX && isSet(eax, 1<<5) && isSet(eax, 1<<6) && isSet(eax, 1<<7)
152
+ }
153
+
154
+ X86.HasAVX = isSet(ecx1, cpuid_AVX) && osSupportsAVX
155
+
156
+ // The FMA instruction set extension requires both the FMA and AVX flags.
157
+ //
158
+ // Furthermore, the FMA instructions are all VEX prefixed instructions.
159
+ // VEX prefixed instructions require OSXSAVE to be enabled.
160
+ // See Intel 64 and IA-32 Architecture Software Developer’s Manual Volume 2
161
+ // Section 2.4 "AVX and SSE Instruction Exception Specification"
162
+ X86.HasFMA = isSet(ecx1, cpuid_FMA) && X86.HasAVX && X86.HasOSXSAVE
163
+
164
+ if maxID < 7 {
165
+ osInit()
166
+ return
167
+ }
168
+
169
+ eax7, ebx7, ecx7, edx7 := cpuid(7, 0)
170
+ X86.HasBMI1 = isSet(ebx7, cpuid_BMI1)
171
+ X86.HasAVX2 = isSet(ebx7, cpuid_AVX2) && osSupportsAVX
172
+ X86.HasBMI2 = isSet(ebx7, cpuid_BMI2)
173
+ X86.HasERMS = isSet(ebx7, cpuid_ERMS)
174
+ X86.HasADX = isSet(ebx7, cpuid_ADX)
175
+ X86.HasSHA = isSet(ebx7, cpuid_SHA)
176
+ X86.HasVAES = isSet(ecx7, cpuid_VAES) && X86.HasAVX
177
+
178
+ X86.HasAVX512F = isSet(ebx7, cpuid_AVX512F) && osSupportsAVX512
179
+ if X86.HasAVX512F {
180
+ X86.HasAVX512CD = isSet(ebx7, cpuid_AVX512CD)
181
+ X86.HasAVX512BW = isSet(ebx7, cpuid_AVX512BW)
182
+ X86.HasAVX512DQ = isSet(ebx7, cpuid_AVX512DQ)
183
+ X86.HasAVX512VL = isSet(ebx7, cpuid_AVX512VL)
184
+ X86.HasAVX512GFNI = isSet(ecx7, cpuid_AVX512GFNI)
185
+ X86.HasAVX512BITALG = isSet(ecx7, cpuid_AVX512BITALG)
186
+ X86.HasAVX512VPOPCNTDQ = isSet(ecx7, cpuid_AVX512VPOPCNTDQ)
187
+ X86.HasAVX512VBMI = isSet(ecx7, cpuid_AVX512VBMI)
188
+ X86.HasAVX512VBMI2 = isSet(ecx7, cpuid_AVX512VBMI2)
189
+ X86.HasAVX512VAES = isSet(ecx7, cpuid_VAES) && X86.HasAES && isSet(ebx7, cpuid_AVX512VL)
190
+ X86.HasAVX512VNNI = isSet(ecx7, cpuid_AVX512VNNI)
191
+ X86.HasAVX512VPCLMULQDQ = isSet(ecx7, cpuid_AVX512VPCLMULQDQ)
192
+ X86.HasAVX512VBMI = isSet(ecx7, cpuid_AVX512_VBMI)
193
+ X86.HasAVX512VBMI2 = isSet(ecx7, cpuid_AVX512_VBMI2)
194
+ X86.HasGFNI = isSet(ecx7, cpuid_GFNI)
195
+ X86.HasAVX512BITALG = isSet(ecx7, cpuid_AVX512_BITALG)
196
+ }
197
+
198
+ X86.HasFSRM = isSet(edx7, cpuid_FSRM)
199
+
200
+ var maxExtendedInformation uint32
201
+ maxExtendedInformation, _, _, _ = cpuid(0x80000000, 0)
202
+
203
+ if maxExtendedInformation < 0x80000001 {
204
+ osInit()
205
+ return
206
+ }
207
+
208
+ _, _, _, edxExt1 := cpuid(0x80000001, 0)
209
+ X86.HasRDTSCP = isSet(edxExt1, cpuid_RDTSCP)
210
+
211
+ doDerived = func() {
212
+ // Rather than carefully gating on fundamental AVX-512 features, we have
213
+ // a virtual "AVX512" feature that captures F+CD+BW+DQ+VL. BW, DQ, and
214
+ // VL have a huge effect on which AVX-512 instructions are available,
215
+ // and these have all been supported on everything except the earliest
216
+ // Phi chips with AVX-512. No CPU has had CD without F, so we include
217
+ // it. GOAMD64=v4 also implies exactly this set, and these are all
218
+ // included in AVX10.1.
219
+ X86.HasAVX512 = X86.HasAVX512F && X86.HasAVX512CD && X86.HasAVX512BW && X86.HasAVX512DQ && X86.HasAVX512VL
220
+ }
221
+
222
+ if eax7 >= 1 {
223
+ eax71, _, _, _ := cpuid(7, 1)
224
+ if X86.HasAVX {
225
+ X86.HasAVXVNNI = isSet(eax71, cpuid_AVXVNNI)
226
+ }
227
+ }
228
+
229
+ osInit()
230
+ }
231
+
232
+ func isSet(hwc uint32, value uint32) bool {
233
+ return hwc&value != 0
234
+ }
235
+
236
+ // Name returns the CPU name given by the vendor.
237
+ // If the CPU name can not be determined an
238
+ // empty string is returned.
239
+ func Name() string {
240
+ if maxExtendedFunctionInformation < 0x80000004 {
241
+ return ""
242
+ }
243
+
244
+ data := make([]byte, 0, 3*4*4)
245
+
246
+ var eax, ebx, ecx, edx uint32
247
+ eax, ebx, ecx, edx = cpuid(0x80000002, 0)
248
+ data = appendBytes(data, eax, ebx, ecx, edx)
249
+ eax, ebx, ecx, edx = cpuid(0x80000003, 0)
250
+ data = appendBytes(data, eax, ebx, ecx, edx)
251
+ eax, ebx, ecx, edx = cpuid(0x80000004, 0)
252
+ data = appendBytes(data, eax, ebx, ecx, edx)
253
+
254
+ // Trim leading spaces.
255
+ for len(data) > 0 && data[0] == ' ' {
256
+ data = data[1:]
257
+ }
258
+
259
+ // Trim tail after and including the first null byte.
260
+ for i, c := range data {
261
+ if c == '\x00' {
262
+ data = data[:i]
263
+ break
264
+ }
265
+ }
266
+
267
+ return string(data)
268
+ }
269
+
270
+ func appendBytes(b []byte, args ...uint32) []byte {
271
+ for _, arg := range args {
272
+ b = append(b,
273
+ byte((arg >> 0)),
274
+ byte((arg >> 8)),
275
+ byte((arg >> 16)),
276
+ byte((arg >> 24)))
277
+ }
278
+ return b
279
+ }
go/src/internal/cpu/cpu_x86.s ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ #include "textflag.h"
8
+
9
+ // func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32)
10
+ TEXT ·cpuid(SB), NOSPLIT, $0-24
11
+ MOVL eaxArg+0(FP), AX
12
+ MOVL ecxArg+4(FP), CX
13
+ CPUID
14
+ MOVL AX, eax+8(FP)
15
+ MOVL BX, ebx+12(FP)
16
+ MOVL CX, ecx+16(FP)
17
+ MOVL DX, edx+20(FP)
18
+ RET
19
+
20
+ // func xgetbv() (eax, edx uint32)
21
+ TEXT ·xgetbv(SB),NOSPLIT,$0-8
22
+ MOVL $0, CX
23
+ XGETBV
24
+ MOVL AX, eax+0(FP)
25
+ MOVL DX, edx+4(FP)
26
+ RET
27
+
28
+ // func getGOAMD64level() int32
29
+ TEXT ·getGOAMD64level(SB),NOSPLIT,$0-4
30
+ #ifdef GOAMD64_v4
31
+ MOVL $4, ret+0(FP)
32
+ #else
33
+ #ifdef GOAMD64_v3
34
+ MOVL $3, ret+0(FP)
35
+ #else
36
+ #ifdef GOAMD64_v2
37
+ MOVL $2, ret+0(FP)
38
+ #else
39
+ MOVL $1, ret+0(FP)
40
+ #endif
41
+ #endif
42
+ #endif
43
+ RET
go/src/internal/cpu/cpu_x86_darwin.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build (386 || amd64) && darwin && !ios
6
+
7
+ package cpu
8
+
9
+ func osInit() {
10
+ if isRosetta() && darwinKernelVersionCheck(24, 0, 0) {
11
+ // Apparently, on macOS 15 (Darwin kernel version 24) or newer,
12
+ // Rosetta 2 supports AVX1 and 2. However, neither CPUID nor
13
+ // sysctl says it has AVX. Detect this situation here and report
14
+ // AVX1 and 2 as supported.
15
+ // TODO: check if any other feature is actually supported.
16
+ X86.HasAVX = true
17
+ X86.HasAVX2 = true
18
+ }
19
+ }
20
+
21
+ func isRosetta() bool {
22
+ return sysctlEnabled([]byte("sysctl.proc_translated\x00"))
23
+ }
go/src/internal/cpu/cpu_x86_other.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build (386 || amd64) && (!darwin || ios)
6
+
7
+ package cpu
8
+
9
+ func osInit() {}
go/src/internal/cpu/cpu_x86_test.go ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ package cpu_test
8
+
9
+ import (
10
+ . "internal/cpu"
11
+ "internal/godebug"
12
+ "testing"
13
+ )
14
+
15
+ func TestX86ifAVX2hasAVX(t *testing.T) {
16
+ if X86.HasAVX2 && !X86.HasAVX {
17
+ t.Fatalf("HasAVX expected true when HasAVX2 is true, got false")
18
+ }
19
+ }
20
+
21
+ func TestX86ifAVX512FhasAVX2(t *testing.T) {
22
+ if X86.HasAVX512F && !X86.HasAVX2 {
23
+ t.Fatalf("HasAVX2 expected true when HasAVX512F is true, got false")
24
+ }
25
+ }
26
+
27
+ func TestX86ifAVX512BWhasAVX512F(t *testing.T) {
28
+ if X86.HasAVX512BW && !X86.HasAVX512F {
29
+ t.Fatalf("HasAVX512F expected true when HasAVX512BW is true, got false")
30
+ }
31
+ }
32
+
33
+ func TestX86ifAVX512VLhasAVX512F(t *testing.T) {
34
+ if X86.HasAVX512VL && !X86.HasAVX512F {
35
+ t.Fatalf("HasAVX512F expected true when HasAVX512VL is true, got false")
36
+ }
37
+ }
38
+
39
+ func TestDisableSSE3(t *testing.T) {
40
+ if GetGOAMD64level() > 1 {
41
+ t.Skip("skipping test: can't run on GOAMD64>v1 machines")
42
+ }
43
+ runDebugOptionsTest(t, "TestSSE3DebugOption", "cpu.sse3=off")
44
+ }
45
+
46
+ func TestSSE3DebugOption(t *testing.T) {
47
+ MustHaveDebugOptionsSupport(t)
48
+
49
+ if godebug.New("#cpu.sse3").Value() != "off" {
50
+ t.Skipf("skipping test: GODEBUG=cpu.sse3=off not set")
51
+ }
52
+
53
+ want := false
54
+ if got := X86.HasSSE3; got != want {
55
+ t.Errorf("X86.HasSSE3 expected %v, got %v", want, got)
56
+ }
57
+ }
go/src/internal/cpu/datacache_unsupported.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build !386 && !amd64
6
+
7
+ package cpu
8
+
9
+ func DataCacheSizes() []uintptr {
10
+ return nil
11
+ }
go/src/internal/cpu/datacache_x86.go ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ package cpu
8
+
9
+ // DataCacheSizes returns the size of each data cache from lowest
10
+ // level in the hierarchy to highest.
11
+ //
12
+ // Unlike other parts of this package's public API, it is not safe
13
+ // to reference early in runtime initialization because it allocates.
14
+ // It's intended for testing only.
15
+ func DataCacheSizes() []uintptr {
16
+ maxFunctionInformation, ebx0, ecx0, edx0 := cpuid(0, 0)
17
+ if maxFunctionInformation < 1 {
18
+ return nil
19
+ }
20
+
21
+ switch {
22
+ // Check for "GenuineIntel"
23
+ case ebx0 == 0x756E6547 && ecx0 == 0x6C65746E && edx0 == 0x49656E69:
24
+ return getDataCacheSizesIntel(maxFunctionInformation)
25
+ // Check for "AuthenticAMD"
26
+ case ebx0 == 0x68747541 && ecx0 == 0x444D4163 && edx0 == 0x69746E65:
27
+ return getDataCacheSizesAMD()
28
+ }
29
+ return nil
30
+ }
31
+
32
+ func extractBits(arg uint32, l int, r int) uint32 {
33
+ if l > r {
34
+ panic("bad bit range")
35
+ }
36
+ return (arg >> l) & ((1 << (r - l + 1)) - 1)
37
+ }
38
+
39
+ func getDataCacheSizesIntel(maxID uint32) []uintptr {
40
+ // Constants for cache types
41
+ const (
42
+ noCache = 0
43
+ dataCache = 1
44
+ instructionCache = 2
45
+ unifiedCache = 3
46
+ )
47
+ if maxID < 4 {
48
+ return nil
49
+ }
50
+
51
+ // Iterate through CPUID leaf 4 (deterministic cache parameters)
52
+ var caches []uintptr
53
+ for i := uint32(0); i < 0xFFFF; i++ {
54
+ eax, ebx, ecx, _ := cpuid(4, i)
55
+
56
+ cacheType := eax & 0xF // EAX bits 4-0: Cache Type
57
+ if cacheType == 0 {
58
+ break
59
+ }
60
+
61
+ // Report only data caches.
62
+ if !(cacheType == dataCache || cacheType == unifiedCache) {
63
+ continue
64
+ }
65
+
66
+ // Guaranteed to always start counting from 1.
67
+ level := (eax >> 5) & 0x7
68
+
69
+ lineSize := extractBits(ebx, 0, 11) + 1 // Bits 11-0: Line size in bytes - 1
70
+ partitions := extractBits(ebx, 12, 21) + 1 // Bits 21-12: Physical line partitions - 1
71
+ ways := extractBits(ebx, 22, 31) + 1 // Bits 31-22: Ways of associativity - 1
72
+ sets := uint64(ecx) + 1 // Number of sets - 1
73
+ size := uint64(ways*partitions*lineSize) * sets // Calculate cache size in bytes
74
+
75
+ caches = append(caches, uintptr(size))
76
+
77
+ // If we see more than one cache described per level, or they appear
78
+ // out of order, crash.
79
+ //
80
+ // Going by the SDM, it's not clear whether this is actually possible,
81
+ // so this code is purely defensive.
82
+ if level != uint32(len(caches)) {
83
+ panic("expected levels to be in order and for there to be one data/unified cache per level")
84
+ }
85
+ }
86
+ return caches
87
+ }
88
+
89
+ func getDataCacheSizesAMD() []uintptr {
90
+ maxExtendedFunctionInformation, _, _, _ := cpuid(0x80000000, 0)
91
+ if maxExtendedFunctionInformation < 0x80000006 {
92
+ return nil
93
+ }
94
+
95
+ var caches []uintptr
96
+
97
+ _, _, ecx5, _ := cpuid(0x80000005, 0)
98
+ _, _, ecx6, edx6 := cpuid(0x80000006, 0)
99
+
100
+ // The size is return in kb, turning into bytes.
101
+ l1dSize := uintptr(extractBits(ecx5, 24, 31) << 10)
102
+ caches = append(caches, l1dSize)
103
+
104
+ // Check that L2 cache is present.
105
+ if l2Assoc := extractBits(ecx6, 12, 15); l2Assoc == 0 {
106
+ return caches
107
+ }
108
+ l2Size := uintptr(extractBits(ecx6, 16, 31) << 10)
109
+ caches = append(caches, l2Size)
110
+
111
+ // Check that L3 cache is present.
112
+ if l3Assoc := extractBits(edx6, 12, 15); l3Assoc == 0 {
113
+ return caches
114
+ }
115
+ // Specifies the L3 cache size is within the following range:
116
+ // (L3Size[31:18] * 512KB) <= L3 cache size < ((L3Size[31:18]+1) * 512KB).
117
+ l3Size := uintptr(extractBits(edx6, 18, 31) * (512 << 10))
118
+ caches = append(caches, l3Size)
119
+
120
+ return caches
121
+ }
go/src/internal/cpu/datacache_x86_test.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ package cpu_test
8
+
9
+ import (
10
+ "internal/cpu"
11
+ "testing"
12
+ )
13
+
14
+ // Tests fetching data cache sizes. This test only checks that DataCacheSizes
15
+ // won't explode. Otherwise it's just informational, and dumps the current
16
+ // data cache sizes.
17
+ func TestDataCacheSizes(t *testing.T) {
18
+ // N.B. Don't try to check these values because we don't know what
19
+ // kind of environment we're running in. We don't want this test to
20
+ // fail on some random x86 chip that happens to not support the right
21
+ // CPUID bits for some reason.
22
+ caches := cpu.DataCacheSizes()
23
+ for i, size := range caches {
24
+ t.Logf("L%d: %d", i+1, size)
25
+ }
26
+ }
go/src/internal/cpu/export_test.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cpu
6
+
7
+ var (
8
+ Options = options
9
+ )
go/src/internal/cpu/export_x86_test.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build 386 || amd64
6
+
7
+ package cpu
8
+
9
+ var (
10
+ GetGOAMD64level = getGOAMD64level
11
+ )
go/src/internal/dag/alg.go ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package dag
6
+
7
+ // Transpose reverses all edges in g.
8
+ func (g *Graph) Transpose() {
9
+ old := g.edges
10
+
11
+ g.edges = make(map[string]map[string]bool)
12
+ for _, n := range g.Nodes {
13
+ g.edges[n] = make(map[string]bool)
14
+ }
15
+
16
+ for from, tos := range old {
17
+ for to := range tos {
18
+ g.edges[to][from] = true
19
+ }
20
+ }
21
+ }
22
+
23
+ // Topo returns a topological sort of g. This function is deterministic.
24
+ func (g *Graph) Topo() []string {
25
+ topo := make([]string, 0, len(g.Nodes))
26
+ marks := make(map[string]bool)
27
+
28
+ var visit func(n string)
29
+ visit = func(n string) {
30
+ if marks[n] {
31
+ return
32
+ }
33
+ for _, to := range g.Edges(n) {
34
+ visit(to)
35
+ }
36
+ marks[n] = true
37
+ topo = append(topo, n)
38
+ }
39
+ for _, root := range g.Nodes {
40
+ visit(root)
41
+ }
42
+ for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
43
+ topo[i], topo[j] = topo[j], topo[i]
44
+ }
45
+ return topo
46
+ }
47
+
48
+ // TransitiveReduction removes edges from g that are transitively
49
+ // reachable. g must be transitively closed.
50
+ func (g *Graph) TransitiveReduction() {
51
+ // For i -> j -> k, if i -> k exists, delete it.
52
+ for _, i := range g.Nodes {
53
+ for _, j := range g.Nodes {
54
+ if g.HasEdge(i, j) {
55
+ for _, k := range g.Nodes {
56
+ if g.HasEdge(j, k) {
57
+ g.DelEdge(i, k)
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ }
go/src/internal/dag/alg_test.go ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package dag
6
+
7
+ import (
8
+ "slices"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ func TestTranspose(t *testing.T) {
14
+ g := mustParse(t, diamond)
15
+ g.Transpose()
16
+ wantEdges(t, g, "a->b a->c a->d b->d c->d")
17
+ }
18
+
19
+ func TestTopo(t *testing.T) {
20
+ g := mustParse(t, diamond)
21
+ got := g.Topo()
22
+ // "d" is the root, so it's first.
23
+ //
24
+ // "c" and "b" could be in either order, but Topo is
25
+ // deterministic in reverse node definition order.
26
+ //
27
+ // "a" is a leaf.
28
+ wantNodes := strings.Fields("d c b a")
29
+ if !slices.Equal(wantNodes, got) {
30
+ t.Fatalf("want topo sort %v, got %v", wantNodes, got)
31
+ }
32
+ }
33
+
34
+ func TestTransitiveReduction(t *testing.T) {
35
+ t.Run("diamond", func(t *testing.T) {
36
+ g := mustParse(t, diamond)
37
+ g.TransitiveReduction()
38
+ wantEdges(t, g, "b->a c->a d->b d->c")
39
+ })
40
+ t.Run("chain", func(t *testing.T) {
41
+ const chain = `NONE < a < b < c < d; a, d < e;`
42
+ g := mustParse(t, chain)
43
+ g.TransitiveReduction()
44
+ wantEdges(t, g, "e->d d->c c->b b->a")
45
+ })
46
+ }
go/src/internal/dag/parse.go ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package dag implements a language for expressing directed acyclic
6
+ // graphs.
7
+ //
8
+ // The general syntax of a rule is:
9
+ //
10
+ // a, b < c, d;
11
+ //
12
+ // which means c and d come after a and b in the partial order
13
+ // (that is, there are edges from c and d to a and b),
14
+ // but doesn't provide a relative order between a vs b or c vs d.
15
+ //
16
+ // The rules can chain together, as in:
17
+ //
18
+ // e < f, g < h;
19
+ //
20
+ // which is equivalent to
21
+ //
22
+ // e < f, g;
23
+ // f, g < h;
24
+ //
25
+ // Except for the special bottom element "NONE", each name
26
+ // must appear exactly once on the right-hand side of any rule.
27
+ // That rule serves as the definition of the allowed successor
28
+ // for that name. The definition must appear before any uses
29
+ // of the name on the left-hand side of a rule. (That is, the
30
+ // rules themselves must be ordered according to the partial
31
+ // order, for easier reading by people.)
32
+ //
33
+ // Negative assertions double-check the partial order:
34
+ //
35
+ // i !< j
36
+ //
37
+ // means that it must NOT be the case that i < j.
38
+ // Negative assertions may appear anywhere in the rules,
39
+ // even before i and j have been defined.
40
+ //
41
+ // Comments begin with #.
42
+ package dag
43
+
44
+ import (
45
+ "cmp"
46
+ "fmt"
47
+ "slices"
48
+ "strings"
49
+ )
50
+
51
+ type Graph struct {
52
+ Nodes []string
53
+ byLabel map[string]int
54
+ edges map[string]map[string]bool
55
+ }
56
+
57
+ func newGraph() *Graph {
58
+ return &Graph{byLabel: map[string]int{}, edges: map[string]map[string]bool{}}
59
+ }
60
+
61
+ func (g *Graph) addNode(label string) bool {
62
+ if _, ok := g.byLabel[label]; ok {
63
+ return false
64
+ }
65
+ g.byLabel[label] = len(g.Nodes)
66
+ g.Nodes = append(g.Nodes, label)
67
+ g.edges[label] = map[string]bool{}
68
+ return true
69
+ }
70
+
71
+ func (g *Graph) AddEdge(from, to string) {
72
+ g.edges[from][to] = true
73
+ }
74
+
75
+ func (g *Graph) DelEdge(from, to string) {
76
+ delete(g.edges[from], to)
77
+ }
78
+
79
+ func (g *Graph) HasEdge(from, to string) bool {
80
+ return g.edges[from] != nil && g.edges[from][to]
81
+ }
82
+
83
+ func (g *Graph) Edges(from string) []string {
84
+ edges := make([]string, 0, 16)
85
+ for k := range g.edges[from] {
86
+ edges = append(edges, k)
87
+ }
88
+ slices.SortFunc(edges, func(a, b string) int {
89
+ return cmp.Compare(g.byLabel[a], g.byLabel[b])
90
+ })
91
+ return edges
92
+ }
93
+
94
+ // Parse parses the DAG language and returns the transitive closure of
95
+ // the described graph. In the returned graph, there is an edge from "b"
96
+ // to "a" if b < a (or a > b) in the partial order.
97
+ func Parse(dag string) (*Graph, error) {
98
+ g := newGraph()
99
+ disallowed := []rule{}
100
+
101
+ rules, err := parseRules(dag)
102
+ if err != nil {
103
+ return nil, err
104
+ }
105
+
106
+ // TODO: Add line numbers to errors.
107
+ var errors []string
108
+ errorf := func(format string, a ...any) {
109
+ errors = append(errors, fmt.Sprintf(format, a...))
110
+ }
111
+ for _, r := range rules {
112
+ if r.op == "!<" {
113
+ disallowed = append(disallowed, r)
114
+ continue
115
+ }
116
+ for _, def := range r.def {
117
+ if def == "NONE" {
118
+ errorf("NONE cannot be a predecessor")
119
+ continue
120
+ }
121
+ if !g.addNode(def) {
122
+ errorf("multiple definitions for %s", def)
123
+ }
124
+ for _, less := range r.less {
125
+ if less == "NONE" {
126
+ continue
127
+ }
128
+ if _, ok := g.byLabel[less]; !ok {
129
+ errorf("use of %s before its definition", less)
130
+ } else {
131
+ g.AddEdge(def, less)
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ // Check for missing definition.
138
+ for _, tos := range g.edges {
139
+ for to := range tos {
140
+ if g.edges[to] == nil {
141
+ errorf("missing definition for %s", to)
142
+ }
143
+ }
144
+ }
145
+
146
+ // Complete transitive closure.
147
+ for _, k := range g.Nodes {
148
+ for _, i := range g.Nodes {
149
+ for _, j := range g.Nodes {
150
+ if i != k && k != j && g.HasEdge(i, k) && g.HasEdge(k, j) {
151
+ if i == j {
152
+ // Can only happen along with a "use of X before deps" error above,
153
+ // but this error is more specific - it makes clear that reordering the
154
+ // rules will not be enough to fix the problem.
155
+ errorf("graph cycle: %s < %s < %s", j, k, i)
156
+ }
157
+ g.AddEdge(i, j)
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ // Check negative assertions against completed allowed graph.
164
+ for _, bad := range disallowed {
165
+ for _, less := range bad.less {
166
+ for _, def := range bad.def {
167
+ if g.HasEdge(def, less) {
168
+ errorf("graph edge assertion failed: %s !< %s", less, def)
169
+ }
170
+ }
171
+ }
172
+ }
173
+
174
+ if len(errors) > 0 {
175
+ return nil, fmt.Errorf("%s", strings.Join(errors, "\n"))
176
+ }
177
+
178
+ return g, nil
179
+ }
180
+
181
+ // A rule is a line in the DAG language where "less < def" or "less !< def".
182
+ type rule struct {
183
+ less []string
184
+ op string // Either "<" or "!<"
185
+ def []string
186
+ }
187
+
188
+ type syntaxError string
189
+
190
+ func (e syntaxError) Error() string {
191
+ return string(e)
192
+ }
193
+
194
+ // parseRules parses the rules of a DAG.
195
+ func parseRules(rules string) (out []rule, err error) {
196
+ defer func() {
197
+ e := recover()
198
+ switch e := e.(type) {
199
+ case nil:
200
+ return
201
+ case syntaxError:
202
+ err = e
203
+ default:
204
+ panic(e)
205
+ }
206
+ }()
207
+ p := &rulesParser{lineno: 1, text: rules}
208
+
209
+ var prev []string
210
+ var op string
211
+ for {
212
+ list, tok := p.nextList()
213
+ if tok == "" {
214
+ if prev == nil {
215
+ break
216
+ }
217
+ p.syntaxError("unexpected EOF")
218
+ }
219
+ if prev != nil {
220
+ out = append(out, rule{prev, op, list})
221
+ }
222
+ prev = list
223
+ if tok == ";" {
224
+ prev = nil
225
+ op = ""
226
+ continue
227
+ }
228
+ if tok != "<" && tok != "!<" {
229
+ p.syntaxError("missing <")
230
+ }
231
+ op = tok
232
+ }
233
+
234
+ return out, err
235
+ }
236
+
237
+ // A rulesParser parses the depsRules syntax described above.
238
+ type rulesParser struct {
239
+ lineno int
240
+ lastWord string
241
+ text string
242
+ }
243
+
244
+ // syntaxError reports a parsing error.
245
+ func (p *rulesParser) syntaxError(msg string) {
246
+ panic(syntaxError(fmt.Sprintf("parsing graph: line %d: syntax error: %s near %s", p.lineno, msg, p.lastWord)))
247
+ }
248
+
249
+ // nextList parses and returns a comma-separated list of names.
250
+ func (p *rulesParser) nextList() (list []string, token string) {
251
+ for {
252
+ tok := p.nextToken()
253
+ switch tok {
254
+ case "":
255
+ if len(list) == 0 {
256
+ return nil, ""
257
+ }
258
+ fallthrough
259
+ case ",", "<", "!<", ";":
260
+ p.syntaxError("bad list syntax")
261
+ }
262
+ list = append(list, tok)
263
+
264
+ tok = p.nextToken()
265
+ if tok != "," {
266
+ return list, tok
267
+ }
268
+ }
269
+ }
270
+
271
+ // nextToken returns the next token in the deps rules,
272
+ // one of ";" "," "<" "!<" or a name.
273
+ func (p *rulesParser) nextToken() string {
274
+ for {
275
+ if p.text == "" {
276
+ return ""
277
+ }
278
+ switch p.text[0] {
279
+ case ';', ',', '<':
280
+ t := p.text[:1]
281
+ p.text = p.text[1:]
282
+ return t
283
+
284
+ case '!':
285
+ if len(p.text) < 2 || p.text[1] != '<' {
286
+ p.syntaxError("unexpected token !")
287
+ }
288
+ p.text = p.text[2:]
289
+ return "!<"
290
+
291
+ case '#':
292
+ i := strings.Index(p.text, "\n")
293
+ if i < 0 {
294
+ i = len(p.text)
295
+ }
296
+ p.text = p.text[i:]
297
+ continue
298
+
299
+ case '\n':
300
+ p.lineno++
301
+ fallthrough
302
+ case ' ', '\t':
303
+ p.text = p.text[1:]
304
+ continue
305
+
306
+ default:
307
+ i := strings.IndexAny(p.text, "!;,<#\n \t")
308
+ if i < 0 {
309
+ i = len(p.text)
310
+ }
311
+ t := p.text[:i]
312
+ p.text = p.text[i:]
313
+ p.lastWord = t
314
+ return t
315
+ }
316
+ }
317
+ }
go/src/internal/dag/parse_test.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package dag
6
+
7
+ import (
8
+ "slices"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ const diamond = `
14
+ NONE < a < b, c < d;
15
+ `
16
+
17
+ func mustParse(t *testing.T, dag string) *Graph {
18
+ t.Helper()
19
+ g, err := Parse(dag)
20
+ if err != nil {
21
+ t.Fatal(err)
22
+ }
23
+ return g
24
+ }
25
+
26
+ func wantEdges(t *testing.T, g *Graph, edges string) {
27
+ t.Helper()
28
+
29
+ wantEdges := strings.Fields(edges)
30
+ wantEdgeMap := make(map[string]bool)
31
+ for _, e := range wantEdges {
32
+ wantEdgeMap[e] = true
33
+ }
34
+
35
+ for _, n1 := range g.Nodes {
36
+ for _, n2 := range g.Nodes {
37
+ got := g.HasEdge(n1, n2)
38
+ want := wantEdgeMap[n1+"->"+n2]
39
+ if got && want {
40
+ t.Logf("%s->%s", n1, n2)
41
+ } else if got && !want {
42
+ t.Errorf("%s->%s present but not expected", n1, n2)
43
+ } else if want && !got {
44
+ t.Errorf("%s->%s missing but expected", n1, n2)
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ func TestParse(t *testing.T) {
51
+ // Basic smoke test for graph parsing.
52
+ g := mustParse(t, diamond)
53
+
54
+ wantNodes := strings.Fields("a b c d")
55
+ if !slices.Equal(wantNodes, g.Nodes) {
56
+ t.Fatalf("want nodes %v, got %v", wantNodes, g.Nodes)
57
+ }
58
+
59
+ // Parse returns the transitive closure, so it adds d->a.
60
+ wantEdges(t, g, "b->a c->a d->a d->b d->c")
61
+ }
go/src/internal/diff/diff.go ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package diff
6
+
7
+ import (
8
+ "bytes"
9
+ "fmt"
10
+ "sort"
11
+ "strings"
12
+ )
13
+
14
+ // A pair is a pair of values tracked for both the x and y side of a diff.
15
+ // It is typically a pair of line indexes.
16
+ type pair struct{ x, y int }
17
+
18
+ // Diff returns an anchored diff of the two texts old and new
19
+ // in the “unified diff” format. If old and new are identical,
20
+ // Diff returns a nil slice (no output).
21
+ //
22
+ // Unix diff implementations typically look for a diff with
23
+ // the smallest number of lines inserted and removed,
24
+ // which can in the worst case take time quadratic in the
25
+ // number of lines in the texts. As a result, many implementations
26
+ // either can be made to run for a long time or cut off the search
27
+ // after a predetermined amount of work.
28
+ //
29
+ // In contrast, this implementation looks for a diff with the
30
+ // smallest number of “unique” lines inserted and removed,
31
+ // where unique means a line that appears just once in both old and new.
32
+ // We call this an “anchored diff” because the unique lines anchor
33
+ // the chosen matching regions. An anchored diff is usually clearer
34
+ // than a standard diff, because the algorithm does not try to
35
+ // reuse unrelated blank lines or closing braces.
36
+ // The algorithm also guarantees to run in O(n log n) time
37
+ // instead of the standard O(n²) time.
38
+ //
39
+ // Some systems call this approach a “patience diff,” named for
40
+ // the “patience sorting” algorithm, itself named for a solitaire card game.
41
+ // We avoid that name for two reasons. First, the name has been used
42
+ // for a few different variants of the algorithm, so it is imprecise.
43
+ // Second, the name is frequently interpreted as meaning that you have
44
+ // to wait longer (to be patient) for the diff, meaning that it is a slower algorithm,
45
+ // when in fact the algorithm is faster than the standard one.
46
+ func Diff(oldName string, old []byte, newName string, new []byte) []byte {
47
+ if bytes.Equal(old, new) {
48
+ return nil
49
+ }
50
+ x := lines(old)
51
+ y := lines(new)
52
+
53
+ // Print diff header.
54
+ var out bytes.Buffer
55
+ fmt.Fprintf(&out, "diff %s %s\n", oldName, newName)
56
+ fmt.Fprintf(&out, "--- %s\n", oldName)
57
+ fmt.Fprintf(&out, "+++ %s\n", newName)
58
+
59
+ // Loop over matches to consider,
60
+ // expanding each match to include surrounding lines,
61
+ // and then printing diff chunks.
62
+ // To avoid setup/teardown cases outside the loop,
63
+ // tgs returns a leading {0,0} and trailing {len(x), len(y)} pair
64
+ // in the sequence of matches.
65
+ var (
66
+ done pair // printed up to x[:done.x] and y[:done.y]
67
+ chunk pair // start lines of current chunk
68
+ count pair // number of lines from each side in current chunk
69
+ ctext []string // lines for current chunk
70
+ )
71
+ for _, m := range tgs(x, y) {
72
+ if m.x < done.x {
73
+ // Already handled scanning forward from earlier match.
74
+ continue
75
+ }
76
+
77
+ // Expand matching lines as far as possible,
78
+ // establishing that x[start.x:end.x] == y[start.y:end.y].
79
+ // Note that on the first (or last) iteration we may (or definitely do)
80
+ // have an empty match: start.x==end.x and start.y==end.y.
81
+ start := m
82
+ for start.x > done.x && start.y > done.y && x[start.x-1] == y[start.y-1] {
83
+ start.x--
84
+ start.y--
85
+ }
86
+ end := m
87
+ for end.x < len(x) && end.y < len(y) && x[end.x] == y[end.y] {
88
+ end.x++
89
+ end.y++
90
+ }
91
+
92
+ // Emit the mismatched lines before start into this chunk.
93
+ // (No effect on first sentinel iteration, when start = {0,0}.)
94
+ for _, s := range x[done.x:start.x] {
95
+ ctext = append(ctext, "-"+s)
96
+ count.x++
97
+ }
98
+ for _, s := range y[done.y:start.y] {
99
+ ctext = append(ctext, "+"+s)
100
+ count.y++
101
+ }
102
+
103
+ // If we're not at EOF and have too few common lines,
104
+ // the chunk includes all the common lines and continues.
105
+ const C = 3 // number of context lines
106
+ if (end.x < len(x) || end.y < len(y)) &&
107
+ (end.x-start.x < C || (len(ctext) > 0 && end.x-start.x < 2*C)) {
108
+ for _, s := range x[start.x:end.x] {
109
+ ctext = append(ctext, " "+s)
110
+ count.x++
111
+ count.y++
112
+ }
113
+ done = end
114
+ continue
115
+ }
116
+
117
+ // End chunk with common lines for context.
118
+ if len(ctext) > 0 {
119
+ n := end.x - start.x
120
+ if n > C {
121
+ n = C
122
+ }
123
+ for _, s := range x[start.x : start.x+n] {
124
+ ctext = append(ctext, " "+s)
125
+ count.x++
126
+ count.y++
127
+ }
128
+ done = pair{start.x + n, start.y + n}
129
+
130
+ // Format and emit chunk.
131
+ // Convert line numbers to 1-indexed.
132
+ // Special case: empty file shows up as 0,0 not 1,0.
133
+ if count.x > 0 {
134
+ chunk.x++
135
+ }
136
+ if count.y > 0 {
137
+ chunk.y++
138
+ }
139
+ fmt.Fprintf(&out, "@@ -%d,%d +%d,%d @@\n", chunk.x, count.x, chunk.y, count.y)
140
+ for _, s := range ctext {
141
+ out.WriteString(s)
142
+ }
143
+ count.x = 0
144
+ count.y = 0
145
+ ctext = ctext[:0]
146
+ }
147
+
148
+ // If we reached EOF, we're done.
149
+ if end.x >= len(x) && end.y >= len(y) {
150
+ break
151
+ }
152
+
153
+ // Otherwise start a new chunk.
154
+ chunk = pair{end.x - C, end.y - C}
155
+ for _, s := range x[chunk.x:end.x] {
156
+ ctext = append(ctext, " "+s)
157
+ count.x++
158
+ count.y++
159
+ }
160
+ done = end
161
+ }
162
+
163
+ return out.Bytes()
164
+ }
165
+
166
+ // lines returns the lines in the file x, including newlines.
167
+ // If the file does not end in a newline, one is supplied
168
+ // along with a warning about the missing newline.
169
+ func lines(x []byte) []string {
170
+ l := strings.SplitAfter(string(x), "\n")
171
+ if l[len(l)-1] == "" {
172
+ l = l[:len(l)-1]
173
+ } else {
174
+ // Treat last line as having a message about the missing newline attached,
175
+ // using the same text as BSD/GNU diff (including the leading backslash).
176
+ l[len(l)-1] += "\n\\n"
177
+ }
178
+ return l
179
+ }
180
+
181
+ // tgs returns the pairs of indexes of the longest common subsequence
182
+ // of unique lines in x and y, where a unique line is one that appears
183
+ // once in x and once in y.
184
+ //
185
+ // The longest common subsequence algorithm is as described in
186
+ // Thomas G. Szymanski, “A Special Case of the Maximal Common
187
+ // Subsequence Problem,” Princeton TR #170 (January 1975),
188
+ // available at https://research.swtch.com/tgs170.pdf.
189
+ func tgs(x, y []string) []pair {
190
+ // Count the number of times each string appears in a and b.
191
+ // We only care about 0, 1, many, counted as 0, -1, -2
192
+ // for the x side and 0, -4, -8 for the y side.
193
+ // Using negative numbers now lets us distinguish positive line numbers later.
194
+ m := make(map[string]int)
195
+ for _, s := range x {
196
+ if c := m[s]; c > -2 {
197
+ m[s] = c - 1
198
+ }
199
+ }
200
+ for _, s := range y {
201
+ if c := m[s]; c > -8 {
202
+ m[s] = c - 4
203
+ }
204
+ }
205
+
206
+ // Now unique strings can be identified by m[s] = -1+-4.
207
+ //
208
+ // Gather the indexes of those strings in x and y, building:
209
+ // xi[i] = increasing indexes of unique strings in x.
210
+ // yi[i] = increasing indexes of unique strings in y.
211
+ // inv[i] = index j such that x[xi[i]] = y[yi[j]].
212
+ var xi, yi, inv []int
213
+ for i, s := range y {
214
+ if m[s] == -1+-4 {
215
+ m[s] = len(yi)
216
+ yi = append(yi, i)
217
+ }
218
+ }
219
+ for i, s := range x {
220
+ if j, ok := m[s]; ok && j >= 0 {
221
+ xi = append(xi, i)
222
+ inv = append(inv, j)
223
+ }
224
+ }
225
+
226
+ // Apply Algorithm A from Szymanski's paper.
227
+ // In those terms, A = J = inv and B = [0, n).
228
+ // We add sentinel pairs {0,0}, and {len(x),len(y)}
229
+ // to the returned sequence, to help the processing loop.
230
+ J := inv
231
+ n := len(xi)
232
+ T := make([]int, n)
233
+ L := make([]int, n)
234
+ for i := range T {
235
+ T[i] = n + 1
236
+ }
237
+ for i := 0; i < n; i++ {
238
+ k := sort.Search(n, func(k int) bool {
239
+ return T[k] >= J[i]
240
+ })
241
+ T[k] = J[i]
242
+ L[i] = k + 1
243
+ }
244
+ k := 0
245
+ for _, v := range L {
246
+ if k < v {
247
+ k = v
248
+ }
249
+ }
250
+ seq := make([]pair, 2+k)
251
+ seq[1+k] = pair{len(x), len(y)} // sentinel at end
252
+ lastj := n
253
+ for i := n - 1; i >= 0; i-- {
254
+ if L[i] == k && J[i] < lastj {
255
+ seq[k] = pair{xi[i], yi[J[i]]}
256
+ k--
257
+ }
258
+ }
259
+ seq[0] = pair{0, 0} // sentinel at start
260
+ return seq
261
+ }
go/src/internal/diff/diff_test.go ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package diff
6
+
7
+ import (
8
+ "bytes"
9
+ "internal/txtar"
10
+ "path/filepath"
11
+ "testing"
12
+ )
13
+
14
+ func clean(text []byte) []byte {
15
+ text = bytes.ReplaceAll(text, []byte("$\n"), []byte("\n"))
16
+ text = bytes.TrimSuffix(text, []byte("^D\n"))
17
+ return text
18
+ }
19
+
20
+ func Test(t *testing.T) {
21
+ files, _ := filepath.Glob("testdata/*.txt")
22
+ if len(files) == 0 {
23
+ t.Fatalf("no testdata")
24
+ }
25
+
26
+ for _, file := range files {
27
+ t.Run(filepath.Base(file), func(t *testing.T) {
28
+ a, err := txtar.ParseFile(file)
29
+ if err != nil {
30
+ t.Fatal(err)
31
+ }
32
+ if len(a.Files) != 3 || a.Files[2].Name != "diff" {
33
+ t.Fatalf("%s: want three files, third named \"diff\"", file)
34
+ }
35
+ diffs := Diff(a.Files[0].Name, clean(a.Files[0].Data), a.Files[1].Name, clean(a.Files[1].Data))
36
+ want := clean(a.Files[2].Data)
37
+ if !bytes.Equal(diffs, want) {
38
+ t.Fatalf("%s: have:\n%s\nwant:\n%s\n%s", file,
39
+ diffs, want, Diff("have", diffs, "want", want))
40
+ }
41
+ })
42
+ }
43
+ }
go/src/internal/exportdata/exportdata.go ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package exportdata implements common utilities for finding
6
+ // and reading gc-generated object files.
7
+ package exportdata
8
+
9
+ // This file should be kept in sync with src/cmd/compile/internal/gc/obj.go .
10
+
11
+ import (
12
+ "bufio"
13
+ "bytes"
14
+ "errors"
15
+ "fmt"
16
+ "go/build"
17
+ "internal/saferio"
18
+ "io"
19
+ "os"
20
+ "os/exec"
21
+ "path/filepath"
22
+ "strings"
23
+ "sync"
24
+ )
25
+
26
+ // ReadUnified reads the contents of the unified export data from a reader r
27
+ // that contains the contents of a GC-created archive file.
28
+ //
29
+ // On success, the reader will be positioned after the end-of-section marker "\n$$\n".
30
+ //
31
+ // Supported GC-created archive files have 4 layers of nesting:
32
+ // - An archive file containing a package definition file.
33
+ // - The package definition file contains headers followed by a data section.
34
+ // Headers are lines (≤ 4kb) that do not start with "$$".
35
+ // - The data section starts with "$$B\n" followed by export data followed
36
+ // by an end of section marker "\n$$\n". (The section start "$$\n" is no
37
+ // longer supported.)
38
+ // - The export data starts with a format byte ('u') followed by the <data> in
39
+ // the given format. (See ReadExportDataHeader for older formats.)
40
+ //
41
+ // Putting this together, the bytes in a GC-created archive files are expected
42
+ // to look like the following.
43
+ // See cmd/internal/archive for more details on ar file headers.
44
+ //
45
+ // | <!arch>\n | ar file signature
46
+ // | __.PKGDEF...size...\n | ar header for __.PKGDEF including size.
47
+ // | go object <...>\n | objabi header
48
+ // | <optional headers>\n | other headers such as build id
49
+ // | $$B\n | binary format marker
50
+ // | u<data>\n | unified export <data>
51
+ // | $$\n | end-of-section marker
52
+ // | [optional padding] | padding byte (0x0A) if size is odd
53
+ // | [ar file header] | other ar files
54
+ // | [ar file data] |
55
+ func ReadUnified(r *bufio.Reader) (data []byte, err error) {
56
+ // We historically guaranteed headers at the default buffer size (4096) work.
57
+ // This ensures we can use ReadSlice throughout.
58
+ const minBufferSize = 4096
59
+ r = bufio.NewReaderSize(r, minBufferSize)
60
+
61
+ size, err := FindPackageDefinition(r)
62
+ if err != nil {
63
+ return
64
+ }
65
+ n := size
66
+
67
+ objapi, headers, err := ReadObjectHeaders(r)
68
+ if err != nil {
69
+ return
70
+ }
71
+ n -= len(objapi)
72
+ for _, h := range headers {
73
+ n -= len(h)
74
+ }
75
+
76
+ hdrlen, err := ReadExportDataHeader(r)
77
+ if err != nil {
78
+ return
79
+ }
80
+ n -= hdrlen
81
+
82
+ // size also includes the end of section marker. Remove that many bytes from the end.
83
+ const marker = "\n$$\n"
84
+ n -= len(marker)
85
+
86
+ if n < 0 {
87
+ err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", size, n)
88
+ return
89
+ }
90
+
91
+ // Read n bytes from buf.
92
+ data, err = saferio.ReadData(r, uint64(n))
93
+ if err != nil {
94
+ return
95
+ }
96
+
97
+ // Check for marker at the end.
98
+ var suffix [len(marker)]byte
99
+ _, err = io.ReadFull(r, suffix[:])
100
+ if err != nil {
101
+ return
102
+ }
103
+ if s := string(suffix[:]); s != marker {
104
+ err = fmt.Errorf("read %q instead of end-of-section marker (%q)", s, marker)
105
+ return
106
+ }
107
+
108
+ return
109
+ }
110
+
111
+ // FindPackageDefinition positions the reader r at the beginning of a package
112
+ // definition file ("__.PKGDEF") within a GC-created archive by reading
113
+ // from it, and returns the size of the package definition file in the archive.
114
+ //
115
+ // The reader must be positioned at the start of the archive file before calling
116
+ // this function, and "__.PKGDEF" is assumed to be the first file in the archive.
117
+ //
118
+ // See cmd/internal/archive for details on the archive format.
119
+ func FindPackageDefinition(r *bufio.Reader) (size int, err error) {
120
+ // Uses ReadSlice to limit risk of malformed inputs.
121
+
122
+ // Read first line to make sure this is an object file.
123
+ line, err := r.ReadSlice('\n')
124
+ if err != nil {
125
+ err = fmt.Errorf("can't find export data (%v)", err)
126
+ return
127
+ }
128
+
129
+ // Is the first line an archive file signature?
130
+ if string(line) != "!<arch>\n" {
131
+ err = fmt.Errorf("not the start of an archive file (%q)", line)
132
+ return
133
+ }
134
+
135
+ // package export block should be first
136
+ size = readArchiveHeader(r, "__.PKGDEF")
137
+ if size <= 0 {
138
+ err = fmt.Errorf("not a package file")
139
+ return
140
+ }
141
+
142
+ return
143
+ }
144
+
145
+ // ReadObjectHeaders reads object headers from the reader. Object headers are
146
+ // lines that do not start with an end-of-section marker "$$". The first header
147
+ // is the objabi header. On success, the reader will be positioned at the beginning
148
+ // of the end-of-section marker.
149
+ //
150
+ // It returns an error if any header does not fit in r.Size() bytes.
151
+ func ReadObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) {
152
+ // line is a temporary buffer for headers.
153
+ // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs.
154
+ var line []byte
155
+
156
+ // objapi header should be the first line
157
+ if line, err = r.ReadSlice('\n'); err != nil {
158
+ err = fmt.Errorf("can't find export data (%v)", err)
159
+ return
160
+ }
161
+ objapi = string(line)
162
+
163
+ // objapi header begins with "go object ".
164
+ if !strings.HasPrefix(objapi, "go object ") {
165
+ err = fmt.Errorf("not a go object file: %s", objapi)
166
+ return
167
+ }
168
+
169
+ // process remaining object header lines
170
+ for {
171
+ // check for an end of section marker "$$"
172
+ line, err = r.Peek(2)
173
+ if err != nil {
174
+ return
175
+ }
176
+ if string(line) == "$$" {
177
+ return // stop
178
+ }
179
+
180
+ // read next header
181
+ line, err = r.ReadSlice('\n')
182
+ if err != nil {
183
+ return
184
+ }
185
+ headers = append(headers, string(line))
186
+ }
187
+ }
188
+
189
+ // ReadExportDataHeader reads the export data header and format from r.
190
+ // It returns the number of bytes read, or an error if the format is no longer
191
+ // supported or it failed to read.
192
+ //
193
+ // The only currently supported format is binary export data in the
194
+ // unified export format.
195
+ func ReadExportDataHeader(r *bufio.Reader) (n int, err error) {
196
+ // Read export data header.
197
+ line, err := r.ReadSlice('\n')
198
+ if err != nil {
199
+ return
200
+ }
201
+
202
+ hdr := string(line)
203
+ switch hdr {
204
+ case "$$\n":
205
+ err = fmt.Errorf("old textual export format no longer supported (recompile package)")
206
+ return
207
+
208
+ case "$$B\n":
209
+ var format byte
210
+ format, err = r.ReadByte()
211
+ if err != nil {
212
+ return
213
+ }
214
+ // The unified export format starts with a 'u'.
215
+ switch format {
216
+ case 'u':
217
+ default:
218
+ // Older no longer supported export formats include:
219
+ // indexed export format which started with an 'i'; and
220
+ // the older binary export format which started with a 'c',
221
+ // 'd', or 'v' (from "version").
222
+ err = fmt.Errorf("binary export format %q is no longer supported (recompile package)", format)
223
+ return
224
+ }
225
+
226
+ default:
227
+ err = fmt.Errorf("unknown export data header: %q", hdr)
228
+ return
229
+ }
230
+
231
+ n = len(hdr) + 1 // + 1 is for 'u'
232
+ return
233
+ }
234
+
235
+ // FindPkg returns the filename and unique package id for an import
236
+ // path based on package information provided by build.Import (using
237
+ // the build.Default build.Context). A relative srcDir is interpreted
238
+ // relative to the current working directory.
239
+ func FindPkg(path, srcDir string) (filename, id string, err error) {
240
+ if path == "" {
241
+ return "", "", errors.New("path is empty")
242
+ }
243
+
244
+ var noext string
245
+ switch {
246
+ default:
247
+ // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x"
248
+ // Don't require the source files to be present.
249
+ if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282
250
+ srcDir = abs
251
+ }
252
+ var bp *build.Package
253
+ bp, err = build.Import(path, srcDir, build.FindOnly|build.AllowBinary)
254
+ if bp.PkgObj == "" {
255
+ if bp.Goroot && bp.Dir != "" {
256
+ filename, err = lookupGorootExport(bp.Dir)
257
+ if err == nil {
258
+ _, err = os.Stat(filename)
259
+ }
260
+ if err == nil {
261
+ return filename, bp.ImportPath, nil
262
+ }
263
+ }
264
+ goto notfound
265
+ } else {
266
+ noext = strings.TrimSuffix(bp.PkgObj, ".a")
267
+ }
268
+ id = bp.ImportPath
269
+
270
+ case build.IsLocalImport(path):
271
+ // "./x" -> "/this/directory/x.ext", "/this/directory/x"
272
+ noext = filepath.Join(srcDir, path)
273
+ id = noext
274
+
275
+ case filepath.IsAbs(path):
276
+ // for completeness only - go/build.Import
277
+ // does not support absolute imports
278
+ // "/x" -> "/x.ext", "/x"
279
+ noext = path
280
+ id = path
281
+ }
282
+
283
+ if false { // for debugging
284
+ if path != id {
285
+ fmt.Printf("%s -> %s\n", path, id)
286
+ }
287
+ }
288
+
289
+ // try extensions
290
+ for _, ext := range pkgExts {
291
+ filename = noext + ext
292
+ f, statErr := os.Stat(filename)
293
+ if statErr == nil && !f.IsDir() {
294
+ return filename, id, nil
295
+ }
296
+ if err == nil {
297
+ err = statErr
298
+ }
299
+ }
300
+
301
+ notfound:
302
+ if err == nil {
303
+ return "", path, fmt.Errorf("can't find import: %q", path)
304
+ }
305
+ return "", path, fmt.Errorf("can't find import: %q: %w", path, err)
306
+ }
307
+
308
+ var pkgExts = [...]string{".a", ".o"} // a file from the build cache will have no extension
309
+
310
+ var exportMap sync.Map // package dir → func() (string, error)
311
+
312
+ // lookupGorootExport returns the location of the export data
313
+ // (normally found in the build cache, but located in GOROOT/pkg
314
+ // in prior Go releases) for the package located in pkgDir.
315
+ //
316
+ // (We use the package's directory instead of its import path
317
+ // mainly to simplify handling of the packages in src/vendor
318
+ // and cmd/vendor.)
319
+ func lookupGorootExport(pkgDir string) (string, error) {
320
+ f, ok := exportMap.Load(pkgDir)
321
+ if !ok {
322
+ var (
323
+ listOnce sync.Once
324
+ exportPath string
325
+ err error
326
+ )
327
+ f, _ = exportMap.LoadOrStore(pkgDir, func() (string, error) {
328
+ listOnce.Do(func() {
329
+ cmd := exec.Command(filepath.Join(build.Default.GOROOT, "bin", "go"), "list", "-export", "-f", "{{.Export}}", pkgDir)
330
+ cmd.Dir = build.Default.GOROOT
331
+ cmd.Env = append(os.Environ(), "PWD="+cmd.Dir, "GOROOT="+build.Default.GOROOT)
332
+ var output []byte
333
+ output, err = cmd.Output()
334
+ if err != nil {
335
+ if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
336
+ err = errors.New(string(ee.Stderr))
337
+ }
338
+ return
339
+ }
340
+
341
+ exports := strings.Split(string(bytes.TrimSpace(output)), "\n")
342
+ if len(exports) != 1 {
343
+ err = fmt.Errorf("go list reported %d exports; expected 1", len(exports))
344
+ return
345
+ }
346
+
347
+ exportPath = exports[0]
348
+ })
349
+
350
+ return exportPath, err
351
+ })
352
+ }
353
+
354
+ return f.(func() (string, error))()
355
+ }
go/src/internal/exportdata/support.go ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // This file contains support functions for exportdata.
6
+
7
+ package exportdata
8
+
9
+ import (
10
+ "bufio"
11
+ "io"
12
+ "strconv"
13
+ "strings"
14
+ )
15
+
16
+ // Copy of cmd/internal/archive.ReadHeader.
17
+ func readArchiveHeader(b *bufio.Reader, name string) int {
18
+ // architecture-independent object file output
19
+ const HeaderSize = 60
20
+
21
+ var buf [HeaderSize]byte
22
+ if _, err := io.ReadFull(b, buf[:]); err != nil {
23
+ return -1
24
+ }
25
+ aname := strings.Trim(string(buf[0:16]), " ")
26
+ if !strings.HasPrefix(aname, name) {
27
+ return -1
28
+ }
29
+ asize := strings.Trim(string(buf[48:58]), " ")
30
+ i, _ := strconv.Atoi(asize)
31
+ return i
32
+ }
go/src/internal/filepathlite/path.go ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package filepathlite implements a subset of path/filepath,
6
+ // only using packages which may be imported by "os".
7
+ //
8
+ // Tests for these functions are in path/filepath.
9
+ package filepathlite
10
+
11
+ import (
12
+ "errors"
13
+ "internal/stringslite"
14
+ "io/fs"
15
+ "slices"
16
+ )
17
+
18
+ var errInvalidPath = errors.New("invalid path")
19
+
20
+ // A lazybuf is a lazily constructed path buffer.
21
+ // It supports append, reading previously appended bytes,
22
+ // and retrieving the final string. It does not allocate a buffer
23
+ // to hold the output until that output diverges from s.
24
+ type lazybuf struct {
25
+ path string
26
+ buf []byte
27
+ w int
28
+ volAndPath string
29
+ volLen int
30
+ }
31
+
32
+ func (b *lazybuf) index(i int) byte {
33
+ if b.buf != nil {
34
+ return b.buf[i]
35
+ }
36
+ return b.path[i]
37
+ }
38
+
39
+ func (b *lazybuf) append(c byte) {
40
+ if b.buf == nil {
41
+ if b.w < len(b.path) && b.path[b.w] == c {
42
+ b.w++
43
+ return
44
+ }
45
+ b.buf = make([]byte, len(b.path))
46
+ copy(b.buf, b.path[:b.w])
47
+ }
48
+ b.buf[b.w] = c
49
+ b.w++
50
+ }
51
+
52
+ func (b *lazybuf) prepend(prefix ...byte) {
53
+ b.buf = slices.Insert(b.buf, 0, prefix...)
54
+ b.w += len(prefix)
55
+ }
56
+
57
+ func (b *lazybuf) string() string {
58
+ if b.buf == nil {
59
+ return b.volAndPath[:b.volLen+b.w]
60
+ }
61
+ return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
62
+ }
63
+
64
+ // Clean is filepath.Clean.
65
+ func Clean(path string) string {
66
+ originalPath := path
67
+ volLen := volumeNameLen(path)
68
+ path = path[volLen:]
69
+ if path == "" {
70
+ if volLen > 1 && IsPathSeparator(originalPath[0]) && IsPathSeparator(originalPath[1]) {
71
+ // should be UNC
72
+ return FromSlash(originalPath)
73
+ }
74
+ return originalPath + "."
75
+ }
76
+ rooted := IsPathSeparator(path[0])
77
+
78
+ // Invariants:
79
+ // reading from path; r is index of next byte to process.
80
+ // writing to buf; w is index of next byte to write.
81
+ // dotdot is index in buf where .. must stop, either because
82
+ // it is the leading slash or it is a leading ../../.. prefix.
83
+ n := len(path)
84
+ out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
85
+ r, dotdot := 0, 0
86
+ if rooted {
87
+ out.append(Separator)
88
+ r, dotdot = 1, 1
89
+ }
90
+
91
+ for r < n {
92
+ switch {
93
+ case IsPathSeparator(path[r]):
94
+ // empty path element
95
+ r++
96
+ case path[r] == '.' && (r+1 == n || IsPathSeparator(path[r+1])):
97
+ // . element
98
+ r++
99
+ case path[r] == '.' && path[r+1] == '.' && (r+2 == n || IsPathSeparator(path[r+2])):
100
+ // .. element: remove to last separator
101
+ r += 2
102
+ switch {
103
+ case out.w > dotdot:
104
+ // can backtrack
105
+ out.w--
106
+ for out.w > dotdot && !IsPathSeparator(out.index(out.w)) {
107
+ out.w--
108
+ }
109
+ case !rooted:
110
+ // cannot backtrack, but not rooted, so append .. element.
111
+ if out.w > 0 {
112
+ out.append(Separator)
113
+ }
114
+ out.append('.')
115
+ out.append('.')
116
+ dotdot = out.w
117
+ }
118
+ default:
119
+ // real path element.
120
+ // add slash if needed
121
+ if rooted && out.w != 1 || !rooted && out.w != 0 {
122
+ out.append(Separator)
123
+ }
124
+ // copy element
125
+ for ; r < n && !IsPathSeparator(path[r]); r++ {
126
+ out.append(path[r])
127
+ }
128
+ }
129
+ }
130
+
131
+ // Turn empty string into "."
132
+ if out.w == 0 {
133
+ out.append('.')
134
+ }
135
+
136
+ postClean(&out) // avoid creating absolute paths on Windows
137
+ return FromSlash(out.string())
138
+ }
139
+
140
+ // IsLocal is filepath.IsLocal.
141
+ func IsLocal(path string) bool {
142
+ return isLocal(path)
143
+ }
144
+
145
+ func unixIsLocal(path string) bool {
146
+ if IsAbs(path) || path == "" {
147
+ return false
148
+ }
149
+ hasDots := false
150
+ for p := path; p != ""; {
151
+ var part string
152
+ part, p, _ = stringslite.Cut(p, "/")
153
+ if part == "." || part == ".." {
154
+ hasDots = true
155
+ break
156
+ }
157
+ }
158
+ if hasDots {
159
+ path = Clean(path)
160
+ }
161
+ if path == ".." || stringslite.HasPrefix(path, "../") {
162
+ return false
163
+ }
164
+ return true
165
+ }
166
+
167
+ // Localize is filepath.Localize.
168
+ func Localize(path string) (string, error) {
169
+ if !fs.ValidPath(path) {
170
+ return "", errInvalidPath
171
+ }
172
+ return localize(path)
173
+ }
174
+
175
+ // ToSlash is filepath.ToSlash.
176
+ func ToSlash(path string) string {
177
+ if Separator == '/' {
178
+ return path
179
+ }
180
+ return replaceStringByte(path, Separator, '/')
181
+ }
182
+
183
+ // FromSlash is filepath.FromSlash.
184
+ func FromSlash(path string) string {
185
+ if Separator == '/' {
186
+ return path
187
+ }
188
+ return replaceStringByte(path, '/', Separator)
189
+ }
190
+
191
+ func replaceStringByte(s string, old, new byte) string {
192
+ if stringslite.IndexByte(s, old) == -1 {
193
+ return s
194
+ }
195
+ n := []byte(s)
196
+ for i := range n {
197
+ if n[i] == old {
198
+ n[i] = new
199
+ }
200
+ }
201
+ return string(n)
202
+ }
203
+
204
+ // Split is filepath.Split.
205
+ func Split(path string) (dir, file string) {
206
+ vol := VolumeName(path)
207
+ i := len(path) - 1
208
+ for i >= len(vol) && !IsPathSeparator(path[i]) {
209
+ i--
210
+ }
211
+ return path[:i+1], path[i+1:]
212
+ }
213
+
214
+ // Ext is filepath.Ext.
215
+ func Ext(path string) string {
216
+ for i := len(path) - 1; i >= 0 && !IsPathSeparator(path[i]); i-- {
217
+ if path[i] == '.' {
218
+ return path[i:]
219
+ }
220
+ }
221
+ return ""
222
+ }
223
+
224
+ // Base is filepath.Base.
225
+ func Base(path string) string {
226
+ if path == "" {
227
+ return "."
228
+ }
229
+ // Strip trailing slashes.
230
+ for len(path) > 0 && IsPathSeparator(path[len(path)-1]) {
231
+ path = path[0 : len(path)-1]
232
+ }
233
+ // Throw away volume name
234
+ path = path[len(VolumeName(path)):]
235
+ // Find the last element
236
+ i := len(path) - 1
237
+ for i >= 0 && !IsPathSeparator(path[i]) {
238
+ i--
239
+ }
240
+ if i >= 0 {
241
+ path = path[i+1:]
242
+ }
243
+ // If empty now, it had only slashes.
244
+ if path == "" {
245
+ return string(Separator)
246
+ }
247
+ return path
248
+ }
249
+
250
+ // Dir is filepath.Dir.
251
+ func Dir(path string) string {
252
+ vol := VolumeName(path)
253
+ i := len(path) - 1
254
+ for i >= len(vol) && !IsPathSeparator(path[i]) {
255
+ i--
256
+ }
257
+ dir := Clean(path[len(vol) : i+1])
258
+ if dir == "." && len(vol) > 2 {
259
+ // must be UNC
260
+ return vol
261
+ }
262
+ return vol + dir
263
+ }
264
+
265
+ // VolumeName is filepath.VolumeName.
266
+ func VolumeName(path string) string {
267
+ return FromSlash(path[:volumeNameLen(path)])
268
+ }
269
+
270
+ // VolumeNameLen returns the length of the leading volume name on Windows.
271
+ // It returns 0 elsewhere.
272
+ func VolumeNameLen(path string) int {
273
+ return volumeNameLen(path)
274
+ }
go/src/internal/filepathlite/path_nonwindows.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build !windows
6
+
7
+ package filepathlite
8
+
9
+ func postClean(out *lazybuf) {}
go/src/internal/filepathlite/path_plan9.go ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package filepathlite
6
+
7
+ import (
8
+ "internal/bytealg"
9
+ "internal/stringslite"
10
+ )
11
+
12
+ const (
13
+ Separator = '/' // OS-specific path separator
14
+ ListSeparator = '\000' // OS-specific path list separator
15
+ )
16
+
17
+ func IsPathSeparator(c uint8) bool {
18
+ return Separator == c
19
+ }
20
+
21
+ func isLocal(path string) bool {
22
+ return unixIsLocal(path)
23
+ }
24
+
25
+ func localize(path string) (string, error) {
26
+ if path[0] == '#' || bytealg.IndexByteString(path, 0) >= 0 {
27
+ return "", errInvalidPath
28
+ }
29
+ return path, nil
30
+ }
31
+
32
+ // IsAbs reports whether the path is absolute.
33
+ func IsAbs(path string) bool {
34
+ return stringslite.HasPrefix(path, "/") || stringslite.HasPrefix(path, "#")
35
+ }
36
+
37
+ // volumeNameLen returns length of the leading volume name on Windows.
38
+ // It returns 0 elsewhere.
39
+ func volumeNameLen(path string) int {
40
+ return 0
41
+ }
go/src/internal/filepathlite/path_unix.go ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || (js && wasm) || wasip1
6
+
7
+ package filepathlite
8
+
9
+ import (
10
+ "internal/bytealg"
11
+ "internal/stringslite"
12
+ )
13
+
14
+ const (
15
+ Separator = '/' // OS-specific path separator
16
+ ListSeparator = ':' // OS-specific path list separator
17
+ )
18
+
19
+ func IsPathSeparator(c uint8) bool {
20
+ return Separator == c
21
+ }
22
+
23
+ func isLocal(path string) bool {
24
+ return unixIsLocal(path)
25
+ }
26
+
27
+ func localize(path string) (string, error) {
28
+ if bytealg.IndexByteString(path, 0) >= 0 {
29
+ return "", errInvalidPath
30
+ }
31
+ return path, nil
32
+ }
33
+
34
+ // IsAbs reports whether the path is absolute.
35
+ func IsAbs(path string) bool {
36
+ return stringslite.HasPrefix(path, "/")
37
+ }
38
+
39
+ // volumeNameLen returns length of the leading volume name on Windows.
40
+ // It returns 0 elsewhere.
41
+ func volumeNameLen(path string) int {
42
+ return 0
43
+ }
go/src/internal/filepathlite/path_windows.go ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package filepathlite
6
+
7
+ import (
8
+ "internal/bytealg"
9
+ "internal/stringslite"
10
+ "internal/syscall/windows"
11
+ "syscall"
12
+ )
13
+
14
+ const (
15
+ Separator = '\\' // OS-specific path separator
16
+ ListSeparator = ';' // OS-specific path list separator
17
+ )
18
+
19
+ func IsPathSeparator(c uint8) bool {
20
+ return c == '\\' || c == '/'
21
+ }
22
+
23
+ func isLocal(path string) bool {
24
+ if path == "" {
25
+ return false
26
+ }
27
+ if IsPathSeparator(path[0]) {
28
+ // Path rooted in the current drive.
29
+ return false
30
+ }
31
+ if stringslite.IndexByte(path, ':') >= 0 {
32
+ // Colons are only valid when marking a drive letter ("C:foo").
33
+ // Rejecting any path with a colon is conservative but safe.
34
+ return false
35
+ }
36
+ hasDots := false // contains . or .. path elements
37
+ for p := path; p != ""; {
38
+ var part string
39
+ part, p, _ = cutPath(p)
40
+ if part == "." || part == ".." {
41
+ hasDots = true
42
+ }
43
+ if isReservedName(part) {
44
+ return false
45
+ }
46
+ }
47
+ if hasDots {
48
+ path = Clean(path)
49
+ }
50
+ if path == ".." || stringslite.HasPrefix(path, `..\`) {
51
+ return false
52
+ }
53
+ return true
54
+ }
55
+
56
+ func localize(path string) (string, error) {
57
+ for i := 0; i < len(path); i++ {
58
+ switch path[i] {
59
+ case ':', '\\', 0:
60
+ return "", errInvalidPath
61
+ }
62
+ }
63
+ containsSlash := false
64
+ for p := path; p != ""; {
65
+ // Find the next path element.
66
+ var element string
67
+ i := bytealg.IndexByteString(p, '/')
68
+ if i < 0 {
69
+ element = p
70
+ p = ""
71
+ } else {
72
+ containsSlash = true
73
+ element = p[:i]
74
+ p = p[i+1:]
75
+ }
76
+ if isReservedName(element) {
77
+ return "", errInvalidPath
78
+ }
79
+ }
80
+ if containsSlash {
81
+ // We can't depend on strings, so substitute \ for / manually.
82
+ buf := []byte(path)
83
+ for i, b := range buf {
84
+ if b == '/' {
85
+ buf[i] = '\\'
86
+ }
87
+ }
88
+ path = string(buf)
89
+ }
90
+ return path, nil
91
+ }
92
+
93
+ // isReservedName reports if name is a Windows reserved device name.
94
+ // It does not detect names with an extension, which are also reserved on some Windows versions.
95
+ //
96
+ // For details, search for PRN in
97
+ // https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file.
98
+ func isReservedName(name string) bool {
99
+ // Device names can have arbitrary trailing characters following a dot or colon.
100
+ base := name
101
+ for i := 0; i < len(base); i++ {
102
+ switch base[i] {
103
+ case ':', '.':
104
+ base = base[:i]
105
+ }
106
+ }
107
+ // Trailing spaces in the last path element are ignored.
108
+ for len(base) > 0 && base[len(base)-1] == ' ' {
109
+ base = base[:len(base)-1]
110
+ }
111
+ if !isReservedBaseName(base) {
112
+ return false
113
+ }
114
+ if len(base) == len(name) {
115
+ return true
116
+ }
117
+ // The path element is a reserved name with an extension.
118
+ // Since Windows 11, reserved names with extensions are no
119
+ // longer reserved. For example, "CON.txt" is a valid file
120
+ // name. Use RtlIsDosDeviceName_U to see if the name is reserved.
121
+ p, err := syscall.UTF16PtrFromString(name)
122
+ if err != nil {
123
+ return false
124
+ }
125
+ return windows.RtlIsDosDeviceName_U(p) > 0
126
+ }
127
+
128
+ func isReservedBaseName(name string) bool {
129
+ if len(name) == 3 {
130
+ switch string([]byte{toUpper(name[0]), toUpper(name[1]), toUpper(name[2])}) {
131
+ case "CON", "PRN", "AUX", "NUL":
132
+ return true
133
+ }
134
+ }
135
+ if len(name) >= 4 {
136
+ switch string([]byte{toUpper(name[0]), toUpper(name[1]), toUpper(name[2])}) {
137
+ case "COM", "LPT":
138
+ if len(name) == 4 && '1' <= name[3] && name[3] <= '9' {
139
+ return true
140
+ }
141
+ // Superscript ¹, ², and ³ are considered numbers as well.
142
+ switch name[3:] {
143
+ case "\u00b2", "\u00b3", "\u00b9":
144
+ return true
145
+ }
146
+ return false
147
+ }
148
+ }
149
+
150
+ // Passing CONIN$ or CONOUT$ to CreateFile opens a console handle.
151
+ // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#consoles
152
+ //
153
+ // While CONIN$ and CONOUT$ aren't documented as being files,
154
+ // they behave the same as CON. For example, ./CONIN$ also opens the console input.
155
+ if len(name) == 6 && name[5] == '$' && equalFold(name, "CONIN$") {
156
+ return true
157
+ }
158
+ if len(name) == 7 && name[6] == '$' && equalFold(name, "CONOUT$") {
159
+ return true
160
+ }
161
+ return false
162
+ }
163
+
164
+ func equalFold(a, b string) bool {
165
+ if len(a) != len(b) {
166
+ return false
167
+ }
168
+ for i := 0; i < len(a); i++ {
169
+ if toUpper(a[i]) != toUpper(b[i]) {
170
+ return false
171
+ }
172
+ }
173
+ return true
174
+ }
175
+
176
+ func toUpper(c byte) byte {
177
+ if 'a' <= c && c <= 'z' {
178
+ return c - ('a' - 'A')
179
+ }
180
+ return c
181
+ }
182
+
183
+ // IsAbs reports whether the path is absolute.
184
+ func IsAbs(path string) (b bool) {
185
+ l := volumeNameLen(path)
186
+ if l == 0 {
187
+ return false
188
+ }
189
+ // If the volume name starts with a double slash, this is an absolute path.
190
+ if IsPathSeparator(path[0]) && IsPathSeparator(path[1]) {
191
+ return true
192
+ }
193
+ path = path[l:]
194
+ if path == "" {
195
+ return false
196
+ }
197
+ return IsPathSeparator(path[0])
198
+ }
199
+
200
+ // volumeNameLen returns length of the leading volume name on Windows.
201
+ // It returns 0 elsewhere.
202
+ //
203
+ // See:
204
+ // https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats
205
+ // https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html
206
+ func volumeNameLen(path string) int {
207
+ switch {
208
+ case len(path) >= 2 && path[1] == ':':
209
+ // Path starts with a drive letter.
210
+ //
211
+ // Not all Windows functions necessarily enforce the requirement that
212
+ // drive letters be in the set A-Z, and we don't try to here.
213
+ //
214
+ // We don't handle the case of a path starting with a non-ASCII character,
215
+ // in which case the "drive letter" might be multiple bytes long.
216
+ return 2
217
+
218
+ case len(path) == 0 || !IsPathSeparator(path[0]):
219
+ // Path does not have a volume component.
220
+ return 0
221
+
222
+ case pathHasPrefixFold(path, `\\.\UNC`):
223
+ // We're going to treat the UNC host and share as part of the volume
224
+ // prefix for historical reasons, but this isn't really principled;
225
+ // Windows's own GetFullPathName will happily remove the first
226
+ // component of the path in this space, converting
227
+ // \\.\unc\a\b\..\c into \\.\unc\a\c.
228
+ return uncLen(path, len(`\\.\UNC\`))
229
+
230
+ case pathHasPrefixFold(path, `\\.`) ||
231
+ pathHasPrefixFold(path, `\\?`) || pathHasPrefixFold(path, `\??`):
232
+ // Path starts with \\.\, and is a Local Device path; or
233
+ // path starts with \\?\ or \??\ and is a Root Local Device path.
234
+ //
235
+ // We treat the next component after the \\.\ prefix as
236
+ // part of the volume name, which means Clean(`\\?\c:\`)
237
+ // won't remove the trailing \. (See #64028.)
238
+ if len(path) == 3 {
239
+ return 3 // exactly \\.
240
+ }
241
+ _, rest, ok := cutPath(path[4:])
242
+ if !ok {
243
+ return len(path)
244
+ }
245
+ return len(path) - len(rest) - 1
246
+
247
+ case len(path) >= 2 && IsPathSeparator(path[1]):
248
+ // Path starts with \\, and is a UNC path.
249
+ return uncLen(path, 2)
250
+ }
251
+ return 0
252
+ }
253
+
254
+ // pathHasPrefixFold tests whether the path s begins with prefix,
255
+ // ignoring case and treating all path separators as equivalent.
256
+ // If s is longer than prefix, then s[len(prefix)] must be a path separator.
257
+ func pathHasPrefixFold(s, prefix string) bool {
258
+ if len(s) < len(prefix) {
259
+ return false
260
+ }
261
+ for i := 0; i < len(prefix); i++ {
262
+ if IsPathSeparator(prefix[i]) {
263
+ if !IsPathSeparator(s[i]) {
264
+ return false
265
+ }
266
+ } else if toUpper(prefix[i]) != toUpper(s[i]) {
267
+ return false
268
+ }
269
+ }
270
+ if len(s) > len(prefix) && !IsPathSeparator(s[len(prefix)]) {
271
+ return false
272
+ }
273
+ return true
274
+ }
275
+
276
+ // uncLen returns the length of the volume prefix of a UNC path.
277
+ // prefixLen is the prefix prior to the start of the UNC host;
278
+ // for example, for "//host/share", the prefixLen is len("//")==2.
279
+ func uncLen(path string, prefixLen int) int {
280
+ count := 0
281
+ for i := prefixLen; i < len(path); i++ {
282
+ if IsPathSeparator(path[i]) {
283
+ count++
284
+ if count == 2 {
285
+ return i
286
+ }
287
+ }
288
+ }
289
+ return len(path)
290
+ }
291
+
292
+ // cutPath slices path around the first path separator.
293
+ func cutPath(path string) (before, after string, found bool) {
294
+ for i := range path {
295
+ if IsPathSeparator(path[i]) {
296
+ return path[:i], path[i+1:], true
297
+ }
298
+ }
299
+ return path, "", false
300
+ }
301
+
302
+ // postClean adjusts the results of Clean to avoid turning a relative path
303
+ // into an absolute or rooted one.
304
+ func postClean(out *lazybuf) {
305
+ if out.volLen != 0 || out.buf == nil {
306
+ return
307
+ }
308
+ // If a ':' appears in the path element at the start of a path,
309
+ // insert a .\ at the beginning to avoid converting relative paths
310
+ // like a/../c: into c:.
311
+ for _, c := range out.buf {
312
+ if IsPathSeparator(c) {
313
+ break
314
+ }
315
+ if c == ':' {
316
+ out.prepend('.', Separator)
317
+ return
318
+ }
319
+ }
320
+ // If a path begins with \??\, insert a \. at the beginning
321
+ // to avoid converting paths like \a\..\??\c:\x into \??\c:\x
322
+ // (equivalent to c:\x).
323
+ if len(out.buf) >= 3 && IsPathSeparator(out.buf[0]) && out.buf[1] == '?' && out.buf[2] == '?' {
324
+ out.prepend(Separator, '.')
325
+ }
326
+ }
go/src/internal/fmtsort/export_test.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package fmtsort
6
+
7
+ import "reflect"
8
+
9
+ func Compare(a, b reflect.Value) int {
10
+ return compare(a, b)
11
+ }
go/src/internal/fmtsort/sort.go ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package fmtsort provides a general stable ordering mechanism
6
+ // for maps, on behalf of the fmt and text/template packages.
7
+ // It is not guaranteed to be efficient and works only for types
8
+ // that are valid map keys.
9
+ package fmtsort
10
+
11
+ import (
12
+ "cmp"
13
+ "reflect"
14
+ "slices"
15
+ )
16
+
17
+ // Note: Throughout this package we avoid calling reflect.Value.Interface as
18
+ // it is not always legal to do so and it's easier to avoid the issue than to face it.
19
+
20
+ // SortedMap is a slice of KeyValue pairs that simplifies sorting
21
+ // and iterating over map entries.
22
+ //
23
+ // Each KeyValue pair contains a map key and its corresponding value.
24
+ type SortedMap []KeyValue
25
+
26
+ // KeyValue holds a single key and value pair found in a map.
27
+ type KeyValue struct {
28
+ Key, Value reflect.Value
29
+ }
30
+
31
+ // Sort accepts a map and returns a SortedMap that has the same keys and
32
+ // values but in a stable sorted order according to the keys, modulo issues
33
+ // raised by unorderable key values such as NaNs.
34
+ //
35
+ // The ordering rules are more general than with Go's < operator:
36
+ //
37
+ // - when applicable, nil compares low
38
+ // - ints, floats, and strings order by <
39
+ // - NaN compares less than non-NaN floats
40
+ // - bool compares false before true
41
+ // - complex compares real, then imag
42
+ // - pointers compare by machine address
43
+ // - channel values compare by machine address
44
+ // - structs compare each field in turn
45
+ // - arrays compare each element in turn.
46
+ // Otherwise identical arrays compare by length.
47
+ // - interface values compare first by reflect.Type describing the concrete type
48
+ // and then by concrete value as described in the previous rules.
49
+ func Sort(mapValue reflect.Value) SortedMap {
50
+ if mapValue.Type().Kind() != reflect.Map {
51
+ return nil
52
+ }
53
+ // Note: this code is arranged to not panic even in the presence
54
+ // of a concurrent map update. The runtime is responsible for
55
+ // yelling loudly if that happens. See issue 33275.
56
+ n := mapValue.Len()
57
+ sorted := make(SortedMap, 0, n)
58
+ iter := mapValue.MapRange()
59
+ for iter.Next() {
60
+ sorted = append(sorted, KeyValue{iter.Key(), iter.Value()})
61
+ }
62
+ slices.SortStableFunc(sorted, func(a, b KeyValue) int {
63
+ return compare(a.Key, b.Key)
64
+ })
65
+ return sorted
66
+ }
67
+
68
+ // compare compares two values of the same type. It returns -1, 0, 1
69
+ // according to whether a > b (1), a == b (0), or a < b (-1).
70
+ // If the types differ, it returns -1.
71
+ // See the comment on Sort for the comparison rules.
72
+ func compare(aVal, bVal reflect.Value) int {
73
+ aType, bType := aVal.Type(), bVal.Type()
74
+ if aType != bType {
75
+ return -1 // No good answer possible, but don't return 0: they're not equal.
76
+ }
77
+ switch aVal.Kind() {
78
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
79
+ return cmp.Compare(aVal.Int(), bVal.Int())
80
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
81
+ return cmp.Compare(aVal.Uint(), bVal.Uint())
82
+ case reflect.String:
83
+ return cmp.Compare(aVal.String(), bVal.String())
84
+ case reflect.Float32, reflect.Float64:
85
+ return cmp.Compare(aVal.Float(), bVal.Float())
86
+ case reflect.Complex64, reflect.Complex128:
87
+ a, b := aVal.Complex(), bVal.Complex()
88
+ if c := cmp.Compare(real(a), real(b)); c != 0 {
89
+ return c
90
+ }
91
+ return cmp.Compare(imag(a), imag(b))
92
+ case reflect.Bool:
93
+ a, b := aVal.Bool(), bVal.Bool()
94
+ switch {
95
+ case a == b:
96
+ return 0
97
+ case a:
98
+ return 1
99
+ default:
100
+ return -1
101
+ }
102
+ case reflect.Pointer, reflect.UnsafePointer:
103
+ return cmp.Compare(aVal.Pointer(), bVal.Pointer())
104
+ case reflect.Chan:
105
+ if c, ok := nilCompare(aVal, bVal); ok {
106
+ return c
107
+ }
108
+ return cmp.Compare(aVal.Pointer(), bVal.Pointer())
109
+ case reflect.Struct:
110
+ for i := 0; i < aVal.NumField(); i++ {
111
+ if c := compare(aVal.Field(i), bVal.Field(i)); c != 0 {
112
+ return c
113
+ }
114
+ }
115
+ return 0
116
+ case reflect.Array:
117
+ for i := 0; i < aVal.Len(); i++ {
118
+ if c := compare(aVal.Index(i), bVal.Index(i)); c != 0 {
119
+ return c
120
+ }
121
+ }
122
+ return 0
123
+ case reflect.Interface:
124
+ if c, ok := nilCompare(aVal, bVal); ok {
125
+ return c
126
+ }
127
+ c := compare(reflect.ValueOf(aVal.Elem().Type()), reflect.ValueOf(bVal.Elem().Type()))
128
+ if c != 0 {
129
+ return c
130
+ }
131
+ return compare(aVal.Elem(), bVal.Elem())
132
+ default:
133
+ // Certain types cannot appear as keys (maps, funcs, slices), but be explicit.
134
+ panic("bad type in compare: " + aType.String())
135
+ }
136
+ }
137
+
138
+ // nilCompare checks whether either value is nil. If not, the boolean is false.
139
+ // If either value is nil, the boolean is true and the integer is the comparison
140
+ // value. The comparison is defined to be 0 if both are nil, otherwise the one
141
+ // nil value compares low. Both arguments must represent a chan, func,
142
+ // interface, map, pointer, or slice.
143
+ func nilCompare(aVal, bVal reflect.Value) (int, bool) {
144
+ if aVal.IsNil() {
145
+ if bVal.IsNil() {
146
+ return 0, true
147
+ }
148
+ return -1, true
149
+ }
150
+ if bVal.IsNil() {
151
+ return 1, true
152
+ }
153
+ return 0, false
154
+ }
go/src/internal/fmtsort/sort_test.go ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package fmtsort_test
6
+
7
+ import (
8
+ "cmp"
9
+ "fmt"
10
+ "internal/fmtsort"
11
+ "math"
12
+ "reflect"
13
+ "runtime"
14
+ "slices"
15
+ "strings"
16
+ "testing"
17
+ "unsafe"
18
+ )
19
+
20
+ var compareTests = [][]reflect.Value{
21
+ ct(reflect.TypeOf(int(0)), -1, 0, 1),
22
+ ct(reflect.TypeOf(int8(0)), -1, 0, 1),
23
+ ct(reflect.TypeOf(int16(0)), -1, 0, 1),
24
+ ct(reflect.TypeOf(int32(0)), -1, 0, 1),
25
+ ct(reflect.TypeOf(int64(0)), -1, 0, 1),
26
+ ct(reflect.TypeOf(uint(0)), 0, 1, 5),
27
+ ct(reflect.TypeOf(uint8(0)), 0, 1, 5),
28
+ ct(reflect.TypeOf(uint16(0)), 0, 1, 5),
29
+ ct(reflect.TypeOf(uint32(0)), 0, 1, 5),
30
+ ct(reflect.TypeOf(uint64(0)), 0, 1, 5),
31
+ ct(reflect.TypeOf(uintptr(0)), 0, 1, 5),
32
+ ct(reflect.TypeOf(string("")), "", "a", "ab"),
33
+ ct(reflect.TypeOf(float32(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)),
34
+ ct(reflect.TypeOf(float64(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)),
35
+ ct(reflect.TypeOf(complex64(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i),
36
+ ct(reflect.TypeOf(complex128(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i),
37
+ ct(reflect.TypeOf(false), false, true),
38
+ ct(reflect.TypeOf(&ints[0]), &ints[0], &ints[1], &ints[2]),
39
+ ct(reflect.TypeOf(unsafe.Pointer(&ints[0])), unsafe.Pointer(&ints[0]), unsafe.Pointer(&ints[1]), unsafe.Pointer(&ints[2])),
40
+ ct(reflect.TypeOf(chans[0]), chans[0], chans[1], chans[2]),
41
+ ct(reflect.TypeOf(toy{}), toy{0, 1}, toy{0, 2}, toy{1, -1}, toy{1, 1}),
42
+ ct(reflect.TypeOf([2]int{}), [2]int{1, 1}, [2]int{1, 2}, [2]int{2, 0}),
43
+ ct(reflect.TypeOf(any(0)), iFace, 1, 2, 3),
44
+ }
45
+
46
+ var iFace any
47
+
48
+ func ct(typ reflect.Type, args ...any) []reflect.Value {
49
+ value := make([]reflect.Value, len(args))
50
+ for i, v := range args {
51
+ x := reflect.ValueOf(v)
52
+ if !x.IsValid() { // Make it a typed nil.
53
+ x = reflect.Zero(typ)
54
+ } else {
55
+ x = x.Convert(typ)
56
+ }
57
+ value[i] = x
58
+ }
59
+ return value
60
+ }
61
+
62
+ func TestCompare(t *testing.T) {
63
+ for _, test := range compareTests {
64
+ for i, v0 := range test {
65
+ for j, v1 := range test {
66
+ c := fmtsort.Compare(v0, v1)
67
+ var expect int
68
+ switch {
69
+ case i == j:
70
+ expect = 0
71
+ case i < j:
72
+ expect = -1
73
+ case i > j:
74
+ expect = 1
75
+ }
76
+ if c != expect {
77
+ t.Errorf("%s: compare(%v,%v)=%d; expect %d", v0.Type(), v0, v1, c, expect)
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ type sortTest struct {
85
+ data any // Always a map.
86
+ print string // Printed result using our custom printer.
87
+ }
88
+
89
+ var sortTests = []sortTest{
90
+ {
91
+ map[int]string{7: "bar", -3: "foo"},
92
+ "-3:foo 7:bar",
93
+ },
94
+ {
95
+ map[uint8]string{7: "bar", 3: "foo"},
96
+ "3:foo 7:bar",
97
+ },
98
+ {
99
+ map[string]string{"7": "bar", "3": "foo"},
100
+ "3:foo 7:bar",
101
+ },
102
+ {
103
+ map[float64]string{7: "bar", -3: "foo", math.NaN(): "nan", math.Inf(0): "inf"},
104
+ "NaN:nan -3:foo 7:bar +Inf:inf",
105
+ },
106
+ {
107
+ map[complex128]string{7 + 2i: "bar2", 7 + 1i: "bar", -3: "foo", complex(math.NaN(), 0i): "nan", complex(math.Inf(0), 0i): "inf"},
108
+ "(NaN+0i):nan (-3+0i):foo (7+1i):bar (7+2i):bar2 (+Inf+0i):inf",
109
+ },
110
+ {
111
+ map[bool]string{true: "true", false: "false"},
112
+ "false:false true:true",
113
+ },
114
+ {
115
+ chanMap(),
116
+ "CHAN0:0 CHAN1:1 CHAN2:2",
117
+ },
118
+ {
119
+ pointerMap(),
120
+ "PTR0:0 PTR1:1 PTR2:2",
121
+ },
122
+ {
123
+ unsafePointerMap(),
124
+ "UNSAFEPTR0:0 UNSAFEPTR1:1 UNSAFEPTR2:2",
125
+ },
126
+ {
127
+ map[toy]string{{7, 2}: "72", {7, 1}: "71", {3, 4}: "34"},
128
+ "{3 4}:34 {7 1}:71 {7 2}:72",
129
+ },
130
+ {
131
+ map[[2]int]string{{7, 2}: "72", {7, 1}: "71", {3, 4}: "34"},
132
+ "[3 4]:34 [7 1]:71 [7 2]:72",
133
+ },
134
+ }
135
+
136
+ func sprint(data any) string {
137
+ om := fmtsort.Sort(reflect.ValueOf(data))
138
+ if om == nil {
139
+ return "nil"
140
+ }
141
+ b := new(strings.Builder)
142
+ for i, m := range om {
143
+ if i > 0 {
144
+ b.WriteRune(' ')
145
+ }
146
+ b.WriteString(sprintKey(m.Key))
147
+ b.WriteRune(':')
148
+ fmt.Fprint(b, m.Value)
149
+ }
150
+ return b.String()
151
+ }
152
+
153
+ // sprintKey formats a reflect.Value but gives reproducible values for some
154
+ // problematic types such as pointers. Note that it only does special handling
155
+ // for the troublesome types used in the test cases; it is not a general
156
+ // printer.
157
+ func sprintKey(key reflect.Value) string {
158
+ switch str := key.Type().String(); str {
159
+ case "*int":
160
+ ptr := key.Interface().(*int)
161
+ for i := range ints {
162
+ if ptr == &ints[i] {
163
+ return fmt.Sprintf("PTR%d", i)
164
+ }
165
+ }
166
+ return "PTR???"
167
+ case "unsafe.Pointer":
168
+ ptr := key.Interface().(unsafe.Pointer)
169
+ for i := range ints {
170
+ if ptr == unsafe.Pointer(&ints[i]) {
171
+ return fmt.Sprintf("UNSAFEPTR%d", i)
172
+ }
173
+ }
174
+ return "UNSAFEPTR???"
175
+ case "chan int":
176
+ c := key.Interface().(chan int)
177
+ for i := range chans {
178
+ if c == chans[i] {
179
+ return fmt.Sprintf("CHAN%d", i)
180
+ }
181
+ }
182
+ return "CHAN???"
183
+ default:
184
+ return fmt.Sprint(key)
185
+ }
186
+ }
187
+
188
+ var (
189
+ ints [3]int
190
+ chans = makeChans()
191
+ pin runtime.Pinner
192
+ )
193
+
194
+ func makeChans() []chan int {
195
+ cs := []chan int{make(chan int), make(chan int), make(chan int)}
196
+ // Order channels by address. See issue #49431.
197
+ for i := range cs {
198
+ pin.Pin(reflect.ValueOf(cs[i]).UnsafePointer())
199
+ }
200
+ slices.SortFunc(cs, func(a, b chan int) int {
201
+ return cmp.Compare(reflect.ValueOf(a).Pointer(), reflect.ValueOf(b).Pointer())
202
+ })
203
+ return cs
204
+ }
205
+
206
+ func pointerMap() map[*int]string {
207
+ m := make(map[*int]string)
208
+ for i := 2; i >= 0; i-- {
209
+ m[&ints[i]] = fmt.Sprint(i)
210
+ }
211
+ return m
212
+ }
213
+
214
+ func unsafePointerMap() map[unsafe.Pointer]string {
215
+ m := make(map[unsafe.Pointer]string)
216
+ for i := 2; i >= 0; i-- {
217
+ m[unsafe.Pointer(&ints[i])] = fmt.Sprint(i)
218
+ }
219
+ return m
220
+ }
221
+
222
+ func chanMap() map[chan int]string {
223
+ m := make(map[chan int]string)
224
+ for i := 2; i >= 0; i-- {
225
+ m[chans[i]] = fmt.Sprint(i)
226
+ }
227
+ return m
228
+ }
229
+
230
+ type toy struct {
231
+ A int // Exported.
232
+ b int // Unexported.
233
+ }
234
+
235
+ func TestOrder(t *testing.T) {
236
+ for _, test := range sortTests {
237
+ got := sprint(test.data)
238
+ if got != test.print {
239
+ t.Errorf("%s: got %q, want %q", reflect.TypeOf(test.data), got, test.print)
240
+ }
241
+ }
242
+ }
243
+
244
+ func TestInterface(t *testing.T) {
245
+ // A map containing multiple concrete types should be sorted by type,
246
+ // then value. However, the relative ordering of types is unspecified,
247
+ // so test this by checking the presence of sorted subgroups.
248
+ m := map[any]string{
249
+ [2]int{1, 0}: "",
250
+ [2]int{0, 1}: "",
251
+ true: "",
252
+ false: "",
253
+ 3.1: "",
254
+ 2.1: "",
255
+ 1.1: "",
256
+ math.NaN(): "",
257
+ 3: "",
258
+ 2: "",
259
+ 1: "",
260
+ "c": "",
261
+ "b": "",
262
+ "a": "",
263
+ struct{ x, y int }{1, 0}: "",
264
+ struct{ x, y int }{0, 1}: "",
265
+ }
266
+ got := sprint(m)
267
+ typeGroups := []string{
268
+ "NaN: 1.1: 2.1: 3.1:", // float64
269
+ "false: true:", // bool
270
+ "1: 2: 3:", // int
271
+ "a: b: c:", // string
272
+ "[0 1]: [1 0]:", // [2]int
273
+ "{0 1}: {1 0}:", // struct{ x int; y int }
274
+ }
275
+ for _, g := range typeGroups {
276
+ if !strings.Contains(got, g) {
277
+ t.Errorf("sorted map should contain %q", g)
278
+ }
279
+ }
280
+ }
go/src/internal/fuzz/counters_supported.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build (darwin || linux || windows || freebsd || openbsd) && (amd64 || arm64 || loong64)
6
+
7
+ package fuzz
8
+
9
+ import (
10
+ "unsafe"
11
+ )
12
+
13
+ // coverage returns a []byte containing unique 8-bit counters for each edge of
14
+ // the instrumented source code. This coverage data will only be generated if
15
+ // `-d=libfuzzer` is set at build time. This can be used to understand the code
16
+ // coverage of a test execution.
17
+ func coverage() []byte {
18
+ addr := unsafe.Pointer(&_counters)
19
+ size := uintptr(unsafe.Pointer(&_ecounters)) - uintptr(addr)
20
+ return unsafe.Slice((*byte)(addr), int(size))
21
+ }
go/src/internal/fuzz/counters_unsupported.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // TODO: expand the set of supported platforms, with testing. Nothing about
6
+ // the instrumentation is OS specific, but only amd64 and arm64 are
7
+ // supported in the runtime. See src/runtime/libfuzzer*.
8
+ //
9
+ // If you update this constraint, also update internal/platform.FuzzInstrumented.
10
+ //
11
+ //go:build !((darwin || linux || windows || freebsd || openbsd) && (amd64 || arm64 || loong64))
12
+
13
+ package fuzz
14
+
15
+ // TODO(#48504): re-enable on platforms where instrumentation works.
16
+ // In theory, we shouldn't need this file at all: if the binary was built
17
+ // without coverage, then _counters and _ecounters should have the same address.
18
+ // However, this caused an init failure on aix/ppc64, so it's disabled here.
19
+
20
+ // coverage returns a []byte containing unique 8-bit counters for each edge of
21
+ // the instrumented source code. This coverage data will only be generated if
22
+ // `-d=libfuzzer` is set at build time. This can be used to understand the code
23
+ // coverage of a test execution.
24
+ func coverage() []byte { return nil }