OLD | NEW |
1 // Copyright 2015 the V8 project authors. All rights reserved. | 1 // Copyright 2015 the V8 project authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "src/wasm/module-decoder.h" | 5 #include "src/wasm/module-decoder.h" |
6 | 6 |
7 #include "src/base/functional.h" | 7 #include "src/base/functional.h" |
8 #include "src/base/platform/platform.h" | 8 #include "src/base/platform/platform.h" |
9 #include "src/macro-assembler.h" | 9 #include "src/macro-assembler.h" |
10 #include "src/objects.h" | 10 #include "src/objects.h" |
11 #include "src/v8.h" | 11 #include "src/v8.h" |
12 | 12 |
13 #include "src/wasm/decoder.h" | 13 #include "src/wasm/decoder.h" |
14 | 14 |
15 namespace v8 { | 15 namespace v8 { |
16 namespace internal { | 16 namespace internal { |
17 namespace wasm { | 17 namespace wasm { |
18 | 18 |
19 #if DEBUG | 19 #if DEBUG |
20 #define TRACE(...) \ | 20 #define TRACE(...) \ |
21 do { \ | 21 do { \ |
22 if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \ | 22 if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \ |
23 } while (false) | 23 } while (false) |
24 #else | 24 #else |
25 #define TRACE(...) | 25 #define TRACE(...) |
26 #endif | 26 #endif |
27 | 27 |
28 namespace { | 28 namespace { |
29 | 29 |
| 30 const char* kNameString = "name"; |
| 31 const size_t kNameStringLength = 4; |
| 32 |
| 33 LocalType TypeOf(const WasmModule* module, const WasmInitExpr& expr) { |
| 34 switch (expr.kind) { |
| 35 case WasmInitExpr::kNone: |
| 36 return kAstStmt; |
| 37 case WasmInitExpr::kGlobalIndex: |
| 38 return expr.val.global_index < module->globals.size() |
| 39 ? module->globals[expr.val.global_index].type |
| 40 : kAstStmt; |
| 41 case WasmInitExpr::kI32Const: |
| 42 return kAstI32; |
| 43 case WasmInitExpr::kI64Const: |
| 44 return kAstI64; |
| 45 case WasmInitExpr::kF32Const: |
| 46 return kAstF32; |
| 47 case WasmInitExpr::kF64Const: |
| 48 return kAstF64; |
| 49 default: |
| 50 UNREACHABLE(); |
| 51 return kAstStmt; |
| 52 } |
| 53 } |
| 54 |
| 55 // An iterator over the sections in a WASM binary module. |
| 56 // Automatically skips all unknown sections. |
| 57 class WasmSectionIterator { |
| 58 public: |
| 59 explicit WasmSectionIterator(Decoder& decoder) |
| 60 : decoder_(decoder), |
| 61 section_code_(kUnknownSectionCode), |
| 62 section_start_(decoder.pc()), |
| 63 section_end_(decoder.pc()) { |
| 64 next(); |
| 65 } |
| 66 |
| 67 inline bool more() const { |
| 68 return section_code_ != kUnknownSectionCode && decoder_.more(); |
| 69 } |
| 70 |
| 71 inline WasmSectionCode section_code() const { return section_code_; } |
| 72 |
| 73 inline const byte* section_start() const { return section_start_; } |
| 74 |
| 75 inline uint32_t section_length() const { |
| 76 return static_cast<uint32_t>(section_end_ - section_start_); |
| 77 } |
| 78 |
| 79 inline const byte* section_end() const { return section_end_; } |
| 80 |
| 81 // Advances to the next section, checking that decoding the current section |
| 82 // stopped at {section_end_}. |
| 83 void advance() { |
| 84 if (decoder_.pc() != section_end_) { |
| 85 const char* msg = decoder_.pc() < section_end_ ? "shorter" : "longer"; |
| 86 decoder_.error(decoder_.pc(), decoder_.pc(), |
| 87 "section was %s than expected size " |
| 88 "(%u bytes expected, %zu decoded)", |
| 89 msg, section_length(), |
| 90 static_cast<size_t>(decoder_.pc() - section_start_)); |
| 91 } |
| 92 next(); |
| 93 } |
| 94 |
| 95 private: |
| 96 Decoder& decoder_; |
| 97 WasmSectionCode section_code_; |
| 98 const byte* section_start_; |
| 99 const byte* section_end_; |
| 100 |
| 101 // Reads the section code/name at the current position and sets up |
| 102 // the internal fields. |
| 103 void next() { |
| 104 while (true) { |
| 105 if (!decoder_.more()) { |
| 106 section_code_ = kUnknownSectionCode; |
| 107 return; |
| 108 } |
| 109 uint8_t section_code = decoder_.consume_u8("section code"); |
| 110 // Read and check the section size. |
| 111 uint32_t section_length = decoder_.consume_u32v("section length"); |
| 112 section_start_ = decoder_.pc(); |
| 113 if (decoder_.checkAvailable(section_length)) { |
| 114 // Get the limit of the section within the module. |
| 115 section_end_ = section_start_ + section_length; |
| 116 } else { |
| 117 // The section would extend beyond the end of the module. |
| 118 section_end_ = section_start_; |
| 119 } |
| 120 |
| 121 if (section_code == kUnknownSectionCode) { |
| 122 // Check for the known "names" section. |
| 123 uint32_t string_length = decoder_.consume_u32v("section name length"); |
| 124 const byte* section_name_start = decoder_.pc(); |
| 125 decoder_.consume_bytes(string_length, "section name"); |
| 126 if (decoder_.failed() || decoder_.pc() > section_end_) { |
| 127 TRACE("Section name of length %u couldn't be read\n", string_length); |
| 128 section_code_ = kUnknownSectionCode; |
| 129 return; |
| 130 } |
| 131 |
| 132 TRACE(" +%d section name : \"%.*s\"\n", |
| 133 static_cast<int>(section_name_start - decoder_.start()), |
| 134 string_length < 20 ? string_length : 20, section_name_start); |
| 135 |
| 136 if (string_length == kNameStringLength && |
| 137 strncmp(reinterpret_cast<const char*>(section_name_start), |
| 138 kNameString, kNameStringLength) == 0) { |
| 139 section_code = kNameSectionCode; |
| 140 } else { |
| 141 section_code = kUnknownSectionCode; |
| 142 } |
| 143 } else if (!IsValidSectionCode(section_code)) { |
| 144 decoder_.error(decoder_.pc(), decoder_.pc(), |
| 145 "unknown section code #0x%02x", section_code); |
| 146 section_code = kUnknownSectionCode; |
| 147 } |
| 148 section_code_ = static_cast<WasmSectionCode>(section_code); |
| 149 |
| 150 TRACE("Section: %s\n", SectionName(section_code_)); |
| 151 if (section_code_ == kUnknownSectionCode && |
| 152 section_end_ > decoder_.pc()) { |
| 153 // skip to the end of the unknown section. |
| 154 uint32_t remaining = |
| 155 static_cast<uint32_t>(section_end_ - decoder_.pc()); |
| 156 decoder_.consume_bytes(remaining, "section payload"); |
| 157 // fall through and continue to the next section. |
| 158 } else { |
| 159 return; |
| 160 } |
| 161 } |
| 162 } |
| 163 }; |
| 164 |
30 // The main logic for decoding the bytes of a module. | 165 // The main logic for decoding the bytes of a module. |
31 class ModuleDecoder : public Decoder { | 166 class ModuleDecoder : public Decoder { |
32 public: | 167 public: |
33 ModuleDecoder(Zone* zone, const byte* module_start, const byte* module_end, | 168 ModuleDecoder(Zone* zone, const byte* module_start, const byte* module_end, |
34 ModuleOrigin origin) | 169 ModuleOrigin origin) |
35 : Decoder(module_start, module_end), module_zone(zone), origin_(origin) { | 170 : Decoder(module_start, module_end), module_zone(zone), origin_(origin) { |
36 result_.start = start_; | 171 result_.start = start_; |
37 if (limit_ < start_) { | 172 if (limit_ < start_) { |
38 error(start_, "end is less than start"); | 173 error(start_, "end is less than start"); |
39 limit_ = start_; | 174 limit_ = start_; |
(...skipping 30 matching lines...) Expand all Loading... |
70 } | 205 } |
71 | 206 |
72 // Decodes an entire module. | 207 // Decodes an entire module. |
73 ModuleResult DecodeModule(WasmModule* module, bool verify_functions = true) { | 208 ModuleResult DecodeModule(WasmModule* module, bool verify_functions = true) { |
74 pc_ = start_; | 209 pc_ = start_; |
75 module->module_start = start_; | 210 module->module_start = start_; |
76 module->module_end = limit_; | 211 module->module_end = limit_; |
77 module->min_mem_pages = 0; | 212 module->min_mem_pages = 0; |
78 module->max_mem_pages = 0; | 213 module->max_mem_pages = 0; |
79 module->mem_export = false; | 214 module->mem_export = false; |
80 module->mem_external = false; | |
81 module->origin = origin_; | 215 module->origin = origin_; |
82 | 216 |
83 const byte* pos = pc_; | 217 const byte* pos = pc_; |
84 int current_order = 0; | |
85 uint32_t magic_word = consume_u32("wasm magic"); | 218 uint32_t magic_word = consume_u32("wasm magic"); |
86 #define BYTES(x) (x & 0xff), (x >> 8) & 0xff, (x >> 16) & 0xff, (x >> 24) & 0xff | 219 #define BYTES(x) (x & 0xff), (x >> 8) & 0xff, (x >> 16) & 0xff, (x >> 24) & 0xff |
87 if (magic_word != kWasmMagic) { | 220 if (magic_word != kWasmMagic) { |
88 error(pos, pos, | 221 error(pos, pos, |
89 "expected magic word %02x %02x %02x %02x, " | 222 "expected magic word %02x %02x %02x %02x, " |
90 "found %02x %02x %02x %02x", | 223 "found %02x %02x %02x %02x", |
91 BYTES(kWasmMagic), BYTES(magic_word)); | 224 BYTES(kWasmMagic), BYTES(magic_word)); |
92 goto done; | |
93 } | 225 } |
94 | 226 |
95 pos = pc_; | 227 pos = pc_; |
96 { | 228 { |
97 uint32_t magic_version = consume_u32("wasm version"); | 229 uint32_t magic_version = consume_u32("wasm version"); |
98 if (magic_version != kWasmVersion) { | 230 if (magic_version != kWasmVersion) { |
99 error(pos, pos, | 231 error(pos, pos, |
100 "expected version %02x %02x %02x %02x, " | 232 "expected version %02x %02x %02x %02x, " |
101 "found %02x %02x %02x %02x", | 233 "found %02x %02x %02x %02x", |
102 BYTES(kWasmVersion), BYTES(magic_version)); | 234 BYTES(kWasmVersion), BYTES(magic_version)); |
103 goto done; | 235 } |
104 } | 236 } |
105 } | 237 |
106 | 238 WasmSectionIterator section_iter(*this); |
107 // Decode the module sections. | 239 |
108 while (pc_ < limit_) { | 240 // ===== Type section ==================================================== |
109 TRACE("DecodeSection\n"); | 241 if (section_iter.section_code() == kTypeSectionCode) { |
110 pos = pc_; | 242 uint32_t signatures_count = consume_u32v("signatures count"); |
111 | 243 module->signatures.reserve(SafeReserve(signatures_count)); |
112 // Read the section name. | 244 for (uint32_t i = 0; ok() && i < signatures_count; ++i) { |
113 uint32_t string_length = consume_u32v("section name length"); | 245 TRACE("DecodeSignature[%d] module+%d\n", i, |
114 const byte* section_name_start = pc_; | 246 static_cast<int>(pc_ - start_)); |
115 consume_bytes(string_length); | 247 FunctionSig* s = consume_sig(); |
116 if (failed()) { | 248 module->signatures.push_back(s); |
117 TRACE("Section name of length %u couldn't be read\n", string_length); | 249 } |
118 break; | 250 section_iter.advance(); |
119 } | 251 } |
120 | 252 |
121 TRACE(" +%d section name : \"%.*s\"\n", | 253 // ===== Import section ================================================== |
122 static_cast<int>(section_name_start - start_), | 254 if (section_iter.section_code() == kImportSectionCode) { |
123 string_length < 20 ? string_length : 20, section_name_start); | 255 uint32_t import_table_count = consume_u32v("import table count"); |
124 | 256 module->import_table.reserve(SafeReserve(import_table_count)); |
125 WasmSection::Code section = | 257 for (uint32_t i = 0; ok() && i < import_table_count; ++i) { |
126 WasmSection::lookup(section_name_start, string_length); | 258 TRACE("DecodeImportTable[%d] module+%d\n", i, |
127 | 259 static_cast<int>(pc_ - start_)); |
128 // Read and check the section size. | 260 |
129 uint32_t section_length = consume_u32v("section length"); | 261 module->import_table.push_back({ |
130 if (!checkAvailable(section_length)) { | 262 0, // module_name_length |
131 // The section would extend beyond the end of the module. | 263 0, // module_name_offset |
132 break; | 264 0, // field_name_offset |
133 } | 265 0, // field_name_length |
134 const byte* section_start = pc_; | 266 kExternalFunction, // kind |
135 const byte* expected_section_end = pc_ + section_length; | 267 0 // index |
136 | 268 }); |
137 current_order = CheckSectionOrder(current_order, section); | 269 WasmImport* import = &module->import_table.back(); |
138 | 270 const byte* pos = pc_; |
139 switch (section) { | 271 import->module_name_offset = |
140 case WasmSection::Code::End: | 272 consume_string(&import->module_name_length, true); |
141 // Terminate section decoding. | 273 if (import->module_name_length == 0) { |
142 limit_ = pc_; | 274 error(pos, "import module name cannot be NULL"); |
143 break; | 275 } |
144 case WasmSection::Code::Memory: { | 276 import->field_name_offset = |
145 module->min_mem_pages = consume_u32v("min memory"); | 277 consume_string(&import->field_name_length, true); |
146 module->max_mem_pages = consume_u32v("max memory"); | 278 |
147 module->mem_export = consume_u8("export memory") != 0; | 279 import->kind = static_cast<WasmExternalKind>(consume_u8("import kind")); |
148 break; | 280 switch (import->kind) { |
149 } | 281 case kExternalFunction: { |
150 case WasmSection::Code::Signatures: { | 282 // ===== Imported function ======================================= |
151 uint32_t signatures_count = consume_u32v("signatures count"); | 283 import->index = static_cast<uint32_t>(module->functions.size()); |
152 module->signatures.reserve(SafeReserve(signatures_count)); | 284 module->num_imported_functions++; |
153 // Decode signatures. | 285 module->functions.push_back({nullptr, // sig |
154 for (uint32_t i = 0; ok() && i < signatures_count; ++i) { | 286 import->index, // func_index |
155 TRACE("DecodeSignature[%d] module+%d\n", i, | 287 0, // sig_index |
156 static_cast<int>(pc_ - start_)); | 288 0, // name_offset |
157 FunctionSig* s = consume_sig(); | 289 0, // name_length |
158 module->signatures.push_back(s); | 290 0, // code_start_offset |
159 } | 291 0, // code_end_offset |
160 break; | 292 true, // imported |
161 } | 293 false}); // exported |
162 case WasmSection::Code::FunctionSignatures: { | |
163 uint32_t functions_count = consume_u32v("functions count"); | |
164 module->functions.reserve(SafeReserve(functions_count)); | |
165 for (uint32_t i = 0; ok() && i < functions_count; ++i) { | |
166 module->functions.push_back({nullptr, // sig | |
167 i, // func_index | |
168 0, // sig_index | |
169 0, // name_offset | |
170 0, // name_length | |
171 0, // code_start_offset | |
172 0}); // code_end_offset | |
173 WasmFunction* function = &module->functions.back(); | 294 WasmFunction* function = &module->functions.back(); |
174 function->sig_index = consume_sig_index(module, &function->sig); | 295 function->sig_index = consume_sig_index(module, &function->sig); |
175 } | 296 break; |
176 break; | 297 } |
177 } | 298 case kExternalTable: { |
178 case WasmSection::Code::FunctionBodies: { | 299 // ===== Imported table ========================================== |
179 const byte* pos = pc_; | 300 import->index = |
180 uint32_t functions_count = consume_u32v("functions count"); | 301 static_cast<uint32_t>(module->function_tables.size()); |
181 if (functions_count != module->functions.size()) { | 302 module->function_tables.push_back( |
182 error(pos, pos, "function body count %u mismatch (%u expected)", | 303 {0, 0, std::vector<int32_t>(), true, false}); |
183 functions_count, | 304 expect_u8("element type", 0x20); |
184 static_cast<uint32_t>(module->functions.size())); | 305 WasmIndirectFunctionTable* table = &module->function_tables.back(); |
185 break; | 306 consume_resizable_limits("element count", "elements", kMaxUInt32, |
186 } | 307 &table->size, &table->max_size); |
187 for (uint32_t i = 0; ok() && i < functions_count; ++i) { | 308 break; |
188 WasmFunction* function = &module->functions[i]; | 309 } |
189 uint32_t size = consume_u32v("body size"); | 310 case kExternalMemory: { |
190 function->code_start_offset = pc_offset(); | 311 // ===== Imported memory ========================================= |
191 function->code_end_offset = pc_offset() + size; | 312 // import->index = |
192 | 313 // static_cast<uint32_t>(module->memories.size()); |
193 TRACE(" +%d %-20s: (%d bytes)\n", pc_offset(), "function body", | 314 // TODO(titzer): imported memories |
194 size); | 315 break; |
195 pc_ += size; | 316 } |
196 if (pc_ > limit_) { | 317 case kExternalGlobal: { |
197 error(pc_, "function body extends beyond end of file"); | 318 // ===== Imported global ========================================= |
198 } | 319 import->index = static_cast<uint32_t>(module->globals.size()); |
199 } | 320 module->globals.push_back( |
200 break; | 321 {kAstStmt, false, NO_INIT, 0, true, false}); |
201 } | |
202 case WasmSection::Code::Names: { | |
203 const byte* pos = pc_; | |
204 uint32_t functions_count = consume_u32v("functions count"); | |
205 if (functions_count != module->functions.size()) { | |
206 error(pos, pos, "function name count %u mismatch (%u expected)", | |
207 functions_count, | |
208 static_cast<uint32_t>(module->functions.size())); | |
209 break; | |
210 } | |
211 | |
212 for (uint32_t i = 0; ok() && i < functions_count; ++i) { | |
213 WasmFunction* function = &module->functions[i]; | |
214 function->name_offset = | |
215 consume_string(&function->name_length, false); | |
216 | |
217 uint32_t local_names_count = consume_u32v("local names count"); | |
218 for (uint32_t j = 0; ok() && j < local_names_count; j++) { | |
219 uint32_t unused = 0; | |
220 uint32_t offset = consume_string(&unused, false); | |
221 USE(unused); | |
222 USE(offset); | |
223 } | |
224 } | |
225 break; | |
226 } | |
227 case WasmSection::Code::Globals: { | |
228 uint32_t globals_count = consume_u32v("globals count"); | |
229 module->globals.reserve(SafeReserve(globals_count)); | |
230 // Decode globals. | |
231 for (uint32_t i = 0; ok() && i < globals_count; ++i) { | |
232 TRACE("DecodeGlobal[%d] module+%d\n", i, | |
233 static_cast<int>(pc_ - start_)); | |
234 // Add an uninitialized global and pass a pointer to it. | |
235 module->globals.push_back({0, 0, kAstStmt, 0, false}); | |
236 WasmGlobal* global = &module->globals.back(); | 322 WasmGlobal* global = &module->globals.back(); |
237 DecodeGlobalInModule(global); | 323 global->type = consume_value_type(); |
238 } | 324 global->mutability = consume_u8("mutability") != 0; |
239 break; | 325 break; |
240 } | 326 } |
241 case WasmSection::Code::DataSegments: { | 327 default: |
242 uint32_t data_segments_count = consume_u32v("data segments count"); | 328 error(pos, pos, "unknown import kind 0x%02x", import->kind); |
243 module->data_segments.reserve(SafeReserve(data_segments_count)); | 329 break; |
244 // Decode data segments. | 330 } |
245 for (uint32_t i = 0; ok() && i < data_segments_count; ++i) { | 331 } |
246 TRACE("DecodeDataSegment[%d] module+%d\n", i, | 332 section_iter.advance(); |
247 static_cast<int>(pc_ - start_)); | 333 } |
248 module->data_segments.push_back({0, // dest_addr | 334 |
249 0, // source_offset | 335 // ===== Function section ================================================ |
250 0, // source_size | 336 if (section_iter.section_code() == kFunctionSectionCode) { |
251 false}); // init | 337 uint32_t functions_count = consume_u32v("functions count"); |
252 WasmDataSegment* segment = &module->data_segments.back(); | 338 module->functions.reserve(SafeReserve(functions_count)); |
253 DecodeDataSegmentInModule(module, segment); | 339 module->num_declared_functions = functions_count; |
254 } | 340 for (uint32_t i = 0; ok() && i < functions_count; ++i) { |
255 break; | 341 uint32_t func_index = static_cast<uint32_t>(module->functions.size()); |
256 } | 342 module->functions.push_back({nullptr, // sig |
257 case WasmSection::Code::FunctionTable: { | 343 func_index, // func_index |
258 // An indirect function table requires functions first. | 344 0, // sig_index |
259 CheckForFunctions(module, section); | 345 0, // name_offset |
260 // Assume only one table for now. | 346 0, // name_length |
261 static const uint32_t kSupportedTableCount = 1; | 347 0, // code_start_offset |
262 module->function_tables.reserve(SafeReserve(kSupportedTableCount)); | 348 0, // code_end_offset |
263 // Decode function table. | 349 false, // imported |
264 for (uint32_t i = 0; ok() && i < kSupportedTableCount; ++i) { | 350 false}); // exported |
265 TRACE("DecodeFunctionTable[%d] module+%d\n", i, | 351 WasmFunction* function = &module->functions.back(); |
266 static_cast<int>(pc_ - start_)); | 352 function->sig_index = consume_sig_index(module, &function->sig); |
267 module->function_tables.push_back({0, 0, std::vector<uint16_t>()}); | 353 } |
268 DecodeFunctionTableInModule(module, &module->function_tables[i]); | 354 section_iter.advance(); |
269 } | 355 } |
270 break; | 356 |
271 } | 357 // ===== Table section =================================================== |
272 case WasmSection::Code::StartFunction: { | 358 if (section_iter.section_code() == kTableSectionCode) { |
273 // Declares a start function for a module. | 359 const byte* pos = pc_; |
274 CheckForFunctions(module, section); | 360 uint32_t table_count = consume_u32v("table count"); |
275 if (module->start_function_index >= 0) { | 361 // Require at most one table for now. |
276 error("start function already declared"); | 362 if (table_count > 1) { |
277 break; | 363 error(pos, pos, "invalid table count %d, maximum 1", table_count); |
278 } | 364 } |
279 WasmFunction* func; | 365 |
280 const byte* pos = pc_; | 366 for (uint32_t i = 0; ok() && i < table_count; i++) { |
281 module->start_function_index = consume_func_index(module, &func); | 367 module->function_tables.push_back( |
282 if (func && func->sig->parameter_count() > 0) { | 368 {0, 0, std::vector<int32_t>(), false, false}); |
283 error(pos, "invalid start function: non-zero parameter count"); | 369 WasmIndirectFunctionTable* table = &module->function_tables.back(); |
284 break; | 370 expect_u8("table type", kWasmAnyFunctionTypeForm); |
285 } | 371 consume_resizable_limits("table elements", "elements", kMaxUInt32, |
286 break; | 372 &table->size, &table->max_size); |
287 } | 373 } |
288 case WasmSection::Code::ImportTable: { | 374 section_iter.advance(); |
289 uint32_t import_table_count = consume_u32v("import table count"); | 375 } |
290 module->import_table.reserve(SafeReserve(import_table_count)); | 376 |
291 // Decode import table. | 377 // ===== Memory section ================================================== |
292 for (uint32_t i = 0; ok() && i < import_table_count; ++i) { | 378 if (section_iter.section_code() == kMemorySectionCode) { |
293 TRACE("DecodeImportTable[%d] module+%d\n", i, | 379 const byte* pos = pc_; |
294 static_cast<int>(pc_ - start_)); | 380 uint32_t memory_count = consume_u32v("memory count"); |
295 | 381 // Require at most one memory for now. |
296 module->import_table.push_back({nullptr, // sig | 382 if (memory_count > 1) { |
297 0, // sig_index | 383 error(pos, pos, "invalid memory count %d, maximum 1", memory_count); |
298 0, // module_name_offset | 384 } |
299 0, // module_name_length | 385 |
300 0, // function_name_offset | 386 for (uint32_t i = 0; ok() && i < memory_count; i++) { |
301 0}); // function_name_length | 387 consume_resizable_limits("memory", "pages", WasmModule::kMaxLegalPages, |
302 WasmImport* import = &module->import_table.back(); | 388 &module->min_mem_pages, |
303 | 389 &module->max_mem_pages); |
304 import->sig_index = consume_sig_index(module, &import->sig); | 390 } |
305 const byte* pos = pc_; | 391 section_iter.advance(); |
306 import->module_name_offset = | 392 } |
307 consume_string(&import->module_name_length, true); | 393 |
308 if (import->module_name_length == 0) { | 394 // ===== Global section ================================================== |
309 error(pos, "import module name cannot be NULL"); | 395 if (section_iter.section_code() == kGlobalSectionCode) { |
310 } | 396 uint32_t globals_count = consume_u32v("globals count"); |
311 import->function_name_offset = | 397 module->globals.reserve(SafeReserve(globals_count)); |
312 consume_string(&import->function_name_length, true); | 398 for (uint32_t i = 0; ok() && i < globals_count; ++i) { |
313 } | 399 TRACE("DecodeGlobal[%d] module+%d\n", i, |
314 break; | 400 static_cast<int>(pc_ - start_)); |
315 } | 401 // Add an uninitialized global and pass a pointer to it. |
316 case WasmSection::Code::ExportTable: { | 402 module->globals.push_back({kAstStmt, false, NO_INIT, 0, false, false}); |
317 // Declares an export table. | 403 WasmGlobal* global = &module->globals.back(); |
318 CheckForFunctions(module, section); | 404 DecodeGlobalInModule(module, i, global); |
319 uint32_t export_table_count = consume_u32v("export table count"); | 405 } |
320 module->export_table.reserve(SafeReserve(export_table_count)); | 406 section_iter.advance(); |
321 // Decode export table. | 407 } |
322 for (uint32_t i = 0; ok() && i < export_table_count; ++i) { | 408 |
323 TRACE("DecodeExportTable[%d] module+%d\n", i, | 409 // ===== Export section ================================================== |
324 static_cast<int>(pc_ - start_)); | 410 if (section_iter.section_code() == kExportSectionCode) { |
325 | 411 uint32_t export_table_count = consume_u32v("export table count"); |
326 module->export_table.push_back({0, // func_index | 412 module->export_table.reserve(SafeReserve(export_table_count)); |
327 0, // name_offset | 413 for (uint32_t i = 0; ok() && i < export_table_count; ++i) { |
328 0}); // name_length | 414 TRACE("DecodeExportTable[%d] module+%d\n", i, |
329 WasmExport* exp = &module->export_table.back(); | 415 static_cast<int>(pc_ - start_)); |
330 | 416 |
331 WasmFunction* func; | 417 module->export_table.push_back({ |
332 exp->func_index = consume_func_index(module, &func); | 418 0, // name_length |
333 exp->name_offset = consume_string(&exp->name_length, true); | 419 0, // name_offset |
334 } | 420 kExternalFunction, // kind |
335 // Check for duplicate exports. | 421 0 // index |
336 if (ok() && module->export_table.size() > 1) { | 422 }); |
337 std::vector<WasmExport> sorted_exports(module->export_table); | 423 WasmExport* exp = &module->export_table.back(); |
338 const byte* base = start_; | 424 |
339 auto cmp_less = [base](const WasmExport& a, const WasmExport& b) { | 425 exp->name_offset = consume_string(&exp->name_length, true); |
340 // Return true if a < b. | 426 const byte* pos = pc(); |
341 uint32_t len = a.name_length; | 427 exp->kind = static_cast<WasmExternalKind>(consume_u8("export kind")); |
342 if (len != b.name_length) return len < b.name_length; | 428 switch (exp->kind) { |
343 return memcmp(base + a.name_offset, base + b.name_offset, len) < | 429 case kExternalFunction: { |
344 0; | 430 WasmFunction* func = nullptr; |
345 }; | 431 exp->index = consume_func_index(module, &func); |
346 std::stable_sort(sorted_exports.begin(), sorted_exports.end(), | 432 module->num_exported_functions++; |
347 cmp_less); | 433 if (func) func->exported = true; |
348 auto it = sorted_exports.begin(); | 434 break; |
349 WasmExport* last = &*it++; | 435 } |
350 for (auto end = sorted_exports.end(); it != end; last = &*it++) { | 436 case kExternalTable: { |
351 DCHECK(!cmp_less(*it, *last)); // Vector must be sorted. | 437 WasmIndirectFunctionTable* table = nullptr; |
352 if (!cmp_less(*last, *it)) { | 438 exp->index = consume_table_index(module, &table); |
353 const byte* pc = start_ + it->name_offset; | 439 if (table) table->exported = true; |
354 error(pc, pc, | 440 break; |
355 "Duplicate export name '%.*s' for functions %d and %d", | 441 } |
356 it->name_length, pc, last->func_index, it->func_index); | 442 case kExternalMemory: { |
357 break; | 443 uint32_t index = consume_u32v("memory index"); |
358 } | 444 if (index != 0) error("invalid memory index != 0"); |
359 } | 445 module->mem_export = true; |
360 } | 446 break; |
361 break; | 447 } |
362 } | 448 case kExternalGlobal: { |
363 case WasmSection::Code::Max: | 449 WasmGlobal* global = nullptr; |
364 // Skip unknown sections. | 450 exp->index = consume_global_index(module, &global); |
365 TRACE("Unknown section: '"); | 451 if (global) global->exported = true; |
366 for (uint32_t i = 0; i != string_length; ++i) { | 452 break; |
367 TRACE("%c", *(section_name_start + i)); | 453 } |
368 } | 454 default: |
369 TRACE("'\n"); | 455 error(pos, pos, "invalid export kind 0x%02x", exp->kind); |
370 consume_bytes(section_length); | 456 break; |
371 break; | 457 } |
372 } | 458 } |
373 | 459 // Check for duplicate exports. |
374 if (pc_ != expected_section_end) { | 460 if (ok() && module->export_table.size() > 1) { |
375 const char* diff = pc_ < expected_section_end ? "shorter" : "longer"; | 461 std::vector<WasmExport> sorted_exports(module->export_table); |
376 size_t expected_length = static_cast<size_t>(section_length); | 462 const byte* base = start_; |
377 size_t actual_length = static_cast<size_t>(pc_ - section_start); | 463 auto cmp_less = [base](const WasmExport& a, const WasmExport& b) { |
378 error(pc_, pc_, | 464 // Return true if a < b. |
379 "section \"%s\" %s (%zu bytes) than specified (%zu bytes)", | 465 if (a.name_length != b.name_length) { |
380 WasmSection::getName(section), diff, actual_length, | 466 return a.name_length < b.name_length; |
381 expected_length); | 467 } |
382 break; | 468 return memcmp(base + a.name_offset, base + b.name_offset, |
383 } | 469 a.name_length) < 0; |
384 } | 470 }; |
385 | 471 std::stable_sort(sorted_exports.begin(), sorted_exports.end(), |
386 done: | 472 cmp_less); |
387 if (ok()) CalculateGlobalsOffsets(module); | 473 auto it = sorted_exports.begin(); |
| 474 WasmExport* last = &*it++; |
| 475 for (auto end = sorted_exports.end(); it != end; last = &*it++) { |
| 476 DCHECK(!cmp_less(*it, *last)); // Vector must be sorted. |
| 477 if (!cmp_less(*last, *it)) { |
| 478 const byte* pc = start_ + it->name_offset; |
| 479 error(pc, pc, |
| 480 "Duplicate export name '%.*s' for functions %d and %d", |
| 481 it->name_length, pc, last->index, it->index); |
| 482 break; |
| 483 } |
| 484 } |
| 485 } |
| 486 section_iter.advance(); |
| 487 } |
| 488 |
| 489 // ===== Start section =================================================== |
| 490 if (section_iter.section_code() == kStartSectionCode) { |
| 491 WasmFunction* func; |
| 492 const byte* pos = pc_; |
| 493 module->start_function_index = consume_func_index(module, &func); |
| 494 if (func && func->sig->parameter_count() > 0) { |
| 495 error(pos, "invalid start function: non-zero parameter count"); |
| 496 } |
| 497 section_iter.advance(); |
| 498 } |
| 499 |
| 500 // ===== Elements section ================================================ |
| 501 if (section_iter.section_code() == kElementSectionCode) { |
| 502 uint32_t element_count = consume_u32v("element count"); |
| 503 for (uint32_t i = 0; ok() && i < element_count; ++i) { |
| 504 uint32_t table_index = consume_u32v("table index"); |
| 505 if (table_index != 0) error("illegal table index != 0"); |
| 506 WasmInitExpr offset = consume_init_expr(module, kAstI32); |
| 507 uint32_t num_elem = consume_u32v("number of elements"); |
| 508 std::vector<uint32_t> vector; |
| 509 module->table_inits.push_back({table_index, offset, vector}); |
| 510 WasmTableInit* init = &module->table_inits.back(); |
| 511 init->entries.reserve(SafeReserve(num_elem)); |
| 512 for (uint32_t j = 0; ok() && j < num_elem; j++) { |
| 513 WasmFunction* func = nullptr; |
| 514 init->entries.push_back(consume_func_index(module, &func)); |
| 515 } |
| 516 } |
| 517 |
| 518 section_iter.advance(); |
| 519 } |
| 520 |
| 521 // ===== Code section ==================================================== |
| 522 if (section_iter.section_code() == kCodeSectionCode) { |
| 523 const byte* pos = pc_; |
| 524 uint32_t functions_count = consume_u32v("functions count"); |
| 525 if (functions_count != module->num_declared_functions) { |
| 526 error(pos, pos, "function body count %u mismatch (%u expected)", |
| 527 functions_count, module->num_declared_functions); |
| 528 } |
| 529 for (uint32_t i = 0; ok() && i < functions_count; ++i) { |
| 530 WasmFunction* function = |
| 531 &module->functions[i + module->num_imported_functions]; |
| 532 uint32_t size = consume_u32v("body size"); |
| 533 function->code_start_offset = pc_offset(); |
| 534 function->code_end_offset = pc_offset() + size; |
| 535 consume_bytes(size, "function body"); |
| 536 } |
| 537 section_iter.advance(); |
| 538 } |
| 539 |
| 540 // ===== Data section ==================================================== |
| 541 if (section_iter.section_code() == kDataSectionCode) { |
| 542 uint32_t data_segments_count = consume_u32v("data segments count"); |
| 543 module->data_segments.reserve(SafeReserve(data_segments_count)); |
| 544 for (uint32_t i = 0; ok() && i < data_segments_count; ++i) { |
| 545 TRACE("DecodeDataSegment[%d] module+%d\n", i, |
| 546 static_cast<int>(pc_ - start_)); |
| 547 module->data_segments.push_back({ |
| 548 NO_INIT, // dest_addr |
| 549 0, // source_offset |
| 550 0 // source_size |
| 551 }); |
| 552 WasmDataSegment* segment = &module->data_segments.back(); |
| 553 DecodeDataSegmentInModule(module, segment); |
| 554 } |
| 555 section_iter.advance(); |
| 556 } |
| 557 |
| 558 // ===== Name section ==================================================== |
| 559 if (section_iter.section_code() == kNameSectionCode) { |
| 560 const byte* pos = pc_; |
| 561 uint32_t functions_count = consume_u32v("functions count"); |
| 562 if (functions_count != module->num_declared_functions) { |
| 563 error(pos, pos, "function name count %u mismatch (%u expected)", |
| 564 functions_count, module->num_declared_functions); |
| 565 } |
| 566 |
| 567 for (uint32_t i = 0; ok() && i < functions_count; ++i) { |
| 568 WasmFunction* function = |
| 569 &module->functions[i + module->num_imported_functions]; |
| 570 function->name_offset = consume_string(&function->name_length, false); |
| 571 |
| 572 uint32_t local_names_count = consume_u32v("local names count"); |
| 573 for (uint32_t j = 0; ok() && j < local_names_count; j++) { |
| 574 uint32_t unused = 0; |
| 575 uint32_t offset = consume_string(&unused, false); |
| 576 USE(unused); |
| 577 USE(offset); |
| 578 } |
| 579 } |
| 580 section_iter.advance(); |
| 581 } |
| 582 |
| 583 // ===== Remaining sections ============================================== |
| 584 if (section_iter.more() && ok()) { |
| 585 error(pc(), pc(), "unexpected section: %s", |
| 586 SectionName(section_iter.section_code())); |
| 587 } |
| 588 |
| 589 if (ok()) { |
| 590 CalculateGlobalOffsets(module); |
| 591 PreinitializeIndirectFunctionTables(module); |
| 592 } |
388 const WasmModule* finished_module = module; | 593 const WasmModule* finished_module = module; |
389 ModuleResult result = toResult(finished_module); | 594 ModuleResult result = toResult(finished_module); |
390 if (FLAG_dump_wasm_module) { | 595 if (FLAG_dump_wasm_module) DumpModule(module, result); |
391 DumpModule(module, result); | |
392 } | |
393 return result; | 596 return result; |
394 } | 597 } |
395 | 598 |
396 uint32_t SafeReserve(uint32_t count) { | 599 uint32_t SafeReserve(uint32_t count) { |
397 // Avoid OOM by only reserving up to a certain size. | 600 // Avoid OOM by only reserving up to a certain size. |
398 const uint32_t kMaxReserve = 20000; | 601 const uint32_t kMaxReserve = 20000; |
399 return count < kMaxReserve ? count : kMaxReserve; | 602 return count < kMaxReserve ? count : kMaxReserve; |
400 } | 603 } |
401 | 604 |
402 void CheckForFunctions(WasmModule* module, WasmSection::Code section) { | |
403 if (module->functions.size() == 0) { | |
404 error(pc_ - 1, nullptr, "functions must appear before section %s", | |
405 WasmSection::getName(section)); | |
406 } | |
407 } | |
408 | |
409 int CheckSectionOrder(int current_order, WasmSection::Code section) { | |
410 int next_order = WasmSection::getOrder(section); | |
411 if (next_order == 0) return current_order; | |
412 if (next_order == current_order) { | |
413 error(pc_, pc_, "section \"%s\" already defined", | |
414 WasmSection::getName(section)); | |
415 } | |
416 if (next_order < current_order) { | |
417 error(pc_, pc_, "section \"%s\" out of order", | |
418 WasmSection::getName(section)); | |
419 } | |
420 return next_order; | |
421 } | |
422 | |
423 // Decodes a single anonymous function starting at {start_}. | 605 // Decodes a single anonymous function starting at {start_}. |
424 FunctionResult DecodeSingleFunction(ModuleEnv* module_env, | 606 FunctionResult DecodeSingleFunction(ModuleEnv* module_env, |
425 WasmFunction* function) { | 607 WasmFunction* function) { |
426 pc_ = start_; | 608 pc_ = start_; |
427 function->sig = consume_sig(); // read signature | 609 function->sig = consume_sig(); // read signature |
428 function->name_offset = 0; // ---- name | 610 function->name_offset = 0; // ---- name |
429 function->name_length = 0; // ---- name length | 611 function->name_length = 0; // ---- name length |
430 function->code_start_offset = off(pc_); // ---- code start | 612 function->code_start_offset = off(pc_); // ---- code start |
431 function->code_end_offset = off(limit_); // ---- code end | 613 function->code_end_offset = off(limit_); // ---- code end |
432 | 614 |
433 if (ok()) VerifyFunctionBody(0, module_env, function); | 615 if (ok()) VerifyFunctionBody(0, module_env, function); |
434 | 616 |
435 FunctionResult result; | 617 FunctionResult result; |
436 result.MoveFrom(result_); // Copy error code and location. | 618 result.MoveFrom(result_); // Copy error code and location. |
437 result.val = function; | 619 result.val = function; |
438 return result; | 620 return result; |
439 } | 621 } |
440 | 622 |
441 // Decodes a single function signature at {start}. | 623 // Decodes a single function signature at {start}. |
442 FunctionSig* DecodeFunctionSignature(const byte* start) { | 624 FunctionSig* DecodeFunctionSignature(const byte* start) { |
443 pc_ = start; | 625 pc_ = start; |
444 FunctionSig* result = consume_sig(); | 626 FunctionSig* result = consume_sig(); |
445 return ok() ? result : nullptr; | 627 return ok() ? result : nullptr; |
446 } | 628 } |
447 | 629 |
| 630 WasmInitExpr DecodeInitExpr(const byte* start) { |
| 631 pc_ = start; |
| 632 return consume_init_expr(nullptr, kAstStmt); |
| 633 } |
| 634 |
448 private: | 635 private: |
449 Zone* module_zone; | 636 Zone* module_zone; |
450 ModuleResult result_; | 637 ModuleResult result_; |
451 ModuleOrigin origin_; | 638 ModuleOrigin origin_; |
452 | 639 |
453 uint32_t off(const byte* ptr) { return static_cast<uint32_t>(ptr - start_); } | 640 uint32_t off(const byte* ptr) { return static_cast<uint32_t>(ptr - start_); } |
454 | 641 |
455 // Decodes a single global entry inside a module starting at {pc_}. | 642 // Decodes a single global entry inside a module starting at {pc_}. |
456 void DecodeGlobalInModule(WasmGlobal* global) { | 643 void DecodeGlobalInModule(WasmModule* module, uint32_t index, |
457 global->name_offset = consume_string(&global->name_length, false); | 644 WasmGlobal* global) { |
458 if (ok() && | 645 global->type = consume_value_type(); |
459 !unibrow::Utf8::Validate(start_ + global->name_offset, | 646 global->mutability = consume_u8("mutability") != 0; |
460 global->name_length)) { | 647 const byte* pos = pc(); |
461 error("global name is not valid utf8"); | 648 global->init = consume_init_expr(module, kAstStmt); |
| 649 switch (global->init.kind) { |
| 650 case WasmInitExpr::kGlobalIndex: |
| 651 if (global->init.val.global_index >= index) { |
| 652 error("invalid global index in init expression"); |
| 653 } else if (module->globals[index].type != global->type) { |
| 654 error("type mismatch in global initialization"); |
| 655 } |
| 656 break; |
| 657 default: |
| 658 if (global->type != TypeOf(module, global->init)) { |
| 659 error(pos, pos, |
| 660 "type error in global initialization, expected %s, got %s", |
| 661 WasmOpcodes::TypeName(global->type), |
| 662 WasmOpcodes::TypeName(TypeOf(module, global->init))); |
| 663 } |
462 } | 664 } |
463 global->type = consume_local_type(); | |
464 if (global->type == kAstStmt) { | |
465 error("invalid global type"); | |
466 } | |
467 global->offset = 0; | |
468 global->exported = consume_u8("exported") != 0; | |
469 } | 665 } |
470 | 666 |
471 bool IsWithinLimit(uint32_t limit, uint32_t offset, uint32_t size) { | 667 bool IsWithinLimit(uint32_t limit, uint32_t offset, uint32_t size) { |
472 if (offset > limit) return false; | 668 if (offset > limit) return false; |
473 if ((offset + size) < offset) return false; // overflow | 669 if ((offset + size) < offset) return false; // overflow |
474 return (offset + size) <= limit; | 670 return (offset + size) <= limit; |
475 } | 671 } |
476 | 672 |
477 // Decodes a single data segment entry inside a module starting at {pc_}. | 673 // Decodes a single data segment entry inside a module starting at {pc_}. |
478 void DecodeDataSegmentInModule(WasmModule* module, WasmDataSegment* segment) { | 674 void DecodeDataSegmentInModule(WasmModule* module, WasmDataSegment* segment) { |
479 const byte* start = pc_; | 675 const byte* start = pc_; |
480 segment->dest_addr = consume_u32v("destination"); | 676 expect_u8("linear memory index", 0); |
| 677 segment->dest_addr = consume_init_expr(module, kAstI32); |
481 segment->source_size = consume_u32v("source size"); | 678 segment->source_size = consume_u32v("source size"); |
482 segment->source_offset = static_cast<uint32_t>(pc_ - start_); | 679 segment->source_offset = static_cast<uint32_t>(pc_ - start_); |
483 segment->init = true; | |
484 | 680 |
485 // Validate the data is in the module. | 681 // Validate the data is in the module. |
486 uint32_t module_limit = static_cast<uint32_t>(limit_ - start_); | 682 uint32_t module_limit = static_cast<uint32_t>(limit_ - start_); |
487 if (!IsWithinLimit(module_limit, segment->source_offset, | 683 if (!IsWithinLimit(module_limit, segment->source_offset, |
488 segment->source_size)) { | 684 segment->source_size)) { |
489 error(start, "segment out of bounds of module"); | 685 error(start, "segment out of bounds of module"); |
490 } | 686 } |
491 | 687 |
492 // Validate that the segment will fit into the (minimum) memory. | 688 consume_bytes(segment->source_size, "segment data"); |
493 uint32_t memory_limit = | |
494 WasmModule::kPageSize * (module ? module->min_mem_pages | |
495 : WasmModule::kMaxMemPages); | |
496 if (!IsWithinLimit(memory_limit, segment->dest_addr, | |
497 segment->source_size)) { | |
498 error(start, "segment out of bounds of memory"); | |
499 } | |
500 | |
501 consume_bytes(segment->source_size); | |
502 } | |
503 | |
504 // Decodes a single function table inside a module starting at {pc_}. | |
505 void DecodeFunctionTableInModule(WasmModule* module, | |
506 WasmIndirectFunctionTable* table) { | |
507 table->size = consume_u32v("function table entry count"); | |
508 table->max_size = table->size; | |
509 | |
510 if (table->max_size != table->size) { | |
511 error("invalid table maximum size"); | |
512 } | |
513 | |
514 for (uint32_t i = 0; ok() && i < table->size; ++i) { | |
515 uint16_t index = consume_u32v(); | |
516 if (index >= module->functions.size()) { | |
517 error(pc_ - sizeof(index), "invalid function index"); | |
518 break; | |
519 } | |
520 table->values.push_back(index); | |
521 } | |
522 } | 689 } |
523 | 690 |
524 // Calculate individual global offsets and total size of globals table. | 691 // Calculate individual global offsets and total size of globals table. |
525 void CalculateGlobalsOffsets(WasmModule* module) { | 692 void CalculateGlobalOffsets(WasmModule* module) { |
526 uint32_t offset = 0; | 693 uint32_t offset = 0; |
527 if (module->globals.size() == 0) { | 694 if (module->globals.size() == 0) { |
528 module->globals_size = 0; | 695 module->globals_size = 0; |
529 return; | 696 return; |
530 } | 697 } |
531 for (WasmGlobal& global : module->globals) { | 698 for (WasmGlobal& global : module->globals) { |
532 byte size = | 699 byte size = |
533 WasmOpcodes::MemSize(WasmOpcodes::MachineTypeFor(global.type)); | 700 WasmOpcodes::MemSize(WasmOpcodes::MachineTypeFor(global.type)); |
534 offset = (offset + size - 1) & ~(size - 1); // align | 701 offset = (offset + size - 1) & ~(size - 1); // align |
535 global.offset = offset; | 702 global.offset = offset; |
536 offset += size; | 703 offset += size; |
537 } | 704 } |
538 module->globals_size = offset; | 705 module->globals_size = offset; |
539 } | 706 } |
540 | 707 |
| 708 // TODO(titzer): this only works without overlapping initializations from |
| 709 // global bases for entries |
| 710 void PreinitializeIndirectFunctionTables(WasmModule* module) { |
| 711 // Fill all tables with invalid entries first. |
| 712 for (WasmIndirectFunctionTable& table : module->function_tables) { |
| 713 table.values.resize(table.size); |
| 714 for (size_t i = 0; i < table.size; i++) { |
| 715 table.values[i] = kInvalidFunctionIndex; |
| 716 } |
| 717 } |
| 718 for (WasmTableInit& init : module->table_inits) { |
| 719 if (init.offset.kind != WasmInitExpr::kI32Const) continue; |
| 720 if (init.table_index >= module->function_tables.size()) continue; |
| 721 WasmIndirectFunctionTable& table = |
| 722 module->function_tables[init.table_index]; |
| 723 for (size_t i = 0; i < init.entries.size(); i++) { |
| 724 size_t index = i + init.offset.val.i32_const; |
| 725 if (index < table.values.size()) { |
| 726 table.values[index] = init.entries[i]; |
| 727 } |
| 728 } |
| 729 } |
| 730 } |
| 731 |
541 // Verifies the body (code) of a given function. | 732 // Verifies the body (code) of a given function. |
542 void VerifyFunctionBody(uint32_t func_num, ModuleEnv* menv, | 733 void VerifyFunctionBody(uint32_t func_num, ModuleEnv* menv, |
543 WasmFunction* function) { | 734 WasmFunction* function) { |
544 if (FLAG_trace_wasm_decoder || FLAG_trace_wasm_decode_time) { | 735 if (FLAG_trace_wasm_decoder || FLAG_trace_wasm_decode_time) { |
545 OFStream os(stdout); | 736 OFStream os(stdout); |
546 os << "Verifying WASM function " << WasmFunctionName(function, menv) | 737 os << "Verifying WASM function " << WasmFunctionName(function, menv) |
547 << std::endl; | 738 << std::endl; |
548 } | 739 } |
549 FunctionBody body = {menv, function->sig, start_, | 740 FunctionBody body = {menv, function->sig, start_, |
550 start_ + function->code_start_offset, | 741 start_ + function->code_start_offset, |
(...skipping 10 matching lines...) Expand all Loading... |
561 char* buffer = new char[len]; | 752 char* buffer = new char[len]; |
562 strncpy(buffer, raw, len); | 753 strncpy(buffer, raw, len); |
563 buffer[len - 1] = 0; | 754 buffer[len - 1] = 0; |
564 | 755 |
565 // Copy error code and location. | 756 // Copy error code and location. |
566 result_.MoveFrom(result); | 757 result_.MoveFrom(result); |
567 result_.error_msg.reset(buffer); | 758 result_.error_msg.reset(buffer); |
568 } | 759 } |
569 } | 760 } |
570 | 761 |
571 // Reads a single 32-bit unsigned integer interpreted as an offset, checking | |
572 // the offset is within bounds and advances. | |
573 uint32_t consume_offset(const char* name = nullptr) { | |
574 uint32_t offset = consume_u32(name ? name : "offset"); | |
575 if (offset > static_cast<uint32_t>(limit_ - start_)) { | |
576 error(pc_ - sizeof(uint32_t), "offset out of bounds of module"); | |
577 } | |
578 return offset; | |
579 } | |
580 | |
581 // Reads a length-prefixed string, checking that it is within bounds. Returns | 762 // Reads a length-prefixed string, checking that it is within bounds. Returns |
582 // the offset of the string, and the length as an out parameter. | 763 // the offset of the string, and the length as an out parameter. |
583 uint32_t consume_string(uint32_t* length, bool validate_utf8) { | 764 uint32_t consume_string(uint32_t* length, bool validate_utf8) { |
584 *length = consume_u32v("string length"); | 765 *length = consume_u32v("string length"); |
585 uint32_t offset = pc_offset(); | 766 uint32_t offset = pc_offset(); |
586 TRACE(" +%u %-20s: (%u bytes)\n", offset, "string", *length); | |
587 const byte* string_start = pc_; | 767 const byte* string_start = pc_; |
588 // Consume bytes before validation to guarantee that the string is not oob. | 768 // Consume bytes before validation to guarantee that the string is not oob. |
589 consume_bytes(*length); | 769 consume_bytes(*length, "string"); |
590 if (ok() && validate_utf8 && | 770 if (ok() && validate_utf8 && |
591 !unibrow::Utf8::Validate(string_start, *length)) { | 771 !unibrow::Utf8::Validate(string_start, *length)) { |
592 error(string_start, "no valid UTF-8 string"); | 772 error(string_start, "no valid UTF-8 string"); |
593 } | 773 } |
594 return offset; | 774 return offset; |
595 } | 775 } |
596 | 776 |
597 uint32_t consume_sig_index(WasmModule* module, FunctionSig** sig) { | 777 uint32_t consume_sig_index(WasmModule* module, FunctionSig** sig) { |
598 const byte* pos = pc_; | 778 const byte* pos = pc_; |
599 uint32_t sig_index = consume_u32v("signature index"); | 779 uint32_t sig_index = consume_u32v("signature index"); |
600 if (sig_index >= module->signatures.size()) { | 780 if (sig_index >= module->signatures.size()) { |
601 error(pos, pos, "signature index %u out of bounds (%d signatures)", | 781 error(pos, pos, "signature index %u out of bounds (%d signatures)", |
602 sig_index, static_cast<int>(module->signatures.size())); | 782 sig_index, static_cast<int>(module->signatures.size())); |
603 *sig = nullptr; | 783 *sig = nullptr; |
604 return 0; | 784 return 0; |
605 } | 785 } |
606 *sig = module->signatures[sig_index]; | 786 *sig = module->signatures[sig_index]; |
607 return sig_index; | 787 return sig_index; |
608 } | 788 } |
609 | 789 |
610 uint32_t consume_func_index(WasmModule* module, WasmFunction** func) { | 790 uint32_t consume_func_index(WasmModule* module, WasmFunction** func) { |
| 791 return consume_index("function index", module->functions, func); |
| 792 } |
| 793 |
| 794 uint32_t consume_global_index(WasmModule* module, WasmGlobal** global) { |
| 795 return consume_index("global index", module->globals, global); |
| 796 } |
| 797 |
| 798 uint32_t consume_table_index(WasmModule* module, |
| 799 WasmIndirectFunctionTable** table) { |
| 800 return consume_index("table index", module->function_tables, table); |
| 801 } |
| 802 |
| 803 template <typename T> |
| 804 uint32_t consume_index(const char* name, std::vector<T>& vector, T** ptr) { |
611 const byte* pos = pc_; | 805 const byte* pos = pc_; |
612 uint32_t func_index = consume_u32v("function index"); | 806 uint32_t index = consume_u32v(name); |
613 if (func_index >= module->functions.size()) { | 807 if (index >= vector.size()) { |
614 error(pos, pos, "function index %u out of bounds (%d functions)", | 808 error(pos, pos, "%s %u out of bounds (%d entries)", name, index, |
615 func_index, static_cast<int>(module->functions.size())); | 809 static_cast<int>(vector.size())); |
616 *func = nullptr; | 810 *ptr = nullptr; |
617 return 0; | 811 return 0; |
618 } | 812 } |
619 *func = &module->functions[func_index]; | 813 *ptr = &vector[index]; |
620 return func_index; | 814 return index; |
| 815 } |
| 816 |
| 817 void consume_resizable_limits(const char* name, const char* units, |
| 818 uint32_t max_value, uint32_t* initial, |
| 819 uint32_t* maximum) { |
| 820 uint32_t flags = consume_u32v("resizable limits flags"); |
| 821 const byte* pos = pc(); |
| 822 *initial = consume_u32v("initial size"); |
| 823 if (*initial > max_value) { |
| 824 error(pos, pos, |
| 825 "initial %s size (%u %s) is larger than maximum allowable (%u)", |
| 826 name, *initial, units, max_value); |
| 827 } |
| 828 if (flags & 1) { |
| 829 pos = pc(); |
| 830 *maximum = consume_u32v("maximum size"); |
| 831 if (*maximum > max_value) { |
| 832 error(pos, pos, |
| 833 "maximum %s size (%u %s) is larger than maximum allowable (%u)", |
| 834 name, *maximum, units, max_value); |
| 835 } |
| 836 if (*maximum < *initial) { |
| 837 error(pos, pos, "maximum %s size (%u %s) is less than initial (%u %s)", |
| 838 name, *maximum, units, *initial, units); |
| 839 } |
| 840 } else { |
| 841 *maximum = 0; |
| 842 } |
| 843 } |
| 844 |
| 845 bool expect_u8(const char* name, uint8_t expected) { |
| 846 const byte* pos = pc(); |
| 847 uint8_t value = consume_u8(name); |
| 848 if (value != expected) { |
| 849 error(pos, pos, "expected %s 0x%02x, got 0x%02x", name, expected, value); |
| 850 return false; |
| 851 } |
| 852 return true; |
| 853 } |
| 854 |
| 855 WasmInitExpr consume_init_expr(WasmModule* module, LocalType expected) { |
| 856 const byte* pos = pc(); |
| 857 uint8_t opcode = consume_u8("opcode"); |
| 858 WasmInitExpr expr; |
| 859 unsigned len = 0; |
| 860 switch (opcode) { |
| 861 case kExprGetGlobal: { |
| 862 GlobalIndexOperand operand(this, pc() - 1); |
| 863 expr.kind = WasmInitExpr::kGlobalIndex; |
| 864 expr.val.global_index = operand.index; |
| 865 len = operand.length; |
| 866 break; |
| 867 } |
| 868 case kExprI32Const: { |
| 869 ImmI32Operand operand(this, pc() - 1); |
| 870 expr.kind = WasmInitExpr::kI32Const; |
| 871 expr.val.i32_const = operand.value; |
| 872 len = operand.length; |
| 873 break; |
| 874 } |
| 875 case kExprF32Const: { |
| 876 ImmF32Operand operand(this, pc() - 1); |
| 877 expr.kind = WasmInitExpr::kF32Const; |
| 878 expr.val.f32_const = operand.value; |
| 879 len = operand.length; |
| 880 break; |
| 881 } |
| 882 case kExprI64Const: { |
| 883 ImmI64Operand operand(this, pc() - 1); |
| 884 expr.kind = WasmInitExpr::kI64Const; |
| 885 expr.val.i64_const = operand.value; |
| 886 len = operand.length; |
| 887 break; |
| 888 } |
| 889 case kExprF64Const: { |
| 890 ImmF64Operand operand(this, pc() - 1); |
| 891 expr.kind = WasmInitExpr::kF64Const; |
| 892 expr.val.f64_const = operand.value; |
| 893 len = operand.length; |
| 894 break; |
| 895 } |
| 896 default: { |
| 897 error("invalid opcode in initialization expression"); |
| 898 expr.kind = WasmInitExpr::kNone; |
| 899 expr.val.i32_const = 0; |
| 900 } |
| 901 } |
| 902 consume_bytes(len, "init code"); |
| 903 if (!expect_u8("end opcode", kExprEnd)) { |
| 904 expr.kind = WasmInitExpr::kNone; |
| 905 } |
| 906 if (expected != kAstStmt && TypeOf(module, expr) != kAstI32) { |
| 907 error(pos, pos, "type error in init expression, expected %s, got %s", |
| 908 WasmOpcodes::TypeName(expected), |
| 909 WasmOpcodes::TypeName(TypeOf(module, expr))); |
| 910 } |
| 911 return expr; |
621 } | 912 } |
622 | 913 |
623 // Reads a single 8-bit integer, interpreting it as a local type. | 914 // Reads a single 8-bit integer, interpreting it as a local type. |
624 LocalType consume_local_type() { | 915 LocalType consume_value_type() { |
625 byte val = consume_u8("local type"); | 916 byte val = consume_u8("value type"); |
626 LocalTypeCode t = static_cast<LocalTypeCode>(val); | 917 LocalTypeCode t = static_cast<LocalTypeCode>(val); |
627 switch (t) { | 918 switch (t) { |
628 case kLocalVoid: | |
629 return kAstStmt; | |
630 case kLocalI32: | 919 case kLocalI32: |
631 return kAstI32; | 920 return kAstI32; |
632 case kLocalI64: | 921 case kLocalI64: |
633 return kAstI64; | 922 return kAstI64; |
634 case kLocalF32: | 923 case kLocalF32: |
635 return kAstF32; | 924 return kAstF32; |
636 case kLocalF64: | 925 case kLocalF64: |
637 return kAstF64; | 926 return kAstF64; |
638 case kLocalS128: | 927 case kLocalS128: |
639 return kAstS128; | 928 return kAstS128; |
640 default: | 929 default: |
641 error(pc_ - 1, "invalid local type"); | 930 error(pc_ - 1, "invalid local type"); |
642 return kAstStmt; | 931 return kAstStmt; |
643 } | 932 } |
644 } | 933 } |
645 | 934 |
646 // Parses a type entry, which is currently limited to functions only. | 935 // Parses a type entry, which is currently limited to functions only. |
647 FunctionSig* consume_sig() { | 936 FunctionSig* consume_sig() { |
648 const byte* pos = pc_; | 937 if (!expect_u8("type form", kWasmFunctionTypeForm)) return nullptr; |
649 byte form = consume_u8("type form"); | |
650 if (form != kWasmFunctionTypeForm) { | |
651 error(pos, pos, "expected function type form (0x%02x), got: 0x%02x", | |
652 kWasmFunctionTypeForm, form); | |
653 return nullptr; | |
654 } | |
655 // parse parameter types | 938 // parse parameter types |
656 uint32_t param_count = consume_u32v("param count"); | 939 uint32_t param_count = consume_u32v("param count"); |
657 std::vector<LocalType> params; | 940 std::vector<LocalType> params; |
658 for (uint32_t i = 0; i < param_count; ++i) { | 941 for (uint32_t i = 0; ok() && i < param_count; ++i) { |
659 LocalType param = consume_local_type(); | 942 LocalType param = consume_value_type(); |
660 if (param == kAstStmt) error(pc_ - 1, "invalid void parameter type"); | |
661 params.push_back(param); | 943 params.push_back(param); |
662 } | 944 } |
663 | 945 |
664 // parse return types | 946 // parse return types |
665 const byte* pt = pc_; | 947 const byte* pt = pc_; |
666 uint32_t return_count = consume_u32v("return count"); | 948 uint32_t return_count = consume_u32v("return count"); |
667 if (return_count > kMaxReturnCount) { | 949 if (return_count > kMaxReturnCount) { |
668 error(pt, pt, "return count of %u exceeds maximum of %u", return_count, | 950 error(pt, pt, "return count of %u exceeds maximum of %u", return_count, |
669 kMaxReturnCount); | 951 kMaxReturnCount); |
670 return nullptr; | 952 return nullptr; |
671 } | 953 } |
672 std::vector<LocalType> returns; | 954 std::vector<LocalType> returns; |
673 for (uint32_t i = 0; i < return_count; ++i) { | 955 for (uint32_t i = 0; ok() && i < return_count; ++i) { |
674 LocalType ret = consume_local_type(); | 956 LocalType ret = consume_value_type(); |
675 if (ret == kAstStmt) error(pc_ - 1, "invalid void return type"); | |
676 returns.push_back(ret); | 957 returns.push_back(ret); |
677 } | 958 } |
678 | 959 |
| 960 if (failed()) { |
| 961 // Decoding failed, return void -> void |
| 962 return new (module_zone) FunctionSig(0, 0, nullptr); |
| 963 } |
| 964 |
679 // FunctionSig stores the return types first. | 965 // FunctionSig stores the return types first. |
680 LocalType* buffer = | 966 LocalType* buffer = |
681 module_zone->NewArray<LocalType>(param_count + return_count); | 967 module_zone->NewArray<LocalType>(param_count + return_count); |
682 uint32_t b = 0; | 968 uint32_t b = 0; |
683 for (uint32_t i = 0; i < return_count; ++i) buffer[b++] = returns[i]; | 969 for (uint32_t i = 0; i < return_count; ++i) buffer[b++] = returns[i]; |
684 for (uint32_t i = 0; i < param_count; ++i) buffer[b++] = params[i]; | 970 for (uint32_t i = 0; i < param_count; ++i) buffer[b++] = params[i]; |
685 | 971 |
686 return new (module_zone) FunctionSig(return_count, param_count, buffer); | 972 return new (module_zone) FunctionSig(return_count, param_count, buffer); |
687 } | 973 } |
688 }; | 974 }; |
(...skipping 18 matching lines...) Expand all Loading... |
707 error_code = kError; | 993 error_code = kError; |
708 size_t len = strlen(msg) + 1; | 994 size_t len = strlen(msg) + 1; |
709 char* result = new char[len]; | 995 char* result = new char[len]; |
710 strncpy(result, msg, len); | 996 strncpy(result, msg, len); |
711 result[len - 1] = 0; | 997 result[len - 1] = 0; |
712 error_msg.reset(result); | 998 error_msg.reset(result); |
713 } | 999 } |
714 }; | 1000 }; |
715 | 1001 |
716 Vector<const byte> FindSection(const byte* module_start, const byte* module_end, | 1002 Vector<const byte> FindSection(const byte* module_start, const byte* module_end, |
717 WasmSection::Code code) { | 1003 WasmSectionCode code) { |
718 Decoder decoder(module_start, module_end); | 1004 Decoder decoder(module_start, module_end); |
719 | 1005 |
720 uint32_t magic_word = decoder.consume_u32("wasm magic"); | 1006 uint32_t magic_word = decoder.consume_u32("wasm magic"); |
721 if (magic_word != kWasmMagic) decoder.error("wrong magic word"); | 1007 if (magic_word != kWasmMagic) decoder.error("wrong magic word"); |
722 | 1008 |
723 uint32_t magic_version = decoder.consume_u32("wasm version"); | 1009 uint32_t magic_version = decoder.consume_u32("wasm version"); |
724 if (magic_version != kWasmVersion) decoder.error("wrong wasm version"); | 1010 if (magic_version != kWasmVersion) decoder.error("wrong wasm version"); |
725 | 1011 |
726 while (decoder.more() && decoder.ok()) { | 1012 WasmSectionIterator section_iter(decoder); |
727 // Read the section name. | 1013 while (section_iter.more()) { |
728 uint32_t string_length = decoder.consume_u32v("section name length"); | 1014 if (section_iter.section_code() == code) { |
729 const byte* section_name_start = decoder.pc(); | 1015 return Vector<const uint8_t>(section_iter.section_start(), |
730 decoder.consume_bytes(string_length); | 1016 section_iter.section_length()); |
731 if (decoder.failed()) break; | |
732 | |
733 WasmSection::Code section = | |
734 WasmSection::lookup(section_name_start, string_length); | |
735 | |
736 // Read and check the section size. | |
737 uint32_t section_length = decoder.consume_u32v("section length"); | |
738 | |
739 const byte* section_start = decoder.pc(); | |
740 decoder.consume_bytes(section_length); | |
741 if (section == code && decoder.ok()) { | |
742 return Vector<const uint8_t>(section_start, section_length); | |
743 } | 1017 } |
| 1018 decoder.consume_bytes(section_iter.section_length(), "section payload"); |
| 1019 section_iter.advance(); |
744 } | 1020 } |
745 | 1021 |
746 return Vector<const uint8_t>(); | 1022 return Vector<const uint8_t>(); |
747 } | 1023 } |
748 | 1024 |
749 } // namespace | 1025 } // namespace |
750 | 1026 |
751 ModuleResult DecodeWasmModule(Isolate* isolate, Zone* zone, | 1027 ModuleResult DecodeWasmModule(Isolate* isolate, Zone* zone, |
752 const byte* module_start, const byte* module_end, | 1028 const byte* module_start, const byte* module_end, |
753 bool verify_functions, ModuleOrigin origin) { | 1029 bool verify_functions, ModuleOrigin origin) { |
(...skipping 14 matching lines...) Expand all Loading... |
768 static_cast<int>(zone->allocation_size() - decode_memory_start)); | 1044 static_cast<int>(zone->allocation_size() - decode_memory_start)); |
769 return result; | 1045 return result; |
770 } | 1046 } |
771 | 1047 |
772 FunctionSig* DecodeWasmSignatureForTesting(Zone* zone, const byte* start, | 1048 FunctionSig* DecodeWasmSignatureForTesting(Zone* zone, const byte* start, |
773 const byte* end) { | 1049 const byte* end) { |
774 ModuleDecoder decoder(zone, start, end, kWasmOrigin); | 1050 ModuleDecoder decoder(zone, start, end, kWasmOrigin); |
775 return decoder.DecodeFunctionSignature(start); | 1051 return decoder.DecodeFunctionSignature(start); |
776 } | 1052 } |
777 | 1053 |
| 1054 WasmInitExpr DecodeWasmInitExprForTesting(const byte* start, const byte* end) { |
| 1055 AccountingAllocator allocator; |
| 1056 Zone zone(&allocator); |
| 1057 ModuleDecoder decoder(&zone, start, end, kWasmOrigin); |
| 1058 return decoder.DecodeInitExpr(start); |
| 1059 } |
| 1060 |
778 FunctionResult DecodeWasmFunction(Isolate* isolate, Zone* zone, | 1061 FunctionResult DecodeWasmFunction(Isolate* isolate, Zone* zone, |
779 ModuleEnv* module_env, | 1062 ModuleEnv* module_env, |
780 const byte* function_start, | 1063 const byte* function_start, |
781 const byte* function_end) { | 1064 const byte* function_end) { |
782 HistogramTimerScope wasm_decode_function_time_scope( | 1065 HistogramTimerScope wasm_decode_function_time_scope( |
783 isolate->counters()->wasm_decode_function_time()); | 1066 isolate->counters()->wasm_decode_function_time()); |
784 size_t size = function_end - function_start; | 1067 size_t size = function_end - function_start; |
785 if (function_start > function_end) return FunctionError("start > end"); | 1068 if (function_start > function_end) return FunctionError("start > end"); |
786 if (size > kMaxFunctionSize) | 1069 if (size > kMaxFunctionSize) |
787 return FunctionError("size > maximum function size"); | 1070 return FunctionError("size > maximum function size"); |
788 isolate->counters()->wasm_function_size_bytes()->AddSample( | 1071 isolate->counters()->wasm_function_size_bytes()->AddSample( |
789 static_cast<int>(size)); | 1072 static_cast<int>(size)); |
790 WasmFunction* function = new WasmFunction(); | 1073 WasmFunction* function = new WasmFunction(); |
791 ModuleDecoder decoder(zone, function_start, function_end, kWasmOrigin); | 1074 ModuleDecoder decoder(zone, function_start, function_end, kWasmOrigin); |
792 return decoder.DecodeSingleFunction(module_env, function); | 1075 return decoder.DecodeSingleFunction(module_env, function); |
793 } | 1076 } |
794 | 1077 |
795 FunctionOffsetsResult DecodeWasmFunctionOffsets(const byte* module_start, | 1078 FunctionOffsetsResult DecodeWasmFunctionOffsets( |
796 const byte* module_end) { | 1079 const byte* module_start, const byte* module_end, |
| 1080 uint32_t num_imported_functions) { |
| 1081 // Find and decode the code section. |
797 Vector<const byte> code_section = | 1082 Vector<const byte> code_section = |
798 FindSection(module_start, module_end, WasmSection::Code::FunctionBodies); | 1083 FindSection(module_start, module_end, kCodeSectionCode); |
799 Decoder decoder(code_section.start(), code_section.end()); | 1084 Decoder decoder(code_section.start(), code_section.end()); |
800 if (!code_section.start()) decoder.error("no code section"); | 1085 FunctionOffsets table; |
| 1086 if (!code_section.start()) { |
| 1087 decoder.error("no code section"); |
| 1088 return decoder.toResult(std::move(table)); |
| 1089 } |
| 1090 |
| 1091 // Reserve entries for the imported functions. |
| 1092 table.reserve(num_imported_functions); |
| 1093 for (uint32_t i = 0; i < num_imported_functions; i++) { |
| 1094 table.push_back(std::make_pair(0, 0)); |
| 1095 } |
801 | 1096 |
802 uint32_t functions_count = decoder.consume_u32v("functions count"); | 1097 uint32_t functions_count = decoder.consume_u32v("functions count"); |
803 FunctionOffsets table; | |
804 // Take care of invalid input here. | 1098 // Take care of invalid input here. |
805 if (functions_count < static_cast<unsigned>(code_section.length()) / 2) | 1099 if (functions_count < static_cast<unsigned>(code_section.length()) / 2) |
806 table.reserve(functions_count); | 1100 table.reserve(functions_count); |
807 int section_offset = static_cast<int>(code_section.start() - module_start); | 1101 int section_offset = static_cast<int>(code_section.start() - module_start); |
808 DCHECK_LE(0, section_offset); | 1102 DCHECK_LE(0, section_offset); |
809 for (uint32_t i = 0; i < functions_count && decoder.ok(); ++i) { | 1103 for (uint32_t i = 0; i < functions_count && decoder.ok(); ++i) { |
810 uint32_t size = decoder.consume_u32v("body size"); | 1104 uint32_t size = decoder.consume_u32v("body size"); |
811 int offset = static_cast<int>(section_offset + decoder.pc_offset()); | 1105 int offset = static_cast<int>(section_offset + decoder.pc_offset()); |
812 table.push_back(std::make_pair(offset, static_cast<int>(size))); | 1106 table.push_back(std::make_pair(offset, static_cast<int>(size))); |
813 DCHECK(table.back().first >= 0 && table.back().second >= 0); | 1107 DCHECK(table.back().first >= 0 && table.back().second >= 0); |
814 decoder.consume_bytes(size); | 1108 decoder.consume_bytes(size); |
815 } | 1109 } |
816 if (decoder.more()) decoder.error("unexpected additional bytes"); | 1110 if (decoder.more()) decoder.error("unexpected additional bytes"); |
817 | 1111 |
818 return decoder.toResult(std::move(table)); | 1112 return decoder.toResult(std::move(table)); |
819 } | 1113 } |
820 | 1114 |
821 } // namespace wasm | 1115 } // namespace wasm |
822 } // namespace internal | 1116 } // namespace internal |
823 } // namespace v8 | 1117 } // namespace v8 |
OLD | NEW |