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
5package reflect
6
7import (
8	"math"
9	"runtime"
10	"unsafe"
11)
12
13const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
14
15// Value is the reflection interface to a Go value.
16//
17// Not all methods apply to all kinds of values. Restrictions,
18// if any, are noted in the documentation for each method.
19// Use the Kind method to find out the kind of value before
20// calling kind-specific methods. Calling a method
21// inappropriate to the kind of type causes a run time panic.
22//
23// The zero Value represents no value.
24// Its IsValid method returns false, its Kind method returns Invalid,
25// its String method returns "<invalid Value>", and all other methods panic.
26// Most functions and methods never return an invalid value.
27// If one does, its documentation states the conditions explicitly.
28//
29// A Value can be used concurrently by multiple goroutines provided that
30// the underlying Go value can be used concurrently for the equivalent
31// direct operations.
32//
33// To compare two Values, compare the results of the Interface method.
34// Using == on two Values does not compare the underlying values
35// they represent.
36type Value struct {
37	// typ holds the type of the value represented by a Value.
38	typ *rtype
39
40	// Pointer-valued data or, if flagIndir is set, pointer to data.
41	// Valid when either flagIndir is set or typ.pointers() is true.
42	ptr unsafe.Pointer
43
44	// flag holds metadata about the value.
45	// The lowest bits are flag bits:
46	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
47	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
48	//	- flagIndir: val holds a pointer to the data
49	//	- flagAddr: v.CanAddr is true (implies flagIndir)
50	//	- flagMethod: v is a method value.
51	// The next five bits give the Kind of the value.
52	// This repeats typ.Kind() except for method values.
53	// The remaining 23+ bits give a method number for method values.
54	// If flag.kind() != Func, code can assume that flagMethod is unset.
55	// If ifaceIndir(typ), code can assume that flagIndir is set.
56	flag
57
58	// A method value represents a curried method invocation
59	// like r.Read for some receiver r. The typ+val+flag bits describe
60	// the receiver r, but the flag's Kind bits say Func (methods are
61	// functions), and the top bits of the flag give the method number
62	// in r's type's method table.
63}
64
65type flag uintptr
66
67const (
68	flagKindWidth        = 5 // there are 27 kinds
69	flagKindMask    flag = 1<<flagKindWidth - 1
70	flagStickyRO    flag = 1 << 5
71	flagEmbedRO     flag = 1 << 6
72	flagIndir       flag = 1 << 7
73	flagAddr        flag = 1 << 8
74	flagMethod      flag = 1 << 9
75	flagMethodShift      = 10
76	flagRO          flag = flagStickyRO | flagEmbedRO
77)
78
79func (f flag) kind() Kind {
80	return Kind(f & flagKindMask)
81}
82
83func (f flag) ro() flag {
84	if f&flagRO != 0 {
85		return flagStickyRO
86	}
87	return 0
88}
89
90// pointer returns the underlying pointer represented by v.
91// v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
92func (v Value) pointer() unsafe.Pointer {
93	if v.typ.size != ptrSize || !v.typ.pointers() {
94		panic("can't call pointer on a non-pointer Value")
95	}
96	if v.flag&flagIndir != 0 {
97		return *(*unsafe.Pointer)(v.ptr)
98	}
99	return v.ptr
100}
101
102// packEface converts v to the empty interface.
103func packEface(v Value) interface{} {
104	t := v.typ
105	var i interface{}
106	e := (*emptyInterface)(unsafe.Pointer(&i))
107	// First, fill in the data portion of the interface.
108	switch {
109	case ifaceIndir(t):
110		if v.flag&flagIndir == 0 {
111			panic("bad indir")
112		}
113		// Value is indirect, and so is the interface we're making.
114		ptr := v.ptr
115		if v.flag&flagAddr != 0 {
116			// TODO: pass safe boolean from valueInterface so
117			// we don't need to copy if safe==true?
118			c := unsafe_New(t)
119			typedmemmove(t, c, ptr)
120			ptr = c
121		}
122		e.word = ptr
123	case v.flag&flagIndir != 0:
124		// Value is indirect, but interface is direct. We need
125		// to load the data at v.ptr into the interface data word.
126		e.word = *(*unsafe.Pointer)(v.ptr)
127	default:
128		// Value is direct, and so is the interface.
129		e.word = v.ptr
130	}
131	// Now, fill in the type portion. We're very careful here not
132	// to have any operation between the e.word and e.typ assignments
133	// that would let the garbage collector observe the partially-built
134	// interface value.
135	e.typ = t
136	return i
137}
138
139// unpackEface converts the empty interface i to a Value.
140func unpackEface(i interface{}) Value {
141	e := (*emptyInterface)(unsafe.Pointer(&i))
142	// NOTE: don't read e.word until we know whether it is really a pointer or not.
143	t := e.typ
144	if t == nil {
145		return Value{}
146	}
147	f := flag(t.Kind())
148	if ifaceIndir(t) {
149		f |= flagIndir
150	}
151	return Value{t, e.word, f}
152}
153
154// A ValueError occurs when a Value method is invoked on
155// a Value that does not support it. Such cases are documented
156// in the description of each method.
157type ValueError struct {
158	Method string
159	Kind   Kind
160}
161
162func (e *ValueError) Error() string {
163	if e.Kind == 0 {
164		return "reflect: call of " + e.Method + " on zero Value"
165	}
166	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
167}
168
169// methodName returns the name of the calling method,
170// assumed to be two stack frames above.
171func methodName() string {
172	pc, _, _, _ := runtime.Caller(2)
173	f := runtime.FuncForPC(pc)
174	if f == nil {
175		return "unknown method"
176	}
177	return f.Name()
178}
179
180// emptyInterface is the header for an interface{} value.
181type emptyInterface struct {
182	typ  *rtype
183	word unsafe.Pointer
184}
185
186// nonEmptyInterface is the header for an interface value with methods.
187type nonEmptyInterface struct {
188	// see ../runtime/iface.go:/Itab
189	itab *struct {
190		ityp *rtype // static interface type
191		typ  *rtype // dynamic concrete type
192		hash uint32 // copy of typ.hash
193		_    [4]byte
194		fun  [100000]unsafe.Pointer // method table
195	}
196	word unsafe.Pointer
197}
198
199// mustBe panics if f's kind is not expected.
200// Making this a method on flag instead of on Value
201// (and embedding flag in Value) means that we can write
202// the very clear v.mustBe(Bool) and have it compile into
203// v.flag.mustBe(Bool), which will only bother to copy the
204// single important word for the receiver.
205func (f flag) mustBe(expected Kind) {
206	// TODO(mvdan): use f.kind() again once mid-stack inlining gets better
207	if Kind(f&flagKindMask) != expected {
208		panic(&ValueError{methodName(), f.kind()})
209	}
210}
211
212// mustBeExported panics if f records that the value was obtained using
213// an unexported field.
214func (f flag) mustBeExported() {
215	if f == 0 || f&flagRO != 0 {
216		f.mustBeExportedSlow()
217	}
218}
219
220func (f flag) mustBeExportedSlow() {
221	if f == 0 {
222		panic(&ValueError{methodName(), Invalid})
223	}
224	if f&flagRO != 0 {
225		panic("reflect: " + methodName() + " using value obtained using unexported field")
226	}
227}
228
229// mustBeAssignable panics if f records that the value is not assignable,
230// which is to say that either it was obtained using an unexported field
231// or it is not addressable.
232func (f flag) mustBeAssignable() {
233	if f&flagRO != 0 || f&flagAddr == 0 {
234		f.mustBeAssignableSlow()
235	}
236}
237
238func (f flag) mustBeAssignableSlow() {
239	if f == 0 {
240		panic(&ValueError{methodName(), Invalid})
241	}
242	// Assignable if addressable and not read-only.
243	if f&flagRO != 0 {
244		panic("reflect: " + methodName() + " using value obtained using unexported field")
245	}
246	if f&flagAddr == 0 {
247		panic("reflect: " + methodName() + " using unaddressable value")
248	}
249}
250
251// Addr returns a pointer value representing the address of v.
252// It panics if CanAddr() returns false.
253// Addr is typically used to obtain a pointer to a struct field
254// or slice element in order to call a method that requires a
255// pointer receiver.
256func (v Value) Addr() Value {
257	if v.flag&flagAddr == 0 {
258		panic("reflect.Value.Addr of unaddressable value")
259	}
260	return Value{v.typ.ptrTo(), v.ptr, v.flag.ro() | flag(Ptr)}
261}
262
263// Bool returns v's underlying value.
264// It panics if v's kind is not Bool.
265func (v Value) Bool() bool {
266	v.mustBe(Bool)
267	return *(*bool)(v.ptr)
268}
269
270// Bytes returns v's underlying value.
271// It panics if v's underlying value is not a slice of bytes.
272func (v Value) Bytes() []byte {
273	v.mustBe(Slice)
274	if v.typ.Elem().Kind() != Uint8 {
275		panic("reflect.Value.Bytes of non-byte slice")
276	}
277	// Slice is always bigger than a word; assume flagIndir.
278	return *(*[]byte)(v.ptr)
279}
280
281// runes returns v's underlying value.
282// It panics if v's underlying value is not a slice of runes (int32s).
283func (v Value) runes() []rune {
284	v.mustBe(Slice)
285	if v.typ.Elem().Kind() != Int32 {
286		panic("reflect.Value.Bytes of non-rune slice")
287	}
288	// Slice is always bigger than a word; assume flagIndir.
289	return *(*[]rune)(v.ptr)
290}
291
292// CanAddr reports whether the value's address can be obtained with Addr.
293// Such values are called addressable. A value is addressable if it is
294// an element of a slice, an element of an addressable array,
295// a field of an addressable struct, or the result of dereferencing a pointer.
296// If CanAddr returns false, calling Addr will panic.
297func (v Value) CanAddr() bool {
298	return v.flag&flagAddr != 0
299}
300
301// CanSet reports whether the value of v can be changed.
302// A Value can be changed only if it is addressable and was not
303// obtained by the use of unexported struct fields.
304// If CanSet returns false, calling Set or any type-specific
305// setter (e.g., SetBool, SetInt) will panic.
306func (v Value) CanSet() bool {
307	return v.flag&(flagAddr|flagRO) == flagAddr
308}
309
310// Call calls the function v with the input arguments in.
311// For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
312// Call panics if v's Kind is not Func.
313// It returns the output results as Values.
314// As in Go, each input argument must be assignable to the
315// type of the function's corresponding input parameter.
316// If v is a variadic function, Call creates the variadic slice parameter
317// itself, copying in the corresponding values.
318func (v Value) Call(in []Value) []Value {
319	v.mustBe(Func)
320	v.mustBeExported()
321	return v.call("Call", in)
322}
323
324// CallSlice calls the variadic function v with the input arguments in,
325// assigning the slice in[len(in)-1] to v's final variadic argument.
326// For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
327// CallSlice panics if v's Kind is not Func or if v is not variadic.
328// It returns the output results as Values.
329// As in Go, each input argument must be assignable to the
330// type of the function's corresponding input parameter.
331func (v Value) CallSlice(in []Value) []Value {
332	v.mustBe(Func)
333	v.mustBeExported()
334	return v.call("CallSlice", in)
335}
336
337var callGC bool // for testing; see TestCallMethodJump
338
339func (v Value) call(op string, in []Value) []Value {
340	// Get function pointer, type.
341	t := (*funcType)(unsafe.Pointer(v.typ))
342	var (
343		fn       unsafe.Pointer
344		rcvr     Value
345		rcvrtype *rtype
346	)
347	if v.flag&flagMethod != 0 {
348		rcvr = v
349		rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
350	} else if v.flag&flagIndir != 0 {
351		fn = *(*unsafe.Pointer)(v.ptr)
352	} else {
353		fn = v.ptr
354	}
355
356	if fn == nil {
357		panic("reflect.Value.Call: call of nil function")
358	}
359
360	isSlice := op == "CallSlice"
361	n := t.NumIn()
362	if isSlice {
363		if !t.IsVariadic() {
364			panic("reflect: CallSlice of non-variadic function")
365		}
366		if len(in) < n {
367			panic("reflect: CallSlice with too few input arguments")
368		}
369		if len(in) > n {
370			panic("reflect: CallSlice with too many input arguments")
371		}
372	} else {
373		if t.IsVariadic() {
374			n--
375		}
376		if len(in) < n {
377			panic("reflect: Call with too few input arguments")
378		}
379		if !t.IsVariadic() && len(in) > n {
380			panic("reflect: Call with too many input arguments")
381		}
382	}
383	for _, x := range in {
384		if x.Kind() == Invalid {
385			panic("reflect: " + op + " using zero Value argument")
386		}
387	}
388	for i := 0; i < n; i++ {
389		if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
390			panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
391		}
392	}
393	if !isSlice && t.IsVariadic() {
394		// prepare slice for remaining values
395		m := len(in) - n
396		slice := MakeSlice(t.In(n), m, m)
397		elem := t.In(n).Elem()
398		for i := 0; i < m; i++ {
399			x := in[n+i]
400			if xt := x.Type(); !xt.AssignableTo(elem) {
401				panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
402			}
403			slice.Index(i).Set(x)
404		}
405		origIn := in
406		in = make([]Value, n+1)
407		copy(in[:n], origIn)
408		in[n] = slice
409	}
410
411	nin := len(in)
412	if nin != t.NumIn() {
413		panic("reflect.Value.Call: wrong argument count")
414	}
415	nout := t.NumOut()
416
417	// Compute frame type.
418	frametype, _, retOffset, _, framePool := funcLayout(t, rcvrtype)
419
420	// Allocate a chunk of memory for frame.
421	var args unsafe.Pointer
422	if nout == 0 {
423		args = framePool.Get().(unsafe.Pointer)
424	} else {
425		// Can't use pool if the function has return values.
426		// We will leak pointer to args in ret, so its lifetime is not scoped.
427		args = unsafe_New(frametype)
428	}
429	off := uintptr(0)
430
431	// Copy inputs into args.
432	if rcvrtype != nil {
433		storeRcvr(rcvr, args)
434		off = ptrSize
435	}
436	for i, v := range in {
437		v.mustBeExported()
438		targ := t.In(i).(*rtype)
439		a := uintptr(targ.align)
440		off = (off + a - 1) &^ (a - 1)
441		n := targ.size
442		if n == 0 {
443			// Not safe to compute args+off pointing at 0 bytes,
444			// because that might point beyond the end of the frame,
445			// but we still need to call assignTo to check assignability.
446			v.assignTo("reflect.Value.Call", targ, nil)
447			continue
448		}
449		addr := add(args, off, "n > 0")
450		v = v.assignTo("reflect.Value.Call", targ, addr)
451		if v.flag&flagIndir != 0 {
452			typedmemmove(targ, addr, v.ptr)
453		} else {
454			*(*unsafe.Pointer)(addr) = v.ptr
455		}
456		off += n
457	}
458
459	// Call.
460	call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
461
462	// For testing; see TestCallMethodJump.
463	if callGC {
464		runtime.GC()
465	}
466
467	var ret []Value
468	if nout == 0 {
469		typedmemclr(frametype, args)
470		framePool.Put(args)
471	} else {
472		// Zero the now unused input area of args,
473		// because the Values returned by this function contain pointers to the args object,
474		// and will thus keep the args object alive indefinitely.
475		typedmemclrpartial(frametype, args, 0, retOffset)
476
477		// Wrap Values around return values in args.
478		ret = make([]Value, nout)
479		off = retOffset
480		for i := 0; i < nout; i++ {
481			tv := t.Out(i)
482			a := uintptr(tv.Align())
483			off = (off + a - 1) &^ (a - 1)
484			if tv.Size() != 0 {
485				fl := flagIndir | flag(tv.Kind())
486				ret[i] = Value{tv.common(), add(args, off, "tv.Size() != 0"), fl}
487				// Note: this does introduce false sharing between results -
488				// if any result is live, they are all live.
489				// (And the space for the args is live as well, but as we've
490				// cleared that space it isn't as big a deal.)
491			} else {
492				// For zero-sized return value, args+off may point to the next object.
493				// In this case, return the zero value instead.
494				ret[i] = Zero(tv)
495			}
496			off += tv.Size()
497		}
498	}
499
500	return ret
501}
502
503// callReflect is the call implementation used by a function
504// returned by MakeFunc. In many ways it is the opposite of the
505// method Value.call above. The method above converts a call using Values
506// into a call of a function with a concrete argument frame, while
507// callReflect converts a call of a function with a concrete argument
508// frame into a call using Values.
509// It is in this file so that it can be next to the call method above.
510// The remainder of the MakeFunc implementation is in makefunc.go.
511//
512// NOTE: This function must be marked as a "wrapper" in the generated code,
513// so that the linker can make it work correctly for panic and recover.
514// The gc compilers know to do that for the name "reflect.callReflect".
515//
516// ctxt is the "closure" generated by MakeFunc.
517// frame is a pointer to the arguments to that closure on the stack.
518// retValid points to a boolean which should be set when the results
519// section of frame is set.
520func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer, retValid *bool) {
521	ftyp := ctxt.ftyp
522	f := ctxt.fn
523
524	// Copy argument frame into Values.
525	ptr := frame
526	off := uintptr(0)
527	in := make([]Value, 0, int(ftyp.inCount))
528	for _, typ := range ftyp.in() {
529		off += -off & uintptr(typ.align-1)
530		v := Value{typ, nil, flag(typ.Kind())}
531		if ifaceIndir(typ) {
532			// value cannot be inlined in interface data.
533			// Must make a copy, because f might keep a reference to it,
534			// and we cannot let f keep a reference to the stack frame
535			// after this function returns, not even a read-only reference.
536			v.ptr = unsafe_New(typ)
537			if typ.size > 0 {
538				typedmemmove(typ, v.ptr, add(ptr, off, "typ.size > 0"))
539			}
540			v.flag |= flagIndir
541		} else {
542			v.ptr = *(*unsafe.Pointer)(add(ptr, off, "1-ptr"))
543		}
544		in = append(in, v)
545		off += typ.size
546	}
547
548	// Call underlying function.
549	out := f(in)
550	numOut := ftyp.NumOut()
551	if len(out) != numOut {
552		panic("reflect: wrong return count from function created by MakeFunc")
553	}
554
555	// Copy results back into argument frame.
556	if numOut > 0 {
557		off += -off & (ptrSize - 1)
558		for i, typ := range ftyp.out() {
559			v := out[i]
560			if v.typ == nil {
561				panic("reflect: function created by MakeFunc using " + funcName(f) +
562					" returned zero Value")
563			}
564			if v.flag&flagRO != 0 {
565				panic("reflect: function created by MakeFunc using " + funcName(f) +
566					" returned value obtained from unexported field")
567			}
568			off += -off & uintptr(typ.align-1)
569			if typ.size == 0 {
570				continue
571			}
572			addr := add(ptr, off, "typ.size > 0")
573
574			// Convert v to type typ if v is assignable to a variable
575			// of type t in the language spec.
576			// See issue 28761.
577			v = v.assignTo("reflect.MakeFunc", typ, addr)
578
579			// We are writing to stack. No write barrier.
580			if v.flag&flagIndir != 0 {
581				memmove(addr, v.ptr, typ.size)
582			} else {
583				*(*uintptr)(addr) = uintptr(v.ptr)
584			}
585			off += typ.size
586		}
587	}
588
589	// Announce that the return values are valid.
590	// After this point the runtime can depend on the return values being valid.
591	*retValid = true
592
593	// We have to make sure that the out slice lives at least until
594	// the runtime knows the return values are valid. Otherwise, the
595	// return values might not be scanned by anyone during a GC.
596	// (out would be dead, and the return slots not yet alive.)
597	runtime.KeepAlive(out)
598
599	// runtime.getArgInfo expects to be able to find ctxt on the
600	// stack when it finds our caller, makeFuncStub. Make sure it
601	// doesn't get garbage collected.
602	runtime.KeepAlive(ctxt)
603}
604
605// methodReceiver returns information about the receiver
606// described by v. The Value v may or may not have the
607// flagMethod bit set, so the kind cached in v.flag should
608// not be used.
609// The return value rcvrtype gives the method's actual receiver type.
610// The return value t gives the method type signature (without the receiver).
611// The return value fn is a pointer to the method code.
612func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *rtype, t *funcType, fn unsafe.Pointer) {
613	i := methodIndex
614	if v.typ.Kind() == Interface {
615		tt := (*interfaceType)(unsafe.Pointer(v.typ))
616		if uint(i) >= uint(len(tt.methods)) {
617			panic("reflect: internal error: invalid method index")
618		}
619		m := &tt.methods[i]
620		if !tt.nameOff(m.name).isExported() {
621			panic("reflect: " + op + " of unexported method")
622		}
623		iface := (*nonEmptyInterface)(v.ptr)
624		if iface.itab == nil {
625			panic("reflect: " + op + " of method on nil interface value")
626		}
627		rcvrtype = iface.itab.typ
628		fn = unsafe.Pointer(&iface.itab.fun[i])
629		t = (*funcType)(unsafe.Pointer(tt.typeOff(m.typ)))
630	} else {
631		rcvrtype = v.typ
632		ms := v.typ.exportedMethods()
633		if uint(i) >= uint(len(ms)) {
634			panic("reflect: internal error: invalid method index")
635		}
636		m := ms[i]
637		if !v.typ.nameOff(m.name).isExported() {
638			panic("reflect: " + op + " of unexported method")
639		}
640		ifn := v.typ.textOff(m.ifn)
641		fn = unsafe.Pointer(&ifn)
642		t = (*funcType)(unsafe.Pointer(v.typ.typeOff(m.mtyp)))
643	}
644	return
645}
646
647// v is a method receiver. Store at p the word which is used to
648// encode that receiver at the start of the argument list.
649// Reflect uses the "interface" calling convention for
650// methods, which always uses one word to record the receiver.
651func storeRcvr(v Value, p unsafe.Pointer) {
652	t := v.typ
653	if t.Kind() == Interface {
654		// the interface data word becomes the receiver word
655		iface := (*nonEmptyInterface)(v.ptr)
656		*(*unsafe.Pointer)(p) = iface.word
657	} else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
658		*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
659	} else {
660		*(*unsafe.Pointer)(p) = v.ptr
661	}
662}
663
664// align returns the result of rounding x up to a multiple of n.
665// n must be a power of two.
666func align(x, n uintptr) uintptr {
667	return (x + n - 1) &^ (n - 1)
668}
669
670// callMethod is the call implementation used by a function returned
671// by makeMethodValue (used by v.Method(i).Interface()).
672// It is a streamlined version of the usual reflect call: the caller has
673// already laid out the argument frame for us, so we don't have
674// to deal with individual Values for each argument.
675// It is in this file so that it can be next to the two similar functions above.
676// The remainder of the makeMethodValue implementation is in makefunc.go.
677//
678// NOTE: This function must be marked as a "wrapper" in the generated code,
679// so that the linker can make it work correctly for panic and recover.
680// The gc compilers know to do that for the name "reflect.callMethod".
681//
682// ctxt is the "closure" generated by makeVethodValue.
683// frame is a pointer to the arguments to that closure on the stack.
684// retValid points to a boolean which should be set when the results
685// section of frame is set.
686func callMethod(ctxt *methodValue, frame unsafe.Pointer, retValid *bool) {
687	rcvr := ctxt.rcvr
688	rcvrtype, t, fn := methodReceiver("call", rcvr, ctxt.method)
689	frametype, argSize, retOffset, _, framePool := funcLayout(t, rcvrtype)
690
691	// Make a new frame that is one word bigger so we can store the receiver.
692	// This space is used for both arguments and return values.
693	scratch := framePool.Get().(unsafe.Pointer)
694
695	// Copy in receiver and rest of args.
696	storeRcvr(rcvr, scratch)
697	// Align the first arg. The alignment can't be larger than ptrSize.
698	argOffset := uintptr(ptrSize)
699	if len(t.in()) > 0 {
700		argOffset = align(argOffset, uintptr(t.in()[0].align))
701	}
702	// Avoid constructing out-of-bounds pointers if there are no args.
703	if argSize-argOffset > 0 {
704		typedmemmovepartial(frametype, add(scratch, argOffset, "argSize > argOffset"), frame, argOffset, argSize-argOffset)
705	}
706
707	// Call.
708	// Call copies the arguments from scratch to the stack, calls fn,
709	// and then copies the results back into scratch.
710	call(frametype, fn, scratch, uint32(frametype.size), uint32(retOffset))
711
712	// Copy return values.
713	// Ignore any changes to args and just copy return values.
714	// Avoid constructing out-of-bounds pointers if there are no return values.
715	if frametype.size-retOffset > 0 {
716		callerRetOffset := retOffset - argOffset
717		// This copies to the stack. Write barriers are not needed.
718		memmove(add(frame, callerRetOffset, "frametype.size > retOffset"),
719			add(scratch, retOffset, "frametype.size > retOffset"),
720			frametype.size-retOffset)
721	}
722
723	// Tell the runtime it can now depend on the return values
724	// being properly initialized.
725	*retValid = true
726
727	// Clear the scratch space and put it back in the pool.
728	// This must happen after the statement above, so that the return
729	// values will always be scanned by someone.
730	typedmemclr(frametype, scratch)
731	framePool.Put(scratch)
732
733	// See the comment in callReflect.
734	runtime.KeepAlive(ctxt)
735}
736
737// funcName returns the name of f, for use in error messages.
738func funcName(f func([]Value) []Value) string {
739	pc := *(*uintptr)(unsafe.Pointer(&f))
740	rf := runtime.FuncForPC(pc)
741	if rf != nil {
742		return rf.Name()
743	}
744	return "closure"
745}
746
747// Cap returns v's capacity.
748// It panics if v's Kind is not Array, Chan, or Slice.
749func (v Value) Cap() int {
750	k := v.kind()
751	switch k {
752	case Array:
753		return v.typ.Len()
754	case Chan:
755		return chancap(v.pointer())
756	case Slice:
757		// Slice is always bigger than a word; assume flagIndir.
758		return (*sliceHeader)(v.ptr).Cap
759	}
760	panic(&ValueError{"reflect.Value.Cap", v.kind()})
761}
762
763// Close closes the channel v.
764// It panics if v's Kind is not Chan.
765func (v Value) Close() {
766	v.mustBe(Chan)
767	v.mustBeExported()
768	chanclose(v.pointer())
769}
770
771// Complex returns v's underlying value, as a complex128.
772// It panics if v's Kind is not Complex64 or Complex128
773func (v Value) Complex() complex128 {
774	k := v.kind()
775	switch k {
776	case Complex64:
777		return complex128(*(*complex64)(v.ptr))
778	case Complex128:
779		return *(*complex128)(v.ptr)
780	}
781	panic(&ValueError{"reflect.Value.Complex", v.kind()})
782}
783
784// Elem returns the value that the interface v contains
785// or that the pointer v points to.
786// It panics if v's Kind is not Interface or Ptr.
787// It returns the zero Value if v is nil.
788func (v Value) Elem() Value {
789	k := v.kind()
790	switch k {
791	case Interface:
792		var eface interface{}
793		if v.typ.NumMethod() == 0 {
794			eface = *(*interface{})(v.ptr)
795		} else {
796			eface = (interface{})(*(*interface {
797				M()
798			})(v.ptr))
799		}
800		x := unpackEface(eface)
801		if x.flag != 0 {
802			x.flag |= v.flag.ro()
803		}
804		return x
805	case Ptr:
806		ptr := v.ptr
807		if v.flag&flagIndir != 0 {
808			ptr = *(*unsafe.Pointer)(ptr)
809		}
810		// The returned value's address is v's value.
811		if ptr == nil {
812			return Value{}
813		}
814		tt := (*ptrType)(unsafe.Pointer(v.typ))
815		typ := tt.elem
816		fl := v.flag&flagRO | flagIndir | flagAddr
817		fl |= flag(typ.Kind())
818		return Value{typ, ptr, fl}
819	}
820	panic(&ValueError{"reflect.Value.Elem", v.kind()})
821}
822
823// Field returns the i'th field of the struct v.
824// It panics if v's Kind is not Struct or i is out of range.
825func (v Value) Field(i int) Value {
826	if v.kind() != Struct {
827		panic(&ValueError{"reflect.Value.Field", v.kind()})
828	}
829	tt := (*structType)(unsafe.Pointer(v.typ))
830	if uint(i) >= uint(len(tt.fields)) {
831		panic("reflect: Field index out of range")
832	}
833	field := &tt.fields[i]
834	typ := field.typ
835
836	// Inherit permission bits from v, but clear flagEmbedRO.
837	fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
838	// Using an unexported field forces flagRO.
839	if !field.name.isExported() {
840		if field.embedded() {
841			fl |= flagEmbedRO
842		} else {
843			fl |= flagStickyRO
844		}
845	}
846	// Either flagIndir is set and v.ptr points at struct,
847	// or flagIndir is not set and v.ptr is the actual struct data.
848	// In the former case, we want v.ptr + offset.
849	// In the latter case, we must have field.offset = 0,
850	// so v.ptr + field.offset is still the correct address.
851	ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field")
852	return Value{typ, ptr, fl}
853}
854
855// FieldByIndex returns the nested field corresponding to index.
856// It panics if v's Kind is not struct.
857func (v Value) FieldByIndex(index []int) Value {
858	if len(index) == 1 {
859		return v.Field(index[0])
860	}
861	v.mustBe(Struct)
862	for i, x := range index {
863		if i > 0 {
864			if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
865				if v.IsNil() {
866					panic("reflect: indirection through nil pointer to embedded struct")
867				}
868				v = v.Elem()
869			}
870		}
871		v = v.Field(x)
872	}
873	return v
874}
875
876// FieldByName returns the struct field with the given name.
877// It returns the zero Value if no field was found.
878// It panics if v's Kind is not struct.
879func (v Value) FieldByName(name string) Value {
880	v.mustBe(Struct)
881	if f, ok := v.typ.FieldByName(name); ok {
882		return v.FieldByIndex(f.Index)
883	}
884	return Value{}
885}
886
887// FieldByNameFunc returns the struct field with a name
888// that satisfies the match function.
889// It panics if v's Kind is not struct.
890// It returns the zero Value if no field was found.
891func (v Value) FieldByNameFunc(match func(string) bool) Value {
892	if f, ok := v.typ.FieldByNameFunc(match); ok {
893		return v.FieldByIndex(f.Index)
894	}
895	return Value{}
896}
897
898// Float returns v's underlying value, as a float64.
899// It panics if v's Kind is not Float32 or Float64
900func (v Value) Float() float64 {
901	k := v.kind()
902	switch k {
903	case Float32:
904		return float64(*(*float32)(v.ptr))
905	case Float64:
906		return *(*float64)(v.ptr)
907	}
908	panic(&ValueError{"reflect.Value.Float", v.kind()})
909}
910
911var uint8Type = TypeOf(uint8(0)).(*rtype)
912
913// Index returns v's i'th element.
914// It panics if v's Kind is not Array, Slice, or String or i is out of range.
915func (v Value) Index(i int) Value {
916	switch v.kind() {
917	case Array:
918		tt := (*arrayType)(unsafe.Pointer(v.typ))
919		if uint(i) >= uint(tt.len) {
920			panic("reflect: array index out of range")
921		}
922		typ := tt.elem
923		offset := uintptr(i) * typ.size
924
925		// Either flagIndir is set and v.ptr points at array,
926		// or flagIndir is not set and v.ptr is the actual array data.
927		// In the former case, we want v.ptr + offset.
928		// In the latter case, we must be doing Index(0), so offset = 0,
929		// so v.ptr + offset is still the correct address.
930		val := add(v.ptr, offset, "same as &v[i], i < tt.len")
931		fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
932		return Value{typ, val, fl}
933
934	case Slice:
935		// Element flag same as Elem of Ptr.
936		// Addressable, indirect, possibly read-only.
937		s := (*sliceHeader)(v.ptr)
938		if uint(i) >= uint(s.Len) {
939			panic("reflect: slice index out of range")
940		}
941		tt := (*sliceType)(unsafe.Pointer(v.typ))
942		typ := tt.elem
943		val := arrayAt(s.Data, i, typ.size, "i < s.Len")
944		fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
945		return Value{typ, val, fl}
946
947	case String:
948		s := (*stringHeader)(v.ptr)
949		if uint(i) >= uint(s.Len) {
950			panic("reflect: string index out of range")
951		}
952		p := arrayAt(s.Data, i, 1, "i < s.Len")
953		fl := v.flag.ro() | flag(Uint8) | flagIndir
954		return Value{uint8Type, p, fl}
955	}
956	panic(&ValueError{"reflect.Value.Index", v.kind()})
957}
958
959// Int returns v's underlying value, as an int64.
960// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
961func (v Value) Int() int64 {
962	k := v.kind()
963	p := v.ptr
964	switch k {
965	case Int:
966		return int64(*(*int)(p))
967	case Int8:
968		return int64(*(*int8)(p))
969	case Int16:
970		return int64(*(*int16)(p))
971	case Int32:
972		return int64(*(*int32)(p))
973	case Int64:
974		return *(*int64)(p)
975	}
976	panic(&ValueError{"reflect.Value.Int", v.kind()})
977}
978
979// CanInterface reports whether Interface can be used without panicking.
980func (v Value) CanInterface() bool {
981	if v.flag == 0 {
982		panic(&ValueError{"reflect.Value.CanInterface", Invalid})
983	}
984	return v.flag&flagRO == 0
985}
986
987// Interface returns v's current value as an interface{}.
988// It is equivalent to:
989//	var i interface{} = (v's underlying value)
990// It panics if the Value was obtained by accessing
991// unexported struct fields.
992func (v Value) Interface() (i interface{}) {
993	return valueInterface(v, true)
994}
995
996func valueInterface(v Value, safe bool) interface{} {
997	if v.flag == 0 {
998		panic(&ValueError{"reflect.Value.Interface", Invalid})
999	}
1000	if safe && v.flag&flagRO != 0 {
1001		// Do not allow access to unexported values via Interface,
1002		// because they might be pointers that should not be
1003		// writable or methods or function that should not be callable.
1004		panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
1005	}
1006	if v.flag&flagMethod != 0 {
1007		v = makeMethodValue("Interface", v)
1008	}
1009
1010	if v.kind() == Interface {
1011		// Special case: return the element inside the interface.
1012		// Empty interface has one layout, all interfaces with
1013		// methods have a second layout.
1014		if v.NumMethod() == 0 {
1015			return *(*interface{})(v.ptr)
1016		}
1017		return *(*interface {
1018			M()
1019		})(v.ptr)
1020	}
1021
1022	// TODO: pass safe to packEface so we don't need to copy if safe==true?
1023	return packEface(v)
1024}
1025
1026// InterfaceData returns the interface v's value as a uintptr pair.
1027// It panics if v's Kind is not Interface.
1028func (v Value) InterfaceData() [2]uintptr {
1029	// TODO: deprecate this
1030	v.mustBe(Interface)
1031	// We treat this as a read operation, so we allow
1032	// it even for unexported data, because the caller
1033	// has to import "unsafe" to turn it into something
1034	// that can be abused.
1035	// Interface value is always bigger than a word; assume flagIndir.
1036	return *(*[2]uintptr)(v.ptr)
1037}
1038
1039// IsNil reports whether its argument v is nil. The argument must be
1040// a chan, func, interface, map, pointer, or slice value; if it is
1041// not, IsNil panics. Note that IsNil is not always equivalent to a
1042// regular comparison with nil in Go. For example, if v was created
1043// by calling ValueOf with an uninitialized interface variable i,
1044// i==nil will be true but v.IsNil will panic as v will be the zero
1045// Value.
1046func (v Value) IsNil() bool {
1047	k := v.kind()
1048	switch k {
1049	case Chan, Func, Map, Ptr, UnsafePointer:
1050		if v.flag&flagMethod != 0 {
1051			return false
1052		}
1053		ptr := v.ptr
1054		if v.flag&flagIndir != 0 {
1055			ptr = *(*unsafe.Pointer)(ptr)
1056		}
1057		return ptr == nil
1058	case Interface, Slice:
1059		// Both interface and slice are nil if first word is 0.
1060		// Both are always bigger than a word; assume flagIndir.
1061		return *(*unsafe.Pointer)(v.ptr) == nil
1062	}
1063	panic(&ValueError{"reflect.Value.IsNil", v.kind()})
1064}
1065
1066// IsValid reports whether v represents a value.
1067// It returns false if v is the zero Value.
1068// If IsValid returns false, all other methods except String panic.
1069// Most functions and methods never return an invalid Value.
1070// If one does, its documentation states the conditions explicitly.
1071func (v Value) IsValid() bool {
1072	return v.flag != 0
1073}
1074
1075// IsZero reports whether v is the zero value for its type.
1076// It panics if the argument is invalid.
1077func (v Value) IsZero() bool {
1078	switch v.kind() {
1079	case Bool:
1080		return !v.Bool()
1081	case Int, Int8, Int16, Int32, Int64:
1082		return v.Int() == 0
1083	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
1084		return v.Uint() == 0
1085	case Float32, Float64:
1086		return math.Float64bits(v.Float()) == 0
1087	case Complex64, Complex128:
1088		c := v.Complex()
1089		return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
1090	case Array:
1091		for i := 0; i < v.Len(); i++ {
1092			if !v.Index(i).IsZero() {
1093				return false
1094			}
1095		}
1096		return true
1097	case Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer:
1098		return v.IsNil()
1099	case String:
1100		return v.Len() == 0
1101	case Struct:
1102		for i := 0; i < v.NumField(); i++ {
1103			if !v.Field(i).IsZero() {
1104				return false
1105			}
1106		}
1107		return true
1108	default:
1109		// This should never happens, but will act as a safeguard for
1110		// later, as a default value doesn't makes sense here.
1111		panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
1112	}
1113}
1114
1115// Kind returns v's Kind.
1116// If v is the zero Value (IsValid returns false), Kind returns Invalid.
1117func (v Value) Kind() Kind {
1118	return v.kind()
1119}
1120
1121// Len returns v's length.
1122// It panics if v's Kind is not Array, Chan, Map, Slice, or String.
1123func (v Value) Len() int {
1124	k := v.kind()
1125	switch k {
1126	case Array:
1127		tt := (*arrayType)(unsafe.Pointer(v.typ))
1128		return int(tt.len)
1129	case Chan:
1130		return chanlen(v.pointer())
1131	case Map:
1132		return maplen(v.pointer())
1133	case Slice:
1134		// Slice is bigger than a word; assume flagIndir.
1135		return (*sliceHeader)(v.ptr).Len
1136	case String:
1137		// String is bigger than a word; assume flagIndir.
1138		return (*stringHeader)(v.ptr).Len
1139	}
1140	panic(&ValueError{"reflect.Value.Len", v.kind()})
1141}
1142
1143// MapIndex returns the value associated with key in the map v.
1144// It panics if v's Kind is not Map.
1145// It returns the zero Value if key is not found in the map or if v represents a nil map.
1146// As in Go, the key's value must be assignable to the map's key type.
1147func (v Value) MapIndex(key Value) Value {
1148	v.mustBe(Map)
1149	tt := (*mapType)(unsafe.Pointer(v.typ))
1150
1151	// Do not require key to be exported, so that DeepEqual
1152	// and other programs can use all the keys returned by
1153	// MapKeys as arguments to MapIndex. If either the map
1154	// or the key is unexported, though, the result will be
1155	// considered unexported. This is consistent with the
1156	// behavior for structs, which allow read but not write
1157	// of unexported fields.
1158	key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
1159
1160	var k unsafe.Pointer
1161	if key.flag&flagIndir != 0 {
1162		k = key.ptr
1163	} else {
1164		k = unsafe.Pointer(&key.ptr)
1165	}
1166	e := mapaccess(v.typ, v.pointer(), k)
1167	if e == nil {
1168		return Value{}
1169	}
1170	typ := tt.elem
1171	fl := (v.flag | key.flag).ro()
1172	fl |= flag(typ.Kind())
1173	return copyVal(typ, fl, e)
1174}
1175
1176// MapKeys returns a slice containing all the keys present in the map,
1177// in unspecified order.
1178// It panics if v's Kind is not Map.
1179// It returns an empty slice if v represents a nil map.
1180func (v Value) MapKeys() []Value {
1181	v.mustBe(Map)
1182	tt := (*mapType)(unsafe.Pointer(v.typ))
1183	keyType := tt.key
1184
1185	fl := v.flag.ro() | flag(keyType.Kind())
1186
1187	m := v.pointer()
1188	mlen := int(0)
1189	if m != nil {
1190		mlen = maplen(m)
1191	}
1192	it := mapiterinit(v.typ, m)
1193	a := make([]Value, mlen)
1194	var i int
1195	for i = 0; i < len(a); i++ {
1196		key := mapiterkey(it)
1197		if key == nil {
1198			// Someone deleted an entry from the map since we
1199			// called maplen above. It's a data race, but nothing
1200			// we can do about it.
1201			break
1202		}
1203		a[i] = copyVal(keyType, fl, key)
1204		mapiternext(it)
1205	}
1206	return a[:i]
1207}
1208
1209// A MapIter is an iterator for ranging over a map.
1210// See Value.MapRange.
1211type MapIter struct {
1212	m  Value
1213	it unsafe.Pointer
1214}
1215
1216// Key returns the key of the iterator's current map entry.
1217func (it *MapIter) Key() Value {
1218	if it.it == nil {
1219		panic("MapIter.Key called before Next")
1220	}
1221	if mapiterkey(it.it) == nil {
1222		panic("MapIter.Key called on exhausted iterator")
1223	}
1224
1225	t := (*mapType)(unsafe.Pointer(it.m.typ))
1226	ktype := t.key
1227	return copyVal(ktype, it.m.flag.ro()|flag(ktype.Kind()), mapiterkey(it.it))
1228}
1229
1230// Value returns the value of the iterator's current map entry.
1231func (it *MapIter) Value() Value {
1232	if it.it == nil {
1233		panic("MapIter.Value called before Next")
1234	}
1235	if mapiterkey(it.it) == nil {
1236		panic("MapIter.Value called on exhausted iterator")
1237	}
1238
1239	t := (*mapType)(unsafe.Pointer(it.m.typ))
1240	vtype := t.elem
1241	return copyVal(vtype, it.m.flag.ro()|flag(vtype.Kind()), mapiterelem(it.it))
1242}
1243
1244// Next advances the map iterator and reports whether there is another
1245// entry. It returns false when the iterator is exhausted; subsequent
1246// calls to Key, Value, or Next will panic.
1247func (it *MapIter) Next() bool {
1248	if it.it == nil {
1249		it.it = mapiterinit(it.m.typ, it.m.pointer())
1250	} else {
1251		if mapiterkey(it.it) == nil {
1252			panic("MapIter.Next called on exhausted iterator")
1253		}
1254		mapiternext(it.it)
1255	}
1256	return mapiterkey(it.it) != nil
1257}
1258
1259// MapRange returns a range iterator for a map.
1260// It panics if v's Kind is not Map.
1261//
1262// Call Next to advance the iterator, and Key/Value to access each entry.
1263// Next returns false when the iterator is exhausted.
1264// MapRange follows the same iteration semantics as a range statement.
1265//
1266// Example:
1267//
1268//	iter := reflect.ValueOf(m).MapRange()
1269// 	for iter.Next() {
1270//		k := iter.Key()
1271//		v := iter.Value()
1272//		...
1273//	}
1274//
1275func (v Value) MapRange() *MapIter {
1276	v.mustBe(Map)
1277	return &MapIter{m: v}
1278}
1279
1280// copyVal returns a Value containing the map key or value at ptr,
1281// allocating a new variable as needed.
1282func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value {
1283	if ifaceIndir(typ) {
1284		// Copy result so future changes to the map
1285		// won't change the underlying value.
1286		c := unsafe_New(typ)
1287		typedmemmove(typ, c, ptr)
1288		return Value{typ, c, fl | flagIndir}
1289	}
1290	return Value{typ, *(*unsafe.Pointer)(ptr), fl}
1291}
1292
1293// Method returns a function value corresponding to v's i'th method.
1294// The arguments to a Call on the returned function should not include
1295// a receiver; the returned function will always use v as the receiver.
1296// Method panics if i is out of range or if v is a nil interface value.
1297func (v Value) Method(i int) Value {
1298	if v.typ == nil {
1299		panic(&ValueError{"reflect.Value.Method", Invalid})
1300	}
1301	if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
1302		panic("reflect: Method index out of range")
1303	}
1304	if v.typ.Kind() == Interface && v.IsNil() {
1305		panic("reflect: Method on nil interface value")
1306	}
1307	fl := v.flag & (flagStickyRO | flagIndir) // Clear flagEmbedRO
1308	fl |= flag(Func)
1309	fl |= flag(i)<<flagMethodShift | flagMethod
1310	return Value{v.typ, v.ptr, fl}
1311}
1312
1313// NumMethod returns the number of exported methods in the value's method set.
1314func (v Value) NumMethod() int {
1315	if v.typ == nil {
1316		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1317	}
1318	if v.flag&flagMethod != 0 {
1319		return 0
1320	}
1321	return v.typ.NumMethod()
1322}
1323
1324// MethodByName returns a function value corresponding to the method
1325// of v with the given name.
1326// The arguments to a Call on the returned function should not include
1327// a receiver; the returned function will always use v as the receiver.
1328// It returns the zero Value if no method was found.
1329func (v Value) MethodByName(name string) Value {
1330	if v.typ == nil {
1331		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1332	}
1333	if v.flag&flagMethod != 0 {
1334		return Value{}
1335	}
1336	m, ok := v.typ.MethodByName(name)
1337	if !ok {
1338		return Value{}
1339	}
1340	return v.Method(m.Index)
1341}
1342
1343// NumField returns the number of fields in the struct v.
1344// It panics if v's Kind is not Struct.
1345func (v Value) NumField() int {
1346	v.mustBe(Struct)
1347	tt := (*structType)(unsafe.Pointer(v.typ))
1348	return len(tt.fields)
1349}
1350
1351// OverflowComplex reports whether the complex128 x cannot be represented by v's type.
1352// It panics if v's Kind is not Complex64 or Complex128.
1353func (v Value) OverflowComplex(x complex128) bool {
1354	k := v.kind()
1355	switch k {
1356	case Complex64:
1357		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1358	case Complex128:
1359		return false
1360	}
1361	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
1362}
1363
1364// OverflowFloat reports whether the float64 x cannot be represented by v's type.
1365// It panics if v's Kind is not Float32 or Float64.
1366func (v Value) OverflowFloat(x float64) bool {
1367	k := v.kind()
1368	switch k {
1369	case Float32:
1370		return overflowFloat32(x)
1371	case Float64:
1372		return false
1373	}
1374	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
1375}
1376
1377func overflowFloat32(x float64) bool {
1378	if x < 0 {
1379		x = -x
1380	}
1381	return math.MaxFloat32 < x && x <= math.MaxFloat64
1382}
1383
1384// OverflowInt reports whether the int64 x cannot be represented by v's type.
1385// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
1386func (v Value) OverflowInt(x int64) bool {
1387	k := v.kind()
1388	switch k {
1389	case Int, Int8, Int16, Int32, Int64:
1390		bitSize := v.typ.size * 8
1391		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1392		return x != trunc
1393	}
1394	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
1395}
1396
1397// OverflowUint reports whether the uint64 x cannot be represented by v's type.
1398// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1399func (v Value) OverflowUint(x uint64) bool {
1400	k := v.kind()
1401	switch k {
1402	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1403		bitSize := v.typ.size * 8
1404		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1405		return x != trunc
1406	}
1407	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
1408}
1409
1410//go:nocheckptr
1411// This prevents inlining Value.Pointer when -d=checkptr is enabled,
1412// which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
1413// and make an exception.
1414
1415// Pointer returns v's value as a uintptr.
1416// It returns uintptr instead of unsafe.Pointer so that
1417// code using reflect cannot obtain unsafe.Pointers
1418// without importing the unsafe package explicitly.
1419// It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1420//
1421// If v's Kind is Func, the returned pointer is an underlying
1422// code pointer, but not necessarily enough to identify a
1423// single function uniquely. The only guarantee is that the
1424// result is zero if and only if v is a nil func Value.
1425//
1426// If v's Kind is Slice, the returned pointer is to the first
1427// element of the slice. If the slice is nil the returned value
1428// is 0.  If the slice is empty but non-nil the return value is non-zero.
1429func (v Value) Pointer() uintptr {
1430	// TODO: deprecate
1431	k := v.kind()
1432	switch k {
1433	case Chan, Map, Ptr, UnsafePointer:
1434		return uintptr(v.pointer())
1435	case Func:
1436		if v.flag&flagMethod != 0 {
1437			// As the doc comment says, the returned pointer is an
1438			// underlying code pointer but not necessarily enough to
1439			// identify a single function uniquely. All method expressions
1440			// created via reflect have the same underlying code pointer,
1441			// so their Pointers are equal. The function used here must
1442			// match the one used in makeMethodValue.
1443			f := methodValueCall
1444			return **(**uintptr)(unsafe.Pointer(&f))
1445		}
1446		p := v.pointer()
1447		// Non-nil func value points at data block.
1448		// First word of data block is actual code.
1449		if p != nil {
1450			p = *(*unsafe.Pointer)(p)
1451		}
1452		return uintptr(p)
1453
1454	case Slice:
1455		return (*SliceHeader)(v.ptr).Data
1456	}
1457	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
1458}
1459
1460// Recv receives and returns a value from the channel v.
1461// It panics if v's Kind is not Chan.
1462// The receive blocks until a value is ready.
1463// The boolean value ok is true if the value x corresponds to a send
1464// on the channel, false if it is a zero value received because the channel is closed.
1465func (v Value) Recv() (x Value, ok bool) {
1466	v.mustBe(Chan)
1467	v.mustBeExported()
1468	return v.recv(false)
1469}
1470
1471// internal recv, possibly non-blocking (nb).
1472// v is known to be a channel.
1473func (v Value) recv(nb bool) (val Value, ok bool) {
1474	tt := (*chanType)(unsafe.Pointer(v.typ))
1475	if ChanDir(tt.dir)&RecvDir == 0 {
1476		panic("reflect: recv on send-only channel")
1477	}
1478	t := tt.elem
1479	val = Value{t, nil, flag(t.Kind())}
1480	var p unsafe.Pointer
1481	if ifaceIndir(t) {
1482		p = unsafe_New(t)
1483		val.ptr = p
1484		val.flag |= flagIndir
1485	} else {
1486		p = unsafe.Pointer(&val.ptr)
1487	}
1488	selected, ok := chanrecv(v.pointer(), nb, p)
1489	if !selected {
1490		val = Value{}
1491	}
1492	return
1493}
1494
1495// Send sends x on the channel v.
1496// It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1497// As in Go, x's value must be assignable to the channel's element type.
1498func (v Value) Send(x Value) {
1499	v.mustBe(Chan)
1500	v.mustBeExported()
1501	v.send(x, false)
1502}
1503
1504// internal send, possibly non-blocking.
1505// v is known to be a channel.
1506func (v Value) send(x Value, nb bool) (selected bool) {
1507	tt := (*chanType)(unsafe.Pointer(v.typ))
1508	if ChanDir(tt.dir)&SendDir == 0 {
1509		panic("reflect: send on recv-only channel")
1510	}
1511	x.mustBeExported()
1512	x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1513	var p unsafe.Pointer
1514	if x.flag&flagIndir != 0 {
1515		p = x.ptr
1516	} else {
1517		p = unsafe.Pointer(&x.ptr)
1518	}
1519	return chansend(v.pointer(), p, nb)
1520}
1521
1522// Set assigns x to the value v.
1523// It panics if CanSet returns false.
1524// As in Go, x's value must be assignable to v's type.
1525func (v Value) Set(x Value) {
1526	v.mustBeAssignable()
1527	x.mustBeExported() // do not let unexported x leak
1528	var target unsafe.Pointer
1529	if v.kind() == Interface {
1530		target = v.ptr
1531	}
1532	x = x.assignTo("reflect.Set", v.typ, target)
1533	if x.flag&flagIndir != 0 {
1534		typedmemmove(v.typ, v.ptr, x.ptr)
1535	} else {
1536		*(*unsafe.Pointer)(v.ptr) = x.ptr
1537	}
1538}
1539
1540// SetBool sets v's underlying value.
1541// It panics if v's Kind is not Bool or if CanSet() is false.
1542func (v Value) SetBool(x bool) {
1543	v.mustBeAssignable()
1544	v.mustBe(Bool)
1545	*(*bool)(v.ptr) = x
1546}
1547
1548// SetBytes sets v's underlying value.
1549// It panics if v's underlying value is not a slice of bytes.
1550func (v Value) SetBytes(x []byte) {
1551	v.mustBeAssignable()
1552	v.mustBe(Slice)
1553	if v.typ.Elem().Kind() != Uint8 {
1554		panic("reflect.Value.SetBytes of non-byte slice")
1555	}
1556	*(*[]byte)(v.ptr) = x
1557}
1558
1559// setRunes sets v's underlying value.
1560// It panics if v's underlying value is not a slice of runes (int32s).
1561func (v Value) setRunes(x []rune) {
1562	v.mustBeAssignable()
1563	v.mustBe(Slice)
1564	if v.typ.Elem().Kind() != Int32 {
1565		panic("reflect.Value.setRunes of non-rune slice")
1566	}
1567	*(*[]rune)(v.ptr) = x
1568}
1569
1570// SetComplex sets v's underlying value to x.
1571// It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1572func (v Value) SetComplex(x complex128) {
1573	v.mustBeAssignable()
1574	switch k := v.kind(); k {
1575	default:
1576		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
1577	case Complex64:
1578		*(*complex64)(v.ptr) = complex64(x)
1579	case Complex128:
1580		*(*complex128)(v.ptr) = x
1581	}
1582}
1583
1584// SetFloat sets v's underlying value to x.
1585// It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1586func (v Value) SetFloat(x float64) {
1587	v.mustBeAssignable()
1588	switch k := v.kind(); k {
1589	default:
1590		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
1591	case Float32:
1592		*(*float32)(v.ptr) = float32(x)
1593	case Float64:
1594		*(*float64)(v.ptr) = x
1595	}
1596}
1597
1598// SetInt sets v's underlying value to x.
1599// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1600func (v Value) SetInt(x int64) {
1601	v.mustBeAssignable()
1602	switch k := v.kind(); k {
1603	default:
1604		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
1605	case Int:
1606		*(*int)(v.ptr) = int(x)
1607	case Int8:
1608		*(*int8)(v.ptr) = int8(x)
1609	case Int16:
1610		*(*int16)(v.ptr) = int16(x)
1611	case Int32:
1612		*(*int32)(v.ptr) = int32(x)
1613	case Int64:
1614		*(*int64)(v.ptr) = x
1615	}
1616}
1617
1618// SetLen sets v's length to n.
1619// It panics if v's Kind is not Slice or if n is negative or
1620// greater than the capacity of the slice.
1621func (v Value) SetLen(n int) {
1622	v.mustBeAssignable()
1623	v.mustBe(Slice)
1624	s := (*sliceHeader)(v.ptr)
1625	if uint(n) > uint(s.Cap) {
1626		panic("reflect: slice length out of range in SetLen")
1627	}
1628	s.Len = n
1629}
1630
1631// SetCap sets v's capacity to n.
1632// It panics if v's Kind is not Slice or if n is smaller than the length or
1633// greater than the capacity of the slice.
1634func (v Value) SetCap(n int) {
1635	v.mustBeAssignable()
1636	v.mustBe(Slice)
1637	s := (*sliceHeader)(v.ptr)
1638	if n < s.Len || n > s.Cap {
1639		panic("reflect: slice capacity out of range in SetCap")
1640	}
1641	s.Cap = n
1642}
1643
1644// SetMapIndex sets the element associated with key in the map v to elem.
1645// It panics if v's Kind is not Map.
1646// If elem is the zero Value, SetMapIndex deletes the key from the map.
1647// Otherwise if v holds a nil map, SetMapIndex will panic.
1648// As in Go, key's elem must be assignable to the map's key type,
1649// and elem's value must be assignable to the map's elem type.
1650func (v Value) SetMapIndex(key, elem Value) {
1651	v.mustBe(Map)
1652	v.mustBeExported()
1653	key.mustBeExported()
1654	tt := (*mapType)(unsafe.Pointer(v.typ))
1655	key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1656	var k unsafe.Pointer
1657	if key.flag&flagIndir != 0 {
1658		k = key.ptr
1659	} else {
1660		k = unsafe.Pointer(&key.ptr)
1661	}
1662	if elem.typ == nil {
1663		mapdelete(v.typ, v.pointer(), k)
1664		return
1665	}
1666	elem.mustBeExported()
1667	elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1668	var e unsafe.Pointer
1669	if elem.flag&flagIndir != 0 {
1670		e = elem.ptr
1671	} else {
1672		e = unsafe.Pointer(&elem.ptr)
1673	}
1674	mapassign(v.typ, v.pointer(), k, e)
1675}
1676
1677// SetUint sets v's underlying value to x.
1678// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1679func (v Value) SetUint(x uint64) {
1680	v.mustBeAssignable()
1681	switch k := v.kind(); k {
1682	default:
1683		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
1684	case Uint:
1685		*(*uint)(v.ptr) = uint(x)
1686	case Uint8:
1687		*(*uint8)(v.ptr) = uint8(x)
1688	case Uint16:
1689		*(*uint16)(v.ptr) = uint16(x)
1690	case Uint32:
1691		*(*uint32)(v.ptr) = uint32(x)
1692	case Uint64:
1693		*(*uint64)(v.ptr) = x
1694	case Uintptr:
1695		*(*uintptr)(v.ptr) = uintptr(x)
1696	}
1697}
1698
1699// SetPointer sets the unsafe.Pointer value v to x.
1700// It panics if v's Kind is not UnsafePointer.
1701func (v Value) SetPointer(x unsafe.Pointer) {
1702	v.mustBeAssignable()
1703	v.mustBe(UnsafePointer)
1704	*(*unsafe.Pointer)(v.ptr) = x
1705}
1706
1707// SetString sets v's underlying value to x.
1708// It panics if v's Kind is not String or if CanSet() is false.
1709func (v Value) SetString(x string) {
1710	v.mustBeAssignable()
1711	v.mustBe(String)
1712	*(*string)(v.ptr) = x
1713}
1714
1715// Slice returns v[i:j].
1716// It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1717// or if the indexes are out of bounds.
1718func (v Value) Slice(i, j int) Value {
1719	var (
1720		cap  int
1721		typ  *sliceType
1722		base unsafe.Pointer
1723	)
1724	switch kind := v.kind(); kind {
1725	default:
1726		panic(&ValueError{"reflect.Value.Slice", v.kind()})
1727
1728	case Array:
1729		if v.flag&flagAddr == 0 {
1730			panic("reflect.Value.Slice: slice of unaddressable array")
1731		}
1732		tt := (*arrayType)(unsafe.Pointer(v.typ))
1733		cap = int(tt.len)
1734		typ = (*sliceType)(unsafe.Pointer(tt.slice))
1735		base = v.ptr
1736
1737	case Slice:
1738		typ = (*sliceType)(unsafe.Pointer(v.typ))
1739		s := (*sliceHeader)(v.ptr)
1740		base = s.Data
1741		cap = s.Cap
1742
1743	case String:
1744		s := (*stringHeader)(v.ptr)
1745		if i < 0 || j < i || j > s.Len {
1746			panic("reflect.Value.Slice: string slice index out of bounds")
1747		}
1748		var t stringHeader
1749		if i < s.Len {
1750			t = stringHeader{arrayAt(s.Data, i, 1, "i < s.Len"), j - i}
1751		}
1752		return Value{v.typ, unsafe.Pointer(&t), v.flag}
1753	}
1754
1755	if i < 0 || j < i || j > cap {
1756		panic("reflect.Value.Slice: slice index out of bounds")
1757	}
1758
1759	// Declare slice so that gc can see the base pointer in it.
1760	var x []unsafe.Pointer
1761
1762	// Reinterpret as *sliceHeader to edit.
1763	s := (*sliceHeader)(unsafe.Pointer(&x))
1764	s.Len = j - i
1765	s.Cap = cap - i
1766	if cap-i > 0 {
1767		s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap")
1768	} else {
1769		// do not advance pointer, to avoid pointing beyond end of slice
1770		s.Data = base
1771	}
1772
1773	fl := v.flag.ro() | flagIndir | flag(Slice)
1774	return Value{typ.common(), unsafe.Pointer(&x), fl}
1775}
1776
1777// Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1778// It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1779// or if the indexes are out of bounds.
1780func (v Value) Slice3(i, j, k int) Value {
1781	var (
1782		cap  int
1783		typ  *sliceType
1784		base unsafe.Pointer
1785	)
1786	switch kind := v.kind(); kind {
1787	default:
1788		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
1789
1790	case Array:
1791		if v.flag&flagAddr == 0 {
1792			panic("reflect.Value.Slice3: slice of unaddressable array")
1793		}
1794		tt := (*arrayType)(unsafe.Pointer(v.typ))
1795		cap = int(tt.len)
1796		typ = (*sliceType)(unsafe.Pointer(tt.slice))
1797		base = v.ptr
1798
1799	case Slice:
1800		typ = (*sliceType)(unsafe.Pointer(v.typ))
1801		s := (*sliceHeader)(v.ptr)
1802		base = s.Data
1803		cap = s.Cap
1804	}
1805
1806	if i < 0 || j < i || k < j || k > cap {
1807		panic("reflect.Value.Slice3: slice index out of bounds")
1808	}
1809
1810	// Declare slice so that the garbage collector
1811	// can see the base pointer in it.
1812	var x []unsafe.Pointer
1813
1814	// Reinterpret as *sliceHeader to edit.
1815	s := (*sliceHeader)(unsafe.Pointer(&x))
1816	s.Len = j - i
1817	s.Cap = k - i
1818	if k-i > 0 {
1819		s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap")
1820	} else {
1821		// do not advance pointer, to avoid pointing beyond end of slice
1822		s.Data = base
1823	}
1824
1825	fl := v.flag.ro() | flagIndir | flag(Slice)
1826	return Value{typ.common(), unsafe.Pointer(&x), fl}
1827}
1828
1829// String returns the string v's underlying value, as a string.
1830// String is a special case because of Go's String method convention.
1831// Unlike the other getters, it does not panic if v's Kind is not String.
1832// Instead, it returns a string of the form "<T value>" where T is v's type.
1833// The fmt package treats Values specially. It does not call their String
1834// method implicitly but instead prints the concrete values they hold.
1835func (v Value) String() string {
1836	switch k := v.kind(); k {
1837	case Invalid:
1838		return "<invalid Value>"
1839	case String:
1840		return *(*string)(v.ptr)
1841	}
1842	// If you call String on a reflect.Value of other type, it's better to
1843	// print something than to panic. Useful in debugging.
1844	return "<" + v.Type().String() + " Value>"
1845}
1846
1847// TryRecv attempts to receive a value from the channel v but will not block.
1848// It panics if v's Kind is not Chan.
1849// If the receive delivers a value, x is the transferred value and ok is true.
1850// If the receive cannot finish without blocking, x is the zero Value and ok is false.
1851// If the channel is closed, x is the zero value for the channel's element type and ok is false.
1852func (v Value) TryRecv() (x Value, ok bool) {
1853	v.mustBe(Chan)
1854	v.mustBeExported()
1855	return v.recv(true)
1856}
1857
1858// TrySend attempts to send x on the channel v but will not block.
1859// It panics if v's Kind is not Chan.
1860// It reports whether the value was sent.
1861// As in Go, x's value must be assignable to the channel's element type.
1862func (v Value) TrySend(x Value) bool {
1863	v.mustBe(Chan)
1864	v.mustBeExported()
1865	return v.send(x, true)
1866}
1867
1868// Type returns v's type.
1869func (v Value) Type() Type {
1870	f := v.flag
1871	if f == 0 {
1872		panic(&ValueError{"reflect.Value.Type", Invalid})
1873	}
1874	if f&flagMethod == 0 {
1875		// Easy case
1876		return v.typ
1877	}
1878
1879	// Method value.
1880	// v.typ describes the receiver, not the method type.
1881	i := int(v.flag) >> flagMethodShift
1882	if v.typ.Kind() == Interface {
1883		// Method on interface.
1884		tt := (*interfaceType)(unsafe.Pointer(v.typ))
1885		if uint(i) >= uint(len(tt.methods)) {
1886			panic("reflect: internal error: invalid method index")
1887		}
1888		m := &tt.methods[i]
1889		return v.typ.typeOff(m.typ)
1890	}
1891	// Method on concrete type.
1892	ms := v.typ.exportedMethods()
1893	if uint(i) >= uint(len(ms)) {
1894		panic("reflect: internal error: invalid method index")
1895	}
1896	m := ms[i]
1897	return v.typ.typeOff(m.mtyp)
1898}
1899
1900// Uint returns v's underlying value, as a uint64.
1901// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1902func (v Value) Uint() uint64 {
1903	k := v.kind()
1904	p := v.ptr
1905	switch k {
1906	case Uint:
1907		return uint64(*(*uint)(p))
1908	case Uint8:
1909		return uint64(*(*uint8)(p))
1910	case Uint16:
1911		return uint64(*(*uint16)(p))
1912	case Uint32:
1913		return uint64(*(*uint32)(p))
1914	case Uint64:
1915		return *(*uint64)(p)
1916	case Uintptr:
1917		return uint64(*(*uintptr)(p))
1918	}
1919	panic(&ValueError{"reflect.Value.Uint", v.kind()})
1920}
1921
1922//go:nocheckptr
1923// This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
1924// which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
1925// and make an exception.
1926
1927// UnsafeAddr returns a pointer to v's data.
1928// It is for advanced clients that also import the "unsafe" package.
1929// It panics if v is not addressable.
1930func (v Value) UnsafeAddr() uintptr {
1931	// TODO: deprecate
1932	if v.typ == nil {
1933		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1934	}
1935	if v.flag&flagAddr == 0 {
1936		panic("reflect.Value.UnsafeAddr of unaddressable value")
1937	}
1938	return uintptr(v.ptr)
1939}
1940
1941// StringHeader is the runtime representation of a string.
1942// It cannot be used safely or portably and its representation may
1943// change in a later release.
1944// Moreover, the Data field is not sufficient to guarantee the data
1945// it references will not be garbage collected, so programs must keep
1946// a separate, correctly typed pointer to the underlying data.
1947type StringHeader struct {
1948	Data uintptr
1949	Len  int
1950}
1951
1952// stringHeader is a safe version of StringHeader used within this package.
1953type stringHeader struct {
1954	Data unsafe.Pointer
1955	Len  int
1956}
1957
1958// SliceHeader is the runtime representation of a slice.
1959// It cannot be used safely or portably and its representation may
1960// change in a later release.
1961// Moreover, the Data field is not sufficient to guarantee the data
1962// it references will not be garbage collected, so programs must keep
1963// a separate, correctly typed pointer to the underlying data.
1964type SliceHeader struct {
1965	Data uintptr
1966	Len  int
1967	Cap  int
1968}
1969
1970// sliceHeader is a safe version of SliceHeader used within this package.
1971type sliceHeader struct {
1972	Data unsafe.Pointer
1973	Len  int
1974	Cap  int
1975}
1976
1977func typesMustMatch(what string, t1, t2 Type) {
1978	if t1 != t2 {
1979		panic(what + ": " + t1.String() + " != " + t2.String())
1980	}
1981}
1982
1983// arrayAt returns the i-th element of p,
1984// an array whose elements are eltSize bytes wide.
1985// The array pointed at by p must have at least i+1 elements:
1986// it is invalid (but impossible to check here) to pass i >= len,
1987// because then the result will point outside the array.
1988// whySafe must explain why i < len. (Passing "i < len" is fine;
1989// the benefit is to surface this assumption at the call site.)
1990func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
1991	return add(p, uintptr(i)*eltSize, "i < len")
1992}
1993
1994// grow grows the slice s so that it can hold extra more values, allocating
1995// more capacity if needed. It also returns the old and new slice lengths.
1996func grow(s Value, extra int) (Value, int, int) {
1997	i0 := s.Len()
1998	i1 := i0 + extra
1999	if i1 < i0 {
2000		panic("reflect.Append: slice overflow")
2001	}
2002	m := s.Cap()
2003	if i1 <= m {
2004		return s.Slice(0, i1), i0, i1
2005	}
2006	if m == 0 {
2007		m = extra
2008	} else {
2009		for m < i1 {
2010			if i0 < 1024 {
2011				m += m
2012			} else {
2013				m += m / 4
2014			}
2015		}
2016	}
2017	t := MakeSlice(s.Type(), i1, m)
2018	Copy(t, s)
2019	return t, i0, i1
2020}
2021
2022// Append appends the values x to a slice s and returns the resulting slice.
2023// As in Go, each x's value must be assignable to the slice's element type.
2024func Append(s Value, x ...Value) Value {
2025	s.mustBe(Slice)
2026	s, i0, i1 := grow(s, len(x))
2027	for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
2028		s.Index(i).Set(x[j])
2029	}
2030	return s
2031}
2032
2033// AppendSlice appends a slice t to a slice s and returns the resulting slice.
2034// The slices s and t must have the same element type.
2035func AppendSlice(s, t Value) Value {
2036	s.mustBe(Slice)
2037	t.mustBe(Slice)
2038	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
2039	s, i0, i1 := grow(s, t.Len())
2040	Copy(s.Slice(i0, i1), t)
2041	return s
2042}
2043
2044// Copy copies the contents of src into dst until either
2045// dst has been filled or src has been exhausted.
2046// It returns the number of elements copied.
2047// Dst and src each must have kind Slice or Array, and
2048// dst and src must have the same element type.
2049//
2050// As a special case, src can have kind String if the element type of dst is kind Uint8.
2051func Copy(dst, src Value) int {
2052	dk := dst.kind()
2053	if dk != Array && dk != Slice {
2054		panic(&ValueError{"reflect.Copy", dk})
2055	}
2056	if dk == Array {
2057		dst.mustBeAssignable()
2058	}
2059	dst.mustBeExported()
2060
2061	sk := src.kind()
2062	var stringCopy bool
2063	if sk != Array && sk != Slice {
2064		stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8
2065		if !stringCopy {
2066			panic(&ValueError{"reflect.Copy", sk})
2067		}
2068	}
2069	src.mustBeExported()
2070
2071	de := dst.typ.Elem()
2072	if !stringCopy {
2073		se := src.typ.Elem()
2074		typesMustMatch("reflect.Copy", de, se)
2075	}
2076
2077	var ds, ss sliceHeader
2078	if dk == Array {
2079		ds.Data = dst.ptr
2080		ds.Len = dst.Len()
2081		ds.Cap = ds.Len
2082	} else {
2083		ds = *(*sliceHeader)(dst.ptr)
2084	}
2085	if sk == Array {
2086		ss.Data = src.ptr
2087		ss.Len = src.Len()
2088		ss.Cap = ss.Len
2089	} else if sk == Slice {
2090		ss = *(*sliceHeader)(src.ptr)
2091	} else {
2092		sh := *(*stringHeader)(src.ptr)
2093		ss.Data = sh.Data
2094		ss.Len = sh.Len
2095		ss.Cap = sh.Len
2096	}
2097
2098	return typedslicecopy(de.common(), ds, ss)
2099}
2100
2101// A runtimeSelect is a single case passed to rselect.
2102// This must match ../runtime/select.go:/runtimeSelect
2103type runtimeSelect struct {
2104	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
2105	typ *rtype         // channel type
2106	ch  unsafe.Pointer // channel
2107	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
2108}
2109
2110// rselect runs a select. It returns the index of the chosen case.
2111// If the case was a receive, val is filled in with the received value.
2112// The conventional OK bool indicates whether the receive corresponds
2113// to a sent value.
2114//go:noescape
2115func rselect([]runtimeSelect) (chosen int, recvOK bool)
2116
2117// A SelectDir describes the communication direction of a select case.
2118type SelectDir int
2119
2120// NOTE: These values must match ../runtime/select.go:/selectDir.
2121
2122const (
2123	_             SelectDir = iota
2124	SelectSend              // case Chan <- Send
2125	SelectRecv              // case <-Chan:
2126	SelectDefault           // default
2127)
2128
2129// A SelectCase describes a single case in a select operation.
2130// The kind of case depends on Dir, the communication direction.
2131//
2132// If Dir is SelectDefault, the case represents a default case.
2133// Chan and Send must be zero Values.
2134//
2135// If Dir is SelectSend, the case represents a send operation.
2136// Normally Chan's underlying value must be a channel, and Send's underlying value must be
2137// assignable to the channel's element type. As a special case, if Chan is a zero Value,
2138// then the case is ignored, and the field Send will also be ignored and may be either zero
2139// or non-zero.
2140//
2141// If Dir is SelectRecv, the case represents a receive operation.
2142// Normally Chan's underlying value must be a channel and Send must be a zero Value.
2143// If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
2144// When a receive operation is selected, the received Value is returned by Select.
2145//
2146type SelectCase struct {
2147	Dir  SelectDir // direction of case
2148	Chan Value     // channel to use (for send or receive)
2149	Send Value     // value to send (for send)
2150}
2151
2152// Select executes a select operation described by the list of cases.
2153// Like the Go select statement, it blocks until at least one of the cases
2154// can proceed, makes a uniform pseudo-random choice,
2155// and then executes that case. It returns the index of the chosen case
2156// and, if that case was a receive operation, the value received and a
2157// boolean indicating whether the value corresponds to a send on the channel
2158// (as opposed to a zero value received because the channel is closed).
2159func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
2160	// NOTE: Do not trust that caller is not modifying cases data underfoot.
2161	// The range is safe because the caller cannot modify our copy of the len
2162	// and each iteration makes its own copy of the value c.
2163	runcases := make([]runtimeSelect, len(cases))
2164	haveDefault := false
2165	for i, c := range cases {
2166		rc := &runcases[i]
2167		rc.dir = c.Dir
2168		switch c.Dir {
2169		default:
2170			panic("reflect.Select: invalid Dir")
2171
2172		case SelectDefault: // default
2173			if haveDefault {
2174				panic("reflect.Select: multiple default cases")
2175			}
2176			haveDefault = true
2177			if c.Chan.IsValid() {
2178				panic("reflect.Select: default case has Chan value")
2179			}
2180			if c.Send.IsValid() {
2181				panic("reflect.Select: default case has Send value")
2182			}
2183
2184		case SelectSend:
2185			ch := c.Chan
2186			if !ch.IsValid() {
2187				break
2188			}
2189			ch.mustBe(Chan)
2190			ch.mustBeExported()
2191			tt := (*chanType)(unsafe.Pointer(ch.typ))
2192			if ChanDir(tt.dir)&SendDir == 0 {
2193				panic("reflect.Select: SendDir case using recv-only channel")
2194			}
2195			rc.ch = ch.pointer()
2196			rc.typ = &tt.rtype
2197			v := c.Send
2198			if !v.IsValid() {
2199				panic("reflect.Select: SendDir case missing Send value")
2200			}
2201			v.mustBeExported()
2202			v = v.assignTo("reflect.Select", tt.elem, nil)
2203			if v.flag&flagIndir != 0 {
2204				rc.val = v.ptr
2205			} else {
2206				rc.val = unsafe.Pointer(&v.ptr)
2207			}
2208
2209		case SelectRecv:
2210			if c.Send.IsValid() {
2211				panic("reflect.Select: RecvDir case has Send value")
2212			}
2213			ch := c.Chan
2214			if !ch.IsValid() {
2215				break
2216			}
2217			ch.mustBe(Chan)
2218			ch.mustBeExported()
2219			tt := (*chanType)(unsafe.Pointer(ch.typ))
2220			if ChanDir(tt.dir)&RecvDir == 0 {
2221				panic("reflect.Select: RecvDir case using send-only channel")
2222			}
2223			rc.ch = ch.pointer()
2224			rc.typ = &tt.rtype
2225			rc.val = unsafe_New(tt.elem)
2226		}
2227	}
2228
2229	chosen, recvOK = rselect(runcases)
2230	if runcases[chosen].dir == SelectRecv {
2231		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
2232		t := tt.elem
2233		p := runcases[chosen].val
2234		fl := flag(t.Kind())
2235		if ifaceIndir(t) {
2236			recv = Value{t, p, fl | flagIndir}
2237		} else {
2238			recv = Value{t, *(*unsafe.Pointer)(p), fl}
2239		}
2240	}
2241	return chosen, recv, recvOK
2242}
2243
2244/*
2245 * constructors
2246 */
2247
2248// implemented in package runtime
2249func unsafe_New(*rtype) unsafe.Pointer
2250func unsafe_NewArray(*rtype, int) unsafe.Pointer
2251
2252// MakeSlice creates a new zero-initialized slice value
2253// for the specified slice type, length, and capacity.
2254func MakeSlice(typ Type, len, cap int) Value {
2255	if typ.Kind() != Slice {
2256		panic("reflect.MakeSlice of non-slice type")
2257	}
2258	if len < 0 {
2259		panic("reflect.MakeSlice: negative len")
2260	}
2261	if cap < 0 {
2262		panic("reflect.MakeSlice: negative cap")
2263	}
2264	if len > cap {
2265		panic("reflect.MakeSlice: len > cap")
2266	}
2267
2268	s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap}
2269	return Value{typ.(*rtype), unsafe.Pointer(&s), flagIndir | flag(Slice)}
2270}
2271
2272// MakeChan creates a new channel with the specified type and buffer size.
2273func MakeChan(typ Type, buffer int) Value {
2274	if typ.Kind() != Chan {
2275		panic("reflect.MakeChan of non-chan type")
2276	}
2277	if buffer < 0 {
2278		panic("reflect.MakeChan: negative buffer size")
2279	}
2280	if typ.ChanDir() != BothDir {
2281		panic("reflect.MakeChan: unidirectional channel type")
2282	}
2283	t := typ.(*rtype)
2284	ch := makechan(t, buffer)
2285	return Value{t, ch, flag(Chan)}
2286}
2287
2288// MakeMap creates a new map with the specified type.
2289func MakeMap(typ Type) Value {
2290	return MakeMapWithSize(typ, 0)
2291}
2292
2293// MakeMapWithSize creates a new map with the specified type
2294// and initial space for approximately n elements.
2295func MakeMapWithSize(typ Type, n int) Value {
2296	if typ.Kind() != Map {
2297		panic("reflect.MakeMapWithSize of non-map type")
2298	}
2299	t := typ.(*rtype)
2300	m := makemap(t, n)
2301	return Value{t, m, flag(Map)}
2302}
2303
2304// Indirect returns the value that v points to.
2305// If v is a nil pointer, Indirect returns a zero Value.
2306// If v is not a pointer, Indirect returns v.
2307func Indirect(v Value) Value {
2308	if v.Kind() != Ptr {
2309		return v
2310	}
2311	return v.Elem()
2312}
2313
2314// ValueOf returns a new Value initialized to the concrete value
2315// stored in the interface i. ValueOf(nil) returns the zero Value.
2316func ValueOf(i interface{}) Value {
2317	if i == nil {
2318		return Value{}
2319	}
2320
2321	// TODO: Maybe allow contents of a Value to live on the stack.
2322	// For now we make the contents always escape to the heap. It
2323	// makes life easier in a few places (see chanrecv/mapassign
2324	// comment below).
2325	escapes(i)
2326
2327	return unpackEface(i)
2328}
2329
2330// Zero returns a Value representing the zero value for the specified type.
2331// The result is different from the zero value of the Value struct,
2332// which represents no value at all.
2333// For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2334// The returned value is neither addressable nor settable.
2335func Zero(typ Type) Value {
2336	if typ == nil {
2337		panic("reflect: Zero(nil)")
2338	}
2339	t := typ.(*rtype)
2340	fl := flag(t.Kind())
2341	if ifaceIndir(t) {
2342		return Value{t, unsafe_New(t), fl | flagIndir}
2343	}
2344	return Value{t, nil, fl}
2345}
2346
2347// New returns a Value representing a pointer to a new zero value
2348// for the specified type. That is, the returned Value's Type is PtrTo(typ).
2349func New(typ Type) Value {
2350	if typ == nil {
2351		panic("reflect: New(nil)")
2352	}
2353	t := typ.(*rtype)
2354	ptr := unsafe_New(t)
2355	fl := flag(Ptr)
2356	return Value{t.ptrTo(), ptr, fl}
2357}
2358
2359// NewAt returns a Value representing a pointer to a value of the
2360// specified type, using p as that pointer.
2361func NewAt(typ Type, p unsafe.Pointer) Value {
2362	fl := flag(Ptr)
2363	t := typ.(*rtype)
2364	return Value{t.ptrTo(), p, fl}
2365}
2366
2367// assignTo returns a value v that can be assigned directly to typ.
2368// It panics if v is not assignable to typ.
2369// For a conversion to an interface type, target is a suggested scratch space to use.
2370func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
2371	if v.flag&flagMethod != 0 {
2372		v = makeMethodValue(context, v)
2373	}
2374
2375	switch {
2376	case directlyAssignable(dst, v.typ):
2377		// Overwrite type so that they match.
2378		// Same memory layout, so no harm done.
2379		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
2380		fl |= flag(dst.Kind())
2381		return Value{dst, v.ptr, fl}
2382
2383	case implements(dst, v.typ):
2384		if target == nil {
2385			target = unsafe_New(dst)
2386		}
2387		if v.Kind() == Interface && v.IsNil() {
2388			// A nil ReadWriter passed to nil Reader is OK,
2389			// but using ifaceE2I below will panic.
2390			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
2391			return Value{dst, nil, flag(Interface)}
2392		}
2393		x := valueInterface(v, false)
2394		if dst.NumMethod() == 0 {
2395			*(*interface{})(target) = x
2396		} else {
2397			ifaceE2I(dst, x, target)
2398		}
2399		return Value{dst, target, flagIndir | flag(Interface)}
2400	}
2401
2402	// Failed.
2403	panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2404}
2405
2406// Convert returns the value v converted to type t.
2407// If the usual Go conversion rules do not allow conversion
2408// of the value v to type t, Convert panics.
2409func (v Value) Convert(t Type) Value {
2410	if v.flag&flagMethod != 0 {
2411		v = makeMethodValue("Convert", v)
2412	}
2413	op := convertOp(t.common(), v.typ)
2414	if op == nil {
2415		panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2416	}
2417	return op(v, t)
2418}
2419
2420// convertOp returns the function to convert a value of type src
2421// to a value of type dst. If the conversion is illegal, convertOp returns nil.
2422func convertOp(dst, src *rtype) func(Value, Type) Value {
2423	switch src.Kind() {
2424	case Int, Int8, Int16, Int32, Int64:
2425		switch dst.Kind() {
2426		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2427			return cvtInt
2428		case Float32, Float64:
2429			return cvtIntFloat
2430		case String:
2431			return cvtIntString
2432		}
2433
2434	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2435		switch dst.Kind() {
2436		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2437			return cvtUint
2438		case Float32, Float64:
2439			return cvtUintFloat
2440		case String:
2441			return cvtUintString
2442		}
2443
2444	case Float32, Float64:
2445		switch dst.Kind() {
2446		case Int, Int8, Int16, Int32, Int64:
2447			return cvtFloatInt
2448		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2449			return cvtFloatUint
2450		case Float32, Float64:
2451			return cvtFloat
2452		}
2453
2454	case Complex64, Complex128:
2455		switch dst.Kind() {
2456		case Complex64, Complex128:
2457			return cvtComplex
2458		}
2459
2460	case String:
2461		if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2462			switch dst.Elem().Kind() {
2463			case Uint8:
2464				return cvtStringBytes
2465			case Int32:
2466				return cvtStringRunes
2467			}
2468		}
2469
2470	case Slice:
2471		if dst.Kind() == String && src.Elem().PkgPath() == "" {
2472			switch src.Elem().Kind() {
2473			case Uint8:
2474				return cvtBytesString
2475			case Int32:
2476				return cvtRunesString
2477			}
2478		}
2479
2480	case Chan:
2481		if dst.Kind() == Chan && specialChannelAssignability(dst, src) {
2482			return cvtDirect
2483		}
2484	}
2485
2486	// dst and src have same underlying type.
2487	if haveIdenticalUnderlyingType(dst, src, false) {
2488		return cvtDirect
2489	}
2490
2491	// dst and src are non-defined pointer types with same underlying base type.
2492	if dst.Kind() == Ptr && dst.Name() == "" &&
2493		src.Kind() == Ptr && src.Name() == "" &&
2494		haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
2495		return cvtDirect
2496	}
2497
2498	if implements(dst, src) {
2499		if src.Kind() == Interface {
2500			return cvtI2I
2501		}
2502		return cvtT2I
2503	}
2504
2505	return nil
2506}
2507
2508// makeInt returns a Value of type t equal to bits (possibly truncated),
2509// where t is a signed or unsigned int type.
2510func makeInt(f flag, bits uint64, t Type) Value {
2511	typ := t.common()
2512	ptr := unsafe_New(typ)
2513	switch typ.size {
2514	case 1:
2515		*(*uint8)(ptr) = uint8(bits)
2516	case 2:
2517		*(*uint16)(ptr) = uint16(bits)
2518	case 4:
2519		*(*uint32)(ptr) = uint32(bits)
2520	case 8:
2521		*(*uint64)(ptr) = bits
2522	}
2523	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2524}
2525
2526// makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2527// where t is a float32 or float64 type.
2528func makeFloat(f flag, v float64, t Type) Value {
2529	typ := t.common()
2530	ptr := unsafe_New(typ)
2531	switch typ.size {
2532	case 4:
2533		*(*float32)(ptr) = float32(v)
2534	case 8:
2535		*(*float64)(ptr) = v
2536	}
2537	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2538}
2539
2540// makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2541// where t is a complex64 or complex128 type.
2542func makeComplex(f flag, v complex128, t Type) Value {
2543	typ := t.common()
2544	ptr := unsafe_New(typ)
2545	switch typ.size {
2546	case 8:
2547		*(*complex64)(ptr) = complex64(v)
2548	case 16:
2549		*(*complex128)(ptr) = v
2550	}
2551	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
2552}
2553
2554func makeString(f flag, v string, t Type) Value {
2555	ret := New(t).Elem()
2556	ret.SetString(v)
2557	ret.flag = ret.flag&^flagAddr | f
2558	return ret
2559}
2560
2561func makeBytes(f flag, v []byte, t Type) Value {
2562	ret := New(t).Elem()
2563	ret.SetBytes(v)
2564	ret.flag = ret.flag&^flagAddr | f
2565	return ret
2566}
2567
2568func makeRunes(f flag, v []rune, t Type) Value {
2569	ret := New(t).Elem()
2570	ret.setRunes(v)
2571	ret.flag = ret.flag&^flagAddr | f
2572	return ret
2573}
2574
2575// These conversion functions are returned by convertOp
2576// for classes of conversions. For example, the first function, cvtInt,
2577// takes any value v of signed int type and returns the value converted
2578// to type t, where t is any signed or unsigned int type.
2579
2580// convertOp: intXX -> [u]intXX
2581func cvtInt(v Value, t Type) Value {
2582	return makeInt(v.flag.ro(), uint64(v.Int()), t)
2583}
2584
2585// convertOp: uintXX -> [u]intXX
2586func cvtUint(v Value, t Type) Value {
2587	return makeInt(v.flag.ro(), v.Uint(), t)
2588}
2589
2590// convertOp: floatXX -> intXX
2591func cvtFloatInt(v Value, t Type) Value {
2592	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
2593}
2594
2595// convertOp: floatXX -> uintXX
2596func cvtFloatUint(v Value, t Type) Value {
2597	return makeInt(v.flag.ro(), uint64(v.Float()), t)
2598}
2599
2600// convertOp: intXX -> floatXX
2601func cvtIntFloat(v Value, t Type) Value {
2602	return makeFloat(v.flag.ro(), float64(v.Int()), t)
2603}
2604
2605// convertOp: uintXX -> floatXX
2606func cvtUintFloat(v Value, t Type) Value {
2607	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
2608}
2609
2610// convertOp: floatXX -> floatXX
2611func cvtFloat(v Value, t Type) Value {
2612	return makeFloat(v.flag.ro(), v.Float(), t)
2613}
2614
2615// convertOp: complexXX -> complexXX
2616func cvtComplex(v Value, t Type) Value {
2617	return makeComplex(v.flag.ro(), v.Complex(), t)
2618}
2619
2620// convertOp: intXX -> string
2621func cvtIntString(v Value, t Type) Value {
2622	return makeString(v.flag.ro(), string(v.Int()), t)
2623}
2624
2625// convertOp: uintXX -> string
2626func cvtUintString(v Value, t Type) Value {
2627	return makeString(v.flag.ro(), string(v.Uint()), t)
2628}
2629
2630// convertOp: []byte -> string
2631func cvtBytesString(v Value, t Type) Value {
2632	return makeString(v.flag.ro(), string(v.Bytes()), t)
2633}
2634
2635// convertOp: string -> []byte
2636func cvtStringBytes(v Value, t Type) Value {
2637	return makeBytes(v.flag.ro(), []byte(v.String()), t)
2638}
2639
2640// convertOp: []rune -> string
2641func cvtRunesString(v Value, t Type) Value {
2642	return makeString(v.flag.ro(), string(v.runes()), t)
2643}
2644
2645// convertOp: string -> []rune
2646func cvtStringRunes(v Value, t Type) Value {
2647	return makeRunes(v.flag.ro(), []rune(v.String()), t)
2648}
2649
2650// convertOp: direct copy
2651func cvtDirect(v Value, typ Type) Value {
2652	f := v.flag
2653	t := typ.common()
2654	ptr := v.ptr
2655	if f&flagAddr != 0 {
2656		// indirect, mutable word - make a copy
2657		c := unsafe_New(t)
2658		typedmemmove(t, c, ptr)
2659		ptr = c
2660		f &^= flagAddr
2661	}
2662	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
2663}
2664
2665// convertOp: concrete -> interface
2666func cvtT2I(v Value, typ Type) Value {
2667	target := unsafe_New(typ.common())
2668	x := valueInterface(v, false)
2669	if typ.NumMethod() == 0 {
2670		*(*interface{})(target) = x
2671	} else {
2672		ifaceE2I(typ.(*rtype), x, target)
2673	}
2674	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
2675}
2676
2677// convertOp: interface -> interface
2678func cvtI2I(v Value, typ Type) Value {
2679	if v.IsNil() {
2680		ret := Zero(typ)
2681		ret.flag |= v.flag.ro()
2682		return ret
2683	}
2684	return cvtT2I(v.Elem(), typ)
2685}
2686
2687// implemented in ../runtime
2688func chancap(ch unsafe.Pointer) int
2689func chanclose(ch unsafe.Pointer)
2690func chanlen(ch unsafe.Pointer) int
2691
2692// Note: some of the noescape annotations below are technically a lie,
2693// but safe in the context of this package. Functions like chansend
2694// and mapassign don't escape the referent, but may escape anything
2695// the referent points to (they do shallow copies of the referent).
2696// It is safe in this package because the referent may only point
2697// to something a Value may point to, and that is always in the heap
2698// (due to the escapes() call in ValueOf).
2699
2700//go:noescape
2701func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
2702
2703//go:noescape
2704func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
2705
2706func makechan(typ *rtype, size int) (ch unsafe.Pointer)
2707func makemap(t *rtype, cap int) (m unsafe.Pointer)
2708
2709//go:noescape
2710func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2711
2712//go:noescape
2713func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2714
2715//go:noescape
2716func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2717
2718// m escapes into the return value, but the caller of mapiterinit
2719// doesn't let the return value escape.
2720//go:noescape
2721func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2722
2723//go:noescape
2724func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2725
2726//go:noescape
2727func mapiterelem(it unsafe.Pointer) (elem unsafe.Pointer)
2728
2729//go:noescape
2730func mapiternext(it unsafe.Pointer)
2731
2732//go:noescape
2733func maplen(m unsafe.Pointer) int
2734
2735// call calls fn with a copy of the n argument bytes pointed at by arg.
2736// After fn returns, reflectcall copies n-retoffset result bytes
2737// back into arg+retoffset before returning. If copying result bytes back,
2738// the caller must pass the argument frame type as argtype, so that
2739// call can execute appropriate write barriers during the copy.
2740//
2741//go:linkname call runtime.reflectcall
2742func call(argtype *rtype, fn, arg unsafe.Pointer, n uint32, retoffset uint32)
2743
2744func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2745
2746// memmove copies size bytes to dst from src. No write barriers are used.
2747//go:noescape
2748func memmove(dst, src unsafe.Pointer, size uintptr)
2749
2750// typedmemmove copies a value of type t to dst from src.
2751//go:noescape
2752func typedmemmove(t *rtype, dst, src unsafe.Pointer)
2753
2754// typedmemmovepartial is like typedmemmove but assumes that
2755// dst and src point off bytes into the value and only copies size bytes.
2756//go:noescape
2757func typedmemmovepartial(t *rtype, dst, src unsafe.Pointer, off, size uintptr)
2758
2759// typedmemclr zeros the value at ptr of type t.
2760//go:noescape
2761func typedmemclr(t *rtype, ptr unsafe.Pointer)
2762
2763// typedmemclrpartial is like typedmemclr but assumes that
2764// dst points off bytes into the value and only clears size bytes.
2765//go:noescape
2766func typedmemclrpartial(t *rtype, ptr unsafe.Pointer, off, size uintptr)
2767
2768// typedslicecopy copies a slice of elemType values from src to dst,
2769// returning the number of elements copied.
2770//go:noescape
2771func typedslicecopy(elemType *rtype, dst, src sliceHeader) int
2772
2773//go:noescape
2774func typehash(t *rtype, p unsafe.Pointer, h uintptr) uintptr
2775
2776// Dummy annotation marking that the value x escapes,
2777// for use in cases where the reflect code is so clever that
2778// the compiler cannot follow.
2779func escapes(x interface{}) {
2780	if dummy.b {
2781		dummy.x = x
2782	}
2783}
2784
2785var dummy struct {
2786	b bool
2787	x interface{}
2788}
2789