Debian Codegraph @

tpmutil/encoding_test.go

raw
1 // Copyright (c) 2018, Google LLC All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package tpmutil
16
17 import (
18 "bytes"
19 "io"
20 "reflect"
21 "testing"
22 )
23
24 type invalidPacked struct {
25 A []int
26 B uint32
27 }
28
29 func TestEncodingPackTypeInvalid(t *testing.T) {
30 d := io.Discard
31
32 // The packedSize function doesn't handle slices to anything other than bytes.
33 var invalid []int
34 if err := packType(d, invalid); err == nil {
35 t.Fatal("The packing function incorrectly succeeds for a slice of integers")
36 }
37 if err := packType(d, &invalid); err == nil {
38 t.Fatal("The packing function incorrectly succeeds for a pointer to a slice of integers")
39 }
40
41 invalid2 := invalidPacked{
42 A: make([]int, 10),
43 B: 137,
44 }
45 if err := packType(d, invalid2); err == nil {
46 t.Fatal("The packing function incorrectly succeeds for a struct that contains an integer slice")
47 }
48 if err := packType(d, &invalid2); err == nil {
49 t.Fatal("The packing function incorrectly succeeds for a pointer to a struct that contains an integer slice")
50 }
51 }
52
53 type simplePacked struct {
54 A uint32
55 B uint32
56 }
57
58 type nestedPacked struct {
59 SP simplePacked
60 C uint32
61 }
62
63 type nestedSlice struct {
64 A uint32
65 S U32Bytes
66 }
67
68 func TestEncodingPackType(t *testing.T) {
69 buf := make([]byte, 10)
70 inputs := []interface{}{
71 uint32(3),
72 buf,
73 &buf,
74 simplePacked{137, 138},
75 nestedPacked{simplePacked{137, 138}, 139},
76 nestedSlice{137, buf},
77 []byte(nil),
78 RawBytes(buf),
79 }
80 for _, i := range inputs {
81 if err := packType(io.Discard, i); err != nil {
82 t.Errorf("packType(%#v): %v", i, err)
83 }
84 }
85 }
86
87 func TestEncodingPackTypeWriteFail(t *testing.T) {
88 u32WithOneByte := U32Bytes([]byte{1})
89 u32Empty := U32Bytes([]byte(nil))
90
91 tests := []struct {
92 limit int
93 in interface{}
94 }{
95 {4, &u32WithOneByte},
96 {3, &u32Empty},
97 }
98 for _, tt := range tests {
99 if err := packType(&limitedDiscard{tt.limit}, tt.in); err == nil {
100 t.Errorf("packType(%#v) with write size limit %d returned nil, want error", tt.in, tt.limit)
101 }
102 }
103 }
104
105 // limitedDiscard is an implementation of io.Writer that accepts a given number
106 // of bytes before returning errors.
107 type limitedDiscard struct {
108 remaining int
109 }
110
111 // Write writes p to the limitedDiscard instance.
112 func (l *limitedDiscard) Write(p []byte) (n int, err error) {
113 n = len(p)
114 if n > l.remaining {
115 n = l.remaining
116 err = io.EOF
117 }
118
119 l.remaining -= n
120 return
121 }
122
123 func TestEncodingCommandHeaderInvalidBody(t *testing.T) {
124 var invalid []int
125 ch := commandHeader{1, 0, 2}
126 _, err := packWithHeader(ch, invalid)
127 if err == nil {
128 t.Fatal("packWithHeader incorrectly packed a body that with an invalid int slice member")
129 }
130 }
131
132 func TestEncodingInvalidPack(t *testing.T) {
133 var invalid []int
134 ch := commandHeader{1, 0, 2}
135 _, err := packWithHeader(ch, invalid)
136 if err == nil {
137 t.Fatal("packWithHeader incorrectly packed a body that with an invalid int slice member")
138 }
139
140 _, err = Pack(invalid)
141 if err == nil {
142 t.Fatal("pack incorrectly packed a slice of int")
143 }
144 }
145
146 func TestEncodingCommandHeaderEncoding(t *testing.T) {
147 ch := commandHeader{1, 0, 2}
148 var c uint32 = 137
149 in := c
150
151 b, err := packWithHeader(ch, in)
152 if err != nil {
153 t.Fatal("Couldn't pack the bytes:", err)
154 }
155
156 var hdr commandHeader
157 var size uint32
158 if _, err := Unpack(b, &hdr, &size); err != nil {
159 t.Fatal("Couldn't unpack the packed bytes")
160 }
161
162 if size != 137 {
163 t.Fatal("Got the wrong size back")
164 }
165 }
166
167 func TestEncodingInvalidUnpack(t *testing.T) {
168 var i *uint32
169 // The value ui is a serialization of uint32(0).
170 ui := []byte{0, 0, 0, 0}
171 uiBuf := bytes.NewBuffer(ui)
172 if err := UnpackBuf(uiBuf, i); err == nil {
173 t.Fatal("UnpackBuf incorrectly deserialized into a nil pointer")
174 }
175
176 var ii uint32
177 if err := UnpackBuf(uiBuf, ii); err == nil {
178 t.Fatal("UnpackBuf incorrectly deserialized into a non pointer")
179 }
180
181 var b U32Bytes
182 var empty []byte
183 emptyBuf := bytes.NewBuffer(empty)
184 if err := UnpackBuf(emptyBuf, &b); err == nil {
185 t.Fatal("UnpackBuf incorrectly deserialized an empty byte array into U32Bytes")
186 }
187
188 // Try to deserialize a byte array that has a length but not enough bytes.
189 // The slice ui represents uint32(1), which is the length of an empty byte array.
190 ui2 := []byte{0, 0, 0, 1}
191 uiBuf2 := bytes.NewBuffer(ui2)
192 if err := UnpackBuf(uiBuf2, &b); err == nil {
193 t.Fatal("UnpackBuf incorrectly deserialized a byte array that didn't have enough bytes available")
194 }
195
196 var iii []int
197 ui3 := []byte{0, 0, 0, 1}
198 uiBuf3 := bytes.NewBuffer(ui3)
199 if err := UnpackBuf(uiBuf3, &iii); err == nil {
200 t.Fatal("UnpackBuf incorrectly deserialized into a slice of ints (only byte slices are supported)")
201 }
202
203 }
204
205 func TestSelfMarshaler(t *testing.T) {
206 var empty16 U16Bytes
207 var empty32 U32Bytes
208 subTests := []struct {
209 encoded []byte
210 decoded interface{}
211 }{
212 {[]byte{0, 0}, &empty16},
213 {[]byte{0, 1, 137}, &empty16},
214 {[]byte{0, 0, 0, 0}, &empty32},
215 {[]byte{0, 0, 0, 1, 137}, &empty32},
216 }
217 for _, st := range subTests {
218 t.Logf("Attempting to Marshal/Unmarshal %#v into %T", st.encoded, st.decoded)
219 buffer := bytes.NewBuffer(st.encoded)
220 if err := UnpackBuf(buffer, st.decoded); err != nil {
221 t.Fatalf("UnpackBuf failed: %v", err)
222 }
223 packed, err := Pack(st.decoded)
224 if err != nil {
225 t.Fatalf("Pack failed: %v", err)
226 }
227 if !bytes.Equal(packed, st.encoded) {
228 t.Fatalf("Pack failed: got %#v, want: %#v", packed, st.encoded)
229 }
230 }
231 }
232
233 func TestEncodingUnpack(t *testing.T) {
234 // Deserialize the empty byte array.
235 var b U32Bytes
236 // The slice ui represents uint32(0), which is the length of an empty byte array.
237 ui := []byte{0, 0, 0, 0}
238 uiBuf := bytes.NewBuffer(ui)
239 if err := UnpackBuf(uiBuf, &b); err != nil {
240 t.Fatal("UnpackBuf failed to unpack the empty byte array")
241 }
242
243 // A byte slice of length 1 with a single entry: b[0] == 137
244 ui2 := []byte{0, 0, 0, 1, 137}
245 uiBuf2 := bytes.NewBuffer(ui2)
246 if err := UnpackBuf(uiBuf2, &b); err != nil {
247 t.Fatal("UnpackBuf failed to unpack a byte array with a single value in it")
248 }
249
250 if !bytes.Equal([]byte(b), []byte{137}) {
251 t.Fatal("UnpackBuf unpacked a small byte array incorrectly")
252 }
253
254 sp := simplePacked{137, 138}
255 bsp, err := Pack(sp)
256 if err != nil {
257 t.Fatal("Couldn't pack a simple struct:", err)
258 }
259 var sp2 simplePacked
260 if _, err := Unpack(bsp, &sp2); err != nil {
261 t.Fatal("Couldn't unpack a simple struct:", err)
262 }
263
264 if sp.A != sp2.A || sp.B != sp2.B {
265 t.Fatal("Unpacked simple struct didn't match the original")
266 }
267
268 // Try unpacking a version that's missing a byte at the end.
269 if _, err := Unpack(bsp[:len(bsp)-1], &sp2); err == nil {
270 t.Fatal("unpack incorrectly unpacked from a byte array that didn't have enough values")
271 }
272
273 np := nestedPacked{sp, 139}
274 bnp, err := Pack(np)
275 if err != nil {
276 t.Fatal("Couldn't pack a nested struct")
277 }
278 var np2 nestedPacked
279 if _, err := Unpack(bnp, &np2); err != nil {
280 t.Fatal("Couldn't unpack a nested struct:", err)
281 }
282 if np.SP.A != np2.SP.A || np.SP.B != np2.SP.B || np.C != np2.C {
283 t.Fatal("Unpacked nested struct didn't match the original")
284 }
285
286 ns := nestedSlice{137, b}
287 bns, err := Pack(&ns)
288 if err != nil {
289 t.Fatal("Couldn't pack a struct with a nested byte slice:", err)
290 }
291 var ns2 nestedSlice
292 if _, err := Unpack(bns, &ns2); err != nil {
293 t.Fatal("Couldn't unpacked a struct with a nested slice:", err)
294 }
295 if ns.A != ns2.A || !bytes.Equal(ns.S, ns2.S) {
296 t.Logf("original = %+v", ns)
297 t.Logf("decoded = %+v", ns2)
298 t.Fatal("Unpacked struct with nested slice didn't match the original")
299 }
300
301 var hs []Handle
302 if _, err := Unpack([]byte{0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, &hs); err != nil {
303 t.Fatal("Couldn't unpack a list of Handles:", err)
304 }
305 if want := []Handle{0x01020304, 0x05060708, 0x090a0b0c}; !reflect.DeepEqual(want, hs) {
306 t.Fatalf("Unpacking []Handle: got %v, want %v", hs, want)
307 }
308 }
309
310 func TestPartialUnpack(t *testing.T) {
311 u1, u2 := uint32(1), uint32(2)
312 buf, err := Pack(u1, u2)
313 if err != nil {
314 t.Fatalf("packing uint32 value: %v", err)
315 }
316
317 var gu1, gu2 uint32
318 read1, err := Unpack(buf, &gu1)
319 if err != nil {
320 t.Fatalf("unpacking first uint32 value: %v", err)
321 }
322 if gu1 != u1 {
323 t.Errorf("first unpacked value: got %d, want %d", gu1, u1)
324 }
325 read2, err := Unpack(buf[read1:], &gu2)
326 if err != nil {
327 t.Fatalf("unpacking second uint32 value: %v", err)
328 }
329 if gu2 != u2 {
330 t.Errorf("second unpacked value: got %d, want %d", gu2, u2)
331 }
332
333 if read1+read2 != len(buf) {
334 t.Errorf("sum of bytes read doesn't ad up to total packed size: got %d+%d=%d, want %d", read1, read2, read1+read2, len(buf))
335 }
336 }
337
338 func TestUnpackHandlesArea(t *testing.T) {
339 buf := []byte{
340 0, 2,
341 0, 0, 0, 1,
342 0, 0, 5, 57,
343 }
344 var out []Handle
345
346 if _, err := Unpack(buf, &out); err != nil {
347 t.Fatalf("Unpack(%v, %T) failed: %v", buf, &out, err)
348 }
349 if want := []Handle{1, 1337}; !reflect.DeepEqual(out, want) {
350 t.Errorf("Unpack(%v, %T): %T = %v, want %v", buf, &out, out, out, want)
351 }
352 }
353
354 func TestUnpackMalformedBytes(t *testing.T) {
355 // buf is malformed because the leading size prefix is illegally large.
356 buf := []byte{0xff, 0xff, 0xff, 0xff, 0x20}
357
358 var u32 U32Bytes
359 if _, err := Unpack(buf, &u32); err != bytes.ErrTooLarge {
360 t.Errorf("Unpack(U32Bytes{}) returned %q, want %q", err, bytes.ErrTooLarge)
361 }
362 var u16 U16Bytes
363 if _, err := Unpack(buf, &u16); err != io.ErrUnexpectedEOF {
364 t.Errorf("Unpack(U16Bytes{}) returned %q, want %q", err, io.ErrUnexpectedEOF)
365 }
366 }