d8-test.cc 34 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2021 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/d8/d8.h"

#include "include/v8-fast-api-calls.h"
8
#include "include/v8-template.h"
9
#include "src/api/api-inl.h"
10 11 12 13 14 15 16 17 18 19

// This file exposes a d8.test.fast_c_api object, which adds testing facility
// for writing mjsunit tests that exercise fast API calls. The fast_c_api object
// contains an `add_all` method with the following signature:
// double add_all(bool /*should_fallback*/, int32_t, uint32_t,
//   int64_t, uint64_t, float, double), that is wired as a "fast API" method.
// The fast_c_api object also supports querying the number of fast/slow calls
// and resetting these counters.

// Make sure to sync the following with src/compiler/globals.h.
20
#if defined(V8_TARGET_ARCH_X64) || defined(V8_TARGET_ARCH_ARM64)
21 22 23 24 25
#define V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
#endif

namespace v8 {
namespace {
26

27 28 29 30 31 32 33 34 35 36 37 38 39
#define CHECK_SELF_OR_FALLBACK(return_value) \
  if (!self) {                               \
    options.fallback = 1;                    \
    return return_value;                     \
  }

#define CHECK_SELF_OR_THROW()                                               \
  if (!self) {                                                              \
    args.GetIsolate()->ThrowError(                                          \
        "This method is not defined on objects inheriting from FastCAPI."); \
    return;                                                                 \
  }

40 41
class FastCApiObject {
 public:
42 43
  static FastCApiObject& instance();

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static AnyCType AddAllFastCallbackPatch(AnyCType receiver,
                                          AnyCType should_fallback,
                                          AnyCType arg_i32, AnyCType arg_u32,
                                          AnyCType arg_i64, AnyCType arg_u64,
                                          AnyCType arg_f32, AnyCType arg_f64,
                                          AnyCType options) {
    AnyCType ret;
    ret.double_value = AddAllFastCallback(
        receiver.object_value, should_fallback.bool_value, arg_i32.int32_value,
        arg_u32.uint32_value, arg_i64.int64_value, arg_u64.uint64_value,
        arg_f32.float_value, arg_f64.double_value, *options.options_value);
    return ret;
  }

#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
60
  static double AddAllFastCallback(Local<Object> receiver, bool should_fallback,
61 62 63 64
                                   int32_t arg_i32, uint32_t arg_u32,
                                   int64_t arg_i64, uint64_t arg_u64,
                                   float arg_f32, double arg_f64,
                                   FastApiCallbackOptions& options) {
65
    FastCApiObject* self = UnwrapObject(receiver);
66
    CHECK_SELF_OR_FALLBACK(0);
67 68 69 70 71
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return 0;
72 73
    } else {
      options.fallback = 0;
74 75 76 77 78 79
    }

    return static_cast<double>(arg_i32) + static_cast<double>(arg_u32) +
           static_cast<double>(arg_i64) + static_cast<double>(arg_u64) +
           static_cast<double>(arg_f32) + arg_f64;
  }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static AnyCType AddAllFastCallbackNoOptionsPatch(
      AnyCType receiver, AnyCType should_fallback, AnyCType arg_i32,
      AnyCType arg_u32, AnyCType arg_i64, AnyCType arg_u64, AnyCType arg_f32,
      AnyCType arg_f64) {
    AnyCType ret;
    ret.double_value = AddAllFastCallbackNoOptions(
        receiver.object_value, should_fallback.bool_value, arg_i32.int32_value,
        arg_u32.uint32_value, arg_i64.int64_value, arg_u64.uint64_value,
        arg_f32.float_value, arg_f64.double_value);
    return ret;
  }
#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static double AddAllFastCallbackNoOptions(Local<Object> receiver,
                                            bool should_fallback,
                                            int32_t arg_i32, uint32_t arg_u32,
                                            int64_t arg_i64, uint64_t arg_u64,
                                            float arg_f32, double arg_f64) {
    // For Wasm call, we don't pass FastCApiObject as the receiver, so we need
    // to retrieve the FastCApiObject instance from a static variable.
    DCHECK(Utils::OpenHandle(*receiver)->IsJSGlobalProxy() ||
           Utils::OpenHandle(*receiver)->IsUndefined());
    // Note: FastCApiObject::instance() returns the reference of an object
    // allocated in thread-local storage, its value cannot be stored in a
    // static variable here.
    FastCApiObject::instance().fast_call_count_++;

    return static_cast<double>(arg_i32) + static_cast<double>(arg_u32) +
           static_cast<double>(arg_i64) + static_cast<double>(arg_u64) +
           static_cast<double>(arg_f32) + arg_f64;
  }

113 114 115
  static void AddAllSlowCallback(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

116
    FastCApiObject* self = UnwrapObject(args.This());
117
    CHECK_SELF_OR_THROW();
118 119 120 121 122
    self->slow_call_count_++;

    HandleScope handle_scope(isolate);

    double sum = 0;
123
    if (args.Length() > 1 && args[1]->IsNumber()) {
124 125
      sum += args[1]->Int32Value(isolate->GetCurrentContext()).FromJust();
    }
126
    if (args.Length() > 2 && args[2]->IsNumber()) {
127 128
      sum += args[2]->Uint32Value(isolate->GetCurrentContext()).FromJust();
    }
129
    if (args.Length() > 3 && args[3]->IsNumber()) {
130 131
      sum += args[3]->IntegerValue(isolate->GetCurrentContext()).FromJust();
    }
132
    if (args.Length() > 4 && args[4]->IsNumber()) {
133 134
      sum += args[4]->IntegerValue(isolate->GetCurrentContext()).FromJust();
    }
135
    if (args.Length() > 5 && args[5]->IsNumber()) {
136 137 138 139
      sum += args[5]->NumberValue(isolate->GetCurrentContext()).FromJust();
    } else {
      sum += std::numeric_limits<double>::quiet_NaN();
    }
140
    if (args.Length() > 6 && args[6]->IsNumber()) {
141 142 143 144 145 146 147 148
      sum += args[6]->NumberValue(isolate->GetCurrentContext()).FromJust();
    } else {
      sum += std::numeric_limits<double>::quiet_NaN();
    }

    args.GetReturnValue().Set(Number::New(isolate, sum));
  }

149 150 151 152 153
#ifdef V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
  typedef double Type;
#else
  typedef int32_t Type;
#endif  // V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static AnyCType AddAllSequenceFastCallbackPatch(AnyCType receiver,
                                                  AnyCType should_fallback,
                                                  AnyCType seq_arg,
                                                  AnyCType options) {
    AnyCType ret;
#ifdef V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
    ret.double_value = AddAllSequenceFastCallback(
        receiver.object_value, should_fallback.bool_value,
        seq_arg.sequence_value, *options.options_value);
#else
    ret.int32_value = AddAllSequenceFastCallback(
        receiver.object_value, should_fallback.bool_value,
        seq_arg.sequence_value, *options.options_value);
#endif  // V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
    return ret;
  }
#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  static Type AddAllSequenceFastCallback(Local<Object> receiver,
                                         bool should_fallback,
                                         Local<Array> seq_arg,
                                         FastApiCallbackOptions& options) {
    FastCApiObject* self = UnwrapObject(receiver);
    CHECK_SELF_OR_FALLBACK(0);
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return 0;
    }

    uint32_t length = seq_arg->Length();
    if (length > 1024) {
      options.fallback = 1;
      return 0;
    }

    Type buffer[1024];
192
    bool result = TryToCopyAndConvertArrayToCppBuffer<
193
        CTypeInfoBuilder<Type>::Build().GetId(), Type>(seq_arg, buffer, 1024);
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    if (!result) {
      options.fallback = 1;
      return 0;
    }
    DCHECK_EQ(seq_arg->Length(), length);

    Type sum = 0;
    for (uint32_t i = 0; i < length; ++i) {
      sum += buffer[i];
    }

    return sum;
  }
  static void AddAllSequenceSlowCallback(
      const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    FastCApiObject* self = UnwrapObject(args.This());
    CHECK_SELF_OR_THROW();

    HandleScope handle_scope(isolate);

216
    if (args.Length() < 2) {
217
      self->slow_call_count_++;
218 219 220
      isolate->ThrowError("This method expects at least 2 arguments.");
      return;
    }
221
    if (args[1]->IsTypedArray()) {
222 223 224 225 226
      AddAllTypedArraySlowCallback(args);
      return;
    }
    self->slow_call_count_++;
    if (args[1]->IsUndefined()) {
227 228 229 230
      Type dummy_result = 0;
      args.GetReturnValue().Set(Number::New(isolate, dummy_result));
      return;
    }
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    if (!args[1]->IsArray()) {
      isolate->ThrowError("This method expects an array as a second argument.");
      return;
    }

    Local<Array> seq_arg = args[1].As<Array>();
    uint32_t length = seq_arg->Length();
    if (length > 1024) {
      isolate->ThrowError(
          "Invalid length of array, must be between 0 and 1024.");
      return;
    }

    Type sum = 0;
    for (uint32_t i = 0; i < length; ++i) {
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
      v8::Local<v8::Value> element =
          seq_arg
              ->Get(isolate->GetCurrentContext(),
                    v8::Integer::NewFromUnsigned(isolate, i))
              .ToLocalChecked();
      if (element->IsNumber()) {
        double value = element->ToNumber(isolate->GetCurrentContext())
                           .ToLocalChecked()
                           ->Value();
        sum += value;
      } else if (element->IsUndefined()) {
        // Hole: ignore the element.
      } else {
        isolate->ThrowError("unexpected element type in JSArray");
        return;
      }
262 263 264
    }
    args.GetReturnValue().Set(Number::New(isolate, sum));
  }
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
#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  template <typename T>
  static const FastApiTypedArray<T>* AnyCTypeToTypedArray(AnyCType arg);

  template <>
  const FastApiTypedArray<int32_t>* AnyCTypeToTypedArray<int32_t>(
      AnyCType arg) {
    return arg.int32_ta_value;
  }
  template <>
  const FastApiTypedArray<uint32_t>* AnyCTypeToTypedArray<uint32_t>(
      AnyCType arg) {
    return arg.uint32_ta_value;
  }
  template <>
  const FastApiTypedArray<int64_t>* AnyCTypeToTypedArray<int64_t>(
      AnyCType arg) {
    return arg.int64_ta_value;
  }
  template <>
  const FastApiTypedArray<uint64_t>* AnyCTypeToTypedArray<uint64_t>(
      AnyCType arg) {
    return arg.uint64_ta_value;
  }
  template <>
  const FastApiTypedArray<float>* AnyCTypeToTypedArray<float>(AnyCType arg) {
    return arg.float_ta_value;
  }
  template <>
  const FastApiTypedArray<double>* AnyCTypeToTypedArray<double>(AnyCType arg) {
    return arg.double_ta_value;
  }

  template <typename T>
  static AnyCType AddAllTypedArrayFastCallbackPatch(AnyCType receiver,
                                                    AnyCType should_fallback,
                                                    AnyCType typed_array_arg,
                                                    AnyCType options) {
    AnyCType ret;
#ifdef V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
    ret.double_value = AddAllTypedArrayFastCallback(
        receiver.object_value, should_fallback.bool_value,
        *AnyCTypeToTypedArray<T>(typed_array_arg), *options.options_value);
#else
    ret.int32_value = AddAllTypedArrayFastCallback(
        receiver.object_value, should_fallback.bool_value,
        *AnyCTypeToTypedArray<T>(typed_array_arg), *options.options_value);
#endif  // V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
    return ret;
  }
#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
316 317 318 319 320
  template <typename T>
  static Type AddAllTypedArrayFastCallback(
      Local<Object> receiver, bool should_fallback,
      const FastApiTypedArray<T>& typed_array_arg,
      FastApiCallbackOptions& options) {
321 322 323 324 325 326 327 328 329
    FastCApiObject* self = UnwrapObject(receiver);
    CHECK_SELF_OR_FALLBACK(0);
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return 0;
    }

330
    T sum = 0;
331 332
    for (unsigned i = 0; i < typed_array_arg.length(); ++i) {
      sum += typed_array_arg.get(i);
333 334
    }
    return static_cast<Type>(sum);
335 336 337
  }
  static void AddAllTypedArraySlowCallback(
      const FunctionCallbackInfo<Value>& args) {
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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
    Isolate* isolate = args.GetIsolate();

    FastCApiObject* self = UnwrapObject(args.This());
    CHECK_SELF_OR_THROW();
    self->slow_call_count_++;

    HandleScope handle_scope(isolate);

    if (args.Length() < 2) {
      isolate->ThrowError("This method expects at least 2 arguments.");
      return;
    }
    if (!args[1]->IsTypedArray()) {
      isolate->ThrowError(
          "This method expects a TypedArray as a second argument.");
      return;
    }

    Local<TypedArray> typed_array_arg = args[1].As<TypedArray>();
    size_t length = typed_array_arg->Length();

    void* data = typed_array_arg->Buffer()->GetBackingStore()->Data();
    if (typed_array_arg->IsInt32Array() || typed_array_arg->IsUint32Array() ||
        typed_array_arg->IsBigInt64Array() ||
        typed_array_arg->IsBigUint64Array()) {
      int64_t sum = 0;
      for (unsigned i = 0; i < length; ++i) {
        if (typed_array_arg->IsInt32Array()) {
          sum += static_cast<int32_t*>(data)[i];
        } else if (typed_array_arg->IsUint32Array()) {
          sum += static_cast<uint32_t*>(data)[i];
        } else if (typed_array_arg->IsBigInt64Array()) {
          sum += static_cast<int64_t*>(data)[i];
        } else if (typed_array_arg->IsBigUint64Array()) {
          sum += static_cast<uint64_t*>(data)[i];
        }
      }
      args.GetReturnValue().Set(Number::New(isolate, sum));
    } else if (typed_array_arg->IsFloat32Array() ||
               typed_array_arg->IsFloat64Array()) {
      double sum = 0;
      for (unsigned i = 0; i < length; ++i) {
        if (typed_array_arg->IsFloat32Array()) {
          sum += static_cast<float*>(data)[i];
        } else if (typed_array_arg->IsFloat64Array()) {
          sum += static_cast<double*>(data)[i];
        }
      }
      args.GetReturnValue().Set(Number::New(isolate, sum));
    } else {
      isolate->ThrowError("TypedArray type is not supported.");
      return;
    }
391 392 393 394 395 396 397 398 399
  }

  static int32_t AddAllIntInvalidCallback(Local<Object> receiver,
                                          bool should_fallback, int32_t arg_i32,
                                          FastApiCallbackOptions& options) {
    // This should never be called
    UNREACHABLE();
  }

400 401 402 403 404 405 406 407 408 409 410 411 412 413
#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static AnyCType Add32BitIntFastCallbackPatch(AnyCType receiver,
                                               AnyCType should_fallback,
                                               AnyCType arg_i32,
                                               AnyCType arg_u32,
                                               AnyCType options) {
    AnyCType ret;
    ret.int32_value = Add32BitIntFastCallback(
        receiver.object_value, should_fallback.bool_value, arg_i32.int32_value,
        arg_u32.uint32_value, *options.options_value);
    return ret;
  }
#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS

414
  static int Add32BitIntFastCallback(v8::Local<v8::Object> receiver,
415 416
                                     bool should_fallback, int32_t arg_i32,
                                     uint32_t arg_u32,
417
                                     FastApiCallbackOptions& options) {
418
    FastCApiObject* self = UnwrapObject(receiver);
419
    CHECK_SELF_OR_FALLBACK(0);
420 421 422 423 424 425 426 427 428 429 430 431
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return 0;
    }

    return arg_i32 + arg_u32;
  }
  static void Add32BitIntSlowCallback(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

432
    FastCApiObject* self = UnwrapObject(args.This());
433
    CHECK_SELF_OR_THROW();
434 435 436 437 438
    self->slow_call_count_++;

    HandleScope handle_scope(isolate);

    double sum = 0;
439
    if (args.Length() > 1 && args[1]->IsNumber()) {
440 441
      sum += args[1]->Int32Value(isolate->GetCurrentContext()).FromJust();
    }
442
    if (args.Length() > 2 && args[2]->IsNumber()) {
443 444 445 446 447 448
      sum += args[2]->Uint32Value(isolate->GetCurrentContext()).FromJust();
    }

    args.GetReturnValue().Set(Number::New(isolate, sum));
  }

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
#ifdef V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS
  static AnyCType AddAll32BitIntFastCallback_6ArgsPatch(
      AnyCType receiver, AnyCType should_fallback, AnyCType arg1_i32,
      AnyCType arg2_i32, AnyCType arg3_i32, AnyCType arg4_u32,
      AnyCType arg5_u32, AnyCType arg6_u32, AnyCType options) {
    AnyCType ret;
    ret.int32_value = AddAll32BitIntFastCallback_6Args(
        receiver.object_value, should_fallback.bool_value, arg1_i32.int32_value,
        arg2_i32.int32_value, arg3_i32.int32_value, arg4_u32.uint32_value,
        arg5_u32.uint32_value, arg6_u32.uint32_value, *options.options_value);
    return ret;
  }
  static AnyCType AddAll32BitIntFastCallback_5ArgsPatch(
      AnyCType receiver, AnyCType should_fallback, AnyCType arg1_i32,
      AnyCType arg2_i32, AnyCType arg3_i32, AnyCType arg4_u32,
      AnyCType arg5_u32, AnyCType options) {
    AnyCType arg6;
    arg6.uint32_value = 0;
    return AddAll32BitIntFastCallback_6ArgsPatch(
        receiver, should_fallback, arg1_i32, arg2_i32, arg3_i32, arg4_u32,
        arg5_u32, arg6, options);
  }
#endif  //  V8_USE_SIMULATOR_WITH_GENERIC_C_CALLS

473 474 475 476 477 478 479 480 481 482 483 484 485
  static int AddAll32BitIntFastCallback_6Args(
      Local<Object> receiver, bool should_fallback, int32_t arg1_i32,
      int32_t arg2_i32, int32_t arg3_i32, uint32_t arg4_u32, uint32_t arg5_u32,
      uint32_t arg6_u32, FastApiCallbackOptions& options) {
    FastCApiObject* self = UnwrapObject(receiver);
    CHECK_SELF_OR_FALLBACK(0);
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return 0;
    }

486 487 488 489 490
    int64_t result = static_cast<int64_t>(arg1_i32) + arg2_i32 + arg3_i32 +
                     arg4_u32 + arg5_u32 + arg6_u32;
    if (result > INT_MAX) return INT_MAX;
    if (result < INT_MIN) return INT_MIN;
    return static_cast<int>(result);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
  }
  static int AddAll32BitIntFastCallback_5Args(
      Local<Object> receiver, bool should_fallback, int32_t arg1_i32,
      int32_t arg2_i32, int32_t arg3_i32, uint32_t arg4_u32, uint32_t arg5_u32,
      FastApiCallbackOptions& options) {
    return AddAll32BitIntFastCallback_6Args(receiver, should_fallback, arg1_i32,
                                            arg2_i32, arg3_i32, arg4_u32,
                                            arg5_u32, 0, options);
  }
  static void AddAll32BitIntSlowCallback(
      const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    FastCApiObject* self = UnwrapObject(args.This());
    CHECK_SELF_OR_THROW();
    self->slow_call_count_++;

    HandleScope handle_scope(isolate);

    double sum = 0;
    if (args.Length() > 1 && args[1]->IsNumber()) {
      sum += args[1]->Int32Value(isolate->GetCurrentContext()).FromJust();
    }
    if (args.Length() > 2 && args[2]->IsNumber()) {
      sum += args[2]->Int32Value(isolate->GetCurrentContext()).FromJust();
    }
    if (args.Length() > 3 && args[3]->IsNumber()) {
      sum += args[3]->Int32Value(isolate->GetCurrentContext()).FromJust();
    }
    if (args.Length() > 4 && args[4]->IsNumber()) {
      sum += args[4]->Uint32Value(isolate->GetCurrentContext()).FromJust();
    }
    if (args.Length() > 5 && args[5]->IsNumber()) {
      sum += args[5]->Uint32Value(isolate->GetCurrentContext()).FromJust();
    }
    if (args.Length() > 6 && args[6]->IsNumber()) {
      sum += args[6]->Uint32Value(isolate->GetCurrentContext()).FromJust();
    }

    args.GetReturnValue().Set(Number::New(isolate, sum));
  }

533
  static bool IsFastCApiObjectFastCallback(v8::Local<v8::Object> receiver,
534 535
                                           bool should_fallback,
                                           v8::Local<v8::Value> arg,
536
                                           FastApiCallbackOptions& options) {
537
    FastCApiObject* self = UnwrapObject(receiver);
538
    CHECK_SELF_OR_FALLBACK(false);
539 540 541 542 543 544 545
    self->fast_call_count_++;

    if (should_fallback) {
      options.fallback = 1;
      return false;
    }

546 547 548
    if (!arg->IsObject()) {
      return false;
    }
549
    Local<Object> object = arg.As<Object>();
550 551 552 553
    if (!IsValidApiObject(object)) return false;

    internal::Isolate* i_isolate =
        internal::IsolateFromNeverReadOnlySpaceObject(
554
            *reinterpret_cast<internal::Address*>(*object));
555 556 557 558 559 560 561 562 563 564 565
    CHECK_NOT_NULL(i_isolate);
    Isolate* isolate = reinterpret_cast<Isolate*>(i_isolate);
    HandleScope handle_scope(isolate);
    return PerIsolateData::Get(isolate)
        ->GetTestApiObjectCtor()
        ->IsLeafTemplateForApiObject(object);
  }
  static void IsFastCApiObjectSlowCallback(
      const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

566
    FastCApiObject* self = UnwrapObject(args.This());
567
    CHECK_SELF_OR_THROW();
568 569 570 571 572 573 574 575 576 577
    self->slow_call_count_++;

    HandleScope handle_scope(isolate);

    bool result = false;
    if (args.Length() < 2) {
      args.GetIsolate()->ThrowError(
          "is_valid_api_object should be called with 2 arguments");
      return;
    }
578
    if (args[1]->IsObject()) {
579
      Local<Object> object = args[1].As<Object>();
580 581 582 583 584 585 586
      if (!IsValidApiObject(object)) {
        result = false;
      } else {
        result = PerIsolateData::Get(args.GetIsolate())
                     ->GetTestApiObjectCtor()
                     ->IsLeafTemplateForApiObject(object);
      }
587 588 589 590 591
    }

    args.GetReturnValue().Set(Boolean::New(isolate, result));
  }

592
  static void FastCallCount(const FunctionCallbackInfo<Value>& args) {
593
    FastCApiObject* self = UnwrapObject(args.This());
594
    CHECK_SELF_OR_THROW();
595 596 597 598
    args.GetReturnValue().Set(
        Number::New(args.GetIsolate(), self->fast_call_count()));
  }
  static void SlowCallCount(const FunctionCallbackInfo<Value>& args) {
599
    FastCApiObject* self = UnwrapObject(args.This());
600
    CHECK_SELF_OR_THROW();
601 602 603 604
    args.GetReturnValue().Set(
        Number::New(args.GetIsolate(), self->slow_call_count()));
  }
  static void ResetCounts(const FunctionCallbackInfo<Value>& args) {
605
    FastCApiObject* self = UnwrapObject(args.This());
606
    CHECK_SELF_OR_THROW();
607 608 609
    self->reset_counts();
    args.GetReturnValue().Set(Undefined(args.GetIsolate()));
  }
610
  static void SupportsFPParams(const FunctionCallbackInfo<Value>& args) {
611
    FastCApiObject* self = UnwrapObject(args.This());
612 613
    CHECK_SELF_OR_THROW();
    args.GetReturnValue().Set(self->supports_fp_params_);
614 615 616 617 618 619 620 621 622 623 624 625
  }

  int fast_call_count() const { return fast_call_count_; }
  int slow_call_count() const { return slow_call_count_; }
  void reset_counts() {
    fast_call_count_ = 0;
    slow_call_count_ = 0;
  }

  static const int kV8WrapperObjectIndex = 1;

 private:
626 627
  static bool IsValidApiObject(Local<Object> object) {
    i::Address addr = *reinterpret_cast<i::Address*>(*object);
628
    auto instance_type = i::Internals::GetInstanceType(addr);
629 630
    return (base::IsInRange(instance_type, i::Internals::kFirstJSApiObjectType,
                            i::Internals::kLastJSApiObjectType) ||
631 632
            instance_type == i::Internals::kJSSpecialApiObjectType);
  }
633
  static FastCApiObject* UnwrapObject(Local<Object> object) {
634
    if (!IsValidApiObject(object)) {
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
      return nullptr;
    }
    FastCApiObject* wrapped = reinterpret_cast<FastCApiObject*>(
        object->GetAlignedPointerFromInternalField(kV8WrapperObjectIndex));
    CHECK_NOT_NULL(wrapped);
    return wrapped;
  }
  int fast_call_count_ = 0, slow_call_count_ = 0;
#ifdef V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
  bool supports_fp_params_ = true;
#else   // V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
  bool supports_fp_params_ = false;
#endif  // V8_ENABLE_FP_PARAMS_IN_C_LINKAGE
};

650 651 652
#undef CHECK_SELF_OR_THROW
#undef CHECK_SELF_OR_FALLBACK

653 654 655 656 657
// The object is statically initialized for simplicity, typically the embedder
// will take care of managing their C++ objects lifetime.
thread_local FastCApiObject kFastCApiObject;
}  // namespace

658 659 660
// static
FastCApiObject& FastCApiObject::instance() { return kFastCApiObject; }

661
void CreateFastCAPIObject(const FunctionCallbackInfo<Value>& info) {
662
  if (!info.IsConstructCall()) {
663 664
    info.GetIsolate()->ThrowError(
        "FastCAPI helper must be constructed with new.");
665 666
    return;
  }
667 668 669 670 671 672 673 674 675 676 677 678
  Local<Object> api_object = info.Holder();
  api_object->SetAlignedPointerInInternalField(
      FastCApiObject::kV8WrapperObjectIndex,
      reinterpret_cast<void*>(&kFastCApiObject));
  api_object->SetAccessorProperty(
      String::NewFromUtf8Literal(info.GetIsolate(), "supports_fp_params"),
      FunctionTemplate::New(info.GetIsolate(), FastCApiObject::SupportsFPParams)
          ->GetFunction(api_object->GetCreationContext().ToLocalChecked())
          .ToLocalChecked());
}

Local<FunctionTemplate> Shell::CreateTestFastCApiTemplate(Isolate* isolate) {
679
  Local<FunctionTemplate> api_obj_ctor =
680 681
      FunctionTemplate::New(isolate, CreateFastCAPIObject);
  PerIsolateData::Get(isolate)->SetTestApiObjectCtor(api_obj_ctor);
682
  Local<Signature> signature = Signature::New(isolate, api_obj_ctor);
683 684
  {
    CFunction add_all_c_func =
685 686
        CFunction::Make(FastCApiObject::AddAllFastCallback V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAllFastCallbackPatch));
687
    api_obj_ctor->PrototypeTemplate()->Set(
688 689 690 691 692
        isolate, "add_all",
        FunctionTemplate::New(isolate, FastCApiObject::AddAllSlowCallback,
                              Local<Value>(), signature, 1,
                              ConstructorBehavior::kThrow,
                              SideEffectType::kHasSideEffect, &add_all_c_func));
693

694 695 696
    CFunction add_all_seq_c_func = CFunction::Make(
        FastCApiObject::AddAllSequenceFastCallback V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAllSequenceFastCallbackPatch));
697 698 699 700 701 702 703
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_sequence",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllSequenceSlowCallback, Local<Value>(),
            signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &add_all_seq_c_func));

704 705 706 707 708
    CFunction add_all_int32_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<int32_t>
            V8_IF_USE_SIMULATOR(
                FastCApiObject::AddAllTypedArrayFastCallbackPatch<int32_t>));

709 710 711 712 713 714 715
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_int32_typed_array",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &add_all_int32_typed_array_c_func));

716 717 718 719
    CFunction add_all_int64_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<int64_t>
            V8_IF_USE_SIMULATOR(
                FastCApiObject::AddAllTypedArrayFastCallbackPatch<int64_t>));
720 721 722 723 724 725 726
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_int64_typed_array",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &add_all_int64_typed_array_c_func));

727 728 729 730
    CFunction add_all_uint64_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<uint64_t>
            V8_IF_USE_SIMULATOR(
                FastCApiObject::AddAllTypedArrayFastCallbackPatch<uint64_t>));
731 732 733 734 735 736 737 738
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_uint64_typed_array",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect,
            &add_all_uint64_typed_array_c_func));

739 740 741 742
    CFunction add_all_uint32_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<uint32_t>
            V8_IF_USE_SIMULATOR(
                FastCApiObject::AddAllTypedArrayFastCallbackPatch<uint32_t>));
743
    api_obj_ctor->PrototypeTemplate()->Set(
744
        isolate, "add_all_uint32_typed_array",
745 746 747
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
748 749
            SideEffectType::kHasSideEffect,
            &add_all_uint32_typed_array_c_func));
750

751 752 753
    CFunction add_all_float32_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<float> V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAllTypedArrayFastCallbackPatch<float>));
754 755 756 757 758 759 760 761
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_float32_typed_array",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect,
            &add_all_float32_typed_array_c_func));

762 763 764 765
    CFunction add_all_float64_typed_array_c_func = CFunction::Make(
        FastCApiObject::AddAllTypedArrayFastCallback<double>
            V8_IF_USE_SIMULATOR(
                FastCApiObject::AddAllTypedArrayFastCallbackPatch<double>));
766 767 768 769 770 771 772 773
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_float64_typed_array",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllTypedArraySlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect,
            &add_all_float64_typed_array_c_func));

774
    const CFunction add_all_overloads[] = {
775
        add_all_uint32_typed_array_c_func,
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
        add_all_seq_c_func,
    };
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_overload",
        FunctionTemplate::NewWithCFunctionOverloads(
            isolate, FastCApiObject::AddAllSequenceSlowCallback, Local<Value>(),
            signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, {add_all_overloads, 2}));

    CFunction add_all_int_invalid_func =
        CFunction::Make(FastCApiObject::AddAllIntInvalidCallback);
    const CFunction add_all_invalid_overloads[] = {
        add_all_int_invalid_func,
        add_all_seq_c_func,
    };
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_invalid_overload",
        FunctionTemplate::NewWithCFunctionOverloads(
            isolate, FastCApiObject::AddAllSequenceSlowCallback, Local<Value>(),
            signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, {add_all_invalid_overloads, 2}));

798 799 800 801 802 803
    CFunction add_all_32bit_int_6args_c_func = CFunction::Make(
        FastCApiObject::AddAll32BitIntFastCallback_6Args V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAll32BitIntFastCallback_6ArgsPatch));
    CFunction add_all_32bit_int_5args_c_func = CFunction::Make(
        FastCApiObject::AddAll32BitIntFastCallback_5Args V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAll32BitIntFastCallback_5ArgsPatch));
804 805
    const CFunction c_function_overloads[] = {add_all_32bit_int_6args_c_func,
                                              add_all_32bit_int_5args_c_func};
806

807
    api_obj_ctor->PrototypeTemplate()->Set(
808
        isolate, "overloaded_add_all_32bit_int",
809
        FunctionTemplate::NewWithCFunctionOverloads(
810
            isolate, FastCApiObject::AddAll32BitIntSlowCallback, Local<Value>(),
811
            signature, 1, ConstructorBehavior::kThrow,
812
            SideEffectType::kHasSideEffect, {c_function_overloads, 2}));
813

814 815 816 817 818 819 820 821 822 823
    CFunction add_all_no_options_c_func = CFunction::Make(
        FastCApiObject::AddAllFastCallbackNoOptions V8_IF_USE_SIMULATOR(
            FastCApiObject::AddAllFastCallbackNoOptionsPatch));
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "add_all_no_options",
        FunctionTemplate::New(
            isolate, FastCApiObject::AddAllSlowCallback, Local<Value>(),
            Local<Signature>(), 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &add_all_no_options_c_func));

824 825 826
    CFunction add_32bit_int_c_func = CFunction::Make(
        FastCApiObject::Add32BitIntFastCallback V8_IF_USE_SIMULATOR(
            FastCApiObject::Add32BitIntFastCallbackPatch));
827
    api_obj_ctor->PrototypeTemplate()->Set(
828 829 830 831 832
        isolate, "add_32bit_int",
        FunctionTemplate::New(
            isolate, FastCApiObject::Add32BitIntSlowCallback, Local<Value>(),
            signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &add_32bit_int_c_func));
833

834 835 836 837 838 839 840 841
    CFunction is_valid_api_object_c_func =
        CFunction::Make(FastCApiObject::IsFastCApiObjectFastCallback);
    api_obj_ctor->PrototypeTemplate()->Set(
        isolate, "is_fast_c_api_object",
        FunctionTemplate::New(
            isolate, FastCApiObject::IsFastCApiObjectSlowCallback,
            Local<Value>(), signature, 1, ConstructorBehavior::kThrow,
            SideEffectType::kHasSideEffect, &is_valid_api_object_c_func));
842

843
    api_obj_ctor->PrototypeTemplate()->Set(
844
        isolate, "fast_call_count",
845 846 847
        FunctionTemplate::New(
            isolate, FastCApiObject::FastCallCount, Local<Value>(), signature,
            1, ConstructorBehavior::kThrow, SideEffectType::kHasNoSideEffect));
848
    api_obj_ctor->PrototypeTemplate()->Set(
849
        isolate, "slow_call_count",
850 851 852
        FunctionTemplate::New(
            isolate, FastCApiObject::SlowCallCount, Local<Value>(), signature,
            1, ConstructorBehavior::kThrow, SideEffectType::kHasNoSideEffect));
853
    api_obj_ctor->PrototypeTemplate()->Set(
854 855
        isolate, "reset_counts",
        FunctionTemplate::New(isolate, FastCApiObject::ResetCounts,
856 857
                              Local<Value>(), signature, 1,
                              ConstructorBehavior::kThrow));
858
  }
859
  api_obj_ctor->InstanceTemplate()->SetInternalFieldCount(
860 861
      FastCApiObject::kV8WrapperObjectIndex + 1);

862
  return api_obj_ctor;
863 864
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
void CreateLeafInterfaceObject(const FunctionCallbackInfo<Value>& info) {
  if (!info.IsConstructCall()) {
    info.GetIsolate()->ThrowError(
        "LeafInterfaceType helper must be constructed with new.");
  }
}

Local<FunctionTemplate> Shell::CreateLeafInterfaceTypeTemplate(
    Isolate* isolate) {
  Local<FunctionTemplate> leaf_object_ctor =
      FunctionTemplate::New(isolate, CreateLeafInterfaceObject);
  leaf_object_ctor->SetClassName(
      String::NewFromUtf8Literal(isolate, "LeafInterfaceType"));
  return leaf_object_ctor;
}

881
}  // namespace v8