summaryrefslogtreecommitdiff
path: root/tests/common/leb128.py
blob: db3013e193aa933310cb51f652a9796baeb797e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

from chrysacase import ChrysalideTestCase
from pychrysalide.common import pack_uleb128, unpack_uleb128, pack_leb128, unpack_leb128
from pychrysalide.common import PackedBuffer


class TestLEB128Values(ChrysalideTestCase):
    """TestCase for common LEB128 features*"""

    def testUnsignedLeb128Encoding(self):
        """Pack and unpack unsigned LEB128 values."""

        cases = {
            624485: b'\xe5\x8e\x26',
            127: b'\x7f',
            128: b'\x80\x01',
        }

        for value, encoding in cases.items():

            pbuf = PackedBuffer()

            status = pack_uleb128(value, pbuf)
            self.assertTrue(status)

            self.assertEqual(pbuf.payload_length, len(encoding))

            pbuf.rewind()

            got = pbuf.extract(len(encoding))

            self.assertEqual(got, encoding)

            self.assertFalse(pbuf.more_data)

        for value, encoding in cases.items():

            pbuf = PackedBuffer()
            pbuf.extend(encoding, False)

            pbuf.rewind()

            got = unpack_uleb128(pbuf)
            self.assertIsNotNone(got)

            self.assertEqual(got, value)


    def testSignedLeb128Encoding(self):
        """Pack and unpack signed LEB128 values."""

        cases = {
            -123456: b'\xc0\xbb\x78',
            -42: b'\x56',
            -9001: b'\xd7\xb9\x7f',
        }

        for value, encoding in cases.items():

            pbuf = PackedBuffer()

            status = pack_leb128(value, pbuf)
            self.assertTrue(status)

            self.assertEqual(pbuf.payload_length, len(encoding))

            pbuf.rewind()

            got = pbuf.extract(len(encoding))

            self.assertEqual(got, encoding)

            self.assertFalse(pbuf.more_data)

        for value, encoding in cases.items():

            pbuf = PackedBuffer()
            pbuf.extend(encoding, False)

            pbuf.rewind()

            got = unpack_leb128(pbuf)
            self.assertIsNotNone(got)

            self.assertEqual(got, value)


    def testTooBigLeb128Encodings(self):
        """Prevent overflow for LEB128 values."""

        pbuf = PackedBuffer()
        pbuf.extend(b'\x80' * 10 + b'\x7f', False)

        pbuf.rewind()

        got = unpack_uleb128(pbuf)

        self.assertIsNone(got)

        pbuf = PackedBuffer()
        pbuf.extend(b'\x80' * 10 + b'\x7f', False)

        pbuf.rewind()

        got = unpack_leb128(pbuf)

        self.assertIsNone(got)