wasm-interpreter.cc 63 KB
Newer Older
1 2 3 4 5
// Copyright 2016 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.

#include "src/wasm/wasm-interpreter.h"
6 7

#include "src/utils.h"
8 9 10
#include "src/wasm/ast-decoder.h"
#include "src/wasm/decoder.h"
#include "src/wasm/wasm-external-refs.h"
11
#include "src/wasm/wasm-limits.h"
12 13
#include "src/wasm/wasm-module.h"

14 15
#include "src/zone/accounting-allocator.h"
#include "src/zone/zone-containers.h"
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

namespace v8 {
namespace internal {
namespace wasm {

#if DEBUG
#define TRACE(...)                                        \
  do {                                                    \
    if (FLAG_trace_wasm_interpreter) PrintF(__VA_ARGS__); \
  } while (false)
#else
#define TRACE(...)
#endif

#define FOREACH_INTERNAL_OPCODE(V) V(Breakpoint, 0xFF)

#define FOREACH_SIMPLE_BINOP(V) \
  V(I32Add, uint32_t, +)        \
  V(I32Sub, uint32_t, -)        \
  V(I32Mul, uint32_t, *)        \
  V(I32And, uint32_t, &)        \
  V(I32Ior, uint32_t, |)        \
  V(I32Xor, uint32_t, ^)        \
  V(I32Eq, uint32_t, ==)        \
  V(I32Ne, uint32_t, !=)        \
  V(I32LtU, uint32_t, <)        \
  V(I32LeU, uint32_t, <=)       \
  V(I32GtU, uint32_t, >)        \
  V(I32GeU, uint32_t, >=)       \
  V(I32LtS, int32_t, <)         \
  V(I32LeS, int32_t, <=)        \
  V(I32GtS, int32_t, >)         \
  V(I32GeS, int32_t, >=)        \
  V(I64Add, uint64_t, +)        \
  V(I64Sub, uint64_t, -)        \
  V(I64Mul, uint64_t, *)        \
  V(I64And, uint64_t, &)        \
  V(I64Ior, uint64_t, |)        \
  V(I64Xor, uint64_t, ^)        \
  V(I64Eq, uint64_t, ==)        \
  V(I64Ne, uint64_t, !=)        \
  V(I64LtU, uint64_t, <)        \
  V(I64LeU, uint64_t, <=)       \
  V(I64GtU, uint64_t, >)        \
  V(I64GeU, uint64_t, >=)       \
  V(I64LtS, int64_t, <)         \
  V(I64LeS, int64_t, <=)        \
  V(I64GtS, int64_t, >)         \
  V(I64GeS, int64_t, >=)        \
  V(F32Add, float, +)           \
  V(F32Eq, float, ==)           \
  V(F32Ne, float, !=)           \
  V(F32Lt, float, <)            \
  V(F32Le, float, <=)           \
  V(F32Gt, float, >)            \
  V(F32Ge, float, >=)           \
  V(F64Add, double, +)          \
  V(F64Eq, double, ==)          \
  V(F64Ne, double, !=)          \
  V(F64Lt, double, <)           \
  V(F64Le, double, <=)          \
  V(F64Gt, double, >)           \
  V(F64Ge, double, >=)

80 81 82 83 84 85
#define FOREACH_SIMPLE_BINOP_NAN(V) \
  V(F32Mul, float, *)               \
  V(F64Mul, double, *)              \
  V(F32Div, float, /)               \
  V(F64Div, double, /)

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
#define FOREACH_OTHER_BINOP(V) \
  V(I32DivS, int32_t)          \
  V(I32DivU, uint32_t)         \
  V(I32RemS, int32_t)          \
  V(I32RemU, uint32_t)         \
  V(I32Shl, uint32_t)          \
  V(I32ShrU, uint32_t)         \
  V(I32ShrS, int32_t)          \
  V(I64DivS, int64_t)          \
  V(I64DivU, uint64_t)         \
  V(I64RemS, int64_t)          \
  V(I64RemU, uint64_t)         \
  V(I64Shl, uint64_t)          \
  V(I64ShrU, uint64_t)         \
  V(I64ShrS, int64_t)          \
  V(I32Ror, int32_t)           \
  V(I32Rol, int32_t)           \
  V(I64Ror, int64_t)           \
  V(I64Rol, int64_t)           \
105
  V(F32Sub, float)             \
106 107 108 109 110
  V(F32Min, float)             \
  V(F32Max, float)             \
  V(F32CopySign, float)        \
  V(F64Min, double)            \
  V(F64Max, double)            \
111
  V(F64Sub, double)            \
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  V(F64CopySign, double)       \
  V(I32AsmjsDivS, int32_t)     \
  V(I32AsmjsDivU, uint32_t)    \
  V(I32AsmjsRemS, int32_t)     \
  V(I32AsmjsRemU, uint32_t)

#define FOREACH_OTHER_UNOP(V)    \
  V(I32Clz, uint32_t)            \
  V(I32Ctz, uint32_t)            \
  V(I32Popcnt, uint32_t)         \
  V(I32Eqz, uint32_t)            \
  V(I64Clz, uint64_t)            \
  V(I64Ctz, uint64_t)            \
  V(I64Popcnt, uint64_t)         \
  V(I64Eqz, uint64_t)            \
  V(F32Abs, float)               \
  V(F32Neg, float)               \
  V(F32Ceil, float)              \
  V(F32Floor, float)             \
  V(F32Trunc, float)             \
  V(F32NearestInt, float)        \
  V(F64Abs, double)              \
  V(F64Neg, double)              \
  V(F64Ceil, double)             \
  V(F64Floor, double)            \
  V(F64Trunc, double)            \
  V(F64NearestInt, double)       \
  V(I32SConvertF32, float)       \
  V(I32SConvertF64, double)      \
  V(I32UConvertF32, float)       \
  V(I32UConvertF64, double)      \
  V(I32ConvertI64, int64_t)      \
  V(I64SConvertF32, float)       \
  V(I64SConvertF64, double)      \
  V(I64UConvertF32, float)       \
  V(I64UConvertF64, double)      \
  V(I64SConvertI32, int32_t)     \
  V(I64UConvertI32, uint32_t)    \
  V(F32SConvertI32, int32_t)     \
  V(F32UConvertI32, uint32_t)    \
  V(F32SConvertI64, int64_t)     \
  V(F32UConvertI64, uint64_t)    \
  V(F32ConvertF64, double)       \
  V(F32ReinterpretI32, int32_t)  \
  V(F64SConvertI32, int32_t)     \
  V(F64UConvertI32, uint32_t)    \
  V(F64SConvertI64, int64_t)     \
  V(F64UConvertI64, uint64_t)    \
  V(F64ConvertF32, float)        \
  V(F64ReinterpretI64, int64_t)  \
  V(I32ReinterpretF32, float)    \
  V(I64ReinterpretF64, double)   \
  V(I32AsmjsSConvertF32, float)  \
  V(I32AsmjsUConvertF32, float)  \
  V(I32AsmjsSConvertF64, double) \
  V(I32AsmjsUConvertF64, double)

169 170 171 172
#define FOREACH_OTHER_UNOP_NAN(V) \
  V(F32Sqrt, float)               \
  V(F64Sqrt, double)

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
static inline int32_t ExecuteI32DivS(int32_t a, int32_t b, TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  if (b == -1 && a == std::numeric_limits<int32_t>::min()) {
    *trap = kTrapDivUnrepresentable;
    return 0;
  }
  return a / b;
}

static inline uint32_t ExecuteI32DivU(uint32_t a, uint32_t b,
                                      TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  return a / b;
}

static inline int32_t ExecuteI32RemS(int32_t a, int32_t b, TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  if (b == -1) return 0;
  return a % b;
}

static inline uint32_t ExecuteI32RemU(uint32_t a, uint32_t b,
                                      TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  return a % b;
}

static inline uint32_t ExecuteI32Shl(uint32_t a, uint32_t b, TrapReason* trap) {
  return a << (b & 0x1f);
}

static inline uint32_t ExecuteI32ShrU(uint32_t a, uint32_t b,
                                      TrapReason* trap) {
  return a >> (b & 0x1f);
}

static inline int32_t ExecuteI32ShrS(int32_t a, int32_t b, TrapReason* trap) {
  return a >> (b & 0x1f);
}

static inline int64_t ExecuteI64DivS(int64_t a, int64_t b, TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  if (b == -1 && a == std::numeric_limits<int64_t>::min()) {
    *trap = kTrapDivUnrepresentable;
    return 0;
  }
  return a / b;
}

static inline uint64_t ExecuteI64DivU(uint64_t a, uint64_t b,
                                      TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  return a / b;
}

static inline int64_t ExecuteI64RemS(int64_t a, int64_t b, TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  if (b == -1) return 0;
  return a % b;
}

static inline uint64_t ExecuteI64RemU(uint64_t a, uint64_t b,
                                      TrapReason* trap) {
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  return a % b;
}

static inline uint64_t ExecuteI64Shl(uint64_t a, uint64_t b, TrapReason* trap) {
  return a << (b & 0x3f);
}

static inline uint64_t ExecuteI64ShrU(uint64_t a, uint64_t b,
                                      TrapReason* trap) {
  return a >> (b & 0x3f);
}

static inline int64_t ExecuteI64ShrS(int64_t a, int64_t b, TrapReason* trap) {
  return a >> (b & 0x3f);
}

static inline uint32_t ExecuteI32Ror(uint32_t a, uint32_t b, TrapReason* trap) {
  uint32_t shift = (b & 0x1f);
  return (a >> shift) | (a << (32 - shift));
}

static inline uint32_t ExecuteI32Rol(uint32_t a, uint32_t b, TrapReason* trap) {
  uint32_t shift = (b & 0x1f);
  return (a << shift) | (a >> (32 - shift));
}

static inline uint64_t ExecuteI64Ror(uint64_t a, uint64_t b, TrapReason* trap) {
  uint32_t shift = (b & 0x3f);
  return (a >> shift) | (a << (64 - shift));
}

static inline uint64_t ExecuteI64Rol(uint64_t a, uint64_t b, TrapReason* trap) {
  uint32_t shift = (b & 0x3f);
  return (a << shift) | (a >> (64 - shift));
}

static float quiet(float a) {
  static const uint32_t kSignalingBit = 1 << 22;
  uint32_t q = bit_cast<uint32_t>(std::numeric_limits<float>::quiet_NaN());
  if ((q & kSignalingBit) != 0) {
    // On some machines, the signaling bit set indicates it's a quiet NaN.
    return bit_cast<float>(bit_cast<uint32_t>(a) | kSignalingBit);
  } else {
    // On others, the signaling bit set indicates it's a signaling NaN.
    return bit_cast<float>(bit_cast<uint32_t>(a) & ~kSignalingBit);
  }
}

static double quiet(double a) {
  static const uint64_t kSignalingBit = 1ULL << 51;
  uint64_t q = bit_cast<uint64_t>(std::numeric_limits<double>::quiet_NaN());
  if ((q & kSignalingBit) != 0) {
    // On some machines, the signaling bit set indicates it's a quiet NaN.
    return bit_cast<double>(bit_cast<uint64_t>(a) | kSignalingBit);
  } else {
    // On others, the signaling bit set indicates it's a signaling NaN.
    return bit_cast<double>(bit_cast<uint64_t>(a) & ~kSignalingBit);
  }
}

321 322 323 324 325 326 327 328 329 330 331
static inline float ExecuteF32Sub(float a, float b, TrapReason* trap) {
  float result = a - b;
  // Some architectures (e.g. MIPS) need extra checking to preserve the payload
  // of a NaN operand.
  if (result - result != 0) {
    if (std::isnan(a)) return quiet(a);
    if (std::isnan(b)) return quiet(b);
  }
  return result;
}

332
static inline float ExecuteF32Min(float a, float b, TrapReason* trap) {
333
  return JSMin(a, b);
334 335 336
}

static inline float ExecuteF32Max(float a, float b, TrapReason* trap) {
337
  return JSMax(a, b);
338 339 340 341 342 343
}

static inline float ExecuteF32CopySign(float a, float b, TrapReason* trap) {
  return copysignf(a, b);
}

344 345 346 347 348 349 350 351 352 353 354
static inline double ExecuteF64Sub(double a, double b, TrapReason* trap) {
  double result = a - b;
  // Some architectures (e.g. MIPS) need extra checking to preserve the payload
  // of a NaN operand.
  if (result - result != 0) {
    if (std::isnan(a)) return quiet(a);
    if (std::isnan(b)) return quiet(b);
  }
  return result;
}

355
static inline double ExecuteF64Min(double a, double b, TrapReason* trap) {
356
  return JSMin(a, b);
357 358 359
}

static inline double ExecuteF64Max(double a, double b, TrapReason* trap) {
360
  return JSMax(a, b);
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
}

static inline double ExecuteF64CopySign(double a, double b, TrapReason* trap) {
  return copysign(a, b);
}

static inline int32_t ExecuteI32AsmjsDivS(int32_t a, int32_t b,
                                          TrapReason* trap) {
  if (b == 0) return 0;
  if (b == -1 && a == std::numeric_limits<int32_t>::min()) {
    return std::numeric_limits<int32_t>::min();
  }
  return a / b;
}

static inline uint32_t ExecuteI32AsmjsDivU(uint32_t a, uint32_t b,
                                           TrapReason* trap) {
  if (b == 0) return 0;
  return a / b;
}

static inline int32_t ExecuteI32AsmjsRemS(int32_t a, int32_t b,
                                          TrapReason* trap) {
  if (b == 0) return 0;
  if (b == -1) return 0;
  return a % b;
}

static inline uint32_t ExecuteI32AsmjsRemU(uint32_t a, uint32_t b,
                                           TrapReason* trap) {
  if (b == 0) return 0;
  return a % b;
}

static inline int32_t ExecuteI32AsmjsSConvertF32(float a, TrapReason* trap) {
  return DoubleToInt32(a);
}

static inline uint32_t ExecuteI32AsmjsUConvertF32(float a, TrapReason* trap) {
  return DoubleToUint32(a);
}

static inline int32_t ExecuteI32AsmjsSConvertF64(double a, TrapReason* trap) {
  return DoubleToInt32(a);
}

static inline uint32_t ExecuteI32AsmjsUConvertF64(double a, TrapReason* trap) {
  return DoubleToUint32(a);
}

static int32_t ExecuteI32Clz(uint32_t val, TrapReason* trap) {
  return base::bits::CountLeadingZeros32(val);
}

static uint32_t ExecuteI32Ctz(uint32_t val, TrapReason* trap) {
  return base::bits::CountTrailingZeros32(val);
}

static uint32_t ExecuteI32Popcnt(uint32_t val, TrapReason* trap) {
  return word32_popcnt_wrapper(&val);
}

static inline uint32_t ExecuteI32Eqz(uint32_t val, TrapReason* trap) {
  return val == 0 ? 1 : 0;
}

static int64_t ExecuteI64Clz(uint64_t val, TrapReason* trap) {
  return base::bits::CountLeadingZeros64(val);
}

static inline uint64_t ExecuteI64Ctz(uint64_t val, TrapReason* trap) {
  return base::bits::CountTrailingZeros64(val);
}

static inline int64_t ExecuteI64Popcnt(uint64_t val, TrapReason* trap) {
  return word64_popcnt_wrapper(&val);
}

static inline int32_t ExecuteI64Eqz(uint64_t val, TrapReason* trap) {
  return val == 0 ? 1 : 0;
}

static inline float ExecuteF32Abs(float a, TrapReason* trap) {
  return bit_cast<float>(bit_cast<uint32_t>(a) & 0x7fffffff);
}

static inline float ExecuteF32Neg(float a, TrapReason* trap) {
  return bit_cast<float>(bit_cast<uint32_t>(a) ^ 0x80000000);
}

static inline float ExecuteF32Ceil(float a, TrapReason* trap) {
  return ceilf(a);
}

static inline float ExecuteF32Floor(float a, TrapReason* trap) {
  return floorf(a);
}

static inline float ExecuteF32Trunc(float a, TrapReason* trap) {
  return truncf(a);
}

static inline float ExecuteF32NearestInt(float a, TrapReason* trap) {
  return nearbyintf(a);
}

static inline float ExecuteF32Sqrt(float a, TrapReason* trap) {
468 469
  float result = sqrtf(a);
  return result;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
}

static inline double ExecuteF64Abs(double a, TrapReason* trap) {
  return bit_cast<double>(bit_cast<uint64_t>(a) & 0x7fffffffffffffff);
}

static inline double ExecuteF64Neg(double a, TrapReason* trap) {
  return bit_cast<double>(bit_cast<uint64_t>(a) ^ 0x8000000000000000);
}

static inline double ExecuteF64Ceil(double a, TrapReason* trap) {
  return ceil(a);
}

static inline double ExecuteF64Floor(double a, TrapReason* trap) {
  return floor(a);
}

static inline double ExecuteF64Trunc(double a, TrapReason* trap) {
  return trunc(a);
}

static inline double ExecuteF64NearestInt(double a, TrapReason* trap) {
  return nearbyint(a);
}

static inline double ExecuteF64Sqrt(double a, TrapReason* trap) {
  return sqrt(a);
}

static int32_t ExecuteI32SConvertF32(float a, TrapReason* trap) {
501 502 503 504 505 506 507 508
  // The upper bound is (INT32_MAX + 1), which is the lowest float-representable
  // number above INT32_MAX which cannot be represented as int32.
  float upper_bound = 2147483648.0f;
  // We use INT32_MIN as a lower bound because (INT32_MIN - 1) is not
  // representable as float, and no number between (INT32_MIN - 1) and INT32_MIN
  // is.
  float lower_bound = static_cast<float>(INT32_MIN);
  if (a < upper_bound && a >= lower_bound) {
509 510 511 512 513 514 515
    return static_cast<int32_t>(a);
  }
  *trap = kTrapFloatUnrepresentable;
  return 0;
}

static int32_t ExecuteI32SConvertF64(double a, TrapReason* trap) {
516 517 518 519 520 521 522
  // The upper bound is (INT32_MAX + 1), which is the lowest double-
  // representable number above INT32_MAX which cannot be represented as int32.
  double upper_bound = 2147483648.0;
  // The lower bound is (INT32_MIN - 1), which is the greatest double-
  // representable number below INT32_MIN which cannot be represented as int32.
  double lower_bound = -2147483649.0;
  if (a < upper_bound && a > lower_bound) {
523 524 525 526 527 528 529
    return static_cast<int32_t>(a);
  }
  *trap = kTrapFloatUnrepresentable;
  return 0;
}

static uint32_t ExecuteI32UConvertF32(float a, TrapReason* trap) {
530 531 532 533 534 535
  // The upper bound is (UINT32_MAX + 1), which is the lowest
  // float-representable number above UINT32_MAX which cannot be represented as
  // uint32.
  double upper_bound = 4294967296.0f;
  double lower_bound = -1.0f;
  if (a < upper_bound && a > lower_bound) {
536 537 538 539 540 541 542
    return static_cast<uint32_t>(a);
  }
  *trap = kTrapFloatUnrepresentable;
  return 0;
}

static uint32_t ExecuteI32UConvertF64(double a, TrapReason* trap) {
543 544 545 546 547 548
  // The upper bound is (UINT32_MAX + 1), which is the lowest
  // double-representable number above UINT32_MAX which cannot be represented as
  // uint32.
  double upper_bound = 4294967296.0;
  double lower_bound = -1.0;
  if (a < upper_bound && a > lower_bound) {
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    return static_cast<uint32_t>(a);
  }
  *trap = kTrapFloatUnrepresentable;
  return 0;
}

static inline uint32_t ExecuteI32ConvertI64(int64_t a, TrapReason* trap) {
  return static_cast<uint32_t>(a & 0xFFFFFFFF);
}

static int64_t ExecuteI64SConvertF32(float a, TrapReason* trap) {
  int64_t output;
  if (!float32_to_int64_wrapper(&a, &output)) {
    *trap = kTrapFloatUnrepresentable;
  }
  return output;
}

static int64_t ExecuteI64SConvertF64(double a, TrapReason* trap) {
  int64_t output;
  if (!float64_to_int64_wrapper(&a, &output)) {
    *trap = kTrapFloatUnrepresentable;
  }
  return output;
}

static uint64_t ExecuteI64UConvertF32(float a, TrapReason* trap) {
  uint64_t output;
  if (!float32_to_uint64_wrapper(&a, &output)) {
    *trap = kTrapFloatUnrepresentable;
  }
  return output;
}

static uint64_t ExecuteI64UConvertF64(double a, TrapReason* trap) {
  uint64_t output;
  if (!float64_to_uint64_wrapper(&a, &output)) {
    *trap = kTrapFloatUnrepresentable;
  }
  return output;
}

static inline int64_t ExecuteI64SConvertI32(int32_t a, TrapReason* trap) {
  return static_cast<int64_t>(a);
}

static inline int64_t ExecuteI64UConvertI32(uint32_t a, TrapReason* trap) {
  return static_cast<uint64_t>(a);
}

static inline float ExecuteF32SConvertI32(int32_t a, TrapReason* trap) {
  return static_cast<float>(a);
}

static inline float ExecuteF32UConvertI32(uint32_t a, TrapReason* trap) {
  return static_cast<float>(a);
}

static inline float ExecuteF32SConvertI64(int64_t a, TrapReason* trap) {
  float output;
  int64_to_float32_wrapper(&a, &output);
  return output;
}

static inline float ExecuteF32UConvertI64(uint64_t a, TrapReason* trap) {
  float output;
  uint64_to_float32_wrapper(&a, &output);
  return output;
}

static inline float ExecuteF32ConvertF64(double a, TrapReason* trap) {
  return static_cast<float>(a);
}

static inline float ExecuteF32ReinterpretI32(int32_t a, TrapReason* trap) {
  return bit_cast<float>(a);
}

static inline double ExecuteF64SConvertI32(int32_t a, TrapReason* trap) {
  return static_cast<double>(a);
}

static inline double ExecuteF64UConvertI32(uint32_t a, TrapReason* trap) {
  return static_cast<double>(a);
}

static inline double ExecuteF64SConvertI64(int64_t a, TrapReason* trap) {
  double output;
  int64_to_float64_wrapper(&a, &output);
  return output;
}

static inline double ExecuteF64UConvertI64(uint64_t a, TrapReason* trap) {
  double output;
  uint64_to_float64_wrapper(&a, &output);
  return output;
}

static inline double ExecuteF64ConvertF32(float a, TrapReason* trap) {
  return static_cast<double>(a);
}

static inline double ExecuteF64ReinterpretI64(int64_t a, TrapReason* trap) {
  return bit_cast<double>(a);
}

static inline int32_t ExecuteI32ReinterpretF32(float a, TrapReason* trap) {
  return bit_cast<int32_t>(a);
}

static inline int64_t ExecuteI64ReinterpretF64(double a, TrapReason* trap) {
  return bit_cast<int64_t>(a);
}

663
static inline int32_t ExecuteGrowMemory(uint32_t delta_pages,
664
                                        WasmInstance* instance) {
665 666
  // TODO(ahaas): Move memory allocation to wasm-module.cc for better
  // encapsulation.
667
  if (delta_pages > wasm::kV8MaxWasmMemoryPages) {
668 669
    return -1;
  }
670 671 672 673 674 675 676 677 678 679 680 681 682
  uint32_t old_size = instance->mem_size;
  uint32_t new_size;
  byte* new_mem_start;
  if (instance->mem_size == 0) {
    // TODO(gdeepti): Fix bounds check to take into account size of memtype.
    new_size = delta_pages * wasm::WasmModule::kPageSize;
    new_mem_start = static_cast<byte*>(calloc(new_size, sizeof(byte)));
    if (!new_mem_start) {
      return -1;
    }
  } else {
    DCHECK_NOT_NULL(instance->mem_start);
    new_size = old_size + delta_pages * wasm::WasmModule::kPageSize;
683
    if (new_size > wasm::kV8MaxWasmMemoryPages * wasm::WasmModule::kPageSize) {
684 685 686 687 688 689 690 691 692 693 694 695 696 697
      return -1;
    }
    new_mem_start = static_cast<byte*>(realloc(instance->mem_start, new_size));
    if (!new_mem_start) {
      return -1;
    }
    // Zero initializing uninitialized memory from realloc
    memset(new_mem_start + old_size, 0, new_size - old_size);
  }
  instance->mem_start = new_mem_start;
  instance->mem_size = new_size;
  return static_cast<int32_t>(old_size / WasmModule::kPageSize);
}

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
enum InternalOpcode {
#define DECL_INTERNAL_ENUM(name, value) kInternal##name = value,
  FOREACH_INTERNAL_OPCODE(DECL_INTERNAL_ENUM)
#undef DECL_INTERNAL_ENUM
};

static const char* OpcodeName(uint32_t val) {
  switch (val) {
#define DECL_INTERNAL_CASE(name, value) \
  case kInternal##name:                 \
    return "Internal" #name;
    FOREACH_INTERNAL_OPCODE(DECL_INTERNAL_CASE)
#undef DECL_INTERNAL_CASE
  }
  return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(val));
}

static const int kRunSteps = 1000;

// A helper class to compute the control transfers for each bytecode offset.
// Control transfers allow Br, BrIf, BrTable, If, Else, and End bytecodes to
// be directly executed without the need to dynamically track blocks.
class ControlTransfers : public ZoneObject {
 public:
  ControlTransferMap map_;

724 725
  ControlTransfers(Zone* zone, AstLocalDecls* locals, const byte* start,
                   const byte* end)
726 727 728 729
      : map_(zone) {
    // Represents a control flow label.
    struct CLabel : public ZoneObject {
      const byte* target;
730
      ZoneVector<const byte*> refs;
731

732
      explicit CLabel(Zone* zone) : target(nullptr), refs(zone) {}
733 734

      // Bind this label to the given PC.
735
      void Bind(ControlTransferMap* map, const byte* start, const byte* pc) {
736 737
        DCHECK_NULL(target);
        target = pc;
738 739 740 741
        for (auto from_pc : refs) {
          auto pcdiff = static_cast<pcdiff_t>(target - from_pc);
          size_t offset = static_cast<size_t>(from_pc - start);
          (*map)[offset] = pcdiff;
742 743 744 745
        }
      }

      // Reference this label from the given location.
746 747
      void Ref(ControlTransferMap* map, const byte* start,
               const byte* from_pc) {
748
        if (target) {
749 750 751 752 753
          // Target being bound before a reference means this is a loop.
          DCHECK_EQ(kExprLoop, *target);
          auto pcdiff = static_cast<pcdiff_t>(target - from_pc);
          size_t offset = static_cast<size_t>(from_pc - start);
          (*map)[offset] = pcdiff;
754
        } else {
755
          refs.push_back(from_pc);
756 757 758 759 760 761 762 763 764 765
        }
      }
    };

    // An entry in the control stack.
    struct Control {
      const byte* pc;
      CLabel* end_label;
      CLabel* else_label;

766 767 768
      void Ref(ControlTransferMap* map, const byte* start,
               const byte* from_pc) {
        end_label->Ref(map, start, from_pc);
769 770 771 772
      }
    };

    // Compute the ControlTransfer map.
773
    // This algorithm maintains a stack of control constructs similar to the
774 775 776 777
    // AST decoder. The {control_stack} allows matching {br,br_if,br_table}
    // bytecodes with their target, as well as determining whether the current
    // bytecodes are within the true or false block of an else.
    std::vector<Control> control_stack;
778 779 780
    CLabel* func_label = new (zone) CLabel(zone);
    control_stack.push_back({start, func_label, nullptr});
    for (BytecodeIterator i(start, end, locals); i.has_next(); i.next()) {
781
      WasmOpcode opcode = i.current();
782 783
      TRACE("@%u: control %s\n", i.pc_offset(),
            WasmOpcodes::OpcodeName(opcode));
784 785
      switch (opcode) {
        case kExprBlock: {
786 787
          TRACE("control @%u: Block\n", i.pc_offset());
          CLabel* label = new (zone) CLabel(zone);
788
          control_stack.push_back({i.pc(), label, nullptr});
789 790 791
          break;
        }
        case kExprLoop: {
792 793 794 795
          TRACE("control @%u: Loop\n", i.pc_offset());
          CLabel* label = new (zone) CLabel(zone);
          control_stack.push_back({i.pc(), label, nullptr});
          label->Bind(&map_, start, i.pc());
796 797 798
          break;
        }
        case kExprIf: {
799 800 801
          TRACE("control @%u: If\n", i.pc_offset());
          CLabel* end_label = new (zone) CLabel(zone);
          CLabel* else_label = new (zone) CLabel(zone);
802
          control_stack.push_back({i.pc(), end_label, else_label});
803
          else_label->Ref(&map_, start, i.pc());
804 805 806 807
          break;
        }
        case kExprElse: {
          Control* c = &control_stack.back();
808 809
          TRACE("control @%u: Else\n", i.pc_offset());
          c->end_label->Ref(&map_, start, i.pc());
810
          DCHECK_NOT_NULL(c->else_label);
811
          c->else_label->Bind(&map_, start, i.pc() + 1);
812 813 814 815 816
          c->else_label = nullptr;
          break;
        }
        case kExprEnd: {
          Control* c = &control_stack.back();
817
          TRACE("control @%u: End\n", i.pc_offset());
818 819 820
          if (c->end_label->target) {
            // only loops have bound labels.
            DCHECK_EQ(kExprLoop, *c->pc);
821 822 823
          } else {
            if (c->else_label) c->else_label->Bind(&map_, start, i.pc());
            c->end_label->Bind(&map_, start, i.pc() + 1);
824 825 826 827 828
          }
          control_stack.pop_back();
          break;
        }
        case kExprBr: {
829
          BreakDepthOperand operand(&i, i.pc());
830 831 832
          TRACE("control @%u: Br[depth=%u]\n", i.pc_offset(), operand.depth);
          Control* c = &control_stack[control_stack.size() - operand.depth - 1];
          c->Ref(&map_, start, i.pc());
833 834 835
          break;
        }
        case kExprBrIf: {
836
          BreakDepthOperand operand(&i, i.pc());
837 838 839
          TRACE("control @%u: BrIf[depth=%u]\n", i.pc_offset(), operand.depth);
          Control* c = &control_stack[control_stack.size() - operand.depth - 1];
          c->Ref(&map_, start, i.pc());
840 841 842
          break;
        }
        case kExprBrTable: {
843
          BranchTableOperand operand(&i, i.pc());
844 845 846 847 848 849 850 851
          BranchTableIterator iterator(&i, operand);
          TRACE("control @%u: BrTable[count=%u]\n", i.pc_offset(),
                operand.table_count);
          while (iterator.has_next()) {
            uint32_t j = iterator.cur_index();
            uint32_t target = iterator.next();
            Control* c = &control_stack[control_stack.size() - target - 1];
            c->Ref(&map_, start, i.pc() + j);
852 853 854 855 856 857 858 859
          }
          break;
        }
        default: {
          break;
        }
      }
    }
860
    if (!func_label->target) func_label->Bind(&map_, start, end);
861 862
  }

863
  pcdiff_t Lookup(pc_t from) {
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    auto result = map_.find(from);
    if (result == map_.end()) {
      V8_Fatal(__FILE__, __LINE__, "no control target for pc %zu", from);
    }
    return result->second;
  }
};

// Code and metadata needed to execute a function.
struct InterpreterCode {
  const WasmFunction* function;  // wasm function
  AstLocalDecls locals;          // local declarations
  const byte* orig_start;        // start of original code
  const byte* orig_end;          // end of original code
  byte* start;                   // start of (maybe altered) code
  byte* end;                     // end of (maybe altered) code
  ControlTransfers* targets;     // helper for control flow.

  const byte* at(pc_t pc) { return start + pc; }
};

// The main storage for interpreter code. It maps {WasmFunction} to the
// metadata needed to execute each function.
class CodeMap {
 public:
  Zone* zone_;
  const WasmModule* module_;
  ZoneVector<InterpreterCode> interpreter_code_;

893
  CodeMap(const WasmModule* module, const uint8_t* module_start, Zone* zone)
894 895
      : zone_(zone), module_(module), interpreter_code_(zone) {
    if (module == nullptr) return;
ritesht's avatar
ritesht committed
896
    for (size_t i = 0; i < module->functions.size(); ++i) {
897
      const WasmFunction* function = &module->functions[i];
898 899
      const byte* code_start = module_start + function->code_start_offset;
      const byte* code_end = module_start + function->code_end_offset;
900 901 902 903 904 905 906 907
      AddFunction(function, code_start, code_end);
    }
  }

  InterpreterCode* FindCode(const WasmFunction* function) {
    if (function->func_index < interpreter_code_.size()) {
      InterpreterCode* code = &interpreter_code_[function->func_index];
      DCHECK_EQ(function, code->function);
908
      return Preprocess(code);
909 910 911 912 913 914 915 916 917
    }
    return nullptr;
  }

  InterpreterCode* GetCode(uint32_t function_index) {
    CHECK_LT(function_index, interpreter_code_.size());
    return Preprocess(&interpreter_code_[function_index]);
  }

918 919 920 921 922 923
  InterpreterCode* GetIndirectCode(uint32_t table_index, uint32_t entry_index) {
    if (table_index >= module_->function_tables.size()) return nullptr;
    const WasmIndirectFunctionTable* table =
        &module_->function_tables[table_index];
    if (entry_index >= table->values.size()) return nullptr;
    uint32_t index = table->values[entry_index];
924 925 926 927 928 929 930 931
    if (index >= interpreter_code_.size()) return nullptr;
    return GetCode(index);
  }

  InterpreterCode* Preprocess(InterpreterCode* code) {
    if (code->targets == nullptr && code->start) {
      // Compute the control targets map and the local declarations.
      CHECK(DecodeLocalDecls(code->locals, code->start, code->end));
932
      code->targets = new (zone_) ControlTransfers(
933
          zone_, &code->locals, code->orig_start, code->orig_end);
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    }
    return code;
  }

  int AddFunction(const WasmFunction* function, const byte* code_start,
                  const byte* code_end) {
    InterpreterCode code = {
        function, AstLocalDecls(zone_),          code_start,
        code_end, const_cast<byte*>(code_start), const_cast<byte*>(code_end),
        nullptr};

    DCHECK_EQ(interpreter_code_.size(), function->func_index);
    interpreter_code_.push_back(code);
    return static_cast<int>(interpreter_code_.size()) - 1;
  }

  bool SetFunctionCode(const WasmFunction* function, const byte* start,
                       const byte* end) {
    InterpreterCode* code = FindCode(function);
    if (code == nullptr) return false;
    code->targets = nullptr;
    code->orig_start = start;
    code->orig_end = end;
    code->start = const_cast<byte*>(start);
    code->end = const_cast<byte*>(end);
    Preprocess(code);
    return true;
  }
};

// Responsible for executing code directly.
class ThreadImpl : public WasmInterpreter::Thread {
 public:
967
  ThreadImpl(Zone* zone, CodeMap* codemap, WasmInstance* instance)
968 969 970 971
      : codemap_(codemap),
        instance_(instance),
        stack_(zone),
        frames_(zone),
972
        blocks_(zone),
973
        state_(WasmInterpreter::STOPPED),
974
        break_pc_(kInvalidPc),
975 976
        trap_reason_(kTrapCount),
        possible_nondeterminism_(false) {}
977 978 979 980 981 982 983 984 985 986 987 988 989

  virtual ~ThreadImpl() {}

  //==========================================================================
  // Implementation of public interface for WasmInterpreter::Thread.
  //==========================================================================

  virtual WasmInterpreter::State state() { return state_; }

  virtual void PushFrame(const WasmFunction* function, WasmVal* args) {
    InterpreterCode* code = codemap()->FindCode(function);
    CHECK_NOT_NULL(code);
    frames_.push_back({code, 0, 0, stack_.size()});
ritesht's avatar
ritesht committed
990
    for (size_t i = 0; i < function->sig->parameter_count(); ++i) {
991 992 993
      stack_.push_back(args[i]);
    }
    frames_.back().ret_pc = InitLocals(code);
994 995 996
    blocks_.push_back(
        {0, stack_.size(), frames_.size(),
         static_cast<uint32_t>(code->function->sig->return_count())});
997
    TRACE("  => PushFrame(#%u @%zu)\n", code->function->func_index,
998 999 1000 1001 1002
          frames_.back().ret_pc);
  }

  virtual WasmInterpreter::State Run() {
    do {
1003
      TRACE("  => Run()\n");
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
      if (state_ == WasmInterpreter::STOPPED ||
          state_ == WasmInterpreter::PAUSED) {
        state_ = WasmInterpreter::RUNNING;
        Execute(frames_.back().code, frames_.back().ret_pc, kRunSteps);
      }
    } while (state_ == WasmInterpreter::STOPPED);
    return state_;
  }

  virtual WasmInterpreter::State Step() {
1014 1015 1016 1017 1018 1019 1020
    TRACE("  => Step()\n");
    if (state_ == WasmInterpreter::STOPPED ||
        state_ == WasmInterpreter::PAUSED) {
      state_ = WasmInterpreter::RUNNING;
      Execute(frames_.back().code, frames_.back().ret_pc, 1);
    }
    return state_;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  }

  virtual void Pause() { UNIMPLEMENTED(); }

  virtual void Reset() {
    TRACE("----- RESET -----\n");
    stack_.clear();
    frames_.clear();
    state_ = WasmInterpreter::STOPPED;
    trap_reason_ = kTrapCount;
1031
    possible_nondeterminism_ = false;
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  }

  virtual int GetFrameCount() { return static_cast<int>(frames_.size()); }

  virtual const WasmFrame* GetFrame(int index) {
    UNIMPLEMENTED();
    return nullptr;
  }

  virtual WasmFrame* GetMutableFrame(int index) {
    UNIMPLEMENTED();
    return nullptr;
  }

1046
  virtual WasmVal GetReturnValue(int index) {
1047 1048
    if (state_ == WasmInterpreter::TRAPPED) return WasmVal(0xdeadbeef);
    CHECK_EQ(WasmInterpreter::FINISHED, state_);
1049 1050
    CHECK_LT(static_cast<size_t>(index), stack_.size());
    return stack_[index];
1051 1052
  }

1053 1054
  virtual pc_t GetBreakpointPc() { return break_pc_; }

1055 1056
  virtual bool PossibleNondeterminism() { return possible_nondeterminism_; }

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  bool Terminated() {
    return state_ == WasmInterpreter::TRAPPED ||
           state_ == WasmInterpreter::FINISHED;
  }

 private:
  // Entries on the stack of functions being evaluated.
  struct Frame {
    InterpreterCode* code;
    pc_t call_pc;
    pc_t ret_pc;
    sp_t sp;

    // Limit of parameters.
    sp_t plimit() { return sp + code->function->sig->parameter_count(); }
    // Limit of locals.
    sp_t llimit() { return plimit() + code->locals.total_local_count; }
  };

1076 1077 1078 1079 1080 1081 1082
  struct Block {
    pc_t pc;
    sp_t sp;
    size_t fp;
    unsigned arity;
  };

1083
  CodeMap* codemap_;
1084
  WasmInstance* instance_;
1085 1086
  ZoneVector<WasmVal> stack_;
  ZoneVector<Frame> frames_;
1087
  ZoneVector<Block> blocks_;
1088
  WasmInterpreter::State state_;
1089
  pc_t break_pc_;
1090
  TrapReason trap_reason_;
1091
  bool possible_nondeterminism_;
1092 1093

  CodeMap* codemap() { return codemap_; }
1094
  WasmInstance* instance() { return instance_; }
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  const WasmModule* module() { return instance_->module; }

  void DoTrap(TrapReason trap, pc_t pc) {
    state_ = WasmInterpreter::TRAPPED;
    trap_reason_ = trap;
    CommitPc(pc);
  }

  // Push a frame with arguments already on the stack.
  void PushFrame(InterpreterCode* code, pc_t call_pc, pc_t ret_pc) {
    CHECK_NOT_NULL(code);
    DCHECK(!frames_.empty());
    frames_.back().call_pc = call_pc;
    frames_.back().ret_pc = ret_pc;
    size_t arity = code->function->sig->parameter_count();
    DCHECK_GE(stack_.size(), arity);
    // The parameters will overlap the arguments already on the stack.
    frames_.push_back({code, 0, 0, stack_.size() - arity});
1113 1114 1115
    blocks_.push_back(
        {0, stack_.size(), frames_.size(),
         static_cast<uint32_t>(code->function->sig->return_count())});
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    frames_.back().ret_pc = InitLocals(code);
    TRACE("  => push func#%u @%zu\n", code->function->func_index,
          frames_.back().ret_pc);
  }

  pc_t InitLocals(InterpreterCode* code) {
    for (auto p : code->locals.local_types) {
      WasmVal val;
      switch (p.first) {
        case kAstI32:
          val = WasmVal(static_cast<int32_t>(0));
          break;
        case kAstI64:
          val = WasmVal(static_cast<int64_t>(0));
          break;
        case kAstF32:
          val = WasmVal(static_cast<float>(0));
          break;
        case kAstF64:
          val = WasmVal(static_cast<double>(0));
          break;
        default:
          UNREACHABLE();
          break;
      }
      stack_.insert(stack_.end(), p.second, val);
    }
    return code->locals.decls_encoded_size;
  }

  void CommitPc(pc_t pc) {
    if (!frames_.empty()) {
      frames_.back().ret_pc = pc;
    }
  }

  bool SkipBreakpoint(InterpreterCode* code, pc_t pc) {
1153
    if (pc == break_pc_) {
1154
      // Skip the previously hit breakpoint when resuming.
1155 1156 1157
      break_pc_ = kInvalidPc;
      return true;
    }
1158 1159 1160
    return false;
  }

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
  int LookupTarget(InterpreterCode* code, pc_t pc) {
    return static_cast<int>(code->targets->Lookup(pc));
  }

  int DoBreak(InterpreterCode* code, pc_t pc, size_t depth) {
    size_t bp = blocks_.size() - depth - 1;
    Block* target = &blocks_[bp];
    DoStackTransfer(target->sp, target->arity);
    blocks_.resize(bp);
    return LookupTarget(code, pc);
  }

  bool DoReturn(InterpreterCode** code, pc_t* pc, pc_t* limit, size_t arity) {
1174
    DCHECK_GT(frames_.size(), 0);
1175 1176 1177 1178 1179 1180
    // Pop all blocks for this frame.
    while (!blocks_.empty() && blocks_.back().fp == frames_.size()) {
      blocks_.pop_back();
    }

    sp_t dest = frames_.back().sp;
1181 1182
    frames_.pop_back();
    if (frames_.size() == 0) {
1183
      // A return from the last frame terminates the execution.
1184
      state_ = WasmInterpreter::FINISHED;
1185
      DoStackTransfer(0, arity);
1186 1187 1188 1189 1190 1191 1192 1193 1194
      TRACE("  => finish\n");
      return false;
    } else {
      // Return to caller frame.
      Frame* top = &frames_.back();
      *code = top->code;
      *pc = top->ret_pc;
      *limit = top->code->end - top->code->start;
      TRACE("  => pop func#%u @%zu\n", (*code)->function->func_index, *pc);
1195
      DoStackTransfer(dest, arity);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
      return true;
    }
  }

  void DoCall(InterpreterCode* target, pc_t* pc, pc_t ret_pc, pc_t* limit) {
    PushFrame(target, *pc, ret_pc);
    *pc = frames_.back().ret_pc;
    *limit = target->end - target->start;
  }

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  // Copies {arity} values on the top of the stack down the stack to {dest},
  // dropping the values in-between.
  void DoStackTransfer(sp_t dest, size_t arity) {
    // before: |---------------| pop_count | arity |
    //         ^ 0             ^ dest              ^ stack_.size()
    //
    // after:  |---------------| arity |
    //         ^ 0                     ^ stack_.size()
    DCHECK_LE(dest, stack_.size());
    DCHECK_LE(dest + arity, stack_.size());
    size_t pop_count = stack_.size() - dest - arity;
    for (size_t i = 0; i < arity; i++) {
      stack_[dest + i] = stack_[dest + pop_count + i];
1219
    }
1220
    stack_.resize(stack_.size() - pop_count);
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
  }

  void Execute(InterpreterCode* code, pc_t pc, int max) {
    Decoder decoder(code->start, code->end);
    pc_t limit = code->end - code->start;
    while (true) {
      if (max-- <= 0) {
        // Maximum number of instructions reached.
        state_ = WasmInterpreter::PAUSED;
        return CommitPc(pc);
      }

      if (pc >= limit) {
        // Fell off end of code; do an implicit return.
        TRACE("@%-3zu: ImplicitReturn\n", pc);
1236 1237
        if (!DoReturn(&code, &pc, &limit, code->function->sig->return_count()))
          return;
1238 1239 1240 1241
        decoder.Reset(code->start, code->end);
        continue;
      }

1242
      const char* skip = "        ";
1243 1244 1245 1246
      int len = 1;
      byte opcode = code->start[pc];
      byte orig = opcode;
      if (opcode == kInternalBreakpoint) {
1247
        orig = code->orig_start[pc];
1248 1249
        if (SkipBreakpoint(code, pc)) {
          // skip breakpoint by switching on original code.
1250
          skip = "[skip]  ";
1251 1252
        } else {
          state_ = WasmInterpreter::PAUSED;
1253 1254 1255 1256 1257
          TRACE("@%-3zu: [break] %-24s:", pc,
                WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(orig)));
          TraceValueStack();
          TRACE("\n");
          break_pc_ = pc;
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
          return CommitPc(pc);
        }
      }

      USE(skip);
      TRACE("@%-3zu: %s%-24s:", pc, skip,
            WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(orig)));
      TraceValueStack();
      TRACE("\n");

      switch (orig) {
        case kExprNop:
          break;
1271 1272 1273 1274 1275 1276
        case kExprBlock: {
          BlockTypeOperand operand(&decoder, code->at(pc));
          blocks_.push_back({pc, stack_.size(), frames_.size(), operand.arity});
          len = 1 + operand.length;
          break;
        }
1277
        case kExprLoop: {
1278 1279 1280
          BlockTypeOperand operand(&decoder, code->at(pc));
          blocks_.push_back({pc, stack_.size(), frames_.size(), 0});
          len = 1 + operand.length;
1281 1282 1283
          break;
        }
        case kExprIf: {
1284
          BlockTypeOperand operand(&decoder, code->at(pc));
1285 1286
          WasmVal cond = Pop();
          bool is_true = cond.to<uint32_t>() != 0;
1287
          blocks_.push_back({pc, stack_.size(), frames_.size(), operand.arity});
1288 1289
          if (is_true) {
            // fall through to the true block.
1290
            len = 1 + operand.length;
1291 1292
            TRACE("  true => fallthrough\n");
          } else {
1293
            len = LookupTarget(code, pc);
1294 1295 1296 1297 1298
            TRACE("  false => @%zu\n", pc + len);
          }
          break;
        }
        case kExprElse: {
1299 1300
          blocks_.pop_back();
          len = LookupTarget(code, pc);
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
          TRACE("  end => @%zu\n", pc + len);
          break;
        }
        case kExprSelect: {
          WasmVal cond = Pop();
          WasmVal fval = Pop();
          WasmVal tval = Pop();
          Push(pc, cond.to<int32_t>() != 0 ? tval : fval);
          break;
        }
        case kExprBr: {
          BreakDepthOperand operand(&decoder, code->at(pc));
1313
          len = DoBreak(code, pc, operand.depth);
1314 1315 1316 1317 1318 1319 1320 1321
          TRACE("  br => @%zu\n", pc + len);
          break;
        }
        case kExprBrIf: {
          BreakDepthOperand operand(&decoder, code->at(pc));
          WasmVal cond = Pop();
          bool is_true = cond.to<uint32_t>() != 0;
          if (is_true) {
1322
            len = DoBreak(code, pc, operand.depth);
1323 1324 1325 1326 1327 1328 1329 1330 1331
            TRACE("  br_if => @%zu\n", pc + len);
          } else {
            TRACE("  false => fallthrough\n");
            len = 1 + operand.length;
          }
          break;
        }
        case kExprBrTable: {
          BranchTableOperand operand(&decoder, code->at(pc));
1332
          BranchTableIterator iterator(&decoder, operand);
1333
          uint32_t key = Pop().to<uint32_t>();
1334
          uint32_t depth = 0;
1335
          if (key >= operand.table_count) key = operand.table_count;
1336 1337 1338 1339 1340
          for (uint32_t i = 0; i <= key; i++) {
            DCHECK(iterator.has_next());
            depth = iterator.next();
          }
          len = key + DoBreak(code, pc + key, static_cast<size_t>(depth));
1341
          TRACE("  br[%u] => @%zu\n", key, pc + key + len);
1342 1343 1344
          break;
        }
        case kExprReturn: {
1345 1346
          size_t arity = code->function->sig->return_count();
          if (!DoReturn(&code, &pc, &limit, arity)) return;
1347 1348 1349 1350 1351 1352 1353 1354
          decoder.Reset(code->start, code->end);
          continue;
        }
        case kExprUnreachable: {
          DoTrap(kTrapUnreachable, pc);
          return CommitPc(pc);
        }
        case kExprEnd: {
1355
          blocks_.pop_back();
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
          break;
        }
        case kExprI8Const: {
          ImmI8Operand operand(&decoder, code->at(pc));
          Push(pc, WasmVal(operand.value));
          len = 1 + operand.length;
          break;
        }
        case kExprI32Const: {
          ImmI32Operand operand(&decoder, code->at(pc));
          Push(pc, WasmVal(operand.value));
          len = 1 + operand.length;
          break;
        }
        case kExprI64Const: {
          ImmI64Operand operand(&decoder, code->at(pc));
          Push(pc, WasmVal(operand.value));
          len = 1 + operand.length;
          break;
        }
        case kExprF32Const: {
          ImmF32Operand operand(&decoder, code->at(pc));
          Push(pc, WasmVal(operand.value));
          len = 1 + operand.length;
          break;
        }
        case kExprF64Const: {
          ImmF64Operand operand(&decoder, code->at(pc));
          Push(pc, WasmVal(operand.value));
          len = 1 + operand.length;
          break;
        }
        case kExprGetLocal: {
          LocalIndexOperand operand(&decoder, code->at(pc));
          Push(pc, stack_[frames_.back().sp + operand.index]);
          len = 1 + operand.length;
          break;
        }
        case kExprSetLocal: {
1395 1396 1397 1398 1399 1400 1401
          LocalIndexOperand operand(&decoder, code->at(pc));
          WasmVal val = Pop();
          stack_[frames_.back().sp + operand.index] = val;
          len = 1 + operand.length;
          break;
        }
        case kExprTeeLocal: {
1402 1403 1404 1405 1406 1407 1408
          LocalIndexOperand operand(&decoder, code->at(pc));
          WasmVal val = Pop();
          stack_[frames_.back().sp + operand.index] = val;
          Push(pc, val);
          len = 1 + operand.length;
          break;
        }
1409 1410 1411 1412
        case kExprDrop: {
          Pop();
          break;
        }
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
        case kExprCallFunction: {
          CallFunctionOperand operand(&decoder, code->at(pc));
          InterpreterCode* target = codemap()->GetCode(operand.index);
          DoCall(target, &pc, pc + 1 + operand.length, &limit);
          code = target;
          decoder.Reset(code->start, code->end);
          continue;
        }
        case kExprCallIndirect: {
          CallIndirectOperand operand(&decoder, code->at(pc));
1423
          uint32_t entry_index = Pop().to<uint32_t>();
1424 1425 1426 1427
          // Assume only one table for now.
          DCHECK_LE(module()->function_tables.size(), 1u);
          InterpreterCode* target = codemap()->GetIndirectCode(0, entry_index);
          if (target == nullptr) {
1428
            return DoTrap(kTrapFuncInvalid, pc);
1429
          } else if (target->function->sig_index != operand.index) {
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
            // If not an exact match, we have to do a canonical check.
            // TODO(titzer): make this faster with some kind of caching?
            const WasmIndirectFunctionTable* table =
                &module()->function_tables[0];
            int function_key = table->map.Find(target->function->sig);
            if (function_key < 0 ||
                (function_key !=
                 table->map.Find(module()->signatures[operand.index]))) {
              return DoTrap(kTrapFuncSigMismatch, pc);
            }
1440 1441 1442 1443 1444 1445 1446
          }

          DoCall(target, &pc, pc + 1 + operand.length, &limit);
          code = target;
          decoder.Reset(code->start, code->end);
          continue;
        }
1447
        case kExprGetGlobal: {
1448 1449 1450
          GlobalIndexOperand operand(&decoder, code->at(pc));
          const WasmGlobal* global = &module()->globals[operand.index];
          byte* ptr = instance()->globals_start + global->offset;
1451
          LocalType type = global->type;
1452
          WasmVal val;
1453
          if (type == kAstI32) {
1454
            val = WasmVal(*reinterpret_cast<int32_t*>(ptr));
1455
          } else if (type == kAstI64) {
1456
            val = WasmVal(*reinterpret_cast<int64_t*>(ptr));
1457
          } else if (type == kAstF32) {
1458
            val = WasmVal(*reinterpret_cast<float*>(ptr));
1459
          } else if (type == kAstF64) {
1460 1461 1462 1463 1464 1465 1466 1467
            val = WasmVal(*reinterpret_cast<double*>(ptr));
          } else {
            UNREACHABLE();
          }
          Push(pc, val);
          len = 1 + operand.length;
          break;
        }
1468
        case kExprSetGlobal: {
1469 1470 1471
          GlobalIndexOperand operand(&decoder, code->at(pc));
          const WasmGlobal* global = &module()->globals[operand.index];
          byte* ptr = instance()->globals_start + global->offset;
1472
          LocalType type = global->type;
1473
          WasmVal val = Pop();
1474
          if (type == kAstI32) {
1475
            *reinterpret_cast<int32_t*>(ptr) = val.to<int32_t>();
1476
          } else if (type == kAstI64) {
1477
            *reinterpret_cast<int64_t*>(ptr) = val.to<int64_t>();
1478
          } else if (type == kAstF32) {
1479
            *reinterpret_cast<float*>(ptr) = val.to<float>();
1480
          } else if (type == kAstF64) {
1481 1482 1483 1484 1485 1486 1487 1488
            *reinterpret_cast<double*>(ptr) = val.to<double>();
          } else {
            UNREACHABLE();
          }
          len = 1 + operand.length;
          break;
        }

1489 1490
#define LOAD_CASE(name, ctype, mtype)                                       \
  case kExpr##name: {                                                       \
1491
    MemoryAccessOperand operand(&decoder, code->at(pc), sizeof(ctype));     \
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    uint32_t index = Pop().to<uint32_t>();                                  \
    size_t effective_mem_size = instance()->mem_size - sizeof(mtype);       \
    if (operand.offset > effective_mem_size ||                              \
        index > (effective_mem_size - operand.offset)) {                    \
      return DoTrap(kTrapMemOutOfBounds, pc);                               \
    }                                                                       \
    byte* addr = instance()->mem_start + operand.offset + index;            \
    WasmVal result(static_cast<ctype>(ReadLittleEndianValue<mtype>(addr))); \
    Push(pc, result);                                                       \
    len = 1 + operand.length;                                               \
    break;                                                                  \
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  }

          LOAD_CASE(I32LoadMem8S, int32_t, int8_t);
          LOAD_CASE(I32LoadMem8U, int32_t, uint8_t);
          LOAD_CASE(I32LoadMem16S, int32_t, int16_t);
          LOAD_CASE(I32LoadMem16U, int32_t, uint16_t);
          LOAD_CASE(I64LoadMem8S, int64_t, int8_t);
          LOAD_CASE(I64LoadMem8U, int64_t, uint8_t);
          LOAD_CASE(I64LoadMem16S, int64_t, int16_t);
          LOAD_CASE(I64LoadMem16U, int64_t, uint16_t);
          LOAD_CASE(I64LoadMem32S, int64_t, int32_t);
          LOAD_CASE(I64LoadMem32U, int64_t, uint32_t);
          LOAD_CASE(I32LoadMem, int32_t, int32_t);
          LOAD_CASE(I64LoadMem, int64_t, int64_t);
          LOAD_CASE(F32LoadMem, float, float);
          LOAD_CASE(F64LoadMem, double, double);
#undef LOAD_CASE

1521 1522
#define STORE_CASE(name, ctype, mtype)                                        \
  case kExpr##name: {                                                         \
1523
    MemoryAccessOperand operand(&decoder, code->at(pc), sizeof(ctype));       \
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
    WasmVal val = Pop();                                                      \
    uint32_t index = Pop().to<uint32_t>();                                    \
    size_t effective_mem_size = instance()->mem_size - sizeof(mtype);         \
    if (operand.offset > effective_mem_size ||                                \
        index > (effective_mem_size - operand.offset)) {                      \
      return DoTrap(kTrapMemOutOfBounds, pc);                                 \
    }                                                                         \
    byte* addr = instance()->mem_start + operand.offset + index;              \
    WriteLittleEndianValue<mtype>(addr, static_cast<mtype>(val.to<ctype>())); \
    len = 1 + operand.length;                                                 \
    break;                                                                    \
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 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
  }

          STORE_CASE(I32StoreMem8, int32_t, int8_t);
          STORE_CASE(I32StoreMem16, int32_t, int16_t);
          STORE_CASE(I64StoreMem8, int64_t, int8_t);
          STORE_CASE(I64StoreMem16, int64_t, int16_t);
          STORE_CASE(I64StoreMem32, int64_t, int32_t);
          STORE_CASE(I32StoreMem, int32_t, int32_t);
          STORE_CASE(I64StoreMem, int64_t, int64_t);
          STORE_CASE(F32StoreMem, float, float);
          STORE_CASE(F64StoreMem, double, double);
#undef STORE_CASE

#define ASMJS_LOAD_CASE(name, ctype, mtype, defval)                 \
  case kExpr##name: {                                               \
    uint32_t index = Pop().to<uint32_t>();                          \
    ctype result;                                                   \
    if (index >= (instance()->mem_size - sizeof(mtype))) {          \
      result = defval;                                              \
    } else {                                                        \
      byte* addr = instance()->mem_start + index;                   \
      /* TODO(titzer): alignment for asmjs load mem? */             \
      result = static_cast<ctype>(*reinterpret_cast<mtype*>(addr)); \
    }                                                               \
    Push(pc, WasmVal(result));                                      \
    break;                                                          \
  }
          ASMJS_LOAD_CASE(I32AsmjsLoadMem8S, int32_t, int8_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem8U, int32_t, uint8_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem16S, int32_t, int16_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem16U, int32_t, uint16_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem, int32_t, int32_t, 0);
          ASMJS_LOAD_CASE(F32AsmjsLoadMem, float, float,
                          std::numeric_limits<float>::quiet_NaN());
          ASMJS_LOAD_CASE(F64AsmjsLoadMem, double, double,
                          std::numeric_limits<double>::quiet_NaN());
#undef ASMJS_LOAD_CASE

#define ASMJS_STORE_CASE(name, ctype, mtype)                                   \
  case kExpr##name: {                                                          \
    WasmVal val = Pop();                                                       \
    uint32_t index = Pop().to<uint32_t>();                                     \
    if (index < (instance()->mem_size - sizeof(mtype))) {                      \
      byte* addr = instance()->mem_start + index;                              \
      /* TODO(titzer): alignment for asmjs store mem? */                       \
      *(reinterpret_cast<mtype*>(addr)) = static_cast<mtype>(val.to<ctype>()); \
    }                                                                          \
    Push(pc, val);                                                             \
    break;                                                                     \
  }

          ASMJS_STORE_CASE(I32AsmjsStoreMem8, int32_t, int8_t);
          ASMJS_STORE_CASE(I32AsmjsStoreMem16, int32_t, int16_t);
          ASMJS_STORE_CASE(I32AsmjsStoreMem, int32_t, int32_t);
          ASMJS_STORE_CASE(F32AsmjsStoreMem, float, float);
          ASMJS_STORE_CASE(F64AsmjsStoreMem, double, double);
#undef ASMJS_STORE_CASE
1592
        case kExprGrowMemory: {
1593
          MemoryIndexOperand operand(&decoder, code->at(pc));
1594 1595
          uint32_t delta_pages = Pop().to<uint32_t>();
          Push(pc, WasmVal(ExecuteGrowMemory(delta_pages, instance())));
1596
          len = 1 + operand.length;
1597 1598
          break;
        }
1599
        case kExprMemorySize: {
1600
          MemoryIndexOperand operand(&decoder, code->at(pc));
1601 1602
          Push(pc, WasmVal(static_cast<uint32_t>(instance()->mem_size /
                                                 WasmModule::kPageSize)));
1603
          len = 1 + operand.length;
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
          break;
        }
#define EXECUTE_SIMPLE_BINOP(name, ctype, op)             \
  case kExpr##name: {                                     \
    WasmVal rval = Pop();                                 \
    WasmVal lval = Pop();                                 \
    WasmVal result(lval.to<ctype>() op rval.to<ctype>()); \
    Push(pc, result);                                     \
    break;                                                \
  }
          FOREACH_SIMPLE_BINOP(EXECUTE_SIMPLE_BINOP)
#undef EXECUTE_SIMPLE_BINOP

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
#define EXECUTE_SIMPLE_BINOP_NAN(name, ctype, op)        \
  case kExpr##name: {                                    \
    WasmVal rval = Pop();                                \
    WasmVal lval = Pop();                                \
    ctype result = lval.to<ctype>() op rval.to<ctype>(); \
    possible_nondeterminism_ |= std::isnan(result);      \
    WasmVal result_val(result);                          \
    Push(pc, result_val);                                \
    break;                                               \
  }
          FOREACH_SIMPLE_BINOP_NAN(EXECUTE_SIMPLE_BINOP_NAN)
#undef EXECUTE_SIMPLE_BINOP_NAN

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
#define EXECUTE_OTHER_BINOP(name, ctype)              \
  case kExpr##name: {                                 \
    TrapReason trap = kTrapCount;                     \
    volatile ctype rval = Pop().to<ctype>();          \
    volatile ctype lval = Pop().to<ctype>();          \
    WasmVal result(Execute##name(lval, rval, &trap)); \
    if (trap != kTrapCount) return DoTrap(trap, pc);  \
    Push(pc, result);                                 \
    break;                                            \
  }
          FOREACH_OTHER_BINOP(EXECUTE_OTHER_BINOP)
#undef EXECUTE_OTHER_BINOP

#define EXECUTE_OTHER_UNOP(name, ctype)              \
  case kExpr##name: {                                \
    TrapReason trap = kTrapCount;                    \
    volatile ctype val = Pop().to<ctype>();          \
    WasmVal result(Execute##name(val, &trap));       \
    if (trap != kTrapCount) return DoTrap(trap, pc); \
    Push(pc, result);                                \
    break;                                           \
  }
          FOREACH_OTHER_UNOP(EXECUTE_OTHER_UNOP)
#undef EXECUTE_OTHER_UNOP

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
#define EXECUTE_OTHER_UNOP_NAN(name, ctype)          \
  case kExpr##name: {                                \
    TrapReason trap = kTrapCount;                    \
    volatile ctype val = Pop().to<ctype>();          \
    ctype result = Execute##name(val, &trap);        \
    possible_nondeterminism_ |= std::isnan(result);  \
    WasmVal result_val(result);                      \
    if (trap != kTrapCount) return DoTrap(trap, pc); \
    Push(pc, result_val);                            \
    break;                                           \
  }
          FOREACH_OTHER_UNOP_NAN(EXECUTE_OTHER_UNOP_NAN)
#undef EXECUTE_OTHER_UNOP_NAN

1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
        default:
          V8_Fatal(__FILE__, __LINE__, "Unknown or unimplemented opcode #%d:%s",
                   code->start[pc], OpcodeName(code->start[pc]));
          UNREACHABLE();
      }

      pc += len;
    }
    UNREACHABLE();  // above decoding loop should run forever.
  }

  WasmVal Pop() {
1681 1682
    DCHECK_GT(stack_.size(), 0);
    DCHECK_GT(frames_.size(), 0);
1683 1684 1685 1686 1687 1688 1689
    DCHECK_GT(stack_.size(), frames_.back().llimit());  // can't pop into locals
    WasmVal val = stack_.back();
    stack_.pop_back();
    return val;
  }

  void PopN(int n) {
1690 1691
    DCHECK_GE(stack_.size(), n);
    DCHECK_GT(frames_.size(), 0);
1692 1693 1694 1695 1696 1697 1698
    size_t nsize = stack_.size() - n;
    DCHECK_GE(nsize, frames_.back().llimit());  // can't pop into locals
    stack_.resize(nsize);
  }

  WasmVal PopArity(size_t arity) {
    if (arity == 0) return WasmVal();
1699
    CHECK_EQ(1, arity);
1700 1701 1702 1703 1704
    return Pop();
  }

  void Push(pc_t pc, WasmVal val) {
    // TODO(titzer): store PC as well?
1705
    if (val.type != kAstStmt) stack_.push_back(val);
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  }

  void TraceStack(const char* phase, pc_t pc) {
    if (FLAG_trace_wasm_interpreter) {
      PrintF("%s @%zu", phase, pc);
      UNIMPLEMENTED();
      PrintF("\n");
    }
  }

  void TraceValueStack() {
    Frame* top = frames_.size() > 0 ? &frames_.back() : nullptr;
    sp_t sp = top ? top->sp : 0;
    sp_t plimit = top ? top->plimit() : 0;
    sp_t llimit = top ? top->llimit() : 0;
    if (FLAG_trace_wasm_interpreter) {
ritesht's avatar
ritesht committed
1722
      for (size_t i = sp; i < stack_.size(); ++i) {
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
        if (i < plimit)
          PrintF(" p%zu:", i);
        else if (i < llimit)
          PrintF(" l%zu:", i);
        else
          PrintF(" s%zu:", i);
        WasmVal val = stack_[i];
        switch (val.type) {
          case kAstI32:
            PrintF("i32:%d", val.to<int32_t>());
            break;
          case kAstI64:
            PrintF("i64:%" PRId64 "", val.to<int64_t>());
            break;
          case kAstF32:
            PrintF("f32:%f", val.to<float>());
            break;
          case kAstF64:
            PrintF("f64:%lf", val.to<double>());
            break;
          case kAstStmt:
            PrintF("void");
            break;
          default:
            UNREACHABLE();
            break;
        }
      }
    }
  }
};

//============================================================================
// The implementation details of the interpreter.
//============================================================================
class WasmInterpreterInternals : public ZoneObject {
 public:
1760
  WasmInstance* instance_;
1761 1762 1763
  // Create a copy of the module bytes for the interpreter, since the passed
  // pointer might be invalidated after constructing the interpreter.
  const ZoneVector<uint8_t> module_bytes_;
1764
  CodeMap codemap_;
1765
  ZoneVector<ThreadImpl*> threads_;
1766

1767 1768 1769 1770 1771
  WasmInterpreterInternals(Zone* zone, const ModuleBytesEnv& env)
      : instance_(env.instance),
        module_bytes_(env.module_bytes.start(), env.module_bytes.end(), zone),
        codemap_(env.instance ? env.instance->module : nullptr,
                 module_bytes_.data(), zone),
1772
        threads_(zone) {
1773
    threads_.push_back(new ThreadImpl(zone, &codemap_, env.instance));
1774 1775 1776 1777 1778 1779
  }

  void Delete() {
    // TODO(titzer): CFI doesn't like threads in the ZoneVector.
    for (auto t : threads_) delete t;
    threads_.resize(0);
1780 1781 1782 1783 1784 1785
  }
};

//============================================================================
// Implementation of the public interface of the interpreter.
//============================================================================
1786
WasmInterpreter::WasmInterpreter(const ModuleBytesEnv& env,
1787
                                 AccountingAllocator* allocator)
1788
    : zone_(allocator, ZONE_NAME),
1789
      internals_(new (&zone_) WasmInterpreterInternals(&zone_, env)) {}
1790

1791
WasmInterpreter::~WasmInterpreter() { internals_->Delete(); }
1792

1793
void WasmInterpreter::Run() { internals_->threads_[0]->Run(); }
1794

1795
void WasmInterpreter::Pause() { internals_->threads_[0]->Pause(); }
1796

1797
bool WasmInterpreter::SetBreakpoint(const WasmFunction* function, pc_t pc,
1798 1799 1800
                                    bool enabled) {
  InterpreterCode* code = internals_->codemap_.FindCode(function);
  if (!code) return false;
1801
  size_t size = static_cast<size_t>(code->end - code->start);
1802
  // Check bounds for {pc}.
1803
  if (pc < code->locals.decls_encoded_size || pc >= size) return false;
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
  // Make a copy of the code before enabling a breakpoint.
  if (enabled && code->orig_start == code->start) {
    code->start = reinterpret_cast<byte*>(zone_.New(size));
    memcpy(code->start, code->orig_start, size);
    code->end = code->start + size;
  }
  bool prev = code->start[pc] == kInternalBreakpoint;
  if (enabled) {
    code->start[pc] = kInternalBreakpoint;
  } else {
    code->start[pc] = code->orig_start[pc];
  }
  return prev;
}

1819
bool WasmInterpreter::GetBreakpoint(const WasmFunction* function, pc_t pc) {
1820 1821
  InterpreterCode* code = internals_->codemap_.FindCode(function);
  if (!code) return false;
1822
  size_t size = static_cast<size_t>(code->end - code->start);
1823
  // Check bounds for {pc}.
1824
  if (pc < code->locals.decls_encoded_size || pc >= size) return false;
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
  // Check if a breakpoint is present at that place in the code.
  return code->start[pc] == kInternalBreakpoint;
}

bool WasmInterpreter::SetTracing(const WasmFunction* function, bool enabled) {
  UNIMPLEMENTED();
  return false;
}

int WasmInterpreter::GetThreadCount() {
  return 1;  // only one thread for now.
}

1838
WasmInterpreter::Thread* WasmInterpreter::GetThread(int id) {
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
  CHECK_EQ(0, id);  // only one thread for now.
  return internals_->threads_[id];
}

WasmVal WasmInterpreter::GetLocalVal(const WasmFrame* frame, int index) {
  CHECK_GE(index, 0);
  UNIMPLEMENTED();
  WasmVal none;
  none.type = kAstStmt;
  return none;
}

WasmVal WasmInterpreter::GetExprVal(const WasmFrame* frame, int pc) {
  UNIMPLEMENTED();
  WasmVal none;
  none.type = kAstStmt;
  return none;
}

void WasmInterpreter::SetLocalVal(WasmFrame* frame, int index, WasmVal val) {
  UNIMPLEMENTED();
}

void WasmInterpreter::SetExprVal(WasmFrame* frame, int pc, WasmVal val) {
  UNIMPLEMENTED();
}

size_t WasmInterpreter::GetMemorySize() {
  return internals_->instance_->mem_size;
}

WasmVal WasmInterpreter::ReadMemory(size_t offset) {
  UNIMPLEMENTED();
  return WasmVal();
}

void WasmInterpreter::WriteMemory(size_t offset, WasmVal val) {
  UNIMPLEMENTED();
}

int WasmInterpreter::AddFunctionForTesting(const WasmFunction* function) {
  return internals_->codemap_.AddFunction(function, nullptr, nullptr);
}

bool WasmInterpreter::SetFunctionCodeForTesting(const WasmFunction* function,
                                                const byte* start,
                                                const byte* end) {
  return internals_->codemap_.SetFunctionCode(function, start, end);
}

ControlTransferMap WasmInterpreter::ComputeControlTransfersForTesting(
    Zone* zone, const byte* start, const byte* end) {
1891
  ControlTransfers targets(zone, nullptr, start, end);
1892 1893 1894 1895 1896 1897
  return targets.map_;
}

}  // namespace wasm
}  // namespace internal
}  // namespace v8