module-decoder.cc 58.3 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

jfb's avatar
jfb committed
5 6 7 8
#include "src/wasm/module-decoder.h"

#include "src/base/functional.h"
#include "src/base/platform/platform.h"
9
#include "src/base/template-utils.h"
10
#include "src/counters.h"
11
#include "src/flags.h"
12
#include "src/macro-assembler.h"
13 14
#include "src/objects-inl.h"
#include "src/ostreams.h"
15 16
#include "src/v8.h"
#include "src/wasm/decoder.h"
17
#include "src/wasm/function-body-decoder-impl.h"
18
#include "src/wasm/wasm-limits.h"
19 20 21 22 23 24 25 26 27 28 29 30 31

namespace v8 {
namespace internal {
namespace wasm {

#if DEBUG
#define TRACE(...)                                    \
  do {                                                \
    if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
  } while (false)
#else
#define TRACE(...)
#endif
32 33
namespace {

34 35 36
constexpr char kNameString[] = "name";
constexpr char kExceptionString[] = "exception";
constexpr char kUnknownString[] = "<unknown>";
37 38 39 40 41 42 43

template <size_t N>
constexpr size_t num_chars(const char (&)[N]) {
  return N - 1;  // remove null character at end.
}

}  // namespace
44

45
const char* SectionName(SectionCode code) {
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
  switch (code) {
    case kUnknownSectionCode:
      return "Unknown";
    case kTypeSectionCode:
      return "Type";
    case kImportSectionCode:
      return "Import";
    case kFunctionSectionCode:
      return "Function";
    case kTableSectionCode:
      return "Table";
    case kMemorySectionCode:
      return "Memory";
    case kGlobalSectionCode:
      return "Global";
    case kExportSectionCode:
      return "Export";
    case kStartSectionCode:
      return "Start";
    case kCodeSectionCode:
      return "Code";
    case kElementSectionCode:
      return "Element";
    case kDataSectionCode:
      return "Data";
    case kNameSectionCode:
72 73
      return kNameString;
    case kExceptionSectionCode:
74 75
      if (FLAG_experimental_wasm_eh) return kExceptionString;
      return kUnknownString;
76
    default:
77
      return kUnknownString;
78 79 80
  }
}

81 82
namespace {

83
ValueType TypeOf(const WasmModule* module, const WasmInitExpr& expr) {
84 85
  switch (expr.kind) {
    case WasmInitExpr::kNone:
86
      return kWasmStmt;
87 88 89
    case WasmInitExpr::kGlobalIndex:
      return expr.val.global_index < module->globals.size()
                 ? module->globals[expr.val.global_index].type
90
                 : kWasmStmt;
91
    case WasmInitExpr::kI32Const:
92
      return kWasmI32;
93
    case WasmInitExpr::kI64Const:
94
      return kWasmI64;
95
    case WasmInitExpr::kF32Const:
96
      return kWasmF32;
97
    case WasmInitExpr::kF64Const:
98
      return kWasmF64;
99 100 101 102 103
    default:
      UNREACHABLE();
  }
}

104 105
// Reads a length-prefixed string, checking that it is within bounds. Returns
// the offset of the string, and the length as an out parameter.
106 107 108
WireBytesRef consume_string(Decoder& decoder, bool validate_utf8,
                            const char* name) {
  uint32_t length = decoder.consume_u32v("string length");
109 110 111
  uint32_t offset = decoder.pc_offset();
  const byte* string_start = decoder.pc();
  // Consume bytes before validation to guarantee that the string is not oob.
112 113
  if (length > 0) {
    decoder.consume_bytes(length, name);
114
    if (decoder.ok() && validate_utf8 &&
115
        !unibrow::Utf8::ValidateEncoding(string_start, length)) {
116
      decoder.errorf(string_start, "%s: no valid UTF-8 string", name);
117 118
    }
  }
119
  return {offset, decoder.failed() ? 0 : length};
120 121
}

122
// An iterator over the sections in a wasm binary module.
123 124 125 126 127 128 129 130 131 132 133
// Automatically skips all unknown sections.
class WasmSectionIterator {
 public:
  explicit WasmSectionIterator(Decoder& decoder)
      : decoder_(decoder),
        section_code_(kUnknownSectionCode),
        section_start_(decoder.pc()),
        section_end_(decoder.pc()) {
    next();
  }

134
  inline bool more() const { return decoder_.ok() && decoder_.more(); }
135

136
  inline SectionCode section_code() const { return section_code_; }
137 138 139 140 141 142 143

  inline const byte* section_start() const { return section_start_; }

  inline uint32_t section_length() const {
    return static_cast<uint32_t>(section_end_ - section_start_);
  }

144 145 146 147
  inline Vector<const uint8_t> payload() const {
    return {payload_start_, payload_length()};
  }

148 149 150 151 152 153
  inline const byte* payload_start() const { return payload_start_; }

  inline uint32_t payload_length() const {
    return static_cast<uint32_t>(section_end_ - payload_start_);
  }

154 155 156 157
  inline const byte* section_end() const { return section_end_; }

  // Advances to the next section, checking that decoding the current section
  // stopped at {section_end_}.
158 159 160 161 162
  void advance(bool move_to_section_end = false) {
    if (move_to_section_end && decoder_.pc() < section_end_) {
      decoder_.consume_bytes(
          static_cast<uint32_t>(section_end_ - decoder_.pc()));
    }
163 164
    if (decoder_.pc() != section_end_) {
      const char* msg = decoder_.pc() < section_end_ ? "shorter" : "longer";
165 166 167 168 169
      decoder_.errorf(decoder_.pc(),
                      "section was %s than expected size "
                      "(%u bytes expected, %zu decoded)",
                      msg, section_length(),
                      static_cast<size_t>(decoder_.pc() - section_start_));
170 171 172 173 174 175
    }
    next();
  }

 private:
  Decoder& decoder_;
176
  SectionCode section_code_;
177
  const byte* section_start_;
178
  const byte* payload_start_;
179 180 181
  const byte* section_end_;

  // Reads the section code/name at the current position and sets up
182
  // the embedder fields.
183
  void next() {
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    if (!decoder_.more()) {
      section_code_ = kUnknownSectionCode;
      return;
    }
    section_start_ = decoder_.pc();
    uint8_t section_code = decoder_.consume_u8("section code");
    // Read and check the section size.
    uint32_t section_length = decoder_.consume_u32v("section length");

    payload_start_ = decoder_.pc();
    if (decoder_.checkAvailable(section_length)) {
      // Get the limit of the section within the module.
      section_end_ = payload_start_ + section_length;
    } else {
      // The section would extend beyond the end of the module.
      section_end_ = payload_start_;
    }

    if (section_code == kUnknownSectionCode) {
      // Check for the known "name" section.
204 205
      WireBytesRef string =
          wasm::consume_string(decoder_, true, "section name");
206
      if (decoder_.failed() || decoder_.pc() > section_end_) {
207 208 209
        section_code_ = kUnknownSectionCode;
        return;
      }
210
      const byte* section_name_start =
211
          decoder_.start() + decoder_.GetBufferRelativeOffset(string.offset());
212 213 214 215
      payload_start_ = decoder_.pc();

      TRACE("  +%d  section name        : \"%.*s\"\n",
            static_cast<int>(section_name_start - decoder_.start()),
216
            string.length() < 20 ? string.length() : 20, section_name_start);
217

218
      if (string.length() == num_chars(kNameString) &&
219
          strncmp(reinterpret_cast<const char*>(section_name_start),
220
                  kNameString, num_chars(kNameString)) == 0) {
221
        section_code = kNameSectionCode;
222
      }
223
    } else if (!IsValidSectionCode(section_code)) {
224 225
      decoder_.errorf(decoder_.pc(), "unknown section code #0x%02x",
                      section_code);
226 227 228 229 230 231 232 233 234 235
      section_code = kUnknownSectionCode;
    }
    section_code_ = decoder_.failed() ? kUnknownSectionCode
                                      : static_cast<SectionCode>(section_code);

    TRACE("Section: %s\n", SectionName(section_code_));
    if (section_code_ == kUnknownSectionCode && section_end_ > decoder_.pc()) {
      // skip to the end of the unknown section.
      uint32_t remaining = static_cast<uint32_t>(section_end_ - decoder_.pc());
      decoder_.consume_bytes(remaining, "section payload");
236 237 238 239
    }
  }
};

240 241
}  // namespace

242
// The main logic for decoding the bytes of a module.
243
class ModuleDecoderImpl : public Decoder {
244
 public:
245 246 247 248 249 250
  explicit ModuleDecoderImpl(ModuleOrigin origin)
      : Decoder(nullptr, nullptr),
        origin_(FLAG_assume_asmjs_origin ? kAsmJsOrigin : origin) {}

  ModuleDecoderImpl(const byte* module_start, const byte* module_end,
                    ModuleOrigin origin)
251 252
      : Decoder(module_start, module_end),
        origin_(FLAG_assume_asmjs_origin ? kAsmJsOrigin : origin) {
253
    if (end_ < start_) {
254
      error(start_, "end is less than start");
255
      end_ = start_;
256 257 258 259
    }
  }

  virtual void onFirstError() {
260
    pc_ = end_;  // On error, terminate section decoding loop.
261 262
  }

263
  void DumpModule(const ModuleResult& result) {
jfb's avatar
jfb committed
264 265 266 267 268 269 270 271 272
    std::string path;
    if (FLAG_dump_wasm_module_path) {
      path = FLAG_dump_wasm_module_path;
      if (path.size() &&
          !base::OS::isDirectorySeparator(path[path.size() - 1])) {
        path += base::OS::DirectorySeparator();
      }
    }
    // File are named `HASH.{ok,failed}.wasm`.
273
    size_t hash = base::hash_range(start_, end_);
274 275 276
    EmbeddedVector<char, 32> buf;
    SNPrintF(buf, "%016zx.%s.wasm", hash, result.ok() ? "ok" : "failed");
    std::string name(buf.start());
jfb's avatar
jfb committed
277
    if (FILE* wasm_file = base::OS::FOpen((path + name).c_str(), "wb")) {
278 279 280 281
      if (fwrite(start_, end_ - start_, 1, wasm_file) != 1) {
        OFStream os(stderr);
        os << "Error while dumping wasm file" << std::endl;
      }
jfb's avatar
jfb committed
282 283 284 285
      fclose(wasm_file);
    }
  }

286 287
  void StartDecoding(Isolate* isolate) {
    CHECK_NULL(module_);
288
    SetCounters(isolate->counters());
289
    module_.reset(new WasmModule(
290
        base::make_unique<Zone>(isolate->allocator(), "signatures")));
291 292
    module_->initial_pages = 0;
    module_->maximum_pages = 0;
293 294 295 296 297 298 299
    module_->mem_export = false;
    module_->set_origin(origin_);
  }

  void DecodeModuleHeader(Vector<const uint8_t> bytes, uint8_t offset) {
    if (failed()) return;
    Reset(bytes, offset);
300

301 302
    const byte* pos = pc_;
    uint32_t magic_word = consume_u32("wasm magic");
303
#define BYTES(x) (x & 0xff), (x >> 8) & 0xff, (x >> 16) & 0xff, (x >> 24) & 0xff
304
    if (magic_word != kWasmMagic) {
305 306 307 308
      errorf(pos,
             "expected magic word %02x %02x %02x %02x, "
             "found %02x %02x %02x %02x",
             BYTES(kWasmMagic), BYTES(magic_word));
309 310 311
    }

    pos = pc_;
jfb's avatar
jfb committed
312 313
    {
      uint32_t magic_version = consume_u32("wasm version");
314
      if (magic_version != kWasmVersion) {
315 316 317 318
        errorf(pos,
               "expected version %02x %02x %02x %02x, "
               "found %02x %02x %02x %02x",
               BYTES(kWasmVersion), BYTES(magic_version));
jfb's avatar
jfb committed
319
      }
320
    }
321
#undef BYTES
322
  }
323

324 325 326 327
  void DecodeSection(SectionCode section_code, Vector<const uint8_t> bytes,
                     uint32_t offset, bool verify_functions = true) {
    if (failed()) return;
    Reset(bytes, offset);
328
    TRACE("Section: %s\n", SectionName(section_code));
329 330
    TRACE("Decode Section %p - %p\n", static_cast<const void*>(bytes.begin()),
          static_cast<const void*>(bytes.end()));
331 332 333

    // Check if the section is out-of-order.
    if (section_code < next_section_) {
334
      errorf(pc(), "unexpected section: %s", SectionName(section_code));
335 336
      return;
    }
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

    switch (section_code) {
      case kUnknownSectionCode:
        break;
      case kExceptionSectionCode:
        // Note: kExceptionSectionCode > kCodeSectionCode, but must appear
        // before the code section. Hence, treat it as a special case.
        if (++number_of_exception_sections > 1) {
          errorf(pc(), "Multiple exception sections not allowed");
          return;
        } else if (next_section_ >= kCodeSectionCode) {
          errorf(pc(), "Exception section must appear before the code section");
          return;
        }
        break;
      default:
        next_section_ = section_code;
        ++next_section_;
        break;
356
    }
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    switch (section_code) {
      case kUnknownSectionCode:
        break;
      case kTypeSectionCode:
        DecodeTypeSection();
        break;
      case kImportSectionCode:
        DecodeImportSection();
        break;
      case kFunctionSectionCode:
        DecodeFunctionSection();
        break;
      case kTableSectionCode:
        DecodeTableSection();
        break;
      case kMemorySectionCode:
        DecodeMemorySection();
        break;
      case kGlobalSectionCode:
        DecodeGlobalSection();
        break;
      case kExportSectionCode:
        DecodeExportSection();
        break;
      case kStartSectionCode:
        DecodeStartSection();
        break;
      case kCodeSectionCode:
        DecodeCodeSection(verify_functions);
        break;
      case kElementSectionCode:
        DecodeElementSection();
        break;
      case kDataSectionCode:
        DecodeDataSection();
        break;
      case kNameSectionCode:
        DecodeNameSection();
        break;
397
      case kExceptionSectionCode:
398 399 400 401 402
        if (FLAG_experimental_wasm_eh) {
          DecodeExceptionSection();
        } else {
          errorf(pc(), "unexpected section: %s", SectionName(section_code));
        }
403
        break;
404
      default:
405
        errorf(pc(), "unexpected section: %s", SectionName(section_code));
406 407 408 409 410
        return;
    }

    if (pc() != bytes.end()) {
      const char* msg = pc() < bytes.end() ? "shorter" : "longer";
411 412 413 414
      errorf(pc(),
             "section was %s than expected size "
             "(%zu bytes expected, %zu decoded)",
             msg, bytes.size(), static_cast<size_t>(pc() - bytes.begin()));
415 416 417 418 419 420 421 422 423 424 425
    }
  }

  void DecodeTypeSection() {
    uint32_t signatures_count = consume_count("types count", kV8MaxWasmTypes);
    module_->signatures.reserve(signatures_count);
    for (uint32_t i = 0; ok() && i < signatures_count; ++i) {
      TRACE("DecodeSignature[%d] module+%d\n", i,
            static_cast<int>(pc_ - start_));
      FunctionSig* s = consume_sig(module_->signature_zone.get());
      module_->signatures.push_back(s);
426 427
      uint32_t id = s ? module_->signature_map.FindOrInsert(s) : 0;
      module_->signature_ids.push_back(id);
428
    }
429
    module_->signature_map.Freeze();
430 431 432 433 434 435 436 437 438 439 440
  }

  void DecodeImportSection() {
    uint32_t import_table_count =
        consume_count("imports count", kV8MaxWasmImports);
    module_->import_table.reserve(import_table_count);
    for (uint32_t i = 0; ok() && i < import_table_count; ++i) {
      TRACE("DecodeImportTable[%d] module+%d\n", i,
            static_cast<int>(pc_ - start_));

      module_->import_table.push_back({
441 442
          {0, 0},             // module_name
          {0, 0},             // field_name
443 444 445 446 447
          kExternalFunction,  // kind
          0                   // index
      });
      WasmImport* import = &module_->import_table.back();
      const byte* pos = pc_;
448 449
      import->module_name = consume_string(true, "module name");
      import->field_name = consume_string(true, "field name");
450 451 452 453 454 455 456 457 458
      import->kind = static_cast<WasmExternalKind>(consume_u8("import kind"));
      switch (import->kind) {
        case kExternalFunction: {
          // ===== Imported function =======================================
          import->index = static_cast<uint32_t>(module_->functions.size());
          module_->num_imported_functions++;
          module_->functions.push_back({nullptr,        // sig
                                        import->index,  // func_index
                                        0,              // sig_index
459 460
                                        {0, 0},         // name_offset
                                        {0, 0},         // code
461 462 463 464 465 466 467 468 469 470 471 472
                                        true,           // imported
                                        false});        // exported
          WasmFunction* function = &module_->functions.back();
          function->sig_index =
              consume_sig_index(module_.get(), &function->sig);
          break;
        }
        case kExternalTable: {
          // ===== Imported table ==========================================
          if (!AddTable(module_.get())) break;
          import->index =
              static_cast<uint32_t>(module_->function_tables.size());
473
          module_->function_tables.emplace_back();
474
          WasmIndirectFunctionTable* table = &module_->function_tables.back();
475 476
          table->imported = true;
          expect_u8("element type", kWasmAnyFunctionTypeForm);
477 478 479 480
          consume_resizable_limits(
              "element count", "elements", FLAG_wasm_max_table_size,
              &table->initial_size, &table->has_maximum_size,
              FLAG_wasm_max_table_size, &table->maximum_size);
481 482 483 484 485 486 487
          break;
        }
        case kExternalMemory: {
          // ===== Imported memory =========================================
          if (!AddMemory(module_.get())) break;
          consume_resizable_limits(
              "memory", "pages", FLAG_wasm_max_mem_pages,
488
              &module_->initial_pages, &module_->has_maximum_pages,
489 490
              kSpecMaxWasmMemoryPages, &module_->maximum_pages,
              &module_->has_shared_memory);
491 492 493 494 495 496 497 498 499 500 501
          break;
        }
        case kExternalGlobal: {
          // ===== Imported global =========================================
          import->index = static_cast<uint32_t>(module_->globals.size());
          module_->globals.push_back(
              {kWasmStmt, false, WasmInitExpr(), 0, true, false});
          WasmGlobal* global = &module_->globals.back();
          global->type = consume_value_type();
          global->mutability = consume_mutability();
          if (global->mutability) {
502
            error("mutable globals cannot be imported");
503
          }
504
          break;
505
        }
506
        default:
507
          errorf(pos, "unknown import kind 0x%02x", import->kind);
508
          break;
509 510
      }
    }
511
  }
512

513 514 515
  void DecodeFunctionSection() {
    uint32_t functions_count =
        consume_count("functions count", kV8MaxWasmFunctions);
516 517 518
    (IsWasm() ? GetCounters()->wasm_functions_per_wasm_module()
              : GetCounters()->wasm_functions_per_asm_module())
        ->AddSample(static_cast<int>(functions_count));
519 520 521 522 523 524 525
    module_->functions.reserve(functions_count);
    module_->num_declared_functions = functions_count;
    for (uint32_t i = 0; ok() && i < functions_count; ++i) {
      uint32_t func_index = static_cast<uint32_t>(module_->functions.size());
      module_->functions.push_back({nullptr,     // sig
                                    func_index,  // func_index
                                    0,           // sig_index
526 527
                                    {0, 0},      // name
                                    {0, 0},      // code
528 529 530 531
                                    false,       // imported
                                    false});     // exported
      WasmFunction* function = &module_->functions.back();
      function->sig_index = consume_sig_index(module_.get(), &function->sig);
532
    }
533
  }
534

535 536 537 538 539
  void DecodeTableSection() {
    uint32_t table_count = consume_count("table count", kV8MaxWasmTables);

    for (uint32_t i = 0; ok() && i < table_count; i++) {
      if (!AddTable(module_.get())) break;
540
      module_->function_tables.emplace_back();
541 542 543
      WasmIndirectFunctionTable* table = &module_->function_tables.back();
      expect_u8("table type", kWasmAnyFunctionTypeForm);
      consume_resizable_limits("table elements", "elements",
544 545 546
                               FLAG_wasm_max_table_size, &table->initial_size,
                               &table->has_maximum_size,
                               FLAG_wasm_max_table_size, &table->maximum_size);
547
    }
548
  }
549

550 551
  void DecodeMemorySection() {
    uint32_t memory_count = consume_count("memory count", kV8MaxWasmMemories);
552

553 554
    for (uint32_t i = 0; ok() && i < memory_count; i++) {
      if (!AddMemory(module_.get())) break;
555 556 557
      consume_resizable_limits(
          "memory", "pages", FLAG_wasm_max_mem_pages, &module_->initial_pages,
          &module_->has_maximum_pages, kSpecMaxWasmMemoryPages,
558
          &module_->maximum_pages, &module_->has_shared_memory);
559
    }
560
  }
561

562 563 564 565 566 567 568 569 570 571 572
  void DecodeGlobalSection() {
    uint32_t globals_count = consume_count("globals count", kV8MaxWasmGlobals);
    uint32_t imported_globals = static_cast<uint32_t>(module_->globals.size());
    module_->globals.reserve(imported_globals + globals_count);
    for (uint32_t i = 0; ok() && i < globals_count; ++i) {
      TRACE("DecodeGlobal[%d] module+%d\n", i, static_cast<int>(pc_ - start_));
      // Add an uninitialized global and pass a pointer to it.
      module_->globals.push_back(
          {kWasmStmt, false, WasmInitExpr(), 0, false, false});
      WasmGlobal* global = &module_->globals.back();
      DecodeGlobalInModule(module_.get(), i + imported_globals, global);
573
    }
574
    if (ok()) CalculateGlobalOffsets(module_.get());
575
  }
576

577 578 579 580 581 582 583 584 585
  void DecodeExportSection() {
    uint32_t export_table_count =
        consume_count("exports count", kV8MaxWasmImports);
    module_->export_table.reserve(export_table_count);
    for (uint32_t i = 0; ok() && i < export_table_count; ++i) {
      TRACE("DecodeExportTable[%d] module+%d\n", i,
            static_cast<int>(pc_ - start_));

      module_->export_table.push_back({
586
          {0, 0},             // name
587 588 589 590 591
          kExternalFunction,  // kind
          0                   // index
      });
      WasmExport* exp = &module_->export_table.back();

592
      exp->name = consume_string(true, "field name");
593 594 595 596 597 598 599 600 601 602

      const byte* pos = pc();
      exp->kind = static_cast<WasmExternalKind>(consume_u8("export kind"));
      switch (exp->kind) {
        case kExternalFunction: {
          WasmFunction* func = nullptr;
          exp->index = consume_func_index(module_.get(), &func);
          module_->num_exported_functions++;
          if (func) func->exported = true;
          break;
603
        }
604 605 606 607 608 609 610 611 612 613 614
        case kExternalTable: {
          WasmIndirectFunctionTable* table = nullptr;
          exp->index = consume_table_index(module_.get(), &table);
          if (table) table->exported = true;
          break;
        }
        case kExternalMemory: {
          uint32_t index = consume_u32v("memory index");
          // TODO(titzer): This should become more regular
          // once we support multiple memories.
          if (!module_->has_memory || index != 0) {
615
            error("invalid memory index != 0");
616
          }
617 618 619 620 621 622 623 624
          module_->mem_export = true;
          break;
        }
        case kExternalGlobal: {
          WasmGlobal* global = nullptr;
          exp->index = consume_global_index(module_.get(), &global);
          if (global) {
            if (global->mutability) {
625
              error("mutable globals cannot be exported");
626 627
            }
            global->exported = true;
628
          }
629
          break;
630
        }
631
        default:
632
          errorf(pos, "invalid export kind 0x%02x", exp->kind);
633
          break;
634
      }
635
    }
636 637 638 639 640 641
    // Check for duplicate exports (except for asm.js).
    if (ok() && origin_ != kAsmJsOrigin && module_->export_table.size() > 1) {
      std::vector<WasmExport> sorted_exports(module_->export_table);

      auto cmp_less = [this](const WasmExport& a, const WasmExport& b) {
        // Return true if a < b.
642 643
        if (a.name.length() != b.name.length()) {
          return a.name.length() < b.name.length();
644
        }
645 646 647
        const byte* left = start() + GetBufferRelativeOffset(a.name.offset());
        const byte* right = start() + GetBufferRelativeOffset(b.name.offset());
        return memcmp(left, right, a.name.length()) < 0;
648 649 650 651 652 653 654 655
      };
      std::stable_sort(sorted_exports.begin(), sorted_exports.end(), cmp_less);

      auto it = sorted_exports.begin();
      WasmExport* last = &*it++;
      for (auto end = sorted_exports.end(); it != end; last = &*it++) {
        DCHECK(!cmp_less(*it, *last));  // Vector must be sorted.
        if (!cmp_less(*last, *it)) {
656
          const byte* pc = start() + GetBufferRelativeOffset(it->name.offset());
657
          TruncatedUserString<> name(pc, it->name.length());
658
          errorf(pc, "Duplicate export name '%.*s' for %s %d and %s %d",
659
                 name.length(), name.start(), ExternalKindName(last->kind),
660
                 last->index, ExternalKindName(it->kind), it->index);
661
          break;
662
        }
663
      }
664 665
    }
  }
666

667 668 669 670 671 672
  void DecodeStartSection() {
    WasmFunction* func;
    const byte* pos = pc_;
    module_->start_function_index = consume_func_index(module_.get(), &func);
    if (func &&
        (func->sig->parameter_count() > 0 || func->sig->return_count() > 0)) {
673
      error(pos, "invalid start function: non-zero parameter or return count");
674
    }
675
  }
676

677 678 679
  void DecodeElementSection() {
    uint32_t element_count =
        consume_count("element count", FLAG_wasm_max_table_size);
680 681 682 683

    if (element_count > 0 && module_->function_tables.size() == 0) {
      error(pc_, "The element section requires a table");
    }
684 685 686 687
    for (uint32_t i = 0; ok() && i < element_count; ++i) {
      const byte* pos = pc();
      uint32_t table_index = consume_u32v("table index");
      if (table_index != 0) {
688
        errorf(pos, "illegal table index %u != 0", table_index);
689
      }
690
      if (table_index >= module_->function_tables.size()) {
691
        errorf(pos, "out of bounds table index %u", table_index);
692 693 694 695 696
        break;
      }
      WasmInitExpr offset = consume_init_expr(module_.get(), kWasmI32);
      uint32_t num_elem =
          consume_count("number of elements", kV8MaxWasmTableEntries);
697
      module_->table_inits.emplace_back(table_index, offset);
698
      WasmTableInit* init = &module_->table_inits.back();
699
      for (uint32_t j = 0; j < num_elem; j++) {
700 701
        WasmFunction* func = nullptr;
        uint32_t index = consume_func_index(module_.get(), &func);
702 703
        DCHECK_IMPLIES(ok(), func != nullptr);
        if (!ok()) break;
704 705
        DCHECK_EQ(index, func->func_index);
        init->entries.push_back(index);
706 707
      }
    }
708
  }
709

710
  void DecodeCodeSection(bool verify_functions) {
711
    uint32_t pos = pc_offset();
712
    uint32_t functions_count = consume_u32v("functions count");
713 714
    CheckFunctionsCount(functions_count, pos);
    for (uint32_t i = 0; ok() && i < functions_count; ++i) {
715
      const byte* pos = pc();
716
      uint32_t size = consume_u32v("body size");
717 718 719 720 721
      if (size > kV8MaxWasmFunctionSize) {
        errorf(pos, "size %u > maximum function size %zu", size,
               kV8MaxWasmFunctionSize);
        return;
      }
722
      uint32_t offset = pc_offset();
723
      consume_bytes(size, "function body");
724
      if (failed()) break;
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
      DecodeFunctionBody(i, size, offset, verify_functions);
    }
  }

  bool CheckFunctionsCount(uint32_t functions_count, uint32_t offset) {
    if (functions_count != module_->num_declared_functions) {
      Reset(nullptr, nullptr, offset);
      errorf(nullptr, "function body count %u mismatch (%u expected)",
             functions_count, module_->num_declared_functions);
      return false;
    }
    return true;
  }

  void DecodeFunctionBody(uint32_t index, uint32_t length, uint32_t offset,
                          bool verify_functions) {
741 742 743 744
    auto size_histogram = module_->is_wasm()
                              ? GetCounters()->wasm_wasm_function_size_bytes()
                              : GetCounters()->wasm_asm_function_size_bytes();
    size_histogram->AddSample(length);
745 746 747 748 749 750 751 752
    WasmFunction* function =
        &module_->functions[index + module_->num_imported_functions];
    function->code = {offset, length};
    if (verify_functions) {
      ModuleWireBytes bytes(start_, end_);
      VerifyFunctionBody(module_->signature_zone->allocator(),
                         index + module_->num_imported_functions, bytes,
                         module_.get(), function);
753
    }
754
  }
755

756 757 758 759 760 761
  void DecodeDataSection() {
    uint32_t data_segments_count =
        consume_count("data segments count", kV8MaxWasmDataSegments);
    module_->data_segments.reserve(data_segments_count);
    for (uint32_t i = 0; ok() && i < data_segments_count; ++i) {
      if (!module_->has_memory) {
762
        error("cannot load data without memory");
763
        break;
764
      }
765 766 767 768
      TRACE("DecodeDataSegment[%d] module+%d\n", i,
            static_cast<int>(pc_ - start_));
      module_->data_segments.push_back({
          WasmInitExpr(),  // dest_addr
769
          {0, 0}           // source
770 771 772
      });
      WasmDataSegment* segment = &module_->data_segments.back();
      DecodeDataSegmentInModule(module_.get(), segment);
773
    }
774
  }
775

776 777 778 779 780 781 782 783
  void DecodeNameSection() {
    // TODO(titzer): find a way to report name errors as warnings.
    // Use an inner decoder so that errors don't fail the outer decoder.
    Decoder inner(start_, pc_, end_, buffer_offset_);
    // Decode all name subsections.
    // Be lenient with their order.
    while (inner.ok() && inner.more()) {
      uint8_t name_type = inner.consume_u8("name type");
784
      if (name_type & 0x80) inner.error("name type if not varuint7");
785 786 787 788 789 790

      uint32_t name_payload_len = inner.consume_u32v("name payload length");
      if (!inner.checkAvailable(name_payload_len)) break;

      // Decode function names, ignore the rest.
      // Local names will be decoded when needed.
791 792
      switch (name_type) {
        case NameSectionType::kModule: {
793 794
          WireBytesRef name = wasm::consume_string(inner, false, "module name");
          if (inner.ok() && validate_utf8(&inner, name)) module_->name = name;
795
          break;
796
        }
797 798 799 800 801
        case NameSectionType::kFunction: {
          uint32_t functions_count = inner.consume_u32v("functions count");

          for (; inner.ok() && functions_count > 0; --functions_count) {
            uint32_t function_index = inner.consume_u32v("function index");
802 803
            WireBytesRef name =
                wasm::consume_string(inner, false, "function name");
804 805 806 807 808

            // Be lenient with errors in the name section: Ignore illegal
            // or out-of-order indexes and non-UTF8 names. You can even assign
            // to the same function multiple times (last valid one wins).
            if (inner.ok() && function_index < module_->functions.size() &&
809 810
                validate_utf8(&inner, name)) {
              module_->functions[function_index].name = name;
811 812 813 814 815 816 817
            }
          }
          break;
        }
        default:
          inner.consume_bytes(name_payload_len, "name subsection payload");
          break;
818
      }
819
    }
820 821 822
    // Skip the whole names section in the outer decoder.
    consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
  }
823

824 825 826 827 828 829 830 831 832 833 834
  void DecodeExceptionSection() {
    uint32_t exception_count =
        consume_count("exception count", kV8MaxWasmExceptions);
    for (uint32_t i = 0; ok() && i < exception_count; ++i) {
      TRACE("DecodeExceptionSignature[%d] module+%d\n", i,
            static_cast<int>(pc_ - start_));
      module_->exceptions.emplace_back(
          consume_exception_sig(module_->signature_zone.get()));
    }
  }

835
  ModuleResult FinishDecoding(bool verify_functions = true) {
836
    if (ok()) {
837
      CalculateGlobalOffsets(module_.get());
838
    }
839
    ModuleResult result = toResult(std::move(module_));
840
    if (verify_functions && result.ok()) {
841 842
      // Copy error code and location.
      result.MoveErrorFrom(intermediate_result_);
843
    }
844
    if (FLAG_dump_wasm_module) DumpModule(result);
jfb's avatar
jfb committed
845
    return result;
846 847
  }

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
  // Decodes an entire module.
  ModuleResult DecodeModule(Isolate* isolate, bool verify_functions = true) {
    StartDecoding(isolate);
    uint32_t offset = 0;
    DecodeModuleHeader(Vector<const uint8_t>(start(), end() - start()), offset);
    if (failed()) {
      return FinishDecoding(verify_functions);
    }
    // Size of the module header.
    offset += 8;
    Decoder decoder(start_ + offset, end_, offset);

    WasmSectionIterator section_iter(decoder);

    while (ok() && section_iter.more()) {
      // Shift the offset by the section header length
      offset += section_iter.payload_start() - section_iter.section_start();
      if (section_iter.section_code() != SectionCode::kUnknownSectionCode) {
        DecodeSection(section_iter.section_code(), section_iter.payload(),
                      offset, verify_functions);
      }
      // Shift the offset by the remaining section payload
      offset += section_iter.payload_length();
      section_iter.advance(true);
    }

    if (decoder.failed()) {
      return decoder.toResult<std::unique_ptr<WasmModule>>(nullptr);
    }

    return FinishDecoding(verify_functions);
  }

881
  // Decodes a single anonymous function starting at {start_}.
882 883 884
  FunctionResult DecodeSingleFunction(Zone* zone,
                                      const ModuleWireBytes& wire_bytes,
                                      const WasmModule* module,
885
                                      std::unique_ptr<WasmFunction> function) {
886
    pc_ = start_;
887 888 889
    function->sig = consume_sig(zone);
    function->name = {0, 0};
    function->code = {off(pc_), static_cast<uint32_t>(end_ - pc_)};
890

891
    if (ok())
892 893
      VerifyFunctionBody(zone->allocator(), 0, wire_bytes, module,
                         function.get());
894

895
    FunctionResult result(std::move(function));
896 897
    // Copy error code and location.
    result.MoveErrorFrom(intermediate_result_);
898 899 900 901
    return result;
  }

  // Decodes a single function signature at {start}.
902
  FunctionSig* DecodeFunctionSignature(Zone* zone, const byte* start) {
903
    pc_ = start;
904
    FunctionSig* result = consume_sig(zone);
905 906 907
    return ok() ? result : nullptr;
  }

908 909
  WasmInitExpr DecodeInitExpr(const byte* start) {
    pc_ = start;
910
    return consume_init_expr(nullptr, kWasmStmt);
911 912
  }

913 914
  WasmModule* module() { return module_.get(); }

915 916 917 918 919 920 921 922 923 924 925 926
  bool IsWasm() { return origin_ == kWasmOrigin; }

  Counters* GetCounters() {
    DCHECK_NOT_NULL(counters_);
    return counters_;
  }

  void SetCounters(Counters* counters) {
    DCHECK_NULL(counters_);
    counters_ = counters;
  }

927
 private:
928
  std::unique_ptr<WasmModule> module_;
929
  Counters* counters_ = nullptr;
930 931
  // The type section is the first section in a module.
  uint8_t next_section_ = kFirstSectionInModule;
932
  uint32_t number_of_exception_sections = 0;
933 934 935
  // We store next_section_ as uint8_t instead of SectionCode so that we can
  // increment it. This static_assert should make sure that SectionCode does not
  // get bigger than uint8_t accidentially.
936
  static_assert(sizeof(ModuleDecoderImpl::next_section_) == sizeof(SectionCode),
937
                "type mismatch");
938
  Result<bool> intermediate_result_;
939
  ModuleOrigin origin_;
940

941 942 943
  uint32_t off(const byte* ptr) {
    return static_cast<uint32_t>(ptr - start_) + buffer_offset_;
  }
944

945 946
  bool AddTable(WasmModule* module) {
    if (module->function_tables.size() > 0) {
947
      error("At most one table is supported");
948 949 950 951 952 953 954
      return false;
    } else {
      return true;
    }
  }

  bool AddMemory(WasmModule* module) {
mtrofin's avatar
mtrofin committed
955
    if (module->has_memory) {
956
      error("At most one memory is supported");
957
      return false;
mtrofin's avatar
mtrofin committed
958 959
    } else {
      module->has_memory = true;
960
      return true;
mtrofin's avatar
mtrofin committed
961 962 963
    }
  }

964
  // Decodes a single global entry inside a module starting at {pc_}.
965 966 967
  void DecodeGlobalInModule(WasmModule* module, uint32_t index,
                            WasmGlobal* global) {
    global->type = consume_value_type();
968
    global->mutability = consume_mutability();
969
    const byte* pos = pc();
970
    global->init = consume_init_expr(module, kWasmStmt);
971
    switch (global->init.kind) {
972 973 974
      case WasmInitExpr::kGlobalIndex: {
        uint32_t other_index = global->init.val.global_index;
        if (other_index >= index) {
975 976 977 978
          errorf(pos,
                 "invalid global index in init expression, "
                 "index %u, other_index %u",
                 index, other_index);
979
        } else if (module->globals[other_index].type != global->type) {
980 981 982 983 984
          errorf(pos,
                 "type mismatch in global initialization "
                 "(from global #%u), expected %s, got %s",
                 other_index, WasmOpcodes::TypeName(global->type),
                 WasmOpcodes::TypeName(module->globals[other_index].type));
985 986
        }
        break;
987
      }
988 989
      default:
        if (global->type != TypeOf(module, global->init)) {
990 991 992 993
          errorf(pos,
                 "type error in global initialization, expected %s, got %s",
                 WasmOpcodes::TypeName(global->type),
                 WasmOpcodes::TypeName(TypeOf(module, global->init)));
994
        }
995
    }
996 997 998
  }

  // Decodes a single data segment entry inside a module starting at {pc_}.
999
  void DecodeDataSegmentInModule(WasmModule* module, WasmDataSegment* segment) {
1000
    expect_u8("linear memory index", 0);
1001
    segment->dest_addr = consume_init_expr(module, kWasmI32);
1002 1003
    uint32_t source_length = consume_u32v("source size");
    uint32_t source_offset = pc_offset();
1004

1005 1006
    consume_bytes(source_length, "segment data");
    if (failed()) return;
1007

1008
    segment->source = {source_offset, source_length};
1009 1010
  }

1011
  // Calculate individual global offsets and total size of globals table.
1012
  void CalculateGlobalOffsets(WasmModule* module) {
1013 1014 1015 1016 1017 1018
    uint32_t offset = 0;
    if (module->globals.size() == 0) {
      module->globals_size = 0;
      return;
    }
    for (WasmGlobal& global : module->globals) {
1019 1020
      byte size =
          WasmOpcodes::MemSize(WasmOpcodes::MachineTypeFor(global.type));
1021 1022 1023 1024 1025 1026 1027
      offset = (offset + size - 1) & ~(size - 1);  // align
      global.offset = offset;
      offset += size;
    }
    module->globals_size = offset;
  }

1028
  // Verifies the body (code) of a given function.
1029
  void VerifyFunctionBody(AccountingAllocator* allocator, uint32_t func_num,
1030 1031 1032
                          const ModuleWireBytes& wire_bytes,
                          const WasmModule* module, WasmFunction* function) {
    WasmFunctionName func_name(function, wire_bytes.GetNameOrNull(function));
1033
    if (FLAG_trace_wasm_decoder || FLAG_trace_wasm_decode_time) {
1034
      OFStream os(stdout);
1035
      os << "Verifying wasm function " << func_name << std::endl;
1036
    }
1037
    FunctionBody body = {
1038
        function->sig, function->code.offset(),
1039 1040
        start_ + GetBufferRelativeOffset(function->code.offset()),
        start_ + GetBufferRelativeOffset(function->code.end_offset())};
1041 1042
    DecodeResult result = VerifyWasmCodeWithStats(allocator, module, body,
                                                  IsWasm(), GetCounters());
1043 1044
    if (result.failed()) {
      // Wrap the error message from the function decoder.
1045 1046 1047
      std::ostringstream wrapped;
      wrapped << "in function " << func_name << ": " << result.error_msg();
      result.error(result.error_offset(), wrapped.str());
1048

1049 1050 1051 1052
      // Set error code and location, if this is the first error.
      if (intermediate_result_.ok()) {
        intermediate_result_.MoveErrorFrom(result);
      }
1053 1054 1055
    }
  }

1056 1057 1058 1059 1060 1061 1062 1063
  WireBytesRef consume_string(bool validate_utf8, const char* name) {
    return wasm::consume_string(*this, validate_utf8, name);
  }

  bool validate_utf8(Decoder* decoder, WireBytesRef string) {
    return unibrow::Utf8::ValidateEncoding(
        decoder->start() + decoder->GetBufferRelativeOffset(string.offset()),
        string.length());
1064 1065
  }

1066 1067
  uint32_t consume_sig_index(WasmModule* module, FunctionSig** sig) {
    const byte* pos = pc_;
1068
    uint32_t sig_index = consume_u32v("signature index");
1069
    if (sig_index >= module->signatures.size()) {
1070 1071
      errorf(pos, "signature index %u out of bounds (%d signatures)", sig_index,
             static_cast<int>(module->signatures.size()));
1072 1073 1074 1075 1076 1077 1078
      *sig = nullptr;
      return 0;
    }
    *sig = module->signatures[sig_index];
    return sig_index;
  }

1079 1080 1081 1082
  uint32_t consume_count(const char* name, size_t maximum) {
    const byte* p = pc_;
    uint32_t count = consume_u32v(name);
    if (count > maximum) {
1083
      errorf(p, "%s of %u exceeds internal limit of %zu", name, count, maximum);
1084 1085 1086 1087 1088
      return static_cast<uint32_t>(maximum);
    }
    return count;
  }

1089
  uint32_t consume_func_index(WasmModule* module, WasmFunction** func) {
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    return consume_index("function index", module->functions, func);
  }

  uint32_t consume_global_index(WasmModule* module, WasmGlobal** global) {
    return consume_index("global index", module->globals, global);
  }

  uint32_t consume_table_index(WasmModule* module,
                               WasmIndirectFunctionTable** table) {
    return consume_index("table index", module->function_tables, table);
  }

  template <typename T>
  uint32_t consume_index(const char* name, std::vector<T>& vector, T** ptr) {
1104
    const byte* pos = pc_;
1105 1106
    uint32_t index = consume_u32v(name);
    if (index >= vector.size()) {
1107 1108
      errorf(pos, "%s %u out of bounds (%d entr%s)", name, index,
             static_cast<int>(vector.size()), vector.size() == 1 ? "y" : "ies");
1109
      *ptr = nullptr;
1110 1111
      return 0;
    }
1112 1113 1114 1115 1116
    *ptr = &vector[index];
    return index;
  }

  void consume_resizable_limits(const char* name, const char* units,
1117 1118
                                uint32_t max_initial, uint32_t* initial,
                                bool* has_max, uint32_t max_maximum,
1119 1120
                                uint32_t* maximum,
                                bool* has_shared_memory = nullptr) {
1121
    uint8_t flags = consume_u8("resizable limits flags");
1122
    const byte* pos = pc();
1123 1124 1125 1126 1127 1128 1129

    if (FLAG_experimental_wasm_threads) {
      bool is_memory = (strcmp(name, "memory") == 0);
      if (flags & 0xfc || (!is_memory && (flags & 0xfe))) {
        errorf(pos - 1, "invalid %s limits flags", name);
      }
      if (flags == 3) {
1130
        DCHECK_NOT_NULL(has_shared_memory);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
        *has_shared_memory = true;
      } else if (flags == 2) {
        errorf(pos - 1,
               "%s limits flags should have maximum defined if shared is true",
               name);
      }
    } else {
      if (flags & 0xfe) {
        errorf(pos - 1, "invalid %s limits flags", name);
      }
1141
    }
1142

1143
    *initial = consume_u32v("initial size");
1144
    *has_max = false;
1145
    if (*initial > max_initial) {
1146 1147 1148
      errorf(pos,
             "initial %s size (%u %s) is larger than implementation limit (%u)",
             name, *initial, units, max_initial);
1149 1150
    }
    if (flags & 1) {
1151
      *has_max = true;
1152 1153
      pos = pc();
      *maximum = consume_u32v("maximum size");
1154
      if (*maximum > max_maximum) {
1155 1156 1157 1158
        errorf(
            pos,
            "maximum %s size (%u %s) is larger than implementation limit (%u)",
            name, *maximum, units, max_maximum);
1159 1160
      }
      if (*maximum < *initial) {
1161 1162
        errorf(pos, "maximum %s size (%u %s) is less than initial (%u %s)",
               name, *maximum, units, *initial, units);
1163 1164
      }
    } else {
1165
      *has_max = false;
1166
      *maximum = max_initial;
1167 1168 1169 1170 1171 1172 1173
    }
  }

  bool expect_u8(const char* name, uint8_t expected) {
    const byte* pos = pc();
    uint8_t value = consume_u8(name);
    if (value != expected) {
1174
      errorf(pos, "expected %s 0x%02x, got 0x%02x", name, expected, value);
1175 1176 1177 1178 1179
      return false;
    }
    return true;
  }

1180
  WasmInitExpr consume_init_expr(WasmModule* module, ValueType expected) {
1181 1182 1183 1184 1185 1186
    const byte* pos = pc();
    uint8_t opcode = consume_u8("opcode");
    WasmInitExpr expr;
    unsigned len = 0;
    switch (opcode) {
      case kExprGetGlobal: {
1187
        GlobalIndexOperand<Decoder::kValidate> operand(this, pc() - 1);
1188
        if (module->globals.size() <= operand.index) {
1189
          error("global index is out of bounds");
1190 1191 1192 1193 1194 1195
          expr.kind = WasmInitExpr::kNone;
          expr.val.i32_const = 0;
          break;
        }
        WasmGlobal* global = &module->globals[operand.index];
        if (global->mutability || !global->imported) {
1196 1197 1198
          error(
              "only immutable imported globals can be used in initializer "
              "expressions");
1199 1200 1201 1202
          expr.kind = WasmInitExpr::kNone;
          expr.val.i32_const = 0;
          break;
        }
1203 1204 1205 1206 1207 1208
        expr.kind = WasmInitExpr::kGlobalIndex;
        expr.val.global_index = operand.index;
        len = operand.length;
        break;
      }
      case kExprI32Const: {
1209
        ImmI32Operand<Decoder::kValidate> operand(this, pc() - 1);
1210 1211 1212 1213 1214 1215
        expr.kind = WasmInitExpr::kI32Const;
        expr.val.i32_const = operand.value;
        len = operand.length;
        break;
      }
      case kExprF32Const: {
1216
        ImmF32Operand<Decoder::kValidate> operand(this, pc() - 1);
1217 1218 1219 1220 1221 1222
        expr.kind = WasmInitExpr::kF32Const;
        expr.val.f32_const = operand.value;
        len = operand.length;
        break;
      }
      case kExprI64Const: {
1223
        ImmI64Operand<Decoder::kValidate> operand(this, pc() - 1);
1224 1225 1226 1227 1228 1229
        expr.kind = WasmInitExpr::kI64Const;
        expr.val.i64_const = operand.value;
        len = operand.length;
        break;
      }
      case kExprF64Const: {
1230
        ImmF64Operand<Decoder::kValidate> operand(this, pc() - 1);
1231 1232 1233 1234 1235 1236
        expr.kind = WasmInitExpr::kF64Const;
        expr.val.f64_const = operand.value;
        len = operand.length;
        break;
      }
      default: {
1237
        error("invalid opcode in initialization expression");
1238 1239 1240 1241 1242 1243 1244 1245
        expr.kind = WasmInitExpr::kNone;
        expr.val.i32_const = 0;
      }
    }
    consume_bytes(len, "init code");
    if (!expect_u8("end opcode", kExprEnd)) {
      expr.kind = WasmInitExpr::kNone;
    }
1246
    if (expected != kWasmStmt && TypeOf(module, expr) != kWasmI32) {
1247 1248 1249
      errorf(pos, "type error in init expression, expected %s, got %s",
             WasmOpcodes::TypeName(expected),
             WasmOpcodes::TypeName(TypeOf(module, expr)));
1250 1251
    }
    return expr;
1252 1253
  }

1254 1255 1256
  // Read a mutability flag
  bool consume_mutability() {
    byte val = consume_u8("mutability");
1257
    if (val > 1) error(pc_ - 1, "invalid mutability");
1258 1259 1260
    return val != 0;
  }

1261
  // Reads a single 8-bit integer, interpreting it as a local type.
1262
  ValueType consume_value_type() {
1263
    byte val = consume_u8("value type");
1264
    ValueTypeCode t = static_cast<ValueTypeCode>(val);
1265 1266
    switch (t) {
      case kLocalI32:
1267
        return kWasmI32;
1268
      case kLocalI64:
1269
        return kWasmI64;
1270
      case kLocalF32:
1271
        return kWasmF32;
1272
      case kLocalF64:
1273
        return kWasmF64;
1274
      default:
1275
        if (IsWasm() && FLAG_experimental_wasm_simd) {
1276 1277 1278 1279 1280 1281
          switch (t) {
            case kLocalS128:
              return kWasmS128;
            default:
              break;
          }
1282
        }
1283
        error(pc_ - 1, "invalid local type");
1284
        return kWasmStmt;
1285 1286 1287
    }
  }

1288
  FunctionSig* consume_sig(Zone* zone) {
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    constexpr bool has_return_values = true;
    return consume_sig_internal(zone, has_return_values);
  }

  WasmExceptionSig* consume_exception_sig(Zone* zone) {
    constexpr bool has_return_values = true;
    return consume_sig_internal(zone, !has_return_values);
  }

 private:
  FunctionSig* consume_sig_internal(Zone* zone, bool has_return_values) {
    if (has_return_values && !expect_u8("type form", kWasmFunctionTypeForm))
      return nullptr;
1302
    // parse parameter types
1303 1304 1305
    uint32_t param_count =
        consume_count("param count", kV8MaxWasmFunctionParams);
    if (failed()) return nullptr;
1306
    std::vector<ValueType> params;
1307
    for (uint32_t i = 0; ok() && i < param_count; ++i) {
1308
      ValueType param = consume_value_type();
1309 1310
      params.push_back(param);
    }
1311
    std::vector<ValueType> returns;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    uint32_t return_count = 0;
    if (has_return_values) {
      // parse return types
      const size_t max_return_count = FLAG_experimental_wasm_mv
                                          ? kV8MaxWasmFunctionMultiReturns
                                          : kV8MaxWasmFunctionReturns;
      return_count = consume_count("return count", max_return_count);
      if (failed()) return nullptr;
      for (uint32_t i = 0; ok() && i < return_count; ++i) {
        ValueType ret = consume_value_type();
        returns.push_back(ret);
      }
1324
    }
1325

1326
    if (failed()) return nullptr;
1327

1328
    // FunctionSig stores the return types first.
1329
    ValueType* buffer = zone->NewArray<ValueType>(param_count + return_count);
1330
    uint32_t b = 0;
ritesht's avatar
ritesht committed
1331 1332
    for (uint32_t i = 0; i < return_count; ++i) buffer[b++] = returns[i];
    for (uint32_t i = 0; i < param_count; ++i) buffer[b++] = params[i];
1333

1334
    return new (zone) FunctionSig(return_count, param_count, buffer);
1335 1336 1337
  }
};

1338 1339
ModuleResult DecodeWasmModule(Isolate* isolate, const byte* module_start,
                              const byte* module_end, bool verify_functions,
1340
                              ModuleOrigin origin, Counters* counters) {
1341 1342 1343 1344
  auto counter = origin == kWasmOrigin
                     ? counters->wasm_decode_wasm_module_time()
                     : counters->wasm_decode_asm_module_time();
  TimedHistogramScope wasm_decode_module_time_scope(counter);
1345
  size_t size = module_end - module_start;
1346
  if (module_start > module_end) return ModuleResult::Error("start > end");
1347
  if (size >= kV8MaxWasmModuleSize)
1348
    return ModuleResult::Error("size > maximum module size: %zu", size);
1349
  // TODO(bradnelson): Improve histogram handling of size_t.
1350 1351 1352 1353
  auto size_counter = origin == kWasmOrigin
                          ? counters->wasm_wasm_module_size_bytes()
                          : counters->wasm_asm_module_size_bytes();
  size_counter->AddSample(static_cast<int>(size));
1354 1355
  // Signatures are stored in zone memory, which have the same lifetime
  // as the {module}.
1356
  ModuleDecoderImpl decoder(module_start, module_end, origin);
1357
  ModuleResult result = decoder.DecodeModule(isolate, verify_functions);
1358
  // TODO(bradnelson): Improve histogram handling of size_t.
1359 1360 1361
  // TODO(titzer): this isn't accurate, since it doesn't count the data
  // allocated on the C++ heap.
  // https://bugs.chromium.org/p/chromium/issues/detail?id=657320
1362 1363 1364 1365 1366 1367
  if (result.ok()) {
    auto peak_counter =
        origin == kWasmOrigin
            ? counters->wasm_decode_wasm_module_peak_memory_bytes()
            : counters->wasm_decode_asm_module_peak_memory_bytes();
    peak_counter->AddSample(
1368
        static_cast<int>(result.val->signature_zone->allocation_size()));
1369
  }
1370
  return result;
1371 1372
}

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
ModuleDecoder::ModuleDecoder() = default;
ModuleDecoder::~ModuleDecoder() = default;

WasmModule* ModuleDecoder::module() const { return impl_->module(); }

void ModuleDecoder::StartDecoding(Isolate* isolate, ModuleOrigin origin) {
  DCHECK_NULL(impl_);
  impl_.reset(new ModuleDecoderImpl(origin));
  impl_->StartDecoding(isolate);
}

void ModuleDecoder::DecodeModuleHeader(Vector<const uint8_t> bytes,
                                       uint32_t offset) {
  impl_->DecodeModuleHeader(bytes, offset);
}

void ModuleDecoder::DecodeSection(SectionCode section_code,
                                  Vector<const uint8_t> bytes, uint32_t offset,
                                  bool verify_functions) {
  impl_->DecodeSection(section_code, bytes, offset, verify_functions);
}

void ModuleDecoder::DecodeFunctionBody(uint32_t index, uint32_t length,
                                       uint32_t offset, bool verify_functions) {
  impl_->DecodeFunctionBody(index, length, offset, verify_functions);
}

bool ModuleDecoder::CheckFunctionsCount(uint32_t functions_count,
                                        uint32_t offset) {
  return impl_->CheckFunctionsCount(functions_count, offset);
}

ModuleResult ModuleDecoder::FinishDecoding(bool verify_functions) {
  return impl_->FinishDecoding(verify_functions);
}

bool ModuleDecoder::ok() { return impl_->ok(); }
1410

1411 1412 1413 1414
ModuleResult SyncDecodeWasmModule(Isolate* isolate, const byte* module_start,
                                  const byte* module_end, bool verify_functions,
                                  ModuleOrigin origin) {
  return DecodeWasmModule(isolate, module_start, module_end, verify_functions,
1415
                          origin, isolate->counters());
1416
}
1417

1418 1419 1420 1421 1422
ModuleResult AsyncDecodeWasmModule(
    Isolate* isolate, const byte* module_start, const byte* module_end,
    bool verify_functions, ModuleOrigin origin,
    const std::shared_ptr<Counters> async_counters) {
  return DecodeWasmModule(isolate, module_start, module_end, verify_functions,
1423
                          origin, async_counters.get());
1424 1425
}

1426 1427
FunctionSig* DecodeWasmSignatureForTesting(Zone* zone, const byte* start,
                                           const byte* end) {
1428
  ModuleDecoderImpl decoder(start, end, kWasmOrigin);
1429
  return decoder.DecodeFunctionSignature(zone, start);
1430 1431
}

1432 1433
WasmInitExpr DecodeWasmInitExprForTesting(const byte* start, const byte* end) {
  AccountingAllocator allocator;
1434
  ModuleDecoderImpl decoder(start, end, kWasmOrigin);
1435 1436 1437
  return decoder.DecodeInitExpr(start);
}

1438 1439
namespace {

1440
FunctionResult DecodeWasmFunction(Isolate* isolate, Zone* zone,
1441 1442
                                  const ModuleWireBytes& wire_bytes,
                                  const WasmModule* module,
1443
                                  const byte* function_start,
1444 1445
                                  const byte* function_end,
                                  Counters* counters) {
1446
  size_t size = function_end - function_start;
1447 1448
  if (function_start > function_end)
    return FunctionResult::Error("start > end");
1449 1450 1451 1452 1453
  auto size_histogram = module->is_wasm()
                            ? counters->wasm_wasm_function_size_bytes()
                            : counters->wasm_asm_function_size_bytes();
  // TODO(bradnelson): Improve histogram handling of ptrdiff_t.
  size_histogram->AddSample(static_cast<int>(size));
1454
  if (size > kV8MaxWasmFunctionSize)
1455
    return FunctionResult::Error("size > maximum function size: %zu", size);
1456
  ModuleDecoderImpl decoder(function_start, function_end, kWasmOrigin);
1457
  decoder.SetCounters(counters);
1458
  return decoder.DecodeSingleFunction(zone, wire_bytes, module,
1459
                                      base::make_unique<WasmFunction>());
1460
}
1461

1462 1463
}  // namespace

1464
FunctionResult SyncDecodeWasmFunction(Isolate* isolate, Zone* zone,
1465 1466
                                      const ModuleWireBytes& wire_bytes,
                                      const WasmModule* module,
1467 1468
                                      const byte* function_start,
                                      const byte* function_end) {
1469
  return DecodeWasmFunction(isolate, zone, wire_bytes, module, function_start,
1470
                            function_end, isolate->counters());
1471 1472 1473
}

FunctionResult AsyncDecodeWasmFunction(
1474 1475 1476 1477
    Isolate* isolate, Zone* zone, const ModuleWireBytes& wire_bytes,
    const WasmModule* module, const byte* function_start,
    const byte* function_end, std::shared_ptr<Counters> async_counters) {
  return DecodeWasmFunction(isolate, zone, wire_bytes, module, function_start,
1478
                            function_end, async_counters.get());
1479 1480
}

1481
AsmJsOffsetsResult DecodeAsmJsOffsets(const byte* tables_start,
1482
                                      const byte* tables_end) {
1483 1484 1485 1486 1487 1488
  AsmJsOffsets table;

  Decoder decoder(tables_start, tables_end);
  uint32_t functions_count = decoder.consume_u32v("functions count");
  // Reserve space for the entries, taking care of invalid input.
  if (functions_count < static_cast<unsigned>(tables_end - tables_start)) {
1489
    table.reserve(functions_count);
1490 1491 1492 1493 1494
  }

  for (uint32_t i = 0; i < functions_count && decoder.ok(); ++i) {
    uint32_t size = decoder.consume_u32v("table size");
    if (size == 0) {
1495
      table.emplace_back();
1496 1497 1498
      continue;
    }
    if (!decoder.checkAvailable(size)) {
1499
      decoder.error("illegal asm function offset table size");
1500 1501
    }
    const byte* table_end = decoder.pc() + size;
1502 1503
    uint32_t locals_size = decoder.consume_u32v("locals size");
    int function_start_position = decoder.consume_u32v("function start pos");
1504
    int last_byte_offset = locals_size;
1505
    int last_asm_position = function_start_position;
1506
    std::vector<AsmJsOffsetEntry> func_asm_offsets;
1507
    func_asm_offsets.reserve(size / 4);  // conservative estimation
1508 1509 1510
    // Add an entry for the stack check, associated with position 0.
    func_asm_offsets.push_back(
        {0, function_start_position, function_start_position});
1511 1512
    while (decoder.ok() && decoder.pc() < table_end) {
      last_byte_offset += decoder.consume_u32v("byte offset delta");
1513 1514 1515 1516 1517 1518 1519
      int call_position =
          last_asm_position + decoder.consume_i32v("call position delta");
      int to_number_position =
          call_position + decoder.consume_i32v("to_number position delta");
      last_asm_position = to_number_position;
      func_asm_offsets.push_back(
          {last_byte_offset, call_position, to_number_position});
1520 1521
    }
    if (decoder.pc() != table_end) {
1522
      decoder.error("broken asm offset table");
1523 1524 1525
    }
    table.push_back(std::move(func_asm_offsets));
  }
1526
  if (decoder.more()) decoder.error("unexpected additional bytes");
1527 1528 1529 1530

  return decoder.toResult(std::move(table));
}

1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
std::vector<CustomSectionOffset> DecodeCustomSections(const byte* start,
                                                      const byte* end) {
  Decoder decoder(start, end);
  decoder.consume_bytes(4, "wasm magic");
  decoder.consume_bytes(4, "wasm version");

  std::vector<CustomSectionOffset> result;

  while (decoder.more()) {
    byte section_code = decoder.consume_u8("section code");
    uint32_t section_length = decoder.consume_u32v("section length");
    uint32_t section_start = decoder.pc_offset();
    if (section_code != 0) {
      // Skip known sections.
      decoder.consume_bytes(section_length, "section bytes");
      continue;
    }
    uint32_t name_length = decoder.consume_u32v("name length");
    uint32_t name_offset = decoder.pc_offset();
    decoder.consume_bytes(name_length, "section name");
    uint32_t payload_offset = decoder.pc_offset();
    uint32_t payload_length = section_length - (payload_offset - section_start);
    decoder.consume_bytes(payload_length);
1554 1555 1556
    result.push_back({{section_start, section_length},
                      {name_offset, name_length},
                      {payload_offset, payload_length}});
1557 1558 1559 1560 1561
  }

  return result;
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
void DecodeLocalNames(const byte* module_start, const byte* module_end,
                      LocalNames* result) {
  DCHECK_NOT_NULL(result);
  DCHECK(result->names.empty());

  static constexpr int kModuleHeaderSize = 8;
  Decoder decoder(module_start, module_end);
  decoder.consume_bytes(kModuleHeaderSize, "module header");

  WasmSectionIterator section_iter(decoder);

  while (decoder.ok() && section_iter.more() &&
         section_iter.section_code() != kNameSectionCode) {
    section_iter.advance(true);
  }
  if (!section_iter.more()) return;

  // Reset the decoder to not read beyond the name section end.
  decoder.Reset(section_iter.payload(), decoder.pc_offset());

  while (decoder.ok() && decoder.more()) {
    uint8_t name_type = decoder.consume_u8("name type");
    if (name_type & 0x80) break;  // no varuint7

    uint32_t name_payload_len = decoder.consume_u32v("name payload length");
    if (!decoder.checkAvailable(name_payload_len)) break;

    if (name_type != NameSectionType::kLocal) {
      decoder.consume_bytes(name_payload_len, "name subsection payload");
      continue;
    }

    uint32_t local_names_count = decoder.consume_u32v("local names count");
    for (uint32_t i = 0; i < local_names_count; ++i) {
      uint32_t func_index = decoder.consume_u32v("function index");
      if (func_index > kMaxInt) continue;
      result->names.emplace_back(static_cast<int>(func_index));
      LocalNamesPerFunction& func_names = result->names.back();
      result->max_function_index =
          std::max(result->max_function_index, func_names.function_index);
      uint32_t num_names = decoder.consume_u32v("namings count");
      for (uint32_t k = 0; k < num_names; ++k) {
        uint32_t local_index = decoder.consume_u32v("local index");
        WireBytesRef name = wasm::consume_string(decoder, true, "local name");
        if (!decoder.ok()) break;
        if (local_index > kMaxInt) continue;
        func_names.max_local_index =
            std::max(func_names.max_local_index, static_cast<int>(local_index));
        func_names.names.emplace_back(static_cast<int>(local_index), name);
      }
    }
  }
}

1616 1617
#undef TRACE

1618 1619 1620
}  // namespace wasm
}  // namespace internal
}  // namespace v8