v8  8.1.307(node14.1.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  * The TaskRunner's NonNestableTasksEnabled() must be true. This function
330  * should only be called from a foreground thread.
331  */
332  virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner(
333  Isolate* isolate) = 0;
334 
335  /**
336  * Schedules a task to be invoked on a worker thread.
337  */
338  virtual void CallOnWorkerThread(std::unique_ptr<Task> task) = 0;
339 
340  /**
341  * Schedules a task that blocks the main thread to be invoked with
342  * high-priority on a worker thread.
343  */
344  virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr<Task> task) {
345  // Embedders may optionally override this to process these tasks in a high
346  // priority pool.
347  CallOnWorkerThread(std::move(task));
348  }
349 
350  /**
351  * Schedules a task to be invoked with low-priority on a worker thread.
352  */
353  virtual void CallLowPriorityTaskOnWorkerThread(std::unique_ptr<Task> task) {
354  // Embedders may optionally override this to process these tasks in a low
355  // priority pool.
356  CallOnWorkerThread(std::move(task));
357  }
358 
359  /**
360  * Schedules a task to be invoked on a worker thread after |delay_in_seconds|
361  * expires.
362  */
363  virtual void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
364  double delay_in_seconds) = 0;
365 
366  /**
367  * Returns true if idle tasks are enabled for the given |isolate|.
368  */
369  virtual bool IdleTasksEnabled(Isolate* isolate) { return false; }
370 
371  /**
372  * Monotonically increasing time in seconds from an arbitrary fixed point in
373  * the past. This function is expected to return at least
374  * millisecond-precision values. For this reason,
375  * it is recommended that the fixed point be no further in the past than
376  * the epoch.
377  **/
378  virtual double MonotonicallyIncreasingTime() = 0;
379 
380  /**
381  * Current wall-clock time in milliseconds since epoch.
382  * This function is expected to return at least millisecond-precision values.
383  */
384  virtual double CurrentClockTimeMillis() = 0;
385 
386  typedef void (*StackTracePrinter)();
387 
388  /**
389  * Returns a function pointer that print a stack trace of the current stack
390  * on invocation. Disables printing of the stack trace if nullptr.
391  */
392  virtual StackTracePrinter GetStackTracePrinter() { return nullptr; }
393 
394  /**
395  * Returns an instance of a v8::TracingController. This must be non-nullptr.
396  */
398 
399  /**
400  * Tells the embedder to generate and upload a crashdump during an unexpected
401  * but non-critical scenario.
402  */
403  virtual void DumpWithoutCrashing() {}
404 
405  protected:
406  /**
407  * Default implementation of current wall-clock time in milliseconds
408  * since epoch. Useful for implementing |CurrentClockTimeMillis| if
409  * nothing special needed.
410  */
411  V8_EXPORT static double SystemClockTimeMillis();
412 };
413 
414 } // namespace v8
415 
416 #endif // V8_V8_PLATFORM_H_
virtual void RemoveTraceStateObserver(TraceStateObserver *)
Definition: v8-platform.h:198
virtual bool DiscardSystemPages(void *address, size_t size)
Definition: v8-platform.h:274
virtual size_t AllocatePageSize()=0
#define V8_EXPORT
Definition: v8config.h:458
virtual ~Platform()=default
virtual void PostNonNestableDelayedTask(std::unique_ptr< Task > task, double delay_in_seconds)
Definition: v8-platform.h:81
static V8_EXPORT double SystemClockTimeMillis()
virtual StackTracePrinter GetStackTracePrinter()
Definition: v8-platform.h:392
virtual void Run()=0
virtual bool NonNestableDelayedTasksEnabled() const
Definition: v8-platform.h:107
virtual void PostIdleTask(std::unique_ptr< IdleTask > task)=0
virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr< Task > task)
Definition: v8-platform.h:344
virtual void CallLowPriorityTaskOnWorkerThread(std::unique_ptr< Task > task)
Definition: v8-platform.h:353
virtual ~TaskRunner()=default
virtual bool IdleTasksEnabled()=0
virtual void * AllocatePages(void *address, size_t length, size_t alignment, Permission permissions)=0
virtual double CurrentClockTimeMillis()=0
virtual size_t CommitPageSize()=0
virtual const uint8_t * GetCategoryGroupEnabled(const char *name)
Definition: v8-platform.h:148
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
virtual void AddTraceStateObserver(TraceStateObserver *)
Definition: v8-platform.h:195
virtual void AppendAsTraceFormat(std::string *out) const =0
virtual std::shared_ptr< v8::TaskRunner > GetForegroundTaskRunner(Isolate *isolate)=0
void(* StackTracePrinter)()
Definition: v8-platform.h:386
Definition: libplatform.h:15
virtual bool NonNestableTasksEnabled() const
Definition: v8-platform.h:102
virtual ~TracingController()=default
virtual ~Task()=default
virtual ~ConvertableToTraceFormat()=default
virtual PageAllocator * GetPageAllocator()
Definition: v8-platform.h:290
virtual void CallDelayedOnWorkerThread(std::unique_ptr< Task > task, double delay_in_seconds)=0
virtual void PostTask(std::unique_ptr< Task > task)=0
virtual bool IdleTasksEnabled(Isolate *isolate)
Definition: v8-platform.h:369
virtual bool SetPermissions(void *address, size_t length, Permission permissions)=0
virtual bool FreePages(void *address, size_t length)=0
virtual double MonotonicallyIncreasingTime()=0
virtual void DumpWithoutCrashing()
Definition: v8-platform.h:403
virtual void * GetRandomMmapAddr()=0
TaskRunner & operator=(const TaskRunner &)=delete
virtual ~IdleTask()=default
virtual void OnCriticalMemoryPressure()
Definition: v8-platform.h:302
virtual void UpdateTraceEventDuration(const uint8_t *category_enabled_flag, const char *name, uint64_t handle)
Definition: v8-platform.h:184
TaskRunner()=default
virtual void SetRandomMmapSeed(int64_t seed)=0
virtual void Run(double deadline_in_seconds)=0
virtual void PostNonNestableTask(std::unique_ptr< Task > task)
Definition: v8-platform.h:63
virtual TracingController * GetTracingController()=0
virtual bool OnCriticalMemoryPressure(size_t length)
Definition: v8-platform.h:316
virtual void CallOnWorkerThread(std::unique_ptr< Task > task)=0
virtual int NumberOfWorkerThreads()=0
virtual ~PageAllocator()=default
virtual void PostDelayedTask(std::unique_ptr< Task > task, double delay_in_seconds)=0
TaskRunner(const TaskRunner &)=delete
virtual bool ReleasePages(void *address, size_t length, size_t new_length)=0
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