Source file src/reflect/value.go

     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
     6  
     7  import (
     8  	"errors"
     9  	"internal/abi"
    10  	"internal/goarch"
    11  	"internal/itoa"
    12  	"internal/unsafeheader"
    13  	"math"
    14  	"runtime"
    15  	"unsafe"
    16  )
    17  
    18  // Value is the reflection interface to a Go value.
    19  //
    20  // Not all methods apply to all kinds of values. Restrictions,
    21  // if any, are noted in the documentation for each method.
    22  // Use the Kind method to find out the kind of value before
    23  // calling kind-specific methods. Calling a method
    24  // inappropriate to the kind of type causes a run time panic.
    25  //
    26  // The zero Value represents no value.
    27  // Its [Value.IsValid] method returns false, its Kind method returns [Invalid],
    28  // its String method returns "<invalid Value>", and all other methods panic.
    29  // Most functions and methods never return an invalid value.
    30  // If one does, its documentation states the conditions explicitly.
    31  //
    32  // A Value can be used concurrently by multiple goroutines provided that
    33  // the underlying Go value can be used concurrently for the equivalent
    34  // direct operations.
    35  //
    36  // To compare two Values, compare the results of the Interface method.
    37  // Using == on two Values does not compare the underlying values
    38  // they represent.
    39  type Value struct {
    40  	// typ_ holds the type of the value represented by a Value.
    41  	// Access using the typ method to avoid escape of v.
    42  	typ_ *abi.Type
    43  
    44  	// Pointer-valued data or, if flagIndir is set, pointer to data.
    45  	// Valid when either flagIndir is set or typ.pointers() is true.
    46  	ptr unsafe.Pointer
    47  
    48  	// flag holds metadata about the value.
    49  	//
    50  	// The lowest five bits give the Kind of the value, mirroring typ.Kind().
    51  	//
    52  	// The next set of bits are flag bits:
    53  	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
    54  	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
    55  	//	- flagIndir: val holds a pointer to the data
    56  	//	- flagAddr: v.CanAddr is true (implies flagIndir and ptr is non-nil)
    57  	//	- flagMethod: v is a method value.
    58  	// If ifaceIndir(typ), code can assume that flagIndir is set.
    59  	//
    60  	// The remaining 22+ bits give a method number for method values.
    61  	// If flag.kind() != Func, code can assume that flagMethod is unset.
    62  	flag
    63  
    64  	// A method value represents a curried method invocation
    65  	// like r.Read for some receiver r. The typ+val+flag bits describe
    66  	// the receiver r, but the flag's Kind bits say Func (methods are
    67  	// functions), and the top bits of the flag give the method number
    68  	// in r's type's method table.
    69  }
    70  
    71  type flag uintptr
    72  
    73  const (
    74  	flagKindWidth        = 5 // there are 27 kinds
    75  	flagKindMask    flag = 1<<flagKindWidth - 1
    76  	flagStickyRO    flag = 1 << 5
    77  	flagEmbedRO     flag = 1 << 6
    78  	flagIndir       flag = 1 << 7
    79  	flagAddr        flag = 1 << 8
    80  	flagMethod      flag = 1 << 9
    81  	flagMethodShift      = 10
    82  	flagRO          flag = flagStickyRO | flagEmbedRO
    83  )
    84  
    85  func (f flag) kind() Kind {
    86  	return Kind(f & flagKindMask)
    87  }
    88  
    89  func (f flag) ro() flag {
    90  	if f&flagRO != 0 {
    91  		return flagStickyRO
    92  	}
    93  	return 0
    94  }
    95  
    96  // typ returns the *abi.Type stored in the Value. This method is fast,
    97  // but it doesn't always return the correct type for the Value.
    98  // See abiType and Type, which do return the correct type.
    99  func (v Value) typ() *abi.Type {
   100  	// Types are either static (for compiler-created types) or
   101  	// heap-allocated but always reachable (for reflection-created
   102  	// types, held in the central map). So there is no need to
   103  	// escape types. noescape here help avoid unnecessary escape
   104  	// of v.
   105  	return (*abi.Type)(abi.NoEscape(unsafe.Pointer(v.typ_)))
   106  }
   107  
   108  // pointer returns the underlying pointer represented by v.
   109  // v.Kind() must be Pointer, Map, Chan, Func, or UnsafePointer
   110  // if v.Kind() == Pointer, the base type must not be not-in-heap.
   111  func (v Value) pointer() unsafe.Pointer {
   112  	if v.typ().Size() != goarch.PtrSize || !v.typ().Pointers() {
   113  		panic("can't call pointer on a non-pointer Value")
   114  	}
   115  	if v.flag&flagIndir != 0 {
   116  		return *(*unsafe.Pointer)(v.ptr)
   117  	}
   118  	return v.ptr
   119  }
   120  
   121  // packEface converts v to the empty interface.
   122  func packEface(v Value) any {
   123  	t := v.typ()
   124  	var i any
   125  	e := (*abi.EmptyInterface)(unsafe.Pointer(&i))
   126  	// First, fill in the data portion of the interface.
   127  	switch {
   128  	case t.IfaceIndir():
   129  		if v.flag&flagIndir == 0 {
   130  			panic("bad indir")
   131  		}
   132  		// Value is indirect, and so is the interface we're making.
   133  		ptr := v.ptr
   134  		if v.flag&flagAddr != 0 {
   135  			c := unsafe_New(t)
   136  			typedmemmove(t, c, ptr)
   137  			ptr = c
   138  		}
   139  		e.Data = ptr
   140  	case v.flag&flagIndir != 0:
   141  		// Value is indirect, but interface is direct. We need
   142  		// to load the data at v.ptr into the interface data word.
   143  		e.Data = *(*unsafe.Pointer)(v.ptr)
   144  	default:
   145  		// Value is direct, and so is the interface.
   146  		e.Data = v.ptr
   147  	}
   148  	// Now, fill in the type portion. We're very careful here not
   149  	// to have any operation between the e.word and e.typ assignments
   150  	// that would let the garbage collector observe the partially-built
   151  	// interface value.
   152  	e.Type = t
   153  	return i
   154  }
   155  
   156  // unpackEface converts the empty interface i to a Value.
   157  func unpackEface(i any) Value {
   158  	e := (*abi.EmptyInterface)(unsafe.Pointer(&i))
   159  	// NOTE: don't read e.word until we know whether it is really a pointer or not.
   160  	t := e.Type
   161  	if t == nil {
   162  		return Value{}
   163  	}
   164  	f := flag(t.Kind())
   165  	if t.IfaceIndir() {
   166  		f |= flagIndir
   167  	}
   168  	return Value{t, e.Data, f}
   169  }
   170  
   171  // A ValueError occurs when a Value method is invoked on
   172  // a [Value] that does not support it. Such cases are documented
   173  // in the description of each method.
   174  type ValueError struct {
   175  	Method string
   176  	Kind   Kind
   177  }
   178  
   179  func (e *ValueError) Error() string {
   180  	if e.Kind == 0 {
   181  		return "reflect: call of " + e.Method + " on zero Value"
   182  	}
   183  	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
   184  }
   185  
   186  // valueMethodName returns the name of the exported calling method on Value.
   187  func valueMethodName() string {
   188  	var pc [5]uintptr
   189  	n := runtime.Callers(1, pc[:])
   190  	frames := runtime.CallersFrames(pc[:n])
   191  	var frame runtime.Frame
   192  	for more := true; more; {
   193  		const prefix = "reflect.Value."
   194  		frame, more = frames.Next()
   195  		name := frame.Function
   196  		if len(name) > len(prefix) && name[:len(prefix)] == prefix {
   197  			methodName := name[len(prefix):]
   198  			if len(methodName) > 0 && 'A' <= methodName[0] && methodName[0] <= 'Z' {
   199  				return name
   200  			}
   201  		}
   202  	}
   203  	return "unknown method"
   204  }
   205  
   206  // nonEmptyInterface is the header for an interface value with methods.
   207  type nonEmptyInterface struct {
   208  	itab *abi.ITab
   209  	word unsafe.Pointer
   210  }
   211  
   212  // mustBe panics if f's kind is not expected.
   213  // Making this a method on flag instead of on Value
   214  // (and embedding flag in Value) means that we can write
   215  // the very clear v.mustBe(Bool) and have it compile into
   216  // v.flag.mustBe(Bool), which will only bother to copy the
   217  // single important word for the receiver.
   218  func (f flag) mustBe(expected Kind) {
   219  	// TODO(mvdan): use f.kind() again once mid-stack inlining gets better
   220  	if Kind(f&flagKindMask) != expected {
   221  		panic(&ValueError{valueMethodName(), f.kind()})
   222  	}
   223  }
   224  
   225  // mustBeExported panics if f records that the value was obtained using
   226  // an unexported field.
   227  func (f flag) mustBeExported() {
   228  	if f == 0 || f&flagRO != 0 {
   229  		f.mustBeExportedSlow()
   230  	}
   231  }
   232  
   233  func (f flag) mustBeExportedSlow() {
   234  	if f == 0 {
   235  		panic(&ValueError{valueMethodName(), Invalid})
   236  	}
   237  	if f&flagRO != 0 {
   238  		panic("reflect: " + valueMethodName() + " using value obtained using unexported field")
   239  	}
   240  }
   241  
   242  // mustBeAssignable panics if f records that the value is not assignable,
   243  // which is to say that either it was obtained using an unexported field
   244  // or it is not addressable.
   245  func (f flag) mustBeAssignable() {
   246  	if f&flagRO != 0 || f&flagAddr == 0 {
   247  		f.mustBeAssignableSlow()
   248  	}
   249  }
   250  
   251  func (f flag) mustBeAssignableSlow() {
   252  	if f == 0 {
   253  		panic(&ValueError{valueMethodName(), Invalid})
   254  	}
   255  	// Assignable if addressable and not read-only.
   256  	if f&flagRO != 0 {
   257  		panic("reflect: " + valueMethodName() + " using value obtained using unexported field")
   258  	}
   259  	if f&flagAddr == 0 {
   260  		panic("reflect: " + valueMethodName() + " using unaddressable value")
   261  	}
   262  }
   263  
   264  // Addr returns a pointer value representing the address of v.
   265  // It panics if [Value.CanAddr] returns false.
   266  // Addr is typically used to obtain a pointer to a struct field
   267  // or slice element in order to call a method that requires a
   268  // pointer receiver.
   269  func (v Value) Addr() Value {
   270  	if v.flag&flagAddr == 0 {
   271  		panic("reflect.Value.Addr of unaddressable value")
   272  	}
   273  	// Preserve flagRO instead of using v.flag.ro() so that
   274  	// v.Addr().Elem() is equivalent to v (#32772)
   275  	fl := v.flag & flagRO
   276  	return Value{ptrTo(v.typ()), v.ptr, fl | flag(Pointer)}
   277  }
   278  
   279  // Bool returns v's underlying value.
   280  // It panics if v's kind is not [Bool].
   281  func (v Value) Bool() bool {
   282  	// panicNotBool is split out to keep Bool inlineable.
   283  	if v.kind() != Bool {
   284  		v.panicNotBool()
   285  	}
   286  	return *(*bool)(v.ptr)
   287  }
   288  
   289  func (v Value) panicNotBool() {
   290  	v.mustBe(Bool)
   291  }
   292  
   293  var bytesType = rtypeOf(([]byte)(nil))
   294  
   295  // Bytes returns v's underlying value.
   296  // It panics if v's underlying value is not a slice of bytes or
   297  // an addressable array of bytes.
   298  func (v Value) Bytes() []byte {
   299  	// bytesSlow is split out to keep Bytes inlineable for unnamed []byte.
   300  	if v.typ_ == bytesType { // ok to use v.typ_ directly as comparison doesn't cause escape
   301  		return *(*[]byte)(v.ptr)
   302  	}
   303  	return v.bytesSlow()
   304  }
   305  
   306  func (v Value) bytesSlow() []byte {
   307  	switch v.kind() {
   308  	case Slice:
   309  		if v.typ().Elem().Kind() != abi.Uint8 {
   310  			panic("reflect.Value.Bytes of non-byte slice")
   311  		}
   312  		// Slice is always bigger than a word; assume flagIndir.
   313  		return *(*[]byte)(v.ptr)
   314  	case Array:
   315  		if v.typ().Elem().Kind() != abi.Uint8 {
   316  			panic("reflect.Value.Bytes of non-byte array")
   317  		}
   318  		if !v.CanAddr() {
   319  			panic("reflect.Value.Bytes of unaddressable byte array")
   320  		}
   321  		p := (*byte)(v.ptr)
   322  		n := int((*arrayType)(unsafe.Pointer(v.typ())).Len)
   323  		return unsafe.Slice(p, n)
   324  	}
   325  	panic(&ValueError{"reflect.Value.Bytes", v.kind()})
   326  }
   327  
   328  // runes returns v's underlying value.
   329  // It panics if v's underlying value is not a slice of runes (int32s).
   330  func (v Value) runes() []rune {
   331  	v.mustBe(Slice)
   332  	if v.typ().Elem().Kind() != abi.Int32 {
   333  		panic("reflect.Value.Bytes of non-rune slice")
   334  	}
   335  	// Slice is always bigger than a word; assume flagIndir.
   336  	return *(*[]rune)(v.ptr)
   337  }
   338  
   339  // CanAddr reports whether the value's address can be obtained with [Value.Addr].
   340  // Such values are called addressable. A value is addressable if it is
   341  // an element of a slice, an element of an addressable array,
   342  // a field of an addressable struct, or the result of dereferencing a pointer.
   343  // If CanAddr returns false, calling [Value.Addr] will panic.
   344  func (v Value) CanAddr() bool {
   345  	return v.flag&flagAddr != 0
   346  }
   347  
   348  // CanSet reports whether the value of v can be changed.
   349  // A [Value] can be changed only if it is addressable and was not
   350  // obtained by the use of unexported struct fields.
   351  // If CanSet returns false, calling [Value.Set] or any type-specific
   352  // setter (e.g., [Value.SetBool], [Value.SetInt]) will panic.
   353  func (v Value) CanSet() bool {
   354  	return v.flag&(flagAddr|flagRO) == flagAddr
   355  }
   356  
   357  // Call calls the function v with the input arguments in.
   358  // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
   359  // Call panics if v's Kind is not [Func].
   360  // It returns the output results as Values.
   361  // As in Go, each input argument must be assignable to the
   362  // type of the function's corresponding input parameter.
   363  // If v is a variadic function, Call creates the variadic slice parameter
   364  // itself, copying in the corresponding values.
   365  func (v Value) Call(in []Value) []Value {
   366  	v.mustBe(Func)
   367  	v.mustBeExported()
   368  	return v.call("Call", in)
   369  }
   370  
   371  // CallSlice calls the variadic function v with the input arguments in,
   372  // assigning the slice in[len(in)-1] to v's final variadic argument.
   373  // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
   374  // CallSlice panics if v's Kind is not [Func] or if v is not variadic.
   375  // It returns the output results as Values.
   376  // As in Go, each input argument must be assignable to the
   377  // type of the function's corresponding input parameter.
   378  func (v Value) CallSlice(in []Value) []Value {
   379  	v.mustBe(Func)
   380  	v.mustBeExported()
   381  	return v.call("CallSlice", in)
   382  }
   383  
   384  var callGC bool // for testing; see TestCallMethodJump and TestCallArgLive
   385  
   386  const debugReflectCall = false
   387  
   388  func (v Value) call(op string, in []Value) []Value {
   389  	// Get function pointer, type.
   390  	t := (*funcType)(unsafe.Pointer(v.typ()))
   391  	var (
   392  		fn       unsafe.Pointer
   393  		rcvr     Value
   394  		rcvrtype *abi.Type
   395  	)
   396  	if v.flag&flagMethod != 0 {
   397  		rcvr = v
   398  		rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
   399  	} else if v.flag&flagIndir != 0 {
   400  		fn = *(*unsafe.Pointer)(v.ptr)
   401  	} else {
   402  		fn = v.ptr
   403  	}
   404  
   405  	if fn == nil {
   406  		panic("reflect.Value.Call: call of nil function")
   407  	}
   408  
   409  	isSlice := op == "CallSlice"
   410  	n := t.NumIn()
   411  	isVariadic := t.IsVariadic()
   412  	if isSlice {
   413  		if !isVariadic {
   414  			panic("reflect: CallSlice of non-variadic function")
   415  		}
   416  		if len(in) < n {
   417  			panic("reflect: CallSlice with too few input arguments")
   418  		}
   419  		if len(in) > n {
   420  			panic("reflect: CallSlice with too many input arguments")
   421  		}
   422  	} else {
   423  		if isVariadic {
   424  			n--
   425  		}
   426  		if len(in) < n {
   427  			panic("reflect: Call with too few input arguments")
   428  		}
   429  		if !isVariadic && len(in) > n {
   430  			panic("reflect: Call with too many input arguments")
   431  		}
   432  	}
   433  	for _, x := range in {
   434  		if x.Kind() == Invalid {
   435  			panic("reflect: " + op + " using zero Value argument")
   436  		}
   437  	}
   438  	for i := 0; i < n; i++ {
   439  		if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(toRType(targ)) {
   440  			panic("reflect: " + op + " using " + xt.String() + " as type " + stringFor(targ))
   441  		}
   442  	}
   443  	if !isSlice && isVariadic {
   444  		// prepare slice for remaining values
   445  		m := len(in) - n
   446  		slice := MakeSlice(toRType(t.In(n)), m, m)
   447  		elem := toRType(t.In(n)).Elem() // FIXME cast to slice type and Elem()
   448  		for i := 0; i < m; i++ {
   449  			x := in[n+i]
   450  			if xt := x.Type(); !xt.AssignableTo(elem) {
   451  				panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
   452  			}
   453  			slice.Index(i).Set(x)
   454  		}
   455  		origIn := in
   456  		in = make([]Value, n+1)
   457  		copy(in[:n], origIn)
   458  		in[n] = slice
   459  	}
   460  
   461  	nin := len(in)
   462  	if nin != t.NumIn() {
   463  		panic("reflect.Value.Call: wrong argument count")
   464  	}
   465  	nout := t.NumOut()
   466  
   467  	// Register argument space.
   468  	var regArgs abi.RegArgs
   469  
   470  	// Compute frame type.
   471  	frametype, framePool, abid := funcLayout(t, rcvrtype)
   472  
   473  	// Allocate a chunk of memory for frame if needed.
   474  	var stackArgs unsafe.Pointer
   475  	if frametype.Size() != 0 {
   476  		if nout == 0 {
   477  			stackArgs = framePool.Get().(unsafe.Pointer)
   478  		} else {
   479  			// Can't use pool if the function has return values.
   480  			// We will leak pointer to args in ret, so its lifetime is not scoped.
   481  			stackArgs = unsafe_New(frametype)
   482  		}
   483  	}
   484  	frameSize := frametype.Size()
   485  
   486  	if debugReflectCall {
   487  		println("reflect.call", stringFor(&t.Type))
   488  		abid.dump()
   489  	}
   490  
   491  	// Copy inputs into args.
   492  
   493  	// Handle receiver.
   494  	inStart := 0
   495  	if rcvrtype != nil {
   496  		// Guaranteed to only be one word in size,
   497  		// so it will only take up exactly 1 abiStep (either
   498  		// in a register or on the stack).
   499  		switch st := abid.call.steps[0]; st.kind {
   500  		case abiStepStack:
   501  			storeRcvr(rcvr, stackArgs)
   502  		case abiStepPointer:
   503  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Ptrs[st.ireg]))
   504  			fallthrough
   505  		case abiStepIntReg:
   506  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Ints[st.ireg]))
   507  		case abiStepFloatReg:
   508  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Floats[st.freg]))
   509  		default:
   510  			panic("unknown ABI parameter kind")
   511  		}
   512  		inStart = 1
   513  	}
   514  
   515  	// Handle arguments.
   516  	for i, v := range in {
   517  		v.mustBeExported()
   518  		targ := toRType(t.In(i))
   519  		// TODO(mknyszek): Figure out if it's possible to get some
   520  		// scratch space for this assignment check. Previously, it
   521  		// was possible to use space in the argument frame.
   522  		v = v.assignTo("reflect.Value.Call", &targ.t, nil)
   523  	stepsLoop:
   524  		for _, st := range abid.call.stepsForValue(i + inStart) {
   525  			switch st.kind {
   526  			case abiStepStack:
   527  				// Copy values to the "stack."
   528  				addr := add(stackArgs, st.stkOff, "precomputed stack arg offset")
   529  				if v.flag&flagIndir != 0 {
   530  					typedmemmove(&targ.t, addr, v.ptr)
   531  				} else {
   532  					*(*unsafe.Pointer)(addr) = v.ptr
   533  				}
   534  				// There's only one step for a stack-allocated value.
   535  				break stepsLoop
   536  			case abiStepIntReg, abiStepPointer:
   537  				// Copy values to "integer registers."
   538  				if v.flag&flagIndir != 0 {
   539  					offset := add(v.ptr, st.offset, "precomputed value offset")
   540  					if st.kind == abiStepPointer {
   541  						// Duplicate this pointer in the pointer area of the
   542  						// register space. Otherwise, there's the potential for
   543  						// this to be the last reference to v.ptr.
   544  						regArgs.Ptrs[st.ireg] = *(*unsafe.Pointer)(offset)
   545  					}
   546  					intToReg(&regArgs, st.ireg, st.size, offset)
   547  				} else {
   548  					if st.kind == abiStepPointer {
   549  						// See the comment in abiStepPointer case above.
   550  						regArgs.Ptrs[st.ireg] = v.ptr
   551  					}
   552  					regArgs.Ints[st.ireg] = uintptr(v.ptr)
   553  				}
   554  			case abiStepFloatReg:
   555  				// Copy values to "float registers."
   556  				if v.flag&flagIndir == 0 {
   557  					panic("attempted to copy pointer to FP register")
   558  				}
   559  				offset := add(v.ptr, st.offset, "precomputed value offset")
   560  				floatToReg(&regArgs, st.freg, st.size, offset)
   561  			default:
   562  				panic("unknown ABI part kind")
   563  			}
   564  		}
   565  	}
   566  	// TODO(mknyszek): Remove this when we no longer have
   567  	// caller reserved spill space.
   568  	frameSize = align(frameSize, goarch.PtrSize)
   569  	frameSize += abid.spill
   570  
   571  	// Mark pointers in registers for the return path.
   572  	regArgs.ReturnIsPtr = abid.outRegPtrs
   573  
   574  	if debugReflectCall {
   575  		regArgs.Dump()
   576  	}
   577  
   578  	// For testing; see TestCallArgLive.
   579  	if callGC {
   580  		runtime.GC()
   581  	}
   582  
   583  	// Call.
   584  	call(frametype, fn, stackArgs, uint32(frametype.Size()), uint32(abid.retOffset), uint32(frameSize), &regArgs)
   585  
   586  	// For testing; see TestCallMethodJump.
   587  	if callGC {
   588  		runtime.GC()
   589  	}
   590  
   591  	var ret []Value
   592  	if nout == 0 {
   593  		if stackArgs != nil {
   594  			typedmemclr(frametype, stackArgs)
   595  			framePool.Put(stackArgs)
   596  		}
   597  	} else {
   598  		if stackArgs != nil {
   599  			// Zero the now unused input area of args,
   600  			// because the Values returned by this function contain pointers to the args object,
   601  			// and will thus keep the args object alive indefinitely.
   602  			typedmemclrpartial(frametype, stackArgs, 0, abid.retOffset)
   603  		}
   604  
   605  		// Wrap Values around return values in args.
   606  		ret = make([]Value, nout)
   607  		for i := 0; i < nout; i++ {
   608  			tv := t.Out(i)
   609  			if tv.Size() == 0 {
   610  				// For zero-sized return value, args+off may point to the next object.
   611  				// In this case, return the zero value instead.
   612  				ret[i] = Zero(toRType(tv))
   613  				continue
   614  			}
   615  			steps := abid.ret.stepsForValue(i)
   616  			if st := steps[0]; st.kind == abiStepStack {
   617  				// This value is on the stack. If part of a value is stack
   618  				// allocated, the entire value is according to the ABI. So
   619  				// just make an indirection into the allocated frame.
   620  				fl := flagIndir | flag(tv.Kind())
   621  				ret[i] = Value{tv, add(stackArgs, st.stkOff, "tv.Size() != 0"), fl}
   622  				// Note: this does introduce false sharing between results -
   623  				// if any result is live, they are all live.
   624  				// (And the space for the args is live as well, but as we've
   625  				// cleared that space it isn't as big a deal.)
   626  				continue
   627  			}
   628  
   629  			// Handle pointers passed in registers.
   630  			if !tv.IfaceIndir() {
   631  				// Pointer-valued data gets put directly
   632  				// into v.ptr.
   633  				if steps[0].kind != abiStepPointer {
   634  					print("kind=", steps[0].kind, ", type=", stringFor(tv), "\n")
   635  					panic("mismatch between ABI description and types")
   636  				}
   637  				ret[i] = Value{tv, regArgs.Ptrs[steps[0].ireg], flag(tv.Kind())}
   638  				continue
   639  			}
   640  
   641  			// All that's left is values passed in registers that we need to
   642  			// create space for and copy values back into.
   643  			//
   644  			// TODO(mknyszek): We make a new allocation for each register-allocated
   645  			// value, but previously we could always point into the heap-allocated
   646  			// stack frame. This is a regression that could be fixed by adding
   647  			// additional space to the allocated stack frame and storing the
   648  			// register-allocated return values into the allocated stack frame and
   649  			// referring there in the resulting Value.
   650  			s := unsafe_New(tv)
   651  			for _, st := range steps {
   652  				switch st.kind {
   653  				case abiStepIntReg:
   654  					offset := add(s, st.offset, "precomputed value offset")
   655  					intFromReg(&regArgs, st.ireg, st.size, offset)
   656  				case abiStepPointer:
   657  					s := add(s, st.offset, "precomputed value offset")
   658  					*((*unsafe.Pointer)(s)) = regArgs.Ptrs[st.ireg]
   659  				case abiStepFloatReg:
   660  					offset := add(s, st.offset, "precomputed value offset")
   661  					floatFromReg(&regArgs, st.freg, st.size, offset)
   662  				case abiStepStack:
   663  					panic("register-based return value has stack component")
   664  				default:
   665  					panic("unknown ABI part kind")
   666  				}
   667  			}
   668  			ret[i] = Value{tv, s, flagIndir | flag(tv.Kind())}
   669  		}
   670  	}
   671  
   672  	return ret
   673  }
   674  
   675  // callReflect is the call implementation used by a function
   676  // returned by MakeFunc. In many ways it is the opposite of the
   677  // method Value.call above. The method above converts a call using Values
   678  // into a call of a function with a concrete argument frame, while
   679  // callReflect converts a call of a function with a concrete argument
   680  // frame into a call using Values.
   681  // It is in this file so that it can be next to the call method above.
   682  // The remainder of the MakeFunc implementation is in makefunc.go.
   683  //
   684  // NOTE: This function must be marked as a "wrapper" in the generated code,
   685  // so that the linker can make it work correctly for panic and recover.
   686  // The gc compilers know to do that for the name "reflect.callReflect".
   687  //
   688  // ctxt is the "closure" generated by MakeFunc.
   689  // frame is a pointer to the arguments to that closure on the stack.
   690  // retValid points to a boolean which should be set when the results
   691  // section of frame is set.
   692  //
   693  // regs contains the argument values passed in registers and will contain
   694  // the values returned from ctxt.fn in registers.
   695  func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer, retValid *bool, regs *abi.RegArgs) {
   696  	if callGC {
   697  		// Call GC upon entry during testing.
   698  		// Getting our stack scanned here is the biggest hazard, because
   699  		// our caller (makeFuncStub) could have failed to place the last
   700  		// pointer to a value in regs' pointer space, in which case it
   701  		// won't be visible to the GC.
   702  		runtime.GC()
   703  	}
   704  	ftyp := ctxt.ftyp
   705  	f := ctxt.fn
   706  
   707  	_, _, abid := funcLayout(ftyp, nil)
   708  
   709  	// Copy arguments into Values.
   710  	ptr := frame
   711  	in := make([]Value, 0, int(ftyp.InCount))
   712  	for i, typ := range ftyp.InSlice() {
   713  		if typ.Size() == 0 {
   714  			in = append(in, Zero(toRType(typ)))
   715  			continue
   716  		}
   717  		v := Value{typ, nil, flag(typ.Kind())}
   718  		steps := abid.call.stepsForValue(i)
   719  		if st := steps[0]; st.kind == abiStepStack {
   720  			if typ.IfaceIndir() {
   721  				// value cannot be inlined in interface data.
   722  				// Must make a copy, because f might keep a reference to it,
   723  				// and we cannot let f keep a reference to the stack frame
   724  				// after this function returns, not even a read-only reference.
   725  				v.ptr = unsafe_New(typ)
   726  				if typ.Size() > 0 {
   727  					typedmemmove(typ, v.ptr, add(ptr, st.stkOff, "typ.size > 0"))
   728  				}
   729  				v.flag |= flagIndir
   730  			} else {
   731  				v.ptr = *(*unsafe.Pointer)(add(ptr, st.stkOff, "1-ptr"))
   732  			}
   733  		} else {
   734  			if typ.IfaceIndir() {
   735  				// All that's left is values passed in registers that we need to
   736  				// create space for the values.
   737  				v.flag |= flagIndir
   738  				v.ptr = unsafe_New(typ)
   739  				for _, st := range steps {
   740  					switch st.kind {
   741  					case abiStepIntReg:
   742  						offset := add(v.ptr, st.offset, "precomputed value offset")
   743  						intFromReg(regs, st.ireg, st.size, offset)
   744  					case abiStepPointer:
   745  						s := add(v.ptr, st.offset, "precomputed value offset")
   746  						*((*unsafe.Pointer)(s)) = regs.Ptrs[st.ireg]
   747  					case abiStepFloatReg:
   748  						offset := add(v.ptr, st.offset, "precomputed value offset")
   749  						floatFromReg(regs, st.freg, st.size, offset)
   750  					case abiStepStack:
   751  						panic("register-based return value has stack component")
   752  					default:
   753  						panic("unknown ABI part kind")
   754  					}
   755  				}
   756  			} else {
   757  				// Pointer-valued data gets put directly
   758  				// into v.ptr.
   759  				if steps[0].kind != abiStepPointer {
   760  					print("kind=", steps[0].kind, ", type=", stringFor(typ), "\n")
   761  					panic("mismatch between ABI description and types")
   762  				}
   763  				v.ptr = regs.Ptrs[steps[0].ireg]
   764  			}
   765  		}
   766  		in = append(in, v)
   767  	}
   768  
   769  	// Call underlying function.
   770  	out := f(in)
   771  	numOut := ftyp.NumOut()
   772  	if len(out) != numOut {
   773  		panic("reflect: wrong return count from function created by MakeFunc")
   774  	}
   775  
   776  	// Copy results back into argument frame and register space.
   777  	if numOut > 0 {
   778  		for i, typ := range ftyp.OutSlice() {
   779  			v := out[i]
   780  			if v.typ() == nil {
   781  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   782  					" returned zero Value")
   783  			}
   784  			if v.flag&flagRO != 0 {
   785  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   786  					" returned value obtained from unexported field")
   787  			}
   788  			if typ.Size() == 0 {
   789  				continue
   790  			}
   791  
   792  			// Convert v to type typ if v is assignable to a variable
   793  			// of type t in the language spec.
   794  			// See issue 28761.
   795  			//
   796  			//
   797  			// TODO(mknyszek): In the switch to the register ABI we lost
   798  			// the scratch space here for the register cases (and
   799  			// temporarily for all the cases).
   800  			//
   801  			// If/when this happens, take note of the following:
   802  			//
   803  			// We must clear the destination before calling assignTo,
   804  			// in case assignTo writes (with memory barriers) to the
   805  			// target location used as scratch space. See issue 39541.
   806  			v = v.assignTo("reflect.MakeFunc", typ, nil)
   807  		stepsLoop:
   808  			for _, st := range abid.ret.stepsForValue(i) {
   809  				switch st.kind {
   810  				case abiStepStack:
   811  					// Copy values to the "stack."
   812  					addr := add(ptr, st.stkOff, "precomputed stack arg offset")
   813  					// Do not use write barriers. The stack space used
   814  					// for this call is not adequately zeroed, and we
   815  					// are careful to keep the arguments alive until we
   816  					// return to makeFuncStub's caller.
   817  					if v.flag&flagIndir != 0 {
   818  						memmove(addr, v.ptr, st.size)
   819  					} else {
   820  						// This case must be a pointer type.
   821  						*(*uintptr)(addr) = uintptr(v.ptr)
   822  					}
   823  					// There's only one step for a stack-allocated value.
   824  					break stepsLoop
   825  				case abiStepIntReg, abiStepPointer:
   826  					// Copy values to "integer registers."
   827  					if v.flag&flagIndir != 0 {
   828  						offset := add(v.ptr, st.offset, "precomputed value offset")
   829  						intToReg(regs, st.ireg, st.size, offset)
   830  					} else {
   831  						// Only populate the Ints space on the return path.
   832  						// This is safe because out is kept alive until the
   833  						// end of this function, and the return path through
   834  						// makeFuncStub has no preemption, so these pointers
   835  						// are always visible to the GC.
   836  						regs.Ints[st.ireg] = uintptr(v.ptr)
   837  					}
   838  				case abiStepFloatReg:
   839  					// Copy values to "float registers."
   840  					if v.flag&flagIndir == 0 {
   841  						panic("attempted to copy pointer to FP register")
   842  					}
   843  					offset := add(v.ptr, st.offset, "precomputed value offset")
   844  					floatToReg(regs, st.freg, st.size, offset)
   845  				default:
   846  					panic("unknown ABI part kind")
   847  				}
   848  			}
   849  		}
   850  	}
   851  
   852  	// Announce that the return values are valid.
   853  	// After this point the runtime can depend on the return values being valid.
   854  	*retValid = true
   855  
   856  	// We have to make sure that the out slice lives at least until
   857  	// the runtime knows the return values are valid. Otherwise, the
   858  	// return values might not be scanned by anyone during a GC.
   859  	// (out would be dead, and the return slots not yet alive.)
   860  	runtime.KeepAlive(out)
   861  
   862  	// runtime.getArgInfo expects to be able to find ctxt on the
   863  	// stack when it finds our caller, makeFuncStub. Make sure it
   864  	// doesn't get garbage collected.
   865  	runtime.KeepAlive(ctxt)
   866  }
   867  
   868  // methodReceiver returns information about the receiver
   869  // described by v. The Value v may or may not have the
   870  // flagMethod bit set, so the kind cached in v.flag should
   871  // not be used.
   872  // The return value rcvrtype gives the method's actual receiver type.
   873  // The return value t gives the method type signature (without the receiver).
   874  // The return value fn is a pointer to the method code.
   875  func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *abi.Type, t *funcType, fn unsafe.Pointer) {
   876  	i := methodIndex
   877  	if v.typ().Kind() == abi.Interface {
   878  		tt := (*interfaceType)(unsafe.Pointer(v.typ()))
   879  		if uint(i) >= uint(len(tt.Methods)) {
   880  			panic("reflect: internal error: invalid method index")
   881  		}
   882  		m := &tt.Methods[i]
   883  		if !tt.nameOff(m.Name).IsExported() {
   884  			panic("reflect: " + op + " of unexported method")
   885  		}
   886  		iface := (*nonEmptyInterface)(v.ptr)
   887  		if iface.itab == nil {
   888  			panic("reflect: " + op + " of method on nil interface value")
   889  		}
   890  		rcvrtype = iface.itab.Type
   891  		fn = unsafe.Pointer(&unsafe.Slice(&iface.itab.Fun[0], i+1)[i])
   892  		t = (*funcType)(unsafe.Pointer(tt.typeOff(m.Typ)))
   893  	} else {
   894  		rcvrtype = v.typ()
   895  		ms := v.typ().ExportedMethods()
   896  		if uint(i) >= uint(len(ms)) {
   897  			panic("reflect: internal error: invalid method index")
   898  		}
   899  		m := ms[i]
   900  		if !nameOffFor(v.typ(), m.Name).IsExported() {
   901  			panic("reflect: " + op + " of unexported method")
   902  		}
   903  		ifn := textOffFor(v.typ(), m.Ifn)
   904  		fn = unsafe.Pointer(&ifn)
   905  		t = (*funcType)(unsafe.Pointer(typeOffFor(v.typ(), m.Mtyp)))
   906  	}
   907  	return
   908  }
   909  
   910  // v is a method receiver. Store at p the word which is used to
   911  // encode that receiver at the start of the argument list.
   912  // Reflect uses the "interface" calling convention for
   913  // methods, which always uses one word to record the receiver.
   914  func storeRcvr(v Value, p unsafe.Pointer) {
   915  	t := v.typ()
   916  	if t.Kind() == abi.Interface {
   917  		// the interface data word becomes the receiver word
   918  		iface := (*nonEmptyInterface)(v.ptr)
   919  		*(*unsafe.Pointer)(p) = iface.word
   920  	} else if v.flag&flagIndir != 0 && !t.IfaceIndir() {
   921  		*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
   922  	} else {
   923  		*(*unsafe.Pointer)(p) = v.ptr
   924  	}
   925  }
   926  
   927  // align returns the result of rounding x up to a multiple of n.
   928  // n must be a power of two.
   929  func align(x, n uintptr) uintptr {
   930  	return (x + n - 1) &^ (n - 1)
   931  }
   932  
   933  // callMethod is the call implementation used by a function returned
   934  // by makeMethodValue (used by v.Method(i).Interface()).
   935  // It is a streamlined version of the usual reflect call: the caller has
   936  // already laid out the argument frame for us, so we don't have
   937  // to deal with individual Values for each argument.
   938  // It is in this file so that it can be next to the two similar functions above.
   939  // The remainder of the makeMethodValue implementation is in makefunc.go.
   940  //
   941  // NOTE: This function must be marked as a "wrapper" in the generated code,
   942  // so that the linker can make it work correctly for panic and recover.
   943  // The gc compilers know to do that for the name "reflect.callMethod".
   944  //
   945  // ctxt is the "closure" generated by makeMethodValue.
   946  // frame is a pointer to the arguments to that closure on the stack.
   947  // retValid points to a boolean which should be set when the results
   948  // section of frame is set.
   949  //
   950  // regs contains the argument values passed in registers and will contain
   951  // the values returned from ctxt.fn in registers.
   952  func callMethod(ctxt *methodValue, frame unsafe.Pointer, retValid *bool, regs *abi.RegArgs) {
   953  	rcvr := ctxt.rcvr
   954  	rcvrType, valueFuncType, methodFn := methodReceiver("call", rcvr, ctxt.method)
   955  
   956  	// There are two ABIs at play here.
   957  	//
   958  	// methodValueCall was invoked with the ABI assuming there was no
   959  	// receiver ("value ABI") and that's what frame and regs are holding.
   960  	//
   961  	// Meanwhile, we need to actually call the method with a receiver, which
   962  	// has its own ABI ("method ABI"). Everything that follows is a translation
   963  	// between the two.
   964  	_, _, valueABI := funcLayout(valueFuncType, nil)
   965  	valueFrame, valueRegs := frame, regs
   966  	methodFrameType, methodFramePool, methodABI := funcLayout(valueFuncType, rcvrType)
   967  
   968  	// Make a new frame that is one word bigger so we can store the receiver.
   969  	// This space is used for both arguments and return values.
   970  	methodFrame := methodFramePool.Get().(unsafe.Pointer)
   971  	var methodRegs abi.RegArgs
   972  
   973  	// Deal with the receiver. It's guaranteed to only be one word in size.
   974  	switch st := methodABI.call.steps[0]; st.kind {
   975  	case abiStepStack:
   976  		// Only copy the receiver to the stack if the ABI says so.
   977  		// Otherwise, it'll be in a register already.
   978  		storeRcvr(rcvr, methodFrame)
   979  	case abiStepPointer:
   980  		// Put the receiver in a register.
   981  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Ptrs[st.ireg]))
   982  		fallthrough
   983  	case abiStepIntReg:
   984  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Ints[st.ireg]))
   985  	case abiStepFloatReg:
   986  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Floats[st.freg]))
   987  	default:
   988  		panic("unknown ABI parameter kind")
   989  	}
   990  
   991  	// Translate the rest of the arguments.
   992  	for i, t := range valueFuncType.InSlice() {
   993  		valueSteps := valueABI.call.stepsForValue(i)
   994  		methodSteps := methodABI.call.stepsForValue(i + 1)
   995  
   996  		// Zero-sized types are trivial: nothing to do.
   997  		if len(valueSteps) == 0 {
   998  			if len(methodSteps) != 0 {
   999  				panic("method ABI and value ABI do not align")
  1000  			}
  1001  			continue
  1002  		}
  1003  
  1004  		// There are four cases to handle in translating each
  1005  		// argument:
  1006  		// 1. Stack -> stack translation.
  1007  		// 2. Stack -> registers translation.
  1008  		// 3. Registers -> stack translation.
  1009  		// 4. Registers -> registers translation.
  1010  
  1011  		// If the value ABI passes the value on the stack,
  1012  		// then the method ABI does too, because it has strictly
  1013  		// fewer arguments. Simply copy between the two.
  1014  		if vStep := valueSteps[0]; vStep.kind == abiStepStack {
  1015  			mStep := methodSteps[0]
  1016  			// Handle stack -> stack translation.
  1017  			if mStep.kind == abiStepStack {
  1018  				if vStep.size != mStep.size {
  1019  					panic("method ABI and value ABI do not align")
  1020  				}
  1021  				typedmemmove(t,
  1022  					add(methodFrame, mStep.stkOff, "precomputed stack offset"),
  1023  					add(valueFrame, vStep.stkOff, "precomputed stack offset"))
  1024  				continue
  1025  			}
  1026  			// Handle stack -> register translation.
  1027  			for _, mStep := range methodSteps {
  1028  				from := add(valueFrame, vStep.stkOff+mStep.offset, "precomputed stack offset")
  1029  				switch mStep.kind {
  1030  				case abiStepPointer:
  1031  					// Do the pointer copy directly so we get a write barrier.
  1032  					methodRegs.Ptrs[mStep.ireg] = *(*unsafe.Pointer)(from)
  1033  					fallthrough // We need to make sure this ends up in Ints, too.
  1034  				case abiStepIntReg:
  1035  					intToReg(&methodRegs, mStep.ireg, mStep.size, from)
  1036  				case abiStepFloatReg:
  1037  					floatToReg(&methodRegs, mStep.freg, mStep.size, from)
  1038  				default:
  1039  					panic("unexpected method step")
  1040  				}
  1041  			}
  1042  			continue
  1043  		}
  1044  		// Handle register -> stack translation.
  1045  		if mStep := methodSteps[0]; mStep.kind == abiStepStack {
  1046  			for _, vStep := range valueSteps {
  1047  				to := add(methodFrame, mStep.stkOff+vStep.offset, "precomputed stack offset")
  1048  				switch vStep.kind {
  1049  				case abiStepPointer:
  1050  					// Do the pointer copy directly so we get a write barrier.
  1051  					*(*unsafe.Pointer)(to) = valueRegs.Ptrs[vStep.ireg]
  1052  				case abiStepIntReg:
  1053  					intFromReg(valueRegs, vStep.ireg, vStep.size, to)
  1054  				case abiStepFloatReg:
  1055  					floatFromReg(valueRegs, vStep.freg, vStep.size, to)
  1056  				default:
  1057  					panic("unexpected value step")
  1058  				}
  1059  			}
  1060  			continue
  1061  		}
  1062  		// Handle register -> register translation.
  1063  		if len(valueSteps) != len(methodSteps) {
  1064  			// Because it's the same type for the value, and it's assigned
  1065  			// to registers both times, it should always take up the same
  1066  			// number of registers for each ABI.
  1067  			panic("method ABI and value ABI don't align")
  1068  		}
  1069  		for i, vStep := range valueSteps {
  1070  			mStep := methodSteps[i]
  1071  			if mStep.kind != vStep.kind {
  1072  				panic("method ABI and value ABI don't align")
  1073  			}
  1074  			switch vStep.kind {
  1075  			case abiStepPointer:
  1076  				// Copy this too, so we get a write barrier.
  1077  				methodRegs.Ptrs[mStep.ireg] = valueRegs.Ptrs[vStep.ireg]
  1078  				fallthrough
  1079  			case abiStepIntReg:
  1080  				methodRegs.Ints[mStep.ireg] = valueRegs.Ints[vStep.ireg]
  1081  			case abiStepFloatReg:
  1082  				methodRegs.Floats[mStep.freg] = valueRegs.Floats[vStep.freg]
  1083  			default:
  1084  				panic("unexpected value step")
  1085  			}
  1086  		}
  1087  	}
  1088  
  1089  	methodFrameSize := methodFrameType.Size()
  1090  	// TODO(mknyszek): Remove this when we no longer have
  1091  	// caller reserved spill space.
  1092  	methodFrameSize = align(methodFrameSize, goarch.PtrSize)
  1093  	methodFrameSize += methodABI.spill
  1094  
  1095  	// Mark pointers in registers for the return path.
  1096  	methodRegs.ReturnIsPtr = methodABI.outRegPtrs
  1097  
  1098  	// Call.
  1099  	// Call copies the arguments from scratch to the stack, calls fn,
  1100  	// and then copies the results back into scratch.
  1101  	call(methodFrameType, methodFn, methodFrame, uint32(methodFrameType.Size()), uint32(methodABI.retOffset), uint32(methodFrameSize), &methodRegs)
  1102  
  1103  	// Copy return values.
  1104  	//
  1105  	// This is somewhat simpler because both ABIs have an identical
  1106  	// return value ABI (the types are identical). As a result, register
  1107  	// results can simply be copied over. Stack-allocated values are laid
  1108  	// out the same, but are at different offsets from the start of the frame
  1109  	// Ignore any changes to args.
  1110  	// Avoid constructing out-of-bounds pointers if there are no return values.
  1111  	// because the arguments may be laid out differently.
  1112  	if valueRegs != nil {
  1113  		*valueRegs = methodRegs
  1114  	}
  1115  	if retSize := methodFrameType.Size() - methodABI.retOffset; retSize > 0 {
  1116  		valueRet := add(valueFrame, valueABI.retOffset, "valueFrame's size > retOffset")
  1117  		methodRet := add(methodFrame, methodABI.retOffset, "methodFrame's size > retOffset")
  1118  		// This copies to the stack. Write barriers are not needed.
  1119  		memmove(valueRet, methodRet, retSize)
  1120  	}
  1121  
  1122  	// Tell the runtime it can now depend on the return values
  1123  	// being properly initialized.
  1124  	*retValid = true
  1125  
  1126  	// Clear the scratch space and put it back in the pool.
  1127  	// This must happen after the statement above, so that the return
  1128  	// values will always be scanned by someone.
  1129  	typedmemclr(methodFrameType, methodFrame)
  1130  	methodFramePool.Put(methodFrame)
  1131  
  1132  	// See the comment in callReflect.
  1133  	runtime.KeepAlive(ctxt)
  1134  
  1135  	// Keep valueRegs alive because it may hold live pointer results.
  1136  	// The caller (methodValueCall) has it as a stack object, which is only
  1137  	// scanned when there is a reference to it.
  1138  	runtime.KeepAlive(valueRegs)
  1139  }
  1140  
  1141  // funcName returns the name of f, for use in error messages.
  1142  func funcName(f func([]Value) []Value) string {
  1143  	pc := *(*uintptr)(unsafe.Pointer(&f))
  1144  	rf := runtime.FuncForPC(pc)
  1145  	if rf != nil {
  1146  		return rf.Name()
  1147  	}
  1148  	return "closure"
  1149  }
  1150  
  1151  // Cap returns v's capacity.
  1152  // It panics if v's Kind is not [Array], [Chan], [Slice] or pointer to [Array].
  1153  func (v Value) Cap() int {
  1154  	// capNonSlice is split out to keep Cap inlineable for slice kinds.
  1155  	if v.kind() == Slice {
  1156  		return (*unsafeheader.Slice)(v.ptr).Cap
  1157  	}
  1158  	return v.capNonSlice()
  1159  }
  1160  
  1161  func (v Value) capNonSlice() int {
  1162  	k := v.kind()
  1163  	switch k {
  1164  	case Array:
  1165  		return v.typ().Len()
  1166  	case Chan:
  1167  		return chancap(v.pointer())
  1168  	case Ptr:
  1169  		if v.typ().Elem().Kind() == abi.Array {
  1170  			return v.typ().Elem().Len()
  1171  		}
  1172  		panic("reflect: call of reflect.Value.Cap on ptr to non-array Value")
  1173  	}
  1174  	panic(&ValueError{"reflect.Value.Cap", v.kind()})
  1175  }
  1176  
  1177  // Close closes the channel v.
  1178  // It panics if v's Kind is not [Chan] or
  1179  // v is a receive-only channel.
  1180  func (v Value) Close() {
  1181  	v.mustBe(Chan)
  1182  	v.mustBeExported()
  1183  	tt := (*chanType)(unsafe.Pointer(v.typ()))
  1184  	if ChanDir(tt.Dir)&SendDir == 0 {
  1185  		panic("reflect: close of receive-only channel")
  1186  	}
  1187  
  1188  	chanclose(v.pointer())
  1189  }
  1190  
  1191  // CanComplex reports whether [Value.Complex] can be used without panicking.
  1192  func (v Value) CanComplex() bool {
  1193  	switch v.kind() {
  1194  	case Complex64, Complex128:
  1195  		return true
  1196  	default:
  1197  		return false
  1198  	}
  1199  }
  1200  
  1201  // Complex returns v's underlying value, as a complex128.
  1202  // It panics if v's Kind is not [Complex64] or [Complex128]
  1203  func (v Value) Complex() complex128 {
  1204  	k := v.kind()
  1205  	switch k {
  1206  	case Complex64:
  1207  		return complex128(*(*complex64)(v.ptr))
  1208  	case Complex128:
  1209  		return *(*complex128)(v.ptr)
  1210  	}
  1211  	panic(&ValueError{"reflect.Value.Complex", v.kind()})
  1212  }
  1213  
  1214  // Elem returns the value that the interface v contains
  1215  // or that the pointer v points to.
  1216  // It panics if v's Kind is not [Interface] or [Pointer].
  1217  // It returns the zero Value if v is nil.
  1218  func (v Value) Elem() Value {
  1219  	k := v.kind()
  1220  	switch k {
  1221  	case Interface:
  1222  		var eface any
  1223  		if v.typ().NumMethod() == 0 {
  1224  			eface = *(*any)(v.ptr)
  1225  		} else {
  1226  			eface = (any)(*(*interface {
  1227  				M()
  1228  			})(v.ptr))
  1229  		}
  1230  		x := unpackEface(eface)
  1231  		if x.flag != 0 {
  1232  			x.flag |= v.flag.ro()
  1233  		}
  1234  		return x
  1235  	case Pointer:
  1236  		ptr := v.ptr
  1237  		if v.flag&flagIndir != 0 {
  1238  			if v.typ().IfaceIndir() {
  1239  				// This is a pointer to a not-in-heap object. ptr points to a uintptr
  1240  				// in the heap. That uintptr is the address of a not-in-heap object.
  1241  				// In general, pointers to not-in-heap objects can be total junk.
  1242  				// But Elem() is asking to dereference it, so the user has asserted
  1243  				// that at least it is a valid pointer (not just an integer stored in
  1244  				// a pointer slot). So let's check, to make sure that it isn't a pointer
  1245  				// that the runtime will crash on if it sees it during GC or write barriers.
  1246  				// Since it is a not-in-heap pointer, all pointers to the heap are
  1247  				// forbidden! That makes the test pretty easy.
  1248  				// See issue 48399.
  1249  				if !verifyNotInHeapPtr(*(*uintptr)(ptr)) {
  1250  					panic("reflect: reflect.Value.Elem on an invalid notinheap pointer")
  1251  				}
  1252  			}
  1253  			ptr = *(*unsafe.Pointer)(ptr)
  1254  		}
  1255  		// The returned value's address is v's value.
  1256  		if ptr == nil {
  1257  			return Value{}
  1258  		}
  1259  		tt := (*ptrType)(unsafe.Pointer(v.typ()))
  1260  		typ := tt.Elem
  1261  		fl := v.flag&flagRO | flagIndir | flagAddr
  1262  		fl |= flag(typ.Kind())
  1263  		return Value{typ, ptr, fl}
  1264  	}
  1265  	panic(&ValueError{"reflect.Value.Elem", v.kind()})
  1266  }
  1267  
  1268  // Field returns the i'th field of the struct v.
  1269  // It panics if v's Kind is not [Struct] or i is out of range.
  1270  func (v Value) Field(i int) Value {
  1271  	if v.kind() != Struct {
  1272  		panic(&ValueError{"reflect.Value.Field", v.kind()})
  1273  	}
  1274  	tt := (*structType)(unsafe.Pointer(v.typ()))
  1275  	if uint(i) >= uint(len(tt.Fields)) {
  1276  		panic("reflect: Field index out of range")
  1277  	}
  1278  	field := &tt.Fields[i]
  1279  	typ := field.Typ
  1280  
  1281  	// Inherit permission bits from v, but clear flagEmbedRO.
  1282  	fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
  1283  	// Using an unexported field forces flagRO.
  1284  	if !field.Name.IsExported() {
  1285  		if field.Embedded() {
  1286  			fl |= flagEmbedRO
  1287  		} else {
  1288  			fl |= flagStickyRO
  1289  		}
  1290  	}
  1291  	// Either flagIndir is set and v.ptr points at struct,
  1292  	// or flagIndir is not set and v.ptr is the actual struct data.
  1293  	// In the former case, we want v.ptr + offset.
  1294  	// In the latter case, we must have field.offset = 0,
  1295  	// so v.ptr + field.offset is still the correct address.
  1296  	ptr := add(v.ptr, field.Offset, "same as non-reflect &v.field")
  1297  	return Value{typ, ptr, fl}
  1298  }
  1299  
  1300  // FieldByIndex returns the nested field corresponding to index.
  1301  // It panics if evaluation requires stepping through a nil
  1302  // pointer or a field that is not a struct.
  1303  func (v Value) FieldByIndex(index []int) Value {
  1304  	if len(index) == 1 {
  1305  		return v.Field(index[0])
  1306  	}
  1307  	v.mustBe(Struct)
  1308  	for i, x := range index {
  1309  		if i > 0 {
  1310  			if v.Kind() == Pointer && v.typ().Elem().Kind() == abi.Struct {
  1311  				if v.IsNil() {
  1312  					panic("reflect: indirection through nil pointer to embedded struct")
  1313  				}
  1314  				v = v.Elem()
  1315  			}
  1316  		}
  1317  		v = v.Field(x)
  1318  	}
  1319  	return v
  1320  }
  1321  
  1322  // FieldByIndexErr returns the nested field corresponding to index.
  1323  // It returns an error if evaluation requires stepping through a nil
  1324  // pointer, but panics if it must step through a field that
  1325  // is not a struct.
  1326  func (v Value) FieldByIndexErr(index []int) (Value, error) {
  1327  	if len(index) == 1 {
  1328  		return v.Field(index[0]), nil
  1329  	}
  1330  	v.mustBe(Struct)
  1331  	for i, x := range index {
  1332  		if i > 0 {
  1333  			if v.Kind() == Ptr && v.typ().Elem().Kind() == abi.Struct {
  1334  				if v.IsNil() {
  1335  					return Value{}, errors.New("reflect: indirection through nil pointer to embedded struct field " + nameFor(v.typ().Elem()))
  1336  				}
  1337  				v = v.Elem()
  1338  			}
  1339  		}
  1340  		v = v.Field(x)
  1341  	}
  1342  	return v, nil
  1343  }
  1344  
  1345  // FieldByName returns the struct field with the given name.
  1346  // It returns the zero Value if no field was found.
  1347  // It panics if v's Kind is not [Struct].
  1348  func (v Value) FieldByName(name string) Value {
  1349  	v.mustBe(Struct)
  1350  	if f, ok := toRType(v.typ()).FieldByName(name); ok {
  1351  		return v.FieldByIndex(f.Index)
  1352  	}
  1353  	return Value{}
  1354  }
  1355  
  1356  // FieldByNameFunc returns the struct field with a name
  1357  // that satisfies the match function.
  1358  // It panics if v's Kind is not [Struct].
  1359  // It returns the zero Value if no field was found.
  1360  func (v Value) FieldByNameFunc(match func(string) bool) Value {
  1361  	if f, ok := toRType(v.typ()).FieldByNameFunc(match); ok {
  1362  		return v.FieldByIndex(f.Index)
  1363  	}
  1364  	return Value{}
  1365  }
  1366  
  1367  // CanFloat reports whether [Value.Float] can be used without panicking.
  1368  func (v Value) CanFloat() bool {
  1369  	switch v.kind() {
  1370  	case Float32, Float64:
  1371  		return true
  1372  	default:
  1373  		return false
  1374  	}
  1375  }
  1376  
  1377  // Float returns v's underlying value, as a float64.
  1378  // It panics if v's Kind is not [Float32] or [Float64]
  1379  func (v Value) Float() float64 {
  1380  	k := v.kind()
  1381  	switch k {
  1382  	case Float32:
  1383  		return float64(*(*float32)(v.ptr))
  1384  	case Float64:
  1385  		return *(*float64)(v.ptr)
  1386  	}
  1387  	panic(&ValueError{"reflect.Value.Float", v.kind()})
  1388  }
  1389  
  1390  var uint8Type = rtypeOf(uint8(0))
  1391  
  1392  // Index returns v's i'th element.
  1393  // It panics if v's Kind is not [Array], [Slice], or [String] or i is out of range.
  1394  func (v Value) Index(i int) Value {
  1395  	switch v.kind() {
  1396  	case Array:
  1397  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  1398  		if uint(i) >= uint(tt.Len) {
  1399  			panic("reflect: array index out of range")
  1400  		}
  1401  		typ := tt.Elem
  1402  		offset := uintptr(i) * typ.Size()
  1403  
  1404  		// Either flagIndir is set and v.ptr points at array,
  1405  		// or flagIndir is not set and v.ptr is the actual array data.
  1406  		// In the former case, we want v.ptr + offset.
  1407  		// In the latter case, we must be doing Index(0), so offset = 0,
  1408  		// so v.ptr + offset is still the correct address.
  1409  		val := add(v.ptr, offset, "same as &v[i], i < tt.len")
  1410  		fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
  1411  		return Value{typ, val, fl}
  1412  
  1413  	case Slice:
  1414  		// Element flag same as Elem of Pointer.
  1415  		// Addressable, indirect, possibly read-only.
  1416  		s := (*unsafeheader.Slice)(v.ptr)
  1417  		if uint(i) >= uint(s.Len) {
  1418  			panic("reflect: slice index out of range")
  1419  		}
  1420  		tt := (*sliceType)(unsafe.Pointer(v.typ()))
  1421  		typ := tt.Elem
  1422  		val := arrayAt(s.Data, i, typ.Size(), "i < s.Len")
  1423  		fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
  1424  		return Value{typ, val, fl}
  1425  
  1426  	case String:
  1427  		s := (*unsafeheader.String)(v.ptr)
  1428  		if uint(i) >= uint(s.Len) {
  1429  			panic("reflect: string index out of range")
  1430  		}
  1431  		p := arrayAt(s.Data, i, 1, "i < s.Len")
  1432  		fl := v.flag.ro() | flag(Uint8) | flagIndir
  1433  		return Value{uint8Type, p, fl}
  1434  	}
  1435  	panic(&ValueError{"reflect.Value.Index", v.kind()})
  1436  }
  1437  
  1438  // CanInt reports whether Int can be used without panicking.
  1439  func (v Value) CanInt() bool {
  1440  	switch v.kind() {
  1441  	case Int, Int8, Int16, Int32, Int64:
  1442  		return true
  1443  	default:
  1444  		return false
  1445  	}
  1446  }
  1447  
  1448  // Int returns v's underlying value, as an int64.
  1449  // It panics if v's Kind is not [Int], [Int8], [Int16], [Int32], or [Int64].
  1450  func (v Value) Int() int64 {
  1451  	k := v.kind()
  1452  	p := v.ptr
  1453  	switch k {
  1454  	case Int:
  1455  		return int64(*(*int)(p))
  1456  	case Int8:
  1457  		return int64(*(*int8)(p))
  1458  	case Int16:
  1459  		return int64(*(*int16)(p))
  1460  	case Int32:
  1461  		return int64(*(*int32)(p))
  1462  	case Int64:
  1463  		return *(*int64)(p)
  1464  	}
  1465  	panic(&ValueError{"reflect.Value.Int", v.kind()})
  1466  }
  1467  
  1468  // CanInterface reports whether [Value.Interface] can be used without panicking.
  1469  func (v Value) CanInterface() bool {
  1470  	if v.flag == 0 {
  1471  		panic(&ValueError{"reflect.Value.CanInterface", Invalid})
  1472  	}
  1473  	return v.flag&flagRO == 0
  1474  }
  1475  
  1476  // Interface returns v's current value as an interface{}.
  1477  // It is equivalent to:
  1478  //
  1479  //	var i interface{} = (v's underlying value)
  1480  //
  1481  // It panics if the Value was obtained by accessing
  1482  // unexported struct fields.
  1483  func (v Value) Interface() (i any) {
  1484  	return valueInterface(v, true)
  1485  }
  1486  
  1487  func valueInterface(v Value, safe bool) any {
  1488  	if v.flag == 0 {
  1489  		panic(&ValueError{"reflect.Value.Interface", Invalid})
  1490  	}
  1491  	if safe && v.flag&flagRO != 0 {
  1492  		// Do not allow access to unexported values via Interface,
  1493  		// because they might be pointers that should not be
  1494  		// writable or methods or function that should not be callable.
  1495  		panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
  1496  	}
  1497  	if v.flag&flagMethod != 0 {
  1498  		v = makeMethodValue("Interface", v)
  1499  	}
  1500  
  1501  	if v.kind() == Interface {
  1502  		// Special case: return the element inside the interface.
  1503  		// Empty interface has one layout, all interfaces with
  1504  		// methods have a second layout.
  1505  		if v.NumMethod() == 0 {
  1506  			return *(*any)(v.ptr)
  1507  		}
  1508  		return *(*interface {
  1509  			M()
  1510  		})(v.ptr)
  1511  	}
  1512  
  1513  	return packEface(v)
  1514  }
  1515  
  1516  // InterfaceData returns a pair of unspecified uintptr values.
  1517  // It panics if v's Kind is not Interface.
  1518  //
  1519  // In earlier versions of Go, this function returned the interface's
  1520  // value as a uintptr pair. As of Go 1.4, the implementation of
  1521  // interface values precludes any defined use of InterfaceData.
  1522  //
  1523  // Deprecated: The memory representation of interface values is not
  1524  // compatible with InterfaceData.
  1525  func (v Value) InterfaceData() [2]uintptr {
  1526  	v.mustBe(Interface)
  1527  	// The compiler loses track as it converts to uintptr. Force escape.
  1528  	escapes(v.ptr)
  1529  	// We treat this as a read operation, so we allow
  1530  	// it even for unexported data, because the caller
  1531  	// has to import "unsafe" to turn it into something
  1532  	// that can be abused.
  1533  	// Interface value is always bigger than a word; assume flagIndir.
  1534  	return *(*[2]uintptr)(v.ptr)
  1535  }
  1536  
  1537  // IsNil reports whether its argument v is nil. The argument must be
  1538  // a chan, func, interface, map, pointer, or slice value; if it is
  1539  // not, IsNil panics. Note that IsNil is not always equivalent to a
  1540  // regular comparison with nil in Go. For example, if v was created
  1541  // by calling [ValueOf] with an uninitialized interface variable i,
  1542  // i==nil will be true but v.IsNil will panic as v will be the zero
  1543  // Value.
  1544  func (v Value) IsNil() bool {
  1545  	k := v.kind()
  1546  	switch k {
  1547  	case Chan, Func, Map, Pointer, UnsafePointer:
  1548  		if v.flag&flagMethod != 0 {
  1549  			return false
  1550  		}
  1551  		ptr := v.ptr
  1552  		if v.flag&flagIndir != 0 {
  1553  			ptr = *(*unsafe.Pointer)(ptr)
  1554  		}
  1555  		return ptr == nil
  1556  	case Interface, Slice:
  1557  		// Both interface and slice are nil if first word is 0.
  1558  		// Both are always bigger than a word; assume flagIndir.
  1559  		return *(*unsafe.Pointer)(v.ptr) == nil
  1560  	}
  1561  	panic(&ValueError{"reflect.Value.IsNil", v.kind()})
  1562  }
  1563  
  1564  // IsValid reports whether v represents a value.
  1565  // It returns false if v is the zero Value.
  1566  // If [Value.IsValid] returns false, all other methods except String panic.
  1567  // Most functions and methods never return an invalid Value.
  1568  // If one does, its documentation states the conditions explicitly.
  1569  func (v Value) IsValid() bool {
  1570  	return v.flag != 0
  1571  }
  1572  
  1573  // IsZero reports whether v is the zero value for its type.
  1574  // It panics if the argument is invalid.
  1575  func (v Value) IsZero() bool {
  1576  	switch v.kind() {
  1577  	case Bool:
  1578  		return !v.Bool()
  1579  	case Int, Int8, Int16, Int32, Int64:
  1580  		return v.Int() == 0
  1581  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  1582  		return v.Uint() == 0
  1583  	case Float32, Float64:
  1584  		return v.Float() == 0
  1585  	case Complex64, Complex128:
  1586  		return v.Complex() == 0
  1587  	case Array:
  1588  		if v.flag&flagIndir == 0 {
  1589  			return v.ptr == nil
  1590  		}
  1591  		typ := (*abi.ArrayType)(unsafe.Pointer(v.typ()))
  1592  		// If the type is comparable, then compare directly with zero.
  1593  		if typ.Equal != nil && typ.Size() <= abi.ZeroValSize {
  1594  			// v.ptr doesn't escape, as Equal functions are compiler generated
  1595  			// and never escape. The escape analysis doesn't know, as it is a
  1596  			// function pointer call.
  1597  			return typ.Equal(abi.NoEscape(v.ptr), unsafe.Pointer(&zeroVal[0]))
  1598  		}
  1599  		if typ.TFlag&abi.TFlagRegularMemory != 0 {
  1600  			// For some types where the zero value is a value where all bits of this type are 0
  1601  			// optimize it.
  1602  			return isZero(unsafe.Slice(((*byte)(v.ptr)), typ.Size()))
  1603  		}
  1604  		n := int(typ.Len)
  1605  		for i := 0; i < n; i++ {
  1606  			if !v.Index(i).IsZero() {
  1607  				return false
  1608  			}
  1609  		}
  1610  		return true
  1611  	case Chan, Func, Interface, Map, Pointer, Slice, UnsafePointer:
  1612  		return v.IsNil()
  1613  	case String:
  1614  		return v.Len() == 0
  1615  	case Struct:
  1616  		if v.flag&flagIndir == 0 {
  1617  			return v.ptr == nil
  1618  		}
  1619  		typ := (*abi.StructType)(unsafe.Pointer(v.typ()))
  1620  		// If the type is comparable, then compare directly with zero.
  1621  		if typ.Equal != nil && typ.Size() <= abi.ZeroValSize {
  1622  			// See noescape justification above.
  1623  			return typ.Equal(abi.NoEscape(v.ptr), unsafe.Pointer(&zeroVal[0]))
  1624  		}
  1625  		if typ.TFlag&abi.TFlagRegularMemory != 0 {
  1626  			// For some types where the zero value is a value where all bits of this type are 0
  1627  			// optimize it.
  1628  			return isZero(unsafe.Slice(((*byte)(v.ptr)), typ.Size()))
  1629  		}
  1630  
  1631  		n := v.NumField()
  1632  		for i := 0; i < n; i++ {
  1633  			if !v.Field(i).IsZero() && v.Type().Field(i).Name != "_" {
  1634  				return false
  1635  			}
  1636  		}
  1637  		return true
  1638  	default:
  1639  		// This should never happen, but will act as a safeguard for later,
  1640  		// as a default value doesn't makes sense here.
  1641  		panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
  1642  	}
  1643  }
  1644  
  1645  // isZero For all zeros, performance is not as good as
  1646  // return bytealg.Count(b, byte(0)) == len(b)
  1647  func isZero(b []byte) bool {
  1648  	if len(b) == 0 {
  1649  		return true
  1650  	}
  1651  	const n = 32
  1652  	// Align memory addresses to 8 bytes.
  1653  	for uintptr(unsafe.Pointer(&b[0]))%8 != 0 {
  1654  		if b[0] != 0 {
  1655  			return false
  1656  		}
  1657  		b = b[1:]
  1658  		if len(b) == 0 {
  1659  			return true
  1660  		}
  1661  	}
  1662  	for len(b)%8 != 0 {
  1663  		if b[len(b)-1] != 0 {
  1664  			return false
  1665  		}
  1666  		b = b[:len(b)-1]
  1667  	}
  1668  	if len(b) == 0 {
  1669  		return true
  1670  	}
  1671  	w := unsafe.Slice((*uint64)(unsafe.Pointer(&b[0])), len(b)/8)
  1672  	for len(w)%n != 0 {
  1673  		if w[0] != 0 {
  1674  			return false
  1675  		}
  1676  		w = w[1:]
  1677  	}
  1678  	for len(w) >= n {
  1679  		if w[0] != 0 || w[1] != 0 || w[2] != 0 || w[3] != 0 ||
  1680  			w[4] != 0 || w[5] != 0 || w[6] != 0 || w[7] != 0 ||
  1681  			w[8] != 0 || w[9] != 0 || w[10] != 0 || w[11] != 0 ||
  1682  			w[12] != 0 || w[13] != 0 || w[14] != 0 || w[15] != 0 ||
  1683  			w[16] != 0 || w[17] != 0 || w[18] != 0 || w[19] != 0 ||
  1684  			w[20] != 0 || w[21] != 0 || w[22] != 0 || w[23] != 0 ||
  1685  			w[24] != 0 || w[25] != 0 || w[26] != 0 || w[27] != 0 ||
  1686  			w[28] != 0 || w[29] != 0 || w[30] != 0 || w[31] != 0 {
  1687  			return false
  1688  		}
  1689  		w = w[n:]
  1690  	}
  1691  	return true
  1692  }
  1693  
  1694  // SetZero sets v to be the zero value of v's type.
  1695  // It panics if [Value.CanSet] returns false.
  1696  func (v Value) SetZero() {
  1697  	v.mustBeAssignable()
  1698  	switch v.kind() {
  1699  	case Bool:
  1700  		*(*bool)(v.ptr) = false
  1701  	case Int:
  1702  		*(*int)(v.ptr) = 0
  1703  	case Int8:
  1704  		*(*int8)(v.ptr) = 0
  1705  	case Int16:
  1706  		*(*int16)(v.ptr) = 0
  1707  	case Int32:
  1708  		*(*int32)(v.ptr) = 0
  1709  	case Int64:
  1710  		*(*int64)(v.ptr) = 0
  1711  	case Uint:
  1712  		*(*uint)(v.ptr) = 0
  1713  	case Uint8:
  1714  		*(*uint8)(v.ptr) = 0
  1715  	case Uint16:
  1716  		*(*uint16)(v.ptr) = 0
  1717  	case Uint32:
  1718  		*(*uint32)(v.ptr) = 0
  1719  	case Uint64:
  1720  		*(*uint64)(v.ptr) = 0
  1721  	case Uintptr:
  1722  		*(*uintptr)(v.ptr) = 0
  1723  	case Float32:
  1724  		*(*float32)(v.ptr) = 0
  1725  	case Float64:
  1726  		*(*float64)(v.ptr) = 0
  1727  	case Complex64:
  1728  		*(*complex64)(v.ptr) = 0
  1729  	case Complex128:
  1730  		*(*complex128)(v.ptr) = 0
  1731  	case String:
  1732  		*(*string)(v.ptr) = ""
  1733  	case Slice:
  1734  		*(*unsafeheader.Slice)(v.ptr) = unsafeheader.Slice{}
  1735  	case Interface:
  1736  		*(*abi.EmptyInterface)(v.ptr) = abi.EmptyInterface{}
  1737  	case Chan, Func, Map, Pointer, UnsafePointer:
  1738  		*(*unsafe.Pointer)(v.ptr) = nil
  1739  	case Array, Struct:
  1740  		typedmemclr(v.typ(), v.ptr)
  1741  	default:
  1742  		// This should never happen, but will act as a safeguard for later,
  1743  		// as a default value doesn't makes sense here.
  1744  		panic(&ValueError{"reflect.Value.SetZero", v.Kind()})
  1745  	}
  1746  }
  1747  
  1748  // Kind returns v's Kind.
  1749  // If v is the zero Value ([Value.IsValid] returns false), Kind returns Invalid.
  1750  func (v Value) Kind() Kind {
  1751  	return v.kind()
  1752  }
  1753  
  1754  // Len returns v's length.
  1755  // It panics if v's Kind is not [Array], [Chan], [Map], [Slice], [String], or pointer to [Array].
  1756  func (v Value) Len() int {
  1757  	// lenNonSlice is split out to keep Len inlineable for slice kinds.
  1758  	if v.kind() == Slice {
  1759  		return (*unsafeheader.Slice)(v.ptr).Len
  1760  	}
  1761  	return v.lenNonSlice()
  1762  }
  1763  
  1764  func (v Value) lenNonSlice() int {
  1765  	switch k := v.kind(); k {
  1766  	case Array:
  1767  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  1768  		return int(tt.Len)
  1769  	case Chan:
  1770  		return chanlen(v.pointer())
  1771  	case Map:
  1772  		return maplen(v.pointer())
  1773  	case String:
  1774  		// String is bigger than a word; assume flagIndir.
  1775  		return (*unsafeheader.String)(v.ptr).Len
  1776  	case Ptr:
  1777  		if v.typ().Elem().Kind() == abi.Array {
  1778  			return v.typ().Elem().Len()
  1779  		}
  1780  		panic("reflect: call of reflect.Value.Len on ptr to non-array Value")
  1781  	}
  1782  	panic(&ValueError{"reflect.Value.Len", v.kind()})
  1783  }
  1784  
  1785  // copyVal returns a Value containing the map key or value at ptr,
  1786  // allocating a new variable as needed.
  1787  func copyVal(typ *abi.Type, fl flag, ptr unsafe.Pointer) Value {
  1788  	if typ.IfaceIndir() {
  1789  		// Copy result so future changes to the map
  1790  		// won't change the underlying value.
  1791  		c := unsafe_New(typ)
  1792  		typedmemmove(typ, c, ptr)
  1793  		return Value{typ, c, fl | flagIndir}
  1794  	}
  1795  	return Value{typ, *(*unsafe.Pointer)(ptr), fl}
  1796  }
  1797  
  1798  // Method returns a function value corresponding to v's i'th method.
  1799  // The arguments to a Call on the returned function should not include
  1800  // a receiver; the returned function will always use v as the receiver.
  1801  // Method panics if i is out of range or if v is a nil interface value.
  1802  func (v Value) Method(i int) Value {
  1803  	if v.typ() == nil {
  1804  		panic(&ValueError{"reflect.Value.Method", Invalid})
  1805  	}
  1806  	if v.flag&flagMethod != 0 || uint(i) >= uint(toRType(v.typ()).NumMethod()) {
  1807  		panic("reflect: Method index out of range")
  1808  	}
  1809  	if v.typ().Kind() == abi.Interface && v.IsNil() {
  1810  		panic("reflect: Method on nil interface value")
  1811  	}
  1812  	fl := v.flag.ro() | (v.flag & flagIndir)
  1813  	fl |= flag(Func)
  1814  	fl |= flag(i)<<flagMethodShift | flagMethod
  1815  	return Value{v.typ(), v.ptr, fl}
  1816  }
  1817  
  1818  // NumMethod returns the number of methods in the value's method set.
  1819  //
  1820  // For a non-interface type, it returns the number of exported methods.
  1821  //
  1822  // For an interface type, it returns the number of exported and unexported methods.
  1823  func (v Value) NumMethod() int {
  1824  	if v.typ() == nil {
  1825  		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
  1826  	}
  1827  	if v.flag&flagMethod != 0 {
  1828  		return 0
  1829  	}
  1830  	return toRType(v.typ()).NumMethod()
  1831  }
  1832  
  1833  // MethodByName returns a function value corresponding to the method
  1834  // of v with the given name.
  1835  // The arguments to a Call on the returned function should not include
  1836  // a receiver; the returned function will always use v as the receiver.
  1837  // It returns the zero Value if no method was found.
  1838  func (v Value) MethodByName(name string) Value {
  1839  	if v.typ() == nil {
  1840  		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
  1841  	}
  1842  	if v.flag&flagMethod != 0 {
  1843  		return Value{}
  1844  	}
  1845  	m, ok := toRType(v.typ()).MethodByName(name)
  1846  	if !ok {
  1847  		return Value{}
  1848  	}
  1849  	return v.Method(m.Index)
  1850  }
  1851  
  1852  // NumField returns the number of fields in the struct v.
  1853  // It panics if v's Kind is not [Struct].
  1854  func (v Value) NumField() int {
  1855  	v.mustBe(Struct)
  1856  	tt := (*structType)(unsafe.Pointer(v.typ()))
  1857  	return len(tt.Fields)
  1858  }
  1859  
  1860  // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
  1861  // It panics if v's Kind is not [Complex64] or [Complex128].
  1862  func (v Value) OverflowComplex(x complex128) bool {
  1863  	k := v.kind()
  1864  	switch k {
  1865  	case Complex64:
  1866  		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
  1867  	case Complex128:
  1868  		return false
  1869  	}
  1870  	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
  1871  }
  1872  
  1873  // OverflowFloat reports whether the float64 x cannot be represented by v's type.
  1874  // It panics if v's Kind is not [Float32] or [Float64].
  1875  func (v Value) OverflowFloat(x float64) bool {
  1876  	k := v.kind()
  1877  	switch k {
  1878  	case Float32:
  1879  		return overflowFloat32(x)
  1880  	case Float64:
  1881  		return false
  1882  	}
  1883  	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
  1884  }
  1885  
  1886  func overflowFloat32(x float64) bool {
  1887  	if x < 0 {
  1888  		x = -x
  1889  	}
  1890  	return math.MaxFloat32 < x && x <= math.MaxFloat64
  1891  }
  1892  
  1893  // OverflowInt reports whether the int64 x cannot be represented by v's type.
  1894  // It panics if v's Kind is not [Int], [Int8], [Int16], [Int32], or [Int64].
  1895  func (v Value) OverflowInt(x int64) bool {
  1896  	k := v.kind()
  1897  	switch k {
  1898  	case Int, Int8, Int16, Int32, Int64:
  1899  		bitSize := v.typ().Size() * 8
  1900  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1901  		return x != trunc
  1902  	}
  1903  	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
  1904  }
  1905  
  1906  // OverflowUint reports whether the uint64 x cannot be represented by v's type.
  1907  // It panics if v's Kind is not [Uint], [Uintptr], [Uint8], [Uint16], [Uint32], or [Uint64].
  1908  func (v Value) OverflowUint(x uint64) bool {
  1909  	k := v.kind()
  1910  	switch k {
  1911  	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
  1912  		bitSize := v.typ_.Size() * 8 // ok to use v.typ_ directly as Size doesn't escape
  1913  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1914  		return x != trunc
  1915  	}
  1916  	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
  1917  }
  1918  
  1919  //go:nocheckptr
  1920  // This prevents inlining Value.Pointer when -d=checkptr is enabled,
  1921  // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
  1922  // and make an exception.
  1923  
  1924  // Pointer returns v's value as a uintptr.
  1925  // It panics if v's Kind is not [Chan], [Func], [Map], [Pointer], [Slice], [String], or [UnsafePointer].
  1926  //
  1927  // If v's Kind is [Func], the returned pointer is an underlying
  1928  // code pointer, but not necessarily enough to identify a
  1929  // single function uniquely. The only guarantee is that the
  1930  // result is zero if and only if v is a nil func Value.
  1931  //
  1932  // If v's Kind is [Slice], the returned pointer is to the first
  1933  // element of the slice. If the slice is nil the returned value
  1934  // is 0.  If the slice is empty but non-nil the return value is non-zero.
  1935  //
  1936  // If v's Kind is [String], the returned pointer is to the first
  1937  // element of the underlying bytes of string.
  1938  //
  1939  // It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result.
  1940  func (v Value) Pointer() uintptr {
  1941  	// The compiler loses track as it converts to uintptr. Force escape.
  1942  	escapes(v.ptr)
  1943  
  1944  	k := v.kind()
  1945  	switch k {
  1946  	case Pointer:
  1947  		if !v.typ().Pointers() {
  1948  			val := *(*uintptr)(v.ptr)
  1949  			// Since it is a not-in-heap pointer, all pointers to the heap are
  1950  			// forbidden! See comment in Value.Elem and issue #48399.
  1951  			if !verifyNotInHeapPtr(val) {
  1952  				panic("reflect: reflect.Value.Pointer on an invalid notinheap pointer")
  1953  			}
  1954  			return val
  1955  		}
  1956  		fallthrough
  1957  	case Chan, Map, UnsafePointer:
  1958  		return uintptr(v.pointer())
  1959  	case Func:
  1960  		if v.flag&flagMethod != 0 {
  1961  			// As the doc comment says, the returned pointer is an
  1962  			// underlying code pointer but not necessarily enough to
  1963  			// identify a single function uniquely. All method expressions
  1964  			// created via reflect have the same underlying code pointer,
  1965  			// so their Pointers are equal. The function used here must
  1966  			// match the one used in makeMethodValue.
  1967  			return methodValueCallCodePtr()
  1968  		}
  1969  		p := v.pointer()
  1970  		// Non-nil func value points at data block.
  1971  		// First word of data block is actual code.
  1972  		if p != nil {
  1973  			p = *(*unsafe.Pointer)(p)
  1974  		}
  1975  		return uintptr(p)
  1976  	case Slice:
  1977  		return uintptr((*unsafeheader.Slice)(v.ptr).Data)
  1978  	case String:
  1979  		return uintptr((*unsafeheader.String)(v.ptr).Data)
  1980  	}
  1981  	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
  1982  }
  1983  
  1984  // Recv receives and returns a value from the channel v.
  1985  // It panics if v's Kind is not [Chan].
  1986  // The receive blocks until a value is ready.
  1987  // The boolean value ok is true if the value x corresponds to a send
  1988  // on the channel, false if it is a zero value received because the channel is closed.
  1989  func (v Value) Recv() (x Value, ok bool) {
  1990  	v.mustBe(Chan)
  1991  	v.mustBeExported()
  1992  	return v.recv(false)
  1993  }
  1994  
  1995  // internal recv, possibly non-blocking (nb).
  1996  // v is known to be a channel.
  1997  func (v Value) recv(nb bool) (val Value, ok bool) {
  1998  	tt := (*chanType)(unsafe.Pointer(v.typ()))
  1999  	if ChanDir(tt.Dir)&RecvDir == 0 {
  2000  		panic("reflect: recv on send-only channel")
  2001  	}
  2002  	t := tt.Elem
  2003  	val = Value{t, nil, flag(t.Kind())}
  2004  	var p unsafe.Pointer
  2005  	if t.IfaceIndir() {
  2006  		p = unsafe_New(t)
  2007  		val.ptr = p
  2008  		val.flag |= flagIndir
  2009  	} else {
  2010  		p = unsafe.Pointer(&val.ptr)
  2011  	}
  2012  	selected, ok := chanrecv(v.pointer(), nb, p)
  2013  	if !selected {
  2014  		val = Value{}
  2015  	}
  2016  	return
  2017  }
  2018  
  2019  // Send sends x on the channel v.
  2020  // It panics if v's kind is not [Chan] or if x's type is not the same type as v's element type.
  2021  // As in Go, x's value must be assignable to the channel's element type.
  2022  func (v Value) Send(x Value) {
  2023  	v.mustBe(Chan)
  2024  	v.mustBeExported()
  2025  	v.send(x, false)
  2026  }
  2027  
  2028  // internal send, possibly non-blocking.
  2029  // v is known to be a channel.
  2030  func (v Value) send(x Value, nb bool) (selected bool) {
  2031  	tt := (*chanType)(unsafe.Pointer(v.typ()))
  2032  	if ChanDir(tt.Dir)&SendDir == 0 {
  2033  		panic("reflect: send on recv-only channel")
  2034  	}
  2035  	x.mustBeExported()
  2036  	x = x.assignTo("reflect.Value.Send", tt.Elem, nil)
  2037  	var p unsafe.Pointer
  2038  	if x.flag&flagIndir != 0 {
  2039  		p = x.ptr
  2040  	} else {
  2041  		p = unsafe.Pointer(&x.ptr)
  2042  	}
  2043  	return chansend(v.pointer(), p, nb)
  2044  }
  2045  
  2046  // Set assigns x to the value v.
  2047  // It panics if [Value.CanSet] returns false.
  2048  // As in Go, x's value must be assignable to v's type and
  2049  // must not be derived from an unexported field.
  2050  func (v Value) Set(x Value) {
  2051  	v.mustBeAssignable()
  2052  	x.mustBeExported() // do not let unexported x leak
  2053  	var target unsafe.Pointer
  2054  	if v.kind() == Interface {
  2055  		target = v.ptr
  2056  	}
  2057  	x = x.assignTo("reflect.Set", v.typ(), target)
  2058  	if x.flag&flagIndir != 0 {
  2059  		if x.ptr == unsafe.Pointer(&zeroVal[0]) {
  2060  			typedmemclr(v.typ(), v.ptr)
  2061  		} else {
  2062  			typedmemmove(v.typ(), v.ptr, x.ptr)
  2063  		}
  2064  	} else {
  2065  		*(*unsafe.Pointer)(v.ptr) = x.ptr
  2066  	}
  2067  }
  2068  
  2069  // SetBool sets v's underlying value.
  2070  // It panics if v's Kind is not [Bool] or if [Value.CanSet] returns false.
  2071  func (v Value) SetBool(x bool) {
  2072  	v.mustBeAssignable()
  2073  	v.mustBe(Bool)
  2074  	*(*bool)(v.ptr) = x
  2075  }
  2076  
  2077  // SetBytes sets v's underlying value.
  2078  // It panics if v's underlying value is not a slice of bytes
  2079  // or if [Value.CanSet] returns false.
  2080  func (v Value) SetBytes(x []byte) {
  2081  	v.mustBeAssignable()
  2082  	v.mustBe(Slice)
  2083  	if toRType(v.typ()).Elem().Kind() != Uint8 { // TODO add Elem method, fix mustBe(Slice) to return slice.
  2084  		panic("reflect.Value.SetBytes of non-byte slice")
  2085  	}
  2086  	*(*[]byte)(v.ptr) = x
  2087  }
  2088  
  2089  // setRunes sets v's underlying value.
  2090  // It panics if v's underlying value is not a slice of runes (int32s)
  2091  // or if [Value.CanSet] returns false.
  2092  func (v Value) setRunes(x []rune) {
  2093  	v.mustBeAssignable()
  2094  	v.mustBe(Slice)
  2095  	if v.typ().Elem().Kind() != abi.Int32 {
  2096  		panic("reflect.Value.setRunes of non-rune slice")
  2097  	}
  2098  	*(*[]rune)(v.ptr) = x
  2099  }
  2100  
  2101  // SetComplex sets v's underlying value to x.
  2102  // It panics if v's Kind is not [Complex64] or [Complex128],
  2103  // or if [Value.CanSet] returns false.
  2104  func (v Value) SetComplex(x complex128) {
  2105  	v.mustBeAssignable()
  2106  	switch k := v.kind(); k {
  2107  	default:
  2108  		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
  2109  	case Complex64:
  2110  		*(*complex64)(v.ptr) = complex64(x)
  2111  	case Complex128:
  2112  		*(*complex128)(v.ptr) = x
  2113  	}
  2114  }
  2115  
  2116  // SetFloat sets v's underlying value to x.
  2117  // It panics if v's Kind is not [Float32] or [Float64],
  2118  // or if [Value.CanSet] returns false.
  2119  func (v Value) SetFloat(x float64) {
  2120  	v.mustBeAssignable()
  2121  	switch k := v.kind(); k {
  2122  	default:
  2123  		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
  2124  	case Float32:
  2125  		*(*float32)(v.ptr) = float32(x)
  2126  	case Float64:
  2127  		*(*float64)(v.ptr) = x
  2128  	}
  2129  }
  2130  
  2131  // SetInt sets v's underlying value to x.
  2132  // It panics if v's Kind is not [Int], [Int8], [Int16], [Int32], or [Int64],
  2133  // or if [Value.CanSet] returns false.
  2134  func (v Value) SetInt(x int64) {
  2135  	v.mustBeAssignable()
  2136  	switch k := v.kind(); k {
  2137  	default:
  2138  		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
  2139  	case Int:
  2140  		*(*int)(v.ptr) = int(x)
  2141  	case Int8:
  2142  		*(*int8)(v.ptr) = int8(x)
  2143  	case Int16:
  2144  		*(*int16)(v.ptr) = int16(x)
  2145  	case Int32:
  2146  		*(*int32)(v.ptr) = int32(x)
  2147  	case Int64:
  2148  		*(*int64)(v.ptr) = x
  2149  	}
  2150  }
  2151  
  2152  // SetLen sets v's length to n.
  2153  // It panics if v's Kind is not [Slice], or if n is negative or
  2154  // greater than the capacity of the slice,
  2155  // or if [Value.CanSet] returns false.
  2156  func (v Value) SetLen(n int) {
  2157  	v.mustBeAssignable()
  2158  	v.mustBe(Slice)
  2159  	s := (*unsafeheader.Slice)(v.ptr)
  2160  	if uint(n) > uint(s.Cap) {
  2161  		panic("reflect: slice length out of range in SetLen")
  2162  	}
  2163  	s.Len = n
  2164  }
  2165  
  2166  // SetCap sets v's capacity to n.
  2167  // It panics if v's Kind is not [Slice], or if n is smaller than the length or
  2168  // greater than the capacity of the slice,
  2169  // or if [Value.CanSet] returns false.
  2170  func (v Value) SetCap(n int) {
  2171  	v.mustBeAssignable()
  2172  	v.mustBe(Slice)
  2173  	s := (*unsafeheader.Slice)(v.ptr)
  2174  	if n < s.Len || n > s.Cap {
  2175  		panic("reflect: slice capacity out of range in SetCap")
  2176  	}
  2177  	s.Cap = n
  2178  }
  2179  
  2180  // SetUint sets v's underlying value to x.
  2181  // It panics if v's Kind is not [Uint], [Uintptr], [Uint8], [Uint16], [Uint32], or [Uint64],
  2182  // or if [Value.CanSet] returns false.
  2183  func (v Value) SetUint(x uint64) {
  2184  	v.mustBeAssignable()
  2185  	switch k := v.kind(); k {
  2186  	default:
  2187  		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
  2188  	case Uint:
  2189  		*(*uint)(v.ptr) = uint(x)
  2190  	case Uint8:
  2191  		*(*uint8)(v.ptr) = uint8(x)
  2192  	case Uint16:
  2193  		*(*uint16)(v.ptr) = uint16(x)
  2194  	case Uint32:
  2195  		*(*uint32)(v.ptr) = uint32(x)
  2196  	case Uint64:
  2197  		*(*uint64)(v.ptr) = x
  2198  	case Uintptr:
  2199  		*(*uintptr)(v.ptr) = uintptr(x)
  2200  	}
  2201  }
  2202  
  2203  // SetPointer sets the [unsafe.Pointer] value v to x.
  2204  // It panics if v's Kind is not [UnsafePointer]
  2205  // or if [Value.CanSet] returns false.
  2206  func (v Value) SetPointer(x unsafe.Pointer) {
  2207  	v.mustBeAssignable()
  2208  	v.mustBe(UnsafePointer)
  2209  	*(*unsafe.Pointer)(v.ptr) = x
  2210  }
  2211  
  2212  // SetString sets v's underlying value to x.
  2213  // It panics if v's Kind is not [String] or if [Value.CanSet] returns false.
  2214  func (v Value) SetString(x string) {
  2215  	v.mustBeAssignable()
  2216  	v.mustBe(String)
  2217  	*(*string)(v.ptr) = x
  2218  }
  2219  
  2220  // Slice returns v[i:j].
  2221  // It panics if v's Kind is not [Array], [Slice] or [String], or if v is an unaddressable array,
  2222  // or if the indexes are out of bounds.
  2223  func (v Value) Slice(i, j int) Value {
  2224  	var (
  2225  		cap  int
  2226  		typ  *sliceType
  2227  		base unsafe.Pointer
  2228  	)
  2229  	switch kind := v.kind(); kind {
  2230  	default:
  2231  		panic(&ValueError{"reflect.Value.Slice", v.kind()})
  2232  
  2233  	case Array:
  2234  		if v.flag&flagAddr == 0 {
  2235  			panic("reflect.Value.Slice: slice of unaddressable array")
  2236  		}
  2237  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  2238  		cap = int(tt.Len)
  2239  		typ = (*sliceType)(unsafe.Pointer(tt.Slice))
  2240  		base = v.ptr
  2241  
  2242  	case Slice:
  2243  		typ = (*sliceType)(unsafe.Pointer(v.typ()))
  2244  		s := (*unsafeheader.Slice)(v.ptr)
  2245  		base = s.Data
  2246  		cap = s.Cap
  2247  
  2248  	case String:
  2249  		s := (*unsafeheader.String)(v.ptr)
  2250  		if i < 0 || j < i || j > s.Len {
  2251  			panic("reflect.Value.Slice: string slice index out of bounds")
  2252  		}
  2253  		var t unsafeheader.String
  2254  		if i < s.Len {
  2255  			t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i}
  2256  		}
  2257  		return Value{v.typ(), unsafe.Pointer(&t), v.flag}
  2258  	}
  2259  
  2260  	if i < 0 || j < i || j > cap {
  2261  		panic("reflect.Value.Slice: slice index out of bounds")
  2262  	}
  2263  
  2264  	// Declare slice so that gc can see the base pointer in it.
  2265  	var x []unsafe.Pointer
  2266  
  2267  	// Reinterpret as *unsafeheader.Slice to edit.
  2268  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  2269  	s.Len = j - i
  2270  	s.Cap = cap - i
  2271  	if cap-i > 0 {
  2272  		s.Data = arrayAt(base, i, typ.Elem.Size(), "i < cap")
  2273  	} else {
  2274  		// do not advance pointer, to avoid pointing beyond end of slice
  2275  		s.Data = base
  2276  	}
  2277  
  2278  	fl := v.flag.ro() | flagIndir | flag(Slice)
  2279  	return Value{typ.Common(), unsafe.Pointer(&x), fl}
  2280  }
  2281  
  2282  // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
  2283  // It panics if v's Kind is not [Array] or [Slice], or if v is an unaddressable array,
  2284  // or if the indexes are out of bounds.
  2285  func (v Value) Slice3(i, j, k int) Value {
  2286  	var (
  2287  		cap  int
  2288  		typ  *sliceType
  2289  		base unsafe.Pointer
  2290  	)
  2291  	switch kind := v.kind(); kind {
  2292  	default:
  2293  		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
  2294  
  2295  	case Array:
  2296  		if v.flag&flagAddr == 0 {
  2297  			panic("reflect.Value.Slice3: slice of unaddressable array")
  2298  		}
  2299  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  2300  		cap = int(tt.Len)
  2301  		typ = (*sliceType)(unsafe.Pointer(tt.Slice))
  2302  		base = v.ptr
  2303  
  2304  	case Slice:
  2305  		typ = (*sliceType)(unsafe.Pointer(v.typ()))
  2306  		s := (*unsafeheader.Slice)(v.ptr)
  2307  		base = s.Data
  2308  		cap = s.Cap
  2309  	}
  2310  
  2311  	if i < 0 || j < i || k < j || k > cap {
  2312  		panic("reflect.Value.Slice3: slice index out of bounds")
  2313  	}
  2314  
  2315  	// Declare slice so that the garbage collector
  2316  	// can see the base pointer in it.
  2317  	var x []unsafe.Pointer
  2318  
  2319  	// Reinterpret as *unsafeheader.Slice to edit.
  2320  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  2321  	s.Len = j - i
  2322  	s.Cap = k - i
  2323  	if k-i > 0 {
  2324  		s.Data = arrayAt(base, i, typ.Elem.Size(), "i < k <= cap")
  2325  	} else {
  2326  		// do not advance pointer, to avoid pointing beyond end of slice
  2327  		s.Data = base
  2328  	}
  2329  
  2330  	fl := v.flag.ro() | flagIndir | flag(Slice)
  2331  	return Value{typ.Common(), unsafe.Pointer(&x), fl}
  2332  }
  2333  
  2334  // String returns the string v's underlying value, as a string.
  2335  // String is a special case because of Go's String method convention.
  2336  // Unlike the other getters, it does not panic if v's Kind is not [String].
  2337  // Instead, it returns a string of the form "<T value>" where T is v's type.
  2338  // The fmt package treats Values specially. It does not call their String
  2339  // method implicitly but instead prints the concrete values they hold.
  2340  func (v Value) String() string {
  2341  	// stringNonString is split out to keep String inlineable for string kinds.
  2342  	if v.kind() == String {
  2343  		return *(*string)(v.ptr)
  2344  	}
  2345  	return v.stringNonString()
  2346  }
  2347  
  2348  func (v Value) stringNonString() string {
  2349  	if v.kind() == Invalid {
  2350  		return "<invalid Value>"
  2351  	}
  2352  	// If you call String on a reflect.Value of other type, it's better to
  2353  	// print something than to panic. Useful in debugging.
  2354  	return "<" + v.Type().String() + " Value>"
  2355  }
  2356  
  2357  // TryRecv attempts to receive a value from the channel v but will not block.
  2358  // It panics if v's Kind is not [Chan].
  2359  // If the receive delivers a value, x is the transferred value and ok is true.
  2360  // If the receive cannot finish without blocking, x is the zero Value and ok is false.
  2361  // If the channel is closed, x is the zero value for the channel's element type and ok is false.
  2362  func (v Value) TryRecv() (x Value, ok bool) {
  2363  	v.mustBe(Chan)
  2364  	v.mustBeExported()
  2365  	return v.recv(true)
  2366  }
  2367  
  2368  // TrySend attempts to send x on the channel v but will not block.
  2369  // It panics if v's Kind is not [Chan].
  2370  // It reports whether the value was sent.
  2371  // As in Go, x's value must be assignable to the channel's element type.
  2372  func (v Value) TrySend(x Value) bool {
  2373  	v.mustBe(Chan)
  2374  	v.mustBeExported()
  2375  	return v.send(x, true)
  2376  }
  2377  
  2378  // Type returns v's type.
  2379  func (v Value) Type() Type {
  2380  	if v.flag != 0 && v.flag&flagMethod == 0 {
  2381  		return (*rtype)(abi.NoEscape(unsafe.Pointer(v.typ_))) // inline of toRType(v.typ()), for own inlining in inline test
  2382  	}
  2383  	return v.typeSlow()
  2384  }
  2385  
  2386  //go:noinline
  2387  func (v Value) typeSlow() Type {
  2388  	return toRType(v.abiTypeSlow())
  2389  }
  2390  
  2391  func (v Value) abiType() *abi.Type {
  2392  	if v.flag != 0 && v.flag&flagMethod == 0 {
  2393  		return v.typ()
  2394  	}
  2395  	return v.abiTypeSlow()
  2396  }
  2397  
  2398  func (v Value) abiTypeSlow() *abi.Type {
  2399  	if v.flag == 0 {
  2400  		panic(&ValueError{"reflect.Value.Type", Invalid})
  2401  	}
  2402  
  2403  	typ := v.typ()
  2404  	if v.flag&flagMethod == 0 {
  2405  		return v.typ()
  2406  	}
  2407  
  2408  	// Method value.
  2409  	// v.typ describes the receiver, not the method type.
  2410  	i := int(v.flag) >> flagMethodShift
  2411  	if v.typ().Kind() == abi.Interface {
  2412  		// Method on interface.
  2413  		tt := (*interfaceType)(unsafe.Pointer(typ))
  2414  		if uint(i) >= uint(len(tt.Methods)) {
  2415  			panic("reflect: internal error: invalid method index")
  2416  		}
  2417  		m := &tt.Methods[i]
  2418  		return typeOffFor(typ, m.Typ)
  2419  	}
  2420  	// Method on concrete type.
  2421  	ms := typ.ExportedMethods()
  2422  	if uint(i) >= uint(len(ms)) {
  2423  		panic("reflect: internal error: invalid method index")
  2424  	}
  2425  	m := ms[i]
  2426  	return typeOffFor(typ, m.Mtyp)
  2427  }
  2428  
  2429  // CanUint reports whether [Value.Uint] can be used without panicking.
  2430  func (v Value) CanUint() bool {
  2431  	switch v.kind() {
  2432  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2433  		return true
  2434  	default:
  2435  		return false
  2436  	}
  2437  }
  2438  
  2439  // Uint returns v's underlying value, as a uint64.
  2440  // It panics if v's Kind is not [Uint], [Uintptr], [Uint8], [Uint16], [Uint32], or [Uint64].
  2441  func (v Value) Uint() uint64 {
  2442  	k := v.kind()
  2443  	p := v.ptr
  2444  	switch k {
  2445  	case Uint:
  2446  		return uint64(*(*uint)(p))
  2447  	case Uint8:
  2448  		return uint64(*(*uint8)(p))
  2449  	case Uint16:
  2450  		return uint64(*(*uint16)(p))
  2451  	case Uint32:
  2452  		return uint64(*(*uint32)(p))
  2453  	case Uint64:
  2454  		return *(*uint64)(p)
  2455  	case Uintptr:
  2456  		return uint64(*(*uintptr)(p))
  2457  	}
  2458  	panic(&ValueError{"reflect.Value.Uint", v.kind()})
  2459  }
  2460  
  2461  //go:nocheckptr
  2462  // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
  2463  // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
  2464  // and make an exception.
  2465  
  2466  // UnsafeAddr returns a pointer to v's data, as a uintptr.
  2467  // It panics if v is not addressable.
  2468  //
  2469  // It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result.
  2470  func (v Value) UnsafeAddr() uintptr {
  2471  	if v.typ() == nil {
  2472  		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
  2473  	}
  2474  	if v.flag&flagAddr == 0 {
  2475  		panic("reflect.Value.UnsafeAddr of unaddressable value")
  2476  	}
  2477  	// The compiler loses track as it converts to uintptr. Force escape.
  2478  	escapes(v.ptr)
  2479  	return uintptr(v.ptr)
  2480  }
  2481  
  2482  // UnsafePointer returns v's value as a [unsafe.Pointer].
  2483  // It panics if v's Kind is not [Chan], [Func], [Map], [Pointer], [Slice], [String] or [UnsafePointer].
  2484  //
  2485  // If v's Kind is [Func], the returned pointer is an underlying
  2486  // code pointer, but not necessarily enough to identify a
  2487  // single function uniquely. The only guarantee is that the
  2488  // result is zero if and only if v is a nil func Value.
  2489  //
  2490  // If v's Kind is [Slice], the returned pointer is to the first
  2491  // element of the slice. If the slice is nil the returned value
  2492  // is nil.  If the slice is empty but non-nil the return value is non-nil.
  2493  //
  2494  // If v's Kind is [String], the returned pointer is to the first
  2495  // element of the underlying bytes of string.
  2496  func (v Value) UnsafePointer() unsafe.Pointer {
  2497  	k := v.kind()
  2498  	switch k {
  2499  	case Pointer:
  2500  		if !v.typ().Pointers() {
  2501  			// Since it is a not-in-heap pointer, all pointers to the heap are
  2502  			// forbidden! See comment in Value.Elem and issue #48399.
  2503  			if !verifyNotInHeapPtr(*(*uintptr)(v.ptr)) {
  2504  				panic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer")
  2505  			}
  2506  			return *(*unsafe.Pointer)(v.ptr)
  2507  		}
  2508  		fallthrough
  2509  	case Chan, Map, UnsafePointer:
  2510  		return v.pointer()
  2511  	case Func:
  2512  		if v.flag&flagMethod != 0 {
  2513  			// As the doc comment says, the returned pointer is an
  2514  			// underlying code pointer but not necessarily enough to
  2515  			// identify a single function uniquely. All method expressions
  2516  			// created via reflect have the same underlying code pointer,
  2517  			// so their Pointers are equal. The function used here must
  2518  			// match the one used in makeMethodValue.
  2519  			code := methodValueCallCodePtr()
  2520  			return *(*unsafe.Pointer)(unsafe.Pointer(&code))
  2521  		}
  2522  		p := v.pointer()
  2523  		// Non-nil func value points at data block.
  2524  		// First word of data block is actual code.
  2525  		if p != nil {
  2526  			p = *(*unsafe.Pointer)(p)
  2527  		}
  2528  		return p
  2529  	case Slice:
  2530  		return (*unsafeheader.Slice)(v.ptr).Data
  2531  	case String:
  2532  		return (*unsafeheader.String)(v.ptr).Data
  2533  	}
  2534  	panic(&ValueError{"reflect.Value.UnsafePointer", v.kind()})
  2535  }
  2536  
  2537  // StringHeader is the runtime representation of a string.
  2538  // It cannot be used safely or portably and its representation may
  2539  // change in a later release.
  2540  // Moreover, the Data field is not sufficient to guarantee the data
  2541  // it references will not be garbage collected, so programs must keep
  2542  // a separate, correctly typed pointer to the underlying data.
  2543  //
  2544  // Deprecated: Use unsafe.String or unsafe.StringData instead.
  2545  type StringHeader struct {
  2546  	Data uintptr
  2547  	Len  int
  2548  }
  2549  
  2550  // SliceHeader is the runtime representation of a slice.
  2551  // It cannot be used safely or portably and its representation may
  2552  // change in a later release.
  2553  // Moreover, the Data field is not sufficient to guarantee the data
  2554  // it references will not be garbage collected, so programs must keep
  2555  // a separate, correctly typed pointer to the underlying data.
  2556  //
  2557  // Deprecated: Use unsafe.Slice or unsafe.SliceData instead.
  2558  type SliceHeader struct {
  2559  	Data uintptr
  2560  	Len  int
  2561  	Cap  int
  2562  }
  2563  
  2564  func typesMustMatch(what string, t1, t2 Type) {
  2565  	if t1 != t2 {
  2566  		panic(what + ": " + t1.String() + " != " + t2.String())
  2567  	}
  2568  }
  2569  
  2570  // arrayAt returns the i-th element of p,
  2571  // an array whose elements are eltSize bytes wide.
  2572  // The array pointed at by p must have at least i+1 elements:
  2573  // it is invalid (but impossible to check here) to pass i >= len,
  2574  // because then the result will point outside the array.
  2575  // whySafe must explain why i < len. (Passing "i < len" is fine;
  2576  // the benefit is to surface this assumption at the call site.)
  2577  func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
  2578  	return add(p, uintptr(i)*eltSize, "i < len")
  2579  }
  2580  
  2581  // Grow increases the slice's capacity, if necessary, to guarantee space for
  2582  // another n elements. After Grow(n), at least n elements can be appended
  2583  // to the slice without another allocation.
  2584  //
  2585  // It panics if v's Kind is not a [Slice], or if n is negative or too large to
  2586  // allocate the memory, or if [Value.CanSet] returns false.
  2587  func (v Value) Grow(n int) {
  2588  	v.mustBeAssignable()
  2589  	v.mustBe(Slice)
  2590  	v.grow(n)
  2591  }
  2592  
  2593  // grow is identical to Grow but does not check for assignability.
  2594  func (v Value) grow(n int) {
  2595  	p := (*unsafeheader.Slice)(v.ptr)
  2596  	switch {
  2597  	case n < 0:
  2598  		panic("reflect.Value.Grow: negative len")
  2599  	case p.Len+n < 0:
  2600  		panic("reflect.Value.Grow: slice overflow")
  2601  	case p.Len+n > p.Cap:
  2602  		t := v.typ().Elem()
  2603  		*p = growslice(t, *p, n)
  2604  	}
  2605  }
  2606  
  2607  // extendSlice extends a slice by n elements.
  2608  //
  2609  // Unlike Value.grow, which modifies the slice in place and
  2610  // does not change the length of the slice in place,
  2611  // extendSlice returns a new slice value with the length
  2612  // incremented by the number of specified elements.
  2613  func (v Value) extendSlice(n int) Value {
  2614  	v.mustBeExported()
  2615  	v.mustBe(Slice)
  2616  
  2617  	// Shallow copy the slice header to avoid mutating the source slice.
  2618  	sh := *(*unsafeheader.Slice)(v.ptr)
  2619  	s := &sh
  2620  	v.ptr = unsafe.Pointer(s)
  2621  	v.flag = flagIndir | flag(Slice) // equivalent flag to MakeSlice
  2622  
  2623  	v.grow(n) // fine to treat as assignable since we allocate a new slice header
  2624  	s.Len += n
  2625  	return v
  2626  }
  2627  
  2628  // Clear clears the contents of a map or zeros the contents of a slice.
  2629  //
  2630  // It panics if v's Kind is not [Map] or [Slice].
  2631  func (v Value) Clear() {
  2632  	switch v.Kind() {
  2633  	case Slice:
  2634  		sh := *(*unsafeheader.Slice)(v.ptr)
  2635  		st := (*sliceType)(unsafe.Pointer(v.typ()))
  2636  		typedarrayclear(st.Elem, sh.Data, sh.Len)
  2637  	case Map:
  2638  		mapclear(v.typ(), v.pointer())
  2639  	default:
  2640  		panic(&ValueError{"reflect.Value.Clear", v.Kind()})
  2641  	}
  2642  }
  2643  
  2644  // Append appends the values x to a slice s and returns the resulting slice.
  2645  // As in Go, each x's value must be assignable to the slice's element type.
  2646  func Append(s Value, x ...Value) Value {
  2647  	s.mustBe(Slice)
  2648  	n := s.Len()
  2649  	s = s.extendSlice(len(x))
  2650  	for i, v := range x {
  2651  		s.Index(n + i).Set(v)
  2652  	}
  2653  	return s
  2654  }
  2655  
  2656  // AppendSlice appends a slice t to a slice s and returns the resulting slice.
  2657  // The slices s and t must have the same element type.
  2658  func AppendSlice(s, t Value) Value {
  2659  	s.mustBe(Slice)
  2660  	t.mustBe(Slice)
  2661  	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
  2662  	ns := s.Len()
  2663  	nt := t.Len()
  2664  	s = s.extendSlice(nt)
  2665  	Copy(s.Slice(ns, ns+nt), t)
  2666  	return s
  2667  }
  2668  
  2669  // Copy copies the contents of src into dst until either
  2670  // dst has been filled or src has been exhausted.
  2671  // It returns the number of elements copied.
  2672  // Dst and src each must have kind [Slice] or [Array], and
  2673  // dst and src must have the same element type.
  2674  // It dst is an [Array], it panics if [Value.CanSet] returns false.
  2675  //
  2676  // As a special case, src can have kind [String] if the element type of dst is kind [Uint8].
  2677  func Copy(dst, src Value) int {
  2678  	dk := dst.kind()
  2679  	if dk != Array && dk != Slice {
  2680  		panic(&ValueError{"reflect.Copy", dk})
  2681  	}
  2682  	if dk == Array {
  2683  		dst.mustBeAssignable()
  2684  	}
  2685  	dst.mustBeExported()
  2686  
  2687  	sk := src.kind()
  2688  	var stringCopy bool
  2689  	if sk != Array && sk != Slice {
  2690  		stringCopy = sk == String && dst.typ().Elem().Kind() == abi.Uint8
  2691  		if !stringCopy {
  2692  			panic(&ValueError{"reflect.Copy", sk})
  2693  		}
  2694  	}
  2695  	src.mustBeExported()
  2696  
  2697  	de := dst.typ().Elem()
  2698  	if !stringCopy {
  2699  		se := src.typ().Elem()
  2700  		typesMustMatch("reflect.Copy", toType(de), toType(se))
  2701  	}
  2702  
  2703  	var ds, ss unsafeheader.Slice
  2704  	if dk == Array {
  2705  		ds.Data = dst.ptr
  2706  		ds.Len = dst.Len()
  2707  		ds.Cap = ds.Len
  2708  	} else {
  2709  		ds = *(*unsafeheader.Slice)(dst.ptr)
  2710  	}
  2711  	if sk == Array {
  2712  		ss.Data = src.ptr
  2713  		ss.Len = src.Len()
  2714  		ss.Cap = ss.Len
  2715  	} else if sk == Slice {
  2716  		ss = *(*unsafeheader.Slice)(src.ptr)
  2717  	} else {
  2718  		sh := *(*unsafeheader.String)(src.ptr)
  2719  		ss.Data = sh.Data
  2720  		ss.Len = sh.Len
  2721  		ss.Cap = sh.Len
  2722  	}
  2723  
  2724  	return typedslicecopy(de.Common(), ds, ss)
  2725  }
  2726  
  2727  // A runtimeSelect is a single case passed to rselect.
  2728  // This must match ../runtime/select.go:/runtimeSelect
  2729  type runtimeSelect struct {
  2730  	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
  2731  	typ *rtype         // channel type
  2732  	ch  unsafe.Pointer // channel
  2733  	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
  2734  }
  2735  
  2736  // rselect runs a select. It returns the index of the chosen case.
  2737  // If the case was a receive, val is filled in with the received value.
  2738  // The conventional OK bool indicates whether the receive corresponds
  2739  // to a sent value.
  2740  //
  2741  // rselect generally doesn't escape the runtimeSelect slice, except
  2742  // that for the send case the value to send needs to escape. We don't
  2743  // have a way to represent that in the function signature. So we handle
  2744  // that with a forced escape in function Select.
  2745  //
  2746  //go:noescape
  2747  func rselect([]runtimeSelect) (chosen int, recvOK bool)
  2748  
  2749  // A SelectDir describes the communication direction of a select case.
  2750  type SelectDir int
  2751  
  2752  // NOTE: These values must match ../runtime/select.go:/selectDir.
  2753  
  2754  const (
  2755  	_             SelectDir = iota
  2756  	SelectSend              // case Chan <- Send
  2757  	SelectRecv              // case <-Chan:
  2758  	SelectDefault           // default
  2759  )
  2760  
  2761  // A SelectCase describes a single case in a select operation.
  2762  // The kind of case depends on Dir, the communication direction.
  2763  //
  2764  // If Dir is SelectDefault, the case represents a default case.
  2765  // Chan and Send must be zero Values.
  2766  //
  2767  // If Dir is SelectSend, the case represents a send operation.
  2768  // Normally Chan's underlying value must be a channel, and Send's underlying value must be
  2769  // assignable to the channel's element type. As a special case, if Chan is a zero Value,
  2770  // then the case is ignored, and the field Send will also be ignored and may be either zero
  2771  // or non-zero.
  2772  //
  2773  // If Dir is [SelectRecv], the case represents a receive operation.
  2774  // Normally Chan's underlying value must be a channel and Send must be a zero Value.
  2775  // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
  2776  // When a receive operation is selected, the received Value is returned by Select.
  2777  type SelectCase struct {
  2778  	Dir  SelectDir // direction of case
  2779  	Chan Value     // channel to use (for send or receive)
  2780  	Send Value     // value to send (for send)
  2781  }
  2782  
  2783  // Select executes a select operation described by the list of cases.
  2784  // Like the Go select statement, it blocks until at least one of the cases
  2785  // can proceed, makes a uniform pseudo-random choice,
  2786  // and then executes that case. It returns the index of the chosen case
  2787  // and, if that case was a receive operation, the value received and a
  2788  // boolean indicating whether the value corresponds to a send on the channel
  2789  // (as opposed to a zero value received because the channel is closed).
  2790  // Select supports a maximum of 65536 cases.
  2791  func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
  2792  	if len(cases) > 65536 {
  2793  		panic("reflect.Select: too many cases (max 65536)")
  2794  	}
  2795  	// NOTE: Do not trust that caller is not modifying cases data underfoot.
  2796  	// The range is safe because the caller cannot modify our copy of the len
  2797  	// and each iteration makes its own copy of the value c.
  2798  	var runcases []runtimeSelect
  2799  	if len(cases) > 4 {
  2800  		// Slice is heap allocated due to runtime dependent capacity.
  2801  		runcases = make([]runtimeSelect, len(cases))
  2802  	} else {
  2803  		// Slice can be stack allocated due to constant capacity.
  2804  		runcases = make([]runtimeSelect, len(cases), 4)
  2805  	}
  2806  
  2807  	haveDefault := false
  2808  	for i, c := range cases {
  2809  		rc := &runcases[i]
  2810  		rc.dir = c.Dir
  2811  		switch c.Dir {
  2812  		default:
  2813  			panic("reflect.Select: invalid Dir")
  2814  
  2815  		case SelectDefault: // default
  2816  			if haveDefault {
  2817  				panic("reflect.Select: multiple default cases")
  2818  			}
  2819  			haveDefault = true
  2820  			if c.Chan.IsValid() {
  2821  				panic("reflect.Select: default case has Chan value")
  2822  			}
  2823  			if c.Send.IsValid() {
  2824  				panic("reflect.Select: default case has Send value")
  2825  			}
  2826  
  2827  		case SelectSend:
  2828  			ch := c.Chan
  2829  			if !ch.IsValid() {
  2830  				break
  2831  			}
  2832  			ch.mustBe(Chan)
  2833  			ch.mustBeExported()
  2834  			tt := (*chanType)(unsafe.Pointer(ch.typ()))
  2835  			if ChanDir(tt.Dir)&SendDir == 0 {
  2836  				panic("reflect.Select: SendDir case using recv-only channel")
  2837  			}
  2838  			rc.ch = ch.pointer()
  2839  			rc.typ = toRType(&tt.Type)
  2840  			v := c.Send
  2841  			if !v.IsValid() {
  2842  				panic("reflect.Select: SendDir case missing Send value")
  2843  			}
  2844  			v.mustBeExported()
  2845  			v = v.assignTo("reflect.Select", tt.Elem, nil)
  2846  			if v.flag&flagIndir != 0 {
  2847  				rc.val = v.ptr
  2848  			} else {
  2849  				rc.val = unsafe.Pointer(&v.ptr)
  2850  			}
  2851  			// The value to send needs to escape. See the comment at rselect for
  2852  			// why we need forced escape.
  2853  			escapes(rc.val)
  2854  
  2855  		case SelectRecv:
  2856  			if c.Send.IsValid() {
  2857  				panic("reflect.Select: RecvDir case has Send value")
  2858  			}
  2859  			ch := c.Chan
  2860  			if !ch.IsValid() {
  2861  				break
  2862  			}
  2863  			ch.mustBe(Chan)
  2864  			ch.mustBeExported()
  2865  			tt := (*chanType)(unsafe.Pointer(ch.typ()))
  2866  			if ChanDir(tt.Dir)&RecvDir == 0 {
  2867  				panic("reflect.Select: RecvDir case using send-only channel")
  2868  			}
  2869  			rc.ch = ch.pointer()
  2870  			rc.typ = toRType(&tt.Type)
  2871  			rc.val = unsafe_New(tt.Elem)
  2872  		}
  2873  	}
  2874  
  2875  	chosen, recvOK = rselect(runcases)
  2876  	if runcases[chosen].dir == SelectRecv {
  2877  		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
  2878  		t := tt.Elem
  2879  		p := runcases[chosen].val
  2880  		fl := flag(t.Kind())
  2881  		if t.IfaceIndir() {
  2882  			recv = Value{t, p, fl | flagIndir}
  2883  		} else {
  2884  			recv = Value{t, *(*unsafe.Pointer)(p), fl}
  2885  		}
  2886  	}
  2887  	return chosen, recv, recvOK
  2888  }
  2889  
  2890  /*
  2891   * constructors
  2892   */
  2893  
  2894  // implemented in package runtime
  2895  
  2896  //go:noescape
  2897  func unsafe_New(*abi.Type) unsafe.Pointer
  2898  
  2899  //go:noescape
  2900  func unsafe_NewArray(*abi.Type, int) unsafe.Pointer
  2901  
  2902  // MakeSlice creates a new zero-initialized slice value
  2903  // for the specified slice type, length, and capacity.
  2904  func MakeSlice(typ Type, len, cap int) Value {
  2905  	if typ.Kind() != Slice {
  2906  		panic("reflect.MakeSlice of non-slice type")
  2907  	}
  2908  	if len < 0 {
  2909  		panic("reflect.MakeSlice: negative len")
  2910  	}
  2911  	if cap < 0 {
  2912  		panic("reflect.MakeSlice: negative cap")
  2913  	}
  2914  	if len > cap {
  2915  		panic("reflect.MakeSlice: len > cap")
  2916  	}
  2917  
  2918  	s := unsafeheader.Slice{Data: unsafe_NewArray(&(typ.Elem().(*rtype).t), cap), Len: len, Cap: cap}
  2919  	return Value{&typ.(*rtype).t, unsafe.Pointer(&s), flagIndir | flag(Slice)}
  2920  }
  2921  
  2922  // SliceAt returns a [Value] representing a slice whose underlying
  2923  // data starts at p, with length and capacity equal to n.
  2924  //
  2925  // This is like [unsafe.Slice].
  2926  func SliceAt(typ Type, p unsafe.Pointer, n int) Value {
  2927  	unsafeslice(typ.common(), p, n)
  2928  	s := unsafeheader.Slice{Data: p, Len: n, Cap: n}
  2929  	return Value{SliceOf(typ).common(), unsafe.Pointer(&s), flagIndir | flag(Slice)}
  2930  }
  2931  
  2932  // MakeChan creates a new channel with the specified type and buffer size.
  2933  func MakeChan(typ Type, buffer int) Value {
  2934  	if typ.Kind() != Chan {
  2935  		panic("reflect.MakeChan of non-chan type")
  2936  	}
  2937  	if buffer < 0 {
  2938  		panic("reflect.MakeChan: negative buffer size")
  2939  	}
  2940  	if typ.ChanDir() != BothDir {
  2941  		panic("reflect.MakeChan: unidirectional channel type")
  2942  	}
  2943  	t := typ.common()
  2944  	ch := makechan(t, buffer)
  2945  	return Value{t, ch, flag(Chan)}
  2946  }
  2947  
  2948  // MakeMap creates a new map with the specified type.
  2949  func MakeMap(typ Type) Value {
  2950  	return MakeMapWithSize(typ, 0)
  2951  }
  2952  
  2953  // MakeMapWithSize creates a new map with the specified type
  2954  // and initial space for approximately n elements.
  2955  func MakeMapWithSize(typ Type, n int) Value {
  2956  	if typ.Kind() != Map {
  2957  		panic("reflect.MakeMapWithSize of non-map type")
  2958  	}
  2959  	t := typ.common()
  2960  	m := makemap(t, n)
  2961  	return Value{t, m, flag(Map)}
  2962  }
  2963  
  2964  // Indirect returns the value that v points to.
  2965  // If v is a nil pointer, Indirect returns a zero Value.
  2966  // If v is not a pointer, Indirect returns v.
  2967  func Indirect(v Value) Value {
  2968  	if v.Kind() != Pointer {
  2969  		return v
  2970  	}
  2971  	return v.Elem()
  2972  }
  2973  
  2974  // ValueOf returns a new Value initialized to the concrete value
  2975  // stored in the interface i. ValueOf(nil) returns the zero Value.
  2976  func ValueOf(i any) Value {
  2977  	if i == nil {
  2978  		return Value{}
  2979  	}
  2980  	return unpackEface(i)
  2981  }
  2982  
  2983  // Zero returns a Value representing the zero value for the specified type.
  2984  // The result is different from the zero value of the Value struct,
  2985  // which represents no value at all.
  2986  // For example, Zero(TypeOf(42)) returns a Value with Kind [Int] and value 0.
  2987  // The returned value is neither addressable nor settable.
  2988  func Zero(typ Type) Value {
  2989  	if typ == nil {
  2990  		panic("reflect: Zero(nil)")
  2991  	}
  2992  	t := &typ.(*rtype).t
  2993  	fl := flag(t.Kind())
  2994  	if t.IfaceIndir() {
  2995  		var p unsafe.Pointer
  2996  		if t.Size() <= abi.ZeroValSize {
  2997  			p = unsafe.Pointer(&zeroVal[0])
  2998  		} else {
  2999  			p = unsafe_New(t)
  3000  		}
  3001  		return Value{t, p, fl | flagIndir}
  3002  	}
  3003  	return Value{t, nil, fl}
  3004  }
  3005  
  3006  //go:linkname zeroVal runtime.zeroVal
  3007  var zeroVal [abi.ZeroValSize]byte
  3008  
  3009  // New returns a Value representing a pointer to a new zero value
  3010  // for the specified type. That is, the returned Value's Type is [PointerTo](typ).
  3011  func New(typ Type) Value {
  3012  	if typ == nil {
  3013  		panic("reflect: New(nil)")
  3014  	}
  3015  	t := &typ.(*rtype).t
  3016  	pt := ptrTo(t)
  3017  	if pt.IfaceIndir() {
  3018  		// This is a pointer to a not-in-heap type.
  3019  		panic("reflect: New of type that may not be allocated in heap (possibly undefined cgo C type)")
  3020  	}
  3021  	ptr := unsafe_New(t)
  3022  	fl := flag(Pointer)
  3023  	return Value{pt, ptr, fl}
  3024  }
  3025  
  3026  // NewAt returns a Value representing a pointer to a value of the
  3027  // specified type, using p as that pointer.
  3028  func NewAt(typ Type, p unsafe.Pointer) Value {
  3029  	fl := flag(Pointer)
  3030  	t := typ.(*rtype)
  3031  	return Value{t.ptrTo(), p, fl}
  3032  }
  3033  
  3034  // assignTo returns a value v that can be assigned directly to dst.
  3035  // It panics if v is not assignable to dst.
  3036  // For a conversion to an interface type, target, if not nil,
  3037  // is a suggested scratch space to use.
  3038  // target must be initialized memory (or nil).
  3039  func (v Value) assignTo(context string, dst *abi.Type, target unsafe.Pointer) Value {
  3040  	if v.flag&flagMethod != 0 {
  3041  		v = makeMethodValue(context, v)
  3042  	}
  3043  
  3044  	switch {
  3045  	case directlyAssignable(dst, v.typ()):
  3046  		// Overwrite type so that they match.
  3047  		// Same memory layout, so no harm done.
  3048  		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
  3049  		fl |= flag(dst.Kind())
  3050  		return Value{dst, v.ptr, fl}
  3051  
  3052  	case implements(dst, v.typ()):
  3053  		if v.Kind() == Interface && v.IsNil() {
  3054  			// A nil ReadWriter passed to nil Reader is OK,
  3055  			// but using ifaceE2I below will panic.
  3056  			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
  3057  			return Value{dst, nil, flag(Interface)}
  3058  		}
  3059  		x := valueInterface(v, false)
  3060  		if target == nil {
  3061  			target = unsafe_New(dst)
  3062  		}
  3063  		if dst.NumMethod() == 0 {
  3064  			*(*any)(target) = x
  3065  		} else {
  3066  			ifaceE2I(dst, x, target)
  3067  		}
  3068  		return Value{dst, target, flagIndir | flag(Interface)}
  3069  	}
  3070  
  3071  	// Failed.
  3072  	panic(context + ": value of type " + stringFor(v.typ()) + " is not assignable to type " + stringFor(dst))
  3073  }
  3074  
  3075  // Convert returns the value v converted to type t.
  3076  // If the usual Go conversion rules do not allow conversion
  3077  // of the value v to type t, or if converting v to type t panics, Convert panics.
  3078  func (v Value) Convert(t Type) Value {
  3079  	if v.flag&flagMethod != 0 {
  3080  		v = makeMethodValue("Convert", v)
  3081  	}
  3082  	op := convertOp(t.common(), v.typ())
  3083  	if op == nil {
  3084  		panic("reflect.Value.Convert: value of type " + stringFor(v.typ()) + " cannot be converted to type " + t.String())
  3085  	}
  3086  	return op(v, t)
  3087  }
  3088  
  3089  // CanConvert reports whether the value v can be converted to type t.
  3090  // If v.CanConvert(t) returns true then v.Convert(t) will not panic.
  3091  func (v Value) CanConvert(t Type) bool {
  3092  	vt := v.Type()
  3093  	if !vt.ConvertibleTo(t) {
  3094  		return false
  3095  	}
  3096  	// Converting from slice to array or to pointer-to-array can panic
  3097  	// depending on the value.
  3098  	switch {
  3099  	case vt.Kind() == Slice && t.Kind() == Array:
  3100  		if t.Len() > v.Len() {
  3101  			return false
  3102  		}
  3103  	case vt.Kind() == Slice && t.Kind() == Pointer && t.Elem().Kind() == Array:
  3104  		n := t.Elem().Len()
  3105  		if n > v.Len() {
  3106  			return false
  3107  		}
  3108  	}
  3109  	return true
  3110  }
  3111  
  3112  // Comparable reports whether the value v is comparable.
  3113  // If the type of v is an interface, this checks the dynamic type.
  3114  // If this reports true then v.Interface() == x will not panic for any x,
  3115  // nor will v.Equal(u) for any Value u.
  3116  func (v Value) Comparable() bool {
  3117  	k := v.Kind()
  3118  	switch k {
  3119  	case Invalid:
  3120  		return false
  3121  
  3122  	case Array:
  3123  		switch v.Type().Elem().Kind() {
  3124  		case Interface, Array, Struct:
  3125  			for i := 0; i < v.Type().Len(); i++ {
  3126  				if !v.Index(i).Comparable() {
  3127  					return false
  3128  				}
  3129  			}
  3130  			return true
  3131  		}
  3132  		return v.Type().Comparable()
  3133  
  3134  	case Interface:
  3135  		return v.IsNil() || v.Elem().Comparable()
  3136  
  3137  	case Struct:
  3138  		for i := 0; i < v.NumField(); i++ {
  3139  			if !v.Field(i).Comparable() {
  3140  				return false
  3141  			}
  3142  		}
  3143  		return true
  3144  
  3145  	default:
  3146  		return v.Type().Comparable()
  3147  	}
  3148  }
  3149  
  3150  // Equal reports true if v is equal to u.
  3151  // For two invalid values, Equal will report true.
  3152  // For an interface value, Equal will compare the value within the interface.
  3153  // Otherwise, If the values have different types, Equal will report false.
  3154  // Otherwise, for arrays and structs Equal will compare each element in order,
  3155  // and report false if it finds non-equal elements.
  3156  // During all comparisons, if values of the same type are compared,
  3157  // and the type is not comparable, Equal will panic.
  3158  func (v Value) Equal(u Value) bool {
  3159  	if v.Kind() == Interface {
  3160  		v = v.Elem()
  3161  	}
  3162  	if u.Kind() == Interface {
  3163  		u = u.Elem()
  3164  	}
  3165  
  3166  	if !v.IsValid() || !u.IsValid() {
  3167  		return v.IsValid() == u.IsValid()
  3168  	}
  3169  
  3170  	if v.Kind() != u.Kind() || v.Type() != u.Type() {
  3171  		return false
  3172  	}
  3173  
  3174  	// Handle each Kind directly rather than calling valueInterface
  3175  	// to avoid allocating.
  3176  	switch v.Kind() {
  3177  	default:
  3178  		panic("reflect.Value.Equal: invalid Kind")
  3179  	case Bool:
  3180  		return v.Bool() == u.Bool()
  3181  	case Int, Int8, Int16, Int32, Int64:
  3182  		return v.Int() == u.Int()
  3183  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3184  		return v.Uint() == u.Uint()
  3185  	case Float32, Float64:
  3186  		return v.Float() == u.Float()
  3187  	case Complex64, Complex128:
  3188  		return v.Complex() == u.Complex()
  3189  	case String:
  3190  		return v.String() == u.String()
  3191  	case Chan, Pointer, UnsafePointer:
  3192  		return v.Pointer() == u.Pointer()
  3193  	case Array:
  3194  		// u and v have the same type so they have the same length
  3195  		vl := v.Len()
  3196  		if vl == 0 {
  3197  			// panic on [0]func()
  3198  			if !v.Type().Elem().Comparable() {
  3199  				break
  3200  			}
  3201  			return true
  3202  		}
  3203  		for i := 0; i < vl; i++ {
  3204  			if !v.Index(i).Equal(u.Index(i)) {
  3205  				return false
  3206  			}
  3207  		}
  3208  		return true
  3209  	case Struct:
  3210  		// u and v have the same type so they have the same fields
  3211  		nf := v.NumField()
  3212  		for i := 0; i < nf; i++ {
  3213  			if !v.Field(i).Equal(u.Field(i)) {
  3214  				return false
  3215  			}
  3216  		}
  3217  		return true
  3218  	case Func, Map, Slice:
  3219  		break
  3220  	}
  3221  	panic("reflect.Value.Equal: values of type " + v.Type().String() + " are not comparable")
  3222  }
  3223  
  3224  // convertOp returns the function to convert a value of type src
  3225  // to a value of type dst. If the conversion is illegal, convertOp returns nil.
  3226  func convertOp(dst, src *abi.Type) func(Value, Type) Value {
  3227  	switch Kind(src.Kind()) {
  3228  	case Int, Int8, Int16, Int32, Int64:
  3229  		switch Kind(dst.Kind()) {
  3230  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3231  			return cvtInt
  3232  		case Float32, Float64:
  3233  			return cvtIntFloat
  3234  		case String:
  3235  			return cvtIntString
  3236  		}
  3237  
  3238  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3239  		switch Kind(dst.Kind()) {
  3240  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3241  			return cvtUint
  3242  		case Float32, Float64:
  3243  			return cvtUintFloat
  3244  		case String:
  3245  			return cvtUintString
  3246  		}
  3247  
  3248  	case Float32, Float64:
  3249  		switch Kind(dst.Kind()) {
  3250  		case Int, Int8, Int16, Int32, Int64:
  3251  			return cvtFloatInt
  3252  		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3253  			return cvtFloatUint
  3254  		case Float32, Float64:
  3255  			return cvtFloat
  3256  		}
  3257  
  3258  	case Complex64, Complex128:
  3259  		switch Kind(dst.Kind()) {
  3260  		case Complex64, Complex128:
  3261  			return cvtComplex
  3262  		}
  3263  
  3264  	case String:
  3265  		if dst.Kind() == abi.Slice && pkgPathFor(dst.Elem()) == "" {
  3266  			switch Kind(dst.Elem().Kind()) {
  3267  			case Uint8:
  3268  				return cvtStringBytes
  3269  			case Int32:
  3270  				return cvtStringRunes
  3271  			}
  3272  		}
  3273  
  3274  	case Slice:
  3275  		if dst.Kind() == abi.String && pkgPathFor(src.Elem()) == "" {
  3276  			switch Kind(src.Elem().Kind()) {
  3277  			case Uint8:
  3278  				return cvtBytesString
  3279  			case Int32:
  3280  				return cvtRunesString
  3281  			}
  3282  		}
  3283  		// "x is a slice, T is a pointer-to-array type,
  3284  		// and the slice and array types have identical element types."
  3285  		if dst.Kind() == abi.Pointer && dst.Elem().Kind() == abi.Array && src.Elem() == dst.Elem().Elem() {
  3286  			return cvtSliceArrayPtr
  3287  		}
  3288  		// "x is a slice, T is an array type,
  3289  		// and the slice and array types have identical element types."
  3290  		if dst.Kind() == abi.Array && src.Elem() == dst.Elem() {
  3291  			return cvtSliceArray
  3292  		}
  3293  
  3294  	case Chan:
  3295  		if dst.Kind() == abi.Chan && specialChannelAssignability(dst, src) {
  3296  			return cvtDirect
  3297  		}
  3298  	}
  3299  
  3300  	// dst and src have same underlying type.
  3301  	if haveIdenticalUnderlyingType(dst, src, false) {
  3302  		return cvtDirect
  3303  	}
  3304  
  3305  	// dst and src are non-defined pointer types with same underlying base type.
  3306  	if dst.Kind() == abi.Pointer && nameFor(dst) == "" &&
  3307  		src.Kind() == abi.Pointer && nameFor(src) == "" &&
  3308  		haveIdenticalUnderlyingType(elem(dst), elem(src), false) {
  3309  		return cvtDirect
  3310  	}
  3311  
  3312  	if implements(dst, src) {
  3313  		if src.Kind() == abi.Interface {
  3314  			return cvtI2I
  3315  		}
  3316  		return cvtT2I
  3317  	}
  3318  
  3319  	return nil
  3320  }
  3321  
  3322  // makeInt returns a Value of type t equal to bits (possibly truncated),
  3323  // where t is a signed or unsigned int type.
  3324  func makeInt(f flag, bits uint64, t Type) Value {
  3325  	typ := t.common()
  3326  	ptr := unsafe_New(typ)
  3327  	switch typ.Size() {
  3328  	case 1:
  3329  		*(*uint8)(ptr) = uint8(bits)
  3330  	case 2:
  3331  		*(*uint16)(ptr) = uint16(bits)
  3332  	case 4:
  3333  		*(*uint32)(ptr) = uint32(bits)
  3334  	case 8:
  3335  		*(*uint64)(ptr) = bits
  3336  	}
  3337  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3338  }
  3339  
  3340  // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
  3341  // where t is a float32 or float64 type.
  3342  func makeFloat(f flag, v float64, t Type) Value {
  3343  	typ := t.common()
  3344  	ptr := unsafe_New(typ)
  3345  	switch typ.Size() {
  3346  	case 4:
  3347  		*(*float32)(ptr) = float32(v)
  3348  	case 8:
  3349  		*(*float64)(ptr) = v
  3350  	}
  3351  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3352  }
  3353  
  3354  // makeFloat32 returns a Value of type t equal to v, where t is a float32 type.
  3355  func makeFloat32(f flag, v float32, t Type) Value {
  3356  	typ := t.common()
  3357  	ptr := unsafe_New(typ)
  3358  	*(*float32)(ptr) = v
  3359  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3360  }
  3361  
  3362  // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
  3363  // where t is a complex64 or complex128 type.
  3364  func makeComplex(f flag, v complex128, t Type) Value {
  3365  	typ := t.common()
  3366  	ptr := unsafe_New(typ)
  3367  	switch typ.Size() {
  3368  	case 8:
  3369  		*(*complex64)(ptr) = complex64(v)
  3370  	case 16:
  3371  		*(*complex128)(ptr) = v
  3372  	}
  3373  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3374  }
  3375  
  3376  func makeString(f flag, v string, t Type) Value {
  3377  	ret := New(t).Elem()
  3378  	ret.SetString(v)
  3379  	ret.flag = ret.flag&^flagAddr | f
  3380  	return ret
  3381  }
  3382  
  3383  func makeBytes(f flag, v []byte, t Type) Value {
  3384  	ret := New(t).Elem()
  3385  	ret.SetBytes(v)
  3386  	ret.flag = ret.flag&^flagAddr | f
  3387  	return ret
  3388  }
  3389  
  3390  func makeRunes(f flag, v []rune, t Type) Value {
  3391  	ret := New(t).Elem()
  3392  	ret.setRunes(v)
  3393  	ret.flag = ret.flag&^flagAddr | f
  3394  	return ret
  3395  }
  3396  
  3397  // These conversion functions are returned by convertOp
  3398  // for classes of conversions. For example, the first function, cvtInt,
  3399  // takes any value v of signed int type and returns the value converted
  3400  // to type t, where t is any signed or unsigned int type.
  3401  
  3402  // convertOp: intXX -> [u]intXX
  3403  func cvtInt(v Value, t Type) Value {
  3404  	return makeInt(v.flag.ro(), uint64(v.Int()), t)
  3405  }
  3406  
  3407  // convertOp: uintXX -> [u]intXX
  3408  func cvtUint(v Value, t Type) Value {
  3409  	return makeInt(v.flag.ro(), v.Uint(), t)
  3410  }
  3411  
  3412  // convertOp: floatXX -> intXX
  3413  func cvtFloatInt(v Value, t Type) Value {
  3414  	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
  3415  }
  3416  
  3417  // convertOp: floatXX -> uintXX
  3418  func cvtFloatUint(v Value, t Type) Value {
  3419  	return makeInt(v.flag.ro(), uint64(v.Float()), t)
  3420  }
  3421  
  3422  // convertOp: intXX -> floatXX
  3423  func cvtIntFloat(v Value, t Type) Value {
  3424  	return makeFloat(v.flag.ro(), float64(v.Int()), t)
  3425  }
  3426  
  3427  // convertOp: uintXX -> floatXX
  3428  func cvtUintFloat(v Value, t Type) Value {
  3429  	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
  3430  }
  3431  
  3432  // convertOp: floatXX -> floatXX
  3433  func cvtFloat(v Value, t Type) Value {
  3434  	if v.Type().Kind() == Float32 && t.Kind() == Float32 {
  3435  		// Don't do any conversion if both types have underlying type float32.
  3436  		// This avoids converting to float64 and back, which will
  3437  		// convert a signaling NaN to a quiet NaN. See issue 36400.
  3438  		return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t)
  3439  	}
  3440  	return makeFloat(v.flag.ro(), v.Float(), t)
  3441  }
  3442  
  3443  // convertOp: complexXX -> complexXX
  3444  func cvtComplex(v Value, t Type) Value {
  3445  	return makeComplex(v.flag.ro(), v.Complex(), t)
  3446  }
  3447  
  3448  // convertOp: intXX -> string
  3449  func cvtIntString(v Value, t Type) Value {
  3450  	s := "\uFFFD"
  3451  	if x := v.Int(); int64(rune(x)) == x {
  3452  		s = string(rune(x))
  3453  	}
  3454  	return makeString(v.flag.ro(), s, t)
  3455  }
  3456  
  3457  // convertOp: uintXX -> string
  3458  func cvtUintString(v Value, t Type) Value {
  3459  	s := "\uFFFD"
  3460  	if x := v.Uint(); uint64(rune(x)) == x {
  3461  		s = string(rune(x))
  3462  	}
  3463  	return makeString(v.flag.ro(), s, t)
  3464  }
  3465  
  3466  // convertOp: []byte -> string
  3467  func cvtBytesString(v Value, t Type) Value {
  3468  	return makeString(v.flag.ro(), string(v.Bytes()), t)
  3469  }
  3470  
  3471  // convertOp: string -> []byte
  3472  func cvtStringBytes(v Value, t Type) Value {
  3473  	return makeBytes(v.flag.ro(), []byte(v.String()), t)
  3474  }
  3475  
  3476  // convertOp: []rune -> string
  3477  func cvtRunesString(v Value, t Type) Value {
  3478  	return makeString(v.flag.ro(), string(v.runes()), t)
  3479  }
  3480  
  3481  // convertOp: string -> []rune
  3482  func cvtStringRunes(v Value, t Type) Value {
  3483  	return makeRunes(v.flag.ro(), []rune(v.String()), t)
  3484  }
  3485  
  3486  // convertOp: []T -> *[N]T
  3487  func cvtSliceArrayPtr(v Value, t Type) Value {
  3488  	n := t.Elem().Len()
  3489  	if n > v.Len() {
  3490  		panic("reflect: cannot convert slice with length " + itoa.Itoa(v.Len()) + " to pointer to array with length " + itoa.Itoa(n))
  3491  	}
  3492  	h := (*unsafeheader.Slice)(v.ptr)
  3493  	return Value{t.common(), h.Data, v.flag&^(flagIndir|flagAddr|flagKindMask) | flag(Pointer)}
  3494  }
  3495  
  3496  // convertOp: []T -> [N]T
  3497  func cvtSliceArray(v Value, t Type) Value {
  3498  	n := t.Len()
  3499  	if n > v.Len() {
  3500  		panic("reflect: cannot convert slice with length " + itoa.Itoa(v.Len()) + " to array with length " + itoa.Itoa(n))
  3501  	}
  3502  	h := (*unsafeheader.Slice)(v.ptr)
  3503  	typ := t.common()
  3504  	ptr := h.Data
  3505  	c := unsafe_New(typ)
  3506  	typedmemmove(typ, c, ptr)
  3507  	ptr = c
  3508  
  3509  	return Value{typ, ptr, v.flag&^(flagAddr|flagKindMask) | flag(Array)}
  3510  }
  3511  
  3512  // convertOp: direct copy
  3513  func cvtDirect(v Value, typ Type) Value {
  3514  	f := v.flag
  3515  	t := typ.common()
  3516  	ptr := v.ptr
  3517  	if f&flagAddr != 0 {
  3518  		// indirect, mutable word - make a copy
  3519  		c := unsafe_New(t)
  3520  		typedmemmove(t, c, ptr)
  3521  		ptr = c
  3522  		f &^= flagAddr
  3523  	}
  3524  	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
  3525  }
  3526  
  3527  // convertOp: concrete -> interface
  3528  func cvtT2I(v Value, typ Type) Value {
  3529  	target := unsafe_New(typ.common())
  3530  	x := valueInterface(v, false)
  3531  	if typ.NumMethod() == 0 {
  3532  		*(*any)(target) = x
  3533  	} else {
  3534  		ifaceE2I(typ.common(), x, target)
  3535  	}
  3536  	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
  3537  }
  3538  
  3539  // convertOp: interface -> interface
  3540  func cvtI2I(v Value, typ Type) Value {
  3541  	if v.IsNil() {
  3542  		ret := Zero(typ)
  3543  		ret.flag |= v.flag.ro()
  3544  		return ret
  3545  	}
  3546  	return cvtT2I(v.Elem(), typ)
  3547  }
  3548  
  3549  // implemented in ../runtime
  3550  //
  3551  //go:noescape
  3552  func chancap(ch unsafe.Pointer) int
  3553  
  3554  //go:noescape
  3555  func chanclose(ch unsafe.Pointer)
  3556  
  3557  //go:noescape
  3558  func chanlen(ch unsafe.Pointer) int
  3559  
  3560  // Note: some of the noescape annotations below are technically a lie,
  3561  // but safe in the context of this package. Functions like chansend0
  3562  // and mapassign0 don't escape the referent, but may escape anything
  3563  // the referent points to (they do shallow copies of the referent).
  3564  // We add a 0 to their names and wrap them in functions with the
  3565  // proper escape behavior.
  3566  
  3567  //go:noescape
  3568  func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
  3569  
  3570  //go:noescape
  3571  func chansend0(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
  3572  
  3573  func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool {
  3574  	contentEscapes(val)
  3575  	return chansend0(ch, val, nb)
  3576  }
  3577  
  3578  func makechan(typ *abi.Type, size int) (ch unsafe.Pointer)
  3579  func makemap(t *abi.Type, cap int) (m unsafe.Pointer)
  3580  
  3581  //go:noescape
  3582  func mapaccess(t *abi.Type, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
  3583  
  3584  //go:noescape
  3585  func mapaccess_faststr(t *abi.Type, m unsafe.Pointer, key string) (val unsafe.Pointer)
  3586  
  3587  //go:noescape
  3588  func mapassign0(t *abi.Type, m unsafe.Pointer, key, val unsafe.Pointer)
  3589  
  3590  // mapassign should be an internal detail,
  3591  // but widely used packages access it using linkname.
  3592  // Notable members of the hall of shame include:
  3593  //   - github.com/modern-go/reflect2
  3594  //   - github.com/goccy/go-json
  3595  //
  3596  // Do not remove or change the type signature.
  3597  // See go.dev/issue/67401.
  3598  //
  3599  //go:linkname mapassign
  3600  func mapassign(t *abi.Type, m unsafe.Pointer, key, val unsafe.Pointer) {
  3601  	contentEscapes(key)
  3602  	contentEscapes(val)
  3603  	mapassign0(t, m, key, val)
  3604  }
  3605  
  3606  //go:noescape
  3607  func mapassign_faststr0(t *abi.Type, m unsafe.Pointer, key string, val unsafe.Pointer)
  3608  
  3609  func mapassign_faststr(t *abi.Type, m unsafe.Pointer, key string, val unsafe.Pointer) {
  3610  	contentEscapes((*unsafeheader.String)(unsafe.Pointer(&key)).Data)
  3611  	contentEscapes(val)
  3612  	mapassign_faststr0(t, m, key, val)
  3613  }
  3614  
  3615  //go:noescape
  3616  func mapdelete(t *abi.Type, m unsafe.Pointer, key unsafe.Pointer)
  3617  
  3618  //go:noescape
  3619  func mapdelete_faststr(t *abi.Type, m unsafe.Pointer, key string)
  3620  
  3621  //go:noescape
  3622  func maplen(m unsafe.Pointer) int
  3623  
  3624  func mapclear(t *abi.Type, m unsafe.Pointer)
  3625  
  3626  // call calls fn with "stackArgsSize" bytes of stack arguments laid out
  3627  // at stackArgs and register arguments laid out in regArgs. frameSize is
  3628  // the total amount of stack space that will be reserved by call, so this
  3629  // should include enough space to spill register arguments to the stack in
  3630  // case of preemption.
  3631  //
  3632  // After fn returns, call copies stackArgsSize-stackRetOffset result bytes
  3633  // back into stackArgs+stackRetOffset before returning, for any return
  3634  // values passed on the stack. Register-based return values will be found
  3635  // in the same regArgs structure.
  3636  //
  3637  // regArgs must also be prepared with an appropriate ReturnIsPtr bitmap
  3638  // indicating which registers will contain pointer-valued return values. The
  3639  // purpose of this bitmap is to keep pointers visible to the GC between
  3640  // returning from reflectcall and actually using them.
  3641  //
  3642  // If copying result bytes back from the stack, the caller must pass the
  3643  // argument frame type as stackArgsType, so that call can execute appropriate
  3644  // write barriers during the copy.
  3645  //
  3646  // Arguments passed through to call do not escape. The type is used only in a
  3647  // very limited callee of call, the stackArgs are copied, and regArgs is only
  3648  // used in the call frame.
  3649  //
  3650  //go:noescape
  3651  //go:linkname call runtime.reflectcall
  3652  func call(stackArgsType *abi.Type, f, stackArgs unsafe.Pointer, stackArgsSize, stackRetOffset, frameSize uint32, regArgs *abi.RegArgs)
  3653  
  3654  func ifaceE2I(t *abi.Type, src any, dst unsafe.Pointer)
  3655  
  3656  // memmove copies size bytes to dst from src. No write barriers are used.
  3657  //
  3658  //go:noescape
  3659  func memmove(dst, src unsafe.Pointer, size uintptr)
  3660  
  3661  // typedmemmove copies a value of type t to dst from src.
  3662  //
  3663  //go:noescape
  3664  func typedmemmove(t *abi.Type, dst, src unsafe.Pointer)
  3665  
  3666  // typedmemclr zeros the value at ptr of type t.
  3667  //
  3668  //go:noescape
  3669  func typedmemclr(t *abi.Type, ptr unsafe.Pointer)
  3670  
  3671  // typedmemclrpartial is like typedmemclr but assumes that
  3672  // dst points off bytes into the value and only clears size bytes.
  3673  //
  3674  //go:noescape
  3675  func typedmemclrpartial(t *abi.Type, ptr unsafe.Pointer, off, size uintptr)
  3676  
  3677  // typedslicecopy copies a slice of elemType values from src to dst,
  3678  // returning the number of elements copied.
  3679  //
  3680  //go:noescape
  3681  func typedslicecopy(t *abi.Type, dst, src unsafeheader.Slice) int
  3682  
  3683  // typedarrayclear zeroes the value at ptr of an array of elemType,
  3684  // only clears len elem.
  3685  //
  3686  //go:noescape
  3687  func typedarrayclear(elemType *abi.Type, ptr unsafe.Pointer, len int)
  3688  
  3689  //go:noescape
  3690  func typehash(t *abi.Type, p unsafe.Pointer, h uintptr) uintptr
  3691  
  3692  func verifyNotInHeapPtr(p uintptr) bool
  3693  
  3694  //go:noescape
  3695  func growslice(t *abi.Type, old unsafeheader.Slice, num int) unsafeheader.Slice
  3696  
  3697  //go:noescape
  3698  func unsafeslice(t *abi.Type, ptr unsafe.Pointer, len int)
  3699  
  3700  // Dummy annotation marking that the value x escapes,
  3701  // for use in cases where the reflect code is so clever that
  3702  // the compiler cannot follow.
  3703  func escapes(x any) {
  3704  	if dummy.b {
  3705  		dummy.x = x
  3706  	}
  3707  }
  3708  
  3709  var dummy struct {
  3710  	b bool
  3711  	x any
  3712  }
  3713  
  3714  // Dummy annotation marking that the content of value x
  3715  // escapes (i.e. modeling roughly heap=*x),
  3716  // for use in cases where the reflect code is so clever that
  3717  // the compiler cannot follow.
  3718  func contentEscapes(x unsafe.Pointer) {
  3719  	if dummy.b {
  3720  		escapes(*(*any)(x)) // the dereference may not always be safe, but never executed
  3721  	}
  3722  }
  3723  

View as plain text