v8  7.8.279(node12.19.0)
V8 is Google's open source JavaScript engine
v8-platform.h
Go to the documentation of this file.
1 // Copyright 2013 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 V8_V8_PLATFORM_H_
6 #define V8_V8_PLATFORM_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <stdlib.h> // For abort.
11 #include <memory>
12 #include <string>
13 
14 #include "v8config.h" // NOLINT(build/include)
15 
16 namespace v8 {
17 
18 class Isolate;
19 
20 /**
21  * A Task represents a unit of work.
22  */
23 class Task {
24  public:
25  virtual ~Task() = default;
26 
27  virtual void Run() = 0;
28 };
29 
30 /**
31  * An IdleTask represents a unit of work to be performed in idle time.
32  * The Run method is invoked with an argument that specifies the deadline in
33  * seconds returned by MonotonicallyIncreasingTime().
34  * The idle task is expected to complete by this deadline.
35  */
36 class IdleTask {
37  public:
38  virtual ~IdleTask() = default;
39  virtual void Run(double deadline_in_seconds) = 0;
40 };
41 
42 /**
43  * A TaskRunner allows scheduling of tasks. The TaskRunner may still be used to
44  * post tasks after the isolate gets destructed, but these tasks may not get
45  * executed anymore. All tasks posted to a given TaskRunner will be invoked in
46  * sequence. Tasks can be posted from any thread.
47  */
48 class TaskRunner {
49  public:
50  /**
51  * Schedules a task to be invoked by this TaskRunner. The TaskRunner
52  * implementation takes ownership of |task|.
53  */
54  virtual void PostTask(std::unique_ptr<Task> task) = 0;
55 
56  /**
57  * Schedules a task to be invoked by this TaskRunner. The TaskRunner
58  * implementation takes ownership of |task|. The |task| cannot be nested
59  * within other task executions.
60  *
61  * Requires that |TaskRunner::NonNestableTasksEnabled()| is true.
62  */
63  virtual void PostNonNestableTask(std::unique_ptr<Task> task) {}
64 
65  /**
66  * Schedules a task to be invoked by this TaskRunner. The task is scheduled
67  * after the given number of seconds |delay_in_seconds|. The TaskRunner
68  * implementation takes ownership of |task|.
69  */
70  virtual void PostDelayedTask(std::unique_ptr<Task> task,
71  double delay_in_seconds) = 0;
72 
73  /**
74  * Schedules a task to be invoked by this TaskRunner. The task is scheduled
75  * after the given number of seconds |delay_in_seconds|. The TaskRunner
76  * implementation takes ownership of |task|. The |task| cannot be nested
77  * within other task executions.
78  *
79  * Requires that |TaskRunner::NonNestableDelayedTasksEnabled()| is true.
80  */
81  virtual void PostNonNestableDelayedTask(std::unique_ptr<Task> task,
82  double delay_in_seconds) {}
83 
84  /**
85  * Schedules an idle task to be invoked by this TaskRunner. The task is
86  * scheduled when the embedder is idle. Requires that
87  * |TaskRunner::IdleTasksEnabled()| is true. Idle tasks may be reordered
88  * relative to other task types and may be starved for an arbitrarily long
89  * time if no idle time is available. The TaskRunner implementation takes
90  * ownership of |task|.
91  */
92  virtual void PostIdleTask(std::unique_ptr<IdleTask> task) = 0;
93 
94  /**
95  * Returns true if idle tasks are enabled for this TaskRunner.
96  */
97  virtual bool IdleTasksEnabled() = 0;
98 
99  /**
100  * Returns true if non-nestable tasks are enabled for this TaskRunner.
101  */
102  virtual bool NonNestableTasksEnabled() const { return false; }
103 
104  /**
105  * Returns true if non-nestable delayed tasks are enabled for this TaskRunner.
106  */
107  virtual bool NonNestableDelayedTasksEnabled() const { return false; }
108 
109  TaskRunner() = default;
110  virtual ~TaskRunner() = default;
111 
112  TaskRunner(const TaskRunner&) = delete;
113  TaskRunner& operator=(const TaskRunner&) = delete;
114 };
115 
116 /**
117  * The interface represents complex arguments to trace events.
118  */
120  public:
121  virtual ~ConvertableToTraceFormat() = default;
122 
123  /**
124  * Append the class info to the provided |out| string. The appended
125  * data must be a valid JSON object. Strings must be properly quoted, and
126  * escaped. There is no processing applied to the content after it is
127  * appended.
128  */
129  virtual void AppendAsTraceFormat(std::string* out) const = 0;
130 };
131 
132 /**
133  * V8 Tracing controller.
134  *
135  * Can be implemented by an embedder to record trace events from V8.
136  */
138  public:
139  virtual ~TracingController() = default;
140 
141  /**
142  * Called by TRACE_EVENT* macros, don't call this directly.
143  * The name parameter is a category group for example:
144  * TRACE_EVENT0("v8,parse", "V8.Parse")
145  * The pointer returned points to a value with zero or more of the bits
146  * defined in CategoryGroupEnabledFlags.
147  **/
148  virtual const uint8_t* GetCategoryGroupEnabled(const char* name) {
149  static uint8_t no = 0;
150  return &no;
151  }
152 
153  /**
154  * Adds a trace event to the platform tracing system. These function calls are
155  * usually the result of a TRACE_* macro from trace_event_common.h when
156  * tracing and the category of the particular trace are enabled. It is not
157  * advisable to call these functions on their own; they are really only meant
158  * to be used by the trace macros. The returned handle can be used by
159  * UpdateTraceEventDuration to update the duration of COMPLETE events.
160  */
161  virtual uint64_t AddTraceEvent(
162  char phase, const uint8_t* category_enabled_flag, const char* name,
163  const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args,
164  const char** arg_names, const uint8_t* arg_types,
165  const uint64_t* arg_values,
166  std::unique_ptr<ConvertableToTraceFormat>* arg_convertables,
167  unsigned int flags) {
168  return 0;
169  }
170  virtual uint64_t AddTraceEventWithTimestamp(
171  char phase, const uint8_t* category_enabled_flag, const char* name,
172  const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args,
173  const char** arg_names, const uint8_t* arg_types,
174  const uint64_t* arg_values,
175  std::unique_ptr<ConvertableToTraceFormat>* arg_convertables,
176  unsigned int flags, int64_t timestamp) {
177  return 0;
178  }
179 
180  /**
181  * Sets the duration field of a COMPLETE trace event. It must be called with
182  * the handle returned from AddTraceEvent().
183  **/
184  virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
185  const char* name, uint64_t handle) {}
186 
188  public:
189  virtual ~TraceStateObserver() = default;
190  virtual void OnTraceEnabled() = 0;
191  virtual void OnTraceDisabled() = 0;
192  };
193 
194  /** Adds tracing state change observer. */
196 
197  /** Removes tracing state change observer. */
199 };
200 
201 /**
202  * A V8 memory page allocator.
203  *
204  * Can be implemented by an embedder to manage large host OS allocations.
205  */
207  public:
208  virtual ~PageAllocator() = default;
209 
210  /**
211  * Gets the page granularity for AllocatePages and FreePages. Addresses and
212  * lengths for those calls should be multiples of AllocatePageSize().
213  */
214  virtual size_t AllocatePageSize() = 0;
215 
216  /**
217  * Gets the page granularity for SetPermissions and ReleasePages. Addresses
218  * and lengths for those calls should be multiples of CommitPageSize().
219  */
220  virtual size_t CommitPageSize() = 0;
221 
222  /**
223  * Sets the random seed so that GetRandomMmapAddr() will generate repeatable
224  * sequences of random mmap addresses.
225  */
226  virtual void SetRandomMmapSeed(int64_t seed) = 0;
227 
228  /**
229  * Returns a randomized address, suitable for memory allocation under ASLR.
230  * The address will be aligned to AllocatePageSize.
231  */
232  virtual void* GetRandomMmapAddr() = 0;
233 
234  /**
235  * Memory permissions.
236  */
237  enum Permission {
241  // TODO(hpayer): Remove this flag. Memory should never be rwx.
244  };
245 
246  /**
247  * Allocates memory in range with the given alignment and permission.
248  */
249  virtual void* AllocatePages(void* address, size_t length, size_t alignment,
250  Permission permissions) = 0;
251 
252  /**
253  * Frees memory in a range that was allocated by a call to AllocatePages.
254  */
255  virtual bool FreePages(void* address, size_t length) = 0;
256 
257  /**
258  * Releases memory in a range that was allocated by a call to AllocatePages.
259  */
260  virtual bool ReleasePages(void* address, size_t length,
261  size_t new_length) = 0;
262 
263  /**
264  * Sets permissions on pages in an allocated range.
265  */
266  virtual bool SetPermissions(void* address, size_t length,
267  Permission permissions) = 0;
268 
269  /**
270  * Frees memory in the given [address, address + size) range. address and size
271  * should be operating system page-aligned. The next write to this
272  * memory area brings the memory transparently back.
273  */
274  virtual bool DiscardSystemPages(void* address, size_t size) { return true; }
275 };
276 
277 /**
278  * V8 Platform abstraction layer.
279  *
280  * The embedder has to provide an implementation of this interface before
281  * initializing the rest of V8.
282  */
283 class Platform {
284  public:
285  virtual ~Platform() = default;
286 
287  /**
288  * Allows the embedder to manage memory page allocations.
289  */
291  // TODO(bbudge) Make this abstract after all embedders implement this.
292  return nullptr;
293  }
294 
295  /**
296  * Enables the embedder to respond in cases where V8 can't allocate large
297  * blocks of memory. V8 retries the failed allocation once after calling this
298  * method. On success, execution continues; otherwise V8 exits with a fatal
299  * error.
300  * Embedder overrides of this function must NOT call back into V8.
301  */
302  virtual void OnCriticalMemoryPressure() {
303  // TODO(bbudge) Remove this when embedders override the following method.
304  // See crbug.com/634547.
305  }
306 
307  /**
308  * Enables the embedder to respond in cases where V8 can't allocate large
309  * memory regions. The |length| parameter is the amount of memory needed.
310  * Returns true if memory is now available. Returns false if no memory could
311  * be made available. V8 will retry allocations until this method returns
312  * false.
313  *
314  * Embedder overrides of this function must NOT call back into V8.
315  */
316  virtual bool OnCriticalMemoryPressure(size_t length) { return false; }
317 
318  /**
319  * Gets the number of worker threads used by
320  * Call(BlockingTask)OnWorkerThread(). This can be used to estimate the number
321  * of tasks a work package should be split into. A return value of 0 means
322  * that there are no worker threads available. Note that a value of 0 won't
323  * prohibit V8 from posting tasks using |CallOnWorkerThread|.
324  */
325  virtual int NumberOfWorkerThreads() = 0;
326 
327  /**
328  * Returns a TaskRunner which can be used to post a task on the foreground.
329  * This function should only be called from a foreground thread.
330  */
331  virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner(
332  Isolate* isolate) = 0;
333 
334  /**
335  * Schedules a task to be invoked on a worker thread.
336  */
337  virtual void CallOnWorkerThread(std::unique_ptr<Task> task) = 0;
338 
339  /**
340  * Schedules a task that blocks the main thread to be invoked with
341  * high-priority on a worker thread.
342  */
343  virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr<Task> task) {
344  // Embedders may optionally override this to process these tasks in a high
345  // priority pool.
346  CallOnWorkerThread(std::move(task));
347  }
348 
349  /**
350  * Schedules a task to be invoked with low-priority on a worker thread.
351  */
352  virtual void CallLowPriorityTaskOnWorkerThread(std::unique_ptr<Task> task) {
353  // Embedders may optionally override this to process these tasks in a low
354  // priority pool.
355  CallOnWorkerThread(std::move(task));
356  }
357 
358  /**
359  * Schedules a task to be invoked on a worker thread after |delay_in_seconds|
360  * expires.
361  */
362  virtual void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
363  double delay_in_seconds) = 0;
364 
365  /**
366  * Schedules a task to be invoked on a foreground thread wrt a specific
367  * |isolate|. Tasks posted for the same isolate should be execute in order of
368  * scheduling. The definition of "foreground" is opaque to V8.
369  */
371  "Use a taskrunner acquired by GetForegroundTaskRunner instead.",
372  virtual void CallOnForegroundThread(Isolate* isolate, Task* task)) = 0;
373 
374  /**
375  * Schedules a task to be invoked on a foreground thread wrt a specific
376  * |isolate| after the given number of seconds |delay_in_seconds|.
377  * Tasks posted for the same isolate should be execute in order of
378  * scheduling. The definition of "foreground" is opaque to V8.
379  */
381  "Use a taskrunner acquired by GetForegroundTaskRunner instead.",
382  virtual void CallDelayedOnForegroundThread(Isolate* isolate, Task* task,
383  double delay_in_seconds)) = 0;
384 
385  /**
386  * Schedules a task to be invoked on a foreground thread wrt a specific
387  * |isolate| when the embedder is idle.
388  * Requires that SupportsIdleTasks(isolate) is true.
389  * Idle tasks may be reordered relative to other task types and may be
390  * starved for an arbitrarily long time if no idle time is available.
391  * The definition of "foreground" is opaque to V8.
392  */
394  "Use a taskrunner acquired by GetForegroundTaskRunner instead.",
395  virtual void CallIdleOnForegroundThread(Isolate* isolate,
396  IdleTask* task)) {
397  // This must be overriden if |IdleTasksEnabled()|.
398  abort();
399  }
400 
401  /**
402  * Returns true if idle tasks are enabled for the given |isolate|.
403  */
404  virtual bool IdleTasksEnabled(Isolate* isolate) {
405  return false;
406  }
407 
408  /**
409  * Monotonically increasing time in seconds from an arbitrary fixed point in
410  * the past. This function is expected to return at least
411  * millisecond-precision values. For this reason,
412  * it is recommended that the fixed point be no further in the past than
413  * the epoch.
414  **/
415  virtual double MonotonicallyIncreasingTime() = 0;
416 
417  /**
418  * Current wall-clock time in milliseconds since epoch.
419  * This function is expected to return at least millisecond-precision values.
420  */
421  virtual double CurrentClockTimeMillis() = 0;
422 
423  typedef void (*StackTracePrinter)();
424 
425  /**
426  * Returns a function pointer that print a stack trace of the current stack
427  * on invocation. Disables printing of the stack trace if nullptr.
428  */
429  virtual StackTracePrinter GetStackTracePrinter() { return nullptr; }
430 
431  /**
432  * Returns an instance of a v8::TracingController. This must be non-nullptr.
433  */
435 
436  /**
437  * Tells the embedder to generate and upload a crashdump during an unexpected
438  * but non-critical scenario.
439  */
440  virtual void DumpWithoutCrashing() {}
441 
442  protected:
443  /**
444  * Default implementation of current wall-clock time in milliseconds
445  * since epoch. Useful for implementing |CurrentClockTimeMillis| if
446  * nothing special needed.
447  */
448  V8_EXPORT static double SystemClockTimeMillis();
449 };
450 
451 } // namespace v8
452 
453 #endif // V8_V8_PLATFORM_H_
v8::Platform::NumberOfWorkerThreads
virtual int NumberOfWorkerThreads()=0
v8::Platform::GetStackTracePrinter
virtual StackTracePrinter GetStackTracePrinter()
Definition: v8-platform.h:429
v8::Task::Run
virtual void Run()=0
v8::IdleTask
Definition: v8-platform.h:36
v8::TaskRunner::PostTask
virtual void PostTask(std::unique_ptr< Task > task)=0
v8::TaskRunner::PostDelayedTask
virtual void PostDelayedTask(std::unique_ptr< Task > task, double delay_in_seconds)=0
v8::Platform::SystemClockTimeMillis
static V8_EXPORT double SystemClockTimeMillis()
v8::PageAllocator::kNoAccess
@ kNoAccess
Definition: v8-platform.h:238
v8::IdleTask::~IdleTask
virtual ~IdleTask()=default
v8::TracingController::TraceStateObserver::OnTraceDisabled
virtual void OnTraceDisabled()=0
v8::TracingController::AddTraceEvent
virtual uint64_t AddTraceEvent(char phase, const uint8_t *category_enabled_flag, const char *name, const char *scope, uint64_t id, uint64_t bind_id, int32_t num_args, const char **arg_names, const uint8_t *arg_types, const uint64_t *arg_values, std::unique_ptr< ConvertableToTraceFormat > *arg_convertables, unsigned int flags)
Definition: v8-platform.h:161
v8::Platform::StackTracePrinter
void(* StackTracePrinter)()
Definition: v8-platform.h:423
v8::PageAllocator
Definition: v8-platform.h:206
v8::TaskRunner::IdleTasksEnabled
virtual bool IdleTasksEnabled()=0
v8::PageAllocator::SetPermissions
virtual bool SetPermissions(void *address, size_t length, Permission permissions)=0
v8::Platform::~Platform
virtual ~Platform()=default
v8::Platform::CallLowPriorityTaskOnWorkerThread
virtual void CallLowPriorityTaskOnWorkerThread(std::unique_ptr< Task > task)
Definition: v8-platform.h:352
v8::PageAllocator::GetRandomMmapAddr
virtual void * GetRandomMmapAddr()=0
v8::TracingController::TraceStateObserver::~TraceStateObserver
virtual ~TraceStateObserver()=default
v8::IdleTask::Run
virtual void Run(double deadline_in_seconds)=0
v8::ConvertableToTraceFormat::~ConvertableToTraceFormat
virtual ~ConvertableToTraceFormat()=default
v8::TaskRunner::PostNonNestableTask
virtual void PostNonNestableTask(std::unique_ptr< Task > task)
Definition: v8-platform.h:63
V8_DEPRECATE_SOON
#define V8_DEPRECATE_SOON(message, declarator)
Definition: v8config.h:350
v8::TracingController::UpdateTraceEventDuration
virtual void UpdateTraceEventDuration(const uint8_t *category_enabled_flag, const char *name, uint64_t handle)
Definition: v8-platform.h:184
v8::Platform::IdleTasksEnabled
virtual bool IdleTasksEnabled(Isolate *isolate)
Definition: v8-platform.h:404
v8::TracingController::AddTraceEventWithTimestamp
virtual uint64_t AddTraceEventWithTimestamp(char phase, const uint8_t *category_enabled_flag, const char *name, const char *scope, uint64_t id, uint64_t bind_id, int32_t num_args, const char **arg_names, const uint8_t *arg_types, const uint64_t *arg_values, std::unique_ptr< ConvertableToTraceFormat > *arg_convertables, unsigned int flags, int64_t timestamp)
Definition: v8-platform.h:170
v8::PageAllocator::AllocatePages
virtual void * AllocatePages(void *address, size_t length, size_t alignment, Permission permissions)=0
v8::TaskRunner::NonNestableTasksEnabled
virtual bool NonNestableTasksEnabled() const
Definition: v8-platform.h:102
v8::TaskRunner::TaskRunner
TaskRunner()=default
v8::TracingController::TraceStateObserver
Definition: v8-platform.h:187
v8::TaskRunner::NonNestableDelayedTasksEnabled
virtual bool NonNestableDelayedTasksEnabled() const
Definition: v8-platform.h:107
v8::PageAllocator::CommitPageSize
virtual size_t CommitPageSize()=0
v8::Platform::CallOnWorkerThread
virtual void CallOnWorkerThread(std::unique_ptr< Task > task)=0
v8::PageAllocator::~PageAllocator
virtual ~PageAllocator()=default
v8::Platform::CurrentClockTimeMillis
virtual double CurrentClockTimeMillis()=0
V8_EXPORT
#define V8_EXPORT
Definition: v8config.h:404
v8::Platform::CallDelayedOnWorkerThread
virtual void CallDelayedOnWorkerThread(std::unique_ptr< Task > task, double delay_in_seconds)=0
v8::PageAllocator::ReleasePages
virtual bool ReleasePages(void *address, size_t length, size_t new_length)=0
v8::PageAllocator::kReadWriteExecute
@ kReadWriteExecute
Definition: v8-platform.h:242
v8::TracingController::TraceStateObserver::OnTraceEnabled
virtual void OnTraceEnabled()=0
v8::TracingController
Definition: v8-platform.h:137
v8::Platform::CallBlockingTaskOnWorkerThread
virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr< Task > task)
Definition: v8-platform.h:343
v8::Isolate
Definition: v8.h:7578
v8::PageAllocator::AllocatePageSize
virtual size_t AllocatePageSize()=0
v8::Task::~Task
virtual ~Task()=default
v8::TaskRunner::PostNonNestableDelayedTask
virtual void PostNonNestableDelayedTask(std::unique_ptr< Task > task, double delay_in_seconds)
Definition: v8-platform.h:81
v8
Definition: libplatform.h:13
v8::PageAllocator::Permission
Permission
Definition: v8-platform.h:237
v8::Platform
Definition: v8-platform.h:283
v8::Platform::GetTracingController
virtual TracingController * GetTracingController()=0
v8::Task
Definition: v8-platform.h:23
v8::Platform::GetForegroundTaskRunner
virtual std::shared_ptr< v8::TaskRunner > GetForegroundTaskRunner(Isolate *isolate)=0
v8::PageAllocator::FreePages
virtual bool FreePages(void *address, size_t length)=0
v8::TracingController::AddTraceStateObserver
virtual void AddTraceStateObserver(TraceStateObserver *)
Definition: v8-platform.h:195
v8::TracingController::RemoveTraceStateObserver
virtual void RemoveTraceStateObserver(TraceStateObserver *)
Definition: v8-platform.h:198
v8::Platform::DumpWithoutCrashing
virtual void DumpWithoutCrashing()
Definition: v8-platform.h:440
v8::ConvertableToTraceFormat
Definition: v8-platform.h:119
v8::PageAllocator::DiscardSystemPages
virtual bool DiscardSystemPages(void *address, size_t size)
Definition: v8-platform.h:274
v8::PageAllocator::kRead
@ kRead
Definition: v8-platform.h:239
v8::ConvertableToTraceFormat::AppendAsTraceFormat
virtual void AppendAsTraceFormat(std::string *out) const =0
v8::PageAllocator::kReadExecute
@ kReadExecute
Definition: v8-platform.h:243
v8::PageAllocator::kReadWrite
@ kReadWrite
Definition: v8-platform.h:240
v8::TaskRunner::TaskRunner
TaskRunner(const TaskRunner &)=delete
v8::Platform::OnCriticalMemoryPressure
virtual bool OnCriticalMemoryPressure(size_t length)
Definition: v8-platform.h:316
v8::TracingController::~TracingController
virtual ~TracingController()=default
v8::TaskRunner
Definition: v8-platform.h:48
v8::Platform::OnCriticalMemoryPressure
virtual void OnCriticalMemoryPressure()
Definition: v8-platform.h:302
v8::TracingController::GetCategoryGroupEnabled
virtual const uint8_t * GetCategoryGroupEnabled(const char *name)
Definition: v8-platform.h:148
v8::TaskRunner::~TaskRunner
virtual ~TaskRunner()=default
v8::TaskRunner::operator=
TaskRunner & operator=(const TaskRunner &)=delete
v8::Platform::GetPageAllocator
virtual PageAllocator * GetPageAllocator()
Definition: v8-platform.h:290
v8::PageAllocator::SetRandomMmapSeed
virtual void SetRandomMmapSeed(int64_t seed)=0
v8::Platform::MonotonicallyIncreasingTime
virtual double MonotonicallyIncreasingTime()=0
v8::TaskRunner::PostIdleTask
virtual void PostIdleTask(std::unique_ptr< IdleTask > task)=0