1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "gtest/gtest.h"
18
19 #include <inttypes.h>
20 #include <limits.h>
21
22 #include <vector>
23
24 #include "byte_input_stream.h"
25
26 namespace nogrod {
27
TEST(byte_input_stream,smoke)28 TEST(byte_input_stream, smoke) {
29 uint8_t bytes[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
30 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xc1, 0x00, 0xc1, 0x7f, 'b',
31 'a', 'r', '\0', 0x2a, 0x2b, 0x2c, 0x1, 0x2, 0x3, 0xFF};
32
33 ByteInputStream in(bytes, sizeof(bytes));
34
35 ASSERT_TRUE(in.available());
36 ASSERT_EQ(0x01, in.ReadUint8());
37 ASSERT_TRUE(in.available());
38 ASSERT_EQ(0x0302, in.ReadUint16());
39 ASSERT_TRUE(in.available());
40 ASSERT_EQ(0x07060504U, in.ReadUint32());
41 // Reading 0 bytes should be a noop that returns empty vector
42 auto empty_vector = in.ReadBytes(0);
43 EXPECT_TRUE(empty_vector.empty());
44 ASSERT_TRUE(in.available());
45 ASSERT_EQ(0x0f0e0d0c0b0a0908U, in.ReadUint64());
46 ASSERT_TRUE(in.available());
47 ASSERT_EQ(65U, in.ReadLeb128());
48 ASSERT_TRUE(in.available());
49 ASSERT_EQ(-63, in.ReadSleb128());
50 ASSERT_TRUE(in.available());
51 ASSERT_EQ("bar", in.ReadString());
52 ASSERT_TRUE(in.available());
53 auto byte_vector = in.ReadBytes(3);
54 ASSERT_EQ(3U, byte_vector.size());
55 ASSERT_EQ(0x2a, byte_vector[0]);
56 ASSERT_EQ(0x2b, byte_vector[1]);
57 ASSERT_EQ(0x2c, byte_vector[2]);
58 ASSERT_EQ(0x030201U, in.ReadUint24());
59 ASSERT_EQ(0xFF, in.ReadUint8());
60 ASSERT_TRUE(!in.available());
61 }
62
TEST(byte_input_stream,out_of_bounds)63 TEST(byte_input_stream, out_of_bounds) {
64 uint8_t array_out_of_bounds[] = {0x80, 0x81, 0x82};
65 ByteInputStream in(array_out_of_bounds, sizeof(array_out_of_bounds));
66
67 EXPECT_DEATH((void)in.ReadString(), "");
68 EXPECT_DEATH((void)in.ReadUint64(), "");
69 EXPECT_DEATH((void)in.ReadUint32(), "");
70
71 // This is ok because EXPECT_DEATH executes in forked process with cloned vm
72 ASSERT_EQ(0x8180, in.ReadUint16());
73 EXPECT_DEATH((void)in.ReadUint16(), "");
74 EXPECT_DEATH((void)in.ReadBytes(3), "");
75 EXPECT_DEATH((void)in.ReadBytes(2), "");
76 ASSERT_EQ(0x82, in.ReadUint8());
77 EXPECT_DEATH((void)in.ReadUint8(), "");
78 }
79
80 } // namespace nogrod
81