1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "jsapi-tests/tests.h"
9 #include "wasm/WasmValidate.h"
11 static bool WriteValidBytes(js::wasm::Encoder
& encoder
, bool* passed
) {
13 if (!encoder
.empty()) {
17 // These remain the same under LEB128 unsigned encoding
18 if (!encoder
.writeVarU32(0x0) || !encoder
.writeVarU32(0x1) ||
19 !encoder
.writeVarU32(0x42)) {
24 if (!encoder
.writeVarU32(0x80)) {
29 if (!encoder
.writeVarU32(0x180)) {
33 if (encoder
.empty()) {
36 if (encoder
.currentOffset() != 7) {
43 BEGIN_TEST(testWasmLEB128_encoding
) {
48 Encoder
encoder(bytes
);
51 if (!WriteValidBytes(encoder
, &passed
)) {
57 CHECK(bytes
[i
++] == 0x0);
58 CHECK(bytes
[i
++] == 0x1);
59 CHECK(bytes
[i
++] == 0x42);
61 CHECK(bytes
[i
++] == 0x80);
62 CHECK(bytes
[i
++] == 0x01);
64 CHECK(bytes
[i
++] == 0x80);
65 CHECK(bytes
[i
++] == 0x03);
67 if (i
+ 1 < bytes
.length()) {
68 CHECK(bytes
[i
++] == 0x00);
72 END_TEST(testWasmLEB128_encoding
)
74 BEGIN_TEST(testWasmLEB128_valid_decoding
) {
79 if (!bytes
.append(0x0) || !bytes
.append(0x1) || !bytes
.append(0x42)) {
83 if (!bytes
.append(0x80) || !bytes
.append(0x01)) {
87 if (!bytes
.append(0x80) || !bytes
.append(0x03)) {
93 Decoder
decoder(bytes
);
96 CHECK(decoder
.readVarU32(&value
) && value
== 0x0);
97 CHECK(decoder
.readVarU32(&value
) && value
== 0x1);
98 CHECK(decoder
.readVarU32(&value
) && value
== 0x42);
99 CHECK(decoder
.readVarU32(&value
) && value
== 0x80);
100 CHECK(decoder
.readVarU32(&value
) && value
== 0x180);
102 CHECK(decoder
.done());
106 // Infallible decoding
107 Decoder
decoder(bytes
);
110 value
= decoder
.uncheckedReadVarU32();
112 value
= decoder
.uncheckedReadVarU32();
114 value
= decoder
.uncheckedReadVarU32();
115 CHECK(value
== 0x42);
116 value
= decoder
.uncheckedReadVarU32();
117 CHECK(value
== 0x80);
118 value
= decoder
.uncheckedReadVarU32();
119 CHECK(value
== 0x180);
121 CHECK(decoder
.done());
125 END_TEST(testWasmLEB128_valid_decoding
)
127 BEGIN_TEST(testWasmLEB128_invalid_decoding
) {
129 using namespace wasm
;
132 // Fill bits as per 28 encoded bits
133 if (!bytes
.append(0x80) || !bytes
.append(0x80) || !bytes
.append(0x80) ||
134 !bytes
.append(0x80)) {
138 // Test last valid values
139 if (!bytes
.append(0x00)) {
143 for (uint8_t i
= 0; i
< 0x0F; i
++) {
147 Decoder
decoder(bytes
);
149 CHECK(decoder
.readVarU32(&value
));
150 CHECK(value
== uint32_t(i
<< 28));
151 CHECK(decoder
.done());
155 Decoder
decoder(bytes
);
156 uint32_t value
= decoder
.uncheckedReadVarU32();
157 CHECK(value
== uint32_t(i
<< 28));
158 CHECK(decoder
.done());
162 // Test all invalid values of the same size
163 for (uint8_t i
= 0x10; i
< 0xF0; i
++) {
166 Decoder
decoder(bytes
);
168 CHECK(!decoder
.readVarU32(&value
));
173 END_TEST(testWasmLEB128_invalid_decoding
)