Loading...
Searching...
No Matches
v8-script.h
Go to the documentation of this file.
1// Copyright 2021 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#ifndef INCLUDE_V8_SCRIPT_H_
6#define INCLUDE_V8_SCRIPT_H_
7
8#include <stddef.h>
9#include <stdint.h>
10
11#include <memory>
12#include <tuple>
13#include <vector>
14
15#include "v8-callbacks.h" // NOLINT(build/include_directory)
16#include "v8-data.h" // NOLINT(build/include_directory)
17#include "v8-local-handle.h" // NOLINT(build/include_directory)
18#include "v8-maybe.h" // NOLINT(build/include_directory)
19#include "v8-memory-span.h" // NOLINT(build/include_directory)
20#include "v8-message.h" // NOLINT(build/include_directory)
21#include "v8config.h" // NOLINT(build/include_directory)
22
23namespace v8 {
24
25class Function;
26class Message;
27class Object;
28class PrimitiveArray;
29class Script;
30
31namespace internal {
32class BackgroundDeserializeTask;
33struct ScriptStreamingData;
34} // namespace internal
35
43 public:
49
55};
56
61 public:
66
67 int GetId() const;
69
78
83 int GetLineNumber(int code_pos = 0);
84
89 int GetColumnNumber(int code_pos = 0);
90
91 static const int kNoScriptId = 0;
92};
93
98 public:
107};
108
113 public:
114 int GetLineNumber() { return line_number_; }
115 int GetColumnNumber() { return column_number_; }
116
117 Location(int line_number, int column_number)
118 : line_number_(line_number), column_number_(column_number) {}
119
120 private:
121 int line_number_;
122 int column_number_;
123};
124
126 public:
131
136
141 int GetSourceOffset() const;
142
157
158 V8_DEPRECATED("Use GetImportAttributes instead")
159 Local<FixedArray> GetImportAssertions() const {
160 return GetImportAttributes();
161 }
162
163 V8_INLINE static ModuleRequest* Cast(Data* data);
164
165 private:
166 static void CheckCast(Data* obj);
167};
168
172class V8_EXPORT Module : public Data {
173 public:
181 enum Status {
187 kErrored
188 };
189
194
199
204
210
214 int GetIdentityHash() const;
215
217 Local<Context> context, Local<String> specifier,
218 Local<FixedArray> import_attributes, Local<Module> referrer);
220 Local<Context> context, Local<String> specifier,
221 Local<FixedArray> import_attributes, Local<Module> referrer);
222
231 Local<Context> context, ResolveModuleCallback module_callback,
232 ResolveSourceCallback source_callback = nullptr);
233
245
252
260
266 int ScriptId() const;
267
274 bool IsGraphAsync() const;
275
281 bool HasTopLevelAwait() const;
282
286 bool IsSourceTextModule() const;
287
291 bool IsSyntheticModule() const;
292
293 /*
294 * Callback defined in the embedder. This is responsible for setting
295 * the module's exported values with calls to SetSyntheticModuleExport().
296 * The callback must return a resolved Promise to indicate success (where no
297 * exception was thrown) and return an empy MaybeLocal to indicate falure
298 * (where an exception was thrown).
299 */
302
311 Isolate* isolate, Local<String> module_name,
312 const MemorySpan<const Local<String>>& export_names,
313 SyntheticModuleEvaluationSteps evaluation_steps);
314
323 Isolate* isolate, Local<String> export_name, Local<Value> export_value);
324
332 std::pair<LocalVector<Module>, LocalVector<Message>>
334
335 V8_INLINE static Module* Cast(Data* data);
336
337 private:
338 static void CheckCast(Data* obj);
339};
340
342 public:
346 std::vector<int> GetCompileHints(Isolate* isolate) const;
347};
348
353class V8_EXPORT Script : public Data {
354 public:
359 Local<Context> context, Local<String> source,
360 ScriptOrigin* origin = nullptr);
361
369 Local<Data> host_defined_options);
370
375
381
386 V8_DEPRECATE_SOON("Use GetCompileHintsCollector instead")
387 std::vector<int> GetProducedCompileHints() const;
388
394 Local<CompileHintsCollector> GetCompileHintsCollector() const;
395};
396
398
403 public:
405
414 enum BufferPolicy { BufferNotOwned, BufferOwned };
415
417 : data(nullptr),
418 length(0),
419 rejected(false),
420 buffer_policy(BufferNotOwned) {}
421
422 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
423 // data and guarantees that it stays alive until the CachedData object is
424 // destroyed. If the policy is BufferOwned, the given data will be deleted
425 // (with delete[]) when the CachedData object is destroyed.
426 CachedData(const uint8_t* data, int length,
427 BufferPolicy buffer_policy = BufferNotOwned);
429
431 // Don't change order/existing values of this enum since it keys into the
432 // `code_cache_reject_reason` histogram. Append-only!
434 kMagicNumberMismatch = 1,
435 kVersionMismatch = 2,
436 kSourceMismatch = 3,
437 kFlagsMismatch = 5,
438 kChecksumMismatch = 6,
439 kInvalidHeader = 7,
440 kLengthMismatch = 8,
441 kReadOnlySnapshotChecksumMismatch = 9,
442
443 // This should always point at the last real enum value.
444 kLast = kReadOnlySnapshotChecksumMismatch
445 };
446
447 // Check if the CachedData can be loaded in the given isolate.
449
450 // TODO(marja): Async compilation; add constructors which take a callback
451 // which will be called when V8 no longer needs the data.
452 const uint8_t* data;
456
457 // Prevent copying.
458 CachedData(const CachedData&) = delete;
459 CachedData& operator=(const CachedData&) = delete;
460 };
461
463 // V8 did not attempt to find this script in its in-memory cache.
464 kNotAttempted,
465
466 // V8 found a previously compiled copy of this script in its in-memory
467 // cache. Any data generated by a streaming compilation or background
468 // deserialization was abandoned.
469 kHit,
470
471 // V8 didn't have any previously compiled data for this script.
472 kMiss,
473
474 // V8 had some previously compiled data for an identical script, but the
475 // data was incomplete.
476 kPartial,
477 };
478
479 // Details about what happened during a compilation.
481 InMemoryCacheResult in_memory_cache_result =
482 InMemoryCacheResult::kNotAttempted;
483
484 static constexpr int64_t kTimeNotMeasured = -1;
485 int64_t foreground_time_in_microseconds = kTimeNotMeasured;
486 int64_t background_time_in_microseconds = kTimeNotMeasured;
487 };
488
492 class Source {
493 public:
494 // Source takes ownership of both CachedData and CodeCacheConsumeTask.
495 // The caller *must* ensure that the cached data is from a trusted source.
496 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
497 CachedData* cached_data = nullptr,
498 ConsumeCodeCacheTask* consume_cache_task = nullptr);
499 // Source takes ownership of both CachedData and CodeCacheConsumeTask.
500 V8_INLINE explicit Source(
501 Local<String> source_string, CachedData* cached_data = nullptr,
502 ConsumeCodeCacheTask* consume_cache_task = nullptr);
503 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
504 CompileHintCallback callback, void* callback_data);
505 V8_INLINE ~Source() = default;
506
507 // Ownership of the CachedData or its buffers is *not* transferred to the
508 // caller. The CachedData object is alive as long as the Source object is
509 // alive.
510 V8_INLINE const CachedData* GetCachedData() const;
511
512 V8_INLINE const ScriptOriginOptions& GetResourceOptions() const;
513
514 V8_INLINE const CompilationDetails& GetCompilationDetails() const;
515
516 private:
517 friend class ScriptCompiler;
518
519 Local<String> source_string;
520
521 // Origin information
522 Local<Value> resource_name;
523 int resource_line_offset = -1;
524 int resource_column_offset = -1;
525 ScriptOriginOptions resource_options;
526 Local<Value> source_map_url;
527 Local<Data> host_defined_options;
528
529 // Cached data from previous compilation (if a kConsume*Cache flag is
530 // set), or hold newly generated cache data (kProduce*Cache flags) are
531 // set when calling a compile method.
532 std::unique_ptr<CachedData> cached_data;
533 std::unique_ptr<ConsumeCodeCacheTask> consume_cache_task;
534
535 // For requesting compile hints from the embedder.
536 CompileHintCallback compile_hint_callback = nullptr;
537 void* compile_hint_callback_data = nullptr;
538
539 // V8 writes this data and never reads it. It exists only to be informative
540 // to the embedder.
541 CompilationDetails compilation_details;
542 };
543
549 public:
550 virtual ~ExternalSourceStream() = default;
551
573 virtual size_t GetMoreData(const uint8_t** src) = 0;
574 };
575
583 public:
584 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8, WINDOWS_1252 };
585
586 StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
587 Encoding encoding);
589
590 internal::ScriptStreamingData* impl() const { return impl_.get(); }
591
592 // Prevent copying.
595
596 CompilationDetails& compilation_details() { return compilation_details_; }
597
598 private:
599 std::unique_ptr<internal::ScriptStreamingData> impl_;
600
601 // V8 writes this data and never reads it. It exists only to be informative
602 // to the embedder.
603 CompilationDetails compilation_details_;
604 };
605
611 public:
612 void Run();
613
614 private:
615 friend class ScriptCompiler;
616
617 explicit ScriptStreamingTask(internal::ScriptStreamingData* data)
618 : data_(data) {}
619
620 internal::ScriptStreamingData* data_;
621 };
622
629 public:
631
632 void Run();
633
647 void SourceTextAvailable(Isolate* isolate, Local<String> source_text,
648 const ScriptOrigin& origin);
649
656
663
664 private:
665 friend class ScriptCompiler;
666
667 explicit ConsumeCodeCacheTask(
668 std::unique_ptr<internal::BackgroundDeserializeTask> impl);
669
670 std::unique_ptr<internal::BackgroundDeserializeTask> impl_;
671 };
672
674 kNoCompileOptions = 0,
675 kConsumeCodeCache = 1 << 0,
676 kEagerCompile = 1 << 1,
677 kProduceCompileHints = 1 << 2,
678 kConsumeCompileHints = 1 << 3,
679 kFollowCompileHintsMagicComment = 1 << 4,
680 };
681
682 static inline bool CompileOptionsIsValid(CompileOptions compile_options) {
683 // kConsumeCodeCache is mutually exclusive with all other flag bits.
684 if ((compile_options & kConsumeCodeCache) &&
685 compile_options != kConsumeCodeCache) {
686 return false;
687 }
688 // kEagerCompile is mutually exclusive with all other flag bits.
689 if ((compile_options & kEagerCompile) && compile_options != kEagerCompile) {
690 return false;
691 }
692 // We don't currently support producing and consuming compile hints at the
693 // same time.
694 constexpr int produce_and_consume = CompileOptions::kProduceCompileHints |
695 CompileOptions::kConsumeCompileHints;
696 if ((compile_options & produce_and_consume) == produce_and_consume) {
697 return false;
698 }
699 return true;
700 }
701
706 kNoCacheNoReason = 0,
720 kNoCacheBecauseDeferredProduceCodeCache
721 };
722
738 Isolate* isolate, Source* source,
739 CompileOptions options = kNoCompileOptions,
740 NoCacheReason no_cache_reason = kNoCacheNoReason);
741
754 Local<Context> context, Source* source,
755 CompileOptions options = kNoCompileOptions,
756 NoCacheReason no_cache_reason = kNoCacheNoReason);
757
770 Isolate* isolate, StreamedSource* source,
771 ScriptType type = ScriptType::kClassic,
772 CompileOptions options = kNoCompileOptions,
773 CompileHintCallback compile_hint_callback = nullptr,
774 void* compile_hint_callback_data = nullptr);
775
777 Isolate* isolate, std::unique_ptr<CachedData> source);
779 Isolate* isolate, std::unique_ptr<CachedData> source);
780
789 Local<Context> context, StreamedSource* source,
790 Local<String> full_source_string, const ScriptOrigin& origin);
791
810 static uint32_t CachedDataVersionTag();
811
820 Isolate* isolate, Source* source,
821 CompileOptions options = kNoCompileOptions,
822 NoCacheReason no_cache_reason = kNoCacheNoReason);
823
832 Local<Context> context, StreamedSource* v8_source,
833 Local<String> full_source_string, const ScriptOrigin& origin);
834
846 Local<Context> context, Source* source, size_t arguments_count = 0,
847 Local<String> arguments[] = nullptr, size_t context_extension_count = 0,
848 Local<Object> context_extensions[] = nullptr,
849 CompileOptions options = kNoCompileOptions,
850 NoCacheReason no_cache_reason = kNoCacheNoReason);
851
858
865 Local<UnboundModuleScript> unbound_module_script);
866
874
875 private:
876 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
877 Isolate* isolate, Source* source, CompileOptions options,
878 NoCacheReason no_cache_reason);
879
880 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInternal(
881 Local<Context> context, Source* source, size_t arguments_count,
882 Local<String> arguments[], size_t context_extension_count,
883 Local<Object> context_extensions[], CompileOptions options,
884 NoCacheReason no_cache_reason,
885 Local<ScriptOrModule>* script_or_module_out);
886};
887
888ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
889 CachedData* data,
890 ConsumeCodeCacheTask* consume_cache_task)
891 : source_string(string),
892 resource_name(origin.ResourceName()),
893 resource_line_offset(origin.LineOffset()),
894 resource_column_offset(origin.ColumnOffset()),
895 resource_options(origin.Options()),
896 source_map_url(origin.SourceMapUrl()),
897 host_defined_options(origin.GetHostDefinedOptions()),
898 cached_data(data),
899 consume_cache_task(consume_cache_task) {}
900
902 ConsumeCodeCacheTask* consume_cache_task)
903 : source_string(string),
904 cached_data(data),
905 consume_cache_task(consume_cache_task) {}
906
908 CompileHintCallback callback,
909 void* callback_data)
910 : source_string(string),
911 resource_name(origin.ResourceName()),
912 resource_line_offset(origin.LineOffset()),
913 resource_column_offset(origin.ColumnOffset()),
914 resource_options(origin.Options()),
915 source_map_url(origin.SourceMapUrl()),
916 host_defined_options(origin.GetHostDefinedOptions()),
917 compile_hint_callback(callback),
918 compile_hint_callback_data(callback_data) {}
919
921 const {
922 return cached_data.get();
923}
924
926 return resource_options;
927}
928
931 return compilation_details;
932}
933
935#ifdef V8_ENABLE_CHECKS
936 CheckCast(data);
937#endif
938 return reinterpret_cast<ModuleRequest*>(data);
939}
940
942#ifdef V8_ENABLE_CHECKS
943 CheckCast(data);
944#endif
945 return reinterpret_cast<Module*>(data);
946}
947
948} // namespace v8
949
950#endif // INCLUDE_V8_SCRIPT_H_
Definition: v8-script.h:341
std::vector< int > GetCompileHints(Isolate *isolate) const
Definition: v8-data.h:18
Definition: v8-data.h:62
Definition: v8-isolate.h:212
Definition: v8-local-handle.h:492
Definition: v8-local-handle.h:266
Definition: v8-script.h:112
int GetLineNumber()
Definition: v8-script.h:114
Location(int line_number, int column_number)
Definition: v8-script.h:117
int GetColumnNumber()
Definition: v8-script.h:115
Definition: v8-local-handle.h:632
Definition: v8-maybe.h:32
Definition: v8-memory-span.h:63
Definition: v8-script.h:125
static ModuleRequest * Cast(Data *data)
Definition: v8-script.h:934
Local< FixedArray > GetImportAttributes() const
Local< String > GetSpecifier() const
ModuleImportPhase GetPhase() const
int GetSourceOffset() const
Definition: v8-script.h:172
Location SourceOffsetToLocation(int offset) const
MaybeLocal< Value > Evaluate(Local< Context > context)
Local< Value > GetModuleNamespace()
Maybe< bool > SetSyntheticModuleExport(Isolate *isolate, Local< String > export_name, Local< Value > export_value)
Local< FixedArray > GetModuleRequests() const
bool IsGraphAsync() const
bool HasTopLevelAwait() const
int ScriptId() const
Status GetStatus() const
bool IsSyntheticModule() const
Local< Value > GetException() const
std::pair< LocalVector< Module >, LocalVector< Message > > GetStalledTopLevelAwaitMessages(Isolate *isolate)
Status
Definition: v8-script.h:181
@ kInstantiating
Definition: v8-script.h:183
@ kInstantiated
Definition: v8-script.h:184
@ kUninstantiated
Definition: v8-script.h:182
@ kEvaluating
Definition: v8-script.h:185
@ kEvaluated
Definition: v8-script.h:186
int GetIdentityHash() const
static Local< Module > CreateSyntheticModule(Isolate *isolate, Local< String > module_name, const MemorySpan< const Local< String > > &export_names, SyntheticModuleEvaluationSteps evaluation_steps)
Local< UnboundModuleScript > GetUnboundModuleScript()
static Module * Cast(Data *data)
Definition: v8-script.h:941
Maybe< bool > InstantiateModule(Local< Context > context, ResolveModuleCallback module_callback, ResolveSourceCallback source_callback=nullptr)
bool IsSourceTextModule() const
Definition: v8-script.h:628
void SourceTextAvailable(Isolate *isolate, Local< String > source_text, const ScriptOrigin &origin)
Definition: v8-script.h:548
virtual size_t GetMoreData(const uint8_t **src)=0
Definition: v8-script.h:610
Definition: v8-script.h:492
Source(Local< String > source_string, const ScriptOrigin &origin, CachedData *cached_data=nullptr, ConsumeCodeCacheTask *consume_cache_task=nullptr)
Definition: v8-script.h:888
const CompilationDetails & GetCompilationDetails() const
Definition: v8-script.h:930
const CachedData * GetCachedData() const
Definition: v8-script.h:920
const ScriptOriginOptions & GetResourceOptions() const
Definition: v8-script.h:925
Definition: v8-script.h:582
internal::ScriptStreamingData * impl() const
Definition: v8-script.h:590
Encoding
Definition: v8-script.h:584
CompilationDetails & compilation_details()
Definition: v8-script.h:596
StreamedSource & operator=(const StreamedSource &)=delete
StreamedSource(const StreamedSource &)=delete
StreamedSource(std::unique_ptr< ExternalSourceStream > source_stream, Encoding encoding)
Definition: v8-script.h:402
static CachedData * CreateCodeCacheForFunction(Local< Function > function)
static MaybeLocal< Function > CompileFunction(Local< Context > context, Source *source, size_t arguments_count=0, Local< String > arguments[]=nullptr, size_t context_extension_count=0, Local< Object > context_extensions[]=nullptr, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
InMemoryCacheResult
Definition: v8-script.h:462
static bool CompileOptionsIsValid(CompileOptions compile_options)
Definition: v8-script.h:682
static CachedData * CreateCodeCache(Local< UnboundModuleScript > unbound_module_script)
NoCacheReason
Definition: v8-script.h:705
@ kNoCacheBecausePacScript
Definition: v8-script.h:717
@ kNoCacheBecauseV8Extension
Definition: v8-script.h:715
@ kNoCacheBecauseStreamingSource
Definition: v8-script.h:711
@ kNoCacheBecauseNoResource
Definition: v8-script.h:708
@ kNoCacheBecauseInspector
Definition: v8-script.h:712
@ kNoCacheBecauseCacheTooCold
Definition: v8-script.h:714
@ kNoCacheBecauseScriptTooSmall
Definition: v8-script.h:713
@ kNoCacheBecauseCachingDisabled
Definition: v8-script.h:707
@ kNoCacheBecauseExtensionModule
Definition: v8-script.h:716
@ kNoCacheBecauseInlineScript
Definition: v8-script.h:709
@ kNoCacheBecauseInDocumentWrite
Definition: v8-script.h:718
@ kNoCacheBecauseModule
Definition: v8-script.h:710
@ kNoCacheBecauseResourceWithNoCacheHandler
Definition: v8-script.h:719
static ConsumeCodeCacheTask * StartConsumingCodeCacheOnBackground(Isolate *isolate, std::unique_ptr< CachedData > source)
static CachedData * CreateCodeCache(Local< UnboundScript > unbound_script)
static MaybeLocal< Module > CompileModule(Local< Context > context, StreamedSource *v8_source, Local< String > full_source_string, const ScriptOrigin &origin)
CompileOptions
Definition: v8-script.h:673
static MaybeLocal< Script > Compile(Local< Context > context, StreamedSource *source, Local< String > full_source_string, const ScriptOrigin &origin)
static MaybeLocal< Script > Compile(Local< Context > context, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
static ScriptStreamingTask * StartStreaming(Isolate *isolate, StreamedSource *source, ScriptType type=ScriptType::kClassic, CompileOptions options=kNoCompileOptions, CompileHintCallback compile_hint_callback=nullptr, void *compile_hint_callback_data=nullptr)
static uint32_t CachedDataVersionTag()
static MaybeLocal< UnboundScript > CompileUnboundScript(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
static ConsumeCodeCacheTask * StartConsumingCodeCache(Isolate *isolate, std::unique_ptr< CachedData > source)
static MaybeLocal< Module > CompileModule(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition: v8-script.h:42
Local< Value > GetResourceName()
Local< Data > HostDefinedOptions()
Definition: v8-message.h:28
Definition: v8-message.h:62
Definition: v8-script.h:353
static MaybeLocal< Script > Compile(Local< Context > context, Local< String > source, ScriptOrigin *origin=nullptr)
MaybeLocal< Value > Run(Local< Context > context)
Local< UnboundScript > GetUnboundScript()
MaybeLocal< Value > Run(Local< Context > context, Local< Data > host_defined_options)
Local< Value > GetResourceName()
Definition: v8-script.h:97
Local< Value > GetSourceURL()
Local< Value > GetSourceMappingURL()
Definition: v8-script.h:60
int GetColumnNumber(int code_pos=0)
Local< Value > GetSourceMappingURL()
Local< Value > GetScriptName()
int GetLineNumber(int code_pos=0)
Local< Value > GetSourceURL()
int GetId() const
Local< Script > BindToCurrentContext()
Definition: libplatform.h:15
bool(*)(int, void *) CompileHintCallback
Definition: v8-callbacks.h:418
ModuleImportPhase
Definition: v8-callbacks.h:336
ScriptType
Definition: v8-script.h:397
Definition: v8-script.h:413
BufferPolicy buffer_policy
Definition: v8-script.h:455
const uint8_t * data
Definition: v8-script.h:452
CachedData(const CachedData &)=delete
CompatibilityCheckResult
Definition: v8-script.h:430
bool rejected
Definition: v8-script.h:454
CachedData(const uint8_t *data, int length, BufferPolicy buffer_policy=BufferNotOwned)
BufferPolicy
Definition: v8-script.h:414
@ BufferNotOwned
Definition: v8-script.h:414
CachedData()
Definition: v8-script.h:416
int length
Definition: v8-script.h:453
CompatibilityCheckResult CompatibilityCheck(Isolate *isolate)
CachedData & operator=(const CachedData &)=delete
Definition: v8-script.h:480
#define V8_EXPORT
Definition: v8config.h:793
#define V8_INLINE
Definition: v8config.h:499
#define V8_DEPRECATE_SOON(message)
Definition: v8config.h:603
#define V8_DEPRECATED(message)
Definition: v8config.h:595
#define V8_WARN_UNUSED_RESULT
Definition: v8config.h:660