1 // Copyright 2012 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "src/api.h" 6 7 #include <string.h> // For memcpy, strlen. 8 #ifdef V8_USE_ADDRESS_SANITIZER 9 #include <sanitizer/asan_interface.h> 10 #endif // V8_USE_ADDRESS_SANITIZER 11 #include <cmath> // For isnan. 12 #include <limits> 13 #include <vector> 14 #include "include/v8-debug.h" 15 #include "include/v8-experimental.h" 16 #include "include/v8-profiler.h" 17 #include "include/v8-testing.h" 18 #include "include/v8-util.h" 19 #include "src/accessors.h" 20 #include "src/api-experimental.h" 21 #include "src/api-natives.h" 22 #include "src/assert-scope.h" 23 #include "src/background-parsing-task.h" 24 #include "src/base/functional.h" 25 #include "src/base/platform/platform.h" 26 #include "src/base/platform/time.h" 27 #include "src/base/safe_conversions.h" 28 #include "src/base/utils/random-number-generator.h" 29 #include "src/bootstrapper.h" 30 #include "src/char-predicates-inl.h" 31 #include "src/code-stubs.h" 32 #include "src/compiler.h" 33 #include "src/context-measure.h" 34 #include "src/contexts.h" 35 #include "src/conversions-inl.h" 36 #include "src/counters.h" 37 #include "src/debug/debug.h" 38 #include "src/deoptimizer.h" 39 #include "src/execution.h" 40 #include "src/frames-inl.h" 41 #include "src/gdb-jit.h" 42 #include "src/global-handles.h" 43 #include "src/globals.h" 44 #include "src/icu_util.h" 45 #include "src/isolate-inl.h" 46 #include "src/json-parser.h" 47 #include "src/json-stringifier.h" 48 #include "src/messages.h" 49 #include "src/parsing/parser.h" 50 #include "src/parsing/scanner-character-streams.h" 51 #include "src/pending-compilation-error-handler.h" 52 #include "src/profiler/cpu-profiler.h" 53 #include "src/profiler/heap-profiler.h" 54 #include "src/profiler/heap-snapshot-generator-inl.h" 55 #include "src/profiler/profile-generator-inl.h" 56 #include "src/profiler/tick-sample.h" 57 #include "src/property-descriptor.h" 58 #include "src/property-details.h" 59 #include "src/property.h" 60 #include "src/prototype.h" 61 #include "src/runtime-profiler.h" 62 #include "src/runtime/runtime.h" 63 #include "src/simulator.h" 64 #include "src/snapshot/code-serializer.h" 65 #include "src/snapshot/natives.h" 66 #include "src/snapshot/snapshot.h" 67 #include "src/startup-data-util.h" 68 #include "src/tracing/trace-event.h" 69 #include "src/unicode-inl.h" 70 #include "src/v8.h" 71 #include "src/v8threads.h" 72 #include "src/value-serializer.h" 73 #include "src/version.h" 74 #include "src/vm-state-inl.h" 75 #include "src/wasm/wasm-module.h" 76 #include "src/wasm/wasm-objects.h" 77 #include "src/wasm/wasm-result.h" 78 79 namespace v8 { 80 81 #define LOG_API(isolate, class_name, function_name) \ 82 i::RuntimeCallTimerScope _runtime_timer( \ 83 isolate, &i::RuntimeCallStats::API_##class_name##_##function_name); \ 84 LOG(isolate, ApiEntryCall("v8::" #class_name "::" #function_name)) 85 86 #define ENTER_V8(isolate) i::VMState<v8::OTHER> __state__((isolate)) 87 88 #define PREPARE_FOR_EXECUTION_GENERIC(isolate, context, class_name, \ 89 function_name, bailout_value, \ 90 HandleScopeClass, do_callback) \ 91 if (IsExecutionTerminatingCheck(isolate)) { \ 92 return bailout_value; \ 93 } \ 94 HandleScopeClass handle_scope(isolate); \ 95 CallDepthScope<do_callback> call_depth_scope(isolate, context); \ 96 LOG_API(isolate, class_name, function_name); \ 97 ENTER_V8(isolate); \ 98 bool has_pending_exception = false 99 100 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ 101 bailout_value, HandleScopeClass, \ 102 do_callback) \ 103 auto isolate = context.IsEmpty() \ 104 ? i::Isolate::Current() \ 105 : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \ 106 PREPARE_FOR_EXECUTION_GENERIC(isolate, context, class_name, function_name, \ 107 bailout_value, HandleScopeClass, do_callback); 108 109 #define PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( \ 110 category, name, context, class_name, function_name, bailout_value, \ 111 HandleScopeClass, do_callback) \ 112 auto isolate = context.IsEmpty() \ 113 ? i::Isolate::Current() \ 114 : reinterpret_cast<i::Isolate*>(context->GetIsolate()); \ 115 TRACE_EVENT_CALL_STATS_SCOPED(isolate, category, name); \ 116 PREPARE_FOR_EXECUTION_GENERIC(isolate, context, class_name, function_name, \ 117 bailout_value, HandleScopeClass, do_callback); 118 119 #define PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, class_name, function_name, \ 120 T) \ 121 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), class_name, \ 122 function_name, MaybeLocal<T>(), \ 123 InternalEscapableScope, false); 124 125 #define PREPARE_FOR_EXECUTION(context, class_name, function_name, T) \ 126 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ 127 MaybeLocal<T>(), InternalEscapableScope, \ 128 false) 129 130 #define PREPARE_FOR_EXECUTION_WITH_CALLBACK(context, class_name, \ 131 function_name, T) \ 132 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ 133 MaybeLocal<T>(), InternalEscapableScope, \ 134 true) 135 136 #define PREPARE_FOR_EXECUTION_PRIMITIVE(context, class_name, function_name, T) \ 137 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ 138 Nothing<T>(), i::HandleScope, false) 139 140 #define PREPARE_FOR_EXECUTION_BOOL(context, class_name, function_name) \ 141 PREPARE_FOR_EXECUTION_WITH_CONTEXT(context, class_name, function_name, \ 142 false, i::HandleScope, false) 143 144 #define EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, value) \ 145 do { \ 146 if (has_pending_exception) { \ 147 call_depth_scope.Escape(); \ 148 return value; \ 149 } \ 150 } while (false) 151 152 153 #define RETURN_ON_FAILED_EXECUTION(T) \ 154 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, MaybeLocal<T>()) 155 156 157 #define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T) \ 158 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, Nothing<T>()) 159 160 #define RETURN_ON_FAILED_EXECUTION_BOOL() \ 161 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false) 162 163 #define RETURN_TO_LOCAL_UNCHECKED(maybe_local, T) \ 164 return maybe_local.FromMaybe(Local<T>()); 165 166 167 #define RETURN_ESCAPED(value) return handle_scope.Escape(value); 168 169 170 namespace { 171 172 Local<Context> ContextFromHeapObject(i::Handle<i::Object> obj) { 173 return reinterpret_cast<v8::Isolate*>(i::HeapObject::cast(*obj)->GetIsolate()) 174 ->GetCurrentContext(); 175 } 176 177 class InternalEscapableScope : public v8::EscapableHandleScope { 178 public: 179 explicit inline InternalEscapableScope(i::Isolate* isolate) 180 : v8::EscapableHandleScope(reinterpret_cast<v8::Isolate*>(isolate)) {} 181 }; 182 183 184 #ifdef DEBUG 185 void CheckMicrotasksScopesConsistency(i::Isolate* isolate) { 186 auto handle_scope_implementer = isolate->handle_scope_implementer(); 187 if (handle_scope_implementer->microtasks_policy() == 188 v8::MicrotasksPolicy::kScoped) { 189 DCHECK(handle_scope_implementer->GetMicrotasksScopeDepth() || 190 !handle_scope_implementer->DebugMicrotasksScopeDepthIsZero()); 191 } 192 } 193 #endif 194 195 template <bool do_callback> 196 class CallDepthScope { 197 public: 198 explicit CallDepthScope(i::Isolate* isolate, Local<Context> context) 199 : isolate_(isolate), context_(context), escaped_(false) { 200 // TODO(dcarney): remove this when blink stops crashing. 201 DCHECK(!isolate_->external_caught_exception()); 202 isolate_->handle_scope_implementer()->IncrementCallDepth(); 203 if (!context.IsEmpty()) { 204 i::Handle<i::Context> env = Utils::OpenHandle(*context); 205 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer(); 206 if (isolate->context() != nullptr && 207 isolate->context()->native_context() == env->native_context() && 208 impl->LastEnteredContextWas(env)) { 209 context_ = Local<Context>(); 210 } else { 211 context_->Enter(); 212 } 213 } 214 if (do_callback) isolate_->FireBeforeCallEnteredCallback(); 215 } 216 ~CallDepthScope() { 217 if (!context_.IsEmpty()) context_->Exit(); 218 if (!escaped_) isolate_->handle_scope_implementer()->DecrementCallDepth(); 219 if (do_callback) isolate_->FireCallCompletedCallback(); 220 #ifdef DEBUG 221 if (do_callback) CheckMicrotasksScopesConsistency(isolate_); 222 #endif 223 } 224 225 void Escape() { 226 DCHECK(!escaped_); 227 escaped_ = true; 228 auto handle_scope_implementer = isolate_->handle_scope_implementer(); 229 handle_scope_implementer->DecrementCallDepth(); 230 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero(); 231 isolate_->OptionalRescheduleException(call_depth_is_zero); 232 } 233 234 private: 235 i::Isolate* const isolate_; 236 Local<Context> context_; 237 bool escaped_; 238 bool do_callback_; 239 }; 240 241 } // namespace 242 243 244 static ScriptOrigin GetScriptOriginForScript(i::Isolate* isolate, 245 i::Handle<i::Script> script) { 246 i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script)); 247 i::Handle<i::Object> source_map_url(script->source_mapping_url(), isolate); 248 v8::Isolate* v8_isolate = 249 reinterpret_cast<v8::Isolate*>(script->GetIsolate()); 250 ScriptOriginOptions options(script->origin_options()); 251 v8::ScriptOrigin origin( 252 Utils::ToLocal(scriptName), 253 v8::Integer::New(v8_isolate, script->line_offset()), 254 v8::Integer::New(v8_isolate, script->column_offset()), 255 v8::Boolean::New(v8_isolate, options.IsSharedCrossOrigin()), 256 v8::Integer::New(v8_isolate, script->id()), 257 v8::Boolean::New(v8_isolate, options.IsEmbedderDebugScript()), 258 Utils::ToLocal(source_map_url), 259 v8::Boolean::New(v8_isolate, options.IsOpaque())); 260 return origin; 261 } 262 263 264 // --- E x c e p t i o n B e h a v i o r --- 265 266 267 void i::FatalProcessOutOfMemory(const char* location) { 268 i::V8::FatalProcessOutOfMemory(location, false); 269 } 270 271 // When V8 cannot allocate memory FatalProcessOutOfMemory is called. The default 272 // OOM error handler is called and execution is stopped. 273 void i::V8::FatalProcessOutOfMemory(const char* location, bool is_heap_oom) { 274 i::Isolate* isolate = i::Isolate::Current(); 275 char last_few_messages[Heap::kTraceRingBufferSize + 1]; 276 char js_stacktrace[Heap::kStacktraceBufferSize + 1]; 277 i::HeapStats heap_stats; 278 279 if (isolate == nullptr) { 280 // On a background thread -> we cannot retrieve memory information from the 281 // Isolate. Write easy-to-recognize values on the stack. 282 memset(last_few_messages, 0x0badc0de, Heap::kTraceRingBufferSize + 1); 283 memset(js_stacktrace, 0x0badc0de, Heap::kStacktraceBufferSize + 1); 284 memset(&heap_stats, 0xbadc0de, sizeof(heap_stats)); 285 // Note that the embedder's oom handler won't be called in this case. We 286 // just crash. 287 FATAL("API fatal error handler returned after process out of memory"); 288 return; 289 } 290 291 memset(last_few_messages, 0, Heap::kTraceRingBufferSize + 1); 292 memset(js_stacktrace, 0, Heap::kStacktraceBufferSize + 1); 293 294 intptr_t start_marker; 295 heap_stats.start_marker = &start_marker; 296 size_t new_space_size; 297 heap_stats.new_space_size = &new_space_size; 298 size_t new_space_capacity; 299 heap_stats.new_space_capacity = &new_space_capacity; 300 size_t old_space_size; 301 heap_stats.old_space_size = &old_space_size; 302 size_t old_space_capacity; 303 heap_stats.old_space_capacity = &old_space_capacity; 304 size_t code_space_size; 305 heap_stats.code_space_size = &code_space_size; 306 size_t code_space_capacity; 307 heap_stats.code_space_capacity = &code_space_capacity; 308 size_t map_space_size; 309 heap_stats.map_space_size = &map_space_size; 310 size_t map_space_capacity; 311 heap_stats.map_space_capacity = &map_space_capacity; 312 size_t lo_space_size; 313 heap_stats.lo_space_size = &lo_space_size; 314 size_t global_handle_count; 315 heap_stats.global_handle_count = &global_handle_count; 316 size_t weak_global_handle_count; 317 heap_stats.weak_global_handle_count = &weak_global_handle_count; 318 size_t pending_global_handle_count; 319 heap_stats.pending_global_handle_count = &pending_global_handle_count; 320 size_t near_death_global_handle_count; 321 heap_stats.near_death_global_handle_count = &near_death_global_handle_count; 322 size_t free_global_handle_count; 323 heap_stats.free_global_handle_count = &free_global_handle_count; 324 size_t memory_allocator_size; 325 heap_stats.memory_allocator_size = &memory_allocator_size; 326 size_t memory_allocator_capacity; 327 heap_stats.memory_allocator_capacity = &memory_allocator_capacity; 328 size_t malloced_memory; 329 heap_stats.malloced_memory = &malloced_memory; 330 size_t malloced_peak_memory; 331 heap_stats.malloced_peak_memory = &malloced_peak_memory; 332 size_t objects_per_type[LAST_TYPE + 1] = {0}; 333 heap_stats.objects_per_type = objects_per_type; 334 size_t size_per_type[LAST_TYPE + 1] = {0}; 335 heap_stats.size_per_type = size_per_type; 336 int os_error; 337 heap_stats.os_error = &os_error; 338 heap_stats.last_few_messages = last_few_messages; 339 heap_stats.js_stacktrace = js_stacktrace; 340 intptr_t end_marker; 341 heap_stats.end_marker = &end_marker; 342 if (isolate->heap()->HasBeenSetUp()) { 343 // BUG(1718): Don't use the take_snapshot since we don't support 344 // HeapIterator here without doing a special GC. 345 isolate->heap()->RecordStats(&heap_stats, false); 346 char* first_newline = strchr(last_few_messages, '\n'); 347 if (first_newline == NULL || first_newline[1] == '\0') 348 first_newline = last_few_messages; 349 PrintF("\n<--- Last few GCs --->\n%s\n", first_newline); 350 PrintF("\n<--- JS stacktrace --->\n%s\n", js_stacktrace); 351 } 352 Utils::ReportOOMFailure(location, is_heap_oom); 353 // If the fatal error handler returns, we stop execution. 354 FATAL("API fatal error handler returned after process out of memory"); 355 } 356 357 358 void Utils::ReportApiFailure(const char* location, const char* message) { 359 i::Isolate* isolate = i::Isolate::Current(); 360 FatalErrorCallback callback = isolate->exception_behavior(); 361 if (callback == nullptr) { 362 base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location, 363 message); 364 base::OS::Abort(); 365 } else { 366 callback(location, message); 367 } 368 isolate->SignalFatalError(); 369 } 370 371 void Utils::ReportOOMFailure(const char* location, bool is_heap_oom) { 372 i::Isolate* isolate = i::Isolate::Current(); 373 OOMErrorCallback oom_callback = isolate->oom_behavior(); 374 if (oom_callback == nullptr) { 375 // TODO(wfh): Remove this fallback once Blink is setting OOM handler. See 376 // crbug.com/614440. 377 FatalErrorCallback fatal_callback = isolate->exception_behavior(); 378 if (fatal_callback == nullptr) { 379 base::OS::PrintError("\n#\n# Fatal %s OOM in %s\n#\n\n", 380 is_heap_oom ? "javascript" : "process", location); 381 base::OS::Abort(); 382 } else { 383 fatal_callback(location, 384 is_heap_oom 385 ? "Allocation failed - JavaScript heap out of memory" 386 : "Allocation failed - process out of memory"); 387 } 388 } else { 389 oom_callback(location, is_heap_oom); 390 } 391 isolate->SignalFatalError(); 392 } 393 394 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) { 395 if (isolate->has_scheduled_exception()) { 396 return isolate->scheduled_exception() == 397 isolate->heap()->termination_exception(); 398 } 399 return false; 400 } 401 402 403 void V8::SetNativesDataBlob(StartupData* natives_blob) { 404 i::V8::SetNativesBlob(natives_blob); 405 } 406 407 408 void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) { 409 i::V8::SetSnapshotBlob(snapshot_blob); 410 } 411 412 namespace { 413 414 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { 415 public: 416 virtual void* Allocate(size_t length) { 417 void* data = AllocateUninitialized(length); 418 return data == NULL ? data : memset(data, 0, length); 419 } 420 virtual void* AllocateUninitialized(size_t length) { return malloc(length); } 421 virtual void Free(void* data, size_t) { free(data); } 422 }; 423 424 bool RunExtraCode(Isolate* isolate, Local<Context> context, 425 const char* utf8_source, const char* name) { 426 base::ElapsedTimer timer; 427 timer.Start(); 428 Context::Scope context_scope(context); 429 TryCatch try_catch(isolate); 430 Local<String> source_string; 431 if (!String::NewFromUtf8(isolate, utf8_source, NewStringType::kNormal) 432 .ToLocal(&source_string)) { 433 return false; 434 } 435 Local<String> resource_name = 436 String::NewFromUtf8(isolate, name, NewStringType::kNormal) 437 .ToLocalChecked(); 438 ScriptOrigin origin(resource_name); 439 ScriptCompiler::Source source(source_string, origin); 440 Local<Script> script; 441 if (!ScriptCompiler::Compile(context, &source).ToLocal(&script)) return false; 442 if (script->Run(context).IsEmpty()) return false; 443 if (i::FLAG_profile_deserialization) { 444 i::PrintF("Executing custom snapshot script %s took %0.3f ms\n", name, 445 timer.Elapsed().InMillisecondsF()); 446 } 447 timer.Stop(); 448 CHECK(!try_catch.HasCaught()); 449 return true; 450 } 451 452 struct SnapshotCreatorData { 453 explicit SnapshotCreatorData(Isolate* isolate) 454 : isolate_(isolate), 455 contexts_(isolate), 456 templates_(isolate), 457 created_(false) {} 458 459 static SnapshotCreatorData* cast(void* data) { 460 return reinterpret_cast<SnapshotCreatorData*>(data); 461 } 462 463 ArrayBufferAllocator allocator_; 464 Isolate* isolate_; 465 PersistentValueVector<Context> contexts_; 466 PersistentValueVector<Template> templates_; 467 bool created_; 468 }; 469 470 } // namespace 471 472 SnapshotCreator::SnapshotCreator(intptr_t* external_references, 473 StartupData* existing_snapshot) { 474 i::Isolate* internal_isolate = new i::Isolate(true); 475 Isolate* isolate = reinterpret_cast<Isolate*>(internal_isolate); 476 SnapshotCreatorData* data = new SnapshotCreatorData(isolate); 477 data->isolate_ = isolate; 478 internal_isolate->set_array_buffer_allocator(&data->allocator_); 479 internal_isolate->set_api_external_references(external_references); 480 isolate->Enter(); 481 if (existing_snapshot) { 482 internal_isolate->set_snapshot_blob(existing_snapshot); 483 i::Snapshot::Initialize(internal_isolate); 484 } else { 485 internal_isolate->Init(nullptr); 486 } 487 data_ = data; 488 } 489 490 SnapshotCreator::~SnapshotCreator() { 491 SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); 492 DCHECK(data->created_); 493 Isolate* isolate = data->isolate_; 494 isolate->Exit(); 495 isolate->Dispose(); 496 delete data; 497 } 498 499 Isolate* SnapshotCreator::GetIsolate() { 500 return SnapshotCreatorData::cast(data_)->isolate_; 501 } 502 503 size_t SnapshotCreator::AddContext(Local<Context> context) { 504 DCHECK(!context.IsEmpty()); 505 SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); 506 DCHECK(!data->created_); 507 Isolate* isolate = data->isolate_; 508 CHECK_EQ(isolate, context->GetIsolate()); 509 size_t index = static_cast<int>(data->contexts_.Size()); 510 data->contexts_.Append(context); 511 return index; 512 } 513 514 size_t SnapshotCreator::AddTemplate(Local<Template> template_obj) { 515 DCHECK(!template_obj.IsEmpty()); 516 SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); 517 DCHECK(!data->created_); 518 DCHECK_EQ(reinterpret_cast<i::Isolate*>(data->isolate_), 519 Utils::OpenHandle(*template_obj)->GetIsolate()); 520 size_t index = static_cast<int>(data->templates_.Size()); 521 data->templates_.Append(template_obj); 522 return index; 523 } 524 525 StartupData SnapshotCreator::CreateBlob( 526 SnapshotCreator::FunctionCodeHandling function_code_handling, 527 SerializeInternalFieldsCallback callback) { 528 SnapshotCreatorData* data = SnapshotCreatorData::cast(data_); 529 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(data->isolate_); 530 DCHECK(!data->created_); 531 532 { 533 int num_templates = static_cast<int>(data->templates_.Size()); 534 i::HandleScope scope(isolate); 535 i::Handle<i::FixedArray> templates = 536 isolate->factory()->NewFixedArray(num_templates, i::TENURED); 537 for (int i = 0; i < num_templates; i++) { 538 templates->set(i, *v8::Utils::OpenHandle(*data->templates_.Get(i))); 539 } 540 isolate->heap()->SetSerializedTemplates(*templates); 541 data->templates_.Clear(); 542 } 543 544 // If we don't do this then we end up with a stray root pointing at the 545 // context even after we have disposed of the context. 546 isolate->heap()->CollectAllAvailableGarbage( 547 i::GarbageCollectionReason::kSnapshotCreator); 548 isolate->heap()->CompactWeakFixedArrays(); 549 550 i::DisallowHeapAllocation no_gc_from_here_on; 551 552 int num_contexts = static_cast<int>(data->contexts_.Size()); 553 i::List<i::Object*> contexts(num_contexts); 554 for (int i = 0; i < num_contexts; i++) { 555 i::HandleScope scope(isolate); 556 i::Handle<i::Context> context = 557 v8::Utils::OpenHandle(*data->contexts_.Get(i)); 558 contexts.Add(*context); 559 } 560 data->contexts_.Clear(); 561 562 #ifdef DEBUG 563 i::ExternalReferenceTable::instance(isolate)->ResetCount(); 564 #endif // DEBUG 565 566 i::StartupSerializer startup_serializer(isolate, function_code_handling); 567 startup_serializer.SerializeStrongReferences(); 568 569 // Serialize each context with a new partial serializer. 570 i::List<i::SnapshotData*> context_snapshots(num_contexts); 571 for (int i = 0; i < num_contexts; i++) { 572 i::PartialSerializer partial_serializer(isolate, &startup_serializer, 573 callback); 574 partial_serializer.Serialize(&contexts[i]); 575 context_snapshots.Add(new i::SnapshotData(&partial_serializer)); 576 } 577 578 startup_serializer.SerializeWeakReferencesAndDeferred(); 579 580 #ifdef DEBUG 581 if (i::FLAG_external_reference_stats) { 582 i::ExternalReferenceTable::instance(isolate)->PrintCount(); 583 } 584 #endif // DEBUG 585 586 i::SnapshotData startup_snapshot(&startup_serializer); 587 StartupData result = 588 i::Snapshot::CreateSnapshotBlob(&startup_snapshot, &context_snapshots); 589 590 // Delete heap-allocated context snapshot instances. 591 for (const auto& context_snapshot : context_snapshots) { 592 delete context_snapshot; 593 } 594 data->created_ = true; 595 return result; 596 } 597 598 StartupData V8::CreateSnapshotDataBlob(const char* embedded_source) { 599 // Create a new isolate and a new context from scratch, optionally run 600 // a script to embed, and serialize to create a snapshot blob. 601 StartupData result = {nullptr, 0}; 602 base::ElapsedTimer timer; 603 timer.Start(); 604 { 605 SnapshotCreator snapshot_creator; 606 Isolate* isolate = snapshot_creator.GetIsolate(); 607 { 608 HandleScope scope(isolate); 609 Local<Context> context = Context::New(isolate); 610 if (embedded_source != NULL && 611 !RunExtraCode(isolate, context, embedded_source, "<embedded>")) { 612 return result; 613 } 614 snapshot_creator.AddContext(context); 615 } 616 result = snapshot_creator.CreateBlob( 617 SnapshotCreator::FunctionCodeHandling::kClear); 618 } 619 620 if (i::FLAG_profile_deserialization) { 621 i::PrintF("Creating snapshot took %0.3f ms\n", 622 timer.Elapsed().InMillisecondsF()); 623 } 624 timer.Stop(); 625 return result; 626 } 627 628 StartupData V8::WarmUpSnapshotDataBlob(StartupData cold_snapshot_blob, 629 const char* warmup_source) { 630 CHECK(cold_snapshot_blob.raw_size > 0 && cold_snapshot_blob.data != NULL); 631 CHECK(warmup_source != NULL); 632 // Use following steps to create a warmed up snapshot blob from a cold one: 633 // - Create a new isolate from the cold snapshot. 634 // - Create a new context to run the warmup script. This will trigger 635 // compilation of executed functions. 636 // - Create a new context. This context will be unpolluted. 637 // - Serialize the isolate and the second context into a new snapshot blob. 638 StartupData result = {nullptr, 0}; 639 base::ElapsedTimer timer; 640 timer.Start(); 641 { 642 SnapshotCreator snapshot_creator(nullptr, &cold_snapshot_blob); 643 Isolate* isolate = snapshot_creator.GetIsolate(); 644 { 645 HandleScope scope(isolate); 646 Local<Context> context = Context::New(isolate); 647 if (!RunExtraCode(isolate, context, warmup_source, "<warm-up>")) { 648 return result; 649 } 650 } 651 { 652 HandleScope handle_scope(isolate); 653 isolate->ContextDisposedNotification(false); 654 Local<Context> context = Context::New(isolate); 655 snapshot_creator.AddContext(context); 656 } 657 result = snapshot_creator.CreateBlob( 658 SnapshotCreator::FunctionCodeHandling::kKeep); 659 } 660 661 if (i::FLAG_profile_deserialization) { 662 i::PrintF("Warming up snapshot took %0.3f ms\n", 663 timer.Elapsed().InMillisecondsF()); 664 } 665 timer.Stop(); 666 return result; 667 } 668 669 670 void V8::SetFlagsFromString(const char* str, int length) { 671 i::FlagList::SetFlagsFromString(str, length); 672 i::FlagList::EnforceFlagImplications(); 673 } 674 675 676 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) { 677 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags); 678 } 679 680 681 RegisteredExtension* RegisteredExtension::first_extension_ = NULL; 682 683 684 RegisteredExtension::RegisteredExtension(Extension* extension) 685 : extension_(extension) { } 686 687 688 void RegisteredExtension::Register(RegisteredExtension* that) { 689 that->next_ = first_extension_; 690 first_extension_ = that; 691 } 692 693 694 void RegisteredExtension::UnregisterAll() { 695 RegisteredExtension* re = first_extension_; 696 while (re != NULL) { 697 RegisteredExtension* next = re->next(); 698 delete re; 699 re = next; 700 } 701 first_extension_ = NULL; 702 } 703 704 705 void RegisterExtension(Extension* that) { 706 RegisteredExtension* extension = new RegisteredExtension(that); 707 RegisteredExtension::Register(extension); 708 } 709 710 711 Extension::Extension(const char* name, 712 const char* source, 713 int dep_count, 714 const char** deps, 715 int source_length) 716 : name_(name), 717 source_length_(source_length >= 0 ? 718 source_length : 719 (source ? static_cast<int>(strlen(source)) : 0)), 720 source_(source, source_length_), 721 dep_count_(dep_count), 722 deps_(deps), 723 auto_enable_(false) { 724 CHECK(source != NULL || source_length_ == 0); 725 } 726 727 ResourceConstraints::ResourceConstraints() 728 : max_semi_space_size_(0), 729 max_old_space_size_(0), 730 max_executable_size_(0), 731 stack_limit_(NULL), 732 code_range_size_(0), 733 max_zone_pool_size_(0) {} 734 735 void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory, 736 uint64_t virtual_memory_limit) { 737 #if V8_OS_ANDROID 738 // Android has higher physical memory requirements before raising the maximum 739 // heap size limits since it has no swap space. 740 const uint64_t low_limit = 512ul * i::MB; 741 const uint64_t medium_limit = 1ul * i::GB; 742 const uint64_t high_limit = 2ul * i::GB; 743 #else 744 const uint64_t low_limit = 512ul * i::MB; 745 const uint64_t medium_limit = 768ul * i::MB; 746 const uint64_t high_limit = 1ul * i::GB; 747 #endif 748 749 if (physical_memory <= low_limit) { 750 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice); 751 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice); 752 set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice); 753 set_max_zone_pool_size(i::AccountingAllocator::kMaxPoolSizeLowMemoryDevice); 754 } else if (physical_memory <= medium_limit) { 755 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice); 756 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice); 757 set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice); 758 set_max_zone_pool_size( 759 i::AccountingAllocator::kMaxPoolSizeMediumMemoryDevice); 760 } else if (physical_memory <= high_limit) { 761 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice); 762 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice); 763 set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice); 764 set_max_zone_pool_size( 765 i::AccountingAllocator::kMaxPoolSizeHighMemoryDevice); 766 } else { 767 set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice); 768 set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice); 769 set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice); 770 set_max_zone_pool_size( 771 i::AccountingAllocator::kMaxPoolSizeHugeMemoryDevice); 772 } 773 774 if (virtual_memory_limit > 0 && i::kRequiresCodeRange) { 775 // Reserve no more than 1/8 of the memory for the code range, but at most 776 // kMaximalCodeRangeSize. 777 set_code_range_size( 778 i::Min(i::kMaximalCodeRangeSize / i::MB, 779 static_cast<size_t>((virtual_memory_limit >> 3) / i::MB))); 780 } 781 } 782 783 784 void SetResourceConstraints(i::Isolate* isolate, 785 const ResourceConstraints& constraints) { 786 int semi_space_size = constraints.max_semi_space_size(); 787 int old_space_size = constraints.max_old_space_size(); 788 int max_executable_size = constraints.max_executable_size(); 789 size_t code_range_size = constraints.code_range_size(); 790 size_t max_pool_size = constraints.max_zone_pool_size(); 791 if (semi_space_size != 0 || old_space_size != 0 || 792 max_executable_size != 0 || code_range_size != 0) { 793 isolate->heap()->ConfigureHeap(semi_space_size, old_space_size, 794 max_executable_size, code_range_size); 795 } 796 isolate->allocator()->ConfigureSegmentPool(max_pool_size); 797 798 if (constraints.stack_limit() != NULL) { 799 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit()); 800 isolate->stack_guard()->SetStackLimit(limit); 801 } 802 } 803 804 805 i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) { 806 LOG_API(isolate, Persistent, New); 807 i::Handle<i::Object> result = isolate->global_handles()->Create(*obj); 808 #ifdef VERIFY_HEAP 809 if (i::FLAG_verify_heap) { 810 (*obj)->ObjectVerify(); 811 } 812 #endif // VERIFY_HEAP 813 return result.location(); 814 } 815 816 817 i::Object** V8::CopyPersistent(i::Object** obj) { 818 i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj); 819 #ifdef VERIFY_HEAP 820 if (i::FLAG_verify_heap) { 821 (*obj)->ObjectVerify(); 822 } 823 #endif // VERIFY_HEAP 824 return result.location(); 825 } 826 827 void V8::RegisterExternallyReferencedObject(i::Object** object, 828 i::Isolate* isolate) { 829 isolate->heap()->RegisterExternallyReferencedObject(object); 830 } 831 832 void V8::MakeWeak(i::Object** location, void* parameter, 833 int internal_field_index1, int internal_field_index2, 834 WeakCallbackInfo<void>::Callback weak_callback) { 835 WeakCallbackType type = WeakCallbackType::kParameter; 836 if (internal_field_index1 == 0) { 837 if (internal_field_index2 == 1) { 838 type = WeakCallbackType::kInternalFields; 839 } else { 840 DCHECK_EQ(internal_field_index2, -1); 841 type = WeakCallbackType::kInternalFields; 842 } 843 } else { 844 DCHECK_EQ(internal_field_index1, -1); 845 DCHECK_EQ(internal_field_index2, -1); 846 } 847 i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type); 848 } 849 850 void V8::MakeWeak(i::Object** location, void* parameter, 851 WeakCallbackInfo<void>::Callback weak_callback, 852 WeakCallbackType type) { 853 i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type); 854 } 855 856 void V8::MakeWeak(i::Object*** location_addr) { 857 i::GlobalHandles::MakeWeak(location_addr); 858 } 859 860 void* V8::ClearWeak(i::Object** location) { 861 return i::GlobalHandles::ClearWeakness(location); 862 } 863 864 void V8::DisposeGlobal(i::Object** location) { 865 i::GlobalHandles::Destroy(location); 866 } 867 868 869 void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) { 870 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 871 i::Object* object = *Utils::OpenHandle(value); 872 isolate->eternal_handles()->Create(isolate, object, index); 873 } 874 875 876 Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) { 877 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 878 return Utils::ToLocal(isolate->eternal_handles()->Get(index)); 879 } 880 881 882 void V8::FromJustIsNothing() { 883 Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing."); 884 } 885 886 887 void V8::ToLocalEmpty() { 888 Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal."); 889 } 890 891 892 void V8::InternalFieldOutOfBounds(int index) { 893 Utils::ApiCheck(0 <= index && index < kInternalFieldsInWeakCallback, 894 "WeakCallbackInfo::GetInternalField", 895 "Internal field out of bounds."); 896 } 897 898 899 // --- H a n d l e s --- 900 901 902 HandleScope::HandleScope(Isolate* isolate) { 903 Initialize(isolate); 904 } 905 906 907 void HandleScope::Initialize(Isolate* isolate) { 908 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 909 // We do not want to check the correct usage of the Locker class all over the 910 // place, so we do it only here: Without a HandleScope, an embedder can do 911 // almost nothing, so it is enough to check in this central place. 912 // We make an exception if the serializer is enabled, which means that the 913 // Isolate is exclusively used to create a snapshot. 914 Utils::ApiCheck( 915 !v8::Locker::IsActive() || 916 internal_isolate->thread_manager()->IsLockedByCurrentThread() || 917 internal_isolate->serializer_enabled(), 918 "HandleScope::HandleScope", 919 "Entering the V8 API without proper locking in place"); 920 i::HandleScopeData* current = internal_isolate->handle_scope_data(); 921 isolate_ = internal_isolate; 922 prev_next_ = current->next; 923 prev_limit_ = current->limit; 924 current->level++; 925 } 926 927 928 HandleScope::~HandleScope() { 929 i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_); 930 } 931 932 933 int HandleScope::NumberOfHandles(Isolate* isolate) { 934 return i::HandleScope::NumberOfHandles( 935 reinterpret_cast<i::Isolate*>(isolate)); 936 } 937 938 939 i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) { 940 return i::HandleScope::CreateHandle(isolate, value); 941 } 942 943 944 i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object, 945 i::Object* value) { 946 DCHECK(heap_object->IsHeapObject()); 947 return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value); 948 } 949 950 951 EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) { 952 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 953 escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value()); 954 Initialize(v8_isolate); 955 } 956 957 958 i::Object** EscapableHandleScope::Escape(i::Object** escape_value) { 959 i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap(); 960 Utils::ApiCheck((*escape_slot_)->IsTheHole(heap->isolate()), 961 "EscapableHandleScope::Escape", "Escape value set twice"); 962 if (escape_value == NULL) { 963 *escape_slot_ = heap->undefined_value(); 964 return NULL; 965 } 966 *escape_slot_ = *escape_value; 967 return escape_slot_; 968 } 969 970 SealHandleScope::SealHandleScope(Isolate* isolate) 971 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) { 972 i::HandleScopeData* current = isolate_->handle_scope_data(); 973 prev_limit_ = current->limit; 974 current->limit = current->next; 975 prev_sealed_level_ = current->sealed_level; 976 current->sealed_level = current->level; 977 } 978 979 980 SealHandleScope::~SealHandleScope() { 981 i::HandleScopeData* current = isolate_->handle_scope_data(); 982 DCHECK_EQ(current->next, current->limit); 983 current->limit = prev_limit_; 984 DCHECK_EQ(current->level, current->sealed_level); 985 current->sealed_level = prev_sealed_level_; 986 } 987 988 989 void Context::Enter() { 990 i::Handle<i::Context> env = Utils::OpenHandle(this); 991 i::Isolate* isolate = env->GetIsolate(); 992 ENTER_V8(isolate); 993 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer(); 994 impl->EnterContext(env); 995 impl->SaveContext(isolate->context()); 996 isolate->set_context(*env); 997 } 998 999 1000 void Context::Exit() { 1001 i::Handle<i::Context> env = Utils::OpenHandle(this); 1002 i::Isolate* isolate = env->GetIsolate(); 1003 ENTER_V8(isolate); 1004 i::HandleScopeImplementer* impl = isolate->handle_scope_implementer(); 1005 if (!Utils::ApiCheck(impl->LastEnteredContextWas(env), 1006 "v8::Context::Exit()", 1007 "Cannot exit non-entered context")) { 1008 return; 1009 } 1010 impl->LeaveContext(); 1011 isolate->set_context(impl->RestoreContext()); 1012 } 1013 1014 1015 static void* DecodeSmiToAligned(i::Object* value, const char* location) { 1016 Utils::ApiCheck(value->IsSmi(), location, "Not a Smi"); 1017 return reinterpret_cast<void*>(value); 1018 } 1019 1020 1021 static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) { 1022 i::Smi* smi = reinterpret_cast<i::Smi*>(value); 1023 Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned"); 1024 return smi; 1025 } 1026 1027 1028 static i::Handle<i::FixedArray> EmbedderDataFor(Context* context, 1029 int index, 1030 bool can_grow, 1031 const char* location) { 1032 i::Handle<i::Context> env = Utils::OpenHandle(context); 1033 i::Isolate* isolate = env->GetIsolate(); 1034 bool ok = 1035 Utils::ApiCheck(env->IsNativeContext(), 1036 location, 1037 "Not a native context") && 1038 Utils::ApiCheck(index >= 0, location, "Negative index"); 1039 if (!ok) return i::Handle<i::FixedArray>(); 1040 i::Handle<i::FixedArray> data(env->embedder_data()); 1041 if (index < data->length()) return data; 1042 if (!Utils::ApiCheck(can_grow, location, "Index too large")) { 1043 return i::Handle<i::FixedArray>(); 1044 } 1045 int new_size = i::Max(index, data->length() << 1) + 1; 1046 int grow_by = new_size - data->length(); 1047 data = isolate->factory()->CopyFixedArrayAndGrow(data, grow_by); 1048 env->set_embedder_data(*data); 1049 return data; 1050 } 1051 1052 1053 v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) { 1054 const char* location = "v8::Context::GetEmbedderData()"; 1055 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location); 1056 if (data.is_null()) return Local<Value>(); 1057 i::Handle<i::Object> result(data->get(index), data->GetIsolate()); 1058 return Utils::ToLocal(result); 1059 } 1060 1061 1062 void Context::SetEmbedderData(int index, v8::Local<Value> value) { 1063 const char* location = "v8::Context::SetEmbedderData()"; 1064 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location); 1065 if (data.is_null()) return; 1066 i::Handle<i::Object> val = Utils::OpenHandle(*value); 1067 data->set(index, *val); 1068 DCHECK_EQ(*Utils::OpenHandle(*value), 1069 *Utils::OpenHandle(*GetEmbedderData(index))); 1070 } 1071 1072 1073 void* Context::SlowGetAlignedPointerFromEmbedderData(int index) { 1074 const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()"; 1075 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location); 1076 if (data.is_null()) return NULL; 1077 return DecodeSmiToAligned(data->get(index), location); 1078 } 1079 1080 1081 void Context::SetAlignedPointerInEmbedderData(int index, void* value) { 1082 const char* location = "v8::Context::SetAlignedPointerInEmbedderData()"; 1083 i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location); 1084 data->set(index, EncodeAlignedAsSmi(value, location)); 1085 DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index)); 1086 } 1087 1088 1089 // --- T e m p l a t e --- 1090 1091 1092 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) { 1093 that->set_number_of_properties(0); 1094 that->set_tag(i::Smi::FromInt(type)); 1095 } 1096 1097 1098 void Template::Set(v8::Local<Name> name, v8::Local<Data> value, 1099 v8::PropertyAttribute attribute) { 1100 auto templ = Utils::OpenHandle(this); 1101 i::Isolate* isolate = templ->GetIsolate(); 1102 ENTER_V8(isolate); 1103 i::HandleScope scope(isolate); 1104 auto value_obj = Utils::OpenHandle(*value); 1105 CHECK(!value_obj->IsJSReceiver() || value_obj->IsTemplateInfo()); 1106 if (value_obj->IsObjectTemplateInfo()) { 1107 templ->set_serial_number(i::Smi::kZero); 1108 if (templ->IsFunctionTemplateInfo()) { 1109 i::Handle<i::FunctionTemplateInfo>::cast(templ)->set_do_not_cache(true); 1110 } 1111 } 1112 i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name), 1113 value_obj, 1114 static_cast<i::PropertyAttributes>(attribute)); 1115 } 1116 1117 void Template::SetPrivate(v8::Local<Private> name, v8::Local<Data> value, 1118 v8::PropertyAttribute attribute) { 1119 Set(Utils::ToLocal(Utils::OpenHandle(reinterpret_cast<Name*>(*name))), value, 1120 attribute); 1121 } 1122 1123 void Template::SetAccessorProperty( 1124 v8::Local<v8::Name> name, 1125 v8::Local<FunctionTemplate> getter, 1126 v8::Local<FunctionTemplate> setter, 1127 v8::PropertyAttribute attribute, 1128 v8::AccessControl access_control) { 1129 // TODO(verwaest): Remove |access_control|. 1130 DCHECK_EQ(v8::DEFAULT, access_control); 1131 auto templ = Utils::OpenHandle(this); 1132 auto isolate = templ->GetIsolate(); 1133 ENTER_V8(isolate); 1134 DCHECK(!name.IsEmpty()); 1135 DCHECK(!getter.IsEmpty() || !setter.IsEmpty()); 1136 i::HandleScope scope(isolate); 1137 i::ApiNatives::AddAccessorProperty( 1138 isolate, templ, Utils::OpenHandle(*name), 1139 Utils::OpenHandle(*getter, true), Utils::OpenHandle(*setter, true), 1140 static_cast<i::PropertyAttributes>(attribute)); 1141 } 1142 1143 1144 // --- F u n c t i o n T e m p l a t e --- 1145 static void InitializeFunctionTemplate( 1146 i::Handle<i::FunctionTemplateInfo> info) { 1147 InitializeTemplate(info, Consts::FUNCTION_TEMPLATE); 1148 info->set_flag(0); 1149 } 1150 1151 static Local<ObjectTemplate> ObjectTemplateNew( 1152 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor, 1153 bool do_not_cache); 1154 1155 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() { 1156 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate(); 1157 ENTER_V8(i_isolate); 1158 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(), 1159 i_isolate); 1160 if (result->IsUndefined(i_isolate)) { 1161 // Do not cache prototype objects. 1162 result = Utils::OpenHandle( 1163 *ObjectTemplateNew(i_isolate, Local<FunctionTemplate>(), true)); 1164 Utils::OpenHandle(this)->set_prototype_template(*result); 1165 } 1166 return ToApiHandle<ObjectTemplate>(result); 1167 } 1168 1169 1170 static void EnsureNotInstantiated(i::Handle<i::FunctionTemplateInfo> info, 1171 const char* func) { 1172 Utils::ApiCheck(!info->instantiated(), func, 1173 "FunctionTemplate already instantiated"); 1174 } 1175 1176 1177 void FunctionTemplate::Inherit(v8::Local<FunctionTemplate> value) { 1178 auto info = Utils::OpenHandle(this); 1179 EnsureNotInstantiated(info, "v8::FunctionTemplate::Inherit"); 1180 i::Isolate* isolate = info->GetIsolate(); 1181 ENTER_V8(isolate); 1182 info->set_parent_template(*Utils::OpenHandle(*value)); 1183 } 1184 1185 static Local<FunctionTemplate> FunctionTemplateNew( 1186 i::Isolate* isolate, FunctionCallback callback, 1187 experimental::FastAccessorBuilder* fast_handler, v8::Local<Value> data, 1188 v8::Local<Signature> signature, int length, bool do_not_cache, 1189 v8::Local<Private> cached_property_name = v8::Local<Private>()) { 1190 i::Handle<i::Struct> struct_obj = 1191 isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE); 1192 i::Handle<i::FunctionTemplateInfo> obj = 1193 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj); 1194 InitializeFunctionTemplate(obj); 1195 obj->set_do_not_cache(do_not_cache); 1196 int next_serial_number = 0; 1197 if (!do_not_cache) { 1198 next_serial_number = isolate->heap()->GetNextTemplateSerialNumber(); 1199 } 1200 obj->set_serial_number(i::Smi::FromInt(next_serial_number)); 1201 if (callback != 0) { 1202 if (data.IsEmpty()) { 1203 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1204 } 1205 Utils::ToLocal(obj)->SetCallHandler(callback, data, fast_handler); 1206 } 1207 obj->set_length(length); 1208 obj->set_undetectable(false); 1209 obj->set_needs_access_check(false); 1210 obj->set_accept_any_receiver(true); 1211 if (!signature.IsEmpty()) 1212 obj->set_signature(*Utils::OpenHandle(*signature)); 1213 obj->set_cached_property_name( 1214 cached_property_name.IsEmpty() 1215 ? isolate->heap()->the_hole_value() 1216 : *Utils::OpenHandle(*cached_property_name)); 1217 return Utils::ToLocal(obj); 1218 } 1219 1220 Local<FunctionTemplate> FunctionTemplate::New( 1221 Isolate* isolate, FunctionCallback callback, v8::Local<Value> data, 1222 v8::Local<Signature> signature, int length, ConstructorBehavior behavior) { 1223 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 1224 // Changes to the environment cannot be captured in the snapshot. Expect no 1225 // function templates when the isolate is created for serialization. 1226 LOG_API(i_isolate, FunctionTemplate, New); 1227 ENTER_V8(i_isolate); 1228 auto templ = FunctionTemplateNew(i_isolate, callback, nullptr, data, 1229 signature, length, false); 1230 if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype(); 1231 return templ; 1232 } 1233 1234 MaybeLocal<FunctionTemplate> FunctionTemplate::FromSnapshot(Isolate* isolate, 1235 size_t index) { 1236 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 1237 i::FixedArray* templates = i_isolate->heap()->serialized_templates(); 1238 int int_index = static_cast<int>(index); 1239 if (int_index < templates->length()) { 1240 i::Object* info = templates->get(int_index); 1241 if (info->IsFunctionTemplateInfo()) { 1242 return Utils::ToLocal(i::Handle<i::FunctionTemplateInfo>( 1243 i::FunctionTemplateInfo::cast(info))); 1244 } 1245 } 1246 return Local<FunctionTemplate>(); 1247 } 1248 1249 Local<FunctionTemplate> FunctionTemplate::NewWithFastHandler( 1250 Isolate* isolate, FunctionCallback callback, 1251 experimental::FastAccessorBuilder* fast_handler, v8::Local<Value> data, 1252 v8::Local<Signature> signature, int length) { 1253 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 1254 LOG_API(i_isolate, FunctionTemplate, NewWithFastHandler); 1255 ENTER_V8(i_isolate); 1256 return FunctionTemplateNew(i_isolate, callback, fast_handler, data, signature, 1257 length, false); 1258 } 1259 1260 Local<FunctionTemplate> FunctionTemplate::NewWithCache( 1261 Isolate* isolate, FunctionCallback callback, Local<Private> cache_property, 1262 Local<Value> data, Local<Signature> signature, int length) { 1263 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 1264 LOG_API(i_isolate, FunctionTemplate, NewWithFastHandler); 1265 ENTER_V8(i_isolate); 1266 return FunctionTemplateNew(i_isolate, callback, nullptr, data, signature, 1267 length, false, cache_property); 1268 } 1269 1270 Local<Signature> Signature::New(Isolate* isolate, 1271 Local<FunctionTemplate> receiver) { 1272 return Utils::SignatureToLocal(Utils::OpenHandle(*receiver)); 1273 } 1274 1275 1276 Local<AccessorSignature> AccessorSignature::New( 1277 Isolate* isolate, Local<FunctionTemplate> receiver) { 1278 return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver)); 1279 } 1280 1281 1282 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \ 1283 i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \ 1284 (obj)->setter(*foreign); \ 1285 } while (false) 1286 1287 1288 void FunctionTemplate::SetCallHandler( 1289 FunctionCallback callback, v8::Local<Value> data, 1290 experimental::FastAccessorBuilder* fast_handler) { 1291 auto info = Utils::OpenHandle(this); 1292 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetCallHandler"); 1293 i::Isolate* isolate = info->GetIsolate(); 1294 ENTER_V8(isolate); 1295 i::HandleScope scope(isolate); 1296 i::Handle<i::Struct> struct_obj = 1297 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE); 1298 i::Handle<i::CallHandlerInfo> obj = 1299 i::Handle<i::CallHandlerInfo>::cast(struct_obj); 1300 SET_FIELD_WRAPPED(obj, set_callback, callback); 1301 i::MaybeHandle<i::Code> code = 1302 i::experimental::BuildCodeFromFastAccessorBuilder(fast_handler); 1303 if (!code.is_null()) { 1304 obj->set_fast_handler(*code.ToHandleChecked()); 1305 } 1306 if (data.IsEmpty()) { 1307 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1308 } 1309 obj->set_data(*Utils::OpenHandle(*data)); 1310 info->set_call_code(*obj); 1311 } 1312 1313 1314 static i::Handle<i::AccessorInfo> SetAccessorInfoProperties( 1315 i::Handle<i::AccessorInfo> obj, v8::Local<Name> name, 1316 v8::AccessControl settings, v8::PropertyAttribute attributes, 1317 v8::Local<AccessorSignature> signature) { 1318 obj->set_name(*Utils::OpenHandle(*name)); 1319 if (settings & ALL_CAN_READ) obj->set_all_can_read(true); 1320 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true); 1321 obj->set_property_attributes(static_cast<i::PropertyAttributes>(attributes)); 1322 if (!signature.IsEmpty()) { 1323 obj->set_expected_receiver_type(*Utils::OpenHandle(*signature)); 1324 } 1325 return obj; 1326 } 1327 1328 namespace { 1329 1330 template <typename Getter, typename Setter> 1331 i::Handle<i::AccessorInfo> MakeAccessorInfo( 1332 v8::Local<Name> name, Getter getter, Setter setter, v8::Local<Value> data, 1333 v8::AccessControl settings, v8::PropertyAttribute attributes, 1334 v8::Local<AccessorSignature> signature, bool is_special_data_property, 1335 bool replace_on_access) { 1336 i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate(); 1337 i::Handle<i::AccessorInfo> obj = isolate->factory()->NewAccessorInfo(); 1338 SET_FIELD_WRAPPED(obj, set_getter, getter); 1339 DCHECK_IMPLIES(replace_on_access, 1340 is_special_data_property && setter == nullptr); 1341 if (is_special_data_property && setter == nullptr) { 1342 setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty); 1343 } 1344 SET_FIELD_WRAPPED(obj, set_setter, setter); 1345 i::Address redirected = obj->redirected_getter(); 1346 if (redirected != nullptr) SET_FIELD_WRAPPED(obj, set_js_getter, redirected); 1347 if (data.IsEmpty()) { 1348 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1349 } 1350 obj->set_data(*Utils::OpenHandle(*data)); 1351 obj->set_is_special_data_property(is_special_data_property); 1352 obj->set_replace_on_access(replace_on_access); 1353 return SetAccessorInfoProperties(obj, name, settings, attributes, signature); 1354 } 1355 1356 } // namespace 1357 1358 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() { 1359 i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true); 1360 if (!Utils::ApiCheck(!handle.is_null(), 1361 "v8::FunctionTemplate::InstanceTemplate()", 1362 "Reading from empty handle")) { 1363 return Local<ObjectTemplate>(); 1364 } 1365 i::Isolate* isolate = handle->GetIsolate(); 1366 ENTER_V8(isolate); 1367 if (handle->instance_template()->IsUndefined(isolate)) { 1368 Local<ObjectTemplate> templ = 1369 ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle)); 1370 handle->set_instance_template(*Utils::OpenHandle(*templ)); 1371 } 1372 i::Handle<i::ObjectTemplateInfo> result( 1373 i::ObjectTemplateInfo::cast(handle->instance_template())); 1374 return Utils::ToLocal(result); 1375 } 1376 1377 1378 void FunctionTemplate::SetLength(int length) { 1379 auto info = Utils::OpenHandle(this); 1380 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetLength"); 1381 auto isolate = info->GetIsolate(); 1382 ENTER_V8(isolate); 1383 info->set_length(length); 1384 } 1385 1386 1387 void FunctionTemplate::SetClassName(Local<String> name) { 1388 auto info = Utils::OpenHandle(this); 1389 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetClassName"); 1390 auto isolate = info->GetIsolate(); 1391 ENTER_V8(isolate); 1392 info->set_class_name(*Utils::OpenHandle(*name)); 1393 } 1394 1395 1396 void FunctionTemplate::SetAcceptAnyReceiver(bool value) { 1397 auto info = Utils::OpenHandle(this); 1398 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetAcceptAnyReceiver"); 1399 auto isolate = info->GetIsolate(); 1400 ENTER_V8(isolate); 1401 info->set_accept_any_receiver(value); 1402 } 1403 1404 1405 void FunctionTemplate::SetHiddenPrototype(bool value) { 1406 auto info = Utils::OpenHandle(this); 1407 EnsureNotInstantiated(info, "v8::FunctionTemplate::SetHiddenPrototype"); 1408 auto isolate = info->GetIsolate(); 1409 ENTER_V8(isolate); 1410 info->set_hidden_prototype(value); 1411 } 1412 1413 1414 void FunctionTemplate::ReadOnlyPrototype() { 1415 auto info = Utils::OpenHandle(this); 1416 EnsureNotInstantiated(info, "v8::FunctionTemplate::ReadOnlyPrototype"); 1417 auto isolate = info->GetIsolate(); 1418 ENTER_V8(isolate); 1419 info->set_read_only_prototype(true); 1420 } 1421 1422 1423 void FunctionTemplate::RemovePrototype() { 1424 auto info = Utils::OpenHandle(this); 1425 EnsureNotInstantiated(info, "v8::FunctionTemplate::RemovePrototype"); 1426 auto isolate = info->GetIsolate(); 1427 ENTER_V8(isolate); 1428 info->set_remove_prototype(true); 1429 } 1430 1431 1432 // --- O b j e c t T e m p l a t e --- 1433 1434 1435 Local<ObjectTemplate> ObjectTemplate::New( 1436 Isolate* isolate, v8::Local<FunctionTemplate> constructor) { 1437 return New(reinterpret_cast<i::Isolate*>(isolate), constructor); 1438 } 1439 1440 1441 Local<ObjectTemplate> ObjectTemplate::New() { 1442 return New(i::Isolate::Current(), Local<FunctionTemplate>()); 1443 } 1444 1445 static Local<ObjectTemplate> ObjectTemplateNew( 1446 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor, 1447 bool do_not_cache) { 1448 LOG_API(isolate, ObjectTemplate, New); 1449 ENTER_V8(isolate); 1450 i::Handle<i::Struct> struct_obj = 1451 isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE); 1452 i::Handle<i::ObjectTemplateInfo> obj = 1453 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj); 1454 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE); 1455 int next_serial_number = 0; 1456 if (!do_not_cache) { 1457 next_serial_number = isolate->heap()->GetNextTemplateSerialNumber(); 1458 } 1459 obj->set_serial_number(i::Smi::FromInt(next_serial_number)); 1460 if (!constructor.IsEmpty()) 1461 obj->set_constructor(*Utils::OpenHandle(*constructor)); 1462 obj->set_data(i::Smi::kZero); 1463 return Utils::ToLocal(obj); 1464 } 1465 1466 Local<ObjectTemplate> ObjectTemplate::New( 1467 i::Isolate* isolate, v8::Local<FunctionTemplate> constructor) { 1468 return ObjectTemplateNew(isolate, constructor, false); 1469 } 1470 1471 MaybeLocal<ObjectTemplate> ObjectTemplate::FromSnapshot(Isolate* isolate, 1472 size_t index) { 1473 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 1474 i::FixedArray* templates = i_isolate->heap()->serialized_templates(); 1475 int int_index = static_cast<int>(index); 1476 if (int_index < templates->length()) { 1477 i::Object* info = templates->get(int_index); 1478 if (info->IsObjectTemplateInfo()) { 1479 return Utils::ToLocal( 1480 i::Handle<i::ObjectTemplateInfo>(i::ObjectTemplateInfo::cast(info))); 1481 } 1482 } 1483 return Local<ObjectTemplate>(); 1484 } 1485 1486 // Ensure that the object template has a constructor. If no 1487 // constructor is available we create one. 1488 static i::Handle<i::FunctionTemplateInfo> EnsureConstructor( 1489 i::Isolate* isolate, 1490 ObjectTemplate* object_template) { 1491 i::Object* obj = Utils::OpenHandle(object_template)->constructor(); 1492 if (!obj->IsUndefined(isolate)) { 1493 i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj); 1494 return i::Handle<i::FunctionTemplateInfo>(info, isolate); 1495 } 1496 Local<FunctionTemplate> templ = 1497 FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate)); 1498 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ); 1499 constructor->set_instance_template(*Utils::OpenHandle(object_template)); 1500 Utils::OpenHandle(object_template)->set_constructor(*constructor); 1501 return constructor; 1502 } 1503 1504 template <typename Getter, typename Setter, typename Data, typename Template> 1505 static bool TemplateSetAccessor(Template* template_obj, v8::Local<Name> name, 1506 Getter getter, Setter setter, Data data, 1507 AccessControl settings, 1508 PropertyAttribute attribute, 1509 v8::Local<AccessorSignature> signature, 1510 bool is_special_data_property, 1511 bool replace_on_access) { 1512 auto info = Utils::OpenHandle(template_obj); 1513 auto isolate = info->GetIsolate(); 1514 ENTER_V8(isolate); 1515 i::HandleScope scope(isolate); 1516 auto obj = 1517 MakeAccessorInfo(name, getter, setter, data, settings, attribute, 1518 signature, is_special_data_property, replace_on_access); 1519 if (obj.is_null()) return false; 1520 i::ApiNatives::AddNativeDataProperty(isolate, info, obj); 1521 return true; 1522 } 1523 1524 1525 void Template::SetNativeDataProperty(v8::Local<String> name, 1526 AccessorGetterCallback getter, 1527 AccessorSetterCallback setter, 1528 v8::Local<Value> data, 1529 PropertyAttribute attribute, 1530 v8::Local<AccessorSignature> signature, 1531 AccessControl settings) { 1532 TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, 1533 signature, true, false); 1534 } 1535 1536 1537 void Template::SetNativeDataProperty(v8::Local<Name> name, 1538 AccessorNameGetterCallback getter, 1539 AccessorNameSetterCallback setter, 1540 v8::Local<Value> data, 1541 PropertyAttribute attribute, 1542 v8::Local<AccessorSignature> signature, 1543 AccessControl settings) { 1544 TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, 1545 signature, true, false); 1546 } 1547 1548 void Template::SetLazyDataProperty(v8::Local<Name> name, 1549 AccessorNameGetterCallback getter, 1550 v8::Local<Value> data, 1551 PropertyAttribute attribute) { 1552 TemplateSetAccessor( 1553 this, name, getter, static_cast<AccessorNameSetterCallback>(nullptr), 1554 data, DEFAULT, attribute, Local<AccessorSignature>(), true, true); 1555 } 1556 1557 void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic, 1558 PropertyAttribute attribute) { 1559 auto templ = Utils::OpenHandle(this); 1560 i::Isolate* isolate = templ->GetIsolate(); 1561 ENTER_V8(isolate); 1562 i::HandleScope scope(isolate); 1563 i::ApiNatives::AddDataProperty(isolate, templ, Utils::OpenHandle(*name), 1564 intrinsic, 1565 static_cast<i::PropertyAttributes>(attribute)); 1566 } 1567 1568 1569 void ObjectTemplate::SetAccessor(v8::Local<String> name, 1570 AccessorGetterCallback getter, 1571 AccessorSetterCallback setter, 1572 v8::Local<Value> data, AccessControl settings, 1573 PropertyAttribute attribute, 1574 v8::Local<AccessorSignature> signature) { 1575 TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, 1576 signature, i::FLAG_disable_old_api_accessors, false); 1577 } 1578 1579 1580 void ObjectTemplate::SetAccessor(v8::Local<Name> name, 1581 AccessorNameGetterCallback getter, 1582 AccessorNameSetterCallback setter, 1583 v8::Local<Value> data, AccessControl settings, 1584 PropertyAttribute attribute, 1585 v8::Local<AccessorSignature> signature) { 1586 TemplateSetAccessor(this, name, getter, setter, data, settings, attribute, 1587 signature, i::FLAG_disable_old_api_accessors, false); 1588 } 1589 1590 template <typename Getter, typename Setter, typename Query, typename Descriptor, 1591 typename Deleter, typename Enumerator, typename Definer> 1592 static i::Handle<i::InterceptorInfo> CreateInterceptorInfo( 1593 i::Isolate* isolate, Getter getter, Setter setter, Query query, 1594 Descriptor descriptor, Deleter remover, Enumerator enumerator, 1595 Definer definer, Local<Value> data, PropertyHandlerFlags flags) { 1596 DCHECK(query == nullptr || 1597 descriptor == nullptr); // Either intercept attributes or descriptor. 1598 DCHECK(query == nullptr || 1599 definer == 1600 nullptr); // Only use descriptor callback with definer callback. 1601 auto obj = i::Handle<i::InterceptorInfo>::cast( 1602 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE)); 1603 obj->set_flags(0); 1604 1605 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter); 1606 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter); 1607 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query); 1608 if (descriptor != 0) SET_FIELD_WRAPPED(obj, set_descriptor, descriptor); 1609 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover); 1610 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator); 1611 if (definer != 0) SET_FIELD_WRAPPED(obj, set_definer, definer); 1612 obj->set_can_intercept_symbols( 1613 !(static_cast<int>(flags) & 1614 static_cast<int>(PropertyHandlerFlags::kOnlyInterceptStrings))); 1615 obj->set_all_can_read(static_cast<int>(flags) & 1616 static_cast<int>(PropertyHandlerFlags::kAllCanRead)); 1617 obj->set_non_masking(static_cast<int>(flags) & 1618 static_cast<int>(PropertyHandlerFlags::kNonMasking)); 1619 1620 if (data.IsEmpty()) { 1621 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1622 } 1623 obj->set_data(*Utils::OpenHandle(*data)); 1624 return obj; 1625 } 1626 1627 template <typename Getter, typename Setter, typename Query, typename Descriptor, 1628 typename Deleter, typename Enumerator, typename Definer> 1629 static void ObjectTemplateSetNamedPropertyHandler( 1630 ObjectTemplate* templ, Getter getter, Setter setter, Query query, 1631 Descriptor descriptor, Deleter remover, Enumerator enumerator, 1632 Definer definer, Local<Value> data, PropertyHandlerFlags flags) { 1633 i::Isolate* isolate = Utils::OpenHandle(templ)->GetIsolate(); 1634 ENTER_V8(isolate); 1635 i::HandleScope scope(isolate); 1636 auto cons = EnsureConstructor(isolate, templ); 1637 EnsureNotInstantiated(cons, "ObjectTemplateSetNamedPropertyHandler"); 1638 auto obj = CreateInterceptorInfo(isolate, getter, setter, query, descriptor, 1639 remover, enumerator, definer, data, flags); 1640 cons->set_named_property_handler(*obj); 1641 } 1642 1643 void ObjectTemplate::SetNamedPropertyHandler( 1644 NamedPropertyGetterCallback getter, NamedPropertySetterCallback setter, 1645 NamedPropertyQueryCallback query, NamedPropertyDeleterCallback remover, 1646 NamedPropertyEnumeratorCallback enumerator, Local<Value> data) { 1647 ObjectTemplateSetNamedPropertyHandler( 1648 this, getter, setter, query, nullptr, remover, enumerator, nullptr, data, 1649 PropertyHandlerFlags::kOnlyInterceptStrings); 1650 } 1651 1652 void ObjectTemplate::SetHandler( 1653 const NamedPropertyHandlerConfiguration& config) { 1654 ObjectTemplateSetNamedPropertyHandler( 1655 this, config.getter, config.setter, config.query, config.descriptor, 1656 config.deleter, config.enumerator, config.definer, config.data, 1657 config.flags); 1658 } 1659 1660 1661 void ObjectTemplate::MarkAsUndetectable() { 1662 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1663 ENTER_V8(isolate); 1664 i::HandleScope scope(isolate); 1665 auto cons = EnsureConstructor(isolate, this); 1666 EnsureNotInstantiated(cons, "v8::ObjectTemplate::MarkAsUndetectable"); 1667 cons->set_undetectable(true); 1668 } 1669 1670 1671 void ObjectTemplate::SetAccessCheckCallback(AccessCheckCallback callback, 1672 Local<Value> data) { 1673 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1674 ENTER_V8(isolate); 1675 i::HandleScope scope(isolate); 1676 auto cons = EnsureConstructor(isolate, this); 1677 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback"); 1678 1679 i::Handle<i::Struct> struct_info = 1680 isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE); 1681 i::Handle<i::AccessCheckInfo> info = 1682 i::Handle<i::AccessCheckInfo>::cast(struct_info); 1683 1684 SET_FIELD_WRAPPED(info, set_callback, callback); 1685 info->set_named_interceptor(nullptr); 1686 info->set_indexed_interceptor(nullptr); 1687 1688 if (data.IsEmpty()) { 1689 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1690 } 1691 info->set_data(*Utils::OpenHandle(*data)); 1692 1693 cons->set_access_check_info(*info); 1694 cons->set_needs_access_check(true); 1695 } 1696 1697 void ObjectTemplate::SetAccessCheckCallbackAndHandler( 1698 AccessCheckCallback callback, 1699 const NamedPropertyHandlerConfiguration& named_handler, 1700 const IndexedPropertyHandlerConfiguration& indexed_handler, 1701 Local<Value> data) { 1702 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1703 ENTER_V8(isolate); 1704 i::HandleScope scope(isolate); 1705 auto cons = EnsureConstructor(isolate, this); 1706 EnsureNotInstantiated( 1707 cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler"); 1708 1709 i::Handle<i::Struct> struct_info = 1710 isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE); 1711 i::Handle<i::AccessCheckInfo> info = 1712 i::Handle<i::AccessCheckInfo>::cast(struct_info); 1713 1714 SET_FIELD_WRAPPED(info, set_callback, callback); 1715 auto named_interceptor = CreateInterceptorInfo( 1716 isolate, named_handler.getter, named_handler.setter, named_handler.query, 1717 named_handler.descriptor, named_handler.deleter, named_handler.enumerator, 1718 named_handler.definer, named_handler.data, named_handler.flags); 1719 info->set_named_interceptor(*named_interceptor); 1720 auto indexed_interceptor = CreateInterceptorInfo( 1721 isolate, indexed_handler.getter, indexed_handler.setter, 1722 indexed_handler.query, indexed_handler.descriptor, 1723 indexed_handler.deleter, indexed_handler.enumerator, 1724 indexed_handler.definer, indexed_handler.data, indexed_handler.flags); 1725 info->set_indexed_interceptor(*indexed_interceptor); 1726 1727 if (data.IsEmpty()) { 1728 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1729 } 1730 info->set_data(*Utils::OpenHandle(*data)); 1731 1732 cons->set_access_check_info(*info); 1733 cons->set_needs_access_check(true); 1734 } 1735 1736 void ObjectTemplate::SetHandler( 1737 const IndexedPropertyHandlerConfiguration& config) { 1738 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1739 ENTER_V8(isolate); 1740 i::HandleScope scope(isolate); 1741 auto cons = EnsureConstructor(isolate, this); 1742 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetHandler"); 1743 auto obj = CreateInterceptorInfo(isolate, config.getter, config.setter, 1744 config.query, config.descriptor, 1745 config.deleter, config.enumerator, 1746 config.definer, config.data, config.flags); 1747 cons->set_indexed_property_handler(*obj); 1748 } 1749 1750 1751 void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback, 1752 Local<Value> data) { 1753 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1754 ENTER_V8(isolate); 1755 i::HandleScope scope(isolate); 1756 auto cons = EnsureConstructor(isolate, this); 1757 EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler"); 1758 i::Handle<i::Struct> struct_obj = 1759 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE); 1760 i::Handle<i::CallHandlerInfo> obj = 1761 i::Handle<i::CallHandlerInfo>::cast(struct_obj); 1762 SET_FIELD_WRAPPED(obj, set_callback, callback); 1763 if (data.IsEmpty()) { 1764 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 1765 } 1766 obj->set_data(*Utils::OpenHandle(*data)); 1767 cons->set_instance_call_handler(*obj); 1768 } 1769 1770 1771 int ObjectTemplate::InternalFieldCount() { 1772 return Utils::OpenHandle(this)->internal_field_count(); 1773 } 1774 1775 1776 void ObjectTemplate::SetInternalFieldCount(int value) { 1777 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1778 if (!Utils::ApiCheck(i::Smi::IsValid(value), 1779 "v8::ObjectTemplate::SetInternalFieldCount()", 1780 "Invalid internal field count")) { 1781 return; 1782 } 1783 ENTER_V8(isolate); 1784 if (value > 0) { 1785 // The internal field count is set by the constructor function's 1786 // construct code, so we ensure that there is a constructor 1787 // function to do the setting. 1788 EnsureConstructor(isolate, this); 1789 } 1790 Utils::OpenHandle(this)->set_internal_field_count(value); 1791 } 1792 1793 bool ObjectTemplate::IsImmutableProto() { 1794 return Utils::OpenHandle(this)->immutable_proto(); 1795 } 1796 1797 void ObjectTemplate::SetImmutableProto() { 1798 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 1799 ENTER_V8(isolate); 1800 Utils::OpenHandle(this)->set_immutable_proto(true); 1801 } 1802 1803 // --- S c r i p t s --- 1804 1805 1806 // Internally, UnboundScript is a SharedFunctionInfo, and Script is a 1807 // JSFunction. 1808 1809 ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_, 1810 BufferPolicy buffer_policy_) 1811 : data(data_), 1812 length(length_), 1813 rejected(false), 1814 buffer_policy(buffer_policy_) {} 1815 1816 1817 ScriptCompiler::CachedData::~CachedData() { 1818 if (buffer_policy == BufferOwned) { 1819 delete[] data; 1820 } 1821 } 1822 1823 1824 bool ScriptCompiler::ExternalSourceStream::SetBookmark() { return false; } 1825 1826 1827 void ScriptCompiler::ExternalSourceStream::ResetToBookmark() { UNREACHABLE(); } 1828 1829 1830 ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream, 1831 Encoding encoding) 1832 : impl_(new i::StreamedSource(stream, encoding)) {} 1833 1834 1835 ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; } 1836 1837 1838 const ScriptCompiler::CachedData* 1839 ScriptCompiler::StreamedSource::GetCachedData() const { 1840 return impl_->cached_data.get(); 1841 } 1842 1843 1844 Local<Script> UnboundScript::BindToCurrentContext() { 1845 i::Handle<i::HeapObject> obj = 1846 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this)); 1847 i::Isolate* isolate = obj->GetIsolate(); 1848 i::Handle<i::SharedFunctionInfo> function_info( 1849 i::SharedFunctionInfo::cast(*obj), isolate); 1850 i::Handle<i::JSFunction> function = 1851 isolate->factory()->NewFunctionFromSharedFunctionInfo( 1852 function_info, isolate->native_context()); 1853 return ToApiHandle<Script>(function); 1854 } 1855 1856 1857 int UnboundScript::GetId() { 1858 i::Handle<i::HeapObject> obj = 1859 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this)); 1860 i::Isolate* isolate = obj->GetIsolate(); 1861 LOG_API(isolate, UnboundScript, GetId); 1862 i::HandleScope scope(isolate); 1863 i::Handle<i::SharedFunctionInfo> function_info( 1864 i::SharedFunctionInfo::cast(*obj)); 1865 i::Handle<i::Script> script(i::Script::cast(function_info->script())); 1866 return script->id(); 1867 } 1868 1869 1870 int UnboundScript::GetLineNumber(int code_pos) { 1871 i::Handle<i::SharedFunctionInfo> obj = 1872 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); 1873 i::Isolate* isolate = obj->GetIsolate(); 1874 LOG_API(isolate, UnboundScript, GetLineNumber); 1875 if (obj->script()->IsScript()) { 1876 i::Handle<i::Script> script(i::Script::cast(obj->script())); 1877 return i::Script::GetLineNumber(script, code_pos); 1878 } else { 1879 return -1; 1880 } 1881 } 1882 1883 1884 Local<Value> UnboundScript::GetScriptName() { 1885 i::Handle<i::SharedFunctionInfo> obj = 1886 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); 1887 i::Isolate* isolate = obj->GetIsolate(); 1888 LOG_API(isolate, UnboundScript, GetName); 1889 if (obj->script()->IsScript()) { 1890 i::Object* name = i::Script::cast(obj->script())->name(); 1891 return Utils::ToLocal(i::Handle<i::Object>(name, isolate)); 1892 } else { 1893 return Local<String>(); 1894 } 1895 } 1896 1897 1898 Local<Value> UnboundScript::GetSourceURL() { 1899 i::Handle<i::SharedFunctionInfo> obj = 1900 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); 1901 i::Isolate* isolate = obj->GetIsolate(); 1902 LOG_API(isolate, UnboundScript, GetSourceURL); 1903 if (obj->script()->IsScript()) { 1904 i::Object* url = i::Script::cast(obj->script())->source_url(); 1905 return Utils::ToLocal(i::Handle<i::Object>(url, isolate)); 1906 } else { 1907 return Local<String>(); 1908 } 1909 } 1910 1911 1912 Local<Value> UnboundScript::GetSourceMappingURL() { 1913 i::Handle<i::SharedFunctionInfo> obj = 1914 i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this)); 1915 i::Isolate* isolate = obj->GetIsolate(); 1916 LOG_API(isolate, UnboundScript, GetSourceMappingURL); 1917 if (obj->script()->IsScript()) { 1918 i::Object* url = i::Script::cast(obj->script())->source_mapping_url(); 1919 return Utils::ToLocal(i::Handle<i::Object>(url, isolate)); 1920 } else { 1921 return Local<String>(); 1922 } 1923 } 1924 1925 1926 MaybeLocal<Value> Script::Run(Local<Context> context) { 1927 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 1928 "v8", "V8.Execute", context, Script, Run, MaybeLocal<Value>(), 1929 InternalEscapableScope, true); 1930 i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true); 1931 i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy()); 1932 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 1933 auto fun = i::Handle<i::JSFunction>::cast(Utils::OpenHandle(this)); 1934 1935 i::Handle<i::Object> receiver = isolate->global_proxy(); 1936 Local<Value> result; 1937 has_pending_exception = !ToLocal<Value>( 1938 i::Execution::Call(isolate, fun, receiver, 0, nullptr), &result); 1939 1940 RETURN_ON_FAILED_EXECUTION(Value); 1941 RETURN_ESCAPED(result); 1942 } 1943 1944 1945 Local<Value> Script::Run() { 1946 auto self = Utils::OpenHandle(this, true); 1947 // If execution is terminating, Compile(..)->Run() requires this 1948 // check. 1949 if (self.is_null()) return Local<Value>(); 1950 auto context = ContextFromHeapObject(self); 1951 RETURN_TO_LOCAL_UNCHECKED(Run(context), Value); 1952 } 1953 1954 1955 Local<UnboundScript> Script::GetUnboundScript() { 1956 i::Handle<i::Object> obj = Utils::OpenHandle(this); 1957 return ToApiHandle<UnboundScript>( 1958 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared())); 1959 } 1960 1961 int Module::GetModuleRequestsLength() const { 1962 i::Handle<i::Module> self = Utils::OpenHandle(this); 1963 return self->info()->module_requests()->length(); 1964 } 1965 1966 Local<String> Module::GetModuleRequest(int i) const { 1967 CHECK_GE(i, 0); 1968 i::Handle<i::Module> self = Utils::OpenHandle(this); 1969 i::Isolate* isolate = self->GetIsolate(); 1970 i::Handle<i::FixedArray> module_requests(self->info()->module_requests(), 1971 isolate); 1972 CHECK_LT(i, module_requests->length()); 1973 return ToApiHandle<String>(i::handle(module_requests->get(i), isolate)); 1974 } 1975 1976 int Module::GetIdentityHash() const { return Utils::OpenHandle(this)->hash(); } 1977 1978 bool Module::Instantiate(Local<Context> context, 1979 Module::ResolveCallback callback) { 1980 PREPARE_FOR_EXECUTION_BOOL(context, Module, Instantiate); 1981 has_pending_exception = 1982 !i::Module::Instantiate(Utils::OpenHandle(this), context, callback); 1983 RETURN_ON_FAILED_EXECUTION_BOOL(); 1984 return true; 1985 } 1986 1987 MaybeLocal<Value> Module::Evaluate(Local<Context> context) { 1988 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 1989 "v8", "V8.Execute", context, Module, Evaluate, MaybeLocal<Value>(), 1990 InternalEscapableScope, true); 1991 i::HistogramTimerScope execute_timer(isolate->counters()->execute(), true); 1992 i::AggregatingHistogramTimerScope timer(isolate->counters()->compile_lazy()); 1993 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 1994 1995 i::Handle<i::Module> self = Utils::OpenHandle(this); 1996 // It's an API error to call Evaluate before Instantiate. 1997 CHECK(self->instantiated()); 1998 1999 Local<Value> result; 2000 has_pending_exception = !ToLocal(i::Module::Evaluate(self), &result); 2001 RETURN_ON_FAILED_EXECUTION(Value); 2002 RETURN_ESCAPED(result); 2003 } 2004 2005 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundInternal( 2006 Isolate* v8_isolate, Source* source, CompileOptions options, 2007 bool is_module) { 2008 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 2009 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, ScriptCompiler, CompileUnbound, 2010 UnboundScript); 2011 TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.ScriptCompiler"); 2012 2013 // Don't try to produce any kind of cache when the debugger is loaded. 2014 if (isolate->debug()->is_loaded() && 2015 (options == kProduceParserCache || options == kProduceCodeCache)) { 2016 options = kNoCompileOptions; 2017 } 2018 2019 i::ScriptData* script_data = NULL; 2020 if (options == kConsumeParserCache || options == kConsumeCodeCache) { 2021 DCHECK(source->cached_data); 2022 // ScriptData takes care of pointer-aligning the data. 2023 script_data = new i::ScriptData(source->cached_data->data, 2024 source->cached_data->length); 2025 } 2026 2027 i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string)); 2028 i::Handle<i::SharedFunctionInfo> result; 2029 { 2030 i::HistogramTimerScope total(isolate->counters()->compile_script(), true); 2031 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileScript"); 2032 i::Handle<i::Object> name_obj; 2033 i::Handle<i::Object> source_map_url; 2034 int line_offset = 0; 2035 int column_offset = 0; 2036 if (!source->resource_name.IsEmpty()) { 2037 name_obj = Utils::OpenHandle(*(source->resource_name)); 2038 } 2039 if (!source->resource_line_offset.IsEmpty()) { 2040 line_offset = static_cast<int>(source->resource_line_offset->Value()); 2041 } 2042 if (!source->resource_column_offset.IsEmpty()) { 2043 column_offset = 2044 static_cast<int>(source->resource_column_offset->Value()); 2045 } 2046 if (!source->source_map_url.IsEmpty()) { 2047 source_map_url = Utils::OpenHandle(*(source->source_map_url)); 2048 } 2049 result = i::Compiler::GetSharedFunctionInfoForScript( 2050 str, name_obj, line_offset, column_offset, source->resource_options, 2051 source_map_url, isolate->native_context(), NULL, &script_data, options, 2052 i::NOT_NATIVES_CODE, is_module); 2053 has_pending_exception = result.is_null(); 2054 if (has_pending_exception && script_data != NULL) { 2055 // This case won't happen during normal operation; we have compiled 2056 // successfully and produced cached data, and but the second compilation 2057 // of the same source code fails. 2058 delete script_data; 2059 script_data = NULL; 2060 } 2061 RETURN_ON_FAILED_EXECUTION(UnboundScript); 2062 2063 if ((options == kProduceParserCache || options == kProduceCodeCache) && 2064 script_data != NULL) { 2065 // script_data now contains the data that was generated. source will 2066 // take the ownership. 2067 source->cached_data = new CachedData( 2068 script_data->data(), script_data->length(), CachedData::BufferOwned); 2069 script_data->ReleaseDataOwnership(); 2070 } else if (options == kConsumeParserCache || options == kConsumeCodeCache) { 2071 source->cached_data->rejected = script_data->rejected(); 2072 } 2073 delete script_data; 2074 } 2075 RETURN_ESCAPED(ToApiHandle<UnboundScript>(result)); 2076 } 2077 2078 2079 MaybeLocal<UnboundScript> ScriptCompiler::CompileUnboundScript( 2080 Isolate* v8_isolate, Source* source, CompileOptions options) { 2081 return CompileUnboundInternal(v8_isolate, source, options, false); 2082 } 2083 2084 2085 Local<UnboundScript> ScriptCompiler::CompileUnbound(Isolate* v8_isolate, 2086 Source* source, 2087 CompileOptions options) { 2088 RETURN_TO_LOCAL_UNCHECKED( 2089 CompileUnboundInternal(v8_isolate, source, options, false), 2090 UnboundScript); 2091 } 2092 2093 2094 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context, 2095 Source* source, 2096 CompileOptions options) { 2097 auto isolate = context->GetIsolate(); 2098 auto maybe = CompileUnboundInternal(isolate, source, options, false); 2099 Local<UnboundScript> result; 2100 if (!maybe.ToLocal(&result)) return MaybeLocal<Script>(); 2101 v8::Context::Scope scope(context); 2102 return result->BindToCurrentContext(); 2103 } 2104 2105 2106 Local<Script> ScriptCompiler::Compile( 2107 Isolate* v8_isolate, 2108 Source* source, 2109 CompileOptions options) { 2110 auto context = v8_isolate->GetCurrentContext(); 2111 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, options), Script); 2112 } 2113 2114 MaybeLocal<Module> ScriptCompiler::CompileModule(Isolate* isolate, 2115 Source* source) { 2116 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 2117 2118 auto maybe = CompileUnboundInternal(isolate, source, kNoCompileOptions, true); 2119 Local<UnboundScript> unbound; 2120 if (!maybe.ToLocal(&unbound)) return MaybeLocal<Module>(); 2121 2122 i::Handle<i::SharedFunctionInfo> shared = Utils::OpenHandle(*unbound); 2123 return ToApiHandle<Module>(i_isolate->factory()->NewModule(shared)); 2124 } 2125 2126 2127 class IsIdentifierHelper { 2128 public: 2129 IsIdentifierHelper() : is_identifier_(false), first_char_(true) {} 2130 2131 bool Check(i::String* string) { 2132 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0); 2133 if (cons_string == NULL) return is_identifier_; 2134 // We don't support cons strings here. 2135 return false; 2136 } 2137 void VisitOneByteString(const uint8_t* chars, int length) { 2138 for (int i = 0; i < length; ++i) { 2139 if (first_char_) { 2140 first_char_ = false; 2141 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]); 2142 } else { 2143 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]); 2144 } 2145 } 2146 } 2147 void VisitTwoByteString(const uint16_t* chars, int length) { 2148 for (int i = 0; i < length; ++i) { 2149 if (first_char_) { 2150 first_char_ = false; 2151 is_identifier_ = unicode_cache_.IsIdentifierStart(chars[0]); 2152 } else { 2153 is_identifier_ &= unicode_cache_.IsIdentifierPart(chars[i]); 2154 } 2155 } 2156 } 2157 2158 private: 2159 bool is_identifier_; 2160 bool first_char_; 2161 i::UnicodeCache unicode_cache_; 2162 DISALLOW_COPY_AND_ASSIGN(IsIdentifierHelper); 2163 }; 2164 2165 2166 MaybeLocal<Function> ScriptCompiler::CompileFunctionInContext( 2167 Local<Context> v8_context, Source* source, size_t arguments_count, 2168 Local<String> arguments[], size_t context_extension_count, 2169 Local<Object> context_extensions[]) { 2170 PREPARE_FOR_EXECUTION(v8_context, ScriptCompiler, CompileFunctionInContext, 2171 Function); 2172 TRACE_EVENT0("v8", "V8.ScriptCompiler"); 2173 i::Handle<i::String> source_string; 2174 auto factory = isolate->factory(); 2175 if (arguments_count) { 2176 source_string = factory->NewStringFromStaticChars("(function("); 2177 for (size_t i = 0; i < arguments_count; ++i) { 2178 IsIdentifierHelper helper; 2179 if (!helper.Check(*Utils::OpenHandle(*arguments[i]))) { 2180 return Local<Function>(); 2181 } 2182 has_pending_exception = 2183 !factory->NewConsString(source_string, 2184 Utils::OpenHandle(*arguments[i])) 2185 .ToHandle(&source_string); 2186 RETURN_ON_FAILED_EXECUTION(Function); 2187 if (i + 1 == arguments_count) continue; 2188 has_pending_exception = 2189 !factory->NewConsString(source_string, 2190 factory->LookupSingleCharacterStringFromCode( 2191 ',')).ToHandle(&source_string); 2192 RETURN_ON_FAILED_EXECUTION(Function); 2193 } 2194 auto brackets = factory->NewStringFromStaticChars("){"); 2195 has_pending_exception = !factory->NewConsString(source_string, brackets) 2196 .ToHandle(&source_string); 2197 RETURN_ON_FAILED_EXECUTION(Function); 2198 } else { 2199 source_string = factory->NewStringFromStaticChars("(function(){"); 2200 } 2201 2202 int scope_position = source_string->length(); 2203 has_pending_exception = 2204 !factory->NewConsString(source_string, 2205 Utils::OpenHandle(*source->source_string)) 2206 .ToHandle(&source_string); 2207 RETURN_ON_FAILED_EXECUTION(Function); 2208 // Include \n in case the source contains a line end comment. 2209 auto brackets = factory->NewStringFromStaticChars("\n})"); 2210 has_pending_exception = 2211 !factory->NewConsString(source_string, brackets).ToHandle(&source_string); 2212 RETURN_ON_FAILED_EXECUTION(Function); 2213 2214 i::Handle<i::Context> context = Utils::OpenHandle(*v8_context); 2215 i::Handle<i::SharedFunctionInfo> outer_info(context->closure()->shared(), 2216 isolate); 2217 for (size_t i = 0; i < context_extension_count; ++i) { 2218 i::Handle<i::JSReceiver> extension = 2219 Utils::OpenHandle(*context_extensions[i]); 2220 if (!extension->IsJSObject()) return Local<Function>(); 2221 i::Handle<i::JSFunction> closure(context->closure(), isolate); 2222 context = factory->NewWithContext( 2223 closure, context, 2224 i::ScopeInfo::CreateForWithScope( 2225 isolate, context->IsNativeContext() 2226 ? i::Handle<i::ScopeInfo>::null() 2227 : i::Handle<i::ScopeInfo>(context->scope_info())), 2228 extension); 2229 } 2230 2231 i::Handle<i::Object> name_obj; 2232 int eval_scope_position = 0; 2233 int eval_position = i::kNoSourcePosition; 2234 int line_offset = 0; 2235 int column_offset = 0; 2236 if (!source->resource_name.IsEmpty()) { 2237 name_obj = Utils::OpenHandle(*(source->resource_name)); 2238 } 2239 if (!source->resource_line_offset.IsEmpty()) { 2240 line_offset = static_cast<int>(source->resource_line_offset->Value()); 2241 } 2242 if (!source->resource_column_offset.IsEmpty()) { 2243 column_offset = static_cast<int>(source->resource_column_offset->Value()); 2244 } 2245 i::Handle<i::JSFunction> fun; 2246 has_pending_exception = 2247 !i::Compiler::GetFunctionFromEval( 2248 source_string, outer_info, context, i::SLOPPY, 2249 i::ONLY_SINGLE_FUNCTION_LITERAL, eval_scope_position, eval_position, 2250 line_offset, column_offset - scope_position, name_obj, 2251 source->resource_options) 2252 .ToHandle(&fun); 2253 if (has_pending_exception) { 2254 isolate->ReportPendingMessages(); 2255 } 2256 RETURN_ON_FAILED_EXECUTION(Function); 2257 2258 i::Handle<i::Object> result; 2259 has_pending_exception = 2260 !i::Execution::Call(isolate, fun, 2261 Utils::OpenHandle(*v8_context->Global()), 0, 2262 nullptr).ToHandle(&result); 2263 RETURN_ON_FAILED_EXECUTION(Function); 2264 RETURN_ESCAPED( 2265 Utils::CallableToLocal(i::Handle<i::JSFunction>::cast(result))); 2266 } 2267 2268 2269 Local<Function> ScriptCompiler::CompileFunctionInContext( 2270 Isolate* v8_isolate, Source* source, Local<Context> v8_context, 2271 size_t arguments_count, Local<String> arguments[], 2272 size_t context_extension_count, Local<Object> context_extensions[]) { 2273 RETURN_TO_LOCAL_UNCHECKED( 2274 CompileFunctionInContext(v8_context, source, arguments_count, arguments, 2275 context_extension_count, context_extensions), 2276 Function); 2277 } 2278 2279 2280 ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript( 2281 Isolate* v8_isolate, StreamedSource* source, CompileOptions options) { 2282 if (!i::FLAG_script_streaming) { 2283 return nullptr; 2284 } 2285 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 2286 return new i::BackgroundParsingTask(source->impl(), options, 2287 i::FLAG_stack_size, isolate); 2288 } 2289 2290 2291 MaybeLocal<Script> ScriptCompiler::Compile(Local<Context> context, 2292 StreamedSource* v8_source, 2293 Local<String> full_source_string, 2294 const ScriptOrigin& origin) { 2295 PREPARE_FOR_EXECUTION(context, ScriptCompiler, Compile, Script); 2296 TRACE_EVENT0("v8", "V8.ScriptCompiler"); 2297 i::StreamedSource* source = v8_source->impl(); 2298 i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string)); 2299 i::Handle<i::Script> script = isolate->factory()->NewScript(str); 2300 if (!origin.ResourceName().IsEmpty()) { 2301 script->set_name(*Utils::OpenHandle(*(origin.ResourceName()))); 2302 } 2303 if (!origin.ResourceLineOffset().IsEmpty()) { 2304 script->set_line_offset( 2305 static_cast<int>(origin.ResourceLineOffset()->Value())); 2306 } 2307 if (!origin.ResourceColumnOffset().IsEmpty()) { 2308 script->set_column_offset( 2309 static_cast<int>(origin.ResourceColumnOffset()->Value())); 2310 } 2311 script->set_origin_options(origin.Options()); 2312 if (!origin.SourceMapUrl().IsEmpty()) { 2313 script->set_source_mapping_url( 2314 *Utils::OpenHandle(*(origin.SourceMapUrl()))); 2315 } 2316 2317 source->info->set_script(script); 2318 2319 // Do the parsing tasks which need to be done on the main thread. This will 2320 // also handle parse errors. 2321 source->parser->Internalize(isolate, script, 2322 source->info->literal() == nullptr); 2323 source->parser->HandleSourceURLComments(isolate, script); 2324 2325 i::Handle<i::SharedFunctionInfo> result; 2326 if (source->info->literal() != nullptr) { 2327 // Parsing has succeeded. 2328 result = i::Compiler::GetSharedFunctionInfoForStreamedScript( 2329 script, source->info.get(), str->length()); 2330 } 2331 has_pending_exception = result.is_null(); 2332 if (has_pending_exception) isolate->ReportPendingMessages(); 2333 2334 source->Release(); 2335 2336 RETURN_ON_FAILED_EXECUTION(Script); 2337 2338 Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result); 2339 if (generic.IsEmpty()) return Local<Script>(); 2340 Local<Script> bound = generic->BindToCurrentContext(); 2341 if (bound.IsEmpty()) return Local<Script>(); 2342 RETURN_ESCAPED(bound); 2343 } 2344 2345 2346 Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate, 2347 StreamedSource* v8_source, 2348 Local<String> full_source_string, 2349 const ScriptOrigin& origin) { 2350 auto context = v8_isolate->GetCurrentContext(); 2351 RETURN_TO_LOCAL_UNCHECKED( 2352 Compile(context, v8_source, full_source_string, origin), Script); 2353 } 2354 2355 2356 uint32_t ScriptCompiler::CachedDataVersionTag() { 2357 return static_cast<uint32_t>(base::hash_combine( 2358 internal::Version::Hash(), internal::FlagList::Hash(), 2359 static_cast<uint32_t>(internal::CpuFeatures::SupportedFeatures()))); 2360 } 2361 2362 2363 MaybeLocal<Script> Script::Compile(Local<Context> context, Local<String> source, 2364 ScriptOrigin* origin) { 2365 if (origin) { 2366 ScriptCompiler::Source script_source(source, *origin); 2367 return ScriptCompiler::Compile(context, &script_source); 2368 } 2369 ScriptCompiler::Source script_source(source); 2370 return ScriptCompiler::Compile(context, &script_source); 2371 } 2372 2373 2374 Local<Script> Script::Compile(v8::Local<String> source, 2375 v8::ScriptOrigin* origin) { 2376 auto str = Utils::OpenHandle(*source); 2377 auto context = ContextFromHeapObject(str); 2378 RETURN_TO_LOCAL_UNCHECKED(Compile(context, source, origin), Script); 2379 } 2380 2381 2382 Local<Script> Script::Compile(v8::Local<String> source, 2383 v8::Local<String> file_name) { 2384 auto str = Utils::OpenHandle(*source); 2385 auto context = ContextFromHeapObject(str); 2386 ScriptOrigin origin(file_name); 2387 return Compile(context, source, &origin).FromMaybe(Local<Script>()); 2388 } 2389 2390 2391 // --- E x c e p t i o n s --- 2392 2393 2394 v8::TryCatch::TryCatch() 2395 : isolate_(i::Isolate::Current()), 2396 next_(isolate_->try_catch_handler()), 2397 is_verbose_(false), 2398 can_continue_(true), 2399 capture_message_(true), 2400 rethrow_(false), 2401 has_terminated_(false) { 2402 ResetInternal(); 2403 // Special handling for simulators which have a separate JS stack. 2404 js_stack_comparable_address_ = 2405 reinterpret_cast<void*>(i::SimulatorStack::RegisterCTryCatch( 2406 isolate_, i::GetCurrentStackPosition())); 2407 isolate_->RegisterTryCatchHandler(this); 2408 } 2409 2410 2411 v8::TryCatch::TryCatch(v8::Isolate* isolate) 2412 : isolate_(reinterpret_cast<i::Isolate*>(isolate)), 2413 next_(isolate_->try_catch_handler()), 2414 is_verbose_(false), 2415 can_continue_(true), 2416 capture_message_(true), 2417 rethrow_(false), 2418 has_terminated_(false) { 2419 ResetInternal(); 2420 // Special handling for simulators which have a separate JS stack. 2421 js_stack_comparable_address_ = 2422 reinterpret_cast<void*>(i::SimulatorStack::RegisterCTryCatch( 2423 isolate_, i::GetCurrentStackPosition())); 2424 isolate_->RegisterTryCatchHandler(this); 2425 } 2426 2427 2428 v8::TryCatch::~TryCatch() { 2429 if (rethrow_) { 2430 v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_); 2431 v8::HandleScope scope(isolate); 2432 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception()); 2433 if (HasCaught() && capture_message_) { 2434 // If an exception was caught and rethrow_ is indicated, the saved 2435 // message, script, and location need to be restored to Isolate TLS 2436 // for reuse. capture_message_ needs to be disabled so that Throw() 2437 // does not create a new message. 2438 isolate_->thread_local_top()->rethrowing_message_ = true; 2439 isolate_->RestorePendingMessageFromTryCatch(this); 2440 } 2441 isolate_->UnregisterTryCatchHandler(this); 2442 i::SimulatorStack::UnregisterCTryCatch(isolate_); 2443 reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc); 2444 DCHECK(!isolate_->thread_local_top()->rethrowing_message_); 2445 } else { 2446 if (HasCaught() && isolate_->has_scheduled_exception()) { 2447 // If an exception was caught but is still scheduled because no API call 2448 // promoted it, then it is canceled to prevent it from being propagated. 2449 // Note that this will not cancel termination exceptions. 2450 isolate_->CancelScheduledExceptionFromTryCatch(this); 2451 } 2452 isolate_->UnregisterTryCatchHandler(this); 2453 i::SimulatorStack::UnregisterCTryCatch(isolate_); 2454 } 2455 } 2456 2457 2458 bool v8::TryCatch::HasCaught() const { 2459 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole(isolate_); 2460 } 2461 2462 2463 bool v8::TryCatch::CanContinue() const { 2464 return can_continue_; 2465 } 2466 2467 2468 bool v8::TryCatch::HasTerminated() const { 2469 return has_terminated_; 2470 } 2471 2472 2473 v8::Local<v8::Value> v8::TryCatch::ReThrow() { 2474 if (!HasCaught()) return v8::Local<v8::Value>(); 2475 rethrow_ = true; 2476 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_)); 2477 } 2478 2479 2480 v8::Local<Value> v8::TryCatch::Exception() const { 2481 if (HasCaught()) { 2482 // Check for out of memory exception. 2483 i::Object* exception = reinterpret_cast<i::Object*>(exception_); 2484 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_)); 2485 } else { 2486 return v8::Local<Value>(); 2487 } 2488 } 2489 2490 2491 MaybeLocal<Value> v8::TryCatch::StackTrace(Local<Context> context) const { 2492 if (!HasCaught()) return v8::Local<Value>(); 2493 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_); 2494 if (!raw_obj->IsJSObject()) return v8::Local<Value>(); 2495 PREPARE_FOR_EXECUTION(context, TryCatch, StackTrace, Value); 2496 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_); 2497 i::Handle<i::String> name = isolate->factory()->stack_string(); 2498 Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name); 2499 has_pending_exception = !maybe.IsJust(); 2500 RETURN_ON_FAILED_EXECUTION(Value); 2501 if (!maybe.FromJust()) return v8::Local<Value>(); 2502 Local<Value> result; 2503 has_pending_exception = 2504 !ToLocal<Value>(i::JSReceiver::GetProperty(obj, name), &result); 2505 RETURN_ON_FAILED_EXECUTION(Value); 2506 RETURN_ESCAPED(result); 2507 } 2508 2509 2510 v8::Local<Value> v8::TryCatch::StackTrace() const { 2511 auto context = reinterpret_cast<v8::Isolate*>(isolate_)->GetCurrentContext(); 2512 RETURN_TO_LOCAL_UNCHECKED(StackTrace(context), Value); 2513 } 2514 2515 2516 v8::Local<v8::Message> v8::TryCatch::Message() const { 2517 i::Object* message = reinterpret_cast<i::Object*>(message_obj_); 2518 DCHECK(message->IsJSMessageObject() || message->IsTheHole(isolate_)); 2519 if (HasCaught() && !message->IsTheHole(isolate_)) { 2520 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_)); 2521 } else { 2522 return v8::Local<v8::Message>(); 2523 } 2524 } 2525 2526 2527 void v8::TryCatch::Reset() { 2528 if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) { 2529 // If an exception was caught but is still scheduled because no API call 2530 // promoted it, then it is canceled to prevent it from being propagated. 2531 // Note that this will not cancel termination exceptions. 2532 isolate_->CancelScheduledExceptionFromTryCatch(this); 2533 } 2534 ResetInternal(); 2535 } 2536 2537 2538 void v8::TryCatch::ResetInternal() { 2539 i::Object* the_hole = isolate_->heap()->the_hole_value(); 2540 exception_ = the_hole; 2541 message_obj_ = the_hole; 2542 } 2543 2544 2545 void v8::TryCatch::SetVerbose(bool value) { 2546 is_verbose_ = value; 2547 } 2548 2549 2550 void v8::TryCatch::SetCaptureMessage(bool value) { 2551 capture_message_ = value; 2552 } 2553 2554 2555 // --- M e s s a g e --- 2556 2557 2558 Local<String> Message::Get() const { 2559 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2560 ENTER_V8(isolate); 2561 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); 2562 i::Handle<i::Object> obj = Utils::OpenHandle(this); 2563 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj); 2564 Local<String> result = Utils::ToLocal(raw_result); 2565 return scope.Escape(result); 2566 } 2567 2568 2569 ScriptOrigin Message::GetScriptOrigin() const { 2570 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2571 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this)); 2572 auto script_wraper = i::Handle<i::Object>(message->script(), isolate); 2573 auto script_value = i::Handle<i::JSValue>::cast(script_wraper); 2574 i::Handle<i::Script> script(i::Script::cast(script_value->value())); 2575 return GetScriptOriginForScript(isolate, script); 2576 } 2577 2578 2579 v8::Local<Value> Message::GetScriptResourceName() const { 2580 return GetScriptOrigin().ResourceName(); 2581 } 2582 2583 2584 v8::Local<v8::StackTrace> Message::GetStackTrace() const { 2585 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2586 ENTER_V8(isolate); 2587 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); 2588 auto message = i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this)); 2589 i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate); 2590 if (!stackFramesObj->IsJSArray()) return v8::Local<v8::StackTrace>(); 2591 auto stackTrace = i::Handle<i::JSArray>::cast(stackFramesObj); 2592 return scope.Escape(Utils::StackTraceToLocal(stackTrace)); 2593 } 2594 2595 2596 Maybe<int> Message::GetLineNumber(Local<Context> context) const { 2597 auto self = Utils::OpenHandle(this); 2598 i::Isolate* isolate = self->GetIsolate(); 2599 ENTER_V8(isolate); 2600 EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate)); 2601 auto msg = i::Handle<i::JSMessageObject>::cast(self); 2602 return Just(msg->GetLineNumber()); 2603 } 2604 2605 2606 int Message::GetLineNumber() const { 2607 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 2608 return GetLineNumber(context).FromMaybe(0); 2609 } 2610 2611 2612 int Message::GetStartPosition() const { 2613 auto self = Utils::OpenHandle(this); 2614 return self->start_position(); 2615 } 2616 2617 2618 int Message::GetEndPosition() const { 2619 auto self = Utils::OpenHandle(this); 2620 return self->end_position(); 2621 } 2622 2623 2624 Maybe<int> Message::GetStartColumn(Local<Context> context) const { 2625 auto self = Utils::OpenHandle(this); 2626 i::Isolate* isolate = self->GetIsolate(); 2627 ENTER_V8(isolate); 2628 EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate)); 2629 auto msg = i::Handle<i::JSMessageObject>::cast(self); 2630 return Just(msg->GetColumnNumber()); 2631 } 2632 2633 2634 int Message::GetStartColumn() const { 2635 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 2636 const int default_value = kNoColumnInfo; 2637 return GetStartColumn(context).FromMaybe(default_value); 2638 } 2639 2640 2641 Maybe<int> Message::GetEndColumn(Local<Context> context) const { 2642 auto self = Utils::OpenHandle(this); 2643 i::Isolate* isolate = self->GetIsolate(); 2644 ENTER_V8(isolate); 2645 EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate)); 2646 auto msg = i::Handle<i::JSMessageObject>::cast(self); 2647 const int column_number = msg->GetColumnNumber(); 2648 if (column_number == -1) return Just(-1); 2649 const int start = self->start_position(); 2650 const int end = self->end_position(); 2651 return Just(column_number + (end - start)); 2652 } 2653 2654 2655 int Message::GetEndColumn() const { 2656 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 2657 const int default_value = kNoColumnInfo; 2658 return GetEndColumn(context).FromMaybe(default_value); 2659 } 2660 2661 2662 bool Message::IsSharedCrossOrigin() const { 2663 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2664 ENTER_V8(isolate); 2665 auto self = Utils::OpenHandle(this); 2666 auto script = i::Handle<i::JSValue>::cast( 2667 i::Handle<i::Object>(self->script(), isolate)); 2668 return i::Script::cast(script->value()) 2669 ->origin_options() 2670 .IsSharedCrossOrigin(); 2671 } 2672 2673 bool Message::IsOpaque() const { 2674 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2675 ENTER_V8(isolate); 2676 auto self = Utils::OpenHandle(this); 2677 auto script = i::Handle<i::JSValue>::cast( 2678 i::Handle<i::Object>(self->script(), isolate)); 2679 return i::Script::cast(script->value())->origin_options().IsOpaque(); 2680 } 2681 2682 2683 MaybeLocal<String> Message::GetSourceLine(Local<Context> context) const { 2684 auto self = Utils::OpenHandle(this); 2685 i::Isolate* isolate = self->GetIsolate(); 2686 ENTER_V8(isolate); 2687 EscapableHandleScope handle_scope(reinterpret_cast<Isolate*>(isolate)); 2688 auto msg = i::Handle<i::JSMessageObject>::cast(self); 2689 RETURN_ESCAPED(Utils::ToLocal(msg->GetSourceLine())); 2690 } 2691 2692 2693 Local<String> Message::GetSourceLine() const { 2694 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 2695 RETURN_TO_LOCAL_UNCHECKED(GetSourceLine(context), String) 2696 } 2697 2698 2699 void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) { 2700 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 2701 ENTER_V8(i_isolate); 2702 i_isolate->PrintCurrentStackTrace(out); 2703 } 2704 2705 2706 // --- S t a c k T r a c e --- 2707 2708 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const { 2709 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 2710 ENTER_V8(isolate); 2711 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); 2712 auto self = Utils::OpenHandle(this); 2713 auto obj = i::JSReceiver::GetElement(isolate, self, index).ToHandleChecked(); 2714 auto jsobj = i::Handle<i::JSObject>::cast(obj); 2715 return scope.Escape(Utils::StackFrameToLocal(jsobj)); 2716 } 2717 2718 2719 int StackTrace::GetFrameCount() const { 2720 return i::Smi::cast(Utils::OpenHandle(this)->length())->value(); 2721 } 2722 2723 2724 Local<Array> StackTrace::AsArray() { 2725 return Utils::ToLocal(Utils::OpenHandle(this)); 2726 } 2727 2728 2729 Local<StackTrace> StackTrace::CurrentStackTrace( 2730 Isolate* isolate, 2731 int frame_limit, 2732 StackTraceOptions options) { 2733 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 2734 ENTER_V8(i_isolate); 2735 // TODO(dcarney): remove when ScriptDebugServer is fixed. 2736 options = static_cast<StackTraceOptions>( 2737 static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins); 2738 i::Handle<i::JSArray> stackTrace = 2739 i_isolate->CaptureCurrentStackTrace(frame_limit, options); 2740 return Utils::StackTraceToLocal(stackTrace); 2741 } 2742 2743 2744 // --- S t a c k F r a m e --- 2745 2746 static int getIntProperty(const StackFrame* f, const char* propertyName, 2747 int defaultValue) { 2748 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate(); 2749 ENTER_V8(isolate); 2750 i::HandleScope scope(isolate); 2751 i::Handle<i::JSObject> self = Utils::OpenHandle(f); 2752 i::Handle<i::Object> obj = 2753 i::JSReceiver::GetProperty(isolate, self, propertyName).ToHandleChecked(); 2754 return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue; 2755 } 2756 2757 2758 int StackFrame::GetLineNumber() const { 2759 return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo); 2760 } 2761 2762 2763 int StackFrame::GetColumn() const { 2764 return getIntProperty(this, "column", Message::kNoColumnInfo); 2765 } 2766 2767 2768 int StackFrame::GetScriptId() const { 2769 return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo); 2770 } 2771 2772 2773 static Local<String> getStringProperty(const StackFrame* f, 2774 const char* propertyName) { 2775 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate(); 2776 ENTER_V8(isolate); 2777 EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate)); 2778 i::Handle<i::JSObject> self = Utils::OpenHandle(f); 2779 i::Handle<i::Object> obj = 2780 i::JSReceiver::GetProperty(isolate, self, propertyName).ToHandleChecked(); 2781 return obj->IsString() 2782 ? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj))) 2783 : Local<String>(); 2784 } 2785 2786 2787 Local<String> StackFrame::GetScriptName() const { 2788 return getStringProperty(this, "scriptName"); 2789 } 2790 2791 2792 Local<String> StackFrame::GetScriptNameOrSourceURL() const { 2793 return getStringProperty(this, "scriptNameOrSourceURL"); 2794 } 2795 2796 2797 Local<String> StackFrame::GetFunctionName() const { 2798 return getStringProperty(this, "functionName"); 2799 } 2800 2801 2802 static bool getBoolProperty(const StackFrame* f, const char* propertyName) { 2803 i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate(); 2804 ENTER_V8(isolate); 2805 i::HandleScope scope(isolate); 2806 i::Handle<i::JSObject> self = Utils::OpenHandle(f); 2807 i::Handle<i::Object> obj = 2808 i::JSReceiver::GetProperty(isolate, self, propertyName).ToHandleChecked(); 2809 return obj->IsTrue(isolate); 2810 } 2811 2812 bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); } 2813 2814 2815 bool StackFrame::IsConstructor() const { 2816 return getBoolProperty(this, "isConstructor"); 2817 } 2818 2819 2820 // --- N a t i v e W e a k M a p --- 2821 2822 Local<NativeWeakMap> NativeWeakMap::New(Isolate* v8_isolate) { 2823 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 2824 ENTER_V8(isolate); 2825 i::Handle<i::JSWeakMap> weakmap = isolate->factory()->NewJSWeakMap(); 2826 i::JSWeakCollection::Initialize(weakmap, isolate); 2827 return Utils::NativeWeakMapToLocal(weakmap); 2828 } 2829 2830 2831 void NativeWeakMap::Set(Local<Value> v8_key, Local<Value> v8_value) { 2832 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this); 2833 i::Isolate* isolate = weak_collection->GetIsolate(); 2834 ENTER_V8(isolate); 2835 i::HandleScope scope(isolate); 2836 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key); 2837 i::Handle<i::Object> value = Utils::OpenHandle(*v8_value); 2838 if (!key->IsJSReceiver() && !key->IsSymbol()) { 2839 DCHECK(false); 2840 return; 2841 } 2842 i::Handle<i::ObjectHashTable> table( 2843 i::ObjectHashTable::cast(weak_collection->table())); 2844 if (!table->IsKey(isolate, *key)) { 2845 DCHECK(false); 2846 return; 2847 } 2848 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value(); 2849 i::JSWeakCollection::Set(weak_collection, key, value, hash); 2850 } 2851 2852 2853 Local<Value> NativeWeakMap::Get(Local<Value> v8_key) { 2854 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this); 2855 i::Isolate* isolate = weak_collection->GetIsolate(); 2856 ENTER_V8(isolate); 2857 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key); 2858 if (!key->IsJSReceiver() && !key->IsSymbol()) { 2859 DCHECK(false); 2860 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 2861 } 2862 i::Handle<i::ObjectHashTable> table( 2863 i::ObjectHashTable::cast(weak_collection->table())); 2864 if (!table->IsKey(isolate, *key)) { 2865 DCHECK(false); 2866 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 2867 } 2868 i::Handle<i::Object> lookup(table->Lookup(key), isolate); 2869 if (lookup->IsTheHole(isolate)) 2870 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 2871 return Utils::ToLocal(lookup); 2872 } 2873 2874 2875 bool NativeWeakMap::Has(Local<Value> v8_key) { 2876 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this); 2877 i::Isolate* isolate = weak_collection->GetIsolate(); 2878 ENTER_V8(isolate); 2879 i::HandleScope scope(isolate); 2880 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key); 2881 if (!key->IsJSReceiver() && !key->IsSymbol()) { 2882 DCHECK(false); 2883 return false; 2884 } 2885 i::Handle<i::ObjectHashTable> table( 2886 i::ObjectHashTable::cast(weak_collection->table())); 2887 if (!table->IsKey(isolate, *key)) { 2888 DCHECK(false); 2889 return false; 2890 } 2891 i::Handle<i::Object> lookup(table->Lookup(key), isolate); 2892 return !lookup->IsTheHole(isolate); 2893 } 2894 2895 2896 bool NativeWeakMap::Delete(Local<Value> v8_key) { 2897 i::Handle<i::JSWeakMap> weak_collection = Utils::OpenHandle(this); 2898 i::Isolate* isolate = weak_collection->GetIsolate(); 2899 ENTER_V8(isolate); 2900 i::HandleScope scope(isolate); 2901 i::Handle<i::Object> key = Utils::OpenHandle(*v8_key); 2902 if (!key->IsJSReceiver() && !key->IsSymbol()) { 2903 DCHECK(false); 2904 return false; 2905 } 2906 i::Handle<i::ObjectHashTable> table( 2907 i::ObjectHashTable::cast(weak_collection->table())); 2908 if (!table->IsKey(isolate, *key)) { 2909 DCHECK(false); 2910 return false; 2911 } 2912 int32_t hash = i::Object::GetOrCreateHash(isolate, key)->value(); 2913 return i::JSWeakCollection::Delete(weak_collection, key, hash); 2914 } 2915 2916 2917 // --- J S O N --- 2918 2919 MaybeLocal<Value> JSON::Parse(Isolate* v8_isolate, Local<String> json_string) { 2920 auto isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 2921 PREPARE_FOR_EXECUTION_WITH_ISOLATE(isolate, JSON, Parse, Value); 2922 i::Handle<i::String> string = Utils::OpenHandle(*json_string); 2923 i::Handle<i::String> source = i::String::Flatten(string); 2924 i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); 2925 auto maybe = source->IsSeqOneByteString() 2926 ? i::JsonParser<true>::Parse(isolate, source, undefined) 2927 : i::JsonParser<false>::Parse(isolate, source, undefined); 2928 Local<Value> result; 2929 has_pending_exception = !ToLocal<Value>(maybe, &result); 2930 RETURN_ON_FAILED_EXECUTION(Value); 2931 RETURN_ESCAPED(result); 2932 } 2933 2934 MaybeLocal<Value> JSON::Parse(Local<Context> context, 2935 Local<String> json_string) { 2936 PREPARE_FOR_EXECUTION(context, JSON, Parse, Value); 2937 i::Handle<i::String> string = Utils::OpenHandle(*json_string); 2938 i::Handle<i::String> source = i::String::Flatten(string); 2939 i::Handle<i::Object> undefined = isolate->factory()->undefined_value(); 2940 auto maybe = source->IsSeqOneByteString() 2941 ? i::JsonParser<true>::Parse(isolate, source, undefined) 2942 : i::JsonParser<false>::Parse(isolate, source, undefined); 2943 Local<Value> result; 2944 has_pending_exception = !ToLocal<Value>(maybe, &result); 2945 RETURN_ON_FAILED_EXECUTION(Value); 2946 RETURN_ESCAPED(result); 2947 } 2948 2949 Local<Value> JSON::Parse(Local<String> json_string) { 2950 RETURN_TO_LOCAL_UNCHECKED(Parse(Local<Context>(), json_string), Value); 2951 } 2952 2953 MaybeLocal<String> JSON::Stringify(Local<Context> context, 2954 Local<Object> json_object, 2955 Local<String> gap) { 2956 PREPARE_FOR_EXECUTION(context, JSON, Stringify, String); 2957 i::Handle<i::Object> object = Utils::OpenHandle(*json_object); 2958 i::Handle<i::Object> replacer = isolate->factory()->undefined_value(); 2959 i::Handle<i::String> gap_string = gap.IsEmpty() 2960 ? isolate->factory()->empty_string() 2961 : Utils::OpenHandle(*gap); 2962 i::Handle<i::Object> maybe; 2963 has_pending_exception = !i::JsonStringifier(isolate) 2964 .Stringify(object, replacer, gap_string) 2965 .ToHandle(&maybe); 2966 RETURN_ON_FAILED_EXECUTION(String); 2967 Local<String> result; 2968 has_pending_exception = 2969 !ToLocal<String>(i::Object::ToString(isolate, maybe), &result); 2970 RETURN_ON_FAILED_EXECUTION(String); 2971 RETURN_ESCAPED(result); 2972 } 2973 2974 // --- V a l u e S e r i a l i z a t i o n --- 2975 2976 Maybe<bool> ValueSerializer::Delegate::WriteHostObject(Isolate* v8_isolate, 2977 Local<Object> object) { 2978 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 2979 isolate->ScheduleThrow(*isolate->factory()->NewError( 2980 isolate->error_function(), i::MessageTemplate::kDataCloneError, 2981 Utils::OpenHandle(*object))); 2982 return Nothing<bool>(); 2983 } 2984 2985 void* ValueSerializer::Delegate::ReallocateBufferMemory(void* old_buffer, 2986 size_t size, 2987 size_t* actual_size) { 2988 *actual_size = size; 2989 return realloc(old_buffer, size); 2990 } 2991 2992 void ValueSerializer::Delegate::FreeBufferMemory(void* buffer) { 2993 return free(buffer); 2994 } 2995 2996 struct ValueSerializer::PrivateData { 2997 explicit PrivateData(i::Isolate* i, ValueSerializer::Delegate* delegate) 2998 : isolate(i), serializer(i, delegate) {} 2999 i::Isolate* isolate; 3000 i::ValueSerializer serializer; 3001 }; 3002 3003 ValueSerializer::ValueSerializer(Isolate* isolate) 3004 : ValueSerializer(isolate, nullptr) {} 3005 3006 ValueSerializer::ValueSerializer(Isolate* isolate, Delegate* delegate) 3007 : private_( 3008 new PrivateData(reinterpret_cast<i::Isolate*>(isolate), delegate)) {} 3009 3010 ValueSerializer::~ValueSerializer() { delete private_; } 3011 3012 void ValueSerializer::WriteHeader() { private_->serializer.WriteHeader(); } 3013 3014 Maybe<bool> ValueSerializer::WriteValue(Local<Context> context, 3015 Local<Value> value) { 3016 PREPARE_FOR_EXECUTION_PRIMITIVE(context, ValueSerializer, WriteValue, bool); 3017 i::Handle<i::Object> object = Utils::OpenHandle(*value); 3018 Maybe<bool> result = private_->serializer.WriteObject(object); 3019 has_pending_exception = result.IsNothing(); 3020 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3021 return result; 3022 } 3023 3024 std::vector<uint8_t> ValueSerializer::ReleaseBuffer() { 3025 return private_->serializer.ReleaseBuffer(); 3026 } 3027 3028 std::pair<uint8_t*, size_t> ValueSerializer::Release() { 3029 return private_->serializer.Release(); 3030 } 3031 3032 void ValueSerializer::TransferArrayBuffer(uint32_t transfer_id, 3033 Local<ArrayBuffer> array_buffer) { 3034 private_->serializer.TransferArrayBuffer(transfer_id, 3035 Utils::OpenHandle(*array_buffer)); 3036 } 3037 3038 void ValueSerializer::TransferSharedArrayBuffer( 3039 uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) { 3040 private_->serializer.TransferArrayBuffer( 3041 transfer_id, Utils::OpenHandle(*shared_array_buffer)); 3042 } 3043 3044 void ValueSerializer::WriteUint32(uint32_t value) { 3045 private_->serializer.WriteUint32(value); 3046 } 3047 3048 void ValueSerializer::WriteUint64(uint64_t value) { 3049 private_->serializer.WriteUint64(value); 3050 } 3051 3052 void ValueSerializer::WriteDouble(double value) { 3053 private_->serializer.WriteDouble(value); 3054 } 3055 3056 void ValueSerializer::WriteRawBytes(const void* source, size_t length) { 3057 private_->serializer.WriteRawBytes(source, length); 3058 } 3059 3060 MaybeLocal<Object> ValueDeserializer::Delegate::ReadHostObject( 3061 Isolate* v8_isolate) { 3062 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 3063 isolate->ScheduleThrow(*isolate->factory()->NewError( 3064 isolate->error_function(), 3065 i::MessageTemplate::kDataCloneDeserializationError)); 3066 return MaybeLocal<Object>(); 3067 } 3068 3069 struct ValueDeserializer::PrivateData { 3070 PrivateData(i::Isolate* i, i::Vector<const uint8_t> data, Delegate* delegate) 3071 : isolate(i), deserializer(i, data, delegate) {} 3072 i::Isolate* isolate; 3073 i::ValueDeserializer deserializer; 3074 bool has_aborted = false; 3075 bool supports_legacy_wire_format = false; 3076 }; 3077 3078 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data, 3079 size_t size) 3080 : ValueDeserializer(isolate, data, size, nullptr) {} 3081 3082 ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data, 3083 size_t size, Delegate* delegate) { 3084 if (base::IsValueInRangeForNumericType<int>(size)) { 3085 private_ = new PrivateData( 3086 reinterpret_cast<i::Isolate*>(isolate), 3087 i::Vector<const uint8_t>(data, static_cast<int>(size)), delegate); 3088 } else { 3089 private_ = new PrivateData(reinterpret_cast<i::Isolate*>(isolate), 3090 i::Vector<const uint8_t>(nullptr, 0), nullptr); 3091 private_->has_aborted = true; 3092 } 3093 } 3094 3095 ValueDeserializer::~ValueDeserializer() { delete private_; } 3096 3097 Maybe<bool> ValueDeserializer::ReadHeader(Local<Context> context) { 3098 PREPARE_FOR_EXECUTION_PRIMITIVE(context, ValueDeserializer, ReadHeader, bool); 3099 3100 // We could have aborted during the constructor. 3101 // If so, ReadHeader is where we report it. 3102 if (private_->has_aborted) { 3103 isolate->Throw(*isolate->factory()->NewError( 3104 i::MessageTemplate::kDataCloneDeserializationError)); 3105 has_pending_exception = true; 3106 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3107 } 3108 3109 bool read_header = false; 3110 has_pending_exception = !private_->deserializer.ReadHeader().To(&read_header); 3111 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3112 DCHECK(read_header); 3113 3114 // TODO(jbroman): Today, all wire formats are "legacy". When a more supported 3115 // format is added, compare the version of the internal serializer to the 3116 // minimum non-legacy version number. 3117 if (!private_->supports_legacy_wire_format) { 3118 isolate->Throw(*isolate->factory()->NewError( 3119 i::MessageTemplate::kDataCloneDeserializationVersionError)); 3120 has_pending_exception = true; 3121 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3122 } 3123 3124 return Just(true); 3125 } 3126 3127 void ValueDeserializer::SetSupportsLegacyWireFormat( 3128 bool supports_legacy_wire_format) { 3129 private_->supports_legacy_wire_format = supports_legacy_wire_format; 3130 } 3131 3132 uint32_t ValueDeserializer::GetWireFormatVersion() const { 3133 CHECK(!private_->has_aborted); 3134 return private_->deserializer.GetWireFormatVersion(); 3135 } 3136 3137 MaybeLocal<Value> ValueDeserializer::ReadValue(Local<Context> context) { 3138 CHECK(!private_->has_aborted); 3139 PREPARE_FOR_EXECUTION(context, ValueDeserializer, ReadValue, Value); 3140 i::MaybeHandle<i::Object> result; 3141 if (GetWireFormatVersion() > 0) { 3142 result = private_->deserializer.ReadObject(); 3143 } else { 3144 result = 3145 private_->deserializer.ReadObjectUsingEntireBufferForLegacyFormat(); 3146 } 3147 Local<Value> value; 3148 has_pending_exception = !ToLocal(result, &value); 3149 RETURN_ON_FAILED_EXECUTION(Value); 3150 RETURN_ESCAPED(value); 3151 } 3152 3153 void ValueDeserializer::TransferArrayBuffer(uint32_t transfer_id, 3154 Local<ArrayBuffer> array_buffer) { 3155 CHECK(!private_->has_aborted); 3156 private_->deserializer.TransferArrayBuffer(transfer_id, 3157 Utils::OpenHandle(*array_buffer)); 3158 } 3159 3160 void ValueDeserializer::TransferSharedArrayBuffer( 3161 uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) { 3162 CHECK(!private_->has_aborted); 3163 private_->deserializer.TransferArrayBuffer( 3164 transfer_id, Utils::OpenHandle(*shared_array_buffer)); 3165 } 3166 3167 bool ValueDeserializer::ReadUint32(uint32_t* value) { 3168 return private_->deserializer.ReadUint32(value); 3169 } 3170 3171 bool ValueDeserializer::ReadUint64(uint64_t* value) { 3172 return private_->deserializer.ReadUint64(value); 3173 } 3174 3175 bool ValueDeserializer::ReadDouble(double* value) { 3176 return private_->deserializer.ReadDouble(value); 3177 } 3178 3179 bool ValueDeserializer::ReadRawBytes(size_t length, const void** data) { 3180 return private_->deserializer.ReadRawBytes(length, data); 3181 } 3182 3183 // --- D a t a --- 3184 3185 bool Value::FullIsUndefined() const { 3186 i::Handle<i::Object> object = Utils::OpenHandle(this); 3187 bool result = false; 3188 if (!object->IsSmi()) { 3189 result = object->IsUndefined(i::HeapObject::cast(*object)->GetIsolate()); 3190 } 3191 DCHECK_EQ(result, QuickIsUndefined()); 3192 return result; 3193 } 3194 3195 3196 bool Value::FullIsNull() const { 3197 i::Handle<i::Object> object = Utils::OpenHandle(this); 3198 bool result = false; 3199 if (!object->IsSmi()) { 3200 result = object->IsNull(i::HeapObject::cast(*object)->GetIsolate()); 3201 } 3202 DCHECK_EQ(result, QuickIsNull()); 3203 return result; 3204 } 3205 3206 3207 bool Value::IsTrue() const { 3208 i::Handle<i::Object> object = Utils::OpenHandle(this); 3209 if (object->IsSmi()) return false; 3210 return object->IsTrue(i::HeapObject::cast(*object)->GetIsolate()); 3211 } 3212 3213 3214 bool Value::IsFalse() const { 3215 i::Handle<i::Object> object = Utils::OpenHandle(this); 3216 if (object->IsSmi()) return false; 3217 return object->IsFalse(i::HeapObject::cast(*object)->GetIsolate()); 3218 } 3219 3220 3221 bool Value::IsFunction() const { return Utils::OpenHandle(this)->IsCallable(); } 3222 3223 3224 bool Value::IsName() const { 3225 return Utils::OpenHandle(this)->IsName(); 3226 } 3227 3228 3229 bool Value::FullIsString() const { 3230 bool result = Utils::OpenHandle(this)->IsString(); 3231 DCHECK_EQ(result, QuickIsString()); 3232 return result; 3233 } 3234 3235 3236 bool Value::IsSymbol() const { 3237 return Utils::OpenHandle(this)->IsSymbol(); 3238 } 3239 3240 3241 bool Value::IsArray() const { 3242 return Utils::OpenHandle(this)->IsJSArray(); 3243 } 3244 3245 3246 bool Value::IsArrayBuffer() const { 3247 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3248 return obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(); 3249 } 3250 3251 3252 bool Value::IsArrayBufferView() const { 3253 return Utils::OpenHandle(this)->IsJSArrayBufferView(); 3254 } 3255 3256 3257 bool Value::IsTypedArray() const { 3258 return Utils::OpenHandle(this)->IsJSTypedArray(); 3259 } 3260 3261 3262 #define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \ 3263 bool Value::Is##Type##Array() const { \ 3264 i::Handle<i::Object> obj = Utils::OpenHandle(this); \ 3265 return obj->IsJSTypedArray() && \ 3266 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array; \ 3267 } 3268 3269 3270 TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY) 3271 3272 #undef VALUE_IS_TYPED_ARRAY 3273 3274 3275 bool Value::IsDataView() const { 3276 return Utils::OpenHandle(this)->IsJSDataView(); 3277 } 3278 3279 3280 bool Value::IsSharedArrayBuffer() const { 3281 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3282 return obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(); 3283 } 3284 3285 3286 bool Value::IsObject() const { return Utils::OpenHandle(this)->IsJSReceiver(); } 3287 3288 3289 bool Value::IsNumber() const { 3290 return Utils::OpenHandle(this)->IsNumber(); 3291 } 3292 3293 3294 bool Value::IsProxy() const { return Utils::OpenHandle(this)->IsJSProxy(); } 3295 3296 bool Value::IsWebAssemblyCompiledModule() const { 3297 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3298 if (!obj->IsJSObject()) return false; 3299 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj); 3300 return js_obj->GetIsolate()->native_context()->wasm_module_constructor() == 3301 js_obj->map()->GetConstructor(); 3302 } 3303 3304 #define VALUE_IS_SPECIFIC_TYPE(Type, Class) \ 3305 bool Value::Is##Type() const { \ 3306 i::Handle<i::Object> obj = Utils::OpenHandle(this); \ 3307 if (!obj->IsHeapObject()) return false; \ 3308 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \ 3309 return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \ 3310 } 3311 3312 VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments) 3313 VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean) 3314 VALUE_IS_SPECIFIC_TYPE(NumberObject, Number) 3315 VALUE_IS_SPECIFIC_TYPE(StringObject, String) 3316 VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol) 3317 VALUE_IS_SPECIFIC_TYPE(Date, Date) 3318 VALUE_IS_SPECIFIC_TYPE(Map, Map) 3319 VALUE_IS_SPECIFIC_TYPE(Set, Set) 3320 VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap) 3321 VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet) 3322 3323 #undef VALUE_IS_SPECIFIC_TYPE 3324 3325 3326 bool Value::IsBoolean() const { 3327 return Utils::OpenHandle(this)->IsBoolean(); 3328 } 3329 3330 3331 bool Value::IsExternal() const { 3332 return Utils::OpenHandle(this)->IsExternal(); 3333 } 3334 3335 3336 bool Value::IsInt32() const { 3337 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3338 if (obj->IsSmi()) return true; 3339 if (obj->IsNumber()) { 3340 return i::IsInt32Double(obj->Number()); 3341 } 3342 return false; 3343 } 3344 3345 3346 bool Value::IsUint32() const { 3347 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3348 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0; 3349 if (obj->IsNumber()) { 3350 double value = obj->Number(); 3351 return !i::IsMinusZero(value) && 3352 value >= 0 && 3353 value <= i::kMaxUInt32 && 3354 value == i::FastUI2D(i::FastD2UI(value)); 3355 } 3356 return false; 3357 } 3358 3359 3360 bool Value::IsNativeError() const { 3361 return Utils::OpenHandle(this)->IsJSError(); 3362 } 3363 3364 3365 bool Value::IsRegExp() const { 3366 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3367 return obj->IsJSRegExp(); 3368 } 3369 3370 bool Value::IsAsyncFunction() const { 3371 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3372 if (!obj->IsJSFunction()) return false; 3373 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj); 3374 return i::IsAsyncFunction(func->shared()->kind()); 3375 } 3376 3377 bool Value::IsGeneratorFunction() const { 3378 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3379 if (!obj->IsJSFunction()) return false; 3380 i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj); 3381 return i::IsGeneratorFunction(func->shared()->kind()); 3382 } 3383 3384 3385 bool Value::IsGeneratorObject() const { 3386 return Utils::OpenHandle(this)->IsJSGeneratorObject(); 3387 } 3388 3389 3390 bool Value::IsMapIterator() const { 3391 return Utils::OpenHandle(this)->IsJSMapIterator(); 3392 } 3393 3394 3395 bool Value::IsSetIterator() const { 3396 return Utils::OpenHandle(this)->IsJSSetIterator(); 3397 } 3398 3399 bool Value::IsPromise() const { return Utils::OpenHandle(this)->IsJSPromise(); } 3400 3401 MaybeLocal<String> Value::ToString(Local<Context> context) const { 3402 auto obj = Utils::OpenHandle(this); 3403 if (obj->IsString()) return ToApiHandle<String>(obj); 3404 PREPARE_FOR_EXECUTION(context, Object, ToString, String); 3405 Local<String> result; 3406 has_pending_exception = 3407 !ToLocal<String>(i::Object::ToString(isolate, obj), &result); 3408 RETURN_ON_FAILED_EXECUTION(String); 3409 RETURN_ESCAPED(result); 3410 } 3411 3412 3413 Local<String> Value::ToString(Isolate* isolate) const { 3414 RETURN_TO_LOCAL_UNCHECKED(ToString(isolate->GetCurrentContext()), String); 3415 } 3416 3417 3418 MaybeLocal<String> Value::ToDetailString(Local<Context> context) const { 3419 i::Handle<i::Object> obj = Utils::OpenHandle(this); 3420 if (obj->IsString()) return ToApiHandle<String>(obj); 3421 PREPARE_FOR_EXECUTION(context, Object, ToDetailString, String); 3422 Local<String> result = 3423 Utils::ToLocal(i::Object::NoSideEffectsToString(isolate, obj)); 3424 RETURN_ON_FAILED_EXECUTION(String); 3425 RETURN_ESCAPED(result); 3426 } 3427 3428 3429 Local<String> Value::ToDetailString(Isolate* isolate) const { 3430 RETURN_TO_LOCAL_UNCHECKED(ToDetailString(isolate->GetCurrentContext()), 3431 String); 3432 } 3433 3434 3435 MaybeLocal<Object> Value::ToObject(Local<Context> context) const { 3436 auto obj = Utils::OpenHandle(this); 3437 if (obj->IsJSReceiver()) return ToApiHandle<Object>(obj); 3438 PREPARE_FOR_EXECUTION(context, Object, ToObject, Object); 3439 Local<Object> result; 3440 has_pending_exception = 3441 !ToLocal<Object>(i::Object::ToObject(isolate, obj), &result); 3442 RETURN_ON_FAILED_EXECUTION(Object); 3443 RETURN_ESCAPED(result); 3444 } 3445 3446 3447 Local<v8::Object> Value::ToObject(Isolate* isolate) const { 3448 RETURN_TO_LOCAL_UNCHECKED(ToObject(isolate->GetCurrentContext()), Object); 3449 } 3450 3451 3452 MaybeLocal<Boolean> Value::ToBoolean(Local<Context> context) const { 3453 auto obj = Utils::OpenHandle(this); 3454 if (obj->IsBoolean()) return ToApiHandle<Boolean>(obj); 3455 auto isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate()); 3456 auto val = isolate->factory()->ToBoolean(obj->BooleanValue()); 3457 return ToApiHandle<Boolean>(val); 3458 } 3459 3460 3461 Local<Boolean> Value::ToBoolean(Isolate* v8_isolate) const { 3462 return ToBoolean(v8_isolate->GetCurrentContext()).ToLocalChecked(); 3463 } 3464 3465 3466 MaybeLocal<Number> Value::ToNumber(Local<Context> context) const { 3467 auto obj = Utils::OpenHandle(this); 3468 if (obj->IsNumber()) return ToApiHandle<Number>(obj); 3469 PREPARE_FOR_EXECUTION(context, Object, ToNumber, Number); 3470 Local<Number> result; 3471 has_pending_exception = !ToLocal<Number>(i::Object::ToNumber(obj), &result); 3472 RETURN_ON_FAILED_EXECUTION(Number); 3473 RETURN_ESCAPED(result); 3474 } 3475 3476 3477 Local<Number> Value::ToNumber(Isolate* isolate) const { 3478 RETURN_TO_LOCAL_UNCHECKED(ToNumber(isolate->GetCurrentContext()), Number); 3479 } 3480 3481 3482 MaybeLocal<Integer> Value::ToInteger(Local<Context> context) const { 3483 auto obj = Utils::OpenHandle(this); 3484 if (obj->IsSmi()) return ToApiHandle<Integer>(obj); 3485 PREPARE_FOR_EXECUTION(context, Object, ToInteger, Integer); 3486 Local<Integer> result; 3487 has_pending_exception = 3488 !ToLocal<Integer>(i::Object::ToInteger(isolate, obj), &result); 3489 RETURN_ON_FAILED_EXECUTION(Integer); 3490 RETURN_ESCAPED(result); 3491 } 3492 3493 3494 Local<Integer> Value::ToInteger(Isolate* isolate) const { 3495 RETURN_TO_LOCAL_UNCHECKED(ToInteger(isolate->GetCurrentContext()), Integer); 3496 } 3497 3498 3499 MaybeLocal<Int32> Value::ToInt32(Local<Context> context) const { 3500 auto obj = Utils::OpenHandle(this); 3501 if (obj->IsSmi()) return ToApiHandle<Int32>(obj); 3502 Local<Int32> result; 3503 PREPARE_FOR_EXECUTION(context, Object, ToInt32, Int32); 3504 has_pending_exception = 3505 !ToLocal<Int32>(i::Object::ToInt32(isolate, obj), &result); 3506 RETURN_ON_FAILED_EXECUTION(Int32); 3507 RETURN_ESCAPED(result); 3508 } 3509 3510 3511 Local<Int32> Value::ToInt32(Isolate* isolate) const { 3512 RETURN_TO_LOCAL_UNCHECKED(ToInt32(isolate->GetCurrentContext()), Int32); 3513 } 3514 3515 3516 MaybeLocal<Uint32> Value::ToUint32(Local<Context> context) const { 3517 auto obj = Utils::OpenHandle(this); 3518 if (obj->IsSmi()) return ToApiHandle<Uint32>(obj); 3519 Local<Uint32> result; 3520 PREPARE_FOR_EXECUTION(context, Object, ToUint32, Uint32); 3521 has_pending_exception = 3522 !ToLocal<Uint32>(i::Object::ToUint32(isolate, obj), &result); 3523 RETURN_ON_FAILED_EXECUTION(Uint32); 3524 RETURN_ESCAPED(result); 3525 } 3526 3527 3528 Local<Uint32> Value::ToUint32(Isolate* isolate) const { 3529 RETURN_TO_LOCAL_UNCHECKED(ToUint32(isolate->GetCurrentContext()), Uint32); 3530 } 3531 3532 3533 void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) { 3534 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate); 3535 Utils::ApiCheck(isolate != NULL && !isolate->IsDead(), 3536 "v8::internal::Internals::CheckInitialized", 3537 "Isolate is not initialized or V8 has died"); 3538 } 3539 3540 3541 void External::CheckCast(v8::Value* that) { 3542 Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(), "v8::External::Cast", 3543 "Could not convert to external"); 3544 } 3545 3546 3547 void v8::Object::CheckCast(Value* that) { 3548 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3549 Utils::ApiCheck(obj->IsJSReceiver(), "v8::Object::Cast", 3550 "Could not convert to object"); 3551 } 3552 3553 3554 void v8::Function::CheckCast(Value* that) { 3555 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3556 Utils::ApiCheck(obj->IsCallable(), "v8::Function::Cast", 3557 "Could not convert to function"); 3558 } 3559 3560 3561 void v8::Boolean::CheckCast(v8::Value* that) { 3562 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3563 Utils::ApiCheck(obj->IsBoolean(), "v8::Boolean::Cast", 3564 "Could not convert to boolean"); 3565 } 3566 3567 3568 void v8::Name::CheckCast(v8::Value* that) { 3569 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3570 Utils::ApiCheck(obj->IsName(), "v8::Name::Cast", "Could not convert to name"); 3571 } 3572 3573 3574 void v8::String::CheckCast(v8::Value* that) { 3575 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3576 Utils::ApiCheck(obj->IsString(), "v8::String::Cast", 3577 "Could not convert to string"); 3578 } 3579 3580 3581 void v8::Symbol::CheckCast(v8::Value* that) { 3582 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3583 Utils::ApiCheck(obj->IsSymbol(), "v8::Symbol::Cast", 3584 "Could not convert to symbol"); 3585 } 3586 3587 3588 void v8::Number::CheckCast(v8::Value* that) { 3589 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3590 Utils::ApiCheck(obj->IsNumber(), 3591 "v8::Number::Cast()", 3592 "Could not convert to number"); 3593 } 3594 3595 3596 void v8::Integer::CheckCast(v8::Value* that) { 3597 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3598 Utils::ApiCheck(obj->IsNumber(), "v8::Integer::Cast", 3599 "Could not convert to number"); 3600 } 3601 3602 3603 void v8::Int32::CheckCast(v8::Value* that) { 3604 Utils::ApiCheck(that->IsInt32(), "v8::Int32::Cast", 3605 "Could not convert to 32-bit signed integer"); 3606 } 3607 3608 3609 void v8::Uint32::CheckCast(v8::Value* that) { 3610 Utils::ApiCheck(that->IsUint32(), "v8::Uint32::Cast", 3611 "Could not convert to 32-bit unsigned integer"); 3612 } 3613 3614 3615 void v8::Array::CheckCast(Value* that) { 3616 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3617 Utils::ApiCheck(obj->IsJSArray(), "v8::Array::Cast", 3618 "Could not convert to array"); 3619 } 3620 3621 3622 void v8::Map::CheckCast(Value* that) { 3623 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3624 Utils::ApiCheck(obj->IsJSMap(), "v8::Map::Cast", "Could not convert to Map"); 3625 } 3626 3627 3628 void v8::Set::CheckCast(Value* that) { 3629 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3630 Utils::ApiCheck(obj->IsJSSet(), "v8_Set_Cast", "Could not convert to Set"); 3631 } 3632 3633 3634 void v8::Promise::CheckCast(Value* that) { 3635 Utils::ApiCheck(that->IsPromise(), "v8::Promise::Cast", 3636 "Could not convert to promise"); 3637 } 3638 3639 3640 void v8::Promise::Resolver::CheckCast(Value* that) { 3641 Utils::ApiCheck(that->IsPromise(), "v8::Promise::Resolver::Cast", 3642 "Could not convert to promise resolver"); 3643 } 3644 3645 3646 void v8::Proxy::CheckCast(Value* that) { 3647 Utils::ApiCheck(that->IsProxy(), "v8::Proxy::Cast", 3648 "Could not convert to proxy"); 3649 } 3650 3651 void v8::WasmCompiledModule::CheckCast(Value* that) { 3652 Utils::ApiCheck(that->IsWebAssemblyCompiledModule(), 3653 "v8::WasmCompiledModule::Cast", 3654 "Could not convert to wasm compiled module"); 3655 } 3656 3657 void v8::ArrayBuffer::CheckCast(Value* that) { 3658 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3659 Utils::ApiCheck( 3660 obj->IsJSArrayBuffer() && !i::JSArrayBuffer::cast(*obj)->is_shared(), 3661 "v8::ArrayBuffer::Cast()", "Could not convert to ArrayBuffer"); 3662 } 3663 3664 3665 void v8::ArrayBufferView::CheckCast(Value* that) { 3666 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3667 Utils::ApiCheck(obj->IsJSArrayBufferView(), 3668 "v8::ArrayBufferView::Cast()", 3669 "Could not convert to ArrayBufferView"); 3670 } 3671 3672 3673 void v8::TypedArray::CheckCast(Value* that) { 3674 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3675 Utils::ApiCheck(obj->IsJSTypedArray(), 3676 "v8::TypedArray::Cast()", 3677 "Could not convert to TypedArray"); 3678 } 3679 3680 3681 #define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \ 3682 void v8::Type##Array::CheckCast(Value* that) { \ 3683 i::Handle<i::Object> obj = Utils::OpenHandle(that); \ 3684 Utils::ApiCheck( \ 3685 obj->IsJSTypedArray() && \ 3686 i::JSTypedArray::cast(*obj)->type() == i::kExternal##Type##Array, \ 3687 "v8::" #Type "Array::Cast()", "Could not convert to " #Type "Array"); \ 3688 } 3689 3690 3691 TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST) 3692 3693 #undef CHECK_TYPED_ARRAY_CAST 3694 3695 3696 void v8::DataView::CheckCast(Value* that) { 3697 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3698 Utils::ApiCheck(obj->IsJSDataView(), 3699 "v8::DataView::Cast()", 3700 "Could not convert to DataView"); 3701 } 3702 3703 3704 void v8::SharedArrayBuffer::CheckCast(Value* that) { 3705 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3706 Utils::ApiCheck( 3707 obj->IsJSArrayBuffer() && i::JSArrayBuffer::cast(*obj)->is_shared(), 3708 "v8::SharedArrayBuffer::Cast()", 3709 "Could not convert to SharedArrayBuffer"); 3710 } 3711 3712 3713 void v8::Date::CheckCast(v8::Value* that) { 3714 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3715 i::Isolate* isolate = NULL; 3716 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate(); 3717 Utils::ApiCheck(isolate != NULL && 3718 obj->HasSpecificClassOf(isolate->heap()->Date_string()), 3719 "v8::Date::Cast()", 3720 "Could not convert to date"); 3721 } 3722 3723 3724 void v8::StringObject::CheckCast(v8::Value* that) { 3725 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3726 i::Isolate* isolate = NULL; 3727 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate(); 3728 Utils::ApiCheck(isolate != NULL && 3729 obj->HasSpecificClassOf(isolate->heap()->String_string()), 3730 "v8::StringObject::Cast()", 3731 "Could not convert to StringObject"); 3732 } 3733 3734 3735 void v8::SymbolObject::CheckCast(v8::Value* that) { 3736 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3737 i::Isolate* isolate = NULL; 3738 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate(); 3739 Utils::ApiCheck(isolate != NULL && 3740 obj->HasSpecificClassOf(isolate->heap()->Symbol_string()), 3741 "v8::SymbolObject::Cast()", 3742 "Could not convert to SymbolObject"); 3743 } 3744 3745 3746 void v8::NumberObject::CheckCast(v8::Value* that) { 3747 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3748 i::Isolate* isolate = NULL; 3749 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate(); 3750 Utils::ApiCheck(isolate != NULL && 3751 obj->HasSpecificClassOf(isolate->heap()->Number_string()), 3752 "v8::NumberObject::Cast()", 3753 "Could not convert to NumberObject"); 3754 } 3755 3756 3757 void v8::BooleanObject::CheckCast(v8::Value* that) { 3758 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3759 i::Isolate* isolate = NULL; 3760 if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate(); 3761 Utils::ApiCheck(isolate != NULL && 3762 obj->HasSpecificClassOf(isolate->heap()->Boolean_string()), 3763 "v8::BooleanObject::Cast()", 3764 "Could not convert to BooleanObject"); 3765 } 3766 3767 3768 void v8::RegExp::CheckCast(v8::Value* that) { 3769 i::Handle<i::Object> obj = Utils::OpenHandle(that); 3770 Utils::ApiCheck(obj->IsJSRegExp(), 3771 "v8::RegExp::Cast()", 3772 "Could not convert to regular expression"); 3773 } 3774 3775 3776 Maybe<bool> Value::BooleanValue(Local<Context> context) const { 3777 return Just(Utils::OpenHandle(this)->BooleanValue()); 3778 } 3779 3780 3781 bool Value::BooleanValue() const { 3782 return Utils::OpenHandle(this)->BooleanValue(); 3783 } 3784 3785 3786 Maybe<double> Value::NumberValue(Local<Context> context) const { 3787 auto obj = Utils::OpenHandle(this); 3788 if (obj->IsNumber()) return Just(obj->Number()); 3789 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, NumberValue, double); 3790 i::Handle<i::Object> num; 3791 has_pending_exception = !i::Object::ToNumber(obj).ToHandle(&num); 3792 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(double); 3793 return Just(num->Number()); 3794 } 3795 3796 3797 double Value::NumberValue() const { 3798 auto obj = Utils::OpenHandle(this); 3799 if (obj->IsNumber()) return obj->Number(); 3800 return NumberValue(ContextFromHeapObject(obj)) 3801 .FromMaybe(std::numeric_limits<double>::quiet_NaN()); 3802 } 3803 3804 3805 Maybe<int64_t> Value::IntegerValue(Local<Context> context) const { 3806 auto obj = Utils::OpenHandle(this); 3807 if (obj->IsNumber()) { 3808 return Just(NumberToInt64(*obj)); 3809 } 3810 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, IntegerValue, int64_t); 3811 i::Handle<i::Object> num; 3812 has_pending_exception = !i::Object::ToInteger(isolate, obj).ToHandle(&num); 3813 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int64_t); 3814 return Just(NumberToInt64(*num)); 3815 } 3816 3817 3818 int64_t Value::IntegerValue() const { 3819 auto obj = Utils::OpenHandle(this); 3820 if (obj->IsNumber()) { 3821 if (obj->IsSmi()) { 3822 return i::Smi::cast(*obj)->value(); 3823 } else { 3824 return static_cast<int64_t>(obj->Number()); 3825 } 3826 } 3827 return IntegerValue(ContextFromHeapObject(obj)).FromMaybe(0); 3828 } 3829 3830 3831 Maybe<int32_t> Value::Int32Value(Local<Context> context) const { 3832 auto obj = Utils::OpenHandle(this); 3833 if (obj->IsNumber()) return Just(NumberToInt32(*obj)); 3834 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Int32Value, int32_t); 3835 i::Handle<i::Object> num; 3836 has_pending_exception = !i::Object::ToInt32(isolate, obj).ToHandle(&num); 3837 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(int32_t); 3838 return Just(num->IsSmi() ? i::Smi::cast(*num)->value() 3839 : static_cast<int32_t>(num->Number())); 3840 } 3841 3842 3843 int32_t Value::Int32Value() const { 3844 auto obj = Utils::OpenHandle(this); 3845 if (obj->IsNumber()) return NumberToInt32(*obj); 3846 return Int32Value(ContextFromHeapObject(obj)).FromMaybe(0); 3847 } 3848 3849 3850 Maybe<uint32_t> Value::Uint32Value(Local<Context> context) const { 3851 auto obj = Utils::OpenHandle(this); 3852 if (obj->IsNumber()) return Just(NumberToUint32(*obj)); 3853 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Uint32Value, uint32_t); 3854 i::Handle<i::Object> num; 3855 has_pending_exception = !i::Object::ToUint32(isolate, obj).ToHandle(&num); 3856 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(uint32_t); 3857 return Just(num->IsSmi() ? static_cast<uint32_t>(i::Smi::cast(*num)->value()) 3858 : static_cast<uint32_t>(num->Number())); 3859 } 3860 3861 3862 uint32_t Value::Uint32Value() const { 3863 auto obj = Utils::OpenHandle(this); 3864 if (obj->IsNumber()) return NumberToUint32(*obj); 3865 return Uint32Value(ContextFromHeapObject(obj)).FromMaybe(0); 3866 } 3867 3868 3869 MaybeLocal<Uint32> Value::ToArrayIndex(Local<Context> context) const { 3870 auto self = Utils::OpenHandle(this); 3871 if (self->IsSmi()) { 3872 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self); 3873 return Local<Uint32>(); 3874 } 3875 PREPARE_FOR_EXECUTION(context, Object, ToArrayIndex, Uint32); 3876 i::Handle<i::Object> string_obj; 3877 has_pending_exception = 3878 !i::Object::ToString(isolate, self).ToHandle(&string_obj); 3879 RETURN_ON_FAILED_EXECUTION(Uint32); 3880 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj); 3881 uint32_t index; 3882 if (str->AsArrayIndex(&index)) { 3883 i::Handle<i::Object> value; 3884 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) { 3885 value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate); 3886 } else { 3887 value = isolate->factory()->NewNumber(index); 3888 } 3889 RETURN_ESCAPED(Utils::Uint32ToLocal(value)); 3890 } 3891 return Local<Uint32>(); 3892 } 3893 3894 3895 Local<Uint32> Value::ToArrayIndex() const { 3896 auto self = Utils::OpenHandle(this); 3897 if (self->IsSmi()) { 3898 if (i::Smi::cast(*self)->value() >= 0) return Utils::Uint32ToLocal(self); 3899 return Local<Uint32>(); 3900 } 3901 auto context = ContextFromHeapObject(self); 3902 RETURN_TO_LOCAL_UNCHECKED(ToArrayIndex(context), Uint32); 3903 } 3904 3905 3906 Maybe<bool> Value::Equals(Local<Context> context, Local<Value> that) const { 3907 auto self = Utils::OpenHandle(this); 3908 auto other = Utils::OpenHandle(*that); 3909 return i::Object::Equals(self, other); 3910 } 3911 3912 3913 bool Value::Equals(Local<Value> that) const { 3914 auto self = Utils::OpenHandle(this); 3915 auto other = Utils::OpenHandle(*that); 3916 if (self->IsSmi() && other->IsSmi()) { 3917 return self->Number() == other->Number(); 3918 } 3919 if (self->IsJSObject() && other->IsJSObject()) { 3920 return *self == *other; 3921 } 3922 auto heap_object = self->IsSmi() ? other : self; 3923 auto context = ContextFromHeapObject(heap_object); 3924 return Equals(context, that).FromMaybe(false); 3925 } 3926 3927 3928 bool Value::StrictEquals(Local<Value> that) const { 3929 auto self = Utils::OpenHandle(this); 3930 auto other = Utils::OpenHandle(*that); 3931 return self->StrictEquals(*other); 3932 } 3933 3934 3935 bool Value::SameValue(Local<Value> that) const { 3936 auto self = Utils::OpenHandle(this); 3937 auto other = Utils::OpenHandle(*that); 3938 return self->SameValue(*other); 3939 } 3940 3941 Local<String> Value::TypeOf(v8::Isolate* external_isolate) { 3942 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate); 3943 ENTER_V8(isolate); 3944 LOG_API(isolate, Value, TypeOf); 3945 return Utils::ToLocal(i::Object::TypeOf(isolate, Utils::OpenHandle(this))); 3946 } 3947 3948 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, 3949 v8::Local<Value> key, v8::Local<Value> value) { 3950 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Set, bool); 3951 auto self = Utils::OpenHandle(this); 3952 auto key_obj = Utils::OpenHandle(*key); 3953 auto value_obj = Utils::OpenHandle(*value); 3954 has_pending_exception = 3955 i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj, 3956 i::SLOPPY).is_null(); 3957 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3958 return Just(true); 3959 } 3960 3961 3962 bool v8::Object::Set(v8::Local<Value> key, v8::Local<Value> value) { 3963 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 3964 return Set(context, key, value).FromMaybe(false); 3965 } 3966 3967 3968 Maybe<bool> v8::Object::Set(v8::Local<v8::Context> context, uint32_t index, 3969 v8::Local<Value> value) { 3970 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Set, bool); 3971 auto self = Utils::OpenHandle(this); 3972 auto value_obj = Utils::OpenHandle(*value); 3973 has_pending_exception = i::Object::SetElement(isolate, self, index, value_obj, 3974 i::SLOPPY).is_null(); 3975 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 3976 return Just(true); 3977 } 3978 3979 3980 bool v8::Object::Set(uint32_t index, v8::Local<Value> value) { 3981 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 3982 return Set(context, index, value).FromMaybe(false); 3983 } 3984 3985 3986 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context, 3987 v8::Local<Name> key, 3988 v8::Local<Value> value) { 3989 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, CreateDataProperty, bool); 3990 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 3991 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key); 3992 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value); 3993 3994 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 3995 isolate, self, key_obj, self, i::LookupIterator::OWN); 3996 Maybe<bool> result = 3997 i::JSReceiver::CreateDataProperty(&it, value_obj, i::Object::DONT_THROW); 3998 has_pending_exception = result.IsNothing(); 3999 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4000 return result; 4001 } 4002 4003 4004 Maybe<bool> v8::Object::CreateDataProperty(v8::Local<v8::Context> context, 4005 uint32_t index, 4006 v8::Local<Value> value) { 4007 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, CreateDataProperty, bool); 4008 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 4009 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value); 4010 4011 i::LookupIterator it(isolate, self, index, self, i::LookupIterator::OWN); 4012 Maybe<bool> result = 4013 i::JSReceiver::CreateDataProperty(&it, value_obj, i::Object::DONT_THROW); 4014 has_pending_exception = result.IsNothing(); 4015 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4016 return result; 4017 } 4018 4019 struct v8::PropertyDescriptor::PrivateData { 4020 PrivateData() : desc() {} 4021 i::PropertyDescriptor desc; 4022 }; 4023 4024 v8::PropertyDescriptor::PropertyDescriptor() : private_(new PrivateData()) {} 4025 4026 // DataDescriptor 4027 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value) 4028 : private_(new PrivateData()) { 4029 private_->desc.set_value(Utils::OpenHandle(*value, true)); 4030 } 4031 4032 // DataDescriptor with writable field 4033 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> value, 4034 bool writable) 4035 : private_(new PrivateData()) { 4036 private_->desc.set_value(Utils::OpenHandle(*value, true)); 4037 private_->desc.set_writable(writable); 4038 } 4039 4040 // AccessorDescriptor 4041 v8::PropertyDescriptor::PropertyDescriptor(v8::Local<v8::Value> get, 4042 v8::Local<v8::Value> set) 4043 : private_(new PrivateData()) { 4044 DCHECK(get.IsEmpty() || get->IsUndefined() || get->IsFunction()); 4045 DCHECK(set.IsEmpty() || set->IsUndefined() || set->IsFunction()); 4046 private_->desc.set_get(Utils::OpenHandle(*get, true)); 4047 private_->desc.set_set(Utils::OpenHandle(*set, true)); 4048 } 4049 4050 v8::PropertyDescriptor::~PropertyDescriptor() { delete private_; } 4051 4052 v8::Local<Value> v8::PropertyDescriptor::value() const { 4053 DCHECK(private_->desc.has_value()); 4054 return Utils::ToLocal(private_->desc.value()); 4055 } 4056 4057 v8::Local<Value> v8::PropertyDescriptor::get() const { 4058 DCHECK(private_->desc.has_get()); 4059 return Utils::ToLocal(private_->desc.get()); 4060 } 4061 4062 v8::Local<Value> v8::PropertyDescriptor::set() const { 4063 DCHECK(private_->desc.has_set()); 4064 return Utils::ToLocal(private_->desc.set()); 4065 } 4066 4067 bool v8::PropertyDescriptor::has_value() const { 4068 return private_->desc.has_value(); 4069 } 4070 bool v8::PropertyDescriptor::has_get() const { 4071 return private_->desc.has_get(); 4072 } 4073 bool v8::PropertyDescriptor::has_set() const { 4074 return private_->desc.has_set(); 4075 } 4076 4077 bool v8::PropertyDescriptor::writable() const { 4078 DCHECK(private_->desc.has_writable()); 4079 return private_->desc.writable(); 4080 } 4081 4082 bool v8::PropertyDescriptor::has_writable() const { 4083 return private_->desc.has_writable(); 4084 } 4085 4086 void v8::PropertyDescriptor::set_enumerable(bool enumerable) { 4087 private_->desc.set_enumerable(enumerable); 4088 } 4089 4090 bool v8::PropertyDescriptor::enumerable() const { 4091 DCHECK(private_->desc.has_enumerable()); 4092 return private_->desc.enumerable(); 4093 } 4094 4095 bool v8::PropertyDescriptor::has_enumerable() const { 4096 return private_->desc.has_enumerable(); 4097 } 4098 4099 void v8::PropertyDescriptor::set_configurable(bool configurable) { 4100 private_->desc.set_configurable(configurable); 4101 } 4102 4103 bool v8::PropertyDescriptor::configurable() const { 4104 DCHECK(private_->desc.has_configurable()); 4105 return private_->desc.configurable(); 4106 } 4107 4108 bool v8::PropertyDescriptor::has_configurable() const { 4109 return private_->desc.has_configurable(); 4110 } 4111 4112 Maybe<bool> v8::Object::DefineOwnProperty(v8::Local<v8::Context> context, 4113 v8::Local<Name> key, 4114 v8::Local<Value> value, 4115 v8::PropertyAttribute attributes) { 4116 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, DefineOwnProperty, bool); 4117 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 4118 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key); 4119 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value); 4120 4121 i::PropertyDescriptor desc; 4122 desc.set_writable(!(attributes & v8::ReadOnly)); 4123 desc.set_enumerable(!(attributes & v8::DontEnum)); 4124 desc.set_configurable(!(attributes & v8::DontDelete)); 4125 desc.set_value(value_obj); 4126 Maybe<bool> success = i::JSReceiver::DefineOwnProperty( 4127 isolate, self, key_obj, &desc, i::Object::DONT_THROW); 4128 // Even though we said DONT_THROW, there might be accessors that do throw. 4129 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4130 return success; 4131 } 4132 4133 Maybe<bool> v8::Object::DefineProperty(v8::Local<v8::Context> context, 4134 v8::Local<Name> key, 4135 PropertyDescriptor& descriptor) { 4136 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, DefineProperty, bool); 4137 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 4138 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key); 4139 4140 Maybe<bool> success = i::JSReceiver::DefineOwnProperty( 4141 isolate, self, key_obj, &descriptor.get_private()->desc, 4142 i::Object::DONT_THROW); 4143 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4144 return success; 4145 } 4146 4147 MUST_USE_RESULT 4148 static i::MaybeHandle<i::Object> DefineObjectProperty( 4149 i::Handle<i::JSObject> js_object, i::Handle<i::Object> key, 4150 i::Handle<i::Object> value, i::PropertyAttributes attrs) { 4151 i::Isolate* isolate = js_object->GetIsolate(); 4152 bool success = false; 4153 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 4154 isolate, js_object, key, &success, i::LookupIterator::OWN); 4155 if (!success) return i::MaybeHandle<i::Object>(); 4156 4157 return i::JSObject::DefineOwnPropertyIgnoreAttributes( 4158 &it, value, attrs, i::JSObject::FORCE_FIELD); 4159 } 4160 4161 4162 Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context> context, 4163 v8::Local<Value> key, v8::Local<Value> value, 4164 v8::PropertyAttribute attribs) { 4165 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, ForceSet, bool); 4166 auto self = i::Handle<i::JSObject>::cast(Utils::OpenHandle(this)); 4167 auto key_obj = Utils::OpenHandle(*key); 4168 auto value_obj = Utils::OpenHandle(*value); 4169 has_pending_exception = 4170 DefineObjectProperty(self, key_obj, value_obj, 4171 static_cast<i::PropertyAttributes>(attribs)) 4172 .is_null(); 4173 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4174 return Just(true); 4175 } 4176 4177 4178 bool v8::Object::ForceSet(v8::Local<Value> key, v8::Local<Value> value, 4179 v8::PropertyAttribute attribs) { 4180 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 4181 PREPARE_FOR_EXECUTION_GENERIC(isolate, Local<Context>(), Object, ForceSet, 4182 false, i::HandleScope, false); 4183 i::Handle<i::JSObject> self = 4184 i::Handle<i::JSObject>::cast(Utils::OpenHandle(this)); 4185 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key); 4186 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value); 4187 has_pending_exception = 4188 DefineObjectProperty(self, key_obj, value_obj, 4189 static_cast<i::PropertyAttributes>(attribs)) 4190 .is_null(); 4191 EXCEPTION_BAILOUT_CHECK_SCOPED(isolate, false); 4192 return true; 4193 } 4194 4195 4196 Maybe<bool> v8::Object::SetPrivate(Local<Context> context, Local<Private> key, 4197 Local<Value> value) { 4198 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, SetPrivate, bool); 4199 auto self = Utils::OpenHandle(this); 4200 auto key_obj = Utils::OpenHandle(reinterpret_cast<Name*>(*key)); 4201 auto value_obj = Utils::OpenHandle(*value); 4202 if (self->IsJSProxy()) { 4203 i::PropertyDescriptor desc; 4204 desc.set_writable(true); 4205 desc.set_enumerable(false); 4206 desc.set_configurable(true); 4207 desc.set_value(value_obj); 4208 return i::JSProxy::SetPrivateProperty( 4209 isolate, i::Handle<i::JSProxy>::cast(self), 4210 i::Handle<i::Symbol>::cast(key_obj), &desc, i::Object::DONT_THROW); 4211 } 4212 auto js_object = i::Handle<i::JSObject>::cast(self); 4213 i::LookupIterator it(js_object, key_obj, js_object); 4214 has_pending_exception = i::JSObject::DefineOwnPropertyIgnoreAttributes( 4215 &it, value_obj, i::DONT_ENUM) 4216 .is_null(); 4217 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4218 return Just(true); 4219 } 4220 4221 4222 MaybeLocal<Value> v8::Object::Get(Local<v8::Context> context, 4223 Local<Value> key) { 4224 PREPARE_FOR_EXECUTION(context, Object, Get, Value); 4225 auto self = Utils::OpenHandle(this); 4226 auto key_obj = Utils::OpenHandle(*key); 4227 i::Handle<i::Object> result; 4228 has_pending_exception = 4229 !i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result); 4230 RETURN_ON_FAILED_EXECUTION(Value); 4231 RETURN_ESCAPED(Utils::ToLocal(result)); 4232 } 4233 4234 4235 Local<Value> v8::Object::Get(v8::Local<Value> key) { 4236 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4237 RETURN_TO_LOCAL_UNCHECKED(Get(context, key), Value); 4238 } 4239 4240 4241 MaybeLocal<Value> v8::Object::Get(Local<Context> context, uint32_t index) { 4242 PREPARE_FOR_EXECUTION(context, Object, Get, Value); 4243 auto self = Utils::OpenHandle(this); 4244 i::Handle<i::Object> result; 4245 has_pending_exception = 4246 !i::JSReceiver::GetElement(isolate, self, index).ToHandle(&result); 4247 RETURN_ON_FAILED_EXECUTION(Value); 4248 RETURN_ESCAPED(Utils::ToLocal(result)); 4249 } 4250 4251 4252 Local<Value> v8::Object::Get(uint32_t index) { 4253 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4254 RETURN_TO_LOCAL_UNCHECKED(Get(context, index), Value); 4255 } 4256 4257 4258 MaybeLocal<Value> v8::Object::GetPrivate(Local<Context> context, 4259 Local<Private> key) { 4260 return Get(context, Local<Value>(reinterpret_cast<Value*>(*key))); 4261 } 4262 4263 4264 Maybe<PropertyAttribute> v8::Object::GetPropertyAttributes( 4265 Local<Context> context, Local<Value> key) { 4266 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, GetPropertyAttributes, 4267 PropertyAttribute); 4268 auto self = Utils::OpenHandle(this); 4269 auto key_obj = Utils::OpenHandle(*key); 4270 if (!key_obj->IsName()) { 4271 has_pending_exception = 4272 !i::Object::ToString(isolate, key_obj).ToHandle(&key_obj); 4273 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute); 4274 } 4275 auto key_name = i::Handle<i::Name>::cast(key_obj); 4276 auto result = i::JSReceiver::GetPropertyAttributes(self, key_name); 4277 has_pending_exception = result.IsNothing(); 4278 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute); 4279 if (result.FromJust() == i::ABSENT) { 4280 return Just(static_cast<PropertyAttribute>(i::NONE)); 4281 } 4282 return Just(static_cast<PropertyAttribute>(result.FromJust())); 4283 } 4284 4285 4286 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Local<Value> key) { 4287 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4288 return GetPropertyAttributes(context, key) 4289 .FromMaybe(static_cast<PropertyAttribute>(i::NONE)); 4290 } 4291 4292 4293 MaybeLocal<Value> v8::Object::GetOwnPropertyDescriptor(Local<Context> context, 4294 Local<String> key) { 4295 PREPARE_FOR_EXECUTION(context, Object, GetOwnPropertyDescriptor, Value); 4296 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 4297 i::Handle<i::String> key_name = Utils::OpenHandle(*key); 4298 4299 i::PropertyDescriptor desc; 4300 Maybe<bool> found = 4301 i::JSReceiver::GetOwnPropertyDescriptor(isolate, obj, key_name, &desc); 4302 has_pending_exception = found.IsNothing(); 4303 RETURN_ON_FAILED_EXECUTION(Value); 4304 if (!found.FromJust()) { 4305 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 4306 } 4307 RETURN_ESCAPED(Utils::ToLocal(desc.ToObject(isolate))); 4308 } 4309 4310 4311 Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) { 4312 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4313 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyDescriptor(context, key), Value); 4314 } 4315 4316 4317 Local<Value> v8::Object::GetPrototype() { 4318 auto isolate = Utils::OpenHandle(this)->GetIsolate(); 4319 auto self = Utils::OpenHandle(this); 4320 i::PrototypeIterator iter(isolate, self); 4321 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter)); 4322 } 4323 4324 4325 Maybe<bool> v8::Object::SetPrototype(Local<Context> context, 4326 Local<Value> value) { 4327 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, SetPrototype, bool); 4328 auto self = Utils::OpenHandle(this); 4329 auto value_obj = Utils::OpenHandle(*value); 4330 // We do not allow exceptions thrown while setting the prototype 4331 // to propagate outside. 4332 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate)); 4333 auto result = i::JSReceiver::SetPrototype(self, value_obj, false, 4334 i::Object::THROW_ON_ERROR); 4335 has_pending_exception = result.IsNothing(); 4336 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4337 return Just(true); 4338 } 4339 4340 4341 bool v8::Object::SetPrototype(Local<Value> value) { 4342 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4343 return SetPrototype(context, value).FromMaybe(false); 4344 } 4345 4346 4347 Local<Object> v8::Object::FindInstanceInPrototypeChain( 4348 v8::Local<FunctionTemplate> tmpl) { 4349 auto isolate = Utils::OpenHandle(this)->GetIsolate(); 4350 i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this), 4351 i::kStartAtReceiver); 4352 auto tmpl_info = *Utils::OpenHandle(*tmpl); 4353 while (!tmpl_info->IsTemplateFor(iter.GetCurrent<i::JSObject>())) { 4354 iter.Advance(); 4355 if (iter.IsAtEnd()) return Local<Object>(); 4356 if (!iter.GetCurrent()->IsJSObject()) return Local<Object>(); 4357 } 4358 // IsTemplateFor() ensures that iter.GetCurrent() can't be a Proxy here. 4359 return Utils::ToLocal(i::handle(iter.GetCurrent<i::JSObject>(), isolate)); 4360 } 4361 4362 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context) { 4363 return GetPropertyNames( 4364 context, v8::KeyCollectionMode::kIncludePrototypes, 4365 static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS), 4366 v8::IndexFilter::kIncludeIndices); 4367 } 4368 4369 MaybeLocal<Array> v8::Object::GetPropertyNames(Local<Context> context, 4370 KeyCollectionMode mode, 4371 PropertyFilter property_filter, 4372 IndexFilter index_filter) { 4373 PREPARE_FOR_EXECUTION(context, Object, GetPropertyNames, Array); 4374 auto self = Utils::OpenHandle(this); 4375 i::Handle<i::FixedArray> value; 4376 i::KeyAccumulator accumulator( 4377 isolate, static_cast<i::KeyCollectionMode>(mode), 4378 static_cast<i::PropertyFilter>(property_filter)); 4379 accumulator.set_skip_indices(index_filter == IndexFilter::kSkipIndices); 4380 has_pending_exception = accumulator.CollectKeys(self, self).IsNothing(); 4381 RETURN_ON_FAILED_EXECUTION(Array); 4382 value = accumulator.GetKeys(i::GetKeysConversion::kKeepNumbers); 4383 DCHECK(self->map()->EnumLength() == i::kInvalidEnumCacheSentinel || 4384 self->map()->EnumLength() == 0 || 4385 self->map()->instance_descriptors()->GetEnumCache() != *value); 4386 auto result = isolate->factory()->NewJSArrayWithElements(value); 4387 RETURN_ESCAPED(Utils::ToLocal(result)); 4388 } 4389 4390 4391 Local<Array> v8::Object::GetPropertyNames() { 4392 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4393 RETURN_TO_LOCAL_UNCHECKED(GetPropertyNames(context), Array); 4394 } 4395 4396 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context) { 4397 return GetOwnPropertyNames( 4398 context, static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS)); 4399 } 4400 4401 Local<Array> v8::Object::GetOwnPropertyNames() { 4402 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4403 RETURN_TO_LOCAL_UNCHECKED(GetOwnPropertyNames(context), Array); 4404 } 4405 4406 MaybeLocal<Array> v8::Object::GetOwnPropertyNames(Local<Context> context, 4407 PropertyFilter filter) { 4408 return GetPropertyNames(context, KeyCollectionMode::kOwnOnly, filter, 4409 v8::IndexFilter::kIncludeIndices); 4410 } 4411 4412 MaybeLocal<String> v8::Object::ObjectProtoToString(Local<Context> context) { 4413 PREPARE_FOR_EXECUTION(context, Object, ObjectProtoToString, String); 4414 auto obj = Utils::OpenHandle(this); 4415 Local<String> result; 4416 has_pending_exception = 4417 !ToLocal<String>(i::JSObject::ObjectProtoToString(isolate, obj), &result); 4418 RETURN_ON_FAILED_EXECUTION(String); 4419 RETURN_ESCAPED(result); 4420 } 4421 4422 4423 Local<String> v8::Object::ObjectProtoToString() { 4424 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4425 RETURN_TO_LOCAL_UNCHECKED(ObjectProtoToString(context), String); 4426 } 4427 4428 4429 Local<String> v8::Object::GetConstructorName() { 4430 auto self = Utils::OpenHandle(this); 4431 i::Handle<i::String> name = i::JSReceiver::GetConstructorName(self); 4432 return Utils::ToLocal(name); 4433 } 4434 4435 Maybe<bool> v8::Object::SetIntegrityLevel(Local<Context> context, 4436 IntegrityLevel level) { 4437 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, SetIntegrityLevel, bool); 4438 auto self = Utils::OpenHandle(this); 4439 i::JSReceiver::IntegrityLevel i_level = 4440 level == IntegrityLevel::kFrozen ? i::FROZEN : i::SEALED; 4441 Maybe<bool> result = 4442 i::JSReceiver::SetIntegrityLevel(self, i_level, i::Object::DONT_THROW); 4443 has_pending_exception = result.IsNothing(); 4444 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4445 return result; 4446 } 4447 4448 Maybe<bool> v8::Object::Delete(Local<Context> context, Local<Value> key) { 4449 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Delete, bool); 4450 auto self = Utils::OpenHandle(this); 4451 auto key_obj = Utils::OpenHandle(*key); 4452 Maybe<bool> result = 4453 i::Runtime::DeleteObjectProperty(isolate, self, key_obj, i::SLOPPY); 4454 has_pending_exception = result.IsNothing(); 4455 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4456 return result; 4457 } 4458 4459 4460 bool v8::Object::Delete(v8::Local<Value> key) { 4461 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4462 return Delete(context, key).FromMaybe(false); 4463 } 4464 4465 4466 Maybe<bool> v8::Object::DeletePrivate(Local<Context> context, 4467 Local<Private> key) { 4468 return Delete(context, Local<Value>(reinterpret_cast<Value*>(*key))); 4469 } 4470 4471 4472 Maybe<bool> v8::Object::Has(Local<Context> context, Local<Value> key) { 4473 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Get, bool); 4474 auto self = Utils::OpenHandle(this); 4475 auto key_obj = Utils::OpenHandle(*key); 4476 Maybe<bool> maybe = Nothing<bool>(); 4477 // Check if the given key is an array index. 4478 uint32_t index = 0; 4479 if (key_obj->ToArrayIndex(&index)) { 4480 maybe = i::JSReceiver::HasElement(self, index); 4481 } else { 4482 // Convert the key to a name - possibly by calling back into JavaScript. 4483 i::Handle<i::Name> name; 4484 if (i::Object::ToName(isolate, key_obj).ToHandle(&name)) { 4485 maybe = i::JSReceiver::HasProperty(self, name); 4486 } 4487 } 4488 has_pending_exception = maybe.IsNothing(); 4489 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4490 return maybe; 4491 } 4492 4493 4494 bool v8::Object::Has(v8::Local<Value> key) { 4495 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4496 return Has(context, key).FromMaybe(false); 4497 } 4498 4499 4500 Maybe<bool> v8::Object::HasPrivate(Local<Context> context, Local<Private> key) { 4501 return HasOwnProperty(context, Local<Name>(reinterpret_cast<Name*>(*key))); 4502 } 4503 4504 4505 Maybe<bool> v8::Object::Delete(Local<Context> context, uint32_t index) { 4506 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, DeleteProperty, bool); 4507 auto self = Utils::OpenHandle(this); 4508 Maybe<bool> result = i::JSReceiver::DeleteElement(self, index); 4509 has_pending_exception = result.IsNothing(); 4510 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4511 return result; 4512 } 4513 4514 4515 bool v8::Object::Delete(uint32_t index) { 4516 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4517 return Delete(context, index).FromMaybe(false); 4518 } 4519 4520 4521 Maybe<bool> v8::Object::Has(Local<Context> context, uint32_t index) { 4522 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, Get, bool); 4523 auto self = Utils::OpenHandle(this); 4524 auto maybe = i::JSReceiver::HasElement(self, index); 4525 has_pending_exception = maybe.IsNothing(); 4526 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4527 return maybe; 4528 } 4529 4530 4531 bool v8::Object::Has(uint32_t index) { 4532 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4533 return Has(context, index).FromMaybe(false); 4534 } 4535 4536 4537 template <typename Getter, typename Setter, typename Data> 4538 static Maybe<bool> ObjectSetAccessor(Local<Context> context, Object* self, 4539 Local<Name> name, Getter getter, 4540 Setter setter, Data data, 4541 AccessControl settings, 4542 PropertyAttribute attributes) { 4543 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, SetAccessor, bool); 4544 if (!Utils::OpenHandle(self)->IsJSObject()) return Just(false); 4545 i::Handle<i::JSObject> obj = 4546 i::Handle<i::JSObject>::cast(Utils::OpenHandle(self)); 4547 v8::Local<AccessorSignature> signature; 4548 auto info = 4549 MakeAccessorInfo(name, getter, setter, data, settings, attributes, 4550 signature, i::FLAG_disable_old_api_accessors, false); 4551 if (info.is_null()) return Nothing<bool>(); 4552 bool fast = obj->HasFastProperties(); 4553 i::Handle<i::Object> result; 4554 has_pending_exception = 4555 !i::JSObject::SetAccessor(obj, info).ToHandle(&result); 4556 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4557 if (result->IsUndefined(obj->GetIsolate())) return Nothing<bool>(); 4558 if (fast) { 4559 i::JSObject::MigrateSlowToFast(obj, 0, "APISetAccessor"); 4560 } 4561 return Just(true); 4562 } 4563 4564 4565 Maybe<bool> Object::SetAccessor(Local<Context> context, Local<Name> name, 4566 AccessorNameGetterCallback getter, 4567 AccessorNameSetterCallback setter, 4568 MaybeLocal<Value> data, AccessControl settings, 4569 PropertyAttribute attribute) { 4570 return ObjectSetAccessor(context, this, name, getter, setter, 4571 data.FromMaybe(Local<Value>()), settings, attribute); 4572 } 4573 4574 4575 bool Object::SetAccessor(Local<String> name, AccessorGetterCallback getter, 4576 AccessorSetterCallback setter, v8::Local<Value> data, 4577 AccessControl settings, PropertyAttribute attributes) { 4578 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4579 return ObjectSetAccessor(context, this, name, getter, setter, data, settings, 4580 attributes).FromMaybe(false); 4581 } 4582 4583 4584 bool Object::SetAccessor(Local<Name> name, AccessorNameGetterCallback getter, 4585 AccessorNameSetterCallback setter, 4586 v8::Local<Value> data, AccessControl settings, 4587 PropertyAttribute attributes) { 4588 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4589 return ObjectSetAccessor(context, this, name, getter, setter, data, settings, 4590 attributes).FromMaybe(false); 4591 } 4592 4593 4594 void Object::SetAccessorProperty(Local<Name> name, Local<Function> getter, 4595 Local<Function> setter, 4596 PropertyAttribute attribute, 4597 AccessControl settings) { 4598 // TODO(verwaest): Remove |settings|. 4599 DCHECK_EQ(v8::DEFAULT, settings); 4600 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 4601 ENTER_V8(isolate); 4602 i::HandleScope scope(isolate); 4603 auto self = Utils::OpenHandle(this); 4604 if (!self->IsJSObject()) return; 4605 i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter); 4606 i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true); 4607 if (setter_i.is_null()) setter_i = isolate->factory()->null_value(); 4608 i::JSObject::DefineAccessor(i::Handle<i::JSObject>::cast(self), 4609 v8::Utils::OpenHandle(*name), getter_i, setter_i, 4610 static_cast<i::PropertyAttributes>(attribute)); 4611 } 4612 4613 4614 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context, 4615 Local<Name> key) { 4616 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, HasOwnProperty, bool); 4617 auto self = Utils::OpenHandle(this); 4618 auto key_val = Utils::OpenHandle(*key); 4619 auto result = i::JSReceiver::HasOwnProperty(self, key_val); 4620 has_pending_exception = result.IsNothing(); 4621 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4622 return result; 4623 } 4624 4625 Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context, uint32_t index) { 4626 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, HasOwnProperty, bool); 4627 auto self = Utils::OpenHandle(this); 4628 auto result = i::JSReceiver::HasOwnProperty(self, index); 4629 has_pending_exception = result.IsNothing(); 4630 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4631 return result; 4632 } 4633 4634 bool v8::Object::HasOwnProperty(Local<String> key) { 4635 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4636 return HasOwnProperty(context, key).FromMaybe(false); 4637 } 4638 4639 4640 Maybe<bool> v8::Object::HasRealNamedProperty(Local<Context> context, 4641 Local<Name> key) { 4642 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, HasRealNamedProperty, bool); 4643 auto self = Utils::OpenHandle(this); 4644 if (!self->IsJSObject()) return Just(false); 4645 auto key_val = Utils::OpenHandle(*key); 4646 auto result = i::JSObject::HasRealNamedProperty( 4647 i::Handle<i::JSObject>::cast(self), key_val); 4648 has_pending_exception = result.IsNothing(); 4649 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4650 return result; 4651 } 4652 4653 4654 bool v8::Object::HasRealNamedProperty(Local<String> key) { 4655 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4656 return HasRealNamedProperty(context, key).FromMaybe(false); 4657 } 4658 4659 4660 Maybe<bool> v8::Object::HasRealIndexedProperty(Local<Context> context, 4661 uint32_t index) { 4662 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, HasRealIndexedProperty, 4663 bool); 4664 auto self = Utils::OpenHandle(this); 4665 if (!self->IsJSObject()) return Just(false); 4666 auto result = i::JSObject::HasRealElementProperty( 4667 i::Handle<i::JSObject>::cast(self), index); 4668 has_pending_exception = result.IsNothing(); 4669 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4670 return result; 4671 } 4672 4673 4674 bool v8::Object::HasRealIndexedProperty(uint32_t index) { 4675 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4676 return HasRealIndexedProperty(context, index).FromMaybe(false); 4677 } 4678 4679 4680 Maybe<bool> v8::Object::HasRealNamedCallbackProperty(Local<Context> context, 4681 Local<Name> key) { 4682 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Object, HasRealNamedCallbackProperty, 4683 bool); 4684 auto self = Utils::OpenHandle(this); 4685 if (!self->IsJSObject()) return Just(false); 4686 auto key_val = Utils::OpenHandle(*key); 4687 auto result = i::JSObject::HasRealNamedCallbackProperty( 4688 i::Handle<i::JSObject>::cast(self), key_val); 4689 has_pending_exception = result.IsNothing(); 4690 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 4691 return result; 4692 } 4693 4694 4695 bool v8::Object::HasRealNamedCallbackProperty(Local<String> key) { 4696 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4697 return HasRealNamedCallbackProperty(context, key).FromMaybe(false); 4698 } 4699 4700 4701 bool v8::Object::HasNamedLookupInterceptor() { 4702 auto self = Utils::OpenHandle(this); 4703 return self->IsJSObject() && 4704 i::Handle<i::JSObject>::cast(self)->HasNamedInterceptor(); 4705 } 4706 4707 4708 bool v8::Object::HasIndexedLookupInterceptor() { 4709 auto self = Utils::OpenHandle(this); 4710 return self->IsJSObject() && 4711 i::Handle<i::JSObject>::cast(self)->HasIndexedInterceptor(); 4712 } 4713 4714 4715 MaybeLocal<Value> v8::Object::GetRealNamedPropertyInPrototypeChain( 4716 Local<Context> context, Local<Name> key) { 4717 PREPARE_FOR_EXECUTION(context, Object, GetRealNamedPropertyInPrototypeChain, 4718 Value); 4719 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 4720 if (!self->IsJSObject()) return MaybeLocal<Value>(); 4721 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key); 4722 i::PrototypeIterator iter(isolate, self); 4723 if (iter.IsAtEnd()) return MaybeLocal<Value>(); 4724 i::Handle<i::JSReceiver> proto = 4725 i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter); 4726 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 4727 isolate, self, key_obj, proto, 4728 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR); 4729 Local<Value> result; 4730 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result); 4731 RETURN_ON_FAILED_EXECUTION(Value); 4732 if (!it.IsFound()) return MaybeLocal<Value>(); 4733 RETURN_ESCAPED(result); 4734 } 4735 4736 4737 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain( 4738 Local<String> key) { 4739 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4740 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedPropertyInPrototypeChain(context, key), 4741 Value); 4742 } 4743 4744 4745 Maybe<PropertyAttribute> 4746 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain( 4747 Local<Context> context, Local<Name> key) { 4748 PREPARE_FOR_EXECUTION_PRIMITIVE( 4749 context, Object, GetRealNamedPropertyAttributesInPrototypeChain, 4750 PropertyAttribute); 4751 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 4752 if (!self->IsJSObject()) return Nothing<PropertyAttribute>(); 4753 i::Handle<i::Name> key_obj = Utils::OpenHandle(*key); 4754 i::PrototypeIterator iter(isolate, self); 4755 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>(); 4756 i::Handle<i::JSReceiver> proto = 4757 i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter); 4758 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 4759 isolate, self, key_obj, proto, 4760 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR); 4761 Maybe<i::PropertyAttributes> result = 4762 i::JSReceiver::GetPropertyAttributes(&it); 4763 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute); 4764 if (!it.IsFound()) return Nothing<PropertyAttribute>(); 4765 if (result.FromJust() == i::ABSENT) return Just(None); 4766 return Just(static_cast<PropertyAttribute>(result.FromJust())); 4767 } 4768 4769 4770 Maybe<PropertyAttribute> 4771 v8::Object::GetRealNamedPropertyAttributesInPrototypeChain(Local<String> key) { 4772 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4773 return GetRealNamedPropertyAttributesInPrototypeChain(context, key); 4774 } 4775 4776 4777 MaybeLocal<Value> v8::Object::GetRealNamedProperty(Local<Context> context, 4778 Local<Name> key) { 4779 PREPARE_FOR_EXECUTION(context, Object, GetRealNamedProperty, Value); 4780 auto self = Utils::OpenHandle(this); 4781 auto key_obj = Utils::OpenHandle(*key); 4782 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 4783 isolate, self, key_obj, self, 4784 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR); 4785 Local<Value> result; 4786 has_pending_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result); 4787 RETURN_ON_FAILED_EXECUTION(Value); 4788 if (!it.IsFound()) return MaybeLocal<Value>(); 4789 RETURN_ESCAPED(result); 4790 } 4791 4792 4793 Local<Value> v8::Object::GetRealNamedProperty(Local<String> key) { 4794 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4795 RETURN_TO_LOCAL_UNCHECKED(GetRealNamedProperty(context, key), Value); 4796 } 4797 4798 4799 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes( 4800 Local<Context> context, Local<Name> key) { 4801 PREPARE_FOR_EXECUTION_PRIMITIVE( 4802 context, Object, GetRealNamedPropertyAttributes, PropertyAttribute); 4803 auto self = Utils::OpenHandle(this); 4804 auto key_obj = Utils::OpenHandle(*key); 4805 i::LookupIterator it = i::LookupIterator::PropertyOrElement( 4806 isolate, self, key_obj, self, 4807 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR); 4808 auto result = i::JSReceiver::GetPropertyAttributes(&it); 4809 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(PropertyAttribute); 4810 if (!it.IsFound()) return Nothing<PropertyAttribute>(); 4811 if (result.FromJust() == i::ABSENT) { 4812 return Just(static_cast<PropertyAttribute>(i::NONE)); 4813 } 4814 return Just<PropertyAttribute>( 4815 static_cast<PropertyAttribute>(result.FromJust())); 4816 } 4817 4818 4819 Maybe<PropertyAttribute> v8::Object::GetRealNamedPropertyAttributes( 4820 Local<String> key) { 4821 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4822 return GetRealNamedPropertyAttributes(context, key); 4823 } 4824 4825 4826 Local<v8::Object> v8::Object::Clone() { 4827 auto self = i::Handle<i::JSObject>::cast(Utils::OpenHandle(this)); 4828 auto isolate = self->GetIsolate(); 4829 ENTER_V8(isolate); 4830 auto result = isolate->factory()->CopyJSObject(self); 4831 CHECK(!result.is_null()); 4832 return Utils::ToLocal(result); 4833 } 4834 4835 4836 Local<v8::Context> v8::Object::CreationContext() { 4837 auto self = Utils::OpenHandle(this); 4838 auto context = handle(self->GetCreationContext()); 4839 return Utils::ToLocal(context); 4840 } 4841 4842 4843 int v8::Object::GetIdentityHash() { 4844 auto isolate = Utils::OpenHandle(this)->GetIsolate(); 4845 i::HandleScope scope(isolate); 4846 auto self = Utils::OpenHandle(this); 4847 return i::JSReceiver::GetOrCreateIdentityHash(isolate, self)->value(); 4848 } 4849 4850 4851 bool v8::Object::IsCallable() { 4852 auto self = Utils::OpenHandle(this); 4853 return self->IsCallable(); 4854 } 4855 4856 bool v8::Object::IsConstructor() { 4857 auto self = Utils::OpenHandle(this); 4858 return self->IsConstructor(); 4859 } 4860 4861 MaybeLocal<Value> Object::CallAsFunction(Local<Context> context, 4862 Local<Value> recv, int argc, 4863 Local<Value> argv[]) { 4864 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 4865 "v8", "V8.Execute", context, Object, CallAsFunction, MaybeLocal<Value>(), 4866 InternalEscapableScope, true); 4867 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 4868 auto self = Utils::OpenHandle(this); 4869 auto recv_obj = Utils::OpenHandle(*recv); 4870 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**)); 4871 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv); 4872 Local<Value> result; 4873 has_pending_exception = !ToLocal<Value>( 4874 i::Execution::Call(isolate, self, recv_obj, argc, args), &result); 4875 RETURN_ON_FAILED_EXECUTION(Value); 4876 RETURN_ESCAPED(result); 4877 } 4878 4879 4880 Local<v8::Value> Object::CallAsFunction(v8::Local<v8::Value> recv, int argc, 4881 v8::Local<v8::Value> argv[]) { 4882 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4883 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv); 4884 RETURN_TO_LOCAL_UNCHECKED(CallAsFunction(context, recv, argc, argv_cast), 4885 Value); 4886 } 4887 4888 4889 MaybeLocal<Value> Object::CallAsConstructor(Local<Context> context, int argc, 4890 Local<Value> argv[]) { 4891 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 4892 "v8", "V8.Execute", context, Object, CallAsConstructor, 4893 MaybeLocal<Value>(), InternalEscapableScope, true); 4894 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 4895 auto self = Utils::OpenHandle(this); 4896 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**)); 4897 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv); 4898 Local<Value> result; 4899 has_pending_exception = !ToLocal<Value>( 4900 i::Execution::New(isolate, self, self, argc, args), &result); 4901 RETURN_ON_FAILED_EXECUTION(Value); 4902 RETURN_ESCAPED(result); 4903 } 4904 4905 4906 Local<v8::Value> Object::CallAsConstructor(int argc, 4907 v8::Local<v8::Value> argv[]) { 4908 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4909 Local<Value>* argv_cast = reinterpret_cast<Local<Value>*>(argv); 4910 RETURN_TO_LOCAL_UNCHECKED(CallAsConstructor(context, argc, argv_cast), Value); 4911 } 4912 4913 MaybeLocal<Function> Function::New(Local<Context> context, 4914 FunctionCallback callback, Local<Value> data, 4915 int length, ConstructorBehavior behavior) { 4916 i::Isolate* isolate = Utils::OpenHandle(*context)->GetIsolate(); 4917 LOG_API(isolate, Function, New); 4918 ENTER_V8(isolate); 4919 auto templ = FunctionTemplateNew(isolate, callback, nullptr, data, 4920 Local<Signature>(), length, true); 4921 if (behavior == ConstructorBehavior::kThrow) templ->RemovePrototype(); 4922 return templ->GetFunction(context); 4923 } 4924 4925 4926 Local<Function> Function::New(Isolate* v8_isolate, FunctionCallback callback, 4927 Local<Value> data, int length) { 4928 return Function::New(v8_isolate->GetCurrentContext(), callback, data, length, 4929 ConstructorBehavior::kAllow) 4930 .FromMaybe(Local<Function>()); 4931 } 4932 4933 4934 Local<v8::Object> Function::NewInstance() const { 4935 return NewInstance(Isolate::GetCurrent()->GetCurrentContext(), 0, NULL) 4936 .FromMaybe(Local<Object>()); 4937 } 4938 4939 4940 MaybeLocal<Object> Function::NewInstance(Local<Context> context, int argc, 4941 v8::Local<v8::Value> argv[]) const { 4942 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 4943 "v8", "V8.Execute", context, Function, NewInstance, MaybeLocal<Object>(), 4944 InternalEscapableScope, true); 4945 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 4946 auto self = Utils::OpenHandle(this); 4947 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**)); 4948 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv); 4949 Local<Object> result; 4950 has_pending_exception = !ToLocal<Object>( 4951 i::Execution::New(isolate, self, self, argc, args), &result); 4952 RETURN_ON_FAILED_EXECUTION(Object); 4953 RETURN_ESCAPED(result); 4954 } 4955 4956 4957 Local<v8::Object> Function::NewInstance(int argc, 4958 v8::Local<v8::Value> argv[]) const { 4959 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4960 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context, argc, argv), Object); 4961 } 4962 4963 4964 MaybeLocal<v8::Value> Function::Call(Local<Context> context, 4965 v8::Local<v8::Value> recv, int argc, 4966 v8::Local<v8::Value> argv[]) { 4967 PREPARE_FOR_EXECUTION_WITH_CONTEXT_IN_RUNTIME_CALL_STATS_SCOPE( 4968 "v8", "V8.Execute", context, Function, Call, MaybeLocal<Value>(), 4969 InternalEscapableScope, true); 4970 i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate); 4971 auto self = Utils::OpenHandle(this); 4972 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv); 4973 STATIC_ASSERT(sizeof(v8::Local<v8::Value>) == sizeof(i::Object**)); 4974 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv); 4975 Local<Value> result; 4976 has_pending_exception = !ToLocal<Value>( 4977 i::Execution::Call(isolate, self, recv_obj, argc, args), &result); 4978 RETURN_ON_FAILED_EXECUTION(Value); 4979 RETURN_ESCAPED(result); 4980 } 4981 4982 4983 Local<v8::Value> Function::Call(v8::Local<v8::Value> recv, int argc, 4984 v8::Local<v8::Value> argv[]) { 4985 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 4986 RETURN_TO_LOCAL_UNCHECKED(Call(context, recv, argc, argv), Value); 4987 } 4988 4989 4990 void Function::SetName(v8::Local<v8::String> name) { 4991 auto self = Utils::OpenHandle(this); 4992 if (!self->IsJSFunction()) return; 4993 auto func = i::Handle<i::JSFunction>::cast(self); 4994 func->shared()->set_name(*Utils::OpenHandle(*name)); 4995 } 4996 4997 4998 Local<Value> Function::GetName() const { 4999 auto self = Utils::OpenHandle(this); 5000 i::Isolate* isolate = self->GetIsolate(); 5001 if (self->IsJSBoundFunction()) { 5002 auto func = i::Handle<i::JSBoundFunction>::cast(self); 5003 i::Handle<i::Object> name; 5004 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, name, 5005 i::JSBoundFunction::GetName(isolate, func), 5006 Local<Value>()); 5007 return Utils::ToLocal(name); 5008 } 5009 if (self->IsJSFunction()) { 5010 auto func = i::Handle<i::JSFunction>::cast(self); 5011 return Utils::ToLocal(handle(func->shared()->name(), isolate)); 5012 } 5013 return ToApiHandle<Primitive>(isolate->factory()->undefined_value()); 5014 } 5015 5016 5017 Local<Value> Function::GetInferredName() const { 5018 auto self = Utils::OpenHandle(this); 5019 if (!self->IsJSFunction()) { 5020 return ToApiHandle<Primitive>( 5021 self->GetIsolate()->factory()->undefined_value()); 5022 } 5023 auto func = i::Handle<i::JSFunction>::cast(self); 5024 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(), 5025 func->GetIsolate())); 5026 } 5027 5028 5029 Local<Value> Function::GetDebugName() const { 5030 auto self = Utils::OpenHandle(this); 5031 if (!self->IsJSFunction()) { 5032 return ToApiHandle<Primitive>( 5033 self->GetIsolate()->factory()->undefined_value()); 5034 } 5035 auto func = i::Handle<i::JSFunction>::cast(self); 5036 i::Handle<i::String> name = i::JSFunction::GetDebugName(func); 5037 return Utils::ToLocal(i::Handle<i::Object>(*name, name->GetIsolate())); 5038 } 5039 5040 5041 Local<Value> Function::GetDisplayName() const { 5042 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 5043 ENTER_V8(isolate); 5044 auto self = Utils::OpenHandle(this); 5045 if (!self->IsJSFunction()) { 5046 return ToApiHandle<Primitive>(isolate->factory()->undefined_value()); 5047 } 5048 auto func = i::Handle<i::JSFunction>::cast(self); 5049 i::Handle<i::String> property_name = 5050 isolate->factory()->NewStringFromStaticChars("displayName"); 5051 i::Handle<i::Object> value = 5052 i::JSReceiver::GetDataProperty(func, property_name); 5053 if (value->IsString()) { 5054 i::Handle<i::String> name = i::Handle<i::String>::cast(value); 5055 if (name->length() > 0) return Utils::ToLocal(name); 5056 } 5057 return ToApiHandle<Primitive>(isolate->factory()->undefined_value()); 5058 } 5059 5060 5061 ScriptOrigin Function::GetScriptOrigin() const { 5062 auto self = Utils::OpenHandle(this); 5063 if (!self->IsJSFunction()) { 5064 return v8::ScriptOrigin(Local<Value>()); 5065 } 5066 auto func = i::Handle<i::JSFunction>::cast(self); 5067 if (func->shared()->script()->IsScript()) { 5068 i::Handle<i::Script> script(i::Script::cast(func->shared()->script())); 5069 return GetScriptOriginForScript(func->GetIsolate(), script); 5070 } 5071 return v8::ScriptOrigin(Local<Value>()); 5072 } 5073 5074 5075 const int Function::kLineOffsetNotFound = -1; 5076 5077 5078 int Function::GetScriptLineNumber() const { 5079 auto self = Utils::OpenHandle(this); 5080 if (!self->IsJSFunction()) { 5081 return kLineOffsetNotFound; 5082 } 5083 auto func = i::Handle<i::JSFunction>::cast(self); 5084 if (func->shared()->script()->IsScript()) { 5085 i::Handle<i::Script> script(i::Script::cast(func->shared()->script())); 5086 return i::Script::GetLineNumber(script, func->shared()->start_position()); 5087 } 5088 return kLineOffsetNotFound; 5089 } 5090 5091 5092 int Function::GetScriptColumnNumber() const { 5093 auto self = Utils::OpenHandle(this); 5094 if (!self->IsJSFunction()) { 5095 return kLineOffsetNotFound; 5096 } 5097 auto func = i::Handle<i::JSFunction>::cast(self); 5098 if (func->shared()->script()->IsScript()) { 5099 i::Handle<i::Script> script(i::Script::cast(func->shared()->script())); 5100 return i::Script::GetColumnNumber(script, func->shared()->start_position()); 5101 } 5102 return kLineOffsetNotFound; 5103 } 5104 5105 5106 bool Function::IsBuiltin() const { 5107 auto self = Utils::OpenHandle(this); 5108 if (!self->IsJSFunction()) { 5109 return false; 5110 } 5111 auto func = i::Handle<i::JSFunction>::cast(self); 5112 return func->shared()->IsBuiltin(); 5113 } 5114 5115 5116 int Function::ScriptId() const { 5117 auto self = Utils::OpenHandle(this); 5118 if (!self->IsJSFunction()) { 5119 return v8::UnboundScript::kNoScriptId; 5120 } 5121 auto func = i::Handle<i::JSFunction>::cast(self); 5122 if (!func->shared()->script()->IsScript()) { 5123 return v8::UnboundScript::kNoScriptId; 5124 } 5125 i::Handle<i::Script> script(i::Script::cast(func->shared()->script())); 5126 return script->id(); 5127 } 5128 5129 5130 Local<v8::Value> Function::GetBoundFunction() const { 5131 auto self = Utils::OpenHandle(this); 5132 if (self->IsJSBoundFunction()) { 5133 auto bound_function = i::Handle<i::JSBoundFunction>::cast(self); 5134 auto bound_target_function = i::handle( 5135 bound_function->bound_target_function(), bound_function->GetIsolate()); 5136 return Utils::CallableToLocal(bound_target_function); 5137 } 5138 return v8::Undefined(reinterpret_cast<v8::Isolate*>(self->GetIsolate())); 5139 } 5140 5141 5142 int Name::GetIdentityHash() { 5143 auto self = Utils::OpenHandle(this); 5144 return static_cast<int>(self->Hash()); 5145 } 5146 5147 5148 int String::Length() const { 5149 i::Handle<i::String> str = Utils::OpenHandle(this); 5150 return str->length(); 5151 } 5152 5153 5154 bool String::IsOneByte() const { 5155 i::Handle<i::String> str = Utils::OpenHandle(this); 5156 return str->HasOnlyOneByteChars(); 5157 } 5158 5159 5160 // Helpers for ContainsOnlyOneByteHelper 5161 template<size_t size> struct OneByteMask; 5162 template<> struct OneByteMask<4> { 5163 static const uint32_t value = 0xFF00FF00; 5164 }; 5165 template<> struct OneByteMask<8> { 5166 static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00); 5167 }; 5168 static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value; 5169 static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1; 5170 static inline bool Unaligned(const uint16_t* chars) { 5171 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask; 5172 } 5173 5174 5175 static inline const uint16_t* Align(const uint16_t* chars) { 5176 return reinterpret_cast<uint16_t*>( 5177 reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask); 5178 } 5179 5180 class ContainsOnlyOneByteHelper { 5181 public: 5182 ContainsOnlyOneByteHelper() : is_one_byte_(true) {} 5183 bool Check(i::String* string) { 5184 i::ConsString* cons_string = i::String::VisitFlat(this, string, 0); 5185 if (cons_string == NULL) return is_one_byte_; 5186 return CheckCons(cons_string); 5187 } 5188 void VisitOneByteString(const uint8_t* chars, int length) { 5189 // Nothing to do. 5190 } 5191 void VisitTwoByteString(const uint16_t* chars, int length) { 5192 // Accumulated bits. 5193 uintptr_t acc = 0; 5194 // Align to uintptr_t. 5195 const uint16_t* end = chars + length; 5196 while (Unaligned(chars) && chars != end) { 5197 acc |= *chars++; 5198 } 5199 // Read word aligned in blocks, 5200 // checking the return value at the end of each block. 5201 const uint16_t* aligned_end = Align(end); 5202 const int increment = sizeof(uintptr_t)/sizeof(uint16_t); 5203 const int inner_loops = 16; 5204 while (chars + inner_loops*increment < aligned_end) { 5205 for (int i = 0; i < inner_loops; i++) { 5206 acc |= *reinterpret_cast<const uintptr_t*>(chars); 5207 chars += increment; 5208 } 5209 // Check for early return. 5210 if ((acc & kOneByteMask) != 0) { 5211 is_one_byte_ = false; 5212 return; 5213 } 5214 } 5215 // Read the rest. 5216 while (chars != end) { 5217 acc |= *chars++; 5218 } 5219 // Check result. 5220 if ((acc & kOneByteMask) != 0) is_one_byte_ = false; 5221 } 5222 5223 private: 5224 bool CheckCons(i::ConsString* cons_string) { 5225 while (true) { 5226 // Check left side if flat. 5227 i::String* left = cons_string->first(); 5228 i::ConsString* left_as_cons = 5229 i::String::VisitFlat(this, left, 0); 5230 if (!is_one_byte_) return false; 5231 // Check right side if flat. 5232 i::String* right = cons_string->second(); 5233 i::ConsString* right_as_cons = 5234 i::String::VisitFlat(this, right, 0); 5235 if (!is_one_byte_) return false; 5236 // Standard recurse/iterate trick. 5237 if (left_as_cons != NULL && right_as_cons != NULL) { 5238 if (left->length() < right->length()) { 5239 CheckCons(left_as_cons); 5240 cons_string = right_as_cons; 5241 } else { 5242 CheckCons(right_as_cons); 5243 cons_string = left_as_cons; 5244 } 5245 // Check fast return. 5246 if (!is_one_byte_) return false; 5247 continue; 5248 } 5249 // Descend left in place. 5250 if (left_as_cons != NULL) { 5251 cons_string = left_as_cons; 5252 continue; 5253 } 5254 // Descend right in place. 5255 if (right_as_cons != NULL) { 5256 cons_string = right_as_cons; 5257 continue; 5258 } 5259 // Terminate. 5260 break; 5261 } 5262 return is_one_byte_; 5263 } 5264 bool is_one_byte_; 5265 DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper); 5266 }; 5267 5268 5269 bool String::ContainsOnlyOneByte() const { 5270 i::Handle<i::String> str = Utils::OpenHandle(this); 5271 if (str->HasOnlyOneByteChars()) return true; 5272 ContainsOnlyOneByteHelper helper; 5273 return helper.Check(*str); 5274 } 5275 5276 5277 class Utf8LengthHelper : public i::AllStatic { 5278 public: 5279 enum State { 5280 kEndsWithLeadingSurrogate = 1 << 0, 5281 kStartsWithTrailingSurrogate = 1 << 1, 5282 kLeftmostEdgeIsCalculated = 1 << 2, 5283 kRightmostEdgeIsCalculated = 1 << 3, 5284 kLeftmostEdgeIsSurrogate = 1 << 4, 5285 kRightmostEdgeIsSurrogate = 1 << 5 5286 }; 5287 5288 static const uint8_t kInitialState = 0; 5289 5290 static inline bool EndsWithSurrogate(uint8_t state) { 5291 return state & kEndsWithLeadingSurrogate; 5292 } 5293 5294 static inline bool StartsWithSurrogate(uint8_t state) { 5295 return state & kStartsWithTrailingSurrogate; 5296 } 5297 5298 class Visitor { 5299 public: 5300 Visitor() : utf8_length_(0), state_(kInitialState) {} 5301 5302 void VisitOneByteString(const uint8_t* chars, int length) { 5303 int utf8_length = 0; 5304 // Add in length 1 for each non-Latin1 character. 5305 for (int i = 0; i < length; i++) { 5306 utf8_length += *chars++ >> 7; 5307 } 5308 // Add in length 1 for each character. 5309 utf8_length_ = utf8_length + length; 5310 state_ = kInitialState; 5311 } 5312 5313 void VisitTwoByteString(const uint16_t* chars, int length) { 5314 int utf8_length = 0; 5315 int last_character = unibrow::Utf16::kNoPreviousCharacter; 5316 for (int i = 0; i < length; i++) { 5317 uint16_t c = chars[i]; 5318 utf8_length += unibrow::Utf8::Length(c, last_character); 5319 last_character = c; 5320 } 5321 utf8_length_ = utf8_length; 5322 uint8_t state = 0; 5323 if (unibrow::Utf16::IsTrailSurrogate(chars[0])) { 5324 state |= kStartsWithTrailingSurrogate; 5325 } 5326 if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) { 5327 state |= kEndsWithLeadingSurrogate; 5328 } 5329 state_ = state; 5330 } 5331 5332 static i::ConsString* VisitFlat(i::String* string, 5333 int* length, 5334 uint8_t* state) { 5335 Visitor visitor; 5336 i::ConsString* cons_string = i::String::VisitFlat(&visitor, string); 5337 *length = visitor.utf8_length_; 5338 *state = visitor.state_; 5339 return cons_string; 5340 } 5341 5342 private: 5343 int utf8_length_; 5344 uint8_t state_; 5345 DISALLOW_COPY_AND_ASSIGN(Visitor); 5346 }; 5347 5348 static inline void MergeLeafLeft(int* length, 5349 uint8_t* state, 5350 uint8_t leaf_state) { 5351 bool edge_surrogate = StartsWithSurrogate(leaf_state); 5352 if (!(*state & kLeftmostEdgeIsCalculated)) { 5353 DCHECK(!(*state & kLeftmostEdgeIsSurrogate)); 5354 *state |= kLeftmostEdgeIsCalculated 5355 | (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0); 5356 } else if (EndsWithSurrogate(*state) && edge_surrogate) { 5357 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates; 5358 } 5359 if (EndsWithSurrogate(leaf_state)) { 5360 *state |= kEndsWithLeadingSurrogate; 5361 } else { 5362 *state &= ~kEndsWithLeadingSurrogate; 5363 } 5364 } 5365 5366 static inline void MergeLeafRight(int* length, 5367 uint8_t* state, 5368 uint8_t leaf_state) { 5369 bool edge_surrogate = EndsWithSurrogate(leaf_state); 5370 if (!(*state & kRightmostEdgeIsCalculated)) { 5371 DCHECK(!(*state & kRightmostEdgeIsSurrogate)); 5372 *state |= (kRightmostEdgeIsCalculated 5373 | (edge_surrogate ? kRightmostEdgeIsSurrogate : 0)); 5374 } else if (edge_surrogate && StartsWithSurrogate(*state)) { 5375 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates; 5376 } 5377 if (StartsWithSurrogate(leaf_state)) { 5378 *state |= kStartsWithTrailingSurrogate; 5379 } else { 5380 *state &= ~kStartsWithTrailingSurrogate; 5381 } 5382 } 5383 5384 static inline void MergeTerminal(int* length, 5385 uint8_t state, 5386 uint8_t* state_out) { 5387 DCHECK((state & kLeftmostEdgeIsCalculated) && 5388 (state & kRightmostEdgeIsCalculated)); 5389 if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) { 5390 *length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates; 5391 } 5392 *state_out = kInitialState | 5393 (state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) | 5394 (state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0); 5395 } 5396 5397 static int Calculate(i::ConsString* current, uint8_t* state_out) { 5398 using internal::ConsString; 5399 int total_length = 0; 5400 uint8_t state = kInitialState; 5401 while (true) { 5402 i::String* left = current->first(); 5403 i::String* right = current->second(); 5404 uint8_t right_leaf_state; 5405 uint8_t left_leaf_state; 5406 int leaf_length; 5407 ConsString* left_as_cons = 5408 Visitor::VisitFlat(left, &leaf_length, &left_leaf_state); 5409 if (left_as_cons == NULL) { 5410 total_length += leaf_length; 5411 MergeLeafLeft(&total_length, &state, left_leaf_state); 5412 } 5413 ConsString* right_as_cons = 5414 Visitor::VisitFlat(right, &leaf_length, &right_leaf_state); 5415 if (right_as_cons == NULL) { 5416 total_length += leaf_length; 5417 MergeLeafRight(&total_length, &state, right_leaf_state); 5418 if (left_as_cons != NULL) { 5419 // 1 Leaf node. Descend in place. 5420 current = left_as_cons; 5421 continue; 5422 } else { 5423 // Terminal node. 5424 MergeTerminal(&total_length, state, state_out); 5425 return total_length; 5426 } 5427 } else if (left_as_cons == NULL) { 5428 // 1 Leaf node. Descend in place. 5429 current = right_as_cons; 5430 continue; 5431 } 5432 // Both strings are ConsStrings. 5433 // Recurse on smallest. 5434 if (left->length() < right->length()) { 5435 total_length += Calculate(left_as_cons, &left_leaf_state); 5436 MergeLeafLeft(&total_length, &state, left_leaf_state); 5437 current = right_as_cons; 5438 } else { 5439 total_length += Calculate(right_as_cons, &right_leaf_state); 5440 MergeLeafRight(&total_length, &state, right_leaf_state); 5441 current = left_as_cons; 5442 } 5443 } 5444 UNREACHABLE(); 5445 return 0; 5446 } 5447 5448 static inline int Calculate(i::ConsString* current) { 5449 uint8_t state = kInitialState; 5450 return Calculate(current, &state); 5451 } 5452 5453 private: 5454 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper); 5455 }; 5456 5457 5458 static int Utf8Length(i::String* str, i::Isolate* isolate) { 5459 int length = str->length(); 5460 if (length == 0) return 0; 5461 uint8_t state; 5462 i::ConsString* cons_string = 5463 Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state); 5464 if (cons_string == NULL) return length; 5465 return Utf8LengthHelper::Calculate(cons_string); 5466 } 5467 5468 5469 int String::Utf8Length() const { 5470 i::Handle<i::String> str = Utils::OpenHandle(this); 5471 i::Isolate* isolate = str->GetIsolate(); 5472 return v8::Utf8Length(*str, isolate); 5473 } 5474 5475 5476 class Utf8WriterVisitor { 5477 public: 5478 Utf8WriterVisitor( 5479 char* buffer, 5480 int capacity, 5481 bool skip_capacity_check, 5482 bool replace_invalid_utf8) 5483 : early_termination_(false), 5484 last_character_(unibrow::Utf16::kNoPreviousCharacter), 5485 buffer_(buffer), 5486 start_(buffer), 5487 capacity_(capacity), 5488 skip_capacity_check_(capacity == -1 || skip_capacity_check), 5489 replace_invalid_utf8_(replace_invalid_utf8), 5490 utf16_chars_read_(0) { 5491 } 5492 5493 static int WriteEndCharacter(uint16_t character, 5494 int last_character, 5495 int remaining, 5496 char* const buffer, 5497 bool replace_invalid_utf8) { 5498 DCHECK_GT(remaining, 0); 5499 // We can't use a local buffer here because Encode needs to modify 5500 // previous characters in the stream. We know, however, that 5501 // exactly one character will be advanced. 5502 if (unibrow::Utf16::IsSurrogatePair(last_character, character)) { 5503 int written = unibrow::Utf8::Encode(buffer, character, last_character, 5504 replace_invalid_utf8); 5505 DCHECK_EQ(written, 1); 5506 return written; 5507 } 5508 // Use a scratch buffer to check the required characters. 5509 char temp_buffer[unibrow::Utf8::kMaxEncodedSize]; 5510 // Can't encode using last_character as gcc has array bounds issues. 5511 int written = unibrow::Utf8::Encode(temp_buffer, character, 5512 unibrow::Utf16::kNoPreviousCharacter, 5513 replace_invalid_utf8); 5514 // Won't fit. 5515 if (written > remaining) return 0; 5516 // Copy over the character from temp_buffer. 5517 for (int j = 0; j < written; j++) { 5518 buffer[j] = temp_buffer[j]; 5519 } 5520 return written; 5521 } 5522 5523 // Visit writes out a group of code units (chars) of a v8::String to the 5524 // internal buffer_. This is done in two phases. The first phase calculates a 5525 // pesimistic estimate (writable_length) on how many code units can be safely 5526 // written without exceeding the buffer capacity and without writing the last 5527 // code unit (it could be a lead surrogate). The estimated number of code 5528 // units is then written out in one go, and the reported byte usage is used 5529 // to correct the estimate. This is repeated until the estimate becomes <= 0 5530 // or all code units have been written out. The second phase writes out code 5531 // units until the buffer capacity is reached, would be exceeded by the next 5532 // unit, or all units have been written out. 5533 template<typename Char> 5534 void Visit(const Char* chars, const int length) { 5535 DCHECK(!early_termination_); 5536 if (length == 0) return; 5537 // Copy state to stack. 5538 char* buffer = buffer_; 5539 int last_character = sizeof(Char) == 1 5540 ? unibrow::Utf16::kNoPreviousCharacter 5541 : last_character_; 5542 int i = 0; 5543 // Do a fast loop where there is no exit capacity check. 5544 while (true) { 5545 int fast_length; 5546 if (skip_capacity_check_) { 5547 fast_length = length; 5548 } else { 5549 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_); 5550 // Need enough space to write everything but one character. 5551 STATIC_ASSERT(unibrow::Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 5552 3); 5553 int max_size_per_char = sizeof(Char) == 1 ? 2 : 3; 5554 int writable_length = 5555 (remaining_capacity - max_size_per_char)/max_size_per_char; 5556 // Need to drop into slow loop. 5557 if (writable_length <= 0) break; 5558 fast_length = i + writable_length; 5559 if (fast_length > length) fast_length = length; 5560 } 5561 // Write the characters to the stream. 5562 if (sizeof(Char) == 1) { 5563 for (; i < fast_length; i++) { 5564 buffer += unibrow::Utf8::EncodeOneByte( 5565 buffer, static_cast<uint8_t>(*chars++)); 5566 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_); 5567 } 5568 } else { 5569 for (; i < fast_length; i++) { 5570 uint16_t character = *chars++; 5571 buffer += unibrow::Utf8::Encode(buffer, character, last_character, 5572 replace_invalid_utf8_); 5573 last_character = character; 5574 DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_); 5575 } 5576 } 5577 // Array is fully written. Exit. 5578 if (fast_length == length) { 5579 // Write state back out to object. 5580 last_character_ = last_character; 5581 buffer_ = buffer; 5582 utf16_chars_read_ += length; 5583 return; 5584 } 5585 } 5586 DCHECK(!skip_capacity_check_); 5587 // Slow loop. Must check capacity on each iteration. 5588 int remaining_capacity = capacity_ - static_cast<int>(buffer - start_); 5589 DCHECK_GE(remaining_capacity, 0); 5590 for (; i < length && remaining_capacity > 0; i++) { 5591 uint16_t character = *chars++; 5592 // remaining_capacity is <= 3 bytes at this point, so we do not write out 5593 // an umatched lead surrogate. 5594 if (replace_invalid_utf8_ && unibrow::Utf16::IsLeadSurrogate(character)) { 5595 early_termination_ = true; 5596 break; 5597 } 5598 int written = WriteEndCharacter(character, 5599 last_character, 5600 remaining_capacity, 5601 buffer, 5602 replace_invalid_utf8_); 5603 if (written == 0) { 5604 early_termination_ = true; 5605 break; 5606 } 5607 buffer += written; 5608 remaining_capacity -= written; 5609 last_character = character; 5610 } 5611 // Write state back out to object. 5612 last_character_ = last_character; 5613 buffer_ = buffer; 5614 utf16_chars_read_ += i; 5615 } 5616 5617 inline bool IsDone() { 5618 return early_termination_; 5619 } 5620 5621 inline void VisitOneByteString(const uint8_t* chars, int length) { 5622 Visit(chars, length); 5623 } 5624 5625 inline void VisitTwoByteString(const uint16_t* chars, int length) { 5626 Visit(chars, length); 5627 } 5628 5629 int CompleteWrite(bool write_null, int* utf16_chars_read_out) { 5630 // Write out number of utf16 characters written to the stream. 5631 if (utf16_chars_read_out != NULL) { 5632 *utf16_chars_read_out = utf16_chars_read_; 5633 } 5634 // Only null terminate if all of the string was written and there's space. 5635 if (write_null && 5636 !early_termination_ && 5637 (capacity_ == -1 || (buffer_ - start_) < capacity_)) { 5638 *buffer_++ = '\0'; 5639 } 5640 return static_cast<int>(buffer_ - start_); 5641 } 5642 5643 private: 5644 bool early_termination_; 5645 int last_character_; 5646 char* buffer_; 5647 char* const start_; 5648 int capacity_; 5649 bool const skip_capacity_check_; 5650 bool const replace_invalid_utf8_; 5651 int utf16_chars_read_; 5652 DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor); 5653 }; 5654 5655 5656 static bool RecursivelySerializeToUtf8(i::String* current, 5657 Utf8WriterVisitor* writer, 5658 int recursion_budget) { 5659 while (!writer->IsDone()) { 5660 i::ConsString* cons_string = i::String::VisitFlat(writer, current); 5661 if (cons_string == NULL) return true; // Leaf node. 5662 if (recursion_budget <= 0) return false; 5663 // Must write the left branch first. 5664 i::String* first = cons_string->first(); 5665 bool success = RecursivelySerializeToUtf8(first, 5666 writer, 5667 recursion_budget - 1); 5668 if (!success) return false; 5669 // Inline tail recurse for right branch. 5670 current = cons_string->second(); 5671 } 5672 return true; 5673 } 5674 5675 5676 int String::WriteUtf8(char* buffer, 5677 int capacity, 5678 int* nchars_ref, 5679 int options) const { 5680 i::Handle<i::String> str = Utils::OpenHandle(this); 5681 i::Isolate* isolate = str->GetIsolate(); 5682 LOG_API(isolate, String, WriteUtf8); 5683 ENTER_V8(isolate); 5684 if (options & HINT_MANY_WRITES_EXPECTED) { 5685 str = i::String::Flatten(str); // Flatten the string for efficiency. 5686 } 5687 const int string_length = str->length(); 5688 bool write_null = !(options & NO_NULL_TERMINATION); 5689 bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8); 5690 int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize; 5691 // First check if we can just write the string without checking capacity. 5692 if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) { 5693 Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8); 5694 const int kMaxRecursion = 100; 5695 bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion); 5696 if (success) return writer.CompleteWrite(write_null, nchars_ref); 5697 } else if (capacity >= string_length) { 5698 // First check that the buffer is large enough. 5699 int utf8_bytes = v8::Utf8Length(*str, isolate); 5700 if (utf8_bytes <= capacity) { 5701 // one-byte fast path. 5702 if (utf8_bytes == string_length) { 5703 WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options); 5704 if (nchars_ref != NULL) *nchars_ref = string_length; 5705 if (write_null && (utf8_bytes+1 <= capacity)) { 5706 return string_length + 1; 5707 } 5708 return string_length; 5709 } 5710 if (write_null && (utf8_bytes+1 > capacity)) { 5711 options |= NO_NULL_TERMINATION; 5712 } 5713 // Recurse once without a capacity limit. 5714 // This will get into the first branch above. 5715 // TODO(dcarney) Check max left rec. in Utf8Length and fall through. 5716 return WriteUtf8(buffer, -1, nchars_ref, options); 5717 } 5718 } 5719 // Recursive slow path can potentially be unreasonable slow. Flatten. 5720 str = i::String::Flatten(str); 5721 Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8); 5722 i::String::VisitFlat(&writer, *str); 5723 return writer.CompleteWrite(write_null, nchars_ref); 5724 } 5725 5726 5727 template<typename CharType> 5728 static inline int WriteHelper(const String* string, 5729 CharType* buffer, 5730 int start, 5731 int length, 5732 int options) { 5733 i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate(); 5734 LOG_API(isolate, String, Write); 5735 ENTER_V8(isolate); 5736 DCHECK(start >= 0 && length >= -1); 5737 i::Handle<i::String> str = Utils::OpenHandle(string); 5738 if (options & String::HINT_MANY_WRITES_EXPECTED) { 5739 // Flatten the string for efficiency. This applies whether we are 5740 // using StringCharacterStream or Get(i) to access the characters. 5741 str = i::String::Flatten(str); 5742 } 5743 int end = start + length; 5744 if ((length == -1) || (length > str->length() - start) ) 5745 end = str->length(); 5746 if (end < 0) return 0; 5747 i::String::WriteToFlat(*str, buffer, start, end); 5748 if (!(options & String::NO_NULL_TERMINATION) && 5749 (length == -1 || end - start < length)) { 5750 buffer[end - start] = '\0'; 5751 } 5752 return end - start; 5753 } 5754 5755 5756 int String::WriteOneByte(uint8_t* buffer, 5757 int start, 5758 int length, 5759 int options) const { 5760 return WriteHelper(this, buffer, start, length, options); 5761 } 5762 5763 5764 int String::Write(uint16_t* buffer, 5765 int start, 5766 int length, 5767 int options) const { 5768 return WriteHelper(this, buffer, start, length, options); 5769 } 5770 5771 5772 bool v8::String::IsExternal() const { 5773 i::Handle<i::String> str = Utils::OpenHandle(this); 5774 return i::StringShape(*str).IsExternalTwoByte(); 5775 } 5776 5777 5778 bool v8::String::IsExternalOneByte() const { 5779 i::Handle<i::String> str = Utils::OpenHandle(this); 5780 return i::StringShape(*str).IsExternalOneByte(); 5781 } 5782 5783 5784 void v8::String::VerifyExternalStringResource( 5785 v8::String::ExternalStringResource* value) const { 5786 i::Handle<i::String> str = Utils::OpenHandle(this); 5787 const v8::String::ExternalStringResource* expected; 5788 if (i::StringShape(*str).IsExternalTwoByte()) { 5789 const void* resource = 5790 i::Handle<i::ExternalTwoByteString>::cast(str)->resource(); 5791 expected = reinterpret_cast<const ExternalStringResource*>(resource); 5792 } else { 5793 expected = NULL; 5794 } 5795 CHECK_EQ(expected, value); 5796 } 5797 5798 void v8::String::VerifyExternalStringResourceBase( 5799 v8::String::ExternalStringResourceBase* value, Encoding encoding) const { 5800 i::Handle<i::String> str = Utils::OpenHandle(this); 5801 const v8::String::ExternalStringResourceBase* expected; 5802 Encoding expectedEncoding; 5803 if (i::StringShape(*str).IsExternalOneByte()) { 5804 const void* resource = 5805 i::Handle<i::ExternalOneByteString>::cast(str)->resource(); 5806 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource); 5807 expectedEncoding = ONE_BYTE_ENCODING; 5808 } else if (i::StringShape(*str).IsExternalTwoByte()) { 5809 const void* resource = 5810 i::Handle<i::ExternalTwoByteString>::cast(str)->resource(); 5811 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource); 5812 expectedEncoding = TWO_BYTE_ENCODING; 5813 } else { 5814 expected = NULL; 5815 expectedEncoding = 5816 str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING; 5817 } 5818 CHECK_EQ(expected, value); 5819 CHECK_EQ(expectedEncoding, encoding); 5820 } 5821 5822 const v8::String::ExternalOneByteStringResource* 5823 v8::String::GetExternalOneByteStringResource() const { 5824 i::Handle<i::String> str = Utils::OpenHandle(this); 5825 if (i::StringShape(*str).IsExternalOneByte()) { 5826 const void* resource = 5827 i::Handle<i::ExternalOneByteString>::cast(str)->resource(); 5828 return reinterpret_cast<const ExternalOneByteStringResource*>(resource); 5829 } else { 5830 return NULL; 5831 } 5832 } 5833 5834 5835 Local<Value> Symbol::Name() const { 5836 i::Handle<i::Symbol> sym = Utils::OpenHandle(this); 5837 i::Handle<i::Object> name(sym->name(), sym->GetIsolate()); 5838 return Utils::ToLocal(name); 5839 } 5840 5841 5842 Local<Value> Private::Name() const { 5843 return reinterpret_cast<const Symbol*>(this)->Name(); 5844 } 5845 5846 5847 double Number::Value() const { 5848 i::Handle<i::Object> obj = Utils::OpenHandle(this); 5849 return obj->Number(); 5850 } 5851 5852 5853 bool Boolean::Value() const { 5854 i::Handle<i::Object> obj = Utils::OpenHandle(this); 5855 return obj->IsTrue(i::HeapObject::cast(*obj)->GetIsolate()); 5856 } 5857 5858 5859 int64_t Integer::Value() const { 5860 i::Handle<i::Object> obj = Utils::OpenHandle(this); 5861 if (obj->IsSmi()) { 5862 return i::Smi::cast(*obj)->value(); 5863 } else { 5864 return static_cast<int64_t>(obj->Number()); 5865 } 5866 } 5867 5868 5869 int32_t Int32::Value() const { 5870 i::Handle<i::Object> obj = Utils::OpenHandle(this); 5871 if (obj->IsSmi()) { 5872 return i::Smi::cast(*obj)->value(); 5873 } else { 5874 return static_cast<int32_t>(obj->Number()); 5875 } 5876 } 5877 5878 5879 uint32_t Uint32::Value() const { 5880 i::Handle<i::Object> obj = Utils::OpenHandle(this); 5881 if (obj->IsSmi()) { 5882 return i::Smi::cast(*obj)->value(); 5883 } else { 5884 return static_cast<uint32_t>(obj->Number()); 5885 } 5886 } 5887 5888 5889 int v8::Object::InternalFieldCount() { 5890 i::Handle<i::JSReceiver> self = Utils::OpenHandle(this); 5891 if (!self->IsJSObject()) return 0; 5892 return i::Handle<i::JSObject>::cast(self)->GetInternalFieldCount(); 5893 } 5894 5895 5896 static bool InternalFieldOK(i::Handle<i::JSReceiver> obj, int index, 5897 const char* location) { 5898 return Utils::ApiCheck( 5899 obj->IsJSObject() && 5900 (index < i::Handle<i::JSObject>::cast(obj)->GetInternalFieldCount()), 5901 location, "Internal field out of bounds"); 5902 } 5903 5904 5905 Local<Value> v8::Object::SlowGetInternalField(int index) { 5906 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 5907 const char* location = "v8::Object::GetInternalField()"; 5908 if (!InternalFieldOK(obj, index, location)) return Local<Value>(); 5909 i::Handle<i::Object> value( 5910 i::Handle<i::JSObject>::cast(obj)->GetInternalField(index), 5911 obj->GetIsolate()); 5912 return Utils::ToLocal(value); 5913 } 5914 5915 5916 void v8::Object::SetInternalField(int index, v8::Local<Value> value) { 5917 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 5918 const char* location = "v8::Object::SetInternalField()"; 5919 if (!InternalFieldOK(obj, index, location)) return; 5920 i::Handle<i::Object> val = Utils::OpenHandle(*value); 5921 i::Handle<i::JSObject>::cast(obj)->SetInternalField(index, *val); 5922 } 5923 5924 5925 void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) { 5926 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 5927 const char* location = "v8::Object::GetAlignedPointerFromInternalField()"; 5928 if (!InternalFieldOK(obj, index, location)) return NULL; 5929 return DecodeSmiToAligned( 5930 i::Handle<i::JSObject>::cast(obj)->GetInternalField(index), location); 5931 } 5932 5933 void v8::Object::SetAlignedPointerInInternalField(int index, void* value) { 5934 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 5935 const char* location = "v8::Object::SetAlignedPointerInInternalField()"; 5936 if (!InternalFieldOK(obj, index, location)) return; 5937 i::Handle<i::JSObject>::cast(obj) 5938 ->SetInternalField(index, EncodeAlignedAsSmi(value, location)); 5939 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index)); 5940 } 5941 5942 void v8::Object::SetAlignedPointerInInternalFields(int argc, int indices[], 5943 void* values[]) { 5944 i::Handle<i::JSReceiver> obj = Utils::OpenHandle(this); 5945 const char* location = "v8::Object::SetAlignedPointerInInternalFields()"; 5946 i::DisallowHeapAllocation no_gc; 5947 i::JSObject* object = i::JSObject::cast(*obj); 5948 int nof_internal_fields = object->GetInternalFieldCount(); 5949 for (int i = 0; i < argc; i++) { 5950 int index = indices[i]; 5951 if (!Utils::ApiCheck(index < nof_internal_fields, location, 5952 "Internal field out of bounds")) { 5953 return; 5954 } 5955 void* value = values[i]; 5956 object->SetInternalField(index, EncodeAlignedAsSmi(value, location)); 5957 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index)); 5958 } 5959 } 5960 5961 static void* ExternalValue(i::Object* obj) { 5962 // Obscure semantics for undefined, but somehow checked in our unit tests... 5963 if (!obj->IsSmi() && 5964 obj->IsUndefined(i::HeapObject::cast(obj)->GetIsolate())) { 5965 return NULL; 5966 } 5967 i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0); 5968 return i::Foreign::cast(foreign)->foreign_address(); 5969 } 5970 5971 5972 // --- E n v i r o n m e n t --- 5973 5974 5975 void v8::V8::InitializePlatform(Platform* platform) { 5976 i::V8::InitializePlatform(platform); 5977 } 5978 5979 5980 void v8::V8::ShutdownPlatform() { 5981 i::V8::ShutdownPlatform(); 5982 } 5983 5984 5985 bool v8::V8::Initialize() { 5986 i::V8::Initialize(); 5987 #ifdef V8_USE_EXTERNAL_STARTUP_DATA 5988 i::ReadNatives(); 5989 #endif 5990 return true; 5991 } 5992 5993 5994 void v8::V8::SetEntropySource(EntropySource entropy_source) { 5995 base::RandomNumberGenerator::SetEntropySource(entropy_source); 5996 } 5997 5998 5999 void v8::V8::SetReturnAddressLocationResolver( 6000 ReturnAddressLocationResolver return_address_resolver) { 6001 i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver); 6002 } 6003 6004 6005 bool v8::V8::Dispose() { 6006 i::V8::TearDown(); 6007 #ifdef V8_USE_EXTERNAL_STARTUP_DATA 6008 i::DisposeNatives(); 6009 #endif 6010 return true; 6011 } 6012 6013 HeapStatistics::HeapStatistics() 6014 : total_heap_size_(0), 6015 total_heap_size_executable_(0), 6016 total_physical_size_(0), 6017 total_available_size_(0), 6018 used_heap_size_(0), 6019 heap_size_limit_(0), 6020 malloced_memory_(0), 6021 peak_malloced_memory_(0), 6022 does_zap_garbage_(0) {} 6023 6024 HeapSpaceStatistics::HeapSpaceStatistics(): space_name_(0), 6025 space_size_(0), 6026 space_used_size_(0), 6027 space_available_size_(0), 6028 physical_space_size_(0) { } 6029 6030 6031 HeapObjectStatistics::HeapObjectStatistics() 6032 : object_type_(nullptr), 6033 object_sub_type_(nullptr), 6034 object_count_(0), 6035 object_size_(0) {} 6036 6037 HeapCodeStatistics::HeapCodeStatistics() 6038 : code_and_metadata_size_(0), bytecode_and_metadata_size_(0) {} 6039 6040 bool v8::V8::InitializeICU(const char* icu_data_file) { 6041 return i::InitializeICU(icu_data_file); 6042 } 6043 6044 bool v8::V8::InitializeICUDefaultLocation(const char* exec_path, 6045 const char* icu_data_file) { 6046 return i::InitializeICUDefaultLocation(exec_path, icu_data_file); 6047 } 6048 6049 void v8::V8::InitializeExternalStartupData(const char* directory_path) { 6050 i::InitializeExternalStartupData(directory_path); 6051 } 6052 6053 6054 void v8::V8::InitializeExternalStartupData(const char* natives_blob, 6055 const char* snapshot_blob) { 6056 i::InitializeExternalStartupData(natives_blob, snapshot_blob); 6057 } 6058 6059 6060 const char* v8::V8::GetVersion() { 6061 return i::Version::GetVersion(); 6062 } 6063 6064 template <typename ObjectType> 6065 struct InvokeBootstrapper; 6066 6067 template <> 6068 struct InvokeBootstrapper<i::Context> { 6069 i::Handle<i::Context> Invoke( 6070 i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy, 6071 v8::Local<v8::ObjectTemplate> global_object_template, 6072 v8::ExtensionConfiguration* extensions, size_t context_snapshot_index) { 6073 return isolate->bootstrapper()->CreateEnvironment( 6074 maybe_global_proxy, global_object_template, extensions, 6075 context_snapshot_index); 6076 } 6077 }; 6078 6079 template <> 6080 struct InvokeBootstrapper<i::JSGlobalProxy> { 6081 i::Handle<i::JSGlobalProxy> Invoke( 6082 i::Isolate* isolate, i::MaybeHandle<i::JSGlobalProxy> maybe_global_proxy, 6083 v8::Local<v8::ObjectTemplate> global_object_template, 6084 v8::ExtensionConfiguration* extensions, size_t context_snapshot_index) { 6085 USE(extensions); 6086 USE(context_snapshot_index); 6087 return isolate->bootstrapper()->NewRemoteContext(maybe_global_proxy, 6088 global_object_template); 6089 } 6090 }; 6091 6092 template <typename ObjectType> 6093 static i::Handle<ObjectType> CreateEnvironment( 6094 i::Isolate* isolate, v8::ExtensionConfiguration* extensions, 6095 v8::MaybeLocal<ObjectTemplate> maybe_global_template, 6096 v8::MaybeLocal<Value> maybe_global_proxy, size_t context_snapshot_index) { 6097 i::Handle<ObjectType> result; 6098 6099 // Enter V8 via an ENTER_V8 scope. 6100 { 6101 ENTER_V8(isolate); 6102 v8::Local<ObjectTemplate> proxy_template; 6103 i::Handle<i::FunctionTemplateInfo> proxy_constructor; 6104 i::Handle<i::FunctionTemplateInfo> global_constructor; 6105 6106 if (!maybe_global_template.IsEmpty()) { 6107 v8::Local<v8::ObjectTemplate> global_template = 6108 maybe_global_template.ToLocalChecked(); 6109 // Make sure that the global_template has a constructor. 6110 global_constructor = EnsureConstructor(isolate, *global_template); 6111 6112 // Create a fresh template for the global proxy object. 6113 proxy_template = ObjectTemplate::New( 6114 reinterpret_cast<v8::Isolate*>(isolate)); 6115 proxy_constructor = EnsureConstructor(isolate, *proxy_template); 6116 6117 // Set the global template to be the prototype template of 6118 // global proxy template. 6119 proxy_constructor->set_prototype_template( 6120 *Utils::OpenHandle(*global_template)); 6121 6122 proxy_template->SetInternalFieldCount( 6123 global_template->InternalFieldCount()); 6124 6125 // Migrate security handlers from global_template to 6126 // proxy_template. Temporarily removing access check 6127 // information from the global template. 6128 if (!global_constructor->access_check_info()->IsUndefined(isolate)) { 6129 proxy_constructor->set_access_check_info( 6130 global_constructor->access_check_info()); 6131 proxy_constructor->set_needs_access_check( 6132 global_constructor->needs_access_check()); 6133 global_constructor->set_needs_access_check(false); 6134 global_constructor->set_access_check_info( 6135 isolate->heap()->undefined_value()); 6136 } 6137 } 6138 6139 i::MaybeHandle<i::JSGlobalProxy> maybe_proxy; 6140 if (!maybe_global_proxy.IsEmpty()) { 6141 maybe_proxy = i::Handle<i::JSGlobalProxy>::cast( 6142 Utils::OpenHandle(*maybe_global_proxy.ToLocalChecked())); 6143 } 6144 // Create the environment. 6145 InvokeBootstrapper<ObjectType> invoke; 6146 result = invoke.Invoke(isolate, maybe_proxy, proxy_template, extensions, 6147 context_snapshot_index); 6148 6149 // Restore the access check info on the global template. 6150 if (!maybe_global_template.IsEmpty()) { 6151 DCHECK(!global_constructor.is_null()); 6152 DCHECK(!proxy_constructor.is_null()); 6153 global_constructor->set_access_check_info( 6154 proxy_constructor->access_check_info()); 6155 global_constructor->set_needs_access_check( 6156 proxy_constructor->needs_access_check()); 6157 } 6158 } 6159 // Leave V8. 6160 6161 return result; 6162 } 6163 6164 Local<Context> NewContext(v8::Isolate* external_isolate, 6165 v8::ExtensionConfiguration* extensions, 6166 v8::MaybeLocal<ObjectTemplate> global_template, 6167 v8::MaybeLocal<Value> global_object, 6168 size_t context_snapshot_index) { 6169 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate); 6170 TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.NewContext"); 6171 LOG_API(isolate, Context, New); 6172 i::HandleScope scope(isolate); 6173 ExtensionConfiguration no_extensions; 6174 if (extensions == NULL) extensions = &no_extensions; 6175 i::Handle<i::Context> env = 6176 CreateEnvironment<i::Context>(isolate, extensions, global_template, 6177 global_object, context_snapshot_index); 6178 if (env.is_null()) { 6179 if (isolate->has_pending_exception()) { 6180 isolate->OptionalRescheduleException(true); 6181 } 6182 return Local<Context>(); 6183 } 6184 return Utils::ToLocal(scope.CloseAndEscape(env)); 6185 } 6186 6187 Local<Context> v8::Context::New(v8::Isolate* external_isolate, 6188 v8::ExtensionConfiguration* extensions, 6189 v8::MaybeLocal<ObjectTemplate> global_template, 6190 v8::MaybeLocal<Value> global_object) { 6191 return NewContext(external_isolate, extensions, global_template, 6192 global_object, 0); 6193 } 6194 6195 MaybeLocal<Context> v8::Context::FromSnapshot( 6196 v8::Isolate* external_isolate, size_t context_snapshot_index, 6197 v8::ExtensionConfiguration* extensions, 6198 v8::MaybeLocal<ObjectTemplate> global_template, 6199 v8::MaybeLocal<Value> global_object) { 6200 if (!i::Snapshot::HasContextSnapshot( 6201 reinterpret_cast<i::Isolate*>(external_isolate), 6202 context_snapshot_index)) { 6203 return MaybeLocal<Context>(); 6204 } 6205 return NewContext(external_isolate, extensions, global_template, 6206 global_object, context_snapshot_index); 6207 } 6208 6209 MaybeLocal<Object> v8::Context::NewRemoteContext( 6210 v8::Isolate* external_isolate, v8::Local<ObjectTemplate> global_template, 6211 v8::MaybeLocal<v8::Value> global_object) { 6212 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate); 6213 LOG_API(isolate, Context, NewRemoteContext); 6214 i::HandleScope scope(isolate); 6215 i::Handle<i::FunctionTemplateInfo> global_constructor = 6216 EnsureConstructor(isolate, *global_template); 6217 Utils::ApiCheck(global_constructor->needs_access_check(), 6218 "v8::Context::NewRemoteContext", 6219 "Global template needs to have access checks enabled."); 6220 i::Handle<i::AccessCheckInfo> access_check_info = i::handle( 6221 i::AccessCheckInfo::cast(global_constructor->access_check_info()), 6222 isolate); 6223 Utils::ApiCheck(access_check_info->named_interceptor() != nullptr, 6224 "v8::Context::NewRemoteContext", 6225 "Global template needs to have access check handlers."); 6226 i::Handle<i::JSGlobalProxy> global_proxy = 6227 CreateEnvironment<i::JSGlobalProxy>(isolate, nullptr, global_template, 6228 global_object, 0); 6229 if (global_proxy.is_null()) { 6230 if (isolate->has_pending_exception()) { 6231 isolate->OptionalRescheduleException(true); 6232 } 6233 return MaybeLocal<Object>(); 6234 } 6235 return Utils::ToLocal( 6236 scope.CloseAndEscape(i::Handle<i::JSObject>::cast(global_proxy))); 6237 } 6238 6239 void v8::Context::SetSecurityToken(Local<Value> token) { 6240 i::Handle<i::Context> env = Utils::OpenHandle(this); 6241 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token); 6242 env->set_security_token(*token_handle); 6243 } 6244 6245 6246 void v8::Context::UseDefaultSecurityToken() { 6247 i::Handle<i::Context> env = Utils::OpenHandle(this); 6248 env->set_security_token(env->global_object()); 6249 } 6250 6251 6252 Local<Value> v8::Context::GetSecurityToken() { 6253 i::Handle<i::Context> env = Utils::OpenHandle(this); 6254 i::Isolate* isolate = env->GetIsolate(); 6255 i::Object* security_token = env->security_token(); 6256 i::Handle<i::Object> token_handle(security_token, isolate); 6257 return Utils::ToLocal(token_handle); 6258 } 6259 6260 6261 v8::Isolate* Context::GetIsolate() { 6262 i::Handle<i::Context> env = Utils::OpenHandle(this); 6263 return reinterpret_cast<Isolate*>(env->GetIsolate()); 6264 } 6265 6266 6267 v8::Local<v8::Object> Context::Global() { 6268 i::Handle<i::Context> context = Utils::OpenHandle(this); 6269 i::Isolate* isolate = context->GetIsolate(); 6270 i::Handle<i::Object> global(context->global_proxy(), isolate); 6271 // TODO(dcarney): This should always return the global proxy 6272 // but can't presently as calls to GetProtoype will return the wrong result. 6273 if (i::Handle<i::JSGlobalProxy>::cast( 6274 global)->IsDetachedFrom(context->global_object())) { 6275 global = i::Handle<i::Object>(context->global_object(), isolate); 6276 } 6277 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global)); 6278 } 6279 6280 6281 void Context::DetachGlobal() { 6282 i::Handle<i::Context> context = Utils::OpenHandle(this); 6283 i::Isolate* isolate = context->GetIsolate(); 6284 ENTER_V8(isolate); 6285 isolate->bootstrapper()->DetachGlobal(context); 6286 } 6287 6288 6289 Local<v8::Object> Context::GetExtrasBindingObject() { 6290 i::Handle<i::Context> context = Utils::OpenHandle(this); 6291 i::Isolate* isolate = context->GetIsolate(); 6292 i::Handle<i::JSObject> binding(context->extras_binding_object(), isolate); 6293 return Utils::ToLocal(binding); 6294 } 6295 6296 6297 void Context::AllowCodeGenerationFromStrings(bool allow) { 6298 i::Handle<i::Context> context = Utils::OpenHandle(this); 6299 i::Isolate* isolate = context->GetIsolate(); 6300 ENTER_V8(isolate); 6301 context->set_allow_code_gen_from_strings( 6302 allow ? isolate->heap()->true_value() : isolate->heap()->false_value()); 6303 } 6304 6305 6306 bool Context::IsCodeGenerationFromStringsAllowed() { 6307 i::Handle<i::Context> context = Utils::OpenHandle(this); 6308 return !context->allow_code_gen_from_strings()->IsFalse( 6309 context->GetIsolate()); 6310 } 6311 6312 6313 void Context::SetErrorMessageForCodeGenerationFromStrings(Local<String> error) { 6314 i::Handle<i::Context> context = Utils::OpenHandle(this); 6315 i::Handle<i::String> error_handle = Utils::OpenHandle(*error); 6316 context->set_error_message_for_code_gen_from_strings(*error_handle); 6317 } 6318 6319 6320 size_t Context::EstimatedSize() { 6321 return static_cast<size_t>( 6322 i::ContextMeasure(*Utils::OpenHandle(this)).Size()); 6323 } 6324 6325 6326 MaybeLocal<v8::Object> ObjectTemplate::NewInstance(Local<Context> context) { 6327 PREPARE_FOR_EXECUTION(context, ObjectTemplate, NewInstance, Object); 6328 auto self = Utils::OpenHandle(this); 6329 Local<Object> result; 6330 has_pending_exception = 6331 !ToLocal<Object>(i::ApiNatives::InstantiateObject(self), &result); 6332 RETURN_ON_FAILED_EXECUTION(Object); 6333 RETURN_ESCAPED(result); 6334 } 6335 6336 6337 Local<v8::Object> ObjectTemplate::NewInstance() { 6338 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 6339 RETURN_TO_LOCAL_UNCHECKED(NewInstance(context), Object); 6340 } 6341 6342 6343 MaybeLocal<v8::Function> FunctionTemplate::GetFunction(Local<Context> context) { 6344 PREPARE_FOR_EXECUTION(context, FunctionTemplate, GetFunction, Function); 6345 auto self = Utils::OpenHandle(this); 6346 Local<Function> result; 6347 has_pending_exception = 6348 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(self), &result); 6349 RETURN_ON_FAILED_EXECUTION(Function); 6350 RETURN_ESCAPED(result); 6351 } 6352 6353 6354 Local<v8::Function> FunctionTemplate::GetFunction() { 6355 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 6356 RETURN_TO_LOCAL_UNCHECKED(GetFunction(context), Function); 6357 } 6358 6359 MaybeLocal<v8::Object> FunctionTemplate::NewRemoteInstance() { 6360 auto self = Utils::OpenHandle(this); 6361 i::Isolate* isolate = self->GetIsolate(); 6362 LOG_API(isolate, FunctionTemplate, NewRemoteInstance); 6363 i::HandleScope scope(isolate); 6364 i::Handle<i::FunctionTemplateInfo> constructor = 6365 EnsureConstructor(isolate, *InstanceTemplate()); 6366 Utils::ApiCheck(constructor->needs_access_check(), 6367 "v8::FunctionTemplate::NewRemoteInstance", 6368 "InstanceTemplate needs to have access checks enabled."); 6369 i::Handle<i::AccessCheckInfo> access_check_info = i::handle( 6370 i::AccessCheckInfo::cast(constructor->access_check_info()), isolate); 6371 Utils::ApiCheck(access_check_info->named_interceptor() != nullptr, 6372 "v8::FunctionTemplate::NewRemoteInstance", 6373 "InstanceTemplate needs to have access check handlers."); 6374 i::Handle<i::JSObject> object; 6375 if (!i::ApiNatives::InstantiateRemoteObject( 6376 Utils::OpenHandle(*InstanceTemplate())) 6377 .ToHandle(&object)) { 6378 if (isolate->has_pending_exception()) { 6379 isolate->OptionalRescheduleException(true); 6380 } 6381 return MaybeLocal<Object>(); 6382 } 6383 return Utils::ToLocal(scope.CloseAndEscape(object)); 6384 } 6385 6386 bool FunctionTemplate::HasInstance(v8::Local<v8::Value> value) { 6387 auto self = Utils::OpenHandle(this); 6388 auto obj = Utils::OpenHandle(*value); 6389 if (obj->IsJSObject() && self->IsTemplateFor(i::JSObject::cast(*obj))) { 6390 return true; 6391 } 6392 if (obj->IsJSGlobalProxy()) { 6393 // If it's a global proxy object, then test with the global object. 6394 i::PrototypeIterator iter(i::JSObject::cast(*obj)->map()); 6395 if (iter.IsAtEnd()) return false; 6396 return self->IsTemplateFor(iter.GetCurrent<i::JSGlobalObject>()); 6397 } 6398 return false; 6399 } 6400 6401 6402 Local<External> v8::External::New(Isolate* isolate, void* value) { 6403 STATIC_ASSERT(sizeof(value) == sizeof(i::Address)); 6404 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6405 LOG_API(i_isolate, External, New); 6406 ENTER_V8(i_isolate); 6407 i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value); 6408 return Utils::ExternalToLocal(external); 6409 } 6410 6411 6412 void* External::Value() const { 6413 return ExternalValue(*Utils::OpenHandle(this)); 6414 } 6415 6416 6417 // anonymous namespace for string creation helper functions 6418 namespace { 6419 6420 inline int StringLength(const char* string) { 6421 return i::StrLength(string); 6422 } 6423 6424 6425 inline int StringLength(const uint8_t* string) { 6426 return i::StrLength(reinterpret_cast<const char*>(string)); 6427 } 6428 6429 6430 inline int StringLength(const uint16_t* string) { 6431 int length = 0; 6432 while (string[length] != '\0') 6433 length++; 6434 return length; 6435 } 6436 6437 6438 MUST_USE_RESULT 6439 inline i::MaybeHandle<i::String> NewString(i::Factory* factory, 6440 v8::NewStringType type, 6441 i::Vector<const char> string) { 6442 if (type == v8::NewStringType::kInternalized) { 6443 return factory->InternalizeUtf8String(string); 6444 } 6445 return factory->NewStringFromUtf8(string); 6446 } 6447 6448 6449 MUST_USE_RESULT 6450 inline i::MaybeHandle<i::String> NewString(i::Factory* factory, 6451 v8::NewStringType type, 6452 i::Vector<const uint8_t> string) { 6453 if (type == v8::NewStringType::kInternalized) { 6454 return factory->InternalizeOneByteString(string); 6455 } 6456 return factory->NewStringFromOneByte(string); 6457 } 6458 6459 6460 MUST_USE_RESULT 6461 inline i::MaybeHandle<i::String> NewString(i::Factory* factory, 6462 v8::NewStringType type, 6463 i::Vector<const uint16_t> string) { 6464 if (type == v8::NewStringType::kInternalized) { 6465 return factory->InternalizeTwoByteString(string); 6466 } 6467 return factory->NewStringFromTwoByte(string); 6468 } 6469 6470 6471 STATIC_ASSERT(v8::String::kMaxLength == i::String::kMaxLength); 6472 6473 } // anonymous namespace 6474 6475 // TODO(dcarney): throw a context free exception. 6476 #define NEW_STRING(isolate, class_name, function_name, Char, data, type, \ 6477 length) \ 6478 MaybeLocal<String> result; \ 6479 if (length == 0) { \ 6480 result = String::Empty(isolate); \ 6481 } else if (length > i::String::kMaxLength) { \ 6482 result = MaybeLocal<String>(); \ 6483 } else { \ 6484 i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(isolate); \ 6485 ENTER_V8(i_isolate); \ 6486 LOG_API(i_isolate, class_name, function_name); \ 6487 if (length < 0) length = StringLength(data); \ 6488 i::Handle<i::String> handle_result = \ 6489 NewString(i_isolate->factory(), type, \ 6490 i::Vector<const Char>(data, length)) \ 6491 .ToHandleChecked(); \ 6492 result = Utils::ToLocal(handle_result); \ 6493 } 6494 6495 Local<String> String::NewFromUtf8(Isolate* isolate, 6496 const char* data, 6497 NewStringType type, 6498 int length) { 6499 NEW_STRING(isolate, String, NewFromUtf8, char, data, 6500 static_cast<v8::NewStringType>(type), length); 6501 RETURN_TO_LOCAL_UNCHECKED(result, String); 6502 } 6503 6504 6505 MaybeLocal<String> String::NewFromUtf8(Isolate* isolate, const char* data, 6506 v8::NewStringType type, int length) { 6507 NEW_STRING(isolate, String, NewFromUtf8, char, data, type, length); 6508 return result; 6509 } 6510 6511 6512 Local<String> String::NewFromOneByte(Isolate* isolate, 6513 const uint8_t* data, 6514 NewStringType type, 6515 int length) { 6516 NEW_STRING(isolate, String, NewFromOneByte, uint8_t, data, 6517 static_cast<v8::NewStringType>(type), length); 6518 RETURN_TO_LOCAL_UNCHECKED(result, String); 6519 } 6520 6521 6522 MaybeLocal<String> String::NewFromOneByte(Isolate* isolate, const uint8_t* data, 6523 v8::NewStringType type, int length) { 6524 NEW_STRING(isolate, String, NewFromOneByte, uint8_t, data, type, length); 6525 return result; 6526 } 6527 6528 6529 Local<String> String::NewFromTwoByte(Isolate* isolate, 6530 const uint16_t* data, 6531 NewStringType type, 6532 int length) { 6533 NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data, 6534 static_cast<v8::NewStringType>(type), length); 6535 RETURN_TO_LOCAL_UNCHECKED(result, String); 6536 } 6537 6538 6539 MaybeLocal<String> String::NewFromTwoByte(Isolate* isolate, 6540 const uint16_t* data, 6541 v8::NewStringType type, int length) { 6542 NEW_STRING(isolate, String, NewFromTwoByte, uint16_t, data, type, length); 6543 return result; 6544 } 6545 6546 6547 Local<String> v8::String::Concat(Local<String> left, Local<String> right) { 6548 i::Handle<i::String> left_string = Utils::OpenHandle(*left); 6549 i::Isolate* isolate = left_string->GetIsolate(); 6550 ENTER_V8(isolate); 6551 LOG_API(isolate, String, Concat); 6552 i::Handle<i::String> right_string = Utils::OpenHandle(*right); 6553 // If we are steering towards a range error, do not wait for the error to be 6554 // thrown, and return the null handle instead. 6555 if (left_string->length() + right_string->length() > i::String::kMaxLength) { 6556 return Local<String>(); 6557 } 6558 i::Handle<i::String> result = isolate->factory()->NewConsString( 6559 left_string, right_string).ToHandleChecked(); 6560 return Utils::ToLocal(result); 6561 } 6562 6563 6564 MaybeLocal<String> v8::String::NewExternalTwoByte( 6565 Isolate* isolate, v8::String::ExternalStringResource* resource) { 6566 CHECK(resource && resource->data()); 6567 // TODO(dcarney): throw a context free exception. 6568 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) { 6569 return MaybeLocal<String>(); 6570 } 6571 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6572 ENTER_V8(i_isolate); 6573 LOG_API(i_isolate, String, NewExternalTwoByte); 6574 i::Handle<i::String> string = i_isolate->factory() 6575 ->NewExternalStringFromTwoByte(resource) 6576 .ToHandleChecked(); 6577 i_isolate->heap()->RegisterExternalString(*string); 6578 return Utils::ToLocal(string); 6579 } 6580 6581 6582 Local<String> v8::String::NewExternal( 6583 Isolate* isolate, v8::String::ExternalStringResource* resource) { 6584 RETURN_TO_LOCAL_UNCHECKED(NewExternalTwoByte(isolate, resource), String); 6585 } 6586 6587 6588 MaybeLocal<String> v8::String::NewExternalOneByte( 6589 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) { 6590 CHECK(resource && resource->data()); 6591 // TODO(dcarney): throw a context free exception. 6592 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) { 6593 return MaybeLocal<String>(); 6594 } 6595 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6596 ENTER_V8(i_isolate); 6597 LOG_API(i_isolate, String, NewExternalOneByte); 6598 i::Handle<i::String> string = i_isolate->factory() 6599 ->NewExternalStringFromOneByte(resource) 6600 .ToHandleChecked(); 6601 i_isolate->heap()->RegisterExternalString(*string); 6602 return Utils::ToLocal(string); 6603 } 6604 6605 6606 Local<String> v8::String::NewExternal( 6607 Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) { 6608 RETURN_TO_LOCAL_UNCHECKED(NewExternalOneByte(isolate, resource), String); 6609 } 6610 6611 6612 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) { 6613 i::Handle<i::String> obj = Utils::OpenHandle(this); 6614 i::Isolate* isolate = obj->GetIsolate(); 6615 if (i::StringShape(*obj).IsExternal()) { 6616 return false; // Already an external string. 6617 } 6618 ENTER_V8(isolate); 6619 if (isolate->heap()->IsInGCPostProcessing()) { 6620 return false; 6621 } 6622 CHECK(resource && resource->data()); 6623 6624 bool result = obj->MakeExternal(resource); 6625 // Assert that if CanMakeExternal(), then externalizing actually succeeds. 6626 DCHECK(!CanMakeExternal() || result); 6627 if (result) { 6628 DCHECK(obj->IsExternalString()); 6629 isolate->heap()->RegisterExternalString(*obj); 6630 } 6631 return result; 6632 } 6633 6634 6635 bool v8::String::MakeExternal( 6636 v8::String::ExternalOneByteStringResource* resource) { 6637 i::Handle<i::String> obj = Utils::OpenHandle(this); 6638 i::Isolate* isolate = obj->GetIsolate(); 6639 if (i::StringShape(*obj).IsExternal()) { 6640 return false; // Already an external string. 6641 } 6642 ENTER_V8(isolate); 6643 if (isolate->heap()->IsInGCPostProcessing()) { 6644 return false; 6645 } 6646 CHECK(resource && resource->data()); 6647 6648 bool result = obj->MakeExternal(resource); 6649 // Assert that if CanMakeExternal(), then externalizing actually succeeds. 6650 DCHECK(!CanMakeExternal() || result); 6651 if (result) { 6652 DCHECK(obj->IsExternalString()); 6653 isolate->heap()->RegisterExternalString(*obj); 6654 } 6655 return result; 6656 } 6657 6658 6659 bool v8::String::CanMakeExternal() { 6660 i::Handle<i::String> obj = Utils::OpenHandle(this); 6661 if (obj->IsExternalString()) return false; 6662 6663 // Old space strings should be externalized. 6664 i::Isolate* isolate = obj->GetIsolate(); 6665 return !isolate->heap()->new_space()->Contains(*obj); 6666 } 6667 6668 6669 Isolate* v8::Object::GetIsolate() { 6670 i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate(); 6671 return reinterpret_cast<Isolate*>(i_isolate); 6672 } 6673 6674 6675 Local<v8::Object> v8::Object::New(Isolate* isolate) { 6676 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6677 LOG_API(i_isolate, Object, New); 6678 ENTER_V8(i_isolate); 6679 i::Handle<i::JSObject> obj = 6680 i_isolate->factory()->NewJSObject(i_isolate->object_function()); 6681 return Utils::ToLocal(obj); 6682 } 6683 6684 6685 Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) { 6686 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6687 LOG_API(i_isolate, NumberObject, New); 6688 ENTER_V8(i_isolate); 6689 i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value); 6690 i::Handle<i::Object> obj = 6691 i::Object::ToObject(i_isolate, number).ToHandleChecked(); 6692 return Utils::ToLocal(obj); 6693 } 6694 6695 6696 double v8::NumberObject::ValueOf() const { 6697 i::Handle<i::Object> obj = Utils::OpenHandle(this); 6698 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj); 6699 i::Isolate* isolate = jsvalue->GetIsolate(); 6700 LOG_API(isolate, NumberObject, NumberValue); 6701 return jsvalue->value()->Number(); 6702 } 6703 6704 6705 Local<v8::Value> v8::BooleanObject::New(Isolate* isolate, bool value) { 6706 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6707 LOG_API(i_isolate, BooleanObject, New); 6708 ENTER_V8(i_isolate); 6709 i::Handle<i::Object> boolean(value ? i_isolate->heap()->true_value() 6710 : i_isolate->heap()->false_value(), 6711 i_isolate); 6712 i::Handle<i::Object> obj = 6713 i::Object::ToObject(i_isolate, boolean).ToHandleChecked(); 6714 return Utils::ToLocal(obj); 6715 } 6716 6717 6718 Local<v8::Value> v8::BooleanObject::New(bool value) { 6719 return New(Isolate::GetCurrent(), value); 6720 } 6721 6722 6723 bool v8::BooleanObject::ValueOf() const { 6724 i::Handle<i::Object> obj = Utils::OpenHandle(this); 6725 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj); 6726 i::Isolate* isolate = jsvalue->GetIsolate(); 6727 LOG_API(isolate, BooleanObject, BooleanValue); 6728 return jsvalue->value()->IsTrue(isolate); 6729 } 6730 6731 6732 Local<v8::Value> v8::StringObject::New(Local<String> value) { 6733 i::Handle<i::String> string = Utils::OpenHandle(*value); 6734 i::Isolate* isolate = string->GetIsolate(); 6735 LOG_API(isolate, StringObject, New); 6736 ENTER_V8(isolate); 6737 i::Handle<i::Object> obj = 6738 i::Object::ToObject(isolate, string).ToHandleChecked(); 6739 return Utils::ToLocal(obj); 6740 } 6741 6742 6743 Local<v8::String> v8::StringObject::ValueOf() const { 6744 i::Handle<i::Object> obj = Utils::OpenHandle(this); 6745 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj); 6746 i::Isolate* isolate = jsvalue->GetIsolate(); 6747 LOG_API(isolate, StringObject, StringValue); 6748 return Utils::ToLocal( 6749 i::Handle<i::String>(i::String::cast(jsvalue->value()))); 6750 } 6751 6752 6753 Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Local<Symbol> value) { 6754 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6755 LOG_API(i_isolate, SymbolObject, New); 6756 ENTER_V8(i_isolate); 6757 i::Handle<i::Object> obj = i::Object::ToObject( 6758 i_isolate, Utils::OpenHandle(*value)).ToHandleChecked(); 6759 return Utils::ToLocal(obj); 6760 } 6761 6762 6763 Local<v8::Symbol> v8::SymbolObject::ValueOf() const { 6764 i::Handle<i::Object> obj = Utils::OpenHandle(this); 6765 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj); 6766 i::Isolate* isolate = jsvalue->GetIsolate(); 6767 LOG_API(isolate, SymbolObject, SymbolValue); 6768 return Utils::ToLocal( 6769 i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value()))); 6770 } 6771 6772 6773 MaybeLocal<v8::Value> v8::Date::New(Local<Context> context, double time) { 6774 if (std::isnan(time)) { 6775 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs. 6776 time = std::numeric_limits<double>::quiet_NaN(); 6777 } 6778 PREPARE_FOR_EXECUTION(context, Date, New, Value); 6779 Local<Value> result; 6780 has_pending_exception = !ToLocal<Value>( 6781 i::JSDate::New(isolate->date_function(), isolate->date_function(), time), 6782 &result); 6783 RETURN_ON_FAILED_EXECUTION(Value); 6784 RETURN_ESCAPED(result); 6785 } 6786 6787 6788 Local<v8::Value> v8::Date::New(Isolate* isolate, double time) { 6789 auto context = isolate->GetCurrentContext(); 6790 RETURN_TO_LOCAL_UNCHECKED(New(context, time), Value); 6791 } 6792 6793 6794 double v8::Date::ValueOf() const { 6795 i::Handle<i::Object> obj = Utils::OpenHandle(this); 6796 i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj); 6797 i::Isolate* isolate = jsdate->GetIsolate(); 6798 LOG_API(isolate, Date, NumberValue); 6799 return jsdate->value()->Number(); 6800 } 6801 6802 6803 void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) { 6804 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6805 LOG_API(i_isolate, Date, DateTimeConfigurationChangeNotification); 6806 ENTER_V8(i_isolate); 6807 i_isolate->date_cache()->ResetDateCache(); 6808 if (!i_isolate->eternal_handles()->Exists( 6809 i::EternalHandles::DATE_CACHE_VERSION)) { 6810 return; 6811 } 6812 i::Handle<i::FixedArray> date_cache_version = 6813 i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton( 6814 i::EternalHandles::DATE_CACHE_VERSION)); 6815 DCHECK_EQ(1, date_cache_version->length()); 6816 CHECK(date_cache_version->get(0)->IsSmi()); 6817 date_cache_version->set( 6818 0, 6819 i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1)); 6820 } 6821 6822 6823 MaybeLocal<v8::RegExp> v8::RegExp::New(Local<Context> context, 6824 Local<String> pattern, Flags flags) { 6825 PREPARE_FOR_EXECUTION(context, RegExp, New, RegExp); 6826 Local<v8::RegExp> result; 6827 has_pending_exception = 6828 !ToLocal<RegExp>(i::JSRegExp::New(Utils::OpenHandle(*pattern), 6829 static_cast<i::JSRegExp::Flags>(flags)), 6830 &result); 6831 RETURN_ON_FAILED_EXECUTION(RegExp); 6832 RETURN_ESCAPED(result); 6833 } 6834 6835 6836 Local<v8::RegExp> v8::RegExp::New(Local<String> pattern, Flags flags) { 6837 auto isolate = 6838 reinterpret_cast<Isolate*>(Utils::OpenHandle(*pattern)->GetIsolate()); 6839 auto context = isolate->GetCurrentContext(); 6840 RETURN_TO_LOCAL_UNCHECKED(New(context, pattern, flags), RegExp); 6841 } 6842 6843 6844 Local<v8::String> v8::RegExp::GetSource() const { 6845 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this); 6846 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern())); 6847 } 6848 6849 6850 // Assert that the static flags cast in GetFlags is valid. 6851 #define REGEXP_FLAG_ASSERT_EQ(flag) \ 6852 STATIC_ASSERT(static_cast<int>(v8::RegExp::flag) == \ 6853 static_cast<int>(i::JSRegExp::flag)) 6854 REGEXP_FLAG_ASSERT_EQ(kNone); 6855 REGEXP_FLAG_ASSERT_EQ(kGlobal); 6856 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase); 6857 REGEXP_FLAG_ASSERT_EQ(kMultiline); 6858 REGEXP_FLAG_ASSERT_EQ(kSticky); 6859 REGEXP_FLAG_ASSERT_EQ(kUnicode); 6860 #undef REGEXP_FLAG_ASSERT_EQ 6861 6862 v8::RegExp::Flags v8::RegExp::GetFlags() const { 6863 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this); 6864 return RegExp::Flags(static_cast<int>(obj->GetFlags())); 6865 } 6866 6867 6868 Local<v8::Array> v8::Array::New(Isolate* isolate, int length) { 6869 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6870 LOG_API(i_isolate, Array, New); 6871 ENTER_V8(i_isolate); 6872 int real_length = length > 0 ? length : 0; 6873 i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length); 6874 i::Handle<i::Object> length_obj = 6875 i_isolate->factory()->NewNumberFromInt(real_length); 6876 obj->set_length(*length_obj); 6877 return Utils::ToLocal(obj); 6878 } 6879 6880 6881 uint32_t v8::Array::Length() const { 6882 i::Handle<i::JSArray> obj = Utils::OpenHandle(this); 6883 i::Object* length = obj->length(); 6884 if (length->IsSmi()) { 6885 return i::Smi::cast(length)->value(); 6886 } else { 6887 return static_cast<uint32_t>(length->Number()); 6888 } 6889 } 6890 6891 6892 MaybeLocal<Object> Array::CloneElementAt(Local<Context> context, 6893 uint32_t index) { 6894 PREPARE_FOR_EXECUTION(context, Array, CloneElementAt, Object); 6895 auto self = Utils::OpenHandle(this); 6896 if (!self->HasFastObjectElements()) return Local<Object>(); 6897 i::FixedArray* elms = i::FixedArray::cast(self->elements()); 6898 i::Object* paragon = elms->get(index); 6899 if (!paragon->IsJSObject()) return Local<Object>(); 6900 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon)); 6901 Local<Object> result; 6902 has_pending_exception = 6903 !ToLocal<Object>(isolate->factory()->CopyJSObject(paragon_handle), 6904 &result); 6905 RETURN_ON_FAILED_EXECUTION(Object); 6906 RETURN_ESCAPED(result); 6907 } 6908 6909 6910 Local<Object> Array::CloneElementAt(uint32_t index) { return Local<Object>(); } 6911 6912 6913 Local<v8::Map> v8::Map::New(Isolate* isolate) { 6914 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 6915 LOG_API(i_isolate, Map, New); 6916 ENTER_V8(i_isolate); 6917 i::Handle<i::JSMap> obj = i_isolate->factory()->NewJSMap(); 6918 return Utils::ToLocal(obj); 6919 } 6920 6921 6922 size_t v8::Map::Size() const { 6923 i::Handle<i::JSMap> obj = Utils::OpenHandle(this); 6924 return i::OrderedHashMap::cast(obj->table())->NumberOfElements(); 6925 } 6926 6927 6928 void Map::Clear() { 6929 auto self = Utils::OpenHandle(this); 6930 i::Isolate* isolate = self->GetIsolate(); 6931 LOG_API(isolate, Map, Clear); 6932 ENTER_V8(isolate); 6933 i::JSMap::Clear(self); 6934 } 6935 6936 6937 MaybeLocal<Value> Map::Get(Local<Context> context, Local<Value> key) { 6938 PREPARE_FOR_EXECUTION(context, Map, Get, Value); 6939 auto self = Utils::OpenHandle(this); 6940 Local<Value> result; 6941 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 6942 has_pending_exception = 6943 !ToLocal<Value>(i::Execution::Call(isolate, isolate->map_get(), self, 6944 arraysize(argv), argv), 6945 &result); 6946 RETURN_ON_FAILED_EXECUTION(Value); 6947 RETURN_ESCAPED(result); 6948 } 6949 6950 6951 MaybeLocal<Map> Map::Set(Local<Context> context, Local<Value> key, 6952 Local<Value> value) { 6953 PREPARE_FOR_EXECUTION(context, Map, Set, Map); 6954 auto self = Utils::OpenHandle(this); 6955 i::Handle<i::Object> result; 6956 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key), 6957 Utils::OpenHandle(*value)}; 6958 has_pending_exception = !i::Execution::Call(isolate, isolate->map_set(), self, 6959 arraysize(argv), argv) 6960 .ToHandle(&result); 6961 RETURN_ON_FAILED_EXECUTION(Map); 6962 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result))); 6963 } 6964 6965 6966 Maybe<bool> Map::Has(Local<Context> context, Local<Value> key) { 6967 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Map, Has, bool); 6968 auto self = Utils::OpenHandle(this); 6969 i::Handle<i::Object> result; 6970 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 6971 has_pending_exception = !i::Execution::Call(isolate, isolate->map_has(), self, 6972 arraysize(argv), argv) 6973 .ToHandle(&result); 6974 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 6975 return Just(result->IsTrue(isolate)); 6976 } 6977 6978 6979 Maybe<bool> Map::Delete(Local<Context> context, Local<Value> key) { 6980 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Map, Delete, bool); 6981 auto self = Utils::OpenHandle(this); 6982 i::Handle<i::Object> result; 6983 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 6984 has_pending_exception = !i::Execution::Call(isolate, isolate->map_delete(), 6985 self, arraysize(argv), argv) 6986 .ToHandle(&result); 6987 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 6988 return Just(result->IsTrue(isolate)); 6989 } 6990 6991 6992 Local<Array> Map::AsArray() const { 6993 i::Handle<i::JSMap> obj = Utils::OpenHandle(this); 6994 i::Isolate* isolate = obj->GetIsolate(); 6995 i::Factory* factory = isolate->factory(); 6996 LOG_API(isolate, Map, AsArray); 6997 ENTER_V8(isolate); 6998 i::Handle<i::OrderedHashMap> table(i::OrderedHashMap::cast(obj->table())); 6999 int length = table->NumberOfElements() * 2; 7000 i::Handle<i::FixedArray> result = factory->NewFixedArray(length); 7001 int result_index = 0; 7002 { 7003 i::DisallowHeapAllocation no_gc; 7004 int capacity = table->UsedCapacity(); 7005 i::Oddball* the_hole = isolate->heap()->the_hole_value(); 7006 for (int i = 0; i < capacity; ++i) { 7007 i::Object* key = table->KeyAt(i); 7008 if (key == the_hole) continue; 7009 result->set(result_index++, key); 7010 result->set(result_index++, table->ValueAt(i)); 7011 } 7012 } 7013 DCHECK_EQ(result_index, result->length()); 7014 DCHECK_EQ(result_index, length); 7015 i::Handle<i::JSArray> result_array = 7016 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length); 7017 return Utils::ToLocal(result_array); 7018 } 7019 7020 7021 Local<v8::Set> v8::Set::New(Isolate* isolate) { 7022 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7023 LOG_API(i_isolate, Set, New); 7024 ENTER_V8(i_isolate); 7025 i::Handle<i::JSSet> obj = i_isolate->factory()->NewJSSet(); 7026 return Utils::ToLocal(obj); 7027 } 7028 7029 7030 size_t v8::Set::Size() const { 7031 i::Handle<i::JSSet> obj = Utils::OpenHandle(this); 7032 return i::OrderedHashSet::cast(obj->table())->NumberOfElements(); 7033 } 7034 7035 7036 void Set::Clear() { 7037 auto self = Utils::OpenHandle(this); 7038 i::Isolate* isolate = self->GetIsolate(); 7039 LOG_API(isolate, Set, Clear); 7040 ENTER_V8(isolate); 7041 i::JSSet::Clear(self); 7042 } 7043 7044 7045 MaybeLocal<Set> Set::Add(Local<Context> context, Local<Value> key) { 7046 PREPARE_FOR_EXECUTION(context, Set, Add, Set); 7047 auto self = Utils::OpenHandle(this); 7048 i::Handle<i::Object> result; 7049 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 7050 has_pending_exception = !i::Execution::Call(isolate, isolate->set_add(), self, 7051 arraysize(argv), argv) 7052 .ToHandle(&result); 7053 RETURN_ON_FAILED_EXECUTION(Set); 7054 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result))); 7055 } 7056 7057 7058 Maybe<bool> Set::Has(Local<Context> context, Local<Value> key) { 7059 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Set, Has, bool); 7060 auto self = Utils::OpenHandle(this); 7061 i::Handle<i::Object> result; 7062 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 7063 has_pending_exception = !i::Execution::Call(isolate, isolate->set_has(), self, 7064 arraysize(argv), argv) 7065 .ToHandle(&result); 7066 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 7067 return Just(result->IsTrue(isolate)); 7068 } 7069 7070 7071 Maybe<bool> Set::Delete(Local<Context> context, Local<Value> key) { 7072 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Set, Delete, bool); 7073 auto self = Utils::OpenHandle(this); 7074 i::Handle<i::Object> result; 7075 i::Handle<i::Object> argv[] = {Utils::OpenHandle(*key)}; 7076 has_pending_exception = !i::Execution::Call(isolate, isolate->set_delete(), 7077 self, arraysize(argv), argv) 7078 .ToHandle(&result); 7079 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 7080 return Just(result->IsTrue(isolate)); 7081 } 7082 7083 7084 Local<Array> Set::AsArray() const { 7085 i::Handle<i::JSSet> obj = Utils::OpenHandle(this); 7086 i::Isolate* isolate = obj->GetIsolate(); 7087 i::Factory* factory = isolate->factory(); 7088 LOG_API(isolate, Set, AsArray); 7089 ENTER_V8(isolate); 7090 i::Handle<i::OrderedHashSet> table(i::OrderedHashSet::cast(obj->table())); 7091 int length = table->NumberOfElements(); 7092 i::Handle<i::FixedArray> result = factory->NewFixedArray(length); 7093 int result_index = 0; 7094 { 7095 i::DisallowHeapAllocation no_gc; 7096 int capacity = table->UsedCapacity(); 7097 i::Oddball* the_hole = isolate->heap()->the_hole_value(); 7098 for (int i = 0; i < capacity; ++i) { 7099 i::Object* key = table->KeyAt(i); 7100 if (key == the_hole) continue; 7101 result->set(result_index++, key); 7102 } 7103 } 7104 DCHECK_EQ(result_index, result->length()); 7105 DCHECK_EQ(result_index, length); 7106 i::Handle<i::JSArray> result_array = 7107 factory->NewJSArrayWithElements(result, i::FAST_ELEMENTS, length); 7108 return Utils::ToLocal(result_array); 7109 } 7110 7111 7112 MaybeLocal<Promise::Resolver> Promise::Resolver::New(Local<Context> context) { 7113 PREPARE_FOR_EXECUTION(context, Promise_Resolver, New, Resolver); 7114 i::Handle<i::Object> result; 7115 has_pending_exception = 7116 !i::Execution::Call(isolate, isolate->promise_create(), 7117 isolate->factory()->undefined_value(), 0, NULL) 7118 .ToHandle(&result); 7119 RETURN_ON_FAILED_EXECUTION(Promise::Resolver); 7120 RETURN_ESCAPED(Local<Promise::Resolver>::Cast(Utils::ToLocal(result))); 7121 } 7122 7123 7124 Local<Promise::Resolver> Promise::Resolver::New(Isolate* isolate) { 7125 RETURN_TO_LOCAL_UNCHECKED(New(isolate->GetCurrentContext()), 7126 Promise::Resolver); 7127 } 7128 7129 7130 Local<Promise> Promise::Resolver::GetPromise() { 7131 i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this); 7132 return Local<Promise>::Cast(Utils::ToLocal(promise)); 7133 } 7134 7135 7136 Maybe<bool> Promise::Resolver::Resolve(Local<Context> context, 7137 Local<Value> value) { 7138 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Promise_Resolver, Resolve, bool); 7139 auto self = Utils::OpenHandle(this); 7140 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)}; 7141 has_pending_exception = 7142 i::Execution::Call(isolate, isolate->promise_resolve(), 7143 isolate->factory()->undefined_value(), arraysize(argv), 7144 argv) 7145 .is_null(); 7146 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 7147 return Just(true); 7148 } 7149 7150 7151 void Promise::Resolver::Resolve(Local<Value> value) { 7152 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 7153 USE(Resolve(context, value)); 7154 } 7155 7156 7157 Maybe<bool> Promise::Resolver::Reject(Local<Context> context, 7158 Local<Value> value) { 7159 PREPARE_FOR_EXECUTION_PRIMITIVE(context, Promise_Resolver, Resolve, bool); 7160 auto self = Utils::OpenHandle(this); 7161 i::Handle<i::Object> argv[] = {self, Utils::OpenHandle(*value)}; 7162 has_pending_exception = 7163 i::Execution::Call(isolate, isolate->promise_reject(), 7164 isolate->factory()->undefined_value(), arraysize(argv), 7165 argv) 7166 .is_null(); 7167 RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); 7168 return Just(true); 7169 } 7170 7171 7172 void Promise::Resolver::Reject(Local<Value> value) { 7173 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 7174 USE(Reject(context, value)); 7175 } 7176 7177 7178 MaybeLocal<Promise> Promise::Catch(Local<Context> context, 7179 Local<Function> handler) { 7180 PREPARE_FOR_EXECUTION(context, Promise, Catch, Promise); 7181 auto self = Utils::OpenHandle(this); 7182 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) }; 7183 i::Handle<i::Object> result; 7184 has_pending_exception = !i::Execution::Call(isolate, isolate->promise_catch(), 7185 self, arraysize(argv), argv) 7186 .ToHandle(&result); 7187 RETURN_ON_FAILED_EXECUTION(Promise); 7188 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result))); 7189 } 7190 7191 7192 Local<Promise> Promise::Catch(Local<Function> handler) { 7193 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 7194 RETURN_TO_LOCAL_UNCHECKED(Catch(context, handler), Promise); 7195 } 7196 7197 7198 MaybeLocal<Promise> Promise::Then(Local<Context> context, 7199 Local<Function> handler) { 7200 PREPARE_FOR_EXECUTION(context, Promise, Then, Promise); 7201 auto self = Utils::OpenHandle(this); 7202 i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) }; 7203 i::Handle<i::Object> result; 7204 has_pending_exception = !i::Execution::Call(isolate, isolate->promise_then(), 7205 self, arraysize(argv), argv) 7206 .ToHandle(&result); 7207 RETURN_ON_FAILED_EXECUTION(Promise); 7208 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result))); 7209 } 7210 7211 7212 Local<Promise> Promise::Then(Local<Function> handler) { 7213 auto context = ContextFromHeapObject(Utils::OpenHandle(this)); 7214 RETURN_TO_LOCAL_UNCHECKED(Then(context, handler), Promise); 7215 } 7216 7217 7218 bool Promise::HasHandler() { 7219 i::Handle<i::JSReceiver> promise = Utils::OpenHandle(this); 7220 i::Isolate* isolate = promise->GetIsolate(); 7221 LOG_API(isolate, Promise, HasRejectHandler); 7222 ENTER_V8(isolate); 7223 i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol(); 7224 return i::JSReceiver::GetDataProperty(promise, key)->IsTrue(isolate); 7225 } 7226 7227 7228 Local<Object> Proxy::GetTarget() { 7229 i::Handle<i::JSProxy> self = Utils::OpenHandle(this); 7230 i::Handle<i::JSReceiver> target(self->target()); 7231 return Utils::ToLocal(target); 7232 } 7233 7234 7235 Local<Value> Proxy::GetHandler() { 7236 i::Handle<i::JSProxy> self = Utils::OpenHandle(this); 7237 i::Handle<i::Object> handler(self->handler(), self->GetIsolate()); 7238 return Utils::ToLocal(handler); 7239 } 7240 7241 7242 bool Proxy::IsRevoked() { 7243 i::Handle<i::JSProxy> self = Utils::OpenHandle(this); 7244 return self->IsRevoked(); 7245 } 7246 7247 7248 void Proxy::Revoke() { 7249 i::Handle<i::JSProxy> self = Utils::OpenHandle(this); 7250 i::JSProxy::Revoke(self); 7251 } 7252 7253 7254 MaybeLocal<Proxy> Proxy::New(Local<Context> context, Local<Object> local_target, 7255 Local<Object> local_handler) { 7256 PREPARE_FOR_EXECUTION(context, Proxy, New, Proxy); 7257 i::Handle<i::JSReceiver> target = Utils::OpenHandle(*local_target); 7258 i::Handle<i::JSReceiver> handler = Utils::OpenHandle(*local_handler); 7259 Local<Proxy> result; 7260 has_pending_exception = 7261 !ToLocal<Proxy>(i::JSProxy::New(isolate, target, handler), &result); 7262 RETURN_ON_FAILED_EXECUTION(Proxy); 7263 RETURN_ESCAPED(result); 7264 } 7265 7266 Local<String> WasmCompiledModule::GetWasmWireBytes() { 7267 i::Handle<i::JSObject> obj = 7268 i::Handle<i::JSObject>::cast(Utils::OpenHandle(this)); 7269 i::Handle<i::WasmCompiledModule> compiled_part = 7270 i::handle(i::WasmCompiledModule::cast(obj->GetInternalField(0))); 7271 i::Handle<i::String> wire_bytes = compiled_part->module_bytes(); 7272 return Local<String>::Cast(Utils::ToLocal(wire_bytes)); 7273 } 7274 7275 WasmCompiledModule::SerializedModule WasmCompiledModule::Serialize() { 7276 i::Handle<i::JSObject> obj = 7277 i::Handle<i::JSObject>::cast(Utils::OpenHandle(this)); 7278 i::Handle<i::WasmCompiledModule> compiled_part = 7279 i::handle(i::WasmCompiledModule::cast(obj->GetInternalField(0))); 7280 7281 std::unique_ptr<i::ScriptData> script_data = 7282 i::WasmCompiledModuleSerializer::SerializeWasmModule(obj->GetIsolate(), 7283 compiled_part); 7284 script_data->ReleaseDataOwnership(); 7285 7286 size_t size = static_cast<size_t>(script_data->length()); 7287 return {std::unique_ptr<const uint8_t[]>(script_data->data()), size}; 7288 } 7289 7290 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Deserialize( 7291 Isolate* isolate, 7292 const WasmCompiledModule::CallerOwnedBuffer& serialized_module, 7293 const WasmCompiledModule::CallerOwnedBuffer& wire_bytes) { 7294 int size = static_cast<int>(serialized_module.second); 7295 i::ScriptData sc(serialized_module.first, size); 7296 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7297 i::MaybeHandle<i::FixedArray> maybe_compiled_part = 7298 i::WasmCompiledModuleSerializer::DeserializeWasmModule( 7299 i_isolate, &sc, 7300 {wire_bytes.first, static_cast<int>(wire_bytes.second)}); 7301 i::Handle<i::FixedArray> compiled_part; 7302 if (!maybe_compiled_part.ToHandle(&compiled_part)) { 7303 return MaybeLocal<WasmCompiledModule>(); 7304 } 7305 i::Handle<i::WasmCompiledModule> compiled_module = 7306 handle(i::WasmCompiledModule::cast(*compiled_part)); 7307 return Local<WasmCompiledModule>::Cast( 7308 Utils::ToLocal(i::Handle<i::JSObject>::cast( 7309 i::WasmModuleObject::New(i_isolate, compiled_module)))); 7310 } 7311 7312 MaybeLocal<WasmCompiledModule> WasmCompiledModule::DeserializeOrCompile( 7313 Isolate* isolate, 7314 const WasmCompiledModule::CallerOwnedBuffer& serialized_module, 7315 const WasmCompiledModule::CallerOwnedBuffer& wire_bytes) { 7316 MaybeLocal<WasmCompiledModule> ret = 7317 Deserialize(isolate, serialized_module, wire_bytes); 7318 if (!ret.IsEmpty()) { 7319 return ret; 7320 } 7321 return Compile(isolate, wire_bytes.first, wire_bytes.second); 7322 } 7323 7324 MaybeLocal<WasmCompiledModule> WasmCompiledModule::Compile(Isolate* isolate, 7325 const uint8_t* start, 7326 size_t length) { 7327 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7328 i::wasm::ErrorThrower thrower(i_isolate, "WasmCompiledModule::Deserialize()"); 7329 i::MaybeHandle<i::JSObject> maybe_compiled = 7330 i::wasm::CreateModuleObjectFromBytes( 7331 i_isolate, start, start + length, &thrower, 7332 i::wasm::ModuleOrigin::kWasmOrigin, i::Handle<i::Script>::null(), 7333 nullptr, nullptr); 7334 if (maybe_compiled.is_null()) return MaybeLocal<WasmCompiledModule>(); 7335 return Local<WasmCompiledModule>::Cast( 7336 Utils::ToLocal(maybe_compiled.ToHandleChecked())); 7337 } 7338 7339 // static 7340 v8::ArrayBuffer::Allocator* v8::ArrayBuffer::Allocator::NewDefaultAllocator() { 7341 return new ArrayBufferAllocator(); 7342 } 7343 7344 bool v8::ArrayBuffer::IsExternal() const { 7345 return Utils::OpenHandle(this)->is_external(); 7346 } 7347 7348 7349 bool v8::ArrayBuffer::IsNeuterable() const { 7350 return Utils::OpenHandle(this)->is_neuterable(); 7351 } 7352 7353 7354 v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() { 7355 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this); 7356 i::Isolate* isolate = self->GetIsolate(); 7357 Utils::ApiCheck(!self->is_external(), "v8_ArrayBuffer_Externalize", 7358 "ArrayBuffer already externalized"); 7359 self->set_is_external(true); 7360 isolate->heap()->UnregisterArrayBuffer(*self); 7361 7362 return GetContents(); 7363 } 7364 7365 7366 v8::ArrayBuffer::Contents v8::ArrayBuffer::GetContents() { 7367 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this); 7368 size_t byte_length = static_cast<size_t>(self->byte_length()->Number()); 7369 Contents contents; 7370 contents.data_ = self->backing_store(); 7371 contents.byte_length_ = byte_length; 7372 return contents; 7373 } 7374 7375 7376 void v8::ArrayBuffer::Neuter() { 7377 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this); 7378 i::Isolate* isolate = obj->GetIsolate(); 7379 Utils::ApiCheck(obj->is_external(), 7380 "v8::ArrayBuffer::Neuter", 7381 "Only externalized ArrayBuffers can be neutered"); 7382 Utils::ApiCheck(obj->is_neuterable(), "v8::ArrayBuffer::Neuter", 7383 "Only neuterable ArrayBuffers can be neutered"); 7384 LOG_API(isolate, ArrayBuffer, Neuter); 7385 ENTER_V8(isolate); 7386 obj->Neuter(); 7387 } 7388 7389 7390 size_t v8::ArrayBuffer::ByteLength() const { 7391 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this); 7392 return static_cast<size_t>(obj->byte_length()->Number()); 7393 } 7394 7395 7396 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) { 7397 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7398 LOG_API(i_isolate, ArrayBuffer, New); 7399 ENTER_V8(i_isolate); 7400 i::Handle<i::JSArrayBuffer> obj = 7401 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared); 7402 // TODO(jbroman): It may be useful in the future to provide a MaybeLocal 7403 // version that throws an exception or otherwise does not crash. 7404 if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length)) { 7405 i::FatalProcessOutOfMemory("v8::ArrayBuffer::New"); 7406 } 7407 return Utils::ToLocal(obj); 7408 } 7409 7410 7411 Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data, 7412 size_t byte_length, 7413 ArrayBufferCreationMode mode) { 7414 // Embedders must guarantee that the external backing store is valid. 7415 CHECK(byte_length == 0 || data != NULL); 7416 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7417 LOG_API(i_isolate, ArrayBuffer, New); 7418 ENTER_V8(i_isolate); 7419 i::Handle<i::JSArrayBuffer> obj = 7420 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kNotShared); 7421 i::JSArrayBuffer::Setup(obj, i_isolate, 7422 mode == ArrayBufferCreationMode::kExternalized, data, 7423 byte_length); 7424 return Utils::ToLocal(obj); 7425 } 7426 7427 7428 Local<ArrayBuffer> v8::ArrayBufferView::Buffer() { 7429 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this); 7430 i::Handle<i::JSArrayBuffer> buffer; 7431 if (obj->IsJSDataView()) { 7432 i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj)); 7433 DCHECK(data_view->buffer()->IsJSArrayBuffer()); 7434 buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer())); 7435 } else { 7436 DCHECK(obj->IsJSTypedArray()); 7437 buffer = i::JSTypedArray::cast(*obj)->GetBuffer(); 7438 } 7439 return Utils::ToLocal(buffer); 7440 } 7441 7442 7443 size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) { 7444 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this); 7445 size_t byte_offset = i::NumberToSize(self->byte_offset()); 7446 size_t bytes_to_copy = 7447 i::Min(byte_length, i::NumberToSize(self->byte_length())); 7448 if (bytes_to_copy) { 7449 i::DisallowHeapAllocation no_gc; 7450 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer())); 7451 const char* source = reinterpret_cast<char*>(buffer->backing_store()); 7452 if (source == nullptr) { 7453 DCHECK(self->IsJSTypedArray()); 7454 i::Handle<i::JSTypedArray> typed_array(i::JSTypedArray::cast(*self)); 7455 i::Handle<i::FixedTypedArrayBase> fixed_array( 7456 i::FixedTypedArrayBase::cast(typed_array->elements())); 7457 source = reinterpret_cast<char*>(fixed_array->DataPtr()); 7458 } 7459 memcpy(dest, source + byte_offset, bytes_to_copy); 7460 } 7461 return bytes_to_copy; 7462 } 7463 7464 7465 bool v8::ArrayBufferView::HasBuffer() const { 7466 i::Handle<i::JSArrayBufferView> self = Utils::OpenHandle(this); 7467 i::Handle<i::JSArrayBuffer> buffer(i::JSArrayBuffer::cast(self->buffer())); 7468 return buffer->backing_store() != nullptr; 7469 } 7470 7471 7472 size_t v8::ArrayBufferView::ByteOffset() { 7473 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this); 7474 return static_cast<size_t>(obj->byte_offset()->Number()); 7475 } 7476 7477 7478 size_t v8::ArrayBufferView::ByteLength() { 7479 i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this); 7480 return static_cast<size_t>(obj->byte_length()->Number()); 7481 } 7482 7483 7484 size_t v8::TypedArray::Length() { 7485 i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this); 7486 return static_cast<size_t>(obj->length_value()); 7487 } 7488 7489 #define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \ 7490 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \ 7491 size_t byte_offset, size_t length) { \ 7492 i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \ 7493 LOG_API(isolate, Type##Array, New); \ 7494 ENTER_V8(isolate); \ 7495 if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \ 7496 "v8::" #Type \ 7497 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \ 7498 "length exceeds max allowed value")) { \ 7499 return Local<Type##Array>(); \ 7500 } \ 7501 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); \ 7502 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \ 7503 i::kExternal##Type##Array, buffer, byte_offset, length); \ 7504 return Utils::ToLocal##Type##Array(obj); \ 7505 } \ 7506 Local<Type##Array> Type##Array::New( \ 7507 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \ 7508 size_t length) { \ 7509 CHECK(i::FLAG_harmony_sharedarraybuffer); \ 7510 i::Isolate* isolate = \ 7511 Utils::OpenHandle(*shared_array_buffer)->GetIsolate(); \ 7512 LOG_API(isolate, Type##Array, New); \ 7513 ENTER_V8(isolate); \ 7514 if (!Utils::ApiCheck( \ 7515 length <= static_cast<size_t>(i::Smi::kMaxValue), \ 7516 "v8::" #Type \ 7517 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \ 7518 "length exceeds max allowed value")) { \ 7519 return Local<Type##Array>(); \ 7520 } \ 7521 i::Handle<i::JSArrayBuffer> buffer = \ 7522 Utils::OpenHandle(*shared_array_buffer); \ 7523 i::Handle<i::JSTypedArray> obj = isolate->factory()->NewJSTypedArray( \ 7524 i::kExternal##Type##Array, buffer, byte_offset, length); \ 7525 return Utils::ToLocal##Type##Array(obj); \ 7526 } 7527 7528 TYPED_ARRAYS(TYPED_ARRAY_NEW) 7529 #undef TYPED_ARRAY_NEW 7530 7531 Local<DataView> DataView::New(Local<ArrayBuffer> array_buffer, 7532 size_t byte_offset, size_t byte_length) { 7533 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer); 7534 i::Isolate* isolate = buffer->GetIsolate(); 7535 LOG_API(isolate, DataView, New); 7536 ENTER_V8(isolate); 7537 i::Handle<i::JSDataView> obj = 7538 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length); 7539 return Utils::ToLocal(obj); 7540 } 7541 7542 7543 Local<DataView> DataView::New(Local<SharedArrayBuffer> shared_array_buffer, 7544 size_t byte_offset, size_t byte_length) { 7545 CHECK(i::FLAG_harmony_sharedarraybuffer); 7546 i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*shared_array_buffer); 7547 i::Isolate* isolate = buffer->GetIsolate(); 7548 LOG_API(isolate, DataView, New); 7549 ENTER_V8(isolate); 7550 i::Handle<i::JSDataView> obj = 7551 isolate->factory()->NewJSDataView(buffer, byte_offset, byte_length); 7552 return Utils::ToLocal(obj); 7553 } 7554 7555 7556 bool v8::SharedArrayBuffer::IsExternal() const { 7557 return Utils::OpenHandle(this)->is_external(); 7558 } 7559 7560 7561 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() { 7562 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this); 7563 i::Isolate* isolate = self->GetIsolate(); 7564 Utils::ApiCheck(!self->is_external(), "v8_SharedArrayBuffer_Externalize", 7565 "SharedArrayBuffer already externalized"); 7566 self->set_is_external(true); 7567 isolate->heap()->UnregisterArrayBuffer(*self); 7568 return GetContents(); 7569 } 7570 7571 7572 v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() { 7573 i::Handle<i::JSArrayBuffer> self = Utils::OpenHandle(this); 7574 size_t byte_length = static_cast<size_t>(self->byte_length()->Number()); 7575 Contents contents; 7576 contents.data_ = self->backing_store(); 7577 contents.byte_length_ = byte_length; 7578 return contents; 7579 } 7580 7581 7582 size_t v8::SharedArrayBuffer::ByteLength() const { 7583 i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this); 7584 return static_cast<size_t>(obj->byte_length()->Number()); 7585 } 7586 7587 7588 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(Isolate* isolate, 7589 size_t byte_length) { 7590 CHECK(i::FLAG_harmony_sharedarraybuffer); 7591 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7592 LOG_API(i_isolate, SharedArrayBuffer, New); 7593 ENTER_V8(i_isolate); 7594 i::Handle<i::JSArrayBuffer> obj = 7595 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared); 7596 // TODO(jbroman): It may be useful in the future to provide a MaybeLocal 7597 // version that throws an exception or otherwise does not crash. 7598 if (!i::JSArrayBuffer::SetupAllocatingData(obj, i_isolate, byte_length, true, 7599 i::SharedFlag::kShared)) { 7600 i::FatalProcessOutOfMemory("v8::SharedArrayBuffer::New"); 7601 } 7602 return Utils::ToLocalShared(obj); 7603 } 7604 7605 7606 Local<SharedArrayBuffer> v8::SharedArrayBuffer::New( 7607 Isolate* isolate, void* data, size_t byte_length, 7608 ArrayBufferCreationMode mode) { 7609 CHECK(i::FLAG_harmony_sharedarraybuffer); 7610 // Embedders must guarantee that the external backing store is valid. 7611 CHECK(byte_length == 0 || data != NULL); 7612 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7613 LOG_API(i_isolate, SharedArrayBuffer, New); 7614 ENTER_V8(i_isolate); 7615 i::Handle<i::JSArrayBuffer> obj = 7616 i_isolate->factory()->NewJSArrayBuffer(i::SharedFlag::kShared); 7617 i::JSArrayBuffer::Setup(obj, i_isolate, 7618 mode == ArrayBufferCreationMode::kExternalized, data, 7619 byte_length, i::SharedFlag::kShared); 7620 return Utils::ToLocalShared(obj); 7621 } 7622 7623 7624 Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) { 7625 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7626 LOG_API(i_isolate, Symbol, New); 7627 ENTER_V8(i_isolate); 7628 i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol(); 7629 if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name)); 7630 return Utils::ToLocal(result); 7631 } 7632 7633 7634 static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate, 7635 i::Handle<i::String> name, 7636 i::Handle<i::String> part, 7637 bool private_symbol) { 7638 i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry(); 7639 i::Handle<i::JSObject> symbols = 7640 i::Handle<i::JSObject>::cast( 7641 i::Object::GetPropertyOrElement(registry, part).ToHandleChecked()); 7642 i::Handle<i::Object> symbol = 7643 i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked(); 7644 if (!symbol->IsSymbol()) { 7645 DCHECK(symbol->IsUndefined(isolate)); 7646 if (private_symbol) 7647 symbol = isolate->factory()->NewPrivateSymbol(); 7648 else 7649 symbol = isolate->factory()->NewSymbol(); 7650 i::Handle<i::Symbol>::cast(symbol)->set_name(*name); 7651 i::Object::SetPropertyOrElement(symbols, name, symbol, i::STRICT).Assert(); 7652 } 7653 return i::Handle<i::Symbol>::cast(symbol); 7654 } 7655 7656 7657 Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) { 7658 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7659 i::Handle<i::String> i_name = Utils::OpenHandle(*name); 7660 i::Handle<i::String> part = i_isolate->factory()->for_string(); 7661 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part, false)); 7662 } 7663 7664 7665 Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) { 7666 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7667 i::Handle<i::String> i_name = Utils::OpenHandle(*name); 7668 i::Handle<i::String> part = i_isolate->factory()->for_api_string(); 7669 return Utils::ToLocal(SymbolFor(i_isolate, i_name, part, false)); 7670 } 7671 7672 7673 Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) { 7674 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7675 return Utils::ToLocal(i_isolate->factory()->iterator_symbol()); 7676 } 7677 7678 7679 Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) { 7680 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7681 return Utils::ToLocal(i_isolate->factory()->unscopables_symbol()); 7682 } 7683 7684 7685 Local<Symbol> v8::Symbol::GetToStringTag(Isolate* isolate) { 7686 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7687 return Utils::ToLocal(i_isolate->factory()->to_string_tag_symbol()); 7688 } 7689 7690 7691 Local<Symbol> v8::Symbol::GetIsConcatSpreadable(Isolate* isolate) { 7692 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7693 return Utils::ToLocal(i_isolate->factory()->is_concat_spreadable_symbol()); 7694 } 7695 7696 7697 Local<Private> v8::Private::New(Isolate* isolate, Local<String> name) { 7698 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7699 LOG_API(i_isolate, Private, New); 7700 ENTER_V8(i_isolate); 7701 i::Handle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol(); 7702 if (!name.IsEmpty()) symbol->set_name(*Utils::OpenHandle(*name)); 7703 Local<Symbol> result = Utils::ToLocal(symbol); 7704 return v8::Local<Private>(reinterpret_cast<Private*>(*result)); 7705 } 7706 7707 7708 Local<Private> v8::Private::ForApi(Isolate* isolate, Local<String> name) { 7709 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 7710 i::Handle<i::String> i_name = Utils::OpenHandle(*name); 7711 i::Handle<i::String> part = i_isolate->factory()->private_api_string(); 7712 Local<Symbol> result = 7713 Utils::ToLocal(SymbolFor(i_isolate, i_name, part, true)); 7714 return v8::Local<Private>(reinterpret_cast<Private*>(*result)); 7715 } 7716 7717 7718 Local<Number> v8::Number::New(Isolate* isolate, double value) { 7719 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 7720 if (std::isnan(value)) { 7721 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs. 7722 value = std::numeric_limits<double>::quiet_NaN(); 7723 } 7724 ENTER_V8(internal_isolate); 7725 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value); 7726 return Utils::NumberToLocal(result); 7727 } 7728 7729 7730 Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) { 7731 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 7732 if (i::Smi::IsValid(value)) { 7733 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value), 7734 internal_isolate)); 7735 } 7736 ENTER_V8(internal_isolate); 7737 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value); 7738 return Utils::IntegerToLocal(result); 7739 } 7740 7741 7742 Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) { 7743 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 7744 bool fits_into_int32_t = (value & (1 << 31)) == 0; 7745 if (fits_into_int32_t) { 7746 return Integer::New(isolate, static_cast<int32_t>(value)); 7747 } 7748 ENTER_V8(internal_isolate); 7749 i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value); 7750 return Utils::IntegerToLocal(result); 7751 } 7752 7753 7754 void Isolate::ReportExternalAllocationLimitReached() { 7755 i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap(); 7756 if (heap->gc_state() != i::Heap::NOT_IN_GC) return; 7757 heap->ReportExternalMemoryPressure(); 7758 } 7759 7760 7761 HeapProfiler* Isolate::GetHeapProfiler() { 7762 i::HeapProfiler* heap_profiler = 7763 reinterpret_cast<i::Isolate*>(this)->heap_profiler(); 7764 return reinterpret_cast<HeapProfiler*>(heap_profiler); 7765 } 7766 7767 7768 CpuProfiler* Isolate::GetCpuProfiler() { 7769 i::CpuProfiler* cpu_profiler = 7770 reinterpret_cast<i::Isolate*>(this)->cpu_profiler(); 7771 return reinterpret_cast<CpuProfiler*>(cpu_profiler); 7772 } 7773 7774 7775 bool Isolate::InContext() { 7776 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7777 return isolate->context() != NULL; 7778 } 7779 7780 7781 v8::Local<v8::Context> Isolate::GetCurrentContext() { 7782 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7783 i::Context* context = isolate->context(); 7784 if (context == NULL) return Local<Context>(); 7785 i::Context* native_context = context->native_context(); 7786 if (native_context == NULL) return Local<Context>(); 7787 return Utils::ToLocal(i::Handle<i::Context>(native_context)); 7788 } 7789 7790 7791 v8::Local<v8::Context> Isolate::GetCallingContext() { 7792 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7793 i::Handle<i::Object> calling = isolate->GetCallingNativeContext(); 7794 if (calling.is_null()) return Local<Context>(); 7795 return Utils::ToLocal(i::Handle<i::Context>::cast(calling)); 7796 } 7797 7798 7799 v8::Local<v8::Context> Isolate::GetEnteredContext() { 7800 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7801 i::Handle<i::Object> last = 7802 isolate->handle_scope_implementer()->LastEnteredContext(); 7803 if (last.is_null()) return Local<Context>(); 7804 return Utils::ToLocal(i::Handle<i::Context>::cast(last)); 7805 } 7806 7807 7808 v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) { 7809 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7810 ENTER_V8(isolate); 7811 // If we're passed an empty handle, we throw an undefined exception 7812 // to deal more gracefully with out of memory situations. 7813 if (value.IsEmpty()) { 7814 isolate->ScheduleThrow(isolate->heap()->undefined_value()); 7815 } else { 7816 isolate->ScheduleThrow(*Utils::OpenHandle(*value)); 7817 } 7818 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 7819 } 7820 7821 7822 void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) { 7823 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this); 7824 internal_isolate->global_handles()->SetObjectGroupId( 7825 i::Handle<i::Object>(object).location(), id); 7826 } 7827 7828 7829 void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) { 7830 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this); 7831 internal_isolate->global_handles()->SetReferenceFromGroup( 7832 id, i::Handle<i::Object>(object).location()); 7833 } 7834 7835 7836 void Isolate::SetReference(internal::Object** parent, 7837 internal::Object** child) { 7838 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this); 7839 i::Object** parent_location = i::Handle<i::Object>(parent).location(); 7840 internal_isolate->global_handles()->SetReference( 7841 reinterpret_cast<i::HeapObject**>(parent_location), 7842 i::Handle<i::Object>(child).location()); 7843 } 7844 7845 7846 void Isolate::AddGCPrologueCallback(GCCallback callback, GCType gc_type) { 7847 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7848 isolate->heap()->AddGCPrologueCallback(callback, gc_type); 7849 } 7850 7851 7852 void Isolate::RemoveGCPrologueCallback(GCCallback callback) { 7853 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7854 isolate->heap()->RemoveGCPrologueCallback(callback); 7855 } 7856 7857 7858 void Isolate::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) { 7859 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7860 isolate->heap()->AddGCEpilogueCallback(callback, gc_type); 7861 } 7862 7863 7864 void Isolate::RemoveGCEpilogueCallback(GCCallback callback) { 7865 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7866 isolate->heap()->RemoveGCEpilogueCallback(callback); 7867 } 7868 7869 7870 void V8::AddGCPrologueCallback(GCCallback callback, GCType gc_type) { 7871 i::Isolate* isolate = i::Isolate::Current(); 7872 isolate->heap()->AddGCPrologueCallback( 7873 reinterpret_cast<v8::Isolate::GCCallback>(callback), gc_type, false); 7874 } 7875 7876 7877 void V8::AddGCEpilogueCallback(GCCallback callback, GCType gc_type) { 7878 i::Isolate* isolate = i::Isolate::Current(); 7879 isolate->heap()->AddGCEpilogueCallback( 7880 reinterpret_cast<v8::Isolate::GCCallback>(callback), gc_type, false); 7881 } 7882 7883 void Isolate::SetEmbedderHeapTracer(EmbedderHeapTracer* tracer) { 7884 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7885 isolate->heap()->SetEmbedderHeapTracer(tracer); 7886 } 7887 7888 void Isolate::TerminateExecution() { 7889 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7890 isolate->stack_guard()->RequestTerminateExecution(); 7891 } 7892 7893 7894 bool Isolate::IsExecutionTerminating() { 7895 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7896 return IsExecutionTerminatingCheck(isolate); 7897 } 7898 7899 7900 void Isolate::CancelTerminateExecution() { 7901 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7902 isolate->stack_guard()->ClearTerminateExecution(); 7903 isolate->CancelTerminateExecution(); 7904 } 7905 7906 7907 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) { 7908 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7909 isolate->RequestInterrupt(callback, data); 7910 } 7911 7912 7913 void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) { 7914 CHECK(i::FLAG_expose_gc); 7915 if (type == kMinorGarbageCollection) { 7916 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage( 7917 i::NEW_SPACE, i::GarbageCollectionReason::kTesting, 7918 kGCCallbackFlagForced); 7919 } else { 7920 DCHECK_EQ(kFullGarbageCollection, type); 7921 reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage( 7922 i::Heap::kAbortIncrementalMarkingMask, 7923 i::GarbageCollectionReason::kTesting, kGCCallbackFlagForced); 7924 } 7925 } 7926 7927 7928 Isolate* Isolate::GetCurrent() { 7929 i::Isolate* isolate = i::Isolate::Current(); 7930 return reinterpret_cast<Isolate*>(isolate); 7931 } 7932 7933 7934 Isolate* Isolate::New(const Isolate::CreateParams& params) { 7935 i::Isolate* isolate = new i::Isolate(false); 7936 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate); 7937 CHECK(params.array_buffer_allocator != NULL); 7938 isolate->set_array_buffer_allocator(params.array_buffer_allocator); 7939 if (params.snapshot_blob != NULL) { 7940 isolate->set_snapshot_blob(params.snapshot_blob); 7941 } else { 7942 isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob()); 7943 } 7944 if (params.entry_hook) { 7945 isolate->set_function_entry_hook(params.entry_hook); 7946 } 7947 auto code_event_handler = params.code_event_handler; 7948 #ifdef ENABLE_GDB_JIT_INTERFACE 7949 if (code_event_handler == nullptr && i::FLAG_gdbjit) { 7950 code_event_handler = i::GDBJITInterface::EventHandler; 7951 } 7952 #endif // ENABLE_GDB_JIT_INTERFACE 7953 if (code_event_handler) { 7954 isolate->InitializeLoggingAndCounters(); 7955 isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault, 7956 code_event_handler); 7957 } 7958 if (params.counter_lookup_callback) { 7959 v8_isolate->SetCounterFunction(params.counter_lookup_callback); 7960 } 7961 7962 if (params.create_histogram_callback) { 7963 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback); 7964 } 7965 7966 if (params.add_histogram_sample_callback) { 7967 v8_isolate->SetAddHistogramSampleFunction( 7968 params.add_histogram_sample_callback); 7969 } 7970 7971 isolate->set_api_external_references(params.external_references); 7972 isolate->set_deserialize_internal_fields_callback( 7973 params.deserialize_internal_fields_callback); 7974 SetResourceConstraints(isolate, params.constraints); 7975 // TODO(jochen): Once we got rid of Isolate::Current(), we can remove this. 7976 Isolate::Scope isolate_scope(v8_isolate); 7977 if (params.entry_hook || !i::Snapshot::Initialize(isolate)) { 7978 isolate->Init(NULL); 7979 } 7980 return v8_isolate; 7981 } 7982 7983 7984 void Isolate::Dispose() { 7985 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7986 if (!Utils::ApiCheck(!isolate->IsInUse(), 7987 "v8::Isolate::Dispose()", 7988 "Disposing the isolate that is entered by a thread.")) { 7989 return; 7990 } 7991 isolate->TearDown(); 7992 } 7993 7994 7995 void Isolate::DiscardThreadSpecificMetadata() { 7996 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 7997 isolate->DiscardPerThreadDataForThisThread(); 7998 } 7999 8000 8001 void Isolate::Enter() { 8002 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8003 isolate->Enter(); 8004 } 8005 8006 8007 void Isolate::Exit() { 8008 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8009 isolate->Exit(); 8010 } 8011 8012 8013 void Isolate::SetAbortOnUncaughtExceptionCallback( 8014 AbortOnUncaughtExceptionCallback callback) { 8015 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8016 isolate->SetAbortOnUncaughtExceptionCallback(callback); 8017 } 8018 8019 8020 Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope( 8021 Isolate* isolate, 8022 Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure) 8023 : on_failure_(on_failure) { 8024 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8025 if (on_failure_ == CRASH_ON_FAILURE) { 8026 internal_ = reinterpret_cast<void*>( 8027 new i::DisallowJavascriptExecution(i_isolate)); 8028 } else { 8029 DCHECK_EQ(THROW_ON_FAILURE, on_failure); 8030 internal_ = reinterpret_cast<void*>( 8031 new i::ThrowOnJavascriptExecution(i_isolate)); 8032 } 8033 } 8034 8035 8036 Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() { 8037 if (on_failure_ == CRASH_ON_FAILURE) { 8038 delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_); 8039 } else { 8040 delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_); 8041 } 8042 } 8043 8044 8045 Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope( 8046 Isolate* isolate) { 8047 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8048 internal_assert_ = reinterpret_cast<void*>( 8049 new i::AllowJavascriptExecution(i_isolate)); 8050 internal_throws_ = reinterpret_cast<void*>( 8051 new i::NoThrowOnJavascriptExecution(i_isolate)); 8052 } 8053 8054 8055 Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() { 8056 delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_); 8057 delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_); 8058 } 8059 8060 8061 Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope( 8062 Isolate* isolate) 8063 : isolate_(reinterpret_cast<i::Isolate*>(isolate)) { 8064 isolate_->handle_scope_implementer()->IncrementCallDepth(); 8065 isolate_->handle_scope_implementer()->IncrementMicrotasksSuppressions(); 8066 } 8067 8068 8069 Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() { 8070 isolate_->handle_scope_implementer()->DecrementMicrotasksSuppressions(); 8071 isolate_->handle_scope_implementer()->DecrementCallDepth(); 8072 } 8073 8074 8075 void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) { 8076 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8077 i::Heap* heap = isolate->heap(); 8078 heap_statistics->total_heap_size_ = heap->CommittedMemory(); 8079 heap_statistics->total_heap_size_executable_ = 8080 heap->CommittedMemoryExecutable(); 8081 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory(); 8082 heap_statistics->total_available_size_ = heap->Available(); 8083 heap_statistics->used_heap_size_ = heap->SizeOfObjects(); 8084 heap_statistics->heap_size_limit_ = heap->MaxReserved(); 8085 heap_statistics->malloced_memory_ = 8086 isolate->allocator()->GetCurrentMemoryUsage(); 8087 heap_statistics->peak_malloced_memory_ = 8088 isolate->allocator()->GetMaxMemoryUsage(); 8089 heap_statistics->does_zap_garbage_ = heap->ShouldZapGarbage(); 8090 } 8091 8092 8093 size_t Isolate::NumberOfHeapSpaces() { 8094 return i::LAST_SPACE - i::FIRST_SPACE + 1; 8095 } 8096 8097 8098 bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics, 8099 size_t index) { 8100 if (!space_statistics) return false; 8101 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index))) 8102 return false; 8103 8104 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8105 i::Heap* heap = isolate->heap(); 8106 i::Space* space = heap->space(static_cast<int>(index)); 8107 8108 space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index)); 8109 space_statistics->space_size_ = space->CommittedMemory(); 8110 space_statistics->space_used_size_ = space->SizeOfObjects(); 8111 space_statistics->space_available_size_ = space->Available(); 8112 space_statistics->physical_space_size_ = space->CommittedPhysicalMemory(); 8113 return true; 8114 } 8115 8116 8117 size_t Isolate::NumberOfTrackedHeapObjectTypes() { 8118 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8119 i::Heap* heap = isolate->heap(); 8120 return heap->NumberOfTrackedHeapObjectTypes(); 8121 } 8122 8123 8124 bool Isolate::GetHeapObjectStatisticsAtLastGC( 8125 HeapObjectStatistics* object_statistics, size_t type_index) { 8126 if (!object_statistics) return false; 8127 if (V8_LIKELY(!i::FLAG_gc_stats)) return false; 8128 8129 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8130 i::Heap* heap = isolate->heap(); 8131 if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false; 8132 8133 const char* object_type; 8134 const char* object_sub_type; 8135 size_t object_count = heap->ObjectCountAtLastGC(type_index); 8136 size_t object_size = heap->ObjectSizeAtLastGC(type_index); 8137 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) { 8138 // There should be no objects counted when the type is unknown. 8139 DCHECK_EQ(object_count, 0U); 8140 DCHECK_EQ(object_size, 0U); 8141 return false; 8142 } 8143 8144 object_statistics->object_type_ = object_type; 8145 object_statistics->object_sub_type_ = object_sub_type; 8146 object_statistics->object_count_ = object_count; 8147 object_statistics->object_size_ = object_size; 8148 return true; 8149 } 8150 8151 bool Isolate::GetHeapCodeAndMetadataStatistics( 8152 HeapCodeStatistics* code_statistics) { 8153 if (!code_statistics) return false; 8154 8155 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8156 isolate->heap()->CollectCodeStatistics(); 8157 8158 code_statistics->code_and_metadata_size_ = isolate->code_and_metadata_size(); 8159 code_statistics->bytecode_and_metadata_size_ = 8160 isolate->bytecode_and_metadata_size(); 8161 return true; 8162 } 8163 8164 void Isolate::GetStackSample(const RegisterState& state, void** frames, 8165 size_t frames_limit, SampleInfo* sample_info) { 8166 RegisterState regs = state; 8167 if (TickSample::GetStackSample(this, ®s, TickSample::kSkipCEntryFrame, 8168 frames, frames_limit, sample_info)) { 8169 return; 8170 } 8171 sample_info->frames_count = 0; 8172 sample_info->vm_state = OTHER; 8173 sample_info->external_callback_entry = nullptr; 8174 } 8175 8176 size_t Isolate::NumberOfPhantomHandleResetsSinceLastCall() { 8177 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8178 size_t result = isolate->global_handles()->NumberOfPhantomHandleResets(); 8179 isolate->global_handles()->ResetNumberOfPhantomHandleResets(); 8180 return result; 8181 } 8182 8183 void Isolate::SetEventLogger(LogEventCallback that) { 8184 // Do not overwrite the event logger if we want to log explicitly. 8185 if (i::FLAG_log_internal_timer_events) return; 8186 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8187 isolate->set_event_logger(that); 8188 } 8189 8190 8191 void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) { 8192 if (callback == NULL) return; 8193 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8194 isolate->AddBeforeCallEnteredCallback(callback); 8195 } 8196 8197 8198 void Isolate::RemoveBeforeCallEnteredCallback( 8199 BeforeCallEnteredCallback callback) { 8200 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8201 isolate->RemoveBeforeCallEnteredCallback(callback); 8202 } 8203 8204 8205 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) { 8206 if (callback == NULL) return; 8207 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8208 isolate->AddCallCompletedCallback(callback); 8209 } 8210 8211 8212 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) { 8213 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8214 isolate->RemoveCallCompletedCallback(callback); 8215 } 8216 8217 8218 void Isolate::AddCallCompletedCallback( 8219 DeprecatedCallCompletedCallback callback) { 8220 AddCallCompletedCallback(reinterpret_cast<CallCompletedCallback>(callback)); 8221 } 8222 8223 8224 void Isolate::RemoveCallCompletedCallback( 8225 DeprecatedCallCompletedCallback callback) { 8226 RemoveCallCompletedCallback( 8227 reinterpret_cast<CallCompletedCallback>(callback)); 8228 } 8229 8230 8231 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) { 8232 if (callback == NULL) return; 8233 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8234 isolate->SetPromiseRejectCallback(callback); 8235 } 8236 8237 8238 void Isolate::RunMicrotasks() { 8239 DCHECK(MicrotasksPolicy::kScoped != GetMicrotasksPolicy()); 8240 reinterpret_cast<i::Isolate*>(this)->RunMicrotasks(); 8241 } 8242 8243 8244 void Isolate::EnqueueMicrotask(Local<Function> microtask) { 8245 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8246 isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask)); 8247 } 8248 8249 8250 void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) { 8251 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8252 i::HandleScope scope(isolate); 8253 i::Handle<i::CallHandlerInfo> callback_info = 8254 i::Handle<i::CallHandlerInfo>::cast( 8255 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE)); 8256 SET_FIELD_WRAPPED(callback_info, set_callback, microtask); 8257 SET_FIELD_WRAPPED(callback_info, set_data, data); 8258 isolate->EnqueueMicrotask(callback_info); 8259 } 8260 8261 8262 void Isolate::SetAutorunMicrotasks(bool autorun) { 8263 SetMicrotasksPolicy( 8264 autorun ? MicrotasksPolicy::kAuto : MicrotasksPolicy::kExplicit); 8265 } 8266 8267 8268 bool Isolate::WillAutorunMicrotasks() const { 8269 return GetMicrotasksPolicy() == MicrotasksPolicy::kAuto; 8270 } 8271 8272 8273 void Isolate::SetMicrotasksPolicy(MicrotasksPolicy policy) { 8274 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8275 isolate->handle_scope_implementer()->set_microtasks_policy(policy); 8276 } 8277 8278 8279 MicrotasksPolicy Isolate::GetMicrotasksPolicy() const { 8280 i::Isolate* isolate = 8281 reinterpret_cast<i::Isolate*>(const_cast<Isolate*>(this)); 8282 return isolate->handle_scope_implementer()->microtasks_policy(); 8283 } 8284 8285 8286 void Isolate::AddMicrotasksCompletedCallback( 8287 MicrotasksCompletedCallback callback) { 8288 DCHECK(callback); 8289 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8290 isolate->AddMicrotasksCompletedCallback(callback); 8291 } 8292 8293 8294 void Isolate::RemoveMicrotasksCompletedCallback( 8295 MicrotasksCompletedCallback callback) { 8296 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8297 isolate->RemoveMicrotasksCompletedCallback(callback); 8298 } 8299 8300 8301 void Isolate::SetUseCounterCallback(UseCounterCallback callback) { 8302 reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback); 8303 } 8304 8305 8306 void Isolate::SetCounterFunction(CounterLookupCallback callback) { 8307 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8308 isolate->stats_table()->SetCounterFunction(callback); 8309 isolate->InitializeLoggingAndCounters(); 8310 isolate->counters()->ResetCounters(); 8311 } 8312 8313 8314 void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) { 8315 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8316 isolate->stats_table()->SetCreateHistogramFunction(callback); 8317 isolate->InitializeLoggingAndCounters(); 8318 isolate->counters()->ResetHistograms(); 8319 } 8320 8321 8322 void Isolate::SetAddHistogramSampleFunction( 8323 AddHistogramSampleCallback callback) { 8324 reinterpret_cast<i::Isolate*>(this) 8325 ->stats_table() 8326 ->SetAddHistogramSampleFunction(callback); 8327 } 8328 8329 8330 bool Isolate::IdleNotification(int idle_time_in_ms) { 8331 // Returning true tells the caller that it need not 8332 // continue to call IdleNotification. 8333 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8334 if (!i::FLAG_use_idle_notification) return true; 8335 return isolate->heap()->IdleNotification(idle_time_in_ms); 8336 } 8337 8338 8339 bool Isolate::IdleNotificationDeadline(double deadline_in_seconds) { 8340 // Returning true tells the caller that it need not 8341 // continue to call IdleNotification. 8342 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8343 if (!i::FLAG_use_idle_notification) return true; 8344 return isolate->heap()->IdleNotification(deadline_in_seconds); 8345 } 8346 8347 8348 void Isolate::LowMemoryNotification() { 8349 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8350 { 8351 i::HistogramTimerScope idle_notification_scope( 8352 isolate->counters()->gc_low_memory_notification()); 8353 TRACE_EVENT0("v8", "V8.GCLowMemoryNotification"); 8354 isolate->heap()->CollectAllAvailableGarbage( 8355 i::GarbageCollectionReason::kLowMemoryNotification); 8356 } 8357 } 8358 8359 8360 int Isolate::ContextDisposedNotification(bool dependant_context) { 8361 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8362 return isolate->heap()->NotifyContextDisposed(dependant_context); 8363 } 8364 8365 8366 void Isolate::IsolateInForegroundNotification() { 8367 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8368 return isolate->IsolateInForegroundNotification(); 8369 } 8370 8371 8372 void Isolate::IsolateInBackgroundNotification() { 8373 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8374 return isolate->IsolateInBackgroundNotification(); 8375 } 8376 8377 void Isolate::MemoryPressureNotification(MemoryPressureLevel level) { 8378 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8379 isolate->heap()->MemoryPressureNotification(level, Locker::IsLocked(this)); 8380 isolate->allocator()->MemoryPressureNotification(level); 8381 } 8382 8383 void Isolate::SetRAILMode(RAILMode rail_mode) { 8384 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8385 return isolate->SetRAILMode(rail_mode); 8386 } 8387 8388 void Isolate::SetJitCodeEventHandler(JitCodeEventOptions options, 8389 JitCodeEventHandler event_handler) { 8390 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8391 // Ensure that logging is initialized for our isolate. 8392 isolate->InitializeLoggingAndCounters(); 8393 isolate->logger()->SetCodeEventHandler(options, event_handler); 8394 } 8395 8396 8397 void Isolate::SetStackLimit(uintptr_t stack_limit) { 8398 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8399 CHECK(stack_limit); 8400 isolate->stack_guard()->SetStackLimit(stack_limit); 8401 } 8402 8403 8404 void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) { 8405 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8406 if (isolate->heap()->memory_allocator()->code_range()->valid()) { 8407 *start = isolate->heap()->memory_allocator()->code_range()->start(); 8408 *length_in_bytes = 8409 isolate->heap()->memory_allocator()->code_range()->size(); 8410 } else { 8411 *start = NULL; 8412 *length_in_bytes = 0; 8413 } 8414 } 8415 8416 8417 void Isolate::SetFatalErrorHandler(FatalErrorCallback that) { 8418 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8419 isolate->set_exception_behavior(that); 8420 } 8421 8422 void Isolate::SetOOMErrorHandler(OOMErrorCallback that) { 8423 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8424 isolate->set_oom_behavior(that); 8425 } 8426 8427 void Isolate::SetAllowCodeGenerationFromStringsCallback( 8428 AllowCodeGenerationFromStringsCallback callback) { 8429 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8430 isolate->set_allow_code_gen_callback(callback); 8431 } 8432 8433 8434 bool Isolate::IsDead() { 8435 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8436 return isolate->IsDead(); 8437 } 8438 8439 8440 bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) { 8441 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8442 ENTER_V8(isolate); 8443 i::HandleScope scope(isolate); 8444 i::Handle<i::TemplateList> list = isolate->factory()->message_listeners(); 8445 i::Handle<i::FixedArray> listener = isolate->factory()->NewFixedArray(2); 8446 i::Handle<i::Foreign> foreign = 8447 isolate->factory()->NewForeign(FUNCTION_ADDR(that)); 8448 listener->set(0, *foreign); 8449 listener->set(1, data.IsEmpty() ? isolate->heap()->undefined_value() 8450 : *Utils::OpenHandle(*data)); 8451 list = i::TemplateList::Add(isolate, list, listener); 8452 isolate->heap()->SetMessageListeners(*list); 8453 return true; 8454 } 8455 8456 8457 void Isolate::RemoveMessageListeners(MessageCallback that) { 8458 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8459 ENTER_V8(isolate); 8460 i::HandleScope scope(isolate); 8461 i::DisallowHeapAllocation no_gc; 8462 i::TemplateList* listeners = isolate->heap()->message_listeners(); 8463 for (int i = 0; i < listeners->length(); i++) { 8464 if (listeners->get(i)->IsUndefined(isolate)) continue; // skip deleted ones 8465 i::FixedArray* listener = i::FixedArray::cast(listeners->get(i)); 8466 i::Foreign* callback_obj = i::Foreign::cast(listener->get(0)); 8467 if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) { 8468 listeners->set(i, isolate->heap()->undefined_value()); 8469 } 8470 } 8471 } 8472 8473 8474 void Isolate::SetFailedAccessCheckCallbackFunction( 8475 FailedAccessCheckCallback callback) { 8476 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8477 isolate->SetFailedAccessCheckCallback(callback); 8478 } 8479 8480 8481 void Isolate::SetCaptureStackTraceForUncaughtExceptions( 8482 bool capture, int frame_limit, StackTrace::StackTraceOptions options) { 8483 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8484 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit, 8485 options); 8486 } 8487 8488 8489 void Isolate::VisitExternalResources(ExternalResourceVisitor* visitor) { 8490 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8491 isolate->heap()->VisitExternalResources(visitor); 8492 } 8493 8494 8495 bool Isolate::IsInUse() { 8496 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8497 return isolate->IsInUse(); 8498 } 8499 8500 8501 class VisitorAdapter : public i::ObjectVisitor { 8502 public: 8503 explicit VisitorAdapter(PersistentHandleVisitor* visitor) 8504 : visitor_(visitor) {} 8505 void VisitPointers(i::Object** start, i::Object** end) override { 8506 UNREACHABLE(); 8507 } 8508 DISABLE_CFI_PERF 8509 void VisitEmbedderReference(i::Object** p, uint16_t class_id) override { 8510 Value* value = ToApi<Value>(i::Handle<i::Object>(p)); 8511 visitor_->VisitPersistentHandle( 8512 reinterpret_cast<Persistent<Value>*>(&value), class_id); 8513 } 8514 8515 private: 8516 PersistentHandleVisitor* visitor_; 8517 }; 8518 8519 8520 void Isolate::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) { 8521 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8522 i::DisallowHeapAllocation no_allocation; 8523 VisitorAdapter visitor_adapter(visitor); 8524 isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter); 8525 } 8526 8527 8528 void Isolate::VisitHandlesForPartialDependence( 8529 PersistentHandleVisitor* visitor) { 8530 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8531 i::DisallowHeapAllocation no_allocation; 8532 VisitorAdapter visitor_adapter(visitor); 8533 isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds( 8534 &visitor_adapter); 8535 } 8536 8537 8538 void Isolate::VisitWeakHandles(PersistentHandleVisitor* visitor) { 8539 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this); 8540 i::DisallowHeapAllocation no_allocation; 8541 VisitorAdapter visitor_adapter(visitor); 8542 isolate->global_handles()->IterateWeakRootsInNewSpaceWithClassIds( 8543 &visitor_adapter); 8544 } 8545 8546 8547 MicrotasksScope::MicrotasksScope(Isolate* isolate, MicrotasksScope::Type type) 8548 : isolate_(reinterpret_cast<i::Isolate*>(isolate)), 8549 run_(type == MicrotasksScope::kRunMicrotasks) { 8550 auto handle_scope_implementer = isolate_->handle_scope_implementer(); 8551 if (run_) handle_scope_implementer->IncrementMicrotasksScopeDepth(); 8552 #ifdef DEBUG 8553 if (!run_) handle_scope_implementer->IncrementDebugMicrotasksScopeDepth(); 8554 #endif 8555 } 8556 8557 8558 MicrotasksScope::~MicrotasksScope() { 8559 auto handle_scope_implementer = isolate_->handle_scope_implementer(); 8560 if (run_) { 8561 handle_scope_implementer->DecrementMicrotasksScopeDepth(); 8562 if (MicrotasksPolicy::kScoped == 8563 handle_scope_implementer->microtasks_policy()) { 8564 PerformCheckpoint(reinterpret_cast<Isolate*>(isolate_)); 8565 } 8566 } 8567 #ifdef DEBUG 8568 if (!run_) handle_scope_implementer->DecrementDebugMicrotasksScopeDepth(); 8569 #endif 8570 } 8571 8572 8573 void MicrotasksScope::PerformCheckpoint(Isolate* v8Isolate) { 8574 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate); 8575 if (IsExecutionTerminatingCheck(isolate)) return; 8576 auto handle_scope_implementer = isolate->handle_scope_implementer(); 8577 if (!handle_scope_implementer->GetMicrotasksScopeDepth() && 8578 !handle_scope_implementer->HasMicrotasksSuppressions()) { 8579 isolate->RunMicrotasks(); 8580 } 8581 } 8582 8583 8584 int MicrotasksScope::GetCurrentDepth(Isolate* v8Isolate) { 8585 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate); 8586 return isolate->handle_scope_implementer()->GetMicrotasksScopeDepth(); 8587 } 8588 8589 bool MicrotasksScope::IsRunningMicrotasks(Isolate* v8Isolate) { 8590 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8Isolate); 8591 return isolate->IsRunningMicrotasks(); 8592 } 8593 8594 String::Utf8Value::Utf8Value(v8::Local<v8::Value> obj) 8595 : str_(NULL), length_(0) { 8596 if (obj.IsEmpty()) return; 8597 i::Isolate* isolate = i::Isolate::Current(); 8598 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate); 8599 ENTER_V8(isolate); 8600 i::HandleScope scope(isolate); 8601 Local<Context> context = v8_isolate->GetCurrentContext(); 8602 TryCatch try_catch(v8_isolate); 8603 Local<String> str; 8604 if (!obj->ToString(context).ToLocal(&str)) return; 8605 i::Handle<i::String> i_str = Utils::OpenHandle(*str); 8606 length_ = v8::Utf8Length(*i_str, isolate); 8607 str_ = i::NewArray<char>(length_ + 1); 8608 str->WriteUtf8(str_); 8609 } 8610 8611 8612 String::Utf8Value::~Utf8Value() { 8613 i::DeleteArray(str_); 8614 } 8615 8616 8617 String::Value::Value(v8::Local<v8::Value> obj) : str_(NULL), length_(0) { 8618 if (obj.IsEmpty()) return; 8619 i::Isolate* isolate = i::Isolate::Current(); 8620 Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate); 8621 ENTER_V8(isolate); 8622 i::HandleScope scope(isolate); 8623 Local<Context> context = v8_isolate->GetCurrentContext(); 8624 TryCatch try_catch(v8_isolate); 8625 Local<String> str; 8626 if (!obj->ToString(context).ToLocal(&str)) return; 8627 length_ = str->Length(); 8628 str_ = i::NewArray<uint16_t>(length_ + 1); 8629 str->Write(str_); 8630 } 8631 8632 8633 String::Value::~Value() { 8634 i::DeleteArray(str_); 8635 } 8636 8637 #define DEFINE_ERROR(NAME, name) \ 8638 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message) { \ 8639 i::Isolate* isolate = i::Isolate::Current(); \ 8640 LOG_API(isolate, NAME, New); \ 8641 ENTER_V8(isolate); \ 8642 i::Object* error; \ 8643 { \ 8644 i::HandleScope scope(isolate); \ 8645 i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \ 8646 i::Handle<i::JSFunction> constructor = isolate->name##_function(); \ 8647 error = *isolate->factory()->NewError(constructor, message); \ 8648 } \ 8649 i::Handle<i::Object> result(error, isolate); \ 8650 return Utils::ToLocal(result); \ 8651 } 8652 8653 DEFINE_ERROR(RangeError, range_error) 8654 DEFINE_ERROR(ReferenceError, reference_error) 8655 DEFINE_ERROR(SyntaxError, syntax_error) 8656 DEFINE_ERROR(TypeError, type_error) 8657 DEFINE_ERROR(Error, error) 8658 8659 #undef DEFINE_ERROR 8660 8661 8662 Local<Message> Exception::CreateMessage(Isolate* isolate, 8663 Local<Value> exception) { 8664 i::Handle<i::Object> obj = Utils::OpenHandle(*exception); 8665 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8666 ENTER_V8(i_isolate); 8667 i::HandleScope scope(i_isolate); 8668 return Utils::MessageToLocal( 8669 scope.CloseAndEscape(i_isolate->CreateMessage(obj, NULL))); 8670 } 8671 8672 8673 Local<Message> Exception::CreateMessage(Local<Value> exception) { 8674 i::Handle<i::Object> obj = Utils::OpenHandle(*exception); 8675 if (!obj->IsHeapObject()) return Local<Message>(); 8676 i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); 8677 return CreateMessage(reinterpret_cast<Isolate*>(isolate), exception); 8678 } 8679 8680 8681 Local<StackTrace> Exception::GetStackTrace(Local<Value> exception) { 8682 i::Handle<i::Object> obj = Utils::OpenHandle(*exception); 8683 if (!obj->IsJSObject()) return Local<StackTrace>(); 8684 i::Handle<i::JSObject> js_obj = i::Handle<i::JSObject>::cast(obj); 8685 i::Isolate* isolate = js_obj->GetIsolate(); 8686 ENTER_V8(isolate); 8687 return Utils::StackTraceToLocal(isolate->GetDetailedStackTrace(js_obj)); 8688 } 8689 8690 8691 // --- D e b u g S u p p o r t --- 8692 8693 bool Debug::SetDebugEventListener(Isolate* isolate, EventCallback that, 8694 Local<Value> data) { 8695 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8696 ENTER_V8(i_isolate); 8697 i::HandleScope scope(i_isolate); 8698 i::Handle<i::Object> foreign = i_isolate->factory()->undefined_value(); 8699 if (that != NULL) { 8700 foreign = i_isolate->factory()->NewForeign(FUNCTION_ADDR(that)); 8701 } 8702 i_isolate->debug()->SetEventListener(foreign, Utils::OpenHandle(*data, true)); 8703 return true; 8704 } 8705 8706 8707 void Debug::DebugBreak(Isolate* isolate) { 8708 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak(); 8709 } 8710 8711 8712 void Debug::CancelDebugBreak(Isolate* isolate) { 8713 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8714 internal_isolate->stack_guard()->ClearDebugBreak(); 8715 } 8716 8717 8718 bool Debug::CheckDebugBreak(Isolate* isolate) { 8719 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8720 return internal_isolate->stack_guard()->CheckDebugBreak(); 8721 } 8722 8723 8724 void Debug::SetMessageHandler(Isolate* isolate, 8725 v8::Debug::MessageHandler handler) { 8726 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8727 ENTER_V8(i_isolate); 8728 i_isolate->debug()->SetMessageHandler(handler); 8729 } 8730 8731 8732 void Debug::SendCommand(Isolate* isolate, 8733 const uint16_t* command, 8734 int length, 8735 ClientData* client_data) { 8736 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8737 internal_isolate->debug()->EnqueueCommandMessage( 8738 i::Vector<const uint16_t>(command, length), client_data); 8739 } 8740 8741 8742 MaybeLocal<Value> Debug::Call(Local<Context> context, 8743 v8::Local<v8::Function> fun, 8744 v8::Local<v8::Value> data) { 8745 PREPARE_FOR_EXECUTION(context, Debug, Call, Value); 8746 i::Handle<i::Object> data_obj; 8747 if (data.IsEmpty()) { 8748 data_obj = isolate->factory()->undefined_value(); 8749 } else { 8750 data_obj = Utils::OpenHandle(*data); 8751 } 8752 Local<Value> result; 8753 has_pending_exception = 8754 !ToLocal<Value>(isolate->debug()->Call(Utils::OpenHandle(*fun), data_obj), 8755 &result); 8756 RETURN_ON_FAILED_EXECUTION(Value); 8757 RETURN_ESCAPED(result); 8758 } 8759 8760 8761 MaybeLocal<Value> Debug::GetMirror(Local<Context> context, 8762 v8::Local<v8::Value> obj) { 8763 PREPARE_FOR_EXECUTION(context, Debug, GetMirror, Value); 8764 i::Debug* isolate_debug = isolate->debug(); 8765 has_pending_exception = !isolate_debug->Load(); 8766 RETURN_ON_FAILED_EXECUTION(Value); 8767 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global_object()); 8768 auto name = isolate->factory()->NewStringFromStaticChars("MakeMirror"); 8769 auto fun_obj = i::JSReceiver::GetProperty(debug, name).ToHandleChecked(); 8770 auto v8_fun = Utils::CallableToLocal(i::Handle<i::JSFunction>::cast(fun_obj)); 8771 const int kArgc = 1; 8772 v8::Local<v8::Value> argv[kArgc] = {obj}; 8773 Local<Value> result; 8774 has_pending_exception = 8775 !v8_fun->Call(context, Utils::ToLocal(debug), kArgc, argv) 8776 .ToLocal(&result); 8777 RETURN_ON_FAILED_EXECUTION(Value); 8778 RETURN_ESCAPED(result); 8779 } 8780 8781 8782 void Debug::ProcessDebugMessages(Isolate* isolate) { 8783 reinterpret_cast<i::Isolate*>(isolate)->debug()->ProcessDebugMessages(true); 8784 } 8785 8786 8787 Local<Context> Debug::GetDebugContext(Isolate* isolate) { 8788 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8789 ENTER_V8(i_isolate); 8790 return Utils::ToLocal(i_isolate->debug()->GetDebugContext()); 8791 } 8792 8793 8794 MaybeLocal<Context> Debug::GetDebuggedContext(Isolate* isolate) { 8795 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8796 ENTER_V8(i_isolate); 8797 if (!i_isolate->debug()->in_debug_scope()) return MaybeLocal<Context>(); 8798 i::Handle<i::Object> calling = i_isolate->GetCallingNativeContext(); 8799 if (calling.is_null()) return MaybeLocal<Context>(); 8800 return Utils::ToLocal(i::Handle<i::Context>::cast(calling)); 8801 } 8802 8803 void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) { 8804 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8805 internal_isolate->debug()->set_live_edit_enabled(enable); 8806 } 8807 8808 bool Debug::IsTailCallEliminationEnabled(Isolate* isolate) { 8809 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8810 return internal_isolate->is_tail_call_elimination_enabled(); 8811 } 8812 8813 void Debug::SetTailCallEliminationEnabled(Isolate* isolate, bool enabled) { 8814 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8815 internal_isolate->SetTailCallEliminationEnabled(enabled); 8816 } 8817 8818 MaybeLocal<Array> Debug::GetInternalProperties(Isolate* v8_isolate, 8819 Local<Value> value) { 8820 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 8821 ENTER_V8(isolate); 8822 i::Handle<i::Object> val = Utils::OpenHandle(*value); 8823 i::Handle<i::JSArray> result; 8824 if (!i::Runtime::GetInternalProperties(isolate, val).ToHandle(&result)) 8825 return MaybeLocal<Array>(); 8826 return Utils::ToLocal(result); 8827 } 8828 8829 bool DebugInterface::SetDebugEventListener(Isolate* isolate, 8830 DebugInterface::EventCallback that, 8831 Local<Value> data) { 8832 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 8833 ENTER_V8(i_isolate); 8834 i::HandleScope scope(i_isolate); 8835 i::Handle<i::Object> foreign = i_isolate->factory()->undefined_value(); 8836 if (that != NULL) { 8837 foreign = i_isolate->factory()->NewForeign(FUNCTION_ADDR(that)); 8838 } 8839 i_isolate->debug()->SetEventListener(foreign, Utils::OpenHandle(*data, true)); 8840 return true; 8841 } 8842 8843 Local<Context> DebugInterface::GetDebugContext(Isolate* isolate) { 8844 return Debug::GetDebugContext(isolate); 8845 } 8846 8847 MaybeLocal<Value> DebugInterface::Call(Local<Context> context, 8848 v8::Local<v8::Function> fun, 8849 v8::Local<v8::Value> data) { 8850 return Debug::Call(context, fun, data); 8851 } 8852 8853 void DebugInterface::SetLiveEditEnabled(Isolate* isolate, bool enable) { 8854 Debug::SetLiveEditEnabled(isolate, enable); 8855 } 8856 8857 void DebugInterface::DebugBreak(Isolate* isolate) { 8858 Debug::DebugBreak(isolate); 8859 } 8860 8861 void DebugInterface::CancelDebugBreak(Isolate* isolate) { 8862 Debug::CancelDebugBreak(isolate); 8863 } 8864 8865 MaybeLocal<Array> DebugInterface::GetInternalProperties(Isolate* isolate, 8866 Local<Value> value) { 8867 return Debug::GetInternalProperties(isolate, value); 8868 } 8869 8870 void DebugInterface::ChangeBreakOnException(Isolate* isolate, 8871 ExceptionBreakState type) { 8872 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate); 8873 internal_isolate->debug()->ChangeBreakOnException( 8874 i::BreakException, type == BreakOnAnyException); 8875 internal_isolate->debug()->ChangeBreakOnException(i::BreakUncaughtException, 8876 type != NoBreakOnException); 8877 } 8878 8879 void DebugInterface::PrepareStep(Isolate* v8_isolate, StepAction action) { 8880 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 8881 ENTER_V8(isolate); 8882 CHECK(isolate->debug()->CheckExecutionState()); 8883 // Clear all current stepping setup. 8884 isolate->debug()->ClearStepping(); 8885 // Prepare step. 8886 isolate->debug()->PrepareStep(static_cast<i::StepAction>(action)); 8887 } 8888 8889 void DebugInterface::ClearStepping(Isolate* v8_isolate) { 8890 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 8891 ENTER_V8(isolate); 8892 // Clear all current stepping setup. 8893 isolate->debug()->ClearStepping(); 8894 } 8895 8896 v8::Isolate* DebugInterface::Script::GetIsolate() const { 8897 return reinterpret_cast<v8::Isolate*>(Utils::OpenHandle(this)->GetIsolate()); 8898 } 8899 8900 ScriptOriginOptions DebugInterface::Script::OriginOptions() const { 8901 return Utils::OpenHandle(this)->origin_options(); 8902 } 8903 8904 bool DebugInterface::Script::WasCompiled() const { 8905 return Utils::OpenHandle(this)->compilation_state() == 8906 i::Script::COMPILATION_STATE_COMPILED; 8907 } 8908 8909 int DebugInterface::Script::Id() const { return Utils::OpenHandle(this)->id(); } 8910 8911 int DebugInterface::Script::LineOffset() const { 8912 return Utils::OpenHandle(this)->line_offset(); 8913 } 8914 8915 int DebugInterface::Script::ColumnOffset() const { 8916 return Utils::OpenHandle(this)->column_offset(); 8917 } 8918 8919 std::vector<int> DebugInterface::Script::LineEnds() const { 8920 i::Handle<i::Script> script = Utils::OpenHandle(this); 8921 i::Isolate* isolate = script->GetIsolate(); 8922 i::HandleScope scope(isolate); 8923 i::Script::InitLineEnds(script); 8924 CHECK(script->line_ends()->IsFixedArray()); 8925 i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends())); 8926 std::vector<int> result(line_ends->length()); 8927 for (int i = 0; i < line_ends->length(); ++i) { 8928 i::Smi* line_end = i::Smi::cast(line_ends->get(i)); 8929 result[i] = line_end->value(); 8930 } 8931 return result; 8932 } 8933 8934 MaybeLocal<String> DebugInterface::Script::Name() const { 8935 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 8936 i::HandleScope handle_scope(isolate); 8937 i::Handle<i::Script> script = Utils::OpenHandle(this); 8938 i::Handle<i::Object> value(script->name(), isolate); 8939 if (!value->IsString()) return MaybeLocal<String>(); 8940 return Utils::ToLocal( 8941 handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value))); 8942 } 8943 8944 MaybeLocal<String> DebugInterface::Script::SourceURL() const { 8945 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 8946 i::HandleScope handle_scope(isolate); 8947 i::Handle<i::Script> script = Utils::OpenHandle(this); 8948 i::Handle<i::Object> value(script->source_url(), isolate); 8949 if (!value->IsString()) return MaybeLocal<String>(); 8950 return Utils::ToLocal( 8951 handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value))); 8952 } 8953 8954 MaybeLocal<String> DebugInterface::Script::SourceMappingURL() const { 8955 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 8956 i::HandleScope handle_scope(isolate); 8957 i::Handle<i::Script> script = Utils::OpenHandle(this); 8958 i::Handle<i::Object> value(script->source_mapping_url(), isolate); 8959 if (!value->IsString()) return MaybeLocal<String>(); 8960 return Utils::ToLocal( 8961 handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value))); 8962 } 8963 8964 MaybeLocal<String> DebugInterface::Script::ContextData() const { 8965 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 8966 i::HandleScope handle_scope(isolate); 8967 i::Handle<i::Script> script = Utils::OpenHandle(this); 8968 i::Handle<i::Object> value(script->context_data(), isolate); 8969 if (!value->IsString()) return MaybeLocal<String>(); 8970 return Utils::ToLocal( 8971 handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value))); 8972 } 8973 8974 MaybeLocal<String> DebugInterface::Script::Source() const { 8975 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate(); 8976 i::HandleScope handle_scope(isolate); 8977 i::Handle<i::Script> script = Utils::OpenHandle(this); 8978 i::Handle<i::Object> value(script->source(), isolate); 8979 if (!value->IsString()) return MaybeLocal<String>(); 8980 return Utils::ToLocal( 8981 handle_scope.CloseAndEscape(i::Handle<i::String>::cast(value))); 8982 } 8983 8984 namespace { 8985 int GetSmiValue(i::Handle<i::FixedArray> array, int index) { 8986 return i::Smi::cast(array->get(index))->value(); 8987 } 8988 } // namespace 8989 8990 bool DebugInterface::Script::GetPossibleBreakpoints( 8991 const Location& start, const Location& end, 8992 std::vector<Location>* locations) const { 8993 CHECK(!start.IsEmpty()); 8994 i::Handle<i::Script> script = Utils::OpenHandle(this); 8995 8996 i::Script::InitLineEnds(script); 8997 CHECK(script->line_ends()->IsFixedArray()); 8998 i::Isolate* isolate = script->GetIsolate(); 8999 i::Handle<i::FixedArray> line_ends = 9000 i::Handle<i::FixedArray>::cast(i::handle(script->line_ends(), isolate)); 9001 CHECK(line_ends->length()); 9002 9003 int start_offset = GetSourcePosition(start); 9004 int end_offset; 9005 if (end.IsEmpty()) { 9006 end_offset = GetSmiValue(line_ends, line_ends->length() - 1) + 1; 9007 } else { 9008 end_offset = GetSourcePosition(end); 9009 } 9010 if (start_offset >= end_offset) return true; 9011 9012 std::set<int> offsets; 9013 if (!isolate->debug()->GetPossibleBreakpoints(script, start_offset, 9014 end_offset, &offsets)) { 9015 return false; 9016 } 9017 9018 int current_line_end_index = 0; 9019 for (const auto& it : offsets) { 9020 int offset = it; 9021 while (offset > GetSmiValue(line_ends, current_line_end_index)) { 9022 ++current_line_end_index; 9023 CHECK(current_line_end_index < line_ends->length()); 9024 } 9025 int line_offset = 0; 9026 9027 if (current_line_end_index > 0) { 9028 line_offset = GetSmiValue(line_ends, current_line_end_index - 1) + 1; 9029 } 9030 locations->push_back(Location( 9031 current_line_end_index + script->line_offset(), 9032 offset - line_offset + 9033 (current_line_end_index == 0 ? script->column_offset() : 0))); 9034 } 9035 return true; 9036 } 9037 9038 int DebugInterface::Script::GetSourcePosition(const Location& location) const { 9039 i::Handle<i::Script> script = Utils::OpenHandle(this); 9040 9041 int line = std::max(location.GetLineNumber() - script->line_offset(), 0); 9042 int column = location.GetColumnNumber(); 9043 if (line == 0) { 9044 column = std::max(0, column - script->column_offset()); 9045 } 9046 9047 i::Script::InitLineEnds(script); 9048 CHECK(script->line_ends()->IsFixedArray()); 9049 i::Handle<i::FixedArray> line_ends = i::Handle<i::FixedArray>::cast( 9050 i::handle(script->line_ends(), script->GetIsolate())); 9051 CHECK(line_ends->length()); 9052 if (line >= line_ends->length()) 9053 return GetSmiValue(line_ends, line_ends->length() - 1); 9054 int line_offset = GetSmiValue(line_ends, line); 9055 if (line == 0) return std::min(column, line_offset); 9056 int prev_line_offset = GetSmiValue(line_ends, line - 1); 9057 return std::min(prev_line_offset + column + 1, line_offset); 9058 } 9059 9060 MaybeLocal<DebugInterface::Script> DebugInterface::Script::Wrap( 9061 v8::Isolate* v8_isolate, v8::Local<v8::Object> script) { 9062 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 9063 ENTER_V8(isolate); 9064 i::HandleScope handle_scope(isolate); 9065 i::Handle<i::JSReceiver> script_receiver(Utils::OpenHandle(*script)); 9066 if (!script_receiver->IsJSValue()) return MaybeLocal<Script>(); 9067 i::Handle<i::Object> script_value( 9068 i::Handle<i::JSValue>::cast(script_receiver)->value(), isolate); 9069 if (!script_value->IsScript()) { 9070 return MaybeLocal<Script>(); 9071 } 9072 i::Handle<i::Script> script_obj = i::Handle<i::Script>::cast(script_value); 9073 if (script_obj->type() != i::Script::TYPE_NORMAL) return MaybeLocal<Script>(); 9074 return ToApiHandle<DebugInterface::Script>( 9075 handle_scope.CloseAndEscape(script_obj)); 9076 } 9077 9078 DebugInterface::Location::Location(int lineNumber, int columnNumber) 9079 : lineNumber_(lineNumber), columnNumber_(columnNumber) { 9080 CHECK(lineNumber >= 0); 9081 CHECK(columnNumber >= 0); 9082 } 9083 9084 DebugInterface::Location::Location() : lineNumber_(-1), columnNumber_(-1) {} 9085 9086 int DebugInterface::Location::GetLineNumber() const { 9087 CHECK(lineNumber_ >= 0); 9088 return lineNumber_; 9089 } 9090 9091 int DebugInterface::Location::GetColumnNumber() const { 9092 CHECK(columnNumber_ >= 0); 9093 return columnNumber_; 9094 } 9095 9096 bool DebugInterface::Location::IsEmpty() const { 9097 return lineNumber_ == -1 && columnNumber_ == -1; 9098 } 9099 9100 void DebugInterface::GetLoadedScripts( 9101 v8::Isolate* v8_isolate, 9102 PersistentValueVector<DebugInterface::Script>& scripts) { 9103 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate); 9104 ENTER_V8(isolate); 9105 // TODO(kozyatinskiy): remove this GC once tests are dealt with. 9106 isolate->heap()->CollectAllGarbage(i::Heap::kFinalizeIncrementalMarkingMask, 9107 i::GarbageCollectionReason::kDebugger); 9108 { 9109 i::DisallowHeapAllocation no_gc; 9110 i::Script::Iterator iterator(isolate); 9111 i::Script* script; 9112 while ((script = iterator.Next())) { 9113 if (script->type() != i::Script::TYPE_NORMAL) continue; 9114 if (script->HasValidSource()) { 9115 i::HandleScope handle_scope(isolate); 9116 i::Handle<i::Script> script_handle(script, isolate); 9117 scripts.Append(ToApiHandle<Script>(script_handle)); 9118 } 9119 } 9120 } 9121 } 9122 9123 Local<String> CpuProfileNode::GetFunctionName() const { 9124 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9125 i::Isolate* isolate = node->isolate(); 9126 const i::CodeEntry* entry = node->entry(); 9127 i::Handle<i::String> name = 9128 isolate->factory()->InternalizeUtf8String(entry->name()); 9129 if (!entry->has_name_prefix()) { 9130 return ToApiHandle<String>(name); 9131 } else { 9132 // We do not expect this to fail. Change this if it does. 9133 i::Handle<i::String> cons = isolate->factory()->NewConsString( 9134 isolate->factory()->InternalizeUtf8String(entry->name_prefix()), 9135 name).ToHandleChecked(); 9136 return ToApiHandle<String>(cons); 9137 } 9138 } 9139 9140 const char* CpuProfileNode::GetFunctionNameStr() const { 9141 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9142 return node->entry()->name(); 9143 } 9144 9145 int CpuProfileNode::GetScriptId() const { 9146 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9147 const i::CodeEntry* entry = node->entry(); 9148 return entry->script_id(); 9149 } 9150 9151 Local<String> CpuProfileNode::GetScriptResourceName() const { 9152 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9153 i::Isolate* isolate = node->isolate(); 9154 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String( 9155 node->entry()->resource_name())); 9156 } 9157 9158 const char* CpuProfileNode::GetScriptResourceNameStr() const { 9159 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9160 return node->entry()->resource_name(); 9161 } 9162 9163 int CpuProfileNode::GetLineNumber() const { 9164 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number(); 9165 } 9166 9167 9168 int CpuProfileNode::GetColumnNumber() const { 9169 return reinterpret_cast<const i::ProfileNode*>(this)-> 9170 entry()->column_number(); 9171 } 9172 9173 9174 unsigned int CpuProfileNode::GetHitLineCount() const { 9175 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9176 return node->GetHitLineCount(); 9177 } 9178 9179 9180 bool CpuProfileNode::GetLineTicks(LineTick* entries, 9181 unsigned int length) const { 9182 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9183 return node->GetLineTicks(entries, length); 9184 } 9185 9186 9187 const char* CpuProfileNode::GetBailoutReason() const { 9188 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9189 return node->entry()->bailout_reason(); 9190 } 9191 9192 9193 unsigned CpuProfileNode::GetHitCount() const { 9194 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks(); 9195 } 9196 9197 9198 unsigned CpuProfileNode::GetCallUid() const { 9199 return reinterpret_cast<const i::ProfileNode*>(this)->function_id(); 9200 } 9201 9202 9203 unsigned CpuProfileNode::GetNodeId() const { 9204 return reinterpret_cast<const i::ProfileNode*>(this)->id(); 9205 } 9206 9207 9208 int CpuProfileNode::GetChildrenCount() const { 9209 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length(); 9210 } 9211 9212 9213 const CpuProfileNode* CpuProfileNode::GetChild(int index) const { 9214 const i::ProfileNode* child = 9215 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index); 9216 return reinterpret_cast<const CpuProfileNode*>(child); 9217 } 9218 9219 9220 const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const { 9221 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this); 9222 return node->deopt_infos(); 9223 } 9224 9225 9226 void CpuProfile::Delete() { 9227 i::CpuProfile* profile = reinterpret_cast<i::CpuProfile*>(this); 9228 i::CpuProfiler* profiler = profile->cpu_profiler(); 9229 DCHECK(profiler != nullptr); 9230 profiler->DeleteProfile(profile); 9231 } 9232 9233 9234 Local<String> CpuProfile::GetTitle() const { 9235 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9236 i::Isolate* isolate = profile->top_down()->isolate(); 9237 return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String( 9238 profile->title())); 9239 } 9240 9241 9242 const CpuProfileNode* CpuProfile::GetTopDownRoot() const { 9243 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9244 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root()); 9245 } 9246 9247 9248 const CpuProfileNode* CpuProfile::GetSample(int index) const { 9249 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9250 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index)); 9251 } 9252 9253 9254 int64_t CpuProfile::GetSampleTimestamp(int index) const { 9255 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9256 return (profile->sample_timestamp(index) - base::TimeTicks()) 9257 .InMicroseconds(); 9258 } 9259 9260 9261 int64_t CpuProfile::GetStartTime() const { 9262 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9263 return (profile->start_time() - base::TimeTicks()).InMicroseconds(); 9264 } 9265 9266 9267 int64_t CpuProfile::GetEndTime() const { 9268 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this); 9269 return (profile->end_time() - base::TimeTicks()).InMicroseconds(); 9270 } 9271 9272 9273 int CpuProfile::GetSamplesCount() const { 9274 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count(); 9275 } 9276 9277 CpuProfiler* CpuProfiler::New(Isolate* isolate) { 9278 return reinterpret_cast<CpuProfiler*>( 9279 new i::CpuProfiler(reinterpret_cast<i::Isolate*>(isolate))); 9280 } 9281 9282 void CpuProfiler::Dispose() { delete reinterpret_cast<i::CpuProfiler*>(this); } 9283 9284 void CpuProfiler::SetSamplingInterval(int us) { 9285 DCHECK_GE(us, 0); 9286 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval( 9287 base::TimeDelta::FromMicroseconds(us)); 9288 } 9289 9290 void CpuProfiler::CollectSample() { 9291 reinterpret_cast<i::CpuProfiler*>(this)->CollectSample(); 9292 } 9293 9294 void CpuProfiler::StartProfiling(Local<String> title, bool record_samples) { 9295 reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling( 9296 *Utils::OpenHandle(*title), record_samples); 9297 } 9298 9299 9300 CpuProfile* CpuProfiler::StopProfiling(Local<String> title) { 9301 return reinterpret_cast<CpuProfile*>( 9302 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling( 9303 *Utils::OpenHandle(*title))); 9304 } 9305 9306 9307 void CpuProfiler::SetIdle(bool is_idle) { 9308 i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(this); 9309 i::Isolate* isolate = profiler->isolate(); 9310 if (!isolate->is_profiling()) return; 9311 v8::StateTag state = isolate->current_vm_state(); 9312 DCHECK(state == v8::EXTERNAL || state == v8::IDLE); 9313 if (isolate->js_entry_sp() != NULL) return; 9314 if (is_idle) { 9315 isolate->set_current_vm_state(v8::IDLE); 9316 } else if (state == v8::IDLE) { 9317 isolate->set_current_vm_state(v8::EXTERNAL); 9318 } 9319 } 9320 9321 9322 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) { 9323 return const_cast<i::HeapGraphEdge*>( 9324 reinterpret_cast<const i::HeapGraphEdge*>(edge)); 9325 } 9326 9327 9328 HeapGraphEdge::Type HeapGraphEdge::GetType() const { 9329 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type()); 9330 } 9331 9332 9333 Local<Value> HeapGraphEdge::GetName() const { 9334 i::HeapGraphEdge* edge = ToInternal(this); 9335 i::Isolate* isolate = edge->isolate(); 9336 switch (edge->type()) { 9337 case i::HeapGraphEdge::kContextVariable: 9338 case i::HeapGraphEdge::kInternal: 9339 case i::HeapGraphEdge::kProperty: 9340 case i::HeapGraphEdge::kShortcut: 9341 case i::HeapGraphEdge::kWeak: 9342 return ToApiHandle<String>( 9343 isolate->factory()->InternalizeUtf8String(edge->name())); 9344 case i::HeapGraphEdge::kElement: 9345 case i::HeapGraphEdge::kHidden: 9346 return ToApiHandle<Number>( 9347 isolate->factory()->NewNumberFromInt(edge->index())); 9348 default: UNREACHABLE(); 9349 } 9350 return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate)); 9351 } 9352 9353 9354 const HeapGraphNode* HeapGraphEdge::GetFromNode() const { 9355 const i::HeapEntry* from = ToInternal(this)->from(); 9356 return reinterpret_cast<const HeapGraphNode*>(from); 9357 } 9358 9359 9360 const HeapGraphNode* HeapGraphEdge::GetToNode() const { 9361 const i::HeapEntry* to = ToInternal(this)->to(); 9362 return reinterpret_cast<const HeapGraphNode*>(to); 9363 } 9364 9365 9366 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) { 9367 return const_cast<i::HeapEntry*>( 9368 reinterpret_cast<const i::HeapEntry*>(entry)); 9369 } 9370 9371 9372 HeapGraphNode::Type HeapGraphNode::GetType() const { 9373 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type()); 9374 } 9375 9376 9377 Local<String> HeapGraphNode::GetName() const { 9378 i::Isolate* isolate = ToInternal(this)->isolate(); 9379 return ToApiHandle<String>( 9380 isolate->factory()->InternalizeUtf8String(ToInternal(this)->name())); 9381 } 9382 9383 9384 SnapshotObjectId HeapGraphNode::GetId() const { 9385 return ToInternal(this)->id(); 9386 } 9387 9388 9389 size_t HeapGraphNode::GetShallowSize() const { 9390 return ToInternal(this)->self_size(); 9391 } 9392 9393 9394 int HeapGraphNode::GetChildrenCount() const { 9395 return ToInternal(this)->children().length(); 9396 } 9397 9398 9399 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const { 9400 return reinterpret_cast<const HeapGraphEdge*>( 9401 ToInternal(this)->children()[index]); 9402 } 9403 9404 9405 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) { 9406 return const_cast<i::HeapSnapshot*>( 9407 reinterpret_cast<const i::HeapSnapshot*>(snapshot)); 9408 } 9409 9410 9411 void HeapSnapshot::Delete() { 9412 i::Isolate* isolate = ToInternal(this)->profiler()->isolate(); 9413 if (isolate->heap_profiler()->GetSnapshotsCount() > 1) { 9414 ToInternal(this)->Delete(); 9415 } else { 9416 // If this is the last snapshot, clean up all accessory data as well. 9417 isolate->heap_profiler()->DeleteAllSnapshots(); 9418 } 9419 } 9420 9421 9422 const HeapGraphNode* HeapSnapshot::GetRoot() const { 9423 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root()); 9424 } 9425 9426 9427 const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const { 9428 return reinterpret_cast<const HeapGraphNode*>( 9429 ToInternal(this)->GetEntryById(id)); 9430 } 9431 9432 9433 int HeapSnapshot::GetNodesCount() const { 9434 return ToInternal(this)->entries().length(); 9435 } 9436 9437 9438 const HeapGraphNode* HeapSnapshot::GetNode(int index) const { 9439 return reinterpret_cast<const HeapGraphNode*>( 9440 &ToInternal(this)->entries().at(index)); 9441 } 9442 9443 9444 SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const { 9445 return ToInternal(this)->max_snapshot_js_object_id(); 9446 } 9447 9448 9449 void HeapSnapshot::Serialize(OutputStream* stream, 9450 HeapSnapshot::SerializationFormat format) const { 9451 Utils::ApiCheck(format == kJSON, 9452 "v8::HeapSnapshot::Serialize", 9453 "Unknown serialization format"); 9454 Utils::ApiCheck(stream->GetChunkSize() > 0, 9455 "v8::HeapSnapshot::Serialize", 9456 "Invalid stream chunk size"); 9457 i::HeapSnapshotJSONSerializer serializer(ToInternal(this)); 9458 serializer.Serialize(stream); 9459 } 9460 9461 9462 // static 9463 STATIC_CONST_MEMBER_DEFINITION const SnapshotObjectId 9464 HeapProfiler::kUnknownObjectId; 9465 9466 9467 int HeapProfiler::GetSnapshotCount() { 9468 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount(); 9469 } 9470 9471 9472 const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) { 9473 return reinterpret_cast<const HeapSnapshot*>( 9474 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index)); 9475 } 9476 9477 9478 SnapshotObjectId HeapProfiler::GetObjectId(Local<Value> value) { 9479 i::Handle<i::Object> obj = Utils::OpenHandle(*value); 9480 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj); 9481 } 9482 9483 9484 Local<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) { 9485 i::Handle<i::Object> obj = 9486 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id); 9487 if (obj.is_null()) return Local<Value>(); 9488 return Utils::ToLocal(obj); 9489 } 9490 9491 9492 void HeapProfiler::ClearObjectIds() { 9493 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap(); 9494 } 9495 9496 9497 const HeapSnapshot* HeapProfiler::TakeHeapSnapshot( 9498 ActivityControl* control, ObjectNameResolver* resolver) { 9499 return reinterpret_cast<const HeapSnapshot*>( 9500 reinterpret_cast<i::HeapProfiler*>(this) 9501 ->TakeSnapshot(control, resolver)); 9502 } 9503 9504 9505 void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) { 9506 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking( 9507 track_allocations); 9508 } 9509 9510 9511 void HeapProfiler::StopTrackingHeapObjects() { 9512 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking(); 9513 } 9514 9515 9516 SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream, 9517 int64_t* timestamp_us) { 9518 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this); 9519 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us); 9520 } 9521 9522 bool HeapProfiler::StartSamplingHeapProfiler(uint64_t sample_interval, 9523 int stack_depth, 9524 SamplingFlags flags) { 9525 return reinterpret_cast<i::HeapProfiler*>(this)->StartSamplingHeapProfiler( 9526 sample_interval, stack_depth, flags); 9527 } 9528 9529 9530 void HeapProfiler::StopSamplingHeapProfiler() { 9531 reinterpret_cast<i::HeapProfiler*>(this)->StopSamplingHeapProfiler(); 9532 } 9533 9534 9535 AllocationProfile* HeapProfiler::GetAllocationProfile() { 9536 return reinterpret_cast<i::HeapProfiler*>(this)->GetAllocationProfile(); 9537 } 9538 9539 9540 void HeapProfiler::DeleteAllHeapSnapshots() { 9541 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots(); 9542 } 9543 9544 9545 void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id, 9546 WrapperInfoCallback callback) { 9547 reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id, 9548 callback); 9549 } 9550 9551 9552 size_t HeapProfiler::GetProfilerMemorySize() { 9553 return reinterpret_cast<i::HeapProfiler*>(this)-> 9554 GetMemorySizeUsedByProfiler(); 9555 } 9556 9557 9558 void HeapProfiler::SetRetainedObjectInfo(UniqueId id, 9559 RetainedObjectInfo* info) { 9560 reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info); 9561 } 9562 9563 9564 v8::Testing::StressType internal::Testing::stress_type_ = 9565 v8::Testing::kStressTypeOpt; 9566 9567 9568 void Testing::SetStressRunType(Testing::StressType type) { 9569 internal::Testing::set_stress_type(type); 9570 } 9571 9572 9573 int Testing::GetStressRuns() { 9574 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs; 9575 #ifdef DEBUG 9576 // In debug mode the code runs much slower so stressing will only make two 9577 // runs. 9578 return 2; 9579 #else 9580 return 5; 9581 #endif 9582 } 9583 9584 9585 static void SetFlagsFromString(const char* flags) { 9586 V8::SetFlagsFromString(flags, i::StrLength(flags)); 9587 } 9588 9589 9590 void Testing::PrepareStressRun(int run) { 9591 static const char* kLazyOptimizations = 9592 "--prepare-always-opt " 9593 "--max-inlined-source-size=999999 " 9594 "--max-inlined-nodes=999999 " 9595 "--max-inlined-nodes-cumulative=999999 " 9596 "--noalways-opt"; 9597 static const char* kForcedOptimizations = "--always-opt"; 9598 9599 // If deoptimization stressed turn on frequent deoptimization. If no value 9600 // is spefified through --deopt-every-n-times use a default default value. 9601 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13"; 9602 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt && 9603 internal::FLAG_deopt_every_n_times == 0) { 9604 SetFlagsFromString(kDeoptEvery13Times); 9605 } 9606 9607 #ifdef DEBUG 9608 // As stressing in debug mode only make two runs skip the deopt stressing 9609 // here. 9610 if (run == GetStressRuns() - 1) { 9611 SetFlagsFromString(kForcedOptimizations); 9612 } else { 9613 SetFlagsFromString(kLazyOptimizations); 9614 } 9615 #else 9616 if (run == GetStressRuns() - 1) { 9617 SetFlagsFromString(kForcedOptimizations); 9618 } else if (run != GetStressRuns() - 2) { 9619 SetFlagsFromString(kLazyOptimizations); 9620 } 9621 #endif 9622 } 9623 9624 9625 void Testing::DeoptimizeAll(Isolate* isolate) { 9626 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); 9627 i::HandleScope scope(i_isolate); 9628 internal::Deoptimizer::DeoptimizeAll(i_isolate); 9629 } 9630 9631 9632 namespace internal { 9633 9634 9635 void HandleScopeImplementer::FreeThreadResources() { 9636 Free(); 9637 } 9638 9639 9640 char* HandleScopeImplementer::ArchiveThread(char* storage) { 9641 HandleScopeData* current = isolate_->handle_scope_data(); 9642 handle_scope_data_ = *current; 9643 MemCopy(storage, this, sizeof(*this)); 9644 9645 ResetAfterArchive(); 9646 current->Initialize(); 9647 9648 return storage + ArchiveSpacePerThread(); 9649 } 9650 9651 9652 int HandleScopeImplementer::ArchiveSpacePerThread() { 9653 return sizeof(HandleScopeImplementer); 9654 } 9655 9656 9657 char* HandleScopeImplementer::RestoreThread(char* storage) { 9658 MemCopy(this, storage, sizeof(*this)); 9659 *isolate_->handle_scope_data() = handle_scope_data_; 9660 return storage + ArchiveSpacePerThread(); 9661 } 9662 9663 9664 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) { 9665 #ifdef DEBUG 9666 bool found_block_before_deferred = false; 9667 #endif 9668 // Iterate over all handles in the blocks except for the last. 9669 for (int i = blocks()->length() - 2; i >= 0; --i) { 9670 Object** block = blocks()->at(i); 9671 if (last_handle_before_deferred_block_ != NULL && 9672 (last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) && 9673 (last_handle_before_deferred_block_ >= block)) { 9674 v->VisitPointers(block, last_handle_before_deferred_block_); 9675 DCHECK(!found_block_before_deferred); 9676 #ifdef DEBUG 9677 found_block_before_deferred = true; 9678 #endif 9679 } else { 9680 v->VisitPointers(block, &block[kHandleBlockSize]); 9681 } 9682 } 9683 9684 DCHECK(last_handle_before_deferred_block_ == NULL || 9685 found_block_before_deferred); 9686 9687 // Iterate over live handles in the last block (if any). 9688 if (!blocks()->is_empty()) { 9689 v->VisitPointers(blocks()->last(), handle_scope_data_.next); 9690 } 9691 9692 List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_}; 9693 for (unsigned i = 0; i < arraysize(context_lists); i++) { 9694 if (context_lists[i]->is_empty()) continue; 9695 Object** start = reinterpret_cast<Object**>(&context_lists[i]->first()); 9696 v->VisitPointers(start, start + context_lists[i]->length()); 9697 } 9698 if (microtask_context_) { 9699 Object** start = reinterpret_cast<Object**>(µtask_context_); 9700 v->VisitPointers(start, start + 1); 9701 } 9702 } 9703 9704 9705 void HandleScopeImplementer::Iterate(ObjectVisitor* v) { 9706 HandleScopeData* current = isolate_->handle_scope_data(); 9707 handle_scope_data_ = *current; 9708 IterateThis(v); 9709 } 9710 9711 9712 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) { 9713 HandleScopeImplementer* scope_implementer = 9714 reinterpret_cast<HandleScopeImplementer*>(storage); 9715 scope_implementer->IterateThis(v); 9716 return storage + ArchiveSpacePerThread(); 9717 } 9718 9719 9720 DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) { 9721 DeferredHandles* deferred = 9722 new DeferredHandles(isolate()->handle_scope_data()->next, isolate()); 9723 9724 while (!blocks_.is_empty()) { 9725 Object** block_start = blocks_.last(); 9726 Object** block_limit = &block_start[kHandleBlockSize]; 9727 // We should not need to check for SealHandleScope here. Assert this. 9728 DCHECK(prev_limit == block_limit || 9729 !(block_start <= prev_limit && prev_limit <= block_limit)); 9730 if (prev_limit == block_limit) break; 9731 deferred->blocks_.Add(blocks_.last()); 9732 blocks_.RemoveLast(); 9733 } 9734 9735 // deferred->blocks_ now contains the blocks installed on the 9736 // HandleScope stack since BeginDeferredScope was called, but in 9737 // reverse order. 9738 9739 DCHECK(prev_limit == NULL || !blocks_.is_empty()); 9740 9741 DCHECK(!blocks_.is_empty() && prev_limit != NULL); 9742 DCHECK(last_handle_before_deferred_block_ != NULL); 9743 last_handle_before_deferred_block_ = NULL; 9744 return deferred; 9745 } 9746 9747 9748 void HandleScopeImplementer::BeginDeferredScope() { 9749 DCHECK(last_handle_before_deferred_block_ == NULL); 9750 last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next; 9751 } 9752 9753 9754 DeferredHandles::~DeferredHandles() { 9755 isolate_->UnlinkDeferredHandles(this); 9756 9757 for (int i = 0; i < blocks_.length(); i++) { 9758 #ifdef ENABLE_HANDLE_ZAPPING 9759 HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]); 9760 #endif 9761 isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]); 9762 } 9763 } 9764 9765 9766 void DeferredHandles::Iterate(ObjectVisitor* v) { 9767 DCHECK(!blocks_.is_empty()); 9768 9769 DCHECK((first_block_limit_ >= blocks_.first()) && 9770 (first_block_limit_ <= &(blocks_.first())[kHandleBlockSize])); 9771 9772 v->VisitPointers(blocks_.first(), first_block_limit_); 9773 9774 for (int i = 1; i < blocks_.length(); i++) { 9775 v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]); 9776 } 9777 } 9778 9779 9780 void InvokeAccessorGetterCallback( 9781 v8::Local<v8::Name> property, 9782 const v8::PropertyCallbackInfo<v8::Value>& info, 9783 v8::AccessorNameGetterCallback getter) { 9784 // Leaving JavaScript. 9785 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate()); 9786 RuntimeCallTimerScope timer(isolate, 9787 &RuntimeCallStats::AccessorGetterCallback); 9788 Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>( 9789 getter)); 9790 VMState<EXTERNAL> state(isolate); 9791 ExternalCallbackScope call_scope(isolate, getter_address); 9792 getter(property, info); 9793 } 9794 9795 9796 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info, 9797 v8::FunctionCallback callback) { 9798 Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate()); 9799 RuntimeCallTimerScope timer(isolate, 9800 &RuntimeCallStats::InvokeFunctionCallback); 9801 Address callback_address = 9802 reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback)); 9803 VMState<EXTERNAL> state(isolate); 9804 ExternalCallbackScope call_scope(isolate, callback_address); 9805 callback(info); 9806 } 9807 9808 9809 } // namespace internal 9810 } // namespace v8 9811