OSDN Git Service

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