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