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