Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- go/src/reflect/float32reg_generic.go +23 -0
- go/src/reflect/float32reg_ppc64x.s +30 -0
- go/src/reflect/float32reg_riscv64.s +27 -0
- go/src/reflect/float32reg_s390x.s +30 -0
- go/src/reflect/iter.go +173 -0
- go/src/reflect/iter_test.go +412 -0
- go/src/reflect/makefunc.go +182 -0
- go/src/reflect/map.go +449 -0
- go/src/reflect/map_test.go +23 -0
- go/src/reflect/nih_test.go +38 -0
- go/src/reflect/set_test.go +227 -0
- go/src/reflect/stubs_ppc64x.go +10 -0
- go/src/reflect/stubs_riscv64.go +8 -0
- go/src/reflect/stubs_s390x.go +10 -0
- go/src/reflect/swapper.go +79 -0
- go/src/reflect/tostring_test.go +95 -0
- go/src/reflect/type.go +2939 -0
- go/src/reflect/type_test.go +173 -0
- go/src/reflect/value.go +0 -0
- go/src/reflect/visiblefields.go +105 -0
- go/src/reflect/visiblefields_test.go +348 -0
- go/src/regexp/all_test.go +991 -0
- go/src/regexp/backtrack.go +365 -0
- go/src/regexp/example_test.go +447 -0
- go/src/regexp/exec.go +554 -0
- go/src/regexp/exec2_test.go +20 -0
- go/src/regexp/exec_test.go +736 -0
- go/src/regexp/find_test.go +520 -0
- go/src/regexp/onepass.go +508 -0
- go/src/regexp/onepass_test.go +227 -0
- go/src/regexp/regexp.go +1287 -0
- go/src/runtime/HACKING.md +544 -0
- go/src/runtime/Makefile +5 -0
- go/src/runtime/abi_test.go +118 -0
- go/src/runtime/alg.go +434 -0
- go/src/runtime/align_runtime_test.go +49 -0
- go/src/runtime/align_test.go +200 -0
- go/src/runtime/arena.go +1130 -0
- go/src/runtime/arena_test.go +541 -0
- go/src/runtime/asan.go +82 -0
- go/src/runtime/asan0.go +27 -0
- go/src/runtime/asan_amd64.s +118 -0
- go/src/runtime/asan_arm64.s +104 -0
- go/src/runtime/asan_loong64.s +102 -0
- go/src/runtime/asan_ppc64le.s +117 -0
- go/src/runtime/asan_riscv64.s +95 -0
- go/src/runtime/asm.s +15 -0
- go/src/runtime/asm_386.s +1565 -0
- go/src/runtime/asm_amd64.h +28 -0
- go/src/runtime/asm_amd64.s +2175 -0
go/src/reflect/float32reg_generic.go
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 !ppc64 && !ppc64le && !riscv64 && !s390x
|
| 6 |
+
|
| 7 |
+
package reflect
|
| 8 |
+
|
| 9 |
+
import "unsafe"
|
| 10 |
+
|
| 11 |
+
// This file implements a straightforward conversion of a float32
|
| 12 |
+
// value into its representation in a register. This conversion
|
| 13 |
+
// applies for amd64 and arm64. It is also chosen for the case of
|
| 14 |
+
// zero argument registers, but is not used.
|
| 15 |
+
|
| 16 |
+
func archFloat32FromReg(reg uint64) float32 {
|
| 17 |
+
i := uint32(reg)
|
| 18 |
+
return *(*float32)(unsafe.Pointer(&i))
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func archFloat32ToReg(val float32) uint64 {
|
| 22 |
+
return uint64(*(*uint32)(unsafe.Pointer(&val)))
|
| 23 |
+
}
|
go/src/reflect/float32reg_ppc64x.s
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ppc64 || ppc64le
|
| 6 |
+
|
| 7 |
+
#include "textflag.h"
|
| 8 |
+
|
| 9 |
+
// On PPC64, the float32 becomes a float64
|
| 10 |
+
// when loaded in a register, different from
|
| 11 |
+
// other platforms. These functions are
|
| 12 |
+
// needed to ensure correct conversions on PPC64.
|
| 13 |
+
|
| 14 |
+
// Convert float32->uint64
|
| 15 |
+
TEXT ·archFloat32ToReg(SB),NOSPLIT,$0-16
|
| 16 |
+
FMOVS val+0(FP), F1
|
| 17 |
+
FMOVD F1, ret+8(FP)
|
| 18 |
+
RET
|
| 19 |
+
|
| 20 |
+
// Convert uint64->float32
|
| 21 |
+
TEXT ·archFloat32FromReg(SB),NOSPLIT,$0-12
|
| 22 |
+
FMOVD reg+0(FP), F1
|
| 23 |
+
// Normally a float64->float32 conversion
|
| 24 |
+
// would need rounding, but that is not needed
|
| 25 |
+
// here since the uint64 was originally converted
|
| 26 |
+
// from float32, and should be avoided to
|
| 27 |
+
// preserve SNaN values.
|
| 28 |
+
FMOVS F1, ret+8(FP)
|
| 29 |
+
RET
|
| 30 |
+
|
go/src/reflect/float32reg_riscv64.s
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
#include "textflag.h"
|
| 6 |
+
|
| 7 |
+
// riscv64 allows 32-bit floats to live in the bottom
|
| 8 |
+
// part of the register, it expects them to be NaN-boxed.
|
| 9 |
+
// These functions are needed to ensure correct conversions
|
| 10 |
+
// on riscv64.
|
| 11 |
+
|
| 12 |
+
// Convert float32->uint64
|
| 13 |
+
TEXT ·archFloat32ToReg(SB),NOSPLIT,$0-16
|
| 14 |
+
MOVF val+0(FP), F1
|
| 15 |
+
MOVD F1, ret+8(FP)
|
| 16 |
+
RET
|
| 17 |
+
|
| 18 |
+
// Convert uint64->float32
|
| 19 |
+
TEXT ·archFloat32FromReg(SB),NOSPLIT,$0-12
|
| 20 |
+
// Normally a float64->float32 conversion
|
| 21 |
+
// would need rounding, but riscv64 store valid
|
| 22 |
+
// float32 in the lower 32 bits, thus we only need to
|
| 23 |
+
// unboxed the NaN-box by store a float32.
|
| 24 |
+
MOVD reg+0(FP), F1
|
| 25 |
+
MOVF F1, ret+8(FP)
|
| 26 |
+
RET
|
| 27 |
+
|
go/src/reflect/float32reg_s390x.s
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 s390x
|
| 6 |
+
|
| 7 |
+
#include "textflag.h"
|
| 8 |
+
|
| 9 |
+
// On s390x, the float32 becomes a float64
|
| 10 |
+
// when loaded in a register, different from
|
| 11 |
+
// other platforms. These functions are
|
| 12 |
+
// needed to ensure correct conversions on s390x.
|
| 13 |
+
|
| 14 |
+
// Convert float32->uint64
|
| 15 |
+
TEXT ·archFloat32ToReg(SB),NOSPLIT,$0-16
|
| 16 |
+
FMOVS val+0(FP), F1
|
| 17 |
+
FMOVD F1, ret+8(FP)
|
| 18 |
+
RET
|
| 19 |
+
|
| 20 |
+
// Convert uint64->float32
|
| 21 |
+
TEXT ·archFloat32FromReg(SB),NOSPLIT,$0-12
|
| 22 |
+
FMOVD reg+0(FP), F1
|
| 23 |
+
// Normally a float64->float32 conversion
|
| 24 |
+
// would need rounding, but that is not needed
|
| 25 |
+
// here since the uint64 was originally converted
|
| 26 |
+
// from float32, and should be avoided to
|
| 27 |
+
// preserve SNaN values.
|
| 28 |
+
FMOVS F1, ret+8(FP)
|
| 29 |
+
RET
|
| 30 |
+
|
go/src/reflect/iter.go
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 reflect
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"iter"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
func rangeNum[T int8 | int16 | int32 | int64 | int |
|
| 12 |
+
uint8 | uint16 | uint32 | uint64 | uint |
|
| 13 |
+
uintptr, N int64 | uint64](num N, t Type) iter.Seq[Value] {
|
| 14 |
+
return func(yield func(v Value) bool) {
|
| 15 |
+
convert := t.PkgPath() != ""
|
| 16 |
+
// cannot use range T(v) because no core type.
|
| 17 |
+
for i := T(0); i < T(num); i++ {
|
| 18 |
+
tmp := ValueOf(i)
|
| 19 |
+
// if the iteration value type is define by
|
| 20 |
+
// type T built-in type.
|
| 21 |
+
if convert {
|
| 22 |
+
tmp = tmp.Convert(t)
|
| 23 |
+
}
|
| 24 |
+
if !yield(tmp) {
|
| 25 |
+
return
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// Seq returns an iter.Seq[Value] that loops over the elements of v.
|
| 32 |
+
// If v's kind is Func, it must be a function that has no results and
|
| 33 |
+
// that takes a single argument of type func(T) bool for some type T.
|
| 34 |
+
// If v's kind is Pointer, the pointer element type must have kind Array.
|
| 35 |
+
// Otherwise v's kind must be Int, Int8, Int16, Int32, Int64,
|
| 36 |
+
// Uint, Uint8, Uint16, Uint32, Uint64, Uintptr,
|
| 37 |
+
// Array, Chan, Map, Slice, or String.
|
| 38 |
+
func (v Value) Seq() iter.Seq[Value] {
|
| 39 |
+
if canRangeFunc(v.abiType()) {
|
| 40 |
+
return func(yield func(Value) bool) {
|
| 41 |
+
rf := MakeFunc(v.Type().In(0), func(in []Value) []Value {
|
| 42 |
+
return []Value{ValueOf(yield(in[0]))}
|
| 43 |
+
})
|
| 44 |
+
v.Call([]Value{rf})
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
switch v.kind() {
|
| 48 |
+
case Int:
|
| 49 |
+
return rangeNum[int](v.Int(), v.Type())
|
| 50 |
+
case Int8:
|
| 51 |
+
return rangeNum[int8](v.Int(), v.Type())
|
| 52 |
+
case Int16:
|
| 53 |
+
return rangeNum[int16](v.Int(), v.Type())
|
| 54 |
+
case Int32:
|
| 55 |
+
return rangeNum[int32](v.Int(), v.Type())
|
| 56 |
+
case Int64:
|
| 57 |
+
return rangeNum[int64](v.Int(), v.Type())
|
| 58 |
+
case Uint:
|
| 59 |
+
return rangeNum[uint](v.Uint(), v.Type())
|
| 60 |
+
case Uint8:
|
| 61 |
+
return rangeNum[uint8](v.Uint(), v.Type())
|
| 62 |
+
case Uint16:
|
| 63 |
+
return rangeNum[uint16](v.Uint(), v.Type())
|
| 64 |
+
case Uint32:
|
| 65 |
+
return rangeNum[uint32](v.Uint(), v.Type())
|
| 66 |
+
case Uint64:
|
| 67 |
+
return rangeNum[uint64](v.Uint(), v.Type())
|
| 68 |
+
case Uintptr:
|
| 69 |
+
return rangeNum[uintptr](v.Uint(), v.Type())
|
| 70 |
+
case Pointer:
|
| 71 |
+
if v.Elem().kind() != Array {
|
| 72 |
+
break
|
| 73 |
+
}
|
| 74 |
+
return func(yield func(Value) bool) {
|
| 75 |
+
v = v.Elem()
|
| 76 |
+
for i := range v.Len() {
|
| 77 |
+
if !yield(ValueOf(i)) {
|
| 78 |
+
return
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
case Array, Slice:
|
| 83 |
+
return func(yield func(Value) bool) {
|
| 84 |
+
for i := range v.Len() {
|
| 85 |
+
if !yield(ValueOf(i)) {
|
| 86 |
+
return
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
case String:
|
| 91 |
+
return func(yield func(Value) bool) {
|
| 92 |
+
for i := range v.String() {
|
| 93 |
+
if !yield(ValueOf(i)) {
|
| 94 |
+
return
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
case Map:
|
| 99 |
+
return func(yield func(Value) bool) {
|
| 100 |
+
i := v.MapRange()
|
| 101 |
+
for i.Next() {
|
| 102 |
+
if !yield(i.Key()) {
|
| 103 |
+
return
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
case Chan:
|
| 108 |
+
return func(yield func(Value) bool) {
|
| 109 |
+
for value, ok := v.Recv(); ok; value, ok = v.Recv() {
|
| 110 |
+
if !yield(value) {
|
| 111 |
+
return
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
panic("reflect: " + v.Type().String() + " cannot produce iter.Seq[Value]")
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// Seq2 returns an iter.Seq2[Value, Value] that loops over the elements of v.
|
| 120 |
+
// If v's kind is Func, it must be a function that has no results and
|
| 121 |
+
// that takes a single argument of type func(K, V) bool for some type K, V.
|
| 122 |
+
// If v's kind is Pointer, the pointer element type must have kind Array.
|
| 123 |
+
// Otherwise v's kind must be Array, Map, Slice, or String.
|
| 124 |
+
func (v Value) Seq2() iter.Seq2[Value, Value] {
|
| 125 |
+
if canRangeFunc2(v.abiType()) {
|
| 126 |
+
return func(yield func(Value, Value) bool) {
|
| 127 |
+
rf := MakeFunc(v.Type().In(0), func(in []Value) []Value {
|
| 128 |
+
return []Value{ValueOf(yield(in[0], in[1]))}
|
| 129 |
+
})
|
| 130 |
+
v.Call([]Value{rf})
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
switch v.Kind() {
|
| 134 |
+
case Pointer:
|
| 135 |
+
if v.Elem().kind() != Array {
|
| 136 |
+
break
|
| 137 |
+
}
|
| 138 |
+
return func(yield func(Value, Value) bool) {
|
| 139 |
+
v = v.Elem()
|
| 140 |
+
for i := range v.Len() {
|
| 141 |
+
if !yield(ValueOf(i), v.Index(i)) {
|
| 142 |
+
return
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
case Array, Slice:
|
| 147 |
+
return func(yield func(Value, Value) bool) {
|
| 148 |
+
for i := range v.Len() {
|
| 149 |
+
if !yield(ValueOf(i), v.Index(i)) {
|
| 150 |
+
return
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
case String:
|
| 155 |
+
return func(yield func(Value, Value) bool) {
|
| 156 |
+
for i, v := range v.String() {
|
| 157 |
+
if !yield(ValueOf(i), ValueOf(v)) {
|
| 158 |
+
return
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
case Map:
|
| 163 |
+
return func(yield func(Value, Value) bool) {
|
| 164 |
+
i := v.MapRange()
|
| 165 |
+
for i.Next() {
|
| 166 |
+
if !yield(i.Key(), i.Value()) {
|
| 167 |
+
return
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
panic("reflect: " + v.Type().String() + " cannot produce iter.Seq2[Value, Value]")
|
| 173 |
+
}
|
go/src/reflect/iter_test.go
ADDED
|
@@ -0,0 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 reflect_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"iter"
|
| 9 |
+
"maps"
|
| 10 |
+
"reflect"
|
| 11 |
+
. "reflect"
|
| 12 |
+
"testing"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type N int8
|
| 16 |
+
|
| 17 |
+
func TestValueSeq(t *testing.T) {
|
| 18 |
+
m := map[string]int{
|
| 19 |
+
"1": 1,
|
| 20 |
+
"2": 2,
|
| 21 |
+
"3": 3,
|
| 22 |
+
"4": 4,
|
| 23 |
+
}
|
| 24 |
+
c := make(chan int, 3)
|
| 25 |
+
for i := range 3 {
|
| 26 |
+
c <- i
|
| 27 |
+
}
|
| 28 |
+
close(c)
|
| 29 |
+
tests := []struct {
|
| 30 |
+
name string
|
| 31 |
+
val Value
|
| 32 |
+
check func(*testing.T, iter.Seq[Value])
|
| 33 |
+
}{
|
| 34 |
+
{"int", ValueOf(4), func(t *testing.T, s iter.Seq[Value]) {
|
| 35 |
+
i := int64(0)
|
| 36 |
+
for v := range s {
|
| 37 |
+
if v.Int() != i {
|
| 38 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 39 |
+
}
|
| 40 |
+
i++
|
| 41 |
+
}
|
| 42 |
+
if i != 4 {
|
| 43 |
+
t.Fatalf("should loop four times")
|
| 44 |
+
}
|
| 45 |
+
}},
|
| 46 |
+
{"int8", ValueOf(int8(4)), func(t *testing.T, s iter.Seq[Value]) {
|
| 47 |
+
i := int8(0)
|
| 48 |
+
for v := range s {
|
| 49 |
+
if v.Interface().(int8) != i {
|
| 50 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 51 |
+
}
|
| 52 |
+
i++
|
| 53 |
+
}
|
| 54 |
+
if i != 4 {
|
| 55 |
+
t.Fatalf("should loop four times")
|
| 56 |
+
}
|
| 57 |
+
}},
|
| 58 |
+
{"uint", ValueOf(uint64(4)), func(t *testing.T, s iter.Seq[Value]) {
|
| 59 |
+
i := uint64(0)
|
| 60 |
+
for v := range s {
|
| 61 |
+
if v.Uint() != i {
|
| 62 |
+
t.Fatalf("got %d, want %d", v.Uint(), i)
|
| 63 |
+
}
|
| 64 |
+
i++
|
| 65 |
+
}
|
| 66 |
+
if i != 4 {
|
| 67 |
+
t.Fatalf("should loop four times")
|
| 68 |
+
}
|
| 69 |
+
}},
|
| 70 |
+
{"uint8", ValueOf(uint8(4)), func(t *testing.T, s iter.Seq[Value]) {
|
| 71 |
+
i := uint8(0)
|
| 72 |
+
for v := range s {
|
| 73 |
+
if v.Interface().(uint8) != i {
|
| 74 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 75 |
+
}
|
| 76 |
+
i++
|
| 77 |
+
}
|
| 78 |
+
if i != 4 {
|
| 79 |
+
t.Fatalf("should loop four times")
|
| 80 |
+
}
|
| 81 |
+
}},
|
| 82 |
+
{"*[4]int", ValueOf(&[4]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq[Value]) {
|
| 83 |
+
i := int64(0)
|
| 84 |
+
for v := range s {
|
| 85 |
+
if v.Int() != i {
|
| 86 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 87 |
+
}
|
| 88 |
+
i++
|
| 89 |
+
}
|
| 90 |
+
if i != 4 {
|
| 91 |
+
t.Fatalf("should loop four times")
|
| 92 |
+
}
|
| 93 |
+
}},
|
| 94 |
+
{"[4]int", ValueOf([4]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq[Value]) {
|
| 95 |
+
i := int64(0)
|
| 96 |
+
for v := range s {
|
| 97 |
+
if v.Int() != i {
|
| 98 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 99 |
+
}
|
| 100 |
+
i++
|
| 101 |
+
}
|
| 102 |
+
if i != 4 {
|
| 103 |
+
t.Fatalf("should loop four times")
|
| 104 |
+
}
|
| 105 |
+
}},
|
| 106 |
+
{"[]int", ValueOf([]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq[Value]) {
|
| 107 |
+
i := int64(0)
|
| 108 |
+
for v := range s {
|
| 109 |
+
if v.Int() != i {
|
| 110 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 111 |
+
}
|
| 112 |
+
i++
|
| 113 |
+
}
|
| 114 |
+
if i != 4 {
|
| 115 |
+
t.Fatalf("should loop four times")
|
| 116 |
+
}
|
| 117 |
+
}},
|
| 118 |
+
{"string", ValueOf("12语言"), func(t *testing.T, s iter.Seq[Value]) {
|
| 119 |
+
i := int64(0)
|
| 120 |
+
indexes := []int64{0, 1, 2, 5}
|
| 121 |
+
for v := range s {
|
| 122 |
+
if v.Int() != indexes[i] {
|
| 123 |
+
t.Fatalf("got %d, want %d", v.Int(), indexes[i])
|
| 124 |
+
}
|
| 125 |
+
i++
|
| 126 |
+
}
|
| 127 |
+
if i != 4 {
|
| 128 |
+
t.Fatalf("should loop four times")
|
| 129 |
+
}
|
| 130 |
+
}},
|
| 131 |
+
{"map[string]int", ValueOf(m), func(t *testing.T, s iter.Seq[Value]) {
|
| 132 |
+
copy := maps.Clone(m)
|
| 133 |
+
for v := range s {
|
| 134 |
+
if _, ok := copy[v.String()]; !ok {
|
| 135 |
+
t.Fatalf("unexpected %v", v.Interface())
|
| 136 |
+
}
|
| 137 |
+
delete(copy, v.String())
|
| 138 |
+
}
|
| 139 |
+
if len(copy) != 0 {
|
| 140 |
+
t.Fatalf("should loop four times")
|
| 141 |
+
}
|
| 142 |
+
}},
|
| 143 |
+
{"chan int", ValueOf(c), func(t *testing.T, s iter.Seq[Value]) {
|
| 144 |
+
i := 0
|
| 145 |
+
m := map[int64]bool{
|
| 146 |
+
0: false,
|
| 147 |
+
1: false,
|
| 148 |
+
2: false,
|
| 149 |
+
}
|
| 150 |
+
for v := range s {
|
| 151 |
+
if b, ok := m[v.Int()]; !ok || b {
|
| 152 |
+
t.Fatalf("unexpected %v", v.Interface())
|
| 153 |
+
}
|
| 154 |
+
m[v.Int()] = true
|
| 155 |
+
i++
|
| 156 |
+
}
|
| 157 |
+
if i != 3 {
|
| 158 |
+
t.Fatalf("should loop three times")
|
| 159 |
+
}
|
| 160 |
+
}},
|
| 161 |
+
{"func", ValueOf(func(yield func(int) bool) {
|
| 162 |
+
for i := range 4 {
|
| 163 |
+
if !yield(i) {
|
| 164 |
+
return
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
}), func(t *testing.T, s iter.Seq[Value]) {
|
| 168 |
+
i := int64(0)
|
| 169 |
+
for v := range s {
|
| 170 |
+
if v.Int() != i {
|
| 171 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 172 |
+
}
|
| 173 |
+
i++
|
| 174 |
+
}
|
| 175 |
+
if i != 4 {
|
| 176 |
+
t.Fatalf("should loop four times")
|
| 177 |
+
}
|
| 178 |
+
}},
|
| 179 |
+
{"method", ValueOf(methodIter{}).MethodByName("Seq"), func(t *testing.T, s iter.Seq[Value]) {
|
| 180 |
+
i := int64(0)
|
| 181 |
+
for v := range s {
|
| 182 |
+
if v.Int() != i {
|
| 183 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 184 |
+
}
|
| 185 |
+
i++
|
| 186 |
+
}
|
| 187 |
+
if i != 4 {
|
| 188 |
+
t.Fatalf("should loop four times")
|
| 189 |
+
}
|
| 190 |
+
}},
|
| 191 |
+
{"type N int8", ValueOf(N(4)), func(t *testing.T, s iter.Seq[Value]) {
|
| 192 |
+
i := N(0)
|
| 193 |
+
for v := range s {
|
| 194 |
+
if v.Int() != int64(i) {
|
| 195 |
+
t.Fatalf("got %d, want %d", v.Int(), i)
|
| 196 |
+
}
|
| 197 |
+
i++
|
| 198 |
+
if v.Type() != reflect.TypeOf(i) {
|
| 199 |
+
t.Fatalf("got %s, want %s", v.Type(), reflect.TypeOf(i))
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
if i != 4 {
|
| 203 |
+
t.Fatalf("should loop four times")
|
| 204 |
+
}
|
| 205 |
+
}},
|
| 206 |
+
}
|
| 207 |
+
for _, tc := range tests {
|
| 208 |
+
seq := tc.val.Seq()
|
| 209 |
+
tc.check(t, seq)
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
func TestValueSeq2(t *testing.T) {
|
| 214 |
+
m := map[string]int{
|
| 215 |
+
"1": 1,
|
| 216 |
+
"2": 2,
|
| 217 |
+
"3": 3,
|
| 218 |
+
"4": 4,
|
| 219 |
+
}
|
| 220 |
+
tests := []struct {
|
| 221 |
+
name string
|
| 222 |
+
val Value
|
| 223 |
+
check func(*testing.T, iter.Seq2[Value, Value])
|
| 224 |
+
}{
|
| 225 |
+
{"*[4]int", ValueOf(&[4]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 226 |
+
i := int64(0)
|
| 227 |
+
for v1, v2 := range s {
|
| 228 |
+
if v1.Int() != i {
|
| 229 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 230 |
+
}
|
| 231 |
+
i++
|
| 232 |
+
if v2.Int() != i {
|
| 233 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
if i != 4 {
|
| 237 |
+
t.Fatalf("should loop four times")
|
| 238 |
+
}
|
| 239 |
+
}},
|
| 240 |
+
{"[4]int", ValueOf([4]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 241 |
+
i := int64(0)
|
| 242 |
+
for v1, v2 := range s {
|
| 243 |
+
if v1.Int() != i {
|
| 244 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 245 |
+
}
|
| 246 |
+
i++
|
| 247 |
+
if v2.Int() != i {
|
| 248 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
if i != 4 {
|
| 252 |
+
t.Fatalf("should loop four times")
|
| 253 |
+
}
|
| 254 |
+
}},
|
| 255 |
+
{"[]int", ValueOf([]int{1, 2, 3, 4}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 256 |
+
i := int64(0)
|
| 257 |
+
for v1, v2 := range s {
|
| 258 |
+
if v1.Int() != i {
|
| 259 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 260 |
+
}
|
| 261 |
+
i++
|
| 262 |
+
if v2.Int() != i {
|
| 263 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
if i != 4 {
|
| 267 |
+
t.Fatalf("should loop four times")
|
| 268 |
+
}
|
| 269 |
+
}},
|
| 270 |
+
{"string", ValueOf("12语言"), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 271 |
+
next, stop := iter.Pull2(s)
|
| 272 |
+
defer stop()
|
| 273 |
+
i := int64(0)
|
| 274 |
+
for j, s := range "12语言" {
|
| 275 |
+
v1, v2, ok := next()
|
| 276 |
+
if !ok {
|
| 277 |
+
t.Fatalf("should loop four times")
|
| 278 |
+
}
|
| 279 |
+
if v1.Int() != int64(j) {
|
| 280 |
+
t.Fatalf("got %d, want %d", v1.Int(), j)
|
| 281 |
+
}
|
| 282 |
+
if v2.Interface() != s {
|
| 283 |
+
t.Fatalf("got %v, want %v", v2.Interface(), s)
|
| 284 |
+
}
|
| 285 |
+
i++
|
| 286 |
+
}
|
| 287 |
+
if i != 4 {
|
| 288 |
+
t.Fatalf("should loop four times")
|
| 289 |
+
}
|
| 290 |
+
}},
|
| 291 |
+
{"map[string]int", ValueOf(m), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 292 |
+
copy := maps.Clone(m)
|
| 293 |
+
for v1, v2 := range s {
|
| 294 |
+
v, ok := copy[v1.String()]
|
| 295 |
+
if !ok {
|
| 296 |
+
t.Fatalf("unexpected %v", v1.String())
|
| 297 |
+
}
|
| 298 |
+
if v != v2.Interface() {
|
| 299 |
+
t.Fatalf("got %v, want %d", v2.Interface(), v)
|
| 300 |
+
}
|
| 301 |
+
delete(copy, v1.String())
|
| 302 |
+
}
|
| 303 |
+
if len(copy) != 0 {
|
| 304 |
+
t.Fatalf("should loop four times")
|
| 305 |
+
}
|
| 306 |
+
}},
|
| 307 |
+
{"func", ValueOf(func(f func(int, int) bool) {
|
| 308 |
+
for i := range 4 {
|
| 309 |
+
f(i, i+1)
|
| 310 |
+
}
|
| 311 |
+
}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 312 |
+
i := int64(0)
|
| 313 |
+
for v1, v2 := range s {
|
| 314 |
+
if v1.Int() != i {
|
| 315 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 316 |
+
}
|
| 317 |
+
i++
|
| 318 |
+
if v2.Int() != i {
|
| 319 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
if i != 4 {
|
| 323 |
+
t.Fatalf("should loop four times")
|
| 324 |
+
}
|
| 325 |
+
}},
|
| 326 |
+
{"method", ValueOf(methodIter2{}).MethodByName("Seq2"), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 327 |
+
i := int64(0)
|
| 328 |
+
for v1, v2 := range s {
|
| 329 |
+
if v1.Int() != i {
|
| 330 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 331 |
+
}
|
| 332 |
+
i++
|
| 333 |
+
if v2.Int() != i {
|
| 334 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 335 |
+
}
|
| 336 |
+
}
|
| 337 |
+
if i != 4 {
|
| 338 |
+
t.Fatalf("should loop four times")
|
| 339 |
+
}
|
| 340 |
+
}},
|
| 341 |
+
{"[4]N", ValueOf([4]N{0, 1, 2, 3}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 342 |
+
i := N(0)
|
| 343 |
+
for v1, v2 := range s {
|
| 344 |
+
if v1.Int() != int64(i) {
|
| 345 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 346 |
+
}
|
| 347 |
+
if v2.Int() != int64(i) {
|
| 348 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 349 |
+
}
|
| 350 |
+
i++
|
| 351 |
+
if v2.Type() != reflect.TypeOf(i) {
|
| 352 |
+
t.Fatalf("got %s, want %s", v2.Type(), reflect.TypeOf(i))
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
if i != 4 {
|
| 356 |
+
t.Fatalf("should loop four times")
|
| 357 |
+
}
|
| 358 |
+
}},
|
| 359 |
+
{"[]N", ValueOf([]N{1, 2, 3, 4}), func(t *testing.T, s iter.Seq2[Value, Value]) {
|
| 360 |
+
i := N(0)
|
| 361 |
+
for v1, v2 := range s {
|
| 362 |
+
if v1.Int() != int64(i) {
|
| 363 |
+
t.Fatalf("got %d, want %d", v1.Int(), i)
|
| 364 |
+
}
|
| 365 |
+
i++
|
| 366 |
+
if v2.Int() != int64(i) {
|
| 367 |
+
t.Fatalf("got %d, want %d", v2.Int(), i)
|
| 368 |
+
}
|
| 369 |
+
if v2.Type() != reflect.TypeOf(i) {
|
| 370 |
+
t.Fatalf("got %s, want %s", v2.Type(), reflect.TypeOf(i))
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
if i != 4 {
|
| 374 |
+
t.Fatalf("should loop four times")
|
| 375 |
+
}
|
| 376 |
+
}},
|
| 377 |
+
}
|
| 378 |
+
for _, tc := range tests {
|
| 379 |
+
seq := tc.val.Seq2()
|
| 380 |
+
tc.check(t, seq)
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
// methodIter is a type from which we can derive a method
|
| 385 |
+
// value that is an iter.Seq.
|
| 386 |
+
type methodIter struct{}
|
| 387 |
+
|
| 388 |
+
func (methodIter) Seq(yield func(int) bool) {
|
| 389 |
+
for i := range 4 {
|
| 390 |
+
if !yield(i) {
|
| 391 |
+
return
|
| 392 |
+
}
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// For Type.CanSeq test.
|
| 397 |
+
func (methodIter) NonSeq(yield func(int)) {}
|
| 398 |
+
|
| 399 |
+
// methodIter2 is a type from which we can derive a method
|
| 400 |
+
// value that is an iter.Seq2.
|
| 401 |
+
type methodIter2 struct{}
|
| 402 |
+
|
| 403 |
+
func (methodIter2) Seq2(yield func(int, int) bool) {
|
| 404 |
+
for i := range 4 {
|
| 405 |
+
if !yield(i, i+1) {
|
| 406 |
+
return
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
// For Type.CanSeq2 test.
|
| 412 |
+
func (methodIter2) NonSeq2(yield func(int, int)) {}
|
go/src/reflect/makefunc.go
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
|
| 5 |
+
// MakeFunc implementation.
|
| 6 |
+
|
| 7 |
+
package reflect
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"internal/abi"
|
| 11 |
+
"internal/goarch"
|
| 12 |
+
"unsafe"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
// makeFuncImpl is the closure value implementing the function
|
| 16 |
+
// returned by MakeFunc.
|
| 17 |
+
// The first three words of this type must be kept in sync with
|
| 18 |
+
// methodValue and runtime.reflectMethodValue.
|
| 19 |
+
// Any changes should be reflected in all three.
|
| 20 |
+
type makeFuncImpl struct {
|
| 21 |
+
makeFuncCtxt
|
| 22 |
+
ftyp *funcType
|
| 23 |
+
fn func([]Value) []Value
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// MakeFunc returns a new function of the given [Type]
|
| 27 |
+
// that wraps the function fn. When called, that new function
|
| 28 |
+
// does the following:
|
| 29 |
+
//
|
| 30 |
+
// - converts its arguments to a slice of Values.
|
| 31 |
+
// - runs results := fn(args).
|
| 32 |
+
// - returns the results as a slice of Values, one per formal result.
|
| 33 |
+
//
|
| 34 |
+
// The implementation fn can assume that the argument [Value] slice
|
| 35 |
+
// has the number and type of arguments given by typ.
|
| 36 |
+
// If typ describes a variadic function, the final Value is itself
|
| 37 |
+
// a slice representing the variadic arguments, as in the
|
| 38 |
+
// body of a variadic function. The result Value slice returned by fn
|
| 39 |
+
// must have the number and type of results given by typ.
|
| 40 |
+
//
|
| 41 |
+
// The [Value.Call] method allows the caller to invoke a typed function
|
| 42 |
+
// in terms of Values; in contrast, MakeFunc allows the caller to implement
|
| 43 |
+
// a typed function in terms of Values.
|
| 44 |
+
//
|
| 45 |
+
// The Examples section of the documentation includes an illustration
|
| 46 |
+
// of how to use MakeFunc to build a swap function for different types.
|
| 47 |
+
func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value {
|
| 48 |
+
if typ.Kind() != Func {
|
| 49 |
+
panic("reflect: call of MakeFunc with non-Func type")
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
t := typ.common()
|
| 53 |
+
ftyp := (*funcType)(unsafe.Pointer(t))
|
| 54 |
+
|
| 55 |
+
code := abi.FuncPCABI0(makeFuncStub)
|
| 56 |
+
|
| 57 |
+
// makeFuncImpl contains a stack map for use by the runtime
|
| 58 |
+
_, _, abid := funcLayout(ftyp, nil)
|
| 59 |
+
|
| 60 |
+
impl := &makeFuncImpl{
|
| 61 |
+
makeFuncCtxt: makeFuncCtxt{
|
| 62 |
+
fn: code,
|
| 63 |
+
stack: abid.stackPtrs,
|
| 64 |
+
argLen: abid.stackCallArgsSize,
|
| 65 |
+
regPtrs: abid.inRegPtrs,
|
| 66 |
+
},
|
| 67 |
+
ftyp: ftyp,
|
| 68 |
+
fn: fn,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
return Value{t, unsafe.Pointer(impl), flag(Func)}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// makeFuncStub is an assembly function that is the code half of
|
| 75 |
+
// the function returned from MakeFunc. It expects a *callReflectFunc
|
| 76 |
+
// as its context register, and its job is to invoke callReflect(ctxt, frame)
|
| 77 |
+
// where ctxt is the context register and frame is a pointer to the first
|
| 78 |
+
// word in the passed-in argument frame.
|
| 79 |
+
func makeFuncStub()
|
| 80 |
+
|
| 81 |
+
// The first 3 words of this type must be kept in sync with
|
| 82 |
+
// makeFuncImpl and runtime.reflectMethodValue.
|
| 83 |
+
// Any changes should be reflected in all three.
|
| 84 |
+
type methodValue struct {
|
| 85 |
+
makeFuncCtxt
|
| 86 |
+
method int
|
| 87 |
+
rcvr Value
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// makeMethodValue converts v from the rcvr+method index representation
|
| 91 |
+
// of a method value to an actual method func value, which is
|
| 92 |
+
// basically the receiver value with a special bit set, into a true
|
| 93 |
+
// func value - a value holding an actual func. The output is
|
| 94 |
+
// semantically equivalent to the input as far as the user of package
|
| 95 |
+
// reflect can tell, but the true func representation can be handled
|
| 96 |
+
// by code like Convert and Interface and Assign.
|
| 97 |
+
func makeMethodValue(op string, v Value) Value {
|
| 98 |
+
if v.flag&flagMethod == 0 {
|
| 99 |
+
panic("reflect: internal error: invalid use of makeMethodValue")
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// Ignoring the flagMethod bit, v describes the receiver, not the method type.
|
| 103 |
+
fl := v.flag & (flagRO | flagAddr | flagIndir)
|
| 104 |
+
fl |= flag(v.typ().Kind())
|
| 105 |
+
rcvr := Value{v.typ(), v.ptr, fl}
|
| 106 |
+
|
| 107 |
+
// v.Type returns the actual type of the method value.
|
| 108 |
+
ftyp := (*funcType)(unsafe.Pointer(v.Type().(*rtype)))
|
| 109 |
+
|
| 110 |
+
code := methodValueCallCodePtr()
|
| 111 |
+
|
| 112 |
+
// methodValue contains a stack map for use by the runtime
|
| 113 |
+
_, _, abid := funcLayout(ftyp, nil)
|
| 114 |
+
fv := &methodValue{
|
| 115 |
+
makeFuncCtxt: makeFuncCtxt{
|
| 116 |
+
fn: code,
|
| 117 |
+
stack: abid.stackPtrs,
|
| 118 |
+
argLen: abid.stackCallArgsSize,
|
| 119 |
+
regPtrs: abid.inRegPtrs,
|
| 120 |
+
},
|
| 121 |
+
method: int(v.flag) >> flagMethodShift,
|
| 122 |
+
rcvr: rcvr,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// Cause panic if method is not appropriate.
|
| 126 |
+
// The panic would still happen during the call if we omit this,
|
| 127 |
+
// but we want Interface() and other operations to fail early.
|
| 128 |
+
methodReceiver(op, fv.rcvr, fv.method)
|
| 129 |
+
|
| 130 |
+
return Value{ftyp.Common(), unsafe.Pointer(fv), v.flag&flagRO | flag(Func)}
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
func methodValueCallCodePtr() uintptr {
|
| 134 |
+
return abi.FuncPCABI0(methodValueCall)
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
// methodValueCall is an assembly function that is the code half of
|
| 138 |
+
// the function returned from makeMethodValue. It expects a *methodValue
|
| 139 |
+
// as its context register, and its job is to invoke callMethod(ctxt, frame)
|
| 140 |
+
// where ctxt is the context register and frame is a pointer to the first
|
| 141 |
+
// word in the passed-in argument frame.
|
| 142 |
+
func methodValueCall()
|
| 143 |
+
|
| 144 |
+
// This structure must be kept in sync with runtime.reflectMethodValue.
|
| 145 |
+
// Any changes should be reflected in all both.
|
| 146 |
+
type makeFuncCtxt struct {
|
| 147 |
+
fn uintptr
|
| 148 |
+
stack *bitVector // ptrmap for both stack args and results
|
| 149 |
+
argLen uintptr // just args
|
| 150 |
+
regPtrs abi.IntArgRegBitmap
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// moveMakeFuncArgPtrs uses ctxt.regPtrs to copy integer pointer arguments
|
| 154 |
+
// in args.Ints to args.Ptrs where the GC can see them.
|
| 155 |
+
//
|
| 156 |
+
// This is similar to what reflectcallmove does in the runtime, except
|
| 157 |
+
// that happens on the return path, whereas this happens on the call path.
|
| 158 |
+
//
|
| 159 |
+
// nosplit because pointers are being held in uintptr slots in args, so
|
| 160 |
+
// having our stack scanned now could lead to accidentally freeing
|
| 161 |
+
// memory.
|
| 162 |
+
//
|
| 163 |
+
//go:nosplit
|
| 164 |
+
func moveMakeFuncArgPtrs(ctxt *makeFuncCtxt, args *abi.RegArgs) {
|
| 165 |
+
for i, arg := range args.Ints {
|
| 166 |
+
// Avoid write barriers! Because our write barrier enqueues what
|
| 167 |
+
// was there before, we might enqueue garbage.
|
| 168 |
+
// Also avoid bounds checks, we don't have the stack space for it.
|
| 169 |
+
// (Normally the prove pass removes them, but for -N builds we
|
| 170 |
+
// use too much stack.)
|
| 171 |
+
// ptr := &args.Ptrs[i] (but cast from *unsafe.Pointer to *uintptr)
|
| 172 |
+
ptr := (*uintptr)(add(unsafe.Pointer(unsafe.SliceData(args.Ptrs[:])), uintptr(i)*goarch.PtrSize, "always in [0:IntArgRegs]"))
|
| 173 |
+
if ctxt.regPtrs.Get(i) {
|
| 174 |
+
*ptr = arg
|
| 175 |
+
} else {
|
| 176 |
+
// We *must* zero this space ourselves because it's defined in
|
| 177 |
+
// assembly code and the GC will scan these pointers. Otherwise,
|
| 178 |
+
// there will be garbage here.
|
| 179 |
+
*ptr = 0
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
}
|
go/src/reflect/map.go
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 reflect
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"internal/abi"
|
| 9 |
+
"internal/race"
|
| 10 |
+
"internal/runtime/maps"
|
| 11 |
+
"internal/runtime/sys"
|
| 12 |
+
"unsafe"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func (t *rtype) Key() Type {
|
| 16 |
+
if t.Kind() != Map {
|
| 17 |
+
panic("reflect: Key of non-map type " + t.String())
|
| 18 |
+
}
|
| 19 |
+
tt := (*abi.MapType)(unsafe.Pointer(t))
|
| 20 |
+
return toType(tt.Key)
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// MapOf returns the map type with the given key and element types.
|
| 24 |
+
// For example, if k represents int and e represents string,
|
| 25 |
+
// MapOf(k, e) represents map[int]string.
|
| 26 |
+
//
|
| 27 |
+
// If the key type is not a valid map key type (that is, if it does
|
| 28 |
+
// not implement Go's == operator), MapOf panics.
|
| 29 |
+
func MapOf(key, elem Type) Type {
|
| 30 |
+
ktyp := key.common()
|
| 31 |
+
etyp := elem.common()
|
| 32 |
+
|
| 33 |
+
if ktyp.Equal == nil {
|
| 34 |
+
panic("reflect.MapOf: invalid key type " + stringFor(ktyp))
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Look in cache.
|
| 38 |
+
ckey := cacheKey{Map, ktyp, etyp, 0}
|
| 39 |
+
if mt, ok := lookupCache.Load(ckey); ok {
|
| 40 |
+
return mt.(Type)
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// Look in known types.
|
| 44 |
+
s := "map[" + stringFor(ktyp) + "]" + stringFor(etyp)
|
| 45 |
+
for _, tt := range typesByString(s) {
|
| 46 |
+
mt := (*abi.MapType)(unsafe.Pointer(tt))
|
| 47 |
+
if mt.Key == ktyp && mt.Elem == etyp {
|
| 48 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(tt))
|
| 49 |
+
return ti.(Type)
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
group, slot := groupAndSlotOf(key, elem)
|
| 54 |
+
|
| 55 |
+
// Make a map type.
|
| 56 |
+
// Note: flag values must match those used in the TMAP case
|
| 57 |
+
// in ../cmd/compile/internal/reflectdata/reflect.go:writeType.
|
| 58 |
+
var imap any = (map[unsafe.Pointer]unsafe.Pointer)(nil)
|
| 59 |
+
mt := **(**abi.MapType)(unsafe.Pointer(&imap))
|
| 60 |
+
mt.Str = resolveReflectName(newName(s, "", false, false))
|
| 61 |
+
mt.TFlag = abi.TFlagDirectIface
|
| 62 |
+
mt.Hash = fnv1(etyp.Hash, 'm', byte(ktyp.Hash>>24), byte(ktyp.Hash>>16), byte(ktyp.Hash>>8), byte(ktyp.Hash))
|
| 63 |
+
mt.Key = ktyp
|
| 64 |
+
mt.Elem = etyp
|
| 65 |
+
mt.Group = group.common()
|
| 66 |
+
mt.Hasher = func(p unsafe.Pointer, seed uintptr) uintptr {
|
| 67 |
+
return typehash(ktyp, p, seed)
|
| 68 |
+
}
|
| 69 |
+
mt.GroupSize = mt.Group.Size()
|
| 70 |
+
mt.SlotSize = slot.Size()
|
| 71 |
+
mt.ElemOff = slot.Field(1).Offset
|
| 72 |
+
mt.Flags = 0
|
| 73 |
+
if needKeyUpdate(ktyp) {
|
| 74 |
+
mt.Flags |= abi.MapNeedKeyUpdate
|
| 75 |
+
}
|
| 76 |
+
if hashMightPanic(ktyp) {
|
| 77 |
+
mt.Flags |= abi.MapHashMightPanic
|
| 78 |
+
}
|
| 79 |
+
if ktyp.Size_ > abi.MapMaxKeyBytes {
|
| 80 |
+
mt.Flags |= abi.MapIndirectKey
|
| 81 |
+
}
|
| 82 |
+
if etyp.Size_ > abi.MapMaxKeyBytes {
|
| 83 |
+
mt.Flags |= abi.MapIndirectElem
|
| 84 |
+
}
|
| 85 |
+
mt.PtrToThis = 0
|
| 86 |
+
|
| 87 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(&mt.Type))
|
| 88 |
+
return ti.(Type)
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
func groupAndSlotOf(ktyp, etyp Type) (Type, Type) {
|
| 92 |
+
// type group struct {
|
| 93 |
+
// ctrl uint64
|
| 94 |
+
// slots [abi.MapGroupSlots]struct {
|
| 95 |
+
// key keyType
|
| 96 |
+
// elem elemType
|
| 97 |
+
// }
|
| 98 |
+
// }
|
| 99 |
+
|
| 100 |
+
if ktyp.Size() > abi.MapMaxKeyBytes {
|
| 101 |
+
ktyp = PointerTo(ktyp)
|
| 102 |
+
}
|
| 103 |
+
if etyp.Size() > abi.MapMaxElemBytes {
|
| 104 |
+
etyp = PointerTo(etyp)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
fields := []StructField{
|
| 108 |
+
{
|
| 109 |
+
Name: "Key",
|
| 110 |
+
Type: ktyp,
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
Name: "Elem",
|
| 114 |
+
Type: etyp,
|
| 115 |
+
},
|
| 116 |
+
}
|
| 117 |
+
slot := StructOf(fields)
|
| 118 |
+
|
| 119 |
+
fields = []StructField{
|
| 120 |
+
{
|
| 121 |
+
Name: "Ctrl",
|
| 122 |
+
Type: TypeFor[uint64](),
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
Name: "Slots",
|
| 126 |
+
Type: ArrayOf(abi.MapGroupSlots, slot),
|
| 127 |
+
},
|
| 128 |
+
}
|
| 129 |
+
group := StructOf(fields)
|
| 130 |
+
return group, slot
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
var stringType = rtypeOf("")
|
| 134 |
+
|
| 135 |
+
// MapIndex returns the value associated with key in the map v.
|
| 136 |
+
// It panics if v's Kind is not [Map].
|
| 137 |
+
// It returns the zero Value if key is not found in the map or if v represents a nil map.
|
| 138 |
+
// As in Go, the key's value must be assignable to the map's key type.
|
| 139 |
+
func (v Value) MapIndex(key Value) Value {
|
| 140 |
+
v.mustBe(Map)
|
| 141 |
+
tt := (*abi.MapType)(unsafe.Pointer(v.typ()))
|
| 142 |
+
|
| 143 |
+
// Do not require key to be exported, so that DeepEqual
|
| 144 |
+
// and other programs can use all the keys returned by
|
| 145 |
+
// MapKeys as arguments to MapIndex. If either the map
|
| 146 |
+
// or the key is unexported, though, the result will be
|
| 147 |
+
// considered unexported. This is consistent with the
|
| 148 |
+
// behavior for structs, which allow read but not write
|
| 149 |
+
// of unexported fields.
|
| 150 |
+
|
| 151 |
+
var e unsafe.Pointer
|
| 152 |
+
if (tt.Key == stringType || key.kind() == String) && tt.Key == key.typ() && tt.Elem.Size() <= abi.MapMaxElemBytes {
|
| 153 |
+
k := *(*string)(key.ptr)
|
| 154 |
+
e = mapaccess_faststr(v.typ(), v.pointer(), k)
|
| 155 |
+
} else {
|
| 156 |
+
key = key.assignTo("reflect.Value.MapIndex", tt.Key, nil)
|
| 157 |
+
var k unsafe.Pointer
|
| 158 |
+
if key.flag&flagIndir != 0 {
|
| 159 |
+
k = key.ptr
|
| 160 |
+
} else {
|
| 161 |
+
k = unsafe.Pointer(&key.ptr)
|
| 162 |
+
}
|
| 163 |
+
e = mapaccess(v.typ(), v.pointer(), k)
|
| 164 |
+
}
|
| 165 |
+
if e == nil {
|
| 166 |
+
return Value{}
|
| 167 |
+
}
|
| 168 |
+
typ := tt.Elem
|
| 169 |
+
fl := (v.flag | key.flag).ro()
|
| 170 |
+
fl |= flag(typ.Kind())
|
| 171 |
+
return copyVal(typ, fl, e)
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
// Equivalent to runtime.mapIterStart.
|
| 175 |
+
//
|
| 176 |
+
//go:noinline
|
| 177 |
+
func mapIterStart(t *abi.MapType, m *maps.Map, it *maps.Iter) {
|
| 178 |
+
if race.Enabled && m != nil {
|
| 179 |
+
callerpc := sys.GetCallerPC()
|
| 180 |
+
race.ReadPC(unsafe.Pointer(m), callerpc, abi.FuncPCABIInternal(mapIterStart))
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
it.Init(t, m)
|
| 184 |
+
it.Next()
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
// Equivalent to runtime.mapIterNext.
|
| 188 |
+
//
|
| 189 |
+
//go:noinline
|
| 190 |
+
func mapIterNext(it *maps.Iter) {
|
| 191 |
+
if race.Enabled {
|
| 192 |
+
callerpc := sys.GetCallerPC()
|
| 193 |
+
race.ReadPC(unsafe.Pointer(it.Map()), callerpc, abi.FuncPCABIInternal(mapIterNext))
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
it.Next()
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
// MapKeys returns a slice containing all the keys present in the map,
|
| 200 |
+
// in unspecified order.
|
| 201 |
+
// It panics if v's Kind is not [Map].
|
| 202 |
+
// It returns an empty slice if v represents a nil map.
|
| 203 |
+
func (v Value) MapKeys() []Value {
|
| 204 |
+
v.mustBe(Map)
|
| 205 |
+
tt := (*abi.MapType)(unsafe.Pointer(v.typ()))
|
| 206 |
+
keyType := tt.Key
|
| 207 |
+
|
| 208 |
+
fl := v.flag.ro() | flag(keyType.Kind())
|
| 209 |
+
|
| 210 |
+
// Escape analysis can't see that the map doesn't escape. It sees an
|
| 211 |
+
// escape from maps.IterStart, via assignment into it, even though it
|
| 212 |
+
// doesn't escape this function.
|
| 213 |
+
mptr := abi.NoEscape(v.pointer())
|
| 214 |
+
m := (*maps.Map)(mptr)
|
| 215 |
+
mlen := int(0)
|
| 216 |
+
if m != nil {
|
| 217 |
+
mlen = maplen(mptr)
|
| 218 |
+
}
|
| 219 |
+
var it maps.Iter
|
| 220 |
+
mapIterStart(tt, m, &it)
|
| 221 |
+
a := make([]Value, mlen)
|
| 222 |
+
var i int
|
| 223 |
+
for i = 0; i < len(a); i++ {
|
| 224 |
+
key := it.Key()
|
| 225 |
+
if key == nil {
|
| 226 |
+
// Someone deleted an entry from the map since we
|
| 227 |
+
// called maplen above. It's a data race, but nothing
|
| 228 |
+
// we can do about it.
|
| 229 |
+
break
|
| 230 |
+
}
|
| 231 |
+
a[i] = copyVal(keyType, fl, key)
|
| 232 |
+
mapIterNext(&it)
|
| 233 |
+
}
|
| 234 |
+
return a[:i]
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
// A MapIter is an iterator for ranging over a map.
|
| 238 |
+
// See [Value.MapRange].
|
| 239 |
+
type MapIter struct {
|
| 240 |
+
m Value
|
| 241 |
+
hiter maps.Iter
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// Key returns the key of iter's current map entry.
|
| 245 |
+
func (iter *MapIter) Key() Value {
|
| 246 |
+
if !iter.hiter.Initialized() {
|
| 247 |
+
panic("MapIter.Key called before Next")
|
| 248 |
+
}
|
| 249 |
+
iterkey := iter.hiter.Key()
|
| 250 |
+
if iterkey == nil {
|
| 251 |
+
panic("MapIter.Key called on exhausted iterator")
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
t := (*abi.MapType)(unsafe.Pointer(iter.m.typ()))
|
| 255 |
+
ktype := t.Key
|
| 256 |
+
return copyVal(ktype, iter.m.flag.ro()|flag(ktype.Kind()), iterkey)
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// SetIterKey assigns to v the key of iter's current map entry.
|
| 260 |
+
// It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value.
|
| 261 |
+
// As in Go, the key must be assignable to v's type and
|
| 262 |
+
// must not be derived from an unexported field.
|
| 263 |
+
// It panics if [Value.CanSet] returns false.
|
| 264 |
+
func (v Value) SetIterKey(iter *MapIter) {
|
| 265 |
+
if !iter.hiter.Initialized() {
|
| 266 |
+
panic("reflect: Value.SetIterKey called before Next")
|
| 267 |
+
}
|
| 268 |
+
iterkey := iter.hiter.Key()
|
| 269 |
+
if iterkey == nil {
|
| 270 |
+
panic("reflect: Value.SetIterKey called on exhausted iterator")
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
v.mustBeAssignable()
|
| 274 |
+
var target unsafe.Pointer
|
| 275 |
+
if v.kind() == Interface {
|
| 276 |
+
target = v.ptr
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
t := (*abi.MapType)(unsafe.Pointer(iter.m.typ()))
|
| 280 |
+
ktype := t.Key
|
| 281 |
+
|
| 282 |
+
iter.m.mustBeExported() // do not let unexported m leak
|
| 283 |
+
key := Value{ktype, iterkey, iter.m.flag | flag(ktype.Kind()) | flagIndir}
|
| 284 |
+
key = key.assignTo("reflect.MapIter.SetKey", v.typ(), target)
|
| 285 |
+
typedmemmove(v.typ(), v.ptr, key.ptr)
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
// Value returns the value of iter's current map entry.
|
| 289 |
+
func (iter *MapIter) Value() Value {
|
| 290 |
+
if !iter.hiter.Initialized() {
|
| 291 |
+
panic("MapIter.Value called before Next")
|
| 292 |
+
}
|
| 293 |
+
iterelem := iter.hiter.Elem()
|
| 294 |
+
if iterelem == nil {
|
| 295 |
+
panic("MapIter.Value called on exhausted iterator")
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
t := (*abi.MapType)(unsafe.Pointer(iter.m.typ()))
|
| 299 |
+
vtype := t.Elem
|
| 300 |
+
return copyVal(vtype, iter.m.flag.ro()|flag(vtype.Kind()), iterelem)
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// SetIterValue assigns to v the value of iter's current map entry.
|
| 304 |
+
// It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value.
|
| 305 |
+
// As in Go, the value must be assignable to v's type and
|
| 306 |
+
// must not be derived from an unexported field.
|
| 307 |
+
// It panics if [Value.CanSet] returns false.
|
| 308 |
+
func (v Value) SetIterValue(iter *MapIter) {
|
| 309 |
+
if !iter.hiter.Initialized() {
|
| 310 |
+
panic("reflect: Value.SetIterValue called before Next")
|
| 311 |
+
}
|
| 312 |
+
iterelem := iter.hiter.Elem()
|
| 313 |
+
if iterelem == nil {
|
| 314 |
+
panic("reflect: Value.SetIterValue called on exhausted iterator")
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
v.mustBeAssignable()
|
| 318 |
+
var target unsafe.Pointer
|
| 319 |
+
if v.kind() == Interface {
|
| 320 |
+
target = v.ptr
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
t := (*abi.MapType)(unsafe.Pointer(iter.m.typ()))
|
| 324 |
+
vtype := t.Elem
|
| 325 |
+
|
| 326 |
+
iter.m.mustBeExported() // do not let unexported m leak
|
| 327 |
+
elem := Value{vtype, iterelem, iter.m.flag | flag(vtype.Kind()) | flagIndir}
|
| 328 |
+
elem = elem.assignTo("reflect.MapIter.SetValue", v.typ(), target)
|
| 329 |
+
typedmemmove(v.typ(), v.ptr, elem.ptr)
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
// Next advances the map iterator and reports whether there is another
|
| 333 |
+
// entry. It returns false when iter is exhausted; subsequent
|
| 334 |
+
// calls to [MapIter.Key], [MapIter.Value], or [MapIter.Next] will panic.
|
| 335 |
+
func (iter *MapIter) Next() bool {
|
| 336 |
+
if !iter.m.IsValid() {
|
| 337 |
+
panic("MapIter.Next called on an iterator that does not have an associated map Value")
|
| 338 |
+
}
|
| 339 |
+
if !iter.hiter.Initialized() {
|
| 340 |
+
t := (*abi.MapType)(unsafe.Pointer(iter.m.typ()))
|
| 341 |
+
m := (*maps.Map)(iter.m.pointer())
|
| 342 |
+
mapIterStart(t, m, &iter.hiter)
|
| 343 |
+
} else {
|
| 344 |
+
if iter.hiter.Key() == nil {
|
| 345 |
+
panic("MapIter.Next called on exhausted iterator")
|
| 346 |
+
}
|
| 347 |
+
mapIterNext(&iter.hiter)
|
| 348 |
+
}
|
| 349 |
+
return iter.hiter.Key() != nil
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
// Reset modifies iter to iterate over v.
|
| 353 |
+
// It panics if v's Kind is not [Map] and v is not the zero Value.
|
| 354 |
+
// Reset(Value{}) causes iter to not to refer to any map,
|
| 355 |
+
// which may allow the previously iterated-over map to be garbage collected.
|
| 356 |
+
func (iter *MapIter) Reset(v Value) {
|
| 357 |
+
if v.IsValid() {
|
| 358 |
+
v.mustBe(Map)
|
| 359 |
+
}
|
| 360 |
+
iter.m = v
|
| 361 |
+
iter.hiter = maps.Iter{}
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
// MapRange returns a range iterator for a map.
|
| 365 |
+
// It panics if v's Kind is not [Map].
|
| 366 |
+
//
|
| 367 |
+
// Call [MapIter.Next] to advance the iterator, and [MapIter.Key]/[MapIter.Value] to access each entry.
|
| 368 |
+
// [MapIter.Next] returns false when the iterator is exhausted.
|
| 369 |
+
// MapRange follows the same iteration semantics as a range statement.
|
| 370 |
+
//
|
| 371 |
+
// Example:
|
| 372 |
+
//
|
| 373 |
+
// iter := reflect.ValueOf(m).MapRange()
|
| 374 |
+
// for iter.Next() {
|
| 375 |
+
// k := iter.Key()
|
| 376 |
+
// v := iter.Value()
|
| 377 |
+
// ...
|
| 378 |
+
// }
|
| 379 |
+
func (v Value) MapRange() *MapIter {
|
| 380 |
+
// This is inlinable to take advantage of "function outlining".
|
| 381 |
+
// The allocation of MapIter can be stack allocated if the caller
|
| 382 |
+
// does not allow it to escape.
|
| 383 |
+
// See https://blog.filippo.io/efficient-go-apis-with-the-inliner/
|
| 384 |
+
if v.kind() != Map {
|
| 385 |
+
v.panicNotMap()
|
| 386 |
+
}
|
| 387 |
+
return &MapIter{m: v}
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
// SetMapIndex sets the element associated with key in the map v to elem.
|
| 391 |
+
// It panics if v's Kind is not [Map].
|
| 392 |
+
// If elem is the zero Value, SetMapIndex deletes the key from the map.
|
| 393 |
+
// Otherwise if v holds a nil map, SetMapIndex will panic.
|
| 394 |
+
// As in Go, key's elem must be assignable to the map's key type,
|
| 395 |
+
// and elem's value must be assignable to the map's elem type.
|
| 396 |
+
func (v Value) SetMapIndex(key, elem Value) {
|
| 397 |
+
v.mustBe(Map)
|
| 398 |
+
v.mustBeExported()
|
| 399 |
+
key.mustBeExported()
|
| 400 |
+
tt := (*abi.MapType)(unsafe.Pointer(v.typ()))
|
| 401 |
+
|
| 402 |
+
if (tt.Key == stringType || key.kind() == String) && tt.Key == key.typ() && tt.Elem.Size() <= abi.MapMaxElemBytes {
|
| 403 |
+
k := *(*string)(key.ptr)
|
| 404 |
+
if elem.typ() == nil {
|
| 405 |
+
mapdelete_faststr(v.typ(), v.pointer(), k)
|
| 406 |
+
return
|
| 407 |
+
}
|
| 408 |
+
elem.mustBeExported()
|
| 409 |
+
elem = elem.assignTo("reflect.Value.SetMapIndex", tt.Elem, nil)
|
| 410 |
+
var e unsafe.Pointer
|
| 411 |
+
if elem.flag&flagIndir != 0 {
|
| 412 |
+
e = elem.ptr
|
| 413 |
+
} else {
|
| 414 |
+
e = unsafe.Pointer(&elem.ptr)
|
| 415 |
+
}
|
| 416 |
+
mapassign_faststr(v.typ(), v.pointer(), k, e)
|
| 417 |
+
return
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
key = key.assignTo("reflect.Value.SetMapIndex", tt.Key, nil)
|
| 421 |
+
var k unsafe.Pointer
|
| 422 |
+
if key.flag&flagIndir != 0 {
|
| 423 |
+
k = key.ptr
|
| 424 |
+
} else {
|
| 425 |
+
k = unsafe.Pointer(&key.ptr)
|
| 426 |
+
}
|
| 427 |
+
if elem.typ() == nil {
|
| 428 |
+
mapdelete(v.typ(), v.pointer(), k)
|
| 429 |
+
return
|
| 430 |
+
}
|
| 431 |
+
elem.mustBeExported()
|
| 432 |
+
elem = elem.assignTo("reflect.Value.SetMapIndex", tt.Elem, nil)
|
| 433 |
+
var e unsafe.Pointer
|
| 434 |
+
if elem.flag&flagIndir != 0 {
|
| 435 |
+
e = elem.ptr
|
| 436 |
+
} else {
|
| 437 |
+
e = unsafe.Pointer(&elem.ptr)
|
| 438 |
+
}
|
| 439 |
+
mapassign(v.typ(), v.pointer(), k, e)
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
// Force slow panicking path not inlined, so it won't add to the
|
| 443 |
+
// inlining budget of the caller.
|
| 444 |
+
// TODO: undo when the inliner is no longer bottom-up only.
|
| 445 |
+
//
|
| 446 |
+
//go:noinline
|
| 447 |
+
func (f flag) panicNotMap() {
|
| 448 |
+
f.mustBe(Map)
|
| 449 |
+
}
|
go/src/reflect/map_test.go
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 reflect_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"reflect"
|
| 9 |
+
"testing"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// See also runtime_test.TestGroupSizeZero.
|
| 13 |
+
func TestGroupSizeZero(t *testing.T) {
|
| 14 |
+
st := reflect.TypeFor[struct{}]()
|
| 15 |
+
grp := reflect.MapGroupOf(st, st)
|
| 16 |
+
|
| 17 |
+
// internal/runtime/maps when create pointers to slots, even if slots
|
| 18 |
+
// are size 0. We should have reserved an extra word to ensure that
|
| 19 |
+
// pointers to the zero-size type at the end of group are valid.
|
| 20 |
+
if grp.Size() <= 8 {
|
| 21 |
+
t.Errorf("Group size got %d want >8", grp.Size())
|
| 22 |
+
}
|
| 23 |
+
}
|
go/src/reflect/nih_test.go
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 cgo
|
| 6 |
+
|
| 7 |
+
package reflect_test
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
. "reflect"
|
| 11 |
+
"runtime/cgo"
|
| 12 |
+
"testing"
|
| 13 |
+
"unsafe"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
type nih struct {
|
| 17 |
+
_ cgo.Incomplete
|
| 18 |
+
x int
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
var global_nih = nih{x: 7}
|
| 22 |
+
|
| 23 |
+
func TestNotInHeapDeref(t *testing.T) {
|
| 24 |
+
// See issue 48399.
|
| 25 |
+
v := ValueOf((*nih)(nil))
|
| 26 |
+
v.Elem()
|
| 27 |
+
shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
|
| 28 |
+
|
| 29 |
+
v = ValueOf(&global_nih)
|
| 30 |
+
if got := v.Elem().Field(1).Int(); got != 7 {
|
| 31 |
+
t.Fatalf("got %d, want 7", got)
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
v = ValueOf((*nih)(unsafe.Pointer(new(int))))
|
| 35 |
+
shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
|
| 36 |
+
shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
|
| 37 |
+
shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
|
| 38 |
+
}
|
go/src/reflect/set_test.go
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2011 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 reflect_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bytes"
|
| 9 |
+
"go/ast"
|
| 10 |
+
"go/token"
|
| 11 |
+
"io"
|
| 12 |
+
. "reflect"
|
| 13 |
+
"strings"
|
| 14 |
+
"testing"
|
| 15 |
+
"unsafe"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
func TestImplicitMapConversion(t *testing.T) {
|
| 19 |
+
// Test implicit conversions in MapIndex and SetMapIndex.
|
| 20 |
+
{
|
| 21 |
+
// direct
|
| 22 |
+
m := make(map[int]int)
|
| 23 |
+
mv := ValueOf(m)
|
| 24 |
+
mv.SetMapIndex(ValueOf(1), ValueOf(2))
|
| 25 |
+
x, ok := m[1]
|
| 26 |
+
if x != 2 {
|
| 27 |
+
t.Errorf("#1 after SetMapIndex(1,2): %d, %t (map=%v)", x, ok, m)
|
| 28 |
+
}
|
| 29 |
+
if n := mv.MapIndex(ValueOf(1)).Interface().(int); n != 2 {
|
| 30 |
+
t.Errorf("#1 MapIndex(1) = %d", n)
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
{
|
| 34 |
+
// convert interface key
|
| 35 |
+
m := make(map[any]int)
|
| 36 |
+
mv := ValueOf(m)
|
| 37 |
+
mv.SetMapIndex(ValueOf(1), ValueOf(2))
|
| 38 |
+
x, ok := m[1]
|
| 39 |
+
if x != 2 {
|
| 40 |
+
t.Errorf("#2 after SetMapIndex(1,2): %d, %t (map=%v)", x, ok, m)
|
| 41 |
+
}
|
| 42 |
+
if n := mv.MapIndex(ValueOf(1)).Interface().(int); n != 2 {
|
| 43 |
+
t.Errorf("#2 MapIndex(1) = %d", n)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
{
|
| 47 |
+
// convert interface value
|
| 48 |
+
m := make(map[int]any)
|
| 49 |
+
mv := ValueOf(m)
|
| 50 |
+
mv.SetMapIndex(ValueOf(1), ValueOf(2))
|
| 51 |
+
x, ok := m[1]
|
| 52 |
+
if x != 2 {
|
| 53 |
+
t.Errorf("#3 after SetMapIndex(1,2): %d, %t (map=%v)", x, ok, m)
|
| 54 |
+
}
|
| 55 |
+
if n := mv.MapIndex(ValueOf(1)).Interface().(int); n != 2 {
|
| 56 |
+
t.Errorf("#3 MapIndex(1) = %d", n)
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
{
|
| 60 |
+
// convert both interface key and interface value
|
| 61 |
+
m := make(map[any]any)
|
| 62 |
+
mv := ValueOf(m)
|
| 63 |
+
mv.SetMapIndex(ValueOf(1), ValueOf(2))
|
| 64 |
+
x, ok := m[1]
|
| 65 |
+
if x != 2 {
|
| 66 |
+
t.Errorf("#4 after SetMapIndex(1,2): %d, %t (map=%v)", x, ok, m)
|
| 67 |
+
}
|
| 68 |
+
if n := mv.MapIndex(ValueOf(1)).Interface().(int); n != 2 {
|
| 69 |
+
t.Errorf("#4 MapIndex(1) = %d", n)
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
{
|
| 73 |
+
// convert both, with non-empty interfaces
|
| 74 |
+
m := make(map[io.Reader]io.Writer)
|
| 75 |
+
mv := ValueOf(m)
|
| 76 |
+
b1 := new(bytes.Buffer)
|
| 77 |
+
b2 := new(bytes.Buffer)
|
| 78 |
+
mv.SetMapIndex(ValueOf(b1), ValueOf(b2))
|
| 79 |
+
x, ok := m[b1]
|
| 80 |
+
if x != b2 {
|
| 81 |
+
t.Errorf("#5 after SetMapIndex(b1, b2): %p (!= %p), %t (map=%v)", x, b2, ok, m)
|
| 82 |
+
}
|
| 83 |
+
if p := mv.MapIndex(ValueOf(b1)).Elem().UnsafePointer(); p != unsafe.Pointer(b2) {
|
| 84 |
+
t.Errorf("#5 MapIndex(b1) = %#x want %p", p, b2)
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
{
|
| 88 |
+
// convert channel direction
|
| 89 |
+
m := make(map[<-chan int]chan int)
|
| 90 |
+
mv := ValueOf(m)
|
| 91 |
+
c1 := make(chan int)
|
| 92 |
+
c2 := make(chan int)
|
| 93 |
+
mv.SetMapIndex(ValueOf(c1), ValueOf(c2))
|
| 94 |
+
x, ok := m[c1]
|
| 95 |
+
if x != c2 {
|
| 96 |
+
t.Errorf("#6 after SetMapIndex(c1, c2): %p (!= %p), %t (map=%v)", x, c2, ok, m)
|
| 97 |
+
}
|
| 98 |
+
if p := mv.MapIndex(ValueOf(c1)).UnsafePointer(); p != ValueOf(c2).UnsafePointer() {
|
| 99 |
+
t.Errorf("#6 MapIndex(c1) = %#x want %p", p, c2)
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
{
|
| 103 |
+
// convert identical underlying types
|
| 104 |
+
type MyBuffer bytes.Buffer
|
| 105 |
+
m := make(map[*MyBuffer]*bytes.Buffer)
|
| 106 |
+
mv := ValueOf(m)
|
| 107 |
+
b1 := new(MyBuffer)
|
| 108 |
+
b2 := new(bytes.Buffer)
|
| 109 |
+
mv.SetMapIndex(ValueOf(b1), ValueOf(b2))
|
| 110 |
+
x, ok := m[b1]
|
| 111 |
+
if x != b2 {
|
| 112 |
+
t.Errorf("#7 after SetMapIndex(b1, b2): %p (!= %p), %t (map=%v)", x, b2, ok, m)
|
| 113 |
+
}
|
| 114 |
+
if p := mv.MapIndex(ValueOf(b1)).UnsafePointer(); p != unsafe.Pointer(b2) {
|
| 115 |
+
t.Errorf("#7 MapIndex(b1) = %#x want %p", p, b2)
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
func TestImplicitSetConversion(t *testing.T) {
|
| 122 |
+
// Assume TestImplicitMapConversion covered the basics.
|
| 123 |
+
// Just make sure conversions are being applied at all.
|
| 124 |
+
var r io.Reader
|
| 125 |
+
b := new(bytes.Buffer)
|
| 126 |
+
rv := ValueOf(&r).Elem()
|
| 127 |
+
rv.Set(ValueOf(b))
|
| 128 |
+
if r != b {
|
| 129 |
+
t.Errorf("after Set: r=%T(%v)", r, r)
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
func TestImplicitSendConversion(t *testing.T) {
|
| 134 |
+
c := make(chan io.Reader, 10)
|
| 135 |
+
b := new(bytes.Buffer)
|
| 136 |
+
ValueOf(c).Send(ValueOf(b))
|
| 137 |
+
if bb := <-c; bb != b {
|
| 138 |
+
t.Errorf("Received %p != %p", bb, b)
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
func TestImplicitCallConversion(t *testing.T) {
|
| 143 |
+
// Arguments must be assignable to parameter types.
|
| 144 |
+
fv := ValueOf(io.WriteString)
|
| 145 |
+
b := new(strings.Builder)
|
| 146 |
+
fv.Call([]Value{ValueOf(b), ValueOf("hello world")})
|
| 147 |
+
if b.String() != "hello world" {
|
| 148 |
+
t.Errorf("After call: string=%q want %q", b.String(), "hello world")
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
func TestImplicitAppendConversion(t *testing.T) {
|
| 153 |
+
// Arguments must be assignable to the slice's element type.
|
| 154 |
+
s := []io.Reader{}
|
| 155 |
+
sv := ValueOf(&s).Elem()
|
| 156 |
+
b := new(bytes.Buffer)
|
| 157 |
+
sv.Set(Append(sv, ValueOf(b)))
|
| 158 |
+
if len(s) != 1 || s[0] != b {
|
| 159 |
+
t.Errorf("after append: s=%v want [%p]", s, b)
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
var implementsTests = []struct {
|
| 164 |
+
x any
|
| 165 |
+
t any
|
| 166 |
+
b bool
|
| 167 |
+
}{
|
| 168 |
+
{new(*bytes.Buffer), new(io.Reader), true},
|
| 169 |
+
{new(bytes.Buffer), new(io.Reader), false},
|
| 170 |
+
{new(*bytes.Buffer), new(io.ReaderAt), false},
|
| 171 |
+
{new(*ast.Ident), new(ast.Expr), true},
|
| 172 |
+
{new(*notAnExpr), new(ast.Expr), false},
|
| 173 |
+
{new(*ast.Ident), new(notASTExpr), false},
|
| 174 |
+
{new(notASTExpr), new(ast.Expr), false},
|
| 175 |
+
{new(ast.Expr), new(notASTExpr), false},
|
| 176 |
+
{new(*notAnExpr), new(notASTExpr), true},
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
type notAnExpr struct{}
|
| 180 |
+
|
| 181 |
+
func (notAnExpr) Pos() token.Pos { return token.NoPos }
|
| 182 |
+
func (notAnExpr) End() token.Pos { return token.NoPos }
|
| 183 |
+
func (notAnExpr) exprNode() {}
|
| 184 |
+
|
| 185 |
+
type notASTExpr interface {
|
| 186 |
+
Pos() token.Pos
|
| 187 |
+
End() token.Pos
|
| 188 |
+
exprNode()
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
func TestImplements(t *testing.T) {
|
| 192 |
+
for _, tt := range implementsTests {
|
| 193 |
+
xv := TypeOf(tt.x).Elem()
|
| 194 |
+
xt := TypeOf(tt.t).Elem()
|
| 195 |
+
if b := xv.Implements(xt); b != tt.b {
|
| 196 |
+
t.Errorf("(%s).Implements(%s) = %v, want %v", xv.String(), xt.String(), b, tt.b)
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
var assignableTests = []struct {
|
| 202 |
+
x any
|
| 203 |
+
t any
|
| 204 |
+
b bool
|
| 205 |
+
}{
|
| 206 |
+
{new(chan int), new(<-chan int), true},
|
| 207 |
+
{new(<-chan int), new(chan int), false},
|
| 208 |
+
{new(*int), new(IntPtr), true},
|
| 209 |
+
{new(IntPtr), new(*int), true},
|
| 210 |
+
{new(IntPtr), new(IntPtr1), false},
|
| 211 |
+
{new(Ch), new(<-chan any), true},
|
| 212 |
+
// test runs implementsTests too
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
type IntPtr *int
|
| 216 |
+
type IntPtr1 *int
|
| 217 |
+
type Ch <-chan any
|
| 218 |
+
|
| 219 |
+
func TestAssignableTo(t *testing.T) {
|
| 220 |
+
for _, tt := range append(assignableTests, implementsTests...) {
|
| 221 |
+
xv := TypeOf(tt.x).Elem()
|
| 222 |
+
xt := TypeOf(tt.t).Elem()
|
| 223 |
+
if b := xv.AssignableTo(xt); b != tt.b {
|
| 224 |
+
t.Errorf("(%s).AssignableTo(%s) = %v, want %v", xv.String(), xt.String(), b, tt.b)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
}
|
go/src/reflect/stubs_ppc64x.go
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ppc64le || ppc64
|
| 6 |
+
|
| 7 |
+
package reflect
|
| 8 |
+
|
| 9 |
+
func archFloat32FromReg(reg uint64) float32
|
| 10 |
+
func archFloat32ToReg(val float32) uint64
|
go/src/reflect/stubs_riscv64.go
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 reflect
|
| 6 |
+
|
| 7 |
+
func archFloat32FromReg(reg uint64) float32
|
| 8 |
+
func archFloat32ToReg(val float32) uint64
|
go/src/reflect/stubs_s390x.go
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 s390x
|
| 6 |
+
|
| 7 |
+
package reflect
|
| 8 |
+
|
| 9 |
+
func archFloat32FromReg(reg uint64) float32
|
| 10 |
+
func archFloat32ToReg(val float32) uint64
|
go/src/reflect/swapper.go
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2016 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 reflect
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"internal/abi"
|
| 9 |
+
"internal/goarch"
|
| 10 |
+
"internal/unsafeheader"
|
| 11 |
+
"unsafe"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
// Swapper returns a function that swaps the elements in the provided
|
| 15 |
+
// slice.
|
| 16 |
+
//
|
| 17 |
+
// Swapper panics if the provided interface is not a slice.
|
| 18 |
+
func Swapper(slice any) func(i, j int) {
|
| 19 |
+
v := ValueOf(slice)
|
| 20 |
+
if v.Kind() != Slice {
|
| 21 |
+
panic(&ValueError{Method: "Swapper", Kind: v.Kind()})
|
| 22 |
+
}
|
| 23 |
+
// Fast path for slices of size 0 and 1. Nothing to swap.
|
| 24 |
+
switch v.Len() {
|
| 25 |
+
case 0:
|
| 26 |
+
return func(i, j int) { panic("reflect: slice index out of range") }
|
| 27 |
+
case 1:
|
| 28 |
+
return func(i, j int) {
|
| 29 |
+
if i != 0 || j != 0 {
|
| 30 |
+
panic("reflect: slice index out of range")
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
typ := v.Type().Elem().common()
|
| 36 |
+
size := typ.Size()
|
| 37 |
+
hasPtr := typ.Pointers()
|
| 38 |
+
|
| 39 |
+
// Some common & small cases, without using memmove:
|
| 40 |
+
if hasPtr {
|
| 41 |
+
if size == goarch.PtrSize {
|
| 42 |
+
ps := *(*[]unsafe.Pointer)(v.ptr)
|
| 43 |
+
return func(i, j int) { ps[i], ps[j] = ps[j], ps[i] }
|
| 44 |
+
}
|
| 45 |
+
if typ.Kind() == abi.String {
|
| 46 |
+
ss := *(*[]string)(v.ptr)
|
| 47 |
+
return func(i, j int) { ss[i], ss[j] = ss[j], ss[i] }
|
| 48 |
+
}
|
| 49 |
+
} else {
|
| 50 |
+
switch size {
|
| 51 |
+
case 8:
|
| 52 |
+
is := *(*[]int64)(v.ptr)
|
| 53 |
+
return func(i, j int) { is[i], is[j] = is[j], is[i] }
|
| 54 |
+
case 4:
|
| 55 |
+
is := *(*[]int32)(v.ptr)
|
| 56 |
+
return func(i, j int) { is[i], is[j] = is[j], is[i] }
|
| 57 |
+
case 2:
|
| 58 |
+
is := *(*[]int16)(v.ptr)
|
| 59 |
+
return func(i, j int) { is[i], is[j] = is[j], is[i] }
|
| 60 |
+
case 1:
|
| 61 |
+
is := *(*[]int8)(v.ptr)
|
| 62 |
+
return func(i, j int) { is[i], is[j] = is[j], is[i] }
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
s := (*unsafeheader.Slice)(v.ptr)
|
| 67 |
+
tmp := unsafe_New(typ) // swap scratch space
|
| 68 |
+
|
| 69 |
+
return func(i, j int) {
|
| 70 |
+
if uint(i) >= uint(s.Len) || uint(j) >= uint(s.Len) {
|
| 71 |
+
panic("reflect: slice index out of range")
|
| 72 |
+
}
|
| 73 |
+
val1 := arrayAt(s.Data, i, size, "i < s.Len")
|
| 74 |
+
val2 := arrayAt(s.Data, j, size, "j < s.Len")
|
| 75 |
+
typedmemmove(typ, tmp, val1)
|
| 76 |
+
typedmemmove(typ, val1, val2)
|
| 77 |
+
typedmemmove(typ, val2, tmp)
|
| 78 |
+
}
|
| 79 |
+
}
|
go/src/reflect/tostring_test.go
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 |
+
// Formatting of reflection types and values for debugging.
|
| 6 |
+
// Not defined as methods so they do not need to be linked into most binaries;
|
| 7 |
+
// the functions are not used by the library itself, only in tests.
|
| 8 |
+
|
| 9 |
+
package reflect_test
|
| 10 |
+
|
| 11 |
+
import (
|
| 12 |
+
. "reflect"
|
| 13 |
+
"strconv"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
// valueToString returns a textual representation of the reflection value val.
|
| 17 |
+
// For debugging only.
|
| 18 |
+
func valueToString(val Value) string {
|
| 19 |
+
var str string
|
| 20 |
+
if !val.IsValid() {
|
| 21 |
+
return "<zero Value>"
|
| 22 |
+
}
|
| 23 |
+
typ := val.Type()
|
| 24 |
+
switch val.Kind() {
|
| 25 |
+
case Int, Int8, Int16, Int32, Int64:
|
| 26 |
+
return strconv.FormatInt(val.Int(), 10)
|
| 27 |
+
case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
|
| 28 |
+
return strconv.FormatUint(val.Uint(), 10)
|
| 29 |
+
case Float32, Float64:
|
| 30 |
+
return strconv.FormatFloat(val.Float(), 'g', -1, 64)
|
| 31 |
+
case Complex64, Complex128:
|
| 32 |
+
c := val.Complex()
|
| 33 |
+
return strconv.FormatFloat(real(c), 'g', -1, 64) + "+" + strconv.FormatFloat(imag(c), 'g', -1, 64) + "i"
|
| 34 |
+
case String:
|
| 35 |
+
return val.String()
|
| 36 |
+
case Bool:
|
| 37 |
+
if val.Bool() {
|
| 38 |
+
return "true"
|
| 39 |
+
} else {
|
| 40 |
+
return "false"
|
| 41 |
+
}
|
| 42 |
+
case Pointer:
|
| 43 |
+
v := val
|
| 44 |
+
str = typ.String() + "("
|
| 45 |
+
if v.IsNil() {
|
| 46 |
+
str += "0"
|
| 47 |
+
} else {
|
| 48 |
+
str += "&" + valueToString(v.Elem())
|
| 49 |
+
}
|
| 50 |
+
str += ")"
|
| 51 |
+
return str
|
| 52 |
+
case Array, Slice:
|
| 53 |
+
v := val
|
| 54 |
+
str += typ.String()
|
| 55 |
+
str += "{"
|
| 56 |
+
for i := 0; i < v.Len(); i++ {
|
| 57 |
+
if i > 0 {
|
| 58 |
+
str += ", "
|
| 59 |
+
}
|
| 60 |
+
str += valueToString(v.Index(i))
|
| 61 |
+
}
|
| 62 |
+
str += "}"
|
| 63 |
+
return str
|
| 64 |
+
case Map:
|
| 65 |
+
t := typ
|
| 66 |
+
str = t.String()
|
| 67 |
+
str += "{"
|
| 68 |
+
str += "<can't iterate on maps>"
|
| 69 |
+
str += "}"
|
| 70 |
+
return str
|
| 71 |
+
case Chan:
|
| 72 |
+
str = typ.String()
|
| 73 |
+
return str
|
| 74 |
+
case Struct:
|
| 75 |
+
t := typ
|
| 76 |
+
v := val
|
| 77 |
+
str += t.String()
|
| 78 |
+
str += "{"
|
| 79 |
+
for i, n := 0, v.NumField(); i < n; i++ {
|
| 80 |
+
if i > 0 {
|
| 81 |
+
str += ", "
|
| 82 |
+
}
|
| 83 |
+
str += valueToString(v.Field(i))
|
| 84 |
+
}
|
| 85 |
+
str += "}"
|
| 86 |
+
return str
|
| 87 |
+
case Interface:
|
| 88 |
+
return typ.String() + "(" + valueToString(val.Elem()) + ")"
|
| 89 |
+
case Func:
|
| 90 |
+
v := val
|
| 91 |
+
return typ.String() + "(" + strconv.FormatUint(uint64(v.Pointer()), 10) + ")"
|
| 92 |
+
default:
|
| 93 |
+
panic("valueToString: can't print type " + typ.String())
|
| 94 |
+
}
|
| 95 |
+
}
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 reflect implements run-time reflection, allowing a program to
|
| 6 |
+
// manipulate objects with arbitrary types. The typical use is to take a value
|
| 7 |
+
// with static type interface{} and extract its dynamic type information by
|
| 8 |
+
// calling TypeOf, which returns a Type.
|
| 9 |
+
//
|
| 10 |
+
// A call to ValueOf returns a Value representing the run-time data.
|
| 11 |
+
// Zero takes a Type and returns a Value representing a zero value
|
| 12 |
+
// for that type.
|
| 13 |
+
//
|
| 14 |
+
// See "The Laws of Reflection" for an introduction to reflection in Go:
|
| 15 |
+
// https://golang.org/doc/articles/laws_of_reflection.html
|
| 16 |
+
package reflect
|
| 17 |
+
|
| 18 |
+
import (
|
| 19 |
+
"internal/abi"
|
| 20 |
+
"internal/goarch"
|
| 21 |
+
"iter"
|
| 22 |
+
"runtime"
|
| 23 |
+
"strconv"
|
| 24 |
+
"sync"
|
| 25 |
+
"unicode"
|
| 26 |
+
"unicode/utf8"
|
| 27 |
+
"unsafe"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
// Type is the representation of a Go type.
|
| 31 |
+
//
|
| 32 |
+
// Not all methods apply to all kinds of types. Restrictions,
|
| 33 |
+
// if any, are noted in the documentation for each method.
|
| 34 |
+
// Use the Kind method to find out the kind of type before
|
| 35 |
+
// calling kind-specific methods. Calling a method
|
| 36 |
+
// inappropriate to the kind of type causes a run-time panic.
|
| 37 |
+
//
|
| 38 |
+
// Type values are comparable, such as with the == operator,
|
| 39 |
+
// so they can be used as map keys.
|
| 40 |
+
// Two Type values are equal if they represent identical types.
|
| 41 |
+
type Type interface {
|
| 42 |
+
// Methods applicable to all types.
|
| 43 |
+
|
| 44 |
+
// Align returns the alignment in bytes of a value of
|
| 45 |
+
// this type when allocated in memory.
|
| 46 |
+
Align() int
|
| 47 |
+
|
| 48 |
+
// FieldAlign returns the alignment in bytes of a value of
|
| 49 |
+
// this type when used as a field in a struct.
|
| 50 |
+
FieldAlign() int
|
| 51 |
+
|
| 52 |
+
// Method returns the i'th method in the type's method set.
|
| 53 |
+
// It panics if i is not in the range [0, NumMethod()).
|
| 54 |
+
//
|
| 55 |
+
// For a non-interface type T or *T, the returned Method's Type and Func
|
| 56 |
+
// fields describe a function whose first argument is the receiver,
|
| 57 |
+
// and only exported methods are accessible.
|
| 58 |
+
//
|
| 59 |
+
// For an interface type, the returned Method's Type field gives the
|
| 60 |
+
// method signature, without a receiver, and the Func field is nil.
|
| 61 |
+
//
|
| 62 |
+
// Methods are sorted in lexicographic order.
|
| 63 |
+
//
|
| 64 |
+
// Calling this method will force the linker to retain all exported methods in all packages.
|
| 65 |
+
// This may make the executable binary larger but will not affect execution time.
|
| 66 |
+
Method(int) Method
|
| 67 |
+
|
| 68 |
+
// Methods returns an iterator over each method in the type's method set. The sequence is
|
| 69 |
+
// equivalent to calling Method successively for each index i in the range [0, NumMethod()).
|
| 70 |
+
Methods() iter.Seq[Method]
|
| 71 |
+
|
| 72 |
+
// MethodByName returns the method with that name in the type's
|
| 73 |
+
// method set and a boolean indicating if the method was found.
|
| 74 |
+
//
|
| 75 |
+
// For a non-interface type T or *T, the returned Method's Type and Func
|
| 76 |
+
// fields describe a function whose first argument is the receiver.
|
| 77 |
+
//
|
| 78 |
+
// For an interface type, the returned Method's Type field gives the
|
| 79 |
+
// method signature, without a receiver, and the Func field is nil.
|
| 80 |
+
//
|
| 81 |
+
// Calling this method will cause the linker to retain all methods with this name in all packages.
|
| 82 |
+
// If the linker can't determine the name, it will retain all exported methods.
|
| 83 |
+
// This may make the executable binary larger but will not affect execution time.
|
| 84 |
+
MethodByName(string) (Method, bool)
|
| 85 |
+
|
| 86 |
+
// NumMethod returns the number of methods accessible using Method.
|
| 87 |
+
//
|
| 88 |
+
// For a non-interface type, it returns the number of exported methods.
|
| 89 |
+
//
|
| 90 |
+
// For an interface type, it returns the number of exported and unexported methods.
|
| 91 |
+
NumMethod() int
|
| 92 |
+
|
| 93 |
+
// Name returns the type's name within its package for a defined type.
|
| 94 |
+
// For other (non-defined) types it returns the empty string.
|
| 95 |
+
Name() string
|
| 96 |
+
|
| 97 |
+
// PkgPath returns a defined type's package path, that is, the import path
|
| 98 |
+
// that uniquely identifies the package, such as "encoding/base64".
|
| 99 |
+
// If the type was predeclared (string, error) or not defined (*T, struct{},
|
| 100 |
+
// []int, or A where A is an alias for a non-defined type), the package path
|
| 101 |
+
// will be the empty string.
|
| 102 |
+
PkgPath() string
|
| 103 |
+
|
| 104 |
+
// Size returns the number of bytes needed to store
|
| 105 |
+
// a value of the given type; it is analogous to unsafe.Sizeof.
|
| 106 |
+
Size() uintptr
|
| 107 |
+
|
| 108 |
+
// String returns a string representation of the type.
|
| 109 |
+
// The string representation may use shortened package names
|
| 110 |
+
// (e.g., base64 instead of "encoding/base64") and is not
|
| 111 |
+
// guaranteed to be unique among types. To test for type identity,
|
| 112 |
+
// compare the Types directly.
|
| 113 |
+
String() string
|
| 114 |
+
|
| 115 |
+
// Kind returns the specific kind of this type.
|
| 116 |
+
Kind() Kind
|
| 117 |
+
|
| 118 |
+
// Implements reports whether the type implements the interface type u.
|
| 119 |
+
Implements(u Type) bool
|
| 120 |
+
|
| 121 |
+
// AssignableTo reports whether a value of the type is assignable to type u.
|
| 122 |
+
AssignableTo(u Type) bool
|
| 123 |
+
|
| 124 |
+
// ConvertibleTo reports whether a value of the type is convertible to type u.
|
| 125 |
+
// Even if ConvertibleTo returns true, the conversion may still panic.
|
| 126 |
+
// For example, a slice of type []T is convertible to *[N]T,
|
| 127 |
+
// but the conversion will panic if its length is less than N.
|
| 128 |
+
ConvertibleTo(u Type) bool
|
| 129 |
+
|
| 130 |
+
// Comparable reports whether values of this type are comparable.
|
| 131 |
+
// Even if Comparable returns true, the comparison may still panic.
|
| 132 |
+
// For example, values of interface type are comparable,
|
| 133 |
+
// but the comparison will panic if their dynamic type is not comparable.
|
| 134 |
+
Comparable() bool
|
| 135 |
+
|
| 136 |
+
// Methods applicable only to some types, depending on Kind.
|
| 137 |
+
// The methods allowed for each kind are:
|
| 138 |
+
//
|
| 139 |
+
// Int*, Uint*, Float*, Complex*: Bits
|
| 140 |
+
// Array: Elem, Len
|
| 141 |
+
// Chan: ChanDir, Elem
|
| 142 |
+
// Func: In, NumIn, Out, NumOut, IsVariadic.
|
| 143 |
+
// Map: Key, Elem
|
| 144 |
+
// Pointer: Elem
|
| 145 |
+
// Slice: Elem
|
| 146 |
+
// Struct: Field, FieldByIndex, FieldByName, FieldByNameFunc, NumField
|
| 147 |
+
|
| 148 |
+
// Bits returns the size of the type in bits.
|
| 149 |
+
// It panics if the type's Kind is not one of the
|
| 150 |
+
// sized or unsized Int, Uint, Float, or Complex kinds.
|
| 151 |
+
Bits() int
|
| 152 |
+
|
| 153 |
+
// ChanDir returns a channel type's direction.
|
| 154 |
+
// It panics if the type's Kind is not Chan.
|
| 155 |
+
ChanDir() ChanDir
|
| 156 |
+
|
| 157 |
+
// IsVariadic reports whether a function type's final input parameter
|
| 158 |
+
// is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's
|
| 159 |
+
// implicit actual type []T.
|
| 160 |
+
//
|
| 161 |
+
// For concreteness, if t represents func(x int, y ... float64), then
|
| 162 |
+
//
|
| 163 |
+
// t.NumIn() == 2
|
| 164 |
+
// t.In(0) is the reflect.Type for "int"
|
| 165 |
+
// t.In(1) is the reflect.Type for "[]float64"
|
| 166 |
+
// t.IsVariadic() == true
|
| 167 |
+
//
|
| 168 |
+
// IsVariadic panics if the type's Kind is not Func.
|
| 169 |
+
IsVariadic() bool
|
| 170 |
+
|
| 171 |
+
// Elem returns a type's element type.
|
| 172 |
+
// It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
|
| 173 |
+
Elem() Type
|
| 174 |
+
|
| 175 |
+
// Field returns a struct type's i'th field.
|
| 176 |
+
// It panics if the type's Kind is not Struct.
|
| 177 |
+
// It panics if i is not in the range [0, NumField()).
|
| 178 |
+
Field(i int) StructField
|
| 179 |
+
|
| 180 |
+
// Fields returns an iterator over each struct field for struct type t. The sequence is
|
| 181 |
+
// equivalent to calling Field successively for each index i in the range [0, NumField()).
|
| 182 |
+
// It panics if the type's Kind is not Struct.
|
| 183 |
+
Fields() iter.Seq[StructField]
|
| 184 |
+
|
| 185 |
+
// FieldByIndex returns the nested field corresponding
|
| 186 |
+
// to the index sequence. It is equivalent to calling Field
|
| 187 |
+
// successively for each index i.
|
| 188 |
+
// It panics if the type's Kind is not Struct.
|
| 189 |
+
FieldByIndex(index []int) StructField
|
| 190 |
+
|
| 191 |
+
// FieldByName returns the struct field with the given name
|
| 192 |
+
// and a boolean indicating if the field was found.
|
| 193 |
+
// If the returned field is promoted from an embedded struct,
|
| 194 |
+
// then Offset in the returned StructField is the offset in
|
| 195 |
+
// the embedded struct.
|
| 196 |
+
FieldByName(name string) (StructField, bool)
|
| 197 |
+
|
| 198 |
+
// FieldByNameFunc returns the struct field with a name
|
| 199 |
+
// that satisfies the match function and a boolean indicating if
|
| 200 |
+
// the field was found.
|
| 201 |
+
//
|
| 202 |
+
// FieldByNameFunc considers the fields in the struct itself
|
| 203 |
+
// and then the fields in any embedded structs, in breadth first order,
|
| 204 |
+
// stopping at the shallowest nesting depth containing one or more
|
| 205 |
+
// fields satisfying the match function. If multiple fields at that depth
|
| 206 |
+
// satisfy the match function, they cancel each other
|
| 207 |
+
// and FieldByNameFunc returns no match.
|
| 208 |
+
// This behavior mirrors Go's handling of name lookup in
|
| 209 |
+
// structs containing embedded fields.
|
| 210 |
+
//
|
| 211 |
+
// If the returned field is promoted from an embedded struct,
|
| 212 |
+
// then Offset in the returned StructField is the offset in
|
| 213 |
+
// the embedded struct.
|
| 214 |
+
FieldByNameFunc(match func(string) bool) (StructField, bool)
|
| 215 |
+
|
| 216 |
+
// In returns the type of a function type's i'th input parameter.
|
| 217 |
+
// It panics if the type's Kind is not Func.
|
| 218 |
+
// It panics if i is not in the range [0, NumIn()).
|
| 219 |
+
In(i int) Type
|
| 220 |
+
|
| 221 |
+
// Ins returns an iterator over each input parameter of function type t. The sequence
|
| 222 |
+
// is equivalent to calling In successively for each index i in the range [0, NumIn()).
|
| 223 |
+
// It panics if the type's Kind is not Func.
|
| 224 |
+
Ins() iter.Seq[Type]
|
| 225 |
+
|
| 226 |
+
// Key returns a map type's key type.
|
| 227 |
+
// It panics if the type's Kind is not Map.
|
| 228 |
+
Key() Type
|
| 229 |
+
|
| 230 |
+
// Len returns an array type's length.
|
| 231 |
+
// It panics if the type's Kind is not Array.
|
| 232 |
+
Len() int
|
| 233 |
+
|
| 234 |
+
// NumField returns a struct type's field count.
|
| 235 |
+
// It panics if the type's Kind is not Struct.
|
| 236 |
+
NumField() int
|
| 237 |
+
|
| 238 |
+
// NumIn returns a function type's input parameter count.
|
| 239 |
+
// It panics if the type's Kind is not Func.
|
| 240 |
+
NumIn() int
|
| 241 |
+
|
| 242 |
+
// NumOut returns a function type's output parameter count.
|
| 243 |
+
// It panics if the type's Kind is not Func.
|
| 244 |
+
NumOut() int
|
| 245 |
+
|
| 246 |
+
// Out returns the type of a function type's i'th output parameter.
|
| 247 |
+
// It panics if the type's Kind is not Func.
|
| 248 |
+
// It panics if i is not in the range [0, NumOut()).
|
| 249 |
+
Out(i int) Type
|
| 250 |
+
|
| 251 |
+
// Outs returns an iterator over each output parameter of function type t. The sequence
|
| 252 |
+
// is equivalent to calling Out successively for each index i in the range [0, NumOut()).
|
| 253 |
+
// It panics if the type's Kind is not Func.
|
| 254 |
+
Outs() iter.Seq[Type]
|
| 255 |
+
|
| 256 |
+
// OverflowComplex reports whether the complex128 x cannot be represented by type t.
|
| 257 |
+
// It panics if t's Kind is not Complex64 or Complex128.
|
| 258 |
+
OverflowComplex(x complex128) bool
|
| 259 |
+
|
| 260 |
+
// OverflowFloat reports whether the float64 x cannot be represented by type t.
|
| 261 |
+
// It panics if t's Kind is not Float32 or Float64.
|
| 262 |
+
OverflowFloat(x float64) bool
|
| 263 |
+
|
| 264 |
+
// OverflowInt reports whether the int64 x cannot be represented by type t.
|
| 265 |
+
// It panics if t's Kind is not Int, Int8, Int16, Int32, or Int64.
|
| 266 |
+
OverflowInt(x int64) bool
|
| 267 |
+
|
| 268 |
+
// OverflowUint reports whether the uint64 x cannot be represented by type t.
|
| 269 |
+
// It panics if t's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
|
| 270 |
+
OverflowUint(x uint64) bool
|
| 271 |
+
|
| 272 |
+
// CanSeq reports whether a [Value] with this type can be iterated over using [Value.Seq].
|
| 273 |
+
CanSeq() bool
|
| 274 |
+
|
| 275 |
+
// CanSeq2 reports whether a [Value] with this type can be iterated over using [Value.Seq2].
|
| 276 |
+
CanSeq2() bool
|
| 277 |
+
|
| 278 |
+
common() *abi.Type
|
| 279 |
+
uncommon() *uncommonType
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
// BUG(rsc): FieldByName and related functions consider struct field names to be equal
|
| 283 |
+
// if the names are equal, even if they are unexported names originating
|
| 284 |
+
// in different packages. The practical effect of this is that the result of
|
| 285 |
+
// t.FieldByName("x") is not well defined if the struct type t contains
|
| 286 |
+
// multiple fields named x (embedded from different packages).
|
| 287 |
+
// FieldByName may return one of the fields named x or may report that there are none.
|
| 288 |
+
// See https://golang.org/issue/4876 for more details.
|
| 289 |
+
|
| 290 |
+
/*
|
| 291 |
+
* These data structures are known to the compiler (../cmd/compile/internal/reflectdata/reflect.go).
|
| 292 |
+
* A few are known to ../runtime/type.go to convey to debuggers.
|
| 293 |
+
* They are also known to ../internal/abi/type.go.
|
| 294 |
+
*/
|
| 295 |
+
|
| 296 |
+
// A Kind represents the specific kind of type that a [Type] represents.
|
| 297 |
+
// The zero Kind is not a valid kind.
|
| 298 |
+
type Kind uint
|
| 299 |
+
|
| 300 |
+
const (
|
| 301 |
+
Invalid Kind = iota
|
| 302 |
+
Bool
|
| 303 |
+
Int
|
| 304 |
+
Int8
|
| 305 |
+
Int16
|
| 306 |
+
Int32
|
| 307 |
+
Int64
|
| 308 |
+
Uint
|
| 309 |
+
Uint8
|
| 310 |
+
Uint16
|
| 311 |
+
Uint32
|
| 312 |
+
Uint64
|
| 313 |
+
Uintptr
|
| 314 |
+
Float32
|
| 315 |
+
Float64
|
| 316 |
+
Complex64
|
| 317 |
+
Complex128
|
| 318 |
+
Array
|
| 319 |
+
Chan
|
| 320 |
+
Func
|
| 321 |
+
Interface
|
| 322 |
+
Map
|
| 323 |
+
Pointer
|
| 324 |
+
Slice
|
| 325 |
+
String
|
| 326 |
+
Struct
|
| 327 |
+
UnsafePointer
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
// Ptr is the old name for the [Pointer] kind.
|
| 331 |
+
//
|
| 332 |
+
//go:fix inline
|
| 333 |
+
const Ptr = Pointer
|
| 334 |
+
|
| 335 |
+
// uncommonType is present only for defined types or types with methods
|
| 336 |
+
// (if T is a defined type, the uncommonTypes for T and *T have methods).
|
| 337 |
+
// When present, the uncommonType struct immediately follows the
|
| 338 |
+
// abi.Type struct in memory.
|
| 339 |
+
// The abi.TFlagUncommon indicates the presence of uncommonType.
|
| 340 |
+
// Using an optional struct reduces the overall size required
|
| 341 |
+
// to describe a non-defined type with no methods.
|
| 342 |
+
type uncommonType = abi.UncommonType
|
| 343 |
+
|
| 344 |
+
// Embed this type to get common/uncommon
|
| 345 |
+
type common struct {
|
| 346 |
+
abi.Type
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
// rtype is the common implementation of most values.
|
| 350 |
+
// It is embedded in other struct types.
|
| 351 |
+
type rtype struct {
|
| 352 |
+
t abi.Type
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
func (t *rtype) common() *abi.Type {
|
| 356 |
+
return &t.t
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
func (t *rtype) uncommon() *abi.UncommonType {
|
| 360 |
+
return t.t.Uncommon()
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
type aNameOff = abi.NameOff
|
| 364 |
+
type aTypeOff = abi.TypeOff
|
| 365 |
+
type aTextOff = abi.TextOff
|
| 366 |
+
|
| 367 |
+
// ChanDir represents a channel type's direction.
|
| 368 |
+
type ChanDir int
|
| 369 |
+
|
| 370 |
+
const (
|
| 371 |
+
RecvDir ChanDir = 1 << iota // <-chan
|
| 372 |
+
SendDir // chan<-
|
| 373 |
+
BothDir = RecvDir | SendDir // chan
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
// arrayType represents a fixed array type.
|
| 377 |
+
type arrayType = abi.ArrayType
|
| 378 |
+
|
| 379 |
+
// chanType represents a channel type.
|
| 380 |
+
type chanType = abi.ChanType
|
| 381 |
+
|
| 382 |
+
// funcType represents a function type.
|
| 383 |
+
//
|
| 384 |
+
// A *rtype for each in and out parameter is stored in an array that
|
| 385 |
+
// directly follows the funcType (and possibly its uncommonType). So
|
| 386 |
+
// a function type with one method, one input, and one output is:
|
| 387 |
+
//
|
| 388 |
+
// struct {
|
| 389 |
+
// funcType
|
| 390 |
+
// uncommonType
|
| 391 |
+
// [2]*rtype // [0] is in, [1] is out
|
| 392 |
+
// }
|
| 393 |
+
type funcType = abi.FuncType
|
| 394 |
+
|
| 395 |
+
// interfaceType represents an interface type.
|
| 396 |
+
type interfaceType struct {
|
| 397 |
+
abi.InterfaceType // can embed directly because not a public type.
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
func (t *interfaceType) nameOff(off aNameOff) abi.Name {
|
| 401 |
+
return toRType(&t.Type).nameOff(off)
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
func nameOffFor(t *abi.Type, off aNameOff) abi.Name {
|
| 405 |
+
return toRType(t).nameOff(off)
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
func typeOffFor(t *abi.Type, off aTypeOff) *abi.Type {
|
| 409 |
+
return toRType(t).typeOff(off)
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
func (t *interfaceType) typeOff(off aTypeOff) *abi.Type {
|
| 413 |
+
return toRType(&t.Type).typeOff(off)
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
func (t *interfaceType) common() *abi.Type {
|
| 417 |
+
return &t.Type
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
func (t *interfaceType) uncommon() *abi.UncommonType {
|
| 421 |
+
return t.Uncommon()
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// ptrType represents a pointer type.
|
| 425 |
+
type ptrType struct {
|
| 426 |
+
abi.PtrType
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
// sliceType represents a slice type.
|
| 430 |
+
type sliceType struct {
|
| 431 |
+
abi.SliceType
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
// Struct field
|
| 435 |
+
type structField = abi.StructField
|
| 436 |
+
|
| 437 |
+
// structType represents a struct type.
|
| 438 |
+
type structType struct {
|
| 439 |
+
abi.StructType
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
func pkgPath(n abi.Name) string {
|
| 443 |
+
if n.Bytes == nil || *n.DataChecked(0, "name flag field")&(1<<2) == 0 {
|
| 444 |
+
return ""
|
| 445 |
+
}
|
| 446 |
+
i, l := n.ReadVarint(1)
|
| 447 |
+
off := 1 + i + l
|
| 448 |
+
if n.HasTag() {
|
| 449 |
+
i2, l2 := n.ReadVarint(off)
|
| 450 |
+
off += i2 + l2
|
| 451 |
+
}
|
| 452 |
+
var nameOff int32
|
| 453 |
+
// Note that this field may not be aligned in memory,
|
| 454 |
+
// so we cannot use a direct int32 assignment here.
|
| 455 |
+
copy((*[4]byte)(unsafe.Pointer(&nameOff))[:], (*[4]byte)(unsafe.Pointer(n.DataChecked(off, "name offset field")))[:])
|
| 456 |
+
pkgPathName := abi.Name{Bytes: (*byte)(resolveTypeOff(unsafe.Pointer(n.Bytes), nameOff))}
|
| 457 |
+
return pkgPathName.Name()
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
func newName(n, tag string, exported, embedded bool) abi.Name {
|
| 461 |
+
return abi.NewName(n, tag, exported, embedded)
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
/*
|
| 465 |
+
* The compiler knows the exact layout of all the data structures above.
|
| 466 |
+
* The compiler does not know about the data structures and methods below.
|
| 467 |
+
*/
|
| 468 |
+
|
| 469 |
+
// Method represents a single method.
|
| 470 |
+
type Method struct {
|
| 471 |
+
// Name is the method name.
|
| 472 |
+
Name string
|
| 473 |
+
|
| 474 |
+
// PkgPath is the package path that qualifies a lower case (unexported)
|
| 475 |
+
// method name. It is empty for upper case (exported) method names.
|
| 476 |
+
// The combination of PkgPath and Name uniquely identifies a method
|
| 477 |
+
// in a method set.
|
| 478 |
+
// See https://golang.org/ref/spec#Uniqueness_of_identifiers
|
| 479 |
+
PkgPath string
|
| 480 |
+
|
| 481 |
+
Type Type // method type
|
| 482 |
+
Func Value // func with receiver as first argument
|
| 483 |
+
Index int // index for Type.Method
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
// IsExported reports whether the method is exported.
|
| 487 |
+
func (m Method) IsExported() bool {
|
| 488 |
+
return m.PkgPath == ""
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
// String returns the name of k.
|
| 492 |
+
func (k Kind) String() string {
|
| 493 |
+
if uint(k) < uint(len(kindNames)) {
|
| 494 |
+
return kindNames[uint(k)]
|
| 495 |
+
}
|
| 496 |
+
return "kind" + strconv.Itoa(int(k))
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
var kindNames = []string{
|
| 500 |
+
Invalid: "invalid",
|
| 501 |
+
Bool: "bool",
|
| 502 |
+
Int: "int",
|
| 503 |
+
Int8: "int8",
|
| 504 |
+
Int16: "int16",
|
| 505 |
+
Int32: "int32",
|
| 506 |
+
Int64: "int64",
|
| 507 |
+
Uint: "uint",
|
| 508 |
+
Uint8: "uint8",
|
| 509 |
+
Uint16: "uint16",
|
| 510 |
+
Uint32: "uint32",
|
| 511 |
+
Uint64: "uint64",
|
| 512 |
+
Uintptr: "uintptr",
|
| 513 |
+
Float32: "float32",
|
| 514 |
+
Float64: "float64",
|
| 515 |
+
Complex64: "complex64",
|
| 516 |
+
Complex128: "complex128",
|
| 517 |
+
Array: "array",
|
| 518 |
+
Chan: "chan",
|
| 519 |
+
Func: "func",
|
| 520 |
+
Interface: "interface",
|
| 521 |
+
Map: "map",
|
| 522 |
+
Pointer: "ptr",
|
| 523 |
+
Slice: "slice",
|
| 524 |
+
String: "string",
|
| 525 |
+
Struct: "struct",
|
| 526 |
+
UnsafePointer: "unsafe.Pointer",
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
// resolveNameOff resolves a name offset from a base pointer.
|
| 530 |
+
// The (*rtype).nameOff method is a convenience wrapper for this function.
|
| 531 |
+
// Implemented in the runtime package.
|
| 532 |
+
//
|
| 533 |
+
//go:noescape
|
| 534 |
+
func resolveNameOff(ptrInModule unsafe.Pointer, off int32) unsafe.Pointer
|
| 535 |
+
|
| 536 |
+
// resolveTypeOff resolves an *rtype offset from a base type.
|
| 537 |
+
// The (*rtype).typeOff method is a convenience wrapper for this function.
|
| 538 |
+
// Implemented in the runtime package.
|
| 539 |
+
//
|
| 540 |
+
//go:noescape
|
| 541 |
+
func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer
|
| 542 |
+
|
| 543 |
+
// resolveTextOff resolves a function pointer offset from a base type.
|
| 544 |
+
// The (*rtype).textOff method is a convenience wrapper for this function.
|
| 545 |
+
// Implemented in the runtime package.
|
| 546 |
+
//
|
| 547 |
+
//go:noescape
|
| 548 |
+
func resolveTextOff(rtype unsafe.Pointer, off int32) unsafe.Pointer
|
| 549 |
+
|
| 550 |
+
// addReflectOff adds a pointer to the reflection lookup map in the runtime.
|
| 551 |
+
// It returns a new ID that can be used as a typeOff or textOff, and will
|
| 552 |
+
// be resolved correctly. Implemented in the runtime package.
|
| 553 |
+
//
|
| 554 |
+
// addReflectOff should be an internal detail,
|
| 555 |
+
// but widely used packages access it using linkname.
|
| 556 |
+
// Notable members of the hall of shame include:
|
| 557 |
+
// - github.com/goplus/reflectx
|
| 558 |
+
//
|
| 559 |
+
// Do not remove or change the type signature.
|
| 560 |
+
// See go.dev/issue/67401.
|
| 561 |
+
//
|
| 562 |
+
//go:linkname addReflectOff
|
| 563 |
+
//go:noescape
|
| 564 |
+
func addReflectOff(ptr unsafe.Pointer) int32
|
| 565 |
+
|
| 566 |
+
// resolveReflectName adds a name to the reflection lookup map in the runtime.
|
| 567 |
+
// It returns a new nameOff that can be used to refer to the pointer.
|
| 568 |
+
func resolveReflectName(n abi.Name) aNameOff {
|
| 569 |
+
return aNameOff(addReflectOff(unsafe.Pointer(n.Bytes)))
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
// resolveReflectType adds a *rtype to the reflection lookup map in the runtime.
|
| 573 |
+
// It returns a new typeOff that can be used to refer to the pointer.
|
| 574 |
+
func resolveReflectType(t *abi.Type) aTypeOff {
|
| 575 |
+
return aTypeOff(addReflectOff(unsafe.Pointer(t)))
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
// resolveReflectText adds a function pointer to the reflection lookup map in
|
| 579 |
+
// the runtime. It returns a new textOff that can be used to refer to the
|
| 580 |
+
// pointer.
|
| 581 |
+
func resolveReflectText(ptr unsafe.Pointer) aTextOff {
|
| 582 |
+
return aTextOff(addReflectOff(ptr))
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
func (t *rtype) nameOff(off aNameOff) abi.Name {
|
| 586 |
+
return abi.Name{Bytes: (*byte)(resolveNameOff(unsafe.Pointer(t), int32(off)))}
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
func (t *rtype) typeOff(off aTypeOff) *abi.Type {
|
| 590 |
+
return (*abi.Type)(resolveTypeOff(unsafe.Pointer(t), int32(off)))
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
func (t *rtype) textOff(off aTextOff) unsafe.Pointer {
|
| 594 |
+
return resolveTextOff(unsafe.Pointer(t), int32(off))
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
func textOffFor(t *abi.Type, off aTextOff) unsafe.Pointer {
|
| 598 |
+
return toRType(t).textOff(off)
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
func (t *rtype) String() string {
|
| 602 |
+
s := t.nameOff(t.t.Str).Name()
|
| 603 |
+
if t.t.TFlag&abi.TFlagExtraStar != 0 {
|
| 604 |
+
return s[1:]
|
| 605 |
+
}
|
| 606 |
+
return s
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
func (t *rtype) Size() uintptr { return t.t.Size() }
|
| 610 |
+
|
| 611 |
+
func (t *rtype) Bits() int {
|
| 612 |
+
if t == nil {
|
| 613 |
+
panic("reflect: Bits of nil Type")
|
| 614 |
+
}
|
| 615 |
+
k := t.Kind()
|
| 616 |
+
if k < Int || k > Complex128 {
|
| 617 |
+
panic("reflect: Bits of non-arithmetic Type " + t.String())
|
| 618 |
+
}
|
| 619 |
+
return int(t.t.Size_) * 8
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
func (t *rtype) Align() int { return t.t.Align() }
|
| 623 |
+
|
| 624 |
+
func (t *rtype) FieldAlign() int { return t.t.FieldAlign() }
|
| 625 |
+
|
| 626 |
+
func (t *rtype) Kind() Kind { return Kind(t.t.Kind()) }
|
| 627 |
+
|
| 628 |
+
func (t *rtype) exportedMethods() []abi.Method {
|
| 629 |
+
ut := t.uncommon()
|
| 630 |
+
if ut == nil {
|
| 631 |
+
return nil
|
| 632 |
+
}
|
| 633 |
+
return ut.ExportedMethods()
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
func (t *rtype) NumMethod() int {
|
| 637 |
+
if t.Kind() == Interface {
|
| 638 |
+
tt := (*interfaceType)(unsafe.Pointer(t))
|
| 639 |
+
return tt.NumMethod()
|
| 640 |
+
}
|
| 641 |
+
return len(t.exportedMethods())
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
func (t *rtype) Method(i int) (m Method) {
|
| 645 |
+
if t.Kind() == Interface {
|
| 646 |
+
tt := (*interfaceType)(unsafe.Pointer(t))
|
| 647 |
+
return tt.Method(i)
|
| 648 |
+
}
|
| 649 |
+
methods := t.exportedMethods()
|
| 650 |
+
if i < 0 || i >= len(methods) {
|
| 651 |
+
panic("reflect: Method index out of range")
|
| 652 |
+
}
|
| 653 |
+
p := methods[i]
|
| 654 |
+
pname := t.nameOff(p.Name)
|
| 655 |
+
m.Name = pname.Name()
|
| 656 |
+
fl := flag(Func)
|
| 657 |
+
mtyp := t.typeOff(p.Mtyp)
|
| 658 |
+
ft := (*funcType)(unsafe.Pointer(mtyp))
|
| 659 |
+
in := make([]Type, 0, 1+ft.NumIn())
|
| 660 |
+
in = append(in, t)
|
| 661 |
+
for _, arg := range ft.InSlice() {
|
| 662 |
+
in = append(in, toRType(arg))
|
| 663 |
+
}
|
| 664 |
+
out := make([]Type, 0, ft.NumOut())
|
| 665 |
+
for _, ret := range ft.OutSlice() {
|
| 666 |
+
out = append(out, toRType(ret))
|
| 667 |
+
}
|
| 668 |
+
mt := FuncOf(in, out, ft.IsVariadic())
|
| 669 |
+
m.Type = mt
|
| 670 |
+
tfn := t.textOff(p.Tfn)
|
| 671 |
+
fn := unsafe.Pointer(&tfn)
|
| 672 |
+
m.Func = Value{&mt.(*rtype).t, fn, fl}
|
| 673 |
+
|
| 674 |
+
m.Index = i
|
| 675 |
+
return m
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
func (t *rtype) MethodByName(name string) (m Method, ok bool) {
|
| 679 |
+
if t.Kind() == Interface {
|
| 680 |
+
tt := (*interfaceType)(unsafe.Pointer(t))
|
| 681 |
+
return tt.MethodByName(name)
|
| 682 |
+
}
|
| 683 |
+
ut := t.uncommon()
|
| 684 |
+
if ut == nil {
|
| 685 |
+
return Method{}, false
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
methods := ut.ExportedMethods()
|
| 689 |
+
|
| 690 |
+
// We are looking for the first index i where the string becomes >= s.
|
| 691 |
+
// This is a copy of sort.Search, with f(h) replaced by (t.nameOff(methods[h].name).name() >= name).
|
| 692 |
+
i, j := 0, len(methods)
|
| 693 |
+
for i < j {
|
| 694 |
+
h := int(uint(i+j) >> 1) // avoid overflow when computing h
|
| 695 |
+
// i ≤ h < j
|
| 696 |
+
if !(t.nameOff(methods[h].Name).Name() >= name) {
|
| 697 |
+
i = h + 1 // preserves f(i-1) == false
|
| 698 |
+
} else {
|
| 699 |
+
j = h // preserves f(j) == true
|
| 700 |
+
}
|
| 701 |
+
}
|
| 702 |
+
// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
|
| 703 |
+
if i < len(methods) && name == t.nameOff(methods[i].Name).Name() {
|
| 704 |
+
return t.Method(i), true
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
return Method{}, false
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
func (t *rtype) PkgPath() string {
|
| 711 |
+
if t.t.TFlag&abi.TFlagNamed == 0 {
|
| 712 |
+
return ""
|
| 713 |
+
}
|
| 714 |
+
ut := t.uncommon()
|
| 715 |
+
if ut == nil {
|
| 716 |
+
return ""
|
| 717 |
+
}
|
| 718 |
+
return t.nameOff(ut.PkgPath).Name()
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
func pkgPathFor(t *abi.Type) string {
|
| 722 |
+
return toRType(t).PkgPath()
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
func (t *rtype) Name() string {
|
| 726 |
+
if !t.t.HasName() {
|
| 727 |
+
return ""
|
| 728 |
+
}
|
| 729 |
+
s := t.String()
|
| 730 |
+
i := len(s) - 1
|
| 731 |
+
sqBrackets := 0
|
| 732 |
+
for i >= 0 && (s[i] != '.' || sqBrackets != 0) {
|
| 733 |
+
switch s[i] {
|
| 734 |
+
case ']':
|
| 735 |
+
sqBrackets++
|
| 736 |
+
case '[':
|
| 737 |
+
sqBrackets--
|
| 738 |
+
}
|
| 739 |
+
i--
|
| 740 |
+
}
|
| 741 |
+
return s[i+1:]
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
func nameFor(t *abi.Type) string {
|
| 745 |
+
return toRType(t).Name()
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
func (t *rtype) ChanDir() ChanDir {
|
| 749 |
+
if t.Kind() != Chan {
|
| 750 |
+
panic("reflect: ChanDir of non-chan type " + t.String())
|
| 751 |
+
}
|
| 752 |
+
tt := (*abi.ChanType)(unsafe.Pointer(t))
|
| 753 |
+
return ChanDir(tt.Dir)
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
func toRType(t *abi.Type) *rtype {
|
| 757 |
+
return (*rtype)(unsafe.Pointer(t))
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
func elem(t *abi.Type) *abi.Type {
|
| 761 |
+
et := t.Elem()
|
| 762 |
+
if et != nil {
|
| 763 |
+
return et
|
| 764 |
+
}
|
| 765 |
+
panic("reflect: Elem of invalid type " + stringFor(t))
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
func (t *rtype) Elem() Type {
|
| 769 |
+
return toType(elem(t.common()))
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
func (t *rtype) Field(i int) StructField {
|
| 773 |
+
if t.Kind() != Struct {
|
| 774 |
+
panic("reflect: Field of non-struct type " + t.String())
|
| 775 |
+
}
|
| 776 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 777 |
+
return tt.Field(i)
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
func (t *rtype) FieldByIndex(index []int) StructField {
|
| 781 |
+
if t.Kind() != Struct {
|
| 782 |
+
panic("reflect: FieldByIndex of non-struct type " + t.String())
|
| 783 |
+
}
|
| 784 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 785 |
+
return tt.FieldByIndex(index)
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
func (t *rtype) FieldByName(name string) (StructField, bool) {
|
| 789 |
+
if t.Kind() != Struct {
|
| 790 |
+
panic("reflect: FieldByName of non-struct type " + t.String())
|
| 791 |
+
}
|
| 792 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 793 |
+
return tt.FieldByName(name)
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
func (t *rtype) FieldByNameFunc(match func(string) bool) (StructField, bool) {
|
| 797 |
+
if t.Kind() != Struct {
|
| 798 |
+
panic("reflect: FieldByNameFunc of non-struct type " + t.String())
|
| 799 |
+
}
|
| 800 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 801 |
+
return tt.FieldByNameFunc(match)
|
| 802 |
+
}
|
| 803 |
+
|
| 804 |
+
func (t *rtype) Len() int {
|
| 805 |
+
if t.Kind() != Array {
|
| 806 |
+
panic("reflect: Len of non-array type " + t.String())
|
| 807 |
+
}
|
| 808 |
+
tt := (*arrayType)(unsafe.Pointer(t))
|
| 809 |
+
return int(tt.Len)
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
func (t *rtype) NumField() int {
|
| 813 |
+
if t.Kind() != Struct {
|
| 814 |
+
panic("reflect: NumField of non-struct type " + t.String())
|
| 815 |
+
}
|
| 816 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 817 |
+
return len(tt.Fields)
|
| 818 |
+
}
|
| 819 |
+
|
| 820 |
+
func (t *rtype) In(i int) Type {
|
| 821 |
+
if t.Kind() != Func {
|
| 822 |
+
panic("reflect: In of non-func type " + t.String())
|
| 823 |
+
}
|
| 824 |
+
tt := (*abi.FuncType)(unsafe.Pointer(t))
|
| 825 |
+
return toType(tt.InSlice()[i])
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
func (t *rtype) NumIn() int {
|
| 829 |
+
if t.Kind() != Func {
|
| 830 |
+
panic("reflect: NumIn of non-func type " + t.String())
|
| 831 |
+
}
|
| 832 |
+
tt := (*abi.FuncType)(unsafe.Pointer(t))
|
| 833 |
+
return tt.NumIn()
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
func (t *rtype) NumOut() int {
|
| 837 |
+
if t.Kind() != Func {
|
| 838 |
+
panic("reflect: NumOut of non-func type " + t.String())
|
| 839 |
+
}
|
| 840 |
+
tt := (*abi.FuncType)(unsafe.Pointer(t))
|
| 841 |
+
return tt.NumOut()
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
func (t *rtype) Out(i int) Type {
|
| 845 |
+
if t.Kind() != Func {
|
| 846 |
+
panic("reflect: Out of non-func type " + t.String())
|
| 847 |
+
}
|
| 848 |
+
tt := (*abi.FuncType)(unsafe.Pointer(t))
|
| 849 |
+
return toType(tt.OutSlice()[i])
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
func (t *rtype) IsVariadic() bool {
|
| 853 |
+
if t.Kind() != Func {
|
| 854 |
+
panic("reflect: IsVariadic of non-func type " + t.String())
|
| 855 |
+
}
|
| 856 |
+
tt := (*abi.FuncType)(unsafe.Pointer(t))
|
| 857 |
+
return tt.IsVariadic()
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
func (t *rtype) OverflowComplex(x complex128) bool {
|
| 861 |
+
k := t.Kind()
|
| 862 |
+
switch k {
|
| 863 |
+
case Complex64:
|
| 864 |
+
return overflowFloat32(real(x)) || overflowFloat32(imag(x))
|
| 865 |
+
case Complex128:
|
| 866 |
+
return false
|
| 867 |
+
}
|
| 868 |
+
panic("reflect: OverflowComplex of non-complex type " + t.String())
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
func (t *rtype) OverflowFloat(x float64) bool {
|
| 872 |
+
k := t.Kind()
|
| 873 |
+
switch k {
|
| 874 |
+
case Float32:
|
| 875 |
+
return overflowFloat32(x)
|
| 876 |
+
case Float64:
|
| 877 |
+
return false
|
| 878 |
+
}
|
| 879 |
+
panic("reflect: OverflowFloat of non-float type " + t.String())
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
func (t *rtype) OverflowInt(x int64) bool {
|
| 883 |
+
k := t.Kind()
|
| 884 |
+
switch k {
|
| 885 |
+
case Int, Int8, Int16, Int32, Int64:
|
| 886 |
+
bitSize := t.Size() * 8
|
| 887 |
+
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
| 888 |
+
return x != trunc
|
| 889 |
+
}
|
| 890 |
+
panic("reflect: OverflowInt of non-int type " + t.String())
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
func (t *rtype) OverflowUint(x uint64) bool {
|
| 894 |
+
k := t.Kind()
|
| 895 |
+
switch k {
|
| 896 |
+
case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
|
| 897 |
+
bitSize := t.Size() * 8
|
| 898 |
+
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
| 899 |
+
return x != trunc
|
| 900 |
+
}
|
| 901 |
+
panic("reflect: OverflowUint of non-uint type " + t.String())
|
| 902 |
+
}
|
| 903 |
+
|
| 904 |
+
func (t *rtype) CanSeq() bool {
|
| 905 |
+
switch t.Kind() {
|
| 906 |
+
case Int8, Int16, Int32, Int64, Int, Uint8, Uint16, Uint32, Uint64, Uint, Uintptr, Array, Slice, Chan, String, Map:
|
| 907 |
+
return true
|
| 908 |
+
case Func:
|
| 909 |
+
return canRangeFunc(&t.t)
|
| 910 |
+
case Pointer:
|
| 911 |
+
return t.Elem().Kind() == Array
|
| 912 |
+
}
|
| 913 |
+
return false
|
| 914 |
+
}
|
| 915 |
+
|
| 916 |
+
func canRangeFunc(t *abi.Type) bool {
|
| 917 |
+
if t.Kind() != abi.Func {
|
| 918 |
+
return false
|
| 919 |
+
}
|
| 920 |
+
f := t.FuncType()
|
| 921 |
+
if f.InCount != 1 || f.OutCount != 0 {
|
| 922 |
+
return false
|
| 923 |
+
}
|
| 924 |
+
y := f.In(0)
|
| 925 |
+
if y.Kind() != abi.Func {
|
| 926 |
+
return false
|
| 927 |
+
}
|
| 928 |
+
yield := y.FuncType()
|
| 929 |
+
return yield.InCount == 1 && yield.OutCount == 1 && yield.Out(0).Kind() == abi.Bool
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
func (t *rtype) CanSeq2() bool {
|
| 933 |
+
switch t.Kind() {
|
| 934 |
+
case Array, Slice, String, Map:
|
| 935 |
+
return true
|
| 936 |
+
case Func:
|
| 937 |
+
return canRangeFunc2(&t.t)
|
| 938 |
+
case Pointer:
|
| 939 |
+
return t.Elem().Kind() == Array
|
| 940 |
+
}
|
| 941 |
+
return false
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
func canRangeFunc2(t *abi.Type) bool {
|
| 945 |
+
if t.Kind() != abi.Func {
|
| 946 |
+
return false
|
| 947 |
+
}
|
| 948 |
+
f := t.FuncType()
|
| 949 |
+
if f.InCount != 1 || f.OutCount != 0 {
|
| 950 |
+
return false
|
| 951 |
+
}
|
| 952 |
+
y := f.In(0)
|
| 953 |
+
if y.Kind() != abi.Func {
|
| 954 |
+
return false
|
| 955 |
+
}
|
| 956 |
+
yield := y.FuncType()
|
| 957 |
+
return yield.InCount == 2 && yield.OutCount == 1 && yield.Out(0).Kind() == abi.Bool
|
| 958 |
+
}
|
| 959 |
+
|
| 960 |
+
func (t *rtype) Fields() iter.Seq[StructField] {
|
| 961 |
+
if t.Kind() != Struct {
|
| 962 |
+
panic("reflect: Fields of non-struct type " + t.String())
|
| 963 |
+
}
|
| 964 |
+
return func(yield func(StructField) bool) {
|
| 965 |
+
for i := range t.NumField() {
|
| 966 |
+
if !yield(t.Field(i)) {
|
| 967 |
+
return
|
| 968 |
+
}
|
| 969 |
+
}
|
| 970 |
+
}
|
| 971 |
+
}
|
| 972 |
+
|
| 973 |
+
func (t *rtype) Methods() iter.Seq[Method] {
|
| 974 |
+
return func(yield func(Method) bool) {
|
| 975 |
+
for i := range t.NumMethod() {
|
| 976 |
+
if !yield(t.Method(i)) {
|
| 977 |
+
return
|
| 978 |
+
}
|
| 979 |
+
}
|
| 980 |
+
}
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
func (t *rtype) Ins() iter.Seq[Type] {
|
| 984 |
+
if t.Kind() != Func {
|
| 985 |
+
panic("reflect: Ins of non-func type " + t.String())
|
| 986 |
+
}
|
| 987 |
+
return func(yield func(Type) bool) {
|
| 988 |
+
for i := range t.NumIn() {
|
| 989 |
+
if !yield(t.In(i)) {
|
| 990 |
+
return
|
| 991 |
+
}
|
| 992 |
+
}
|
| 993 |
+
}
|
| 994 |
+
}
|
| 995 |
+
|
| 996 |
+
func (t *rtype) Outs() iter.Seq[Type] {
|
| 997 |
+
if t.Kind() != Func {
|
| 998 |
+
panic("reflect: Outs of non-func type " + t.String())
|
| 999 |
+
}
|
| 1000 |
+
return func(yield func(Type) bool) {
|
| 1001 |
+
for i := range t.NumOut() {
|
| 1002 |
+
if !yield(t.Out(i)) {
|
| 1003 |
+
return
|
| 1004 |
+
}
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
}
|
| 1008 |
+
|
| 1009 |
+
// add returns p+x.
|
| 1010 |
+
//
|
| 1011 |
+
// The whySafe string is ignored, so that the function still inlines
|
| 1012 |
+
// as efficiently as p+x, but all call sites should use the string to
|
| 1013 |
+
// record why the addition is safe, which is to say why the addition
|
| 1014 |
+
// does not cause x to advance to the very end of p's allocation
|
| 1015 |
+
// and therefore point incorrectly at the next block in memory.
|
| 1016 |
+
//
|
| 1017 |
+
// add should be an internal detail (and is trivially copyable),
|
| 1018 |
+
// but widely used packages access it using linkname.
|
| 1019 |
+
// Notable members of the hall of shame include:
|
| 1020 |
+
// - github.com/pinpoint-apm/pinpoint-go-agent
|
| 1021 |
+
// - github.com/vmware/govmomi
|
| 1022 |
+
//
|
| 1023 |
+
// Do not remove or change the type signature.
|
| 1024 |
+
// See go.dev/issue/67401.
|
| 1025 |
+
//
|
| 1026 |
+
//go:linkname add
|
| 1027 |
+
func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer {
|
| 1028 |
+
return unsafe.Pointer(uintptr(p) + x)
|
| 1029 |
+
}
|
| 1030 |
+
|
| 1031 |
+
func (d ChanDir) String() string {
|
| 1032 |
+
switch d {
|
| 1033 |
+
case SendDir:
|
| 1034 |
+
return "chan<-"
|
| 1035 |
+
case RecvDir:
|
| 1036 |
+
return "<-chan"
|
| 1037 |
+
case BothDir:
|
| 1038 |
+
return "chan"
|
| 1039 |
+
}
|
| 1040 |
+
return "ChanDir" + strconv.Itoa(int(d))
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
// Method returns the i'th method in the type's method set.
|
| 1044 |
+
func (t *interfaceType) Method(i int) (m Method) {
|
| 1045 |
+
if i < 0 || i >= len(t.Methods) {
|
| 1046 |
+
return
|
| 1047 |
+
}
|
| 1048 |
+
p := &t.Methods[i]
|
| 1049 |
+
pname := t.nameOff(p.Name)
|
| 1050 |
+
m.Name = pname.Name()
|
| 1051 |
+
if !pname.IsExported() {
|
| 1052 |
+
m.PkgPath = pkgPath(pname)
|
| 1053 |
+
if m.PkgPath == "" {
|
| 1054 |
+
m.PkgPath = t.PkgPath.Name()
|
| 1055 |
+
}
|
| 1056 |
+
}
|
| 1057 |
+
m.Type = toType(t.typeOff(p.Typ))
|
| 1058 |
+
m.Index = i
|
| 1059 |
+
return
|
| 1060 |
+
}
|
| 1061 |
+
|
| 1062 |
+
// NumMethod returns the number of interface methods in the type's method set.
|
| 1063 |
+
func (t *interfaceType) NumMethod() int { return len(t.Methods) }
|
| 1064 |
+
|
| 1065 |
+
// MethodByName method with the given name in the type's method set.
|
| 1066 |
+
func (t *interfaceType) MethodByName(name string) (m Method, ok bool) {
|
| 1067 |
+
if t == nil {
|
| 1068 |
+
return
|
| 1069 |
+
}
|
| 1070 |
+
var p *abi.Imethod
|
| 1071 |
+
for i := range t.Methods {
|
| 1072 |
+
p = &t.Methods[i]
|
| 1073 |
+
if t.nameOff(p.Name).Name() == name {
|
| 1074 |
+
return t.Method(i), true
|
| 1075 |
+
}
|
| 1076 |
+
}
|
| 1077 |
+
return
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
// A StructField describes a single field in a struct.
|
| 1081 |
+
type StructField struct {
|
| 1082 |
+
// Name is the field name.
|
| 1083 |
+
Name string
|
| 1084 |
+
|
| 1085 |
+
// PkgPath is the package path that qualifies a lower case (unexported)
|
| 1086 |
+
// field name. It is empty for upper case (exported) field names.
|
| 1087 |
+
// See https://golang.org/ref/spec#Uniqueness_of_identifiers
|
| 1088 |
+
PkgPath string
|
| 1089 |
+
|
| 1090 |
+
Type Type // field type
|
| 1091 |
+
Tag StructTag // field tag string
|
| 1092 |
+
Offset uintptr // offset within struct, in bytes
|
| 1093 |
+
Index []int // index sequence for Type.FieldByIndex
|
| 1094 |
+
Anonymous bool // is an embedded field
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
// IsExported reports whether the field is exported.
|
| 1098 |
+
func (f StructField) IsExported() bool {
|
| 1099 |
+
return f.PkgPath == ""
|
| 1100 |
+
}
|
| 1101 |
+
|
| 1102 |
+
// A StructTag is the tag string in a struct field.
|
| 1103 |
+
//
|
| 1104 |
+
// By convention, tag strings are a concatenation of
|
| 1105 |
+
// optionally space-separated key:"value" pairs.
|
| 1106 |
+
// Each key is a non-empty string consisting of non-control
|
| 1107 |
+
// characters other than space (U+0020 ' '), quote (U+0022 '"'),
|
| 1108 |
+
// and colon (U+003A ':'). Each value is quoted using U+0022 '"'
|
| 1109 |
+
// characters and Go string literal syntax.
|
| 1110 |
+
type StructTag string
|
| 1111 |
+
|
| 1112 |
+
// Get returns the value associated with key in the tag string.
|
| 1113 |
+
// If there is no such key in the tag, Get returns the empty string.
|
| 1114 |
+
// If the tag does not have the conventional format, the value
|
| 1115 |
+
// returned by Get is unspecified. To determine whether a tag is
|
| 1116 |
+
// explicitly set to the empty string, use [StructTag.Lookup].
|
| 1117 |
+
func (tag StructTag) Get(key string) string {
|
| 1118 |
+
v, _ := tag.Lookup(key)
|
| 1119 |
+
return v
|
| 1120 |
+
}
|
| 1121 |
+
|
| 1122 |
+
// Lookup returns the value associated with key in the tag string.
|
| 1123 |
+
// If the key is present in the tag the value (which may be empty)
|
| 1124 |
+
// is returned. Otherwise the returned value will be the empty string.
|
| 1125 |
+
// The ok return value reports whether the value was explicitly set in
|
| 1126 |
+
// the tag string. If the tag does not have the conventional format,
|
| 1127 |
+
// the value returned by Lookup is unspecified.
|
| 1128 |
+
func (tag StructTag) Lookup(key string) (value string, ok bool) {
|
| 1129 |
+
// When modifying this code, also update the validateStructTag code
|
| 1130 |
+
// in cmd/vet/structtag.go.
|
| 1131 |
+
|
| 1132 |
+
for tag != "" {
|
| 1133 |
+
// Skip leading space.
|
| 1134 |
+
i := 0
|
| 1135 |
+
for i < len(tag) && tag[i] == ' ' {
|
| 1136 |
+
i++
|
| 1137 |
+
}
|
| 1138 |
+
tag = tag[i:]
|
| 1139 |
+
if tag == "" {
|
| 1140 |
+
break
|
| 1141 |
+
}
|
| 1142 |
+
|
| 1143 |
+
// Scan to colon. A space, a quote or a control character is a syntax error.
|
| 1144 |
+
// Strictly speaking, control chars include the range [0x7f, 0x9f], not just
|
| 1145 |
+
// [0x00, 0x1f], but in practice, we ignore the multi-byte control characters
|
| 1146 |
+
// as it is simpler to inspect the tag's bytes than the tag's runes.
|
| 1147 |
+
i = 0
|
| 1148 |
+
for i < len(tag) && tag[i] > ' ' && tag[i] != ':' && tag[i] != '"' && tag[i] != 0x7f {
|
| 1149 |
+
i++
|
| 1150 |
+
}
|
| 1151 |
+
if i == 0 || i+1 >= len(tag) || tag[i] != ':' || tag[i+1] != '"' {
|
| 1152 |
+
break
|
| 1153 |
+
}
|
| 1154 |
+
name := string(tag[:i])
|
| 1155 |
+
tag = tag[i+1:]
|
| 1156 |
+
|
| 1157 |
+
// Scan quoted string to find value.
|
| 1158 |
+
i = 1
|
| 1159 |
+
for i < len(tag) && tag[i] != '"' {
|
| 1160 |
+
if tag[i] == '\\' {
|
| 1161 |
+
i++
|
| 1162 |
+
}
|
| 1163 |
+
i++
|
| 1164 |
+
}
|
| 1165 |
+
if i >= len(tag) {
|
| 1166 |
+
break
|
| 1167 |
+
}
|
| 1168 |
+
qvalue := string(tag[:i+1])
|
| 1169 |
+
tag = tag[i+1:]
|
| 1170 |
+
|
| 1171 |
+
if key == name {
|
| 1172 |
+
value, err := strconv.Unquote(qvalue)
|
| 1173 |
+
if err != nil {
|
| 1174 |
+
break
|
| 1175 |
+
}
|
| 1176 |
+
return value, true
|
| 1177 |
+
}
|
| 1178 |
+
}
|
| 1179 |
+
return "", false
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
// Field returns the i'th struct field.
|
| 1183 |
+
func (t *structType) Field(i int) (f StructField) {
|
| 1184 |
+
if i < 0 || i >= len(t.Fields) {
|
| 1185 |
+
panic("reflect: Field index out of bounds")
|
| 1186 |
+
}
|
| 1187 |
+
p := &t.Fields[i]
|
| 1188 |
+
f.Type = toType(p.Typ)
|
| 1189 |
+
f.Name = p.Name.Name()
|
| 1190 |
+
f.Anonymous = p.Embedded()
|
| 1191 |
+
if !p.Name.IsExported() {
|
| 1192 |
+
f.PkgPath = t.PkgPath.Name()
|
| 1193 |
+
}
|
| 1194 |
+
if tag := p.Name.Tag(); tag != "" {
|
| 1195 |
+
f.Tag = StructTag(tag)
|
| 1196 |
+
}
|
| 1197 |
+
f.Offset = p.Offset
|
| 1198 |
+
|
| 1199 |
+
// We can't safely use this optimization on js or wasi,
|
| 1200 |
+
// which do not appear to support read-only data.
|
| 1201 |
+
if i < 256 && runtime.GOOS != "js" && runtime.GOOS != "wasip1" {
|
| 1202 |
+
staticuint64s := getStaticuint64s()
|
| 1203 |
+
p := unsafe.Pointer(&(*staticuint64s)[i])
|
| 1204 |
+
if unsafe.Sizeof(int(0)) == 4 && goarch.BigEndian {
|
| 1205 |
+
p = unsafe.Add(p, 4)
|
| 1206 |
+
}
|
| 1207 |
+
f.Index = unsafe.Slice((*int)(p), 1)
|
| 1208 |
+
} else {
|
| 1209 |
+
// NOTE(rsc): This is the only allocation in the interface
|
| 1210 |
+
// presented by a reflect.Type. It would be nice to avoid,
|
| 1211 |
+
// but we need to make sure that misbehaving clients of
|
| 1212 |
+
// reflect cannot affect other uses of reflect.
|
| 1213 |
+
// One possibility is CL 5371098, but we postponed that
|
| 1214 |
+
// ugliness until there is a demonstrated
|
| 1215 |
+
// need for the performance. This is issue 2320.
|
| 1216 |
+
f.Index = []int{i}
|
| 1217 |
+
}
|
| 1218 |
+
return
|
| 1219 |
+
}
|
| 1220 |
+
|
| 1221 |
+
// getStaticuint64s returns a pointer to an array of 256 uint64 values,
|
| 1222 |
+
// defined in the runtime package in read-only memory.
|
| 1223 |
+
// staticuint64s[0] == 0, staticuint64s[1] == 1, and so forth.
|
| 1224 |
+
//
|
| 1225 |
+
//go:linkname getStaticuint64s runtime.getStaticuint64s
|
| 1226 |
+
func getStaticuint64s() *[256]uint64
|
| 1227 |
+
|
| 1228 |
+
// TODO(gri): Should there be an error/bool indicator if the index
|
| 1229 |
+
// is wrong for FieldByIndex?
|
| 1230 |
+
|
| 1231 |
+
// FieldByIndex returns the nested field corresponding to index.
|
| 1232 |
+
func (t *structType) FieldByIndex(index []int) (f StructField) {
|
| 1233 |
+
f.Type = toType(&t.Type)
|
| 1234 |
+
for i, x := range index {
|
| 1235 |
+
if i > 0 {
|
| 1236 |
+
ft := f.Type
|
| 1237 |
+
if ft.Kind() == Pointer && ft.Elem().Kind() == Struct {
|
| 1238 |
+
ft = ft.Elem()
|
| 1239 |
+
}
|
| 1240 |
+
f.Type = ft
|
| 1241 |
+
}
|
| 1242 |
+
f = f.Type.Field(x)
|
| 1243 |
+
}
|
| 1244 |
+
return
|
| 1245 |
+
}
|
| 1246 |
+
|
| 1247 |
+
// A fieldScan represents an item on the fieldByNameFunc scan work list.
|
| 1248 |
+
type fieldScan struct {
|
| 1249 |
+
typ *structType
|
| 1250 |
+
index []int
|
| 1251 |
+
}
|
| 1252 |
+
|
| 1253 |
+
// FieldByNameFunc returns the struct field with a name that satisfies the
|
| 1254 |
+
// match function and a boolean to indicate if the field was found.
|
| 1255 |
+
func (t *structType) FieldByNameFunc(match func(string) bool) (result StructField, ok bool) {
|
| 1256 |
+
// This uses the same condition that the Go language does: there must be a unique instance
|
| 1257 |
+
// of the match at a given depth level. If there are multiple instances of a match at the
|
| 1258 |
+
// same depth, they annihilate each other and inhibit any possible match at a lower level.
|
| 1259 |
+
// The algorithm is breadth first search, one depth level at a time.
|
| 1260 |
+
|
| 1261 |
+
// The current and next slices are work queues:
|
| 1262 |
+
// current lists the fields to visit on this depth level,
|
| 1263 |
+
// and next lists the fields on the next lower level.
|
| 1264 |
+
current := []fieldScan{}
|
| 1265 |
+
next := []fieldScan{{typ: t}}
|
| 1266 |
+
|
| 1267 |
+
// nextCount records the number of times an embedded type has been
|
| 1268 |
+
// encountered and considered for queueing in the 'next' slice.
|
| 1269 |
+
// We only queue the first one, but we increment the count on each.
|
| 1270 |
+
// If a struct type T can be reached more than once at a given depth level,
|
| 1271 |
+
// then it annihilates itself and need not be considered at all when we
|
| 1272 |
+
// process that next depth level.
|
| 1273 |
+
var nextCount map[*structType]int
|
| 1274 |
+
|
| 1275 |
+
// visited records the structs that have been considered already.
|
| 1276 |
+
// Embedded pointer fields can create cycles in the graph of
|
| 1277 |
+
// reachable embedded types; visited avoids following those cycles.
|
| 1278 |
+
// It also avoids duplicated effort: if we didn't find the field in an
|
| 1279 |
+
// embedded type T at level 2, we won't find it in one at level 4 either.
|
| 1280 |
+
visited := map[*structType]bool{}
|
| 1281 |
+
|
| 1282 |
+
for len(next) > 0 {
|
| 1283 |
+
current, next = next, current[:0]
|
| 1284 |
+
count := nextCount
|
| 1285 |
+
nextCount = nil
|
| 1286 |
+
|
| 1287 |
+
// Process all the fields at this depth, now listed in 'current'.
|
| 1288 |
+
// The loop queues embedded fields found in 'next', for processing during the next
|
| 1289 |
+
// iteration. The multiplicity of the 'current' field counts is recorded
|
| 1290 |
+
// in 'count'; the multiplicity of the 'next' field counts is recorded in 'nextCount'.
|
| 1291 |
+
for _, scan := range current {
|
| 1292 |
+
t := scan.typ
|
| 1293 |
+
if visited[t] {
|
| 1294 |
+
// We've looked through this type before, at a higher level.
|
| 1295 |
+
// That higher level would shadow the lower level we're now at,
|
| 1296 |
+
// so this one can't be useful to us. Ignore it.
|
| 1297 |
+
continue
|
| 1298 |
+
}
|
| 1299 |
+
visited[t] = true
|
| 1300 |
+
for i := range t.Fields {
|
| 1301 |
+
f := &t.Fields[i]
|
| 1302 |
+
// Find name and (for embedded field) type for field f.
|
| 1303 |
+
fname := f.Name.Name()
|
| 1304 |
+
var ntyp *abi.Type
|
| 1305 |
+
if f.Embedded() {
|
| 1306 |
+
// Embedded field of type T or *T.
|
| 1307 |
+
ntyp = f.Typ
|
| 1308 |
+
if ntyp.Kind() == abi.Pointer {
|
| 1309 |
+
ntyp = ntyp.Elem()
|
| 1310 |
+
}
|
| 1311 |
+
}
|
| 1312 |
+
|
| 1313 |
+
// Does it match?
|
| 1314 |
+
if match(fname) {
|
| 1315 |
+
// Potential match
|
| 1316 |
+
if count[t] > 1 || ok {
|
| 1317 |
+
// Name appeared multiple times at this level: annihilate.
|
| 1318 |
+
return StructField{}, false
|
| 1319 |
+
}
|
| 1320 |
+
result = t.Field(i)
|
| 1321 |
+
result.Index = nil
|
| 1322 |
+
result.Index = append(result.Index, scan.index...)
|
| 1323 |
+
result.Index = append(result.Index, i)
|
| 1324 |
+
ok = true
|
| 1325 |
+
continue
|
| 1326 |
+
}
|
| 1327 |
+
|
| 1328 |
+
// Queue embedded struct fields for processing with next level,
|
| 1329 |
+
// but only if we haven't seen a match yet at this level and only
|
| 1330 |
+
// if the embedded types haven't already been queued.
|
| 1331 |
+
if ok || ntyp == nil || ntyp.Kind() != abi.Struct {
|
| 1332 |
+
continue
|
| 1333 |
+
}
|
| 1334 |
+
styp := (*structType)(unsafe.Pointer(ntyp))
|
| 1335 |
+
if nextCount[styp] > 0 {
|
| 1336 |
+
nextCount[styp] = 2 // exact multiple doesn't matter
|
| 1337 |
+
continue
|
| 1338 |
+
}
|
| 1339 |
+
if nextCount == nil {
|
| 1340 |
+
nextCount = map[*structType]int{}
|
| 1341 |
+
}
|
| 1342 |
+
nextCount[styp] = 1
|
| 1343 |
+
if count[t] > 1 {
|
| 1344 |
+
nextCount[styp] = 2 // exact multiple doesn't matter
|
| 1345 |
+
}
|
| 1346 |
+
var index []int
|
| 1347 |
+
index = append(index, scan.index...)
|
| 1348 |
+
index = append(index, i)
|
| 1349 |
+
next = append(next, fieldScan{styp, index})
|
| 1350 |
+
}
|
| 1351 |
+
}
|
| 1352 |
+
if ok {
|
| 1353 |
+
break
|
| 1354 |
+
}
|
| 1355 |
+
}
|
| 1356 |
+
return
|
| 1357 |
+
}
|
| 1358 |
+
|
| 1359 |
+
// FieldByName returns the struct field with the given name
|
| 1360 |
+
// and a boolean to indicate if the field was found.
|
| 1361 |
+
func (t *structType) FieldByName(name string) (f StructField, present bool) {
|
| 1362 |
+
// Quick check for top-level name, or struct without embedded fields.
|
| 1363 |
+
hasEmbeds := false
|
| 1364 |
+
if name != "" {
|
| 1365 |
+
for i := range t.Fields {
|
| 1366 |
+
tf := &t.Fields[i]
|
| 1367 |
+
if tf.Name.Name() == name {
|
| 1368 |
+
return t.Field(i), true
|
| 1369 |
+
}
|
| 1370 |
+
if tf.Embedded() {
|
| 1371 |
+
hasEmbeds = true
|
| 1372 |
+
}
|
| 1373 |
+
}
|
| 1374 |
+
}
|
| 1375 |
+
if !hasEmbeds {
|
| 1376 |
+
return
|
| 1377 |
+
}
|
| 1378 |
+
return t.FieldByNameFunc(func(s string) bool { return s == name })
|
| 1379 |
+
}
|
| 1380 |
+
|
| 1381 |
+
// TypeOf returns the reflection [Type] that represents the dynamic type of i.
|
| 1382 |
+
// If i is a nil interface value, TypeOf returns nil.
|
| 1383 |
+
func TypeOf(i any) Type {
|
| 1384 |
+
return toType(abi.TypeOf(i))
|
| 1385 |
+
}
|
| 1386 |
+
|
| 1387 |
+
// TypeFor returns the [Type] that represents the type argument T.
|
| 1388 |
+
func TypeFor[T any]() Type {
|
| 1389 |
+
// toRType is safe to use here; type is never nil as T is statically known.
|
| 1390 |
+
return toRType(abi.TypeFor[T]())
|
| 1391 |
+
}
|
| 1392 |
+
|
| 1393 |
+
// rtypeOf directly extracts the *rtype of the provided value.
|
| 1394 |
+
func rtypeOf(i any) *abi.Type {
|
| 1395 |
+
return abi.TypeOf(i)
|
| 1396 |
+
}
|
| 1397 |
+
|
| 1398 |
+
// ptrMap is the cache for PointerTo.
|
| 1399 |
+
var ptrMap sync.Map // map[*rtype]*ptrType
|
| 1400 |
+
|
| 1401 |
+
// PtrTo returns the pointer type with element t.
|
| 1402 |
+
// For example, if t represents type Foo, PtrTo(t) represents *Foo.
|
| 1403 |
+
//
|
| 1404 |
+
// PtrTo is the old spelling of [PointerTo].
|
| 1405 |
+
// The two functions behave identically.
|
| 1406 |
+
//
|
| 1407 |
+
// Deprecated: Superseded by [PointerTo].
|
| 1408 |
+
//
|
| 1409 |
+
//go:fix inline
|
| 1410 |
+
func PtrTo(t Type) Type { return PointerTo(t) }
|
| 1411 |
+
|
| 1412 |
+
// PointerTo returns the pointer type with element t.
|
| 1413 |
+
// For example, if t represents type Foo, PointerTo(t) represents *Foo.
|
| 1414 |
+
func PointerTo(t Type) Type {
|
| 1415 |
+
return toRType(t.(*rtype).ptrTo())
|
| 1416 |
+
}
|
| 1417 |
+
|
| 1418 |
+
func (t *rtype) ptrTo() *abi.Type {
|
| 1419 |
+
at := &t.t
|
| 1420 |
+
if at.PtrToThis != 0 {
|
| 1421 |
+
return t.typeOff(at.PtrToThis)
|
| 1422 |
+
}
|
| 1423 |
+
|
| 1424 |
+
// Check the cache.
|
| 1425 |
+
if pi, ok := ptrMap.Load(t); ok {
|
| 1426 |
+
return &pi.(*ptrType).Type
|
| 1427 |
+
}
|
| 1428 |
+
|
| 1429 |
+
// Look in known types.
|
| 1430 |
+
s := "*" + t.String()
|
| 1431 |
+
for _, tt := range typesByString(s) {
|
| 1432 |
+
p := (*ptrType)(unsafe.Pointer(tt))
|
| 1433 |
+
if p.Elem != &t.t {
|
| 1434 |
+
continue
|
| 1435 |
+
}
|
| 1436 |
+
pi, _ := ptrMap.LoadOrStore(t, p)
|
| 1437 |
+
return &pi.(*ptrType).Type
|
| 1438 |
+
}
|
| 1439 |
+
|
| 1440 |
+
// Create a new ptrType starting with the description
|
| 1441 |
+
// of an *unsafe.Pointer.
|
| 1442 |
+
var iptr any = (*unsafe.Pointer)(nil)
|
| 1443 |
+
prototype := *(**ptrType)(unsafe.Pointer(&iptr))
|
| 1444 |
+
pp := *prototype
|
| 1445 |
+
|
| 1446 |
+
pp.Str = resolveReflectName(newName(s, "", false, false))
|
| 1447 |
+
pp.PtrToThis = 0
|
| 1448 |
+
|
| 1449 |
+
// For the type structures linked into the binary, the
|
| 1450 |
+
// compiler provides a good hash of the string.
|
| 1451 |
+
// Create a good hash for the new string by using
|
| 1452 |
+
// the FNV-1 hash's mixing function to combine the
|
| 1453 |
+
// old hash and the new "*".
|
| 1454 |
+
pp.Hash = fnv1(t.t.Hash, '*')
|
| 1455 |
+
|
| 1456 |
+
pp.Elem = at
|
| 1457 |
+
|
| 1458 |
+
pi, _ := ptrMap.LoadOrStore(t, &pp)
|
| 1459 |
+
return &pi.(*ptrType).Type
|
| 1460 |
+
}
|
| 1461 |
+
|
| 1462 |
+
func ptrTo(t *abi.Type) *abi.Type {
|
| 1463 |
+
return toRType(t).ptrTo()
|
| 1464 |
+
}
|
| 1465 |
+
|
| 1466 |
+
// fnv1 incorporates the list of bytes into the hash x using the FNV-1 hash function.
|
| 1467 |
+
func fnv1(x uint32, list ...byte) uint32 {
|
| 1468 |
+
for _, b := range list {
|
| 1469 |
+
x = x*16777619 ^ uint32(b)
|
| 1470 |
+
}
|
| 1471 |
+
return x
|
| 1472 |
+
}
|
| 1473 |
+
|
| 1474 |
+
func (t *rtype) Implements(u Type) bool {
|
| 1475 |
+
if u == nil {
|
| 1476 |
+
panic("reflect: nil type passed to Type.Implements")
|
| 1477 |
+
}
|
| 1478 |
+
if u.Kind() != Interface {
|
| 1479 |
+
panic("reflect: non-interface type passed to Type.Implements")
|
| 1480 |
+
}
|
| 1481 |
+
return implements(u.common(), t.common())
|
| 1482 |
+
}
|
| 1483 |
+
|
| 1484 |
+
func (t *rtype) AssignableTo(u Type) bool {
|
| 1485 |
+
if u == nil {
|
| 1486 |
+
panic("reflect: nil type passed to Type.AssignableTo")
|
| 1487 |
+
}
|
| 1488 |
+
uu := u.common()
|
| 1489 |
+
return directlyAssignable(uu, t.common()) || implements(uu, t.common())
|
| 1490 |
+
}
|
| 1491 |
+
|
| 1492 |
+
func (t *rtype) ConvertibleTo(u Type) bool {
|
| 1493 |
+
if u == nil {
|
| 1494 |
+
panic("reflect: nil type passed to Type.ConvertibleTo")
|
| 1495 |
+
}
|
| 1496 |
+
return convertOp(u.common(), t.common()) != nil
|
| 1497 |
+
}
|
| 1498 |
+
|
| 1499 |
+
func (t *rtype) Comparable() bool {
|
| 1500 |
+
return t.t.Equal != nil
|
| 1501 |
+
}
|
| 1502 |
+
|
| 1503 |
+
// implements reports whether the type V implements the interface type T.
|
| 1504 |
+
func implements(T, V *abi.Type) bool {
|
| 1505 |
+
if T.Kind() != abi.Interface {
|
| 1506 |
+
return false
|
| 1507 |
+
}
|
| 1508 |
+
t := (*interfaceType)(unsafe.Pointer(T))
|
| 1509 |
+
if len(t.Methods) == 0 {
|
| 1510 |
+
return true
|
| 1511 |
+
}
|
| 1512 |
+
|
| 1513 |
+
// The same algorithm applies in both cases, but the
|
| 1514 |
+
// method tables for an interface type and a concrete type
|
| 1515 |
+
// are different, so the code is duplicated.
|
| 1516 |
+
// In both cases the algorithm is a linear scan over the two
|
| 1517 |
+
// lists - T's methods and V's methods - simultaneously.
|
| 1518 |
+
// Since method tables are stored in a unique sorted order
|
| 1519 |
+
// (alphabetical, with no duplicate method names), the scan
|
| 1520 |
+
// through V's methods must hit a match for each of T's
|
| 1521 |
+
// methods along the way, or else V does not implement T.
|
| 1522 |
+
// This lets us run the scan in overall linear time instead of
|
| 1523 |
+
// the quadratic time a naive search would require.
|
| 1524 |
+
// See also ../runtime/iface.go.
|
| 1525 |
+
if V.Kind() == abi.Interface {
|
| 1526 |
+
v := (*interfaceType)(unsafe.Pointer(V))
|
| 1527 |
+
i := 0
|
| 1528 |
+
for j := 0; j < len(v.Methods); j++ {
|
| 1529 |
+
tm := &t.Methods[i]
|
| 1530 |
+
tmName := t.nameOff(tm.Name)
|
| 1531 |
+
vm := &v.Methods[j]
|
| 1532 |
+
vmName := nameOffFor(V, vm.Name)
|
| 1533 |
+
if vmName.Name() == tmName.Name() && typeOffFor(V, vm.Typ) == t.typeOff(tm.Typ) {
|
| 1534 |
+
if !tmName.IsExported() {
|
| 1535 |
+
tmPkgPath := pkgPath(tmName)
|
| 1536 |
+
if tmPkgPath == "" {
|
| 1537 |
+
tmPkgPath = t.PkgPath.Name()
|
| 1538 |
+
}
|
| 1539 |
+
vmPkgPath := pkgPath(vmName)
|
| 1540 |
+
if vmPkgPath == "" {
|
| 1541 |
+
vmPkgPath = v.PkgPath.Name()
|
| 1542 |
+
}
|
| 1543 |
+
if tmPkgPath != vmPkgPath {
|
| 1544 |
+
continue
|
| 1545 |
+
}
|
| 1546 |
+
}
|
| 1547 |
+
if i++; i >= len(t.Methods) {
|
| 1548 |
+
return true
|
| 1549 |
+
}
|
| 1550 |
+
}
|
| 1551 |
+
}
|
| 1552 |
+
return false
|
| 1553 |
+
}
|
| 1554 |
+
|
| 1555 |
+
v := V.Uncommon()
|
| 1556 |
+
if v == nil {
|
| 1557 |
+
return false
|
| 1558 |
+
}
|
| 1559 |
+
i := 0
|
| 1560 |
+
vmethods := v.Methods()
|
| 1561 |
+
for j := 0; j < int(v.Mcount); j++ {
|
| 1562 |
+
tm := &t.Methods[i]
|
| 1563 |
+
tmName := t.nameOff(tm.Name)
|
| 1564 |
+
vm := vmethods[j]
|
| 1565 |
+
vmName := nameOffFor(V, vm.Name)
|
| 1566 |
+
if vmName.Name() == tmName.Name() && typeOffFor(V, vm.Mtyp) == t.typeOff(tm.Typ) {
|
| 1567 |
+
if !tmName.IsExported() {
|
| 1568 |
+
tmPkgPath := pkgPath(tmName)
|
| 1569 |
+
if tmPkgPath == "" {
|
| 1570 |
+
tmPkgPath = t.PkgPath.Name()
|
| 1571 |
+
}
|
| 1572 |
+
vmPkgPath := pkgPath(vmName)
|
| 1573 |
+
if vmPkgPath == "" {
|
| 1574 |
+
vmPkgPath = nameOffFor(V, v.PkgPath).Name()
|
| 1575 |
+
}
|
| 1576 |
+
if tmPkgPath != vmPkgPath {
|
| 1577 |
+
continue
|
| 1578 |
+
}
|
| 1579 |
+
}
|
| 1580 |
+
if i++; i >= len(t.Methods) {
|
| 1581 |
+
return true
|
| 1582 |
+
}
|
| 1583 |
+
}
|
| 1584 |
+
}
|
| 1585 |
+
return false
|
| 1586 |
+
}
|
| 1587 |
+
|
| 1588 |
+
// specialChannelAssignability reports whether a value x of channel type V
|
| 1589 |
+
// can be directly assigned (using memmove) to another channel type T.
|
| 1590 |
+
// https://golang.org/doc/go_spec.html#Assignability
|
| 1591 |
+
// T and V must be both of Chan kind.
|
| 1592 |
+
func specialChannelAssignability(T, V *abi.Type) bool {
|
| 1593 |
+
// Special case:
|
| 1594 |
+
// x is a bidirectional channel value, T is a channel type,
|
| 1595 |
+
// x's type V and T have identical element types,
|
| 1596 |
+
// and at least one of V or T is not a defined type.
|
| 1597 |
+
return V.ChanDir() == abi.BothDir && (nameFor(T) == "" || nameFor(V) == "") && haveIdenticalType(T.Elem(), V.Elem(), true)
|
| 1598 |
+
}
|
| 1599 |
+
|
| 1600 |
+
// directlyAssignable reports whether a value x of type V can be directly
|
| 1601 |
+
// assigned (using memmove) to a value of type T.
|
| 1602 |
+
// https://golang.org/doc/go_spec.html#Assignability
|
| 1603 |
+
// Ignoring the interface rules (implemented elsewhere)
|
| 1604 |
+
// and the ideal constant rules (no ideal constants at run time).
|
| 1605 |
+
func directlyAssignable(T, V *abi.Type) bool {
|
| 1606 |
+
// x's type V is identical to T?
|
| 1607 |
+
if T == V {
|
| 1608 |
+
return true
|
| 1609 |
+
}
|
| 1610 |
+
|
| 1611 |
+
// Otherwise at least one of T and V must not be defined
|
| 1612 |
+
// and they must have the same kind.
|
| 1613 |
+
if T.HasName() && V.HasName() || T.Kind() != V.Kind() {
|
| 1614 |
+
return false
|
| 1615 |
+
}
|
| 1616 |
+
|
| 1617 |
+
if T.Kind() == abi.Chan && specialChannelAssignability(T, V) {
|
| 1618 |
+
return true
|
| 1619 |
+
}
|
| 1620 |
+
|
| 1621 |
+
// x's type T and V must have identical underlying types.
|
| 1622 |
+
return haveIdenticalUnderlyingType(T, V, true)
|
| 1623 |
+
}
|
| 1624 |
+
|
| 1625 |
+
func haveIdenticalType(T, V *abi.Type, cmpTags bool) bool {
|
| 1626 |
+
if cmpTags {
|
| 1627 |
+
return T == V
|
| 1628 |
+
}
|
| 1629 |
+
|
| 1630 |
+
if nameFor(T) != nameFor(V) || T.Kind() != V.Kind() || pkgPathFor(T) != pkgPathFor(V) {
|
| 1631 |
+
return false
|
| 1632 |
+
}
|
| 1633 |
+
|
| 1634 |
+
return haveIdenticalUnderlyingType(T, V, false)
|
| 1635 |
+
}
|
| 1636 |
+
|
| 1637 |
+
func haveIdenticalUnderlyingType(T, V *abi.Type, cmpTags bool) bool {
|
| 1638 |
+
if T == V {
|
| 1639 |
+
return true
|
| 1640 |
+
}
|
| 1641 |
+
|
| 1642 |
+
kind := Kind(T.Kind())
|
| 1643 |
+
if kind != Kind(V.Kind()) {
|
| 1644 |
+
return false
|
| 1645 |
+
}
|
| 1646 |
+
|
| 1647 |
+
// Non-composite types of equal kind have same underlying type
|
| 1648 |
+
// (the predefined instance of the type).
|
| 1649 |
+
if Bool <= kind && kind <= Complex128 || kind == String || kind == UnsafePointer {
|
| 1650 |
+
return true
|
| 1651 |
+
}
|
| 1652 |
+
|
| 1653 |
+
// Composite types.
|
| 1654 |
+
switch kind {
|
| 1655 |
+
case Array:
|
| 1656 |
+
return T.Len() == V.Len() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
|
| 1657 |
+
|
| 1658 |
+
case Chan:
|
| 1659 |
+
return V.ChanDir() == T.ChanDir() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
|
| 1660 |
+
|
| 1661 |
+
case Func:
|
| 1662 |
+
t := (*funcType)(unsafe.Pointer(T))
|
| 1663 |
+
v := (*funcType)(unsafe.Pointer(V))
|
| 1664 |
+
if t.OutCount != v.OutCount || t.InCount != v.InCount {
|
| 1665 |
+
return false
|
| 1666 |
+
}
|
| 1667 |
+
for i := 0; i < t.NumIn(); i++ {
|
| 1668 |
+
if !haveIdenticalType(t.In(i), v.In(i), cmpTags) {
|
| 1669 |
+
return false
|
| 1670 |
+
}
|
| 1671 |
+
}
|
| 1672 |
+
for i := 0; i < t.NumOut(); i++ {
|
| 1673 |
+
if !haveIdenticalType(t.Out(i), v.Out(i), cmpTags) {
|
| 1674 |
+
return false
|
| 1675 |
+
}
|
| 1676 |
+
}
|
| 1677 |
+
return true
|
| 1678 |
+
|
| 1679 |
+
case Interface:
|
| 1680 |
+
t := (*interfaceType)(unsafe.Pointer(T))
|
| 1681 |
+
v := (*interfaceType)(unsafe.Pointer(V))
|
| 1682 |
+
if len(t.Methods) == 0 && len(v.Methods) == 0 {
|
| 1683 |
+
return true
|
| 1684 |
+
}
|
| 1685 |
+
// Might have the same methods but still
|
| 1686 |
+
// need a run time conversion.
|
| 1687 |
+
return false
|
| 1688 |
+
|
| 1689 |
+
case Map:
|
| 1690 |
+
return haveIdenticalType(T.Key(), V.Key(), cmpTags) && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
|
| 1691 |
+
|
| 1692 |
+
case Pointer, Slice:
|
| 1693 |
+
return haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
|
| 1694 |
+
|
| 1695 |
+
case Struct:
|
| 1696 |
+
t := (*structType)(unsafe.Pointer(T))
|
| 1697 |
+
v := (*structType)(unsafe.Pointer(V))
|
| 1698 |
+
if len(t.Fields) != len(v.Fields) {
|
| 1699 |
+
return false
|
| 1700 |
+
}
|
| 1701 |
+
if t.PkgPath.Name() != v.PkgPath.Name() {
|
| 1702 |
+
return false
|
| 1703 |
+
}
|
| 1704 |
+
for i := range t.Fields {
|
| 1705 |
+
tf := &t.Fields[i]
|
| 1706 |
+
vf := &v.Fields[i]
|
| 1707 |
+
if tf.Name.Name() != vf.Name.Name() {
|
| 1708 |
+
return false
|
| 1709 |
+
}
|
| 1710 |
+
if !haveIdenticalType(tf.Typ, vf.Typ, cmpTags) {
|
| 1711 |
+
return false
|
| 1712 |
+
}
|
| 1713 |
+
if cmpTags && tf.Name.Tag() != vf.Name.Tag() {
|
| 1714 |
+
return false
|
| 1715 |
+
}
|
| 1716 |
+
if tf.Offset != vf.Offset {
|
| 1717 |
+
return false
|
| 1718 |
+
}
|
| 1719 |
+
if tf.Embedded() != vf.Embedded() {
|
| 1720 |
+
return false
|
| 1721 |
+
}
|
| 1722 |
+
}
|
| 1723 |
+
return true
|
| 1724 |
+
}
|
| 1725 |
+
|
| 1726 |
+
return false
|
| 1727 |
+
}
|
| 1728 |
+
|
| 1729 |
+
// typelinks is implemented in package runtime.
|
| 1730 |
+
// It returns a slice of the sections in each module,
|
| 1731 |
+
// and a slice of *rtype offsets in each module.
|
| 1732 |
+
//
|
| 1733 |
+
// The types in each module are sorted by string. That is, the first
|
| 1734 |
+
// two linked types of the first module are:
|
| 1735 |
+
//
|
| 1736 |
+
// d0 := sections[0]
|
| 1737 |
+
// t1 := (*rtype)(add(d0, offset[0][0]))
|
| 1738 |
+
// t2 := (*rtype)(add(d0, offset[0][1]))
|
| 1739 |
+
//
|
| 1740 |
+
// and
|
| 1741 |
+
//
|
| 1742 |
+
// t1.String() < t2.String()
|
| 1743 |
+
//
|
| 1744 |
+
// Note that strings are not unique identifiers for types:
|
| 1745 |
+
// there can be more than one with a given string.
|
| 1746 |
+
// Only types we might want to look up are included:
|
| 1747 |
+
// pointers, channels, maps, slices, and arrays.
|
| 1748 |
+
func typelinks() (sections []unsafe.Pointer, offset [][]int32)
|
| 1749 |
+
|
| 1750 |
+
// rtypeOff should be an internal detail,
|
| 1751 |
+
// but widely used packages access it using linkname.
|
| 1752 |
+
// Notable members of the hall of shame include:
|
| 1753 |
+
// - github.com/goccy/go-json
|
| 1754 |
+
//
|
| 1755 |
+
// Do not remove or change the type signature.
|
| 1756 |
+
// See go.dev/issue/67401.
|
| 1757 |
+
//
|
| 1758 |
+
//go:linkname rtypeOff
|
| 1759 |
+
func rtypeOff(section unsafe.Pointer, off int32) *abi.Type {
|
| 1760 |
+
return (*abi.Type)(add(section, uintptr(off), "sizeof(rtype) > 0"))
|
| 1761 |
+
}
|
| 1762 |
+
|
| 1763 |
+
// typesByString returns the subslice of typelinks() whose elements have
|
| 1764 |
+
// the given string representation.
|
| 1765 |
+
// It may be empty (no known types with that string) or may have
|
| 1766 |
+
// multiple elements (multiple types with that string).
|
| 1767 |
+
//
|
| 1768 |
+
// typesByString should be an internal detail,
|
| 1769 |
+
// but widely used packages access it using linkname.
|
| 1770 |
+
// Notable members of the hall of shame include:
|
| 1771 |
+
// - github.com/aristanetworks/goarista
|
| 1772 |
+
// - fortio.org/log
|
| 1773 |
+
//
|
| 1774 |
+
// Do not remove or change the type signature.
|
| 1775 |
+
// See go.dev/issue/67401.
|
| 1776 |
+
//
|
| 1777 |
+
//go:linkname typesByString
|
| 1778 |
+
func typesByString(s string) []*abi.Type {
|
| 1779 |
+
sections, offset := typelinks()
|
| 1780 |
+
var ret []*abi.Type
|
| 1781 |
+
|
| 1782 |
+
for offsI, offs := range offset {
|
| 1783 |
+
section := sections[offsI]
|
| 1784 |
+
|
| 1785 |
+
// We are looking for the first index i where the string becomes >= s.
|
| 1786 |
+
// This is a copy of sort.Search, with f(h) replaced by (*typ[h].String() >= s).
|
| 1787 |
+
i, j := 0, len(offs)
|
| 1788 |
+
for i < j {
|
| 1789 |
+
h := int(uint(i+j) >> 1) // avoid overflow when computing h
|
| 1790 |
+
// i ≤ h < j
|
| 1791 |
+
if !(stringFor(rtypeOff(section, offs[h])) >= s) {
|
| 1792 |
+
i = h + 1 // preserves f(i-1) == false
|
| 1793 |
+
} else {
|
| 1794 |
+
j = h // preserves f(j) == true
|
| 1795 |
+
}
|
| 1796 |
+
}
|
| 1797 |
+
// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
|
| 1798 |
+
|
| 1799 |
+
// Having found the first, linear scan forward to find the last.
|
| 1800 |
+
// We could do a second binary search, but the caller is going
|
| 1801 |
+
// to do a linear scan anyway.
|
| 1802 |
+
for j := i; j < len(offs); j++ {
|
| 1803 |
+
typ := rtypeOff(section, offs[j])
|
| 1804 |
+
if stringFor(typ) != s {
|
| 1805 |
+
break
|
| 1806 |
+
}
|
| 1807 |
+
ret = append(ret, typ)
|
| 1808 |
+
}
|
| 1809 |
+
}
|
| 1810 |
+
return ret
|
| 1811 |
+
}
|
| 1812 |
+
|
| 1813 |
+
// The lookupCache caches ArrayOf, ChanOf, MapOf and SliceOf lookups.
|
| 1814 |
+
var lookupCache sync.Map // map[cacheKey]*rtype
|
| 1815 |
+
|
| 1816 |
+
// A cacheKey is the key for use in the lookupCache.
|
| 1817 |
+
// Four values describe any of the types we are looking for:
|
| 1818 |
+
// type kind, one or two subtypes, and an extra integer.
|
| 1819 |
+
type cacheKey struct {
|
| 1820 |
+
kind Kind
|
| 1821 |
+
t1 *abi.Type
|
| 1822 |
+
t2 *abi.Type
|
| 1823 |
+
extra uintptr
|
| 1824 |
+
}
|
| 1825 |
+
|
| 1826 |
+
// The funcLookupCache caches FuncOf lookups.
|
| 1827 |
+
// FuncOf does not share the common lookupCache since cacheKey is not
|
| 1828 |
+
// sufficient to represent functions unambiguously.
|
| 1829 |
+
var funcLookupCache struct {
|
| 1830 |
+
sync.Mutex // Guards stores (but not loads) on m.
|
| 1831 |
+
|
| 1832 |
+
// m is a map[uint32][]*rtype keyed by the hash calculated in FuncOf.
|
| 1833 |
+
// Elements of m are append-only and thus safe for concurrent reading.
|
| 1834 |
+
m sync.Map
|
| 1835 |
+
}
|
| 1836 |
+
|
| 1837 |
+
// ChanOf returns the channel type with the given direction and element type.
|
| 1838 |
+
// For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.
|
| 1839 |
+
//
|
| 1840 |
+
// The gc runtime imposes a limit of 64 kB on channel element types.
|
| 1841 |
+
// If t's size is equal to or exceeds this limit, ChanOf panics.
|
| 1842 |
+
func ChanOf(dir ChanDir, t Type) Type {
|
| 1843 |
+
typ := t.common()
|
| 1844 |
+
|
| 1845 |
+
// Look in cache.
|
| 1846 |
+
ckey := cacheKey{Chan, typ, nil, uintptr(dir)}
|
| 1847 |
+
if ch, ok := lookupCache.Load(ckey); ok {
|
| 1848 |
+
return ch.(*rtype)
|
| 1849 |
+
}
|
| 1850 |
+
|
| 1851 |
+
// This restriction is imposed by the gc compiler and the runtime.
|
| 1852 |
+
if typ.Size_ >= 1<<16 {
|
| 1853 |
+
panic("reflect.ChanOf: element size too large")
|
| 1854 |
+
}
|
| 1855 |
+
|
| 1856 |
+
// Look in known types.
|
| 1857 |
+
var s string
|
| 1858 |
+
switch dir {
|
| 1859 |
+
default:
|
| 1860 |
+
panic("reflect.ChanOf: invalid dir")
|
| 1861 |
+
case SendDir:
|
| 1862 |
+
s = "chan<- " + stringFor(typ)
|
| 1863 |
+
case RecvDir:
|
| 1864 |
+
s = "<-chan " + stringFor(typ)
|
| 1865 |
+
case BothDir:
|
| 1866 |
+
typeStr := stringFor(typ)
|
| 1867 |
+
if typeStr[0] == '<' {
|
| 1868 |
+
// typ is recv chan, need parentheses as "<-" associates with leftmost
|
| 1869 |
+
// chan possible, see:
|
| 1870 |
+
// * https://golang.org/ref/spec#Channel_types
|
| 1871 |
+
// * https://github.com/golang/go/issues/39897
|
| 1872 |
+
s = "chan (" + typeStr + ")"
|
| 1873 |
+
} else {
|
| 1874 |
+
s = "chan " + typeStr
|
| 1875 |
+
}
|
| 1876 |
+
}
|
| 1877 |
+
for _, tt := range typesByString(s) {
|
| 1878 |
+
ch := (*chanType)(unsafe.Pointer(tt))
|
| 1879 |
+
if ch.Elem == typ && ch.Dir == abi.ChanDir(dir) {
|
| 1880 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(tt))
|
| 1881 |
+
return ti.(Type)
|
| 1882 |
+
}
|
| 1883 |
+
}
|
| 1884 |
+
|
| 1885 |
+
// Make a channel type.
|
| 1886 |
+
var ichan any = (chan unsafe.Pointer)(nil)
|
| 1887 |
+
prototype := *(**chanType)(unsafe.Pointer(&ichan))
|
| 1888 |
+
ch := *prototype
|
| 1889 |
+
ch.TFlag = abi.TFlagRegularMemory | abi.TFlagDirectIface
|
| 1890 |
+
ch.Dir = abi.ChanDir(dir)
|
| 1891 |
+
ch.Str = resolveReflectName(newName(s, "", false, false))
|
| 1892 |
+
ch.Hash = fnv1(typ.Hash, 'c', byte(dir))
|
| 1893 |
+
ch.Elem = typ
|
| 1894 |
+
|
| 1895 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(&ch.Type))
|
| 1896 |
+
return ti.(Type)
|
| 1897 |
+
}
|
| 1898 |
+
|
| 1899 |
+
var funcTypes []Type
|
| 1900 |
+
var funcTypesMutex sync.Mutex
|
| 1901 |
+
|
| 1902 |
+
func initFuncTypes(n int) Type {
|
| 1903 |
+
funcTypesMutex.Lock()
|
| 1904 |
+
defer funcTypesMutex.Unlock()
|
| 1905 |
+
if n >= len(funcTypes) {
|
| 1906 |
+
newFuncTypes := make([]Type, n+1)
|
| 1907 |
+
copy(newFuncTypes, funcTypes)
|
| 1908 |
+
funcTypes = newFuncTypes
|
| 1909 |
+
}
|
| 1910 |
+
if funcTypes[n] != nil {
|
| 1911 |
+
return funcTypes[n]
|
| 1912 |
+
}
|
| 1913 |
+
|
| 1914 |
+
funcTypes[n] = StructOf([]StructField{
|
| 1915 |
+
{
|
| 1916 |
+
Name: "FuncType",
|
| 1917 |
+
Type: TypeOf(funcType{}),
|
| 1918 |
+
},
|
| 1919 |
+
{
|
| 1920 |
+
Name: "Args",
|
| 1921 |
+
Type: ArrayOf(n, TypeOf(&rtype{})),
|
| 1922 |
+
},
|
| 1923 |
+
})
|
| 1924 |
+
return funcTypes[n]
|
| 1925 |
+
}
|
| 1926 |
+
|
| 1927 |
+
// FuncOf returns the function type with the given argument and result types.
|
| 1928 |
+
// For example if k represents int and e represents string,
|
| 1929 |
+
// FuncOf([]Type{k}, []Type{e}, false) represents func(int) string.
|
| 1930 |
+
//
|
| 1931 |
+
// The variadic argument controls whether the function is variadic. FuncOf
|
| 1932 |
+
// panics if the in[len(in)-1] does not represent a slice and variadic is
|
| 1933 |
+
// true.
|
| 1934 |
+
func FuncOf(in, out []Type, variadic bool) Type {
|
| 1935 |
+
if variadic && (len(in) == 0 || in[len(in)-1].Kind() != Slice) {
|
| 1936 |
+
panic("reflect.FuncOf: last arg of variadic func must be slice")
|
| 1937 |
+
}
|
| 1938 |
+
|
| 1939 |
+
// Make a func type.
|
| 1940 |
+
var ifunc any = (func())(nil)
|
| 1941 |
+
prototype := *(**funcType)(unsafe.Pointer(&ifunc))
|
| 1942 |
+
n := len(in) + len(out)
|
| 1943 |
+
|
| 1944 |
+
if n > 128 {
|
| 1945 |
+
panic("reflect.FuncOf: too many arguments")
|
| 1946 |
+
}
|
| 1947 |
+
|
| 1948 |
+
o := New(initFuncTypes(n)).Elem()
|
| 1949 |
+
ft := (*funcType)(unsafe.Pointer(o.Field(0).Addr().Pointer()))
|
| 1950 |
+
args := unsafe.Slice((**rtype)(unsafe.Pointer(o.Field(1).Addr().Pointer())), n)[0:0:n]
|
| 1951 |
+
*ft = *prototype
|
| 1952 |
+
|
| 1953 |
+
// Build a hash and minimally populate ft.
|
| 1954 |
+
var hash uint32
|
| 1955 |
+
for _, in := range in {
|
| 1956 |
+
t := in.(*rtype)
|
| 1957 |
+
args = append(args, t)
|
| 1958 |
+
hash = fnv1(hash, byte(t.t.Hash>>24), byte(t.t.Hash>>16), byte(t.t.Hash>>8), byte(t.t.Hash))
|
| 1959 |
+
}
|
| 1960 |
+
if variadic {
|
| 1961 |
+
hash = fnv1(hash, 'v')
|
| 1962 |
+
}
|
| 1963 |
+
hash = fnv1(hash, '.')
|
| 1964 |
+
for _, out := range out {
|
| 1965 |
+
t := out.(*rtype)
|
| 1966 |
+
args = append(args, t)
|
| 1967 |
+
hash = fnv1(hash, byte(t.t.Hash>>24), byte(t.t.Hash>>16), byte(t.t.Hash>>8), byte(t.t.Hash))
|
| 1968 |
+
}
|
| 1969 |
+
|
| 1970 |
+
ft.TFlag = abi.TFlagDirectIface
|
| 1971 |
+
ft.Hash = hash
|
| 1972 |
+
ft.InCount = uint16(len(in))
|
| 1973 |
+
ft.OutCount = uint16(len(out))
|
| 1974 |
+
if variadic {
|
| 1975 |
+
ft.OutCount |= 1 << 15
|
| 1976 |
+
}
|
| 1977 |
+
|
| 1978 |
+
// Look in cache.
|
| 1979 |
+
if ts, ok := funcLookupCache.m.Load(hash); ok {
|
| 1980 |
+
for _, t := range ts.([]*abi.Type) {
|
| 1981 |
+
if haveIdenticalUnderlyingType(&ft.Type, t, true) {
|
| 1982 |
+
return toRType(t)
|
| 1983 |
+
}
|
| 1984 |
+
}
|
| 1985 |
+
}
|
| 1986 |
+
|
| 1987 |
+
// Not in cache, lock and retry.
|
| 1988 |
+
funcLookupCache.Lock()
|
| 1989 |
+
defer funcLookupCache.Unlock()
|
| 1990 |
+
if ts, ok := funcLookupCache.m.Load(hash); ok {
|
| 1991 |
+
for _, t := range ts.([]*abi.Type) {
|
| 1992 |
+
if haveIdenticalUnderlyingType(&ft.Type, t, true) {
|
| 1993 |
+
return toRType(t)
|
| 1994 |
+
}
|
| 1995 |
+
}
|
| 1996 |
+
}
|
| 1997 |
+
|
| 1998 |
+
addToCache := func(tt *abi.Type) Type {
|
| 1999 |
+
var rts []*abi.Type
|
| 2000 |
+
if rti, ok := funcLookupCache.m.Load(hash); ok {
|
| 2001 |
+
rts = rti.([]*abi.Type)
|
| 2002 |
+
}
|
| 2003 |
+
funcLookupCache.m.Store(hash, append(rts, tt))
|
| 2004 |
+
return toType(tt)
|
| 2005 |
+
}
|
| 2006 |
+
|
| 2007 |
+
// Look in known types for the same string representation.
|
| 2008 |
+
str := funcStr(ft)
|
| 2009 |
+
for _, tt := range typesByString(str) {
|
| 2010 |
+
if haveIdenticalUnderlyingType(&ft.Type, tt, true) {
|
| 2011 |
+
return addToCache(tt)
|
| 2012 |
+
}
|
| 2013 |
+
}
|
| 2014 |
+
|
| 2015 |
+
// Populate the remaining fields of ft and store in cache.
|
| 2016 |
+
ft.Str = resolveReflectName(newName(str, "", false, false))
|
| 2017 |
+
ft.PtrToThis = 0
|
| 2018 |
+
return addToCache(&ft.Type)
|
| 2019 |
+
}
|
| 2020 |
+
func stringFor(t *abi.Type) string {
|
| 2021 |
+
return toRType(t).String()
|
| 2022 |
+
}
|
| 2023 |
+
|
| 2024 |
+
// funcStr builds a string representation of a funcType.
|
| 2025 |
+
func funcStr(ft *funcType) string {
|
| 2026 |
+
repr := make([]byte, 0, 64)
|
| 2027 |
+
repr = append(repr, "func("...)
|
| 2028 |
+
for i, t := range ft.InSlice() {
|
| 2029 |
+
if i > 0 {
|
| 2030 |
+
repr = append(repr, ", "...)
|
| 2031 |
+
}
|
| 2032 |
+
if ft.IsVariadic() && i == int(ft.InCount)-1 {
|
| 2033 |
+
repr = append(repr, "..."...)
|
| 2034 |
+
repr = append(repr, stringFor((*sliceType)(unsafe.Pointer(t)).Elem)...)
|
| 2035 |
+
} else {
|
| 2036 |
+
repr = append(repr, stringFor(t)...)
|
| 2037 |
+
}
|
| 2038 |
+
}
|
| 2039 |
+
repr = append(repr, ')')
|
| 2040 |
+
out := ft.OutSlice()
|
| 2041 |
+
if len(out) == 1 {
|
| 2042 |
+
repr = append(repr, ' ')
|
| 2043 |
+
} else if len(out) > 1 {
|
| 2044 |
+
repr = append(repr, " ("...)
|
| 2045 |
+
}
|
| 2046 |
+
for i, t := range out {
|
| 2047 |
+
if i > 0 {
|
| 2048 |
+
repr = append(repr, ", "...)
|
| 2049 |
+
}
|
| 2050 |
+
repr = append(repr, stringFor(t)...)
|
| 2051 |
+
}
|
| 2052 |
+
if len(out) > 1 {
|
| 2053 |
+
repr = append(repr, ')')
|
| 2054 |
+
}
|
| 2055 |
+
return string(repr)
|
| 2056 |
+
}
|
| 2057 |
+
|
| 2058 |
+
// isReflexive reports whether the == operation on the type is reflexive.
|
| 2059 |
+
// That is, x == x for all values x of type t.
|
| 2060 |
+
func isReflexive(t *abi.Type) bool {
|
| 2061 |
+
switch Kind(t.Kind()) {
|
| 2062 |
+
case Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Chan, Pointer, String, UnsafePointer:
|
| 2063 |
+
return true
|
| 2064 |
+
case Float32, Float64, Complex64, Complex128, Interface:
|
| 2065 |
+
return false
|
| 2066 |
+
case Array:
|
| 2067 |
+
tt := (*arrayType)(unsafe.Pointer(t))
|
| 2068 |
+
return isReflexive(tt.Elem)
|
| 2069 |
+
case Struct:
|
| 2070 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 2071 |
+
for _, f := range tt.Fields {
|
| 2072 |
+
if !isReflexive(f.Typ) {
|
| 2073 |
+
return false
|
| 2074 |
+
}
|
| 2075 |
+
}
|
| 2076 |
+
return true
|
| 2077 |
+
default:
|
| 2078 |
+
// Func, Map, Slice, Invalid
|
| 2079 |
+
panic("isReflexive called on non-key type " + stringFor(t))
|
| 2080 |
+
}
|
| 2081 |
+
}
|
| 2082 |
+
|
| 2083 |
+
// needKeyUpdate reports whether map overwrites require the key to be copied.
|
| 2084 |
+
func needKeyUpdate(t *abi.Type) bool {
|
| 2085 |
+
switch Kind(t.Kind()) {
|
| 2086 |
+
case Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Chan, Pointer, UnsafePointer:
|
| 2087 |
+
return false
|
| 2088 |
+
case Float32, Float64, Complex64, Complex128, Interface, String:
|
| 2089 |
+
// Float keys can be updated from +0 to -0.
|
| 2090 |
+
// String keys can be updated to use a smaller backing store.
|
| 2091 |
+
// Interfaces might have floats or strings in them.
|
| 2092 |
+
return true
|
| 2093 |
+
case Array:
|
| 2094 |
+
tt := (*arrayType)(unsafe.Pointer(t))
|
| 2095 |
+
return needKeyUpdate(tt.Elem)
|
| 2096 |
+
case Struct:
|
| 2097 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 2098 |
+
for _, f := range tt.Fields {
|
| 2099 |
+
if needKeyUpdate(f.Typ) {
|
| 2100 |
+
return true
|
| 2101 |
+
}
|
| 2102 |
+
}
|
| 2103 |
+
return false
|
| 2104 |
+
default:
|
| 2105 |
+
// Func, Map, Slice, Invalid
|
| 2106 |
+
panic("needKeyUpdate called on non-key type " + stringFor(t))
|
| 2107 |
+
}
|
| 2108 |
+
}
|
| 2109 |
+
|
| 2110 |
+
// hashMightPanic reports whether the hash of a map key of type t might panic.
|
| 2111 |
+
func hashMightPanic(t *abi.Type) bool {
|
| 2112 |
+
switch Kind(t.Kind()) {
|
| 2113 |
+
case Interface:
|
| 2114 |
+
return true
|
| 2115 |
+
case Array:
|
| 2116 |
+
tt := (*arrayType)(unsafe.Pointer(t))
|
| 2117 |
+
return hashMightPanic(tt.Elem)
|
| 2118 |
+
case Struct:
|
| 2119 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 2120 |
+
for _, f := range tt.Fields {
|
| 2121 |
+
if hashMightPanic(f.Typ) {
|
| 2122 |
+
return true
|
| 2123 |
+
}
|
| 2124 |
+
}
|
| 2125 |
+
return false
|
| 2126 |
+
default:
|
| 2127 |
+
return false
|
| 2128 |
+
}
|
| 2129 |
+
}
|
| 2130 |
+
|
| 2131 |
+
// emitGCMask writes the GC mask for [n]typ into out, starting at bit
|
| 2132 |
+
// offset base.
|
| 2133 |
+
func emitGCMask(out []byte, base uintptr, typ *abi.Type, n uintptr) {
|
| 2134 |
+
ptrs := typ.PtrBytes / goarch.PtrSize
|
| 2135 |
+
words := typ.Size_ / goarch.PtrSize
|
| 2136 |
+
mask := typ.GcSlice(0, (ptrs+7)/8)
|
| 2137 |
+
for j := uintptr(0); j < ptrs; j++ {
|
| 2138 |
+
if (mask[j/8]>>(j%8))&1 != 0 {
|
| 2139 |
+
for i := uintptr(0); i < n; i++ {
|
| 2140 |
+
k := base + i*words + j
|
| 2141 |
+
out[k/8] |= 1 << (k % 8)
|
| 2142 |
+
}
|
| 2143 |
+
}
|
| 2144 |
+
}
|
| 2145 |
+
}
|
| 2146 |
+
|
| 2147 |
+
// SliceOf returns the slice type with element type t.
|
| 2148 |
+
// For example, if t represents int, SliceOf(t) represents []int.
|
| 2149 |
+
func SliceOf(t Type) Type {
|
| 2150 |
+
typ := t.common()
|
| 2151 |
+
|
| 2152 |
+
// Look in cache.
|
| 2153 |
+
ckey := cacheKey{Slice, typ, nil, 0}
|
| 2154 |
+
if slice, ok := lookupCache.Load(ckey); ok {
|
| 2155 |
+
return slice.(Type)
|
| 2156 |
+
}
|
| 2157 |
+
|
| 2158 |
+
// Look in known types.
|
| 2159 |
+
s := "[]" + stringFor(typ)
|
| 2160 |
+
for _, tt := range typesByString(s) {
|
| 2161 |
+
slice := (*sliceType)(unsafe.Pointer(tt))
|
| 2162 |
+
if slice.Elem == typ {
|
| 2163 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(tt))
|
| 2164 |
+
return ti.(Type)
|
| 2165 |
+
}
|
| 2166 |
+
}
|
| 2167 |
+
|
| 2168 |
+
// Make a slice type.
|
| 2169 |
+
var islice any = ([]unsafe.Pointer)(nil)
|
| 2170 |
+
prototype := *(**sliceType)(unsafe.Pointer(&islice))
|
| 2171 |
+
slice := *prototype
|
| 2172 |
+
slice.TFlag = 0
|
| 2173 |
+
slice.Str = resolveReflectName(newName(s, "", false, false))
|
| 2174 |
+
slice.Hash = fnv1(typ.Hash, '[')
|
| 2175 |
+
slice.Elem = typ
|
| 2176 |
+
slice.PtrToThis = 0
|
| 2177 |
+
|
| 2178 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(&slice.Type))
|
| 2179 |
+
return ti.(Type)
|
| 2180 |
+
}
|
| 2181 |
+
|
| 2182 |
+
// The structLookupCache caches StructOf lookups.
|
| 2183 |
+
// StructOf does not share the common lookupCache since we need to pin
|
| 2184 |
+
// the memory associated with *structTypeFixedN.
|
| 2185 |
+
var structLookupCache struct {
|
| 2186 |
+
sync.Mutex // Guards stores (but not loads) on m.
|
| 2187 |
+
|
| 2188 |
+
// m is a map[uint32][]Type keyed by the hash calculated in StructOf.
|
| 2189 |
+
// Elements in m are append-only and thus safe for concurrent reading.
|
| 2190 |
+
m sync.Map
|
| 2191 |
+
}
|
| 2192 |
+
|
| 2193 |
+
type structTypeUncommon struct {
|
| 2194 |
+
structType
|
| 2195 |
+
u uncommonType
|
| 2196 |
+
}
|
| 2197 |
+
|
| 2198 |
+
// isLetter reports whether a given 'rune' is classified as a Letter.
|
| 2199 |
+
func isLetter(ch rune) bool {
|
| 2200 |
+
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= utf8.RuneSelf && unicode.IsLetter(ch)
|
| 2201 |
+
}
|
| 2202 |
+
|
| 2203 |
+
// isValidFieldName checks if a string is a valid (struct) field name or not.
|
| 2204 |
+
//
|
| 2205 |
+
// According to the language spec, a field name should be an identifier.
|
| 2206 |
+
//
|
| 2207 |
+
// identifier = letter { letter | unicode_digit } .
|
| 2208 |
+
// letter = unicode_letter | "_" .
|
| 2209 |
+
func isValidFieldName(fieldName string) bool {
|
| 2210 |
+
for i, c := range fieldName {
|
| 2211 |
+
if i == 0 && !isLetter(c) {
|
| 2212 |
+
return false
|
| 2213 |
+
}
|
| 2214 |
+
|
| 2215 |
+
if !(isLetter(c) || unicode.IsDigit(c)) {
|
| 2216 |
+
return false
|
| 2217 |
+
}
|
| 2218 |
+
}
|
| 2219 |
+
|
| 2220 |
+
return len(fieldName) > 0
|
| 2221 |
+
}
|
| 2222 |
+
|
| 2223 |
+
// This must match cmd/compile/internal/compare.IsRegularMemory
|
| 2224 |
+
func isRegularMemory(t Type) bool {
|
| 2225 |
+
switch t.Kind() {
|
| 2226 |
+
case Array:
|
| 2227 |
+
elem := t.Elem()
|
| 2228 |
+
if isRegularMemory(elem) {
|
| 2229 |
+
return true
|
| 2230 |
+
}
|
| 2231 |
+
return elem.Comparable() && t.Len() == 0
|
| 2232 |
+
case Int8, Int16, Int32, Int64, Int, Uint8, Uint16, Uint32, Uint64, Uint, Uintptr, Chan, Pointer, Bool, UnsafePointer:
|
| 2233 |
+
return true
|
| 2234 |
+
case Struct:
|
| 2235 |
+
num := t.NumField()
|
| 2236 |
+
switch num {
|
| 2237 |
+
case 0:
|
| 2238 |
+
return true
|
| 2239 |
+
case 1:
|
| 2240 |
+
field := t.Field(0)
|
| 2241 |
+
if field.Name == "_" {
|
| 2242 |
+
return false
|
| 2243 |
+
}
|
| 2244 |
+
return isRegularMemory(field.Type)
|
| 2245 |
+
default:
|
| 2246 |
+
for i := range num {
|
| 2247 |
+
field := t.Field(i)
|
| 2248 |
+
if field.Name == "_" || !isRegularMemory(field.Type) || isPaddedField(t, i) {
|
| 2249 |
+
return false
|
| 2250 |
+
}
|
| 2251 |
+
}
|
| 2252 |
+
return true
|
| 2253 |
+
}
|
| 2254 |
+
}
|
| 2255 |
+
return false
|
| 2256 |
+
}
|
| 2257 |
+
|
| 2258 |
+
// isPaddedField reports whether the i'th field of struct type t is followed
|
| 2259 |
+
// by padding.
|
| 2260 |
+
func isPaddedField(t Type, i int) bool {
|
| 2261 |
+
field := t.Field(i)
|
| 2262 |
+
if i+1 < t.NumField() {
|
| 2263 |
+
return field.Offset+field.Type.Size() != t.Field(i+1).Offset
|
| 2264 |
+
}
|
| 2265 |
+
return field.Offset+field.Type.Size() != t.Size()
|
| 2266 |
+
}
|
| 2267 |
+
|
| 2268 |
+
// StructOf returns the struct type containing fields.
|
| 2269 |
+
// The Offset and Index fields are ignored and computed as they would be
|
| 2270 |
+
// by the compiler.
|
| 2271 |
+
//
|
| 2272 |
+
// StructOf currently does not support promoted methods of embedded fields
|
| 2273 |
+
// and panics if passed unexported StructFields.
|
| 2274 |
+
func StructOf(fields []StructField) Type {
|
| 2275 |
+
var (
|
| 2276 |
+
hash = fnv1(0, []byte("struct {")...)
|
| 2277 |
+
size uintptr
|
| 2278 |
+
typalign uint8
|
| 2279 |
+
comparable = true
|
| 2280 |
+
methods []abi.Method
|
| 2281 |
+
|
| 2282 |
+
fs = make([]structField, len(fields))
|
| 2283 |
+
repr = make([]byte, 0, 64)
|
| 2284 |
+
fset = map[string]struct{}{} // fields' names
|
| 2285 |
+
)
|
| 2286 |
+
|
| 2287 |
+
lastzero := uintptr(0)
|
| 2288 |
+
repr = append(repr, "struct {"...)
|
| 2289 |
+
pkgpath := ""
|
| 2290 |
+
for i, field := range fields {
|
| 2291 |
+
if field.Name == "" {
|
| 2292 |
+
panic("reflect.StructOf: field " + strconv.Itoa(i) + " has no name")
|
| 2293 |
+
}
|
| 2294 |
+
if !isValidFieldName(field.Name) {
|
| 2295 |
+
panic("reflect.StructOf: field " + strconv.Itoa(i) + " has invalid name")
|
| 2296 |
+
}
|
| 2297 |
+
if field.Type == nil {
|
| 2298 |
+
panic("reflect.StructOf: field " + strconv.Itoa(i) + " has no type")
|
| 2299 |
+
}
|
| 2300 |
+
f, fpkgpath := runtimeStructField(field)
|
| 2301 |
+
ft := f.Typ
|
| 2302 |
+
if fpkgpath != "" {
|
| 2303 |
+
if pkgpath == "" {
|
| 2304 |
+
pkgpath = fpkgpath
|
| 2305 |
+
} else if pkgpath != fpkgpath {
|
| 2306 |
+
panic("reflect.Struct: fields with different PkgPath " + pkgpath + " and " + fpkgpath)
|
| 2307 |
+
}
|
| 2308 |
+
}
|
| 2309 |
+
|
| 2310 |
+
// Update string and hash
|
| 2311 |
+
name := f.Name.Name()
|
| 2312 |
+
hash = fnv1(hash, []byte(name)...)
|
| 2313 |
+
if !f.Embedded() {
|
| 2314 |
+
repr = append(repr, (" " + name)...)
|
| 2315 |
+
} else {
|
| 2316 |
+
// Embedded field
|
| 2317 |
+
if f.Typ.Kind() == abi.Pointer {
|
| 2318 |
+
// Embedded ** and *interface{} are illegal
|
| 2319 |
+
elem := ft.Elem()
|
| 2320 |
+
if k := elem.Kind(); k == abi.Pointer || k == abi.Interface {
|
| 2321 |
+
panic("reflect.StructOf: illegal embedded field type " + stringFor(ft))
|
| 2322 |
+
}
|
| 2323 |
+
}
|
| 2324 |
+
|
| 2325 |
+
switch Kind(f.Typ.Kind()) {
|
| 2326 |
+
case Interface:
|
| 2327 |
+
ift := (*interfaceType)(unsafe.Pointer(ft))
|
| 2328 |
+
for _, m := range ift.Methods {
|
| 2329 |
+
if pkgPath(ift.nameOff(m.Name)) != "" {
|
| 2330 |
+
// TODO(sbinet). Issue 15924.
|
| 2331 |
+
panic("reflect: embedded interface with unexported method(s) not implemented")
|
| 2332 |
+
}
|
| 2333 |
+
|
| 2334 |
+
fnStub := resolveReflectText(unsafe.Pointer(abi.FuncPCABIInternal(embeddedIfaceMethStub)))
|
| 2335 |
+
methods = append(methods, abi.Method{
|
| 2336 |
+
Name: resolveReflectName(ift.nameOff(m.Name)),
|
| 2337 |
+
Mtyp: resolveReflectType(ift.typeOff(m.Typ)),
|
| 2338 |
+
Ifn: fnStub,
|
| 2339 |
+
Tfn: fnStub,
|
| 2340 |
+
})
|
| 2341 |
+
}
|
| 2342 |
+
case Pointer:
|
| 2343 |
+
ptr := (*ptrType)(unsafe.Pointer(ft))
|
| 2344 |
+
if unt := ptr.Uncommon(); unt != nil {
|
| 2345 |
+
if i > 0 && unt.Mcount > 0 {
|
| 2346 |
+
// Issue 15924.
|
| 2347 |
+
panic("reflect: embedded type with methods not implemented if type is not first field")
|
| 2348 |
+
}
|
| 2349 |
+
if len(fields) > 1 {
|
| 2350 |
+
panic("reflect: embedded type with methods not implemented if there is more than one field")
|
| 2351 |
+
}
|
| 2352 |
+
for _, m := range unt.Methods() {
|
| 2353 |
+
mname := nameOffFor(ft, m.Name)
|
| 2354 |
+
if pkgPath(mname) != "" {
|
| 2355 |
+
// TODO(sbinet).
|
| 2356 |
+
// Issue 15924.
|
| 2357 |
+
panic("reflect: embedded interface with unexported method(s) not implemented")
|
| 2358 |
+
}
|
| 2359 |
+
methods = append(methods, abi.Method{
|
| 2360 |
+
Name: resolveReflectName(mname),
|
| 2361 |
+
Mtyp: resolveReflectType(typeOffFor(ft, m.Mtyp)),
|
| 2362 |
+
Ifn: resolveReflectText(textOffFor(ft, m.Ifn)),
|
| 2363 |
+
Tfn: resolveReflectText(textOffFor(ft, m.Tfn)),
|
| 2364 |
+
})
|
| 2365 |
+
}
|
| 2366 |
+
}
|
| 2367 |
+
if unt := ptr.Elem.Uncommon(); unt != nil {
|
| 2368 |
+
for _, m := range unt.Methods() {
|
| 2369 |
+
mname := nameOffFor(ft, m.Name)
|
| 2370 |
+
if pkgPath(mname) != "" {
|
| 2371 |
+
// TODO(sbinet)
|
| 2372 |
+
// Issue 15924.
|
| 2373 |
+
panic("reflect: embedded interface with unexported method(s) not implemented")
|
| 2374 |
+
}
|
| 2375 |
+
methods = append(methods, abi.Method{
|
| 2376 |
+
Name: resolveReflectName(mname),
|
| 2377 |
+
Mtyp: resolveReflectType(typeOffFor(ptr.Elem, m.Mtyp)),
|
| 2378 |
+
Ifn: resolveReflectText(textOffFor(ptr.Elem, m.Ifn)),
|
| 2379 |
+
Tfn: resolveReflectText(textOffFor(ptr.Elem, m.Tfn)),
|
| 2380 |
+
})
|
| 2381 |
+
}
|
| 2382 |
+
}
|
| 2383 |
+
default:
|
| 2384 |
+
if unt := ft.Uncommon(); unt != nil {
|
| 2385 |
+
if i > 0 && unt.Mcount > 0 {
|
| 2386 |
+
// Issue 15924.
|
| 2387 |
+
panic("reflect: embedded type with methods not implemented if type is not first field")
|
| 2388 |
+
}
|
| 2389 |
+
if len(fields) > 1 && ft.IsDirectIface() {
|
| 2390 |
+
panic("reflect: embedded type with methods not implemented for non-pointer type")
|
| 2391 |
+
}
|
| 2392 |
+
for _, m := range unt.Methods() {
|
| 2393 |
+
mname := nameOffFor(ft, m.Name)
|
| 2394 |
+
if pkgPath(mname) != "" {
|
| 2395 |
+
// TODO(sbinet)
|
| 2396 |
+
// Issue 15924.
|
| 2397 |
+
panic("reflect: embedded interface with unexported method(s) not implemented")
|
| 2398 |
+
}
|
| 2399 |
+
methods = append(methods, abi.Method{
|
| 2400 |
+
Name: resolveReflectName(mname),
|
| 2401 |
+
Mtyp: resolveReflectType(typeOffFor(ft, m.Mtyp)),
|
| 2402 |
+
Ifn: resolveReflectText(textOffFor(ft, m.Ifn)),
|
| 2403 |
+
Tfn: resolveReflectText(textOffFor(ft, m.Tfn)),
|
| 2404 |
+
})
|
| 2405 |
+
|
| 2406 |
+
}
|
| 2407 |
+
}
|
| 2408 |
+
}
|
| 2409 |
+
}
|
| 2410 |
+
if _, dup := fset[name]; dup && name != "_" {
|
| 2411 |
+
panic("reflect.StructOf: duplicate field " + name)
|
| 2412 |
+
}
|
| 2413 |
+
fset[name] = struct{}{}
|
| 2414 |
+
|
| 2415 |
+
hash = fnv1(hash, byte(ft.Hash>>24), byte(ft.Hash>>16), byte(ft.Hash>>8), byte(ft.Hash))
|
| 2416 |
+
|
| 2417 |
+
repr = append(repr, (" " + stringFor(ft))...)
|
| 2418 |
+
if f.Name.HasTag() {
|
| 2419 |
+
hash = fnv1(hash, []byte(f.Name.Tag())...)
|
| 2420 |
+
repr = append(repr, (" " + strconv.Quote(f.Name.Tag()))...)
|
| 2421 |
+
}
|
| 2422 |
+
if i < len(fields)-1 {
|
| 2423 |
+
repr = append(repr, ';')
|
| 2424 |
+
}
|
| 2425 |
+
|
| 2426 |
+
comparable = comparable && (ft.Equal != nil)
|
| 2427 |
+
|
| 2428 |
+
offset := align(size, uintptr(ft.Align_))
|
| 2429 |
+
if offset < size {
|
| 2430 |
+
panic("reflect.StructOf: struct size would exceed virtual address space")
|
| 2431 |
+
}
|
| 2432 |
+
if ft.Align_ > typalign {
|
| 2433 |
+
typalign = ft.Align_
|
| 2434 |
+
}
|
| 2435 |
+
size = offset + ft.Size_
|
| 2436 |
+
if size < offset {
|
| 2437 |
+
panic("reflect.StructOf: struct size would exceed virtual address space")
|
| 2438 |
+
}
|
| 2439 |
+
f.Offset = offset
|
| 2440 |
+
|
| 2441 |
+
if ft.Size_ == 0 {
|
| 2442 |
+
lastzero = size
|
| 2443 |
+
}
|
| 2444 |
+
|
| 2445 |
+
fs[i] = f
|
| 2446 |
+
}
|
| 2447 |
+
|
| 2448 |
+
if size > 0 && lastzero == size {
|
| 2449 |
+
// This is a non-zero sized struct that ends in a
|
| 2450 |
+
// zero-sized field. We add an extra byte of padding,
|
| 2451 |
+
// to ensure that taking the address of the final
|
| 2452 |
+
// zero-sized field can't manufacture a pointer to the
|
| 2453 |
+
// next object in the heap. See issue 9401.
|
| 2454 |
+
size++
|
| 2455 |
+
if size == 0 {
|
| 2456 |
+
panic("reflect.StructOf: struct size would exceed virtual address space")
|
| 2457 |
+
}
|
| 2458 |
+
}
|
| 2459 |
+
|
| 2460 |
+
var typ *structType
|
| 2461 |
+
var ut *uncommonType
|
| 2462 |
+
|
| 2463 |
+
if len(methods) == 0 {
|
| 2464 |
+
t := new(structTypeUncommon)
|
| 2465 |
+
typ = &t.structType
|
| 2466 |
+
ut = &t.u
|
| 2467 |
+
} else {
|
| 2468 |
+
// A *rtype representing a struct is followed directly in memory by an
|
| 2469 |
+
// array of method objects representing the methods attached to the
|
| 2470 |
+
// struct. To get the same layout for a run time generated type, we
|
| 2471 |
+
// need an array directly following the uncommonType memory.
|
| 2472 |
+
// A similar strategy is used for funcTypeFixed4, ...funcTypeFixedN.
|
| 2473 |
+
tt := New(StructOf([]StructField{
|
| 2474 |
+
{Name: "S", Type: TypeOf(structType{})},
|
| 2475 |
+
{Name: "U", Type: TypeOf(uncommonType{})},
|
| 2476 |
+
{Name: "M", Type: ArrayOf(len(methods), TypeOf(methods[0]))},
|
| 2477 |
+
}))
|
| 2478 |
+
|
| 2479 |
+
typ = (*structType)(tt.Elem().Field(0).Addr().UnsafePointer())
|
| 2480 |
+
ut = (*uncommonType)(tt.Elem().Field(1).Addr().UnsafePointer())
|
| 2481 |
+
|
| 2482 |
+
copy(tt.Elem().Field(2).Slice(0, len(methods)).Interface().([]abi.Method), methods)
|
| 2483 |
+
}
|
| 2484 |
+
// TODO(sbinet): Once we allow embedding multiple types,
|
| 2485 |
+
// methods will need to be sorted like the compiler does.
|
| 2486 |
+
// TODO(sbinet): Once we allow non-exported methods, we will
|
| 2487 |
+
// need to compute xcount as the number of exported methods.
|
| 2488 |
+
ut.Mcount = uint16(len(methods))
|
| 2489 |
+
ut.Xcount = ut.Mcount
|
| 2490 |
+
ut.Moff = uint32(unsafe.Sizeof(uncommonType{}))
|
| 2491 |
+
|
| 2492 |
+
if len(fs) > 0 {
|
| 2493 |
+
repr = append(repr, ' ')
|
| 2494 |
+
}
|
| 2495 |
+
repr = append(repr, '}')
|
| 2496 |
+
hash = fnv1(hash, '}')
|
| 2497 |
+
str := string(repr)
|
| 2498 |
+
|
| 2499 |
+
// Round the size up to be a multiple of the alignment.
|
| 2500 |
+
s := align(size, uintptr(typalign))
|
| 2501 |
+
if s < size {
|
| 2502 |
+
panic("reflect.StructOf: struct size would exceed virtual address space")
|
| 2503 |
+
}
|
| 2504 |
+
size = s
|
| 2505 |
+
|
| 2506 |
+
// Make the struct type.
|
| 2507 |
+
var istruct any = struct{}{}
|
| 2508 |
+
prototype := *(**structType)(unsafe.Pointer(&istruct))
|
| 2509 |
+
*typ = *prototype
|
| 2510 |
+
typ.Fields = fs
|
| 2511 |
+
if pkgpath != "" {
|
| 2512 |
+
typ.PkgPath = newName(pkgpath, "", false, false)
|
| 2513 |
+
}
|
| 2514 |
+
|
| 2515 |
+
// Look in cache.
|
| 2516 |
+
if ts, ok := structLookupCache.m.Load(hash); ok {
|
| 2517 |
+
for _, st := range ts.([]Type) {
|
| 2518 |
+
t := st.common()
|
| 2519 |
+
if haveIdenticalUnderlyingType(&typ.Type, t, true) {
|
| 2520 |
+
return toType(t)
|
| 2521 |
+
}
|
| 2522 |
+
}
|
| 2523 |
+
}
|
| 2524 |
+
|
| 2525 |
+
// Not in cache, lock and retry.
|
| 2526 |
+
structLookupCache.Lock()
|
| 2527 |
+
defer structLookupCache.Unlock()
|
| 2528 |
+
if ts, ok := structLookupCache.m.Load(hash); ok {
|
| 2529 |
+
for _, st := range ts.([]Type) {
|
| 2530 |
+
t := st.common()
|
| 2531 |
+
if haveIdenticalUnderlyingType(&typ.Type, t, true) {
|
| 2532 |
+
return toType(t)
|
| 2533 |
+
}
|
| 2534 |
+
}
|
| 2535 |
+
}
|
| 2536 |
+
|
| 2537 |
+
addToCache := func(t Type) Type {
|
| 2538 |
+
var ts []Type
|
| 2539 |
+
if ti, ok := structLookupCache.m.Load(hash); ok {
|
| 2540 |
+
ts = ti.([]Type)
|
| 2541 |
+
}
|
| 2542 |
+
structLookupCache.m.Store(hash, append(ts, t))
|
| 2543 |
+
return t
|
| 2544 |
+
}
|
| 2545 |
+
|
| 2546 |
+
// Look in known types.
|
| 2547 |
+
for _, t := range typesByString(str) {
|
| 2548 |
+
if haveIdenticalUnderlyingType(&typ.Type, t, true) {
|
| 2549 |
+
// even if 't' wasn't a structType with methods, we should be ok
|
| 2550 |
+
// as the 'u uncommonType' field won't be accessed except when
|
| 2551 |
+
// tflag&abi.TFlagUncommon is set.
|
| 2552 |
+
return addToCache(toType(t))
|
| 2553 |
+
}
|
| 2554 |
+
}
|
| 2555 |
+
|
| 2556 |
+
typ.Str = resolveReflectName(newName(str, "", false, false))
|
| 2557 |
+
if isRegularMemory(toType(&typ.Type)) {
|
| 2558 |
+
typ.TFlag = abi.TFlagRegularMemory
|
| 2559 |
+
} else {
|
| 2560 |
+
typ.TFlag = 0
|
| 2561 |
+
}
|
| 2562 |
+
typ.Hash = hash
|
| 2563 |
+
typ.Size_ = size
|
| 2564 |
+
typ.PtrBytes = typeptrdata(&typ.Type)
|
| 2565 |
+
typ.Align_ = typalign
|
| 2566 |
+
typ.FieldAlign_ = typalign
|
| 2567 |
+
typ.PtrToThis = 0
|
| 2568 |
+
if len(methods) > 0 {
|
| 2569 |
+
typ.TFlag |= abi.TFlagUncommon
|
| 2570 |
+
}
|
| 2571 |
+
|
| 2572 |
+
if typ.PtrBytes == 0 {
|
| 2573 |
+
typ.GCData = nil
|
| 2574 |
+
} else if typ.PtrBytes <= abi.MaxPtrmaskBytes*8*goarch.PtrSize {
|
| 2575 |
+
bv := new(bitVector)
|
| 2576 |
+
addTypeBits(bv, 0, &typ.Type)
|
| 2577 |
+
typ.GCData = &bv.data[0]
|
| 2578 |
+
} else {
|
| 2579 |
+
// Runtime will build the mask if needed. We just need to allocate
|
| 2580 |
+
// space to store it.
|
| 2581 |
+
typ.TFlag |= abi.TFlagGCMaskOnDemand
|
| 2582 |
+
typ.GCData = (*byte)(unsafe.Pointer(new(uintptr)))
|
| 2583 |
+
}
|
| 2584 |
+
|
| 2585 |
+
typ.Equal = nil
|
| 2586 |
+
if comparable {
|
| 2587 |
+
typ.Equal = func(p, q unsafe.Pointer) bool {
|
| 2588 |
+
for _, ft := range typ.Fields {
|
| 2589 |
+
pi := add(p, ft.Offset, "&x.field safe")
|
| 2590 |
+
qi := add(q, ft.Offset, "&x.field safe")
|
| 2591 |
+
if !ft.Typ.Equal(pi, qi) {
|
| 2592 |
+
return false
|
| 2593 |
+
}
|
| 2594 |
+
}
|
| 2595 |
+
return true
|
| 2596 |
+
}
|
| 2597 |
+
}
|
| 2598 |
+
|
| 2599 |
+
switch {
|
| 2600 |
+
case typ.Size_ == goarch.PtrSize && typ.PtrBytes == goarch.PtrSize:
|
| 2601 |
+
typ.TFlag |= abi.TFlagDirectIface
|
| 2602 |
+
default:
|
| 2603 |
+
typ.TFlag &^= abi.TFlagDirectIface
|
| 2604 |
+
}
|
| 2605 |
+
|
| 2606 |
+
return addToCache(toType(&typ.Type))
|
| 2607 |
+
}
|
| 2608 |
+
|
| 2609 |
+
func embeddedIfaceMethStub() {
|
| 2610 |
+
panic("reflect: StructOf does not support methods of embedded interfaces")
|
| 2611 |
+
}
|
| 2612 |
+
|
| 2613 |
+
// runtimeStructField takes a StructField value passed to StructOf and
|
| 2614 |
+
// returns both the corresponding internal representation, of type
|
| 2615 |
+
// structField, and the pkgpath value to use for this field.
|
| 2616 |
+
func runtimeStructField(field StructField) (structField, string) {
|
| 2617 |
+
if field.Anonymous && field.PkgPath != "" {
|
| 2618 |
+
panic("reflect.StructOf: field \"" + field.Name + "\" is anonymous but has PkgPath set")
|
| 2619 |
+
}
|
| 2620 |
+
|
| 2621 |
+
if field.IsExported() {
|
| 2622 |
+
// Best-effort check for misuse.
|
| 2623 |
+
// Since this field will be treated as exported, not much harm done if Unicode lowercase slips through.
|
| 2624 |
+
c := field.Name[0]
|
| 2625 |
+
if 'a' <= c && c <= 'z' || c == '_' {
|
| 2626 |
+
panic("reflect.StructOf: field \"" + field.Name + "\" is unexported but missing PkgPath")
|
| 2627 |
+
}
|
| 2628 |
+
}
|
| 2629 |
+
|
| 2630 |
+
resolveReflectType(field.Type.common()) // install in runtime
|
| 2631 |
+
f := structField{
|
| 2632 |
+
Name: newName(field.Name, string(field.Tag), field.IsExported(), field.Anonymous),
|
| 2633 |
+
Typ: field.Type.common(),
|
| 2634 |
+
Offset: 0,
|
| 2635 |
+
}
|
| 2636 |
+
return f, field.PkgPath
|
| 2637 |
+
}
|
| 2638 |
+
|
| 2639 |
+
// typeptrdata returns the length in bytes of the prefix of t
|
| 2640 |
+
// containing pointer data. Anything after this offset is scalar data.
|
| 2641 |
+
// keep in sync with ../cmd/compile/internal/reflectdata/reflect.go
|
| 2642 |
+
func typeptrdata(t *abi.Type) uintptr {
|
| 2643 |
+
switch t.Kind() {
|
| 2644 |
+
case abi.Struct:
|
| 2645 |
+
st := (*structType)(unsafe.Pointer(t))
|
| 2646 |
+
// find the last field that has pointers.
|
| 2647 |
+
field := -1
|
| 2648 |
+
for i := range st.Fields {
|
| 2649 |
+
ft := st.Fields[i].Typ
|
| 2650 |
+
if ft.Pointers() {
|
| 2651 |
+
field = i
|
| 2652 |
+
}
|
| 2653 |
+
}
|
| 2654 |
+
if field == -1 {
|
| 2655 |
+
return 0
|
| 2656 |
+
}
|
| 2657 |
+
f := st.Fields[field]
|
| 2658 |
+
return f.Offset + f.Typ.PtrBytes
|
| 2659 |
+
|
| 2660 |
+
default:
|
| 2661 |
+
panic("reflect.typeptrdata: unexpected type, " + stringFor(t))
|
| 2662 |
+
}
|
| 2663 |
+
}
|
| 2664 |
+
|
| 2665 |
+
// ArrayOf returns the array type with the given length and element type.
|
| 2666 |
+
// For example, if t represents int, ArrayOf(5, t) represents [5]int.
|
| 2667 |
+
//
|
| 2668 |
+
// If the resulting type would be larger than the available address space,
|
| 2669 |
+
// ArrayOf panics.
|
| 2670 |
+
func ArrayOf(length int, elem Type) Type {
|
| 2671 |
+
if length < 0 {
|
| 2672 |
+
panic("reflect: negative length passed to ArrayOf")
|
| 2673 |
+
}
|
| 2674 |
+
|
| 2675 |
+
typ := elem.common()
|
| 2676 |
+
|
| 2677 |
+
// Look in cache.
|
| 2678 |
+
ckey := cacheKey{Array, typ, nil, uintptr(length)}
|
| 2679 |
+
if array, ok := lookupCache.Load(ckey); ok {
|
| 2680 |
+
return array.(Type)
|
| 2681 |
+
}
|
| 2682 |
+
|
| 2683 |
+
// Look in known types.
|
| 2684 |
+
s := "[" + strconv.Itoa(length) + "]" + stringFor(typ)
|
| 2685 |
+
for _, tt := range typesByString(s) {
|
| 2686 |
+
array := (*arrayType)(unsafe.Pointer(tt))
|
| 2687 |
+
if array.Elem == typ {
|
| 2688 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(tt))
|
| 2689 |
+
return ti.(Type)
|
| 2690 |
+
}
|
| 2691 |
+
}
|
| 2692 |
+
|
| 2693 |
+
// Make an array type.
|
| 2694 |
+
var iarray any = [1]unsafe.Pointer{}
|
| 2695 |
+
prototype := *(**arrayType)(unsafe.Pointer(&iarray))
|
| 2696 |
+
array := *prototype
|
| 2697 |
+
array.TFlag = typ.TFlag & abi.TFlagRegularMemory
|
| 2698 |
+
array.Str = resolveReflectName(newName(s, "", false, false))
|
| 2699 |
+
array.Hash = fnv1(typ.Hash, '[')
|
| 2700 |
+
for n := uint32(length); n > 0; n >>= 8 {
|
| 2701 |
+
array.Hash = fnv1(array.Hash, byte(n))
|
| 2702 |
+
}
|
| 2703 |
+
array.Hash = fnv1(array.Hash, ']')
|
| 2704 |
+
array.Elem = typ
|
| 2705 |
+
array.PtrToThis = 0
|
| 2706 |
+
if typ.Size_ > 0 {
|
| 2707 |
+
max := ^uintptr(0) / typ.Size_
|
| 2708 |
+
if uintptr(length) > max {
|
| 2709 |
+
panic("reflect.ArrayOf: array size would exceed virtual address space")
|
| 2710 |
+
}
|
| 2711 |
+
}
|
| 2712 |
+
array.Size_ = typ.Size_ * uintptr(length)
|
| 2713 |
+
if length > 0 && typ.Pointers() {
|
| 2714 |
+
array.PtrBytes = typ.Size_*uintptr(length-1) + typ.PtrBytes
|
| 2715 |
+
} else {
|
| 2716 |
+
array.PtrBytes = 0
|
| 2717 |
+
}
|
| 2718 |
+
array.Align_ = typ.Align_
|
| 2719 |
+
array.FieldAlign_ = typ.FieldAlign_
|
| 2720 |
+
array.Len = uintptr(length)
|
| 2721 |
+
array.Slice = &(SliceOf(elem).(*rtype).t)
|
| 2722 |
+
|
| 2723 |
+
switch {
|
| 2724 |
+
case array.PtrBytes == 0:
|
| 2725 |
+
// No pointers.
|
| 2726 |
+
array.GCData = nil
|
| 2727 |
+
|
| 2728 |
+
case length == 1:
|
| 2729 |
+
// In memory, 1-element array looks just like the element.
|
| 2730 |
+
// We share the bitmask with the element type.
|
| 2731 |
+
array.TFlag |= typ.TFlag & abi.TFlagGCMaskOnDemand
|
| 2732 |
+
array.GCData = typ.GCData
|
| 2733 |
+
|
| 2734 |
+
case array.PtrBytes <= abi.MaxPtrmaskBytes*8*goarch.PtrSize:
|
| 2735 |
+
// Create pointer mask by repeating the element bitmask Len times.
|
| 2736 |
+
n := (array.PtrBytes/goarch.PtrSize + 7) / 8
|
| 2737 |
+
// Runtime needs pointer masks to be a multiple of uintptr in size.
|
| 2738 |
+
n = (n + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
|
| 2739 |
+
mask := make([]byte, n)
|
| 2740 |
+
emitGCMask(mask, 0, typ, array.Len)
|
| 2741 |
+
array.GCData = &mask[0]
|
| 2742 |
+
|
| 2743 |
+
default:
|
| 2744 |
+
// Runtime will build the mask if needed. We just need to allocate
|
| 2745 |
+
// space to store it.
|
| 2746 |
+
array.TFlag |= abi.TFlagGCMaskOnDemand
|
| 2747 |
+
array.GCData = (*byte)(unsafe.Pointer(new(uintptr)))
|
| 2748 |
+
}
|
| 2749 |
+
|
| 2750 |
+
etyp := typ
|
| 2751 |
+
esize := etyp.Size()
|
| 2752 |
+
|
| 2753 |
+
array.Equal = nil
|
| 2754 |
+
if eequal := etyp.Equal; eequal != nil {
|
| 2755 |
+
array.Equal = func(p, q unsafe.Pointer) bool {
|
| 2756 |
+
for i := 0; i < length; i++ {
|
| 2757 |
+
pi := arrayAt(p, i, esize, "i < length")
|
| 2758 |
+
qi := arrayAt(q, i, esize, "i < length")
|
| 2759 |
+
if !eequal(pi, qi) {
|
| 2760 |
+
return false
|
| 2761 |
+
}
|
| 2762 |
+
|
| 2763 |
+
}
|
| 2764 |
+
return true
|
| 2765 |
+
}
|
| 2766 |
+
}
|
| 2767 |
+
|
| 2768 |
+
switch {
|
| 2769 |
+
case array.Size_ == goarch.PtrSize && array.PtrBytes == goarch.PtrSize:
|
| 2770 |
+
array.TFlag |= abi.TFlagDirectIface
|
| 2771 |
+
default:
|
| 2772 |
+
array.TFlag &^= abi.TFlagDirectIface
|
| 2773 |
+
}
|
| 2774 |
+
|
| 2775 |
+
ti, _ := lookupCache.LoadOrStore(ckey, toRType(&array.Type))
|
| 2776 |
+
return ti.(Type)
|
| 2777 |
+
}
|
| 2778 |
+
|
| 2779 |
+
func appendVarint(x []byte, v uintptr) []byte {
|
| 2780 |
+
for ; v >= 0x80; v >>= 7 {
|
| 2781 |
+
x = append(x, byte(v|0x80))
|
| 2782 |
+
}
|
| 2783 |
+
x = append(x, byte(v))
|
| 2784 |
+
return x
|
| 2785 |
+
}
|
| 2786 |
+
|
| 2787 |
+
// toType converts from a *rtype to a Type that can be returned
|
| 2788 |
+
// to the client of package reflect. In gc, the only concern is that
|
| 2789 |
+
// a nil *rtype must be replaced by a nil Type, but in gccgo this
|
| 2790 |
+
// function takes care of ensuring that multiple *rtype for the same
|
| 2791 |
+
// type are coalesced into a single Type.
|
| 2792 |
+
//
|
| 2793 |
+
// toType should be an internal detail,
|
| 2794 |
+
// but widely used packages access it using linkname.
|
| 2795 |
+
// Notable members of the hall of shame include:
|
| 2796 |
+
// - fortio.org/log
|
| 2797 |
+
// - github.com/goccy/go-json
|
| 2798 |
+
// - github.com/goccy/go-reflect
|
| 2799 |
+
// - github.com/sohaha/zlsgo
|
| 2800 |
+
//
|
| 2801 |
+
// Do not remove or change the type signature.
|
| 2802 |
+
// See go.dev/issue/67401.
|
| 2803 |
+
//
|
| 2804 |
+
//go:linkname toType
|
| 2805 |
+
func toType(t *abi.Type) Type {
|
| 2806 |
+
if t == nil {
|
| 2807 |
+
return nil
|
| 2808 |
+
}
|
| 2809 |
+
return toRType(t)
|
| 2810 |
+
}
|
| 2811 |
+
|
| 2812 |
+
type layoutKey struct {
|
| 2813 |
+
ftyp *funcType // function signature
|
| 2814 |
+
rcvr *abi.Type // receiver type, or nil if none
|
| 2815 |
+
}
|
| 2816 |
+
|
| 2817 |
+
type layoutType struct {
|
| 2818 |
+
t *abi.Type
|
| 2819 |
+
framePool *sync.Pool
|
| 2820 |
+
abid abiDesc
|
| 2821 |
+
}
|
| 2822 |
+
|
| 2823 |
+
var layoutCache sync.Map // map[layoutKey]layoutType
|
| 2824 |
+
|
| 2825 |
+
// funcLayout computes a struct type representing the layout of the
|
| 2826 |
+
// stack-assigned function arguments and return values for the function
|
| 2827 |
+
// type t.
|
| 2828 |
+
// If rcvr != nil, rcvr specifies the type of the receiver.
|
| 2829 |
+
// The returned type exists only for GC, so we only fill out GC relevant info.
|
| 2830 |
+
// Currently, that's just size and the GC program. We also fill in
|
| 2831 |
+
// the name for possible debugging use.
|
| 2832 |
+
func funcLayout(t *funcType, rcvr *abi.Type) (frametype *abi.Type, framePool *sync.Pool, abid abiDesc) {
|
| 2833 |
+
if t.Kind() != abi.Func {
|
| 2834 |
+
panic("reflect: funcLayout of non-func type " + stringFor(&t.Type))
|
| 2835 |
+
}
|
| 2836 |
+
if rcvr != nil && rcvr.Kind() == abi.Interface {
|
| 2837 |
+
panic("reflect: funcLayout with interface receiver " + stringFor(rcvr))
|
| 2838 |
+
}
|
| 2839 |
+
k := layoutKey{t, rcvr}
|
| 2840 |
+
if lti, ok := layoutCache.Load(k); ok {
|
| 2841 |
+
lt := lti.(layoutType)
|
| 2842 |
+
return lt.t, lt.framePool, lt.abid
|
| 2843 |
+
}
|
| 2844 |
+
|
| 2845 |
+
// Compute the ABI layout.
|
| 2846 |
+
abid = newAbiDesc(t, rcvr)
|
| 2847 |
+
|
| 2848 |
+
// build dummy rtype holding gc program
|
| 2849 |
+
x := &abi.Type{
|
| 2850 |
+
Align_: goarch.PtrSize,
|
| 2851 |
+
// Don't add spill space here; it's only necessary in
|
| 2852 |
+
// reflectcall's frame, not in the allocated frame.
|
| 2853 |
+
// TODO(mknyszek): Remove this comment when register
|
| 2854 |
+
// spill space in the frame is no longer required.
|
| 2855 |
+
Size_: align(abid.retOffset+abid.ret.stackBytes, goarch.PtrSize),
|
| 2856 |
+
PtrBytes: uintptr(abid.stackPtrs.n) * goarch.PtrSize,
|
| 2857 |
+
}
|
| 2858 |
+
if abid.stackPtrs.n > 0 {
|
| 2859 |
+
x.GCData = &abid.stackPtrs.data[0]
|
| 2860 |
+
}
|
| 2861 |
+
|
| 2862 |
+
var s string
|
| 2863 |
+
if rcvr != nil {
|
| 2864 |
+
s = "methodargs(" + stringFor(rcvr) + ")(" + stringFor(&t.Type) + ")"
|
| 2865 |
+
} else {
|
| 2866 |
+
s = "funcargs(" + stringFor(&t.Type) + ")"
|
| 2867 |
+
}
|
| 2868 |
+
x.Str = resolveReflectName(newName(s, "", false, false))
|
| 2869 |
+
|
| 2870 |
+
// cache result for future callers
|
| 2871 |
+
framePool = &sync.Pool{New: func() any {
|
| 2872 |
+
return unsafe_New(x)
|
| 2873 |
+
}}
|
| 2874 |
+
lti, _ := layoutCache.LoadOrStore(k, layoutType{
|
| 2875 |
+
t: x,
|
| 2876 |
+
framePool: framePool,
|
| 2877 |
+
abid: abid,
|
| 2878 |
+
})
|
| 2879 |
+
lt := lti.(layoutType)
|
| 2880 |
+
return lt.t, lt.framePool, lt.abid
|
| 2881 |
+
}
|
| 2882 |
+
|
| 2883 |
+
// Note: this type must agree with runtime.bitvector.
|
| 2884 |
+
type bitVector struct {
|
| 2885 |
+
n uint32 // number of bits
|
| 2886 |
+
data []byte
|
| 2887 |
+
}
|
| 2888 |
+
|
| 2889 |
+
// append a bit to the bitmap.
|
| 2890 |
+
func (bv *bitVector) append(bit uint8) {
|
| 2891 |
+
if bv.n%(8*goarch.PtrSize) == 0 {
|
| 2892 |
+
// Runtime needs pointer masks to be a multiple of uintptr in size.
|
| 2893 |
+
// Since reflect passes bv.data directly to the runtime as a pointer mask,
|
| 2894 |
+
// we append a full uintptr of zeros at a time.
|
| 2895 |
+
for i := 0; i < goarch.PtrSize; i++ {
|
| 2896 |
+
bv.data = append(bv.data, 0)
|
| 2897 |
+
}
|
| 2898 |
+
}
|
| 2899 |
+
bv.data[bv.n/8] |= bit << (bv.n % 8)
|
| 2900 |
+
bv.n++
|
| 2901 |
+
}
|
| 2902 |
+
|
| 2903 |
+
func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
|
| 2904 |
+
if !t.Pointers() {
|
| 2905 |
+
return
|
| 2906 |
+
}
|
| 2907 |
+
|
| 2908 |
+
switch Kind(t.Kind()) {
|
| 2909 |
+
case Chan, Func, Map, Pointer, Slice, String, UnsafePointer:
|
| 2910 |
+
// 1 pointer at start of representation
|
| 2911 |
+
for bv.n < uint32(offset/goarch.PtrSize) {
|
| 2912 |
+
bv.append(0)
|
| 2913 |
+
}
|
| 2914 |
+
bv.append(1)
|
| 2915 |
+
|
| 2916 |
+
case Interface:
|
| 2917 |
+
// 2 pointers
|
| 2918 |
+
for bv.n < uint32(offset/goarch.PtrSize) {
|
| 2919 |
+
bv.append(0)
|
| 2920 |
+
}
|
| 2921 |
+
bv.append(1)
|
| 2922 |
+
bv.append(1)
|
| 2923 |
+
|
| 2924 |
+
case Array:
|
| 2925 |
+
// repeat inner type
|
| 2926 |
+
tt := (*arrayType)(unsafe.Pointer(t))
|
| 2927 |
+
for i := 0; i < int(tt.Len); i++ {
|
| 2928 |
+
addTypeBits(bv, offset+uintptr(i)*tt.Elem.Size_, tt.Elem)
|
| 2929 |
+
}
|
| 2930 |
+
|
| 2931 |
+
case Struct:
|
| 2932 |
+
// apply fields
|
| 2933 |
+
tt := (*structType)(unsafe.Pointer(t))
|
| 2934 |
+
for i := range tt.Fields {
|
| 2935 |
+
f := &tt.Fields[i]
|
| 2936 |
+
addTypeBits(bv, offset+f.Offset, f.Typ)
|
| 2937 |
+
}
|
| 2938 |
+
}
|
| 2939 |
+
}
|
go/src/reflect/type_test.go
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
// license that can be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
package reflect_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"reflect"
|
| 9 |
+
"testing"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
func TestTypeFor(t *testing.T) {
|
| 13 |
+
type (
|
| 14 |
+
mystring string
|
| 15 |
+
myiface any
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
testcases := []struct {
|
| 19 |
+
wantFrom any
|
| 20 |
+
got reflect.Type
|
| 21 |
+
}{
|
| 22 |
+
{new(int), reflect.TypeFor[int]()},
|
| 23 |
+
{new(int64), reflect.TypeFor[int64]()},
|
| 24 |
+
{new(string), reflect.TypeFor[string]()},
|
| 25 |
+
{new(mystring), reflect.TypeFor[mystring]()},
|
| 26 |
+
{new(any), reflect.TypeFor[any]()},
|
| 27 |
+
{new(myiface), reflect.TypeFor[myiface]()},
|
| 28 |
+
}
|
| 29 |
+
for _, tc := range testcases {
|
| 30 |
+
want := reflect.ValueOf(tc.wantFrom).Elem().Type()
|
| 31 |
+
if want != tc.got {
|
| 32 |
+
t.Errorf("unexpected reflect.Type: got %v; want %v", tc.got, want)
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
func TestStructOfEmbeddedIfaceMethodCall(t *testing.T) {
|
| 38 |
+
type Named interface {
|
| 39 |
+
Name() string
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
typ := reflect.StructOf([]reflect.StructField{
|
| 43 |
+
{
|
| 44 |
+
Anonymous: true,
|
| 45 |
+
Name: "Named",
|
| 46 |
+
Type: reflect.TypeFor[Named](),
|
| 47 |
+
},
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
v := reflect.New(typ).Elem()
|
| 51 |
+
v.Field(0).Set(
|
| 52 |
+
reflect.ValueOf(reflect.TypeFor[string]()),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
x := v.Interface().(Named)
|
| 56 |
+
shouldPanic("StructOf does not support methods of embedded interfaces", func() {
|
| 57 |
+
_ = x.Name()
|
| 58 |
+
})
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
func TestIsRegularMemory(t *testing.T) {
|
| 62 |
+
type args struct {
|
| 63 |
+
t reflect.Type
|
| 64 |
+
}
|
| 65 |
+
type S struct {
|
| 66 |
+
int
|
| 67 |
+
}
|
| 68 |
+
tests := []struct {
|
| 69 |
+
name string
|
| 70 |
+
args args
|
| 71 |
+
want bool
|
| 72 |
+
}{
|
| 73 |
+
{"struct{i int}", args{reflect.TypeOf(struct{ i int }{})}, true},
|
| 74 |
+
{"struct{}", args{reflect.TypeOf(struct{}{})}, true},
|
| 75 |
+
{"struct{i int; s S}", args{reflect.TypeOf(struct {
|
| 76 |
+
i int
|
| 77 |
+
s S
|
| 78 |
+
}{})}, true},
|
| 79 |
+
{"map[int][int]", args{reflect.TypeOf(map[int]int{})}, false},
|
| 80 |
+
{"[4]chan int", args{reflect.TypeOf([4]chan int{})}, true},
|
| 81 |
+
{"[0]struct{_ S}", args{reflect.TypeOf([0]struct {
|
| 82 |
+
_ S
|
| 83 |
+
}{})}, true},
|
| 84 |
+
{"struct{i int; _ S}", args{reflect.TypeOf(struct {
|
| 85 |
+
i int
|
| 86 |
+
_ S
|
| 87 |
+
}{})}, false},
|
| 88 |
+
{"struct{a int16; b int32}", args{reflect.TypeOf(struct {
|
| 89 |
+
a int16
|
| 90 |
+
b int32
|
| 91 |
+
}{})}, false},
|
| 92 |
+
{"struct {x int32; y int16}", args{reflect.TypeOf(struct {
|
| 93 |
+
x int32
|
| 94 |
+
y int16
|
| 95 |
+
}{})}, false},
|
| 96 |
+
{"struct {_ int32 }", args{reflect.TypeOf(struct{ _ int32 }{})}, false},
|
| 97 |
+
}
|
| 98 |
+
for _, tt := range tests {
|
| 99 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 100 |
+
if got := reflect.IsRegularMemory(tt.args.t); got != tt.want {
|
| 101 |
+
t.Errorf("isRegularMemory() = %v, want %v", got, tt.want)
|
| 102 |
+
}
|
| 103 |
+
})
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
var sinkType reflect.Type
|
| 108 |
+
|
| 109 |
+
func BenchmarkTypeForString(b *testing.B) {
|
| 110 |
+
for i := 0; i < b.N; i++ {
|
| 111 |
+
sinkType = reflect.TypeFor[string]()
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
func BenchmarkTypeForError(b *testing.B) {
|
| 116 |
+
for i := 0; i < b.N; i++ {
|
| 117 |
+
sinkType = reflect.TypeFor[error]()
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
func TestType_CanSeq(t *testing.T) {
|
| 122 |
+
tests := []struct {
|
| 123 |
+
name string
|
| 124 |
+
tr reflect.Type
|
| 125 |
+
want bool
|
| 126 |
+
}{
|
| 127 |
+
{"func(func(int) bool)", reflect.TypeOf(func(func(int) bool) {}), true},
|
| 128 |
+
{"func(func(int))", reflect.TypeOf(func(func(int)) {}), false},
|
| 129 |
+
{"methodIter.Seq", reflect.ValueOf(methodIter{}).MethodByName("Seq").Type(), true},
|
| 130 |
+
{"methodIter.NonSeq", reflect.ValueOf(methodIter{}).MethodByName("NonSeq").Type(), false},
|
| 131 |
+
{"int64", reflect.TypeOf(int64(1)), true},
|
| 132 |
+
{"uint64", reflect.TypeOf(uint64(1)), true},
|
| 133 |
+
{"*[4]int", reflect.TypeOf(&[4]int{}), true},
|
| 134 |
+
{"chan int64", reflect.TypeOf(make(chan int64)), true},
|
| 135 |
+
{"map[int]int", reflect.TypeOf(make(map[int]int)), true},
|
| 136 |
+
{"string", reflect.TypeOf(""), true},
|
| 137 |
+
{"[]int", reflect.TypeOf([]int{}), true},
|
| 138 |
+
}
|
| 139 |
+
for _, tt := range tests {
|
| 140 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 141 |
+
if got := tt.tr.CanSeq(); got != tt.want {
|
| 142 |
+
t.Errorf("Type.CanSeq() = %v, want %v", got, tt.want)
|
| 143 |
+
}
|
| 144 |
+
})
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
func TestType_CanSeq2(t *testing.T) {
|
| 149 |
+
tests := []struct {
|
| 150 |
+
name string
|
| 151 |
+
tr reflect.Type
|
| 152 |
+
want bool
|
| 153 |
+
}{
|
| 154 |
+
{"func(func(int, int) bool)", reflect.TypeOf(func(func(int, int) bool) {}), true},
|
| 155 |
+
{"func(func(int, int))", reflect.TypeOf(func(func(int, int)) {}), false},
|
| 156 |
+
{"methodIter2.Seq2", reflect.ValueOf(methodIter2{}).MethodByName("Seq2").Type(), true},
|
| 157 |
+
{"methodIter2.NonSeq2", reflect.ValueOf(methodIter2{}).MethodByName("NonSeq2").Type(), false},
|
| 158 |
+
{"int64", reflect.TypeOf(int64(1)), false},
|
| 159 |
+
{"uint64", reflect.TypeOf(uint64(1)), false},
|
| 160 |
+
{"*[4]int", reflect.TypeOf(&[4]int{}), true},
|
| 161 |
+
{"chan int64", reflect.TypeOf(make(chan int64)), false},
|
| 162 |
+
{"map[int]int", reflect.TypeOf(make(map[int]int)), true},
|
| 163 |
+
{"string", reflect.TypeOf(""), true},
|
| 164 |
+
{"[]int", reflect.TypeOf([]int{}), true},
|
| 165 |
+
}
|
| 166 |
+
for _, tt := range tests {
|
| 167 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 168 |
+
if got := tt.tr.CanSeq2(); got != tt.want {
|
| 169 |
+
t.Errorf("Type.CanSeq2() = %v, want %v", got, tt.want)
|
| 170 |
+
}
|
| 171 |
+
})
|
| 172 |
+
}
|
| 173 |
+
}
|
go/src/reflect/value.go
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
go/src/reflect/visiblefields.go
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package reflect
|
| 6 |
+
|
| 7 |
+
// VisibleFields returns all the visible fields in t, which must be a
|
| 8 |
+
// struct type. A field is defined as visible if it's accessible
|
| 9 |
+
// directly with a FieldByName call. The returned fields include fields
|
| 10 |
+
// inside anonymous struct members and unexported fields. They follow
|
| 11 |
+
// the same order found in the struct, with anonymous fields followed
|
| 12 |
+
// immediately by their promoted fields.
|
| 13 |
+
//
|
| 14 |
+
// For each element e of the returned slice, the corresponding field
|
| 15 |
+
// can be retrieved from a value v of type t by calling v.FieldByIndex(e.Index).
|
| 16 |
+
func VisibleFields(t Type) []StructField {
|
| 17 |
+
if t == nil {
|
| 18 |
+
panic("reflect: VisibleFields(nil)")
|
| 19 |
+
}
|
| 20 |
+
if t.Kind() != Struct {
|
| 21 |
+
panic("reflect.VisibleFields of non-struct type")
|
| 22 |
+
}
|
| 23 |
+
w := &visibleFieldsWalker{
|
| 24 |
+
byName: make(map[string]int),
|
| 25 |
+
visiting: make(map[Type]bool),
|
| 26 |
+
fields: make([]StructField, 0, t.NumField()),
|
| 27 |
+
index: make([]int, 0, 2),
|
| 28 |
+
}
|
| 29 |
+
w.walk(t)
|
| 30 |
+
// Remove all the fields that have been hidden.
|
| 31 |
+
// Use an in-place removal that avoids copying in
|
| 32 |
+
// the common case that there are no hidden fields.
|
| 33 |
+
j := 0
|
| 34 |
+
for i := range w.fields {
|
| 35 |
+
f := &w.fields[i]
|
| 36 |
+
if f.Name == "" {
|
| 37 |
+
continue
|
| 38 |
+
}
|
| 39 |
+
if i != j {
|
| 40 |
+
// A field has been removed. We need to shuffle
|
| 41 |
+
// all the subsequent elements up.
|
| 42 |
+
w.fields[j] = *f
|
| 43 |
+
}
|
| 44 |
+
j++
|
| 45 |
+
}
|
| 46 |
+
return w.fields[:j]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
type visibleFieldsWalker struct {
|
| 50 |
+
byName map[string]int
|
| 51 |
+
visiting map[Type]bool
|
| 52 |
+
fields []StructField
|
| 53 |
+
index []int
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// walk walks all the fields in the struct type t, visiting
|
| 57 |
+
// fields in index preorder and appending them to w.fields
|
| 58 |
+
// (this maintains the required ordering).
|
| 59 |
+
// Fields that have been overridden have their
|
| 60 |
+
// Name field cleared.
|
| 61 |
+
func (w *visibleFieldsWalker) walk(t Type) {
|
| 62 |
+
if w.visiting[t] {
|
| 63 |
+
return
|
| 64 |
+
}
|
| 65 |
+
w.visiting[t] = true
|
| 66 |
+
for i := 0; i < t.NumField(); i++ {
|
| 67 |
+
f := t.Field(i)
|
| 68 |
+
w.index = append(w.index, i)
|
| 69 |
+
add := true
|
| 70 |
+
if oldIndex, ok := w.byName[f.Name]; ok {
|
| 71 |
+
old := &w.fields[oldIndex]
|
| 72 |
+
if len(w.index) == len(old.Index) {
|
| 73 |
+
// Fields with the same name at the same depth
|
| 74 |
+
// cancel one another out. Set the field name
|
| 75 |
+
// to empty to signify that has happened, and
|
| 76 |
+
// there's no need to add this field.
|
| 77 |
+
old.Name = ""
|
| 78 |
+
add = false
|
| 79 |
+
} else if len(w.index) < len(old.Index) {
|
| 80 |
+
// The old field loses because it's deeper than the new one.
|
| 81 |
+
old.Name = ""
|
| 82 |
+
} else {
|
| 83 |
+
// The old field wins because it's shallower than the new one.
|
| 84 |
+
add = false
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
if add {
|
| 88 |
+
// Copy the index so that it's not overwritten
|
| 89 |
+
// by the other appends.
|
| 90 |
+
f.Index = append([]int(nil), w.index...)
|
| 91 |
+
w.byName[f.Name] = len(w.fields)
|
| 92 |
+
w.fields = append(w.fields, f)
|
| 93 |
+
}
|
| 94 |
+
if f.Anonymous {
|
| 95 |
+
if f.Type.Kind() == Pointer {
|
| 96 |
+
f.Type = f.Type.Elem()
|
| 97 |
+
}
|
| 98 |
+
if f.Type.Kind() == Struct {
|
| 99 |
+
w.walk(f.Type)
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
w.index = w.index[:len(w.index)-1]
|
| 103 |
+
}
|
| 104 |
+
delete(w.visiting, t)
|
| 105 |
+
}
|
go/src/reflect/visiblefields_test.go
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
package reflect_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
. "reflect"
|
| 9 |
+
"strings"
|
| 10 |
+
"testing"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
type structField struct {
|
| 14 |
+
name string
|
| 15 |
+
index []int
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
var fieldsTests = []struct {
|
| 19 |
+
testName string
|
| 20 |
+
val any
|
| 21 |
+
expect []structField
|
| 22 |
+
}{{
|
| 23 |
+
testName: "SimpleStruct",
|
| 24 |
+
val: struct {
|
| 25 |
+
A int
|
| 26 |
+
B string
|
| 27 |
+
C bool
|
| 28 |
+
}{},
|
| 29 |
+
expect: []structField{{
|
| 30 |
+
name: "A",
|
| 31 |
+
index: []int{0},
|
| 32 |
+
}, {
|
| 33 |
+
name: "B",
|
| 34 |
+
index: []int{1},
|
| 35 |
+
}, {
|
| 36 |
+
name: "C",
|
| 37 |
+
index: []int{2},
|
| 38 |
+
}},
|
| 39 |
+
}, {
|
| 40 |
+
testName: "NonEmbeddedStructMember",
|
| 41 |
+
val: struct {
|
| 42 |
+
A struct {
|
| 43 |
+
X int
|
| 44 |
+
}
|
| 45 |
+
}{},
|
| 46 |
+
expect: []structField{{
|
| 47 |
+
name: "A",
|
| 48 |
+
index: []int{0},
|
| 49 |
+
}},
|
| 50 |
+
}, {
|
| 51 |
+
testName: "EmbeddedExportedStruct",
|
| 52 |
+
val: struct {
|
| 53 |
+
SFG
|
| 54 |
+
}{},
|
| 55 |
+
expect: []structField{{
|
| 56 |
+
name: "SFG",
|
| 57 |
+
index: []int{0},
|
| 58 |
+
}, {
|
| 59 |
+
name: "F",
|
| 60 |
+
index: []int{0, 0},
|
| 61 |
+
}, {
|
| 62 |
+
name: "G",
|
| 63 |
+
index: []int{0, 1},
|
| 64 |
+
}},
|
| 65 |
+
}, {
|
| 66 |
+
testName: "EmbeddedUnexportedStruct",
|
| 67 |
+
val: struct {
|
| 68 |
+
sFG
|
| 69 |
+
}{},
|
| 70 |
+
expect: []structField{{
|
| 71 |
+
name: "sFG",
|
| 72 |
+
index: []int{0},
|
| 73 |
+
}, {
|
| 74 |
+
name: "F",
|
| 75 |
+
index: []int{0, 0},
|
| 76 |
+
}, {
|
| 77 |
+
name: "G",
|
| 78 |
+
index: []int{0, 1},
|
| 79 |
+
}},
|
| 80 |
+
}, {
|
| 81 |
+
testName: "TwoEmbeddedStructsWithCancelingMembers",
|
| 82 |
+
val: struct {
|
| 83 |
+
SFG
|
| 84 |
+
SF
|
| 85 |
+
}{},
|
| 86 |
+
expect: []structField{{
|
| 87 |
+
name: "SFG",
|
| 88 |
+
index: []int{0},
|
| 89 |
+
}, {
|
| 90 |
+
name: "G",
|
| 91 |
+
index: []int{0, 1},
|
| 92 |
+
}, {
|
| 93 |
+
name: "SF",
|
| 94 |
+
index: []int{1},
|
| 95 |
+
}},
|
| 96 |
+
}, {
|
| 97 |
+
testName: "EmbeddedStructsWithSameFieldsAtDifferentDepths",
|
| 98 |
+
val: struct {
|
| 99 |
+
SFGH3
|
| 100 |
+
SG1
|
| 101 |
+
SFG2
|
| 102 |
+
SF2
|
| 103 |
+
L int
|
| 104 |
+
}{},
|
| 105 |
+
expect: []structField{{
|
| 106 |
+
name: "SFGH3",
|
| 107 |
+
index: []int{0},
|
| 108 |
+
}, {
|
| 109 |
+
name: "SFGH2",
|
| 110 |
+
index: []int{0, 0},
|
| 111 |
+
}, {
|
| 112 |
+
name: "SFGH1",
|
| 113 |
+
index: []int{0, 0, 0},
|
| 114 |
+
}, {
|
| 115 |
+
name: "SFGH",
|
| 116 |
+
index: []int{0, 0, 0, 0},
|
| 117 |
+
}, {
|
| 118 |
+
name: "H",
|
| 119 |
+
index: []int{0, 0, 0, 0, 2},
|
| 120 |
+
}, {
|
| 121 |
+
name: "SG1",
|
| 122 |
+
index: []int{1},
|
| 123 |
+
}, {
|
| 124 |
+
name: "SG",
|
| 125 |
+
index: []int{1, 0},
|
| 126 |
+
}, {
|
| 127 |
+
name: "G",
|
| 128 |
+
index: []int{1, 0, 0},
|
| 129 |
+
}, {
|
| 130 |
+
name: "SFG2",
|
| 131 |
+
index: []int{2},
|
| 132 |
+
}, {
|
| 133 |
+
name: "SFG1",
|
| 134 |
+
index: []int{2, 0},
|
| 135 |
+
}, {
|
| 136 |
+
name: "SFG",
|
| 137 |
+
index: []int{2, 0, 0},
|
| 138 |
+
}, {
|
| 139 |
+
name: "SF2",
|
| 140 |
+
index: []int{3},
|
| 141 |
+
}, {
|
| 142 |
+
name: "SF1",
|
| 143 |
+
index: []int{3, 0},
|
| 144 |
+
}, {
|
| 145 |
+
name: "SF",
|
| 146 |
+
index: []int{3, 0, 0},
|
| 147 |
+
}, {
|
| 148 |
+
name: "L",
|
| 149 |
+
index: []int{4},
|
| 150 |
+
}},
|
| 151 |
+
}, {
|
| 152 |
+
testName: "EmbeddedPointerStruct",
|
| 153 |
+
val: struct {
|
| 154 |
+
*SF
|
| 155 |
+
}{},
|
| 156 |
+
expect: []structField{{
|
| 157 |
+
name: "SF",
|
| 158 |
+
index: []int{0},
|
| 159 |
+
}, {
|
| 160 |
+
name: "F",
|
| 161 |
+
index: []int{0, 0},
|
| 162 |
+
}},
|
| 163 |
+
}, {
|
| 164 |
+
testName: "EmbeddedNotAPointer",
|
| 165 |
+
val: struct {
|
| 166 |
+
M
|
| 167 |
+
}{},
|
| 168 |
+
expect: []structField{{
|
| 169 |
+
name: "M",
|
| 170 |
+
index: []int{0},
|
| 171 |
+
}},
|
| 172 |
+
}, {
|
| 173 |
+
testName: "RecursiveEmbedding",
|
| 174 |
+
val: Rec1{},
|
| 175 |
+
expect: []structField{{
|
| 176 |
+
name: "Rec2",
|
| 177 |
+
index: []int{0},
|
| 178 |
+
}, {
|
| 179 |
+
name: "F",
|
| 180 |
+
index: []int{0, 0},
|
| 181 |
+
}, {
|
| 182 |
+
name: "Rec1",
|
| 183 |
+
index: []int{0, 1},
|
| 184 |
+
}},
|
| 185 |
+
}, {
|
| 186 |
+
testName: "RecursiveEmbedding2",
|
| 187 |
+
val: Rec2{},
|
| 188 |
+
expect: []structField{{
|
| 189 |
+
name: "F",
|
| 190 |
+
index: []int{0},
|
| 191 |
+
}, {
|
| 192 |
+
name: "Rec1",
|
| 193 |
+
index: []int{1},
|
| 194 |
+
}, {
|
| 195 |
+
name: "Rec2",
|
| 196 |
+
index: []int{1, 0},
|
| 197 |
+
}},
|
| 198 |
+
}, {
|
| 199 |
+
testName: "RecursiveEmbedding3",
|
| 200 |
+
val: RS3{},
|
| 201 |
+
expect: []structField{{
|
| 202 |
+
name: "RS2",
|
| 203 |
+
index: []int{0},
|
| 204 |
+
}, {
|
| 205 |
+
name: "RS1",
|
| 206 |
+
index: []int{1},
|
| 207 |
+
}, {
|
| 208 |
+
name: "i",
|
| 209 |
+
index: []int{1, 0},
|
| 210 |
+
}},
|
| 211 |
+
}}
|
| 212 |
+
|
| 213 |
+
type SFG struct {
|
| 214 |
+
F int
|
| 215 |
+
G int
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
type SFG1 struct {
|
| 219 |
+
SFG
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
type SFG2 struct {
|
| 223 |
+
SFG1
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
type SFGH struct {
|
| 227 |
+
F int
|
| 228 |
+
G int
|
| 229 |
+
H int
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
type SFGH1 struct {
|
| 233 |
+
SFGH
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
type SFGH2 struct {
|
| 237 |
+
SFGH1
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
type SFGH3 struct {
|
| 241 |
+
SFGH2
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
type SF struct {
|
| 245 |
+
F int
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
type SF1 struct {
|
| 249 |
+
SF
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
type SF2 struct {
|
| 253 |
+
SF1
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
type SG struct {
|
| 257 |
+
G int
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
type SG1 struct {
|
| 261 |
+
SG
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
type sFG struct {
|
| 265 |
+
F int
|
| 266 |
+
G int
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
type RS1 struct {
|
| 270 |
+
i int
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
type RS2 struct {
|
| 274 |
+
RS1
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
type RS3 struct {
|
| 278 |
+
RS2
|
| 279 |
+
RS1
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
type M map[string]any
|
| 283 |
+
|
| 284 |
+
type Rec1 struct {
|
| 285 |
+
*Rec2
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
type Rec2 struct {
|
| 289 |
+
F string
|
| 290 |
+
*Rec1
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
func TestFields(t *testing.T) {
|
| 294 |
+
for _, test := range fieldsTests {
|
| 295 |
+
t.Run(test.testName, func(t *testing.T) {
|
| 296 |
+
typ := TypeOf(test.val)
|
| 297 |
+
fields := VisibleFields(typ)
|
| 298 |
+
if got, want := len(fields), len(test.expect); got != want {
|
| 299 |
+
t.Fatalf("unexpected field count; got %d want %d", got, want)
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
for j, field := range fields {
|
| 303 |
+
expect := test.expect[j]
|
| 304 |
+
t.Logf("field %d: %s", j, expect.name)
|
| 305 |
+
gotField := typ.FieldByIndex(field.Index)
|
| 306 |
+
// Unfortunately, FieldByIndex does not return
|
| 307 |
+
// a field with the same index that we passed in,
|
| 308 |
+
// so we set it to the expected value so that
|
| 309 |
+
// it can be compared later with the result of FieldByName.
|
| 310 |
+
gotField.Index = field.Index
|
| 311 |
+
expectField := typ.FieldByIndex(expect.index)
|
| 312 |
+
// ditto.
|
| 313 |
+
expectField.Index = expect.index
|
| 314 |
+
if !DeepEqual(gotField, expectField) {
|
| 315 |
+
t.Fatalf("unexpected field result\ngot %#v\nwant %#v", gotField, expectField)
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
// Sanity check that we can actually access the field by the
|
| 319 |
+
// expected name.
|
| 320 |
+
gotField1, ok := typ.FieldByName(expect.name)
|
| 321 |
+
if !ok {
|
| 322 |
+
t.Fatalf("field %q not accessible by name", expect.name)
|
| 323 |
+
}
|
| 324 |
+
if !DeepEqual(gotField1, expectField) {
|
| 325 |
+
t.Fatalf("unexpected FieldByName result; got %#v want %#v", gotField1, expectField)
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
})
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
// Must not panic with nil embedded pointer.
|
| 333 |
+
func TestFieldByIndexErr(t *testing.T) {
|
| 334 |
+
type A struct {
|
| 335 |
+
S string
|
| 336 |
+
}
|
| 337 |
+
type B struct {
|
| 338 |
+
*A
|
| 339 |
+
}
|
| 340 |
+
v := ValueOf(B{})
|
| 341 |
+
_, err := v.FieldByIndexErr([]int{0, 0})
|
| 342 |
+
if err == nil {
|
| 343 |
+
t.Fatal("expected error")
|
| 344 |
+
}
|
| 345 |
+
if !strings.Contains(err.Error(), "embedded struct field A") {
|
| 346 |
+
t.Fatal(err)
|
| 347 |
+
}
|
| 348 |
+
}
|
go/src/regexp/all_test.go
ADDED
|
@@ -0,0 +1,991 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"reflect"
|
| 9 |
+
"regexp/syntax"
|
| 10 |
+
"slices"
|
| 11 |
+
"strings"
|
| 12 |
+
"testing"
|
| 13 |
+
"unicode/utf8"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
var goodRe = []string{
|
| 17 |
+
``,
|
| 18 |
+
`.`,
|
| 19 |
+
`^.$`,
|
| 20 |
+
`a`,
|
| 21 |
+
`a*`,
|
| 22 |
+
`a+`,
|
| 23 |
+
`a?`,
|
| 24 |
+
`a|b`,
|
| 25 |
+
`a*|b*`,
|
| 26 |
+
`(a*|b)(c*|d)`,
|
| 27 |
+
`[a-z]`,
|
| 28 |
+
`[a-abc-c\-\]\[]`,
|
| 29 |
+
`[a-z]+`,
|
| 30 |
+
`[abc]`,
|
| 31 |
+
`[^1234]`,
|
| 32 |
+
`[^\n]`,
|
| 33 |
+
`\!\\`,
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
type stringError struct {
|
| 37 |
+
re string
|
| 38 |
+
err string
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
var badRe = []stringError{
|
| 42 |
+
{`*`, "missing argument to repetition operator: `*`"},
|
| 43 |
+
{`+`, "missing argument to repetition operator: `+`"},
|
| 44 |
+
{`?`, "missing argument to repetition operator: `?`"},
|
| 45 |
+
{`(abc`, "missing closing ): `(abc`"},
|
| 46 |
+
{`abc)`, "unexpected ): `abc)`"},
|
| 47 |
+
{`x[a-z`, "missing closing ]: `[a-z`"},
|
| 48 |
+
{`[z-a]`, "invalid character class range: `z-a`"},
|
| 49 |
+
{`abc\`, "trailing backslash at end of expression"},
|
| 50 |
+
{`a**`, "invalid nested repetition operator: `**`"},
|
| 51 |
+
{`a*+`, "invalid nested repetition operator: `*+`"},
|
| 52 |
+
{`\x`, "invalid escape sequence: `\\x`"},
|
| 53 |
+
{strings.Repeat(`\pL`, 27000), "expression too large"},
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func compileTest(t *testing.T, expr string, error string) *Regexp {
|
| 57 |
+
re, err := Compile(expr)
|
| 58 |
+
if error == "" && err != nil {
|
| 59 |
+
t.Error("compiling `", expr, "`; unexpected error: ", err.Error())
|
| 60 |
+
}
|
| 61 |
+
if error != "" && err == nil {
|
| 62 |
+
t.Error("compiling `", expr, "`; missing error")
|
| 63 |
+
} else if error != "" && !strings.Contains(err.Error(), error) {
|
| 64 |
+
t.Error("compiling `", expr, "`; wrong error: ", err.Error(), "; want ", error)
|
| 65 |
+
}
|
| 66 |
+
return re
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
func TestGoodCompile(t *testing.T) {
|
| 70 |
+
for i := 0; i < len(goodRe); i++ {
|
| 71 |
+
compileTest(t, goodRe[i], "")
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
func TestBadCompile(t *testing.T) {
|
| 76 |
+
for i := 0; i < len(badRe); i++ {
|
| 77 |
+
compileTest(t, badRe[i].re, badRe[i].err)
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func matchTest(t *testing.T, test *FindTest) {
|
| 82 |
+
re := compileTest(t, test.pat, "")
|
| 83 |
+
if re == nil {
|
| 84 |
+
return
|
| 85 |
+
}
|
| 86 |
+
m := re.MatchString(test.text)
|
| 87 |
+
if m != (len(test.matches) > 0) {
|
| 88 |
+
t.Errorf("MatchString failure on %s: %t should be %t", test, m, len(test.matches) > 0)
|
| 89 |
+
}
|
| 90 |
+
// now try bytes
|
| 91 |
+
m = re.Match([]byte(test.text))
|
| 92 |
+
if m != (len(test.matches) > 0) {
|
| 93 |
+
t.Errorf("Match failure on %s: %t should be %t", test, m, len(test.matches) > 0)
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
func TestMatch(t *testing.T) {
|
| 98 |
+
for _, test := range findTests {
|
| 99 |
+
matchTest(t, &test)
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
func matchFunctionTest(t *testing.T, test *FindTest) {
|
| 104 |
+
m, err := MatchString(test.pat, test.text)
|
| 105 |
+
if err == nil {
|
| 106 |
+
return
|
| 107 |
+
}
|
| 108 |
+
if m != (len(test.matches) > 0) {
|
| 109 |
+
t.Errorf("Match failure on %s: %t should be %t", test, m, len(test.matches) > 0)
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
func TestMatchFunction(t *testing.T) {
|
| 114 |
+
for _, test := range findTests {
|
| 115 |
+
matchFunctionTest(t, &test)
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
func copyMatchTest(t *testing.T, test *FindTest) {
|
| 120 |
+
re := compileTest(t, test.pat, "")
|
| 121 |
+
if re == nil {
|
| 122 |
+
return
|
| 123 |
+
}
|
| 124 |
+
m1 := re.MatchString(test.text)
|
| 125 |
+
m2 := re.Copy().MatchString(test.text)
|
| 126 |
+
if m1 != m2 {
|
| 127 |
+
t.Errorf("Copied Regexp match failure on %s: original gave %t; copy gave %t; should be %t",
|
| 128 |
+
test, m1, m2, len(test.matches) > 0)
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
func TestCopyMatch(t *testing.T) {
|
| 133 |
+
for _, test := range findTests {
|
| 134 |
+
copyMatchTest(t, &test)
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
type ReplaceTest struct {
|
| 139 |
+
pattern, replacement, input, output string
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
var replaceTests = []ReplaceTest{
|
| 143 |
+
// Test empty input and/or replacement, with pattern that matches the empty string.
|
| 144 |
+
{"", "", "", ""},
|
| 145 |
+
{"", "x", "", "x"},
|
| 146 |
+
{"", "", "abc", "abc"},
|
| 147 |
+
{"", "x", "abc", "xaxbxcx"},
|
| 148 |
+
|
| 149 |
+
// Test empty input and/or replacement, with pattern that does not match the empty string.
|
| 150 |
+
{"b", "", "", ""},
|
| 151 |
+
{"b", "x", "", ""},
|
| 152 |
+
{"b", "", "abc", "ac"},
|
| 153 |
+
{"b", "x", "abc", "axc"},
|
| 154 |
+
{"y", "", "", ""},
|
| 155 |
+
{"y", "x", "", ""},
|
| 156 |
+
{"y", "", "abc", "abc"},
|
| 157 |
+
{"y", "x", "abc", "abc"},
|
| 158 |
+
|
| 159 |
+
// Multibyte characters -- verify that we don't try to match in the middle
|
| 160 |
+
// of a character.
|
| 161 |
+
{"[a-c]*", "x", "\u65e5", "x\u65e5x"},
|
| 162 |
+
{"[^\u65e5]", "x", "abc\u65e5def", "xxx\u65e5xxx"},
|
| 163 |
+
|
| 164 |
+
// Start and end of a string.
|
| 165 |
+
{"^[a-c]*", "x", "abcdabc", "xdabc"},
|
| 166 |
+
{"[a-c]*$", "x", "abcdabc", "abcdx"},
|
| 167 |
+
{"^[a-c]*$", "x", "abcdabc", "abcdabc"},
|
| 168 |
+
{"^[a-c]*", "x", "abc", "x"},
|
| 169 |
+
{"[a-c]*$", "x", "abc", "x"},
|
| 170 |
+
{"^[a-c]*$", "x", "abc", "x"},
|
| 171 |
+
{"^[a-c]*", "x", "dabce", "xdabce"},
|
| 172 |
+
{"[a-c]*$", "x", "dabce", "dabcex"},
|
| 173 |
+
{"^[a-c]*$", "x", "dabce", "dabce"},
|
| 174 |
+
{"^[a-c]*", "x", "", "x"},
|
| 175 |
+
{"[a-c]*$", "x", "", "x"},
|
| 176 |
+
{"^[a-c]*$", "x", "", "x"},
|
| 177 |
+
|
| 178 |
+
{"^[a-c]+", "x", "abcdabc", "xdabc"},
|
| 179 |
+
{"[a-c]+$", "x", "abcdabc", "abcdx"},
|
| 180 |
+
{"^[a-c]+$", "x", "abcdabc", "abcdabc"},
|
| 181 |
+
{"^[a-c]+", "x", "abc", "x"},
|
| 182 |
+
{"[a-c]+$", "x", "abc", "x"},
|
| 183 |
+
{"^[a-c]+$", "x", "abc", "x"},
|
| 184 |
+
{"^[a-c]+", "x", "dabce", "dabce"},
|
| 185 |
+
{"[a-c]+$", "x", "dabce", "dabce"},
|
| 186 |
+
{"^[a-c]+$", "x", "dabce", "dabce"},
|
| 187 |
+
{"^[a-c]+", "x", "", ""},
|
| 188 |
+
{"[a-c]+$", "x", "", ""},
|
| 189 |
+
{"^[a-c]+$", "x", "", ""},
|
| 190 |
+
|
| 191 |
+
// Other cases.
|
| 192 |
+
{"abc", "def", "abcdefg", "defdefg"},
|
| 193 |
+
{"bc", "BC", "abcbcdcdedef", "aBCBCdcdedef"},
|
| 194 |
+
{"abc", "", "abcdabc", "d"},
|
| 195 |
+
{"x", "xXx", "xxxXxxx", "xXxxXxxXxXxXxxXxxXx"},
|
| 196 |
+
{"abc", "d", "", ""},
|
| 197 |
+
{"abc", "d", "abc", "d"},
|
| 198 |
+
{".+", "x", "abc", "x"},
|
| 199 |
+
{"[a-c]*", "x", "def", "xdxexfx"},
|
| 200 |
+
{"[a-c]+", "x", "abcbcdcdedef", "xdxdedef"},
|
| 201 |
+
{"[a-c]*", "x", "abcbcdcdedef", "xdxdxexdxexfx"},
|
| 202 |
+
|
| 203 |
+
// Substitutions
|
| 204 |
+
{"a+", "($0)", "banana", "b(a)n(a)n(a)"},
|
| 205 |
+
{"a+", "(${0})", "banana", "b(a)n(a)n(a)"},
|
| 206 |
+
{"a+", "(${0})$0", "banana", "b(a)an(a)an(a)a"},
|
| 207 |
+
{"a+", "(${0})$0", "banana", "b(a)an(a)an(a)a"},
|
| 208 |
+
{"hello, (.+)", "goodbye, ${1}", "hello, world", "goodbye, world"},
|
| 209 |
+
{"hello, (.+)", "goodbye, $1x", "hello, world", "goodbye, "},
|
| 210 |
+
{"hello, (.+)", "goodbye, ${1}x", "hello, world", "goodbye, worldx"},
|
| 211 |
+
{"hello, (.+)", "<$0><$1><$2><$3>", "hello, world", "<hello, world><world><><>"},
|
| 212 |
+
{"hello, (?P<noun>.+)", "goodbye, $noun!", "hello, world", "goodbye, world!"},
|
| 213 |
+
{"hello, (?P<noun>.+)", "goodbye, ${noun}", "hello, world", "goodbye, world"},
|
| 214 |
+
{"(?P<x>hi)|(?P<x>bye)", "$x$x$x", "hi", "hihihi"},
|
| 215 |
+
{"(?P<x>hi)|(?P<x>bye)", "$x$x$x", "bye", "byebyebye"},
|
| 216 |
+
{"(?P<x>hi)|(?P<x>bye)", "$xyz", "hi", ""},
|
| 217 |
+
{"(?P<x>hi)|(?P<x>bye)", "${x}yz", "hi", "hiyz"},
|
| 218 |
+
{"(?P<x>hi)|(?P<x>bye)", "hello $$x", "hi", "hello $x"},
|
| 219 |
+
{"a+", "${oops", "aaa", "${oops"},
|
| 220 |
+
{"a+", "$$", "aaa", "$"},
|
| 221 |
+
{"a+", "$", "aaa", "$"},
|
| 222 |
+
|
| 223 |
+
// Substitution when subexpression isn't found
|
| 224 |
+
{"(x)?", "$1", "123", "123"},
|
| 225 |
+
{"abc", "$1", "123", "123"},
|
| 226 |
+
|
| 227 |
+
// Substitutions involving a (x){0}
|
| 228 |
+
{"(a)(b){0}(c)", ".$1|$3.", "xacxacx", "x.a|c.x.a|c.x"},
|
| 229 |
+
{"(a)(((b))){0}c", ".$1.", "xacxacx", "x.a.x.a.x"},
|
| 230 |
+
{"((a(b){0}){3}){5}(h)", "y caramb$2", "say aaaaaaaaaaaaaaaah", "say ay caramba"},
|
| 231 |
+
{"((a(b){0}){3}){5}h", "y caramb$2", "say aaaaaaaaaaaaaaaah", "say ay caramba"},
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
var replaceLiteralTests = []ReplaceTest{
|
| 235 |
+
// Substitutions
|
| 236 |
+
{"a+", "($0)", "banana", "b($0)n($0)n($0)"},
|
| 237 |
+
{"a+", "(${0})", "banana", "b(${0})n(${0})n(${0})"},
|
| 238 |
+
{"a+", "(${0})$0", "banana", "b(${0})$0n(${0})$0n(${0})$0"},
|
| 239 |
+
{"a+", "(${0})$0", "banana", "b(${0})$0n(${0})$0n(${0})$0"},
|
| 240 |
+
{"hello, (.+)", "goodbye, ${1}", "hello, world", "goodbye, ${1}"},
|
| 241 |
+
{"hello, (?P<noun>.+)", "goodbye, $noun!", "hello, world", "goodbye, $noun!"},
|
| 242 |
+
{"hello, (?P<noun>.+)", "goodbye, ${noun}", "hello, world", "goodbye, ${noun}"},
|
| 243 |
+
{"(?P<x>hi)|(?P<x>bye)", "$x$x$x", "hi", "$x$x$x"},
|
| 244 |
+
{"(?P<x>hi)|(?P<x>bye)", "$x$x$x", "bye", "$x$x$x"},
|
| 245 |
+
{"(?P<x>hi)|(?P<x>bye)", "$xyz", "hi", "$xyz"},
|
| 246 |
+
{"(?P<x>hi)|(?P<x>bye)", "${x}yz", "hi", "${x}yz"},
|
| 247 |
+
{"(?P<x>hi)|(?P<x>bye)", "hello $$x", "hi", "hello $$x"},
|
| 248 |
+
{"a+", "${oops", "aaa", "${oops"},
|
| 249 |
+
{"a+", "$$", "aaa", "$$"},
|
| 250 |
+
{"a+", "$", "aaa", "$"},
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
type ReplaceFuncTest struct {
|
| 254 |
+
pattern string
|
| 255 |
+
replacement func(string) string
|
| 256 |
+
input, output string
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
var replaceFuncTests = []ReplaceFuncTest{
|
| 260 |
+
{"[a-c]", func(s string) string { return "x" + s + "y" }, "defabcdef", "defxayxbyxcydef"},
|
| 261 |
+
{"[a-c]+", func(s string) string { return "x" + s + "y" }, "defabcdef", "defxabcydef"},
|
| 262 |
+
{"[a-c]*", func(s string) string { return "x" + s + "y" }, "defabcdef", "xydxyexyfxabcydxyexyfxy"},
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
func TestReplaceAll(t *testing.T) {
|
| 266 |
+
for _, tc := range replaceTests {
|
| 267 |
+
re, err := Compile(tc.pattern)
|
| 268 |
+
if err != nil {
|
| 269 |
+
t.Errorf("Unexpected error compiling %q: %v", tc.pattern, err)
|
| 270 |
+
continue
|
| 271 |
+
}
|
| 272 |
+
actual := re.ReplaceAllString(tc.input, tc.replacement)
|
| 273 |
+
if actual != tc.output {
|
| 274 |
+
t.Errorf("%q.ReplaceAllString(%q,%q) = %q; want %q",
|
| 275 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 276 |
+
}
|
| 277 |
+
// now try bytes
|
| 278 |
+
actual = string(re.ReplaceAll([]byte(tc.input), []byte(tc.replacement)))
|
| 279 |
+
if actual != tc.output {
|
| 280 |
+
t.Errorf("%q.ReplaceAll(%q,%q) = %q; want %q",
|
| 281 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
func TestReplaceAllLiteral(t *testing.T) {
|
| 287 |
+
// Run ReplaceAll tests that do not have $ expansions.
|
| 288 |
+
for _, tc := range replaceTests {
|
| 289 |
+
if strings.Contains(tc.replacement, "$") {
|
| 290 |
+
continue
|
| 291 |
+
}
|
| 292 |
+
re, err := Compile(tc.pattern)
|
| 293 |
+
if err != nil {
|
| 294 |
+
t.Errorf("Unexpected error compiling %q: %v", tc.pattern, err)
|
| 295 |
+
continue
|
| 296 |
+
}
|
| 297 |
+
actual := re.ReplaceAllLiteralString(tc.input, tc.replacement)
|
| 298 |
+
if actual != tc.output {
|
| 299 |
+
t.Errorf("%q.ReplaceAllLiteralString(%q,%q) = %q; want %q",
|
| 300 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 301 |
+
}
|
| 302 |
+
// now try bytes
|
| 303 |
+
actual = string(re.ReplaceAllLiteral([]byte(tc.input), []byte(tc.replacement)))
|
| 304 |
+
if actual != tc.output {
|
| 305 |
+
t.Errorf("%q.ReplaceAllLiteral(%q,%q) = %q; want %q",
|
| 306 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
// Run literal-specific tests.
|
| 311 |
+
for _, tc := range replaceLiteralTests {
|
| 312 |
+
re, err := Compile(tc.pattern)
|
| 313 |
+
if err != nil {
|
| 314 |
+
t.Errorf("Unexpected error compiling %q: %v", tc.pattern, err)
|
| 315 |
+
continue
|
| 316 |
+
}
|
| 317 |
+
actual := re.ReplaceAllLiteralString(tc.input, tc.replacement)
|
| 318 |
+
if actual != tc.output {
|
| 319 |
+
t.Errorf("%q.ReplaceAllLiteralString(%q,%q) = %q; want %q",
|
| 320 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 321 |
+
}
|
| 322 |
+
// now try bytes
|
| 323 |
+
actual = string(re.ReplaceAllLiteral([]byte(tc.input), []byte(tc.replacement)))
|
| 324 |
+
if actual != tc.output {
|
| 325 |
+
t.Errorf("%q.ReplaceAllLiteral(%q,%q) = %q; want %q",
|
| 326 |
+
tc.pattern, tc.input, tc.replacement, actual, tc.output)
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
func TestReplaceAllFunc(t *testing.T) {
|
| 332 |
+
for _, tc := range replaceFuncTests {
|
| 333 |
+
re, err := Compile(tc.pattern)
|
| 334 |
+
if err != nil {
|
| 335 |
+
t.Errorf("Unexpected error compiling %q: %v", tc.pattern, err)
|
| 336 |
+
continue
|
| 337 |
+
}
|
| 338 |
+
actual := re.ReplaceAllStringFunc(tc.input, tc.replacement)
|
| 339 |
+
if actual != tc.output {
|
| 340 |
+
t.Errorf("%q.ReplaceFunc(%q,fn) = %q; want %q",
|
| 341 |
+
tc.pattern, tc.input, actual, tc.output)
|
| 342 |
+
}
|
| 343 |
+
// now try bytes
|
| 344 |
+
actual = string(re.ReplaceAllFunc([]byte(tc.input), func(s []byte) []byte { return []byte(tc.replacement(string(s))) }))
|
| 345 |
+
if actual != tc.output {
|
| 346 |
+
t.Errorf("%q.ReplaceFunc(%q,fn) = %q; want %q",
|
| 347 |
+
tc.pattern, tc.input, actual, tc.output)
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
type MetaTest struct {
|
| 353 |
+
pattern, output, literal string
|
| 354 |
+
isLiteral bool
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
var metaTests = []MetaTest{
|
| 358 |
+
{``, ``, ``, true},
|
| 359 |
+
{`foo`, `foo`, `foo`, true},
|
| 360 |
+
{`日本語+`, `日本語\+`, `日本語`, false},
|
| 361 |
+
{`foo\.\$`, `foo\\\.\\\$`, `foo.$`, true}, // has meta but no operator
|
| 362 |
+
{`foo.\$`, `foo\.\\\$`, `foo`, false}, // has escaped operators and real operators
|
| 363 |
+
{`!@#$%^&*()_+-=[{]}\|,<.>/?~`, `!@#\$%\^&\*\(\)_\+-=\[\{\]\}\\\|,<\.>/\?~`, `!@#`, false},
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
var literalPrefixTests = []MetaTest{
|
| 367 |
+
// See golang.org/issue/11175.
|
| 368 |
+
// output is unused.
|
| 369 |
+
{`^0^0$`, ``, `0`, false},
|
| 370 |
+
{`^0^`, ``, ``, false},
|
| 371 |
+
{`^0$`, ``, `0`, true},
|
| 372 |
+
{`$0^`, ``, ``, false},
|
| 373 |
+
{`$0$`, ``, ``, false},
|
| 374 |
+
{`^^0$$`, ``, ``, false},
|
| 375 |
+
{`^$^$`, ``, ``, false},
|
| 376 |
+
{`$$0^^`, ``, ``, false},
|
| 377 |
+
{`a\x{fffd}b`, ``, `a`, false},
|
| 378 |
+
{`\x{fffd}b`, ``, ``, false},
|
| 379 |
+
{"\ufffd", ``, ``, false},
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
func TestQuoteMeta(t *testing.T) {
|
| 383 |
+
for _, tc := range metaTests {
|
| 384 |
+
// Verify that QuoteMeta returns the expected string.
|
| 385 |
+
quoted := QuoteMeta(tc.pattern)
|
| 386 |
+
if quoted != tc.output {
|
| 387 |
+
t.Errorf("QuoteMeta(`%s`) = `%s`; want `%s`",
|
| 388 |
+
tc.pattern, quoted, tc.output)
|
| 389 |
+
continue
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
// Verify that the quoted string is in fact treated as expected
|
| 393 |
+
// by Compile -- i.e. that it matches the original, unquoted string.
|
| 394 |
+
if tc.pattern != "" {
|
| 395 |
+
re, err := Compile(quoted)
|
| 396 |
+
if err != nil {
|
| 397 |
+
t.Errorf("Unexpected error compiling QuoteMeta(`%s`): %v", tc.pattern, err)
|
| 398 |
+
continue
|
| 399 |
+
}
|
| 400 |
+
src := "abc" + tc.pattern + "def"
|
| 401 |
+
repl := "xyz"
|
| 402 |
+
replaced := re.ReplaceAllString(src, repl)
|
| 403 |
+
expected := "abcxyzdef"
|
| 404 |
+
if replaced != expected {
|
| 405 |
+
t.Errorf("QuoteMeta(`%s`).Replace(`%s`,`%s`) = `%s`; want `%s`",
|
| 406 |
+
tc.pattern, src, repl, replaced, expected)
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
}
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
func TestLiteralPrefix(t *testing.T) {
|
| 413 |
+
for _, tc := range append(metaTests, literalPrefixTests...) {
|
| 414 |
+
// Literal method needs to scan the pattern.
|
| 415 |
+
re := MustCompile(tc.pattern)
|
| 416 |
+
str, complete := re.LiteralPrefix()
|
| 417 |
+
if complete != tc.isLiteral {
|
| 418 |
+
t.Errorf("LiteralPrefix(`%s`) = %t; want %t", tc.pattern, complete, tc.isLiteral)
|
| 419 |
+
}
|
| 420 |
+
if str != tc.literal {
|
| 421 |
+
t.Errorf("LiteralPrefix(`%s`) = `%s`; want `%s`", tc.pattern, str, tc.literal)
|
| 422 |
+
}
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
type subexpIndex struct {
|
| 427 |
+
name string
|
| 428 |
+
index int
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
type subexpCase struct {
|
| 432 |
+
input string
|
| 433 |
+
num int
|
| 434 |
+
names []string
|
| 435 |
+
indices []subexpIndex
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
var emptySubexpIndices = []subexpIndex{{"", -1}, {"missing", -1}}
|
| 439 |
+
|
| 440 |
+
var subexpCases = []subexpCase{
|
| 441 |
+
{``, 0, nil, emptySubexpIndices},
|
| 442 |
+
{`.*`, 0, nil, emptySubexpIndices},
|
| 443 |
+
{`abba`, 0, nil, emptySubexpIndices},
|
| 444 |
+
{`ab(b)a`, 1, []string{"", ""}, emptySubexpIndices},
|
| 445 |
+
{`ab(.*)a`, 1, []string{"", ""}, emptySubexpIndices},
|
| 446 |
+
{`(.*)ab(.*)a`, 2, []string{"", "", ""}, emptySubexpIndices},
|
| 447 |
+
{`(.*)(ab)(.*)a`, 3, []string{"", "", "", ""}, emptySubexpIndices},
|
| 448 |
+
{`(.*)((a)b)(.*)a`, 4, []string{"", "", "", "", ""}, emptySubexpIndices},
|
| 449 |
+
{`(.*)(\(ab)(.*)a`, 3, []string{"", "", "", ""}, emptySubexpIndices},
|
| 450 |
+
{`(.*)(\(a\)b)(.*)a`, 3, []string{"", "", "", ""}, emptySubexpIndices},
|
| 451 |
+
{`(?P<foo>.*)(?P<bar>(a)b)(?P<foo>.*)a`, 4, []string{"", "foo", "bar", "", "foo"}, []subexpIndex{{"", -1}, {"missing", -1}, {"foo", 1}, {"bar", 2}}},
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
func TestSubexp(t *testing.T) {
|
| 455 |
+
for _, c := range subexpCases {
|
| 456 |
+
re := MustCompile(c.input)
|
| 457 |
+
n := re.NumSubexp()
|
| 458 |
+
if n != c.num {
|
| 459 |
+
t.Errorf("%q: NumSubexp = %d, want %d", c.input, n, c.num)
|
| 460 |
+
continue
|
| 461 |
+
}
|
| 462 |
+
names := re.SubexpNames()
|
| 463 |
+
if len(names) != 1+n {
|
| 464 |
+
t.Errorf("%q: len(SubexpNames) = %d, want %d", c.input, len(names), n)
|
| 465 |
+
continue
|
| 466 |
+
}
|
| 467 |
+
if c.names != nil {
|
| 468 |
+
for i := 0; i < 1+n; i++ {
|
| 469 |
+
if names[i] != c.names[i] {
|
| 470 |
+
t.Errorf("%q: SubexpNames[%d] = %q, want %q", c.input, i, names[i], c.names[i])
|
| 471 |
+
}
|
| 472 |
+
}
|
| 473 |
+
}
|
| 474 |
+
for _, subexp := range c.indices {
|
| 475 |
+
index := re.SubexpIndex(subexp.name)
|
| 476 |
+
if index != subexp.index {
|
| 477 |
+
t.Errorf("%q: SubexpIndex(%q) = %d, want %d", c.input, subexp.name, index, subexp.index)
|
| 478 |
+
}
|
| 479 |
+
}
|
| 480 |
+
}
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
var splitTests = []struct {
|
| 484 |
+
s string
|
| 485 |
+
r string
|
| 486 |
+
n int
|
| 487 |
+
out []string
|
| 488 |
+
}{
|
| 489 |
+
{"foo:and:bar", ":", -1, []string{"foo", "and", "bar"}},
|
| 490 |
+
{"foo:and:bar", ":", 1, []string{"foo:and:bar"}},
|
| 491 |
+
{"foo:and:bar", ":", 2, []string{"foo", "and:bar"}},
|
| 492 |
+
{"foo:and:bar", "foo", -1, []string{"", ":and:bar"}},
|
| 493 |
+
{"foo:and:bar", "bar", -1, []string{"foo:and:", ""}},
|
| 494 |
+
{"foo:and:bar", "baz", -1, []string{"foo:and:bar"}},
|
| 495 |
+
{"baabaab", "a", -1, []string{"b", "", "b", "", "b"}},
|
| 496 |
+
{"baabaab", "a*", -1, []string{"b", "b", "b"}},
|
| 497 |
+
{"baabaab", "ba*", -1, []string{"", "", "", ""}},
|
| 498 |
+
{"foobar", "f*b*", -1, []string{"", "o", "o", "a", "r"}},
|
| 499 |
+
{"foobar", "f+.*b+", -1, []string{"", "ar"}},
|
| 500 |
+
{"foobooboar", "o{2}", -1, []string{"f", "b", "boar"}},
|
| 501 |
+
{"a,b,c,d,e,f", ",", 3, []string{"a", "b", "c,d,e,f"}},
|
| 502 |
+
{"a,b,c,d,e,f", ",", 0, nil},
|
| 503 |
+
{",", ",", -1, []string{"", ""}},
|
| 504 |
+
{",,,", ",", -1, []string{"", "", "", ""}},
|
| 505 |
+
{"", ",", -1, []string{""}},
|
| 506 |
+
{"", ".*", -1, []string{""}},
|
| 507 |
+
{"", ".+", -1, []string{""}},
|
| 508 |
+
{"", "", -1, []string{}},
|
| 509 |
+
{"foobar", "", -1, []string{"f", "o", "o", "b", "a", "r"}},
|
| 510 |
+
{"abaabaccadaaae", "a*", 5, []string{"", "b", "b", "c", "cadaaae"}},
|
| 511 |
+
{":x:y:z:", ":", -1, []string{"", "x", "y", "z", ""}},
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
func TestSplit(t *testing.T) {
|
| 515 |
+
for i, test := range splitTests {
|
| 516 |
+
re, err := Compile(test.r)
|
| 517 |
+
if err != nil {
|
| 518 |
+
t.Errorf("#%d: %q: compile error: %s", i, test.r, err.Error())
|
| 519 |
+
continue
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
split := re.Split(test.s, test.n)
|
| 523 |
+
if !slices.Equal(split, test.out) {
|
| 524 |
+
t.Errorf("#%d: %q: got %q; want %q", i, test.r, split, test.out)
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
if QuoteMeta(test.r) == test.r {
|
| 528 |
+
strsplit := strings.SplitN(test.s, test.r, test.n)
|
| 529 |
+
if !slices.Equal(split, strsplit) {
|
| 530 |
+
t.Errorf("#%d: Split(%q, %q, %d): regexp vs strings mismatch\nregexp=%q\nstrings=%q", i, test.s, test.r, test.n, split, strsplit)
|
| 531 |
+
}
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
// The following sequence of Match calls used to panic. See issue #12980.
|
| 537 |
+
func TestParseAndCompile(t *testing.T) {
|
| 538 |
+
expr := "a$"
|
| 539 |
+
s := "a\nb"
|
| 540 |
+
|
| 541 |
+
for i, tc := range []struct {
|
| 542 |
+
reFlags syntax.Flags
|
| 543 |
+
expMatch bool
|
| 544 |
+
}{
|
| 545 |
+
{syntax.Perl | syntax.OneLine, false},
|
| 546 |
+
{syntax.Perl &^ syntax.OneLine, true},
|
| 547 |
+
} {
|
| 548 |
+
parsed, err := syntax.Parse(expr, tc.reFlags)
|
| 549 |
+
if err != nil {
|
| 550 |
+
t.Fatalf("%d: parse: %v", i, err)
|
| 551 |
+
}
|
| 552 |
+
re, err := Compile(parsed.String())
|
| 553 |
+
if err != nil {
|
| 554 |
+
t.Fatalf("%d: compile: %v", i, err)
|
| 555 |
+
}
|
| 556 |
+
if match := re.MatchString(s); match != tc.expMatch {
|
| 557 |
+
t.Errorf("%d: %q.MatchString(%q)=%t; expected=%t", i, re, s, match, tc.expMatch)
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
// Check that one-pass cutoff does trigger.
|
| 563 |
+
func TestOnePassCutoff(t *testing.T) {
|
| 564 |
+
re, err := syntax.Parse(`^x{1,1000}y{1,1000}$`, syntax.Perl)
|
| 565 |
+
if err != nil {
|
| 566 |
+
t.Fatalf("parse: %v", err)
|
| 567 |
+
}
|
| 568 |
+
p, err := syntax.Compile(re.Simplify())
|
| 569 |
+
if err != nil {
|
| 570 |
+
t.Fatalf("compile: %v", err)
|
| 571 |
+
}
|
| 572 |
+
if compileOnePass(p) != nil {
|
| 573 |
+
t.Fatalf("makeOnePass succeeded; wanted nil")
|
| 574 |
+
}
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
// Check that the same machine can be used with the standard matcher
|
| 578 |
+
// and then the backtracker when there are no captures.
|
| 579 |
+
func TestSwitchBacktrack(t *testing.T) {
|
| 580 |
+
re := MustCompile(`a|b`)
|
| 581 |
+
long := make([]byte, maxBacktrackVector+1)
|
| 582 |
+
|
| 583 |
+
// The following sequence of Match calls used to panic. See issue #10319.
|
| 584 |
+
re.Match(long) // triggers standard matcher
|
| 585 |
+
re.Match(long[:1]) // triggers backtracker
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
func BenchmarkFind(b *testing.B) {
|
| 589 |
+
b.StopTimer()
|
| 590 |
+
re := MustCompile("a+b+")
|
| 591 |
+
wantSubs := "aaabb"
|
| 592 |
+
s := []byte("acbb" + wantSubs + "dd")
|
| 593 |
+
b.StartTimer()
|
| 594 |
+
b.ReportAllocs()
|
| 595 |
+
for i := 0; i < b.N; i++ {
|
| 596 |
+
subs := re.Find(s)
|
| 597 |
+
if string(subs) != wantSubs {
|
| 598 |
+
b.Fatalf("Find(%q) = %q; want %q", s, subs, wantSubs)
|
| 599 |
+
}
|
| 600 |
+
}
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
func BenchmarkFindAllNoMatches(b *testing.B) {
|
| 604 |
+
re := MustCompile("a+b+")
|
| 605 |
+
s := []byte("acddee")
|
| 606 |
+
b.ReportAllocs()
|
| 607 |
+
b.ResetTimer()
|
| 608 |
+
for i := 0; i < b.N; i++ {
|
| 609 |
+
all := re.FindAll(s, -1)
|
| 610 |
+
if all != nil {
|
| 611 |
+
b.Fatalf("FindAll(%q) = %q; want nil", s, all)
|
| 612 |
+
}
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
func BenchmarkFindString(b *testing.B) {
|
| 617 |
+
b.StopTimer()
|
| 618 |
+
re := MustCompile("a+b+")
|
| 619 |
+
wantSubs := "aaabb"
|
| 620 |
+
s := "acbb" + wantSubs + "dd"
|
| 621 |
+
b.StartTimer()
|
| 622 |
+
b.ReportAllocs()
|
| 623 |
+
for i := 0; i < b.N; i++ {
|
| 624 |
+
subs := re.FindString(s)
|
| 625 |
+
if subs != wantSubs {
|
| 626 |
+
b.Fatalf("FindString(%q) = %q; want %q", s, subs, wantSubs)
|
| 627 |
+
}
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
func BenchmarkFindSubmatch(b *testing.B) {
|
| 632 |
+
b.StopTimer()
|
| 633 |
+
re := MustCompile("a(a+b+)b")
|
| 634 |
+
wantSubs := "aaabb"
|
| 635 |
+
s := []byte("acbb" + wantSubs + "dd")
|
| 636 |
+
b.StartTimer()
|
| 637 |
+
b.ReportAllocs()
|
| 638 |
+
for i := 0; i < b.N; i++ {
|
| 639 |
+
subs := re.FindSubmatch(s)
|
| 640 |
+
if string(subs[0]) != wantSubs {
|
| 641 |
+
b.Fatalf("FindSubmatch(%q)[0] = %q; want %q", s, subs[0], wantSubs)
|
| 642 |
+
}
|
| 643 |
+
if string(subs[1]) != "aab" {
|
| 644 |
+
b.Fatalf("FindSubmatch(%q)[1] = %q; want %q", s, subs[1], "aab")
|
| 645 |
+
}
|
| 646 |
+
}
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
func BenchmarkFindStringSubmatch(b *testing.B) {
|
| 650 |
+
b.StopTimer()
|
| 651 |
+
re := MustCompile("a(a+b+)b")
|
| 652 |
+
wantSubs := "aaabb"
|
| 653 |
+
s := "acbb" + wantSubs + "dd"
|
| 654 |
+
b.StartTimer()
|
| 655 |
+
b.ReportAllocs()
|
| 656 |
+
for i := 0; i < b.N; i++ {
|
| 657 |
+
subs := re.FindStringSubmatch(s)
|
| 658 |
+
if subs[0] != wantSubs {
|
| 659 |
+
b.Fatalf("FindStringSubmatch(%q)[0] = %q; want %q", s, subs[0], wantSubs)
|
| 660 |
+
}
|
| 661 |
+
if subs[1] != "aab" {
|
| 662 |
+
b.Fatalf("FindStringSubmatch(%q)[1] = %q; want %q", s, subs[1], "aab")
|
| 663 |
+
}
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
func BenchmarkLiteral(b *testing.B) {
|
| 668 |
+
x := strings.Repeat("x", 50) + "y"
|
| 669 |
+
b.StopTimer()
|
| 670 |
+
re := MustCompile("y")
|
| 671 |
+
b.StartTimer()
|
| 672 |
+
for i := 0; i < b.N; i++ {
|
| 673 |
+
if !re.MatchString(x) {
|
| 674 |
+
b.Fatalf("no match!")
|
| 675 |
+
}
|
| 676 |
+
}
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
func BenchmarkNotLiteral(b *testing.B) {
|
| 680 |
+
x := strings.Repeat("x", 50) + "y"
|
| 681 |
+
b.StopTimer()
|
| 682 |
+
re := MustCompile(".y")
|
| 683 |
+
b.StartTimer()
|
| 684 |
+
for i := 0; i < b.N; i++ {
|
| 685 |
+
if !re.MatchString(x) {
|
| 686 |
+
b.Fatalf("no match!")
|
| 687 |
+
}
|
| 688 |
+
}
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
func BenchmarkMatchClass(b *testing.B) {
|
| 692 |
+
b.StopTimer()
|
| 693 |
+
x := strings.Repeat("xxxx", 20) + "w"
|
| 694 |
+
re := MustCompile("[abcdw]")
|
| 695 |
+
b.StartTimer()
|
| 696 |
+
for i := 0; i < b.N; i++ {
|
| 697 |
+
if !re.MatchString(x) {
|
| 698 |
+
b.Fatalf("no match!")
|
| 699 |
+
}
|
| 700 |
+
}
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
func BenchmarkMatchClass_InRange(b *testing.B) {
|
| 704 |
+
b.StopTimer()
|
| 705 |
+
// 'b' is between 'a' and 'c', so the charclass
|
| 706 |
+
// range checking is no help here.
|
| 707 |
+
x := strings.Repeat("bbbb", 20) + "c"
|
| 708 |
+
re := MustCompile("[ac]")
|
| 709 |
+
b.StartTimer()
|
| 710 |
+
for i := 0; i < b.N; i++ {
|
| 711 |
+
if !re.MatchString(x) {
|
| 712 |
+
b.Fatalf("no match!")
|
| 713 |
+
}
|
| 714 |
+
}
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
func BenchmarkReplaceAll(b *testing.B) {
|
| 718 |
+
x := "abcdefghijklmnopqrstuvwxyz"
|
| 719 |
+
b.StopTimer()
|
| 720 |
+
re := MustCompile("[cjrw]")
|
| 721 |
+
b.StartTimer()
|
| 722 |
+
for i := 0; i < b.N; i++ {
|
| 723 |
+
re.ReplaceAllString(x, "")
|
| 724 |
+
}
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
func BenchmarkAnchoredLiteralShortNonMatch(b *testing.B) {
|
| 728 |
+
b.StopTimer()
|
| 729 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 730 |
+
re := MustCompile("^zbc(d|e)")
|
| 731 |
+
b.StartTimer()
|
| 732 |
+
for i := 0; i < b.N; i++ {
|
| 733 |
+
re.Match(x)
|
| 734 |
+
}
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
func BenchmarkAnchoredLiteralLongNonMatch(b *testing.B) {
|
| 738 |
+
b.StopTimer()
|
| 739 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 740 |
+
for i := 0; i < 15; i++ {
|
| 741 |
+
x = append(x, x...)
|
| 742 |
+
}
|
| 743 |
+
re := MustCompile("^zbc(d|e)")
|
| 744 |
+
b.StartTimer()
|
| 745 |
+
for i := 0; i < b.N; i++ {
|
| 746 |
+
re.Match(x)
|
| 747 |
+
}
|
| 748 |
+
}
|
| 749 |
+
|
| 750 |
+
func BenchmarkAnchoredShortMatch(b *testing.B) {
|
| 751 |
+
b.StopTimer()
|
| 752 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 753 |
+
re := MustCompile("^.bc(d|e)")
|
| 754 |
+
b.StartTimer()
|
| 755 |
+
for i := 0; i < b.N; i++ {
|
| 756 |
+
re.Match(x)
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
func BenchmarkAnchoredLongMatch(b *testing.B) {
|
| 761 |
+
b.StopTimer()
|
| 762 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 763 |
+
for i := 0; i < 15; i++ {
|
| 764 |
+
x = append(x, x...)
|
| 765 |
+
}
|
| 766 |
+
re := MustCompile("^.bc(d|e)")
|
| 767 |
+
b.StartTimer()
|
| 768 |
+
for i := 0; i < b.N; i++ {
|
| 769 |
+
re.Match(x)
|
| 770 |
+
}
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
func BenchmarkOnePassShortA(b *testing.B) {
|
| 774 |
+
b.StopTimer()
|
| 775 |
+
x := []byte("abcddddddeeeededd")
|
| 776 |
+
re := MustCompile("^.bc(d|e)*$")
|
| 777 |
+
b.StartTimer()
|
| 778 |
+
for i := 0; i < b.N; i++ {
|
| 779 |
+
re.Match(x)
|
| 780 |
+
}
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
func BenchmarkNotOnePassShortA(b *testing.B) {
|
| 784 |
+
b.StopTimer()
|
| 785 |
+
x := []byte("abcddddddeeeededd")
|
| 786 |
+
re := MustCompile(".bc(d|e)*$")
|
| 787 |
+
b.StartTimer()
|
| 788 |
+
for i := 0; i < b.N; i++ {
|
| 789 |
+
re.Match(x)
|
| 790 |
+
}
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
func BenchmarkOnePassShortB(b *testing.B) {
|
| 794 |
+
b.StopTimer()
|
| 795 |
+
x := []byte("abcddddddeeeededd")
|
| 796 |
+
re := MustCompile("^.bc(?:d|e)*$")
|
| 797 |
+
b.StartTimer()
|
| 798 |
+
for i := 0; i < b.N; i++ {
|
| 799 |
+
re.Match(x)
|
| 800 |
+
}
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
func BenchmarkNotOnePassShortB(b *testing.B) {
|
| 804 |
+
b.StopTimer()
|
| 805 |
+
x := []byte("abcddddddeeeededd")
|
| 806 |
+
re := MustCompile(".bc(?:d|e)*$")
|
| 807 |
+
b.StartTimer()
|
| 808 |
+
for i := 0; i < b.N; i++ {
|
| 809 |
+
re.Match(x)
|
| 810 |
+
}
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
func BenchmarkOnePassLongPrefix(b *testing.B) {
|
| 814 |
+
b.StopTimer()
|
| 815 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 816 |
+
re := MustCompile("^abcdefghijklmnopqrstuvwxyz.*$")
|
| 817 |
+
b.StartTimer()
|
| 818 |
+
for i := 0; i < b.N; i++ {
|
| 819 |
+
re.Match(x)
|
| 820 |
+
}
|
| 821 |
+
}
|
| 822 |
+
|
| 823 |
+
func BenchmarkOnePassLongNotPrefix(b *testing.B) {
|
| 824 |
+
b.StopTimer()
|
| 825 |
+
x := []byte("abcdefghijklmnopqrstuvwxyz")
|
| 826 |
+
re := MustCompile("^.bcdefghijklmnopqrstuvwxyz.*$")
|
| 827 |
+
b.StartTimer()
|
| 828 |
+
for i := 0; i < b.N; i++ {
|
| 829 |
+
re.Match(x)
|
| 830 |
+
}
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
func BenchmarkMatchParallelShared(b *testing.B) {
|
| 834 |
+
x := []byte("this is a long line that contains foo bar baz")
|
| 835 |
+
re := MustCompile("foo (ba+r)? baz")
|
| 836 |
+
b.ResetTimer()
|
| 837 |
+
b.RunParallel(func(pb *testing.PB) {
|
| 838 |
+
for pb.Next() {
|
| 839 |
+
re.Match(x)
|
| 840 |
+
}
|
| 841 |
+
})
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
func BenchmarkMatchParallelCopied(b *testing.B) {
|
| 845 |
+
x := []byte("this is a long line that contains foo bar baz")
|
| 846 |
+
re := MustCompile("foo (ba+r)? baz")
|
| 847 |
+
b.ResetTimer()
|
| 848 |
+
b.RunParallel(func(pb *testing.PB) {
|
| 849 |
+
re := re.Copy()
|
| 850 |
+
for pb.Next() {
|
| 851 |
+
re.Match(x)
|
| 852 |
+
}
|
| 853 |
+
})
|
| 854 |
+
}
|
| 855 |
+
|
| 856 |
+
var sink string
|
| 857 |
+
|
| 858 |
+
func BenchmarkQuoteMetaAll(b *testing.B) {
|
| 859 |
+
specials := make([]byte, 0)
|
| 860 |
+
for i := byte(0); i < utf8.RuneSelf; i++ {
|
| 861 |
+
if special(i) {
|
| 862 |
+
specials = append(specials, i)
|
| 863 |
+
}
|
| 864 |
+
}
|
| 865 |
+
s := string(specials)
|
| 866 |
+
b.SetBytes(int64(len(s)))
|
| 867 |
+
b.ResetTimer()
|
| 868 |
+
for i := 0; i < b.N; i++ {
|
| 869 |
+
sink = QuoteMeta(s)
|
| 870 |
+
}
|
| 871 |
+
}
|
| 872 |
+
|
| 873 |
+
func BenchmarkQuoteMetaNone(b *testing.B) {
|
| 874 |
+
s := "abcdefghijklmnopqrstuvwxyz"
|
| 875 |
+
b.SetBytes(int64(len(s)))
|
| 876 |
+
b.ResetTimer()
|
| 877 |
+
for i := 0; i < b.N; i++ {
|
| 878 |
+
sink = QuoteMeta(s)
|
| 879 |
+
}
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
var compileBenchData = []struct{ name, re string }{
|
| 883 |
+
{"Onepass", `^a.[l-nA-Cg-j]?e$`},
|
| 884 |
+
{"Medium", `^((a|b|[d-z0-9])*(日){4,5}.)+$`},
|
| 885 |
+
{"Hard", strings.Repeat(`((abc)*|`, 50) + strings.Repeat(`)`, 50)},
|
| 886 |
+
}
|
| 887 |
+
|
| 888 |
+
func BenchmarkCompile(b *testing.B) {
|
| 889 |
+
for _, data := range compileBenchData {
|
| 890 |
+
b.Run(data.name, func(b *testing.B) {
|
| 891 |
+
b.ReportAllocs()
|
| 892 |
+
for i := 0; i < b.N; i++ {
|
| 893 |
+
if _, err := Compile(data.re); err != nil {
|
| 894 |
+
b.Fatal(err)
|
| 895 |
+
}
|
| 896 |
+
}
|
| 897 |
+
})
|
| 898 |
+
}
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
func TestDeepEqual(t *testing.T) {
|
| 902 |
+
re1 := MustCompile("a.*b.*c.*d")
|
| 903 |
+
re2 := MustCompile("a.*b.*c.*d")
|
| 904 |
+
if !reflect.DeepEqual(re1, re2) { // has always been true, since Go 1.
|
| 905 |
+
t.Errorf("DeepEqual(re1, re2) = false, want true")
|
| 906 |
+
}
|
| 907 |
+
|
| 908 |
+
re1.MatchString("abcdefghijklmn")
|
| 909 |
+
if !reflect.DeepEqual(re1, re2) {
|
| 910 |
+
t.Errorf("DeepEqual(re1, re2) = false, want true")
|
| 911 |
+
}
|
| 912 |
+
|
| 913 |
+
re2.MatchString("abcdefghijklmn")
|
| 914 |
+
if !reflect.DeepEqual(re1, re2) {
|
| 915 |
+
t.Errorf("DeepEqual(re1, re2) = false, want true")
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
re2.MatchString(strings.Repeat("abcdefghijklmn", 100))
|
| 919 |
+
if !reflect.DeepEqual(re1, re2) {
|
| 920 |
+
t.Errorf("DeepEqual(re1, re2) = false, want true")
|
| 921 |
+
}
|
| 922 |
+
}
|
| 923 |
+
|
| 924 |
+
var minInputLenTests = []struct {
|
| 925 |
+
Regexp string
|
| 926 |
+
min int
|
| 927 |
+
}{
|
| 928 |
+
{``, 0},
|
| 929 |
+
{`a`, 1},
|
| 930 |
+
{`aa`, 2},
|
| 931 |
+
{`(aa)a`, 3},
|
| 932 |
+
{`(?:aa)a`, 3},
|
| 933 |
+
{`a?a`, 1},
|
| 934 |
+
{`(aaa)|(aa)`, 2},
|
| 935 |
+
{`(aa)+a`, 3},
|
| 936 |
+
{`(aa)*a`, 1},
|
| 937 |
+
{`(aa){3,5}`, 6},
|
| 938 |
+
{`[a-z]`, 1},
|
| 939 |
+
{`日`, 3},
|
| 940 |
+
}
|
| 941 |
+
|
| 942 |
+
func TestMinInputLen(t *testing.T) {
|
| 943 |
+
for _, tt := range minInputLenTests {
|
| 944 |
+
re, _ := syntax.Parse(tt.Regexp, syntax.Perl)
|
| 945 |
+
m := minInputLen(re)
|
| 946 |
+
if m != tt.min {
|
| 947 |
+
t.Errorf("regexp %#q has minInputLen %d, should be %d", tt.Regexp, m, tt.min)
|
| 948 |
+
}
|
| 949 |
+
}
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
func TestUnmarshalText(t *testing.T) {
|
| 953 |
+
unmarshaled := new(Regexp)
|
| 954 |
+
for i := range goodRe {
|
| 955 |
+
re := compileTest(t, goodRe[i], "")
|
| 956 |
+
marshaled, err := re.MarshalText()
|
| 957 |
+
if err != nil {
|
| 958 |
+
t.Errorf("regexp %#q failed to marshal: %s", re, err)
|
| 959 |
+
continue
|
| 960 |
+
}
|
| 961 |
+
if err := unmarshaled.UnmarshalText(marshaled); err != nil {
|
| 962 |
+
t.Errorf("regexp %#q failed to unmarshal: %s", re, err)
|
| 963 |
+
continue
|
| 964 |
+
}
|
| 965 |
+
if unmarshaled.String() != goodRe[i] {
|
| 966 |
+
t.Errorf("UnmarshalText returned unexpected value: %s", unmarshaled.String())
|
| 967 |
+
}
|
| 968 |
+
|
| 969 |
+
buf := make([]byte, 4, 32)
|
| 970 |
+
marshalAppend, err := re.AppendText(buf)
|
| 971 |
+
if err != nil {
|
| 972 |
+
t.Errorf("regexp %#q failed to marshal: %s", re, err)
|
| 973 |
+
continue
|
| 974 |
+
}
|
| 975 |
+
marshalAppend = marshalAppend[4:]
|
| 976 |
+
if err := unmarshaled.UnmarshalText(marshalAppend); err != nil {
|
| 977 |
+
t.Errorf("regexp %#q failed to unmarshal: %s", re, err)
|
| 978 |
+
continue
|
| 979 |
+
}
|
| 980 |
+
if unmarshaled.String() != goodRe[i] {
|
| 981 |
+
t.Errorf("UnmarshalText returned unexpected value: %s", unmarshaled.String())
|
| 982 |
+
}
|
| 983 |
+
}
|
| 984 |
+
t.Run("invalid pattern", func(t *testing.T) {
|
| 985 |
+
re := new(Regexp)
|
| 986 |
+
err := re.UnmarshalText([]byte(`\`))
|
| 987 |
+
if err == nil {
|
| 988 |
+
t.Error("unexpected success")
|
| 989 |
+
}
|
| 990 |
+
})
|
| 991 |
+
}
|
go/src/regexp/backtrack.go
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2015 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 |
+
// backtrack is a regular expression search with submatch
|
| 6 |
+
// tracking for small regular expressions and texts. It allocates
|
| 7 |
+
// a bit vector with (length of input) * (length of prog) bits,
|
| 8 |
+
// to make sure it never explores the same (character position, instruction)
|
| 9 |
+
// state multiple times. This limits the search to run in time linear in
|
| 10 |
+
// the length of the test.
|
| 11 |
+
//
|
| 12 |
+
// backtrack is a fast replacement for the NFA code on small
|
| 13 |
+
// regexps when onepass cannot be used.
|
| 14 |
+
|
| 15 |
+
package regexp
|
| 16 |
+
|
| 17 |
+
import (
|
| 18 |
+
"regexp/syntax"
|
| 19 |
+
"sync"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
// A job is an entry on the backtracker's job stack. It holds
|
| 23 |
+
// the instruction pc and the position in the input.
|
| 24 |
+
type job struct {
|
| 25 |
+
pc uint32
|
| 26 |
+
arg bool
|
| 27 |
+
pos int
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
const (
|
| 31 |
+
visitedBits = 32
|
| 32 |
+
maxBacktrackProg = 500 // len(prog.Inst) <= max
|
| 33 |
+
maxBacktrackVector = 256 * 1024 // bit vector size <= max (bits)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
// bitState holds state for the backtracker.
|
| 37 |
+
type bitState struct {
|
| 38 |
+
end int
|
| 39 |
+
cap []int
|
| 40 |
+
matchcap []int
|
| 41 |
+
jobs []job
|
| 42 |
+
visited []uint32
|
| 43 |
+
|
| 44 |
+
inputs inputs
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
var bitStatePool sync.Pool
|
| 48 |
+
|
| 49 |
+
func newBitState() *bitState {
|
| 50 |
+
b, ok := bitStatePool.Get().(*bitState)
|
| 51 |
+
if !ok {
|
| 52 |
+
b = new(bitState)
|
| 53 |
+
}
|
| 54 |
+
return b
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func freeBitState(b *bitState) {
|
| 58 |
+
b.inputs.clear()
|
| 59 |
+
bitStatePool.Put(b)
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// maxBitStateLen returns the maximum length of a string to search with
|
| 63 |
+
// the backtracker using prog.
|
| 64 |
+
func maxBitStateLen(prog *syntax.Prog) int {
|
| 65 |
+
if !shouldBacktrack(prog) {
|
| 66 |
+
return 0
|
| 67 |
+
}
|
| 68 |
+
return maxBacktrackVector / len(prog.Inst)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// shouldBacktrack reports whether the program is too
|
| 72 |
+
// long for the backtracker to run.
|
| 73 |
+
func shouldBacktrack(prog *syntax.Prog) bool {
|
| 74 |
+
return len(prog.Inst) <= maxBacktrackProg
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// reset resets the state of the backtracker.
|
| 78 |
+
// end is the end position in the input.
|
| 79 |
+
// ncap is the number of captures.
|
| 80 |
+
func (b *bitState) reset(prog *syntax.Prog, end int, ncap int) {
|
| 81 |
+
b.end = end
|
| 82 |
+
|
| 83 |
+
if cap(b.jobs) == 0 {
|
| 84 |
+
b.jobs = make([]job, 0, 256)
|
| 85 |
+
} else {
|
| 86 |
+
b.jobs = b.jobs[:0]
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
visitedSize := (len(prog.Inst)*(end+1) + visitedBits - 1) / visitedBits
|
| 90 |
+
if cap(b.visited) < visitedSize {
|
| 91 |
+
b.visited = make([]uint32, visitedSize, maxBacktrackVector/visitedBits)
|
| 92 |
+
} else {
|
| 93 |
+
b.visited = b.visited[:visitedSize]
|
| 94 |
+
clear(b.visited) // set to 0
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
if cap(b.cap) < ncap {
|
| 98 |
+
b.cap = make([]int, ncap)
|
| 99 |
+
} else {
|
| 100 |
+
b.cap = b.cap[:ncap]
|
| 101 |
+
}
|
| 102 |
+
for i := range b.cap {
|
| 103 |
+
b.cap[i] = -1
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if cap(b.matchcap) < ncap {
|
| 107 |
+
b.matchcap = make([]int, ncap)
|
| 108 |
+
} else {
|
| 109 |
+
b.matchcap = b.matchcap[:ncap]
|
| 110 |
+
}
|
| 111 |
+
for i := range b.matchcap {
|
| 112 |
+
b.matchcap[i] = -1
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// shouldVisit reports whether the combination of (pc, pos) has not
|
| 117 |
+
// been visited yet.
|
| 118 |
+
func (b *bitState) shouldVisit(pc uint32, pos int) bool {
|
| 119 |
+
n := uint(int(pc)*(b.end+1) + pos)
|
| 120 |
+
if b.visited[n/visitedBits]&(1<<(n&(visitedBits-1))) != 0 {
|
| 121 |
+
return false
|
| 122 |
+
}
|
| 123 |
+
b.visited[n/visitedBits] |= 1 << (n & (visitedBits - 1))
|
| 124 |
+
return true
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
// push pushes (pc, pos, arg) onto the job stack if it should be
|
| 128 |
+
// visited.
|
| 129 |
+
func (b *bitState) push(re *Regexp, pc uint32, pos int, arg bool) {
|
| 130 |
+
// Only check shouldVisit when arg is false.
|
| 131 |
+
// When arg is true, we are continuing a previous visit.
|
| 132 |
+
if re.prog.Inst[pc].Op != syntax.InstFail && (arg || b.shouldVisit(pc, pos)) {
|
| 133 |
+
b.jobs = append(b.jobs, job{pc: pc, arg: arg, pos: pos})
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
// tryBacktrack runs a backtracking search starting at pos.
|
| 138 |
+
func (re *Regexp) tryBacktrack(b *bitState, i input, pc uint32, pos int) bool {
|
| 139 |
+
longest := re.longest
|
| 140 |
+
|
| 141 |
+
b.push(re, pc, pos, false)
|
| 142 |
+
for len(b.jobs) > 0 {
|
| 143 |
+
l := len(b.jobs) - 1
|
| 144 |
+
// Pop job off the stack.
|
| 145 |
+
pc := b.jobs[l].pc
|
| 146 |
+
pos := b.jobs[l].pos
|
| 147 |
+
arg := b.jobs[l].arg
|
| 148 |
+
b.jobs = b.jobs[:l]
|
| 149 |
+
|
| 150 |
+
// Optimization: rather than push and pop,
|
| 151 |
+
// code that is going to Push and continue
|
| 152 |
+
// the loop simply updates ip, p, and arg
|
| 153 |
+
// and jumps to CheckAndLoop. We have to
|
| 154 |
+
// do the ShouldVisit check that Push
|
| 155 |
+
// would have, but we avoid the stack
|
| 156 |
+
// manipulation.
|
| 157 |
+
goto Skip
|
| 158 |
+
CheckAndLoop:
|
| 159 |
+
if !b.shouldVisit(pc, pos) {
|
| 160 |
+
continue
|
| 161 |
+
}
|
| 162 |
+
Skip:
|
| 163 |
+
|
| 164 |
+
inst := &re.prog.Inst[pc]
|
| 165 |
+
|
| 166 |
+
switch inst.Op {
|
| 167 |
+
default:
|
| 168 |
+
panic("bad inst")
|
| 169 |
+
case syntax.InstFail:
|
| 170 |
+
panic("unexpected InstFail")
|
| 171 |
+
case syntax.InstAlt:
|
| 172 |
+
// Cannot just
|
| 173 |
+
// b.push(inst.Out, pos, false)
|
| 174 |
+
// b.push(inst.Arg, pos, false)
|
| 175 |
+
// If during the processing of inst.Out, we encounter
|
| 176 |
+
// inst.Arg via another path, we want to process it then.
|
| 177 |
+
// Pushing it here will inhibit that. Instead, re-push
|
| 178 |
+
// inst with arg==true as a reminder to push inst.Arg out
|
| 179 |
+
// later.
|
| 180 |
+
if arg {
|
| 181 |
+
// Finished inst.Out; try inst.Arg.
|
| 182 |
+
arg = false
|
| 183 |
+
pc = inst.Arg
|
| 184 |
+
goto CheckAndLoop
|
| 185 |
+
} else {
|
| 186 |
+
b.push(re, pc, pos, true)
|
| 187 |
+
pc = inst.Out
|
| 188 |
+
goto CheckAndLoop
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
case syntax.InstAltMatch:
|
| 192 |
+
// One opcode consumes runes; the other leads to match.
|
| 193 |
+
switch re.prog.Inst[inst.Out].Op {
|
| 194 |
+
case syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
|
| 195 |
+
// inst.Arg is the match.
|
| 196 |
+
b.push(re, inst.Arg, pos, false)
|
| 197 |
+
pc = inst.Arg
|
| 198 |
+
pos = b.end
|
| 199 |
+
goto CheckAndLoop
|
| 200 |
+
}
|
| 201 |
+
// inst.Out is the match - non-greedy
|
| 202 |
+
b.push(re, inst.Out, b.end, false)
|
| 203 |
+
pc = inst.Out
|
| 204 |
+
goto CheckAndLoop
|
| 205 |
+
|
| 206 |
+
case syntax.InstRune:
|
| 207 |
+
r, width := i.step(pos)
|
| 208 |
+
if !inst.MatchRune(r) {
|
| 209 |
+
continue
|
| 210 |
+
}
|
| 211 |
+
pos += width
|
| 212 |
+
pc = inst.Out
|
| 213 |
+
goto CheckAndLoop
|
| 214 |
+
|
| 215 |
+
case syntax.InstRune1:
|
| 216 |
+
r, width := i.step(pos)
|
| 217 |
+
if r != inst.Rune[0] {
|
| 218 |
+
continue
|
| 219 |
+
}
|
| 220 |
+
pos += width
|
| 221 |
+
pc = inst.Out
|
| 222 |
+
goto CheckAndLoop
|
| 223 |
+
|
| 224 |
+
case syntax.InstRuneAnyNotNL:
|
| 225 |
+
r, width := i.step(pos)
|
| 226 |
+
if r == '\n' || r == endOfText {
|
| 227 |
+
continue
|
| 228 |
+
}
|
| 229 |
+
pos += width
|
| 230 |
+
pc = inst.Out
|
| 231 |
+
goto CheckAndLoop
|
| 232 |
+
|
| 233 |
+
case syntax.InstRuneAny:
|
| 234 |
+
r, width := i.step(pos)
|
| 235 |
+
if r == endOfText {
|
| 236 |
+
continue
|
| 237 |
+
}
|
| 238 |
+
pos += width
|
| 239 |
+
pc = inst.Out
|
| 240 |
+
goto CheckAndLoop
|
| 241 |
+
|
| 242 |
+
case syntax.InstCapture:
|
| 243 |
+
if arg {
|
| 244 |
+
// Finished inst.Out; restore the old value.
|
| 245 |
+
b.cap[inst.Arg] = pos
|
| 246 |
+
continue
|
| 247 |
+
} else {
|
| 248 |
+
if inst.Arg < uint32(len(b.cap)) {
|
| 249 |
+
// Capture pos to register, but save old value.
|
| 250 |
+
b.push(re, pc, b.cap[inst.Arg], true) // come back when we're done.
|
| 251 |
+
b.cap[inst.Arg] = pos
|
| 252 |
+
}
|
| 253 |
+
pc = inst.Out
|
| 254 |
+
goto CheckAndLoop
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
case syntax.InstEmptyWidth:
|
| 258 |
+
flag := i.context(pos)
|
| 259 |
+
if !flag.match(syntax.EmptyOp(inst.Arg)) {
|
| 260 |
+
continue
|
| 261 |
+
}
|
| 262 |
+
pc = inst.Out
|
| 263 |
+
goto CheckAndLoop
|
| 264 |
+
|
| 265 |
+
case syntax.InstNop:
|
| 266 |
+
pc = inst.Out
|
| 267 |
+
goto CheckAndLoop
|
| 268 |
+
|
| 269 |
+
case syntax.InstMatch:
|
| 270 |
+
// We found a match. If the caller doesn't care
|
| 271 |
+
// where the match is, no point going further.
|
| 272 |
+
if len(b.cap) == 0 {
|
| 273 |
+
return true
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
// Record best match so far.
|
| 277 |
+
// Only need to check end point, because this entire
|
| 278 |
+
// call is only considering one start position.
|
| 279 |
+
if len(b.cap) > 1 {
|
| 280 |
+
b.cap[1] = pos
|
| 281 |
+
}
|
| 282 |
+
if old := b.matchcap[1]; old == -1 || (longest && pos > 0 && pos > old) {
|
| 283 |
+
copy(b.matchcap, b.cap)
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
// If going for first match, we're done.
|
| 287 |
+
if !longest {
|
| 288 |
+
return true
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
// If we used the entire text, no longer match is possible.
|
| 292 |
+
if pos == b.end {
|
| 293 |
+
return true
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
// Otherwise, continue on in hope of a longer match.
|
| 297 |
+
continue
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
return longest && len(b.matchcap) > 1 && b.matchcap[1] >= 0
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// backtrack runs a backtracking search of prog on the input starting at pos.
|
| 305 |
+
func (re *Regexp) backtrack(ib []byte, is string, pos int, ncap int, dstCap []int) []int {
|
| 306 |
+
startCond := re.cond
|
| 307 |
+
if startCond == ^syntax.EmptyOp(0) { // impossible
|
| 308 |
+
return nil
|
| 309 |
+
}
|
| 310 |
+
if startCond&syntax.EmptyBeginText != 0 && pos != 0 {
|
| 311 |
+
// Anchored match, past beginning of text.
|
| 312 |
+
return nil
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
b := newBitState()
|
| 316 |
+
i, end := b.inputs.init(nil, ib, is)
|
| 317 |
+
b.reset(re.prog, end, ncap)
|
| 318 |
+
|
| 319 |
+
// Anchored search must start at the beginning of the input
|
| 320 |
+
if startCond&syntax.EmptyBeginText != 0 {
|
| 321 |
+
if len(b.cap) > 0 {
|
| 322 |
+
b.cap[0] = pos
|
| 323 |
+
}
|
| 324 |
+
if !re.tryBacktrack(b, i, uint32(re.prog.Start), pos) {
|
| 325 |
+
freeBitState(b)
|
| 326 |
+
return nil
|
| 327 |
+
}
|
| 328 |
+
} else {
|
| 329 |
+
|
| 330 |
+
// Unanchored search, starting from each possible text position.
|
| 331 |
+
// Notice that we have to try the empty string at the end of
|
| 332 |
+
// the text, so the loop condition is pos <= end, not pos < end.
|
| 333 |
+
// This looks like it's quadratic in the size of the text,
|
| 334 |
+
// but we are not clearing visited between calls to TrySearch,
|
| 335 |
+
// so no work is duplicated and it ends up still being linear.
|
| 336 |
+
width := -1
|
| 337 |
+
for ; pos <= end && width != 0; pos += width {
|
| 338 |
+
if len(re.prefix) > 0 {
|
| 339 |
+
// Match requires literal prefix; fast search for it.
|
| 340 |
+
advance := i.index(re, pos)
|
| 341 |
+
if advance < 0 {
|
| 342 |
+
freeBitState(b)
|
| 343 |
+
return nil
|
| 344 |
+
}
|
| 345 |
+
pos += advance
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
if len(b.cap) > 0 {
|
| 349 |
+
b.cap[0] = pos
|
| 350 |
+
}
|
| 351 |
+
if re.tryBacktrack(b, i, uint32(re.prog.Start), pos) {
|
| 352 |
+
// Match must be leftmost; done.
|
| 353 |
+
goto Match
|
| 354 |
+
}
|
| 355 |
+
_, width = i.step(pos)
|
| 356 |
+
}
|
| 357 |
+
freeBitState(b)
|
| 358 |
+
return nil
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
Match:
|
| 362 |
+
dstCap = append(dstCap, b.matchcap...)
|
| 363 |
+
freeBitState(b)
|
| 364 |
+
return dstCap
|
| 365 |
+
}
|
go/src/regexp/example_test.go
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 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 regexp_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"regexp"
|
| 10 |
+
"strings"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func Example() {
|
| 14 |
+
// Compile the expression once, usually at init time.
|
| 15 |
+
// Use raw strings to avoid having to quote the backslashes.
|
| 16 |
+
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
|
| 17 |
+
|
| 18 |
+
fmt.Println(validID.MatchString("adam[23]"))
|
| 19 |
+
fmt.Println(validID.MatchString("eve[7]"))
|
| 20 |
+
fmt.Println(validID.MatchString("Job[48]"))
|
| 21 |
+
fmt.Println(validID.MatchString("snakey"))
|
| 22 |
+
// Output:
|
| 23 |
+
// true
|
| 24 |
+
// true
|
| 25 |
+
// false
|
| 26 |
+
// false
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
func ExampleMatch() {
|
| 30 |
+
matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
|
| 31 |
+
fmt.Println(matched, err)
|
| 32 |
+
matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
|
| 33 |
+
fmt.Println(matched, err)
|
| 34 |
+
matched, err = regexp.Match(`a(b`, []byte(`seafood`))
|
| 35 |
+
fmt.Println(matched, err)
|
| 36 |
+
|
| 37 |
+
// Output:
|
| 38 |
+
// true <nil>
|
| 39 |
+
// false <nil>
|
| 40 |
+
// false error parsing regexp: missing closing ): `a(b`
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
func ExampleMatchString() {
|
| 44 |
+
matched, err := regexp.MatchString(`foo.*`, "seafood")
|
| 45 |
+
fmt.Println(matched, err)
|
| 46 |
+
matched, err = regexp.MatchString(`bar.*`, "seafood")
|
| 47 |
+
fmt.Println(matched, err)
|
| 48 |
+
matched, err = regexp.MatchString(`a(b`, "seafood")
|
| 49 |
+
fmt.Println(matched, err)
|
| 50 |
+
// Output:
|
| 51 |
+
// true <nil>
|
| 52 |
+
// false <nil>
|
| 53 |
+
// false error parsing regexp: missing closing ): `a(b`
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func ExampleQuoteMeta() {
|
| 57 |
+
fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
|
| 58 |
+
// Output:
|
| 59 |
+
// Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
func ExampleRegexp_Find() {
|
| 63 |
+
re := regexp.MustCompile(`foo.?`)
|
| 64 |
+
fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
|
| 65 |
+
|
| 66 |
+
// Output:
|
| 67 |
+
// "food"
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
func ExampleRegexp_FindAll() {
|
| 71 |
+
re := regexp.MustCompile(`foo.?`)
|
| 72 |
+
fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))
|
| 73 |
+
|
| 74 |
+
// Output:
|
| 75 |
+
// ["food" "fool"]
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
func ExampleRegexp_FindAllSubmatch() {
|
| 79 |
+
re := regexp.MustCompile(`foo(.?)`)
|
| 80 |
+
fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))
|
| 81 |
+
|
| 82 |
+
// Output:
|
| 83 |
+
// [["food" "d"] ["fool" "l"]]
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func ExampleRegexp_FindSubmatch() {
|
| 87 |
+
re := regexp.MustCompile(`foo(.?)`)
|
| 88 |
+
fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))
|
| 89 |
+
|
| 90 |
+
// Output:
|
| 91 |
+
// ["food" "d"]
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func ExampleRegexp_Match() {
|
| 95 |
+
re := regexp.MustCompile(`foo.?`)
|
| 96 |
+
fmt.Println(re.Match([]byte(`seafood fool`)))
|
| 97 |
+
fmt.Println(re.Match([]byte(`something else`)))
|
| 98 |
+
|
| 99 |
+
// Output:
|
| 100 |
+
// true
|
| 101 |
+
// false
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
func ExampleRegexp_FindString() {
|
| 105 |
+
re := regexp.MustCompile(`foo.?`)
|
| 106 |
+
fmt.Printf("%q\n", re.FindString("seafood fool"))
|
| 107 |
+
fmt.Printf("%q\n", re.FindString("meat"))
|
| 108 |
+
// Output:
|
| 109 |
+
// "food"
|
| 110 |
+
// ""
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
func ExampleRegexp_FindStringIndex() {
|
| 114 |
+
re := regexp.MustCompile(`ab?`)
|
| 115 |
+
fmt.Println(re.FindStringIndex("tablett"))
|
| 116 |
+
fmt.Println(re.FindStringIndex("foo") == nil)
|
| 117 |
+
// Output:
|
| 118 |
+
// [1 3]
|
| 119 |
+
// true
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
func ExampleRegexp_FindStringSubmatch() {
|
| 123 |
+
re := regexp.MustCompile(`a(x*)b(y|z)c`)
|
| 124 |
+
fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
|
| 125 |
+
fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
|
| 126 |
+
// Output:
|
| 127 |
+
// ["axxxbyc" "xxx" "y"]
|
| 128 |
+
// ["abzc" "" "z"]
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
func ExampleRegexp_FindAllString() {
|
| 132 |
+
re := regexp.MustCompile(`a.`)
|
| 133 |
+
fmt.Println(re.FindAllString("paranormal", -1))
|
| 134 |
+
fmt.Println(re.FindAllString("paranormal", 2))
|
| 135 |
+
fmt.Println(re.FindAllString("graal", -1))
|
| 136 |
+
fmt.Println(re.FindAllString("none", -1))
|
| 137 |
+
// Output:
|
| 138 |
+
// [ar an al]
|
| 139 |
+
// [ar an]
|
| 140 |
+
// [aa]
|
| 141 |
+
// []
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
func ExampleRegexp_FindAllStringSubmatch() {
|
| 145 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 146 |
+
fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
|
| 147 |
+
fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
|
| 148 |
+
fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
|
| 149 |
+
fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
|
| 150 |
+
// Output:
|
| 151 |
+
// [["ab" ""]]
|
| 152 |
+
// [["axxb" "xx"]]
|
| 153 |
+
// [["ab" ""] ["axb" "x"]]
|
| 154 |
+
// [["axxb" "xx"] ["ab" ""]]
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
func ExampleRegexp_FindAllStringSubmatchIndex() {
|
| 158 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 159 |
+
// Indices:
|
| 160 |
+
// 01234567 012345678
|
| 161 |
+
// -ab-axb- -axxb-ab-
|
| 162 |
+
fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
|
| 163 |
+
fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
|
| 164 |
+
fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
|
| 165 |
+
fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
|
| 166 |
+
fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
|
| 167 |
+
// Output:
|
| 168 |
+
// [[1 3 2 2]]
|
| 169 |
+
// [[1 5 2 4]]
|
| 170 |
+
// [[1 3 2 2] [4 7 5 6]]
|
| 171 |
+
// [[1 5 2 4] [6 8 7 7]]
|
| 172 |
+
// []
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func ExampleRegexp_FindSubmatchIndex() {
|
| 176 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 177 |
+
// Indices:
|
| 178 |
+
// 01234567 012345678
|
| 179 |
+
// -ab-axb- -axxb-ab-
|
| 180 |
+
fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
|
| 181 |
+
fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
|
| 182 |
+
fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
|
| 183 |
+
fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
|
| 184 |
+
fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))
|
| 185 |
+
// Output:
|
| 186 |
+
// [1 3 2 2]
|
| 187 |
+
// [1 5 2 4]
|
| 188 |
+
// [1 3 2 2]
|
| 189 |
+
// [1 5 2 4]
|
| 190 |
+
// []
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
func ExampleRegexp_Longest() {
|
| 194 |
+
re := regexp.MustCompile(`a(|b)`)
|
| 195 |
+
fmt.Println(re.FindString("ab"))
|
| 196 |
+
re.Longest()
|
| 197 |
+
fmt.Println(re.FindString("ab"))
|
| 198 |
+
// Output:
|
| 199 |
+
// a
|
| 200 |
+
// ab
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
func ExampleRegexp_MatchString() {
|
| 204 |
+
re := regexp.MustCompile(`(gopher){2}`)
|
| 205 |
+
fmt.Println(re.MatchString("gopher"))
|
| 206 |
+
fmt.Println(re.MatchString("gophergopher"))
|
| 207 |
+
fmt.Println(re.MatchString("gophergophergopher"))
|
| 208 |
+
// Output:
|
| 209 |
+
// false
|
| 210 |
+
// true
|
| 211 |
+
// true
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
func ExampleRegexp_NumSubexp() {
|
| 215 |
+
re0 := regexp.MustCompile(`a.`)
|
| 216 |
+
fmt.Printf("%d\n", re0.NumSubexp())
|
| 217 |
+
|
| 218 |
+
re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
|
| 219 |
+
fmt.Println(re.NumSubexp())
|
| 220 |
+
// Output:
|
| 221 |
+
// 0
|
| 222 |
+
// 4
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
func ExampleRegexp_ReplaceAll() {
|
| 226 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 227 |
+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
|
| 228 |
+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
|
| 229 |
+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
|
| 230 |
+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
|
| 231 |
+
|
| 232 |
+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
|
| 233 |
+
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
|
| 234 |
+
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
|
| 235 |
+
|
| 236 |
+
// Output:
|
| 237 |
+
// -T-T-
|
| 238 |
+
// --xx-
|
| 239 |
+
// ---
|
| 240 |
+
// -W-xxW-
|
| 241 |
+
// --xx-
|
| 242 |
+
// -W-xxW-
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
func ExampleRegexp_ReplaceAllLiteralString() {
|
| 246 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 247 |
+
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
|
| 248 |
+
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
|
| 249 |
+
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
|
| 250 |
+
// Output:
|
| 251 |
+
// -T-T-
|
| 252 |
+
// -$1-$1-
|
| 253 |
+
// -${1}-${1}-
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
func ExampleRegexp_ReplaceAllString() {
|
| 257 |
+
re := regexp.MustCompile(`a(x*)b`)
|
| 258 |
+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
|
| 259 |
+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
|
| 260 |
+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
|
| 261 |
+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
|
| 262 |
+
|
| 263 |
+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
|
| 264 |
+
fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
|
| 265 |
+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
|
| 266 |
+
|
| 267 |
+
// Output:
|
| 268 |
+
// -T-T-
|
| 269 |
+
// --xx-
|
| 270 |
+
// ---
|
| 271 |
+
// -W-xxW-
|
| 272 |
+
// --xx-
|
| 273 |
+
// -W-xxW-
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
func ExampleRegexp_ReplaceAllStringFunc() {
|
| 277 |
+
re := regexp.MustCompile(`[^aeiou]`)
|
| 278 |
+
fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
|
| 279 |
+
// Output:
|
| 280 |
+
// SeaFooD FooL
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
func ExampleRegexp_SubexpNames() {
|
| 284 |
+
re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
|
| 285 |
+
fmt.Println(re.MatchString("Alan Turing"))
|
| 286 |
+
fmt.Printf("%q\n", re.SubexpNames())
|
| 287 |
+
reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
|
| 288 |
+
fmt.Println(reversed)
|
| 289 |
+
fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
|
| 290 |
+
// Output:
|
| 291 |
+
// true
|
| 292 |
+
// ["" "first" "last"]
|
| 293 |
+
// ${last} ${first}
|
| 294 |
+
// Turing Alan
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
func ExampleRegexp_SubexpIndex() {
|
| 298 |
+
re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
|
| 299 |
+
fmt.Println(re.MatchString("Alan Turing"))
|
| 300 |
+
matches := re.FindStringSubmatch("Alan Turing")
|
| 301 |
+
lastIndex := re.SubexpIndex("last")
|
| 302 |
+
fmt.Printf("last => %d\n", lastIndex)
|
| 303 |
+
fmt.Println(matches[lastIndex])
|
| 304 |
+
// Output:
|
| 305 |
+
// true
|
| 306 |
+
// last => 2
|
| 307 |
+
// Turing
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
func ExampleRegexp_Split() {
|
| 311 |
+
a := regexp.MustCompile(`a`)
|
| 312 |
+
fmt.Println(a.Split("banana", -1))
|
| 313 |
+
fmt.Println(a.Split("banana", 0))
|
| 314 |
+
fmt.Println(a.Split("banana", 1))
|
| 315 |
+
fmt.Println(a.Split("banana", 2))
|
| 316 |
+
zp := regexp.MustCompile(`z+`)
|
| 317 |
+
fmt.Println(zp.Split("pizza", -1))
|
| 318 |
+
fmt.Println(zp.Split("pizza", 0))
|
| 319 |
+
fmt.Println(zp.Split("pizza", 1))
|
| 320 |
+
fmt.Println(zp.Split("pizza", 2))
|
| 321 |
+
// Output:
|
| 322 |
+
// [b n n ]
|
| 323 |
+
// []
|
| 324 |
+
// [banana]
|
| 325 |
+
// [b nana]
|
| 326 |
+
// [pi a]
|
| 327 |
+
// []
|
| 328 |
+
// [pizza]
|
| 329 |
+
// [pi a]
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
func ExampleRegexp_Expand() {
|
| 333 |
+
content := []byte(`
|
| 334 |
+
# comment line
|
| 335 |
+
option1: value1
|
| 336 |
+
option2: value2
|
| 337 |
+
|
| 338 |
+
# another comment line
|
| 339 |
+
option3: value3
|
| 340 |
+
`)
|
| 341 |
+
|
| 342 |
+
// Regex pattern captures "key: value" pair from the content.
|
| 343 |
+
pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
|
| 344 |
+
|
| 345 |
+
// Template to convert "key: value" to "key=value" by
|
| 346 |
+
// referencing the values captured by the regex pattern.
|
| 347 |
+
template := []byte("$key=$value\n")
|
| 348 |
+
|
| 349 |
+
result := []byte{}
|
| 350 |
+
|
| 351 |
+
// For each match of the regex in the content.
|
| 352 |
+
for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
|
| 353 |
+
// Apply the captured submatches to the template and append the output
|
| 354 |
+
// to the result.
|
| 355 |
+
result = pattern.Expand(result, template, content, submatches)
|
| 356 |
+
}
|
| 357 |
+
fmt.Println(string(result))
|
| 358 |
+
// Output:
|
| 359 |
+
// option1=value1
|
| 360 |
+
// option2=value2
|
| 361 |
+
// option3=value3
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
func ExampleRegexp_ExpandString() {
|
| 365 |
+
content := `
|
| 366 |
+
# comment line
|
| 367 |
+
option1: value1
|
| 368 |
+
option2: value2
|
| 369 |
+
|
| 370 |
+
# another comment line
|
| 371 |
+
option3: value3
|
| 372 |
+
`
|
| 373 |
+
|
| 374 |
+
// Regex pattern captures "key: value" pair from the content.
|
| 375 |
+
pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
|
| 376 |
+
|
| 377 |
+
// Template to convert "key: value" to "key=value" by
|
| 378 |
+
// referencing the values captured by the regex pattern.
|
| 379 |
+
template := "$key=$value\n"
|
| 380 |
+
|
| 381 |
+
result := []byte{}
|
| 382 |
+
|
| 383 |
+
// For each match of the regex in the content.
|
| 384 |
+
for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
|
| 385 |
+
// Apply the captured submatches to the template and append the output
|
| 386 |
+
// to the result.
|
| 387 |
+
result = pattern.ExpandString(result, template, content, submatches)
|
| 388 |
+
}
|
| 389 |
+
fmt.Println(string(result))
|
| 390 |
+
// Output:
|
| 391 |
+
// option1=value1
|
| 392 |
+
// option2=value2
|
| 393 |
+
// option3=value3
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
func ExampleRegexp_FindIndex() {
|
| 397 |
+
content := []byte(`
|
| 398 |
+
# comment line
|
| 399 |
+
option1: value1
|
| 400 |
+
option2: value2
|
| 401 |
+
`)
|
| 402 |
+
// Regex pattern captures "key: value" pair from the content.
|
| 403 |
+
pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
|
| 404 |
+
|
| 405 |
+
loc := pattern.FindIndex(content)
|
| 406 |
+
fmt.Println(loc)
|
| 407 |
+
fmt.Println(string(content[loc[0]:loc[1]]))
|
| 408 |
+
// Output:
|
| 409 |
+
// [18 33]
|
| 410 |
+
// option1: value1
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
func ExampleRegexp_FindAllSubmatchIndex() {
|
| 414 |
+
content := []byte(`
|
| 415 |
+
# comment line
|
| 416 |
+
option1: value1
|
| 417 |
+
option2: value2
|
| 418 |
+
`)
|
| 419 |
+
// Regex pattern captures "key: value" pair from the content.
|
| 420 |
+
pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
|
| 421 |
+
allIndexes := pattern.FindAllSubmatchIndex(content, -1)
|
| 422 |
+
for _, loc := range allIndexes {
|
| 423 |
+
fmt.Println(loc)
|
| 424 |
+
fmt.Println(string(content[loc[0]:loc[1]]))
|
| 425 |
+
fmt.Println(string(content[loc[2]:loc[3]]))
|
| 426 |
+
fmt.Println(string(content[loc[4]:loc[5]]))
|
| 427 |
+
}
|
| 428 |
+
// Output:
|
| 429 |
+
// [18 33 18 25 27 33]
|
| 430 |
+
// option1: value1
|
| 431 |
+
// option1
|
| 432 |
+
// value1
|
| 433 |
+
// [35 50 35 42 44 50]
|
| 434 |
+
// option2: value2
|
| 435 |
+
// option2
|
| 436 |
+
// value2
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
func ExampleRegexp_FindAllIndex() {
|
| 440 |
+
content := []byte("London")
|
| 441 |
+
re := regexp.MustCompile(`o.`)
|
| 442 |
+
fmt.Println(re.FindAllIndex(content, 1))
|
| 443 |
+
fmt.Println(re.FindAllIndex(content, -1))
|
| 444 |
+
// Output:
|
| 445 |
+
// [[1 3]]
|
| 446 |
+
// [[1 3] [4 6]]
|
| 447 |
+
}
|
go/src/regexp/exec.go
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ed by a BSD-style
|
| 3 |
+
// license that can be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
package regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"io"
|
| 9 |
+
"regexp/syntax"
|
| 10 |
+
"sync"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// A queue is a 'sparse array' holding pending threads of execution.
|
| 14 |
+
// See https://research.swtch.com/2008/03/using-uninitialized-memory-for-fun-and.html
|
| 15 |
+
type queue struct {
|
| 16 |
+
sparse []uint32
|
| 17 |
+
dense []entry
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
// An entry is an entry on a queue.
|
| 21 |
+
// It holds both the instruction pc and the actual thread.
|
| 22 |
+
// Some queue entries are just place holders so that the machine
|
| 23 |
+
// knows it has considered that pc. Such entries have t == nil.
|
| 24 |
+
type entry struct {
|
| 25 |
+
pc uint32
|
| 26 |
+
t *thread
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// A thread is the state of a single path through the machine:
|
| 30 |
+
// an instruction and a corresponding capture array.
|
| 31 |
+
// See https://swtch.com/~rsc/regexp/regexp2.html
|
| 32 |
+
type thread struct {
|
| 33 |
+
inst *syntax.Inst
|
| 34 |
+
cap []int
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// A machine holds all the state during an NFA simulation for p.
|
| 38 |
+
type machine struct {
|
| 39 |
+
re *Regexp // corresponding Regexp
|
| 40 |
+
p *syntax.Prog // compiled program
|
| 41 |
+
q0, q1 queue // two queues for runq, nextq
|
| 42 |
+
pool []*thread // pool of available threads
|
| 43 |
+
matched bool // whether a match was found
|
| 44 |
+
matchcap []int // capture information for the match
|
| 45 |
+
|
| 46 |
+
inputs inputs
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
type inputs struct {
|
| 50 |
+
// cached inputs, to avoid allocation
|
| 51 |
+
bytes inputBytes
|
| 52 |
+
string inputString
|
| 53 |
+
reader inputReader
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func (i *inputs) newBytes(b []byte) input {
|
| 57 |
+
i.bytes.str = b
|
| 58 |
+
return &i.bytes
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
func (i *inputs) newString(s string) input {
|
| 62 |
+
i.string.str = s
|
| 63 |
+
return &i.string
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
func (i *inputs) newReader(r io.RuneReader) input {
|
| 67 |
+
i.reader.r = r
|
| 68 |
+
i.reader.atEOT = false
|
| 69 |
+
i.reader.pos = 0
|
| 70 |
+
return &i.reader
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func (i *inputs) clear() {
|
| 74 |
+
// We need to clear 1 of these.
|
| 75 |
+
// Avoid the expense of clearing the others (pointer write barrier).
|
| 76 |
+
if i.bytes.str != nil {
|
| 77 |
+
i.bytes.str = nil
|
| 78 |
+
} else if i.reader.r != nil {
|
| 79 |
+
i.reader.r = nil
|
| 80 |
+
} else {
|
| 81 |
+
i.string.str = ""
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
func (i *inputs) init(r io.RuneReader, b []byte, s string) (input, int) {
|
| 86 |
+
if r != nil {
|
| 87 |
+
return i.newReader(r), 0
|
| 88 |
+
}
|
| 89 |
+
if b != nil {
|
| 90 |
+
return i.newBytes(b), len(b)
|
| 91 |
+
}
|
| 92 |
+
return i.newString(s), len(s)
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
func (m *machine) init(ncap int) {
|
| 96 |
+
for _, t := range m.pool {
|
| 97 |
+
t.cap = t.cap[:ncap]
|
| 98 |
+
}
|
| 99 |
+
m.matchcap = m.matchcap[:ncap]
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// alloc allocates a new thread with the given instruction.
|
| 103 |
+
// It uses the free pool if possible.
|
| 104 |
+
func (m *machine) alloc(i *syntax.Inst) *thread {
|
| 105 |
+
var t *thread
|
| 106 |
+
if n := len(m.pool); n > 0 {
|
| 107 |
+
t = m.pool[n-1]
|
| 108 |
+
m.pool = m.pool[:n-1]
|
| 109 |
+
} else {
|
| 110 |
+
t = new(thread)
|
| 111 |
+
t.cap = make([]int, len(m.matchcap), cap(m.matchcap))
|
| 112 |
+
}
|
| 113 |
+
t.inst = i
|
| 114 |
+
return t
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// A lazyFlag is a lazily-evaluated syntax.EmptyOp,
|
| 118 |
+
// for checking zero-width flags like ^ $ \A \z \B \b.
|
| 119 |
+
// It records the pair of relevant runes and does not
|
| 120 |
+
// determine the implied flags until absolutely necessary
|
| 121 |
+
// (most of the time, that means never).
|
| 122 |
+
type lazyFlag uint64
|
| 123 |
+
|
| 124 |
+
func newLazyFlag(r1, r2 rune) lazyFlag {
|
| 125 |
+
return lazyFlag(uint64(r1)<<32 | uint64(uint32(r2)))
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
func (f lazyFlag) match(op syntax.EmptyOp) bool {
|
| 129 |
+
if op == 0 {
|
| 130 |
+
return true
|
| 131 |
+
}
|
| 132 |
+
r1 := rune(f >> 32)
|
| 133 |
+
if op&syntax.EmptyBeginLine != 0 {
|
| 134 |
+
if r1 != '\n' && r1 >= 0 {
|
| 135 |
+
return false
|
| 136 |
+
}
|
| 137 |
+
op &^= syntax.EmptyBeginLine
|
| 138 |
+
}
|
| 139 |
+
if op&syntax.EmptyBeginText != 0 {
|
| 140 |
+
if r1 >= 0 {
|
| 141 |
+
return false
|
| 142 |
+
}
|
| 143 |
+
op &^= syntax.EmptyBeginText
|
| 144 |
+
}
|
| 145 |
+
if op == 0 {
|
| 146 |
+
return true
|
| 147 |
+
}
|
| 148 |
+
r2 := rune(f)
|
| 149 |
+
if op&syntax.EmptyEndLine != 0 {
|
| 150 |
+
if r2 != '\n' && r2 >= 0 {
|
| 151 |
+
return false
|
| 152 |
+
}
|
| 153 |
+
op &^= syntax.EmptyEndLine
|
| 154 |
+
}
|
| 155 |
+
if op&syntax.EmptyEndText != 0 {
|
| 156 |
+
if r2 >= 0 {
|
| 157 |
+
return false
|
| 158 |
+
}
|
| 159 |
+
op &^= syntax.EmptyEndText
|
| 160 |
+
}
|
| 161 |
+
if op == 0 {
|
| 162 |
+
return true
|
| 163 |
+
}
|
| 164 |
+
if syntax.IsWordChar(r1) != syntax.IsWordChar(r2) {
|
| 165 |
+
op &^= syntax.EmptyWordBoundary
|
| 166 |
+
} else {
|
| 167 |
+
op &^= syntax.EmptyNoWordBoundary
|
| 168 |
+
}
|
| 169 |
+
return op == 0
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
// match runs the machine over the input starting at pos.
|
| 173 |
+
// It reports whether a match was found.
|
| 174 |
+
// If so, m.matchcap holds the submatch information.
|
| 175 |
+
func (m *machine) match(i input, pos int) bool {
|
| 176 |
+
startCond := m.re.cond
|
| 177 |
+
if startCond == ^syntax.EmptyOp(0) { // impossible
|
| 178 |
+
return false
|
| 179 |
+
}
|
| 180 |
+
m.matched = false
|
| 181 |
+
for i := range m.matchcap {
|
| 182 |
+
m.matchcap[i] = -1
|
| 183 |
+
}
|
| 184 |
+
runq, nextq := &m.q0, &m.q1
|
| 185 |
+
r, r1 := endOfText, endOfText
|
| 186 |
+
width, width1 := 0, 0
|
| 187 |
+
r, width = i.step(pos)
|
| 188 |
+
if r != endOfText {
|
| 189 |
+
r1, width1 = i.step(pos + width)
|
| 190 |
+
}
|
| 191 |
+
var flag lazyFlag
|
| 192 |
+
if pos == 0 {
|
| 193 |
+
flag = newLazyFlag(-1, r)
|
| 194 |
+
} else {
|
| 195 |
+
flag = i.context(pos)
|
| 196 |
+
}
|
| 197 |
+
for {
|
| 198 |
+
if len(runq.dense) == 0 {
|
| 199 |
+
if startCond&syntax.EmptyBeginText != 0 && pos != 0 {
|
| 200 |
+
// Anchored match, past beginning of text.
|
| 201 |
+
break
|
| 202 |
+
}
|
| 203 |
+
if m.matched {
|
| 204 |
+
// Have match; finished exploring alternatives.
|
| 205 |
+
break
|
| 206 |
+
}
|
| 207 |
+
if len(m.re.prefix) > 0 && r1 != m.re.prefixRune && i.canCheckPrefix() {
|
| 208 |
+
// Match requires literal prefix; fast search for it.
|
| 209 |
+
advance := i.index(m.re, pos)
|
| 210 |
+
if advance < 0 {
|
| 211 |
+
break
|
| 212 |
+
}
|
| 213 |
+
pos += advance
|
| 214 |
+
r, width = i.step(pos)
|
| 215 |
+
r1, width1 = i.step(pos + width)
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
if !m.matched {
|
| 219 |
+
if len(m.matchcap) > 0 {
|
| 220 |
+
m.matchcap[0] = pos
|
| 221 |
+
}
|
| 222 |
+
m.add(runq, uint32(m.p.Start), pos, m.matchcap, &flag, nil)
|
| 223 |
+
}
|
| 224 |
+
flag = newLazyFlag(r, r1)
|
| 225 |
+
m.step(runq, nextq, pos, pos+width, r, &flag)
|
| 226 |
+
if width == 0 {
|
| 227 |
+
break
|
| 228 |
+
}
|
| 229 |
+
if len(m.matchcap) == 0 && m.matched {
|
| 230 |
+
// Found a match and not paying attention
|
| 231 |
+
// to where it is, so any match will do.
|
| 232 |
+
break
|
| 233 |
+
}
|
| 234 |
+
pos += width
|
| 235 |
+
r, width = r1, width1
|
| 236 |
+
if r != endOfText {
|
| 237 |
+
r1, width1 = i.step(pos + width)
|
| 238 |
+
}
|
| 239 |
+
runq, nextq = nextq, runq
|
| 240 |
+
}
|
| 241 |
+
m.clear(nextq)
|
| 242 |
+
return m.matched
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
// clear frees all threads on the thread queue.
|
| 246 |
+
func (m *machine) clear(q *queue) {
|
| 247 |
+
for _, d := range q.dense {
|
| 248 |
+
if d.t != nil {
|
| 249 |
+
m.pool = append(m.pool, d.t)
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
q.dense = q.dense[:0]
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// step executes one step of the machine, running each of the threads
|
| 256 |
+
// on runq and appending new threads to nextq.
|
| 257 |
+
// The step processes the rune c (which may be endOfText),
|
| 258 |
+
// which starts at position pos and ends at nextPos.
|
| 259 |
+
// nextCond gives the setting for the empty-width flags after c.
|
| 260 |
+
func (m *machine) step(runq, nextq *queue, pos, nextPos int, c rune, nextCond *lazyFlag) {
|
| 261 |
+
longest := m.re.longest
|
| 262 |
+
for j := 0; j < len(runq.dense); j++ {
|
| 263 |
+
d := &runq.dense[j]
|
| 264 |
+
t := d.t
|
| 265 |
+
if t == nil {
|
| 266 |
+
continue
|
| 267 |
+
}
|
| 268 |
+
if longest && m.matched && len(t.cap) > 0 && m.matchcap[0] < t.cap[0] {
|
| 269 |
+
m.pool = append(m.pool, t)
|
| 270 |
+
continue
|
| 271 |
+
}
|
| 272 |
+
i := t.inst
|
| 273 |
+
add := false
|
| 274 |
+
switch i.Op {
|
| 275 |
+
default:
|
| 276 |
+
panic("bad inst")
|
| 277 |
+
|
| 278 |
+
case syntax.InstMatch:
|
| 279 |
+
if len(t.cap) > 0 && (!longest || !m.matched || m.matchcap[1] < pos) {
|
| 280 |
+
t.cap[1] = pos
|
| 281 |
+
copy(m.matchcap, t.cap)
|
| 282 |
+
}
|
| 283 |
+
if !longest {
|
| 284 |
+
// First-match mode: cut off all lower-priority threads.
|
| 285 |
+
for _, d := range runq.dense[j+1:] {
|
| 286 |
+
if d.t != nil {
|
| 287 |
+
m.pool = append(m.pool, d.t)
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
runq.dense = runq.dense[:0]
|
| 291 |
+
}
|
| 292 |
+
m.matched = true
|
| 293 |
+
|
| 294 |
+
case syntax.InstRune:
|
| 295 |
+
add = i.MatchRune(c)
|
| 296 |
+
case syntax.InstRune1:
|
| 297 |
+
add = c == i.Rune[0]
|
| 298 |
+
case syntax.InstRuneAny:
|
| 299 |
+
add = true
|
| 300 |
+
case syntax.InstRuneAnyNotNL:
|
| 301 |
+
add = c != '\n'
|
| 302 |
+
}
|
| 303 |
+
if add {
|
| 304 |
+
t = m.add(nextq, i.Out, nextPos, t.cap, nextCond, t)
|
| 305 |
+
}
|
| 306 |
+
if t != nil {
|
| 307 |
+
m.pool = append(m.pool, t)
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
runq.dense = runq.dense[:0]
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// add adds an entry to q for pc, unless the q already has such an entry.
|
| 314 |
+
// It also recursively adds an entry for all instructions reachable from pc by following
|
| 315 |
+
// empty-width conditions satisfied by cond. pos gives the current position
|
| 316 |
+
// in the input.
|
| 317 |
+
func (m *machine) add(q *queue, pc uint32, pos int, cap []int, cond *lazyFlag, t *thread) *thread {
|
| 318 |
+
Again:
|
| 319 |
+
if pc == 0 {
|
| 320 |
+
return t
|
| 321 |
+
}
|
| 322 |
+
if j := q.sparse[pc]; j < uint32(len(q.dense)) && q.dense[j].pc == pc {
|
| 323 |
+
return t
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
j := len(q.dense)
|
| 327 |
+
q.dense = q.dense[:j+1]
|
| 328 |
+
d := &q.dense[j]
|
| 329 |
+
d.t = nil
|
| 330 |
+
d.pc = pc
|
| 331 |
+
q.sparse[pc] = uint32(j)
|
| 332 |
+
|
| 333 |
+
i := &m.p.Inst[pc]
|
| 334 |
+
switch i.Op {
|
| 335 |
+
default:
|
| 336 |
+
panic("unhandled")
|
| 337 |
+
case syntax.InstFail:
|
| 338 |
+
// nothing
|
| 339 |
+
case syntax.InstAlt, syntax.InstAltMatch:
|
| 340 |
+
t = m.add(q, i.Out, pos, cap, cond, t)
|
| 341 |
+
pc = i.Arg
|
| 342 |
+
goto Again
|
| 343 |
+
case syntax.InstEmptyWidth:
|
| 344 |
+
if cond.match(syntax.EmptyOp(i.Arg)) {
|
| 345 |
+
pc = i.Out
|
| 346 |
+
goto Again
|
| 347 |
+
}
|
| 348 |
+
case syntax.InstNop:
|
| 349 |
+
pc = i.Out
|
| 350 |
+
goto Again
|
| 351 |
+
case syntax.InstCapture:
|
| 352 |
+
if int(i.Arg) < len(cap) {
|
| 353 |
+
opos := cap[i.Arg]
|
| 354 |
+
cap[i.Arg] = pos
|
| 355 |
+
m.add(q, i.Out, pos, cap, cond, nil)
|
| 356 |
+
cap[i.Arg] = opos
|
| 357 |
+
} else {
|
| 358 |
+
pc = i.Out
|
| 359 |
+
goto Again
|
| 360 |
+
}
|
| 361 |
+
case syntax.InstMatch, syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
|
| 362 |
+
if t == nil {
|
| 363 |
+
t = m.alloc(i)
|
| 364 |
+
} else {
|
| 365 |
+
t.inst = i
|
| 366 |
+
}
|
| 367 |
+
if len(cap) > 0 && &t.cap[0] != &cap[0] {
|
| 368 |
+
copy(t.cap, cap)
|
| 369 |
+
}
|
| 370 |
+
d.t = t
|
| 371 |
+
t = nil
|
| 372 |
+
}
|
| 373 |
+
return t
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
type onePassMachine struct {
|
| 377 |
+
inputs inputs
|
| 378 |
+
matchcap []int
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
var onePassPool sync.Pool
|
| 382 |
+
|
| 383 |
+
func newOnePassMachine() *onePassMachine {
|
| 384 |
+
m, ok := onePassPool.Get().(*onePassMachine)
|
| 385 |
+
if !ok {
|
| 386 |
+
m = new(onePassMachine)
|
| 387 |
+
}
|
| 388 |
+
return m
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
func freeOnePassMachine(m *onePassMachine) {
|
| 392 |
+
m.inputs.clear()
|
| 393 |
+
onePassPool.Put(m)
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// doOnePass implements r.doExecute using the one-pass execution engine.
|
| 397 |
+
func (re *Regexp) doOnePass(ir io.RuneReader, ib []byte, is string, pos, ncap int, dstCap []int) []int {
|
| 398 |
+
startCond := re.cond
|
| 399 |
+
if startCond == ^syntax.EmptyOp(0) { // impossible
|
| 400 |
+
return nil
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
m := newOnePassMachine()
|
| 404 |
+
if cap(m.matchcap) < ncap {
|
| 405 |
+
m.matchcap = make([]int, ncap)
|
| 406 |
+
} else {
|
| 407 |
+
m.matchcap = m.matchcap[:ncap]
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
matched := false
|
| 411 |
+
for i := range m.matchcap {
|
| 412 |
+
m.matchcap[i] = -1
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
i, _ := m.inputs.init(ir, ib, is)
|
| 416 |
+
|
| 417 |
+
r, r1 := endOfText, endOfText
|
| 418 |
+
width, width1 := 0, 0
|
| 419 |
+
r, width = i.step(pos)
|
| 420 |
+
if r != endOfText {
|
| 421 |
+
r1, width1 = i.step(pos + width)
|
| 422 |
+
}
|
| 423 |
+
var flag lazyFlag
|
| 424 |
+
if pos == 0 {
|
| 425 |
+
flag = newLazyFlag(-1, r)
|
| 426 |
+
} else {
|
| 427 |
+
flag = i.context(pos)
|
| 428 |
+
}
|
| 429 |
+
pc := re.onepass.Start
|
| 430 |
+
inst := &re.onepass.Inst[pc]
|
| 431 |
+
// If there is a simple literal prefix, skip over it.
|
| 432 |
+
if pos == 0 && flag.match(syntax.EmptyOp(inst.Arg)) &&
|
| 433 |
+
len(re.prefix) > 0 && i.canCheckPrefix() {
|
| 434 |
+
// Match requires literal prefix; fast search for it.
|
| 435 |
+
if !i.hasPrefix(re) {
|
| 436 |
+
goto Return
|
| 437 |
+
}
|
| 438 |
+
pos += len(re.prefix)
|
| 439 |
+
r, width = i.step(pos)
|
| 440 |
+
r1, width1 = i.step(pos + width)
|
| 441 |
+
flag = i.context(pos)
|
| 442 |
+
pc = int(re.prefixEnd)
|
| 443 |
+
}
|
| 444 |
+
for {
|
| 445 |
+
inst = &re.onepass.Inst[pc]
|
| 446 |
+
pc = int(inst.Out)
|
| 447 |
+
switch inst.Op {
|
| 448 |
+
default:
|
| 449 |
+
panic("bad inst")
|
| 450 |
+
case syntax.InstMatch:
|
| 451 |
+
matched = true
|
| 452 |
+
if len(m.matchcap) > 0 {
|
| 453 |
+
m.matchcap[0] = 0
|
| 454 |
+
m.matchcap[1] = pos
|
| 455 |
+
}
|
| 456 |
+
goto Return
|
| 457 |
+
case syntax.InstRune:
|
| 458 |
+
if !inst.MatchRune(r) {
|
| 459 |
+
goto Return
|
| 460 |
+
}
|
| 461 |
+
case syntax.InstRune1:
|
| 462 |
+
if r != inst.Rune[0] {
|
| 463 |
+
goto Return
|
| 464 |
+
}
|
| 465 |
+
case syntax.InstRuneAny:
|
| 466 |
+
// Nothing
|
| 467 |
+
case syntax.InstRuneAnyNotNL:
|
| 468 |
+
if r == '\n' {
|
| 469 |
+
goto Return
|
| 470 |
+
}
|
| 471 |
+
// peek at the input rune to see which branch of the Alt to take
|
| 472 |
+
case syntax.InstAlt, syntax.InstAltMatch:
|
| 473 |
+
pc = int(onePassNext(inst, r))
|
| 474 |
+
continue
|
| 475 |
+
case syntax.InstFail:
|
| 476 |
+
goto Return
|
| 477 |
+
case syntax.InstNop:
|
| 478 |
+
continue
|
| 479 |
+
case syntax.InstEmptyWidth:
|
| 480 |
+
if !flag.match(syntax.EmptyOp(inst.Arg)) {
|
| 481 |
+
goto Return
|
| 482 |
+
}
|
| 483 |
+
continue
|
| 484 |
+
case syntax.InstCapture:
|
| 485 |
+
if int(inst.Arg) < len(m.matchcap) {
|
| 486 |
+
m.matchcap[inst.Arg] = pos
|
| 487 |
+
}
|
| 488 |
+
continue
|
| 489 |
+
}
|
| 490 |
+
if width == 0 {
|
| 491 |
+
break
|
| 492 |
+
}
|
| 493 |
+
flag = newLazyFlag(r, r1)
|
| 494 |
+
pos += width
|
| 495 |
+
r, width = r1, width1
|
| 496 |
+
if r != endOfText {
|
| 497 |
+
r1, width1 = i.step(pos + width)
|
| 498 |
+
}
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
Return:
|
| 502 |
+
if !matched {
|
| 503 |
+
freeOnePassMachine(m)
|
| 504 |
+
return nil
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
dstCap = append(dstCap, m.matchcap...)
|
| 508 |
+
freeOnePassMachine(m)
|
| 509 |
+
return dstCap
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
// doMatch reports whether either r, b or s match the regexp.
|
| 513 |
+
func (re *Regexp) doMatch(r io.RuneReader, b []byte, s string) bool {
|
| 514 |
+
return re.doExecute(r, b, s, 0, 0, nil) != nil
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
// doExecute finds the leftmost match in the input, appends the position
|
| 518 |
+
// of its subexpressions to dstCap and returns dstCap.
|
| 519 |
+
//
|
| 520 |
+
// nil is returned if no matches are found and non-nil if matches are found.
|
| 521 |
+
func (re *Regexp) doExecute(r io.RuneReader, b []byte, s string, pos int, ncap int, dstCap []int) []int {
|
| 522 |
+
if dstCap == nil {
|
| 523 |
+
// Make sure 'return dstCap' is non-nil.
|
| 524 |
+
dstCap = arrayNoInts[:0:0]
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
if r == nil && len(b)+len(s) < re.minInputLen {
|
| 528 |
+
return nil
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
if re.onepass != nil {
|
| 532 |
+
return re.doOnePass(r, b, s, pos, ncap, dstCap)
|
| 533 |
+
}
|
| 534 |
+
if r == nil && len(b)+len(s) < re.maxBitStateLen {
|
| 535 |
+
return re.backtrack(b, s, pos, ncap, dstCap)
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
m := re.get()
|
| 539 |
+
i, _ := m.inputs.init(r, b, s)
|
| 540 |
+
|
| 541 |
+
m.init(ncap)
|
| 542 |
+
if !m.match(i, pos) {
|
| 543 |
+
re.put(m)
|
| 544 |
+
return nil
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
dstCap = append(dstCap, m.matchcap...)
|
| 548 |
+
re.put(m)
|
| 549 |
+
return dstCap
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
// arrayNoInts is returned by doExecute match if nil dstCap is passed
|
| 553 |
+
// to it with ncap=0.
|
| 554 |
+
var arrayNoInts [0]int
|
go/src/regexp/exec2_test.go
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 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 !race
|
| 6 |
+
|
| 7 |
+
package regexp
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"testing"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// This test is excluded when running under the race detector because
|
| 14 |
+
// it is a very expensive test and takes too long.
|
| 15 |
+
func TestRE2Exhaustive(t *testing.T) {
|
| 16 |
+
if testing.Short() {
|
| 17 |
+
t.Skip("skipping TestRE2Exhaustive during short test")
|
| 18 |
+
}
|
| 19 |
+
testRE2(t, "testdata/re2-exhaustive.txt.bz2")
|
| 20 |
+
}
|
go/src/regexp/exec_test.go
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
package regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"bufio"
|
| 9 |
+
"compress/bzip2"
|
| 10 |
+
"fmt"
|
| 11 |
+
"internal/testenv"
|
| 12 |
+
"io"
|
| 13 |
+
"os"
|
| 14 |
+
"path/filepath"
|
| 15 |
+
"regexp/syntax"
|
| 16 |
+
"slices"
|
| 17 |
+
"strconv"
|
| 18 |
+
"strings"
|
| 19 |
+
"testing"
|
| 20 |
+
"unicode/utf8"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
// TestRE2 tests this package's regexp API against test cases
|
| 24 |
+
// considered during RE2's exhaustive tests, which run all possible
|
| 25 |
+
// regexps over a given set of atoms and operators, up to a given
|
| 26 |
+
// complexity, over all possible strings over a given alphabet,
|
| 27 |
+
// up to a given size. Rather than try to link with RE2, we read a
|
| 28 |
+
// log file containing the test cases and the expected matches.
|
| 29 |
+
// The log file, re2-exhaustive.txt, is generated by running 'make log'
|
| 30 |
+
// in the open source RE2 distribution https://github.com/google/re2/.
|
| 31 |
+
//
|
| 32 |
+
// The test file format is a sequence of stanzas like:
|
| 33 |
+
//
|
| 34 |
+
// strings
|
| 35 |
+
// "abc"
|
| 36 |
+
// "123x"
|
| 37 |
+
// regexps
|
| 38 |
+
// "[a-z]+"
|
| 39 |
+
// 0-3;0-3
|
| 40 |
+
// -;-
|
| 41 |
+
// "([0-9])([0-9])([0-9])"
|
| 42 |
+
// -;-
|
| 43 |
+
// -;0-3 0-1 1-2 2-3
|
| 44 |
+
//
|
| 45 |
+
// The stanza begins by defining a set of strings, quoted
|
| 46 |
+
// using Go double-quote syntax, one per line. Then the
|
| 47 |
+
// regexps section gives a sequence of regexps to run on
|
| 48 |
+
// the strings. In the block that follows a regexp, each line
|
| 49 |
+
// gives the semicolon-separated match results of running
|
| 50 |
+
// the regexp on the corresponding string.
|
| 51 |
+
// Each match result is either a single -, meaning no match, or a
|
| 52 |
+
// space-separated sequence of pairs giving the match and
|
| 53 |
+
// submatch indices. An unmatched subexpression formats
|
| 54 |
+
// its pair as a single - (not illustrated above). For now
|
| 55 |
+
// each regexp run produces two match results, one for a
|
| 56 |
+
// “full match” that restricts the regexp to matching the entire
|
| 57 |
+
// string or nothing, and one for a “partial match” that gives
|
| 58 |
+
// the leftmost first match found in the string.
|
| 59 |
+
//
|
| 60 |
+
// Lines beginning with # are comments. Lines beginning with
|
| 61 |
+
// a capital letter are test names printed during RE2's test suite
|
| 62 |
+
// and are echoed into t but otherwise ignored.
|
| 63 |
+
//
|
| 64 |
+
// At time of writing, re2-exhaustive.txt is 59 MB but compresses to 385 kB,
|
| 65 |
+
// so we store re2-exhaustive.txt.bz2 in the repository and decompress it on the fly.
|
| 66 |
+
func TestRE2Search(t *testing.T) {
|
| 67 |
+
testRE2(t, "testdata/re2-search.txt")
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
func testRE2(t *testing.T, file string) {
|
| 71 |
+
f, err := os.Open(file)
|
| 72 |
+
if err != nil {
|
| 73 |
+
t.Fatal(err)
|
| 74 |
+
}
|
| 75 |
+
defer f.Close()
|
| 76 |
+
var txt io.Reader
|
| 77 |
+
if strings.HasSuffix(file, ".bz2") {
|
| 78 |
+
z := bzip2.NewReader(f)
|
| 79 |
+
txt = z
|
| 80 |
+
file = file[:len(file)-len(".bz2")] // for error messages
|
| 81 |
+
} else {
|
| 82 |
+
txt = f
|
| 83 |
+
}
|
| 84 |
+
lineno := 0
|
| 85 |
+
scanner := bufio.NewScanner(txt)
|
| 86 |
+
var (
|
| 87 |
+
str []string
|
| 88 |
+
input []string
|
| 89 |
+
inStrings bool
|
| 90 |
+
re *Regexp
|
| 91 |
+
refull *Regexp
|
| 92 |
+
nfail int
|
| 93 |
+
ncase int
|
| 94 |
+
)
|
| 95 |
+
for lineno := 1; scanner.Scan(); lineno++ {
|
| 96 |
+
line := scanner.Text()
|
| 97 |
+
switch {
|
| 98 |
+
case line == "":
|
| 99 |
+
t.Fatalf("%s:%d: unexpected blank line", file, lineno)
|
| 100 |
+
case line[0] == '#':
|
| 101 |
+
continue
|
| 102 |
+
case 'A' <= line[0] && line[0] <= 'Z':
|
| 103 |
+
// Test name.
|
| 104 |
+
t.Logf("%s\n", line)
|
| 105 |
+
continue
|
| 106 |
+
case line == "strings":
|
| 107 |
+
str = str[:0]
|
| 108 |
+
inStrings = true
|
| 109 |
+
case line == "regexps":
|
| 110 |
+
inStrings = false
|
| 111 |
+
case line[0] == '"':
|
| 112 |
+
q, err := strconv.Unquote(line)
|
| 113 |
+
if err != nil {
|
| 114 |
+
// Fatal because we'll get out of sync.
|
| 115 |
+
t.Fatalf("%s:%d: unquote %s: %v", file, lineno, line, err)
|
| 116 |
+
}
|
| 117 |
+
if inStrings {
|
| 118 |
+
str = append(str, q)
|
| 119 |
+
continue
|
| 120 |
+
}
|
| 121 |
+
// Is a regexp.
|
| 122 |
+
if len(input) != 0 {
|
| 123 |
+
t.Fatalf("%s:%d: out of sync: have %d strings left before %#q", file, lineno, len(input), q)
|
| 124 |
+
}
|
| 125 |
+
re, err = tryCompile(q)
|
| 126 |
+
if err != nil {
|
| 127 |
+
if err.Error() == "error parsing regexp: invalid escape sequence: `\\C`" {
|
| 128 |
+
// We don't and likely never will support \C; keep going.
|
| 129 |
+
continue
|
| 130 |
+
}
|
| 131 |
+
t.Errorf("%s:%d: compile %#q: %v", file, lineno, q, err)
|
| 132 |
+
if nfail++; nfail >= 100 {
|
| 133 |
+
t.Fatalf("stopping after %d errors", nfail)
|
| 134 |
+
}
|
| 135 |
+
continue
|
| 136 |
+
}
|
| 137 |
+
full := `\A(?:` + q + `)\z`
|
| 138 |
+
refull, err = tryCompile(full)
|
| 139 |
+
if err != nil {
|
| 140 |
+
// Fatal because q worked, so this should always work.
|
| 141 |
+
t.Fatalf("%s:%d: compile full %#q: %v", file, lineno, full, err)
|
| 142 |
+
}
|
| 143 |
+
input = str
|
| 144 |
+
case line[0] == '-' || '0' <= line[0] && line[0] <= '9':
|
| 145 |
+
// A sequence of match results.
|
| 146 |
+
ncase++
|
| 147 |
+
if re == nil {
|
| 148 |
+
// Failed to compile: skip results.
|
| 149 |
+
continue
|
| 150 |
+
}
|
| 151 |
+
if len(input) == 0 {
|
| 152 |
+
t.Fatalf("%s:%d: out of sync: no input remaining", file, lineno)
|
| 153 |
+
}
|
| 154 |
+
var text string
|
| 155 |
+
text, input = input[0], input[1:]
|
| 156 |
+
if !isSingleBytes(text) && strings.Contains(re.String(), `\B`) {
|
| 157 |
+
// RE2's \B considers every byte position,
|
| 158 |
+
// so it sees 'not word boundary' in the
|
| 159 |
+
// middle of UTF-8 sequences. This package
|
| 160 |
+
// only considers the positions between runes,
|
| 161 |
+
// so it disagrees. Skip those cases.
|
| 162 |
+
continue
|
| 163 |
+
}
|
| 164 |
+
res := strings.Split(line, ";")
|
| 165 |
+
if len(res) != len(run) {
|
| 166 |
+
t.Fatalf("%s:%d: have %d test results, want %d", file, lineno, len(res), len(run))
|
| 167 |
+
}
|
| 168 |
+
for i := range res {
|
| 169 |
+
have, suffix := run[i](re, refull, text)
|
| 170 |
+
want := parseResult(t, file, lineno, res[i])
|
| 171 |
+
if !slices.Equal(have, want) {
|
| 172 |
+
t.Errorf("%s:%d: %#q%s.FindSubmatchIndex(%#q) = %v, want %v", file, lineno, re, suffix, text, have, want)
|
| 173 |
+
if nfail++; nfail >= 100 {
|
| 174 |
+
t.Fatalf("stopping after %d errors", nfail)
|
| 175 |
+
}
|
| 176 |
+
continue
|
| 177 |
+
}
|
| 178 |
+
b, suffix := match[i](re, refull, text)
|
| 179 |
+
if b != (want != nil) {
|
| 180 |
+
t.Errorf("%s:%d: %#q%s.MatchString(%#q) = %v, want %v", file, lineno, re, suffix, text, b, !b)
|
| 181 |
+
if nfail++; nfail >= 100 {
|
| 182 |
+
t.Fatalf("stopping after %d errors", nfail)
|
| 183 |
+
}
|
| 184 |
+
continue
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
default:
|
| 189 |
+
t.Fatalf("%s:%d: out of sync: %s\n", file, lineno, line)
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
if err := scanner.Err(); err != nil {
|
| 193 |
+
t.Fatalf("%s:%d: %v", file, lineno, err)
|
| 194 |
+
}
|
| 195 |
+
if len(input) != 0 {
|
| 196 |
+
t.Fatalf("%s:%d: out of sync: have %d strings left at EOF", file, lineno, len(input))
|
| 197 |
+
}
|
| 198 |
+
t.Logf("%d cases tested", ncase)
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
var run = []func(*Regexp, *Regexp, string) ([]int, string){
|
| 202 |
+
runFull,
|
| 203 |
+
runPartial,
|
| 204 |
+
runFullLongest,
|
| 205 |
+
runPartialLongest,
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
func runFull(re, refull *Regexp, text string) ([]int, string) {
|
| 209 |
+
refull.longest = false
|
| 210 |
+
return refull.FindStringSubmatchIndex(text), "[full]"
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
func runPartial(re, refull *Regexp, text string) ([]int, string) {
|
| 214 |
+
re.longest = false
|
| 215 |
+
return re.FindStringSubmatchIndex(text), ""
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
func runFullLongest(re, refull *Regexp, text string) ([]int, string) {
|
| 219 |
+
refull.longest = true
|
| 220 |
+
return refull.FindStringSubmatchIndex(text), "[full,longest]"
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
func runPartialLongest(re, refull *Regexp, text string) ([]int, string) {
|
| 224 |
+
re.longest = true
|
| 225 |
+
return re.FindStringSubmatchIndex(text), "[longest]"
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
var match = []func(*Regexp, *Regexp, string) (bool, string){
|
| 229 |
+
matchFull,
|
| 230 |
+
matchPartial,
|
| 231 |
+
matchFullLongest,
|
| 232 |
+
matchPartialLongest,
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
func matchFull(re, refull *Regexp, text string) (bool, string) {
|
| 236 |
+
refull.longest = false
|
| 237 |
+
return refull.MatchString(text), "[full]"
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
func matchPartial(re, refull *Regexp, text string) (bool, string) {
|
| 241 |
+
re.longest = false
|
| 242 |
+
return re.MatchString(text), ""
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
func matchFullLongest(re, refull *Regexp, text string) (bool, string) {
|
| 246 |
+
refull.longest = true
|
| 247 |
+
return refull.MatchString(text), "[full,longest]"
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
func matchPartialLongest(re, refull *Regexp, text string) (bool, string) {
|
| 251 |
+
re.longest = true
|
| 252 |
+
return re.MatchString(text), "[longest]"
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
func isSingleBytes(s string) bool {
|
| 256 |
+
for _, c := range s {
|
| 257 |
+
if c >= utf8.RuneSelf {
|
| 258 |
+
return false
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
return true
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
func tryCompile(s string) (re *Regexp, err error) {
|
| 265 |
+
// Protect against panic during Compile.
|
| 266 |
+
defer func() {
|
| 267 |
+
if r := recover(); r != nil {
|
| 268 |
+
err = fmt.Errorf("panic: %v", r)
|
| 269 |
+
}
|
| 270 |
+
}()
|
| 271 |
+
return Compile(s)
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
func parseResult(t *testing.T, file string, lineno int, res string) []int {
|
| 275 |
+
// A single - indicates no match.
|
| 276 |
+
if res == "-" {
|
| 277 |
+
return nil
|
| 278 |
+
}
|
| 279 |
+
// Otherwise, a space-separated list of pairs.
|
| 280 |
+
n := 1
|
| 281 |
+
for j := 0; j < len(res); j++ {
|
| 282 |
+
if res[j] == ' ' {
|
| 283 |
+
n++
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
out := make([]int, 2*n)
|
| 287 |
+
i := 0
|
| 288 |
+
n = 0
|
| 289 |
+
for j := 0; j <= len(res); j++ {
|
| 290 |
+
if j == len(res) || res[j] == ' ' {
|
| 291 |
+
// Process a single pair. - means no submatch.
|
| 292 |
+
pair := res[i:j]
|
| 293 |
+
if pair == "-" {
|
| 294 |
+
out[n] = -1
|
| 295 |
+
out[n+1] = -1
|
| 296 |
+
} else {
|
| 297 |
+
loStr, hiStr, _ := strings.Cut(pair, "-")
|
| 298 |
+
lo, err1 := strconv.Atoi(loStr)
|
| 299 |
+
hi, err2 := strconv.Atoi(hiStr)
|
| 300 |
+
if err1 != nil || err2 != nil || lo > hi {
|
| 301 |
+
t.Fatalf("%s:%d: invalid pair %s", file, lineno, pair)
|
| 302 |
+
}
|
| 303 |
+
out[n] = lo
|
| 304 |
+
out[n+1] = hi
|
| 305 |
+
}
|
| 306 |
+
n += 2
|
| 307 |
+
i = j + 1
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
return out
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// TestFowler runs this package's regexp API against the
|
| 314 |
+
// POSIX regular expression tests collected by Glenn Fowler
|
| 315 |
+
// at http://www2.research.att.com/~astopen/testregex/testregex.html.
|
| 316 |
+
func TestFowler(t *testing.T) {
|
| 317 |
+
files, err := filepath.Glob("testdata/*.dat")
|
| 318 |
+
if err != nil {
|
| 319 |
+
t.Fatal(err)
|
| 320 |
+
}
|
| 321 |
+
for _, file := range files {
|
| 322 |
+
t.Log(file)
|
| 323 |
+
testFowler(t, file)
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
var notab = MustCompilePOSIX(`[^\t]+`)
|
| 328 |
+
|
| 329 |
+
func testFowler(t *testing.T, file string) {
|
| 330 |
+
f, err := os.Open(file)
|
| 331 |
+
if err != nil {
|
| 332 |
+
t.Error(err)
|
| 333 |
+
return
|
| 334 |
+
}
|
| 335 |
+
defer f.Close()
|
| 336 |
+
b := bufio.NewReader(f)
|
| 337 |
+
lineno := 0
|
| 338 |
+
lastRegexp := ""
|
| 339 |
+
Reading:
|
| 340 |
+
for {
|
| 341 |
+
lineno++
|
| 342 |
+
line, err := b.ReadString('\n')
|
| 343 |
+
if err != nil {
|
| 344 |
+
if err != io.EOF {
|
| 345 |
+
t.Errorf("%s:%d: %v", file, lineno, err)
|
| 346 |
+
}
|
| 347 |
+
break Reading
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
// http://www2.research.att.com/~astopen/man/man1/testregex.html
|
| 351 |
+
//
|
| 352 |
+
// INPUT FORMAT
|
| 353 |
+
// Input lines may be blank, a comment beginning with #, or a test
|
| 354 |
+
// specification. A specification is five fields separated by one
|
| 355 |
+
// or more tabs. NULL denotes the empty string and NIL denotes the
|
| 356 |
+
// 0 pointer.
|
| 357 |
+
if line[0] == '#' || line[0] == '\n' {
|
| 358 |
+
continue Reading
|
| 359 |
+
}
|
| 360 |
+
line = line[:len(line)-1]
|
| 361 |
+
field := notab.FindAllString(line, -1)
|
| 362 |
+
for i, f := range field {
|
| 363 |
+
if f == "NULL" {
|
| 364 |
+
field[i] = ""
|
| 365 |
+
}
|
| 366 |
+
if f == "NIL" {
|
| 367 |
+
t.Logf("%s:%d: skip: %s", file, lineno, line)
|
| 368 |
+
continue Reading
|
| 369 |
+
}
|
| 370 |
+
}
|
| 371 |
+
if len(field) == 0 {
|
| 372 |
+
continue Reading
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
// Field 1: the regex(3) flags to apply, one character per REG_feature
|
| 376 |
+
// flag. The test is skipped if REG_feature is not supported by the
|
| 377 |
+
// implementation. If the first character is not [BEASKLP] then the
|
| 378 |
+
// specification is a global control line. One or more of [BEASKLP] may be
|
| 379 |
+
// specified; the test will be repeated for each mode.
|
| 380 |
+
//
|
| 381 |
+
// B basic BRE (grep, ed, sed)
|
| 382 |
+
// E REG_EXTENDED ERE (egrep)
|
| 383 |
+
// A REG_AUGMENTED ARE (egrep with negation)
|
| 384 |
+
// S REG_SHELL SRE (sh glob)
|
| 385 |
+
// K REG_SHELL|REG_AUGMENTED KRE (ksh glob)
|
| 386 |
+
// L REG_LITERAL LRE (fgrep)
|
| 387 |
+
//
|
| 388 |
+
// a REG_LEFT|REG_RIGHT implicit ^...$
|
| 389 |
+
// b REG_NOTBOL lhs does not match ^
|
| 390 |
+
// c REG_COMMENT ignore space and #...\n
|
| 391 |
+
// d REG_SHELL_DOT explicit leading . match
|
| 392 |
+
// e REG_NOTEOL rhs does not match $
|
| 393 |
+
// f REG_MULTIPLE multiple \n separated patterns
|
| 394 |
+
// g FNM_LEADING_DIR testfnmatch only -- match until /
|
| 395 |
+
// h REG_MULTIREF multiple digit backref
|
| 396 |
+
// i REG_ICASE ignore case
|
| 397 |
+
// j REG_SPAN . matches \n
|
| 398 |
+
// k REG_ESCAPE \ to escape [...] delimiter
|
| 399 |
+
// l REG_LEFT implicit ^...
|
| 400 |
+
// m REG_MINIMAL minimal match
|
| 401 |
+
// n REG_NEWLINE explicit \n match
|
| 402 |
+
// o REG_ENCLOSED (|&) magic inside [@|&](...)
|
| 403 |
+
// p REG_SHELL_PATH explicit / match
|
| 404 |
+
// q REG_DELIMITED delimited pattern
|
| 405 |
+
// r REG_RIGHT implicit ...$
|
| 406 |
+
// s REG_SHELL_ESCAPED \ not special
|
| 407 |
+
// t REG_MUSTDELIM all delimiters must be specified
|
| 408 |
+
// u standard unspecified behavior -- errors not counted
|
| 409 |
+
// v REG_CLASS_ESCAPE \ special inside [...]
|
| 410 |
+
// w REG_NOSUB no subexpression match array
|
| 411 |
+
// x REG_LENIENT let some errors slide
|
| 412 |
+
// y REG_LEFT regexec() implicit ^...
|
| 413 |
+
// z REG_NULL NULL subexpressions ok
|
| 414 |
+
// $ expand C \c escapes in fields 2 and 3
|
| 415 |
+
// / field 2 is a regsubcomp() expression
|
| 416 |
+
// = field 3 is a regdecomp() expression
|
| 417 |
+
//
|
| 418 |
+
// Field 1 control lines:
|
| 419 |
+
//
|
| 420 |
+
// C set LC_COLLATE and LC_CTYPE to locale in field 2
|
| 421 |
+
//
|
| 422 |
+
// ?test ... output field 5 if passed and != EXPECTED, silent otherwise
|
| 423 |
+
// &test ... output field 5 if current and previous passed
|
| 424 |
+
// |test ... output field 5 if current passed and previous failed
|
| 425 |
+
// ; ... output field 2 if previous failed
|
| 426 |
+
// {test ... skip if failed until }
|
| 427 |
+
// } end of skip
|
| 428 |
+
//
|
| 429 |
+
// : comment comment copied as output NOTE
|
| 430 |
+
// :comment:test :comment: ignored
|
| 431 |
+
// N[OTE] comment comment copied as output NOTE
|
| 432 |
+
// T[EST] comment comment
|
| 433 |
+
//
|
| 434 |
+
// number use number for nmatch (20 by default)
|
| 435 |
+
flag := field[0]
|
| 436 |
+
switch flag[0] {
|
| 437 |
+
case '?', '&', '|', ';', '{', '}':
|
| 438 |
+
// Ignore all the control operators.
|
| 439 |
+
// Just run everything.
|
| 440 |
+
flag = flag[1:]
|
| 441 |
+
if flag == "" {
|
| 442 |
+
continue Reading
|
| 443 |
+
}
|
| 444 |
+
case ':':
|
| 445 |
+
var ok bool
|
| 446 |
+
if _, flag, ok = strings.Cut(flag[1:], ":"); !ok {
|
| 447 |
+
t.Logf("skip: %s", line)
|
| 448 |
+
continue Reading
|
| 449 |
+
}
|
| 450 |
+
case 'C', 'N', 'T', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
| 451 |
+
t.Logf("skip: %s", line)
|
| 452 |
+
continue Reading
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
// Can check field count now that we've handled the myriad comment formats.
|
| 456 |
+
if len(field) < 4 {
|
| 457 |
+
t.Errorf("%s:%d: too few fields: %s", file, lineno, line)
|
| 458 |
+
continue Reading
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
// Expand C escapes (a.k.a. Go escapes).
|
| 462 |
+
if strings.Contains(flag, "$") {
|
| 463 |
+
f := `"` + field[1] + `"`
|
| 464 |
+
if field[1], err = strconv.Unquote(f); err != nil {
|
| 465 |
+
t.Errorf("%s:%d: cannot unquote %s", file, lineno, f)
|
| 466 |
+
}
|
| 467 |
+
f = `"` + field[2] + `"`
|
| 468 |
+
if field[2], err = strconv.Unquote(f); err != nil {
|
| 469 |
+
t.Errorf("%s:%d: cannot unquote %s", file, lineno, f)
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
// Field 2: the regular expression pattern; SAME uses the pattern from
|
| 474 |
+
// the previous specification.
|
| 475 |
+
//
|
| 476 |
+
if field[1] == "SAME" {
|
| 477 |
+
field[1] = lastRegexp
|
| 478 |
+
}
|
| 479 |
+
lastRegexp = field[1]
|
| 480 |
+
|
| 481 |
+
// Field 3: the string to match.
|
| 482 |
+
text := field[2]
|
| 483 |
+
|
| 484 |
+
// Field 4: the test outcome...
|
| 485 |
+
ok, shouldCompile, shouldMatch, pos := parseFowlerResult(field[3])
|
| 486 |
+
if !ok {
|
| 487 |
+
t.Errorf("%s:%d: cannot parse result %#q", file, lineno, field[3])
|
| 488 |
+
continue Reading
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
// Field 5: optional comment appended to the report.
|
| 492 |
+
|
| 493 |
+
Testing:
|
| 494 |
+
// Run test once for each specified capital letter mode that we support.
|
| 495 |
+
for _, c := range flag {
|
| 496 |
+
pattern := field[1]
|
| 497 |
+
syn := syntax.POSIX | syntax.ClassNL
|
| 498 |
+
switch c {
|
| 499 |
+
default:
|
| 500 |
+
continue Testing
|
| 501 |
+
case 'E':
|
| 502 |
+
// extended regexp (what we support)
|
| 503 |
+
case 'L':
|
| 504 |
+
// literal
|
| 505 |
+
pattern = QuoteMeta(pattern)
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
for _, c := range flag {
|
| 509 |
+
switch c {
|
| 510 |
+
case 'i':
|
| 511 |
+
syn |= syntax.FoldCase
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
re, err := compile(pattern, syn, true)
|
| 516 |
+
if err != nil {
|
| 517 |
+
if shouldCompile {
|
| 518 |
+
t.Errorf("%s:%d: %#q did not compile", file, lineno, pattern)
|
| 519 |
+
}
|
| 520 |
+
continue Testing
|
| 521 |
+
}
|
| 522 |
+
if !shouldCompile {
|
| 523 |
+
t.Errorf("%s:%d: %#q should not compile", file, lineno, pattern)
|
| 524 |
+
continue Testing
|
| 525 |
+
}
|
| 526 |
+
match := re.MatchString(text)
|
| 527 |
+
if match != shouldMatch {
|
| 528 |
+
t.Errorf("%s:%d: %#q.Match(%#q) = %v, want %v", file, lineno, pattern, text, match, shouldMatch)
|
| 529 |
+
continue Testing
|
| 530 |
+
}
|
| 531 |
+
have := re.FindStringSubmatchIndex(text)
|
| 532 |
+
if (len(have) > 0) != match {
|
| 533 |
+
t.Errorf("%s:%d: %#q.Match(%#q) = %v, but %#q.FindSubmatchIndex(%#q) = %v", file, lineno, pattern, text, match, pattern, text, have)
|
| 534 |
+
continue Testing
|
| 535 |
+
}
|
| 536 |
+
if len(have) > len(pos) {
|
| 537 |
+
have = have[:len(pos)]
|
| 538 |
+
}
|
| 539 |
+
if !slices.Equal(have, pos) {
|
| 540 |
+
t.Errorf("%s:%d: %#q.FindSubmatchIndex(%#q) = %v, want %v", file, lineno, pattern, text, have, pos)
|
| 541 |
+
}
|
| 542 |
+
}
|
| 543 |
+
}
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
func parseFowlerResult(s string) (ok, compiled, matched bool, pos []int) {
|
| 547 |
+
// Field 4: the test outcome. This is either one of the posix error
|
| 548 |
+
// codes (with REG_ omitted) or the match array, a list of (m,n)
|
| 549 |
+
// entries with m and n being first and last+1 positions in the
|
| 550 |
+
// field 3 string, or NULL if REG_NOSUB is in effect and success
|
| 551 |
+
// is expected. BADPAT is acceptable in place of any regcomp(3)
|
| 552 |
+
// error code. The match[] array is initialized to (-2,-2) before
|
| 553 |
+
// each test. All array elements from 0 to nmatch-1 must be specified
|
| 554 |
+
// in the outcome. Unspecified endpoints (offset -1) are denoted by ?.
|
| 555 |
+
// Unset endpoints (offset -2) are denoted by X. {x}(o:n) denotes a
|
| 556 |
+
// matched (?{...}) expression, where x is the text enclosed by {...},
|
| 557 |
+
// o is the expression ordinal counting from 1, and n is the length of
|
| 558 |
+
// the unmatched portion of the subject string. If x starts with a
|
| 559 |
+
// number then that is the return value of re_execf(), otherwise 0 is
|
| 560 |
+
// returned.
|
| 561 |
+
switch {
|
| 562 |
+
case s == "":
|
| 563 |
+
// Match with no position information.
|
| 564 |
+
ok = true
|
| 565 |
+
compiled = true
|
| 566 |
+
matched = true
|
| 567 |
+
return
|
| 568 |
+
case s == "NOMATCH":
|
| 569 |
+
// Match failure.
|
| 570 |
+
ok = true
|
| 571 |
+
compiled = true
|
| 572 |
+
matched = false
|
| 573 |
+
return
|
| 574 |
+
case 'A' <= s[0] && s[0] <= 'Z':
|
| 575 |
+
// All the other error codes are compile errors.
|
| 576 |
+
ok = true
|
| 577 |
+
compiled = false
|
| 578 |
+
return
|
| 579 |
+
}
|
| 580 |
+
compiled = true
|
| 581 |
+
|
| 582 |
+
var x []int
|
| 583 |
+
for s != "" {
|
| 584 |
+
var end byte = ')'
|
| 585 |
+
if len(x)%2 == 0 {
|
| 586 |
+
if s[0] != '(' {
|
| 587 |
+
ok = false
|
| 588 |
+
return
|
| 589 |
+
}
|
| 590 |
+
s = s[1:]
|
| 591 |
+
end = ','
|
| 592 |
+
}
|
| 593 |
+
i := 0
|
| 594 |
+
for i < len(s) && s[i] != end {
|
| 595 |
+
i++
|
| 596 |
+
}
|
| 597 |
+
if i == 0 || i == len(s) {
|
| 598 |
+
ok = false
|
| 599 |
+
return
|
| 600 |
+
}
|
| 601 |
+
var v = -1
|
| 602 |
+
var err error
|
| 603 |
+
if s[:i] != "?" {
|
| 604 |
+
v, err = strconv.Atoi(s[:i])
|
| 605 |
+
if err != nil {
|
| 606 |
+
ok = false
|
| 607 |
+
return
|
| 608 |
+
}
|
| 609 |
+
}
|
| 610 |
+
x = append(x, v)
|
| 611 |
+
s = s[i+1:]
|
| 612 |
+
}
|
| 613 |
+
if len(x)%2 != 0 {
|
| 614 |
+
ok = false
|
| 615 |
+
return
|
| 616 |
+
}
|
| 617 |
+
ok = true
|
| 618 |
+
matched = true
|
| 619 |
+
pos = x
|
| 620 |
+
return
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
var text []byte
|
| 624 |
+
|
| 625 |
+
func makeText(n int) []byte {
|
| 626 |
+
if len(text) >= n {
|
| 627 |
+
return text[:n]
|
| 628 |
+
}
|
| 629 |
+
text = make([]byte, n)
|
| 630 |
+
x := ^uint32(0)
|
| 631 |
+
for i := range text {
|
| 632 |
+
x += x
|
| 633 |
+
x ^= 1
|
| 634 |
+
if int32(x) < 0 {
|
| 635 |
+
x ^= 0x88888eef
|
| 636 |
+
}
|
| 637 |
+
if x%31 == 0 {
|
| 638 |
+
text[i] = '\n'
|
| 639 |
+
} else {
|
| 640 |
+
text[i] = byte(x%(0x7E+1-0x20) + 0x20)
|
| 641 |
+
}
|
| 642 |
+
}
|
| 643 |
+
return text
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
func BenchmarkMatch(b *testing.B) {
|
| 647 |
+
isRaceBuilder := strings.HasSuffix(testenv.Builder(), "-race")
|
| 648 |
+
|
| 649 |
+
for _, data := range benchData {
|
| 650 |
+
r := MustCompile(data.re)
|
| 651 |
+
for _, size := range benchSizes {
|
| 652 |
+
if (isRaceBuilder || testing.Short()) && size.n > 1<<10 {
|
| 653 |
+
continue
|
| 654 |
+
}
|
| 655 |
+
t := makeText(size.n)
|
| 656 |
+
b.Run(data.name+"/"+size.name, func(b *testing.B) {
|
| 657 |
+
b.SetBytes(int64(size.n))
|
| 658 |
+
for i := 0; i < b.N; i++ {
|
| 659 |
+
if r.Match(t) {
|
| 660 |
+
b.Fatal("match!")
|
| 661 |
+
}
|
| 662 |
+
}
|
| 663 |
+
})
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
func BenchmarkMatch_onepass_regex(b *testing.B) {
|
| 669 |
+
isRaceBuilder := strings.HasSuffix(testenv.Builder(), "-race")
|
| 670 |
+
r := MustCompile(`(?s)\A.*\z`)
|
| 671 |
+
if r.onepass == nil {
|
| 672 |
+
b.Fatalf("want onepass regex, but %q is not onepass", r)
|
| 673 |
+
}
|
| 674 |
+
for _, size := range benchSizes {
|
| 675 |
+
if (isRaceBuilder || testing.Short()) && size.n > 1<<10 {
|
| 676 |
+
continue
|
| 677 |
+
}
|
| 678 |
+
t := makeText(size.n)
|
| 679 |
+
b.Run(size.name, func(b *testing.B) {
|
| 680 |
+
b.SetBytes(int64(size.n))
|
| 681 |
+
b.ReportAllocs()
|
| 682 |
+
for i := 0; i < b.N; i++ {
|
| 683 |
+
if !r.Match(t) {
|
| 684 |
+
b.Fatal("not match!")
|
| 685 |
+
}
|
| 686 |
+
}
|
| 687 |
+
})
|
| 688 |
+
}
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
var benchData = []struct{ name, re string }{
|
| 692 |
+
{"Easy0", "ABCDEFGHIJKLMNOPQRSTUVWXYZ$"},
|
| 693 |
+
{"Easy0i", "(?i)ABCDEFGHIJklmnopqrstuvwxyz$"},
|
| 694 |
+
{"Easy1", "A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$"},
|
| 695 |
+
{"Medium", "[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$"},
|
| 696 |
+
{"Hard", "[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$"},
|
| 697 |
+
{"Hard1", "ABCD|CDEF|EFGH|GHIJ|IJKL|KLMN|MNOP|OPQR|QRST|STUV|UVWX|WXYZ"},
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
var benchSizes = []struct {
|
| 701 |
+
name string
|
| 702 |
+
n int
|
| 703 |
+
}{
|
| 704 |
+
{"16", 16},
|
| 705 |
+
{"32", 32},
|
| 706 |
+
{"1K", 1 << 10},
|
| 707 |
+
{"32K", 32 << 10},
|
| 708 |
+
{"1M", 1 << 20},
|
| 709 |
+
{"32M", 32 << 20},
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
func TestLongest(t *testing.T) {
|
| 713 |
+
re, err := Compile(`a(|b)`)
|
| 714 |
+
if err != nil {
|
| 715 |
+
t.Fatal(err)
|
| 716 |
+
}
|
| 717 |
+
if g, w := re.FindString("ab"), "a"; g != w {
|
| 718 |
+
t.Errorf("first match was %q, want %q", g, w)
|
| 719 |
+
}
|
| 720 |
+
re.Longest()
|
| 721 |
+
if g, w := re.FindString("ab"), "ab"; g != w {
|
| 722 |
+
t.Errorf("longest match was %q, want %q", g, w)
|
| 723 |
+
}
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
// TestProgramTooLongForBacktrack tests that a regex which is too long
|
| 727 |
+
// for the backtracker still executes properly.
|
| 728 |
+
func TestProgramTooLongForBacktrack(t *testing.T) {
|
| 729 |
+
longRegex := MustCompile(`(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|twentyone|twentytwo|twentythree|twentyfour|twentyfive|twentysix|twentyseven|twentyeight|twentynine|thirty|thirtyone|thirtytwo|thirtythree|thirtyfour|thirtyfive|thirtysix|thirtyseven|thirtyeight|thirtynine|forty|fortyone|fortytwo|fortythree|fortyfour|fortyfive|fortysix|fortyseven|fortyeight|fortynine|fifty|fiftyone|fiftytwo|fiftythree|fiftyfour|fiftyfive|fiftysix|fiftyseven|fiftyeight|fiftynine|sixty|sixtyone|sixtytwo|sixtythree|sixtyfour|sixtyfive|sixtysix|sixtyseven|sixtyeight|sixtynine|seventy|seventyone|seventytwo|seventythree|seventyfour|seventyfive|seventysix|seventyseven|seventyeight|seventynine|eighty|eightyone|eightytwo|eightythree|eightyfour|eightyfive|eightysix|eightyseven|eightyeight|eightynine|ninety|ninetyone|ninetytwo|ninetythree|ninetyfour|ninetyfive|ninetysix|ninetyseven|ninetyeight|ninetynine|onehundred)`)
|
| 730 |
+
if !longRegex.MatchString("two") {
|
| 731 |
+
t.Errorf("longRegex.MatchString(\"two\") was false, want true")
|
| 732 |
+
}
|
| 733 |
+
if longRegex.MatchString("xxx") {
|
| 734 |
+
t.Errorf("longRegex.MatchString(\"xxx\") was true, want false")
|
| 735 |
+
}
|
| 736 |
+
}
|
go/src/regexp/find_test.go
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"fmt"
|
| 9 |
+
"strings"
|
| 10 |
+
"testing"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// For each pattern/text pair, what is the expected output of each function?
|
| 14 |
+
// We can derive the textual results from the indexed results, the non-submatch
|
| 15 |
+
// results from the submatched results, the single results from the 'all' results,
|
| 16 |
+
// and the byte results from the string results. Therefore the table includes
|
| 17 |
+
// only the FindAllStringSubmatchIndex result.
|
| 18 |
+
type FindTest struct {
|
| 19 |
+
pat string
|
| 20 |
+
text string
|
| 21 |
+
matches [][]int
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func (t FindTest) String() string {
|
| 25 |
+
return fmt.Sprintf("pat: %#q text: %#q", t.pat, t.text)
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
var findTests = []FindTest{
|
| 29 |
+
{``, ``, build(1, 0, 0)},
|
| 30 |
+
{`^abcdefg`, "abcdefg", build(1, 0, 7)},
|
| 31 |
+
{`a+`, "baaab", build(1, 1, 4)},
|
| 32 |
+
{"abcd..", "abcdef", build(1, 0, 6)},
|
| 33 |
+
{`a`, "a", build(1, 0, 1)},
|
| 34 |
+
{`x`, "y", nil},
|
| 35 |
+
{`b`, "abc", build(1, 1, 2)},
|
| 36 |
+
{`.`, "a", build(1, 0, 1)},
|
| 37 |
+
{`.*`, "abcdef", build(1, 0, 6)},
|
| 38 |
+
{`^`, "abcde", build(1, 0, 0)},
|
| 39 |
+
{`$`, "abcde", build(1, 5, 5)},
|
| 40 |
+
{`^abcd$`, "abcd", build(1, 0, 4)},
|
| 41 |
+
{`^bcd'`, "abcdef", nil},
|
| 42 |
+
{`^abcd$`, "abcde", nil},
|
| 43 |
+
{`a+`, "baaab", build(1, 1, 4)},
|
| 44 |
+
{`a*`, "baaab", build(3, 0, 0, 1, 4, 5, 5)},
|
| 45 |
+
{`[a-z]+`, "abcd", build(1, 0, 4)},
|
| 46 |
+
{`[^a-z]+`, "ab1234cd", build(1, 2, 6)},
|
| 47 |
+
{`[a\-\]z]+`, "az]-bcz", build(2, 0, 4, 6, 7)},
|
| 48 |
+
{`[^\n]+`, "abcd\n", build(1, 0, 4)},
|
| 49 |
+
{`[日本語]+`, "日本語日本語", build(1, 0, 18)},
|
| 50 |
+
{`日本語+`, "日本語", build(1, 0, 9)},
|
| 51 |
+
{`日本語+`, "日本語語語語", build(1, 0, 18)},
|
| 52 |
+
{`()`, "", build(1, 0, 0, 0, 0)},
|
| 53 |
+
{`(a)`, "a", build(1, 0, 1, 0, 1)},
|
| 54 |
+
{`(.)(.)`, "日a", build(1, 0, 4, 0, 3, 3, 4)},
|
| 55 |
+
{`(.*)`, "", build(1, 0, 0, 0, 0)},
|
| 56 |
+
{`(.*)`, "abcd", build(1, 0, 4, 0, 4)},
|
| 57 |
+
{`(..)(..)`, "abcd", build(1, 0, 4, 0, 2, 2, 4)},
|
| 58 |
+
{`(([^xyz]*)(d))`, "abcd", build(1, 0, 4, 0, 4, 0, 3, 3, 4)},
|
| 59 |
+
{`((a|b|c)*(d))`, "abcd", build(1, 0, 4, 0, 4, 2, 3, 3, 4)},
|
| 60 |
+
{`(((a|b|c)*)(d))`, "abcd", build(1, 0, 4, 0, 4, 0, 3, 2, 3, 3, 4)},
|
| 61 |
+
{`\a\f\n\r\t\v`, "\a\f\n\r\t\v", build(1, 0, 6)},
|
| 62 |
+
{`[\a\f\n\r\t\v]+`, "\a\f\n\r\t\v", build(1, 0, 6)},
|
| 63 |
+
|
| 64 |
+
{`a*(|(b))c*`, "aacc", build(1, 0, 4, 2, 2, -1, -1)},
|
| 65 |
+
{`(.*).*`, "ab", build(1, 0, 2, 0, 2)},
|
| 66 |
+
{`[.]`, ".", build(1, 0, 1)},
|
| 67 |
+
{`/$`, "/abc/", build(1, 4, 5)},
|
| 68 |
+
{`/$`, "/abc", nil},
|
| 69 |
+
|
| 70 |
+
// multiple matches
|
| 71 |
+
{`.`, "abc", build(3, 0, 1, 1, 2, 2, 3)},
|
| 72 |
+
{`(.)`, "abc", build(3, 0, 1, 0, 1, 1, 2, 1, 2, 2, 3, 2, 3)},
|
| 73 |
+
{`.(.)`, "abcd", build(2, 0, 2, 1, 2, 2, 4, 3, 4)},
|
| 74 |
+
{`ab*`, "abbaab", build(3, 0, 3, 3, 4, 4, 6)},
|
| 75 |
+
{`a(b*)`, "abbaab", build(3, 0, 3, 1, 3, 3, 4, 4, 4, 4, 6, 5, 6)},
|
| 76 |
+
|
| 77 |
+
// fixed bugs
|
| 78 |
+
{`ab$`, "cab", build(1, 1, 3)},
|
| 79 |
+
{`axxb$`, "axxcb", nil},
|
| 80 |
+
{`data`, "daXY data", build(1, 5, 9)},
|
| 81 |
+
{`da(.)a$`, "daXY data", build(1, 5, 9, 7, 8)},
|
| 82 |
+
{`zx+`, "zzx", build(1, 1, 3)},
|
| 83 |
+
{`ab$`, "abcab", build(1, 3, 5)},
|
| 84 |
+
{`(aa)*$`, "a", build(1, 1, 1, -1, -1)},
|
| 85 |
+
{`(?:.|(?:.a))`, "", nil},
|
| 86 |
+
{`(?:A(?:A|a))`, "Aa", build(1, 0, 2)},
|
| 87 |
+
{`(?:A|(?:A|a))`, "a", build(1, 0, 1)},
|
| 88 |
+
{`(a){0}`, "", build(1, 0, 0, -1, -1)},
|
| 89 |
+
{`(?-s)(?:(?:^).)`, "\n", nil},
|
| 90 |
+
{`(?s)(?:(?:^).)`, "\n", build(1, 0, 1)},
|
| 91 |
+
{`(?:(?:^).)`, "\n", nil},
|
| 92 |
+
{`\b`, "x", build(2, 0, 0, 1, 1)},
|
| 93 |
+
{`\b`, "xx", build(2, 0, 0, 2, 2)},
|
| 94 |
+
{`\b`, "x y", build(4, 0, 0, 1, 1, 2, 2, 3, 3)},
|
| 95 |
+
{`\b`, "xx yy", build(4, 0, 0, 2, 2, 3, 3, 5, 5)},
|
| 96 |
+
{`\B`, "x", nil},
|
| 97 |
+
{`\B`, "xx", build(1, 1, 1)},
|
| 98 |
+
{`\B`, "x y", nil},
|
| 99 |
+
{`\B`, "xx yy", build(2, 1, 1, 4, 4)},
|
| 100 |
+
{`(|a)*`, "aa", build(3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2)},
|
| 101 |
+
{`0A|0[aA]`, "0a", build(1, 0, 2)},
|
| 102 |
+
{`0[aA]|0A`, "0a", build(1, 0, 2)},
|
| 103 |
+
|
| 104 |
+
// RE2 tests
|
| 105 |
+
{`[^\S\s]`, "abcd", nil},
|
| 106 |
+
{`[^\S[:space:]]`, "abcd", nil},
|
| 107 |
+
{`[^\D\d]`, "abcd", nil},
|
| 108 |
+
{`[^\D[:digit:]]`, "abcd", nil},
|
| 109 |
+
{`(?i)\W`, "x", nil},
|
| 110 |
+
{`(?i)\W`, "k", nil},
|
| 111 |
+
{`(?i)\W`, "s", nil},
|
| 112 |
+
|
| 113 |
+
// can backslash-escape any punctuation
|
| 114 |
+
{`\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_\{\|\}\~`,
|
| 115 |
+
`!"#$%&'()*+,-./:;<=>?@[\]^_{|}~`, build(1, 0, 31)},
|
| 116 |
+
{`[\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_\{\|\}\~]+`,
|
| 117 |
+
`!"#$%&'()*+,-./:;<=>?@[\]^_{|}~`, build(1, 0, 31)},
|
| 118 |
+
{"\\`", "`", build(1, 0, 1)},
|
| 119 |
+
{"[\\`]+", "`", build(1, 0, 1)},
|
| 120 |
+
|
| 121 |
+
{"\ufffd", "\xff", build(1, 0, 1)},
|
| 122 |
+
{"\ufffd", "hello\xffworld", build(1, 5, 6)},
|
| 123 |
+
{`.*`, "hello\xffworld", build(1, 0, 11)},
|
| 124 |
+
{`\x{fffd}`, "\xc2\x00", build(1, 0, 1)},
|
| 125 |
+
{"[\ufffd]", "\xff", build(1, 0, 1)},
|
| 126 |
+
{`[\x{fffd}]`, "\xc2\x00", build(1, 0, 1)},
|
| 127 |
+
|
| 128 |
+
// long set of matches (longer than startSize)
|
| 129 |
+
{
|
| 130 |
+
".",
|
| 131 |
+
"qwertyuiopasdfghjklzxcvbnm1234567890",
|
| 132 |
+
build(36, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10,
|
| 133 |
+
10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20,
|
| 134 |
+
20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30,
|
| 135 |
+
30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36),
|
| 136 |
+
},
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// build is a helper to construct a [][]int by extracting n sequences from x.
|
| 140 |
+
// This represents n matches with len(x)/n submatches each.
|
| 141 |
+
func build(n int, x ...int) [][]int {
|
| 142 |
+
ret := make([][]int, n)
|
| 143 |
+
runLength := len(x) / n
|
| 144 |
+
j := 0
|
| 145 |
+
for i := range ret {
|
| 146 |
+
ret[i] = make([]int, runLength)
|
| 147 |
+
copy(ret[i], x[j:])
|
| 148 |
+
j += runLength
|
| 149 |
+
if j > len(x) {
|
| 150 |
+
panic("invalid build entry")
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
return ret
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
// First the simple cases.
|
| 157 |
+
|
| 158 |
+
func TestFind(t *testing.T) {
|
| 159 |
+
for _, test := range findTests {
|
| 160 |
+
re := MustCompile(test.pat)
|
| 161 |
+
if re.String() != test.pat {
|
| 162 |
+
t.Errorf("re.String() = %q, want %q", re.String(), test.pat)
|
| 163 |
+
}
|
| 164 |
+
result := re.Find([]byte(test.text))
|
| 165 |
+
switch {
|
| 166 |
+
case len(test.matches) == 0 && len(result) == 0:
|
| 167 |
+
// ok
|
| 168 |
+
case test.matches == nil && result != nil:
|
| 169 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 170 |
+
case test.matches != nil && result == nil:
|
| 171 |
+
t.Errorf("got no match, want one: %s", test)
|
| 172 |
+
case test.matches != nil && result != nil:
|
| 173 |
+
want := test.text[test.matches[0][0]:test.matches[0][1]]
|
| 174 |
+
if len(result) != cap(result) {
|
| 175 |
+
t.Errorf("got capacity %d, want %d: %s", cap(result), len(result), test)
|
| 176 |
+
}
|
| 177 |
+
if want != string(result) {
|
| 178 |
+
t.Errorf("got %q, want %q: %s", result, want, test)
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
func TestFindString(t *testing.T) {
|
| 185 |
+
for _, test := range findTests {
|
| 186 |
+
result := MustCompile(test.pat).FindString(test.text)
|
| 187 |
+
switch {
|
| 188 |
+
case len(test.matches) == 0 && len(result) == 0:
|
| 189 |
+
// ok
|
| 190 |
+
case test.matches == nil && result != "":
|
| 191 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 192 |
+
case test.matches != nil && result == "":
|
| 193 |
+
// Tricky because an empty result has two meanings: no match or empty match.
|
| 194 |
+
if test.matches[0][0] != test.matches[0][1] {
|
| 195 |
+
t.Errorf("got no match, want one: %s", test)
|
| 196 |
+
}
|
| 197 |
+
case test.matches != nil && result != "":
|
| 198 |
+
want := test.text[test.matches[0][0]:test.matches[0][1]]
|
| 199 |
+
if want != result {
|
| 200 |
+
t.Errorf("got %q, want %q: %s", result, want, test)
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
func testFindIndex(test *FindTest, result []int, t *testing.T) {
|
| 207 |
+
switch {
|
| 208 |
+
case len(test.matches) == 0 && len(result) == 0:
|
| 209 |
+
// ok
|
| 210 |
+
case test.matches == nil && result != nil:
|
| 211 |
+
t.Errorf("got match %v, want none: %s", result, test)
|
| 212 |
+
case test.matches != nil && result == nil:
|
| 213 |
+
t.Errorf("got no match, want one: %s", test)
|
| 214 |
+
case test.matches != nil && result != nil:
|
| 215 |
+
want := test.matches[0]
|
| 216 |
+
if want[0] != result[0] || want[1] != result[1] {
|
| 217 |
+
t.Errorf("got %v, want %v: %s", result, want, test)
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
func TestFindIndex(t *testing.T) {
|
| 223 |
+
for _, test := range findTests {
|
| 224 |
+
testFindIndex(&test, MustCompile(test.pat).FindIndex([]byte(test.text)), t)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func TestFindStringIndex(t *testing.T) {
|
| 229 |
+
for _, test := range findTests {
|
| 230 |
+
testFindIndex(&test, MustCompile(test.pat).FindStringIndex(test.text), t)
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
func TestFindReaderIndex(t *testing.T) {
|
| 235 |
+
for _, test := range findTests {
|
| 236 |
+
testFindIndex(&test, MustCompile(test.pat).FindReaderIndex(strings.NewReader(test.text)), t)
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
// Now come the simple All cases.
|
| 241 |
+
|
| 242 |
+
func TestFindAll(t *testing.T) {
|
| 243 |
+
for _, test := range findTests {
|
| 244 |
+
result := MustCompile(test.pat).FindAll([]byte(test.text), -1)
|
| 245 |
+
switch {
|
| 246 |
+
case test.matches == nil && result == nil:
|
| 247 |
+
// ok
|
| 248 |
+
case test.matches == nil && result != nil:
|
| 249 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 250 |
+
case test.matches != nil && result == nil:
|
| 251 |
+
t.Fatalf("got no match, want one: %s", test)
|
| 252 |
+
case test.matches != nil && result != nil:
|
| 253 |
+
if len(test.matches) != len(result) {
|
| 254 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 255 |
+
continue
|
| 256 |
+
}
|
| 257 |
+
for k, e := range test.matches {
|
| 258 |
+
got := result[k]
|
| 259 |
+
if len(got) != cap(got) {
|
| 260 |
+
t.Errorf("match %d: got capacity %d, want %d: %s", k, cap(got), len(got), test)
|
| 261 |
+
}
|
| 262 |
+
want := test.text[e[0]:e[1]]
|
| 263 |
+
if want != string(got) {
|
| 264 |
+
t.Errorf("match %d: got %q, want %q: %s", k, got, want, test)
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
func TestFindAllString(t *testing.T) {
|
| 272 |
+
for _, test := range findTests {
|
| 273 |
+
result := MustCompile(test.pat).FindAllString(test.text, -1)
|
| 274 |
+
switch {
|
| 275 |
+
case test.matches == nil && result == nil:
|
| 276 |
+
// ok
|
| 277 |
+
case test.matches == nil && result != nil:
|
| 278 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 279 |
+
case test.matches != nil && result == nil:
|
| 280 |
+
t.Errorf("got no match, want one: %s", test)
|
| 281 |
+
case test.matches != nil && result != nil:
|
| 282 |
+
if len(test.matches) != len(result) {
|
| 283 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 284 |
+
continue
|
| 285 |
+
}
|
| 286 |
+
for k, e := range test.matches {
|
| 287 |
+
want := test.text[e[0]:e[1]]
|
| 288 |
+
if want != result[k] {
|
| 289 |
+
t.Errorf("got %q, want %q: %s", result[k], want, test)
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
func testFindAllIndex(test *FindTest, result [][]int, t *testing.T) {
|
| 297 |
+
switch {
|
| 298 |
+
case test.matches == nil && result == nil:
|
| 299 |
+
// ok
|
| 300 |
+
case test.matches == nil && result != nil:
|
| 301 |
+
t.Errorf("got match %v, want none: %s", result, test)
|
| 302 |
+
case test.matches != nil && result == nil:
|
| 303 |
+
t.Errorf("got no match, want one: %s", test)
|
| 304 |
+
case test.matches != nil && result != nil:
|
| 305 |
+
if len(test.matches) != len(result) {
|
| 306 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 307 |
+
return
|
| 308 |
+
}
|
| 309 |
+
for k, e := range test.matches {
|
| 310 |
+
if e[0] != result[k][0] || e[1] != result[k][1] {
|
| 311 |
+
t.Errorf("match %d: got %v, want %v: %s", k, result[k], e, test)
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
func TestFindAllIndex(t *testing.T) {
|
| 318 |
+
for _, test := range findTests {
|
| 319 |
+
testFindAllIndex(&test, MustCompile(test.pat).FindAllIndex([]byte(test.text), -1), t)
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
func TestFindAllStringIndex(t *testing.T) {
|
| 324 |
+
for _, test := range findTests {
|
| 325 |
+
testFindAllIndex(&test, MustCompile(test.pat).FindAllStringIndex(test.text, -1), t)
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
// Now come the Submatch cases.
|
| 330 |
+
|
| 331 |
+
func testSubmatchBytes(test *FindTest, n int, submatches []int, result [][]byte, t *testing.T) {
|
| 332 |
+
if len(submatches) != len(result)*2 {
|
| 333 |
+
t.Errorf("match %d: got %d submatches, want %d: %s", n, len(result), len(submatches)/2, test)
|
| 334 |
+
return
|
| 335 |
+
}
|
| 336 |
+
for k := 0; k < len(submatches); k += 2 {
|
| 337 |
+
if submatches[k] == -1 {
|
| 338 |
+
if result[k/2] != nil {
|
| 339 |
+
t.Errorf("match %d: got %q, want nil: %s", n, result, test)
|
| 340 |
+
}
|
| 341 |
+
continue
|
| 342 |
+
}
|
| 343 |
+
got := result[k/2]
|
| 344 |
+
if len(got) != cap(got) {
|
| 345 |
+
t.Errorf("match %d: got capacity %d, want %d: %s", n, cap(got), len(got), test)
|
| 346 |
+
return
|
| 347 |
+
}
|
| 348 |
+
want := test.text[submatches[k]:submatches[k+1]]
|
| 349 |
+
if want != string(got) {
|
| 350 |
+
t.Errorf("match %d: got %q, want %q: %s", n, got, want, test)
|
| 351 |
+
return
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
func TestFindSubmatch(t *testing.T) {
|
| 357 |
+
for _, test := range findTests {
|
| 358 |
+
result := MustCompile(test.pat).FindSubmatch([]byte(test.text))
|
| 359 |
+
switch {
|
| 360 |
+
case test.matches == nil && result == nil:
|
| 361 |
+
// ok
|
| 362 |
+
case test.matches == nil && result != nil:
|
| 363 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 364 |
+
case test.matches != nil && result == nil:
|
| 365 |
+
t.Errorf("got no match, want one: %s", test)
|
| 366 |
+
case test.matches != nil && result != nil:
|
| 367 |
+
testSubmatchBytes(&test, 0, test.matches[0], result, t)
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
func testSubmatchString(test *FindTest, n int, submatches []int, result []string, t *testing.T) {
|
| 373 |
+
if len(submatches) != len(result)*2 {
|
| 374 |
+
t.Errorf("match %d: got %d submatches, want %d: %s", n, len(result), len(submatches)/2, test)
|
| 375 |
+
return
|
| 376 |
+
}
|
| 377 |
+
for k := 0; k < len(submatches); k += 2 {
|
| 378 |
+
if submatches[k] == -1 {
|
| 379 |
+
if result[k/2] != "" {
|
| 380 |
+
t.Errorf("match %d: got %q, want empty string: %s", n, result, test)
|
| 381 |
+
}
|
| 382 |
+
continue
|
| 383 |
+
}
|
| 384 |
+
want := test.text[submatches[k]:submatches[k+1]]
|
| 385 |
+
if want != result[k/2] {
|
| 386 |
+
t.Errorf("match %d: got %q, want %q: %s", n, result[k/2], want, test)
|
| 387 |
+
return
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
func TestFindStringSubmatch(t *testing.T) {
|
| 393 |
+
for _, test := range findTests {
|
| 394 |
+
result := MustCompile(test.pat).FindStringSubmatch(test.text)
|
| 395 |
+
switch {
|
| 396 |
+
case test.matches == nil && result == nil:
|
| 397 |
+
// ok
|
| 398 |
+
case test.matches == nil && result != nil:
|
| 399 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 400 |
+
case test.matches != nil && result == nil:
|
| 401 |
+
t.Errorf("got no match, want one: %s", test)
|
| 402 |
+
case test.matches != nil && result != nil:
|
| 403 |
+
testSubmatchString(&test, 0, test.matches[0], result, t)
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
func testSubmatchIndices(test *FindTest, n int, want, result []int, t *testing.T) {
|
| 409 |
+
if len(want) != len(result) {
|
| 410 |
+
t.Errorf("match %d: got %d matches, want %d: %s", n, len(result)/2, len(want)/2, test)
|
| 411 |
+
return
|
| 412 |
+
}
|
| 413 |
+
for k, e := range want {
|
| 414 |
+
if e != result[k] {
|
| 415 |
+
t.Errorf("match %d: submatch error: got %v, want %v: %s", n, result, want, test)
|
| 416 |
+
}
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
func testFindSubmatchIndex(test *FindTest, result []int, t *testing.T) {
|
| 421 |
+
switch {
|
| 422 |
+
case test.matches == nil && result == nil:
|
| 423 |
+
// ok
|
| 424 |
+
case test.matches == nil && result != nil:
|
| 425 |
+
t.Errorf("got match %v, want none: %s", result, test)
|
| 426 |
+
case test.matches != nil && result == nil:
|
| 427 |
+
t.Errorf("got no match, want one: %s", test)
|
| 428 |
+
case test.matches != nil && result != nil:
|
| 429 |
+
testSubmatchIndices(test, 0, test.matches[0], result, t)
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
func TestFindSubmatchIndex(t *testing.T) {
|
| 434 |
+
for _, test := range findTests {
|
| 435 |
+
testFindSubmatchIndex(&test, MustCompile(test.pat).FindSubmatchIndex([]byte(test.text)), t)
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
func TestFindStringSubmatchIndex(t *testing.T) {
|
| 440 |
+
for _, test := range findTests {
|
| 441 |
+
testFindSubmatchIndex(&test, MustCompile(test.pat).FindStringSubmatchIndex(test.text), t)
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
func TestFindReaderSubmatchIndex(t *testing.T) {
|
| 446 |
+
for _, test := range findTests {
|
| 447 |
+
testFindSubmatchIndex(&test, MustCompile(test.pat).FindReaderSubmatchIndex(strings.NewReader(test.text)), t)
|
| 448 |
+
}
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
// Now come the monster AllSubmatch cases.
|
| 452 |
+
|
| 453 |
+
func TestFindAllSubmatch(t *testing.T) {
|
| 454 |
+
for _, test := range findTests {
|
| 455 |
+
result := MustCompile(test.pat).FindAllSubmatch([]byte(test.text), -1)
|
| 456 |
+
switch {
|
| 457 |
+
case test.matches == nil && result == nil:
|
| 458 |
+
// ok
|
| 459 |
+
case test.matches == nil && result != nil:
|
| 460 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 461 |
+
case test.matches != nil && result == nil:
|
| 462 |
+
t.Errorf("got no match, want one: %s", test)
|
| 463 |
+
case len(test.matches) != len(result):
|
| 464 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 465 |
+
case test.matches != nil && result != nil:
|
| 466 |
+
for k, match := range test.matches {
|
| 467 |
+
testSubmatchBytes(&test, k, match, result[k], t)
|
| 468 |
+
}
|
| 469 |
+
}
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
func TestFindAllStringSubmatch(t *testing.T) {
|
| 474 |
+
for _, test := range findTests {
|
| 475 |
+
result := MustCompile(test.pat).FindAllStringSubmatch(test.text, -1)
|
| 476 |
+
switch {
|
| 477 |
+
case test.matches == nil && result == nil:
|
| 478 |
+
// ok
|
| 479 |
+
case test.matches == nil && result != nil:
|
| 480 |
+
t.Errorf("got match %q, want none: %s", result, test)
|
| 481 |
+
case test.matches != nil && result == nil:
|
| 482 |
+
t.Errorf("got no match, want one: %s", test)
|
| 483 |
+
case len(test.matches) != len(result):
|
| 484 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 485 |
+
case test.matches != nil && result != nil:
|
| 486 |
+
for k, match := range test.matches {
|
| 487 |
+
testSubmatchString(&test, k, match, result[k], t)
|
| 488 |
+
}
|
| 489 |
+
}
|
| 490 |
+
}
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
func testFindAllSubmatchIndex(test *FindTest, result [][]int, t *testing.T) {
|
| 494 |
+
switch {
|
| 495 |
+
case test.matches == nil && result == nil:
|
| 496 |
+
// ok
|
| 497 |
+
case test.matches == nil && result != nil:
|
| 498 |
+
t.Errorf("got match %v, want none: %s", result, test)
|
| 499 |
+
case test.matches != nil && result == nil:
|
| 500 |
+
t.Errorf("got no match, want one: %s", test)
|
| 501 |
+
case len(test.matches) != len(result):
|
| 502 |
+
t.Errorf("got %d matches, want %d: %s", len(result), len(test.matches), test)
|
| 503 |
+
case test.matches != nil && result != nil:
|
| 504 |
+
for k, match := range test.matches {
|
| 505 |
+
testSubmatchIndices(test, k, match, result[k], t)
|
| 506 |
+
}
|
| 507 |
+
}
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
func TestFindAllSubmatchIndex(t *testing.T) {
|
| 511 |
+
for _, test := range findTests {
|
| 512 |
+
testFindAllSubmatchIndex(&test, MustCompile(test.pat).FindAllSubmatchIndex([]byte(test.text), -1), t)
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
func TestFindAllStringSubmatchIndex(t *testing.T) {
|
| 517 |
+
for _, test := range findTests {
|
| 518 |
+
testFindAllSubmatchIndex(&test, MustCompile(test.pat).FindAllStringSubmatchIndex(test.text, -1), t)
|
| 519 |
+
}
|
| 520 |
+
}
|
go/src/regexp/onepass.go
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"regexp/syntax"
|
| 9 |
+
"slices"
|
| 10 |
+
"strings"
|
| 11 |
+
"unicode"
|
| 12 |
+
"unicode/utf8"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
// "One-pass" regexp execution.
|
| 16 |
+
// Some regexps can be analyzed to determine that they never need
|
| 17 |
+
// backtracking: they are guaranteed to run in one pass over the string
|
| 18 |
+
// without bothering to save all the usual NFA state.
|
| 19 |
+
// Detect those and execute them more quickly.
|
| 20 |
+
|
| 21 |
+
// A onePassProg is a compiled one-pass regular expression program.
|
| 22 |
+
// It is the same as syntax.Prog except for the use of onePassInst.
|
| 23 |
+
type onePassProg struct {
|
| 24 |
+
Inst []onePassInst
|
| 25 |
+
Start int // index of start instruction
|
| 26 |
+
NumCap int // number of InstCapture insts in re
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// A onePassInst is a single instruction in a one-pass regular expression program.
|
| 30 |
+
// It is the same as syntax.Inst except for the new 'Next' field.
|
| 31 |
+
type onePassInst struct {
|
| 32 |
+
syntax.Inst
|
| 33 |
+
Next []uint32
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// onePassPrefix returns a literal string that all matches for the
|
| 37 |
+
// regexp must start with. Complete is true if the prefix
|
| 38 |
+
// is the entire match. Pc is the index of the last rune instruction
|
| 39 |
+
// in the string. The onePassPrefix skips over the mandatory
|
| 40 |
+
// EmptyBeginText.
|
| 41 |
+
func onePassPrefix(p *syntax.Prog) (prefix string, complete bool, pc uint32) {
|
| 42 |
+
i := &p.Inst[p.Start]
|
| 43 |
+
if i.Op != syntax.InstEmptyWidth || (syntax.EmptyOp(i.Arg))&syntax.EmptyBeginText == 0 {
|
| 44 |
+
return "", i.Op == syntax.InstMatch, uint32(p.Start)
|
| 45 |
+
}
|
| 46 |
+
pc = i.Out
|
| 47 |
+
i = &p.Inst[pc]
|
| 48 |
+
for i.Op == syntax.InstNop {
|
| 49 |
+
pc = i.Out
|
| 50 |
+
i = &p.Inst[pc]
|
| 51 |
+
}
|
| 52 |
+
// Avoid allocation of buffer if prefix is empty.
|
| 53 |
+
if iop(i) != syntax.InstRune || len(i.Rune) != 1 {
|
| 54 |
+
return "", i.Op == syntax.InstMatch, uint32(p.Start)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// Have prefix; gather characters.
|
| 58 |
+
var buf strings.Builder
|
| 59 |
+
for iop(i) == syntax.InstRune && len(i.Rune) == 1 && syntax.Flags(i.Arg)&syntax.FoldCase == 0 && i.Rune[0] != utf8.RuneError {
|
| 60 |
+
buf.WriteRune(i.Rune[0])
|
| 61 |
+
pc, i = i.Out, &p.Inst[i.Out]
|
| 62 |
+
}
|
| 63 |
+
if i.Op == syntax.InstEmptyWidth &&
|
| 64 |
+
syntax.EmptyOp(i.Arg)&syntax.EmptyEndText != 0 &&
|
| 65 |
+
p.Inst[i.Out].Op == syntax.InstMatch {
|
| 66 |
+
complete = true
|
| 67 |
+
}
|
| 68 |
+
return buf.String(), complete, pc
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// onePassNext selects the next actionable state of the prog, based on the input character.
|
| 72 |
+
// It should only be called when i.Op == InstAlt or InstAltMatch, and from the one-pass machine.
|
| 73 |
+
// One of the alternates may ultimately lead without input to end of line. If the instruction
|
| 74 |
+
// is InstAltMatch the path to the InstMatch is in i.Out, the normal node in i.Next.
|
| 75 |
+
func onePassNext(i *onePassInst, r rune) uint32 {
|
| 76 |
+
next := i.MatchRunePos(r)
|
| 77 |
+
if next >= 0 {
|
| 78 |
+
return i.Next[next]
|
| 79 |
+
}
|
| 80 |
+
if i.Op == syntax.InstAltMatch {
|
| 81 |
+
return i.Out
|
| 82 |
+
}
|
| 83 |
+
return 0
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func iop(i *syntax.Inst) syntax.InstOp {
|
| 87 |
+
op := i.Op
|
| 88 |
+
switch op {
|
| 89 |
+
case syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
|
| 90 |
+
op = syntax.InstRune
|
| 91 |
+
}
|
| 92 |
+
return op
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Sparse Array implementation is used as a queueOnePass.
|
| 96 |
+
type queueOnePass struct {
|
| 97 |
+
sparse []uint32
|
| 98 |
+
dense []uint32
|
| 99 |
+
size, nextIndex uint32
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
func (q *queueOnePass) empty() bool {
|
| 103 |
+
return q.nextIndex >= q.size
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
func (q *queueOnePass) next() (n uint32) {
|
| 107 |
+
n = q.dense[q.nextIndex]
|
| 108 |
+
q.nextIndex++
|
| 109 |
+
return
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
func (q *queueOnePass) clear() {
|
| 113 |
+
q.size = 0
|
| 114 |
+
q.nextIndex = 0
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
func (q *queueOnePass) contains(u uint32) bool {
|
| 118 |
+
if u >= uint32(len(q.sparse)) {
|
| 119 |
+
return false
|
| 120 |
+
}
|
| 121 |
+
return q.sparse[u] < q.size && q.dense[q.sparse[u]] == u
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
func (q *queueOnePass) insert(u uint32) {
|
| 125 |
+
if !q.contains(u) {
|
| 126 |
+
q.insertNew(u)
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
func (q *queueOnePass) insertNew(u uint32) {
|
| 131 |
+
if u >= uint32(len(q.sparse)) {
|
| 132 |
+
return
|
| 133 |
+
}
|
| 134 |
+
q.sparse[u] = q.size
|
| 135 |
+
q.dense[q.size] = u
|
| 136 |
+
q.size++
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
func newQueue(size int) (q *queueOnePass) {
|
| 140 |
+
return &queueOnePass{
|
| 141 |
+
sparse: make([]uint32, size),
|
| 142 |
+
dense: make([]uint32, size),
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// mergeRuneSets merges two non-intersecting runesets, and returns the merged result,
|
| 147 |
+
// and a NextIp array. The idea is that if a rune matches the OnePassRunes at index
|
| 148 |
+
// i, NextIp[i/2] is the target. If the input sets intersect, an empty runeset and a
|
| 149 |
+
// NextIp array with the single element mergeFailed is returned.
|
| 150 |
+
// The code assumes that both inputs contain ordered and non-intersecting rune pairs.
|
| 151 |
+
const mergeFailed = uint32(0xffffffff)
|
| 152 |
+
|
| 153 |
+
var (
|
| 154 |
+
noRune = []rune{}
|
| 155 |
+
noNext = []uint32{mergeFailed}
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
func mergeRuneSets(leftRunes, rightRunes *[]rune, leftPC, rightPC uint32) ([]rune, []uint32) {
|
| 159 |
+
leftLen := len(*leftRunes)
|
| 160 |
+
rightLen := len(*rightRunes)
|
| 161 |
+
if leftLen&0x1 != 0 || rightLen&0x1 != 0 {
|
| 162 |
+
panic("mergeRuneSets odd length []rune")
|
| 163 |
+
}
|
| 164 |
+
var (
|
| 165 |
+
lx, rx int
|
| 166 |
+
)
|
| 167 |
+
merged := make([]rune, 0)
|
| 168 |
+
next := make([]uint32, 0)
|
| 169 |
+
ok := true
|
| 170 |
+
defer func() {
|
| 171 |
+
if !ok {
|
| 172 |
+
merged = nil
|
| 173 |
+
next = nil
|
| 174 |
+
}
|
| 175 |
+
}()
|
| 176 |
+
|
| 177 |
+
ix := -1
|
| 178 |
+
extend := func(newLow *int, newArray *[]rune, pc uint32) bool {
|
| 179 |
+
if ix > 0 && (*newArray)[*newLow] <= merged[ix] {
|
| 180 |
+
return false
|
| 181 |
+
}
|
| 182 |
+
merged = append(merged, (*newArray)[*newLow], (*newArray)[*newLow+1])
|
| 183 |
+
*newLow += 2
|
| 184 |
+
ix += 2
|
| 185 |
+
next = append(next, pc)
|
| 186 |
+
return true
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
for lx < leftLen || rx < rightLen {
|
| 190 |
+
switch {
|
| 191 |
+
case rx >= rightLen:
|
| 192 |
+
ok = extend(&lx, leftRunes, leftPC)
|
| 193 |
+
case lx >= leftLen:
|
| 194 |
+
ok = extend(&rx, rightRunes, rightPC)
|
| 195 |
+
case (*rightRunes)[rx] < (*leftRunes)[lx]:
|
| 196 |
+
ok = extend(&rx, rightRunes, rightPC)
|
| 197 |
+
default:
|
| 198 |
+
ok = extend(&lx, leftRunes, leftPC)
|
| 199 |
+
}
|
| 200 |
+
if !ok {
|
| 201 |
+
return noRune, noNext
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
return merged, next
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
// cleanupOnePass drops working memory, and restores certain shortcut instructions.
|
| 208 |
+
func cleanupOnePass(prog *onePassProg, original *syntax.Prog) {
|
| 209 |
+
for ix, instOriginal := range original.Inst {
|
| 210 |
+
switch instOriginal.Op {
|
| 211 |
+
case syntax.InstAlt, syntax.InstAltMatch, syntax.InstRune:
|
| 212 |
+
case syntax.InstCapture, syntax.InstEmptyWidth, syntax.InstNop, syntax.InstMatch, syntax.InstFail:
|
| 213 |
+
prog.Inst[ix].Next = nil
|
| 214 |
+
case syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
|
| 215 |
+
prog.Inst[ix].Next = nil
|
| 216 |
+
prog.Inst[ix] = onePassInst{Inst: instOriginal}
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
// onePassCopy creates a copy of the original Prog, as we'll be modifying it.
|
| 222 |
+
func onePassCopy(prog *syntax.Prog) *onePassProg {
|
| 223 |
+
p := &onePassProg{
|
| 224 |
+
Start: prog.Start,
|
| 225 |
+
NumCap: prog.NumCap,
|
| 226 |
+
Inst: make([]onePassInst, len(prog.Inst)),
|
| 227 |
+
}
|
| 228 |
+
for i, inst := range prog.Inst {
|
| 229 |
+
p.Inst[i] = onePassInst{Inst: inst}
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
// rewrites one or more common Prog constructs that enable some otherwise
|
| 233 |
+
// non-onepass Progs to be onepass. A:BD (for example) means an InstAlt at
|
| 234 |
+
// ip A, that points to ips B & C.
|
| 235 |
+
// A:BC + B:DA => A:BC + B:CD
|
| 236 |
+
// A:BC + B:DC => A:DC + B:DC
|
| 237 |
+
for pc := range p.Inst {
|
| 238 |
+
switch p.Inst[pc].Op {
|
| 239 |
+
default:
|
| 240 |
+
continue
|
| 241 |
+
case syntax.InstAlt, syntax.InstAltMatch:
|
| 242 |
+
// A:Bx + B:Ay
|
| 243 |
+
p_A_Other := &p.Inst[pc].Out
|
| 244 |
+
p_A_Alt := &p.Inst[pc].Arg
|
| 245 |
+
// make sure a target is another Alt
|
| 246 |
+
instAlt := p.Inst[*p_A_Alt]
|
| 247 |
+
if !(instAlt.Op == syntax.InstAlt || instAlt.Op == syntax.InstAltMatch) {
|
| 248 |
+
p_A_Alt, p_A_Other = p_A_Other, p_A_Alt
|
| 249 |
+
instAlt = p.Inst[*p_A_Alt]
|
| 250 |
+
if !(instAlt.Op == syntax.InstAlt || instAlt.Op == syntax.InstAltMatch) {
|
| 251 |
+
continue
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
instOther := p.Inst[*p_A_Other]
|
| 255 |
+
// Analyzing both legs pointing to Alts is for another day
|
| 256 |
+
if instOther.Op == syntax.InstAlt || instOther.Op == syntax.InstAltMatch {
|
| 257 |
+
// too complicated
|
| 258 |
+
continue
|
| 259 |
+
}
|
| 260 |
+
// simple empty transition loop
|
| 261 |
+
// A:BC + B:DA => A:BC + B:DC
|
| 262 |
+
p_B_Alt := &p.Inst[*p_A_Alt].Out
|
| 263 |
+
p_B_Other := &p.Inst[*p_A_Alt].Arg
|
| 264 |
+
patch := false
|
| 265 |
+
if instAlt.Out == uint32(pc) {
|
| 266 |
+
patch = true
|
| 267 |
+
} else if instAlt.Arg == uint32(pc) {
|
| 268 |
+
patch = true
|
| 269 |
+
p_B_Alt, p_B_Other = p_B_Other, p_B_Alt
|
| 270 |
+
}
|
| 271 |
+
if patch {
|
| 272 |
+
*p_B_Alt = *p_A_Other
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
// empty transition to common target
|
| 276 |
+
// A:BC + B:DC => A:DC + B:DC
|
| 277 |
+
if *p_A_Other == *p_B_Alt {
|
| 278 |
+
*p_A_Alt = *p_B_Other
|
| 279 |
+
}
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
return p
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
var anyRuneNotNL = []rune{0, '\n' - 1, '\n' + 1, unicode.MaxRune}
|
| 286 |
+
var anyRune = []rune{0, unicode.MaxRune}
|
| 287 |
+
|
| 288 |
+
// makeOnePass creates a onepass Prog, if possible. It is possible if at any alt,
|
| 289 |
+
// the match engine can always tell which branch to take. The routine may modify
|
| 290 |
+
// p if it is turned into a onepass Prog. If it isn't possible for this to be a
|
| 291 |
+
// onepass Prog, the Prog nil is returned. makeOnePass is recursive
|
| 292 |
+
// to the size of the Prog.
|
| 293 |
+
func makeOnePass(p *onePassProg) *onePassProg {
|
| 294 |
+
// If the machine is very long, it's not worth the time to check if we can use one pass.
|
| 295 |
+
if len(p.Inst) >= 1000 {
|
| 296 |
+
return nil
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
var (
|
| 300 |
+
instQueue = newQueue(len(p.Inst))
|
| 301 |
+
visitQueue = newQueue(len(p.Inst))
|
| 302 |
+
check func(uint32, []bool) bool
|
| 303 |
+
onePassRunes = make([][]rune, len(p.Inst))
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
// check that paths from Alt instructions are unambiguous, and rebuild the new
|
| 307 |
+
// program as a onepass program
|
| 308 |
+
check = func(pc uint32, m []bool) (ok bool) {
|
| 309 |
+
ok = true
|
| 310 |
+
inst := &p.Inst[pc]
|
| 311 |
+
if visitQueue.contains(pc) {
|
| 312 |
+
return
|
| 313 |
+
}
|
| 314 |
+
visitQueue.insert(pc)
|
| 315 |
+
switch inst.Op {
|
| 316 |
+
case syntax.InstAlt, syntax.InstAltMatch:
|
| 317 |
+
ok = check(inst.Out, m) && check(inst.Arg, m)
|
| 318 |
+
// check no-input paths to InstMatch
|
| 319 |
+
matchOut := m[inst.Out]
|
| 320 |
+
matchArg := m[inst.Arg]
|
| 321 |
+
if matchOut && matchArg {
|
| 322 |
+
ok = false
|
| 323 |
+
break
|
| 324 |
+
}
|
| 325 |
+
// Match on empty goes in inst.Out
|
| 326 |
+
if matchArg {
|
| 327 |
+
inst.Out, inst.Arg = inst.Arg, inst.Out
|
| 328 |
+
matchOut, matchArg = matchArg, matchOut
|
| 329 |
+
}
|
| 330 |
+
if matchOut {
|
| 331 |
+
m[pc] = true
|
| 332 |
+
inst.Op = syntax.InstAltMatch
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// build a dispatch operator from the two legs of the alt.
|
| 336 |
+
onePassRunes[pc], inst.Next = mergeRuneSets(
|
| 337 |
+
&onePassRunes[inst.Out], &onePassRunes[inst.Arg], inst.Out, inst.Arg)
|
| 338 |
+
if len(inst.Next) > 0 && inst.Next[0] == mergeFailed {
|
| 339 |
+
ok = false
|
| 340 |
+
break
|
| 341 |
+
}
|
| 342 |
+
case syntax.InstCapture, syntax.InstNop:
|
| 343 |
+
ok = check(inst.Out, m)
|
| 344 |
+
m[pc] = m[inst.Out]
|
| 345 |
+
// pass matching runes back through these no-ops.
|
| 346 |
+
onePassRunes[pc] = append([]rune{}, onePassRunes[inst.Out]...)
|
| 347 |
+
inst.Next = make([]uint32, len(onePassRunes[pc])/2+1)
|
| 348 |
+
for i := range inst.Next {
|
| 349 |
+
inst.Next[i] = inst.Out
|
| 350 |
+
}
|
| 351 |
+
case syntax.InstEmptyWidth:
|
| 352 |
+
ok = check(inst.Out, m)
|
| 353 |
+
m[pc] = m[inst.Out]
|
| 354 |
+
onePassRunes[pc] = append([]rune{}, onePassRunes[inst.Out]...)
|
| 355 |
+
inst.Next = make([]uint32, len(onePassRunes[pc])/2+1)
|
| 356 |
+
for i := range inst.Next {
|
| 357 |
+
inst.Next[i] = inst.Out
|
| 358 |
+
}
|
| 359 |
+
case syntax.InstMatch, syntax.InstFail:
|
| 360 |
+
m[pc] = inst.Op == syntax.InstMatch
|
| 361 |
+
case syntax.InstRune:
|
| 362 |
+
m[pc] = false
|
| 363 |
+
if len(inst.Next) > 0 {
|
| 364 |
+
break
|
| 365 |
+
}
|
| 366 |
+
instQueue.insert(inst.Out)
|
| 367 |
+
if len(inst.Rune) == 0 {
|
| 368 |
+
onePassRunes[pc] = []rune{}
|
| 369 |
+
inst.Next = []uint32{inst.Out}
|
| 370 |
+
break
|
| 371 |
+
}
|
| 372 |
+
runes := make([]rune, 0)
|
| 373 |
+
if len(inst.Rune) == 1 && syntax.Flags(inst.Arg)&syntax.FoldCase != 0 {
|
| 374 |
+
r0 := inst.Rune[0]
|
| 375 |
+
runes = append(runes, r0, r0)
|
| 376 |
+
for r1 := unicode.SimpleFold(r0); r1 != r0; r1 = unicode.SimpleFold(r1) {
|
| 377 |
+
runes = append(runes, r1, r1)
|
| 378 |
+
}
|
| 379 |
+
slices.Sort(runes)
|
| 380 |
+
} else {
|
| 381 |
+
runes = append(runes, inst.Rune...)
|
| 382 |
+
}
|
| 383 |
+
onePassRunes[pc] = runes
|
| 384 |
+
inst.Next = make([]uint32, len(onePassRunes[pc])/2+1)
|
| 385 |
+
for i := range inst.Next {
|
| 386 |
+
inst.Next[i] = inst.Out
|
| 387 |
+
}
|
| 388 |
+
inst.Op = syntax.InstRune
|
| 389 |
+
case syntax.InstRune1:
|
| 390 |
+
m[pc] = false
|
| 391 |
+
if len(inst.Next) > 0 {
|
| 392 |
+
break
|
| 393 |
+
}
|
| 394 |
+
instQueue.insert(inst.Out)
|
| 395 |
+
runes := []rune{}
|
| 396 |
+
// expand case-folded runes
|
| 397 |
+
if syntax.Flags(inst.Arg)&syntax.FoldCase != 0 {
|
| 398 |
+
r0 := inst.Rune[0]
|
| 399 |
+
runes = append(runes, r0, r0)
|
| 400 |
+
for r1 := unicode.SimpleFold(r0); r1 != r0; r1 = unicode.SimpleFold(r1) {
|
| 401 |
+
runes = append(runes, r1, r1)
|
| 402 |
+
}
|
| 403 |
+
slices.Sort(runes)
|
| 404 |
+
} else {
|
| 405 |
+
runes = append(runes, inst.Rune[0], inst.Rune[0])
|
| 406 |
+
}
|
| 407 |
+
onePassRunes[pc] = runes
|
| 408 |
+
inst.Next = make([]uint32, len(onePassRunes[pc])/2+1)
|
| 409 |
+
for i := range inst.Next {
|
| 410 |
+
inst.Next[i] = inst.Out
|
| 411 |
+
}
|
| 412 |
+
inst.Op = syntax.InstRune
|
| 413 |
+
case syntax.InstRuneAny:
|
| 414 |
+
m[pc] = false
|
| 415 |
+
if len(inst.Next) > 0 {
|
| 416 |
+
break
|
| 417 |
+
}
|
| 418 |
+
instQueue.insert(inst.Out)
|
| 419 |
+
onePassRunes[pc] = append([]rune{}, anyRune...)
|
| 420 |
+
inst.Next = []uint32{inst.Out}
|
| 421 |
+
case syntax.InstRuneAnyNotNL:
|
| 422 |
+
m[pc] = false
|
| 423 |
+
if len(inst.Next) > 0 {
|
| 424 |
+
break
|
| 425 |
+
}
|
| 426 |
+
instQueue.insert(inst.Out)
|
| 427 |
+
onePassRunes[pc] = append([]rune{}, anyRuneNotNL...)
|
| 428 |
+
inst.Next = make([]uint32, len(onePassRunes[pc])/2+1)
|
| 429 |
+
for i := range inst.Next {
|
| 430 |
+
inst.Next[i] = inst.Out
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
return
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
instQueue.clear()
|
| 437 |
+
instQueue.insert(uint32(p.Start))
|
| 438 |
+
m := make([]bool, len(p.Inst))
|
| 439 |
+
for !instQueue.empty() {
|
| 440 |
+
visitQueue.clear()
|
| 441 |
+
pc := instQueue.next()
|
| 442 |
+
if !check(pc, m) {
|
| 443 |
+
p = nil
|
| 444 |
+
break
|
| 445 |
+
}
|
| 446 |
+
}
|
| 447 |
+
if p != nil {
|
| 448 |
+
for i := range p.Inst {
|
| 449 |
+
p.Inst[i].Rune = onePassRunes[i]
|
| 450 |
+
}
|
| 451 |
+
}
|
| 452 |
+
return p
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
// compileOnePass returns a new *syntax.Prog suitable for onePass execution if the original Prog
|
| 456 |
+
// can be recharacterized as a one-pass regexp program, or syntax.nil if the
|
| 457 |
+
// Prog cannot be converted. For a one pass prog, the fundamental condition that must
|
| 458 |
+
// be true is: at any InstAlt, there must be no ambiguity about what branch to take.
|
| 459 |
+
func compileOnePass(prog *syntax.Prog) (p *onePassProg) {
|
| 460 |
+
if prog.Start == 0 {
|
| 461 |
+
return nil
|
| 462 |
+
}
|
| 463 |
+
// onepass regexp is anchored
|
| 464 |
+
if prog.Inst[prog.Start].Op != syntax.InstEmptyWidth ||
|
| 465 |
+
syntax.EmptyOp(prog.Inst[prog.Start].Arg)&syntax.EmptyBeginText != syntax.EmptyBeginText {
|
| 466 |
+
return nil
|
| 467 |
+
}
|
| 468 |
+
hasAlt := false
|
| 469 |
+
for _, inst := range prog.Inst {
|
| 470 |
+
if inst.Op == syntax.InstAlt || inst.Op == syntax.InstAltMatch {
|
| 471 |
+
hasAlt = true
|
| 472 |
+
break
|
| 473 |
+
}
|
| 474 |
+
}
|
| 475 |
+
// If we have alternates, every instruction leading to InstMatch must be EmptyEndText.
|
| 476 |
+
// Also, any match on empty text must be $.
|
| 477 |
+
for _, inst := range prog.Inst {
|
| 478 |
+
opOut := prog.Inst[inst.Out].Op
|
| 479 |
+
switch inst.Op {
|
| 480 |
+
default:
|
| 481 |
+
if opOut == syntax.InstMatch && hasAlt {
|
| 482 |
+
return nil
|
| 483 |
+
}
|
| 484 |
+
case syntax.InstAlt, syntax.InstAltMatch:
|
| 485 |
+
if opOut == syntax.InstMatch || prog.Inst[inst.Arg].Op == syntax.InstMatch {
|
| 486 |
+
return nil
|
| 487 |
+
}
|
| 488 |
+
case syntax.InstEmptyWidth:
|
| 489 |
+
if opOut == syntax.InstMatch {
|
| 490 |
+
if syntax.EmptyOp(inst.Arg)&syntax.EmptyEndText == syntax.EmptyEndText {
|
| 491 |
+
continue
|
| 492 |
+
}
|
| 493 |
+
return nil
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
// Creates a slightly optimized copy of the original Prog
|
| 498 |
+
// that cleans up some Prog idioms that block valid onepass programs
|
| 499 |
+
p = onePassCopy(prog)
|
| 500 |
+
|
| 501 |
+
// checkAmbiguity on InstAlts, build onepass Prog if possible
|
| 502 |
+
p = makeOnePass(p)
|
| 503 |
+
|
| 504 |
+
if p != nil {
|
| 505 |
+
cleanupOnePass(p, prog)
|
| 506 |
+
}
|
| 507 |
+
return p
|
| 508 |
+
}
|
go/src/regexp/onepass_test.go
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 regexp
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"regexp/syntax"
|
| 9 |
+
"slices"
|
| 10 |
+
"strings"
|
| 11 |
+
"testing"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
var runeMergeTests = []struct {
|
| 15 |
+
left, right, merged []rune
|
| 16 |
+
next []uint32
|
| 17 |
+
leftPC, rightPC uint32
|
| 18 |
+
}{
|
| 19 |
+
{
|
| 20 |
+
// empty rhs
|
| 21 |
+
[]rune{69, 69},
|
| 22 |
+
[]rune{},
|
| 23 |
+
[]rune{69, 69},
|
| 24 |
+
[]uint32{1},
|
| 25 |
+
1, 2,
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
// identical runes, identical targets
|
| 29 |
+
[]rune{69, 69},
|
| 30 |
+
[]rune{69, 69},
|
| 31 |
+
[]rune{},
|
| 32 |
+
[]uint32{mergeFailed},
|
| 33 |
+
1, 1,
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
// identical runes, different targets
|
| 37 |
+
[]rune{69, 69},
|
| 38 |
+
[]rune{69, 69},
|
| 39 |
+
[]rune{},
|
| 40 |
+
[]uint32{mergeFailed},
|
| 41 |
+
1, 2,
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
// append right-first
|
| 45 |
+
[]rune{69, 69},
|
| 46 |
+
[]rune{71, 71},
|
| 47 |
+
[]rune{69, 69, 71, 71},
|
| 48 |
+
[]uint32{1, 2},
|
| 49 |
+
1, 2,
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
// append, left-first
|
| 53 |
+
[]rune{71, 71},
|
| 54 |
+
[]rune{69, 69},
|
| 55 |
+
[]rune{69, 69, 71, 71},
|
| 56 |
+
[]uint32{2, 1},
|
| 57 |
+
1, 2,
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
// successful interleave
|
| 61 |
+
[]rune{60, 60, 71, 71, 101, 101},
|
| 62 |
+
[]rune{69, 69, 88, 88},
|
| 63 |
+
[]rune{60, 60, 69, 69, 71, 71, 88, 88, 101, 101},
|
| 64 |
+
[]uint32{1, 2, 1, 2, 1},
|
| 65 |
+
1, 2,
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
// left surrounds right
|
| 69 |
+
[]rune{69, 74},
|
| 70 |
+
[]rune{71, 71},
|
| 71 |
+
[]rune{},
|
| 72 |
+
[]uint32{mergeFailed},
|
| 73 |
+
1, 2,
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
// right surrounds left
|
| 77 |
+
[]rune{69, 74},
|
| 78 |
+
[]rune{68, 75},
|
| 79 |
+
[]rune{},
|
| 80 |
+
[]uint32{mergeFailed},
|
| 81 |
+
1, 2,
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
// overlap at interval begin
|
| 85 |
+
[]rune{69, 74},
|
| 86 |
+
[]rune{74, 75},
|
| 87 |
+
[]rune{},
|
| 88 |
+
[]uint32{mergeFailed},
|
| 89 |
+
1, 2,
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
// overlap ar interval end
|
| 93 |
+
[]rune{69, 74},
|
| 94 |
+
[]rune{65, 69},
|
| 95 |
+
[]rune{},
|
| 96 |
+
[]uint32{mergeFailed},
|
| 97 |
+
1, 2,
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
// overlap from above
|
| 101 |
+
[]rune{69, 74},
|
| 102 |
+
[]rune{71, 74},
|
| 103 |
+
[]rune{},
|
| 104 |
+
[]uint32{mergeFailed},
|
| 105 |
+
1, 2,
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
// overlap from below
|
| 109 |
+
[]rune{69, 74},
|
| 110 |
+
[]rune{65, 71},
|
| 111 |
+
[]rune{},
|
| 112 |
+
[]uint32{mergeFailed},
|
| 113 |
+
1, 2,
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
// out of order []rune
|
| 117 |
+
[]rune{69, 74, 60, 65},
|
| 118 |
+
[]rune{66, 67},
|
| 119 |
+
[]rune{},
|
| 120 |
+
[]uint32{mergeFailed},
|
| 121 |
+
1, 2,
|
| 122 |
+
},
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
func TestMergeRuneSet(t *testing.T) {
|
| 126 |
+
for ix, test := range runeMergeTests {
|
| 127 |
+
merged, next := mergeRuneSets(&test.left, &test.right, test.leftPC, test.rightPC)
|
| 128 |
+
if !slices.Equal(merged, test.merged) {
|
| 129 |
+
t.Errorf("mergeRuneSet :%d (%v, %v) merged\n have\n%v\nwant\n%v", ix, test.left, test.right, merged, test.merged)
|
| 130 |
+
}
|
| 131 |
+
if !slices.Equal(next, test.next) {
|
| 132 |
+
t.Errorf("mergeRuneSet :%d(%v, %v) next\n have\n%v\nwant\n%v", ix, test.left, test.right, next, test.next)
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
var onePassTests = []struct {
|
| 138 |
+
re string
|
| 139 |
+
isOnePass bool
|
| 140 |
+
}{
|
| 141 |
+
{`^(?:a|(?:a*))$`, false},
|
| 142 |
+
{`^(?:(a)|(?:a*))$`, false},
|
| 143 |
+
{`^(?:(?:(?:.(?:$))?))$`, true},
|
| 144 |
+
{`^abcd$`, true},
|
| 145 |
+
{`^abcd`, true},
|
| 146 |
+
{`^(?:(?:a{0,})*?)$`, false},
|
| 147 |
+
{`^(?:(?:a+)*)$`, true},
|
| 148 |
+
{`^(?:(?:a|(?:aa)))$`, true},
|
| 149 |
+
{`^(?:[^\s\S])$`, true},
|
| 150 |
+
{`^(?:(?:a{3,4}){0,})$`, false},
|
| 151 |
+
{`^(?:(?:(?:a*)+))$`, true},
|
| 152 |
+
{`^[a-c]+$`, true},
|
| 153 |
+
{`^[a-c]*$`, true},
|
| 154 |
+
{`^(?:a*)$`, true},
|
| 155 |
+
{`^(?:(?:aa)|a)$`, true},
|
| 156 |
+
{`^[a-c]*`, false},
|
| 157 |
+
{`^...$`, true},
|
| 158 |
+
{`^...`, true},
|
| 159 |
+
{`^(?:a|(?:aa))$`, true},
|
| 160 |
+
{`^a((b))c$`, true},
|
| 161 |
+
{`^a.[l-nA-Cg-j]?e$`, true},
|
| 162 |
+
{`^a((b))$`, true},
|
| 163 |
+
{`^a(?:(b)|(c))c$`, true},
|
| 164 |
+
{`^a(?:(b*)|(c))c$`, false},
|
| 165 |
+
{`^a(?:b|c)$`, true},
|
| 166 |
+
{`^a(?:b?|c)$`, true},
|
| 167 |
+
{`^a(?:b?|c?)$`, false},
|
| 168 |
+
{`^a(?:b?|c+)$`, true},
|
| 169 |
+
{`^a(?:b+|(bc))d$`, false},
|
| 170 |
+
{`^a(?:bc)+$`, true},
|
| 171 |
+
{`^a(?:[bcd])+$`, true},
|
| 172 |
+
{`^a((?:[bcd])+)$`, true},
|
| 173 |
+
{`^a(:?b|c)*d$`, true},
|
| 174 |
+
{`^.bc(d|e)*$`, true},
|
| 175 |
+
{`^(?:(?:aa)|.)$`, false},
|
| 176 |
+
{`^(?:(?:a{1,2}){1,2})$`, false},
|
| 177 |
+
{`^l` + strings.Repeat("o", 2<<8) + `ng$`, true},
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
func TestCompileOnePass(t *testing.T) {
|
| 181 |
+
var (
|
| 182 |
+
p *syntax.Prog
|
| 183 |
+
re *syntax.Regexp
|
| 184 |
+
err error
|
| 185 |
+
)
|
| 186 |
+
for _, test := range onePassTests {
|
| 187 |
+
if re, err = syntax.Parse(test.re, syntax.Perl); err != nil {
|
| 188 |
+
t.Errorf("Parse(%q) got err:%s, want success", test.re, err)
|
| 189 |
+
continue
|
| 190 |
+
}
|
| 191 |
+
// needs to be done before compile...
|
| 192 |
+
re = re.Simplify()
|
| 193 |
+
if p, err = syntax.Compile(re); err != nil {
|
| 194 |
+
t.Errorf("Compile(%q) got err:%s, want success", test.re, err)
|
| 195 |
+
continue
|
| 196 |
+
}
|
| 197 |
+
isOnePass := compileOnePass(p) != nil
|
| 198 |
+
if isOnePass != test.isOnePass {
|
| 199 |
+
t.Errorf("CompileOnePass(%q) got isOnePass=%v, expected %v", test.re, isOnePass, test.isOnePass)
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
// TODO(cespare): Unify with onePassTests and rationalize one-pass test cases.
|
| 205 |
+
var onePassTests1 = []struct {
|
| 206 |
+
re string
|
| 207 |
+
match string
|
| 208 |
+
}{
|
| 209 |
+
{`^a(/b+(#c+)*)*$`, "a/b#c"}, // golang.org/issue/11905
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
func TestRunOnePass(t *testing.T) {
|
| 213 |
+
for _, test := range onePassTests1 {
|
| 214 |
+
re, err := Compile(test.re)
|
| 215 |
+
if err != nil {
|
| 216 |
+
t.Errorf("Compile(%q): got err: %s", test.re, err)
|
| 217 |
+
continue
|
| 218 |
+
}
|
| 219 |
+
if re.onepass == nil {
|
| 220 |
+
t.Errorf("Compile(%q): got nil, want one-pass", test.re)
|
| 221 |
+
continue
|
| 222 |
+
}
|
| 223 |
+
if !re.MatchString(test.match) {
|
| 224 |
+
t.Errorf("onepass %q did not match %q", test.re, test.match)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
}
|
go/src/regexp/regexp.go
ADDED
|
@@ -0,0 +1,1287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 regexp implements regular expression search.
|
| 6 |
+
//
|
| 7 |
+
// The syntax of the regular expressions accepted is the same
|
| 8 |
+
// general syntax used by Perl, Python, and other languages.
|
| 9 |
+
// More precisely, it is the syntax accepted by RE2 and described at
|
| 10 |
+
// https://golang.org/s/re2syntax, except for \C.
|
| 11 |
+
// For an overview of the syntax, see the [regexp/syntax] package.
|
| 12 |
+
//
|
| 13 |
+
// The regexp implementation provided by this package is
|
| 14 |
+
// guaranteed to run in time linear in the size of the input.
|
| 15 |
+
// (This is a property not guaranteed by most open source
|
| 16 |
+
// implementations of regular expressions.) For more information
|
| 17 |
+
// about this property, see https://swtch.com/~rsc/regexp/regexp1.html
|
| 18 |
+
// or any book about automata theory.
|
| 19 |
+
//
|
| 20 |
+
// All characters are UTF-8-encoded code points.
|
| 21 |
+
// Following [utf8.DecodeRune], each byte of an invalid UTF-8 sequence
|
| 22 |
+
// is treated as if it encoded utf8.RuneError (U+FFFD).
|
| 23 |
+
//
|
| 24 |
+
// There are 16 methods of [Regexp] that match a regular expression and identify
|
| 25 |
+
// the matched text. Their names are matched by this regular expression:
|
| 26 |
+
//
|
| 27 |
+
// Find(All)?(String)?(Submatch)?(Index)?
|
| 28 |
+
//
|
| 29 |
+
// If 'All' is present, the routine matches successive non-overlapping
|
| 30 |
+
// matches of the entire expression. Empty matches abutting a preceding
|
| 31 |
+
// match are ignored. The return value is a slice containing the successive
|
| 32 |
+
// return values of the corresponding non-'All' routine. These routines take
|
| 33 |
+
// an extra integer argument, n. If n >= 0, the function returns at most n
|
| 34 |
+
// matches/submatches; otherwise, it returns all of them.
|
| 35 |
+
//
|
| 36 |
+
// If 'String' is present, the argument is a string; otherwise it is a slice
|
| 37 |
+
// of bytes; return values are adjusted as appropriate.
|
| 38 |
+
//
|
| 39 |
+
// If 'Submatch' is present, the return value is a slice identifying the
|
| 40 |
+
// successive submatches of the expression. Submatches are matches of
|
| 41 |
+
// parenthesized subexpressions (also known as capturing groups) within the
|
| 42 |
+
// regular expression, numbered from left to right in order of opening
|
| 43 |
+
// parenthesis. Submatch 0 is the match of the entire expression, submatch 1 is
|
| 44 |
+
// the match of the first parenthesized subexpression, and so on.
|
| 45 |
+
//
|
| 46 |
+
// If 'Index' is present, matches and submatches are identified by byte index
|
| 47 |
+
// pairs within the input string: result[2*n:2*n+2] identifies the indexes of
|
| 48 |
+
// the nth submatch. The pair for n==0 identifies the match of the entire
|
| 49 |
+
// expression. If 'Index' is not present, the match is identified by the text
|
| 50 |
+
// of the match/submatch. If an index is negative or text is nil, it means that
|
| 51 |
+
// subexpression did not match any string in the input. For 'String' versions
|
| 52 |
+
// an empty string means either no match or an empty match.
|
| 53 |
+
//
|
| 54 |
+
// There is also a subset of the methods that can be applied to text read from
|
| 55 |
+
// an [io.RuneReader]: [Regexp.MatchReader], [Regexp.FindReaderIndex],
|
| 56 |
+
// [Regexp.FindReaderSubmatchIndex].
|
| 57 |
+
//
|
| 58 |
+
// This set may grow. Note that regular expression matches may need to
|
| 59 |
+
// examine text beyond the text returned by a match, so the methods that
|
| 60 |
+
// match text from an [io.RuneReader] may read arbitrarily far into the input
|
| 61 |
+
// before returning.
|
| 62 |
+
//
|
| 63 |
+
// (There are a few other methods that do not match this pattern.)
|
| 64 |
+
package regexp
|
| 65 |
+
|
| 66 |
+
import (
|
| 67 |
+
"bytes"
|
| 68 |
+
"io"
|
| 69 |
+
"regexp/syntax"
|
| 70 |
+
"strconv"
|
| 71 |
+
"strings"
|
| 72 |
+
"sync"
|
| 73 |
+
"unicode"
|
| 74 |
+
"unicode/utf8"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
// Regexp is the representation of a compiled regular expression.
|
| 78 |
+
// A Regexp is safe for concurrent use by multiple goroutines,
|
| 79 |
+
// except for configuration methods, such as [Regexp.Longest].
|
| 80 |
+
type Regexp struct {
|
| 81 |
+
expr string // as passed to Compile
|
| 82 |
+
prog *syntax.Prog // compiled program
|
| 83 |
+
onepass *onePassProg // onepass program or nil
|
| 84 |
+
numSubexp int
|
| 85 |
+
maxBitStateLen int
|
| 86 |
+
subexpNames []string
|
| 87 |
+
prefix string // required prefix in unanchored matches
|
| 88 |
+
prefixBytes []byte // prefix, as a []byte
|
| 89 |
+
prefixRune rune // first rune in prefix
|
| 90 |
+
prefixEnd uint32 // pc for last rune in prefix
|
| 91 |
+
mpool int // pool for machines
|
| 92 |
+
matchcap int // size of recorded match lengths
|
| 93 |
+
prefixComplete bool // prefix is the entire regexp
|
| 94 |
+
cond syntax.EmptyOp // empty-width conditions required at start of match
|
| 95 |
+
minInputLen int // minimum length of the input in bytes
|
| 96 |
+
|
| 97 |
+
// This field can be modified by the Longest method,
|
| 98 |
+
// but it is otherwise read-only.
|
| 99 |
+
longest bool // whether regexp prefers leftmost-longest match
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// String returns the source text used to compile the regular expression.
|
| 103 |
+
func (re *Regexp) String() string {
|
| 104 |
+
return re.expr
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Copy returns a new [Regexp] object copied from re.
|
| 108 |
+
// Calling [Regexp.Longest] on one copy does not affect another.
|
| 109 |
+
//
|
| 110 |
+
// Deprecated: In earlier releases, when using a [Regexp] in multiple goroutines,
|
| 111 |
+
// giving each goroutine its own copy helped to avoid lock contention.
|
| 112 |
+
// As of Go 1.12, using Copy is no longer necessary to avoid lock contention.
|
| 113 |
+
// Copy may still be appropriate if the reason for its use is to make
|
| 114 |
+
// two copies with different [Regexp.Longest] settings.
|
| 115 |
+
func (re *Regexp) Copy() *Regexp {
|
| 116 |
+
re2 := *re
|
| 117 |
+
return &re2
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
// Compile parses a regular expression and returns, if successful,
|
| 121 |
+
// a [Regexp] object that can be used to match against text.
|
| 122 |
+
//
|
| 123 |
+
// When matching against text, the regexp returns a match that
|
| 124 |
+
// begins as early as possible in the input (leftmost), and among those
|
| 125 |
+
// it chooses the one that a backtracking search would have found first.
|
| 126 |
+
// This so-called leftmost-first matching is the same semantics
|
| 127 |
+
// that Perl, Python, and other implementations use, although this
|
| 128 |
+
// package implements it without the expense of backtracking.
|
| 129 |
+
// For POSIX leftmost-longest matching, see [CompilePOSIX].
|
| 130 |
+
func Compile(expr string) (*Regexp, error) {
|
| 131 |
+
return compile(expr, syntax.Perl, false)
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// CompilePOSIX is like [Compile] but restricts the regular expression
|
| 135 |
+
// to POSIX ERE (egrep) syntax and changes the match semantics to
|
| 136 |
+
// leftmost-longest.
|
| 137 |
+
//
|
| 138 |
+
// That is, when matching against text, the regexp returns a match that
|
| 139 |
+
// begins as early as possible in the input (leftmost), and among those
|
| 140 |
+
// it chooses a match that is as long as possible.
|
| 141 |
+
// This so-called leftmost-longest matching is the same semantics
|
| 142 |
+
// that early regular expression implementations used and that POSIX
|
| 143 |
+
// specifies.
|
| 144 |
+
//
|
| 145 |
+
// However, there can be multiple leftmost-longest matches, with different
|
| 146 |
+
// submatch choices, and here this package diverges from POSIX.
|
| 147 |
+
// Among the possible leftmost-longest matches, this package chooses
|
| 148 |
+
// the one that a backtracking search would have found first, while POSIX
|
| 149 |
+
// specifies that the match be chosen to maximize the length of the first
|
| 150 |
+
// subexpression, then the second, and so on from left to right.
|
| 151 |
+
// The POSIX rule is computationally prohibitive and not even well-defined.
|
| 152 |
+
// See https://swtch.com/~rsc/regexp/regexp2.html#posix for details.
|
| 153 |
+
func CompilePOSIX(expr string) (*Regexp, error) {
|
| 154 |
+
return compile(expr, syntax.POSIX, true)
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// Longest makes future searches prefer the leftmost-longest match.
|
| 158 |
+
// That is, when matching against text, the regexp returns a match that
|
| 159 |
+
// begins as early as possible in the input (leftmost), and among those
|
| 160 |
+
// it chooses a match that is as long as possible.
|
| 161 |
+
// This method modifies the [Regexp] and may not be called concurrently
|
| 162 |
+
// with any other methods.
|
| 163 |
+
func (re *Regexp) Longest() {
|
| 164 |
+
re.longest = true
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) {
|
| 168 |
+
re, err := syntax.Parse(expr, mode)
|
| 169 |
+
if err != nil {
|
| 170 |
+
return nil, err
|
| 171 |
+
}
|
| 172 |
+
maxCap := re.MaxCap()
|
| 173 |
+
capNames := re.CapNames()
|
| 174 |
+
|
| 175 |
+
re = re.Simplify()
|
| 176 |
+
prog, err := syntax.Compile(re)
|
| 177 |
+
if err != nil {
|
| 178 |
+
return nil, err
|
| 179 |
+
}
|
| 180 |
+
matchcap := prog.NumCap
|
| 181 |
+
if matchcap < 2 {
|
| 182 |
+
matchcap = 2
|
| 183 |
+
}
|
| 184 |
+
regexp := &Regexp{
|
| 185 |
+
expr: expr,
|
| 186 |
+
prog: prog,
|
| 187 |
+
onepass: compileOnePass(prog),
|
| 188 |
+
numSubexp: maxCap,
|
| 189 |
+
subexpNames: capNames,
|
| 190 |
+
cond: prog.StartCond(),
|
| 191 |
+
longest: longest,
|
| 192 |
+
matchcap: matchcap,
|
| 193 |
+
minInputLen: minInputLen(re),
|
| 194 |
+
}
|
| 195 |
+
if regexp.onepass == nil {
|
| 196 |
+
regexp.prefix, regexp.prefixComplete = prog.Prefix()
|
| 197 |
+
regexp.maxBitStateLen = maxBitStateLen(prog)
|
| 198 |
+
} else {
|
| 199 |
+
regexp.prefix, regexp.prefixComplete, regexp.prefixEnd = onePassPrefix(prog)
|
| 200 |
+
}
|
| 201 |
+
if regexp.prefix != "" {
|
| 202 |
+
// TODO(rsc): Remove this allocation by adding
|
| 203 |
+
// IndexString to package bytes.
|
| 204 |
+
regexp.prefixBytes = []byte(regexp.prefix)
|
| 205 |
+
regexp.prefixRune, _ = utf8.DecodeRuneInString(regexp.prefix)
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
n := len(prog.Inst)
|
| 209 |
+
i := 0
|
| 210 |
+
for matchSize[i] != 0 && matchSize[i] < n {
|
| 211 |
+
i++
|
| 212 |
+
}
|
| 213 |
+
regexp.mpool = i
|
| 214 |
+
|
| 215 |
+
return regexp, nil
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
// Pools of *machine for use during (*Regexp).doExecute,
|
| 219 |
+
// split up by the size of the execution queues.
|
| 220 |
+
// matchPool[i] machines have queue size matchSize[i].
|
| 221 |
+
// On a 64-bit system each queue entry is 16 bytes,
|
| 222 |
+
// so matchPool[0] has 16*2*128 = 4kB queues, etc.
|
| 223 |
+
// The final matchPool is a catch-all for very large queues.
|
| 224 |
+
var (
|
| 225 |
+
matchSize = [...]int{128, 512, 2048, 16384, 0}
|
| 226 |
+
matchPool [len(matchSize)]sync.Pool
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
// get returns a machine to use for matching re.
|
| 230 |
+
// It uses the re's machine cache if possible, to avoid
|
| 231 |
+
// unnecessary allocation.
|
| 232 |
+
func (re *Regexp) get() *machine {
|
| 233 |
+
m, ok := matchPool[re.mpool].Get().(*machine)
|
| 234 |
+
if !ok {
|
| 235 |
+
m = new(machine)
|
| 236 |
+
}
|
| 237 |
+
m.re = re
|
| 238 |
+
m.p = re.prog
|
| 239 |
+
if cap(m.matchcap) < re.matchcap {
|
| 240 |
+
m.matchcap = make([]int, re.matchcap)
|
| 241 |
+
for _, t := range m.pool {
|
| 242 |
+
t.cap = make([]int, re.matchcap)
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
// Allocate queues if needed.
|
| 247 |
+
// Or reallocate, for "large" match pool.
|
| 248 |
+
n := matchSize[re.mpool]
|
| 249 |
+
if n == 0 { // large pool
|
| 250 |
+
n = len(re.prog.Inst)
|
| 251 |
+
}
|
| 252 |
+
if len(m.q0.sparse) < n {
|
| 253 |
+
m.q0 = queue{make([]uint32, n), make([]entry, 0, n)}
|
| 254 |
+
m.q1 = queue{make([]uint32, n), make([]entry, 0, n)}
|
| 255 |
+
}
|
| 256 |
+
return m
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// put returns a machine to the correct machine pool.
|
| 260 |
+
func (re *Regexp) put(m *machine) {
|
| 261 |
+
m.re = nil
|
| 262 |
+
m.p = nil
|
| 263 |
+
m.inputs.clear()
|
| 264 |
+
matchPool[re.mpool].Put(m)
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
// minInputLen walks the regexp to find the minimum length of any matchable input.
|
| 268 |
+
func minInputLen(re *syntax.Regexp) int {
|
| 269 |
+
switch re.Op {
|
| 270 |
+
default:
|
| 271 |
+
return 0
|
| 272 |
+
case syntax.OpAnyChar, syntax.OpAnyCharNotNL, syntax.OpCharClass:
|
| 273 |
+
return 1
|
| 274 |
+
case syntax.OpLiteral:
|
| 275 |
+
l := 0
|
| 276 |
+
for _, r := range re.Rune {
|
| 277 |
+
if r == utf8.RuneError {
|
| 278 |
+
l++
|
| 279 |
+
} else {
|
| 280 |
+
l += utf8.RuneLen(r)
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
return l
|
| 284 |
+
case syntax.OpCapture, syntax.OpPlus:
|
| 285 |
+
return minInputLen(re.Sub[0])
|
| 286 |
+
case syntax.OpRepeat:
|
| 287 |
+
return re.Min * minInputLen(re.Sub[0])
|
| 288 |
+
case syntax.OpConcat:
|
| 289 |
+
l := 0
|
| 290 |
+
for _, sub := range re.Sub {
|
| 291 |
+
l += minInputLen(sub)
|
| 292 |
+
}
|
| 293 |
+
return l
|
| 294 |
+
case syntax.OpAlternate:
|
| 295 |
+
l := minInputLen(re.Sub[0])
|
| 296 |
+
var lnext int
|
| 297 |
+
for _, sub := range re.Sub[1:] {
|
| 298 |
+
lnext = minInputLen(sub)
|
| 299 |
+
if lnext < l {
|
| 300 |
+
l = lnext
|
| 301 |
+
}
|
| 302 |
+
}
|
| 303 |
+
return l
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
// MustCompile is like [Compile] but panics if the expression cannot be parsed.
|
| 308 |
+
// It simplifies safe initialization of global variables holding compiled regular
|
| 309 |
+
// expressions.
|
| 310 |
+
func MustCompile(str string) *Regexp {
|
| 311 |
+
regexp, err := Compile(str)
|
| 312 |
+
if err != nil {
|
| 313 |
+
panic(`regexp: Compile(` + quote(str) + `): ` + err.Error())
|
| 314 |
+
}
|
| 315 |
+
return regexp
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
// MustCompilePOSIX is like [CompilePOSIX] but panics if the expression cannot be parsed.
|
| 319 |
+
// It simplifies safe initialization of global variables holding compiled regular
|
| 320 |
+
// expressions.
|
| 321 |
+
func MustCompilePOSIX(str string) *Regexp {
|
| 322 |
+
regexp, err := CompilePOSIX(str)
|
| 323 |
+
if err != nil {
|
| 324 |
+
panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + err.Error())
|
| 325 |
+
}
|
| 326 |
+
return regexp
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
func quote(s string) string {
|
| 330 |
+
if strconv.CanBackquote(s) {
|
| 331 |
+
return "`" + s + "`"
|
| 332 |
+
}
|
| 333 |
+
return strconv.Quote(s)
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// NumSubexp returns the number of parenthesized subexpressions in this [Regexp].
|
| 337 |
+
func (re *Regexp) NumSubexp() int {
|
| 338 |
+
return re.numSubexp
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
// SubexpNames returns the names of the parenthesized subexpressions
|
| 342 |
+
// in this [Regexp]. The name for the first sub-expression is names[1],
|
| 343 |
+
// so that if m is a match slice, the name for m[i] is SubexpNames()[i].
|
| 344 |
+
// Since the Regexp as a whole cannot be named, names[0] is always
|
| 345 |
+
// the empty string. The slice should not be modified.
|
| 346 |
+
func (re *Regexp) SubexpNames() []string {
|
| 347 |
+
return re.subexpNames
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
// SubexpIndex returns the index of the first subexpression with the given name,
|
| 351 |
+
// or -1 if there is no subexpression with that name.
|
| 352 |
+
//
|
| 353 |
+
// Note that multiple subexpressions can be written using the same name, as in
|
| 354 |
+
// (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob".
|
| 355 |
+
// In this case, SubexpIndex returns the index of the leftmost such subexpression
|
| 356 |
+
// in the regular expression.
|
| 357 |
+
func (re *Regexp) SubexpIndex(name string) int {
|
| 358 |
+
if name != "" {
|
| 359 |
+
for i, s := range re.subexpNames {
|
| 360 |
+
if name == s {
|
| 361 |
+
return i
|
| 362 |
+
}
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
return -1
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
const endOfText rune = -1
|
| 369 |
+
|
| 370 |
+
// input abstracts different representations of the input text. It provides
|
| 371 |
+
// one-character lookahead.
|
| 372 |
+
type input interface {
|
| 373 |
+
step(pos int) (r rune, width int) // advance one rune
|
| 374 |
+
canCheckPrefix() bool // can we look ahead without losing info?
|
| 375 |
+
hasPrefix(re *Regexp) bool
|
| 376 |
+
index(re *Regexp, pos int) int
|
| 377 |
+
context(pos int) lazyFlag
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
// inputString scans a string.
|
| 381 |
+
type inputString struct {
|
| 382 |
+
str string
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
func (i *inputString) step(pos int) (rune, int) {
|
| 386 |
+
if pos < len(i.str) {
|
| 387 |
+
return utf8.DecodeRuneInString(i.str[pos:])
|
| 388 |
+
}
|
| 389 |
+
return endOfText, 0
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
func (i *inputString) canCheckPrefix() bool {
|
| 393 |
+
return true
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
func (i *inputString) hasPrefix(re *Regexp) bool {
|
| 397 |
+
return strings.HasPrefix(i.str, re.prefix)
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
func (i *inputString) index(re *Regexp, pos int) int {
|
| 401 |
+
return strings.Index(i.str[pos:], re.prefix)
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
func (i *inputString) context(pos int) lazyFlag {
|
| 405 |
+
r1, r2 := endOfText, endOfText
|
| 406 |
+
// 0 < pos && pos <= len(i.str)
|
| 407 |
+
if uint(pos-1) < uint(len(i.str)) {
|
| 408 |
+
r1, _ = utf8.DecodeLastRuneInString(i.str[:pos])
|
| 409 |
+
}
|
| 410 |
+
// 0 <= pos && pos < len(i.str)
|
| 411 |
+
if uint(pos) < uint(len(i.str)) {
|
| 412 |
+
r2, _ = utf8.DecodeRuneInString(i.str[pos:])
|
| 413 |
+
}
|
| 414 |
+
return newLazyFlag(r1, r2)
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
// inputBytes scans a byte slice.
|
| 418 |
+
type inputBytes struct {
|
| 419 |
+
str []byte
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
func (i *inputBytes) step(pos int) (rune, int) {
|
| 423 |
+
if pos < len(i.str) {
|
| 424 |
+
return utf8.DecodeRune(i.str[pos:])
|
| 425 |
+
}
|
| 426 |
+
return endOfText, 0
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
func (i *inputBytes) canCheckPrefix() bool {
|
| 430 |
+
return true
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
func (i *inputBytes) hasPrefix(re *Regexp) bool {
|
| 434 |
+
return bytes.HasPrefix(i.str, re.prefixBytes)
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
func (i *inputBytes) index(re *Regexp, pos int) int {
|
| 438 |
+
return bytes.Index(i.str[pos:], re.prefixBytes)
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
func (i *inputBytes) context(pos int) lazyFlag {
|
| 442 |
+
r1, r2 := endOfText, endOfText
|
| 443 |
+
// 0 < pos && pos <= len(i.str)
|
| 444 |
+
if uint(pos-1) < uint(len(i.str)) {
|
| 445 |
+
r1, _ = utf8.DecodeLastRune(i.str[:pos])
|
| 446 |
+
}
|
| 447 |
+
// 0 <= pos && pos < len(i.str)
|
| 448 |
+
if uint(pos) < uint(len(i.str)) {
|
| 449 |
+
r2, _ = utf8.DecodeRune(i.str[pos:])
|
| 450 |
+
}
|
| 451 |
+
return newLazyFlag(r1, r2)
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// inputReader scans a RuneReader.
|
| 455 |
+
type inputReader struct {
|
| 456 |
+
r io.RuneReader
|
| 457 |
+
atEOT bool
|
| 458 |
+
pos int
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
func (i *inputReader) step(pos int) (rune, int) {
|
| 462 |
+
if !i.atEOT && pos != i.pos {
|
| 463 |
+
return endOfText, 0
|
| 464 |
+
|
| 465 |
+
}
|
| 466 |
+
r, w, err := i.r.ReadRune()
|
| 467 |
+
if err != nil {
|
| 468 |
+
i.atEOT = true
|
| 469 |
+
return endOfText, 0
|
| 470 |
+
}
|
| 471 |
+
i.pos += w
|
| 472 |
+
return r, w
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
func (i *inputReader) canCheckPrefix() bool {
|
| 476 |
+
return false
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
func (i *inputReader) hasPrefix(re *Regexp) bool {
|
| 480 |
+
return false
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
func (i *inputReader) index(re *Regexp, pos int) int {
|
| 484 |
+
return -1
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
func (i *inputReader) context(pos int) lazyFlag {
|
| 488 |
+
return 0 // not used
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
// LiteralPrefix returns a literal string that must begin any match
|
| 492 |
+
// of the regular expression re. It returns the boolean true if the
|
| 493 |
+
// literal string comprises the entire regular expression.
|
| 494 |
+
func (re *Regexp) LiteralPrefix() (prefix string, complete bool) {
|
| 495 |
+
return re.prefix, re.prefixComplete
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
// MatchReader reports whether the text returned by the [io.RuneReader]
|
| 499 |
+
// contains any match of the regular expression re.
|
| 500 |
+
func (re *Regexp) MatchReader(r io.RuneReader) bool {
|
| 501 |
+
return re.doMatch(r, nil, "")
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
// MatchString reports whether the string s
|
| 505 |
+
// contains any match of the regular expression re.
|
| 506 |
+
func (re *Regexp) MatchString(s string) bool {
|
| 507 |
+
return re.doMatch(nil, nil, s)
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
// Match reports whether the byte slice b
|
| 511 |
+
// contains any match of the regular expression re.
|
| 512 |
+
func (re *Regexp) Match(b []byte) bool {
|
| 513 |
+
return re.doMatch(nil, b, "")
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// MatchReader reports whether the text returned by the [io.RuneReader]
|
| 517 |
+
// contains any match of the regular expression pattern.
|
| 518 |
+
// More complicated queries need to use [Compile] and the full [Regexp] interface.
|
| 519 |
+
func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) {
|
| 520 |
+
re, err := Compile(pattern)
|
| 521 |
+
if err != nil {
|
| 522 |
+
return false, err
|
| 523 |
+
}
|
| 524 |
+
return re.MatchReader(r), nil
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
// MatchString reports whether the string s
|
| 528 |
+
// contains any match of the regular expression pattern.
|
| 529 |
+
// More complicated queries need to use [Compile] and the full [Regexp] interface.
|
| 530 |
+
func MatchString(pattern string, s string) (matched bool, err error) {
|
| 531 |
+
re, err := Compile(pattern)
|
| 532 |
+
if err != nil {
|
| 533 |
+
return false, err
|
| 534 |
+
}
|
| 535 |
+
return re.MatchString(s), nil
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
// Match reports whether the byte slice b
|
| 539 |
+
// contains any match of the regular expression pattern.
|
| 540 |
+
// More complicated queries need to use [Compile] and the full [Regexp] interface.
|
| 541 |
+
func Match(pattern string, b []byte) (matched bool, err error) {
|
| 542 |
+
re, err := Compile(pattern)
|
| 543 |
+
if err != nil {
|
| 544 |
+
return false, err
|
| 545 |
+
}
|
| 546 |
+
return re.Match(b), nil
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
// ReplaceAllString returns a copy of src, replacing matches of the [Regexp]
|
| 550 |
+
// with the replacement string repl.
|
| 551 |
+
// Inside repl, $ signs are interpreted as in [Regexp.Expand].
|
| 552 |
+
func (re *Regexp) ReplaceAllString(src, repl string) string {
|
| 553 |
+
n := 2
|
| 554 |
+
if strings.Contains(repl, "$") {
|
| 555 |
+
n = 2 * (re.numSubexp + 1)
|
| 556 |
+
}
|
| 557 |
+
b := re.replaceAll(nil, src, n, func(dst []byte, match []int) []byte {
|
| 558 |
+
return re.expand(dst, repl, nil, src, match)
|
| 559 |
+
})
|
| 560 |
+
return string(b)
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
// ReplaceAllLiteralString returns a copy of src, replacing matches of the [Regexp]
|
| 564 |
+
// with the replacement string repl. The replacement repl is substituted directly,
|
| 565 |
+
// without using [Regexp.Expand].
|
| 566 |
+
func (re *Regexp) ReplaceAllLiteralString(src, repl string) string {
|
| 567 |
+
return string(re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte {
|
| 568 |
+
return append(dst, repl...)
|
| 569 |
+
}))
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
// ReplaceAllStringFunc returns a copy of src in which all matches of the
|
| 573 |
+
// [Regexp] have been replaced by the return value of function repl applied
|
| 574 |
+
// to the matched substring. The replacement returned by repl is substituted
|
| 575 |
+
// directly, without using [Regexp.Expand].
|
| 576 |
+
func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string {
|
| 577 |
+
b := re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte {
|
| 578 |
+
return append(dst, repl(src[match[0]:match[1]])...)
|
| 579 |
+
})
|
| 580 |
+
return string(b)
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst []byte, m []int) []byte) []byte {
|
| 584 |
+
lastMatchEnd := 0 // end position of the most recent match
|
| 585 |
+
searchPos := 0 // position where we next look for a match
|
| 586 |
+
var buf []byte
|
| 587 |
+
var endPos int
|
| 588 |
+
if bsrc != nil {
|
| 589 |
+
endPos = len(bsrc)
|
| 590 |
+
} else {
|
| 591 |
+
endPos = len(src)
|
| 592 |
+
}
|
| 593 |
+
if nmatch > re.prog.NumCap {
|
| 594 |
+
nmatch = re.prog.NumCap
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
var dstCap [2]int
|
| 598 |
+
for searchPos <= endPos {
|
| 599 |
+
a := re.doExecute(nil, bsrc, src, searchPos, nmatch, dstCap[:0])
|
| 600 |
+
if len(a) == 0 {
|
| 601 |
+
break // no more matches
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
// Copy the unmatched characters before this match.
|
| 605 |
+
if bsrc != nil {
|
| 606 |
+
buf = append(buf, bsrc[lastMatchEnd:a[0]]...)
|
| 607 |
+
} else {
|
| 608 |
+
buf = append(buf, src[lastMatchEnd:a[0]]...)
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
// Now insert a copy of the replacement string, but not for a
|
| 612 |
+
// match of the empty string immediately after another match.
|
| 613 |
+
// (Otherwise, we get double replacement for patterns that
|
| 614 |
+
// match both empty and nonempty strings.)
|
| 615 |
+
if a[1] > lastMatchEnd || a[0] == 0 {
|
| 616 |
+
buf = repl(buf, a)
|
| 617 |
+
}
|
| 618 |
+
lastMatchEnd = a[1]
|
| 619 |
+
|
| 620 |
+
// Advance past this match; always advance at least one character.
|
| 621 |
+
var width int
|
| 622 |
+
if bsrc != nil {
|
| 623 |
+
_, width = utf8.DecodeRune(bsrc[searchPos:])
|
| 624 |
+
} else {
|
| 625 |
+
_, width = utf8.DecodeRuneInString(src[searchPos:])
|
| 626 |
+
}
|
| 627 |
+
if searchPos+width > a[1] {
|
| 628 |
+
searchPos += width
|
| 629 |
+
} else if searchPos+1 > a[1] {
|
| 630 |
+
// This clause is only needed at the end of the input
|
| 631 |
+
// string. In that case, DecodeRuneInString returns width=0.
|
| 632 |
+
searchPos++
|
| 633 |
+
} else {
|
| 634 |
+
searchPos = a[1]
|
| 635 |
+
}
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
// Copy the unmatched characters after the last match.
|
| 639 |
+
if bsrc != nil {
|
| 640 |
+
buf = append(buf, bsrc[lastMatchEnd:]...)
|
| 641 |
+
} else {
|
| 642 |
+
buf = append(buf, src[lastMatchEnd:]...)
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
return buf
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
// ReplaceAll returns a copy of src, replacing matches of the [Regexp]
|
| 649 |
+
// with the replacement text repl.
|
| 650 |
+
// Inside repl, $ signs are interpreted as in [Regexp.Expand].
|
| 651 |
+
func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
|
| 652 |
+
n := 2
|
| 653 |
+
if bytes.IndexByte(repl, '$') >= 0 {
|
| 654 |
+
n = 2 * (re.numSubexp + 1)
|
| 655 |
+
}
|
| 656 |
+
srepl := ""
|
| 657 |
+
b := re.replaceAll(src, "", n, func(dst []byte, match []int) []byte {
|
| 658 |
+
if len(srepl) != len(repl) {
|
| 659 |
+
srepl = string(repl)
|
| 660 |
+
}
|
| 661 |
+
return re.expand(dst, srepl, src, "", match)
|
| 662 |
+
})
|
| 663 |
+
return b
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
// ReplaceAllLiteral returns a copy of src, replacing matches of the [Regexp]
|
| 667 |
+
// with the replacement bytes repl. The replacement repl is substituted directly,
|
| 668 |
+
// without using [Regexp.Expand].
|
| 669 |
+
func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte {
|
| 670 |
+
return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte {
|
| 671 |
+
return append(dst, repl...)
|
| 672 |
+
})
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
// ReplaceAllFunc returns a copy of src in which all matches of the
|
| 676 |
+
// [Regexp] have been replaced by the return value of function repl applied
|
| 677 |
+
// to the matched byte slice. The replacement returned by repl is substituted
|
| 678 |
+
// directly, without using [Regexp.Expand].
|
| 679 |
+
func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte {
|
| 680 |
+
return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte {
|
| 681 |
+
return append(dst, repl(src[match[0]:match[1]])...)
|
| 682 |
+
})
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
// Bitmap used by func special to check whether a character needs to be escaped.
|
| 686 |
+
var specialBytes [16]byte
|
| 687 |
+
|
| 688 |
+
// special reports whether byte b needs to be escaped by QuoteMeta.
|
| 689 |
+
func special(b byte) bool {
|
| 690 |
+
return b < utf8.RuneSelf && specialBytes[b%16]&(1<<(b/16)) != 0
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
func init() {
|
| 694 |
+
for _, b := range []byte(`\.+*?()|[]{}^$`) {
|
| 695 |
+
specialBytes[b%16] |= 1 << (b / 16)
|
| 696 |
+
}
|
| 697 |
+
}
|
| 698 |
+
|
| 699 |
+
// QuoteMeta returns a string that escapes all regular expression metacharacters
|
| 700 |
+
// inside the argument text; the returned string is a regular expression matching
|
| 701 |
+
// the literal text.
|
| 702 |
+
func QuoteMeta(s string) string {
|
| 703 |
+
// A byte loop is correct because all metacharacters are ASCII.
|
| 704 |
+
var i int
|
| 705 |
+
for i = 0; i < len(s); i++ {
|
| 706 |
+
if special(s[i]) {
|
| 707 |
+
break
|
| 708 |
+
}
|
| 709 |
+
}
|
| 710 |
+
// No meta characters found, so return original string.
|
| 711 |
+
if i >= len(s) {
|
| 712 |
+
return s
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
b := make([]byte, 2*len(s)-i)
|
| 716 |
+
copy(b, s[:i])
|
| 717 |
+
j := i
|
| 718 |
+
for ; i < len(s); i++ {
|
| 719 |
+
if special(s[i]) {
|
| 720 |
+
b[j] = '\\'
|
| 721 |
+
j++
|
| 722 |
+
}
|
| 723 |
+
b[j] = s[i]
|
| 724 |
+
j++
|
| 725 |
+
}
|
| 726 |
+
return string(b[:j])
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
// The number of capture values in the program may correspond
|
| 730 |
+
// to fewer capturing expressions than are in the regexp.
|
| 731 |
+
// For example, "(a){0}" turns into an empty program, so the
|
| 732 |
+
// maximum capture in the program is 0 but we need to return
|
| 733 |
+
// an expression for \1. Pad appends -1s to the slice a as needed.
|
| 734 |
+
func (re *Regexp) pad(a []int) []int {
|
| 735 |
+
if a == nil {
|
| 736 |
+
// No match.
|
| 737 |
+
return nil
|
| 738 |
+
}
|
| 739 |
+
n := (1 + re.numSubexp) * 2
|
| 740 |
+
for len(a) < n {
|
| 741 |
+
a = append(a, -1)
|
| 742 |
+
}
|
| 743 |
+
return a
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
// allMatches calls deliver at most n times
|
| 747 |
+
// with the location of successive matches in the input text.
|
| 748 |
+
// The input text is b if non-nil, otherwise s.
|
| 749 |
+
func (re *Regexp) allMatches(s string, b []byte, n int, deliver func([]int)) {
|
| 750 |
+
var end int
|
| 751 |
+
if b == nil {
|
| 752 |
+
end = len(s)
|
| 753 |
+
} else {
|
| 754 |
+
end = len(b)
|
| 755 |
+
}
|
| 756 |
+
|
| 757 |
+
for pos, i, prevMatchEnd := 0, 0, -1; i < n && pos <= end; {
|
| 758 |
+
matches := re.doExecute(nil, b, s, pos, re.prog.NumCap, nil)
|
| 759 |
+
if len(matches) == 0 {
|
| 760 |
+
break
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
accept := true
|
| 764 |
+
if matches[1] == pos {
|
| 765 |
+
// We've found an empty match.
|
| 766 |
+
if matches[0] == prevMatchEnd {
|
| 767 |
+
// We don't allow an empty match right
|
| 768 |
+
// after a previous match, so ignore it.
|
| 769 |
+
accept = false
|
| 770 |
+
}
|
| 771 |
+
var width int
|
| 772 |
+
if b == nil {
|
| 773 |
+
is := inputString{str: s}
|
| 774 |
+
_, width = is.step(pos)
|
| 775 |
+
} else {
|
| 776 |
+
ib := inputBytes{str: b}
|
| 777 |
+
_, width = ib.step(pos)
|
| 778 |
+
}
|
| 779 |
+
if width > 0 {
|
| 780 |
+
pos += width
|
| 781 |
+
} else {
|
| 782 |
+
pos = end + 1
|
| 783 |
+
}
|
| 784 |
+
} else {
|
| 785 |
+
pos = matches[1]
|
| 786 |
+
}
|
| 787 |
+
prevMatchEnd = matches[1]
|
| 788 |
+
|
| 789 |
+
if accept {
|
| 790 |
+
deliver(re.pad(matches))
|
| 791 |
+
i++
|
| 792 |
+
}
|
| 793 |
+
}
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
// Find returns a slice holding the text of the leftmost match in b of the regular expression.
|
| 797 |
+
// A return value of nil indicates no match.
|
| 798 |
+
func (re *Regexp) Find(b []byte) []byte {
|
| 799 |
+
var dstCap [2]int
|
| 800 |
+
a := re.doExecute(nil, b, "", 0, 2, dstCap[:0])
|
| 801 |
+
if a == nil {
|
| 802 |
+
return nil
|
| 803 |
+
}
|
| 804 |
+
return b[a[0]:a[1]:a[1]]
|
| 805 |
+
}
|
| 806 |
+
|
| 807 |
+
// FindIndex returns a two-element slice of integers defining the location of
|
| 808 |
+
// the leftmost match in b of the regular expression. The match itself is at
|
| 809 |
+
// b[loc[0]:loc[1]].
|
| 810 |
+
// A return value of nil indicates no match.
|
| 811 |
+
func (re *Regexp) FindIndex(b []byte) (loc []int) {
|
| 812 |
+
a := re.doExecute(nil, b, "", 0, 2, nil)
|
| 813 |
+
if a == nil {
|
| 814 |
+
return nil
|
| 815 |
+
}
|
| 816 |
+
return a[0:2]
|
| 817 |
+
}
|
| 818 |
+
|
| 819 |
+
// FindString returns a string holding the text of the leftmost match in s of the regular
|
| 820 |
+
// expression. If there is no match, the return value is an empty string,
|
| 821 |
+
// but it will also be empty if the regular expression successfully matches
|
| 822 |
+
// an empty string. Use [Regexp.FindStringIndex] or [Regexp.FindStringSubmatch] if it is
|
| 823 |
+
// necessary to distinguish these cases.
|
| 824 |
+
func (re *Regexp) FindString(s string) string {
|
| 825 |
+
var dstCap [2]int
|
| 826 |
+
a := re.doExecute(nil, nil, s, 0, 2, dstCap[:0])
|
| 827 |
+
if a == nil {
|
| 828 |
+
return ""
|
| 829 |
+
}
|
| 830 |
+
return s[a[0]:a[1]]
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
// FindStringIndex returns a two-element slice of integers defining the
|
| 834 |
+
// location of the leftmost match in s of the regular expression. The match
|
| 835 |
+
// itself is at s[loc[0]:loc[1]].
|
| 836 |
+
// A return value of nil indicates no match.
|
| 837 |
+
func (re *Regexp) FindStringIndex(s string) (loc []int) {
|
| 838 |
+
a := re.doExecute(nil, nil, s, 0, 2, nil)
|
| 839 |
+
if a == nil {
|
| 840 |
+
return nil
|
| 841 |
+
}
|
| 842 |
+
return a[0:2]
|
| 843 |
+
}
|
| 844 |
+
|
| 845 |
+
// FindReaderIndex returns a two-element slice of integers defining the
|
| 846 |
+
// location of the leftmost match of the regular expression in text read from
|
| 847 |
+
// the [io.RuneReader]. The match text was found in the input stream at
|
| 848 |
+
// byte offset loc[0] through loc[1]-1.
|
| 849 |
+
// A return value of nil indicates no match.
|
| 850 |
+
func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int) {
|
| 851 |
+
a := re.doExecute(r, nil, "", 0, 2, nil)
|
| 852 |
+
if a == nil {
|
| 853 |
+
return nil
|
| 854 |
+
}
|
| 855 |
+
return a[0:2]
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
// FindSubmatch returns a slice of slices holding the text of the leftmost
|
| 859 |
+
// match of the regular expression in b and the matches, if any, of its
|
| 860 |
+
// subexpressions, as defined by the 'Submatch' descriptions in the package
|
| 861 |
+
// comment.
|
| 862 |
+
// A return value of nil indicates no match.
|
| 863 |
+
func (re *Regexp) FindSubmatch(b []byte) [][]byte {
|
| 864 |
+
var dstCap [4]int
|
| 865 |
+
a := re.doExecute(nil, b, "", 0, re.prog.NumCap, dstCap[:0])
|
| 866 |
+
if a == nil {
|
| 867 |
+
return nil
|
| 868 |
+
}
|
| 869 |
+
ret := make([][]byte, 1+re.numSubexp)
|
| 870 |
+
for i := range ret {
|
| 871 |
+
if 2*i < len(a) && a[2*i] >= 0 {
|
| 872 |
+
ret[i] = b[a[2*i]:a[2*i+1]:a[2*i+1]]
|
| 873 |
+
}
|
| 874 |
+
}
|
| 875 |
+
return ret
|
| 876 |
+
}
|
| 877 |
+
|
| 878 |
+
// Expand appends template to dst and returns the result; during the
|
| 879 |
+
// append, Expand replaces variables in the template with corresponding
|
| 880 |
+
// matches drawn from src. The match slice should have been returned by
|
| 881 |
+
// [Regexp.FindSubmatchIndex].
|
| 882 |
+
//
|
| 883 |
+
// In the template, a variable is denoted by a substring of the form
|
| 884 |
+
// $name or ${name}, where name is a non-empty sequence of letters,
|
| 885 |
+
// digits, and underscores. A purely numeric name like $1 refers to
|
| 886 |
+
// the submatch with the corresponding index; other names refer to
|
| 887 |
+
// capturing parentheses named with the (?P<name>...) syntax. A
|
| 888 |
+
// reference to an out of range or unmatched index or a name that is not
|
| 889 |
+
// present in the regular expression is replaced with an empty slice.
|
| 890 |
+
//
|
| 891 |
+
// In the $name form, name is taken to be as long as possible: $1x is
|
| 892 |
+
// equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.
|
| 893 |
+
//
|
| 894 |
+
// To insert a literal $ in the output, use $$ in the template.
|
| 895 |
+
func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte {
|
| 896 |
+
return re.expand(dst, string(template), src, "", match)
|
| 897 |
+
}
|
| 898 |
+
|
| 899 |
+
// ExpandString is like [Regexp.Expand] but the template and source are strings.
|
| 900 |
+
// It appends to and returns a byte slice in order to give the calling
|
| 901 |
+
// code control over allocation.
|
| 902 |
+
func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte {
|
| 903 |
+
return re.expand(dst, template, nil, src, match)
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
+
func (re *Regexp) expand(dst []byte, template string, bsrc []byte, src string, match []int) []byte {
|
| 907 |
+
for len(template) > 0 {
|
| 908 |
+
before, after, ok := strings.Cut(template, "$")
|
| 909 |
+
if !ok {
|
| 910 |
+
break
|
| 911 |
+
}
|
| 912 |
+
dst = append(dst, before...)
|
| 913 |
+
template = after
|
| 914 |
+
if template != "" && template[0] == '$' {
|
| 915 |
+
// Treat $$ as $.
|
| 916 |
+
dst = append(dst, '$')
|
| 917 |
+
template = template[1:]
|
| 918 |
+
continue
|
| 919 |
+
}
|
| 920 |
+
name, num, rest, ok := extract(template)
|
| 921 |
+
if !ok {
|
| 922 |
+
// Malformed; treat $ as raw text.
|
| 923 |
+
dst = append(dst, '$')
|
| 924 |
+
continue
|
| 925 |
+
}
|
| 926 |
+
template = rest
|
| 927 |
+
if num >= 0 {
|
| 928 |
+
if 2*num+1 < len(match) && match[2*num] >= 0 {
|
| 929 |
+
if bsrc != nil {
|
| 930 |
+
dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...)
|
| 931 |
+
} else {
|
| 932 |
+
dst = append(dst, src[match[2*num]:match[2*num+1]]...)
|
| 933 |
+
}
|
| 934 |
+
}
|
| 935 |
+
} else {
|
| 936 |
+
for i, namei := range re.subexpNames {
|
| 937 |
+
if name == namei && 2*i+1 < len(match) && match[2*i] >= 0 {
|
| 938 |
+
if bsrc != nil {
|
| 939 |
+
dst = append(dst, bsrc[match[2*i]:match[2*i+1]]...)
|
| 940 |
+
} else {
|
| 941 |
+
dst = append(dst, src[match[2*i]:match[2*i+1]]...)
|
| 942 |
+
}
|
| 943 |
+
break
|
| 944 |
+
}
|
| 945 |
+
}
|
| 946 |
+
}
|
| 947 |
+
}
|
| 948 |
+
dst = append(dst, template...)
|
| 949 |
+
return dst
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
// extract returns the name from a leading "name" or "{name}" in str.
|
| 953 |
+
// (The $ has already been removed by the caller.)
|
| 954 |
+
// If it is a number, extract returns num set to that number; otherwise num = -1.
|
| 955 |
+
func extract(str string) (name string, num int, rest string, ok bool) {
|
| 956 |
+
if str == "" {
|
| 957 |
+
return
|
| 958 |
+
}
|
| 959 |
+
brace := false
|
| 960 |
+
if str[0] == '{' {
|
| 961 |
+
brace = true
|
| 962 |
+
str = str[1:]
|
| 963 |
+
}
|
| 964 |
+
i := 0
|
| 965 |
+
for i < len(str) {
|
| 966 |
+
rune, size := utf8.DecodeRuneInString(str[i:])
|
| 967 |
+
if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) && rune != '_' {
|
| 968 |
+
break
|
| 969 |
+
}
|
| 970 |
+
i += size
|
| 971 |
+
}
|
| 972 |
+
if i == 0 {
|
| 973 |
+
// empty name is not okay
|
| 974 |
+
return
|
| 975 |
+
}
|
| 976 |
+
name = str[:i]
|
| 977 |
+
if brace {
|
| 978 |
+
if i >= len(str) || str[i] != '}' {
|
| 979 |
+
// missing closing brace
|
| 980 |
+
return
|
| 981 |
+
}
|
| 982 |
+
i++
|
| 983 |
+
}
|
| 984 |
+
|
| 985 |
+
// Parse number.
|
| 986 |
+
num = 0
|
| 987 |
+
for i := 0; i < len(name); i++ {
|
| 988 |
+
if name[i] < '0' || '9' < name[i] || num >= 1e8 {
|
| 989 |
+
num = -1
|
| 990 |
+
break
|
| 991 |
+
}
|
| 992 |
+
num = num*10 + int(name[i]) - '0'
|
| 993 |
+
}
|
| 994 |
+
// Disallow leading zeros.
|
| 995 |
+
if name[0] == '0' && len(name) > 1 {
|
| 996 |
+
num = -1
|
| 997 |
+
}
|
| 998 |
+
|
| 999 |
+
rest = str[i:]
|
| 1000 |
+
ok = true
|
| 1001 |
+
return
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
// FindSubmatchIndex returns a slice holding the index pairs identifying the
|
| 1005 |
+
// leftmost match of the regular expression in b and the matches, if any, of
|
| 1006 |
+
// its subexpressions, as defined by the 'Submatch' and 'Index' descriptions
|
| 1007 |
+
// in the package comment.
|
| 1008 |
+
// A return value of nil indicates no match.
|
| 1009 |
+
func (re *Regexp) FindSubmatchIndex(b []byte) []int {
|
| 1010 |
+
return re.pad(re.doExecute(nil, b, "", 0, re.prog.NumCap, nil))
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
// FindStringSubmatch returns a slice of strings holding the text of the
|
| 1014 |
+
// leftmost match of the regular expression in s and the matches, if any, of
|
| 1015 |
+
// its subexpressions, as defined by the 'Submatch' description in the
|
| 1016 |
+
// package comment.
|
| 1017 |
+
// A return value of nil indicates no match.
|
| 1018 |
+
func (re *Regexp) FindStringSubmatch(s string) []string {
|
| 1019 |
+
var dstCap [4]int
|
| 1020 |
+
a := re.doExecute(nil, nil, s, 0, re.prog.NumCap, dstCap[:0])
|
| 1021 |
+
if a == nil {
|
| 1022 |
+
return nil
|
| 1023 |
+
}
|
| 1024 |
+
ret := make([]string, 1+re.numSubexp)
|
| 1025 |
+
for i := range ret {
|
| 1026 |
+
if 2*i < len(a) && a[2*i] >= 0 {
|
| 1027 |
+
ret[i] = s[a[2*i]:a[2*i+1]]
|
| 1028 |
+
}
|
| 1029 |
+
}
|
| 1030 |
+
return ret
|
| 1031 |
+
}
|
| 1032 |
+
|
| 1033 |
+
// FindStringSubmatchIndex returns a slice holding the index pairs
|
| 1034 |
+
// identifying the leftmost match of the regular expression in s and the
|
| 1035 |
+
// matches, if any, of its subexpressions, as defined by the 'Submatch' and
|
| 1036 |
+
// 'Index' descriptions in the package comment.
|
| 1037 |
+
// A return value of nil indicates no match.
|
| 1038 |
+
func (re *Regexp) FindStringSubmatchIndex(s string) []int {
|
| 1039 |
+
return re.pad(re.doExecute(nil, nil, s, 0, re.prog.NumCap, nil))
|
| 1040 |
+
}
|
| 1041 |
+
|
| 1042 |
+
// FindReaderSubmatchIndex returns a slice holding the index pairs
|
| 1043 |
+
// identifying the leftmost match of the regular expression of text read by
|
| 1044 |
+
// the [io.RuneReader], and the matches, if any, of its subexpressions, as defined
|
| 1045 |
+
// by the 'Submatch' and 'Index' descriptions in the package comment. A
|
| 1046 |
+
// return value of nil indicates no match.
|
| 1047 |
+
func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int {
|
| 1048 |
+
return re.pad(re.doExecute(r, nil, "", 0, re.prog.NumCap, nil))
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
const startSize = 10 // The size at which to start a slice in the 'All' routines.
|
| 1052 |
+
|
| 1053 |
+
// FindAll is the 'All' version of [Regexp.Find]; it returns a slice of all successive
|
| 1054 |
+
// matches of the expression, as defined by the 'All' description in the
|
| 1055 |
+
// package comment.
|
| 1056 |
+
// A return value of nil indicates no match.
|
| 1057 |
+
func (re *Regexp) FindAll(b []byte, n int) [][]byte {
|
| 1058 |
+
if n < 0 {
|
| 1059 |
+
n = len(b) + 1
|
| 1060 |
+
}
|
| 1061 |
+
var result [][]byte
|
| 1062 |
+
re.allMatches("", b, n, func(match []int) {
|
| 1063 |
+
if result == nil {
|
| 1064 |
+
result = make([][]byte, 0, startSize)
|
| 1065 |
+
}
|
| 1066 |
+
result = append(result, b[match[0]:match[1]:match[1]])
|
| 1067 |
+
})
|
| 1068 |
+
return result
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
// FindAllIndex is the 'All' version of [Regexp.FindIndex]; it returns a slice of all
|
| 1072 |
+
// successive matches of the expression, as defined by the 'All' description
|
| 1073 |
+
// in the package comment.
|
| 1074 |
+
// A return value of nil indicates no match.
|
| 1075 |
+
func (re *Regexp) FindAllIndex(b []byte, n int) [][]int {
|
| 1076 |
+
if n < 0 {
|
| 1077 |
+
n = len(b) + 1
|
| 1078 |
+
}
|
| 1079 |
+
var result [][]int
|
| 1080 |
+
re.allMatches("", b, n, func(match []int) {
|
| 1081 |
+
if result == nil {
|
| 1082 |
+
result = make([][]int, 0, startSize)
|
| 1083 |
+
}
|
| 1084 |
+
result = append(result, match[0:2])
|
| 1085 |
+
})
|
| 1086 |
+
return result
|
| 1087 |
+
}
|
| 1088 |
+
|
| 1089 |
+
// FindAllString is the 'All' version of [Regexp.FindString]; it returns a slice of all
|
| 1090 |
+
// successive matches of the expression, as defined by the 'All' description
|
| 1091 |
+
// in the package comment.
|
| 1092 |
+
// A return value of nil indicates no match.
|
| 1093 |
+
func (re *Regexp) FindAllString(s string, n int) []string {
|
| 1094 |
+
if n < 0 {
|
| 1095 |
+
n = len(s) + 1
|
| 1096 |
+
}
|
| 1097 |
+
var result []string
|
| 1098 |
+
re.allMatches(s, nil, n, func(match []int) {
|
| 1099 |
+
if result == nil {
|
| 1100 |
+
result = make([]string, 0, startSize)
|
| 1101 |
+
}
|
| 1102 |
+
result = append(result, s[match[0]:match[1]])
|
| 1103 |
+
})
|
| 1104 |
+
return result
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
// FindAllStringIndex is the 'All' version of [Regexp.FindStringIndex]; it returns a
|
| 1108 |
+
// slice of all successive matches of the expression, as defined by the 'All'
|
| 1109 |
+
// description in the package comment.
|
| 1110 |
+
// A return value of nil indicates no match.
|
| 1111 |
+
func (re *Regexp) FindAllStringIndex(s string, n int) [][]int {
|
| 1112 |
+
if n < 0 {
|
| 1113 |
+
n = len(s) + 1
|
| 1114 |
+
}
|
| 1115 |
+
var result [][]int
|
| 1116 |
+
re.allMatches(s, nil, n, func(match []int) {
|
| 1117 |
+
if result == nil {
|
| 1118 |
+
result = make([][]int, 0, startSize)
|
| 1119 |
+
}
|
| 1120 |
+
result = append(result, match[0:2])
|
| 1121 |
+
})
|
| 1122 |
+
return result
|
| 1123 |
+
}
|
| 1124 |
+
|
| 1125 |
+
// FindAllSubmatch is the 'All' version of [Regexp.FindSubmatch]; it returns a slice
|
| 1126 |
+
// of all successive matches of the expression, as defined by the 'All'
|
| 1127 |
+
// description in the package comment.
|
| 1128 |
+
// A return value of nil indicates no match.
|
| 1129 |
+
func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte {
|
| 1130 |
+
if n < 0 {
|
| 1131 |
+
n = len(b) + 1
|
| 1132 |
+
}
|
| 1133 |
+
var result [][][]byte
|
| 1134 |
+
re.allMatches("", b, n, func(match []int) {
|
| 1135 |
+
if result == nil {
|
| 1136 |
+
result = make([][][]byte, 0, startSize)
|
| 1137 |
+
}
|
| 1138 |
+
slice := make([][]byte, len(match)/2)
|
| 1139 |
+
for j := range slice {
|
| 1140 |
+
if match[2*j] >= 0 {
|
| 1141 |
+
slice[j] = b[match[2*j]:match[2*j+1]:match[2*j+1]]
|
| 1142 |
+
}
|
| 1143 |
+
}
|
| 1144 |
+
result = append(result, slice)
|
| 1145 |
+
})
|
| 1146 |
+
return result
|
| 1147 |
+
}
|
| 1148 |
+
|
| 1149 |
+
// FindAllSubmatchIndex is the 'All' version of [Regexp.FindSubmatchIndex]; it returns
|
| 1150 |
+
// a slice of all successive matches of the expression, as defined by the
|
| 1151 |
+
// 'All' description in the package comment.
|
| 1152 |
+
// A return value of nil indicates no match.
|
| 1153 |
+
func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int {
|
| 1154 |
+
if n < 0 {
|
| 1155 |
+
n = len(b) + 1
|
| 1156 |
+
}
|
| 1157 |
+
var result [][]int
|
| 1158 |
+
re.allMatches("", b, n, func(match []int) {
|
| 1159 |
+
if result == nil {
|
| 1160 |
+
result = make([][]int, 0, startSize)
|
| 1161 |
+
}
|
| 1162 |
+
result = append(result, match)
|
| 1163 |
+
})
|
| 1164 |
+
return result
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
// FindAllStringSubmatch is the 'All' version of [Regexp.FindStringSubmatch]; it
|
| 1168 |
+
// returns a slice of all successive matches of the expression, as defined by
|
| 1169 |
+
// the 'All' description in the package comment.
|
| 1170 |
+
// A return value of nil indicates no match.
|
| 1171 |
+
func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string {
|
| 1172 |
+
if n < 0 {
|
| 1173 |
+
n = len(s) + 1
|
| 1174 |
+
}
|
| 1175 |
+
var result [][]string
|
| 1176 |
+
re.allMatches(s, nil, n, func(match []int) {
|
| 1177 |
+
if result == nil {
|
| 1178 |
+
result = make([][]string, 0, startSize)
|
| 1179 |
+
}
|
| 1180 |
+
slice := make([]string, len(match)/2)
|
| 1181 |
+
for j := range slice {
|
| 1182 |
+
if match[2*j] >= 0 {
|
| 1183 |
+
slice[j] = s[match[2*j]:match[2*j+1]]
|
| 1184 |
+
}
|
| 1185 |
+
}
|
| 1186 |
+
result = append(result, slice)
|
| 1187 |
+
})
|
| 1188 |
+
return result
|
| 1189 |
+
}
|
| 1190 |
+
|
| 1191 |
+
// FindAllStringSubmatchIndex is the 'All' version of
|
| 1192 |
+
// [Regexp.FindStringSubmatchIndex]; it returns a slice of all successive matches of
|
| 1193 |
+
// the expression, as defined by the 'All' description in the package
|
| 1194 |
+
// comment.
|
| 1195 |
+
// A return value of nil indicates no match.
|
| 1196 |
+
func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int {
|
| 1197 |
+
if n < 0 {
|
| 1198 |
+
n = len(s) + 1
|
| 1199 |
+
}
|
| 1200 |
+
var result [][]int
|
| 1201 |
+
re.allMatches(s, nil, n, func(match []int) {
|
| 1202 |
+
if result == nil {
|
| 1203 |
+
result = make([][]int, 0, startSize)
|
| 1204 |
+
}
|
| 1205 |
+
result = append(result, match)
|
| 1206 |
+
})
|
| 1207 |
+
return result
|
| 1208 |
+
}
|
| 1209 |
+
|
| 1210 |
+
// Split slices s into substrings separated by the expression and returns a slice of
|
| 1211 |
+
// the substrings between those expression matches.
|
| 1212 |
+
//
|
| 1213 |
+
// The slice returned by this method consists of all the substrings of s
|
| 1214 |
+
// not contained in the slice returned by [Regexp.FindAllString]. When called on an expression
|
| 1215 |
+
// that contains no metacharacters, it is equivalent to [strings.SplitN].
|
| 1216 |
+
//
|
| 1217 |
+
// Example:
|
| 1218 |
+
//
|
| 1219 |
+
// s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
|
| 1220 |
+
// // s: ["", "b", "b", "c", "cadaaae"]
|
| 1221 |
+
//
|
| 1222 |
+
// The count determines the number of substrings to return:
|
| 1223 |
+
// - n > 0: at most n substrings; the last substring will be the unsplit remainder;
|
| 1224 |
+
// - n == 0: the result is nil (zero substrings);
|
| 1225 |
+
// - n < 0: all substrings.
|
| 1226 |
+
func (re *Regexp) Split(s string, n int) []string {
|
| 1227 |
+
|
| 1228 |
+
if n == 0 {
|
| 1229 |
+
return nil
|
| 1230 |
+
}
|
| 1231 |
+
|
| 1232 |
+
if len(re.expr) > 0 && len(s) == 0 {
|
| 1233 |
+
return []string{""}
|
| 1234 |
+
}
|
| 1235 |
+
|
| 1236 |
+
matches := re.FindAllStringIndex(s, n)
|
| 1237 |
+
strings := make([]string, 0, len(matches))
|
| 1238 |
+
|
| 1239 |
+
beg := 0
|
| 1240 |
+
end := 0
|
| 1241 |
+
for _, match := range matches {
|
| 1242 |
+
if n > 0 && len(strings) >= n-1 {
|
| 1243 |
+
break
|
| 1244 |
+
}
|
| 1245 |
+
|
| 1246 |
+
end = match[0]
|
| 1247 |
+
if match[1] != 0 {
|
| 1248 |
+
strings = append(strings, s[beg:end])
|
| 1249 |
+
}
|
| 1250 |
+
beg = match[1]
|
| 1251 |
+
}
|
| 1252 |
+
|
| 1253 |
+
if end != len(s) {
|
| 1254 |
+
strings = append(strings, s[beg:])
|
| 1255 |
+
}
|
| 1256 |
+
|
| 1257 |
+
return strings
|
| 1258 |
+
}
|
| 1259 |
+
|
| 1260 |
+
// AppendText implements [encoding.TextAppender]. The output
|
| 1261 |
+
// matches that of calling the [Regexp.String] method.
|
| 1262 |
+
//
|
| 1263 |
+
// Note that the output is lossy in some cases: This method does not indicate
|
| 1264 |
+
// POSIX regular expressions (i.e. those compiled by calling [CompilePOSIX]), or
|
| 1265 |
+
// those for which the [Regexp.Longest] method has been called.
|
| 1266 |
+
func (re *Regexp) AppendText(b []byte) ([]byte, error) {
|
| 1267 |
+
return append(b, re.String()...), nil
|
| 1268 |
+
}
|
| 1269 |
+
|
| 1270 |
+
// MarshalText implements [encoding.TextMarshaler]. The output
|
| 1271 |
+
// matches that of calling the [Regexp.AppendText] method.
|
| 1272 |
+
//
|
| 1273 |
+
// See [Regexp.AppendText] for more information.
|
| 1274 |
+
func (re *Regexp) MarshalText() ([]byte, error) {
|
| 1275 |
+
return re.AppendText(nil)
|
| 1276 |
+
}
|
| 1277 |
+
|
| 1278 |
+
// UnmarshalText implements [encoding.TextUnmarshaler] by calling
|
| 1279 |
+
// [Compile] on the encoded value.
|
| 1280 |
+
func (re *Regexp) UnmarshalText(text []byte) error {
|
| 1281 |
+
newRE, err := Compile(string(text))
|
| 1282 |
+
if err != nil {
|
| 1283 |
+
return err
|
| 1284 |
+
}
|
| 1285 |
+
*re = *newRE
|
| 1286 |
+
return nil
|
| 1287 |
+
}
|
go/src/runtime/HACKING.md
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This is a living document and at times it will be out of date. It is
|
| 2 |
+
intended to articulate how programming in the Go runtime differs from
|
| 3 |
+
writing normal Go. It focuses on pervasive concepts rather than
|
| 4 |
+
details of particular interfaces.
|
| 5 |
+
|
| 6 |
+
Scheduler structures
|
| 7 |
+
====================
|
| 8 |
+
|
| 9 |
+
The scheduler manages three types of resources that pervade the
|
| 10 |
+
runtime: Gs, Ms, and Ps. It's important to understand these even if
|
| 11 |
+
you're not working on the scheduler.
|
| 12 |
+
|
| 13 |
+
Gs, Ms, Ps
|
| 14 |
+
----------
|
| 15 |
+
|
| 16 |
+
A "G" is simply a goroutine. It's represented by type `g`. When a
|
| 17 |
+
goroutine exits, its `g` object is returned to a pool of free `g`s and
|
| 18 |
+
can later be reused for some other goroutine.
|
| 19 |
+
|
| 20 |
+
An "M" is an OS thread that can be executing user Go code, runtime
|
| 21 |
+
code, a system call, or be idle. It's represented by type `m`. There
|
| 22 |
+
can be any number of Ms at a time since any number of threads may be
|
| 23 |
+
blocked in system calls.
|
| 24 |
+
|
| 25 |
+
Finally, a "P" represents the resources required to execute user Go
|
| 26 |
+
code, such as scheduler and memory allocator state. It's represented
|
| 27 |
+
by type `p`. There are exactly `GOMAXPROCS` Ps. A P can be thought of
|
| 28 |
+
like a CPU in the OS scheduler and the contents of the `p` type like
|
| 29 |
+
per-CPU state. This is a good place to put state that needs to be
|
| 30 |
+
sharded for efficiency, but doesn't need to be per-thread or
|
| 31 |
+
per-goroutine.
|
| 32 |
+
|
| 33 |
+
The scheduler's job is to match up a G (the code to execute), an M
|
| 34 |
+
(where to execute it), and a P (the rights and resources to execute
|
| 35 |
+
it). When an M stops executing user Go code, for example by entering a
|
| 36 |
+
system call, it returns its P to the idle P pool. In order to resume
|
| 37 |
+
executing user Go code, for example on return from a system call, it
|
| 38 |
+
must acquire a P from the idle pool.
|
| 39 |
+
|
| 40 |
+
All `g`, `m`, and `p` objects are heap allocated, but are never freed,
|
| 41 |
+
so their memory remains type stable. As a result, the runtime can
|
| 42 |
+
avoid write barriers in the depths of the scheduler.
|
| 43 |
+
|
| 44 |
+
`getg()` and `getg().m.curg`
|
| 45 |
+
----------------------------
|
| 46 |
+
|
| 47 |
+
To get the current user `g`, use `getg().m.curg`.
|
| 48 |
+
|
| 49 |
+
`getg()` alone returns the current `g`, but when executing on the
|
| 50 |
+
system or signal stacks, this will return the current M's "g0" or
|
| 51 |
+
"gsignal", respectively. This is usually not what you want.
|
| 52 |
+
|
| 53 |
+
To determine if you're running on the user stack or the system stack,
|
| 54 |
+
use `getg() == getg().m.curg`.
|
| 55 |
+
|
| 56 |
+
Stacks
|
| 57 |
+
======
|
| 58 |
+
|
| 59 |
+
Every non-dead G has a *user stack* associated with it, which is what
|
| 60 |
+
user Go code executes on. User stacks start small (e.g., 2K) and grow
|
| 61 |
+
or shrink dynamically.
|
| 62 |
+
|
| 63 |
+
Every M has a *system stack* associated with it (also known as the M's
|
| 64 |
+
"g0" stack because it's implemented as a stub G) and, on Unix
|
| 65 |
+
platforms, a *signal stack* (also known as the M's "gsignal" stack).
|
| 66 |
+
System and signal stacks cannot grow, but are large enough to execute
|
| 67 |
+
runtime and cgo code (8K in a pure Go binary; system-allocated in a
|
| 68 |
+
cgo binary).
|
| 69 |
+
|
| 70 |
+
Runtime code often temporarily switches to the system stack using
|
| 71 |
+
`systemstack`, `mcall`, or `asmcgocall` to perform tasks that must not
|
| 72 |
+
be preempted, that must not grow the user stack, or that switch user
|
| 73 |
+
goroutines. Code running on the system stack is implicitly
|
| 74 |
+
non-preemptible and the garbage collector does not scan system stacks.
|
| 75 |
+
While running on the system stack, the current user stack is not used
|
| 76 |
+
for execution.
|
| 77 |
+
|
| 78 |
+
nosplit functions
|
| 79 |
+
-----------------
|
| 80 |
+
|
| 81 |
+
Most functions start with a prologue that inspects the stack pointer
|
| 82 |
+
and the current G's stack bound and calls `morestack` if the stack
|
| 83 |
+
needs to grow.
|
| 84 |
+
|
| 85 |
+
Functions can be marked `//go:nosplit` (or `NOSPLIT` in assembly) to
|
| 86 |
+
indicate that they should not get this prologue. This has several
|
| 87 |
+
uses:
|
| 88 |
+
|
| 89 |
+
- Functions that must run on the user stack, but must not call into
|
| 90 |
+
stack growth, for example because this would cause a deadlock, or
|
| 91 |
+
because they have untyped words on the stack.
|
| 92 |
+
|
| 93 |
+
- Functions that must not be preempted on entry.
|
| 94 |
+
|
| 95 |
+
- Functions that may run without a valid G. For example, functions
|
| 96 |
+
that run in early runtime start-up, or that may be entered from C
|
| 97 |
+
code such as cgo callbacks or the signal handler.
|
| 98 |
+
|
| 99 |
+
Splittable functions ensure there's some amount of space on the stack
|
| 100 |
+
for nosplit functions to run in and the linker checks that any static
|
| 101 |
+
chain of nosplit function calls cannot exceed this bound.
|
| 102 |
+
|
| 103 |
+
Any function with a `//go:nosplit` annotation should explain why it is
|
| 104 |
+
nosplit in its documentation comment.
|
| 105 |
+
|
| 106 |
+
Error handling and reporting
|
| 107 |
+
============================
|
| 108 |
+
|
| 109 |
+
Errors that can reasonably be recovered from in user code should use
|
| 110 |
+
`panic` like usual. However, there are some situations where `panic`
|
| 111 |
+
will cause an immediate fatal error, such as when called on the system
|
| 112 |
+
stack or when called during `mallocgc`.
|
| 113 |
+
|
| 114 |
+
Most errors in the runtime are not recoverable. For these, use
|
| 115 |
+
`throw`, which dumps the traceback and immediately terminates the
|
| 116 |
+
process. In general, `throw` should be passed a string constant to
|
| 117 |
+
avoid allocating in perilous situations. By convention, additional
|
| 118 |
+
details are printed before `throw` using `print` or `println` and the
|
| 119 |
+
messages are prefixed with "runtime:".
|
| 120 |
+
|
| 121 |
+
For unrecoverable errors where user code is expected to be at fault for the
|
| 122 |
+
failure (such as racing map writes), use `fatal`.
|
| 123 |
+
|
| 124 |
+
For runtime error debugging, it may be useful to run with `GOTRACEBACK=system`
|
| 125 |
+
or `GOTRACEBACK=crash`. The output of `panic` and `fatal` is as described by
|
| 126 |
+
`GOTRACEBACK`. The output of `throw` always includes runtime frames, metadata
|
| 127 |
+
and all goroutines regardless of `GOTRACEBACK` (i.e., equivalent to
|
| 128 |
+
`GOTRACEBACK=system`). Whether `throw` crashes or not is still controlled by
|
| 129 |
+
`GOTRACEBACK`.
|
| 130 |
+
|
| 131 |
+
Synchronization
|
| 132 |
+
===============
|
| 133 |
+
|
| 134 |
+
The runtime has multiple synchronization mechanisms. They differ in
|
| 135 |
+
semantics and, in particular, in whether they interact with the
|
| 136 |
+
goroutine scheduler or the OS scheduler.
|
| 137 |
+
|
| 138 |
+
The simplest is `mutex`, which is manipulated using `lock` and
|
| 139 |
+
`unlock`. This should be used to protect shared structures for short
|
| 140 |
+
periods. Blocking on a `mutex` directly blocks the M, without
|
| 141 |
+
interacting with the Go scheduler. This means it is safe to use from
|
| 142 |
+
the lowest levels of the runtime, but also prevents any associated G
|
| 143 |
+
and P from being rescheduled. `rwmutex` is similar.
|
| 144 |
+
|
| 145 |
+
For one-shot notifications, use `note`, which provides `notesleep` and
|
| 146 |
+
`notewakeup`. Unlike traditional UNIX `sleep`/`wakeup`, `note`s are
|
| 147 |
+
race-free, so `notesleep` returns immediately if the `notewakeup` has
|
| 148 |
+
already happened. A `note` can be reset after use with `noteclear`,
|
| 149 |
+
which must not race with a sleep or wakeup. Like `mutex`, blocking on
|
| 150 |
+
a `note` blocks the M. However, there are different ways to sleep on a
|
| 151 |
+
`note`:`notesleep` also prevents rescheduling of any associated G and
|
| 152 |
+
P, while `notetsleepg` acts like a blocking system call that allows
|
| 153 |
+
the P to be reused to run another G. This is still less efficient than
|
| 154 |
+
blocking the G directly since it consumes an M.
|
| 155 |
+
|
| 156 |
+
To interact directly with the goroutine scheduler, use `gopark` and
|
| 157 |
+
`goready`. `gopark` parks the current goroutine—putting it in the
|
| 158 |
+
"waiting" state and removing it from the scheduler's run queue—and
|
| 159 |
+
schedules another goroutine on the current M/P. `goready` puts a
|
| 160 |
+
parked goroutine back in the "runnable" state and adds it to the run
|
| 161 |
+
queue.
|
| 162 |
+
|
| 163 |
+
In summary,
|
| 164 |
+
|
| 165 |
+
<table>
|
| 166 |
+
<tr><th></th><th colspan="3">Blocks</th></tr>
|
| 167 |
+
<tr><th>Interface</th><th>G</th><th>M</th><th>P</th></tr>
|
| 168 |
+
<tr><td>(rw)mutex</td><td>Y</td><td>Y</td><td>Y</td></tr>
|
| 169 |
+
<tr><td>note</td><td>Y</td><td>Y</td><td>Y/N</td></tr>
|
| 170 |
+
<tr><td>park</td><td>Y</td><td>N</td><td>N</td></tr>
|
| 171 |
+
</table>
|
| 172 |
+
|
| 173 |
+
Atomics
|
| 174 |
+
=======
|
| 175 |
+
|
| 176 |
+
The runtime uses its own atomics package at `internal/runtime/atomic`.
|
| 177 |
+
This corresponds to `sync/atomic`, but functions have different names
|
| 178 |
+
for historical reasons and there are a few additional functions needed
|
| 179 |
+
by the runtime.
|
| 180 |
+
|
| 181 |
+
In general, we think hard about the uses of atomics in the runtime and
|
| 182 |
+
try to avoid unnecessary atomic operations. If access to a variable is
|
| 183 |
+
sometimes protected by another synchronization mechanism, the
|
| 184 |
+
already-protected accesses generally don't need to be atomic. There
|
| 185 |
+
are several reasons for this:
|
| 186 |
+
|
| 187 |
+
1. Using non-atomic or atomic access where appropriate makes the code
|
| 188 |
+
more self-documenting. Atomic access to a variable implies there's
|
| 189 |
+
somewhere else that may concurrently access the variable.
|
| 190 |
+
|
| 191 |
+
2. Non-atomic access allows for automatic race detection. The runtime
|
| 192 |
+
doesn't currently have a race detector, but it may in the future.
|
| 193 |
+
Atomic access defeats the race detector, while non-atomic access
|
| 194 |
+
allows the race detector to check your assumptions.
|
| 195 |
+
|
| 196 |
+
3. Non-atomic access may improve performance.
|
| 197 |
+
|
| 198 |
+
Of course, any non-atomic access to a shared variable should be
|
| 199 |
+
documented to explain how that access is protected.
|
| 200 |
+
|
| 201 |
+
Some common patterns that mix atomic and non-atomic access are:
|
| 202 |
+
|
| 203 |
+
* Read-mostly variables where updates are protected by a lock. Within
|
| 204 |
+
the locked region, reads do not need to be atomic, but the write
|
| 205 |
+
does. Outside the locked region, reads need to be atomic.
|
| 206 |
+
|
| 207 |
+
* Reads that only happen during STW, where no writes can happen during
|
| 208 |
+
STW, do not need to be atomic.
|
| 209 |
+
|
| 210 |
+
That said, the advice from the Go memory model stands: "Don't be
|
| 211 |
+
[too] clever." The performance of the runtime matters, but its
|
| 212 |
+
robustness matters more.
|
| 213 |
+
|
| 214 |
+
Unmanaged memory
|
| 215 |
+
================
|
| 216 |
+
|
| 217 |
+
In general, the runtime tries to use regular heap allocation. However,
|
| 218 |
+
in some cases the runtime must allocate objects outside of the garbage
|
| 219 |
+
collected heap, in *unmanaged memory*. This is necessary if the
|
| 220 |
+
objects are part of the memory manager itself or if they must be
|
| 221 |
+
allocated in situations where the caller may not have a P.
|
| 222 |
+
|
| 223 |
+
There are three mechanisms for allocating unmanaged memory:
|
| 224 |
+
|
| 225 |
+
* sysAlloc obtains memory directly from the OS. This comes in whole
|
| 226 |
+
multiples of the system page size, but it can be freed with sysFree.
|
| 227 |
+
|
| 228 |
+
* persistentalloc combines multiple smaller allocations into a single
|
| 229 |
+
sysAlloc to avoid fragmentation. However, there is no way to free
|
| 230 |
+
persistentalloced objects (hence the name).
|
| 231 |
+
|
| 232 |
+
* fixalloc is a SLAB-style allocator that allocates objects of a fixed
|
| 233 |
+
size. fixalloced objects can be freed, but this memory can only be
|
| 234 |
+
reused by the same fixalloc pool, so it can only be reused for
|
| 235 |
+
objects of the same type.
|
| 236 |
+
|
| 237 |
+
In general, types that are allocated using any of these should be
|
| 238 |
+
marked as not in heap by embedding `internal/runtime/sys.NotInHeap`.
|
| 239 |
+
|
| 240 |
+
Objects that are allocated in unmanaged memory **must not** contain
|
| 241 |
+
heap pointers unless the following rules are also obeyed:
|
| 242 |
+
|
| 243 |
+
1. Any pointers from unmanaged memory to the heap must be garbage
|
| 244 |
+
collection roots. More specifically, any pointer must either be
|
| 245 |
+
accessible through a global variable or be added as an explicit
|
| 246 |
+
garbage collection root in `runtime.markroot`.
|
| 247 |
+
|
| 248 |
+
2. If the memory is reused, the heap pointers must be zero-initialized
|
| 249 |
+
before they become visible as GC roots. Otherwise, the GC may
|
| 250 |
+
observe stale heap pointers. See "Zero-initialization versus
|
| 251 |
+
zeroing".
|
| 252 |
+
|
| 253 |
+
Zero-initialization versus zeroing
|
| 254 |
+
==================================
|
| 255 |
+
|
| 256 |
+
There are two types of zeroing in the runtime, depending on whether
|
| 257 |
+
the memory is already initialized to a type-safe state.
|
| 258 |
+
|
| 259 |
+
If memory is not in a type-safe state, meaning it potentially contains
|
| 260 |
+
"garbage" because it was just allocated and it is being initialized
|
| 261 |
+
for first use, then it must be *zero-initialized* using
|
| 262 |
+
`memclrNoHeapPointers` or non-pointer writes. This does not perform
|
| 263 |
+
write barriers.
|
| 264 |
+
|
| 265 |
+
If memory is already in a type-safe state and is simply being set to
|
| 266 |
+
the zero value, this must be done using regular writes, `typedmemclr`,
|
| 267 |
+
or `memclrHasPointers`. This performs write barriers.
|
| 268 |
+
|
| 269 |
+
Linkname conventions
|
| 270 |
+
====================
|
| 271 |
+
|
| 272 |
+
```
|
| 273 |
+
//go:linkname localname [importpath.name]
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
`//go:linkname` specifies the symbol name (`importpath.name`) used to a
|
| 277 |
+
reference a local identifier (`localname`). The target symbol name is an
|
| 278 |
+
arbitrary ELF/macho/etc symbol name, but by convention we typically use a
|
| 279 |
+
package-prefixed symbol name to keep things organized.
|
| 280 |
+
|
| 281 |
+
The full generality of `//go:linkname` is very flexible, so as a convention to
|
| 282 |
+
simplify things, we define three standard forms of `//go:linkname` directives.
|
| 283 |
+
|
| 284 |
+
When possible, always prefer to use the linkname "handshake" described below.
|
| 285 |
+
|
| 286 |
+
"Push linkname"
|
| 287 |
+
---------------
|
| 288 |
+
|
| 289 |
+
A "push" linkname gives a local _definition_ a final symbol name in a different
|
| 290 |
+
package. This effectively "pushes" the symbol to the other package.
|
| 291 |
+
|
| 292 |
+
```
|
| 293 |
+
//go:linkname foo otherpkg.foo
|
| 294 |
+
func foo() {
|
| 295 |
+
// impl
|
| 296 |
+
}
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
The other package needs a _declaration_ to use the symbol from Go, or it can
|
| 300 |
+
directly reference the symbol in assembly. Typically this is an "export
|
| 301 |
+
linkname" declaration (below).
|
| 302 |
+
|
| 303 |
+
"Pull linkname"
|
| 304 |
+
---------------
|
| 305 |
+
|
| 306 |
+
A "pull" linkname gives references to a local _declaration_ a final symbol name
|
| 307 |
+
in a different package. This effectively "pulls" the symbol from the other
|
| 308 |
+
package.
|
| 309 |
+
|
| 310 |
+
```
|
| 311 |
+
//go:linkname foo otherpkg.foo
|
| 312 |
+
func foo()
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
The other package simply needs to define the symbol, but typically this is a
|
| 316 |
+
"export linkname" definition (below).
|
| 317 |
+
|
| 318 |
+
"Export linkname"
|
| 319 |
+
-----------------
|
| 320 |
+
|
| 321 |
+
The second argument to `//go:linkname` is the target symbol name. If it is
|
| 322 |
+
omitted, the toolchain uses the default symbol name. In other words, this is a
|
| 323 |
+
linkname to itself. This seems to be a no-op, but it is used to mean that this
|
| 324 |
+
symbol is "exported" for use with another linkname.
|
| 325 |
+
|
| 326 |
+
```
|
| 327 |
+
//go:linkname foo
|
| 328 |
+
func foo() {
|
| 329 |
+
// impl
|
| 330 |
+
}
|
| 331 |
+
```
|
| 332 |
+
|
| 333 |
+
When applied to a definition, an export linkname indicates that another package
|
| 334 |
+
has a pull linkname targeting this symbol. This has a few effects:
|
| 335 |
+
|
| 336 |
+
- The compiler avoids generates ABI wrappers for ABI0 and/or ABIInternal, so a
|
| 337 |
+
symbol defined in Go can be referenced from assembly in another package, or
|
| 338 |
+
vice versa.
|
| 339 |
+
- The linker will allow pull linknames to this symbol even with
|
| 340 |
+
`-checklinkname=true` (see "Handshake" section below).
|
| 341 |
+
|
| 342 |
+
```
|
| 343 |
+
//go:linkname foo
|
| 344 |
+
func foo()
|
| 345 |
+
```
|
| 346 |
+
|
| 347 |
+
When applied to a declaration, an export linkname indicates that another package
|
| 348 |
+
has a push linkname targeting this symbol. Other than documentation, the only
|
| 349 |
+
effect this has on the toolchain is that the compiler will not require a `.s`
|
| 350 |
+
file in the package (normally the compiler requires a `.s` file when there are
|
| 351 |
+
function declarations without a body).
|
| 352 |
+
|
| 353 |
+
Handshake
|
| 354 |
+
---------
|
| 355 |
+
|
| 356 |
+
We always prefer to use push linknames rather than pull linknames. With a push
|
| 357 |
+
linkname, the package with the definition is aware it is publishing an API to
|
| 358 |
+
another package. On the other hand, with a pull linkname, the definition
|
| 359 |
+
package may be completely unaware of the dependency and may unintentionally
|
| 360 |
+
break users.
|
| 361 |
+
|
| 362 |
+
The preferred form for a linkname is to use a push linkname in the defining
|
| 363 |
+
package, and a target linkname in the receiving package. The latter is not
|
| 364 |
+
strictly required, but serves as documentation. By convention, the receiving
|
| 365 |
+
package names the symbol containing the source package to further aid
|
| 366 |
+
documentation.
|
| 367 |
+
|
| 368 |
+
```
|
| 369 |
+
package runtime
|
| 370 |
+
|
| 371 |
+
//go:linkname foo otherpkg.runtime_foo
|
| 372 |
+
func foo() {
|
| 373 |
+
// impl
|
| 374 |
+
}
|
| 375 |
+
```
|
| 376 |
+
|
| 377 |
+
```
|
| 378 |
+
package otherpkg
|
| 379 |
+
|
| 380 |
+
//go:linkname runtime_foo
|
| 381 |
+
func runtime_foo()
|
| 382 |
+
```
|
| 383 |
+
|
| 384 |
+
As of Go 1.23, the linker forbids pull linknames of symbols in the standard
|
| 385 |
+
library unless they participate in a handshake. Since many third-party packages
|
| 386 |
+
already have pull linknames to standard library functions, for backwards
|
| 387 |
+
compatibility, standard library symbols that are the target of external pull
|
| 388 |
+
linknames must use a target linkname to signal to the linker that pull
|
| 389 |
+
linknames are acceptable.
|
| 390 |
+
|
| 391 |
+
```
|
| 392 |
+
package runtime
|
| 393 |
+
|
| 394 |
+
//go:linkname fastrand
|
| 395 |
+
func fastrand() {
|
| 396 |
+
// impl
|
| 397 |
+
}
|
| 398 |
+
```
|
| 399 |
+
|
| 400 |
+
Note that linker enforcement can be disabled with the `-checklinkname=false`
|
| 401 |
+
flag.
|
| 402 |
+
|
| 403 |
+
Variables
|
| 404 |
+
---------
|
| 405 |
+
|
| 406 |
+
All of the examples above use `//go:linkname` on functions. It is also possible
|
| 407 |
+
to use it on global variables as well, though this is much less common.
|
| 408 |
+
|
| 409 |
+
Variables don't have a clear distinction between definition and declaration. As
|
| 410 |
+
a rule, only one side should have a non-zero initial value. That side is the
|
| 411 |
+
"definition" and the other is the "declaration".
|
| 412 |
+
|
| 413 |
+
Both sides should have the same type, including size. Though if one side is
|
| 414 |
+
larger than another, the linker allocates space for the larger size.
|
| 415 |
+
|
| 416 |
+
Runtime-only compiler directives
|
| 417 |
+
================================
|
| 418 |
+
|
| 419 |
+
In addition to the "//go:" directives documented in "go doc compile",
|
| 420 |
+
the compiler supports additional directives only in the runtime.
|
| 421 |
+
|
| 422 |
+
go:systemstack
|
| 423 |
+
--------------
|
| 424 |
+
|
| 425 |
+
`go:systemstack` indicates that a function must run on the system
|
| 426 |
+
stack. This is checked dynamically by a special function prologue.
|
| 427 |
+
|
| 428 |
+
go:nowritebarrier
|
| 429 |
+
-----------------
|
| 430 |
+
|
| 431 |
+
`go:nowritebarrier` directs the compiler to emit an error if the
|
| 432 |
+
following function contains any write barriers. (It *does not*
|
| 433 |
+
suppress the generation of write barriers; it is simply an assertion.)
|
| 434 |
+
|
| 435 |
+
Usually you want `go:nowritebarrierrec`. `go:nowritebarrier` is
|
| 436 |
+
primarily useful in situations where it's "nice" not to have write
|
| 437 |
+
barriers, but not required for correctness.
|
| 438 |
+
|
| 439 |
+
go:nowritebarrierrec and go:yeswritebarrierrec
|
| 440 |
+
----------------------------------------------
|
| 441 |
+
|
| 442 |
+
`go:nowritebarrierrec` directs the compiler to emit an error if the
|
| 443 |
+
following function or any function it calls recursively, up to a
|
| 444 |
+
`go:yeswritebarrierrec`, contains a write barrier.
|
| 445 |
+
|
| 446 |
+
Logically, the compiler floods the call graph starting from each
|
| 447 |
+
`go:nowritebarrierrec` function and produces an error if it encounters
|
| 448 |
+
a function containing a write barrier. This flood stops at
|
| 449 |
+
`go:yeswritebarrierrec` functions.
|
| 450 |
+
|
| 451 |
+
`go:nowritebarrierrec` is used in the implementation of the write
|
| 452 |
+
barrier to prevent infinite loops.
|
| 453 |
+
|
| 454 |
+
Both directives are used in the scheduler. The write barrier requires
|
| 455 |
+
an active P (`getg().m.p != nil`) and scheduler code often runs
|
| 456 |
+
without an active P. In this case, `go:nowritebarrierrec` is used on
|
| 457 |
+
functions that release the P or may run without a P and
|
| 458 |
+
`go:yeswritebarrierrec` is used when code re-acquires an active P.
|
| 459 |
+
Since these are function-level annotations, code that releases or
|
| 460 |
+
acquires a P may need to be split across two functions.
|
| 461 |
+
|
| 462 |
+
go:uintptrkeepalive
|
| 463 |
+
-------------------
|
| 464 |
+
|
| 465 |
+
The //go:uintptrkeepalive directive must be followed by a function declaration.
|
| 466 |
+
|
| 467 |
+
It specifies that the function's uintptr arguments may be pointer values that
|
| 468 |
+
have been converted to uintptr and must be kept alive for the duration of the
|
| 469 |
+
call, even though from the types alone it would appear that the object is no
|
| 470 |
+
longer needed during the call.
|
| 471 |
+
|
| 472 |
+
This directive is similar to //go:uintptrescapes, but it does not force
|
| 473 |
+
arguments to escape. Since stack growth does not understand these arguments,
|
| 474 |
+
this directive must be used with //go:nosplit (in the marked function and all
|
| 475 |
+
transitive calls) to prevent stack growth.
|
| 476 |
+
|
| 477 |
+
The conversion from pointer to uintptr must appear in the argument list of any
|
| 478 |
+
call to this function. This directive is used for some low-level system call
|
| 479 |
+
implementations.
|
| 480 |
+
|
| 481 |
+
Execution tracer
|
| 482 |
+
================
|
| 483 |
+
|
| 484 |
+
The execution tracer is a way for users to see what their goroutines are doing,
|
| 485 |
+
but they're also useful for runtime hacking.
|
| 486 |
+
|
| 487 |
+
Using execution traces to debug runtime problems
|
| 488 |
+
------------------------------------------------
|
| 489 |
+
|
| 490 |
+
Execution traces contain a wealth of information about what the runtime is
|
| 491 |
+
doing. They contain all goroutine scheduling actions, data about time spent in
|
| 492 |
+
the scheduler (P running without a G), data about time spent in the garbage
|
| 493 |
+
collector, and more. Use `go tool trace` or [gotraceui](https://gotraceui.dev)
|
| 494 |
+
to inspect traces.
|
| 495 |
+
|
| 496 |
+
Traces are especially useful for debugging latency issues, and especially if you
|
| 497 |
+
can catch the problem in the act. Consider using the flight recorder to help
|
| 498 |
+
with this.
|
| 499 |
+
|
| 500 |
+
Turn on CPU profiling when you take a trace. This will put the CPU profiling
|
| 501 |
+
samples as timestamped events into the trace, allowing you to see execution with
|
| 502 |
+
greater detail. If you see CPU profiling sample events appear at a rate that does
|
| 503 |
+
not match the sample rate, consider that the OS or platform might be taking away
|
| 504 |
+
CPU time from the process, and that you might not be debugging a Go issue.
|
| 505 |
+
|
| 506 |
+
If you're really stuck on a problem, adding new instrumentation with the tracer
|
| 507 |
+
might help, especially if it's helpful to see events in relation to other
|
| 508 |
+
scheduling events. See the next section on modifying the execution tracer.
|
| 509 |
+
However, consider using `debuglog` for additional instrumentation first, as that
|
| 510 |
+
is far easier to get started with.
|
| 511 |
+
|
| 512 |
+
Notes on modifying the execution tracer
|
| 513 |
+
---------------------------------------
|
| 514 |
+
|
| 515 |
+
The execution tracer lives in the files whose names start with "trace."
|
| 516 |
+
The parser for the execution trace format lives in the `internal/trace` package.
|
| 517 |
+
|
| 518 |
+
If you plan on adding new trace events, consider starting with a [trace
|
| 519 |
+
experiment](../internal/trace/tracev2/EXPERIMENTS.md).
|
| 520 |
+
|
| 521 |
+
If you plan to add new trace instrumentation to the runtime, read the comment
|
| 522 |
+
at the top of [trace.go](./trace.go), especially the invariants.
|
| 523 |
+
|
| 524 |
+
debuglog
|
| 525 |
+
========
|
| 526 |
+
|
| 527 |
+
`debuglog` is a powerful runtime-only debugging tool. Think of it as an
|
| 528 |
+
ultra-low-overhead `println` that works just about anywhere in the runtime.
|
| 529 |
+
These properties are invaluable when debugging subtle problems in tricky parts
|
| 530 |
+
of the codebase. `println` can often perturb code enough to stop data races from
|
| 531 |
+
happening, while `debuglog` perturbs execution far less.
|
| 532 |
+
|
| 533 |
+
`debuglog` accumulates log messages in a ring buffer on each M, and dumps out
|
| 534 |
+
the contents, ordering it by timestamp, on certain kinds of crashes. Some messages
|
| 535 |
+
might be lost if the ring buffer gets full, in which case consider increasing the
|
| 536 |
+
size, or just work with a partial log.
|
| 537 |
+
|
| 538 |
+
1. Add `debuglog` instrumentation to the runtime. Don't forget to call `end`!
|
| 539 |
+
Example: `dlog().s("hello world").u32(5).end()`
|
| 540 |
+
2. By default, `debuglog` only dumps its contents in certain kinds of crashes.
|
| 541 |
+
Consider adding more calls to `printDebugLog` if you're not getting any output.
|
| 542 |
+
3. Build the program you wish to debug with the `debuglog` build tag.
|
| 543 |
+
|
| 544 |
+
`debuglog` is lower level than execution traces, and much easier to set up.
|
go/src/runtime/Makefile
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2009 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 ../Make.dist
|
go/src/runtime/abi_test.go
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 goexperiment.regabiargs
|
| 6 |
+
|
| 7 |
+
// This file contains tests specific to making sure the register ABI
|
| 8 |
+
// works in a bunch of contexts in the runtime.
|
| 9 |
+
|
| 10 |
+
package runtime_test
|
| 11 |
+
|
| 12 |
+
import (
|
| 13 |
+
"internal/abi"
|
| 14 |
+
"internal/runtime/atomic"
|
| 15 |
+
"internal/testenv"
|
| 16 |
+
"os"
|
| 17 |
+
"os/exec"
|
| 18 |
+
"runtime"
|
| 19 |
+
"strings"
|
| 20 |
+
"testing"
|
| 21 |
+
"time"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
var regConfirmRun atomic.Int32
|
| 25 |
+
|
| 26 |
+
//go:registerparams
|
| 27 |
+
func regFinalizerPointer(v *TintPointer) (int, float32, [10]byte) {
|
| 28 |
+
regConfirmRun.Store(int32(*(*int)(v.p)))
|
| 29 |
+
return 5151, 4.0, [10]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
//go:registerparams
|
| 33 |
+
func regFinalizerIface(v Tinter) (int, float32, [10]byte) {
|
| 34 |
+
regConfirmRun.Store(int32(*(*int)(v.(*TintPointer).p)))
|
| 35 |
+
return 5151, 4.0, [10]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
// TintPointer has a pointer member to make sure that it isn't allocated by the
|
| 39 |
+
// tiny allocator, so we know when its finalizer will run
|
| 40 |
+
type TintPointer struct {
|
| 41 |
+
p *Tint
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func (*TintPointer) m() {}
|
| 45 |
+
|
| 46 |
+
func TestFinalizerRegisterABI(t *testing.T) {
|
| 47 |
+
// Actually run the test in a subprocess because we don't want
|
| 48 |
+
// finalizers from other tests interfering.
|
| 49 |
+
if os.Getenv("TEST_FINALIZER_REGABI") != "1" {
|
| 50 |
+
cmd := testenv.CleanCmdEnv(exec.Command(testenv.Executable(t), "-test.run=^TestFinalizerRegisterABI$", "-test.v"))
|
| 51 |
+
cmd.Env = append(cmd.Env, "TEST_FINALIZER_REGABI=1")
|
| 52 |
+
out, err := cmd.CombinedOutput()
|
| 53 |
+
if !strings.Contains(string(out), "PASS\n") || err != nil {
|
| 54 |
+
t.Fatalf("%s\n(exit status %v)", string(out), err)
|
| 55 |
+
}
|
| 56 |
+
return
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// Optimistically clear any latent finalizers from e.g. the testing
|
| 60 |
+
// package before continuing.
|
| 61 |
+
//
|
| 62 |
+
// It's possible that a finalizer only becomes available to run
|
| 63 |
+
// after this point, which would interfere with the test and could
|
| 64 |
+
// cause a crash, but because we're running in a separate process
|
| 65 |
+
// it's extremely unlikely.
|
| 66 |
+
runtime.GC()
|
| 67 |
+
runtime.GC()
|
| 68 |
+
|
| 69 |
+
// Make sure the finalizer goroutine is running.
|
| 70 |
+
runtime.SetFinalizer(new(TintPointer), func(_ *TintPointer) {})
|
| 71 |
+
|
| 72 |
+
// fing will only pick the new IntRegArgs up if it's currently
|
| 73 |
+
// sleeping and wakes up, so wait for it to go to sleep.
|
| 74 |
+
success := false
|
| 75 |
+
for i := 0; i < 100; i++ {
|
| 76 |
+
if runtime.FinalizerGAsleep() {
|
| 77 |
+
success = true
|
| 78 |
+
break
|
| 79 |
+
}
|
| 80 |
+
time.Sleep(20 * time.Millisecond)
|
| 81 |
+
}
|
| 82 |
+
if !success {
|
| 83 |
+
t.Fatal("finalizer not asleep?")
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
argRegsBefore := runtime.SetIntArgRegs(abi.IntArgRegs)
|
| 87 |
+
defer runtime.SetIntArgRegs(argRegsBefore)
|
| 88 |
+
|
| 89 |
+
tests := []struct {
|
| 90 |
+
name string
|
| 91 |
+
fin any
|
| 92 |
+
confirmValue int
|
| 93 |
+
}{
|
| 94 |
+
{"Pointer", regFinalizerPointer, -1},
|
| 95 |
+
{"Interface", regFinalizerIface, -2},
|
| 96 |
+
}
|
| 97 |
+
for i := range tests {
|
| 98 |
+
test := &tests[i]
|
| 99 |
+
t.Run(test.name, func(t *testing.T) {
|
| 100 |
+
x := &TintPointer{p: new(Tint)}
|
| 101 |
+
*x.p = (Tint)(test.confirmValue)
|
| 102 |
+
runtime.SetFinalizer(x, test.fin)
|
| 103 |
+
|
| 104 |
+
runtime.KeepAlive(x)
|
| 105 |
+
|
| 106 |
+
// Queue the finalizer.
|
| 107 |
+
runtime.GC()
|
| 108 |
+
runtime.GC()
|
| 109 |
+
|
| 110 |
+
if !runtime.BlockUntilEmptyFinalizerQueue(int64(time.Second)) {
|
| 111 |
+
t.Fatal("finalizer failed to execute")
|
| 112 |
+
}
|
| 113 |
+
if got := int(regConfirmRun.Load()); got !=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 runtime
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"internal/abi"
|
| 9 |
+
"internal/byteorder"
|
| 10 |
+
"internal/cpu"
|
| 11 |
+
"internal/goarch"
|
| 12 |
+
"internal/runtime/sys"
|
| 13 |
+
"unsafe"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
const (
|
| 17 |
+
// We use 32-bit hash on Wasm, see hash32.go.
|
| 18 |
+
hashSize = (1-goarch.IsWasm)*goarch.PtrSize + goarch.IsWasm*4
|
| 19 |
+
c0 = uintptr((8-hashSize)/4*2860486313 + (hashSize-4)/4*33054211828000289)
|
| 20 |
+
c1 = uintptr((8-hashSize)/4*3267000013 + (hashSize-4)/4*23344194077549503)
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
func trimHash(h uintptr) uintptr {
|
| 24 |
+
if goarch.IsWasm != 0 {
|
| 25 |
+
// On Wasm, we use 32-bit hash, despite that uintptr is 64-bit.
|
| 26 |
+
// memhash* always returns a uintptr with high 32-bit being 0
|
| 27 |
+
// (see hash32.go). We trim the hash in other places where we
|
| 28 |
+
// compute the hash manually, e.g. in interhash.
|
| 29 |
+
return uintptr(uint32(h))
|
| 30 |
+
}
|
| 31 |
+
return h
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
func memhash0(p unsafe.Pointer, h uintptr) uintptr {
|
| 35 |
+
return h
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
func memhash8(p unsafe.Pointer, h uintptr) uintptr {
|
| 39 |
+
return memhash(p, h, 1)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
func memhash16(p unsafe.Pointer, h uintptr) uintptr {
|
| 43 |
+
return memhash(p, h, 2)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
func memhash128(p unsafe.Pointer, h uintptr) uintptr {
|
| 47 |
+
return memhash(p, h, 16)
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
//go:nosplit
|
| 51 |
+
func memhash_varlen(p unsafe.Pointer, h uintptr) uintptr {
|
| 52 |
+
ptr := sys.GetClosurePtr()
|
| 53 |
+
size := *(*uintptr)(unsafe.Pointer(ptr + unsafe.Sizeof(h)))
|
| 54 |
+
return memhash(p, h, size)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// runtime variable to check if the processor we're running on
|
| 58 |
+
// actually supports the instructions used by the AES-based
|
| 59 |
+
// hash implementation.
|
| 60 |
+
var useAeshash bool
|
| 61 |
+
|
| 62 |
+
// in asm_*.s
|
| 63 |
+
|
| 64 |
+
// memhash should be an internal detail,
|
| 65 |
+
// but widely used packages access it using linkname.
|
| 66 |
+
// Notable members of the hall of shame include:
|
| 67 |
+
// - github.com/aacfactory/fns
|
| 68 |
+
// - github.com/dgraph-io/ristretto
|
| 69 |
+
// - github.com/minio/simdjson-go
|
| 70 |
+
// - github.com/nbd-wtf/go-nostr
|
| 71 |
+
// - github.com/outcaste-io/ristretto
|
| 72 |
+
// - github.com/puzpuzpuz/xsync/v2
|
| 73 |
+
// - github.com/puzpuzpuz/xsync/v3
|
| 74 |
+
// - github.com/authzed/spicedb
|
| 75 |
+
// - github.com/pingcap/badger
|
| 76 |
+
//
|
| 77 |
+
// Do not remove or change the type signature.
|
| 78 |
+
// See go.dev/issue/67401.
|
| 79 |
+
//
|
| 80 |
+
//go:linkname memhash
|
| 81 |
+
func memhash(p unsafe.Pointer, h, s uintptr) uintptr
|
| 82 |
+
|
| 83 |
+
func memhash32(p unsafe.Pointer, h uintptr) uintptr
|
| 84 |
+
|
| 85 |
+
func memhash64(p unsafe.Pointer, h uintptr) uintptr
|
| 86 |
+
|
| 87 |
+
// strhash should be an internal detail,
|
| 88 |
+
// but widely used packages access it using linkname.
|
| 89 |
+
// Notable members of the hall of shame include:
|
| 90 |
+
// - github.com/aristanetworks/goarista
|
| 91 |
+
// - github.com/bytedance/sonic
|
| 92 |
+
// - github.com/bytedance/go-tagexpr/v2
|
| 93 |
+
// - github.com/cloudwego/dynamicgo
|
| 94 |
+
// - github.com/v2fly/v2ray-core/v5
|
| 95 |
+
//
|
| 96 |
+
// Do not remove or change the type signature.
|
| 97 |
+
// See go.dev/issue/67401.
|
| 98 |
+
//
|
| 99 |
+
//go:linkname strhash
|
| 100 |
+
func strhash(p unsafe.Pointer, h uintptr) uintptr
|
| 101 |
+
|
| 102 |
+
func strhashFallback(a unsafe.Pointer, h uintptr) uintptr {
|
| 103 |
+
x := (*stringStruct)(a)
|
| 104 |
+
return memhashFallback(x.str, h, uintptr(x.len))
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// NOTE: Because NaN != NaN, a map can contain any
|
| 108 |
+
// number of (mostly useless) entries keyed with NaNs.
|
| 109 |
+
// To avoid long hash chains, we assign a random number
|
| 110 |
+
// as the hash value for a NaN.
|
| 111 |
+
|
| 112 |
+
func f32hash(p unsafe.Pointer, h uintptr) uintptr {
|
| 113 |
+
f := *(*float32)(p)
|
| 114 |
+
switch {
|
| 115 |
+
case f == 0:
|
| 116 |
+
return trimHash(c1 * (c0 ^ h)) // +0, -0
|
| 117 |
+
case f != f:
|
| 118 |
+
return trimHash(c1 * (c0 ^ h ^ uintptr(rand()))) // any kind of NaN
|
| 119 |
+
default:
|
| 120 |
+
return memhash(p, h, 4)
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
func f64hash(p unsafe.Pointer, h uintptr) uintptr {
|
| 125 |
+
f := *(*float64)(p)
|
| 126 |
+
switch {
|
| 127 |
+
case f == 0:
|
| 128 |
+
return trimHash(c1 * (c0 ^ h)) // +0, -0
|
| 129 |
+
case f != f:
|
| 130 |
+
return trimHash(c1 * (c0 ^ h ^ uintptr(rand()))) // any kind of NaN
|
| 131 |
+
default:
|
| 132 |
+
return memhash(p, h, 8)
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
func c64hash(p unsafe.Pointer, h uintptr) uintptr {
|
| 137 |
+
x := (*[2]float32)(p)
|
| 138 |
+
return f32hash(unsafe.Pointer(&x[1]), f32hash(unsafe.Pointer(&x[0]), h))
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
func c128hash(p unsafe.Pointer, h uintptr) uintptr {
|
| 142 |
+
x := (*[2]float64)(p)
|
| 143 |
+
return f64hash(unsafe.Pointer(&x[1]), f64hash(unsafe.Pointer(&x[0]), h))
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
func interhash(p unsafe.Pointer, h uintptr) uintptr {
|
| 147 |
+
a := (*iface)(p)
|
| 148 |
+
tab := a.tab
|
| 149 |
+
if tab == nil {
|
| 150 |
+
return h
|
| 151 |
+
}
|
| 152 |
+
t := tab.Type
|
| 153 |
+
if t.Equal == nil {
|
| 154 |
+
// Check hashability here. We could do this check inside
|
| 155 |
+
// typehash, but we want to report the topmost type in
|
| 156 |
+
// the error text (e.g. in a struct with a field of slice type
|
| 157 |
+
// we want to report the struct, not the slice).
|
| 158 |
+
panic(errorString("hash of unhashable type " + toRType(t).string()))
|
| 159 |
+
}
|
| 160 |
+
if t.IsDirectIface() {
|
| 161 |
+
return trimHash(c1 * typehash(t, unsafe.Pointer(&a.data), h^c0))
|
| 162 |
+
} else {
|
| 163 |
+
return trimHash(c1 * typehash(t, a.data, h^c0))
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
// nilinterhash should be an internal detail,
|
| 168 |
+
// but widely used packages access it using linkname.
|
| 169 |
+
// Notable members of the hall of shame include:
|
| 170 |
+
// - github.com/anacrolix/stm
|
| 171 |
+
// - github.com/aristanetworks/goarista
|
| 172 |
+
//
|
| 173 |
+
// Do not remove or change the type signature.
|
| 174 |
+
// See go.dev/issue/67401.
|
| 175 |
+
//
|
| 176 |
+
//go:linkname nilinterhash
|
| 177 |
+
func nilinterhash(p unsafe.Pointer, h uintptr) uintptr {
|
| 178 |
+
a := (*eface)(p)
|
| 179 |
+
t := a._type
|
| 180 |
+
if t == nil {
|
| 181 |
+
return h
|
| 182 |
+
}
|
| 183 |
+
if t.Equal == nil {
|
| 184 |
+
// See comment in interhash above.
|
| 185 |
+
panic(errorString("hash of unhashable type " + toRType(t).string()))
|
| 186 |
+
}
|
| 187 |
+
if t.IsDirectIface() {
|
| 188 |
+
return trimHash(c1 * typehash(t, unsafe.Pointer(&a.data), h^c0))
|
| 189 |
+
} else {
|
| 190 |
+
return trimHash(c1 * typehash(t, a.data, h^c0))
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
// typehash computes the hash of the object of type t at address p.
|
| 195 |
+
// h is the seed.
|
| 196 |
+
// This function is seldom used. Most maps use for hashing either
|
| 197 |
+
// fixed functions (e.g. f32hash) or compiler-generated functions
|
| 198 |
+
// (e.g. for a type like struct { x, y string }). This implementation
|
| 199 |
+
// is slower but more general and is used for hashing interface types
|
| 200 |
+
// (called from interhash or nilinterhash, above) or for hashing in
|
| 201 |
+
// maps generated by reflect.MapOf (reflect_typehash, below).
|
| 202 |
+
// Note: this function must match the compiler generated
|
| 203 |
+
// functions exactly. See issue 37716.
|
| 204 |
+
//
|
| 205 |
+
// typehash should be an internal detail,
|
| 206 |
+
// but widely used packages access it using linkname.
|
| 207 |
+
// Notable members of the hall of shame include:
|
| 208 |
+
// - github.com/puzpuzpuz/xsync/v2
|
| 209 |
+
// - github.com/puzpuzpuz/xsync/v3
|
| 210 |
+
//
|
| 211 |
+
// Do not remove or change the type signature.
|
| 212 |
+
// See go.dev/issue/67401.
|
| 213 |
+
//
|
| 214 |
+
//go:linkname typehash
|
| 215 |
+
func typehash(t *_type, p unsafe.Pointer, h uintptr) uintptr {
|
| 216 |
+
if t.TFlag&abi.TFlagRegularMemory != 0 {
|
| 217 |
+
// Handle ptr sizes specially, see issue 37086.
|
| 218 |
+
switch t.Size_ {
|
| 219 |
+
case 4:
|
| 220 |
+
return memhash32(p, h)
|
| 221 |
+
case 8:
|
| 222 |
+
return memhash64(p, h)
|
| 223 |
+
default:
|
| 224 |
+
return memhash(p, h, t.Size_)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
switch t.Kind() {
|
| 228 |
+
case abi.Float32:
|
| 229 |
+
return f32hash(p, h)
|
| 230 |
+
case abi.Float64:
|
| 231 |
+
return f64hash(p, h)
|
| 232 |
+
case abi.Complex64:
|
| 233 |
+
return c64hash(p, h)
|
| 234 |
+
case abi.Complex128:
|
| 235 |
+
return c128hash(p, h)
|
| 236 |
+
case abi.String:
|
| 237 |
+
return strhash(p, h)
|
| 238 |
+
case abi.Interface:
|
| 239 |
+
i := (*interfacetype)(unsafe.Pointer(t))
|
| 240 |
+
if len(i.Methods) == 0 {
|
| 241 |
+
return nilinterhash(p, h)
|
| 242 |
+
}
|
| 243 |
+
return interhash(p, h)
|
| 244 |
+
case abi.Array:
|
| 245 |
+
a := (*arraytype)(unsafe.Pointer(t))
|
| 246 |
+
for i := uintptr(0); i < a.Len; i++ {
|
| 247 |
+
h = typehash(a.Elem, add(p, i*a.Elem.Size_), h)
|
| 248 |
+
}
|
| 249 |
+
return h
|
| 250 |
+
case abi.Struct:
|
| 251 |
+
s := (*structtype)(unsafe.Pointer(t))
|
| 252 |
+
for _, f := range s.Fields {
|
| 253 |
+
if f.Name.IsBlank() {
|
| 254 |
+
continue
|
| 255 |
+
}
|
| 256 |
+
h = typehash(f.Typ, add(p, f.Offset), h)
|
| 257 |
+
}
|
| 258 |
+
return h
|
| 259 |
+
default:
|
| 260 |
+
// Should never happen, as typehash should only be called
|
| 261 |
+
// with comparable types.
|
| 262 |
+
panic(errorString("hash of unhashable type " + toRType(t).string()))
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
//go:linkname reflect_typehash reflect.typehash
|
| 267 |
+
func reflect_typehash(t *_type, p unsafe.Pointer, h uintptr) uintptr {
|
| 268 |
+
return typehash(t, p, h)
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
func memequal0(p, q unsafe.Pointer) bool {
|
| 272 |
+
return true
|
| 273 |
+
}
|
| 274 |
+
func memequal8(p, q unsafe.Pointer) bool {
|
| 275 |
+
return *(*int8)(p) == *(*int8)(q)
|
| 276 |
+
}
|
| 277 |
+
func memequal16(p, q unsafe.Pointer) bool {
|
| 278 |
+
return *(*int16)(p) == *(*int16)(q)
|
| 279 |
+
}
|
| 280 |
+
func memequal32(p, q unsafe.Pointer) bool {
|
| 281 |
+
return *(*int32)(p) == *(*int32)(q)
|
| 282 |
+
}
|
| 283 |
+
func memequal64(p, q unsafe.Pointer) bool {
|
| 284 |
+
return *(*int64)(p) == *(*int64)(q)
|
| 285 |
+
}
|
| 286 |
+
func memequal128(p, q unsafe.Pointer) bool {
|
| 287 |
+
return *(*[2]int64)(p) == *(*[2]int64)(q)
|
| 288 |
+
}
|
| 289 |
+
func f32equal(p, q unsafe.Pointer) bool {
|
| 290 |
+
return *(*float32)(p) == *(*float32)(q)
|
| 291 |
+
}
|
| 292 |
+
func f64equal(p, q unsafe.Pointer) bool {
|
| 293 |
+
return *(*float64)(p) == *(*float64)(q)
|
| 294 |
+
}
|
| 295 |
+
func c64equal(p, q unsafe.Pointer) bool {
|
| 296 |
+
return *(*complex64)(p) == *(*complex64)(q)
|
| 297 |
+
}
|
| 298 |
+
func c128equal(p, q unsafe.Pointer) bool {
|
| 299 |
+
return *(*complex128)(p) == *(*complex128)(q)
|
| 300 |
+
}
|
| 301 |
+
func strequal(p, q unsafe.Pointer) bool {
|
| 302 |
+
return *(*string)(p) == *(*string)(q)
|
| 303 |
+
}
|
| 304 |
+
func interequal(p, q unsafe.Pointer) bool {
|
| 305 |
+
x := *(*iface)(p)
|
| 306 |
+
y := *(*iface)(q)
|
| 307 |
+
return x.tab == y.tab && ifaceeq(x.tab, x.data, y.data)
|
| 308 |
+
}
|
| 309 |
+
func nilinterequal(p, q unsafe.Pointer) bool {
|
| 310 |
+
x := *(*eface)(p)
|
| 311 |
+
y := *(*eface)(q)
|
| 312 |
+
return x._type == y._type && efaceeq(x._type, x.data, y.data)
|
| 313 |
+
}
|
| 314 |
+
func efaceeq(t *_type, x, y unsafe.Pointer) bool {
|
| 315 |
+
if t == nil {
|
| 316 |
+
return true
|
| 317 |
+
}
|
| 318 |
+
eq := t.Equal
|
| 319 |
+
if eq == nil {
|
| 320 |
+
panic(errorString("comparing uncomparable type " + toRType(t).string()))
|
| 321 |
+
}
|
| 322 |
+
if t.IsDirectIface() {
|
| 323 |
+
// Direct interface types are ptr, chan, map, func, and single-element structs/arrays thereof.
|
| 324 |
+
// Maps and funcs are not comparable, so they can't reach here.
|
| 325 |
+
// Ptrs, chans, and single-element items can be compared directly using ==.
|
| 326 |
+
return x == y
|
| 327 |
+
}
|
| 328 |
+
return eq(x, y)
|
| 329 |
+
}
|
| 330 |
+
func ifaceeq(tab *itab, x, y unsafe.Pointer) bool {
|
| 331 |
+
if tab == nil {
|
| 332 |
+
return true
|
| 333 |
+
}
|
| 334 |
+
t := tab.Type
|
| 335 |
+
eq := t.Equal
|
| 336 |
+
if eq == nil {
|
| 337 |
+
panic(errorString("comparing uncomparable type " + toRType(t).string()))
|
| 338 |
+
}
|
| 339 |
+
if t.IsDirectIface() {
|
| 340 |
+
// See comment in efaceeq.
|
| 341 |
+
return x == y
|
| 342 |
+
}
|
| 343 |
+
return eq(x, y)
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// Testing adapters for hash quality tests (see hash_test.go)
|
| 347 |
+
//
|
| 348 |
+
// stringHash should be an internal detail,
|
| 349 |
+
// but widely used packages access it using linkname.
|
| 350 |
+
// Notable members of the hall of shame include:
|
| 351 |
+
// - github.com/k14s/starlark-go
|
| 352 |
+
//
|
| 353 |
+
// Do not remove or change the type signature.
|
| 354 |
+
// See go.dev/issue/67401.
|
| 355 |
+
//
|
| 356 |
+
//go:linkname stringHash
|
| 357 |
+
func stringHash(s string, seed uintptr) uintptr {
|
| 358 |
+
return strhash(noescape(unsafe.Pointer(&s)), seed)
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
func bytesHash(b []byte, seed uintptr) uintptr {
|
| 362 |
+
s := (*slice)(unsafe.Pointer(&b))
|
| 363 |
+
return memhash(s.array, seed, uintptr(s.len))
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
func int32Hash(i uint32, seed uintptr) uintptr {
|
| 367 |
+
return memhash32(noescape(unsafe.Pointer(&i)), seed)
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
func int64Hash(i uint64, seed uintptr) uintptr {
|
| 371 |
+
return memhash64(noescape(unsafe.Pointer(&i)), seed)
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
func efaceHash(i any, seed uintptr) uintptr {
|
| 375 |
+
return nilinterhash(noescape(unsafe.Pointer(&i)), seed)
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
func ifaceHash(i interface {
|
| 379 |
+
F()
|
| 380 |
+
}, seed uintptr) uintptr {
|
| 381 |
+
return interhash(noescape(unsafe.Pointer(&i)), seed)
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
const hashRandomBytes = goarch.PtrSize / 4 * 64
|
| 385 |
+
|
| 386 |
+
// used in asm_{386,amd64,arm64}.s to seed the hash function
|
| 387 |
+
var aeskeysched [hashRandomBytes]byte
|
| 388 |
+
|
| 389 |
+
// used in hash{32,64}.go to seed the hash function
|
| 390 |
+
var hashkey [4]uintptr
|
| 391 |
+
|
| 392 |
+
func alginit() {
|
| 393 |
+
// Install AES hash algorithms if the instructions needed are present.
|
| 394 |
+
if (GOARCH == "386" || GOARCH == "amd64") &&
|
| 395 |
+
cpu.X86.HasAES && // AESENC
|
| 396 |
+
cpu.X86.HasSSSE3 && // PSHUFB
|
| 397 |
+
cpu.X86.HasSSE41 { // PINSR{D,Q}
|
| 398 |
+
initAlgAES()
|
| 399 |
+
return
|
| 400 |
+
}
|
| 401 |
+
if GOARCH == "arm64" && cpu.ARM64.HasAES {
|
| 402 |
+
initAlgAES()
|
| 403 |
+
return
|
| 404 |
+
}
|
| 405 |
+
for i := range hashkey {
|
| 406 |
+
hashkey[i] = uintptr(bootstrapRand())
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
func initAlgAES() {
|
| 411 |
+
useAeshash = true
|
| 412 |
+
// Initialize with random data so hash collisions will be hard to engineer.
|
| 413 |
+
key := (*[hashRandomBytes / 8]uint64)(unsafe.Pointer(&aeskeysched))
|
| 414 |
+
for i := range key {
|
| 415 |
+
key[i] = bootstrapRand()
|
| 416 |
+
}
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
// Note: These routines perform the read with a native endianness.
|
| 420 |
+
func readUnaligned32(p unsafe.Pointer) uint32 {
|
| 421 |
+
q := (*[4]byte)(p)
|
| 422 |
+
if goarch.BigEndian {
|
| 423 |
+
return byteorder.BEUint32(q[:])
|
| 424 |
+
}
|
| 425 |
+
return byteorder.LEUint32(q[:])
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
func readUnaligned64(p unsafe.Pointer) uint64 {
|
| 429 |
+
q := (*[8]byte)(p)
|
| 430 |
+
if goarch.BigEndian {
|
| 431 |
+
return byteorder.BEUint64(q[:])
|
| 432 |
+
}
|
| 433 |
+
return byteorder.LEUint64(q[:])
|
| 434 |
+
}
|
go/src/runtime/align_runtime_test.go
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// This file lives in the runtime package
|
| 6 |
+
// so we can get access to the runtime guts.
|
| 7 |
+
// The rest of the implementation of this test is in align_test.go.
|
| 8 |
+
|
| 9 |
+
package runtime
|
| 10 |
+
|
| 11 |
+
import "unsafe"
|
| 12 |
+
|
| 13 |
+
// AtomicFields is the set of fields on which we perform 64-bit atomic
|
| 14 |
+
// operations (all the *64 operations in internal/runtime/atomic).
|
| 15 |
+
var AtomicFields = []uintptr{
|
| 16 |
+
unsafe.Offsetof(m{}.procid),
|
| 17 |
+
unsafe.Offsetof(profBuf{}.overflow),
|
| 18 |
+
unsafe.Offsetof(profBuf{}.overflowTime),
|
| 19 |
+
unsafe.Offsetof(heapStatsDelta{}.tinyAllocCount),
|
| 20 |
+
unsafe.Offsetof(heapStatsDelta{}.smallAllocCount),
|
| 21 |
+
unsafe.Offsetof(heapStatsDelta{}.smallFreeCount),
|
| 22 |
+
unsafe.Offsetof(heapStatsDelta{}.largeAlloc),
|
| 23 |
+
unsafe.Offsetof(heapStatsDelta{}.largeAllocCount),
|
| 24 |
+
unsafe.Offsetof(heapStatsDelta{}.largeFree),
|
| 25 |
+
unsafe.Offsetof(heapStatsDelta{}.largeFreeCount),
|
| 26 |
+
unsafe.Offsetof(heapStatsDelta{}.committed),
|
| 27 |
+
unsafe.Offsetof(heapStatsDelta{}.released),
|
| 28 |
+
unsafe.Offsetof(heapStatsDelta{}.inHeap),
|
| 29 |
+
unsafe.Offsetof(heapStatsDelta{}.inStacks),
|
| 30 |
+
unsafe.Offsetof(heapStatsDelta{}.inWorkBufs),
|
| 31 |
+
unsafe.Offsetof(lfnode{}.next),
|
| 32 |
+
unsafe.Offsetof(mstats{}.last_gc_nanotime),
|
| 33 |
+
unsafe.Offsetof(mstats{}.last_gc_unix),
|
| 34 |
+
unsafe.Offsetof(workType{}.bytesMarked),
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// AtomicVariables is the set of global variables on which we perform
|
| 38 |
+
// 64-bit atomic operations.
|
| 39 |
+
var AtomicVariables = []unsafe.Pointer{
|
| 40 |
+
unsafe.Pointer(&ncgocall),
|
| 41 |
+
unsafe.Pointer(&test_z64),
|
| 42 |
+
unsafe.Pointer(&blockprofilerate),
|
| 43 |
+
unsafe.Pointer(&mutexprofilerate),
|
| 44 |
+
unsafe.Pointer(&gcController),
|
| 45 |
+
unsafe.Pointer(&memstats),
|
| 46 |
+
unsafe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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 runtime_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"go/ast"
|
| 9 |
+
"go/build"
|
| 10 |
+
"go/importer"
|
| 11 |
+
"go/parser"
|
| 12 |
+
"go/printer"
|
| 13 |
+
"go/token"
|
| 14 |
+
"go/types"
|
| 15 |
+
"internal/testenv"
|
| 16 |
+
"os"
|
| 17 |
+
"regexp"
|
| 18 |
+
"runtime"
|
| 19 |
+
"strings"
|
| 20 |
+
"testing"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
// Check that 64-bit fields on which we apply atomic operations
|
| 24 |
+
// are aligned to 8 bytes. This can be a problem on 32-bit systems.
|
| 25 |
+
func TestAtomicAlignment(t *testing.T) {
|
| 26 |
+
testenv.MustHaveGoBuild(t) // go command needed to resolve std .a files for importer.Default().
|
| 27 |
+
|
| 28 |
+
// Read the code making the tables above, to see which fields and
|
| 29 |
+
// variables we are currently checking.
|
| 30 |
+
checked := map[string]bool{}
|
| 31 |
+
x, err := os.ReadFile("./align_runtime_test.go")
|
| 32 |
+
if err != nil {
|
| 33 |
+
t.Fatalf("read failed: %v", err)
|
| 34 |
+
}
|
| 35 |
+
fieldDesc := map[int]string{}
|
| 36 |
+
r := regexp.MustCompile(`unsafe[.]Offsetof[(](\w+){}[.](\w+)[)]`)
|
| 37 |
+
matches := r.FindAllStringSubmatch(string(x), -1)
|
| 38 |
+
for i, v := range matches {
|
| 39 |
+
checked["field runtime."+v[1]+"."+v[2]] = true
|
| 40 |
+
fieldDesc[i] = v[1] + "." + v[2]
|
| 41 |
+
}
|
| 42 |
+
varDesc := map[int]string{}
|
| 43 |
+
r = regexp.MustCompile(`unsafe[.]Pointer[(]&(\w+)[)]`)
|
| 44 |
+
matches = r.FindAllStringSubmatch(string(x), -1)
|
| 45 |
+
for i, v := range matches {
|
| 46 |
+
checked["var "+v[1]] = true
|
| 47 |
+
varDesc[i] = v[1]
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// Check all of our alignments. This is the actual core of the test.
|
| 51 |
+
for i, d := range runtime.AtomicFields {
|
| 52 |
+
if d%8 != 0 {
|
| 53 |
+
t.Errorf("field alignment of %s failed: offset is %d", fieldDesc[i], d)
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
for i, p := range runtime.AtomicVariables {
|
| 57 |
+
if uintptr(p)%8 != 0 {
|
| 58 |
+
t.Errorf("variable alignment of %s failed: address is %x", varDesc[i], p)
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// The code above is the actual test. The code below attempts to check
|
| 63 |
+
// that the tables used by the code above are exhaustive.
|
| 64 |
+
|
| 65 |
+
// Parse the whole runtime package, checking that arguments of
|
| 66 |
+
// appropriate atomic operations are in the list above.
|
| 67 |
+
fset := token.NewFileSet()
|
| 68 |
+
m, err := parser.ParseDir(fset, ".", nil, 0)
|
| 69 |
+
if err != nil {
|
| 70 |
+
t.Fatalf("parsing runtime failed: %v", err)
|
| 71 |
+
}
|
| 72 |
+
pkg := m["runtime"] // Note: ignore runtime_test and main packages
|
| 73 |
+
|
| 74 |
+
// Filter files by those for the current architecture/os being tested.
|
| 75 |
+
fileMap := map[string]bool{}
|
| 76 |
+
for _, f := range buildableFiles(t, ".") {
|
| 77 |
+
fileMap[f] = true
|
| 78 |
+
}
|
| 79 |
+
var files []*ast.File
|
| 80 |
+
for fname, f := range pkg.Files {
|
| 81 |
+
if fileMap[fname] {
|
| 82 |
+
files = append(files, f)
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
// Call go/types to analyze the runtime package.
|
| 87 |
+
var info types.Info
|
| 88 |
+
info.Types = map[ast.Expr]types.TypeAndValue{}
|
| 89 |
+
conf := types.Config{Importer: importer.Default()}
|
| 90 |
+
_, err = conf.Check("runtime", fset, files, &info)
|
| 91 |
+
if err != nil {
|
| 92 |
+
t.Fatalf("typechecking runtime failed: %v", err)
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Analyze all atomic.*64 callsites.
|
| 96 |
+
v := Visitor{t: t, fset: fset, types: info.Types, checked: checked}
|
| 97 |
+
ast.Walk(&v, pkg)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
type Visitor struct {
|
| 101 |
+
fset *token.FileSet
|
| 102 |
+
types map[ast.Expr]types.TypeAndValue
|
| 103 |
+
checked map[string]bool
|
| 104 |
+
t *testing.T
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func (v *Visitor) Visit(n ast.Node) ast.Visitor {
|
| 108 |
+
c, ok := n.(*ast.CallExpr)
|
| 109 |
+
if !ok {
|
| 110 |
+
return v
|
| 111 |
+
}
|
| 112 |
+
f, ok := c.Fun.(*ast.SelectorExpr)
|
| 113 |
+
if !ok {
|
| 114 |
+
return v
|
| 115 |
+
}
|
| 116 |
+
p, ok := f.X.(*ast.Ident)
|
| 117 |
+
if !ok {
|
| 118 |
+
return v
|
| 119 |
+
}
|
| 120 |
+
if p.Name != "atomic" {
|
| 121 |
+
return v
|
| 122 |
+
}
|
| 123 |
+
if !strings.HasSuffix(f.Sel.Name, "64") {
|
| 124 |
+
return v
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
a := c.Args[0]
|
| 128 |
+
|
| 129 |
+
// This is a call to atomic.XXX64(a, ...). Make sure a is aligned to 8 bytes.
|
| 130 |
+
// XXX = one of Load, Store, Cas, etc.
|
| 131 |
+
// The arg we care about the alignment of is always the first one.
|
| 132 |
+
|
| 133 |
+
if u, ok := a.(*ast.UnaryExpr); ok && u.Op == token.AND {
|
| 134 |
+
v.checkAddr(u.X)
|
| 135 |
+
return v
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
// Other cases there's nothing we can check. Assume we're ok.
|
| 139 |
+
v.t.Logf("unchecked atomic operation %s %v", v.fset.Position(n.Pos()), v.print(n))
|
| 140 |
+
|
| 141 |
+
return v
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// checkAddr checks to make sure n is a properly aligned address for a 64-bit atomic operation.
|
| 145 |
+
func (v *Visitor) checkAddr(n ast.Node) {
|
| 146 |
+
switch n := n.(type) {
|
| 147 |
+
case *ast.IndexExpr:
|
| 148 |
+
// Alignment of an array element is the same as the whole array.
|
| 149 |
+
v.checkAddr(n.X)
|
| 150 |
+
return
|
| 151 |
+
case *ast.Ident:
|
| 152 |
+
key := "var " + v.print(n)
|
| 153 |
+
if !v.checked[key] {
|
| 154 |
+
v.t.Errorf("unchecked variable %s %s", v.fset.Position(n.Pos()), key)
|
| 155 |
+
}
|
| 156 |
+
return
|
| 157 |
+
case *ast.SelectorExpr:
|
| 158 |
+
t := v.types[n.X].Type
|
| 159 |
+
if t == nil {
|
| 160 |
+
// Not sure what is happening here, go/types fails to
|
| 161 |
+
// type the selector arg on some platforms.
|
| 162 |
+
return
|
| 163 |
+
}
|
| 164 |
+
if p, ok := t.(*types.Pointer); ok {
|
| 165 |
+
// Note: we assume here that the pointer p in p.foo is properly
|
| 166 |
+
// aligned. We just check that foo is at a properly aligned offset.
|
| 167 |
+
t = p.Elem()
|
| 168 |
+
} else {
|
| 169 |
+
v.checkAddr(n.X)
|
| 170 |
+
}
|
| 171 |
+
if t.Underlying() == t {
|
| 172 |
+
v.t.Errorf("analysis can't handle unnamed type %s %v", v.fset.Position(n.Pos()), t)
|
| 173 |
+
}
|
| 174 |
+
key := "field " + t.String() + "." + n.Sel.Name
|
| 175 |
+
if !v.checked[key] {
|
| 176 |
+
v.t.Errorf("unchecked field %s %s", v.fset.Position(n.Pos()), key)
|
| 177 |
+
}
|
| 178 |
+
default:
|
| 179 |
+
v.t.Errorf("unchecked atomic address %s %v", v.fset.Position(n.Pos()), v.print(n))
|
| 180 |
+
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
func (v *Visitor) print(n ast.Node) string {
|
| 185 |
+
var b strings.Builder
|
| 186 |
+
printer.Fprint(&b, v.fset, n)
|
| 187 |
+
return b.String()
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
// buildableFiles returns the list of files in the given directory
|
| 191 |
+
// that are actually used for the build, given GOOS/GOARCH restrictions.
|
| 192 |
+
func buildableFiles(t *testing.T, dir string) []string {
|
| 193 |
+
ctxt := build.Default
|
| 194 |
+
ctxt.CgoEnabled = true
|
| 195 |
+
pkg, err := ctxt.ImportDir(dir, 0)
|
| 196 |
+
if err != nil {
|
| 197 |
+
t.Fatalf("can't find buildable files: %v", err)
|
| 198 |
+
}
|
| 199 |
+
return pkg.GoFiles
|
| 200 |
+
}
|
go/src/runtime/arena.go
ADDED
|
@@ -0,0 +1,1130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// Implementation of (safe) user arenas.
|
| 6 |
+
//
|
| 7 |
+
// This file contains the implementation of user arenas wherein Go values can
|
| 8 |
+
// be manually allocated and freed in bulk. The act of manually freeing memory,
|
| 9 |
+
// potentially before a GC cycle, means that a garbage collection cycle can be
|
| 10 |
+
// delayed, improving efficiency by reducing GC cycle frequency. There are other
|
| 11 |
+
// potential efficiency benefits, such as improved locality and access to a more
|
| 12 |
+
// efficient allocation strategy.
|
| 13 |
+
//
|
| 14 |
+
// What makes the arenas here safe is that once they are freed, accessing the
|
| 15 |
+
// arena's memory will cause an explicit program fault, and the arena's address
|
| 16 |
+
// space will not be reused until no more pointers into it are found. There's one
|
| 17 |
+
// exception to this: if an arena allocated memory that isn't exhausted, it's placed
|
| 18 |
+
// back into a pool for reuse. This means that a crash is not always guaranteed.
|
| 19 |
+
//
|
| 20 |
+
// While this may seem unsafe, it still prevents memory corruption, and is in fact
|
| 21 |
+
// necessary in order to make new(T) a valid implementation of arenas. Such a property
|
| 22 |
+
// is desirable to allow for a trivial implementation. (It also avoids complexities
|
| 23 |
+
// that arise from synchronization with the GC when trying to set the arena chunks to
|
| 24 |
+
// fault while the GC is active.)
|
| 25 |
+
//
|
| 26 |
+
// The implementation works in layers. At the bottom, arenas are managed in chunks.
|
| 27 |
+
// Each chunk must be a multiple of the heap arena size, or the heap arena size must
|
| 28 |
+
// be divisible by the arena chunks. The address space for each chunk, and each
|
| 29 |
+
// corresponding heapArena for that address space, are eternally reserved for use as
|
| 30 |
+
// arena chunks. That is, they can never be used for the general heap. Each chunk
|
| 31 |
+
// is also represented by a single mspan, and is modeled as a single large heap
|
| 32 |
+
// allocation. It must be, because each chunk contains ordinary Go values that may
|
| 33 |
+
// point into the heap, so it must be scanned just like any other object. Any
|
| 34 |
+
// pointer into a chunk will therefore always cause the whole chunk to be scanned
|
| 35 |
+
// while its corresponding arena is still live.
|
| 36 |
+
//
|
| 37 |
+
// Chunks may be allocated either from new memory mapped by the OS on our behalf,
|
| 38 |
+
// or by reusing old freed chunks. When chunks are freed, their underlying memory
|
| 39 |
+
// is returned to the OS, set to fault on access, and may not be reused until the
|
| 40 |
+
// program doesn't point into the chunk anymore (the code refers to this state as
|
| 41 |
+
// "quarantined"), a property checked by the GC.
|
| 42 |
+
//
|
| 43 |
+
// The sweeper handles moving chunks out of this quarantine state to be ready for
|
| 44 |
+
// reuse. When the chunk is placed into the quarantine state, its corresponding
|
| 45 |
+
// span is marked as noscan so that the GC doesn't try to scan memory that would
|
| 46 |
+
// cause a fault.
|
| 47 |
+
//
|
| 48 |
+
// At the next layer are the user arenas themselves. They consist of a single
|
| 49 |
+
// active chunk which new Go values are bump-allocated into and a list of chunks
|
| 50 |
+
// that were exhausted when allocating into the arena. Once the arena is freed,
|
| 51 |
+
// it frees all full chunks it references, and places the active one onto a reuse
|
| 52 |
+
// list for a future arena to use. Each arena keeps its list of referenced chunks
|
| 53 |
+
// explicitly live until it is freed. Each user arena also maps to an object which
|
| 54 |
+
// has a finalizer attached that ensures the arena's chunks are all freed even if
|
| 55 |
+
// the arena itself is never explicitly freed.
|
| 56 |
+
//
|
| 57 |
+
// Pointer-ful memory is bump-allocated from low addresses to high addresses in each
|
| 58 |
+
// chunk, while pointer-free memory is bump-allocated from high address to low
|
| 59 |
+
// addresses. The reason for this is to take advantage of a GC optimization wherein
|
| 60 |
+
// the GC will stop scanning an object when there are no more pointers in it, which
|
| 61 |
+
// also allows us to elide clearing the heap bitmap for pointer-free Go values
|
| 62 |
+
// allocated into arenas.
|
| 63 |
+
//
|
| 64 |
+
// Note that arenas are not safe to use concurrently.
|
| 65 |
+
//
|
| 66 |
+
// In summary, there are 2 resources: arenas, and arena chunks. They exist in the
|
| 67 |
+
// following lifecycle:
|
| 68 |
+
//
|
| 69 |
+
// (1) A new arena is created via newArena.
|
| 70 |
+
// (2) Chunks are allocated to hold memory allocated into the arena with new or slice.
|
| 71 |
+
// (a) Chunks are first allocated from the reuse list of partially-used chunks.
|
| 72 |
+
// (b) If there are no such chunks, then chunks on the ready list are taken.
|
| 73 |
+
// (c) Failing all the above, memory for a new chunk is mapped.
|
| 74 |
+
// (3) The arena is freed, or all references to it are dropped, triggering its finalizer.
|
| 75 |
+
// (a) If the GC is not active, exhausted chunks are set to fault and placed on a
|
| 76 |
+
// quarantine list.
|
| 77 |
+
// (b) If the GC is active, exhausted chunks are placed on a fault list and will
|
| 78 |
+
// go through step (a) at a later point in time.
|
| 79 |
+
// (c) Any remaining partially-used chunk is placed on a reuse list.
|
| 80 |
+
// (4) Once no more pointers are found into quarantined arena chunks, the sweeper
|
| 81 |
+
// takes these chunks out of quarantine and places them on the ready list.
|
| 82 |
+
|
| 83 |
+
package runtime
|
| 84 |
+
|
| 85 |
+
import (
|
| 86 |
+
"internal/abi"
|
| 87 |
+
"internal/goarch"
|
| 88 |
+
"internal/runtime/atomic"
|
| 89 |
+
"internal/runtime/math"
|
| 90 |
+
"internal/runtime/sys"
|
| 91 |
+
"unsafe"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
// Functions starting with arena_ are meant to be exported to downstream users
|
| 95 |
+
// of arenas. They should wrap these functions in a higher-lever API.
|
| 96 |
+
//
|
| 97 |
+
// The underlying arena and its resources are managed through an opaque unsafe.Pointer.
|
| 98 |
+
|
| 99 |
+
// arena_newArena is a wrapper around newUserArena.
|
| 100 |
+
//
|
| 101 |
+
//go:linkname arena_newArena arena.runtime_arena_newArena
|
| 102 |
+
func arena_newArena() unsafe.Pointer {
|
| 103 |
+
return unsafe.Pointer(newUserArena())
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
// arena_arena_New is a wrapper around (*userArena).new, except that typ
|
| 107 |
+
// is an any (must be a *_type, still) and typ must be a type descriptor
|
| 108 |
+
// for a pointer to the type to actually be allocated, i.e. pass a *T
|
| 109 |
+
// to allocate a T. This is necessary because this function returns a *T.
|
| 110 |
+
//
|
| 111 |
+
//go:linkname arena_arena_New arena.runtime_arena_arena_New
|
| 112 |
+
func arena_arena_New(arena unsafe.Pointer, typ any) any {
|
| 113 |
+
t := (*_type)(efaceOf(&typ).data)
|
| 114 |
+
if t.Kind() != abi.Pointer {
|
| 115 |
+
throw("arena_New: non-pointer type")
|
| 116 |
+
}
|
| 117 |
+
te := (*ptrtype)(unsafe.Pointer(t)).Elem
|
| 118 |
+
x := ((*userArena)(arena)).new(te)
|
| 119 |
+
var result any
|
| 120 |
+
e := efaceOf(&result)
|
| 121 |
+
e._type = t
|
| 122 |
+
e.data = x
|
| 123 |
+
return result
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// arena_arena_Slice is a wrapper around (*userArena).slice.
|
| 127 |
+
//
|
| 128 |
+
//go:linkname arena_arena_Slice arena.runtime_arena_arena_Slice
|
| 129 |
+
func arena_arena_Slice(arena unsafe.Pointer, slice any, cap int) {
|
| 130 |
+
((*userArena)(arena)).slice(slice, cap)
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
// arena_arena_Free is a wrapper around (*userArena).free.
|
| 134 |
+
//
|
| 135 |
+
//go:linkname arena_arena_Free arena.runtime_arena_arena_Free
|
| 136 |
+
func arena_arena_Free(arena unsafe.Pointer) {
|
| 137 |
+
((*userArena)(arena)).free()
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// arena_heapify takes a value that lives in an arena and makes a copy
|
| 141 |
+
// of it on the heap. Values that don't live in an arena are returned unmodified.
|
| 142 |
+
//
|
| 143 |
+
//go:linkname arena_heapify arena.runtime_arena_heapify
|
| 144 |
+
func arena_heapify(s any) any {
|
| 145 |
+
var v unsafe.Pointer
|
| 146 |
+
e := efaceOf(&s)
|
| 147 |
+
t := e._type
|
| 148 |
+
switch t.Kind() {
|
| 149 |
+
case abi.String:
|
| 150 |
+
v = stringStructOf((*string)(e.data)).str
|
| 151 |
+
case abi.Slice:
|
| 152 |
+
v = (*slice)(e.data).array
|
| 153 |
+
case abi.Pointer:
|
| 154 |
+
v = e.data
|
| 155 |
+
default:
|
| 156 |
+
panic("arena: Clone only supports pointers, slices, and strings")
|
| 157 |
+
}
|
| 158 |
+
span := spanOf(uintptr(v))
|
| 159 |
+
if span == nil || !span.isUserArenaChunk {
|
| 160 |
+
// Not stored in a user arena chunk.
|
| 161 |
+
return s
|
| 162 |
+
}
|
| 163 |
+
// Heap-allocate storage for a copy.
|
| 164 |
+
var x any
|
| 165 |
+
switch t.Kind() {
|
| 166 |
+
case abi.String:
|
| 167 |
+
s1 := s.(string)
|
| 168 |
+
s2, b := rawstring(len(s1))
|
| 169 |
+
copy(b, s1)
|
| 170 |
+
x = s2
|
| 171 |
+
case abi.Slice:
|
| 172 |
+
len := (*slice)(e.data).len
|
| 173 |
+
et := (*slicetype)(unsafe.Pointer(t)).Elem
|
| 174 |
+
sl := new(slice)
|
| 175 |
+
*sl = slice{makeslicecopy(et, len, len, (*slice)(e.data).array), len, len}
|
| 176 |
+
xe := efaceOf(&x)
|
| 177 |
+
xe._type = t
|
| 178 |
+
xe.data = unsafe.Pointer(sl)
|
| 179 |
+
case abi.Pointer:
|
| 180 |
+
et := (*ptrtype)(unsafe.Pointer(t)).Elem
|
| 181 |
+
e2 := newobject(et)
|
| 182 |
+
typedmemmove(et, e2, e.data)
|
| 183 |
+
xe := efaceOf(&x)
|
| 184 |
+
xe._type = t
|
| 185 |
+
xe.data = e2
|
| 186 |
+
}
|
| 187 |
+
return x
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
const (
|
| 191 |
+
// userArenaChunkBytes is the size of a user arena chunk.
|
| 192 |
+
userArenaChunkBytesMax = 8 << 20
|
| 193 |
+
userArenaChunkBytes = uintptr(int64(userArenaChunkBytesMax-heapArenaBytes)&(int64(userArenaChunkBytesMax-heapArenaBytes)>>63) + heapArenaBytes) // min(userArenaChunkBytesMax, heapArenaBytes)
|
| 194 |
+
|
| 195 |
+
// userArenaChunkPages is the number of pages a user arena chunk uses.
|
| 196 |
+
userArenaChunkPages = userArenaChunkBytes / pageSize
|
| 197 |
+
|
| 198 |
+
// userArenaChunkMaxAllocBytes is the maximum size of an object that can
|
| 199 |
+
// be allocated from an arena. This number is chosen to cap worst-case
|
| 200 |
+
// fragmentation of user arenas to 25%. Larger allocations are redirected
|
| 201 |
+
// to the heap.
|
| 202 |
+
userArenaChunkMaxAllocBytes = userArenaChunkBytes / 4
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
func init() {
|
| 206 |
+
if userArenaChunkPages*pageSize != userArenaChunkBytes {
|
| 207 |
+
throw("user arena chunk size is not a multiple of the page size")
|
| 208 |
+
}
|
| 209 |
+
if userArenaChunkBytes%physPageSize != 0 {
|
| 210 |
+
throw("user arena chunk size is not a multiple of the physical page size")
|
| 211 |
+
}
|
| 212 |
+
if userArenaChunkBytes < heapArenaBytes {
|
| 213 |
+
if heapArenaBytes%userArenaChunkBytes != 0 {
|
| 214 |
+
throw("user arena chunk size is smaller than a heap arena, but doesn't divide it")
|
| 215 |
+
}
|
| 216 |
+
} else {
|
| 217 |
+
if userArenaChunkBytes%heapArenaBytes != 0 {
|
| 218 |
+
throw("user arena chunks size is larger than a heap arena, but not a multiple")
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
lockInit(&userArenaState.lock, lockRankUserArenaState)
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
// userArenaChunkReserveBytes returns the amount of additional bytes to reserve for
|
| 225 |
+
// heap metadata.
|
| 226 |
+
func userArenaChunkReserveBytes() uintptr {
|
| 227 |
+
// In the allocation headers experiment, we reserve the end of the chunk for
|
| 228 |
+
// a pointer/scalar bitmap. We also reserve space for a dummy _type that
|
| 229 |
+
// refers to the bitmap. The PtrBytes field of the dummy _type indicates how
|
| 230 |
+
// many of those bits are valid.
|
| 231 |
+
return userArenaChunkBytes/goarch.PtrSize/8 + unsafe.Sizeof(_type{})
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
type userArena struct {
|
| 235 |
+
// fullList is a list of full chunks that have not enough free memory left, and
|
| 236 |
+
// that we'll free once this user arena is freed.
|
| 237 |
+
//
|
| 238 |
+
// Can't use mSpanList here because it's not-in-heap.
|
| 239 |
+
fullList *mspan
|
| 240 |
+
|
| 241 |
+
// active is the user arena chunk we're currently allocating into.
|
| 242 |
+
active *mspan
|
| 243 |
+
|
| 244 |
+
// refs is a set of references to the arena chunks so that they're kept alive.
|
| 245 |
+
//
|
| 246 |
+
// The last reference in the list always refers to active, while the rest of
|
| 247 |
+
// them correspond to fullList. Specifically, the head of fullList is the
|
| 248 |
+
// second-to-last one, fullList.next is the third-to-last, and so on.
|
| 249 |
+
//
|
| 250 |
+
// In other words, every time a new chunk becomes active, its appended to this
|
| 251 |
+
// list.
|
| 252 |
+
refs []unsafe.Pointer
|
| 253 |
+
|
| 254 |
+
// defunct is true if free has been called on this arena.
|
| 255 |
+
//
|
| 256 |
+
// This is just a best-effort way to discover a concurrent allocation
|
| 257 |
+
// and free. Also used to detect a double-free.
|
| 258 |
+
defunct atomic.Bool
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
// newUserArena creates a new userArena ready to be used.
|
| 262 |
+
func newUserArena() *userArena {
|
| 263 |
+
a := new(userArena)
|
| 264 |
+
SetFinalizer(a, func(a *userArena) {
|
| 265 |
+
// If arena handle is dropped without being freed, then call
|
| 266 |
+
// free on the arena, so the arena chunks are never reclaimed
|
| 267 |
+
// by the garbage collector.
|
| 268 |
+
a.free()
|
| 269 |
+
})
|
| 270 |
+
a.refill()
|
| 271 |
+
return a
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
// new allocates a new object of the provided type into the arena, and returns
|
| 275 |
+
// its pointer.
|
| 276 |
+
//
|
| 277 |
+
// This operation is not safe to call concurrently with other operations on the
|
| 278 |
+
// same arena.
|
| 279 |
+
func (a *userArena) new(typ *_type) unsafe.Pointer {
|
| 280 |
+
return a.alloc(typ, -1)
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
// slice allocates a new slice backing store. slice must be a pointer to a slice
|
| 284 |
+
// (i.e. *[]T), because userArenaSlice will update the slice directly.
|
| 285 |
+
//
|
| 286 |
+
// cap determines the capacity of the slice backing store and must be non-negative.
|
| 287 |
+
//
|
| 288 |
+
// This operation is not safe to call concurrently with other operations on the
|
| 289 |
+
// same arena.
|
| 290 |
+
func (a *userArena) slice(sl any, cap int) {
|
| 291 |
+
if cap < 0 {
|
| 292 |
+
panic("userArena.slice: negative cap")
|
| 293 |
+
}
|
| 294 |
+
i := efaceOf(&sl)
|
| 295 |
+
typ := i._type
|
| 296 |
+
if typ.Kind() != abi.Pointer {
|
| 297 |
+
panic("slice result of non-ptr type")
|
| 298 |
+
}
|
| 299 |
+
typ = (*ptrtype)(unsafe.Pointer(typ)).Elem
|
| 300 |
+
if typ.Kind() != abi.Slice {
|
| 301 |
+
panic("slice of non-ptr-to-slice type")
|
| 302 |
+
}
|
| 303 |
+
typ = (*slicetype)(unsafe.Pointer(typ)).Elem
|
| 304 |
+
// t is now the element type of the slice we want to allocate.
|
| 305 |
+
|
| 306 |
+
*((*slice)(i.data)) = slice{a.alloc(typ, cap), cap, cap}
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
// free returns the userArena's chunks back to mheap and marks it as defunct.
|
| 310 |
+
//
|
| 311 |
+
// Must be called at most once for any given arena.
|
| 312 |
+
//
|
| 313 |
+
// This operation is not safe to call concurrently with other operations on the
|
| 314 |
+
// same arena.
|
| 315 |
+
func (a *userArena) free() {
|
| 316 |
+
// Check for a double-free.
|
| 317 |
+
if a.defunct.Load() {
|
| 318 |
+
panic("arena double free")
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
// Mark ourselves as defunct.
|
| 322 |
+
a.defunct.Store(true)
|
| 323 |
+
SetFinalizer(a, nil)
|
| 324 |
+
|
| 325 |
+
// Free all the full arenas.
|
| 326 |
+
//
|
| 327 |
+
// The refs on this list are in reverse order from the second-to-last.
|
| 328 |
+
s := a.fullList
|
| 329 |
+
i := len(a.refs) - 2
|
| 330 |
+
for s != nil {
|
| 331 |
+
a.fullList = s.next
|
| 332 |
+
s.next = nil
|
| 333 |
+
freeUserArenaChunk(s, a.refs[i])
|
| 334 |
+
s = a.fullList
|
| 335 |
+
i--
|
| 336 |
+
}
|
| 337 |
+
if a.fullList != nil || i >= 0 {
|
| 338 |
+
// There's still something left on the full list, or we
|
| 339 |
+
// failed to actually iterate over the entire refs list.
|
| 340 |
+
throw("full list doesn't match refs list in length")
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
// Put the active chunk onto the reuse list.
|
| 344 |
+
//
|
| 345 |
+
// Note that active's reference is always the last reference in refs.
|
| 346 |
+
s = a.active
|
| 347 |
+
if s != nil {
|
| 348 |
+
if raceenabled || msanenabled || asanenabled {
|
| 349 |
+
// Don't reuse arenas with sanitizers enabled. We want to catch
|
| 350 |
+
// any use-after-free errors aggressively.
|
| 351 |
+
freeUserArenaChunk(s, a.refs[len(a.refs)-1])
|
| 352 |
+
} else {
|
| 353 |
+
lock(&userArenaState.lock)
|
| 354 |
+
userArenaState.reuse = append(userArenaState.reuse, liveUserArenaChunk{s, a.refs[len(a.refs)-1]})
|
| 355 |
+
unlock(&userArenaState.lock)
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
// nil out a.active so that a race with freeing will more likely cause a crash.
|
| 359 |
+
a.active = nil
|
| 360 |
+
a.refs = nil
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
// alloc reserves space in the current chunk or calls refill and reserves space
|
| 364 |
+
// in a new chunk. If cap is negative, the type will be taken literally, otherwise
|
| 365 |
+
// it will be considered as an element type for a slice backing store with capacity
|
| 366 |
+
// cap.
|
| 367 |
+
func (a *userArena) alloc(typ *_type, cap int) unsafe.Pointer {
|
| 368 |
+
s := a.active
|
| 369 |
+
var x unsafe.Pointer
|
| 370 |
+
for {
|
| 371 |
+
x = s.userArenaNextFree(typ, cap)
|
| 372 |
+
if x != nil {
|
| 373 |
+
break
|
| 374 |
+
}
|
| 375 |
+
s = a.refill()
|
| 376 |
+
}
|
| 377 |
+
return x
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
// refill inserts the current arena chunk onto the full list and obtains a new
|
| 381 |
+
// one, either from the partial list or allocating a new one, both from mheap.
|
| 382 |
+
func (a *userArena) refill() *mspan {
|
| 383 |
+
// If there's an active chunk, assume it's full.
|
| 384 |
+
s := a.active
|
| 385 |
+
if s != nil {
|
| 386 |
+
if s.userArenaChunkFree.size() > userArenaChunkMaxAllocBytes {
|
| 387 |
+
// It's difficult to tell when we're actually out of memory
|
| 388 |
+
// in a chunk because the allocation that failed may still leave
|
| 389 |
+
// some free space available. However, that amount of free space
|
| 390 |
+
// should never exceed the maximum allocation size.
|
| 391 |
+
throw("wasted too much memory in an arena chunk")
|
| 392 |
+
}
|
| 393 |
+
s.next = a.fullList
|
| 394 |
+
a.fullList = s
|
| 395 |
+
a.active = nil
|
| 396 |
+
s = nil
|
| 397 |
+
}
|
| 398 |
+
var x unsafe.Pointer
|
| 399 |
+
|
| 400 |
+
// Check the partially-used list.
|
| 401 |
+
lock(&userArenaState.lock)
|
| 402 |
+
if len(userArenaState.reuse) > 0 {
|
| 403 |
+
// Pick off the last arena chunk from the list.
|
| 404 |
+
n := len(userArenaState.reuse) - 1
|
| 405 |
+
x = userArenaState.reuse[n].x
|
| 406 |
+
s = userArenaState.reuse[n].mspan
|
| 407 |
+
userArenaState.reuse[n].x = nil
|
| 408 |
+
userArenaState.reuse[n].mspan = nil
|
| 409 |
+
userArenaState.reuse = userArenaState.reuse[:n]
|
| 410 |
+
}
|
| 411 |
+
unlock(&userArenaState.lock)
|
| 412 |
+
if s == nil {
|
| 413 |
+
// Allocate a new one.
|
| 414 |
+
x, s = newUserArenaChunk()
|
| 415 |
+
if s == nil {
|
| 416 |
+
throw("out of memory")
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
a.refs = append(a.refs, x)
|
| 420 |
+
a.active = s
|
| 421 |
+
return s
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
type liveUserArenaChunk struct {
|
| 425 |
+
*mspan // Must represent a user arena chunk.
|
| 426 |
+
|
| 427 |
+
// Reference to mspan.base() to keep the chunk alive.
|
| 428 |
+
x unsafe.Pointer
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
var userArenaState struct {
|
| 432 |
+
lock mutex
|
| 433 |
+
|
| 434 |
+
// reuse contains a list of partially-used and already-live
|
| 435 |
+
// user arena chunks that can be quickly reused for another
|
| 436 |
+
// arena.
|
| 437 |
+
//
|
| 438 |
+
// Protected by lock.
|
| 439 |
+
reuse []liveUserArenaChunk
|
| 440 |
+
|
| 441 |
+
// fault contains full user arena chunks that need to be faulted.
|
| 442 |
+
//
|
| 443 |
+
// Protected by lock.
|
| 444 |
+
fault []liveUserArenaChunk
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
// userArenaNextFree reserves space in the user arena for an item of the specified
|
| 448 |
+
// type. If cap is not -1, this is for an array of cap elements of type t.
|
| 449 |
+
func (s *mspan) userArenaNextFree(typ *_type, cap int) unsafe.Pointer {
|
| 450 |
+
size := typ.Size_
|
| 451 |
+
if cap > 0 {
|
| 452 |
+
if size > ^uintptr(0)/uintptr(cap) {
|
| 453 |
+
// Overflow.
|
| 454 |
+
throw("out of memory")
|
| 455 |
+
}
|
| 456 |
+
size *= uintptr(cap)
|
| 457 |
+
}
|
| 458 |
+
if size == 0 || cap == 0 {
|
| 459 |
+
return unsafe.Pointer(&zerobase)
|
| 460 |
+
}
|
| 461 |
+
if size > userArenaChunkMaxAllocBytes {
|
| 462 |
+
// Redirect allocations that don't fit into a chunk well directly
|
| 463 |
+
// from the heap.
|
| 464 |
+
if cap >= 0 {
|
| 465 |
+
return newarray(typ, cap)
|
| 466 |
+
}
|
| 467 |
+
return newobject(typ)
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
// Prevent preemption as we set up the space for a new object.
|
| 471 |
+
//
|
| 472 |
+
// Act like we're allocating.
|
| 473 |
+
mp := acquirem()
|
| 474 |
+
if mp.mallocing != 0 {
|
| 475 |
+
throw("malloc deadlock")
|
| 476 |
+
}
|
| 477 |
+
if mp.gsignal == getg() {
|
| 478 |
+
throw("malloc during signal")
|
| 479 |
+
}
|
| 480 |
+
mp.mallocing = 1
|
| 481 |
+
|
| 482 |
+
var ptr unsafe.Pointer
|
| 483 |
+
if !typ.Pointers() {
|
| 484 |
+
// Allocate pointer-less objects from the tail end of the chunk.
|
| 485 |
+
v, ok := s.userArenaChunkFree.takeFromBack(size, typ.Align_)
|
| 486 |
+
if ok {
|
| 487 |
+
ptr = unsafe.Pointer(v)
|
| 488 |
+
}
|
| 489 |
+
} else {
|
| 490 |
+
v, ok := s.userArenaChunkFree.takeFromFront(size, typ.Align_)
|
| 491 |
+
if ok {
|
| 492 |
+
ptr = unsafe.Pointer(v)
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
if ptr == nil {
|
| 496 |
+
// Failed to allocate.
|
| 497 |
+
mp.mallocing = 0
|
| 498 |
+
releasem(mp)
|
| 499 |
+
return nil
|
| 500 |
+
}
|
| 501 |
+
if s.needzero != 0 {
|
| 502 |
+
throw("arena chunk needs zeroing, but should already be zeroed")
|
| 503 |
+
}
|
| 504 |
+
// Set up heap bitmap and do extra accounting.
|
| 505 |
+
if typ.Pointers() {
|
| 506 |
+
if cap >= 0 {
|
| 507 |
+
userArenaHeapBitsSetSliceType(typ, cap, ptr, s)
|
| 508 |
+
} else {
|
| 509 |
+
userArenaHeapBitsSetType(typ, ptr, s)
|
| 510 |
+
}
|
| 511 |
+
c := getMCache(mp)
|
| 512 |
+
if c == nil {
|
| 513 |
+
throw("mallocgc called without a P or outside bootstrapping")
|
| 514 |
+
}
|
| 515 |
+
if cap > 0 {
|
| 516 |
+
c.scanAlloc += size - (typ.Size_ - typ.PtrBytes)
|
| 517 |
+
} else {
|
| 518 |
+
c.scanAlloc += typ.PtrBytes
|
| 519 |
+
}
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
// Ensure that the stores above that initialize x to
|
| 523 |
+
// type-safe memory and set the heap bits occur before
|
| 524 |
+
// the caller can make ptr observable to the garbage
|
| 525 |
+
// collector. Otherwise, on weakly ordered machines,
|
| 526 |
+
// the garbage collector could follow a pointer to x,
|
| 527 |
+
// but see uninitialized memory or stale heap bits.
|
| 528 |
+
publicationBarrier()
|
| 529 |
+
|
| 530 |
+
mp.mallocing = 0
|
| 531 |
+
releasem(mp)
|
| 532 |
+
|
| 533 |
+
return ptr
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
// userArenaHeapBitsSetSliceType is the equivalent of heapBitsSetType but for
|
| 537 |
+
// Go slice backing store values allocated in a user arena chunk. It sets up the
|
| 538 |
+
// heap bitmap for n consecutive values with type typ allocated at address ptr.
|
| 539 |
+
func userArenaHeapBitsSetSliceType(typ *_type, n int, ptr unsafe.Pointer, s *mspan) {
|
| 540 |
+
mem, overflow := math.MulUintptr(typ.Size_, uintptr(n))
|
| 541 |
+
if overflow || n < 0 || mem > maxAlloc {
|
| 542 |
+
panic(plainError("runtime: allocation size out of range"))
|
| 543 |
+
}
|
| 544 |
+
for i := 0; i < n; i++ {
|
| 545 |
+
userArenaHeapBitsSetType(typ, add(ptr, uintptr(i)*typ.Size_), s)
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
// userArenaHeapBitsSetType is the equivalent of heapSetType but for
|
| 550 |
+
// non-slice-backing-store Go values allocated in a user arena chunk. It
|
| 551 |
+
// sets up the type metadata for the value with type typ allocated at address ptr.
|
| 552 |
+
// base is the base address of the arena chunk.
|
| 553 |
+
func userArenaHeapBitsSetType(typ *_type, ptr unsafe.Pointer, s *mspan) {
|
| 554 |
+
base := s.base()
|
| 555 |
+
h := s.writeUserArenaHeapBits(uintptr(ptr))
|
| 556 |
+
|
| 557 |
+
p := getGCMask(typ) // start of 1-bit pointer mask
|
| 558 |
+
nb := typ.PtrBytes / goarch.PtrSize
|
| 559 |
+
|
| 560 |
+
for i := uintptr(0); i < nb; i += ptrBits {
|
| 561 |
+
k := nb - i
|
| 562 |
+
if k > ptrBits {
|
| 563 |
+
k = ptrBits
|
| 564 |
+
}
|
| 565 |
+
// N.B. On big endian platforms we byte swap the data that we
|
| 566 |
+
// read from GCData, which is always stored in little-endian order
|
| 567 |
+
// by the compiler. writeUserArenaHeapBits handles data in
|
| 568 |
+
// a platform-ordered way for efficiency, but stores back the
|
| 569 |
+
// data in little endian order, since we expose the bitmap through
|
| 570 |
+
// a dummy type.
|
| 571 |
+
h = h.write(s, readUintptr(addb(p, i/8)), k)
|
| 572 |
+
}
|
| 573 |
+
// Note: we call pad here to ensure we emit explicit 0 bits
|
| 574 |
+
// for the pointerless tail of the object. This ensures that
|
| 575 |
+
// there's only a single noMorePtrs mark for the next object
|
| 576 |
+
// to clear. We don't need to do this to clear stale noMorePtrs
|
| 577 |
+
// markers from previous uses because arena chunk pointer bitmaps
|
| 578 |
+
// are always fully cleared when reused.
|
| 579 |
+
h = h.pad(s, typ.Size_-typ.PtrBytes)
|
| 580 |
+
h.flush(s, uintptr(ptr), typ.Size_)
|
| 581 |
+
|
| 582 |
+
// Update the PtrBytes value in the type information. After this
|
| 583 |
+
// point, the GC will observe the new bitmap.
|
| 584 |
+
s.largeType.PtrBytes = uintptr(ptr) - base + typ.PtrBytes
|
| 585 |
+
|
| 586 |
+
// Double-check that the bitmap was written out correctly.
|
| 587 |
+
const doubleCheck = false
|
| 588 |
+
if doubleCheck {
|
| 589 |
+
doubleCheckHeapPointersInterior(uintptr(ptr), uintptr(ptr), typ.Size_, typ.Size_, typ, &s.largeType, s)
|
| 590 |
+
}
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
type writeUserArenaHeapBits struct {
|
| 594 |
+
offset uintptr // offset in span that the low bit of mask represents the pointer state of.
|
| 595 |
+
mask uintptr // some pointer bits starting at the address addr.
|
| 596 |
+
valid uintptr // number of bits in buf that are valid (including low)
|
| 597 |
+
low uintptr // number of low-order bits to not overwrite
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
func (s *mspan) writeUserArenaHeapBits(addr uintptr) (h writeUserArenaHeapBits) {
|
| 601 |
+
offset := addr - s.base()
|
| 602 |
+
|
| 603 |
+
// We start writing bits maybe in the middle of a heap bitmap word.
|
| 604 |
+
// Remember how many bits into the word we started, so we can be sure
|
| 605 |
+
// not to overwrite the previous bits.
|
| 606 |
+
h.low = offset / goarch.PtrSize % ptrBits
|
| 607 |
+
|
| 608 |
+
// round down to heap word that starts the bitmap word.
|
| 609 |
+
h.offset = offset - h.low*goarch.PtrSize
|
| 610 |
+
|
| 611 |
+
// We don't have any bits yet.
|
| 612 |
+
h.mask = 0
|
| 613 |
+
h.valid = h.low
|
| 614 |
+
|
| 615 |
+
return
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
// write appends the pointerness of the next valid pointer slots
|
| 619 |
+
// using the low valid bits of bits. 1=pointer, 0=scalar.
|
| 620 |
+
func (h writeUserArenaHeapBits) write(s *mspan, bits, valid uintptr) writeUserArenaHeapBits {
|
| 621 |
+
if h.valid+valid <= ptrBits {
|
| 622 |
+
// Fast path - just accumulate the bits.
|
| 623 |
+
h.mask |= bits << h.valid
|
| 624 |
+
h.valid += valid
|
| 625 |
+
return h
|
| 626 |
+
}
|
| 627 |
+
// Too many bits to fit in this word. Write the current word
|
| 628 |
+
// out and move on to the next word.
|
| 629 |
+
|
| 630 |
+
data := h.mask | bits<<h.valid // mask for this word
|
| 631 |
+
h.mask = bits >> (ptrBits - h.valid) // leftover for next word
|
| 632 |
+
h.valid += valid - ptrBits // have h.valid+valid bits, writing ptrBits of them
|
| 633 |
+
|
| 634 |
+
// Flush mask to the memory bitmap.
|
| 635 |
+
idx := h.offset / (ptrBits * goarch.PtrSize)
|
| 636 |
+
m := uintptr(1)<<h.low - 1
|
| 637 |
+
bitmap := s.heapBits()
|
| 638 |
+
bitmap[idx] = bswapIfBigEndian(bswapIfBigEndian(bitmap[idx])&m | data)
|
| 639 |
+
// Note: no synchronization required for this write because
|
| 640 |
+
// the allocator has exclusive access to the page, and the bitmap
|
| 641 |
+
// entries are all for a single page. Also, visibility of these
|
| 642 |
+
// writes is guaranteed by the publication barrier in mallocgc.
|
| 643 |
+
|
| 644 |
+
// Move to next word of bitmap.
|
| 645 |
+
h.offset += ptrBits * goarch.PtrSize
|
| 646 |
+
h.low = 0
|
| 647 |
+
return h
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
// Add padding of size bytes.
|
| 651 |
+
func (h writeUserArenaHeapBits) pad(s *mspan, size uintptr) writeUserArenaHeapBits {
|
| 652 |
+
if size == 0 {
|
| 653 |
+
return h
|
| 654 |
+
}
|
| 655 |
+
words := size / goarch.PtrSize
|
| 656 |
+
for words > ptrBits {
|
| 657 |
+
h = h.write(s, 0, ptrBits)
|
| 658 |
+
words -= ptrBits
|
| 659 |
+
}
|
| 660 |
+
return h.write(s, 0, words)
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
// Flush the bits that have been written, and add zeros as needed
|
| 664 |
+
// to cover the full object [addr, addr+size).
|
| 665 |
+
func (h writeUserArenaHeapBits) flush(s *mspan, addr, size uintptr) {
|
| 666 |
+
offset := addr - s.base()
|
| 667 |
+
|
| 668 |
+
// zeros counts the number of bits needed to represent the object minus the
|
| 669 |
+
// number of bits we've already written. This is the number of 0 bits
|
| 670 |
+
// that need to be added.
|
| 671 |
+
zeros := (offset+size-h.offset)/goarch.PtrSize - h.valid
|
| 672 |
+
|
| 673 |
+
// Add zero bits up to the bitmap word boundary
|
| 674 |
+
if zeros > 0 {
|
| 675 |
+
z := ptrBits - h.valid
|
| 676 |
+
if z > zeros {
|
| 677 |
+
z = zeros
|
| 678 |
+
}
|
| 679 |
+
h.valid += z
|
| 680 |
+
zeros -= z
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
// Find word in bitmap that we're going to write.
|
| 684 |
+
bitmap := s.heapBits()
|
| 685 |
+
idx := h.offset / (ptrBits * goarch.PtrSize)
|
| 686 |
+
|
| 687 |
+
// Write remaining bits.
|
| 688 |
+
if h.valid != h.low {
|
| 689 |
+
m := uintptr(1)<<h.low - 1 // don't clear existing bits below "low"
|
| 690 |
+
m |= ^(uintptr(1)<<h.valid - 1) // don't clear existing bits above "valid"
|
| 691 |
+
bitmap[idx] = bswapIfBigEndian(bswapIfBigEndian(bitmap[idx])&m | h.mask)
|
| 692 |
+
}
|
| 693 |
+
if zeros == 0 {
|
| 694 |
+
return
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
// Advance to next bitmap word.
|
| 698 |
+
h.offset += ptrBits * goarch.PtrSize
|
| 699 |
+
|
| 700 |
+
// Continue on writing zeros for the rest of the object.
|
| 701 |
+
// For standard use of the ptr bits this is not required, as
|
| 702 |
+
// the bits are read from the beginning of the object. Some uses,
|
| 703 |
+
// like noscan spans, oblets, bulk write barriers, and cgocheck, might
|
| 704 |
+
// start mid-object, so these writes are still required.
|
| 705 |
+
for {
|
| 706 |
+
// Write zero bits.
|
| 707 |
+
idx := h.offset / (ptrBits * goarch.PtrSize)
|
| 708 |
+
if zeros < ptrBits {
|
| 709 |
+
bitmap[idx] = bswapIfBigEndian(bswapIfBigEndian(bitmap[idx]) &^ (uintptr(1)<<zeros - 1))
|
| 710 |
+
break
|
| 711 |
+
} else if zeros == ptrBits {
|
| 712 |
+
bitmap[idx] = 0
|
| 713 |
+
break
|
| 714 |
+
} else {
|
| 715 |
+
bitmap[idx] = 0
|
| 716 |
+
zeros -= ptrBits
|
| 717 |
+
}
|
| 718 |
+
h.offset += ptrBits * goarch.PtrSize
|
| 719 |
+
}
|
| 720 |
+
}
|
| 721 |
+
|
| 722 |
+
// bswapIfBigEndian swaps the byte order of the uintptr on goarch.BigEndian platforms,
|
| 723 |
+
// and leaves it alone elsewhere.
|
| 724 |
+
func bswapIfBigEndian(x uintptr) uintptr {
|
| 725 |
+
if goarch.BigEndian {
|
| 726 |
+
if goarch.PtrSize == 8 {
|
| 727 |
+
return uintptr(sys.Bswap64(uint64(x)))
|
| 728 |
+
}
|
| 729 |
+
return uintptr(sys.Bswap32(uint32(x)))
|
| 730 |
+
}
|
| 731 |
+
return x
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
// newUserArenaChunk allocates a user arena chunk, which maps to a single
|
| 735 |
+
// heap arena and single span. Returns a pointer to the base of the chunk
|
| 736 |
+
// (this is really important: we need to keep the chunk alive) and the span.
|
| 737 |
+
func newUserArenaChunk() (unsafe.Pointer, *mspan) {
|
| 738 |
+
if gcphase == _GCmarktermination {
|
| 739 |
+
throw("newUserArenaChunk called with gcphase == _GCmarktermination")
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
// Deduct assist credit. Because user arena chunks are modeled as one
|
| 743 |
+
// giant heap object which counts toward heapLive, we're obligated to
|
| 744 |
+
// assist the GC proportionally (and it's worth noting that the arena
|
| 745 |
+
// does represent additional work for the GC, but we also have no idea
|
| 746 |
+
// what that looks like until we actually allocate things into the
|
| 747 |
+
// arena).
|
| 748 |
+
if gcBlackenEnabled != 0 {
|
| 749 |
+
deductAssistCredit(userArenaChunkBytes)
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
// Set mp.mallocing to keep from being preempted by GC.
|
| 753 |
+
mp := acquirem()
|
| 754 |
+
if mp.mallocing != 0 {
|
| 755 |
+
throw("malloc deadlock")
|
| 756 |
+
}
|
| 757 |
+
if mp.gsignal == getg() {
|
| 758 |
+
throw("malloc during signal")
|
| 759 |
+
}
|
| 760 |
+
mp.mallocing = 1
|
| 761 |
+
|
| 762 |
+
// Allocate a new user arena.
|
| 763 |
+
var span *mspan
|
| 764 |
+
systemstack(func() {
|
| 765 |
+
span = mheap_.allocUserArenaChunk()
|
| 766 |
+
})
|
| 767 |
+
if span == nil {
|
| 768 |
+
throw("out of memory")
|
| 769 |
+
}
|
| 770 |
+
x := unsafe.Pointer(span.base())
|
| 771 |
+
|
| 772 |
+
// Allocate black during GC.
|
| 773 |
+
// All slots hold nil so no scanning is needed.
|
| 774 |
+
// This may be racing with GC so do it atomically if there can be
|
| 775 |
+
// a race marking the bit.
|
| 776 |
+
if gcphase != _GCoff {
|
| 777 |
+
gcmarknewobject(span, span.base())
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
if raceenabled {
|
| 781 |
+
// TODO(mknyszek): Track individual objects.
|
| 782 |
+
racemalloc(unsafe.Pointer(span.base()), span.elemsize)
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
if msanenabled {
|
| 786 |
+
// TODO(mknyszek): Track individual objects.
|
| 787 |
+
msanmalloc(unsafe.Pointer(span.base()), span.elemsize)
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
if asanenabled {
|
| 791 |
+
// TODO(mknyszek): Track individual objects.
|
| 792 |
+
// N.B. span.elemsize includes a redzone already.
|
| 793 |
+
rzStart := span.base() + span.elemsize
|
| 794 |
+
asanpoison(unsafe.Pointer(rzStart), span.limit-rzStart)
|
| 795 |
+
asanunpoison(unsafe.Pointer(span.base()), span.elemsize)
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
if rate := MemProfileRate; rate > 0 {
|
| 799 |
+
c := getMCache(mp)
|
| 800 |
+
if c == nil {
|
| 801 |
+
throw("newUserArenaChunk called without a P or outside bootstrapping")
|
| 802 |
+
}
|
| 803 |
+
// Note cache c only valid while m acquired; see #47302
|
| 804 |
+
if rate != 1 && int64(userArenaChunkBytes) < c.nextSample {
|
| 805 |
+
c.nextSample -= int64(userArenaChunkBytes)
|
| 806 |
+
} else {
|
| 807 |
+
profilealloc(mp, unsafe.Pointer(span.base()), userArenaChunkBytes)
|
| 808 |
+
}
|
| 809 |
+
}
|
| 810 |
+
mp.mallocing = 0
|
| 811 |
+
releasem(mp)
|
| 812 |
+
|
| 813 |
+
// Again, because this chunk counts toward heapLive, potentially trigger a GC.
|
| 814 |
+
if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
|
| 815 |
+
gcStart(t)
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
if debug.malloc {
|
| 819 |
+
if inittrace.active && inittrace.id == getg().goid {
|
| 820 |
+
// Init functions are executed sequentially in a single goroutine.
|
| 821 |
+
inittrace.bytes += uint64(userArenaChunkBytes)
|
| 822 |
+
}
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
// Double-check it's aligned to the physical page size. Based on the current
|
| 826 |
+
// implementation this is trivially true, but it need not be in the future.
|
| 827 |
+
// However, if it's not aligned to the physical page size then we can't properly
|
| 828 |
+
// set it to fault later.
|
| 829 |
+
if uintptr(x)%physPageSize != 0 {
|
| 830 |
+
throw("user arena chunk is not aligned to the physical page size")
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
return x, span
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
// isUnusedUserArenaChunk indicates that the arena chunk has been set to fault
|
| 837 |
+
// and doesn't contain any scannable memory anymore. However, it might still be
|
| 838 |
+
// mSpanInUse as it sits on the quarantine list, since it needs to be swept.
|
| 839 |
+
//
|
| 840 |
+
// This is not safe to execute unless the caller has ownership of the mspan or
|
| 841 |
+
// the world is stopped (preemption is prevented while the relevant state changes).
|
| 842 |
+
//
|
| 843 |
+
// This is really only meant to be used by accounting tests in the runtime to
|
| 844 |
+
// distinguish when a span shouldn't be counted (since mSpanInUse might not be
|
| 845 |
+
// enough).
|
| 846 |
+
func (s *mspan) isUnusedUserArenaChunk() bool {
|
| 847 |
+
return s.isUserArenaChunk && s.spanclass == makeSpanClass(0, true)
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
// setUserArenaChunkToFault sets the address space for the user arena chunk to fault
|
| 851 |
+
// and releases any underlying memory resources.
|
| 852 |
+
//
|
| 853 |
+
// Must be in a non-preemptible state to ensure the consistency of statistics
|
| 854 |
+
// exported to MemStats.
|
| 855 |
+
func (s *mspan) setUserArenaChunkToFault() {
|
| 856 |
+
if !s.isUserArenaChunk {
|
| 857 |
+
throw("invalid span in heapArena for user arena")
|
| 858 |
+
}
|
| 859 |
+
if s.npages*pageSize != userArenaChunkBytes {
|
| 860 |
+
throw("span on userArena.faultList has invalid size")
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
// Update the span class to be noscan. What we want to happen is that
|
| 864 |
+
// any pointer into the span keeps it from getting recycled, so we want
|
| 865 |
+
// the mark bit to get set, but we're about to set the address space to fault,
|
| 866 |
+
// so we have to prevent the GC from scanning this memory.
|
| 867 |
+
//
|
| 868 |
+
// It's OK to set it here because (1) a GC isn't in progress, so the scanning code
|
| 869 |
+
// won't make a bad decision, (2) we're currently non-preemptible and in the runtime,
|
| 870 |
+
// so a GC is blocked from starting. We might race with sweeping, which could
|
| 871 |
+
// put it on the "wrong" sweep list, but really don't care because the chunk is
|
| 872 |
+
// treated as a large object span and there's no meaningful difference between scan
|
| 873 |
+
// and noscan large objects in the sweeper. The STW at the start of the GC acts as a
|
| 874 |
+
// barrier for this update.
|
| 875 |
+
s.spanclass = makeSpanClass(0, true)
|
| 876 |
+
|
| 877 |
+
// Actually set the arena chunk to fault, so we'll get dangling pointer errors.
|
| 878 |
+
// sysFault currently uses a method on each OS that forces it to evacuate all
|
| 879 |
+
// memory backing the chunk.
|
| 880 |
+
sysFault(unsafe.Pointer(s.base()), s.npages*pageSize)
|
| 881 |
+
|
| 882 |
+
// Everything on the list is counted as in-use, however sysFault transitions to
|
| 883 |
+
// Reserved, not Prepared, so we skip updating heapFree or heapReleased and just
|
| 884 |
+
// remove the memory from the total altogether; it's just address space now.
|
| 885 |
+
gcController.heapInUse.add(-int64(s.npages * pageSize))
|
| 886 |
+
|
| 887 |
+
// Count this as a free of an object right now as opposed to when
|
| 888 |
+
// the span gets off the quarantine list. The main reason is so that the
|
| 889 |
+
// amount of bytes allocated doesn't exceed how much is counted as
|
| 890 |
+
// "mapped ready," which could cause a deadlock in the pacer.
|
| 891 |
+
gcController.totalFree.Add(int64(s.elemsize))
|
| 892 |
+
|
| 893 |
+
// Update consistent stats to match.
|
| 894 |
+
//
|
| 895 |
+
// We're non-preemptible, so it's safe to update consistent stats (our P
|
| 896 |
+
// won't change out from under us).
|
| 897 |
+
stats := memstats.heapStats.acquire()
|
| 898 |
+
atomic.Xaddint64(&stats.committed, -int64(s.npages*pageSize))
|
| 899 |
+
atomic.Xaddint64(&stats.inHeap, -int64(s.npages*pageSize))
|
| 900 |
+
atomic.Xadd64(&stats.largeFreeCount, 1)
|
| 901 |
+
atomic.Xadd64(&stats.largeFree, int64(s.elemsize))
|
| 902 |
+
memstats.heapStats.release()
|
| 903 |
+
|
| 904 |
+
// This counts as a free, so update heapLive.
|
| 905 |
+
gcController.update(-int64(s.elemsize), 0)
|
| 906 |
+
|
| 907 |
+
// Mark it as free for the race detector.
|
| 908 |
+
if raceenabled {
|
| 909 |
+
racefree(unsafe.Pointer(s.base()), s.elemsize)
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
systemstack(func() {
|
| 913 |
+
// Add the user arena to the quarantine list.
|
| 914 |
+
lock(&mheap_.lock)
|
| 915 |
+
mheap_.userArena.quarantineList.insert(s)
|
| 916 |
+
unlock(&mheap_.lock)
|
| 917 |
+
})
|
| 918 |
+
}
|
| 919 |
+
|
| 920 |
+
// inUserArenaChunk returns true if p points to a user arena chunk.
|
| 921 |
+
func inUserArenaChunk(p uintptr) bool {
|
| 922 |
+
s := spanOf(p)
|
| 923 |
+
if s == nil {
|
| 924 |
+
return false
|
| 925 |
+
}
|
| 926 |
+
return s.isUserArenaChunk
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
// freeUserArenaChunk releases the user arena represented by s back to the runtime.
|
| 930 |
+
//
|
| 931 |
+
// x must be a live pointer within s.
|
| 932 |
+
//
|
| 933 |
+
// The runtime will set the user arena to fault once it's safe (the GC is no longer running)
|
| 934 |
+
// and then once the user arena is no longer referenced by the application, will allow it to
|
| 935 |
+
// be reused.
|
| 936 |
+
func freeUserArenaChunk(s *mspan, x unsafe.Pointer) {
|
| 937 |
+
if !s.isUserArenaChunk {
|
| 938 |
+
throw("span is not for a user arena")
|
| 939 |
+
}
|
| 940 |
+
if s.npages*pageSize != userArenaChunkBytes {
|
| 941 |
+
throw("invalid user arena span size")
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
// Mark the region as free to various sanitizers immediately instead
|
| 945 |
+
// of handling them at sweep time.
|
| 946 |
+
if raceenabled {
|
| 947 |
+
racefree(unsafe.Pointer(s.base()), s.elemsize)
|
| 948 |
+
}
|
| 949 |
+
if msanenabled {
|
| 950 |
+
msanfree(unsafe.Pointer(s.base()), s.elemsize)
|
| 951 |
+
}
|
| 952 |
+
if asanenabled {
|
| 953 |
+
asanpoison(unsafe.Pointer(s.base()), s.elemsize)
|
| 954 |
+
}
|
| 955 |
+
if valgrindenabled {
|
| 956 |
+
valgrindFree(unsafe.Pointer(s.base()))
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
// Make ourselves non-preemptible as we manipulate state and statistics.
|
| 960 |
+
//
|
| 961 |
+
// Also required by setUserArenaChunksToFault.
|
| 962 |
+
mp := acquirem()
|
| 963 |
+
|
| 964 |
+
// We can only set user arenas to fault if we're in the _GCoff phase.
|
| 965 |
+
if gcphase == _GCoff {
|
| 966 |
+
lock(&userArenaState.lock)
|
| 967 |
+
faultList := userArenaState.fault
|
| 968 |
+
userArenaState.fault = nil
|
| 969 |
+
unlock(&userArenaState.lock)
|
| 970 |
+
|
| 971 |
+
s.setUserArenaChunkToFault()
|
| 972 |
+
for _, lc := range faultList {
|
| 973 |
+
lc.mspan.setUserArenaChunkToFault()
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
// Until the chunks are set to fault, keep them alive via the fault list.
|
| 977 |
+
KeepAlive(x)
|
| 978 |
+
KeepAlive(faultList)
|
| 979 |
+
} else {
|
| 980 |
+
// Put the user arena on the fault list.
|
| 981 |
+
lock(&userArenaState.lock)
|
| 982 |
+
userArenaState.fault = append(userArenaState.fault, liveUserArenaChunk{s, x})
|
| 983 |
+
unlock(&userArenaState.lock)
|
| 984 |
+
}
|
| 985 |
+
releasem(mp)
|
| 986 |
+
}
|
| 987 |
+
|
| 988 |
+
// allocUserArenaChunk attempts to reuse a free user arena chunk represented
|
| 989 |
+
// as a span.
|
| 990 |
+
//
|
| 991 |
+
// Must be in a non-preemptible state to ensure the consistency of statistics
|
| 992 |
+
// exported to MemStats.
|
| 993 |
+
//
|
| 994 |
+
// Acquires the heap lock. Must run on the system stack for that reason.
|
| 995 |
+
//
|
| 996 |
+
//go:systemstack
|
| 997 |
+
func (h *mheap) allocUserArenaChunk() *mspan {
|
| 998 |
+
var s *mspan
|
| 999 |
+
var base uintptr
|
| 1000 |
+
|
| 1001 |
+
// First check the free list.
|
| 1002 |
+
lock(&h.lock)
|
| 1003 |
+
if !h.userArena.readyList.isEmpty() {
|
| 1004 |
+
s = h.userArena.readyList.first
|
| 1005 |
+
h.userArena.readyList.remove(s)
|
| 1006 |
+
base = s.base()
|
| 1007 |
+
} else {
|
| 1008 |
+
// Free list was empty, so allocate a new arena.
|
| 1009 |
+
hintList := &h.userArena.arenaHints
|
| 1010 |
+
if raceenabled {
|
| 1011 |
+
// In race mode just use the regular heap hints. We might fragment
|
| 1012 |
+
// the address space, but the race detector requires that the heap
|
| 1013 |
+
// is mapped contiguously.
|
| 1014 |
+
hintList = &h.arenaHints
|
| 1015 |
+
}
|
| 1016 |
+
v, size := h.sysAlloc(userArenaChunkBytes, hintList, &mheap_.userArenaArenas)
|
| 1017 |
+
if size%userArenaChunkBytes != 0 {
|
| 1018 |
+
throw("sysAlloc size is not divisible by userArenaChunkBytes")
|
| 1019 |
+
}
|
| 1020 |
+
if size > userArenaChunkBytes {
|
| 1021 |
+
// We got more than we asked for. This can happen if
|
| 1022 |
+
// heapArenaSize > userArenaChunkSize, or if sysAlloc just returns
|
| 1023 |
+
// some extra as a result of trying to find an aligned region.
|
| 1024 |
+
//
|
| 1025 |
+
// Divide it up and put it on the ready list.
|
| 1026 |
+
for i := userArenaChunkBytes; i < size; i += userArenaChunkBytes {
|
| 1027 |
+
s := h.allocMSpanLocked()
|
| 1028 |
+
s.init(uintptr(v)+i, userArenaChunkPages)
|
| 1029 |
+
h.userArena.readyList.insertBack(s)
|
| 1030 |
+
}
|
| 1031 |
+
size = userArenaChunkBytes
|
| 1032 |
+
}
|
| 1033 |
+
base = uintptr(v)
|
| 1034 |
+
if base == 0 {
|
| 1035 |
+
// Out of memory.
|
| 1036 |
+
unlock(&h.lock)
|
| 1037 |
+
return nil
|
| 1038 |
+
}
|
| 1039 |
+
s = h.allocMSpanLocked()
|
| 1040 |
+
}
|
| 1041 |
+
unlock(&h.lock)
|
| 1042 |
+
|
| 1043 |
+
// sysAlloc returns Reserved address space, and any span we're
|
| 1044 |
+
// reusing is set to fault (so, also Reserved), so transition
|
| 1045 |
+
// it to Prepared and then Ready.
|
| 1046 |
+
//
|
| 1047 |
+
// Unlike (*mheap).grow, just map in everything that we
|
| 1048 |
+
// asked for. We're likely going to use it all.
|
| 1049 |
+
sysMap(unsafe.Pointer(base), userArenaChunkBytes, &gcController.heapReleased, "user arena chunk")
|
| 1050 |
+
sysUsed(unsafe.Pointer(base), userArenaChunkBytes, userArenaChunkBytes)
|
| 1051 |
+
|
| 1052 |
+
// Model the user arena as a heap span for a large object.
|
| 1053 |
+
spc := makeSpanClass(0, false)
|
| 1054 |
+
// A user arena chunk is always fresh from the OS. It's either newly allocated
|
| 1055 |
+
// via sysAlloc() or reused from the readyList after a sysFault(). The memory is
|
| 1056 |
+
// then re-mapped via sysMap(), so we can safely treat it as scavenged; the
|
| 1057 |
+
// kernel guarantees it will be zero-filled on its next use.
|
| 1058 |
+
h.initSpan(s, spanAllocHeap, spc, base, userArenaChunkPages, userArenaChunkBytes)
|
| 1059 |
+
s.isUserArenaChunk = true
|
| 1060 |
+
s.elemsize -= userArenaChunkReserveBytes()
|
| 1061 |
+
s.freeindex = 1
|
| 1062 |
+
s.allocCount = 1
|
| 1063 |
+
|
| 1064 |
+
// Adjust s.limit down to the object-containing part of the span.
|
| 1065 |
+
//
|
| 1066 |
+
// This is just to create a slightly tighter bound on the limit.
|
| 1067 |
+
// It's totally OK if the garbage collector, in particular
|
| 1068 |
+
// conservative scanning, can temporarily observes an inflated
|
| 1069 |
+
// limit. It will simply mark the whole chunk or just skip it
|
| 1070 |
+
// since we're in the mark phase anyway.
|
| 1071 |
+
s.limit = s.base() + s.elemsize
|
| 1072 |
+
|
| 1073 |
+
// Adjust size to include redzone.
|
| 1074 |
+
if asanenabled {
|
| 1075 |
+
s.elemsize -= redZoneSize(s.elemsize)
|
| 1076 |
+
}
|
| 1077 |
+
|
| 1078 |
+
// Account for this new arena chunk memory.
|
| 1079 |
+
gcController.heapInUse.add(int64(userArenaChunkBytes))
|
| 1080 |
+
gcController.heapReleased.add(-int64(userArenaChunkBytes))
|
| 1081 |
+
|
| 1082 |
+
stats := memstats.heapStats.acquire()
|
| 1083 |
+
atomic.Xaddint64(&stats.inHeap, int64(userArenaChunkBytes))
|
| 1084 |
+
atomic.Xaddint64(&stats.committed, int64(userArenaChunkBytes))
|
| 1085 |
+
|
| 1086 |
+
// Model the arena as a single large malloc.
|
| 1087 |
+
atomic.Xadd64(&stats.largeAlloc, int64(s.elemsize))
|
| 1088 |
+
atomic.Xadd64(&stats.largeAllocCount, 1)
|
| 1089 |
+
memstats.heapStats.release()
|
| 1090 |
+
|
| 1091 |
+
// Count the alloc in inconsistent, internal stats.
|
| 1092 |
+
gcController.totalAlloc.Add(int64(s.elemsize))
|
| 1093 |
+
|
| 1094 |
+
// Update heapLive.
|
| 1095 |
+
gcController.update(int64(s.elemsize), 0)
|
| 1096 |
+
|
| 1097 |
+
// This must clear the entire heap bitmap so that it's safe
|
| 1098 |
+
// to allocate noscan data without writing anything out.
|
| 1099 |
+
s.initHeapBits()
|
| 1100 |
+
|
| 1101 |
+
// Clear the span preemptively. It's an arena chunk, so let's assume
|
| 1102 |
+
// everything is going to be used.
|
| 1103 |
+
//
|
| 1104 |
+
// This also seems to make a massive difference as to whether or
|
| 1105 |
+
// not Linux decides to back this memory with transparent huge
|
| 1106 |
+
// pages. There's latency involved in this zeroing, but the hugepage
|
| 1107 |
+
// gains are almost always worth it. Note: it's important that we
|
| 1108 |
+
// clear even if it's freshly mapped and we know there's no point
|
| 1109 |
+
// to zeroing as *that* is the critical signal to use huge pages.
|
| 1110 |
+
memclrNoHeapPointers(unsafe.Pointer(s.base()), s.elemsize)
|
| 1111 |
+
s.needzero = 0
|
| 1112 |
+
|
| 1113 |
+
s.freeIndexForScan = 1
|
| 1114 |
+
|
| 1115 |
+
// Set up the range for allocation.
|
| 1116 |
+
s.userArenaChunkFree = makeAddrRange(base, base+s.elemsize)
|
| 1117 |
+
|
| 1118 |
+
// Put the large span in the mcentral swept list so that it's
|
| 1119 |
+
// visible to the background sweeper.
|
| 1120 |
+
h.central[spc].mcentral.fullSwept(h.sweepgen).push(s)
|
| 1121 |
+
|
| 1122 |
+
// Set up an allocation header. Avoid write barriers here because this type
|
| 1123 |
+
// is not a real type, and it exists in an invalid location.
|
| 1124 |
+
*(*uintptr)(unsafe.Pointer(&s.largeType)) = uintptr(unsafe.Pointer(s.limit))
|
| 1125 |
+
*(*uintptr)(unsafe.Pointer(&s.largeType.GCData)) = s.limit + unsafe.Sizeof(_type{})
|
| 1126 |
+
s.largeType.PtrBytes = 0
|
| 1127 |
+
s.largeType.Size_ = s.elemsize
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 runtime_test
|
| 6 |
+
|
| 7 |
+
import (
|
| 8 |
+
"internal/goarch"
|
| 9 |
+
"internal/runtime/atomic"
|
| 10 |
+
"reflect"
|
| 11 |
+
. "runtime"
|
| 12 |
+
"runtime/debug"
|
| 13 |
+
"testing"
|
| 14 |
+
"time"
|
| 15 |
+
"unsafe"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
type smallScalar struct {
|
| 19 |
+
X uintptr
|
| 20 |
+
}
|
| 21 |
+
type smallPointer struct {
|
| 22 |
+
X *smallPointer
|
| 23 |
+
}
|
| 24 |
+
type smallPointerMix struct {
|
| 25 |
+
A *smallPointer
|
| 26 |
+
B byte
|
| 27 |
+
C *smallPointer
|
| 28 |
+
D [11]byte
|
| 29 |
+
}
|
| 30 |
+
type mediumScalarEven [8192]byte
|
| 31 |
+
type mediumScalarOdd [3321]byte
|
| 32 |
+
type mediumPointerEven [1024]*smallPointer
|
| 33 |
+
type mediumPointerOdd [1023]*smallPointer
|
| 34 |
+
|
| 35 |
+
type largeScalar [UserArenaChunkBytes + 1]byte
|
| 36 |
+
type largePointer [UserArenaChunkBytes/unsafe.Sizeof(&smallPointer{}) + 1]*smallPointer
|
| 37 |
+
|
| 38 |
+
func TestUserArena(t *testing.T) {
|
| 39 |
+
if Clobberfree() {
|
| 40 |
+
// This test crashes with SEGV in clobberfree in mgcsweep.go with GODEBUG=clobberfree=1.
|
| 41 |
+
t.Skip("triggers SEGV with GODEBUG=clobberfree=1")
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// Set GOMAXPROCS to 2 so we don't run too many of these
|
| 45 |
+
// tests in parallel.
|
| 46 |
+
defer GOMAXPROCS(GOMAXPROCS(2))
|
| 47 |
+
|
| 48 |
+
// Start a subtest so that we can clean up after any parallel tests within.
|
| 49 |
+
t.Run("Alloc", func(t *testing.T) {
|
| 50 |
+
ss := &smallScalar{5}
|
| 51 |
+
runSubTestUserArenaNew(t, ss, true)
|
| 52 |
+
|
| 53 |
+
sp := &smallPointer{new(smallPointer)}
|
| 54 |
+
runSubTestUserArenaNew(t, sp, true)
|
| 55 |
+
|
| 56 |
+
spm := &smallPointerMix{sp, 5, nil, [11]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}
|
| 57 |
+
runSubTestUserArenaNew(t, spm, true)
|
| 58 |
+
|
| 59 |
+
mse := new(mediumScalarEven)
|
| 60 |
+
for i := range mse {
|
| 61 |
+
mse[i] = 121
|
| 62 |
+
}
|
| 63 |
+
runSubTestUserArenaNew(t, mse, true)
|
| 64 |
+
|
| 65 |
+
mso := new(mediumScalarOdd)
|
| 66 |
+
for i := range mso {
|
| 67 |
+
mso[i] = 122
|
| 68 |
+
}
|
| 69 |
+
runSubTestUserArenaNew(t, mso, true)
|
| 70 |
+
|
| 71 |
+
mpe := new(mediumPointerEven)
|
| 72 |
+
for i := range mpe {
|
| 73 |
+
mpe[i] = sp
|
| 74 |
+
}
|
| 75 |
+
runSubTestUserArenaNew(t, mpe, true)
|
| 76 |
+
|
| 77 |
+
mpo := new(mediumPointerOdd)
|
| 78 |
+
for i := range mpo {
|
| 79 |
+
mpo[i] = sp
|
| 80 |
+
}
|
| 81 |
+
runSubTestUserArenaNew(t, mpo, true)
|
| 82 |
+
|
| 83 |
+
ls := new(largeScalar)
|
| 84 |
+
for i := range ls {
|
| 85 |
+
ls[i] = 123
|
| 86 |
+
}
|
| 87 |
+
// Not in parallel because we don't want to hold this large allocation live.
|
| 88 |
+
runSubTestUserArenaNew(t, ls, false)
|
| 89 |
+
|
| 90 |
+
lp := new(largePointer)
|
| 91 |
+
for i := range lp {
|
| 92 |
+
lp[i] = sp
|
| 93 |
+
}
|
| 94 |
+
// Not in parallel because we don't want to hold this large allocation live.
|
| 95 |
+
runSubTestUserArenaNew(t, lp, false)
|
| 96 |
+
|
| 97 |
+
sss := make([]smallScalar, 25)
|
| 98 |
+
for i := range sss {
|
| 99 |
+
sss[i] = smallScalar{12}
|
| 100 |
+
}
|
| 101 |
+
runSubTestUserArenaSlice(t, sss, true)
|
| 102 |
+
|
| 103 |
+
mpos := make([]mediumPointerOdd, 5)
|
| 104 |
+
for i := range mpos {
|
| 105 |
+
mpos[i] = *mpo
|
| 106 |
+
}
|
| 107 |
+
runSubTestUserArenaSlice(t, mpos, true)
|
| 108 |
+
|
| 109 |
+
sps := make([]smallPointer, UserArenaChunkBytes/unsafe.Sizeof(smallPointer{})+1)
|
| 110 |
+
for i := range sps {
|
| 111 |
+
sps[i] = *sp
|
| 112 |
+
}
|
| 113 |
+
// Not in parallel because we don't want to hold this large allocation live.
|
| 114 |
+
runSubTestUserArenaSlice(t, sps, false)
|
| 115 |
+
|
| 116 |
+
// Test zero-sized types.
|
| 117 |
+
t.Run("struct{}", func(t *testing.T) {
|
| 118 |
+
arena := NewUserArena()
|
| 119 |
+
var x any
|
| 120 |
+
x = (*struct{})(nil)
|
| 121 |
+
arena.New(&x)
|
| 122 |
+
if v := unsafe.Pointer(x.(*struct{})); v != ZeroBase {
|
| 123 |
+
t.Errorf("expected zero-sized type to be allocated as zerobase: got %x, want %x", v, ZeroBase)
|
| 124 |
+
}
|
| 125 |
+
arena.Free()
|
| 126 |
+
})
|
| 127 |
+
t.Run("[]struct{}", func(t *testing.T) {
|
| 128 |
+
arena := NewUserArena()
|
| 129 |
+
var sl []struct{}
|
| 130 |
+
arena.Slice(&sl, 10)
|
| 131 |
+
if v := unsafe.Pointer(&sl[0]); v != ZeroBase {
|
| 132 |
+
t.Errorf("expected zero-sized type to be allocated as zerobase: got %x, want %x", v, ZeroBase)
|
| 133 |
+
}
|
| 134 |
+
arena.Free()
|
| 135 |
+
})
|
| 136 |
+
t.Run("[]int (cap 0)", func(t *testing.T) {
|
| 137 |
+
arena := NewUserArena()
|
| 138 |
+
var sl []int
|
| 139 |
+
arena.Slice(&sl, 0)
|
| 140 |
+
if len(sl) != 0 {
|
| 141 |
+
t.Errorf("expected requested zero-sized slice to still have zero length: got %x, want 0", len(sl))
|
| 142 |
+
}
|
| 143 |
+
arena.Free()
|
| 144 |
+
})
|
| 145 |
+
})
|
| 146 |
+
|
| 147 |
+
// Run a GC cycle to get any arenas off the quarantine list.
|
| 148 |
+
GC()
|
| 149 |
+
|
| 150 |
+
if n := GlobalWaitingArenaChunks(); n != 0 {
|
| 151 |
+
t.Errorf("expected zero waiting arena chunks, found %d", n)
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
func runSubTestUserArenaNew[S comparable](t *testing.T, value *S, parallel bool) {
|
| 156 |
+
t.Run(reflect.TypeOf(value).Elem().Name(), func(t *testing.T) {
|
| 157 |
+
if parallel {
|
| 158 |
+
t.Parallel()
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// Allocate and write data, enough to exhaust the arena.
|
| 162 |
+
//
|
| 163 |
+
// This is an underestimate, likely leaving some space in the arena. That's a good thing,
|
| 164 |
+
// because it gives us coverage of boundary cases.
|
| 165 |
+
n := int(UserArenaChunkBytes / unsafe.Sizeof(*value))
|
| 166 |
+
if n == 0 {
|
| 167 |
+
n = 1
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
// Create a new arena and do a bunch of operations on it.
|
| 171 |
+
arena := NewUserArena()
|
| 172 |
+
|
| 173 |
+
arenaValues := make([]*S, 0, n)
|
| 174 |
+
for j := 0; j < n; j++ {
|
| 175 |
+
var x any
|
| 176 |
+
x = (*S)(nil)
|
| 177 |
+
arena.New(&x)
|
| 178 |
+
s := x.(*S)
|
| 179 |
+
*s = *value
|
| 180 |
+
arenaValues = append(arenaValues, s)
|
| 181 |
+
}
|
| 182 |
+
// Check integrity of allocated data.
|
| 183 |
+
for _, s := range arenaValues {
|
| 184 |
+
if *s != *value {
|
| 185 |
+
t.Errorf("failed integrity check: got %#v, want %#v", *s, *value)
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
// Release the arena.
|
| 190 |
+
arena.Free()
|
| 191 |
+
})
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
func runSubTestUserArenaSlice[S comparable](t *testing.T, value []S, parallel bool) {
|
| 195 |
+
t.Run("[]"+reflect.TypeOf(value).Elem().Name(), func(t *testing.T) {
|
| 196 |
+
if parallel {
|
| 197 |
+
t.Parallel()
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// Allocate and write data, enough to exhaust the arena.
|
| 201 |
+
//
|
| 202 |
+
// This is an underestimate, likely leaving some space in the arena. That's a good thing,
|
| 203 |
+
// because it gives us coverage of boundary cases.
|
| 204 |
+
n := int(UserArenaChunkBytes / (unsafe.Sizeof(*new(S)) * uintptr(cap(value))))
|
| 205 |
+
if n == 0 {
|
| 206 |
+
n = 1
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// Create a new arena and do a bunch of operations on it.
|
| 210 |
+
arena := NewUserArena()
|
| 211 |
+
|
| 212 |
+
arenaValues := make([][]S, 0, n)
|
| 213 |
+
for j := 0; j < n; j++ {
|
| 214 |
+
var sl []S
|
| 215 |
+
arena.Slice(&sl, cap(value))
|
| 216 |
+
copy(sl, value)
|
| 217 |
+
arenaValues = append(arenaValues, sl)
|
| 218 |
+
}
|
| 219 |
+
// Check integrity of allocated data.
|
| 220 |
+
for _, sl := range arenaValues {
|
| 221 |
+
for i := range sl {
|
| 222 |
+
got := sl[i]
|
| 223 |
+
want := value[i]
|
| 224 |
+
if got != want {
|
| 225 |
+
t.Errorf("failed integrity check: got %#v, want %#v at index %d", got, want, i)
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
// Release the arena.
|
| 231 |
+
arena.Free()
|
| 232 |
+
})
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
func TestUserArenaLiveness(t *testing.T) {
|
| 236 |
+
if Clobberfree() {
|
| 237 |
+
// This test crashes with SEGV in clobberfree in mgcsweep.go with GODEBUG=clobberfree=1.
|
| 238 |
+
t.Skip("triggers SEGV with GODEBUG=clobberfree=1")
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
t.Run("Free", func(t *testing.T) {
|
| 242 |
+
testUserArenaLiveness(t, false)
|
| 243 |
+
})
|
| 244 |
+
t.Run("Finalizer", func(t *testing.T) {
|
| 245 |
+
testUserArenaLiveness(t, true)
|
| 246 |
+
})
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
func testUserArenaLiveness(t *testing.T, useArenaFinalizer bool) {
|
| 250 |
+
// Disable the GC so that there's zero chance we try doing anything arena related *during*
|
| 251 |
+
// a mark phase, since otherwise a bunch of arenas could end up on the fault list.
|
| 252 |
+
defer debug.SetGCPercent(debug.SetGCPercent(-1))
|
| 253 |
+
|
| 254 |
+
// Defensively ensure that any full arena chunks leftover from previous tests have been cleared.
|
| 255 |
+
GC()
|
| 256 |
+
GC()
|
| 257 |
+
|
| 258 |
+
arena := NewUserArena()
|
| 259 |
+
|
| 260 |
+
// Allocate a few pointer-ful but un-initialized objects so that later we can
|
| 261 |
+
// place a reference to heap object at a more interesting location.
|
| 262 |
+
for i := 0; i < 3; i++ {
|
| 263 |
+
var x any
|
| 264 |
+
x = (*mediumPointerOdd)(nil)
|
| 265 |
+
arena.New(&x)
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
var x any
|
| 269 |
+
x = (*smallPointerMix)(nil)
|
| 270 |
+
arena.New(&x)
|
| 271 |
+
v := x.(*smallPointerMix)
|
| 272 |
+
|
| 273 |
+
var safeToFinalize atomic.Bool
|
| 274 |
+
var finalized atomic.Bool
|
| 275 |
+
v.C = new(smallPointer)
|
| 276 |
+
SetFinalizer(v.C, func(_ *smallPointer) {
|
| 277 |
+
if !safeToFinalize.Load() {
|
| 278 |
+
t.Error("finalized arena-referenced object unexpectedly")
|
| 279 |
+
}
|
| 280 |
+
finalized.Store(true)
|
| 281 |
+
})
|
| 282 |
+
|
| 283 |
+
// Make sure it stays alive.
|
| 284 |
+
GC()
|
| 285 |
+
GC()
|
| 286 |
+
|
| 287 |
+
// In order to ensure the object can be freed, we now need to make sure to use
|
| 288 |
+
// the entire arena. Exhaust the rest of the arena.
|
| 289 |
+
|
| 290 |
+
for i := 0; i < int(UserArenaChunkBytes/unsafe.Sizeof(mediumScalarEven{})); i++ {
|
| 291 |
+
var x any
|
| 292 |
+
x = (*mediumScalarEven)(nil)
|
| 293 |
+
arena.New(&x)
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
// Make sure it stays alive again.
|
| 297 |
+
GC()
|
| 298 |
+
GC()
|
| 299 |
+
|
| 300 |
+
v = nil
|
| 301 |
+
|
| 302 |
+
safeToFinalize.Store(true)
|
| 303 |
+
if useArenaFinalizer {
|
| 304 |
+
arena = nil
|
| 305 |
+
|
| 306 |
+
// Try to queue the arena finalizer.
|
| 307 |
+
GC()
|
| 308 |
+
GC()
|
| 309 |
+
|
| 310 |
+
// In order for the finalizer we actually want to run to execute,
|
| 311 |
+
// we need to make sure this one runs first.
|
| 312 |
+
if !BlockUntilEmptyFinalizerQueue(int64(2 * time.Second)) {
|
| 313 |
+
t.Fatal("finalizer queue was never emptied")
|
| 314 |
+
}
|
| 315 |
+
} else {
|
| 316 |
+
// Free the arena explicitly.
|
| 317 |
+
arena.Free()
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
// Try to queue the object's finalizer that we set earlier.
|
| 321 |
+
GC()
|
| 322 |
+
GC()
|
| 323 |
+
|
| 324 |
+
if !BlockUntilEmptyFinalizerQueue(int64(2 * time.Second)) {
|
| 325 |
+
t.Fatal("finalizer queue was never emptied")
|
| 326 |
+
}
|
| 327 |
+
if !finalized.Load() {
|
| 328 |
+
t.Error("expected arena-referenced object to be finalized")
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
func TestUserArenaClearsPointerBits(t *testing.T) {
|
| 333 |
+
if Clobberfree() {
|
| 334 |
+
// This test crashes with SEGV in clobberfree in mgcsweep.go with GODEBUG=clobberfree=1.
|
| 335 |
+
t.Skip("triggers SEGV with GODEBUG=clobberfree=1")
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
// This is a regression test for a serious issue wherein if pointer bits
|
| 339 |
+
// aren't properly cleared, it's possible to allocate scalar data down
|
| 340 |
+
// into a previously pointer-ful area, causing misinterpretation by the GC.
|
| 341 |
+
|
| 342 |
+
// Create a large object, grab a pointer into it, and free it.
|
| 343 |
+
x := new([8 << 20]byte)
|
| 344 |
+
xp := uintptr(unsafe.Pointer(&x[124]))
|
| 345 |
+
var finalized atomic.Bool
|
| 346 |
+
SetFinalizer(x, func(_ *[8 << 20]byte) {
|
| 347 |
+
finalized.Store(true)
|
| 348 |
+
})
|
| 349 |
+
|
| 350 |
+
// Write three chunks worth of pointer data. Three gives us a
|
| 351 |
+
// high likelihood that when we write 2 later, we'll get the behavior
|
| 352 |
+
// we want.
|
| 353 |
+
a := NewUserArena()
|
| 354 |
+
for i := 0; i < int(UserArenaChunkBytes/goarch.PtrSize*3); i++ {
|
| 355 |
+
var x any
|
| 356 |
+
x = (*smallPointer)(nil)
|
| 357 |
+
a.New(&x)
|
| 358 |
+
}
|
| 359 |
+
a.Free()
|
| 360 |
+
|
| 361 |
+
// Recycle the arena chunks.
|
| 362 |
+
GC()
|
| 363 |
+
GC()
|
| 364 |
+
|
| 365 |
+
a = NewUserArena()
|
| 366 |
+
for i := 0; i < int(UserArenaChunkBytes/goarch.PtrSize*2); i++ {
|
| 367 |
+
var x any
|
| 368 |
+
x = (*smallScalar)(nil)
|
| 369 |
+
a.New(&x)
|
| 370 |
+
v := x.(*smallScalar)
|
| 371 |
+
// Write a pointer that should not keep x alive.
|
| 372 |
+
*v = smallScalar{xp}
|
| 373 |
+
}
|
| 374 |
+
KeepAlive(x)
|
| 375 |
+
x = nil
|
| 376 |
+
|
| 377 |
+
// Try to free x.
|
| 378 |
+
GC()
|
| 379 |
+
GC()
|
| 380 |
+
|
| 381 |
+
if !BlockUntilEmptyFinalizerQueue(int64(2 * time.Second)) {
|
| 382 |
+
t.Fatal("finalizer queue was never emptied")
|
| 383 |
+
}
|
| 384 |
+
if !finalized.Load() {
|
| 385 |
+
t.Fatal("heap allocation kept alive through non-pointer reference")
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
// Clean up the arena.
|
| 389 |
+
a.Free()
|
| 390 |
+
GC()
|
| 391 |
+
GC()
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
func TestUserArenaCloneString(t *testing.T) {
|
| 395 |
+
a := NewUserArena()
|
| 396 |
+
|
| 397 |
+
// A static string (not on heap or arena)
|
| 398 |
+
var s = "abcdefghij"
|
| 399 |
+
|
| 400 |
+
// Create a byte slice in the arena, initialize it with s
|
| 401 |
+
var b []byte
|
| 402 |
+
a.Slice(&b, len(s))
|
| 403 |
+
copy(b, s)
|
| 404 |
+
|
| 405 |
+
// Create a string as using the same memory as the byte slice, hence in
|
| 406 |
+
// the arena. This could be an arena API, but hasn't really been needed
|
| 407 |
+
// yet.
|
| 408 |
+
as := unsafe.String(&b[0], len(b))
|
| 409 |
+
|
| 410 |
+
// Clone should make a copy of as, since it is in the arena.
|
| 411 |
+
asCopy := UserArenaClone(as)
|
| 412 |
+
if unsafe.StringData(as) == unsafe.StringData(asCopy) {
|
| 413 |
+
t.Error("Clone did not make a copy")
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
// Clone should make a copy of subAs, since subAs is just part of as and so is in the arena.
|
| 417 |
+
subAs := as[1:3]
|
| 418 |
+
subAsCopy := UserArenaClone(subAs)
|
| 419 |
+
if unsafe.StringData(subAs) == unsafe.StringData(subAsCopy) {
|
| 420 |
+
t.Error("Clone did not make a copy")
|
| 421 |
+
}
|
| 422 |
+
if len(subAs) != len(subAsCopy) {
|
| 423 |
+
t.Errorf("Clone made an incorrect copy (bad length): %d -> %d", len(subAs), len(subAsCopy))
|
| 424 |
+
} else {
|
| 425 |
+
for i := range subAs {
|
| 426 |
+
if subAs[i] != subAsCopy[i] {
|
| 427 |
+
t.Errorf("Clone made an incorrect copy (data at index %d): %d -> %d", i, subAs[i], subAs[i])
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
// Clone should not make a copy of doubleAs, since doubleAs will be on the heap.
|
| 433 |
+
doubleAs := as + as
|
| 434 |
+
doubleAsCopy := UserArenaClone(doubleAs)
|
| 435 |
+
if unsafe.StringData(doubleAs) != unsafe.StringData(doubleAsCopy) {
|
| 436 |
+
t.Error("Clone should not have made a copy")
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
// Clone should not make a copy of s, since s is a static string.
|
| 440 |
+
sCopy := UserArenaClone(s)
|
| 441 |
+
if unsafe.StringData(s) != unsafe.StringData(sCopy) {
|
| 442 |
+
t.Error("Clone should not have made a copy")
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
a.Free()
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
func TestUserArenaClonePointer(t *testing.T) {
|
| 449 |
+
a := NewUserArena()
|
| 450 |
+
|
| 451 |
+
// Clone should not make a copy of a heap-allocated smallScalar.
|
| 452 |
+
x := Escape(new(smallScalar))
|
| 453 |
+
xCopy := UserArenaClone(x)
|
| 454 |
+
if unsafe.Pointer(x) != unsafe.Pointer(xCopy) {
|
| 455 |
+
t.Errorf("Clone should not have made a copy: %#v -> %#v", x, xCopy)
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
// Clone should make a copy of an arena-allocated smallScalar.
|
| 459 |
+
var i any
|
| 460 |
+
i = (*smallScalar)(nil)
|
| 461 |
+
a.New(&i)
|
| 462 |
+
xArena := i.(*smallScalar)
|
| 463 |
+
xArenaCopy := UserArenaClone(xArena)
|
| 464 |
+
if unsafe.Pointer(xArena) == unsafe.Pointer(xArenaCopy) {
|
| 465 |
+
t.Errorf("Clone should have made a copy: %#v -> %#v", xArena, xArenaCopy)
|
| 466 |
+
}
|
| 467 |
+
if *xArena != *xArenaCopy {
|
| 468 |
+
t.Errorf("Clone made an incorrect copy copy: %#v -> %#v", *xArena, *xArenaCopy)
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
a.Free()
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
func TestUserArenaCloneSlice(t *testing.T) {
|
| 475 |
+
a := NewUserArena()
|
| 476 |
+
|
| 477 |
+
// A static string (not on heap or arena)
|
| 478 |
+
var s = "klmnopqrstuv"
|
| 479 |
+
|
| 480 |
+
// Create a byte slice in the arena, initialize it with s
|
| 481 |
+
var b []byte
|
| 482 |
+
a.Slice(&b, len(s))
|
| 483 |
+
copy(b, s)
|
| 484 |
+
|
| 485 |
+
// Clone should make a copy of b, since it is in the arena.
|
| 486 |
+
bCopy := UserArenaClone(b)
|
| 487 |
+
if unsafe.Pointer(&b[0]) == unsafe.Pointer(&bCopy[0]) {
|
| 488 |
+
t.Errorf("Clone did not make a copy: %#v -> %#v", b, bCopy)
|
| 489 |
+
}
|
| 490 |
+
if len(b) != len(bCopy) {
|
| 491 |
+
t.Errorf("Clone made an incorrect copy (bad length): %d -> %d", len(b), len(bCopy))
|
| 492 |
+
} else {
|
| 493 |
+
for i := range b {
|
| 494 |
+
if b[i] != bCopy[i] {
|
| 495 |
+
t.Errorf("Clone made an incorrect copy (data at index %d): %d -> %d", i, b[i], bCopy[i])
|
| 496 |
+
}
|
| 497 |
+
}
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
// Clone should make a copy of bSub, since bSub is just part of b and so is in the arena.
|
| 501 |
+
bSub := b[1:3]
|
| 502 |
+
bSubCopy := UserArenaClone(bSub)
|
| 503 |
+
if unsafe.Pointer(&bSub[0]) == unsafe.Pointer(&bSubCopy[0]) {
|
| 504 |
+
t.Errorf("Clone did not make a copy: %#v -> %#v", bSub, bSubCopy)
|
| 505 |
+
}
|
| 506 |
+
if len(bSub) != len(bSubCopy) {
|
| 507 |
+
t.Errorf("Clone made an incorrect copy (bad length): %d -> %d", len(bSub), len(bSubCopy))
|
| 508 |
+
} else {
|
| 509 |
+
for i := range bSub {
|
| 510 |
+
if bSub[i] != bSubCopy[i] {
|
| 511 |
+
t.Errorf("Clone made an incorrect copy (data at index %d): %d -> %d", i, bSub[i], bSubCopy[i])
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// Clone should not make a copy of bNotArena, since it will not be in an arena.
|
| 517 |
+
bNotArena := make([]byte, len(s))
|
| 518 |
+
copy(bNotArena, s)
|
| 519 |
+
bNotArenaCopy := UserArenaClone(bNotArena)
|
| 520 |
+
if unsafe.Pointer(&bNotArena[0]) != unsafe.Pointer(&bNotArenaCopy[0]) {
|
| 521 |
+
t.Error("Clone should not have made a copy")
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
a.Free()
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
func TestUserArenaClonePanic(t *testing.T) {
|
| 528 |
+
var s string
|
| 529 |
+
func() {
|
| 530 |
+
x := smallScalar{2}
|
| 531 |
+
defer func() {
|
| 532 |
+
if v := recover(); v != nil {
|
| 533 |
+
s = v.(string)
|
| 534 |
+
}
|
| 535 |
+
}()
|
| 536 |
+
UserArenaClone(x)
|
| 537 |
+
}()
|
| 538 |
+
if s == "" {
|
| 539 |
+
t.Errorf("expected panic from Clone")
|
| 540 |
+
}
|
| 541 |
+
}
|
go/src/runtime/asan.go
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
package runtime
|
| 8 |
+
|
| 9 |
+
import (
|
| 10 |
+
"internal/runtime/sys"
|
| 11 |
+
"unsafe"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
// Public address sanitizer API.
|
| 15 |
+
func ASanRead(addr unsafe.Pointer, len int) {
|
| 16 |
+
sp := sys.GetCallerSP()
|
| 17 |
+
pc := sys.GetCallerPC()
|
| 18 |
+
doasanread(addr, uintptr(len), sp, pc)
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func ASanWrite(addr unsafe.Pointer, len int) {
|
| 22 |
+
sp := sys.GetCallerSP()
|
| 23 |
+
pc := sys.GetCallerPC()
|
| 24 |
+
doasanwrite(addr, uintptr(len), sp, pc)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
// Private interface for the runtime.
|
| 28 |
+
const asanenabled = true
|
| 29 |
+
const asanenabledBit = 1
|
| 30 |
+
|
| 31 |
+
// asan{read,write} are nosplit because they may be called between
|
| 32 |
+
// fork and exec, when the stack must not grow. See issue #50391.
|
| 33 |
+
|
| 34 |
+
//go:linkname asanread
|
| 35 |
+
//go:nosplit
|
| 36 |
+
func asanread(addr unsafe.Pointer, sz uintptr) {
|
| 37 |
+
sp := sys.GetCallerSP()
|
| 38 |
+
pc := sys.GetCallerPC()
|
| 39 |
+
doasanread(addr, sz, sp, pc)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
//go:linkname asanwrite
|
| 43 |
+
//go:nosplit
|
| 44 |
+
func asanwrite(addr unsafe.Pointer, sz uintptr) {
|
| 45 |
+
sp := sys.GetCallerSP()
|
| 46 |
+
pc := sys.GetCallerPC()
|
| 47 |
+
doasanwrite(addr, sz, sp, pc)
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
//go:noescape
|
| 51 |
+
func doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 52 |
+
|
| 53 |
+
//go:noescape
|
| 54 |
+
func doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 55 |
+
|
| 56 |
+
//go:noescape
|
| 57 |
+
func asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 58 |
+
|
| 59 |
+
//go:noescape
|
| 60 |
+
func asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 61 |
+
|
| 62 |
+
//go:noescape
|
| 63 |
+
func asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 64 |
+
|
| 65 |
+
//go:noescape
|
| 66 |
+
func lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 67 |
+
|
| 68 |
+
//go:noescape
|
| 69 |
+
func lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 70 |
+
|
| 71 |
+
func lsandoleakcheck()
|
| 72 |
+
|
| 73 |
+
// These are called from asan_GOARCH.s
|
| 74 |
+
//
|
| 75 |
+
//go:cgo_import_static __asan_read_go
|
| 76 |
+
//go:cgo_import_static __asan_write_go
|
| 77 |
+
//go:cgo_import_static __asan_unpoison_go
|
| 78 |
+
//go:cgo_import_static __asan_poison_go
|
| 79 |
+
//go:cgo_import_static __asan_register_globals_go
|
| 80 |
+
//go:cgo_import_static __lsan_register_root_region_go
|
| 81 |
+
//go:cgo_import_static __lsan_unregister_root_region_go
|
| 82 |
+
//go:cgo_import_static __lsan_do_leak_check_go
|
go/src/runtime/asan0.go
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 !asan
|
| 6 |
+
|
| 7 |
+
// Dummy ASan support API, used when not built with -asan.
|
| 8 |
+
|
| 9 |
+
package runtime
|
| 10 |
+
|
| 11 |
+
import (
|
| 12 |
+
"unsafe"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
const asanenabled = false
|
| 16 |
+
const asanenabledBit = 0
|
| 17 |
+
|
| 18 |
+
// Because asanenabled is false, none of these functions should be called.
|
| 19 |
+
|
| 20 |
+
func asanread(addr unsafe.Pointer, sz uintptr) { throw("asan") }
|
| 21 |
+
func asanwrite(addr unsafe.Pointer, sz uintptr) { throw("asan") }
|
| 22 |
+
func asanunpoison(addr unsafe.Pointer, sz uintptr) { throw("asan") }
|
| 23 |
+
func asanpoison(addr unsafe.Pointer, sz uintptr) { throw("asan") }
|
| 24 |
+
func asanregisterglobals(addr unsafe.Pointer, sz uintptr) { throw("asan") }
|
| 25 |
+
func lsanregisterrootregion(unsafe.Pointer, uintptr) { throw("asan") }
|
| 26 |
+
func lsanunregisterrootregion(unsafe.Pointer, uintptr) { throw("asan") }
|
| 27 |
+
func lsandoleakcheck() { throw("asan") }
|
go/src/runtime/asan_amd64.s
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
#include "go_asm.h"
|
| 8 |
+
#include "go_tls.h"
|
| 9 |
+
#include "funcdata.h"
|
| 10 |
+
#include "textflag.h"
|
| 11 |
+
|
| 12 |
+
// This is like race_amd64.s, but for the asan calls.
|
| 13 |
+
// See race_amd64.s for detailed comments.
|
| 14 |
+
|
| 15 |
+
#ifdef GOOS_windows
|
| 16 |
+
#define RARG0 CX
|
| 17 |
+
#define RARG1 DX
|
| 18 |
+
#define RARG2 R8
|
| 19 |
+
#define RARG3 R9
|
| 20 |
+
#else
|
| 21 |
+
#define RARG0 DI
|
| 22 |
+
#define RARG1 SI
|
| 23 |
+
#define RARG2 DX
|
| 24 |
+
#define RARG3 CX
|
| 25 |
+
#endif
|
| 26 |
+
|
| 27 |
+
// Called from instrumented code.
|
| 28 |
+
// func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 29 |
+
TEXT runtime·doasanread(SB), NOSPLIT, $0-32
|
| 30 |
+
MOVQ addr+0(FP), RARG0
|
| 31 |
+
MOVQ sz+8(FP), RARG1
|
| 32 |
+
MOVQ sp+16(FP), RARG2
|
| 33 |
+
MOVQ pc+24(FP), RARG3
|
| 34 |
+
// void __asan_read_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 35 |
+
MOVQ $__asan_read_go(SB), AX
|
| 36 |
+
JMP asancall<>(SB)
|
| 37 |
+
|
| 38 |
+
// func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 39 |
+
TEXT runtime·doasanwrite(SB), NOSPLIT, $0-32
|
| 40 |
+
MOVQ addr+0(FP), RARG0
|
| 41 |
+
MOVQ sz+8(FP), RARG1
|
| 42 |
+
MOVQ sp+16(FP), RARG2
|
| 43 |
+
MOVQ pc+24(FP), RARG3
|
| 44 |
+
// void __asan_write_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 45 |
+
MOVQ $__asan_write_go(SB), AX
|
| 46 |
+
JMP asancall<>(SB)
|
| 47 |
+
|
| 48 |
+
// func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 49 |
+
TEXT runtime·asanunpoison(SB), NOSPLIT, $0-16
|
| 50 |
+
MOVQ addr+0(FP), RARG0
|
| 51 |
+
MOVQ sz+8(FP), RARG1
|
| 52 |
+
// void __asan_unpoison_go(void *addr, uintptr_t sz);
|
| 53 |
+
MOVQ $__asan_unpoison_go(SB), AX
|
| 54 |
+
JMP asancall<>(SB)
|
| 55 |
+
|
| 56 |
+
// func runtime·asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 57 |
+
TEXT runtime·asanpoison(SB), NOSPLIT, $0-16
|
| 58 |
+
MOVQ addr+0(FP), RARG0
|
| 59 |
+
MOVQ sz+8(FP), RARG1
|
| 60 |
+
// void __asan_poison_go(void *addr, uintptr_t sz);
|
| 61 |
+
MOVQ $__asan_poison_go(SB), AX
|
| 62 |
+
JMP asancall<>(SB)
|
| 63 |
+
|
| 64 |
+
// func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 65 |
+
TEXT runtime·asanregisterglobals(SB), NOSPLIT, $0-16
|
| 66 |
+
MOVQ addr+0(FP), RARG0
|
| 67 |
+
MOVQ n+8(FP), RARG1
|
| 68 |
+
// void __asan_register_globals_go(void *addr, uintptr_t n);
|
| 69 |
+
MOVQ $__asan_register_globals_go(SB), AX
|
| 70 |
+
JMP asancall<>(SB)
|
| 71 |
+
|
| 72 |
+
// func runtime·lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 73 |
+
TEXT runtime·lsanregisterrootregion(SB), NOSPLIT, $0-16
|
| 74 |
+
MOVQ addr+0(FP), RARG0
|
| 75 |
+
MOVQ n+8(FP), RARG1
|
| 76 |
+
// void __lsan_register_root_region_go(void *addr, uintptr_t sz)
|
| 77 |
+
MOVQ $__lsan_register_root_region_go(SB), AX
|
| 78 |
+
JMP asancall<>(SB)
|
| 79 |
+
|
| 80 |
+
// func runtime·lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 81 |
+
TEXT runtime·lsanunregisterrootregion(SB), NOSPLIT, $0-16
|
| 82 |
+
MOVQ addr+0(FP), RARG0
|
| 83 |
+
MOVQ n+8(FP), RARG1
|
| 84 |
+
// void __lsan_unregister_root_region_go(void *addr, uintptr_t sz)
|
| 85 |
+
MOVQ $__lsan_unregister_root_region_go(SB), AX
|
| 86 |
+
JMP asancall<>(SB)
|
| 87 |
+
|
| 88 |
+
// func runtime·lsandoleakcheck()
|
| 89 |
+
TEXT runtime·lsandoleakcheck(SB), NOSPLIT, $0-0
|
| 90 |
+
// void __lsan_do_leak_check_go(void);
|
| 91 |
+
MOVQ $__lsan_do_leak_check_go(SB), AX
|
| 92 |
+
JMP asancall<>(SB)
|
| 93 |
+
|
| 94 |
+
// Switches SP to g0 stack and calls (AX). Arguments already set.
|
| 95 |
+
TEXT asancall<>(SB), NOSPLIT, $0-0
|
| 96 |
+
get_tls(R12)
|
| 97 |
+
MOVQ g(R12), R14
|
| 98 |
+
MOVQ SP, R12 // callee-saved, preserved across the CALL
|
| 99 |
+
CMPQ R14, $0
|
| 100 |
+
JE call // no g; still on a system stack
|
| 101 |
+
|
| 102 |
+
MOVQ g_m(R14), R13
|
| 103 |
+
|
| 104 |
+
// Switch to g0 stack if we aren't already on g0 or gsignal.
|
| 105 |
+
MOVQ m_gsignal(R13), R10
|
| 106 |
+
CMPQ R10, R14
|
| 107 |
+
JE call // already on gsignal
|
| 108 |
+
|
| 109 |
+
MOVQ m_g0(R13), R10
|
| 110 |
+
CMPQ R10, R14
|
| 111 |
+
JE call // already on g0
|
| 112 |
+
|
| 113 |
+
MOVQ (g_sched+gobuf_sp)(R10), SP
|
| 114 |
+
call:
|
| 115 |
+
ANDQ $~15, SP // alignment for gcc ABI
|
| 116 |
+
CALL AX
|
| 117 |
+
MOVQ R12, SP
|
| 118 |
+
RET
|
go/src/runtime/asan_arm64.s
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
#include "go_asm.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
|
| 10 |
+
#define RARG0 R0
|
| 11 |
+
#define RARG1 R1
|
| 12 |
+
#define RARG2 R2
|
| 13 |
+
#define RARG3 R3
|
| 14 |
+
#define FARG R4
|
| 15 |
+
|
| 16 |
+
// Called from instrumented code.
|
| 17 |
+
// func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 18 |
+
TEXT runtime·doasanread(SB), NOSPLIT, $0-32
|
| 19 |
+
MOVD addr+0(FP), RARG0
|
| 20 |
+
MOVD sz+8(FP), RARG1
|
| 21 |
+
MOVD sp+16(FP), RARG2
|
| 22 |
+
MOVD pc+24(FP), RARG3
|
| 23 |
+
// void __asan_read_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 24 |
+
MOVD $__asan_read_go(SB), FARG
|
| 25 |
+
JMP asancall<>(SB)
|
| 26 |
+
|
| 27 |
+
// func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 28 |
+
TEXT runtime·doasanwrite(SB), NOSPLIT, $0-32
|
| 29 |
+
MOVD addr+0(FP), RARG0
|
| 30 |
+
MOVD sz+8(FP), RARG1
|
| 31 |
+
MOVD sp+16(FP), RARG2
|
| 32 |
+
MOVD pc+24(FP), RARG3
|
| 33 |
+
// void __asan_write_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 34 |
+
MOVD $__asan_write_go(SB), FARG
|
| 35 |
+
JMP asancall<>(SB)
|
| 36 |
+
|
| 37 |
+
// func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 38 |
+
TEXT runtime·asanunpoison(SB), NOSPLIT, $0-16
|
| 39 |
+
MOVD addr+0(FP), RARG0
|
| 40 |
+
MOVD sz+8(FP), RARG1
|
| 41 |
+
// void __asan_unpoison_go(void *addr, uintptr_t sz);
|
| 42 |
+
MOVD $__asan_unpoison_go(SB), FARG
|
| 43 |
+
JMP asancall<>(SB)
|
| 44 |
+
|
| 45 |
+
// func runtime·asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 46 |
+
TEXT runtime·asanpoison(SB), NOSPLIT, $0-16
|
| 47 |
+
MOVD addr+0(FP), RARG0
|
| 48 |
+
MOVD sz+8(FP), RARG1
|
| 49 |
+
// void __asan_poison_go(void *addr, uintptr_t sz);
|
| 50 |
+
MOVD $__asan_poison_go(SB), FARG
|
| 51 |
+
JMP asancall<>(SB)
|
| 52 |
+
|
| 53 |
+
// func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 54 |
+
TEXT runtime·asanregisterglobals(SB), NOSPLIT, $0-16
|
| 55 |
+
MOVD addr+0(FP), RARG0
|
| 56 |
+
MOVD n+8(FP), RARG1
|
| 57 |
+
// void __asan_register_globals_go(void *addr, uintptr_t n);
|
| 58 |
+
MOVD $__asan_register_globals_go(SB), FARG
|
| 59 |
+
JMP asancall<>(SB)
|
| 60 |
+
|
| 61 |
+
// func runtime·lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 62 |
+
TEXT runtime·lsanregisterrootregion(SB), NOSPLIT, $0-16
|
| 63 |
+
MOVD addr+0(FP), RARG0
|
| 64 |
+
MOVD n+8(FP), RARG1
|
| 65 |
+
// void __lsan_register_root_region_go(void *addr, uintptr_t n);
|
| 66 |
+
MOVD $__lsan_register_root_region_go(SB), FARG
|
| 67 |
+
JMP asancall<>(SB)
|
| 68 |
+
|
| 69 |
+
// func runtime·lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 70 |
+
TEXT runtime·lsanunregisterrootregion(SB), NOSPLIT, $0-16
|
| 71 |
+
MOVD addr+0(FP), RARG0
|
| 72 |
+
MOVD n+8(FP), RARG1
|
| 73 |
+
// void __lsan_unregister_root_region_go(void *addr, uintptr_t n);
|
| 74 |
+
MOVD $__lsan_unregister_root_region_go(SB), FARG
|
| 75 |
+
JMP asancall<>(SB)
|
| 76 |
+
|
| 77 |
+
// func runtime·lsandoleakcheck()
|
| 78 |
+
TEXT runtime·lsandoleakcheck(SB), NOSPLIT, $0-0
|
| 79 |
+
// void __lsan_do_leak_check_go(void);
|
| 80 |
+
MOVD $__lsan_do_leak_check_go(SB), FARG
|
| 81 |
+
JMP asancall<>(SB)
|
| 82 |
+
|
| 83 |
+
// Switches SP to g0 stack and calls (FARG). Arguments already set.
|
| 84 |
+
TEXT asancall<>(SB), NOSPLIT, $0-0
|
| 85 |
+
MOVD RSP, R19 // callee-saved
|
| 86 |
+
CBZ g, call // no g, still on a system stack
|
| 87 |
+
MOVD g_m(g), R10
|
| 88 |
+
|
| 89 |
+
// Switch to g0 stack if we aren't already on g0 or gsignal.
|
| 90 |
+
MOVD m_gsignal(R10), R11
|
| 91 |
+
CMP R11, g
|
| 92 |
+
BEQ call
|
| 93 |
+
|
| 94 |
+
MOVD m_g0(R10), R11
|
| 95 |
+
CMP R11, g
|
| 96 |
+
BEQ call
|
| 97 |
+
|
| 98 |
+
MOVD (g_sched+gobuf_sp)(R11), R5
|
| 99 |
+
MOVD R5, RSP
|
| 100 |
+
|
| 101 |
+
call:
|
| 102 |
+
BL (FARG)
|
| 103 |
+
MOVD R19, RSP
|
| 104 |
+
RET
|
go/src/runtime/asan_loong64.s
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
#include "go_asm.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
|
| 10 |
+
#define RARG0 R4
|
| 11 |
+
#define RARG1 R5
|
| 12 |
+
#define RARG2 R6
|
| 13 |
+
#define RARG3 R7
|
| 14 |
+
#define FARG R8
|
| 15 |
+
|
| 16 |
+
// Called from instrumented code.
|
| 17 |
+
// func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 18 |
+
TEXT runtime·doasanread(SB), NOSPLIT, $0-32
|
| 19 |
+
MOVV addr+0(FP), RARG0
|
| 20 |
+
MOVV sz+8(FP), RARG1
|
| 21 |
+
MOVV sp+16(FP), RARG2
|
| 22 |
+
MOVV pc+24(FP), RARG3
|
| 23 |
+
// void __asan_read_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 24 |
+
MOVV $__asan_read_go(SB), FARG
|
| 25 |
+
JMP asancall<>(SB)
|
| 26 |
+
|
| 27 |
+
// func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 28 |
+
TEXT runtime·doasanwrite(SB), NOSPLIT, $0-32
|
| 29 |
+
MOVV addr+0(FP), RARG0
|
| 30 |
+
MOVV sz+8(FP), RARG1
|
| 31 |
+
MOVV sp+16(FP), RARG2
|
| 32 |
+
MOVV pc+24(FP), RARG3
|
| 33 |
+
// void __asan_write_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 34 |
+
MOVV $__asan_write_go(SB), FARG
|
| 35 |
+
JMP asancall<>(SB)
|
| 36 |
+
|
| 37 |
+
// func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 38 |
+
TEXT runtime·asanunpoison(SB), NOSPLIT, $0-16
|
| 39 |
+
MOVV addr+0(FP), RARG0
|
| 40 |
+
MOVV sz+8(FP), RARG1
|
| 41 |
+
// void __asan_unpoison_go(void *addr, uintptr_t sz);
|
| 42 |
+
MOVV $__asan_unpoison_go(SB), FARG
|
| 43 |
+
JMP asancall<>(SB)
|
| 44 |
+
|
| 45 |
+
// func runtime·asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 46 |
+
TEXT runtime·asanpoison(SB), NOSPLIT, $0-16
|
| 47 |
+
MOVV addr+0(FP), RARG0
|
| 48 |
+
MOVV sz+8(FP), RARG1
|
| 49 |
+
// void __asan_poison_go(void *addr, uintptr_t sz);
|
| 50 |
+
MOVV $__asan_poison_go(SB), FARG
|
| 51 |
+
JMP asancall<>(SB)
|
| 52 |
+
|
| 53 |
+
// func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 54 |
+
TEXT runtime·asanregisterglobals(SB), NOSPLIT, $0-16
|
| 55 |
+
MOVV addr+0(FP), RARG0
|
| 56 |
+
MOVV n+8(FP), RARG1
|
| 57 |
+
// void __asan_register_globals_go(void *addr, uintptr_t n);
|
| 58 |
+
MOVV $__asan_register_globals_go(SB), FARG
|
| 59 |
+
JMP asancall<>(SB)
|
| 60 |
+
|
| 61 |
+
// func runtime·lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 62 |
+
TEXT runtime·lsanregisterrootregion(SB), NOSPLIT, $0-16
|
| 63 |
+
MOVV addr+0(FP), RARG0
|
| 64 |
+
MOVV n+8(FP), RARG1
|
| 65 |
+
// void __lsan_register_root_region_go(void *addr, uintptr_t n);
|
| 66 |
+
MOVV $__lsan_register_root_region_go(SB), FARG
|
| 67 |
+
JMP asancall<>(SB)
|
| 68 |
+
|
| 69 |
+
// func runtime·lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 70 |
+
TEXT runtime·lsanunregisterrootregion(SB), NOSPLIT, $0-16
|
| 71 |
+
MOVV addr+0(FP), RARG0
|
| 72 |
+
MOVV n+8(FP), RARG1
|
| 73 |
+
// void __lsan_unregister_root_region_go(void *addr, uintptr_t n);
|
| 74 |
+
MOVV $__lsan_unregister_root_region_go(SB), FARG
|
| 75 |
+
JMP asancall<>(SB)
|
| 76 |
+
|
| 77 |
+
// func runtime·lsandoleakcheck()
|
| 78 |
+
TEXT runtime·lsandoleakcheck(SB), NOSPLIT, $0-0
|
| 79 |
+
// void __lsan_do_leak_check_go(void);
|
| 80 |
+
MOVV $__lsan_do_leak_check_go(SB), FARG
|
| 81 |
+
JMP asancall<>(SB)
|
| 82 |
+
|
| 83 |
+
// Switches SP to g0 stack and calls (FARG). Arguments already set.
|
| 84 |
+
TEXT asancall<>(SB), NOSPLIT, $0-0
|
| 85 |
+
MOVV R3, R23 // callee-saved
|
| 86 |
+
BEQ g, call // no g, still on a system stack
|
| 87 |
+
MOVV g_m(g), R14
|
| 88 |
+
|
| 89 |
+
// Switch to g0 stack if we aren't already on g0 or gsignal.
|
| 90 |
+
MOVV m_gsignal(R14), R15
|
| 91 |
+
BEQ R15, g, call
|
| 92 |
+
|
| 93 |
+
MOVV m_g0(R14), R15
|
| 94 |
+
BEQ R15, g, call
|
| 95 |
+
|
| 96 |
+
MOVV (g_sched+gobuf_sp)(R15), R9
|
| 97 |
+
MOVV R9, R3
|
| 98 |
+
|
| 99 |
+
call:
|
| 100 |
+
JAL (FARG)
|
| 101 |
+
MOVV R23, R3
|
| 102 |
+
RET
|
go/src/runtime/asan_ppc64le.s
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
#include "go_asm.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
|
| 10 |
+
#define RARG0 R3
|
| 11 |
+
#define RARG1 R4
|
| 12 |
+
#define RARG2 R5
|
| 13 |
+
#define RARG3 R6
|
| 14 |
+
#define FARG R12
|
| 15 |
+
|
| 16 |
+
// Called from instrumented code.
|
| 17 |
+
// func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 18 |
+
TEXT runtime·doasanread(SB),NOSPLIT|NOFRAME,$0-32
|
| 19 |
+
MOVD addr+0(FP), RARG0
|
| 20 |
+
MOVD sz+8(FP), RARG1
|
| 21 |
+
MOVD sp+16(FP), RARG2
|
| 22 |
+
MOVD pc+24(FP), RARG3
|
| 23 |
+
// void __asan_read_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 24 |
+
MOVD $__asan_read_go(SB), FARG
|
| 25 |
+
BR asancall<>(SB)
|
| 26 |
+
|
| 27 |
+
// func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 28 |
+
TEXT runtime·doasanwrite(SB),NOSPLIT|NOFRAME,$0-32
|
| 29 |
+
MOVD addr+0(FP), RARG0
|
| 30 |
+
MOVD sz+8(FP), RARG1
|
| 31 |
+
MOVD sp+16(FP), RARG2
|
| 32 |
+
MOVD pc+24(FP), RARG3
|
| 33 |
+
// void __asan_write_go(void *addr, uintptr_t sz, void *sp, void *pc);
|
| 34 |
+
MOVD $__asan_write_go(SB), FARG
|
| 35 |
+
BR asancall<>(SB)
|
| 36 |
+
|
| 37 |
+
// func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 38 |
+
TEXT runtime·asanunpoison(SB),NOSPLIT|NOFRAME,$0-16
|
| 39 |
+
MOVD addr+0(FP), RARG0
|
| 40 |
+
MOVD sz+8(FP), RARG1
|
| 41 |
+
// void __asan_unpoison_go(void *addr, uintptr_t sz);
|
| 42 |
+
MOVD $__asan_unpoison_go(SB), FARG
|
| 43 |
+
BR asancall<>(SB)
|
| 44 |
+
|
| 45 |
+
// func runtime·asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 46 |
+
TEXT runtime·asanpoison(SB),NOSPLIT|NOFRAME,$0-16
|
| 47 |
+
MOVD addr+0(FP), RARG0
|
| 48 |
+
MOVD sz+8(FP), RARG1
|
| 49 |
+
// void __asan_poison_go(void *addr, uintptr_t sz);
|
| 50 |
+
MOVD $__asan_poison_go(SB), FARG
|
| 51 |
+
BR asancall<>(SB)
|
| 52 |
+
|
| 53 |
+
// func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 54 |
+
TEXT runtime·asanregisterglobals(SB),NOSPLIT|NOFRAME,$0-16
|
| 55 |
+
MOVD addr+0(FP), RARG0
|
| 56 |
+
MOVD n+8(FP), RARG1
|
| 57 |
+
// void __asan_register_globals_go(void *addr, uintptr_t n);
|
| 58 |
+
MOVD $__asan_register_globals_go(SB), FARG
|
| 59 |
+
BR asancall<>(SB)
|
| 60 |
+
|
| 61 |
+
// func runtime·lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 62 |
+
TEXT runtime·lsanregisterrootregion(SB),NOSPLIT|NOFRAME,$0-16
|
| 63 |
+
MOVD addr+0(FP), RARG0
|
| 64 |
+
MOVD n+8(FP), RARG1
|
| 65 |
+
// void __lsan_register_root_region_go(void *addr, uintptr_t n);
|
| 66 |
+
MOVD $__lsan_register_root_region_go(SB), FARG
|
| 67 |
+
BR asancall<>(SB)
|
| 68 |
+
|
| 69 |
+
// func runtime·lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 70 |
+
TEXT runtime·lsanunregisterrootregion(SB),NOSPLIT|NOFRAME,$0-16
|
| 71 |
+
MOVD addr+0(FP), RARG0
|
| 72 |
+
MOVD n+8(FP), RARG1
|
| 73 |
+
// void __lsan_unregister_root_region_go(void *addr, uintptr_t n);
|
| 74 |
+
MOVD $__lsan_unregister_root_region_go(SB), FARG
|
| 75 |
+
BR asancall<>(SB)
|
| 76 |
+
|
| 77 |
+
// func runtime·lsandoleakcheck()
|
| 78 |
+
TEXT runtime·lsandoleakcheck(SB), NOSPLIT|NOFRAME, $0-0
|
| 79 |
+
// void __lsan_do_leak_check_go(void);
|
| 80 |
+
MOVD $__lsan_do_leak_check_go(SB), FARG
|
| 81 |
+
BR asancall<>(SB)
|
| 82 |
+
|
| 83 |
+
// Switches SP to g0 stack and calls (FARG). Arguments already set.
|
| 84 |
+
TEXT asancall<>(SB), NOSPLIT, $0-0
|
| 85 |
+
// LR saved in generated prologue
|
| 86 |
+
// Get info from the current goroutine
|
| 87 |
+
MOVD runtime·tls_g(SB), R10 // g offset in TLS
|
| 88 |
+
MOVD 0(R10), g
|
| 89 |
+
MOVD g_m(g), R7 // m for g
|
| 90 |
+
MOVD R1, R16 // callee-saved, preserved across C call
|
| 91 |
+
|
| 92 |
+
// Switch to g0 stack if we aren't already on g0 or gsignal.
|
| 93 |
+
MOVD m_gsignal(R7), R10
|
| 94 |
+
CMP R10, g
|
| 95 |
+
BEQ call
|
| 96 |
+
|
| 97 |
+
MOVD m_g0(R7), R10
|
| 98 |
+
CMP R10, g
|
| 99 |
+
BEQ call
|
| 100 |
+
|
| 101 |
+
MOVD (g_sched+gobuf_sp)(R10), R1 // switch R1
|
| 102 |
+
|
| 103 |
+
call:
|
| 104 |
+
// prepare frame for C ABI
|
| 105 |
+
SUB $32, R1 // create frame for callee saving LR, CR, R2 etc.
|
| 106 |
+
RLDCR $0, R1, $~15, R1 // align SP to 16 bytes
|
| 107 |
+
MOVD FARG, CTR // address of function to be called
|
| 108 |
+
MOVD R0, 0(R1) // clear back chain pointer
|
| 109 |
+
BL (CTR)
|
| 110 |
+
MOVD $0, R0 // C code can clobber R0 set it back to 0
|
| 111 |
+
MOVD R16, R1 // restore R1;
|
| 112 |
+
MOVD runtime·tls_g(SB), R10 // find correct g
|
| 113 |
+
MOVD 0(R10), g
|
| 114 |
+
RET
|
| 115 |
+
|
| 116 |
+
// tls_g, g value for each thread in TLS
|
| 117 |
+
GLOBL runtime·tls_g+0(SB), TLSBSS+DUPOK, $8
|
go/src/runtime/asan_riscv64.s
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asan
|
| 6 |
+
|
| 7 |
+
#include "go_asm.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
|
| 10 |
+
// Called from instrumented code.
|
| 11 |
+
// func runtime·doasanread(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 12 |
+
TEXT runtime·doasanread(SB), NOSPLIT, $0-32
|
| 13 |
+
MOV addr+0(FP), X10
|
| 14 |
+
MOV sz+8(FP), X11
|
| 15 |
+
MOV sp+16(FP), X12
|
| 16 |
+
MOV pc+24(FP), X13
|
| 17 |
+
// void __asan_read_go(void *addr, uintptr_t sz);
|
| 18 |
+
MOV $__asan_read_go(SB), X14
|
| 19 |
+
JMP asancall<>(SB)
|
| 20 |
+
|
| 21 |
+
// func runtime·doasanwrite(addr unsafe.Pointer, sz, sp, pc uintptr)
|
| 22 |
+
TEXT runtime·doasanwrite(SB), NOSPLIT, $0-32
|
| 23 |
+
MOV addr+0(FP), X10
|
| 24 |
+
MOV sz+8(FP), X11
|
| 25 |
+
MOV sp+16(FP), X12
|
| 26 |
+
MOV pc+24(FP), X13
|
| 27 |
+
// void __asan_write_go(void *addr, uintptr_t sz);
|
| 28 |
+
MOV $__asan_write_go(SB), X14
|
| 29 |
+
JMP asancall<>(SB)
|
| 30 |
+
|
| 31 |
+
// func runtime·asanunpoison(addr unsafe.Pointer, sz uintptr)
|
| 32 |
+
TEXT runtime·asanunpoison(SB), NOSPLIT, $0-16
|
| 33 |
+
MOV addr+0(FP), X10
|
| 34 |
+
MOV sz+8(FP), X11
|
| 35 |
+
// void __asan_unpoison_go(void *addr, uintptr_t sz);
|
| 36 |
+
MOV $__asan_unpoison_go(SB), X14
|
| 37 |
+
JMP asancall<>(SB)
|
| 38 |
+
|
| 39 |
+
// func runtime·asanpoison(addr unsafe.Pointer, sz uintptr)
|
| 40 |
+
TEXT runtime·asanpoison(SB), NOSPLIT, $0-16
|
| 41 |
+
MOV addr+0(FP), X10
|
| 42 |
+
MOV sz+8(FP), X11
|
| 43 |
+
// void __asan_poison_go(void *addr, uintptr_t sz);
|
| 44 |
+
MOV $__asan_poison_go(SB), X14
|
| 45 |
+
JMP asancall<>(SB)
|
| 46 |
+
|
| 47 |
+
// func runtime·asanregisterglobals(addr unsafe.Pointer, n uintptr)
|
| 48 |
+
TEXT runtime·asanregisterglobals(SB), NOSPLIT, $0-16
|
| 49 |
+
MOV addr+0(FP), X10
|
| 50 |
+
MOV n+8(FP), X11
|
| 51 |
+
// void __asan_register_globals_go(void *addr, uintptr_t n);
|
| 52 |
+
MOV $__asan_register_globals_go(SB), X14
|
| 53 |
+
JMP asancall<>(SB)
|
| 54 |
+
|
| 55 |
+
// func runtime·lsanregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 56 |
+
TEXT runtime·lsanregisterrootregion(SB), NOSPLIT, $0-16
|
| 57 |
+
MOV addr+0(FP), X10
|
| 58 |
+
MOV n+8(FP), X11
|
| 59 |
+
// void __lsan_register_root_region_go(void *addr, uintptr_t n);
|
| 60 |
+
MOV $__lsan_register_root_region_go(SB), X14
|
| 61 |
+
JMP asancall<>(SB)
|
| 62 |
+
|
| 63 |
+
// func runtime·lsanunregisterrootregion(addr unsafe.Pointer, n uintptr)
|
| 64 |
+
TEXT runtime·lsanunregisterrootregion(SB), NOSPLIT, $0-16
|
| 65 |
+
MOV addr+0(FP), X10
|
| 66 |
+
MOV n+8(FP), X11
|
| 67 |
+
// void __lsan_unregister_root_region_go(void *addr, uintptr_t n);
|
| 68 |
+
MOV $__lsan_unregister_root_region_go(SB), X14
|
| 69 |
+
JMP asancall<>(SB)
|
| 70 |
+
|
| 71 |
+
// func runtime·lsandoleakcheck()
|
| 72 |
+
TEXT runtime·lsandoleakcheck(SB), NOSPLIT, $0-0
|
| 73 |
+
// void __lsan_do_leak_check_go(void);
|
| 74 |
+
MOV $__lsan_do_leak_check_go(SB), X14
|
| 75 |
+
JMP asancall<>(SB)
|
| 76 |
+
|
| 77 |
+
// Switches SP to g0 stack and calls (X14). Arguments already set.
|
| 78 |
+
TEXT asancall<>(SB), NOSPLIT, $0-0
|
| 79 |
+
MOV X2, X8 // callee-saved
|
| 80 |
+
BEQZ g, call // no g, still on a system stack
|
| 81 |
+
MOV g_m(g), X21
|
| 82 |
+
|
| 83 |
+
// Switch to g0 stack if we aren't already on g0 or gsignal.
|
| 84 |
+
MOV m_gsignal(X21), X22
|
| 85 |
+
BEQ X22, g, call
|
| 86 |
+
|
| 87 |
+
MOV m_g0(X21), X22
|
| 88 |
+
BEQ X22, g, call
|
| 89 |
+
|
| 90 |
+
MOV (g_sched+gobuf_sp)(X22), X2
|
| 91 |
+
|
| 92 |
+
call:
|
| 93 |
+
JALR RA, X14
|
| 94 |
+
MOV X8, X2
|
| 95 |
+
RET
|
go/src/runtime/asm.s
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2014 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 |
+
#ifndef GOARCH_amd64
|
| 8 |
+
TEXT ·sigpanic0(SB),NOSPLIT,$0-0
|
| 9 |
+
JMP ·sigpanic<ABIInternal>(SB)
|
| 10 |
+
#endif
|
| 11 |
+
|
| 12 |
+
// See map.go comment on the need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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 "go_asm.h"
|
| 6 |
+
#include "go_tls.h"
|
| 7 |
+
#include "funcdata.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
|
| 10 |
+
// _rt0_386 is common startup code for most 386 systems when using
|
| 11 |
+
// internal linking. This is the entry point for the program from the
|
| 12 |
+
// kernel for an ordinary -buildmode=exe program. The stack holds the
|
| 13 |
+
// number of arguments and the C-style argv.
|
| 14 |
+
TEXT _rt0_386(SB),NOSPLIT,$8
|
| 15 |
+
MOVL 8(SP), AX // argc
|
| 16 |
+
LEAL 12(SP), BX // argv
|
| 17 |
+
MOVL AX, 0(SP)
|
| 18 |
+
MOVL BX, 4(SP)
|
| 19 |
+
JMP runtime·rt0_go(SB)
|
| 20 |
+
|
| 21 |
+
// _rt0_386_lib is common startup code for most 386 systems when
|
| 22 |
+
// using -buildmode=c-archive or -buildmode=c-shared. The linker will
|
| 23 |
+
// arrange to invoke this function as a global constructor (for
|
| 24 |
+
// c-archive) or when the shared library is loaded (for c-shared).
|
| 25 |
+
// We expect argc and argv to be passed on the stack following the
|
| 26 |
+
// usual C ABI.
|
| 27 |
+
TEXT _rt0_386_lib(SB),NOSPLIT,$0
|
| 28 |
+
PUSHL BP
|
| 29 |
+
MOVL SP, BP
|
| 30 |
+
PUSHL BX
|
| 31 |
+
PUSHL SI
|
| 32 |
+
PUSHL DI
|
| 33 |
+
|
| 34 |
+
MOVL 8(BP), AX
|
| 35 |
+
MOVL AX, _rt0_386_lib_argc<>(SB)
|
| 36 |
+
MOVL 12(BP), AX
|
| 37 |
+
MOVL AX, _rt0_386_lib_argv<>(SB)
|
| 38 |
+
|
| 39 |
+
// Synchronous initialization.
|
| 40 |
+
CALL runtime·libpreinit(SB)
|
| 41 |
+
|
| 42 |
+
SUBL $8, SP
|
| 43 |
+
|
| 44 |
+
// Create a new thread to do the runtime initialization.
|
| 45 |
+
MOVL _cgo_sys_thread_create(SB), AX
|
| 46 |
+
TESTL AX, AX
|
| 47 |
+
JZ nocgo
|
| 48 |
+
|
| 49 |
+
// Align stack to call C function.
|
| 50 |
+
// We moved SP to BP above, but BP was clobbered by the libpreinit call.
|
| 51 |
+
MOVL SP, BP
|
| 52 |
+
ANDL $~15, SP
|
| 53 |
+
|
| 54 |
+
MOVL $_rt0_386_lib_go(SB), BX
|
| 55 |
+
MOVL BX, 0(SP)
|
| 56 |
+
MOVL $0, 4(SP)
|
| 57 |
+
|
| 58 |
+
CALL AX
|
| 59 |
+
|
| 60 |
+
MOVL BP, SP
|
| 61 |
+
|
| 62 |
+
JMP restore
|
| 63 |
+
|
| 64 |
+
nocgo:
|
| 65 |
+
MOVL $0x800000, 0(SP) // stacksize = 8192KB
|
| 66 |
+
MOVL $_rt0_386_lib_go(SB), AX
|
| 67 |
+
MOVL AX, 4(SP) // fn
|
| 68 |
+
CALL runtime·newosproc0(SB)
|
| 69 |
+
|
| 70 |
+
restore:
|
| 71 |
+
ADDL $8, SP
|
| 72 |
+
POPL DI
|
| 73 |
+
POPL SI
|
| 74 |
+
POPL BX
|
| 75 |
+
POPL BP
|
| 76 |
+
RET
|
| 77 |
+
|
| 78 |
+
// _rt0_386_lib_go initializes the Go runtime.
|
| 79 |
+
// This is started in a separate thread by _rt0_386_lib.
|
| 80 |
+
TEXT _rt0_386_lib_go(SB),NOSPLIT,$8
|
| 81 |
+
MOVL _rt0_386_lib_argc<>(SB), AX
|
| 82 |
+
MOVL AX, 0(SP)
|
| 83 |
+
MOVL _rt0_386_lib_argv<>(SB), AX
|
| 84 |
+
MOVL AX, 4(SP)
|
| 85 |
+
JMP runtime·rt0_go(SB)
|
| 86 |
+
|
| 87 |
+
DATA _rt0_386_lib_argc<>(SB)/4, $0
|
| 88 |
+
GLOBL _rt0_386_lib_argc<>(SB),NOPTR, $4
|
| 89 |
+
DATA _rt0_386_lib_argv<>(SB)/4, $0
|
| 90 |
+
GLOBL _rt0_386_lib_argv<>(SB),NOPTR, $4
|
| 91 |
+
|
| 92 |
+
TEXT runtime·rt0_go(SB),NOSPLIT|NOFRAME|TOPFRAME,$0
|
| 93 |
+
// Copy arguments forward on an even stack.
|
| 94 |
+
// Users of this function jump to it, they don't call it.
|
| 95 |
+
MOVL 0(SP), AX
|
| 96 |
+
MOVL 4(SP), BX
|
| 97 |
+
SUBL $128, SP // plenty of scratch
|
| 98 |
+
ANDL $~15, SP
|
| 99 |
+
MOVL AX, 120(SP) // save argc, argv away
|
| 100 |
+
MOVL BX, 124(SP)
|
| 101 |
+
|
| 102 |
+
// set default stack bounds.
|
| 103 |
+
// _cgo_init may update stackguard.
|
| 104 |
+
MOVL $runtime·g0(SB), BP
|
| 105 |
+
LEAL (-64*1024+104)(SP), BX
|
| 106 |
+
MOVL BX, g_stackguard0(BP)
|
| 107 |
+
MOVL BX, g_stackguard1(BP)
|
| 108 |
+
MOVL BX, (g_stack+stack_lo)(BP)
|
| 109 |
+
MOVL SP, (g_stack+stack_hi)(BP)
|
| 110 |
+
|
| 111 |
+
// find out information about the processor we're on
|
| 112 |
+
// first see if CPUID instruction is supported.
|
| 113 |
+
PUSHFL
|
| 114 |
+
PUSHFL
|
| 115 |
+
XORL $(1<<21), 0(SP) // flip ID bit
|
| 116 |
+
POPFL
|
| 117 |
+
PUSHFL
|
| 118 |
+
POPL AX
|
| 119 |
+
XORL 0(SP), AX
|
| 120 |
+
POPFL // restore EFLAGS
|
| 121 |
+
TESTL $(1<<21), AX
|
| 122 |
+
JNE has_cpuid
|
| 123 |
+
|
| 124 |
+
bad_proc: // show that the program requires MMX.
|
| 125 |
+
MOVL $2, 0(SP)
|
| 126 |
+
MOVL $bad_proc_msg<>(SB), 4(SP)
|
| 127 |
+
MOVL $0x3d, 8(SP)
|
| 128 |
+
CALL runtime·write(SB)
|
| 129 |
+
MOVL $1, 0(SP)
|
| 130 |
+
CALL runtime·exit(SB)
|
| 131 |
+
CALL runtime·abort(SB)
|
| 132 |
+
|
| 133 |
+
has_cpuid:
|
| 134 |
+
MOVL $0, AX
|
| 135 |
+
CPUID
|
| 136 |
+
MOVL AX, SI
|
| 137 |
+
CMPL AX, $0
|
| 138 |
+
JE nocpuinfo
|
| 139 |
+
|
| 140 |
+
CMPL BX, $0x756E6547 // "Genu"
|
| 141 |
+
JNE notintel
|
| 142 |
+
CMPL DX, $0x49656E69 // "ineI"
|
| 143 |
+
JNE notintel
|
| 144 |
+
CMPL CX, $0x6C65746E // "ntel"
|
| 145 |
+
JNE notintel
|
| 146 |
+
MOVB $1, runtime·isIntel(SB)
|
| 147 |
+
notintel:
|
| 148 |
+
|
| 149 |
+
// Load EAX=1 cpuid flags
|
| 150 |
+
MOVL $1, AX
|
| 151 |
+
CPUID
|
| 152 |
+
MOVL CX, DI // Move to global variable clobbers CX when generating PIC
|
| 153 |
+
MOVL AX, runtime·processorVersionInfo(SB)
|
| 154 |
+
|
| 155 |
+
// Check for MMX support
|
| 156 |
+
TESTL $(1<<23), DX // MMX
|
| 157 |
+
JZ bad_proc
|
| 158 |
+
|
| 159 |
+
nocpuinfo:
|
| 160 |
+
// if there is an _cgo_init, call it to let it
|
| 161 |
+
// initialize and to set up GS. if not,
|
| 162 |
+
// we set up GS ourselves.
|
| 163 |
+
MOVL _cgo_init(SB), AX
|
| 164 |
+
TESTL AX, AX
|
| 165 |
+
JZ needtls
|
| 166 |
+
#ifdef GOOS_android
|
| 167 |
+
// arg 4: TLS base, stored in slot 0 (Android's TLS_SLOT_SELF).
|
| 168 |
+
// Compensate for tls_g (+8).
|
| 169 |
+
MOVL -8(TLS), BX
|
| 170 |
+
MOVL BX, 12(SP)
|
| 171 |
+
MOVL $runtime·tls_g(SB), 8(SP) // arg 3: &tls_g
|
| 172 |
+
#else
|
| 173 |
+
MOVL $0, BX
|
| 174 |
+
MOVL BX, 12(SP) // arg 4: not used when using platform's TLS
|
| 175 |
+
#ifdef GOOS_windows
|
| 176 |
+
MOVL $runtime·tls_g(SB), 8(SP) // arg 3: &tls_g
|
| 177 |
+
#else
|
| 178 |
+
MOVL BX, 8(SP) // arg 3: not used when using platform's TLS
|
| 179 |
+
#endif
|
| 180 |
+
#endif
|
| 181 |
+
MOVL $setg_gcc<>(SB), BX
|
| 182 |
+
MOVL BX, 4(SP) // arg 2: setg_gcc
|
| 183 |
+
MOVL BP, 0(SP) // arg 1: g0
|
| 184 |
+
CALL AX
|
| 185 |
+
|
| 186 |
+
// update stackguard after _cgo_init
|
| 187 |
+
MOVL $runtime·g0(SB), CX
|
| 188 |
+
MOVL (g_stack+stack_lo)(CX), AX
|
| 189 |
+
ADDL $const_stackGuard, AX
|
| 190 |
+
MOVL AX, g_stackguard0(CX)
|
| 191 |
+
MOVL AX, g_stackguard1(CX)
|
| 192 |
+
|
| 193 |
+
#ifndef GOOS_windows
|
| 194 |
+
// skip runtime·ldt0setup(SB) and tls test after _cgo_init for non-windows
|
| 195 |
+
JMP ok
|
| 196 |
+
#endif
|
| 197 |
+
needtls:
|
| 198 |
+
#ifdef GOOS_openbsd
|
| 199 |
+
// skip runtime·ldt0setup(SB) and tls test on OpenBSD in all cases
|
| 200 |
+
JMP ok
|
| 201 |
+
#endif
|
| 202 |
+
#ifdef GOOS_plan9
|
| 203 |
+
// skip runtime·ldt0setup(SB) and tls test on Plan 9 in all cases
|
| 204 |
+
JMP ok
|
| 205 |
+
#endif
|
| 206 |
+
|
| 207 |
+
// set up %gs
|
| 208 |
+
CALL ldt0setup<>(SB)
|
| 209 |
+
|
| 210 |
+
// store through it, to make sure it works
|
| 211 |
+
get_tls(BX)
|
| 212 |
+
MOVL $0x123, g(BX)
|
| 213 |
+
MOVL runtime·m0+m_tls(SB), AX
|
| 214 |
+
CMPL AX, $0x123
|
| 215 |
+
JEQ ok
|
| 216 |
+
MOVL AX, 0 // abort
|
| 217 |
+
ok:
|
| 218 |
+
// set up m and g "registers"
|
| 219 |
+
get_tls(BX)
|
| 220 |
+
LEAL runtime·g0(SB), DX
|
| 221 |
+
MOVL DX, g(BX)
|
| 222 |
+
LEAL runtime·m0(SB), AX
|
| 223 |
+
|
| 224 |
+
// save m->g0 = g0
|
| 225 |
+
MOVL DX, m_g0(AX)
|
| 226 |
+
// save g0->m = m0
|
| 227 |
+
MOVL AX, g_m(DX)
|
| 228 |
+
|
| 229 |
+
CALL runtime·emptyfunc(SB) // fault if stack check is wrong
|
| 230 |
+
|
| 231 |
+
// convention is D is always cleared
|
| 232 |
+
CLD
|
| 233 |
+
|
| 234 |
+
CALL runtime·check(SB)
|
| 235 |
+
|
| 236 |
+
// saved argc, argv
|
| 237 |
+
MOVL 120(SP), AX
|
| 238 |
+
MOVL AX, 0(SP)
|
| 239 |
+
MOVL 124(SP), AX
|
| 240 |
+
MOVL AX, 4(SP)
|
| 241 |
+
CALL runtime·args(SB)
|
| 242 |
+
CALL runtime·osinit(SB)
|
| 243 |
+
CALL runtime·schedinit(SB)
|
| 244 |
+
|
| 245 |
+
// create a new goroutine to start program
|
| 246 |
+
PUSHL $runtime·mainPC(SB) // entry
|
| 247 |
+
CALL runtime·newproc(SB)
|
| 248 |
+
POPL AX
|
| 249 |
+
|
| 250 |
+
// start this M
|
| 251 |
+
CALL runtime·mstart(SB)
|
| 252 |
+
|
| 253 |
+
CALL runtime·abort(SB)
|
| 254 |
+
RET
|
| 255 |
+
|
| 256 |
+
DATA bad_proc_msg<>+0x00(SB)/61, $"This program can only be run on processors with MMX support.\n"
|
| 257 |
+
GLOBL bad_proc_msg<>(SB), RODATA, $61
|
| 258 |
+
|
| 259 |
+
DATA runtime·mainPC+0(SB)/4,$runtime·main(SB)
|
| 260 |
+
GLOBL runtime·mainPC(SB),RODATA,$4
|
| 261 |
+
|
| 262 |
+
TEXT runtime·breakpoint(SB),NOSPLIT,$0-0
|
| 263 |
+
INT $3
|
| 264 |
+
RET
|
| 265 |
+
|
| 266 |
+
TEXT runtime·asminit(SB),NOSPLIT,$0-0
|
| 267 |
+
// Linux and MinGW start the FPU in extended double precision.
|
| 268 |
+
// Other operating systems use double precision.
|
| 269 |
+
// Change to double precision to match them,
|
| 270 |
+
// and to match other hardware that only has double.
|
| 271 |
+
FLDCW runtime·controlWord64(SB)
|
| 272 |
+
RET
|
| 273 |
+
|
| 274 |
+
TEXT runtime·mstart(SB),NOSPLIT|TOPFRAME,$0
|
| 275 |
+
CALL runtime·mstart0(SB)
|
| 276 |
+
RET // not reached
|
| 277 |
+
|
| 278 |
+
/*
|
| 279 |
+
* go-routine
|
| 280 |
+
*/
|
| 281 |
+
|
| 282 |
+
// void gogo(Gobuf*)
|
| 283 |
+
// restore state from Gobuf; longjmp
|
| 284 |
+
TEXT runtime·gogo(SB), NOSPLIT, $0-4
|
| 285 |
+
MOVL buf+0(FP), BX // gobuf
|
| 286 |
+
MOVL gobuf_g(BX), DX
|
| 287 |
+
MOVL 0(DX), CX // make sure g != nil
|
| 288 |
+
JMP gogo<>(SB)
|
| 289 |
+
|
| 290 |
+
TEXT gogo<>(SB), NOSPLIT, $0
|
| 291 |
+
get_tls(CX)
|
| 292 |
+
MOVL DX, g(CX)
|
| 293 |
+
MOVL gobuf_sp(BX), SP // restore SP
|
| 294 |
+
MOVL gobuf_ctxt(BX), DX
|
| 295 |
+
MOVL $0, gobuf_sp(BX) // clear to help garbage collector
|
| 296 |
+
MOVL $0, gobuf_ctxt(BX)
|
| 297 |
+
MOVL gobuf_pc(BX), BX
|
| 298 |
+
JMP BX
|
| 299 |
+
|
| 300 |
+
// func mcall(fn func(*g))
|
| 301 |
+
// Switch to m->g0's stack, call fn(g).
|
| 302 |
+
// Fn must never return. It should gogo(&g->sched)
|
| 303 |
+
// to keep running g.
|
| 304 |
+
TEXT runtime·mcall(SB), NOSPLIT, $0-4
|
| 305 |
+
MOVL fn+0(FP), DI
|
| 306 |
+
|
| 307 |
+
get_tls(DX)
|
| 308 |
+
MOVL g(DX), AX // save state in g->sched
|
| 309 |
+
MOVL 0(SP), BX // caller's PC
|
| 310 |
+
MOVL BX, (g_sched+gobuf_pc)(AX)
|
| 311 |
+
LEAL fn+0(FP), BX // caller's SP
|
| 312 |
+
MOVL BX, (g_sched+gobuf_sp)(AX)
|
| 313 |
+
|
| 314 |
+
// switch to m->g0 & its stack, call fn
|
| 315 |
+
MOVL g(DX), BX
|
| 316 |
+
MOVL g_m(BX), BX
|
| 317 |
+
MOVL m_g0(BX), SI
|
| 318 |
+
CMPL SI, AX // if g == m->g0 call badmcall
|
| 319 |
+
JNE 3(PC)
|
| 320 |
+
MOVL $runtime·badmcall(SB), AX
|
| 321 |
+
JMP AX
|
| 322 |
+
MOVL SI, g(DX) // g = m->g0
|
| 323 |
+
MOVL (g_sched+gobuf_sp)(SI), SP // sp = m->g0->sched.sp
|
| 324 |
+
PUSHL AX
|
| 325 |
+
MOVL DI, DX
|
| 326 |
+
MOVL 0(DI), DI
|
| 327 |
+
CALL DI
|
| 328 |
+
POPL AX
|
| 329 |
+
MOVL $runtime·badmcall2(SB), AX
|
| 330 |
+
JMP AX
|
| 331 |
+
RET
|
| 332 |
+
|
| 333 |
+
// systemstack_switch is a dummy routine that systemstack leaves at the bottom
|
| 334 |
+
// of the G stack. We need to distinguish the routine that
|
| 335 |
+
// lives at the bottom of the G stack from the one that lives
|
| 336 |
+
// at the top of the system stack because the one at the top of
|
| 337 |
+
// the system stack terminates the stack walk (see topofstack()).
|
| 338 |
+
TEXT runtime·systemstack_switch(SB), NOSPLIT, $0-0
|
| 339 |
+
RET
|
| 340 |
+
|
| 341 |
+
// func systemstack(fn func())
|
| 342 |
+
TEXT runtime·systemstack(SB), NOSPLIT, $0-4
|
| 343 |
+
MOVL fn+0(FP), DI // DI = fn
|
| 344 |
+
get_tls(CX)
|
| 345 |
+
MOVL g(CX), AX // AX = g
|
| 346 |
+
MOVL g_m(AX), BX // BX = m
|
| 347 |
+
|
| 348 |
+
CMPL AX, m_gsignal(BX)
|
| 349 |
+
JEQ noswitch
|
| 350 |
+
|
| 351 |
+
MOVL m_g0(BX), DX // DX = g0
|
| 352 |
+
CMPL AX, DX
|
| 353 |
+
JEQ noswitch
|
| 354 |
+
|
| 355 |
+
CMPL AX, m_curg(BX)
|
| 356 |
+
JNE bad
|
| 357 |
+
|
| 358 |
+
// switch stacks
|
| 359 |
+
// save our state in g->sched. Pretend to
|
| 360 |
+
// be systemstack_switch if the G stack is scanned.
|
| 361 |
+
CALL gosave_systemstack_switch<>(SB)
|
| 362 |
+
|
| 363 |
+
// switch to g0
|
| 364 |
+
get_tls(CX)
|
| 365 |
+
MOVL DX, g(CX)
|
| 366 |
+
MOVL (g_sched+gobuf_sp)(DX), BX
|
| 367 |
+
MOVL BX, SP
|
| 368 |
+
|
| 369 |
+
// call target function
|
| 370 |
+
MOVL DI, DX
|
| 371 |
+
MOVL 0(DI), DI
|
| 372 |
+
CALL DI
|
| 373 |
+
|
| 374 |
+
// switch back to g
|
| 375 |
+
get_tls(CX)
|
| 376 |
+
MOVL g(CX), AX
|
| 377 |
+
MOVL g_m(AX), BX
|
| 378 |
+
MOVL m_curg(BX), AX
|
| 379 |
+
MOVL AX, g(CX)
|
| 380 |
+
MOVL (g_sched+gobuf_sp)(AX), SP
|
| 381 |
+
MOVL $0, (g_sched+gobuf_sp)(AX)
|
| 382 |
+
RET
|
| 383 |
+
|
| 384 |
+
noswitch:
|
| 385 |
+
// already on system stack; tail call the function
|
| 386 |
+
// Using a tail call here cleans up tracebacks since we won't stop
|
| 387 |
+
// at an intermediate systemstack.
|
| 388 |
+
MOVL DI, DX
|
| 389 |
+
MOVL 0(DI), DI
|
| 390 |
+
JMP DI
|
| 391 |
+
|
| 392 |
+
bad:
|
| 393 |
+
// Bad: g is not gsignal, not g0, not curg. What is it?
|
| 394 |
+
// Hide call from linker nosplit analysis.
|
| 395 |
+
MOVL $runtime·badsystemstack(SB), AX
|
| 396 |
+
CALL AX
|
| 397 |
+
INT $3
|
| 398 |
+
|
| 399 |
+
// func switchToCrashStack0(fn func())
|
| 400 |
+
TEXT runtime·switchToCrashStack0(SB), NOSPLIT, $0-4
|
| 401 |
+
MOVL fn+0(FP), AX
|
| 402 |
+
|
| 403 |
+
get_tls(CX)
|
| 404 |
+
MOVL g(CX), BX // BX = g
|
| 405 |
+
MOVL g_m(BX), DX // DX = curm
|
| 406 |
+
|
| 407 |
+
// set g to gcrash
|
| 408 |
+
LEAL runtime·gcrash(SB), BX // g = &gcrash
|
| 409 |
+
MOVL DX, g_m(BX) // g.m = curm
|
| 410 |
+
MOVL BX, m_g0(DX) // curm.g0 = g
|
| 411 |
+
get_tls(CX)
|
| 412 |
+
MOVL BX, g(CX)
|
| 413 |
+
|
| 414 |
+
// switch to crashstack
|
| 415 |
+
MOVL (g_stack+stack_hi)(BX), DX
|
| 416 |
+
SUBL $(4*8), DX
|
| 417 |
+
MOVL DX, SP
|
| 418 |
+
|
| 419 |
+
// call target function
|
| 420 |
+
MOVL AX, DX
|
| 421 |
+
MOVL 0(AX), AX
|
| 422 |
+
CALL AX
|
| 423 |
+
|
| 424 |
+
// should never return
|
| 425 |
+
CALL runtime·abort(SB)
|
| 426 |
+
UNDEF
|
| 427 |
+
|
| 428 |
+
/*
|
| 429 |
+
* support for morestack
|
| 430 |
+
*/
|
| 431 |
+
|
| 432 |
+
// Called during function prolog when more stack is needed.
|
| 433 |
+
//
|
| 434 |
+
// The traceback routines see morestack on a g0 as being
|
| 435 |
+
// the top of a stack (for example, morestack calling newstack
|
| 436 |
+
// calling the scheduler calling newm calling gc), so we must
|
| 437 |
+
// record an argument size. For that purpose, it has no arguments.
|
| 438 |
+
TEXT runtime·morestack(SB),NOSPLIT|NOFRAME,$0-0
|
| 439 |
+
// Cannot grow scheduler stack (m->g0).
|
| 440 |
+
get_tls(CX)
|
| 441 |
+
MOVL g(CX), DI
|
| 442 |
+
MOVL g_m(DI), BX
|
| 443 |
+
|
| 444 |
+
// Set g->sched to context in f.
|
| 445 |
+
MOVL 0(SP), AX // f's PC
|
| 446 |
+
MOVL AX, (g_sched+gobuf_pc)(DI)
|
| 447 |
+
LEAL 4(SP), AX // f's SP
|
| 448 |
+
MOVL AX, (g_sched+gobuf_sp)(DI)
|
| 449 |
+
MOVL DX, (g_sched+gobuf_ctxt)(DI)
|
| 450 |
+
|
| 451 |
+
MOVL m_g0(BX), SI
|
| 452 |
+
CMPL g(CX), SI
|
| 453 |
+
JNE 3(PC)
|
| 454 |
+
CALL runtime·badmorestackg0(SB)
|
| 455 |
+
CALL runtime·abort(SB)
|
| 456 |
+
|
| 457 |
+
// Cannot grow signal stack.
|
| 458 |
+
MOVL m_gsignal(BX), SI
|
| 459 |
+
CMPL g(CX), SI
|
| 460 |
+
JNE 3(PC)
|
| 461 |
+
CALL runtime·badmorestackgsignal(SB)
|
| 462 |
+
CALL runtime·abort(SB)
|
| 463 |
+
|
| 464 |
+
// Called from f.
|
| 465 |
+
// Set m->morebuf to f's caller.
|
| 466 |
+
NOP SP // tell vet SP changed - stop checking offsets
|
| 467 |
+
MOVL 4(SP), DI // f's caller's PC
|
| 468 |
+
MOVL DI, (m_morebuf+gobuf_pc)(BX)
|
| 469 |
+
LEAL 8(SP), CX // f's caller's SP
|
| 470 |
+
MOVL CX, (m_morebuf+gobuf_sp)(BX)
|
| 471 |
+
get_tls(CX)
|
| 472 |
+
MOVL g(CX), SI
|
| 473 |
+
MOVL SI, (m_morebuf+gobuf_g)(BX)
|
| 474 |
+
|
| 475 |
+
// Call newstack on m->g0's stack.
|
| 476 |
+
MOVL m_g0(BX), BP
|
| 477 |
+
MOVL BP, g(CX)
|
| 478 |
+
MOVL (g_sched+gobuf_sp)(BP), AX
|
| 479 |
+
MOVL -4(AX), BX // fault if CALL would, before smashing SP
|
| 480 |
+
MOVL AX, SP
|
| 481 |
+
CALL runtime·newstack(SB)
|
| 482 |
+
CALL runtime·abort(SB) // crash if newstack returns
|
| 483 |
+
RET
|
| 484 |
+
|
| 485 |
+
TEXT runtime·morestack_noctxt(SB),NOSPLIT,$0-0
|
| 486 |
+
MOVL $0, DX
|
| 487 |
+
JMP runtime·morestack(SB)
|
| 488 |
+
|
| 489 |
+
// reflectcall: call a function with the given argument list
|
| 490 |
+
// func call(stackArgsType *_type, f *FuncVal, stackArgs *byte, stackArgsSize, stackRetOffset, frameSize uint32, regArgs *abi.RegArgs).
|
| 491 |
+
// we don't have variable-sized frames, so we use a small number
|
| 492 |
+
// of constant-sized-frame functions to encode a few bits of size in the pc.
|
| 493 |
+
// Caution: ugly multiline assembly macros in your future!
|
| 494 |
+
|
| 495 |
+
#define DISPATCH(NAME,MAXSIZE) \
|
| 496 |
+
CMPL CX, $MAXSIZE; \
|
| 497 |
+
JA 3(PC); \
|
| 498 |
+
MOVL $NAME(SB), AX; \
|
| 499 |
+
JMP AX
|
| 500 |
+
// Note: can't just "JMP NAME(SB)" - bad inlining results.
|
| 501 |
+
|
| 502 |
+
TEXT ·reflectcall(SB), NOSPLIT, $0-28
|
| 503 |
+
MOVL frameSize+20(FP), CX
|
| 504 |
+
DISPATCH(runtime·call16, 16)
|
| 505 |
+
DISPATCH(runtime·call32, 32)
|
| 506 |
+
DISPATCH(runtime·call64, 64)
|
| 507 |
+
DISPATCH(runtime·call128, 128)
|
| 508 |
+
DISPATCH(runtime·call256, 256)
|
| 509 |
+
DISPATCH(runtime·call512, 512)
|
| 510 |
+
DISPATCH(runtime·call1024, 1024)
|
| 511 |
+
DISPATCH(runtime·call2048, 2048)
|
| 512 |
+
DISPATCH(runtime·call4096, 4096)
|
| 513 |
+
DISPATCH(runtime·call8192, 8192)
|
| 514 |
+
DISPATCH(runtime·call16384, 16384)
|
| 515 |
+
DISPATCH(runtime·call32768, 32768)
|
| 516 |
+
DISPATCH(runtime·call65536, 65536)
|
| 517 |
+
DISPATCH(runtime·call131072, 131072)
|
| 518 |
+
DISPATCH(runtime·call262144, 262144)
|
| 519 |
+
DISPATCH(runtime·call524288, 524288)
|
| 520 |
+
DISPATCH(runtime·call1048576, 1048576)
|
| 521 |
+
DISPATCH(runtime·call2097152, 2097152)
|
| 522 |
+
DISPATCH(runtime·call4194304, 4194304)
|
| 523 |
+
DISPATCH(runtime·call8388608, 8388608)
|
| 524 |
+
DISPATCH(runtime·call16777216, 16777216)
|
| 525 |
+
DISPATCH(runtime·call33554432, 33554432)
|
| 526 |
+
DISPATCH(runtime·call67108864, 67108864)
|
| 527 |
+
DISPATCH(runtime·call134217728, 134217728)
|
| 528 |
+
DISPATCH(runtime·call268435456, 268435456)
|
| 529 |
+
DISPATCH(runtime·call536870912, 536870912)
|
| 530 |
+
DISPATCH(runtime·call1073741824, 1073741824)
|
| 531 |
+
MOVL $runtime·badreflectcall(SB), AX
|
| 532 |
+
JMP AX
|
| 533 |
+
|
| 534 |
+
#define CALLFN(NAME,MAXSIZE) \
|
| 535 |
+
TEXT NAME(SB), WRAPPER, $MAXSIZE-28; \
|
| 536 |
+
NO_LOCAL_POINTERS; \
|
| 537 |
+
/* copy arguments to stack */ \
|
| 538 |
+
MOVL stackArgs+8(FP), SI; \
|
| 539 |
+
MOVL stackArgsSize+12(FP), CX; \
|
| 540 |
+
MOVL SP, DI; \
|
| 541 |
+
REP;MOVSB; \
|
| 542 |
+
/* call function */ \
|
| 543 |
+
MOVL f+4(FP), DX; \
|
| 544 |
+
MOVL (DX), AX; \
|
| 545 |
+
PCDATA $PCDATA_StackMapIndex, $0; \
|
| 546 |
+
CALL AX; \
|
| 547 |
+
/* copy return values back */ \
|
| 548 |
+
MOVL stackArgsType+0(FP), DX; \
|
| 549 |
+
MOVL stackArgs+8(FP), DI; \
|
| 550 |
+
MOVL stackArgsSize+12(FP), CX; \
|
| 551 |
+
MOVL stackRetOffset+16(FP), BX; \
|
| 552 |
+
MOVL SP, SI; \
|
| 553 |
+
ADDL BX, DI; \
|
| 554 |
+
ADDL BX, SI; \
|
| 555 |
+
SUBL BX, CX; \
|
| 556 |
+
CALL callRet<>(SB); \
|
| 557 |
+
RET
|
| 558 |
+
|
| 559 |
+
// callRet copies return values back at the end of call*. This is a
|
| 560 |
+
// separate function so it can allocate stack space for the arguments
|
| 561 |
+
// to reflectcallmove. It does not follow the Go ABI; it expects its
|
| 562 |
+
// arguments in registers.
|
| 563 |
+
TEXT callRet<>(SB), NOSPLIT, $20-0
|
| 564 |
+
MOVL DX, 0(SP)
|
| 565 |
+
MOVL DI, 4(SP)
|
| 566 |
+
MOVL SI, 8(SP)
|
| 567 |
+
MOVL CX, 12(SP)
|
| 568 |
+
MOVL $0, 16(SP)
|
| 569 |
+
CALL runtime·reflectcallmove(SB)
|
| 570 |
+
RET
|
| 571 |
+
|
| 572 |
+
CALLFN(·call16, 16)
|
| 573 |
+
CALLFN(·call32, 32)
|
| 574 |
+
CALLFN(·call64, 64)
|
| 575 |
+
CALLFN(·call128, 128)
|
| 576 |
+
CALLFN(·call256, 256)
|
| 577 |
+
CALLFN(·call512, 512)
|
| 578 |
+
CALLFN(·call1024, 1024)
|
| 579 |
+
CALLFN(·call2048, 2048)
|
| 580 |
+
CALLFN(·call4096, 4096)
|
| 581 |
+
CALLFN(·call8192, 8192)
|
| 582 |
+
CALLFN(·call16384, 16384)
|
| 583 |
+
CALLFN(·call32768, 32768)
|
| 584 |
+
CALLFN(·call65536, 65536)
|
| 585 |
+
CALLFN(·call131072, 131072)
|
| 586 |
+
CALLFN(·call262144, 262144)
|
| 587 |
+
CALLFN(·call524288, 524288)
|
| 588 |
+
CALLFN(·call1048576, 1048576)
|
| 589 |
+
CALLFN(·call2097152, 2097152)
|
| 590 |
+
CALLFN(·call4194304, 4194304)
|
| 591 |
+
CALLFN(·call8388608, 8388608)
|
| 592 |
+
CALLFN(·call16777216, 16777216)
|
| 593 |
+
CALLFN(·call33554432, 33554432)
|
| 594 |
+
CALLFN(·call67108864, 67108864)
|
| 595 |
+
CALLFN(·call134217728, 134217728)
|
| 596 |
+
CALLFN(·call268435456, 268435456)
|
| 597 |
+
CALLFN(·call536870912, 536870912)
|
| 598 |
+
CALLFN(·call1073741824, 1073741824)
|
| 599 |
+
|
| 600 |
+
TEXT runtime·procyieldAsm(SB),NOSPLIT,$0-0
|
| 601 |
+
MOVL cycles+0(FP), AX
|
| 602 |
+
TESTL AX, AX
|
| 603 |
+
JZ done
|
| 604 |
+
again:
|
| 605 |
+
PAUSE
|
| 606 |
+
SUBL $1, AX
|
| 607 |
+
JNZ again
|
| 608 |
+
done:
|
| 609 |
+
RET
|
| 610 |
+
|
| 611 |
+
TEXT ·publicationBarrier(SB),NOSPLIT,$0-0
|
| 612 |
+
// Stores are already ordered on x86, so this is just a
|
| 613 |
+
// compile barrier.
|
| 614 |
+
RET
|
| 615 |
+
|
| 616 |
+
// Save state of caller into g->sched,
|
| 617 |
+
// but using fake PC from systemstack_switch.
|
| 618 |
+
// Must only be called from functions with no locals ($0)
|
| 619 |
+
// or else unwinding from systemstack_switch is incorrect.
|
| 620 |
+
TEXT gosave_systemstack_switch<>(SB),NOSPLIT,$0
|
| 621 |
+
PUSHL AX
|
| 622 |
+
PUSHL BX
|
| 623 |
+
get_tls(BX)
|
| 624 |
+
MOVL g(BX), BX
|
| 625 |
+
LEAL arg+0(FP), AX
|
| 626 |
+
MOVL AX, (g_sched+gobuf_sp)(BX)
|
| 627 |
+
MOVL $runtime·systemstack_switch(SB), AX
|
| 628 |
+
MOVL AX, (g_sched+gobuf_pc)(BX)
|
| 629 |
+
// Assert ctxt is zero. See func save.
|
| 630 |
+
MOVL (g_sched+gobuf_ctxt)(BX), AX
|
| 631 |
+
TESTL AX, AX
|
| 632 |
+
JZ 2(PC)
|
| 633 |
+
CALL runtime·abort(SB)
|
| 634 |
+
POPL BX
|
| 635 |
+
POPL AX
|
| 636 |
+
RET
|
| 637 |
+
|
| 638 |
+
// func asmcgocall_no_g(fn, arg unsafe.Pointer)
|
| 639 |
+
// Call fn(arg) aligned appropriately for the gcc ABI.
|
| 640 |
+
// Called on a system stack, and there may be no g yet (during needm).
|
| 641 |
+
TEXT ·asmcgocall_no_g(SB),NOSPLIT,$0-8
|
| 642 |
+
MOVL fn+0(FP), AX
|
| 643 |
+
MOVL arg+4(FP), BX
|
| 644 |
+
MOVL SP, DX
|
| 645 |
+
SUBL $32, SP
|
| 646 |
+
ANDL $~15, SP // alignment, perhaps unnecessary
|
| 647 |
+
MOVL DX, 8(SP) // save old SP
|
| 648 |
+
MOVL BX, 0(SP) // first argument in x86-32 ABI
|
| 649 |
+
CALL AX
|
| 650 |
+
MOVL 8(SP), DX
|
| 651 |
+
MOVL DX, SP
|
| 652 |
+
RET
|
| 653 |
+
|
| 654 |
+
// func asmcgocall(fn, arg unsafe.Pointer) int32
|
| 655 |
+
// Call fn(arg) on the scheduler stack,
|
| 656 |
+
// aligned appropriately for the gcc ABI.
|
| 657 |
+
// See cgocall.go for more details.
|
| 658 |
+
TEXT ·asmcgocall(SB),NOSPLIT,$0-12
|
| 659 |
+
MOVL fn+0(FP), AX
|
| 660 |
+
MOVL arg+4(FP), BX
|
| 661 |
+
|
| 662 |
+
MOVL SP, DX
|
| 663 |
+
|
| 664 |
+
// Figure out if we need to switch to m->g0 stack.
|
| 665 |
+
// We get called to create new OS threads too, and those
|
| 666 |
+
// come in on the m->g0 stack already. Or we might already
|
| 667 |
+
// be on the m->gsignal stack.
|
| 668 |
+
get_tls(CX)
|
| 669 |
+
MOVL g(CX), DI
|
| 670 |
+
CMPL DI, $0
|
| 671 |
+
JEQ nosave // Don't even have a G yet.
|
| 672 |
+
MOVL g_m(DI), BP
|
| 673 |
+
CMPL DI, m_gsignal(BP)
|
| 674 |
+
JEQ noswitch
|
| 675 |
+
MOVL m_g0(BP), SI
|
| 676 |
+
CMPL DI, SI
|
| 677 |
+
JEQ noswitch
|
| 678 |
+
CALL gosave_systemstack_switch<>(SB)
|
| 679 |
+
get_tls(CX)
|
| 680 |
+
MOVL SI, g(CX)
|
| 681 |
+
MOVL (g_sched+gobuf_sp)(SI), SP
|
| 682 |
+
|
| 683 |
+
noswitch:
|
| 684 |
+
// Now on a scheduling stack (a pthread-created stack).
|
| 685 |
+
SUBL $32, SP
|
| 686 |
+
ANDL $~15, SP // alignment, perhaps unnecessary
|
| 687 |
+
MOVL DI, 8(SP) // save g
|
| 688 |
+
MOVL (g_stack+stack_hi)(DI), DI
|
| 689 |
+
SUBL DX, DI
|
| 690 |
+
MOVL DI, 4(SP) // save depth in stack (can't just save SP, as stack might be copied during a callback)
|
| 691 |
+
MOVL BX, 0(SP) // first argument in x86-32 ABI
|
| 692 |
+
CALL AX
|
| 693 |
+
|
| 694 |
+
// Restore registers, g, stack pointer.
|
| 695 |
+
get_tls(CX)
|
| 696 |
+
MOVL 8(SP), DI
|
| 697 |
+
MOVL (g_stack+stack_hi)(DI), SI
|
| 698 |
+
SUBL 4(SP), SI
|
| 699 |
+
MOVL DI, g(CX)
|
| 700 |
+
MOVL SI, SP
|
| 701 |
+
|
| 702 |
+
MOVL AX, ret+8(FP)
|
| 703 |
+
RET
|
| 704 |
+
nosave:
|
| 705 |
+
// Now on a scheduling stack (a pthread-created stack).
|
| 706 |
+
SUBL $32, SP
|
| 707 |
+
ANDL $~15, SP // alignment, perhaps unnecessary
|
| 708 |
+
MOVL DX, 4(SP) // save original stack pointer
|
| 709 |
+
MOVL BX, 0(SP) // first argument in x86-32 ABI
|
| 710 |
+
CALL AX
|
| 711 |
+
|
| 712 |
+
MOVL 4(SP), CX // restore original stack pointer
|
| 713 |
+
MOVL CX, SP
|
| 714 |
+
MOVL AX, ret+8(FP)
|
| 715 |
+
RET
|
| 716 |
+
|
| 717 |
+
// cgocallback(fn, frame unsafe.Pointer, ctxt uintptr)
|
| 718 |
+
// See cgocall.go for more details.
|
| 719 |
+
TEXT ·cgocallback(SB),NOSPLIT,$12-12 // Frame size must match commented places below
|
| 720 |
+
NO_LOCAL_POINTERS
|
| 721 |
+
|
| 722 |
+
// Skip cgocallbackg, just dropm when fn is nil, and frame is the saved g.
|
| 723 |
+
// It is used to dropm while thread is exiting.
|
| 724 |
+
MOVL fn+0(FP), AX
|
| 725 |
+
CMPL AX, $0
|
| 726 |
+
JNE loadg
|
| 727 |
+
// Restore the g from frame.
|
| 728 |
+
get_tls(CX)
|
| 729 |
+
MOVL frame+4(FP), BX
|
| 730 |
+
MOVL BX, g(CX)
|
| 731 |
+
JMP dropm
|
| 732 |
+
|
| 733 |
+
loadg:
|
| 734 |
+
// If g is nil, Go did not create the current thread,
|
| 735 |
+
// or if this thread never called into Go on pthread platforms.
|
| 736 |
+
// Call needm to obtain one for temporary use.
|
| 737 |
+
// In this case, we're running on the thread stack, so there's
|
| 738 |
+
// lots of space, but the linker doesn't know. Hide the call from
|
| 739 |
+
// the linker analysis by using an indirect call through AX.
|
| 740 |
+
get_tls(CX)
|
| 741 |
+
#ifdef GOOS_windows
|
| 742 |
+
MOVL $0, BP
|
| 743 |
+
CMPL CX, $0
|
| 744 |
+
JEQ 2(PC) // TODO
|
| 745 |
+
#endif
|
| 746 |
+
MOVL g(CX), BP
|
| 747 |
+
CMPL BP, $0
|
| 748 |
+
JEQ needm
|
| 749 |
+
MOVL g_m(BP), BP
|
| 750 |
+
MOVL BP, savedm-4(SP) // saved copy of oldm
|
| 751 |
+
JMP havem
|
| 752 |
+
needm:
|
| 753 |
+
MOVL $runtime·needAndBindM(SB), AX
|
| 754 |
+
CALL AX
|
| 755 |
+
MOVL $0, savedm-4(SP)
|
| 756 |
+
get_tls(CX)
|
| 757 |
+
MOVL g(CX), BP
|
| 758 |
+
MOVL g_m(BP), BP
|
| 759 |
+
|
| 760 |
+
// Set m->sched.sp = SP, so that if a panic happens
|
| 761 |
+
// during the function we are about to execute, it will
|
| 762 |
+
// have a valid SP to run on the g0 stack.
|
| 763 |
+
// The next few lines (after the havem label)
|
| 764 |
+
// will save this SP onto the stack and then write
|
| 765 |
+
// the same SP back to m->sched.sp. That seems redundant,
|
| 766 |
+
// but if an unrecovered panic happens, unwindm will
|
| 767 |
+
// restore the g->sched.sp from the stack location
|
| 768 |
+
// and then systemstack will try to use it. If we don't set it here,
|
| 769 |
+
// that restored SP will be uninitialized (typically 0) and
|
| 770 |
+
// will not be usable.
|
| 771 |
+
MOVL m_g0(BP), SI
|
| 772 |
+
MOVL SP, (g_sched+gobuf_sp)(SI)
|
| 773 |
+
|
| 774 |
+
havem:
|
| 775 |
+
// Now there's a valid m, and we're running on its m->g0.
|
| 776 |
+
// Save current m->g0->sched.sp on stack and then set it to SP.
|
| 777 |
+
// Save current sp in m->g0->sched.sp in preparation for
|
| 778 |
+
// switch back to m->curg stack.
|
| 779 |
+
// NOTE: unwindm knows that the saved g->sched.sp is at 0(SP).
|
| 780 |
+
MOVL m_g0(BP), SI
|
| 781 |
+
MOVL (g_sched+gobuf_sp)(SI), AX
|
| 782 |
+
MOVL AX, 0(SP)
|
| 783 |
+
MOVL SP, (g_sched+gobuf_sp)(SI)
|
| 784 |
+
|
| 785 |
+
// Switch to m->curg stack and call runtime.cgocallbackg.
|
| 786 |
+
// Because we are taking over the execution of m->curg
|
| 787 |
+
// but *not* resuming what had been running, we need to
|
| 788 |
+
// save that information (m->curg->sched) so we can restore it.
|
| 789 |
+
// We can restore m->curg->sched.sp easily, because calling
|
| 790 |
+
// runtime.cgocallbackg leaves SP unchanged upon return.
|
| 791 |
+
// To save m->curg->sched.pc, we push it onto the curg stack and
|
| 792 |
+
// open a frame the same size as cgocallback's g0 frame.
|
| 793 |
+
// Once we switch to the curg stack, the pushed PC will appear
|
| 794 |
+
// to be the return PC of cgocallback, so that the traceback
|
| 795 |
+
// will seamlessly trace back into the earlier calls.
|
| 796 |
+
MOVL m_curg(BP), SI
|
| 797 |
+
MOVL SI, g(CX)
|
| 798 |
+
MOVL (g_sched+gobuf_sp)(SI), DI // prepare stack as DI
|
| 799 |
+
MOVL (g_sched+gobuf_pc)(SI), BP
|
| 800 |
+
MOVL BP, -4(DI) // "push" return PC on the g stack
|
| 801 |
+
// Gather our arguments into registers.
|
| 802 |
+
MOVL fn+0(FP), AX
|
| 803 |
+
MOVL frame+4(FP), BX
|
| 804 |
+
MOVL ctxt+8(FP), CX
|
| 805 |
+
LEAL -(4+12)(DI), SP // Must match declared frame size
|
| 806 |
+
MOVL AX, 0(SP)
|
| 807 |
+
MOVL BX, 4(SP)
|
| 808 |
+
MOVL CX, 8(SP)
|
| 809 |
+
CALL runtime·cgocallbackg(SB)
|
| 810 |
+
|
| 811 |
+
// Restore g->sched (== m->curg->sched) from saved values.
|
| 812 |
+
get_tls(CX)
|
| 813 |
+
MOVL g(CX), SI
|
| 814 |
+
MOVL 12(SP), BP // Must match declared frame size
|
| 815 |
+
MOVL BP, (g_sched+gobuf_pc)(SI)
|
| 816 |
+
LEAL (12+4)(SP), DI // Must match declared frame size
|
| 817 |
+
MOVL DI, (g_sched+gobuf_sp)(SI)
|
| 818 |
+
|
| 819 |
+
// Switch back to m->g0's stack and restore m->g0->sched.sp.
|
| 820 |
+
// (Unlike m->curg, the g0 goroutine never uses sched.pc,
|
| 821 |
+
// so we do not have to restore it.)
|
| 822 |
+
MOVL g(CX), BP
|
| 823 |
+
MOVL g_m(BP), BP
|
| 824 |
+
MOVL m_g0(BP), SI
|
| 825 |
+
MOVL SI, g(CX)
|
| 826 |
+
MOVL (g_sched+gobuf_sp)(SI), SP
|
| 827 |
+
MOVL 0(SP), AX
|
| 828 |
+
MOVL AX, (g_sched+gobuf_sp)(SI)
|
| 829 |
+
|
| 830 |
+
// If the m on entry was nil, we called needm above to borrow an m,
|
| 831 |
+
// 1. for the duration of the call on non-pthread platforms,
|
| 832 |
+
// 2. or the duration of the C thread alive on pthread platforms.
|
| 833 |
+
// If the m on entry wasn't nil,
|
| 834 |
+
// 1. the thread might be a Go thread,
|
| 835 |
+
// 2. or it wasn't the first call from a C thread on pthread platforms,
|
| 836 |
+
// since then we skip dropm to reuse the m in the first call.
|
| 837 |
+
MOVL savedm-4(SP), DX
|
| 838 |
+
CMPL DX, $0
|
| 839 |
+
JNE droppedm
|
| 840 |
+
|
| 841 |
+
// Skip dropm to reuse it in the next call, when a pthread key has been created.
|
| 842 |
+
MOVL _cgo_pthread_key_created(SB), DX
|
| 843 |
+
// It means cgo is disabled when _cgo_pthread_key_created is a nil pointer, need dropm.
|
| 844 |
+
CMPL DX, $0
|
| 845 |
+
JEQ dropm
|
| 846 |
+
CMPL (DX), $0
|
| 847 |
+
JNE droppedm
|
| 848 |
+
|
| 849 |
+
dropm:
|
| 850 |
+
MOVL $runtime·dropm(SB), AX
|
| 851 |
+
CALL AX
|
| 852 |
+
droppedm:
|
| 853 |
+
|
| 854 |
+
// Done!
|
| 855 |
+
RET
|
| 856 |
+
|
| 857 |
+
// void setg(G*); set g. for use by needm.
|
| 858 |
+
TEXT runtime·setg(SB), NOSPLIT, $0-4
|
| 859 |
+
MOVL gg+0(FP), BX
|
| 860 |
+
#ifdef GOOS_windows
|
| 861 |
+
MOVL runtime·tls_g(SB), CX
|
| 862 |
+
CMPL BX, $0
|
| 863 |
+
JNE settls
|
| 864 |
+
MOVL $0, 0(CX)(FS)
|
| 865 |
+
RET
|
| 866 |
+
settls:
|
| 867 |
+
MOVL g_m(BX), AX
|
| 868 |
+
LEAL m_tls(AX), AX
|
| 869 |
+
MOVL AX, 0(CX)(FS)
|
| 870 |
+
#endif
|
| 871 |
+
get_tls(CX)
|
| 872 |
+
MOVL BX, g(CX)
|
| 873 |
+
RET
|
| 874 |
+
|
| 875 |
+
// void setg_gcc(G*); set g. for use by gcc
|
| 876 |
+
TEXT setg_gcc<>(SB), NOSPLIT, $0
|
| 877 |
+
get_tls(AX)
|
| 878 |
+
MOVL gg+0(FP), DX
|
| 879 |
+
MOVL DX, g(AX)
|
| 880 |
+
RET
|
| 881 |
+
|
| 882 |
+
TEXT runtime·abort(SB),NOSPLIT,$0-0
|
| 883 |
+
INT $3
|
| 884 |
+
loop:
|
| 885 |
+
JMP loop
|
| 886 |
+
|
| 887 |
+
// check that SP is in range [g->stack.lo, g->stack.hi)
|
| 888 |
+
TEXT runtime·stackcheck(SB), NOSPLIT, $0-0
|
| 889 |
+
get_tls(CX)
|
| 890 |
+
MOVL g(CX), AX
|
| 891 |
+
CMPL (g_stack+stack_hi)(AX), SP
|
| 892 |
+
JHI 2(PC)
|
| 893 |
+
CALL runtime·abort(SB)
|
| 894 |
+
CMPL SP, (g_stack+stack_lo)(AX)
|
| 895 |
+
JHI 2(PC)
|
| 896 |
+
CALL runtime·abort(SB)
|
| 897 |
+
RET
|
| 898 |
+
|
| 899 |
+
// func cputicks() int64
|
| 900 |
+
TEXT runtime·cputicks(SB),NOSPLIT,$0-8
|
| 901 |
+
// LFENCE/MFENCE instruction support is dependent on SSE2.
|
| 902 |
+
// When no SSE2 support is present do not enforce any serialization
|
| 903 |
+
// since using CPUID to serialize the instruction stream is
|
| 904 |
+
// very costly.
|
| 905 |
+
#ifdef GO386_softfloat
|
| 906 |
+
JMP rdtsc // no fence instructions available
|
| 907 |
+
#endif
|
| 908 |
+
CMPB internal∕cpu·X86+const_offsetX86HasRDTSCP(SB), $1
|
| 909 |
+
JNE fences
|
| 910 |
+
// Instruction stream serializing RDTSCP is supported.
|
| 911 |
+
// RDTSCP is supported by Intel Nehalem (2008) and
|
| 912 |
+
// AMD K8 Rev. F (2006) and newer.
|
| 913 |
+
RDTSCP
|
| 914 |
+
done:
|
| 915 |
+
MOVL AX, ret_lo+0(FP)
|
| 916 |
+
MOVL DX, ret_hi+4(FP)
|
| 917 |
+
RET
|
| 918 |
+
fences:
|
| 919 |
+
// MFENCE is instruction stream serializing and flushes the
|
| 920 |
+
// store buffers on AMD. The serialization semantics of LFENCE on AMD
|
| 921 |
+
// are dependent on MSR C001_1029 and CPU generation.
|
| 922 |
+
// LFENCE on Intel does wait for all previous instructions to have executed.
|
| 923 |
+
// Intel recommends MFENCE;LFENCE in its manuals before RDTSC to have all
|
| 924 |
+
// previous instructions executed and all previous loads and stores to globally visible.
|
| 925 |
+
// Using MFENCE;LFENCE here aligns the serializing properties without
|
| 926 |
+
// runtime detection of CPU manufacturer.
|
| 927 |
+
MFENCE
|
| 928 |
+
LFENCE
|
| 929 |
+
rdtsc:
|
| 930 |
+
RDTSC
|
| 931 |
+
JMP done
|
| 932 |
+
|
| 933 |
+
TEXT ldt0setup<>(SB),NOSPLIT,$16-0
|
| 934 |
+
#ifdef GOOS_windows
|
| 935 |
+
CALL runtime·wintls(SB)
|
| 936 |
+
#endif
|
| 937 |
+
// set up ldt 7 to point at m0.tls
|
| 938 |
+
// ldt 1 would be fine on Linux, but on OS X, 7 is as low as we can go.
|
| 939 |
+
// the entry number is just a hint. setldt will set up GS with what it used.
|
| 940 |
+
MOVL $7, 0(SP)
|
| 941 |
+
LEAL runtime·m0+m_tls(SB), AX
|
| 942 |
+
MOVL AX, 4(SP)
|
| 943 |
+
MOVL $32, 8(SP) // sizeof(tls array)
|
| 944 |
+
CALL runtime·setldt(SB)
|
| 945 |
+
RET
|
| 946 |
+
|
| 947 |
+
TEXT runtime·emptyfunc(SB),0,$0-0
|
| 948 |
+
RET
|
| 949 |
+
|
| 950 |
+
// hash function using AES hardware instructions
|
| 951 |
+
TEXT runtime·memhash(SB),NOSPLIT,$0-16
|
| 952 |
+
CMPB runtime·useAeshash(SB), $0
|
| 953 |
+
JEQ noaes
|
| 954 |
+
MOVL p+0(FP), AX // ptr to data
|
| 955 |
+
MOVL s+8(FP), BX // size
|
| 956 |
+
LEAL ret+12(FP), DX
|
| 957 |
+
JMP aeshashbody<>(SB)
|
| 958 |
+
noaes:
|
| 959 |
+
JMP runtime·memhashFallback(SB)
|
| 960 |
+
|
| 961 |
+
TEXT runtime·strhash(SB),NOSPLIT,$0-12
|
| 962 |
+
CMPB runtime·useAeshash(SB), $0
|
| 963 |
+
JEQ noaes
|
| 964 |
+
MOVL p+0(FP), AX // ptr to string object
|
| 965 |
+
MOVL 4(AX), BX // length of string
|
| 966 |
+
MOVL (AX), AX // string data
|
| 967 |
+
LEAL ret+8(FP), DX
|
| 968 |
+
JMP aeshashbody<>(SB)
|
| 969 |
+
noaes:
|
| 970 |
+
JMP runtime·strhashFallback(SB)
|
| 971 |
+
|
| 972 |
+
// AX: data
|
| 973 |
+
// BX: length
|
| 974 |
+
// DX: address to put return value
|
| 975 |
+
TEXT aeshashbody<>(SB),NOSPLIT,$0-0
|
| 976 |
+
MOVL h+4(FP), X0 // 32 bits of per-table hash seed
|
| 977 |
+
PINSRW $4, BX, X0 // 16 bits of length
|
| 978 |
+
PSHUFHW $0, X0, X0 // replace size with its low 2 bytes repeated 4 times
|
| 979 |
+
MOVO X0, X1 // save unscrambled seed
|
| 980 |
+
PXOR runtime·aeskeysched(SB), X0 // xor in per-process seed
|
| 981 |
+
AESENC X0, X0 // scramble seed
|
| 982 |
+
|
| 983 |
+
CMPL BX, $16
|
| 984 |
+
JB aes0to15
|
| 985 |
+
JE aes16
|
| 986 |
+
CMPL BX, $32
|
| 987 |
+
JBE aes17to32
|
| 988 |
+
CMPL BX, $64
|
| 989 |
+
JBE aes33to64
|
| 990 |
+
JMP aes65plus
|
| 991 |
+
|
| 992 |
+
aes0to15:
|
| 993 |
+
TESTL BX, BX
|
| 994 |
+
JE aes0
|
| 995 |
+
|
| 996 |
+
ADDL $16, AX
|
| 997 |
+
TESTW $0xff0, AX
|
| 998 |
+
JE endofpage
|
| 999 |
+
|
| 1000 |
+
// 16 bytes loaded at this address won't cross
|
| 1001 |
+
// a page boundary, so we can load it directly.
|
| 1002 |
+
MOVOU -16(AX), X1
|
| 1003 |
+
ADDL BX, BX
|
| 1004 |
+
PAND masks<>(SB)(BX*8), X1
|
| 1005 |
+
|
| 1006 |
+
final1:
|
| 1007 |
+
PXOR X0, X1 // xor data with seed
|
| 1008 |
+
AESENC X1, X1 // scramble combo 3 times
|
| 1009 |
+
AESENC X1, X1
|
| 1010 |
+
AESENC X1, X1
|
| 1011 |
+
MOVL X1, (DX)
|
| 1012 |
+
RET
|
| 1013 |
+
|
| 1014 |
+
endofpage:
|
| 1015 |
+
// address ends in 1111xxxx. Might be up against
|
| 1016 |
+
// a page boundary, so load ending at last byte.
|
| 1017 |
+
// Then shift bytes down using pshufb.
|
| 1018 |
+
MOVOU -32(AX)(BX*1), X1
|
| 1019 |
+
ADDL BX, BX
|
| 1020 |
+
PSHUFB shifts<>(SB)(BX*8), X1
|
| 1021 |
+
JMP final1
|
| 1022 |
+
|
| 1023 |
+
aes0:
|
| 1024 |
+
// Return scrambled input seed
|
| 1025 |
+
AESENC X0, X0
|
| 1026 |
+
MOVL X0, (DX)
|
| 1027 |
+
RET
|
| 1028 |
+
|
| 1029 |
+
aes16:
|
| 1030 |
+
MOVOU (AX), X1
|
| 1031 |
+
JMP final1
|
| 1032 |
+
|
| 1033 |
+
aes17to32:
|
| 1034 |
+
// make second starting seed
|
| 1035 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1036 |
+
AESENC X1, X1
|
| 1037 |
+
|
| 1038 |
+
// load data to be hashed
|
| 1039 |
+
MOVOU (AX), X2
|
| 1040 |
+
MOVOU -16(AX)(BX*1), X3
|
| 1041 |
+
|
| 1042 |
+
// xor with seed
|
| 1043 |
+
PXOR X0, X2
|
| 1044 |
+
PXOR X1, X3
|
| 1045 |
+
|
| 1046 |
+
// scramble 3 times
|
| 1047 |
+
AESENC X2, X2
|
| 1048 |
+
AESENC X3, X3
|
| 1049 |
+
AESENC X2, X2
|
| 1050 |
+
AESENC X3, X3
|
| 1051 |
+
AESENC X2, X2
|
| 1052 |
+
AESENC X3, X3
|
| 1053 |
+
|
| 1054 |
+
// combine results
|
| 1055 |
+
PXOR X3, X2
|
| 1056 |
+
MOVL X2, (DX)
|
| 1057 |
+
RET
|
| 1058 |
+
|
| 1059 |
+
aes33to64:
|
| 1060 |
+
// make 3 more starting seeds
|
| 1061 |
+
MOVO X1, X2
|
| 1062 |
+
MOVO X1, X3
|
| 1063 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1064 |
+
PXOR runtime·aeskeysched+32(SB), X2
|
| 1065 |
+
PXOR runtime·aeskeysched+48(SB), X3
|
| 1066 |
+
AESENC X1, X1
|
| 1067 |
+
AESENC X2, X2
|
| 1068 |
+
AESENC X3, X3
|
| 1069 |
+
|
| 1070 |
+
MOVOU (AX), X4
|
| 1071 |
+
MOVOU 16(AX), X5
|
| 1072 |
+
MOVOU -32(AX)(BX*1), X6
|
| 1073 |
+
MOVOU -16(AX)(BX*1), X7
|
| 1074 |
+
|
| 1075 |
+
PXOR X0, X4
|
| 1076 |
+
PXOR X1, X5
|
| 1077 |
+
PXOR X2, X6
|
| 1078 |
+
PXOR X3, X7
|
| 1079 |
+
|
| 1080 |
+
AESENC X4, X4
|
| 1081 |
+
AESENC X5, X5
|
| 1082 |
+
AESENC X6, X6
|
| 1083 |
+
AESENC X7, X7
|
| 1084 |
+
|
| 1085 |
+
AESENC X4, X4
|
| 1086 |
+
AESENC X5, X5
|
| 1087 |
+
AESENC X6, X6
|
| 1088 |
+
AESENC X7, X7
|
| 1089 |
+
|
| 1090 |
+
AESENC X4, X4
|
| 1091 |
+
AESENC X5, X5
|
| 1092 |
+
AESENC X6, X6
|
| 1093 |
+
AESENC X7, X7
|
| 1094 |
+
|
| 1095 |
+
PXOR X6, X4
|
| 1096 |
+
PXOR X7, X5
|
| 1097 |
+
PXOR X5, X4
|
| 1098 |
+
MOVL X4, (DX)
|
| 1099 |
+
RET
|
| 1100 |
+
|
| 1101 |
+
aes65plus:
|
| 1102 |
+
// make 3 more starting seeds
|
| 1103 |
+
MOVO X1, X2
|
| 1104 |
+
MOVO X1, X3
|
| 1105 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1106 |
+
PXOR runtime·aeskeysched+32(SB), X2
|
| 1107 |
+
PXOR runtime·aeskeysched+48(SB), X3
|
| 1108 |
+
AESENC X1, X1
|
| 1109 |
+
AESENC X2, X2
|
| 1110 |
+
AESENC X3, X3
|
| 1111 |
+
|
| 1112 |
+
// start with last (possibly overlapping) block
|
| 1113 |
+
MOVOU -64(AX)(BX*1), X4
|
| 1114 |
+
MOVOU -48(AX)(BX*1), X5
|
| 1115 |
+
MOVOU -32(AX)(BX*1), X6
|
| 1116 |
+
MOVOU -16(AX)(BX*1), X7
|
| 1117 |
+
|
| 1118 |
+
// scramble state once
|
| 1119 |
+
AESENC X0, X4
|
| 1120 |
+
AESENC X1, X5
|
| 1121 |
+
AESENC X2, X6
|
| 1122 |
+
AESENC X3, X7
|
| 1123 |
+
|
| 1124 |
+
// compute number of remaining 64-byte blocks
|
| 1125 |
+
DECL BX
|
| 1126 |
+
SHRL $6, BX
|
| 1127 |
+
|
| 1128 |
+
aesloop:
|
| 1129 |
+
// scramble state, xor in a block
|
| 1130 |
+
MOVOU (AX), X0
|
| 1131 |
+
MOVOU 16(AX), X1
|
| 1132 |
+
MOVOU 32(AX), X2
|
| 1133 |
+
MOVOU 48(AX), X3
|
| 1134 |
+
AESENC X0, X4
|
| 1135 |
+
AESENC X1, X5
|
| 1136 |
+
AESENC X2, X6
|
| 1137 |
+
AESENC X3, X7
|
| 1138 |
+
|
| 1139 |
+
// scramble state
|
| 1140 |
+
AESENC X4, X4
|
| 1141 |
+
AESENC X5, X5
|
| 1142 |
+
AESENC X6, X6
|
| 1143 |
+
AESENC X7, X7
|
| 1144 |
+
|
| 1145 |
+
ADDL $64, AX
|
| 1146 |
+
DECL BX
|
| 1147 |
+
JNE aesloop
|
| 1148 |
+
|
| 1149 |
+
// 3 more scrambles to finish
|
| 1150 |
+
AESENC X4, X4
|
| 1151 |
+
AESENC X5, X5
|
| 1152 |
+
AESENC X6, X6
|
| 1153 |
+
AESENC X7, X7
|
| 1154 |
+
|
| 1155 |
+
AESENC X4, X4
|
| 1156 |
+
AESENC X5, X5
|
| 1157 |
+
AESENC X6, X6
|
| 1158 |
+
AESENC X7, X7
|
| 1159 |
+
|
| 1160 |
+
AESENC X4, X4
|
| 1161 |
+
AESENC X5, X5
|
| 1162 |
+
AESENC X6, X6
|
| 1163 |
+
AESENC X7, X7
|
| 1164 |
+
|
| 1165 |
+
PXOR X6, X4
|
| 1166 |
+
PXOR X7, X5
|
| 1167 |
+
PXOR X5, X4
|
| 1168 |
+
MOVL X4, (DX)
|
| 1169 |
+
RET
|
| 1170 |
+
|
| 1171 |
+
TEXT runtime·memhash32(SB),NOSPLIT,$0-12
|
| 1172 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1173 |
+
JEQ noaes
|
| 1174 |
+
MOVL p+0(FP), AX // ptr to data
|
| 1175 |
+
MOVL h+4(FP), X0 // seed
|
| 1176 |
+
PINSRD $1, (AX), X0 // data
|
| 1177 |
+
AESENC runtime·aeskeysched+0(SB), X0
|
| 1178 |
+
AESENC runtime·aeskeysched+16(SB), X0
|
| 1179 |
+
AESENC runtime·aeskeysched+32(SB), X0
|
| 1180 |
+
MOVL X0, ret+8(FP)
|
| 1181 |
+
RET
|
| 1182 |
+
noaes:
|
| 1183 |
+
JMP runtime·memhash32Fallback(SB)
|
| 1184 |
+
|
| 1185 |
+
TEXT runtime·memhash64(SB),NOSPLIT,$0-12
|
| 1186 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1187 |
+
JEQ noaes
|
| 1188 |
+
MOVL p+0(FP), AX // ptr to data
|
| 1189 |
+
MOVQ (AX), X0 // data
|
| 1190 |
+
PINSRD $2, h+4(FP), X0 // seed
|
| 1191 |
+
AESENC runtime·aeskeysched+0(SB), X0
|
| 1192 |
+
AESENC runtime·aeskeysched+16(SB), X0
|
| 1193 |
+
AESENC runtime·aeskeysched+32(SB), X0
|
| 1194 |
+
MOVL X0, ret+8(FP)
|
| 1195 |
+
RET
|
| 1196 |
+
noaes:
|
| 1197 |
+
JMP runtime·memhash64Fallback(SB)
|
| 1198 |
+
|
| 1199 |
+
// simple mask to get rid of data in the high part of the register.
|
| 1200 |
+
DATA masks<>+0x00(SB)/4, $0x00000000
|
| 1201 |
+
DATA masks<>+0x04(SB)/4, $0x00000000
|
| 1202 |
+
DATA masks<>+0x08(SB)/4, $0x00000000
|
| 1203 |
+
DATA masks<>+0x0c(SB)/4, $0x00000000
|
| 1204 |
+
|
| 1205 |
+
DATA masks<>+0x10(SB)/4, $0x000000ff
|
| 1206 |
+
DATA masks<>+0x14(SB)/4, $0x00000000
|
| 1207 |
+
DATA masks<>+0x18(SB)/4, $0x00000000
|
| 1208 |
+
DATA masks<>+0x1c(SB)/4, $0x00000000
|
| 1209 |
+
|
| 1210 |
+
DATA masks<>+0x20(SB)/4, $0x0000ffff
|
| 1211 |
+
DATA masks<>+0x24(SB)/4, $0x00000000
|
| 1212 |
+
DATA masks<>+0x28(SB)/4, $0x00000000
|
| 1213 |
+
DATA masks<>+0x2c(SB)/4, $0x00000000
|
| 1214 |
+
|
| 1215 |
+
DATA masks<>+0x30(SB)/4, $0x00ffffff
|
| 1216 |
+
DATA masks<>+0x34(SB)/4, $0x00000000
|
| 1217 |
+
DATA masks<>+0x38(SB)/4, $0x00000000
|
| 1218 |
+
DATA masks<>+0x3c(SB)/4, $0x00000000
|
| 1219 |
+
|
| 1220 |
+
DATA masks<>+0x40(SB)/4, $0xffffffff
|
| 1221 |
+
DATA masks<>+0x44(SB)/4, $0x00000000
|
| 1222 |
+
DATA masks<>+0x48(SB)/4, $0x00000000
|
| 1223 |
+
DATA masks<>+0x4c(SB)/4, $0x00000000
|
| 1224 |
+
|
| 1225 |
+
DATA masks<>+0x50(SB)/4, $0xffffffff
|
| 1226 |
+
DATA masks<>+0x54(SB)/4, $0x000000ff
|
| 1227 |
+
DATA masks<>+0x58(SB)/4, $0x00000000
|
| 1228 |
+
DATA masks<>+0x5c(SB)/4, $0x00000000
|
| 1229 |
+
|
| 1230 |
+
DATA masks<>+0x60(SB)/4, $0xffffffff
|
| 1231 |
+
DATA masks<>+0x64(SB)/4, $0x0000ffff
|
| 1232 |
+
DATA masks<>+0x68(SB)/4, $0x00000000
|
| 1233 |
+
DATA masks<>+0x6c(SB)/4, $0x00000000
|
| 1234 |
+
|
| 1235 |
+
DATA masks<>+0x70(SB)/4, $0xffffffff
|
| 1236 |
+
DATA masks<>+0x74(SB)/4, $0x00ffffff
|
| 1237 |
+
DATA masks<>+0x78(SB)/4, $0x00000000
|
| 1238 |
+
DATA masks<>+0x7c(SB)/4, $0x00000000
|
| 1239 |
+
|
| 1240 |
+
DATA masks<>+0x80(SB)/4, $0xffffffff
|
| 1241 |
+
DATA masks<>+0x84(SB)/4, $0xffffffff
|
| 1242 |
+
DATA masks<>+0x88(SB)/4, $0x00000000
|
| 1243 |
+
DATA masks<>+0x8c(SB)/4, $0x00000000
|
| 1244 |
+
|
| 1245 |
+
DATA masks<>+0x90(SB)/4, $0xffffffff
|
| 1246 |
+
DATA masks<>+0x94(SB)/4, $0xffffffff
|
| 1247 |
+
DATA masks<>+0x98(SB)/4, $0x000000ff
|
| 1248 |
+
DATA masks<>+0x9c(SB)/4, $0x00000000
|
| 1249 |
+
|
| 1250 |
+
DATA masks<>+0xa0(SB)/4, $0xffffffff
|
| 1251 |
+
DATA masks<>+0xa4(SB)/4, $0xffffffff
|
| 1252 |
+
DATA masks<>+0xa8(SB)/4, $0x0000ffff
|
| 1253 |
+
DATA masks<>+0xac(SB)/4, $0x00000000
|
| 1254 |
+
|
| 1255 |
+
DATA masks<>+0xb0(SB)/4, $0xffffffff
|
| 1256 |
+
DATA masks<>+0xb4(SB)/4, $0xffffffff
|
| 1257 |
+
DATA masks<>+0xb8(SB)/4, $0x00ffffff
|
| 1258 |
+
DATA masks<>+0xbc(SB)/4, $0x00000000
|
| 1259 |
+
|
| 1260 |
+
DATA masks<>+0xc0(SB)/4, $0xffffffff
|
| 1261 |
+
DATA masks<>+0xc4(SB)/4, $0xffffffff
|
| 1262 |
+
DATA masks<>+0xc8(SB)/4, $0xffffffff
|
| 1263 |
+
DATA masks<>+0xcc(SB)/4, $0x00000000
|
| 1264 |
+
|
| 1265 |
+
DATA masks<>+0xd0(SB)/4, $0xffffffff
|
| 1266 |
+
DATA masks<>+0xd4(SB)/4, $0xffffffff
|
| 1267 |
+
DATA masks<>+0xd8(SB)/4, $0xffffffff
|
| 1268 |
+
DATA masks<>+0xdc(SB)/4, $0x000000ff
|
| 1269 |
+
|
| 1270 |
+
DATA masks<>+0xe0(SB)/4, $0xffffffff
|
| 1271 |
+
DATA masks<>+0xe4(SB)/4, $0xffffffff
|
| 1272 |
+
DATA masks<>+0xe8(SB)/4, $0xffffffff
|
| 1273 |
+
DATA masks<>+0xec(SB)/4, $0x0000ffff
|
| 1274 |
+
|
| 1275 |
+
DATA masks<>+0xf0(SB)/4, $0xffffffff
|
| 1276 |
+
DATA masks<>+0xf4(SB)/4, $0xffffffff
|
| 1277 |
+
DATA masks<>+0xf8(SB)/4, $0xffffffff
|
| 1278 |
+
DATA masks<>+0xfc(SB)/4, $0x00ffffff
|
| 1279 |
+
|
| 1280 |
+
GLOBL masks<>(SB),RODATA,$256
|
| 1281 |
+
|
| 1282 |
+
// these are arguments to pshufb. They move data down from
|
| 1283 |
+
// the high bytes of the register to the low bytes of the register.
|
| 1284 |
+
// index is how many bytes to move.
|
| 1285 |
+
DATA shifts<>+0x00(SB)/4, $0x00000000
|
| 1286 |
+
DATA shifts<>+0x04(SB)/4, $0x00000000
|
| 1287 |
+
DATA shifts<>+0x08(SB)/4, $0x00000000
|
| 1288 |
+
DATA shifts<>+0x0c(SB)/4, $0x00000000
|
| 1289 |
+
|
| 1290 |
+
DATA shifts<>+0x10(SB)/4, $0xffffff0f
|
| 1291 |
+
DATA shifts<>+0x14(SB)/4, $0xffffffff
|
| 1292 |
+
DATA shifts<>+0x18(SB)/4, $0xffffffff
|
| 1293 |
+
DATA shifts<>+0x1c(SB)/4, $0xffffffff
|
| 1294 |
+
|
| 1295 |
+
DATA shifts<>+0x20(SB)/4, $0xffff0f0e
|
| 1296 |
+
DATA shifts<>+0x24(SB)/4, $0xffffffff
|
| 1297 |
+
DATA shifts<>+0x28(SB)/4, $0xffffffff
|
| 1298 |
+
DATA shifts<>+0x2c(SB)/4, $0xffffffff
|
| 1299 |
+
|
| 1300 |
+
DATA shifts<>+0x30(SB)/4, $0xff0f0e0d
|
| 1301 |
+
DATA shifts<>+0x34(SB)/4, $0xffffffff
|
| 1302 |
+
DATA shifts<>+0x38(SB)/4, $0xffffffff
|
| 1303 |
+
DATA shifts<>+0x3c(SB)/4, $0xffffffff
|
| 1304 |
+
|
| 1305 |
+
DATA shifts<>+0x40(SB)/4, $0x0f0e0d0c
|
| 1306 |
+
DATA shifts<>+0x44(SB)/4, $0xffffffff
|
| 1307 |
+
DATA shifts<>+0x48(SB)/4, $0xffffffff
|
| 1308 |
+
DATA shifts<>+0x4c(SB)/4, $0xffffffff
|
| 1309 |
+
|
| 1310 |
+
DATA shifts<>+0x50(SB)/4, $0x0e0d0c0b
|
| 1311 |
+
DATA shifts<>+0x54(SB)/4, $0xffffff0f
|
| 1312 |
+
DATA shifts<>+0x58(SB)/4, $0xffffffff
|
| 1313 |
+
DATA shifts<>+0x5c(SB)/4, $0xffffffff
|
| 1314 |
+
|
| 1315 |
+
DATA shifts<>+0x60(SB)/4, $0x0d0c0b0a
|
| 1316 |
+
DATA shifts<>+0x64(SB)/4, $0xffff0f0e
|
| 1317 |
+
DATA shifts<>+0x68(SB)/4, $0xffffffff
|
| 1318 |
+
DATA shifts<>+0x6c(SB)/4, $0xffffffff
|
| 1319 |
+
|
| 1320 |
+
DATA shifts<>+0x70(SB)/4, $0x0c0b0a09
|
| 1321 |
+
DATA shifts<>+0x74(SB)/4, $0xff0f0e0d
|
| 1322 |
+
DATA shifts<>+0x78(SB)/4, $0xffffffff
|
| 1323 |
+
DATA shifts<>+0x7c(SB)/4, $0xffffffff
|
| 1324 |
+
|
| 1325 |
+
DATA shifts<>+0x80(SB)/4, $0x0b0a0908
|
| 1326 |
+
DATA shifts<>+0x84(SB)/4, $0x0f0e0d0c
|
| 1327 |
+
DATA shifts<>+0x88(SB)/4, $0xffffffff
|
| 1328 |
+
DATA shifts<>+0x8c(SB)/4, $0xffffffff
|
| 1329 |
+
|
| 1330 |
+
DATA shifts<>+0x90(SB)/4, $0x0a090807
|
| 1331 |
+
DATA shifts<>+0x94(SB)/4, $0x0e0d0c0b
|
| 1332 |
+
DATA shifts<>+0x98(SB)/4, $0xffffff0f
|
| 1333 |
+
DATA shifts<>+0x9c(SB)/4, $0xffffffff
|
| 1334 |
+
|
| 1335 |
+
DATA shifts<>+0xa0(SB)/4, $0x09080706
|
| 1336 |
+
DATA shifts<>+0xa4(SB)/4, $0x0d0c0b0a
|
| 1337 |
+
DATA shifts<>+0xa8(SB)/4, $0xffff0f0e
|
| 1338 |
+
DATA shifts<>+0xac(SB)/4, $0xffffffff
|
| 1339 |
+
|
| 1340 |
+
DATA shifts<>+0xb0(SB)/4, $0x08070605
|
| 1341 |
+
DATA shifts<>+0xb4(SB)/4, $0x0c0b0a09
|
| 1342 |
+
DATA shifts<>+0xb8(SB)/4, $0xff0f0e0d
|
| 1343 |
+
DATA shifts<>+0xbc(SB)/4, $0xffffffff
|
| 1344 |
+
|
| 1345 |
+
DATA shifts<>+0xc0(SB)/4, $0x07060504
|
| 1346 |
+
DATA shifts<>+0xc4(SB)/4, $0x0b0a0908
|
| 1347 |
+
DATA shifts<>+0xc8(SB)/4, $0x0f0e0d0c
|
| 1348 |
+
DATA shifts<>+0xcc(SB)/4, $0xffffffff
|
| 1349 |
+
|
| 1350 |
+
DATA shifts<>+0xd0(SB)/4, $0x06050403
|
| 1351 |
+
DATA shifts<>+0xd4(SB)/4, $0x0a090807
|
| 1352 |
+
DATA shifts<>+0xd8(SB)/4, $0x0e0d0c0b
|
| 1353 |
+
DATA shifts<>+0xdc(SB)/4, $0xffffff0f
|
| 1354 |
+
|
| 1355 |
+
DATA shifts<>+0xe0(SB)/4, $0x05040302
|
| 1356 |
+
DATA shifts<>+0xe4(SB)/4, $0x09080706
|
| 1357 |
+
DATA shifts<>+0xe8(SB)/4, $0x0d0c0b0a
|
| 1358 |
+
DATA shifts<>+0xec(SB)/4, $0xffff0f0e
|
| 1359 |
+
|
| 1360 |
+
DATA shifts<>+0xf0(SB)/4, $0x04030201
|
| 1361 |
+
DATA shifts<>+0xf4(SB)/4, $0x08070605
|
| 1362 |
+
DATA shifts<>+0xf8(SB)/4, $0x0c0b0a09
|
| 1363 |
+
DATA shifts<>+0xfc(SB)/4, $0xff0f0e0d
|
| 1364 |
+
|
| 1365 |
+
GLOBL shifts<>(SB),RODATA,$256
|
| 1366 |
+
|
| 1367 |
+
TEXT ·checkASM(SB),NOSPLIT,$0-1
|
| 1368 |
+
// check that masks<>(SB) and shifts<>(SB) are aligned to 16-byte
|
| 1369 |
+
MOVL $masks<>(SB), AX
|
| 1370 |
+
MOVL $shifts<>(SB), BX
|
| 1371 |
+
ORL BX, AX
|
| 1372 |
+
TESTL $15, AX
|
| 1373 |
+
SETEQ ret+0(FP)
|
| 1374 |
+
RET
|
| 1375 |
+
|
| 1376 |
+
// Called from cgo wrappers, this function returns g->m->curg.stack.hi.
|
| 1377 |
+
// Must obey the gcc calling convention.
|
| 1378 |
+
TEXT _cgo_topofstack(SB),NOSPLIT,$0
|
| 1379 |
+
get_tls(CX)
|
| 1380 |
+
MOVL g(CX), AX
|
| 1381 |
+
MOVL g_m(AX), AX
|
| 1382 |
+
MOVL m_curg(AX), AX
|
| 1383 |
+
MOVL (g_stack+stack_hi)(AX), AX
|
| 1384 |
+
RET
|
| 1385 |
+
|
| 1386 |
+
// The top-most function running on a goroutine
|
| 1387 |
+
// returns to goexit+PCQuantum.
|
| 1388 |
+
TEXT runtime·goexit(SB),NOSPLIT|TOPFRAME,$0-0
|
| 1389 |
+
BYTE $0x90 // NOP
|
| 1390 |
+
CALL runtime·goexit1(SB) // does not return
|
| 1391 |
+
// traceback from goexit1 must hit code range of goexit
|
| 1392 |
+
BYTE $0x90 // NOP
|
| 1393 |
+
|
| 1394 |
+
// Add a module's moduledata to the linked list of moduledata objects. This
|
| 1395 |
+
// is called from .init_array by a function generated in the linker and so
|
| 1396 |
+
// follows the platform ABI wrt register preservation -- it only touches AX,
|
| 1397 |
+
// CX (implicitly) and DX, but it does not follow the ABI wrt arguments:
|
| 1398 |
+
// instead the pointer to the moduledata is passed in AX.
|
| 1399 |
+
TEXT runtime·addmoduledata(SB),NOSPLIT,$0-0
|
| 1400 |
+
MOVL runtime·lastmoduledatap(SB), DX
|
| 1401 |
+
MOVL AX, moduledata_next(DX)
|
| 1402 |
+
MOVL AX, runtime·lastmoduledatap(SB)
|
| 1403 |
+
RET
|
| 1404 |
+
|
| 1405 |
+
TEXT runtime·uint32tofloat64(SB),NOSPLIT,$8-12
|
| 1406 |
+
MOVL a+0(FP), AX
|
| 1407 |
+
MOVL AX, 0(SP)
|
| 1408 |
+
MOVL $0, 4(SP)
|
| 1409 |
+
FMOVV 0(SP), F0
|
| 1410 |
+
FMOVDP F0, ret+4(FP)
|
| 1411 |
+
RET
|
| 1412 |
+
|
| 1413 |
+
TEXT runtime·float64touint32(SB),NOSPLIT,$12-12
|
| 1414 |
+
FMOVD a+0(FP), F0
|
| 1415 |
+
FSTCW 0(SP)
|
| 1416 |
+
FLDCW runtime·controlWord64trunc(SB)
|
| 1417 |
+
FMOVVP F0, 4(SP)
|
| 1418 |
+
FLDCW 0(SP)
|
| 1419 |
+
MOVL 4(SP), AX
|
| 1420 |
+
MOVL AX, ret+8(FP)
|
| 1421 |
+
RET
|
| 1422 |
+
|
| 1423 |
+
// gcWriteBarrier informs the GC about heap pointer writes.
|
| 1424 |
+
//
|
| 1425 |
+
// gcWriteBarrier returns space in a write barrier buffer which
|
| 1426 |
+
// should be filled in by the caller.
|
| 1427 |
+
// gcWriteBarrier does NOT follow the Go ABI. It accepts the
|
| 1428 |
+
// number of bytes of buffer needed in DI, and returns a pointer
|
| 1429 |
+
// to the buffer space in DI.
|
| 1430 |
+
// It clobbers FLAGS. It does not clobber any general-purpose registers,
|
| 1431 |
+
// but may clobber others (e.g., SSE registers).
|
| 1432 |
+
// Typical use would be, when doing *(CX+88) = AX
|
| 1433 |
+
// CMPL $0, runtime.writeBarrier(SB)
|
| 1434 |
+
// JEQ dowrite
|
| 1435 |
+
// CALL runtime.gcBatchBarrier2(SB)
|
| 1436 |
+
// MOVL AX, (DI)
|
| 1437 |
+
// MOVL 88(CX), DX
|
| 1438 |
+
// MOVL DX, 4(DI)
|
| 1439 |
+
// dowrite:
|
| 1440 |
+
// MOVL AX, 88(CX)
|
| 1441 |
+
TEXT gcWriteBarrier<>(SB),NOSPLIT,$28
|
| 1442 |
+
// Save the registers clobbered by the fast path. This is slightly
|
| 1443 |
+
// faster than having the caller spill these.
|
| 1444 |
+
MOVL CX, 20(SP)
|
| 1445 |
+
MOVL BX, 24(SP)
|
| 1446 |
+
retry:
|
| 1447 |
+
// TODO: Consider passing g.m.p in as an argument so they can be shared
|
| 1448 |
+
// across a sequence of write barriers.
|
| 1449 |
+
get_tls(BX)
|
| 1450 |
+
MOVL g(BX), BX
|
| 1451 |
+
MOVL g_m(BX), BX
|
| 1452 |
+
MOVL m_p(BX), BX
|
| 1453 |
+
// Get current buffer write position.
|
| 1454 |
+
MOVL (p_wbBuf+wbBuf_next)(BX), CX // original next position
|
| 1455 |
+
ADDL DI, CX // new next position
|
| 1456 |
+
// Is the buffer full?
|
| 1457 |
+
CMPL CX, (p_wbBuf+wbBuf_end)(BX)
|
| 1458 |
+
JA flush
|
| 1459 |
+
// Commit to the larger buffer.
|
| 1460 |
+
MOVL CX, (p_wbBuf+wbBuf_next)(BX)
|
| 1461 |
+
// Make return value (the original next position)
|
| 1462 |
+
SUBL DI, CX
|
| 1463 |
+
MOVL CX, DI
|
| 1464 |
+
// Restore registers.
|
| 1465 |
+
MOVL 20(SP), CX
|
| 1466 |
+
MOVL 24(SP), BX
|
| 1467 |
+
RET
|
| 1468 |
+
|
| 1469 |
+
flush:
|
| 1470 |
+
// Save all general purpose registers since these could be
|
| 1471 |
+
// clobbered by wbBufFlush and were not saved by the caller.
|
| 1472 |
+
MOVL DI, 0(SP)
|
| 1473 |
+
MOVL AX, 4(SP)
|
| 1474 |
+
// BX already saved
|
| 1475 |
+
// CX already saved
|
| 1476 |
+
MOVL DX, 8(SP)
|
| 1477 |
+
MOVL BP, 12(SP)
|
| 1478 |
+
MOVL SI, 16(SP)
|
| 1479 |
+
// DI already saved
|
| 1480 |
+
|
| 1481 |
+
CALL runtime·wbBufFlush(SB)
|
| 1482 |
+
|
| 1483 |
+
MOVL 0(SP), DI
|
| 1484 |
+
MOVL 4(SP), AX
|
| 1485 |
+
MOVL 8(SP), DX
|
| 1486 |
+
MOVL 12(SP), BP
|
| 1487 |
+
MOVL 16(SP), SI
|
| 1488 |
+
JMP retry
|
| 1489 |
+
|
| 1490 |
+
TEXT runtime·gcWriteBarrier1<ABIInternal>(SB),NOSPLIT,$0
|
| 1491 |
+
MOVL $4, DI
|
| 1492 |
+
JMP gcWriteBarrier<>(SB)
|
| 1493 |
+
TEXT runtime·gcWriteBarrier2<ABIInternal>(SB),NOSPLIT,$0
|
| 1494 |
+
MOVL $8, DI
|
| 1495 |
+
JMP gcWriteBarrier<>(SB)
|
| 1496 |
+
TEXT runtime·gcWriteBarrier3<ABIInternal>(SB),NOSPLIT,$0
|
| 1497 |
+
MOVL $12, DI
|
| 1498 |
+
JMP gcWriteBarrier<>(SB)
|
| 1499 |
+
TEXT runtime·gcWriteBarrier4<ABIInternal>(SB),NOSPLIT,$0
|
| 1500 |
+
MOVL $16, DI
|
| 1501 |
+
JMP gcWriteBarrier<>(SB)
|
| 1502 |
+
TEXT runtime·gcWriteBarrier5<ABIInternal>(SB),NOSPLIT,$0
|
| 1503 |
+
MOVL $20, DI
|
| 1504 |
+
JMP gcWriteBarrier<>(SB)
|
| 1505 |
+
TEXT runtime·gcWriteBarrier6<ABIInternal>(SB),NOSPLIT,$0
|
| 1506 |
+
MOVL $24, DI
|
| 1507 |
+
JMP gcWriteBarrier<>(SB)
|
| 1508 |
+
TEXT runtime·gcWriteBarrier7<ABIInternal>(SB),NOSPLIT,$0
|
| 1509 |
+
MOVL $28, DI
|
| 1510 |
+
JMP gcWriteBarrier<>(SB)
|
| 1511 |
+
TEXT runtime·gcWriteBarrier8<ABIInternal>(SB),NOSPLIT,$0
|
| 1512 |
+
MOVL $32, DI
|
| 1513 |
+
JMP gcWriteBarrier<>(SB)
|
| 1514 |
+
|
| 1515 |
+
TEXT runtime·panicBounds<ABIInternal>(SB),NOSPLIT,$40-0
|
| 1516 |
+
NO_LOCAL_POINTERS
|
| 1517 |
+
// Save all int registers that could have an index in them.
|
| 1518 |
+
// They may be pointers, but if they are they are dead.
|
| 1519 |
+
MOVL AX, 8(SP)
|
| 1520 |
+
MOVL CX, 12(SP)
|
| 1521 |
+
MOVL DX, 16(SP)
|
| 1522 |
+
MOVL BX, 20(SP)
|
| 1523 |
+
// skip SP @ 24(SP)
|
| 1524 |
+
MOVL BP, 28(SP)
|
| 1525 |
+
MOVL SI, 32(SP)
|
| 1526 |
+
MOVL DI, 36(SP)
|
| 1527 |
+
|
| 1528 |
+
MOVL SP, AX // hide SP read from vet
|
| 1529 |
+
MOVL 40(AX), AX // PC immediately after call to panicBounds
|
| 1530 |
+
MOVL AX, 0(SP)
|
| 1531 |
+
LEAL 8(SP), AX
|
| 1532 |
+
MOVL AX, 4(SP)
|
| 1533 |
+
CALL runtime·panicBounds32<ABIInternal>(SB)
|
| 1534 |
+
RET
|
| 1535 |
+
|
| 1536 |
+
TEXT runtime·panicExtend<ABIInternal>(SB),NOSPLIT,$40-0
|
| 1537 |
+
NO_LOCAL_POINTERS
|
| 1538 |
+
// Save all int registers that could have an index in them.
|
| 1539 |
+
// They may be pointers, but if they are they are dead.
|
| 1540 |
+
MOVL AX, 8(SP)
|
| 1541 |
+
MOVL CX, 12(SP)
|
| 1542 |
+
MOVL DX, 16(SP)
|
| 1543 |
+
MOVL BX, 20(SP)
|
| 1544 |
+
// skip SP @ 24(SP)
|
| 1545 |
+
MOVL BP, 28(SP)
|
| 1546 |
+
MOVL SI, 32(SP)
|
| 1547 |
+
MOVL DI, 36(SP)
|
| 1548 |
+
|
| 1549 |
+
MOVL SP, AX // hide SP read from vet
|
| 1550 |
+
MOVL 40(AX), AX // PC immediately after call to panicExtend
|
| 1551 |
+
MOVL AX, 0(SP)
|
| 1552 |
+
LEAL 8(SP), AX
|
| 1553 |
+
MOVL AX, 4(SP)
|
| 1554 |
+
CALL runtime·panicBounds32X<ABIInternal>(SB)
|
| 1555 |
+
RET
|
| 1556 |
+
|
| 1557 |
+
#ifdef GOOS_android
|
| 1558 |
+
// Use the free TLS_SLOT_APP slot #2 on Android Q.
|
| 1559 |
+
// Earlier androids are set up in gcc_android.c.
|
| 1560 |
+
DATA runtime·tls_g+0(SB)/4, $8
|
| 1561 |
+
GLOBL runtime·tls_g+0(SB), NOPTR, $4
|
| 1562 |
+
#endif
|
| 1563 |
+
#ifdef GOOS_windows
|
| 1564 |
+
GLOBL runtime·tls_g+0(SB), NOPTR, $4
|
| 1565 |
+
#endif
|
go/src/runtime/asm_amd64.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// Define features that are guaranteed to be supported by setting the AMD64 variable.
|
| 6 |
+
// If a feature is supported, there's no need to check it at runtime every time.
|
| 7 |
+
|
| 8 |
+
#ifdef GOAMD64_v2
|
| 9 |
+
#define hasPOPCNT
|
| 10 |
+
#define hasSSE42
|
| 11 |
+
#endif
|
| 12 |
+
|
| 13 |
+
#ifdef GOAMD64_v3
|
| 14 |
+
#define hasAVX
|
| 15 |
+
#define hasAVX2
|
| 16 |
+
#define hasPOPCNT
|
| 17 |
+
#define hasSSE42
|
| 18 |
+
#endif
|
| 19 |
+
|
| 20 |
+
#ifdef GOAMD64_v4
|
| 21 |
+
#define hasAVX
|
| 22 |
+
#define hasAVX2
|
| 23 |
+
#define hasAVX512F
|
| 24 |
+
#define hasAVX512BW
|
| 25 |
+
#define hasAVX512VL
|
| 26 |
+
#define hasPOPCNT
|
| 27 |
+
#define hasSSE42
|
| 28 |
+
#endif
|
go/src/runtime/asm_amd64.s
ADDED
|
@@ -0,0 +1,2175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2009 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 "go_asm.h"
|
| 6 |
+
#include "go_tls.h"
|
| 7 |
+
#include "funcdata.h"
|
| 8 |
+
#include "textflag.h"
|
| 9 |
+
#include "cgo/abi_amd64.h"
|
| 10 |
+
|
| 11 |
+
// _rt0_amd64 is common startup code for most amd64 systems when using
|
| 12 |
+
// internal linking. This is the entry point for the program from the
|
| 13 |
+
// kernel for an ordinary -buildmode=exe program. The stack holds the
|
| 14 |
+
// number of arguments and the C-style argv.
|
| 15 |
+
TEXT _rt0_amd64(SB),NOSPLIT,$-8
|
| 16 |
+
MOVQ 0(SP), DI // argc
|
| 17 |
+
LEAQ 8(SP), SI // argv
|
| 18 |
+
JMP runtime·rt0_go(SB)
|
| 19 |
+
|
| 20 |
+
// main is common startup code for most amd64 systems when using
|
| 21 |
+
// external linking. The C startup code will call the symbol "main"
|
| 22 |
+
// passing argc and argv in the usual C ABI registers DI and SI.
|
| 23 |
+
TEXT main(SB),NOSPLIT,$-8
|
| 24 |
+
JMP runtime·rt0_go(SB)
|
| 25 |
+
|
| 26 |
+
// _rt0_amd64_lib is common startup code for most amd64 systems when
|
| 27 |
+
// using -buildmode=c-archive or -buildmode=c-shared. The linker will
|
| 28 |
+
// arrange to invoke this function as a global constructor (for
|
| 29 |
+
// c-archive) or when the shared library is loaded (for c-shared).
|
| 30 |
+
// We expect argc and argv to be passed in the usual C ABI registers
|
| 31 |
+
// DI and SI.
|
| 32 |
+
TEXT _rt0_amd64_lib(SB),NOSPLIT|NOFRAME,$0
|
| 33 |
+
// Transition from C ABI to Go ABI.
|
| 34 |
+
PUSH_REGS_HOST_TO_ABI0()
|
| 35 |
+
|
| 36 |
+
MOVQ DI, _rt0_amd64_lib_argc<>(SB)
|
| 37 |
+
MOVQ SI, _rt0_amd64_lib_argv<>(SB)
|
| 38 |
+
|
| 39 |
+
// Synchronous initialization.
|
| 40 |
+
#ifndef GOOS_windows
|
| 41 |
+
// Avoid calling it on Windows because it is not used
|
| 42 |
+
// and it would crash the application due to the autogenerated
|
| 43 |
+
// ABI wrapper trying to access a non-existent TLS slot.
|
| 44 |
+
CALL runtime·libpreinit(SB)
|
| 45 |
+
#endif
|
| 46 |
+
|
| 47 |
+
// Create a new thread to finish Go runtime initialization.
|
| 48 |
+
MOVQ _cgo_sys_thread_create(SB), AX
|
| 49 |
+
TESTQ AX, AX
|
| 50 |
+
JZ nocgo
|
| 51 |
+
|
| 52 |
+
// We're calling back to C.
|
| 53 |
+
// Align stack per C ABI requirements.
|
| 54 |
+
MOVQ SP, BX // Callee-save in C ABI
|
| 55 |
+
ANDQ $~15, SP
|
| 56 |
+
MOVQ $_rt0_amd64_lib_go(SB), DI
|
| 57 |
+
MOVQ $0, SI
|
| 58 |
+
#ifdef GOOS_windows
|
| 59 |
+
// For Windows ABI
|
| 60 |
+
MOVQ DI, CX
|
| 61 |
+
MOVQ SI, DX
|
| 62 |
+
// Leave space for four words on the stack as required
|
| 63 |
+
// by the Windows amd64 calling convention.
|
| 64 |
+
ADJSP $32
|
| 65 |
+
#endif
|
| 66 |
+
CALL AX
|
| 67 |
+
#ifdef GOOS_windows
|
| 68 |
+
ADJSP $-32 // just to make the assembler not complain about unbalanced stack
|
| 69 |
+
#endif
|
| 70 |
+
MOVQ BX, SP
|
| 71 |
+
JMP restore
|
| 72 |
+
|
| 73 |
+
nocgo:
|
| 74 |
+
ADJSP $16
|
| 75 |
+
MOVQ $0x800000, 0(SP) // stacksize
|
| 76 |
+
MOVQ $_rt0_amd64_lib_go(SB), AX
|
| 77 |
+
MOVQ AX, 8(SP) // fn
|
| 78 |
+
CALL runtime·newosproc0(SB)
|
| 79 |
+
ADJSP $-16
|
| 80 |
+
|
| 81 |
+
restore:
|
| 82 |
+
POP_REGS_HOST_TO_ABI0()
|
| 83 |
+
RET
|
| 84 |
+
|
| 85 |
+
// _rt0_amd64_lib_go initializes the Go runtime.
|
| 86 |
+
// This is started in a separate thread by _rt0_amd64_lib.
|
| 87 |
+
TEXT _rt0_amd64_lib_go(SB),NOSPLIT,$0
|
| 88 |
+
MOVQ _rt0_amd64_lib_argc<>(SB), DI
|
| 89 |
+
MOVQ _rt0_amd64_lib_argv<>(SB), SI
|
| 90 |
+
JMP runtime·rt0_go(SB)
|
| 91 |
+
|
| 92 |
+
DATA _rt0_amd64_lib_argc<>(SB)/8, $0
|
| 93 |
+
GLOBL _rt0_amd64_lib_argc<>(SB),NOPTR, $8
|
| 94 |
+
DATA _rt0_amd64_lib_argv<>(SB)/8, $0
|
| 95 |
+
GLOBL _rt0_amd64_lib_argv<>(SB),NOPTR, $8
|
| 96 |
+
|
| 97 |
+
#ifdef GOAMD64_v2
|
| 98 |
+
DATA bad_cpu_msg<>+0x00(SB)/84, $"This program can only be run on AMD64 processors with v2 microarchitecture support.\n"
|
| 99 |
+
#endif
|
| 100 |
+
|
| 101 |
+
#ifdef GOAMD64_v3
|
| 102 |
+
DATA bad_cpu_msg<>+0x00(SB)/84, $"This program can only be run on AMD64 processors with v3 microarchitecture support.\n"
|
| 103 |
+
#endif
|
| 104 |
+
|
| 105 |
+
#ifdef GOAMD64_v4
|
| 106 |
+
DATA bad_cpu_msg<>+0x00(SB)/84, $"This program can only be run on AMD64 processors with v4 microarchitecture support.\n"
|
| 107 |
+
#endif
|
| 108 |
+
|
| 109 |
+
GLOBL bad_cpu_msg<>(SB), RODATA, $84
|
| 110 |
+
|
| 111 |
+
// Define a list of AMD64 microarchitecture level features
|
| 112 |
+
// https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels
|
| 113 |
+
|
| 114 |
+
// SSE3 SSSE3 CMPXCHNG16 SSE4.1 SSE4.2 POPCNT
|
| 115 |
+
#define V2_FEATURES_CX (1 << 0 | 1 << 9 | 1 << 13 | 1 << 19 | 1 << 20 | 1 << 23)
|
| 116 |
+
// LAHF/SAHF
|
| 117 |
+
#define V2_EXT_FEATURES_CX (1 << 0)
|
| 118 |
+
// FMA MOVBE OSXSAVE AVX F16C
|
| 119 |
+
#define V3_FEATURES_CX (V2_FEATURES_CX | 1 << 12 | 1 << 22 | 1 << 27 | 1 << 28 | 1 << 29)
|
| 120 |
+
// ABM (FOR LZNCT)
|
| 121 |
+
#define V3_EXT_FEATURES_CX (V2_EXT_FEATURES_CX | 1 << 5)
|
| 122 |
+
// BMI1 AVX2 BMI2
|
| 123 |
+
#define V3_EXT_FEATURES_BX (1 << 3 | 1 << 5 | 1 << 8)
|
| 124 |
+
// XMM YMM
|
| 125 |
+
#define V3_OS_SUPPORT_AX (1 << 1 | 1 << 2)
|
| 126 |
+
|
| 127 |
+
#define V4_FEATURES_CX V3_FEATURES_CX
|
| 128 |
+
|
| 129 |
+
#define V4_EXT_FEATURES_CX V3_EXT_FEATURES_CX
|
| 130 |
+
// AVX512F AVX512DQ AVX512CD AVX512BW AVX512VL
|
| 131 |
+
#define V4_EXT_FEATURES_BX (V3_EXT_FEATURES_BX | 1 << 16 | 1 << 17 | 1 << 28 | 1 << 30 | 1 << 31)
|
| 132 |
+
// OPMASK ZMM
|
| 133 |
+
#define V4_OS_SUPPORT_AX (V3_OS_SUPPORT_AX | 1 << 5 | (1 << 6 | 1 << 7))
|
| 134 |
+
|
| 135 |
+
#ifdef GOAMD64_v2
|
| 136 |
+
#define NEED_MAX_CPUID 0x80000001
|
| 137 |
+
#define NEED_FEATURES_CX V2_FEATURES_CX
|
| 138 |
+
#define NEED_EXT_FEATURES_CX V2_EXT_FEATURES_CX
|
| 139 |
+
#endif
|
| 140 |
+
|
| 141 |
+
#ifdef GOAMD64_v3
|
| 142 |
+
#define NEED_MAX_CPUID 0x80000001
|
| 143 |
+
#define NEED_FEATURES_CX V3_FEATURES_CX
|
| 144 |
+
#define NEED_EXT_FEATURES_CX V3_EXT_FEATURES_CX
|
| 145 |
+
#define NEED_EXT_FEATURES_BX V3_EXT_FEATURES_BX
|
| 146 |
+
#define NEED_OS_SUPPORT_AX V3_OS_SUPPORT_AX
|
| 147 |
+
#endif
|
| 148 |
+
|
| 149 |
+
#ifdef GOAMD64_v4
|
| 150 |
+
#define NEED_MAX_CPUID 0x80000001
|
| 151 |
+
#define NEED_FEATURES_CX V4_FEATURES_CX
|
| 152 |
+
#define NEED_EXT_FEATURES_CX V4_EXT_FEATURES_CX
|
| 153 |
+
#define NEED_EXT_FEATURES_BX V4_EXT_FEATURES_BX
|
| 154 |
+
|
| 155 |
+
// Darwin requires a different approach to check AVX512 support, see CL 285572.
|
| 156 |
+
#ifdef GOOS_darwin
|
| 157 |
+
#define NEED_OS_SUPPORT_AX V3_OS_SUPPORT_AX
|
| 158 |
+
// These values are from:
|
| 159 |
+
// https://github.com/apple/darwin-xnu/blob/xnu-4570.1.46/osfmk/i386/cpu_capabilities.h
|
| 160 |
+
#define commpage64_base_address 0x00007fffffe00000
|
| 161 |
+
#define commpage64_cpu_capabilities64 (commpage64_base_address+0x010)
|
| 162 |
+
#define commpage64_version (commpage64_base_address+0x01E)
|
| 163 |
+
#define AVX512F 0x0000004000000000
|
| 164 |
+
#define AVX512CD 0x0000008000000000
|
| 165 |
+
#define AVX512DQ 0x0000010000000000
|
| 166 |
+
#define AVX512BW 0x0000020000000000
|
| 167 |
+
#define AVX512VL 0x0000100000000000
|
| 168 |
+
#define NEED_DARWIN_SUPPORT (AVX512F | AVX512DQ | AVX512CD | AVX512BW | AVX512VL)
|
| 169 |
+
#else
|
| 170 |
+
#define NEED_OS_SUPPORT_AX V4_OS_SUPPORT_AX
|
| 171 |
+
#endif
|
| 172 |
+
|
| 173 |
+
#endif
|
| 174 |
+
|
| 175 |
+
TEXT runtime·rt0_go(SB),NOSPLIT|NOFRAME|TOPFRAME,$0
|
| 176 |
+
// copy arguments forward on an even stack
|
| 177 |
+
MOVQ DI, AX // argc
|
| 178 |
+
MOVQ SI, BX // argv
|
| 179 |
+
SUBQ $(5*8), SP // 3args 2auto
|
| 180 |
+
ANDQ $~15, SP
|
| 181 |
+
MOVQ AX, 24(SP)
|
| 182 |
+
MOVQ BX, 32(SP)
|
| 183 |
+
|
| 184 |
+
// This is typically the entry point for Go programs.
|
| 185 |
+
// Call stack unwinding must not proceed past this frame.
|
| 186 |
+
// Set the frame pointer register to 0 so that frame pointer-based unwinders
|
| 187 |
+
// (which don't use debug info for performance reasons)
|
| 188 |
+
// won't attempt to unwind past this function.
|
| 189 |
+
// See go.dev/issue/63630
|
| 190 |
+
MOVQ $0, BP
|
| 191 |
+
|
| 192 |
+
// create istack out of the given (operating system) stack.
|
| 193 |
+
// _cgo_init may update stackguard.
|
| 194 |
+
MOVQ $runtime·g0(SB), DI
|
| 195 |
+
LEAQ (-64*1024)(SP), BX
|
| 196 |
+
MOVQ BX, g_stackguard0(DI)
|
| 197 |
+
MOVQ BX, g_stackguard1(DI)
|
| 198 |
+
MOVQ BX, (g_stack+stack_lo)(DI)
|
| 199 |
+
MOVQ SP, (g_stack+stack_hi)(DI)
|
| 200 |
+
|
| 201 |
+
// find out information about the processor we're on
|
| 202 |
+
MOVL $0, AX
|
| 203 |
+
CPUID
|
| 204 |
+
CMPL AX, $0
|
| 205 |
+
JE nocpuinfo
|
| 206 |
+
|
| 207 |
+
CMPL BX, $0x756E6547 // "Genu"
|
| 208 |
+
JNE notintel
|
| 209 |
+
CMPL DX, $0x49656E69 // "ineI"
|
| 210 |
+
JNE notintel
|
| 211 |
+
CMPL CX, $0x6C65746E // "ntel"
|
| 212 |
+
JNE notintel
|
| 213 |
+
MOVB $1, runtime·isIntel(SB)
|
| 214 |
+
|
| 215 |
+
notintel:
|
| 216 |
+
// Load EAX=1 cpuid flags
|
| 217 |
+
MOVL $1, AX
|
| 218 |
+
CPUID
|
| 219 |
+
MOVL AX, runtime·processorVersionInfo(SB)
|
| 220 |
+
|
| 221 |
+
nocpuinfo:
|
| 222 |
+
// if there is an _cgo_init, call it.
|
| 223 |
+
MOVQ _cgo_init(SB), AX
|
| 224 |
+
TESTQ AX, AX
|
| 225 |
+
JZ needtls
|
| 226 |
+
// arg 1: g0, already in DI
|
| 227 |
+
MOVQ $setg_gcc<>(SB), SI // arg 2: setg_gcc
|
| 228 |
+
MOVQ $0, DX // arg 3, 4: not used when using platform's TLS
|
| 229 |
+
MOVQ $0, CX
|
| 230 |
+
#ifdef GOOS_android
|
| 231 |
+
MOVQ $runtime·tls_g(SB), DX // arg 3: &tls_g
|
| 232 |
+
// arg 4: TLS base, stored in slot 0 (Android's TLS_SLOT_SELF).
|
| 233 |
+
// Compensate for tls_g (+16).
|
| 234 |
+
MOVQ -16(TLS), CX
|
| 235 |
+
#endif
|
| 236 |
+
#ifdef GOOS_windows
|
| 237 |
+
MOVQ $runtime·tls_g(SB), DX // arg 3: &tls_g
|
| 238 |
+
// Adjust for the Win64 calling convention.
|
| 239 |
+
MOVQ CX, R9 // arg 4
|
| 240 |
+
MOVQ DX, R8 // arg 3
|
| 241 |
+
MOVQ SI, DX // arg 2
|
| 242 |
+
MOVQ DI, CX // arg 1
|
| 243 |
+
#endif
|
| 244 |
+
CALL AX
|
| 245 |
+
|
| 246 |
+
// update stackguard after _cgo_init
|
| 247 |
+
MOVQ $runtime·g0(SB), CX
|
| 248 |
+
MOVQ (g_stack+stack_lo)(CX), AX
|
| 249 |
+
ADDQ $const_stackGuard, AX
|
| 250 |
+
MOVQ AX, g_stackguard0(CX)
|
| 251 |
+
MOVQ AX, g_stackguard1(CX)
|
| 252 |
+
|
| 253 |
+
#ifndef GOOS_windows
|
| 254 |
+
JMP ok
|
| 255 |
+
#endif
|
| 256 |
+
needtls:
|
| 257 |
+
#ifdef GOOS_plan9
|
| 258 |
+
// skip TLS setup on Plan 9
|
| 259 |
+
JMP ok
|
| 260 |
+
#endif
|
| 261 |
+
#ifdef GOOS_solaris
|
| 262 |
+
// skip TLS setup on Solaris
|
| 263 |
+
JMP ok
|
| 264 |
+
#endif
|
| 265 |
+
#ifdef GOOS_illumos
|
| 266 |
+
// skip TLS setup on illumos
|
| 267 |
+
JMP ok
|
| 268 |
+
#endif
|
| 269 |
+
#ifdef GOOS_darwin
|
| 270 |
+
// skip TLS setup on Darwin
|
| 271 |
+
JMP ok
|
| 272 |
+
#endif
|
| 273 |
+
#ifdef GOOS_openbsd
|
| 274 |
+
// skip TLS setup on OpenBSD
|
| 275 |
+
JMP ok
|
| 276 |
+
#endif
|
| 277 |
+
|
| 278 |
+
#ifdef GOOS_windows
|
| 279 |
+
CALL runtime·wintls(SB)
|
| 280 |
+
#endif
|
| 281 |
+
|
| 282 |
+
LEAQ runtime·m0+m_tls(SB), DI
|
| 283 |
+
CALL runtime·settls(SB)
|
| 284 |
+
|
| 285 |
+
// store through it, to make sure it works
|
| 286 |
+
get_tls(BX)
|
| 287 |
+
MOVQ $0x123, g(BX)
|
| 288 |
+
MOVQ runtime·m0+m_tls(SB), AX
|
| 289 |
+
CMPQ AX, $0x123
|
| 290 |
+
JEQ 2(PC)
|
| 291 |
+
CALL runtime·abort(SB)
|
| 292 |
+
ok:
|
| 293 |
+
// set the per-goroutine and per-mach "registers"
|
| 294 |
+
get_tls(BX)
|
| 295 |
+
LEAQ runtime·g0(SB), CX
|
| 296 |
+
MOVQ CX, g(BX)
|
| 297 |
+
LEAQ runtime·m0(SB), AX
|
| 298 |
+
|
| 299 |
+
// save m->g0 = g0
|
| 300 |
+
MOVQ CX, m_g0(AX)
|
| 301 |
+
// save m0 to g0->m
|
| 302 |
+
MOVQ AX, g_m(CX)
|
| 303 |
+
|
| 304 |
+
CLD // convention is D is always left cleared
|
| 305 |
+
|
| 306 |
+
// Check GOAMD64 requirements
|
| 307 |
+
// We need to do this after setting up TLS, so that
|
| 308 |
+
// we can report an error if there is a failure. See issue 49586.
|
| 309 |
+
#ifdef NEED_FEATURES_CX
|
| 310 |
+
MOVL $0, AX
|
| 311 |
+
CPUID
|
| 312 |
+
CMPL AX, $0
|
| 313 |
+
JE bad_cpu
|
| 314 |
+
MOVL $1, AX
|
| 315 |
+
CPUID
|
| 316 |
+
ANDL $NEED_FEATURES_CX, CX
|
| 317 |
+
CMPL CX, $NEED_FEATURES_CX
|
| 318 |
+
JNE bad_cpu
|
| 319 |
+
#endif
|
| 320 |
+
|
| 321 |
+
#ifdef NEED_MAX_CPUID
|
| 322 |
+
MOVL $0x80000000, AX
|
| 323 |
+
CPUID
|
| 324 |
+
CMPL AX, $NEED_MAX_CPUID
|
| 325 |
+
JL bad_cpu
|
| 326 |
+
#endif
|
| 327 |
+
|
| 328 |
+
#ifdef NEED_EXT_FEATURES_BX
|
| 329 |
+
MOVL $7, AX
|
| 330 |
+
MOVL $0, CX
|
| 331 |
+
CPUID
|
| 332 |
+
ANDL $NEED_EXT_FEATURES_BX, BX
|
| 333 |
+
CMPL BX, $NEED_EXT_FEATURES_BX
|
| 334 |
+
JNE bad_cpu
|
| 335 |
+
#endif
|
| 336 |
+
|
| 337 |
+
#ifdef NEED_EXT_FEATURES_CX
|
| 338 |
+
MOVL $0x80000001, AX
|
| 339 |
+
CPUID
|
| 340 |
+
ANDL $NEED_EXT_FEATURES_CX, CX
|
| 341 |
+
CMPL CX, $NEED_EXT_FEATURES_CX
|
| 342 |
+
JNE bad_cpu
|
| 343 |
+
#endif
|
| 344 |
+
|
| 345 |
+
#ifdef NEED_OS_SUPPORT_AX
|
| 346 |
+
XORL CX, CX
|
| 347 |
+
XGETBV
|
| 348 |
+
ANDL $NEED_OS_SUPPORT_AX, AX
|
| 349 |
+
CMPL AX, $NEED_OS_SUPPORT_AX
|
| 350 |
+
JNE bad_cpu
|
| 351 |
+
#endif
|
| 352 |
+
|
| 353 |
+
#ifdef NEED_DARWIN_SUPPORT
|
| 354 |
+
MOVQ $commpage64_version, BX
|
| 355 |
+
CMPW (BX), $13 // cpu_capabilities64 undefined in versions < 13
|
| 356 |
+
JL bad_cpu
|
| 357 |
+
MOVQ $commpage64_cpu_capabilities64, BX
|
| 358 |
+
MOVQ (BX), BX
|
| 359 |
+
MOVQ $NEED_DARWIN_SUPPORT, CX
|
| 360 |
+
ANDQ CX, BX
|
| 361 |
+
CMPQ BX, CX
|
| 362 |
+
JNE bad_cpu
|
| 363 |
+
#endif
|
| 364 |
+
|
| 365 |
+
CALL runtime·check(SB)
|
| 366 |
+
|
| 367 |
+
MOVL 24(SP), AX // copy argc
|
| 368 |
+
MOVL AX, 0(SP)
|
| 369 |
+
MOVQ 32(SP), AX // copy argv
|
| 370 |
+
MOVQ AX, 8(SP)
|
| 371 |
+
CALL runtime·args(SB)
|
| 372 |
+
CALL runtime·osinit(SB)
|
| 373 |
+
CALL runtime·schedinit(SB)
|
| 374 |
+
|
| 375 |
+
// create a new goroutine to start program
|
| 376 |
+
MOVQ $runtime·mainPC(SB), AX // entry
|
| 377 |
+
PUSHQ AX
|
| 378 |
+
CALL runtime·newproc(SB)
|
| 379 |
+
POPQ AX
|
| 380 |
+
|
| 381 |
+
// start this M
|
| 382 |
+
CALL runtime·mstart(SB)
|
| 383 |
+
|
| 384 |
+
CALL runtime·abort(SB) // mstart should never return
|
| 385 |
+
RET
|
| 386 |
+
|
| 387 |
+
bad_cpu: // show that the program requires a certain microarchitecture level.
|
| 388 |
+
MOVQ $2, 0(SP)
|
| 389 |
+
MOVQ $bad_cpu_msg<>(SB), AX
|
| 390 |
+
MOVQ AX, 8(SP)
|
| 391 |
+
MOVQ $84, 16(SP)
|
| 392 |
+
CALL runtime·write(SB)
|
| 393 |
+
MOVQ $1, 0(SP)
|
| 394 |
+
CALL runtime·exit(SB)
|
| 395 |
+
CALL runtime·abort(SB)
|
| 396 |
+
RET
|
| 397 |
+
|
| 398 |
+
// Prevent dead-code elimination of debugCallV2 and debugPinnerV1, which are
|
| 399 |
+
// intended to be called by debuggers.
|
| 400 |
+
MOVQ $runtime·debugPinnerV1<ABIInternal>(SB), AX
|
| 401 |
+
MOVQ $runtime·debugCallV2<ABIInternal>(SB), AX
|
| 402 |
+
RET
|
| 403 |
+
|
| 404 |
+
// mainPC is a function value for runtime.main, to be passed to newproc.
|
| 405 |
+
// The reference to runtime.main is made via ABIInternal, since the
|
| 406 |
+
// actual function (not the ABI0 wrapper) is needed by newproc.
|
| 407 |
+
DATA runtime·mainPC+0(SB)/8,$runtime·main<ABIInternal>(SB)
|
| 408 |
+
GLOBL runtime·mainPC(SB),RODATA,$8
|
| 409 |
+
|
| 410 |
+
TEXT runtime·breakpoint(SB),NOSPLIT,$0-0
|
| 411 |
+
BYTE $0xcc
|
| 412 |
+
RET
|
| 413 |
+
|
| 414 |
+
TEXT runtime·asminit(SB),NOSPLIT,$0-0
|
| 415 |
+
// No per-thread init.
|
| 416 |
+
RET
|
| 417 |
+
|
| 418 |
+
TEXT runtime·mstart(SB),NOSPLIT|TOPFRAME|NOFRAME,$0
|
| 419 |
+
// This is the root frame of new Go-created OS threads.
|
| 420 |
+
// Call stack unwinding must not proceed past this frame.
|
| 421 |
+
// Set the frame pointer register to 0 so that frame pointer-based unwinders
|
| 422 |
+
// (which don't use debug info for performance reasons)
|
| 423 |
+
// won't attempt to unwind past this function.
|
| 424 |
+
// See go.dev/issue/63630
|
| 425 |
+
MOVD $0, BP
|
| 426 |
+
CALL runtime·mstart0(SB)
|
| 427 |
+
RET // not reached
|
| 428 |
+
|
| 429 |
+
/*
|
| 430 |
+
* go-routine
|
| 431 |
+
*/
|
| 432 |
+
|
| 433 |
+
// func gogo(buf *gobuf)
|
| 434 |
+
// restore state from Gobuf; longjmp
|
| 435 |
+
TEXT runtime·gogo(SB), NOSPLIT, $0-8
|
| 436 |
+
MOVQ buf+0(FP), BX // gobuf
|
| 437 |
+
MOVQ gobuf_g(BX), DX
|
| 438 |
+
MOVQ 0(DX), CX // make sure g != nil
|
| 439 |
+
JMP gogo<>(SB)
|
| 440 |
+
|
| 441 |
+
TEXT gogo<>(SB), NOSPLIT, $0
|
| 442 |
+
get_tls(CX)
|
| 443 |
+
MOVQ DX, g(CX)
|
| 444 |
+
MOVQ DX, R14 // set the g register
|
| 445 |
+
MOVQ gobuf_sp(BX), SP // restore SP
|
| 446 |
+
MOVQ gobuf_ctxt(BX), DX
|
| 447 |
+
MOVQ gobuf_bp(BX), BP
|
| 448 |
+
MOVQ $0, gobuf_sp(BX) // clear to help garbage collector
|
| 449 |
+
MOVQ $0, gobuf_ctxt(BX)
|
| 450 |
+
MOVQ $0, gobuf_bp(BX)
|
| 451 |
+
MOVQ gobuf_pc(BX), BX
|
| 452 |
+
JMP BX
|
| 453 |
+
|
| 454 |
+
// func mcall(fn func(*g))
|
| 455 |
+
// Switch to m->g0's stack, call fn(g).
|
| 456 |
+
// Fn must never return. It should gogo(&g->sched)
|
| 457 |
+
// to keep running g.
|
| 458 |
+
TEXT runtime·mcall<ABIInternal>(SB), NOSPLIT, $0-8
|
| 459 |
+
#ifdef GOEXPERIMENT_runtimesecret
|
| 460 |
+
CMPL g_secret(R14), $0
|
| 461 |
+
JEQ nosecret
|
| 462 |
+
CALL ·secretEraseRegistersMcall(SB)
|
| 463 |
+
nosecret:
|
| 464 |
+
#endif
|
| 465 |
+
|
| 466 |
+
MOVQ AX, DX // DX = fn
|
| 467 |
+
|
| 468 |
+
// Save state in g->sched. The caller's SP and PC are restored by gogo to
|
| 469 |
+
// resume execution in the caller's frame (implicit return). The caller's BP
|
| 470 |
+
// is also restored to support frame pointer unwinding.
|
| 471 |
+
MOVQ SP, BX // hide (SP) reads from vet
|
| 472 |
+
MOVQ 8(BX), BX // caller's PC
|
| 473 |
+
MOVQ BX, (g_sched+gobuf_pc)(R14)
|
| 474 |
+
LEAQ fn+0(FP), BX // caller's SP
|
| 475 |
+
MOVQ BX, (g_sched+gobuf_sp)(R14)
|
| 476 |
+
// Get the caller's frame pointer by dereferencing BP. Storing BP as it is
|
| 477 |
+
// can cause a frame pointer cycle, see CL 476235.
|
| 478 |
+
MOVQ (BP), BX // caller's BP
|
| 479 |
+
MOVQ BX, (g_sched+gobuf_bp)(R14)
|
| 480 |
+
|
| 481 |
+
// switch to m->g0 & its stack, call fn
|
| 482 |
+
MOVQ g_m(R14), BX
|
| 483 |
+
MOVQ m_g0(BX), SI // SI = g.m.g0
|
| 484 |
+
CMPQ SI, R14 // if g == m->g0 call badmcall
|
| 485 |
+
JNE goodm
|
| 486 |
+
JMP runtime·badmcall(SB)
|
| 487 |
+
goodm:
|
| 488 |
+
MOVQ R14, AX // AX (and arg 0) = g
|
| 489 |
+
MOVQ SI, R14 // g = g.m.g0
|
| 490 |
+
get_tls(CX) // Set G in TLS
|
| 491 |
+
MOVQ R14, g(CX)
|
| 492 |
+
MOVQ (g_sched+gobuf_sp)(R14), SP // sp = g0.sched.sp
|
| 493 |
+
MOVQ $0, BP // clear frame pointer, as caller may execute on another M
|
| 494 |
+
PUSHQ AX // open up space for fn's arg spill slot
|
| 495 |
+
MOVQ 0(DX), R12
|
| 496 |
+
CALL R12 // fn(g)
|
| 497 |
+
// The Windows native stack unwinder incorrectly classifies the next instruction
|
| 498 |
+
// as part of the function epilogue, producing a wrong call stack.
|
| 499 |
+
// Add a NOP to work around this issue. See go.dev/issue/67007.
|
| 500 |
+
BYTE $0x90
|
| 501 |
+
POPQ AX
|
| 502 |
+
JMP runtime·badmcall2(SB)
|
| 503 |
+
RET
|
| 504 |
+
|
| 505 |
+
// systemstack_switch is a dummy routine that systemstack leaves at the bottom
|
| 506 |
+
// of the G stack. We need to distinguish the routine that
|
| 507 |
+
// lives at the bottom of the G stack from the one that lives
|
| 508 |
+
// at the top of the system stack because the one at the top of
|
| 509 |
+
// the system stack terminates the stack walk (see topofstack()).
|
| 510 |
+
// The frame layout needs to match systemstack
|
| 511 |
+
// so that it can pretend to be systemstack_switch.
|
| 512 |
+
TEXT runtime·systemstack_switch(SB), NOSPLIT, $0-0
|
| 513 |
+
UNDEF
|
| 514 |
+
// Make sure this function is not leaf,
|
| 515 |
+
// so the frame is saved.
|
| 516 |
+
CALL runtime·abort(SB)
|
| 517 |
+
RET
|
| 518 |
+
|
| 519 |
+
// func systemstack(fn func())
|
| 520 |
+
TEXT runtime·systemstack(SB), NOSPLIT, $0-8
|
| 521 |
+
#ifdef GOEXPERIMENT_runtimesecret
|
| 522 |
+
// If in secret mode, erase registers on transition
|
| 523 |
+
// from G stack to M stack,
|
| 524 |
+
get_tls(CX)
|
| 525 |
+
MOVQ g(CX), AX
|
| 526 |
+
CMPL g_secret(AX), $0
|
| 527 |
+
JEQ nosecret
|
| 528 |
+
CALL ·secretEraseRegisters(SB)
|
| 529 |
+
nosecret:
|
| 530 |
+
#endif
|
| 531 |
+
|
| 532 |
+
MOVQ fn+0(FP), DI // DI = fn
|
| 533 |
+
get_tls(CX)
|
| 534 |
+
MOVQ g(CX), AX // AX = g
|
| 535 |
+
MOVQ g_m(AX), BX // BX = m
|
| 536 |
+
|
| 537 |
+
CMPQ AX, m_gsignal(BX)
|
| 538 |
+
JEQ noswitch
|
| 539 |
+
|
| 540 |
+
MOVQ m_g0(BX), DX // DX = g0
|
| 541 |
+
CMPQ AX, DX
|
| 542 |
+
JEQ noswitch
|
| 543 |
+
|
| 544 |
+
CMPQ AX, m_curg(BX)
|
| 545 |
+
JNE bad
|
| 546 |
+
|
| 547 |
+
// Switch stacks.
|
| 548 |
+
// The original frame pointer is stored in BP,
|
| 549 |
+
// which is useful for stack unwinding.
|
| 550 |
+
// Save our state in g->sched. Pretend to
|
| 551 |
+
// be systemstack_switch if the G stack is scanned.
|
| 552 |
+
CALL gosave_systemstack_switch<>(SB)
|
| 553 |
+
|
| 554 |
+
// switch to g0
|
| 555 |
+
MOVQ DX, g(CX)
|
| 556 |
+
MOVQ DX, R14 // set the g register
|
| 557 |
+
MOVQ (g_sched+gobuf_sp)(DX), SP
|
| 558 |
+
|
| 559 |
+
// call target function
|
| 560 |
+
MOVQ DI, DX
|
| 561 |
+
MOVQ 0(DI), DI
|
| 562 |
+
CALL DI
|
| 563 |
+
|
| 564 |
+
// switch back to g
|
| 565 |
+
get_tls(CX)
|
| 566 |
+
MOVQ g(CX), AX
|
| 567 |
+
MOVQ g_m(AX), BX
|
| 568 |
+
MOVQ m_curg(BX), AX
|
| 569 |
+
MOVQ AX, g(CX)
|
| 570 |
+
MOVQ (g_sched+gobuf_sp)(AX), SP
|
| 571 |
+
MOVQ (g_sched+gobuf_bp)(AX), BP
|
| 572 |
+
MOVQ $0, (g_sched+gobuf_sp)(AX)
|
| 573 |
+
MOVQ $0, (g_sched+gobuf_bp)(AX)
|
| 574 |
+
RET
|
| 575 |
+
|
| 576 |
+
noswitch:
|
| 577 |
+
// already on m stack; tail call the function
|
| 578 |
+
// Using a tail call here cleans up tracebacks since we won't stop
|
| 579 |
+
// at an intermediate systemstack.
|
| 580 |
+
MOVQ DI, DX
|
| 581 |
+
MOVQ 0(DI), DI
|
| 582 |
+
// The function epilogue is not called on a tail call.
|
| 583 |
+
// Pop BP from the stack to simulate it.
|
| 584 |
+
POPQ BP
|
| 585 |
+
JMP DI
|
| 586 |
+
|
| 587 |
+
bad:
|
| 588 |
+
// Bad: g is not gsignal, not g0, not curg. What is it?
|
| 589 |
+
MOVQ $runtime·badsystemstack(SB), AX
|
| 590 |
+
CALL AX
|
| 591 |
+
INT $3
|
| 592 |
+
|
| 593 |
+
// func switchToCrashStack0(fn func())
|
| 594 |
+
TEXT runtime·switchToCrashStack0<ABIInternal>(SB), NOSPLIT, $0-8
|
| 595 |
+
MOVQ g_m(R14), BX // curm
|
| 596 |
+
|
| 597 |
+
// set g to gcrash
|
| 598 |
+
LEAQ runtime·gcrash(SB), R14 // g = &gcrash
|
| 599 |
+
MOVQ BX, g_m(R14) // g.m = curm
|
| 600 |
+
MOVQ R14, m_g0(BX) // curm.g0 = g
|
| 601 |
+
get_tls(CX)
|
| 602 |
+
MOVQ R14, g(CX)
|
| 603 |
+
|
| 604 |
+
// switch to crashstack
|
| 605 |
+
MOVQ (g_stack+stack_hi)(R14), BX
|
| 606 |
+
SUBQ $(4*8), BX
|
| 607 |
+
MOVQ BX, SP
|
| 608 |
+
|
| 609 |
+
// call target function
|
| 610 |
+
MOVQ AX, DX
|
| 611 |
+
MOVQ 0(AX), AX
|
| 612 |
+
CALL AX
|
| 613 |
+
|
| 614 |
+
// should never return
|
| 615 |
+
CALL runtime·abort(SB)
|
| 616 |
+
UNDEF
|
| 617 |
+
|
| 618 |
+
/*
|
| 619 |
+
* support for morestack
|
| 620 |
+
*/
|
| 621 |
+
|
| 622 |
+
// Called during function prolog when more stack is needed.
|
| 623 |
+
//
|
| 624 |
+
// The traceback routines see morestack on a g0 as being
|
| 625 |
+
// the top of a stack (for example, morestack calling newstack
|
| 626 |
+
// calling the scheduler calling newm calling gc), so we must
|
| 627 |
+
// record an argument size. For that purpose, it has no arguments.
|
| 628 |
+
TEXT runtime·morestack(SB),NOSPLIT|NOFRAME,$0-0
|
| 629 |
+
// Cannot grow scheduler stack (m->g0).
|
| 630 |
+
get_tls(CX)
|
| 631 |
+
MOVQ g(CX), DI // DI = g
|
| 632 |
+
MOVQ g_m(DI), BX // BX = m
|
| 633 |
+
|
| 634 |
+
// Set g->sched to context in f.
|
| 635 |
+
MOVQ 0(SP), AX // f's PC
|
| 636 |
+
MOVQ AX, (g_sched+gobuf_pc)(DI)
|
| 637 |
+
LEAQ 8(SP), AX // f's SP
|
| 638 |
+
MOVQ AX, (g_sched+gobuf_sp)(DI)
|
| 639 |
+
MOVQ BP, (g_sched+gobuf_bp)(DI)
|
| 640 |
+
MOVQ DX, (g_sched+gobuf_ctxt)(DI)
|
| 641 |
+
|
| 642 |
+
MOVQ m_g0(BX), SI // SI = m.g0
|
| 643 |
+
CMPQ DI, SI
|
| 644 |
+
JNE 3(PC)
|
| 645 |
+
CALL runtime·badmorestackg0(SB)
|
| 646 |
+
CALL runtime·abort(SB)
|
| 647 |
+
|
| 648 |
+
// Cannot grow signal stack (m->gsignal).
|
| 649 |
+
MOVQ m_gsignal(BX), SI
|
| 650 |
+
CMPQ DI, SI
|
| 651 |
+
JNE 3(PC)
|
| 652 |
+
CALL runtime·badmorestackgsignal(SB)
|
| 653 |
+
CALL runtime·abort(SB)
|
| 654 |
+
|
| 655 |
+
// Called from f.
|
| 656 |
+
// Set m->morebuf to f's caller.
|
| 657 |
+
NOP SP // tell vet SP changed - stop checking offsets
|
| 658 |
+
MOVQ 8(SP), AX // f's caller's PC
|
| 659 |
+
MOVQ AX, (m_morebuf+gobuf_pc)(BX)
|
| 660 |
+
LEAQ 16(SP), AX // f's caller's SP
|
| 661 |
+
MOVQ AX, (m_morebuf+gobuf_sp)(BX)
|
| 662 |
+
MOVQ DI, (m_morebuf+gobuf_g)(BX)
|
| 663 |
+
|
| 664 |
+
// If in secret mode, erase registers on transition
|
| 665 |
+
// from G stack to M stack,
|
| 666 |
+
#ifdef GOEXPERIMENT_runtimesecret
|
| 667 |
+
CMPL g_secret(DI), $0
|
| 668 |
+
JEQ nosecret
|
| 669 |
+
CALL ·secretEraseRegisters(SB)
|
| 670 |
+
get_tls(CX)
|
| 671 |
+
MOVQ g(CX), DI // DI = g
|
| 672 |
+
MOVQ g_m(DI), BX // BX = m
|
| 673 |
+
nosecret:
|
| 674 |
+
#endif
|
| 675 |
+
|
| 676 |
+
// Call newstack on m->g0's stack.
|
| 677 |
+
MOVQ m_g0(BX), BX
|
| 678 |
+
MOVQ BX, g(CX)
|
| 679 |
+
MOVQ (g_sched+gobuf_sp)(BX), SP
|
| 680 |
+
MOVQ $0, BP // clear frame pointer, as caller may execute on another M
|
| 681 |
+
CALL runtime·newstack(SB)
|
| 682 |
+
CALL runtime·abort(SB) // crash if newstack returns
|
| 683 |
+
RET
|
| 684 |
+
|
| 685 |
+
// morestack but not preserving ctxt.
|
| 686 |
+
TEXT runtime·morestack_noctxt(SB),NOSPLIT,$0
|
| 687 |
+
MOVL $0, DX
|
| 688 |
+
JMP runtime·morestack(SB)
|
| 689 |
+
|
| 690 |
+
// spillArgs stores return values from registers to a *internal/abi.RegArgs in R12.
|
| 691 |
+
TEXT ·spillArgs(SB),NOSPLIT,$0-0
|
| 692 |
+
MOVQ AX, 0(R12)
|
| 693 |
+
MOVQ BX, 8(R12)
|
| 694 |
+
MOVQ CX, 16(R12)
|
| 695 |
+
MOVQ DI, 24(R12)
|
| 696 |
+
MOVQ SI, 32(R12)
|
| 697 |
+
MOVQ R8, 40(R12)
|
| 698 |
+
MOVQ R9, 48(R12)
|
| 699 |
+
MOVQ R10, 56(R12)
|
| 700 |
+
MOVQ R11, 64(R12)
|
| 701 |
+
MOVQ X0, 72(R12)
|
| 702 |
+
MOVQ X1, 80(R12)
|
| 703 |
+
MOVQ X2, 88(R12)
|
| 704 |
+
MOVQ X3, 96(R12)
|
| 705 |
+
MOVQ X4, 104(R12)
|
| 706 |
+
MOVQ X5, 112(R12)
|
| 707 |
+
MOVQ X6, 120(R12)
|
| 708 |
+
MOVQ X7, 128(R12)
|
| 709 |
+
MOVQ X8, 136(R12)
|
| 710 |
+
MOVQ X9, 144(R12)
|
| 711 |
+
MOVQ X10, 152(R12)
|
| 712 |
+
MOVQ X11, 160(R12)
|
| 713 |
+
MOVQ X12, 168(R12)
|
| 714 |
+
MOVQ X13, 176(R12)
|
| 715 |
+
MOVQ X14, 184(R12)
|
| 716 |
+
RET
|
| 717 |
+
|
| 718 |
+
// unspillArgs loads args into registers from a *internal/abi.RegArgs in R12.
|
| 719 |
+
TEXT ·unspillArgs(SB),NOSPLIT,$0-0
|
| 720 |
+
MOVQ 0(R12), AX
|
| 721 |
+
MOVQ 8(R12), BX
|
| 722 |
+
MOVQ 16(R12), CX
|
| 723 |
+
MOVQ 24(R12), DI
|
| 724 |
+
MOVQ 32(R12), SI
|
| 725 |
+
MOVQ 40(R12), R8
|
| 726 |
+
MOVQ 48(R12), R9
|
| 727 |
+
MOVQ 56(R12), R10
|
| 728 |
+
MOVQ 64(R12), R11
|
| 729 |
+
MOVQ 72(R12), X0
|
| 730 |
+
MOVQ 80(R12), X1
|
| 731 |
+
MOVQ 88(R12), X2
|
| 732 |
+
MOVQ 96(R12), X3
|
| 733 |
+
MOVQ 104(R12), X4
|
| 734 |
+
MOVQ 112(R12), X5
|
| 735 |
+
MOVQ 120(R12), X6
|
| 736 |
+
MOVQ 128(R12), X7
|
| 737 |
+
MOVQ 136(R12), X8
|
| 738 |
+
MOVQ 144(R12), X9
|
| 739 |
+
MOVQ 152(R12), X10
|
| 740 |
+
MOVQ 160(R12), X11
|
| 741 |
+
MOVQ 168(R12), X12
|
| 742 |
+
MOVQ 176(R12), X13
|
| 743 |
+
MOVQ 184(R12), X14
|
| 744 |
+
RET
|
| 745 |
+
|
| 746 |
+
// reflectcall: call a function with the given argument list
|
| 747 |
+
// func call(stackArgsType *_type, f *FuncVal, stackArgs *byte, stackArgsSize, stackRetOffset, frameSize uint32, regArgs *abi.RegArgs).
|
| 748 |
+
// we don't have variable-sized frames, so we use a small number
|
| 749 |
+
// of constant-sized-frame functions to encode a few bits of size in the pc.
|
| 750 |
+
// Caution: ugly multiline assembly macros in your future!
|
| 751 |
+
|
| 752 |
+
#define DISPATCH(NAME,MAXSIZE) \
|
| 753 |
+
CMPQ CX, $MAXSIZE; \
|
| 754 |
+
JA 3(PC); \
|
| 755 |
+
MOVQ $NAME(SB), AX; \
|
| 756 |
+
JMP AX
|
| 757 |
+
// Note: can't just "JMP NAME(SB)" - bad inlining results.
|
| 758 |
+
|
| 759 |
+
TEXT ·reflectcall(SB), NOSPLIT, $0-48
|
| 760 |
+
MOVLQZX frameSize+32(FP), CX
|
| 761 |
+
DISPATCH(runtime·call16, 16)
|
| 762 |
+
DISPATCH(runtime·call32, 32)
|
| 763 |
+
DISPATCH(runtime·call64, 64)
|
| 764 |
+
DISPATCH(runtime·call128, 128)
|
| 765 |
+
DISPATCH(runtime·call256, 256)
|
| 766 |
+
DISPATCH(runtime·call512, 512)
|
| 767 |
+
DISPATCH(runtime·call1024, 1024)
|
| 768 |
+
DISPATCH(runtime·call2048, 2048)
|
| 769 |
+
DISPATCH(runtime·call4096, 4096)
|
| 770 |
+
DISPATCH(runtime·call8192, 8192)
|
| 771 |
+
DISPATCH(runtime·call16384, 16384)
|
| 772 |
+
DISPATCH(runtime·call32768, 32768)
|
| 773 |
+
DISPATCH(runtime·call65536, 65536)
|
| 774 |
+
DISPATCH(runtime·call131072, 131072)
|
| 775 |
+
DISPATCH(runtime·call262144, 262144)
|
| 776 |
+
DISPATCH(runtime·call524288, 524288)
|
| 777 |
+
DISPATCH(runtime·call1048576, 1048576)
|
| 778 |
+
DISPATCH(runtime·call2097152, 2097152)
|
| 779 |
+
DISPATCH(runtime·call4194304, 4194304)
|
| 780 |
+
DISPATCH(runtime·call8388608, 8388608)
|
| 781 |
+
DISPATCH(runtime·call16777216, 16777216)
|
| 782 |
+
DISPATCH(runtime·call33554432, 33554432)
|
| 783 |
+
DISPATCH(runtime·call67108864, 67108864)
|
| 784 |
+
DISPATCH(runtime·call134217728, 134217728)
|
| 785 |
+
DISPATCH(runtime·call268435456, 268435456)
|
| 786 |
+
DISPATCH(runtime·call536870912, 536870912)
|
| 787 |
+
DISPATCH(runtime·call1073741824, 1073741824)
|
| 788 |
+
MOVQ $runtime·badreflectcall(SB), AX
|
| 789 |
+
JMP AX
|
| 790 |
+
|
| 791 |
+
#define CALLFN(NAME,MAXSIZE) \
|
| 792 |
+
TEXT NAME(SB), WRAPPER, $MAXSIZE-48; \
|
| 793 |
+
NO_LOCAL_POINTERS; \
|
| 794 |
+
/* copy arguments to stack */ \
|
| 795 |
+
MOVQ stackArgs+16(FP), SI; \
|
| 796 |
+
MOVLQZX stackArgsSize+24(FP), CX; \
|
| 797 |
+
MOVQ SP, DI; \
|
| 798 |
+
REP;MOVSB; \
|
| 799 |
+
/* set up argument registers */ \
|
| 800 |
+
MOVQ regArgs+40(FP), R12; \
|
| 801 |
+
CALL ·unspillArgs(SB); \
|
| 802 |
+
/* call function */ \
|
| 803 |
+
MOVQ f+8(FP), DX; \
|
| 804 |
+
PCDATA $PCDATA_StackMapIndex, $0; \
|
| 805 |
+
MOVQ (DX), R12; \
|
| 806 |
+
CALL R12; \
|
| 807 |
+
/* copy register return values back */ \
|
| 808 |
+
MOVQ regArgs+40(FP), R12; \
|
| 809 |
+
CALL ·spillArgs(SB); \
|
| 810 |
+
MOVLQZX stackArgsSize+24(FP), CX; \
|
| 811 |
+
MOVLQZX stackRetOffset+28(FP), BX; \
|
| 812 |
+
MOVQ stackArgs+16(FP), DI; \
|
| 813 |
+
MOVQ stackArgsType+0(FP), DX; \
|
| 814 |
+
MOVQ SP, SI; \
|
| 815 |
+
ADDQ BX, DI; \
|
| 816 |
+
ADDQ BX, SI; \
|
| 817 |
+
SUBQ BX, CX; \
|
| 818 |
+
CALL callRet<>(SB); \
|
| 819 |
+
RET
|
| 820 |
+
|
| 821 |
+
// callRet copies return values back at the end of call*. This is a
|
| 822 |
+
// separate function so it can allocate stack space for the arguments
|
| 823 |
+
// to reflectcallmove. It does not follow the Go ABI; it expects its
|
| 824 |
+
// arguments in registers.
|
| 825 |
+
TEXT callRet<>(SB), NOSPLIT, $40-0
|
| 826 |
+
NO_LOCAL_POINTERS
|
| 827 |
+
MOVQ DX, 0(SP)
|
| 828 |
+
MOVQ DI, 8(SP)
|
| 829 |
+
MOVQ SI, 16(SP)
|
| 830 |
+
MOVQ CX, 24(SP)
|
| 831 |
+
MOVQ R12, 32(SP)
|
| 832 |
+
CALL runtime·reflectcallmove(SB)
|
| 833 |
+
RET
|
| 834 |
+
|
| 835 |
+
CALLFN(·call16, 16)
|
| 836 |
+
CALLFN(·call32, 32)
|
| 837 |
+
CALLFN(·call64, 64)
|
| 838 |
+
CALLFN(·call128, 128)
|
| 839 |
+
CALLFN(·call256, 256)
|
| 840 |
+
CALLFN(·call512, 512)
|
| 841 |
+
CALLFN(·call1024, 1024)
|
| 842 |
+
CALLFN(·call2048, 2048)
|
| 843 |
+
CALLFN(·call4096, 4096)
|
| 844 |
+
CALLFN(·call8192, 8192)
|
| 845 |
+
CALLFN(·call16384, 16384)
|
| 846 |
+
CALLFN(·call32768, 32768)
|
| 847 |
+
CALLFN(·call65536, 65536)
|
| 848 |
+
CALLFN(·call131072, 131072)
|
| 849 |
+
CALLFN(·call262144, 262144)
|
| 850 |
+
CALLFN(·call524288, 524288)
|
| 851 |
+
CALLFN(·call1048576, 1048576)
|
| 852 |
+
CALLFN(·call2097152, 2097152)
|
| 853 |
+
CALLFN(·call4194304, 4194304)
|
| 854 |
+
CALLFN(·call8388608, 8388608)
|
| 855 |
+
CALLFN(·call16777216, 16777216)
|
| 856 |
+
CALLFN(·call33554432, 33554432)
|
| 857 |
+
CALLFN(·call67108864, 67108864)
|
| 858 |
+
CALLFN(·call134217728, 134217728)
|
| 859 |
+
CALLFN(·call268435456, 268435456)
|
| 860 |
+
CALLFN(·call536870912, 536870912)
|
| 861 |
+
CALLFN(·call1073741824, 1073741824)
|
| 862 |
+
|
| 863 |
+
TEXT runtime·procyieldAsm(SB),NOSPLIT,$0-0
|
| 864 |
+
MOVL cycles+0(FP), AX
|
| 865 |
+
TESTL AX, AX
|
| 866 |
+
JZ done
|
| 867 |
+
again:
|
| 868 |
+
PAUSE
|
| 869 |
+
SUBL $1, AX
|
| 870 |
+
JNZ again
|
| 871 |
+
done:
|
| 872 |
+
RET
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
TEXT ·publicationBarrier<ABIInternal>(SB),NOSPLIT,$0-0
|
| 876 |
+
// Stores are already ordered on x86, so this is just a
|
| 877 |
+
// compile barrier.
|
| 878 |
+
RET
|
| 879 |
+
|
| 880 |
+
// Save state of caller into g->sched,
|
| 881 |
+
// but using fake PC from systemstack_switch.
|
| 882 |
+
// Must only be called from functions with frame pointer
|
| 883 |
+
// and without locals ($0) or else unwinding from
|
| 884 |
+
// systemstack_switch is incorrect.
|
| 885 |
+
// Smashes R9.
|
| 886 |
+
TEXT gosave_systemstack_switch<>(SB),NOSPLIT|NOFRAME,$0
|
| 887 |
+
// Take systemstack_switch PC and add 8 bytes to skip
|
| 888 |
+
// the prologue. The final location does not matter
|
| 889 |
+
// as long as we are between the prologue and the epilogue.
|
| 890 |
+
MOVQ $runtime·systemstack_switch+8(SB), R9
|
| 891 |
+
MOVQ R9, (g_sched+gobuf_pc)(R14)
|
| 892 |
+
LEAQ 8(SP), R9
|
| 893 |
+
MOVQ R9, (g_sched+gobuf_sp)(R14)
|
| 894 |
+
MOVQ BP, (g_sched+gobuf_bp)(R14)
|
| 895 |
+
// Assert ctxt is zero. See func save.
|
| 896 |
+
MOVQ (g_sched+gobuf_ctxt)(R14), R9
|
| 897 |
+
TESTQ R9, R9
|
| 898 |
+
JZ 2(PC)
|
| 899 |
+
CALL runtime·abort(SB)
|
| 900 |
+
RET
|
| 901 |
+
|
| 902 |
+
// func asmcgocall_no_g(fn, arg unsafe.Pointer)
|
| 903 |
+
// Call fn(arg) aligned appropriately for the gcc ABI.
|
| 904 |
+
// Called on a system stack, and there may be no g yet (during needm).
|
| 905 |
+
TEXT ·asmcgocall_no_g(SB),NOSPLIT,$32-16
|
| 906 |
+
MOVQ fn+0(FP), AX
|
| 907 |
+
MOVQ arg+8(FP), BX
|
| 908 |
+
MOVQ SP, DX
|
| 909 |
+
ANDQ $~15, SP // alignment
|
| 910 |
+
MOVQ DX, 8(SP)
|
| 911 |
+
MOVQ BX, DI // DI = first argument in AMD64 ABI
|
| 912 |
+
MOVQ BX, CX // CX = first argument in Win64
|
| 913 |
+
CALL AX
|
| 914 |
+
MOVQ 8(SP), DX
|
| 915 |
+
MOVQ DX, SP
|
| 916 |
+
RET
|
| 917 |
+
|
| 918 |
+
// asmcgocall_landingpad calls AX with BX as argument.
|
| 919 |
+
// Must be called on the system stack.
|
| 920 |
+
TEXT ·asmcgocall_landingpad(SB),NOSPLIT,$0-0
|
| 921 |
+
#ifdef GOOS_windows
|
| 922 |
+
// Make sure we have enough room for 4 stack-backed fast-call
|
| 923 |
+
// registers as per Windows amd64 calling convention.
|
| 924 |
+
ADJSP $32
|
| 925 |
+
// On Windows, asmcgocall_landingpad acts as landing pad for exceptions
|
| 926 |
+
// thrown in the cgo call. Exceptions that reach this function will be
|
| 927 |
+
// handled by runtime.sehtramp thanks to the SEH metadata added
|
| 928 |
+
// by the compiler.
|
| 929 |
+
// Note that runtime.sehtramp can't be attached directly to asmcgocall
|
| 930 |
+
// because its initial stack pointer can be outside the system stack bounds,
|
| 931 |
+
// and Windows stops the stack unwinding without calling the exception handler
|
| 932 |
+
// when it reaches that point.
|
| 933 |
+
MOVQ BX, CX // CX = first argument in Win64
|
| 934 |
+
CALL AX
|
| 935 |
+
// The exception handler is not called if the next instruction is part of
|
| 936 |
+
// the epilogue, which includes the RET instruction, so we need to add a NOP here.
|
| 937 |
+
BYTE $0x90
|
| 938 |
+
ADJSP $-32
|
| 939 |
+
RET
|
| 940 |
+
#endif
|
| 941 |
+
// Tail call AX on non-Windows, as the extra stack frame is not needed.
|
| 942 |
+
MOVQ BX, DI // DI = first argument in AMD64 ABI
|
| 943 |
+
JMP AX
|
| 944 |
+
|
| 945 |
+
// func asmcgocall(fn, arg unsafe.Pointer) int32
|
| 946 |
+
// Call fn(arg) on the scheduler stack,
|
| 947 |
+
// aligned appropriately for the gcc ABI.
|
| 948 |
+
// See cgocall.go for more details.
|
| 949 |
+
TEXT ·asmcgocall(SB),NOSPLIT,$0-20
|
| 950 |
+
// Figure out if we need to switch to m->g0 stack.
|
| 951 |
+
// We get called to create new OS threads too, and those
|
| 952 |
+
// come in on the m->g0 stack already. Or we might already
|
| 953 |
+
// be on the m->gsignal stack.
|
| 954 |
+
get_tls(CX)
|
| 955 |
+
MOVQ g(CX), DI
|
| 956 |
+
CMPQ DI, $0
|
| 957 |
+
JEQ nosave
|
| 958 |
+
MOVQ g_m(DI), R8
|
| 959 |
+
MOVQ m_gsignal(R8), SI
|
| 960 |
+
CMPQ DI, SI
|
| 961 |
+
JEQ nosave
|
| 962 |
+
MOVQ m_g0(R8), SI
|
| 963 |
+
CMPQ DI, SI
|
| 964 |
+
JEQ nosave
|
| 965 |
+
|
| 966 |
+
// Running on a user G
|
| 967 |
+
// Figure out if we're running secret code and clear the registers
|
| 968 |
+
// so that the C code we're about to call doesn't spill confidential
|
| 969 |
+
// information into memory
|
| 970 |
+
#ifdef GOEXPERIMENT_runtimesecret
|
| 971 |
+
CMPL g_secret(DI), $0
|
| 972 |
+
JEQ nosecret
|
| 973 |
+
CALL ·secretEraseRegisters(SB)
|
| 974 |
+
|
| 975 |
+
nosecret:
|
| 976 |
+
#endif
|
| 977 |
+
MOVQ fn+0(FP), AX
|
| 978 |
+
MOVQ arg+8(FP), BX
|
| 979 |
+
MOVQ SP, DX
|
| 980 |
+
|
| 981 |
+
// Switch to system stack.
|
| 982 |
+
// The original frame pointer is stored in BP,
|
| 983 |
+
// which is useful for stack unwinding.
|
| 984 |
+
CALL gosave_systemstack_switch<>(SB)
|
| 985 |
+
MOVQ SI, g(CX)
|
| 986 |
+
MOVQ (g_sched+gobuf_sp)(SI), SP
|
| 987 |
+
|
| 988 |
+
// Now on a scheduling stack (a pthread-created stack).
|
| 989 |
+
SUBQ $16, SP
|
| 990 |
+
ANDQ $~15, SP // alignment for gcc ABI
|
| 991 |
+
MOVQ DI, 8(SP) // save g
|
| 992 |
+
MOVQ (g_stack+stack_hi)(DI), DI
|
| 993 |
+
SUBQ DX, DI
|
| 994 |
+
MOVQ DI, 0(SP) // save depth in stack (can't just save SP, as stack might be copied during a callback)
|
| 995 |
+
CALL runtime·asmcgocall_landingpad(SB)
|
| 996 |
+
|
| 997 |
+
// Restore registers, g, stack pointer.
|
| 998 |
+
get_tls(CX)
|
| 999 |
+
MOVQ 8(SP), DI
|
| 1000 |
+
MOVQ (g_stack+stack_hi)(DI), SI
|
| 1001 |
+
SUBQ 0(SP), SI
|
| 1002 |
+
MOVQ DI, g(CX)
|
| 1003 |
+
MOVQ SI, SP
|
| 1004 |
+
|
| 1005 |
+
MOVL AX, ret+16(FP)
|
| 1006 |
+
RET
|
| 1007 |
+
|
| 1008 |
+
nosave:
|
| 1009 |
+
// Running on a system stack, perhaps even without a g.
|
| 1010 |
+
// Having no g can happen during thread creation or thread teardown
|
| 1011 |
+
// (see needm/dropm on Solaris, for example).
|
| 1012 |
+
// This code is like the above sequence but without saving/restoring g
|
| 1013 |
+
// and without worrying about the stack moving out from under us
|
| 1014 |
+
// (because we're on a system stack, not a goroutine stack).
|
| 1015 |
+
// The above code could be used directly if already on a system stack,
|
| 1016 |
+
// but then the only path through this code would be a rare case on Solaris.
|
| 1017 |
+
// Using this code for all "already on system stack" calls exercises it more,
|
| 1018 |
+
// which should help keep it correct.
|
| 1019 |
+
MOVQ fn+0(FP), AX
|
| 1020 |
+
MOVQ arg+8(FP), BX
|
| 1021 |
+
MOVQ SP, DX
|
| 1022 |
+
|
| 1023 |
+
SUBQ $16, SP
|
| 1024 |
+
ANDQ $~15, SP
|
| 1025 |
+
MOVQ $0, 8(SP) // where above code stores g, in case someone looks during debugging
|
| 1026 |
+
MOVQ DX, 0(SP) // save original stack pointer
|
| 1027 |
+
CALL runtime·asmcgocall_landingpad(SB)
|
| 1028 |
+
MOVQ 0(SP), SI // restore original stack pointer
|
| 1029 |
+
MOVQ SI, SP
|
| 1030 |
+
MOVL AX, ret+16(FP)
|
| 1031 |
+
RET
|
| 1032 |
+
|
| 1033 |
+
#ifdef GOOS_windows
|
| 1034 |
+
// Dummy TLS that's used on Windows so that we don't crash trying
|
| 1035 |
+
// to restore the G register in needm. needm and its callees are
|
| 1036 |
+
// very careful never to actually use the G, the TLS just can't be
|
| 1037 |
+
// unset since we're in Go code.
|
| 1038 |
+
GLOBL zeroTLS<>(SB),RODATA,$const_tlsSize
|
| 1039 |
+
#endif
|
| 1040 |
+
|
| 1041 |
+
// func cgocallback(fn, frame unsafe.Pointer, ctxt uintptr)
|
| 1042 |
+
// See cgocall.go for more details.
|
| 1043 |
+
TEXT ·cgocallback(SB),NOSPLIT,$24-24
|
| 1044 |
+
NO_LOCAL_POINTERS
|
| 1045 |
+
|
| 1046 |
+
// Skip cgocallbackg, just dropm when fn is nil, and frame is the saved g.
|
| 1047 |
+
// It is used to dropm while thread is exiting.
|
| 1048 |
+
MOVQ fn+0(FP), AX
|
| 1049 |
+
CMPQ AX, $0
|
| 1050 |
+
JNE loadg
|
| 1051 |
+
// Restore the g from frame.
|
| 1052 |
+
get_tls(CX)
|
| 1053 |
+
MOVQ frame+8(FP), BX
|
| 1054 |
+
MOVQ BX, g(CX)
|
| 1055 |
+
JMP dropm
|
| 1056 |
+
|
| 1057 |
+
loadg:
|
| 1058 |
+
// If g is nil, Go did not create the current thread,
|
| 1059 |
+
// or if this thread never called into Go on pthread platforms.
|
| 1060 |
+
// Call needm to obtain one m for temporary use.
|
| 1061 |
+
// In this case, we're running on the thread stack, so there's
|
| 1062 |
+
// lots of space, but the linker doesn't know. Hide the call from
|
| 1063 |
+
// the linker analysis by using an indirect call through AX.
|
| 1064 |
+
get_tls(CX)
|
| 1065 |
+
#ifdef GOOS_windows
|
| 1066 |
+
MOVL $0, BX
|
| 1067 |
+
CMPQ CX, $0
|
| 1068 |
+
JEQ 2(PC)
|
| 1069 |
+
#endif
|
| 1070 |
+
MOVQ g(CX), BX
|
| 1071 |
+
CMPQ BX, $0
|
| 1072 |
+
JEQ needm
|
| 1073 |
+
MOVQ g_m(BX), BX
|
| 1074 |
+
MOVQ BX, savedm-8(SP) // saved copy of oldm
|
| 1075 |
+
JMP havem
|
| 1076 |
+
needm:
|
| 1077 |
+
#ifdef GOOS_windows
|
| 1078 |
+
// Set up a dummy TLS value. needm is careful not to use it,
|
| 1079 |
+
// but it needs to be there to prevent autogenerated code from
|
| 1080 |
+
// crashing when it loads from it.
|
| 1081 |
+
// We don't need to clear it or anything later because needm
|
| 1082 |
+
// will set up TLS properly.
|
| 1083 |
+
MOVQ $zeroTLS<>(SB), DI
|
| 1084 |
+
CALL runtime·settls(SB)
|
| 1085 |
+
#endif
|
| 1086 |
+
// On some platforms (Windows) we cannot call needm through
|
| 1087 |
+
// an ABI wrapper because there's no TLS set up, and the ABI
|
| 1088 |
+
// wrapper will try to restore the G register (R14) from TLS.
|
| 1089 |
+
// Clear X15 because Go expects it and we're not calling
|
| 1090 |
+
// through a wrapper, but otherwise avoid setting the G
|
| 1091 |
+
// register in the wrapper and call needm directly. It
|
| 1092 |
+
// takes no arguments and doesn't return any values so
|
| 1093 |
+
// there's no need to handle that. Clear R14 so that there's
|
| 1094 |
+
// a bad value in there, in case needm tries to use it.
|
| 1095 |
+
XORPS X15, X15
|
| 1096 |
+
XORQ R14, R14
|
| 1097 |
+
MOVQ $runtime·needAndBindM<ABIInternal>(SB), AX
|
| 1098 |
+
CALL AX
|
| 1099 |
+
MOVQ $0, savedm-8(SP)
|
| 1100 |
+
get_tls(CX)
|
| 1101 |
+
MOVQ g(CX), BX
|
| 1102 |
+
MOVQ g_m(BX), BX
|
| 1103 |
+
|
| 1104 |
+
// Set m->sched.sp = SP, so that if a panic happens
|
| 1105 |
+
// during the function we are about to execute, it will
|
| 1106 |
+
// have a valid SP to run on the g0 stack.
|
| 1107 |
+
// The next few lines (after the havem label)
|
| 1108 |
+
// will save this SP onto the stack and then write
|
| 1109 |
+
// the same SP back to m->sched.sp. That seems redundant,
|
| 1110 |
+
// but if an unrecovered panic happens, unwindm will
|
| 1111 |
+
// restore the g->sched.sp from the stack location
|
| 1112 |
+
// and then systemstack will try to use it. If we don't set it here,
|
| 1113 |
+
// that restored SP will be uninitialized (typically 0) and
|
| 1114 |
+
// will not be usable.
|
| 1115 |
+
MOVQ m_g0(BX), SI
|
| 1116 |
+
MOVQ SP, (g_sched+gobuf_sp)(SI)
|
| 1117 |
+
|
| 1118 |
+
havem:
|
| 1119 |
+
// Now there's a valid m, and we're running on its m->g0.
|
| 1120 |
+
// Save current m->g0->sched.sp on stack and then set it to SP.
|
| 1121 |
+
// Save current sp in m->g0->sched.sp in preparation for
|
| 1122 |
+
// switch back to m->curg stack.
|
| 1123 |
+
// NOTE: unwindm knows that the saved g->sched.sp is at 0(SP).
|
| 1124 |
+
MOVQ m_g0(BX), SI
|
| 1125 |
+
MOVQ (g_sched+gobuf_sp)(SI), AX
|
| 1126 |
+
MOVQ AX, 0(SP)
|
| 1127 |
+
MOVQ SP, (g_sched+gobuf_sp)(SI)
|
| 1128 |
+
|
| 1129 |
+
// Switch to m->curg stack and call runtime.cgocallbackg.
|
| 1130 |
+
// Because we are taking over the execution of m->curg
|
| 1131 |
+
// but *not* resuming what had been running, we need to
|
| 1132 |
+
// save that information (m->curg->sched) so we can restore it.
|
| 1133 |
+
// We can restore m->curg->sched.sp easily, because calling
|
| 1134 |
+
// runtime.cgocallbackg leaves SP unchanged upon return.
|
| 1135 |
+
// To save m->curg->sched.pc, we push it onto the curg stack and
|
| 1136 |
+
// open a frame the same size as cgocallback's g0 frame.
|
| 1137 |
+
// Once we switch to the curg stack, the pushed PC will appear
|
| 1138 |
+
// to be the return PC of cgocallback, so that the traceback
|
| 1139 |
+
// will seamlessly trace back into the earlier calls.
|
| 1140 |
+
MOVQ m_curg(BX), SI
|
| 1141 |
+
MOVQ SI, g(CX)
|
| 1142 |
+
MOVQ (g_sched+gobuf_sp)(SI), DI // prepare stack as DI
|
| 1143 |
+
MOVQ (g_sched+gobuf_pc)(SI), BX
|
| 1144 |
+
MOVQ BX, -8(DI) // "push" return PC on the g stack
|
| 1145 |
+
// Gather our arguments into registers.
|
| 1146 |
+
MOVQ fn+0(FP), BX
|
| 1147 |
+
MOVQ frame+8(FP), CX
|
| 1148 |
+
MOVQ ctxt+16(FP), DX
|
| 1149 |
+
// Compute the size of the frame, including return PC and, if
|
| 1150 |
+
// GOEXPERIMENT=framepointer, the saved base pointer
|
| 1151 |
+
LEAQ fn+0(FP), AX
|
| 1152 |
+
SUBQ SP, AX // AX is our actual frame size
|
| 1153 |
+
SUBQ AX, DI // Allocate the same frame size on the g stack
|
| 1154 |
+
MOVQ DI, SP
|
| 1155 |
+
|
| 1156 |
+
MOVQ BX, 0(SP)
|
| 1157 |
+
MOVQ CX, 8(SP)
|
| 1158 |
+
MOVQ DX, 16(SP)
|
| 1159 |
+
MOVQ $runtime·cgocallbackg(SB), AX
|
| 1160 |
+
CALL AX // indirect call to bypass nosplit check. We're on a different stack now.
|
| 1161 |
+
|
| 1162 |
+
// Compute the size of the frame again. FP and SP have
|
| 1163 |
+
// completely different values here than they did above,
|
| 1164 |
+
// but only their difference matters.
|
| 1165 |
+
LEAQ fn+0(FP), AX
|
| 1166 |
+
SUBQ SP, AX
|
| 1167 |
+
|
| 1168 |
+
// Restore g->sched (== m->curg->sched) from saved values.
|
| 1169 |
+
get_tls(CX)
|
| 1170 |
+
MOVQ g(CX), SI
|
| 1171 |
+
MOVQ SP, DI
|
| 1172 |
+
ADDQ AX, DI
|
| 1173 |
+
MOVQ -8(DI), BX
|
| 1174 |
+
MOVQ BX, (g_sched+gobuf_pc)(SI)
|
| 1175 |
+
MOVQ DI, (g_sched+gobuf_sp)(SI)
|
| 1176 |
+
|
| 1177 |
+
// Switch back to m->g0's stack and restore m->g0->sched.sp.
|
| 1178 |
+
// (Unlike m->curg, the g0 goroutine never uses sched.pc,
|
| 1179 |
+
// so we do not have to restore it.)
|
| 1180 |
+
MOVQ g(CX), BX
|
| 1181 |
+
MOVQ g_m(BX), BX
|
| 1182 |
+
MOVQ m_g0(BX), SI
|
| 1183 |
+
MOVQ SI, g(CX)
|
| 1184 |
+
MOVQ (g_sched+gobuf_sp)(SI), SP
|
| 1185 |
+
MOVQ 0(SP), AX
|
| 1186 |
+
MOVQ AX, (g_sched+gobuf_sp)(SI)
|
| 1187 |
+
|
| 1188 |
+
// If the m on entry was nil, we called needm above to borrow an m,
|
| 1189 |
+
// 1. for the duration of the call on non-pthread platforms,
|
| 1190 |
+
// 2. or the duration of the C thread alive on pthread platforms.
|
| 1191 |
+
// If the m on entry wasn't nil,
|
| 1192 |
+
// 1. the thread might be a Go thread,
|
| 1193 |
+
// 2. or it wasn't the first call from a C thread on pthread platforms,
|
| 1194 |
+
// since then we skip dropm to reuse the m in the first call.
|
| 1195 |
+
MOVQ savedm-8(SP), BX
|
| 1196 |
+
CMPQ BX, $0
|
| 1197 |
+
JNE done
|
| 1198 |
+
|
| 1199 |
+
// Skip dropm to reuse it in the next call, when a pthread key has been created.
|
| 1200 |
+
MOVQ _cgo_pthread_key_created(SB), AX
|
| 1201 |
+
// It means cgo is disabled when _cgo_pthread_key_created is a nil pointer, need dropm.
|
| 1202 |
+
CMPQ AX, $0
|
| 1203 |
+
JEQ dropm
|
| 1204 |
+
CMPQ (AX), $0
|
| 1205 |
+
JNE done
|
| 1206 |
+
|
| 1207 |
+
dropm:
|
| 1208 |
+
MOVQ $runtime·dropm(SB), AX
|
| 1209 |
+
CALL AX
|
| 1210 |
+
#ifdef GOOS_windows
|
| 1211 |
+
// We need to clear the TLS pointer in case the next
|
| 1212 |
+
// thread that comes into Go tries to reuse that space
|
| 1213 |
+
// but uses the same M.
|
| 1214 |
+
XORQ DI, DI
|
| 1215 |
+
CALL runtime·settls(SB)
|
| 1216 |
+
#endif
|
| 1217 |
+
done:
|
| 1218 |
+
|
| 1219 |
+
// Done!
|
| 1220 |
+
RET
|
| 1221 |
+
|
| 1222 |
+
// func setg(gg *g)
|
| 1223 |
+
// set g. for use by needm.
|
| 1224 |
+
TEXT runtime·setg(SB), NOSPLIT, $0-8
|
| 1225 |
+
MOVQ gg+0(FP), BX
|
| 1226 |
+
get_tls(CX)
|
| 1227 |
+
MOVQ BX, g(CX)
|
| 1228 |
+
RET
|
| 1229 |
+
|
| 1230 |
+
// void setg_gcc(G*); set g called from gcc.
|
| 1231 |
+
TEXT setg_gcc<>(SB),NOSPLIT,$0
|
| 1232 |
+
get_tls(AX)
|
| 1233 |
+
MOVQ DI, g(AX)
|
| 1234 |
+
MOVQ DI, R14 // set the g register
|
| 1235 |
+
RET
|
| 1236 |
+
|
| 1237 |
+
TEXT runtime·abort(SB),NOSPLIT,$0-0
|
| 1238 |
+
INT $3
|
| 1239 |
+
loop:
|
| 1240 |
+
JMP loop
|
| 1241 |
+
|
| 1242 |
+
// check that SP is in range [g->stack.lo, g->stack.hi)
|
| 1243 |
+
TEXT runtime·stackcheck(SB), NOSPLIT|NOFRAME, $0-0
|
| 1244 |
+
get_tls(CX)
|
| 1245 |
+
MOVQ g(CX), AX
|
| 1246 |
+
CMPQ (g_stack+stack_hi)(AX), SP
|
| 1247 |
+
JHI 2(PC)
|
| 1248 |
+
CALL runtime·abort(SB)
|
| 1249 |
+
CMPQ SP, (g_stack+stack_lo)(AX)
|
| 1250 |
+
JHI 2(PC)
|
| 1251 |
+
CALL runtime·abort(SB)
|
| 1252 |
+
RET
|
| 1253 |
+
|
| 1254 |
+
// func cputicks() int64
|
| 1255 |
+
TEXT runtime·cputicks(SB),NOSPLIT,$0-0
|
| 1256 |
+
CMPB internal∕cpu·X86+const_offsetX86HasRDTSCP(SB), $1
|
| 1257 |
+
JNE fences
|
| 1258 |
+
// Instruction stream serializing RDTSCP is supported.
|
| 1259 |
+
// RDTSCP is supported by Intel Nehalem (2008) and
|
| 1260 |
+
// AMD K8 Rev. F (2006) and newer.
|
| 1261 |
+
RDTSCP
|
| 1262 |
+
done:
|
| 1263 |
+
SHLQ $32, DX
|
| 1264 |
+
ADDQ DX, AX
|
| 1265 |
+
MOVQ AX, ret+0(FP)
|
| 1266 |
+
RET
|
| 1267 |
+
fences:
|
| 1268 |
+
// MFENCE is instruction stream serializing and flushes the
|
| 1269 |
+
// store buffers on AMD. The serialization semantics of LFENCE on AMD
|
| 1270 |
+
// are dependent on MSR C001_1029 and CPU generation.
|
| 1271 |
+
// LFENCE on Intel does wait for all previous instructions to have executed.
|
| 1272 |
+
// Intel recommends MFENCE;LFENCE in its manuals before RDTSC to have all
|
| 1273 |
+
// previous instructions executed and all previous loads and stores to globally visible.
|
| 1274 |
+
// Using MFENCE;LFENCE here aligns the serializing properties without
|
| 1275 |
+
// runtime detection of CPU manufacturer.
|
| 1276 |
+
MFENCE
|
| 1277 |
+
LFENCE
|
| 1278 |
+
RDTSC
|
| 1279 |
+
JMP done
|
| 1280 |
+
|
| 1281 |
+
// func memhash(p unsafe.Pointer, h, s uintptr) uintptr
|
| 1282 |
+
// hash function using AES hardware instructions
|
| 1283 |
+
TEXT runtime·memhash<ABIInternal>(SB),NOSPLIT,$0-32
|
| 1284 |
+
// AX = ptr to data
|
| 1285 |
+
// BX = seed
|
| 1286 |
+
// CX = size
|
| 1287 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1288 |
+
JEQ noaes
|
| 1289 |
+
JMP aeshashbody<>(SB)
|
| 1290 |
+
noaes:
|
| 1291 |
+
JMP runtime·memhashFallback<ABIInternal>(SB)
|
| 1292 |
+
|
| 1293 |
+
// func strhash(p unsafe.Pointer, h uintptr) uintptr
|
| 1294 |
+
TEXT runtime·strhash<ABIInternal>(SB),NOSPLIT,$0-24
|
| 1295 |
+
// AX = ptr to string struct
|
| 1296 |
+
// BX = seed
|
| 1297 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1298 |
+
JEQ noaes
|
| 1299 |
+
MOVQ 8(AX), CX // length of string
|
| 1300 |
+
MOVQ (AX), AX // string data
|
| 1301 |
+
JMP aeshashbody<>(SB)
|
| 1302 |
+
noaes:
|
| 1303 |
+
JMP runtime·strhashFallback<ABIInternal>(SB)
|
| 1304 |
+
|
| 1305 |
+
// AX: data
|
| 1306 |
+
// BX: hash seed
|
| 1307 |
+
// CX: length
|
| 1308 |
+
// At return: AX = return value
|
| 1309 |
+
TEXT aeshashbody<>(SB),NOSPLIT,$0-0
|
| 1310 |
+
// Fill an SSE register with our seeds.
|
| 1311 |
+
MOVQ BX, X0 // 64 bits of per-table hash seed
|
| 1312 |
+
PINSRW $4, CX, X0 // 16 bits of length
|
| 1313 |
+
PSHUFHW $0, X0, X0 // repeat length 4 times total
|
| 1314 |
+
MOVO X0, X1 // save unscrambled seed
|
| 1315 |
+
PXOR runtime·aeskeysched(SB), X0 // xor in per-process seed
|
| 1316 |
+
AESENC X0, X0 // scramble seed
|
| 1317 |
+
|
| 1318 |
+
CMPQ CX, $16
|
| 1319 |
+
JB aes0to15
|
| 1320 |
+
JE aes16
|
| 1321 |
+
CMPQ CX, $32
|
| 1322 |
+
JBE aes17to32
|
| 1323 |
+
CMPQ CX, $64
|
| 1324 |
+
JBE aes33to64
|
| 1325 |
+
CMPQ CX, $128
|
| 1326 |
+
JBE aes65to128
|
| 1327 |
+
JMP aes129plus
|
| 1328 |
+
|
| 1329 |
+
aes0to15:
|
| 1330 |
+
TESTQ CX, CX
|
| 1331 |
+
JE aes0
|
| 1332 |
+
|
| 1333 |
+
ADDQ $16, AX
|
| 1334 |
+
TESTW $0xff0, AX
|
| 1335 |
+
JE endofpage
|
| 1336 |
+
|
| 1337 |
+
// 16 bytes loaded at this address won't cross
|
| 1338 |
+
// a page boundary, so we can load it directly.
|
| 1339 |
+
MOVOU -16(AX), X1
|
| 1340 |
+
ADDQ CX, CX
|
| 1341 |
+
MOVQ $masks<>(SB), AX
|
| 1342 |
+
PAND (AX)(CX*8), X1
|
| 1343 |
+
final1:
|
| 1344 |
+
PXOR X0, X1 // xor data with seed
|
| 1345 |
+
AESENC X1, X1 // scramble combo 3 times
|
| 1346 |
+
AESENC X1, X1
|
| 1347 |
+
AESENC X1, X1
|
| 1348 |
+
MOVQ X1, AX // return X1
|
| 1349 |
+
RET
|
| 1350 |
+
|
| 1351 |
+
endofpage:
|
| 1352 |
+
// address ends in 1111xxxx. Might be up against
|
| 1353 |
+
// a page boundary, so load ending at last byte.
|
| 1354 |
+
// Then shift bytes down using pshufb.
|
| 1355 |
+
MOVOU -32(AX)(CX*1), X1
|
| 1356 |
+
ADDQ CX, CX
|
| 1357 |
+
MOVQ $shifts<>(SB), AX
|
| 1358 |
+
PSHUFB (AX)(CX*8), X1
|
| 1359 |
+
JMP final1
|
| 1360 |
+
|
| 1361 |
+
aes0:
|
| 1362 |
+
// Return scrambled input seed
|
| 1363 |
+
AESENC X0, X0
|
| 1364 |
+
MOVQ X0, AX // return X0
|
| 1365 |
+
RET
|
| 1366 |
+
|
| 1367 |
+
aes16:
|
| 1368 |
+
MOVOU (AX), X1
|
| 1369 |
+
JMP final1
|
| 1370 |
+
|
| 1371 |
+
aes17to32:
|
| 1372 |
+
// make second starting seed
|
| 1373 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1374 |
+
AESENC X1, X1
|
| 1375 |
+
|
| 1376 |
+
// load data to be hashed
|
| 1377 |
+
MOVOU (AX), X2
|
| 1378 |
+
MOVOU -16(AX)(CX*1), X3
|
| 1379 |
+
|
| 1380 |
+
// xor with seed
|
| 1381 |
+
PXOR X0, X2
|
| 1382 |
+
PXOR X1, X3
|
| 1383 |
+
|
| 1384 |
+
// scramble 3 times
|
| 1385 |
+
AESENC X2, X2
|
| 1386 |
+
AESENC X3, X3
|
| 1387 |
+
AESENC X2, X2
|
| 1388 |
+
AESENC X3, X3
|
| 1389 |
+
AESENC X2, X2
|
| 1390 |
+
AESENC X3, X3
|
| 1391 |
+
|
| 1392 |
+
// combine results
|
| 1393 |
+
PXOR X3, X2
|
| 1394 |
+
MOVQ X2, AX // return X2
|
| 1395 |
+
RET
|
| 1396 |
+
|
| 1397 |
+
aes33to64:
|
| 1398 |
+
// make 3 more starting seeds
|
| 1399 |
+
MOVO X1, X2
|
| 1400 |
+
MOVO X1, X3
|
| 1401 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1402 |
+
PXOR runtime·aeskeysched+32(SB), X2
|
| 1403 |
+
PXOR runtime·aeskeysched+48(SB), X3
|
| 1404 |
+
AESENC X1, X1
|
| 1405 |
+
AESENC X2, X2
|
| 1406 |
+
AESENC X3, X3
|
| 1407 |
+
|
| 1408 |
+
MOVOU (AX), X4
|
| 1409 |
+
MOVOU 16(AX), X5
|
| 1410 |
+
MOVOU -32(AX)(CX*1), X6
|
| 1411 |
+
MOVOU -16(AX)(CX*1), X7
|
| 1412 |
+
|
| 1413 |
+
PXOR X0, X4
|
| 1414 |
+
PXOR X1, X5
|
| 1415 |
+
PXOR X2, X6
|
| 1416 |
+
PXOR X3, X7
|
| 1417 |
+
|
| 1418 |
+
AESENC X4, X4
|
| 1419 |
+
AESENC X5, X5
|
| 1420 |
+
AESENC X6, X6
|
| 1421 |
+
AESENC X7, X7
|
| 1422 |
+
|
| 1423 |
+
AESENC X4, X4
|
| 1424 |
+
AESENC X5, X5
|
| 1425 |
+
AESENC X6, X6
|
| 1426 |
+
AESENC X7, X7
|
| 1427 |
+
|
| 1428 |
+
AESENC X4, X4
|
| 1429 |
+
AESENC X5, X5
|
| 1430 |
+
AESENC X6, X6
|
| 1431 |
+
AESENC X7, X7
|
| 1432 |
+
|
| 1433 |
+
PXOR X6, X4
|
| 1434 |
+
PXOR X7, X5
|
| 1435 |
+
PXOR X5, X4
|
| 1436 |
+
MOVQ X4, AX // return X4
|
| 1437 |
+
RET
|
| 1438 |
+
|
| 1439 |
+
aes65to128:
|
| 1440 |
+
// make 7 more starting seeds
|
| 1441 |
+
MOVO X1, X2
|
| 1442 |
+
MOVO X1, X3
|
| 1443 |
+
MOVO X1, X4
|
| 1444 |
+
MOVO X1, X5
|
| 1445 |
+
MOVO X1, X6
|
| 1446 |
+
MOVO X1, X7
|
| 1447 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1448 |
+
PXOR runtime·aeskeysched+32(SB), X2
|
| 1449 |
+
PXOR runtime·aeskeysched+48(SB), X3
|
| 1450 |
+
PXOR runtime·aeskeysched+64(SB), X4
|
| 1451 |
+
PXOR runtime·aeskeysched+80(SB), X5
|
| 1452 |
+
PXOR runtime·aeskeysched+96(SB), X6
|
| 1453 |
+
PXOR runtime·aeskeysched+112(SB), X7
|
| 1454 |
+
AESENC X1, X1
|
| 1455 |
+
AESENC X2, X2
|
| 1456 |
+
AESENC X3, X3
|
| 1457 |
+
AESENC X4, X4
|
| 1458 |
+
AESENC X5, X5
|
| 1459 |
+
AESENC X6, X6
|
| 1460 |
+
AESENC X7, X7
|
| 1461 |
+
|
| 1462 |
+
// load data
|
| 1463 |
+
MOVOU (AX), X8
|
| 1464 |
+
MOVOU 16(AX), X9
|
| 1465 |
+
MOVOU 32(AX), X10
|
| 1466 |
+
MOVOU 48(AX), X11
|
| 1467 |
+
MOVOU -64(AX)(CX*1), X12
|
| 1468 |
+
MOVOU -48(AX)(CX*1), X13
|
| 1469 |
+
MOVOU -32(AX)(CX*1), X14
|
| 1470 |
+
MOVOU -16(AX)(CX*1), X15
|
| 1471 |
+
|
| 1472 |
+
// xor with seed
|
| 1473 |
+
PXOR X0, X8
|
| 1474 |
+
PXOR X1, X9
|
| 1475 |
+
PXOR X2, X10
|
| 1476 |
+
PXOR X3, X11
|
| 1477 |
+
PXOR X4, X12
|
| 1478 |
+
PXOR X5, X13
|
| 1479 |
+
PXOR X6, X14
|
| 1480 |
+
PXOR X7, X15
|
| 1481 |
+
|
| 1482 |
+
// scramble 3 times
|
| 1483 |
+
AESENC X8, X8
|
| 1484 |
+
AESENC X9, X9
|
| 1485 |
+
AESENC X10, X10
|
| 1486 |
+
AESENC X11, X11
|
| 1487 |
+
AESENC X12, X12
|
| 1488 |
+
AESENC X13, X13
|
| 1489 |
+
AESENC X14, X14
|
| 1490 |
+
AESENC X15, X15
|
| 1491 |
+
|
| 1492 |
+
AESENC X8, X8
|
| 1493 |
+
AESENC X9, X9
|
| 1494 |
+
AESENC X10, X10
|
| 1495 |
+
AESENC X11, X11
|
| 1496 |
+
AESENC X12, X12
|
| 1497 |
+
AESENC X13, X13
|
| 1498 |
+
AESENC X14, X14
|
| 1499 |
+
AESENC X15, X15
|
| 1500 |
+
|
| 1501 |
+
AESENC X8, X8
|
| 1502 |
+
AESENC X9, X9
|
| 1503 |
+
AESENC X10, X10
|
| 1504 |
+
AESENC X11, X11
|
| 1505 |
+
AESENC X12, X12
|
| 1506 |
+
AESENC X13, X13
|
| 1507 |
+
AESENC X14, X14
|
| 1508 |
+
AESENC X15, X15
|
| 1509 |
+
|
| 1510 |
+
// combine results
|
| 1511 |
+
PXOR X12, X8
|
| 1512 |
+
PXOR X13, X9
|
| 1513 |
+
PXOR X14, X10
|
| 1514 |
+
PXOR X15, X11
|
| 1515 |
+
PXOR X10, X8
|
| 1516 |
+
PXOR X11, X9
|
| 1517 |
+
PXOR X9, X8
|
| 1518 |
+
// X15 must be zero on return
|
| 1519 |
+
PXOR X15, X15
|
| 1520 |
+
MOVQ X8, AX // return X8
|
| 1521 |
+
RET
|
| 1522 |
+
|
| 1523 |
+
aes129plus:
|
| 1524 |
+
// make 7 more starting seeds
|
| 1525 |
+
MOVO X1, X2
|
| 1526 |
+
MOVO X1, X3
|
| 1527 |
+
MOVO X1, X4
|
| 1528 |
+
MOVO X1, X5
|
| 1529 |
+
MOVO X1, X6
|
| 1530 |
+
MOVO X1, X7
|
| 1531 |
+
PXOR runtime·aeskeysched+16(SB), X1
|
| 1532 |
+
PXOR runtime·aeskeysched+32(SB), X2
|
| 1533 |
+
PXOR runtime·aeskeysched+48(SB), X3
|
| 1534 |
+
PXOR runtime·aeskeysched+64(SB), X4
|
| 1535 |
+
PXOR runtime·aeskeysched+80(SB), X5
|
| 1536 |
+
PXOR runtime·aeskeysched+96(SB), X6
|
| 1537 |
+
PXOR runtime·aeskeysched+112(SB), X7
|
| 1538 |
+
AESENC X1, X1
|
| 1539 |
+
AESENC X2, X2
|
| 1540 |
+
AESENC X3, X3
|
| 1541 |
+
AESENC X4, X4
|
| 1542 |
+
AESENC X5, X5
|
| 1543 |
+
AESENC X6, X6
|
| 1544 |
+
AESENC X7, X7
|
| 1545 |
+
|
| 1546 |
+
// start with last (possibly overlapping) block
|
| 1547 |
+
MOVOU -128(AX)(CX*1), X8
|
| 1548 |
+
MOVOU -112(AX)(CX*1), X9
|
| 1549 |
+
MOVOU -96(AX)(CX*1), X10
|
| 1550 |
+
MOVOU -80(AX)(CX*1), X11
|
| 1551 |
+
MOVOU -64(AX)(CX*1), X12
|
| 1552 |
+
MOVOU -48(AX)(CX*1), X13
|
| 1553 |
+
MOVOU -32(AX)(CX*1), X14
|
| 1554 |
+
MOVOU -16(AX)(CX*1), X15
|
| 1555 |
+
|
| 1556 |
+
// xor in seed
|
| 1557 |
+
PXOR X0, X8
|
| 1558 |
+
PXOR X1, X9
|
| 1559 |
+
PXOR X2, X10
|
| 1560 |
+
PXOR X3, X11
|
| 1561 |
+
PXOR X4, X12
|
| 1562 |
+
PXOR X5, X13
|
| 1563 |
+
PXOR X6, X14
|
| 1564 |
+
PXOR X7, X15
|
| 1565 |
+
|
| 1566 |
+
// compute number of remaining 128-byte blocks
|
| 1567 |
+
DECQ CX
|
| 1568 |
+
SHRQ $7, CX
|
| 1569 |
+
|
| 1570 |
+
PCALIGN $16
|
| 1571 |
+
aesloop:
|
| 1572 |
+
// scramble state
|
| 1573 |
+
AESENC X8, X8
|
| 1574 |
+
AESENC X9, X9
|
| 1575 |
+
AESENC X10, X10
|
| 1576 |
+
AESENC X11, X11
|
| 1577 |
+
AESENC X12, X12
|
| 1578 |
+
AESENC X13, X13
|
| 1579 |
+
AESENC X14, X14
|
| 1580 |
+
AESENC X15, X15
|
| 1581 |
+
|
| 1582 |
+
// scramble state, xor in a block
|
| 1583 |
+
MOVOU (AX), X0
|
| 1584 |
+
MOVOU 16(AX), X1
|
| 1585 |
+
MOVOU 32(AX), X2
|
| 1586 |
+
MOVOU 48(AX), X3
|
| 1587 |
+
AESENC X0, X8
|
| 1588 |
+
AESENC X1, X9
|
| 1589 |
+
AESENC X2, X10
|
| 1590 |
+
AESENC X3, X11
|
| 1591 |
+
MOVOU 64(AX), X4
|
| 1592 |
+
MOVOU 80(AX), X5
|
| 1593 |
+
MOVOU 96(AX), X6
|
| 1594 |
+
MOVOU 112(AX), X7
|
| 1595 |
+
AESENC X4, X12
|
| 1596 |
+
AESENC X5, X13
|
| 1597 |
+
AESENC X6, X14
|
| 1598 |
+
AESENC X7, X15
|
| 1599 |
+
|
| 1600 |
+
ADDQ $128, AX
|
| 1601 |
+
DECQ CX
|
| 1602 |
+
JNE aesloop
|
| 1603 |
+
|
| 1604 |
+
// 3 more scrambles to finish
|
| 1605 |
+
AESENC X8, X8
|
| 1606 |
+
AESENC X9, X9
|
| 1607 |
+
AESENC X10, X10
|
| 1608 |
+
AESENC X11, X11
|
| 1609 |
+
AESENC X12, X12
|
| 1610 |
+
AESENC X13, X13
|
| 1611 |
+
AESENC X14, X14
|
| 1612 |
+
AESENC X15, X15
|
| 1613 |
+
AESENC X8, X8
|
| 1614 |
+
AESENC X9, X9
|
| 1615 |
+
AESENC X10, X10
|
| 1616 |
+
AESENC X11, X11
|
| 1617 |
+
AESENC X12, X12
|
| 1618 |
+
AESENC X13, X13
|
| 1619 |
+
AESENC X14, X14
|
| 1620 |
+
AESENC X15, X15
|
| 1621 |
+
AESENC X8, X8
|
| 1622 |
+
AESENC X9, X9
|
| 1623 |
+
AESENC X10, X10
|
| 1624 |
+
AESENC X11, X11
|
| 1625 |
+
AESENC X12, X12
|
| 1626 |
+
AESENC X13, X13
|
| 1627 |
+
AESENC X14, X14
|
| 1628 |
+
AESENC X15, X15
|
| 1629 |
+
|
| 1630 |
+
PXOR X12, X8
|
| 1631 |
+
PXOR X13, X9
|
| 1632 |
+
PXOR X14, X10
|
| 1633 |
+
PXOR X15, X11
|
| 1634 |
+
PXOR X10, X8
|
| 1635 |
+
PXOR X11, X9
|
| 1636 |
+
PXOR X9, X8
|
| 1637 |
+
// X15 must be zero on return
|
| 1638 |
+
PXOR X15, X15
|
| 1639 |
+
MOVQ X8, AX // return X8
|
| 1640 |
+
RET
|
| 1641 |
+
|
| 1642 |
+
// func memhash32(p unsafe.Pointer, h uintptr) uintptr
|
| 1643 |
+
// ABIInternal for performance.
|
| 1644 |
+
TEXT runtime·memhash32<ABIInternal>(SB),NOSPLIT,$0-24
|
| 1645 |
+
// AX = ptr to data
|
| 1646 |
+
// BX = seed
|
| 1647 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1648 |
+
JEQ noaes
|
| 1649 |
+
MOVQ BX, X0 // X0 = seed
|
| 1650 |
+
PINSRD $2, (AX), X0 // data
|
| 1651 |
+
AESENC runtime·aeskeysched+0(SB), X0
|
| 1652 |
+
AESENC runtime·aeskeysched+16(SB), X0
|
| 1653 |
+
AESENC runtime·aeskeysched+32(SB), X0
|
| 1654 |
+
MOVQ X0, AX // return X0
|
| 1655 |
+
RET
|
| 1656 |
+
noaes:
|
| 1657 |
+
JMP runtime·memhash32Fallback<ABIInternal>(SB)
|
| 1658 |
+
|
| 1659 |
+
// func memhash64(p unsafe.Pointer, h uintptr) uintptr
|
| 1660 |
+
// ABIInternal for performance.
|
| 1661 |
+
TEXT runtime·memhash64<ABIInternal>(SB),NOSPLIT,$0-24
|
| 1662 |
+
// AX = ptr to data
|
| 1663 |
+
// BX = seed
|
| 1664 |
+
CMPB runtime·useAeshash(SB), $0
|
| 1665 |
+
JEQ noaes
|
| 1666 |
+
MOVQ BX, X0 // X0 = seed
|
| 1667 |
+
PINSRQ $1, (AX), X0 // data
|
| 1668 |
+
AESENC runtime·aeskeysched+0(SB), X0
|
| 1669 |
+
AESENC runtime·aeskeysched+16(SB), X0
|
| 1670 |
+
AESENC runtime·aeskeysched+32(SB), X0
|
| 1671 |
+
MOVQ X0, AX // return X0
|
| 1672 |
+
RET
|
| 1673 |
+
noaes:
|
| 1674 |
+
JMP runtime·memhash64Fallback<ABIInternal>(SB)
|
| 1675 |
+
|
| 1676 |
+
// simple mask to get rid of data in the high part of the register.
|
| 1677 |
+
DATA masks<>+0x00(SB)/8, $0x0000000000000000
|
| 1678 |
+
DATA masks<>+0x08(SB)/8, $0x0000000000000000
|
| 1679 |
+
DATA masks<>+0x10(SB)/8, $0x00000000000000ff
|
| 1680 |
+
DATA masks<>+0x18(SB)/8, $0x0000000000000000
|
| 1681 |
+
DATA masks<>+0x20(SB)/8, $0x000000000000ffff
|
| 1682 |
+
DATA masks<>+0x28(SB)/8, $0x0000000000000000
|
| 1683 |
+
DATA masks<>+0x30(SB)/8, $0x0000000000ffffff
|
| 1684 |
+
DATA masks<>+0x38(SB)/8, $0x0000000000000000
|
| 1685 |
+
DATA masks<>+0x40(SB)/8, $0x00000000ffffffff
|
| 1686 |
+
DATA masks<>+0x48(SB)/8, $0x0000000000000000
|
| 1687 |
+
DATA masks<>+0x50(SB)/8, $0x000000ffffffffff
|
| 1688 |
+
DATA masks<>+0x58(SB)/8, $0x0000000000000000
|
| 1689 |
+
DATA masks<>+0x60(SB)/8, $0x0000ffffffffffff
|
| 1690 |
+
DATA masks<>+0x68(SB)/8, $0x0000000000000000
|
| 1691 |
+
DATA masks<>+0x70(SB)/8, $0x00ffffffffffffff
|
| 1692 |
+
DATA masks<>+0x78(SB)/8, $0x0000000000000000
|
| 1693 |
+
DATA masks<>+0x80(SB)/8, $0xffffffffffffffff
|
| 1694 |
+
DATA masks<>+0x88(SB)/8, $0x0000000000000000
|
| 1695 |
+
DATA masks<>+0x90(SB)/8, $0xffffffffffffffff
|
| 1696 |
+
DATA masks<>+0x98(SB)/8, $0x00000000000000ff
|
| 1697 |
+
DATA masks<>+0xa0(SB)/8, $0xffffffffffffffff
|
| 1698 |
+
DATA masks<>+0xa8(SB)/8, $0x000000000000ffff
|
| 1699 |
+
DATA masks<>+0xb0(SB)/8, $0xffffffffffffffff
|
| 1700 |
+
DATA masks<>+0xb8(SB)/8, $0x0000000000ffffff
|
| 1701 |
+
DATA masks<>+0xc0(SB)/8, $0xffffffffffffffff
|
| 1702 |
+
DATA masks<>+0xc8(SB)/8, $0x00000000ffffffff
|
| 1703 |
+
DATA masks<>+0xd0(SB)/8, $0xffffffffffffffff
|
| 1704 |
+
DATA masks<>+0xd8(SB)/8, $0x000000ffffffffff
|
| 1705 |
+
DATA masks<>+0xe0(SB)/8, $0xffffffffffffffff
|
| 1706 |
+
DATA masks<>+0xe8(SB)/8, $0x0000ffffffffffff
|
| 1707 |
+
DATA masks<>+0xf0(SB)/8, $0xffffffffffffffff
|
| 1708 |
+
DATA masks<>+0xf8(SB)/8, $0x00ffffffffffffff
|
| 1709 |
+
GLOBL masks<>(SB),RODATA,$256
|
| 1710 |
+
|
| 1711 |
+
// func checkASM() bool
|
| 1712 |
+
TEXT ·checkASM(SB),NOSPLIT,$0-1
|
| 1713 |
+
// check that masks<>(SB) and shifts<>(SB) are aligned to 16-byte
|
| 1714 |
+
MOVQ $masks<>(SB), AX
|
| 1715 |
+
MOVQ $shifts<>(SB), BX
|
| 1716 |
+
ORQ BX, AX
|
| 1717 |
+
TESTQ $15, AX
|
| 1718 |
+
SETEQ ret+0(FP)
|
| 1719 |
+
RET
|
| 1720 |
+
|
| 1721 |
+
// these are arguments to pshufb. They move data down from
|
| 1722 |
+
// the high bytes of the register to the low bytes of the register.
|
| 1723 |
+
// index is how many bytes to move.
|
| 1724 |
+
DATA shifts<>+0x00(SB)/8, $0x0000000000000000
|
| 1725 |
+
DATA shifts<>+0x08(SB)/8, $0x0000000000000000
|
| 1726 |
+
DATA shifts<>+0x10(SB)/8, $0xffffffffffffff0f
|
| 1727 |
+
DATA shifts<>+0x18(SB)/8, $0xffffffffffffffff
|
| 1728 |
+
DATA shifts<>+0x20(SB)/8, $0xffffffffffff0f0e
|
| 1729 |
+
DATA shifts<>+0x28(SB)/8, $0xffffffffffffffff
|
| 1730 |
+
DATA shifts<>+0x30(SB)/8, $0xffffffffff0f0e0d
|
| 1731 |
+
DATA shifts<>+0x38(SB)/8, $0xffffffffffffffff
|
| 1732 |
+
DATA shifts<>+0x40(SB)/8, $0xffffffff0f0e0d0c
|
| 1733 |
+
DATA shifts<>+0x48(SB)/8, $0xffffffffffffffff
|
| 1734 |
+
DATA shifts<>+0x50(SB)/8, $0xffffff0f0e0d0c0b
|
| 1735 |
+
DATA shifts<>+0x58(SB)/8, $0xffffffffffffffff
|
| 1736 |
+
DATA shifts<>+0x60(SB)/8, $0xffff0f0e0d0c0b0a
|
| 1737 |
+
DATA shifts<>+0x68(SB)/8, $0xffffffffffffffff
|
| 1738 |
+
DATA shifts<>+0x70(SB)/8, $0xff0f0e0d0c0b0a09
|
| 1739 |
+
DATA shifts<>+0x78(SB)/8, $0xffffffffffffffff
|
| 1740 |
+
DATA shifts<>+0x80(SB)/8, $0x0f0e0d0c0b0a0908
|
| 1741 |
+
DATA shifts<>+0x88(SB)/8, $0xffffffffffffffff
|
| 1742 |
+
DATA shifts<>+0x90(SB)/8, $0x0e0d0c0b0a090807
|
| 1743 |
+
DATA shifts<>+0x98(SB)/8, $0xffffffffffffff0f
|
| 1744 |
+
DATA shifts<>+0xa0(SB)/8, $0x0d0c0b0a09080706
|
| 1745 |
+
DATA shifts<>+0xa8(SB)/8, $0xffffffffffff0f0e
|
| 1746 |
+
DATA shifts<>+0xb0(SB)/8, $0x0c0b0a0908070605
|
| 1747 |
+
DATA shifts<>+0xb8(SB)/8, $0xffffffffff0f0e0d
|
| 1748 |
+
DATA shifts<>+0xc0(SB)/8, $0x0b0a090807060504
|
| 1749 |
+
DATA shifts<>+0xc8(SB)/8, $0xffffffff0f0e0d0c
|
| 1750 |
+
DATA shifts<>+0xd0(SB)/8, $0x0a09080706050403
|
| 1751 |
+
DATA shifts<>+0xd8(SB)/8, $0xffffff0f0e0d0c0b
|
| 1752 |
+
DATA shifts<>+0xe0(SB)/8, $0x0908070605040302
|
| 1753 |
+
DATA shifts<>+0xe8(SB)/8, $0xffff0f0e0d0c0b0a
|
| 1754 |
+
DATA shifts<>+0xf0(SB)/8, $0x0807060504030201
|
| 1755 |
+
DATA shifts<>+0xf8(SB)/8, $0xff0f0e0d0c0b0a09
|
| 1756 |
+
GLOBL shifts<>(SB),RODATA,$256
|
| 1757 |
+
|
| 1758 |
+
// Called from cgo wrappers, this function returns g->m->curg.stack.hi.
|
| 1759 |
+
// Must obey the gcc calling convention.
|
| 1760 |
+
TEXT _cgo_topofstack(SB),NOSPLIT,$0
|
| 1761 |
+
get_tls(CX)
|
| 1762 |
+
MOVQ g(CX), AX
|
| 1763 |
+
MOVQ g_m(AX), AX
|
| 1764 |
+
MOVQ m_curg(AX), AX
|
| 1765 |
+
MOVQ (g_stack+stack_hi)(AX), AX
|
| 1766 |
+
RET
|
| 1767 |
+
|
| 1768 |
+
// The top-most function running on a goroutine
|
| 1769 |
+
// returns to goexit+PCQuantum.
|
| 1770 |
+
TEXT runtime·goexit(SB),NOSPLIT|TOPFRAME|NOFRAME,$0-0
|
| 1771 |
+
BYTE $0x90 // NOP
|
| 1772 |
+
CALL runtime·goexit1(SB) // does not return
|
| 1773 |
+
// traceback from goexit1 must hit code range of goexit
|
| 1774 |
+
BYTE $0x90 // NOP
|
| 1775 |
+
|
| 1776 |
+
// This is called from .init_array and follows the platform, not Go, ABI.
|
| 1777 |
+
TEXT runtime·addmoduledata(SB),NOSPLIT,$0-0
|
| 1778 |
+
PUSHQ R15 // The access to global variables below implicitly uses R15, which is callee-save
|
| 1779 |
+
MOVQ runtime·lastmoduledatap(SB), AX
|
| 1780 |
+
MOVQ DI, moduledata_next(AX)
|
| 1781 |
+
MOVQ DI, runtime·lastmoduledatap(SB)
|
| 1782 |
+
POPQ R15
|
| 1783 |
+
RET
|
| 1784 |
+
|
| 1785 |
+
// Initialize special registers then jump to sigpanic.
|
| 1786 |
+
// This function is injected from the signal handler for panicking
|
| 1787 |
+
// signals. It is quite painful to set X15 in the signal context,
|
| 1788 |
+
// so we do it here.
|
| 1789 |
+
TEXT ·sigpanic0(SB),NOSPLIT,$0-0
|
| 1790 |
+
get_tls(R14)
|
| 1791 |
+
MOVQ g(R14), R14
|
| 1792 |
+
XORPS X15, X15
|
| 1793 |
+
JMP ·sigpanic<ABIInternal>(SB)
|
| 1794 |
+
|
| 1795 |
+
// gcWriteBarrier informs the GC about heap pointer writes.
|
| 1796 |
+
//
|
| 1797 |
+
// gcWriteBarrier returns space in a write barrier buffer which
|
| 1798 |
+
// should be filled in by the caller.
|
| 1799 |
+
// gcWriteBarrier does NOT follow the Go ABI. It accepts the
|
| 1800 |
+
// number of bytes of buffer needed in R11, and returns a pointer
|
| 1801 |
+
// to the buffer space in R11.
|
| 1802 |
+
// It clobbers FLAGS. It does not clobber any general-purpose registers,
|
| 1803 |
+
// but may clobber others (e.g., SSE registers).
|
| 1804 |
+
// Typical use would be, when doing *(CX+88) = AX
|
| 1805 |
+
// CMPL $0, runtime.writeBarrier(SB)
|
| 1806 |
+
// JEQ dowrite
|
| 1807 |
+
// CALL runtime.gcBatchBarrier2(SB)
|
| 1808 |
+
// MOVQ AX, (R11)
|
| 1809 |
+
// MOVQ 88(CX), DX
|
| 1810 |
+
// MOVQ DX, 8(R11)
|
| 1811 |
+
// dowrite:
|
| 1812 |
+
// MOVQ AX, 88(CX)
|
| 1813 |
+
TEXT gcWriteBarrier<>(SB),NOSPLIT,$112
|
| 1814 |
+
// Save the registers clobbered by the fast path. This is slightly
|
| 1815 |
+
// faster than having the caller spill these.
|
| 1816 |
+
MOVQ R12, 96(SP)
|
| 1817 |
+
MOVQ R13, 104(SP)
|
| 1818 |
+
retry:
|
| 1819 |
+
// TODO: Consider passing g.m.p in as an argument so they can be shared
|
| 1820 |
+
// across a sequence of write barriers.
|
| 1821 |
+
MOVQ g_m(R14), R13
|
| 1822 |
+
MOVQ m_p(R13), R13
|
| 1823 |
+
// Get current buffer write position.
|
| 1824 |
+
MOVQ (p_wbBuf+wbBuf_next)(R13), R12 // original next position
|
| 1825 |
+
ADDQ R11, R12 // new next position
|
| 1826 |
+
// Is the buffer full?
|
| 1827 |
+
CMPQ R12, (p_wbBuf+wbBuf_end)(R13)
|
| 1828 |
+
JA flush
|
| 1829 |
+
// Commit to the larger buffer.
|
| 1830 |
+
MOVQ R12, (p_wbBuf+wbBuf_next)(R13)
|
| 1831 |
+
// Make return value (the original next position)
|
| 1832 |
+
SUBQ R11, R12
|
| 1833 |
+
MOVQ R12, R11
|
| 1834 |
+
// Restore registers.
|
| 1835 |
+
MOVQ 96(SP), R12
|
| 1836 |
+
MOVQ 104(SP), R13
|
| 1837 |
+
RET
|
| 1838 |
+
|
| 1839 |
+
flush:
|
| 1840 |
+
// Save all general purpose registers since these could be
|
| 1841 |
+
// clobbered by wbBufFlush and were not saved by the caller.
|
| 1842 |
+
// It is possible for wbBufFlush to clobber other registers
|
| 1843 |
+
// (e.g., SSE registers), but the compiler takes care of saving
|
| 1844 |
+
// those in the caller if necessary. This strikes a balance
|
| 1845 |
+
// with registers that are likely to be used.
|
| 1846 |
+
//
|
| 1847 |
+
// We don't have type information for these, but all code under
|
| 1848 |
+
// here is NOSPLIT, so nothing will observe these.
|
| 1849 |
+
//
|
| 1850 |
+
// TODO: We could strike a different balance; e.g., saving X0
|
| 1851 |
+
// and not saving GP registers that are less likely to be used.
|
| 1852 |
+
MOVQ DI, 0(SP)
|
| 1853 |
+
MOVQ AX, 8(SP)
|
| 1854 |
+
MOVQ BX, 16(SP)
|
| 1855 |
+
MOVQ CX, 24(SP)
|
| 1856 |
+
MOVQ DX, 32(SP)
|
| 1857 |
+
// DI already saved
|
| 1858 |
+
MOVQ SI, 40(SP)
|
| 1859 |
+
MOVQ BP, 48(SP)
|
| 1860 |
+
MOVQ R8, 56(SP)
|
| 1861 |
+
MOVQ R9, 64(SP)
|
| 1862 |
+
MOVQ R10, 72(SP)
|
| 1863 |
+
MOVQ R11, 80(SP)
|
| 1864 |
+
// R12 already saved
|
| 1865 |
+
// R13 already saved
|
| 1866 |
+
// R14 is g
|
| 1867 |
+
MOVQ R15, 88(SP)
|
| 1868 |
+
|
| 1869 |
+
CALL runtime·wbBufFlush(SB)
|
| 1870 |
+
|
| 1871 |
+
MOVQ 0(SP), DI
|
| 1872 |
+
MOVQ 8(SP), AX
|
| 1873 |
+
MOVQ 16(SP), BX
|
| 1874 |
+
MOVQ 24(SP), CX
|
| 1875 |
+
MOVQ 32(SP), DX
|
| 1876 |
+
MOVQ 40(SP), SI
|
| 1877 |
+
MOVQ 48(SP), BP
|
| 1878 |
+
MOVQ 56(SP), R8
|
| 1879 |
+
MOVQ 64(SP), R9
|
| 1880 |
+
MOVQ 72(SP), R10
|
| 1881 |
+
MOVQ 80(SP), R11
|
| 1882 |
+
MOVQ 88(SP), R15
|
| 1883 |
+
JMP retry
|
| 1884 |
+
|
| 1885 |
+
TEXT runtime·gcWriteBarrier1<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1886 |
+
MOVL $8, R11
|
| 1887 |
+
JMP gcWriteBarrier<>(SB)
|
| 1888 |
+
TEXT runtime·gcWriteBarrier2<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1889 |
+
MOVL $16, R11
|
| 1890 |
+
JMP gcWriteBarrier<>(SB)
|
| 1891 |
+
TEXT runtime·gcWriteBarrier3<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1892 |
+
MOVL $24, R11
|
| 1893 |
+
JMP gcWriteBarrier<>(SB)
|
| 1894 |
+
TEXT runtime·gcWriteBarrier4<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1895 |
+
MOVL $32, R11
|
| 1896 |
+
JMP gcWriteBarrier<>(SB)
|
| 1897 |
+
TEXT runtime·gcWriteBarrier5<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1898 |
+
MOVL $40, R11
|
| 1899 |
+
JMP gcWriteBarrier<>(SB)
|
| 1900 |
+
TEXT runtime·gcWriteBarrier6<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1901 |
+
MOVL $48, R11
|
| 1902 |
+
JMP gcWriteBarrier<>(SB)
|
| 1903 |
+
TEXT runtime·gcWriteBarrier7<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1904 |
+
MOVL $56, R11
|
| 1905 |
+
JMP gcWriteBarrier<>(SB)
|
| 1906 |
+
TEXT runtime·gcWriteBarrier8<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 1907 |
+
MOVL $64, R11
|
| 1908 |
+
JMP gcWriteBarrier<>(SB)
|
| 1909 |
+
|
| 1910 |
+
DATA debugCallFrameTooLarge<>+0x00(SB)/20, $"call frame too large"
|
| 1911 |
+
GLOBL debugCallFrameTooLarge<>(SB), RODATA, $20 // Size duplicated below
|
| 1912 |
+
|
| 1913 |
+
// debugCallV2 is the entry point for debugger-injected function
|
| 1914 |
+
// calls on running goroutines. It informs the runtime that a
|
| 1915 |
+
// debug call has been injected and creates a call frame for the
|
| 1916 |
+
// debugger to fill in.
|
| 1917 |
+
//
|
| 1918 |
+
// To inject a function call, a debugger should:
|
| 1919 |
+
// 1. Check that the goroutine is in state _Grunning and that
|
| 1920 |
+
// there are at least 256 bytes free on the stack.
|
| 1921 |
+
// 2. Push the current PC on the stack (updating SP).
|
| 1922 |
+
// 3. Write the desired argument frame size at SP-16 (using the SP
|
| 1923 |
+
// after step 2).
|
| 1924 |
+
// 4. Save all machine registers (including flags and XMM registers)
|
| 1925 |
+
// so they can be restored later by the debugger.
|
| 1926 |
+
// 5. Set the PC to debugCallV2 and resume execution.
|
| 1927 |
+
//
|
| 1928 |
+
// If the goroutine is in state _Grunnable, then it's not generally
|
| 1929 |
+
// safe to inject a call because it may return out via other runtime
|
| 1930 |
+
// operations. Instead, the debugger should unwind the stack to find
|
| 1931 |
+
// the return to non-runtime code, add a temporary breakpoint there,
|
| 1932 |
+
// and inject the call once that breakpoint is hit.
|
| 1933 |
+
//
|
| 1934 |
+
// If the goroutine is in any other state, it's not safe to inject a call.
|
| 1935 |
+
//
|
| 1936 |
+
// This function communicates back to the debugger by setting R12 and
|
| 1937 |
+
// invoking INT3 to raise a breakpoint signal. See the comments in the
|
| 1938 |
+
// implementation for the protocol the debugger is expected to
|
| 1939 |
+
// follow. InjectDebugCall in the runtime tests demonstrates this protocol.
|
| 1940 |
+
//
|
| 1941 |
+
// The debugger must ensure that any pointers passed to the function
|
| 1942 |
+
// obey escape analysis requirements. Specifically, it must not pass
|
| 1943 |
+
// a stack pointer to an escaping argument. debugCallV2 cannot check
|
| 1944 |
+
// this invariant.
|
| 1945 |
+
//
|
| 1946 |
+
// This is ABIInternal because Go code injects its PC directly into new
|
| 1947 |
+
// goroutine stacks.
|
| 1948 |
+
TEXT runtime·debugCallV2<ABIInternal>(SB),NOSPLIT,$152-0
|
| 1949 |
+
// Save all registers that may contain pointers so they can be
|
| 1950 |
+
// conservatively scanned.
|
| 1951 |
+
//
|
| 1952 |
+
// We can't do anything that might clobber any of these
|
| 1953 |
+
// registers before this.
|
| 1954 |
+
MOVQ R15, r15-(14*8+8)(SP)
|
| 1955 |
+
MOVQ R14, r14-(13*8+8)(SP)
|
| 1956 |
+
MOVQ R13, r13-(12*8+8)(SP)
|
| 1957 |
+
MOVQ R12, r12-(11*8+8)(SP)
|
| 1958 |
+
MOVQ R11, r11-(10*8+8)(SP)
|
| 1959 |
+
MOVQ R10, r10-(9*8+8)(SP)
|
| 1960 |
+
MOVQ R9, r9-(8*8+8)(SP)
|
| 1961 |
+
MOVQ R8, r8-(7*8+8)(SP)
|
| 1962 |
+
MOVQ DI, di-(6*8+8)(SP)
|
| 1963 |
+
MOVQ SI, si-(5*8+8)(SP)
|
| 1964 |
+
MOVQ BP, bp-(4*8+8)(SP)
|
| 1965 |
+
MOVQ BX, bx-(3*8+8)(SP)
|
| 1966 |
+
MOVQ DX, dx-(2*8+8)(SP)
|
| 1967 |
+
// Save the frame size before we clobber it. Either of the last
|
| 1968 |
+
// saves could clobber this depending on whether there's a saved BP.
|
| 1969 |
+
MOVQ frameSize-24(FP), DX // aka -16(RSP) before prologue
|
| 1970 |
+
MOVQ CX, cx-(1*8+8)(SP)
|
| 1971 |
+
MOVQ AX, ax-(0*8+8)(SP)
|
| 1972 |
+
|
| 1973 |
+
// Save the argument frame size.
|
| 1974 |
+
MOVQ DX, frameSize-128(SP)
|
| 1975 |
+
|
| 1976 |
+
// Perform a safe-point check.
|
| 1977 |
+
MOVQ retpc-8(FP), AX // Caller's PC
|
| 1978 |
+
MOVQ AX, 0(SP)
|
| 1979 |
+
CALL runtime·debugCallCheck(SB)
|
| 1980 |
+
MOVQ 8(SP), AX
|
| 1981 |
+
TESTQ AX, AX
|
| 1982 |
+
JZ good
|
| 1983 |
+
// The safety check failed. Put the reason string at the top
|
| 1984 |
+
// of the stack.
|
| 1985 |
+
MOVQ AX, 0(SP)
|
| 1986 |
+
MOVQ 16(SP), AX
|
| 1987 |
+
MOVQ AX, 8(SP)
|
| 1988 |
+
// Set R12 to 8 and invoke INT3. The debugger should get the
|
| 1989 |
+
// reason a call can't be injected from the top of the stack
|
| 1990 |
+
// and resume execution.
|
| 1991 |
+
MOVQ $8, R12
|
| 1992 |
+
BYTE $0xcc
|
| 1993 |
+
JMP restore
|
| 1994 |
+
|
| 1995 |
+
good:
|
| 1996 |
+
// Registers are saved and it's safe to make a call.
|
| 1997 |
+
// Open up a call frame, moving the stack if necessary.
|
| 1998 |
+
//
|
| 1999 |
+
// Once the frame is allocated, this will set R12 to 0 and
|
| 2000 |
+
// invoke INT3. The debugger should write the argument
|
| 2001 |
+
// frame for the call at SP, set up argument registers, push
|
| 2002 |
+
// the trapping PC on the stack, set the PC to the function to
|
| 2003 |
+
// call, set RDX to point to the closure (if a closure call),
|
| 2004 |
+
// and resume execution.
|
| 2005 |
+
//
|
| 2006 |
+
// If the function returns, this will set R12 to 1 and invoke
|
| 2007 |
+
// INT3. The debugger can then inspect any return value saved
|
| 2008 |
+
// on the stack at SP and in registers and resume execution again.
|
| 2009 |
+
//
|
| 2010 |
+
// If the function panics, this will set R12 to 2 and invoke INT3.
|
| 2011 |
+
// The interface{} value of the panic will be at SP. The debugger
|
| 2012 |
+
// can inspect the panic value and resume execution again.
|
| 2013 |
+
#define DEBUG_CALL_DISPATCH(NAME,MAXSIZE) \
|
| 2014 |
+
CMPQ AX, $MAXSIZE; \
|
| 2015 |
+
JA 5(PC); \
|
| 2016 |
+
MOVQ $NAME(SB), AX; \
|
| 2017 |
+
MOVQ AX, 0(SP); \
|
| 2018 |
+
CALL runtime·debugCallWrap(SB); \
|
| 2019 |
+
JMP restore
|
| 2020 |
+
|
| 2021 |
+
MOVQ frameSize-128(SP), AX
|
| 2022 |
+
DEBUG_CALL_DISPATCH(debugCall32<>, 32)
|
| 2023 |
+
DEBUG_CALL_DISPATCH(debugCall64<>, 64)
|
| 2024 |
+
DEBUG_CALL_DISPATCH(debugCall128<>, 128)
|
| 2025 |
+
DEBUG_CALL_DISPATCH(debugCall256<>, 256)
|
| 2026 |
+
DEBUG_CALL_DISPATCH(debugCall512<>, 512)
|
| 2027 |
+
DEBUG_CALL_DISPATCH(debugCall1024<>, 1024)
|
| 2028 |
+
DEBUG_CALL_DISPATCH(debugCall2048<>, 2048)
|
| 2029 |
+
DEBUG_CALL_DISPATCH(debugCall4096<>, 4096)
|
| 2030 |
+
DEBUG_CALL_DISPATCH(debugCall8192<>, 8192)
|
| 2031 |
+
DEBUG_CALL_DISPATCH(debugCall16384<>, 16384)
|
| 2032 |
+
DEBUG_CALL_DISPATCH(debugCall32768<>, 32768)
|
| 2033 |
+
DEBUG_CALL_DISPATCH(debugCall65536<>, 65536)
|
| 2034 |
+
// The frame size is too large. Report the error.
|
| 2035 |
+
MOVQ $debugCallFrameTooLarge<>(SB), AX
|
| 2036 |
+
MOVQ AX, 0(SP)
|
| 2037 |
+
MOVQ $20, 8(SP) // length of debugCallFrameTooLarge string
|
| 2038 |
+
MOVQ $8, R12
|
| 2039 |
+
BYTE $0xcc
|
| 2040 |
+
JMP restore
|
| 2041 |
+
|
| 2042 |
+
restore:
|
| 2043 |
+
// Calls and failures resume here.
|
| 2044 |
+
//
|
| 2045 |
+
// Set R12 to 16 and invoke INT3. The debugger should restore
|
| 2046 |
+
// all registers except RIP and RSP and resume execution.
|
| 2047 |
+
MOVQ $16, R12
|
| 2048 |
+
BYTE $0xcc
|
| 2049 |
+
// We must not modify flags after this point.
|
| 2050 |
+
|
| 2051 |
+
// Restore pointer-containing registers, which may have been
|
| 2052 |
+
// modified from the debugger's copy by stack copying.
|
| 2053 |
+
MOVQ ax-(0*8+8)(SP), AX
|
| 2054 |
+
MOVQ cx-(1*8+8)(SP), CX
|
| 2055 |
+
MOVQ dx-(2*8+8)(SP), DX
|
| 2056 |
+
MOVQ bx-(3*8+8)(SP), BX
|
| 2057 |
+
MOVQ bp-(4*8+8)(SP), BP
|
| 2058 |
+
MOVQ si-(5*8+8)(SP), SI
|
| 2059 |
+
MOVQ di-(6*8+8)(SP), DI
|
| 2060 |
+
MOVQ r8-(7*8+8)(SP), R8
|
| 2061 |
+
MOVQ r9-(8*8+8)(SP), R9
|
| 2062 |
+
MOVQ r10-(9*8+8)(SP), R10
|
| 2063 |
+
MOVQ r11-(10*8+8)(SP), R11
|
| 2064 |
+
MOVQ r12-(11*8+8)(SP), R12
|
| 2065 |
+
MOVQ r13-(12*8+8)(SP), R13
|
| 2066 |
+
MOVQ r14-(13*8+8)(SP), R14
|
| 2067 |
+
MOVQ r15-(14*8+8)(SP), R15
|
| 2068 |
+
|
| 2069 |
+
RET
|
| 2070 |
+
|
| 2071 |
+
// runtime.debugCallCheck assumes that functions defined with the
|
| 2072 |
+
// DEBUG_CALL_FN macro are safe points to inject calls.
|
| 2073 |
+
#define DEBUG_CALL_FN(NAME,MAXSIZE) \
|
| 2074 |
+
TEXT NAME(SB),WRAPPER,$MAXSIZE-0; \
|
| 2075 |
+
NO_LOCAL_POINTERS; \
|
| 2076 |
+
MOVQ $0, R12; \
|
| 2077 |
+
BYTE $0xcc; \
|
| 2078 |
+
MOVQ $1, R12; \
|
| 2079 |
+
BYTE $0xcc; \
|
| 2080 |
+
RET
|
| 2081 |
+
DEBUG_CALL_FN(debugCall32<>, 32)
|
| 2082 |
+
DEBUG_CALL_FN(debugCall64<>, 64)
|
| 2083 |
+
DEBUG_CALL_FN(debugCall128<>, 128)
|
| 2084 |
+
DEBUG_CALL_FN(debugCall256<>, 256)
|
| 2085 |
+
DEBUG_CALL_FN(debugCall512<>, 512)
|
| 2086 |
+
DEBUG_CALL_FN(debugCall1024<>, 1024)
|
| 2087 |
+
DEBUG_CALL_FN(debugCall2048<>, 2048)
|
| 2088 |
+
DEBUG_CALL_FN(debugCall4096<>, 4096)
|
| 2089 |
+
DEBUG_CALL_FN(debugCall8192<>, 8192)
|
| 2090 |
+
DEBUG_CALL_FN(debugCall16384<>, 16384)
|
| 2091 |
+
DEBUG_CALL_FN(debugCall32768<>, 32768)
|
| 2092 |
+
DEBUG_CALL_FN(debugCall65536<>, 65536)
|
| 2093 |
+
|
| 2094 |
+
// func debugCallPanicked(val interface{})
|
| 2095 |
+
TEXT runtime·debugCallPanicked(SB),NOSPLIT,$16-16
|
| 2096 |
+
// Copy the panic value to the top of stack.
|
| 2097 |
+
MOVQ val_type+0(FP), AX
|
| 2098 |
+
MOVQ AX, 0(SP)
|
| 2099 |
+
MOVQ val_data+8(FP), AX
|
| 2100 |
+
MOVQ AX, 8(SP)
|
| 2101 |
+
MOVQ $2, R12
|
| 2102 |
+
BYTE $0xcc
|
| 2103 |
+
RET
|
| 2104 |
+
|
| 2105 |
+
TEXT runtime·panicBounds<ABIInternal>(SB),NOSPLIT,$144-0
|
| 2106 |
+
NO_LOCAL_POINTERS
|
| 2107 |
+
// Save all 14 int registers that could have an index in them.
|
| 2108 |
+
// They may be pointers, but if they are they are dead.
|
| 2109 |
+
MOVQ AX, 16(SP)
|
| 2110 |
+
MOVQ CX, 24(SP)
|
| 2111 |
+
MOVQ DX, 32(SP)
|
| 2112 |
+
MOVQ BX, 40(SP)
|
| 2113 |
+
// skip SP @ 48(SP)
|
| 2114 |
+
MOVQ BP, 56(SP)
|
| 2115 |
+
MOVQ SI, 64(SP)
|
| 2116 |
+
MOVQ DI, 72(SP)
|
| 2117 |
+
MOVQ R8, 80(SP)
|
| 2118 |
+
MOVQ R9, 88(SP)
|
| 2119 |
+
MOVQ R10, 96(SP)
|
| 2120 |
+
MOVQ R11, 104(SP)
|
| 2121 |
+
MOVQ R12, 112(SP)
|
| 2122 |
+
MOVQ R13, 120(SP)
|
| 2123 |
+
// skip R14 @ 128(SP) (aka G)
|
| 2124 |
+
MOVQ R15, 136(SP)
|
| 2125 |
+
|
| 2126 |
+
MOVQ SP, AX // hide SP read from vet
|
| 2127 |
+
MOVQ 152(AX), AX // PC immediately after call to panicBounds
|
| 2128 |
+
LEAQ 16(SP), BX
|
| 2129 |
+
CALL runtime·panicBounds64<ABIInternal>(SB)
|
| 2130 |
+
RET
|
| 2131 |
+
|
| 2132 |
+
#ifdef GOOS_android
|
| 2133 |
+
// Use the free TLS_SLOT_APP slot #2 on Android Q.
|
| 2134 |
+
// Earlier androids are set up in gcc_android.c.
|
| 2135 |
+
DATA runtime·tls_g+0(SB)/8, $16
|
| 2136 |
+
GLOBL runtime·tls_g+0(SB), NOPTR, $8
|
| 2137 |
+
#endif
|
| 2138 |
+
#ifdef GOOS_windows
|
| 2139 |
+
GLOBL runtime·tls_g+0(SB), NOPTR, $8
|
| 2140 |
+
#endif
|
| 2141 |
+
|
| 2142 |
+
// The compiler and assembler's -spectre=ret mode rewrites
|
| 2143 |
+
// all indirect CALL AX / JMP AX instructions to be
|
| 2144 |
+
// CALL retpolineAX / JMP retpolineAX.
|
| 2145 |
+
// See https://support.google.com/faqs/answer/7625886.
|
| 2146 |
+
#define RETPOLINE(reg) \
|
| 2147 |
+
/* CALL setup */ BYTE $0xE8; BYTE $(2+2); BYTE $0; BYTE $0; BYTE $0; \
|
| 2148 |
+
/* nospec: */ \
|
| 2149 |
+
/* PAUSE */ BYTE $0xF3; BYTE $0x90; \
|
| 2150 |
+
/* JMP nospec */ BYTE $0xEB; BYTE $-(2+2); \
|
| 2151 |
+
/* setup: */ \
|
| 2152 |
+
/* MOVQ AX, 0(SP) */ BYTE $0x48|((reg&8)>>1); BYTE $0x89; \
|
| 2153 |
+
BYTE $0x04|((reg&7)<<3); BYTE $0x24; \
|
| 2154 |
+
/* RET */ BYTE $0xC3
|
| 2155 |
+
|
| 2156 |
+
TEXT runtime·retpolineAX(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(0)
|
| 2157 |
+
TEXT runtime·retpolineCX(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(1)
|
| 2158 |
+
TEXT runtime·retpolineDX(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(2)
|
| 2159 |
+
TEXT runtime·retpolineBX(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(3)
|
| 2160 |
+
/* SP is 4, can't happen / magic encodings */
|
| 2161 |
+
TEXT runtime·retpolineBP(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(5)
|
| 2162 |
+
TEXT runtime·retpolineSI(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(6)
|
| 2163 |
+
TEXT runtime·retpolineDI(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(7)
|
| 2164 |
+
TEXT runtime·retpolineR8(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(8)
|
| 2165 |
+
TEXT runtime·retpolineR9(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(9)
|
| 2166 |
+
TEXT runtime·retpolineR10(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(10)
|
| 2167 |
+
TEXT runtime·retpolineR11(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(11)
|
| 2168 |
+
TEXT runtime·retpolineR12(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(12)
|
| 2169 |
+
TEXT runtime·retpolineR13(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(13)
|
| 2170 |
+
TEXT runtime·retpolineR14(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(14)
|
| 2171 |
+
TEXT runtime·retpolineR15(SB),NOSPLIT|NOFRAME,$0; RETPOLINE(15)
|
| 2172 |
+
|
| 2173 |
+
TEXT ·getfp<ABIInternal>(SB),NOSPLIT|NOFRAME,$0
|
| 2174 |
+
MOVQ BP, AX
|
| 2175 |
+
RET
|