github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/encoding/gob/decode.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 //go:generate go run decgen.go -output dec_helpers.go 6 7 package gob 8 9 import ( 10 "encoding" 11 "errors" 12 "io" 13 "math" 14 "math/bits" 15 "reflect" 16 ) 17 18 var ( 19 errBadUint = errors.New("gob: encoded unsigned integer out of range") 20 errBadType = errors.New("gob: unknown type id or corrupted data") 21 errRange = errors.New("gob: bad data: field numbers out of bounds") 22 ) 23 24 type decHelper func(state *decoderState, v reflect.Value, length int, ovfl error) bool 25 26 // decoderState is the execution state of an instance of the decoder. A new state 27 // is created for nested objects. 28 type decoderState struct { 29 dec *Decoder 30 // The buffer is stored with an extra indirection because it may be replaced 31 // if we load a type during decode (when reading an interface value). 32 b *decBuffer 33 fieldnum int // the last field number read. 34 next *decoderState // for free list 35 } 36 37 // decBuffer is an extremely simple, fast implementation of a read-only byte buffer. 38 // It is initialized by calling Size and then copying the data into the slice returned by Bytes(). 39 type decBuffer struct { 40 data []byte 41 offset int // Read offset. 42 } 43 44 func (d *decBuffer) Read(p []byte) (int, error) { 45 n := copy(p, d.data[d.offset:]) 46 if n == 0 && len(p) != 0 { 47 return 0, io.EOF 48 } 49 d.offset += n 50 return n, nil 51 } 52 53 func (d *decBuffer) Drop(n int) { 54 if n > d.Len() { 55 panic("drop") 56 } 57 d.offset += n 58 } 59 60 // Size grows the buffer to exactly n bytes, so d.Bytes() will 61 // return a slice of length n. Existing data is first discarded. 62 func (d *decBuffer) Size(n int) { 63 d.Reset() 64 if cap(d.data) < n { 65 d.data = make([]byte, n) 66 } else { 67 d.data = d.data[0:n] 68 } 69 } 70 71 func (d *decBuffer) ReadByte() (byte, error) { 72 if d.offset >= len(d.data) { 73 return 0, io.EOF 74 } 75 c := d.data[d.offset] 76 d.offset++ 77 return c, nil 78 } 79 80 func (d *decBuffer) Len() int { 81 return len(d.data) - d.offset 82 } 83 84 func (d *decBuffer) Bytes() []byte { 85 return d.data[d.offset:] 86 } 87 88 func (d *decBuffer) Reset() { 89 d.data = d.data[0:0] 90 d.offset = 0 91 } 92 93 // We pass the bytes.Buffer separately for easier testing of the infrastructure 94 // without requiring a full Decoder. 95 func (dec *Decoder) newDecoderState(buf *decBuffer) *decoderState { 96 d := dec.freeList 97 if d == nil { 98 d = new(decoderState) 99 d.dec = dec 100 } else { 101 dec.freeList = d.next 102 } 103 d.b = buf 104 return d 105 } 106 107 func (dec *Decoder) freeDecoderState(d *decoderState) { 108 d.next = dec.freeList 109 dec.freeList = d 110 } 111 112 func overflow(name string) error { 113 return errors.New(`value for "` + name + `" out of range`) 114 } 115 116 // decodeUintReader reads an encoded unsigned integer from an io.Reader. 117 // Used only by the Decoder to read the message length. 118 func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) { 119 width = 1 120 n, err := io.ReadFull(r, buf[0:width]) 121 if n == 0 { 122 return 123 } 124 b := buf[0] 125 if b <= 0x7f { 126 return uint64(b), width, nil 127 } 128 n = -int(int8(b)) 129 if n > uint64Size { 130 err = errBadUint 131 return 132 } 133 width, err = io.ReadFull(r, buf[0:n]) 134 if err != nil { 135 if err == io.EOF { 136 err = io.ErrUnexpectedEOF 137 } 138 return 139 } 140 // Could check that the high byte is zero but it's not worth it. 141 for _, b := range buf[0:width] { 142 x = x<<8 | uint64(b) 143 } 144 width++ // +1 for length byte 145 return 146 } 147 148 // decodeUint reads an encoded unsigned integer from state.r. 149 // Does not check for overflow. 150 func (state *decoderState) decodeUint() (x uint64) { 151 b, err := state.b.ReadByte() 152 if err != nil { 153 error_(err) 154 } 155 if b <= 0x7f { 156 return uint64(b) 157 } 158 n := -int(int8(b)) 159 if n > uint64Size { 160 error_(errBadUint) 161 } 162 buf := state.b.Bytes() 163 if len(buf) < n { 164 errorf("invalid uint data length %d: exceeds input size %d", n, len(buf)) 165 } 166 // Don't need to check error; it's safe to loop regardless. 167 // Could check that the high byte is zero but it's not worth it. 168 for _, b := range buf[0:n] { 169 x = x<<8 | uint64(b) 170 } 171 state.b.Drop(n) 172 return x 173 } 174 175 // decodeInt reads an encoded signed integer from state.r. 176 // Does not check for overflow. 177 func (state *decoderState) decodeInt() int64 { 178 x := state.decodeUint() 179 if x&1 != 0 { 180 return ^int64(x >> 1) 181 } 182 return int64(x >> 1) 183 } 184 185 // getLength decodes the next uint and makes sure it is a possible 186 // size for a data item that follows, which means it must fit in a 187 // non-negative int and fit in the buffer. 188 func (state *decoderState) getLength() (int, bool) { 189 n := int(state.decodeUint()) 190 if n < 0 || state.b.Len() < n || tooBig <= n { 191 return 0, false 192 } 193 return n, true 194 } 195 196 // decOp is the signature of a decoding operator for a given type. 197 type decOp func(i *decInstr, state *decoderState, v reflect.Value) 198 199 // The 'instructions' of the decoding machine 200 type decInstr struct { 201 op decOp 202 field int // field number of the wire type 203 index []int // field access indices for destination type 204 ovfl error // error message for overflow/underflow (for arrays, of the elements) 205 } 206 207 // ignoreUint discards a uint value with no destination. 208 func ignoreUint(i *decInstr, state *decoderState, v reflect.Value) { 209 state.decodeUint() 210 } 211 212 // ignoreTwoUints discards a uint value with no destination. It's used to skip 213 // complex values. 214 func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value) { 215 state.decodeUint() 216 state.decodeUint() 217 } 218 219 // Since the encoder writes no zeros, if we arrive at a decoder we have 220 // a value to extract and store. The field number has already been read 221 // (it's how we knew to call this decoder). 222 // Each decoder is responsible for handling any indirections associated 223 // with the data structure. If any pointer so reached is nil, allocation must 224 // be done. 225 226 // decAlloc takes a value and returns a settable value that can 227 // be assigned to. If the value is a pointer, decAlloc guarantees it points to storage. 228 // The callers to the individual decoders are expected to have used decAlloc. 229 // The individual decoders don't need to it. 230 func decAlloc(v reflect.Value) reflect.Value { 231 for v.Kind() == reflect.Ptr { 232 if v.IsNil() { 233 v.Set(reflect.New(v.Type().Elem())) 234 } 235 v = v.Elem() 236 } 237 return v 238 } 239 240 // decBool decodes a uint and stores it as a boolean in value. 241 func decBool(i *decInstr, state *decoderState, value reflect.Value) { 242 value.SetBool(state.decodeUint() != 0) 243 } 244 245 // decInt8 decodes an integer and stores it as an int8 in value. 246 func decInt8(i *decInstr, state *decoderState, value reflect.Value) { 247 v := state.decodeInt() 248 if v < math.MinInt8 || math.MaxInt8 < v { 249 error_(i.ovfl) 250 } 251 value.SetInt(v) 252 } 253 254 // decUint8 decodes an unsigned integer and stores it as a uint8 in value. 255 func decUint8(i *decInstr, state *decoderState, value reflect.Value) { 256 v := state.decodeUint() 257 if math.MaxUint8 < v { 258 error_(i.ovfl) 259 } 260 value.SetUint(v) 261 } 262 263 // decInt16 decodes an integer and stores it as an int16 in value. 264 func decInt16(i *decInstr, state *decoderState, value reflect.Value) { 265 v := state.decodeInt() 266 if v < math.MinInt16 || math.MaxInt16 < v { 267 error_(i.ovfl) 268 } 269 value.SetInt(v) 270 } 271 272 // decUint16 decodes an unsigned integer and stores it as a uint16 in value. 273 func decUint16(i *decInstr, state *decoderState, value reflect.Value) { 274 v := state.decodeUint() 275 if math.MaxUint16 < v { 276 error_(i.ovfl) 277 } 278 value.SetUint(v) 279 } 280 281 // decInt32 decodes an integer and stores it as an int32 in value. 282 func decInt32(i *decInstr, state *decoderState, value reflect.Value) { 283 v := state.decodeInt() 284 if v < math.MinInt32 || math.MaxInt32 < v { 285 error_(i.ovfl) 286 } 287 value.SetInt(v) 288 } 289 290 // decUint32 decodes an unsigned integer and stores it as a uint32 in value. 291 func decUint32(i *decInstr, state *decoderState, value reflect.Value) { 292 v := state.decodeUint() 293 if math.MaxUint32 < v { 294 error_(i.ovfl) 295 } 296 value.SetUint(v) 297 } 298 299 // decInt64 decodes an integer and stores it as an int64 in value. 300 func decInt64(i *decInstr, state *decoderState, value reflect.Value) { 301 v := state.decodeInt() 302 value.SetInt(v) 303 } 304 305 // decUint64 decodes an unsigned integer and stores it as a uint64 in value. 306 func decUint64(i *decInstr, state *decoderState, value reflect.Value) { 307 v := state.decodeUint() 308 value.SetUint(v) 309 } 310 311 // Floating-point numbers are transmitted as uint64s holding the bits 312 // of the underlying representation. They are sent byte-reversed, with 313 // the exponent end coming out first, so integer floating point numbers 314 // (for example) transmit more compactly. This routine does the 315 // unswizzling. 316 func float64FromBits(u uint64) float64 { 317 v := bits.ReverseBytes64(u) 318 return math.Float64frombits(v) 319 } 320 321 // float32FromBits decodes an unsigned integer, treats it as a 32-bit floating-point 322 // number, and returns it. It's a helper function for float32 and complex64. 323 // It returns a float64 because that's what reflection needs, but its return 324 // value is known to be accurately representable in a float32. 325 func float32FromBits(u uint64, ovfl error) float64 { 326 v := float64FromBits(u) 327 av := v 328 if av < 0 { 329 av = -av 330 } 331 // +Inf is OK in both 32- and 64-bit floats. Underflow is always OK. 332 if math.MaxFloat32 < av && av <= math.MaxFloat64 { 333 error_(ovfl) 334 } 335 return v 336 } 337 338 // decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point 339 // number, and stores it in value. 340 func decFloat32(i *decInstr, state *decoderState, value reflect.Value) { 341 value.SetFloat(float32FromBits(state.decodeUint(), i.ovfl)) 342 } 343 344 // decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point 345 // number, and stores it in value. 346 func decFloat64(i *decInstr, state *decoderState, value reflect.Value) { 347 value.SetFloat(float64FromBits(state.decodeUint())) 348 } 349 350 // decComplex64 decodes a pair of unsigned integers, treats them as a 351 // pair of floating point numbers, and stores them as a complex64 in value. 352 // The real part comes first. 353 func decComplex64(i *decInstr, state *decoderState, value reflect.Value) { 354 real := float32FromBits(state.decodeUint(), i.ovfl) 355 imag := float32FromBits(state.decodeUint(), i.ovfl) 356 value.SetComplex(complex(real, imag)) 357 } 358 359 // decComplex128 decodes a pair of unsigned integers, treats them as a 360 // pair of floating point numbers, and stores them as a complex128 in value. 361 // The real part comes first. 362 func decComplex128(i *decInstr, state *decoderState, value reflect.Value) { 363 real := float64FromBits(state.decodeUint()) 364 imag := float64FromBits(state.decodeUint()) 365 value.SetComplex(complex(real, imag)) 366 } 367 368 // decUint8Slice decodes a byte slice and stores in value a slice header 369 // describing the data. 370 // uint8 slices are encoded as an unsigned count followed by the raw bytes. 371 func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value) { 372 n, ok := state.getLength() 373 if !ok { 374 errorf("bad %s slice length: %d", value.Type(), n) 375 } 376 if value.Cap() < n { 377 value.Set(reflect.MakeSlice(value.Type(), n, n)) 378 } else { 379 value.Set(value.Slice(0, n)) 380 } 381 if _, err := state.b.Read(value.Bytes()); err != nil { 382 errorf("error decoding []byte: %s", err) 383 } 384 } 385 386 // decString decodes byte array and stores in value a string header 387 // describing the data. 388 // Strings are encoded as an unsigned count followed by the raw bytes. 389 func decString(i *decInstr, state *decoderState, value reflect.Value) { 390 n, ok := state.getLength() 391 if !ok { 392 errorf("bad %s slice length: %d", value.Type(), n) 393 } 394 // Read the data. 395 data := state.b.Bytes() 396 if len(data) < n { 397 errorf("invalid string length %d: exceeds input size %d", n, len(data)) 398 } 399 s := string(data[:n]) 400 state.b.Drop(n) 401 value.SetString(s) 402 } 403 404 // ignoreUint8Array skips over the data for a byte slice value with no destination. 405 func ignoreUint8Array(i *decInstr, state *decoderState, value reflect.Value) { 406 n, ok := state.getLength() 407 if !ok { 408 errorf("slice length too large") 409 } 410 bn := state.b.Len() 411 if bn < n { 412 errorf("invalid slice length %d: exceeds input size %d", n, bn) 413 } 414 state.b.Drop(n) 415 } 416 417 // Execution engine 418 419 // The encoder engine is an array of instructions indexed by field number of the incoming 420 // decoder. It is executed with random access according to field number. 421 type decEngine struct { 422 instr []decInstr 423 numInstr int // the number of active instructions 424 } 425 426 // decodeSingle decodes a top-level value that is not a struct and stores it in value. 427 // Such values are preceded by a zero, making them have the memory layout of a 428 // struct field (although with an illegal field number). 429 func (dec *Decoder) decodeSingle(engine *decEngine, value reflect.Value) { 430 state := dec.newDecoderState(&dec.buf) 431 defer dec.freeDecoderState(state) 432 state.fieldnum = singletonField 433 if state.decodeUint() != 0 { 434 errorf("decode: corrupted data: non-zero delta for singleton") 435 } 436 instr := &engine.instr[singletonField] 437 instr.op(instr, state, value) 438 } 439 440 // decodeStruct decodes a top-level struct and stores it in value. 441 // Indir is for the value, not the type. At the time of the call it may 442 // differ from ut.indir, which was computed when the engine was built. 443 // This state cannot arise for decodeSingle, which is called directly 444 // from the user's value, not from the innards of an engine. 445 func (dec *Decoder) decodeStruct(engine *decEngine, value reflect.Value) { 446 state := dec.newDecoderState(&dec.buf) 447 defer dec.freeDecoderState(state) 448 state.fieldnum = -1 449 for state.b.Len() > 0 { 450 delta := int(state.decodeUint()) 451 if delta < 0 { 452 errorf("decode: corrupted data: negative delta") 453 } 454 if delta == 0 { // struct terminator is zero delta fieldnum 455 break 456 } 457 fieldnum := state.fieldnum + delta 458 if fieldnum >= len(engine.instr) { 459 error_(errRange) 460 break 461 } 462 instr := &engine.instr[fieldnum] 463 var field reflect.Value 464 if instr.index != nil { 465 // Otherwise the field is unknown to us and instr.op is an ignore op. 466 field = value.FieldByIndex(instr.index) 467 if field.Kind() == reflect.Ptr { 468 field = decAlloc(field) 469 } 470 } 471 instr.op(instr, state, field) 472 state.fieldnum = fieldnum 473 } 474 } 475 476 var noValue reflect.Value 477 478 // ignoreStruct discards the data for a struct with no destination. 479 func (dec *Decoder) ignoreStruct(engine *decEngine) { 480 state := dec.newDecoderState(&dec.buf) 481 defer dec.freeDecoderState(state) 482 state.fieldnum = -1 483 for state.b.Len() > 0 { 484 delta := int(state.decodeUint()) 485 if delta < 0 { 486 errorf("ignore decode: corrupted data: negative delta") 487 } 488 if delta == 0 { // struct terminator is zero delta fieldnum 489 break 490 } 491 fieldnum := state.fieldnum + delta 492 if fieldnum >= len(engine.instr) { 493 error_(errRange) 494 } 495 instr := &engine.instr[fieldnum] 496 instr.op(instr, state, noValue) 497 state.fieldnum = fieldnum 498 } 499 } 500 501 // ignoreSingle discards the data for a top-level non-struct value with no 502 // destination. It's used when calling Decode with a nil value. 503 func (dec *Decoder) ignoreSingle(engine *decEngine) { 504 state := dec.newDecoderState(&dec.buf) 505 defer dec.freeDecoderState(state) 506 state.fieldnum = singletonField 507 delta := int(state.decodeUint()) 508 if delta != 0 { 509 errorf("decode: corrupted data: non-zero delta for singleton") 510 } 511 instr := &engine.instr[singletonField] 512 instr.op(instr, state, noValue) 513 } 514 515 // decodeArrayHelper does the work for decoding arrays and slices. 516 func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) { 517 if helper != nil && helper(state, value, length, ovfl) { 518 return 519 } 520 instr := &decInstr{elemOp, 0, nil, ovfl} 521 isPtr := value.Type().Elem().Kind() == reflect.Ptr 522 for i := 0; i < length; i++ { 523 if state.b.Len() == 0 { 524 errorf("decoding array or slice: length exceeds input size (%d elements)", length) 525 } 526 v := value.Index(i) 527 if isPtr { 528 v = decAlloc(v) 529 } 530 elemOp(instr, state, v) 531 } 532 } 533 534 // decodeArray decodes an array and stores it in value. 535 // The length is an unsigned integer preceding the elements. Even though the length is redundant 536 // (it's part of the type), it's a useful check and is included in the encoding. 537 func (dec *Decoder) decodeArray(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) { 538 if n := state.decodeUint(); n != uint64(length) { 539 errorf("length mismatch in decodeArray") 540 } 541 dec.decodeArrayHelper(state, value, elemOp, length, ovfl, helper) 542 } 543 544 // decodeIntoValue is a helper for map decoding. 545 func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, instr *decInstr) reflect.Value { 546 v := value 547 if isPtr { 548 v = decAlloc(value) 549 } 550 551 op(instr, state, v) 552 return value 553 } 554 555 // decodeMap decodes a map and stores it in value. 556 // Maps are encoded as a length followed by key:value pairs. 557 // Because the internals of maps are not visible to us, we must 558 // use reflection rather than pointer magic. 559 func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value reflect.Value, keyOp, elemOp decOp, ovfl error) { 560 if value.IsNil() { 561 // Allocate map. 562 value.Set(reflect.MakeMap(mtyp)) 563 } 564 n := int(state.decodeUint()) 565 keyIsPtr := mtyp.Key().Kind() == reflect.Ptr 566 elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr 567 keyInstr := &decInstr{keyOp, 0, nil, ovfl} 568 elemInstr := &decInstr{elemOp, 0, nil, ovfl} 569 for i := 0; i < n; i++ { 570 key := decodeIntoValue(state, keyOp, keyIsPtr, allocValue(mtyp.Key()), keyInstr) 571 elem := decodeIntoValue(state, elemOp, elemIsPtr, allocValue(mtyp.Elem()), elemInstr) 572 value.SetMapIndex(key, elem) 573 } 574 } 575 576 // ignoreArrayHelper does the work for discarding arrays and slices. 577 func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) { 578 instr := &decInstr{elemOp, 0, nil, errors.New("no error")} 579 for i := 0; i < length; i++ { 580 if state.b.Len() == 0 { 581 errorf("decoding array or slice: length exceeds input size (%d elements)", length) 582 } 583 elemOp(instr, state, noValue) 584 } 585 } 586 587 // ignoreArray discards the data for an array value with no destination. 588 func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) { 589 if n := state.decodeUint(); n != uint64(length) { 590 errorf("length mismatch in ignoreArray") 591 } 592 dec.ignoreArrayHelper(state, elemOp, length) 593 } 594 595 // ignoreMap discards the data for a map value with no destination. 596 func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) { 597 n := int(state.decodeUint()) 598 keyInstr := &decInstr{keyOp, 0, nil, errors.New("no error")} 599 elemInstr := &decInstr{elemOp, 0, nil, errors.New("no error")} 600 for i := 0; i < n; i++ { 601 keyOp(keyInstr, state, noValue) 602 elemOp(elemInstr, state, noValue) 603 } 604 } 605 606 // decodeSlice decodes a slice and stores it in value. 607 // Slices are encoded as an unsigned length followed by the elements. 608 func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp decOp, ovfl error, helper decHelper) { 609 u := state.decodeUint() 610 typ := value.Type() 611 size := uint64(typ.Elem().Size()) 612 nBytes := u * size 613 n := int(u) 614 // Take care with overflow in this calculation. 615 if n < 0 || uint64(n) != u || nBytes > tooBig || (size > 0 && nBytes/size != u) { 616 // We don't check n against buffer length here because if it's a slice 617 // of interfaces, there will be buffer reloads. 618 errorf("%s slice too big: %d elements of %d bytes", typ.Elem(), u, size) 619 } 620 if value.Cap() < n { 621 value.Set(reflect.MakeSlice(typ, n, n)) 622 } else { 623 value.Set(value.Slice(0, n)) 624 } 625 dec.decodeArrayHelper(state, value, elemOp, n, ovfl, helper) 626 } 627 628 // ignoreSlice skips over the data for a slice value with no destination. 629 func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) { 630 dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint())) 631 } 632 633 // decodeInterface decodes an interface value and stores it in value. 634 // Interfaces are encoded as the name of a concrete type followed by a value. 635 // If the name is empty, the value is nil and no value is sent. 636 func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, value reflect.Value) { 637 // Read the name of the concrete type. 638 nr := state.decodeUint() 639 if nr > 1<<31 { // zero is permissible for anonymous types 640 errorf("invalid type name length %d", nr) 641 } 642 if nr > uint64(state.b.Len()) { 643 errorf("invalid type name length %d: exceeds input size", nr) 644 } 645 n := int(nr) 646 name := state.b.Bytes()[:n] 647 state.b.Drop(n) 648 // Allocate the destination interface value. 649 if len(name) == 0 { 650 // Copy the nil interface value to the target. 651 value.Set(reflect.Zero(value.Type())) 652 return 653 } 654 if len(name) > 1024 { 655 errorf("name too long (%d bytes): %.20q...", len(name), name) 656 } 657 // The concrete type must be registered. 658 registerLock.RLock() 659 typ, ok := nameToConcreteType[string(name)] 660 registerLock.RUnlock() 661 if !ok { 662 errorf("name not registered for interface: %q", name) 663 } 664 // Read the type id of the concrete value. 665 concreteId := dec.decodeTypeSequence(true) 666 if concreteId < 0 { 667 error_(dec.err) 668 } 669 // Byte count of value is next; we don't care what it is (it's there 670 // in case we want to ignore the value by skipping it completely). 671 state.decodeUint() 672 // Read the concrete value. 673 v := allocValue(typ) 674 dec.decodeValue(concreteId, v) 675 if dec.err != nil { 676 error_(dec.err) 677 } 678 // Assign the concrete value to the interface. 679 // Tread carefully; it might not satisfy the interface. 680 if !typ.AssignableTo(ityp) { 681 errorf("%s is not assignable to type %s", typ, ityp) 682 } 683 // Copy the interface value to the target. 684 value.Set(v) 685 } 686 687 // ignoreInterface discards the data for an interface value with no destination. 688 func (dec *Decoder) ignoreInterface(state *decoderState) { 689 // Read the name of the concrete type. 690 n, ok := state.getLength() 691 if !ok { 692 errorf("bad interface encoding: name too large for buffer") 693 } 694 bn := state.b.Len() 695 if bn < n { 696 errorf("invalid interface value length %d: exceeds input size %d", n, bn) 697 } 698 state.b.Drop(n) 699 id := dec.decodeTypeSequence(true) 700 if id < 0 { 701 error_(dec.err) 702 } 703 // At this point, the decoder buffer contains a delimited value. Just toss it. 704 n, ok = state.getLength() 705 if !ok { 706 errorf("bad interface encoding: data length too large for buffer") 707 } 708 state.b.Drop(n) 709 } 710 711 // decodeGobDecoder decodes something implementing the GobDecoder interface. 712 // The data is encoded as a byte slice. 713 func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, value reflect.Value) { 714 // Read the bytes for the value. 715 n, ok := state.getLength() 716 if !ok { 717 errorf("GobDecoder: length too large for buffer") 718 } 719 b := state.b.Bytes() 720 if len(b) < n { 721 errorf("GobDecoder: invalid data length %d: exceeds input size %d", n, len(b)) 722 } 723 b = b[:n] 724 state.b.Drop(n) 725 var err error 726 // We know it's one of these. 727 switch ut.externalDec { 728 case xGob: 729 err = value.Interface().(GobDecoder).GobDecode(b) 730 case xBinary: 731 err = value.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary(b) 732 case xText: 733 err = value.Interface().(encoding.TextUnmarshaler).UnmarshalText(b) 734 } 735 if err != nil { 736 error_(err) 737 } 738 } 739 740 // ignoreGobDecoder discards the data for a GobDecoder value with no destination. 741 func (dec *Decoder) ignoreGobDecoder(state *decoderState) { 742 // Read the bytes for the value. 743 n, ok := state.getLength() 744 if !ok { 745 errorf("GobDecoder: length too large for buffer") 746 } 747 bn := state.b.Len() 748 if bn < n { 749 errorf("GobDecoder: invalid data length %d: exceeds input size %d", n, bn) 750 } 751 state.b.Drop(n) 752 } 753 754 // Index by Go types. 755 var decOpTable = [...]decOp{ 756 reflect.Bool: decBool, 757 reflect.Int8: decInt8, 758 reflect.Int16: decInt16, 759 reflect.Int32: decInt32, 760 reflect.Int64: decInt64, 761 reflect.Uint8: decUint8, 762 reflect.Uint16: decUint16, 763 reflect.Uint32: decUint32, 764 reflect.Uint64: decUint64, 765 reflect.Float32: decFloat32, 766 reflect.Float64: decFloat64, 767 reflect.Complex64: decComplex64, 768 reflect.Complex128: decComplex128, 769 reflect.String: decString, 770 } 771 772 // Indexed by gob types. tComplex will be added during type.init(). 773 var decIgnoreOpMap = map[typeId]decOp{ 774 tBool: ignoreUint, 775 tInt: ignoreUint, 776 tUint: ignoreUint, 777 tFloat: ignoreUint, 778 tBytes: ignoreUint8Array, 779 tString: ignoreUint8Array, 780 tComplex: ignoreTwoUints, 781 } 782 783 // decOpFor returns the decoding op for the base type under rt and 784 // the indirection count to reach it. 785 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) *decOp { 786 ut := userType(rt) 787 // If the type implements GobEncoder, we handle it without further processing. 788 if ut.externalDec != 0 { 789 return dec.gobDecodeOpFor(ut) 790 } 791 792 // If this type is already in progress, it's a recursive type (e.g. map[string]*T). 793 // Return the pointer to the op we're already building. 794 if opPtr := inProgress[rt]; opPtr != nil { 795 return opPtr 796 } 797 typ := ut.base 798 var op decOp 799 k := typ.Kind() 800 if int(k) < len(decOpTable) { 801 op = decOpTable[k] 802 } 803 if op == nil { 804 inProgress[rt] = &op 805 // Special cases 806 switch t := typ; t.Kind() { 807 case reflect.Array: 808 name = "element of " + name 809 elemId := dec.wireType[wireId].ArrayT.Elem 810 elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress) 811 ovfl := overflow(name) 812 helper := decArrayHelper[t.Elem().Kind()] 813 op = func(i *decInstr, state *decoderState, value reflect.Value) { 814 state.dec.decodeArray(state, value, *elemOp, t.Len(), ovfl, helper) 815 } 816 817 case reflect.Map: 818 keyId := dec.wireType[wireId].MapT.Key 819 elemId := dec.wireType[wireId].MapT.Elem 820 keyOp := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress) 821 elemOp := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress) 822 ovfl := overflow(name) 823 op = func(i *decInstr, state *decoderState, value reflect.Value) { 824 state.dec.decodeMap(t, state, value, *keyOp, *elemOp, ovfl) 825 } 826 827 case reflect.Slice: 828 name = "element of " + name 829 if t.Elem().Kind() == reflect.Uint8 { 830 op = decUint8Slice 831 break 832 } 833 var elemId typeId 834 if tt, ok := builtinIdToType[wireId]; ok { 835 elemId = tt.(*sliceType).Elem 836 } else { 837 elemId = dec.wireType[wireId].SliceT.Elem 838 } 839 elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress) 840 ovfl := overflow(name) 841 helper := decSliceHelper[t.Elem().Kind()] 842 op = func(i *decInstr, state *decoderState, value reflect.Value) { 843 state.dec.decodeSlice(state, value, *elemOp, ovfl, helper) 844 } 845 846 case reflect.Struct: 847 // Generate a closure that calls out to the engine for the nested type. 848 ut := userType(typ) 849 enginePtr, err := dec.getDecEnginePtr(wireId, ut) 850 if err != nil { 851 error_(err) 852 } 853 op = func(i *decInstr, state *decoderState, value reflect.Value) { 854 // indirect through enginePtr to delay evaluation for recursive structs. 855 dec.decodeStruct(*enginePtr, value) 856 } 857 case reflect.Interface: 858 op = func(i *decInstr, state *decoderState, value reflect.Value) { 859 state.dec.decodeInterface(t, state, value) 860 } 861 } 862 } 863 if op == nil { 864 errorf("decode can't handle type %s", rt) 865 } 866 return &op 867 } 868 869 // decIgnoreOpFor returns the decoding op for a field that has no destination. 870 func (dec *Decoder) decIgnoreOpFor(wireId typeId, inProgress map[typeId]*decOp) *decOp { 871 // If this type is already in progress, it's a recursive type (e.g. map[string]*T). 872 // Return the pointer to the op we're already building. 873 if opPtr := inProgress[wireId]; opPtr != nil { 874 return opPtr 875 } 876 op, ok := decIgnoreOpMap[wireId] 877 if !ok { 878 inProgress[wireId] = &op 879 if wireId == tInterface { 880 // Special case because it's a method: the ignored item might 881 // define types and we need to record their state in the decoder. 882 op = func(i *decInstr, state *decoderState, value reflect.Value) { 883 state.dec.ignoreInterface(state) 884 } 885 return &op 886 } 887 // Special cases 888 wire := dec.wireType[wireId] 889 switch { 890 case wire == nil: 891 errorf("bad data: undefined type %s", wireId.string()) 892 case wire.ArrayT != nil: 893 elemId := wire.ArrayT.Elem 894 elemOp := dec.decIgnoreOpFor(elemId, inProgress) 895 op = func(i *decInstr, state *decoderState, value reflect.Value) { 896 state.dec.ignoreArray(state, *elemOp, wire.ArrayT.Len) 897 } 898 899 case wire.MapT != nil: 900 keyId := dec.wireType[wireId].MapT.Key 901 elemId := dec.wireType[wireId].MapT.Elem 902 keyOp := dec.decIgnoreOpFor(keyId, inProgress) 903 elemOp := dec.decIgnoreOpFor(elemId, inProgress) 904 op = func(i *decInstr, state *decoderState, value reflect.Value) { 905 state.dec.ignoreMap(state, *keyOp, *elemOp) 906 } 907 908 case wire.SliceT != nil: 909 elemId := wire.SliceT.Elem 910 elemOp := dec.decIgnoreOpFor(elemId, inProgress) 911 op = func(i *decInstr, state *decoderState, value reflect.Value) { 912 state.dec.ignoreSlice(state, *elemOp) 913 } 914 915 case wire.StructT != nil: 916 // Generate a closure that calls out to the engine for the nested type. 917 enginePtr, err := dec.getIgnoreEnginePtr(wireId) 918 if err != nil { 919 error_(err) 920 } 921 op = func(i *decInstr, state *decoderState, value reflect.Value) { 922 // indirect through enginePtr to delay evaluation for recursive structs 923 state.dec.ignoreStruct(*enginePtr) 924 } 925 926 case wire.GobEncoderT != nil, wire.BinaryMarshalerT != nil, wire.TextMarshalerT != nil: 927 op = func(i *decInstr, state *decoderState, value reflect.Value) { 928 state.dec.ignoreGobDecoder(state) 929 } 930 } 931 } 932 if op == nil { 933 errorf("bad data: ignore can't handle type %s", wireId.string()) 934 } 935 return &op 936 } 937 938 // gobDecodeOpFor returns the op for a type that is known to implement 939 // GobDecoder. 940 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp { 941 rcvrType := ut.user 942 if ut.decIndir == -1 { 943 rcvrType = reflect.PtrTo(rcvrType) 944 } else if ut.decIndir > 0 { 945 for i := int8(0); i < ut.decIndir; i++ { 946 rcvrType = rcvrType.Elem() 947 } 948 } 949 var op decOp 950 op = func(i *decInstr, state *decoderState, value reflect.Value) { 951 // We now have the base type. We need its address if the receiver is a pointer. 952 if value.Kind() != reflect.Ptr && rcvrType.Kind() == reflect.Ptr { 953 value = value.Addr() 954 } 955 state.dec.decodeGobDecoder(ut, state, value) 956 } 957 return &op 958 } 959 960 // compatibleType asks: Are these two gob Types compatible? 961 // Answers the question for basic types, arrays, maps and slices, plus 962 // GobEncoder/Decoder pairs. 963 // Structs are considered ok; fields will be checked later. 964 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool { 965 if rhs, ok := inProgress[fr]; ok { 966 return rhs == fw 967 } 968 inProgress[fr] = fw 969 ut := userType(fr) 970 wire, ok := dec.wireType[fw] 971 // If wire was encoded with an encoding method, fr must have that method. 972 // And if not, it must not. 973 // At most one of the booleans in ut is set. 974 // We could possibly relax this constraint in the future in order to 975 // choose the decoding method using the data in the wireType. 976 // The parentheses look odd but are correct. 977 if (ut.externalDec == xGob) != (ok && wire.GobEncoderT != nil) || 978 (ut.externalDec == xBinary) != (ok && wire.BinaryMarshalerT != nil) || 979 (ut.externalDec == xText) != (ok && wire.TextMarshalerT != nil) { 980 return false 981 } 982 if ut.externalDec != 0 { // This test trumps all others. 983 return true 984 } 985 switch t := ut.base; t.Kind() { 986 default: 987 // chan, etc: cannot handle. 988 return false 989 case reflect.Bool: 990 return fw == tBool 991 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 992 return fw == tInt 993 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 994 return fw == tUint 995 case reflect.Float32, reflect.Float64: 996 return fw == tFloat 997 case reflect.Complex64, reflect.Complex128: 998 return fw == tComplex 999 case reflect.String: 1000 return fw == tString 1001 case reflect.Interface: 1002 return fw == tInterface 1003 case reflect.Array: 1004 if !ok || wire.ArrayT == nil { 1005 return false 1006 } 1007 array := wire.ArrayT 1008 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress) 1009 case reflect.Map: 1010 if !ok || wire.MapT == nil { 1011 return false 1012 } 1013 MapType := wire.MapT 1014 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress) 1015 case reflect.Slice: 1016 // Is it an array of bytes? 1017 if t.Elem().Kind() == reflect.Uint8 { 1018 return fw == tBytes 1019 } 1020 // Extract and compare element types. 1021 var sw *sliceType 1022 if tt, ok := builtinIdToType[fw]; ok { 1023 sw, _ = tt.(*sliceType) 1024 } else if wire != nil { 1025 sw = wire.SliceT 1026 } 1027 elem := userType(t.Elem()).base 1028 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress) 1029 case reflect.Struct: 1030 return true 1031 } 1032 } 1033 1034 // typeString returns a human-readable description of the type identified by remoteId. 1035 func (dec *Decoder) typeString(remoteId typeId) string { 1036 if t := idToType[remoteId]; t != nil { 1037 // globally known type. 1038 return t.string() 1039 } 1040 return dec.wireType[remoteId].string() 1041 } 1042 1043 // compileSingle compiles the decoder engine for a non-struct top-level value, including 1044 // GobDecoders. 1045 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1046 rt := ut.user 1047 engine = new(decEngine) 1048 engine.instr = make([]decInstr, 1) // one item 1049 name := rt.String() // best we can do 1050 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) { 1051 remoteType := dec.typeString(remoteId) 1052 // Common confusing case: local interface type, remote concrete type. 1053 if ut.base.Kind() == reflect.Interface && remoteId != tInterface { 1054 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType) 1055 } 1056 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType) 1057 } 1058 op := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp)) 1059 ovfl := errors.New(`value for "` + name + `" out of range`) 1060 engine.instr[singletonField] = decInstr{*op, singletonField, nil, ovfl} 1061 engine.numInstr = 1 1062 return 1063 } 1064 1065 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded. 1066 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) { 1067 engine = new(decEngine) 1068 engine.instr = make([]decInstr, 1) // one item 1069 op := dec.decIgnoreOpFor(remoteId, make(map[typeId]*decOp)) 1070 ovfl := overflow(dec.typeString(remoteId)) 1071 engine.instr[0] = decInstr{*op, 0, nil, ovfl} 1072 engine.numInstr = 1 1073 return 1074 } 1075 1076 // compileDec compiles the decoder engine for a value. If the value is not a struct, 1077 // it calls out to compileSingle. 1078 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1079 defer catchError(&err) 1080 rt := ut.base 1081 srt := rt 1082 if srt.Kind() != reflect.Struct || ut.externalDec != 0 { 1083 return dec.compileSingle(remoteId, ut) 1084 } 1085 var wireStruct *structType 1086 // Builtin types can come from global pool; the rest must be defined by the decoder. 1087 // Also we know we're decoding a struct now, so the client must have sent one. 1088 if t, ok := builtinIdToType[remoteId]; ok { 1089 wireStruct, _ = t.(*structType) 1090 } else { 1091 wire := dec.wireType[remoteId] 1092 if wire == nil { 1093 error_(errBadType) 1094 } 1095 wireStruct = wire.StructT 1096 } 1097 if wireStruct == nil { 1098 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt) 1099 } 1100 engine = new(decEngine) 1101 engine.instr = make([]decInstr, len(wireStruct.Field)) 1102 seen := make(map[reflect.Type]*decOp) 1103 // Loop over the fields of the wire type. 1104 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ { 1105 wireField := wireStruct.Field[fieldnum] 1106 if wireField.Name == "" { 1107 errorf("empty name for remote field of type %s", wireStruct.Name) 1108 } 1109 ovfl := overflow(wireField.Name) 1110 // Find the field of the local type with the same name. 1111 localField, present := srt.FieldByName(wireField.Name) 1112 // TODO(r): anonymous names 1113 if !present || !isExported(wireField.Name) { 1114 op := dec.decIgnoreOpFor(wireField.Id, make(map[typeId]*decOp)) 1115 engine.instr[fieldnum] = decInstr{*op, fieldnum, nil, ovfl} 1116 continue 1117 } 1118 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) { 1119 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name) 1120 } 1121 op := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen) 1122 engine.instr[fieldnum] = decInstr{*op, fieldnum, localField.Index, ovfl} 1123 engine.numInstr++ 1124 } 1125 return 1126 } 1127 1128 // getDecEnginePtr returns the engine for the specified type. 1129 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) { 1130 rt := ut.user 1131 decoderMap, ok := dec.decoderCache[rt] 1132 if !ok { 1133 decoderMap = make(map[typeId]**decEngine) 1134 dec.decoderCache[rt] = decoderMap 1135 } 1136 if enginePtr, ok = decoderMap[remoteId]; !ok { 1137 // To handle recursive types, mark this engine as underway before compiling. 1138 enginePtr = new(*decEngine) 1139 decoderMap[remoteId] = enginePtr 1140 *enginePtr, err = dec.compileDec(remoteId, ut) 1141 if err != nil { 1142 delete(decoderMap, remoteId) 1143 } 1144 } 1145 return 1146 } 1147 1148 // emptyStruct is the type we compile into when ignoring a struct value. 1149 type emptyStruct struct{} 1150 1151 var emptyStructType = reflect.TypeOf(emptyStruct{}) 1152 1153 // getIgnoreEnginePtr returns the engine for the specified type when the value is to be discarded. 1154 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) { 1155 var ok bool 1156 if enginePtr, ok = dec.ignorerCache[wireId]; !ok { 1157 // To handle recursive types, mark this engine as underway before compiling. 1158 enginePtr = new(*decEngine) 1159 dec.ignorerCache[wireId] = enginePtr 1160 wire := dec.wireType[wireId] 1161 if wire != nil && wire.StructT != nil { 1162 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType)) 1163 } else { 1164 *enginePtr, err = dec.compileIgnoreSingle(wireId) 1165 } 1166 if err != nil { 1167 delete(dec.ignorerCache, wireId) 1168 } 1169 } 1170 return 1171 } 1172 1173 // decodeValue decodes the data stream representing a value and stores it in value. 1174 func (dec *Decoder) decodeValue(wireId typeId, value reflect.Value) { 1175 defer catchError(&dec.err) 1176 // If the value is nil, it means we should just ignore this item. 1177 if !value.IsValid() { 1178 dec.decodeIgnoredValue(wireId) 1179 return 1180 } 1181 // Dereference down to the underlying type. 1182 ut := userType(value.Type()) 1183 base := ut.base 1184 var enginePtr **decEngine 1185 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut) 1186 if dec.err != nil { 1187 return 1188 } 1189 value = decAlloc(value) 1190 engine := *enginePtr 1191 if st := base; st.Kind() == reflect.Struct && ut.externalDec == 0 { 1192 wt := dec.wireType[wireId] 1193 if engine.numInstr == 0 && st.NumField() > 0 && 1194 wt != nil && len(wt.StructT.Field) > 0 { 1195 name := base.Name() 1196 errorf("type mismatch: no fields matched compiling decoder for %s", name) 1197 } 1198 dec.decodeStruct(engine, value) 1199 } else { 1200 dec.decodeSingle(engine, value) 1201 } 1202 } 1203 1204 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it. 1205 func (dec *Decoder) decodeIgnoredValue(wireId typeId) { 1206 var enginePtr **decEngine 1207 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId) 1208 if dec.err != nil { 1209 return 1210 } 1211 wire := dec.wireType[wireId] 1212 if wire != nil && wire.StructT != nil { 1213 dec.ignoreStruct(*enginePtr) 1214 } else { 1215 dec.ignoreSingle(*enginePtr) 1216 } 1217 } 1218 1219 func init() { 1220 var iop, uop decOp 1221 switch reflect.TypeOf(int(0)).Bits() { 1222 case 32: 1223 iop = decInt32 1224 uop = decUint32 1225 case 64: 1226 iop = decInt64 1227 uop = decUint64 1228 default: 1229 panic("gob: unknown size of int/uint") 1230 } 1231 decOpTable[reflect.Int] = iop 1232 decOpTable[reflect.Uint] = uop 1233 1234 // Finally uintptr 1235 switch reflect.TypeOf(uintptr(0)).Bits() { 1236 case 32: 1237 uop = decUint32 1238 case 64: 1239 uop = decUint64 1240 default: 1241 panic("gob: unknown size of uintptr") 1242 } 1243 decOpTable[reflect.Uintptr] = uop 1244 } 1245 1246 // Gob depends on being able to take the address 1247 // of zeroed Values it creates, so use this wrapper instead 1248 // of the standard reflect.Zero. 1249 // Each call allocates once. 1250 func allocValue(t reflect.Type) reflect.Value { 1251 return reflect.New(t).Elem() 1252 }