v8  6.8.275 (node 10.15.3)
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 task is scheduled
58  * after the given number of seconds |delay_in_seconds|. The TaskRunner
59  * implementation takes ownership of |task|.
60  */
61  virtual void PostDelayedTask(std::unique_ptr<Task> task,
62  double delay_in_seconds) = 0;
63 
64  /**
65  * Schedules an idle task to be invoked by this TaskRunner. The task is
66  * scheduled when the embedder is idle. Requires that
67  * TaskRunner::SupportsIdleTasks(isolate) is true. Idle tasks may be reordered
68  * relative to other task types and may be starved for an arbitrarily long
69  * time if no idle time is available. The TaskRunner implementation takes
70  * ownership of |task|.
71  */
72  virtual void PostIdleTask(std::unique_ptr<IdleTask> task) = 0;
73 
74  /**
75  * Returns true if idle tasks are enabled for this TaskRunner.
76  */
77  virtual bool IdleTasksEnabled() = 0;
78 
79  TaskRunner() = default;
80  virtual ~TaskRunner() = default;
81 
82  private:
83  TaskRunner(const TaskRunner&) = delete;
84  TaskRunner& operator=(const TaskRunner&) = delete;
85 };
86 
87 /**
88  * The interface represents complex arguments to trace events.
89  */
91  public:
92  virtual ~ConvertableToTraceFormat() = default;
93 
94  /**
95  * Append the class info to the provided |out| string. The appended
96  * data must be a valid JSON object. Strings must be properly quoted, and
97  * escaped. There is no processing applied to the content after it is
98  * appended.
99  */
100  virtual void AppendAsTraceFormat(std::string* out) const = 0;
101 };
102 
103 /**
104  * V8 Tracing controller.
105  *
106  * Can be implemented by an embedder to record trace events from V8.
107  */
109  public:
110  virtual ~TracingController() = default;
111 
112  /**
113  * Called by TRACE_EVENT* macros, don't call this directly.
114  * The name parameter is a category group for example:
115  * TRACE_EVENT0("v8,parse", "V8.Parse")
116  * The pointer returned points to a value with zero or more of the bits
117  * defined in CategoryGroupEnabledFlags.
118  **/
119  virtual const uint8_t* GetCategoryGroupEnabled(const char* name) {
120  static uint8_t no = 0;
121  return &no;
122  }
123 
124  /**
125  * Adds a trace event to the platform tracing system. These function calls are
126  * usually the result of a TRACE_* macro from trace_event_common.h when
127  * tracing and the category of the particular trace are enabled. It is not
128  * advisable to call these functions on their own; they are really only meant
129  * to be used by the trace macros. The returned handle can be used by
130  * UpdateTraceEventDuration to update the duration of COMPLETE events.
131  */
132  virtual uint64_t AddTraceEvent(
133  char phase, const uint8_t* category_enabled_flag, const char* name,
134  const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args,
135  const char** arg_names, const uint8_t* arg_types,
136  const uint64_t* arg_values,
137  std::unique_ptr<ConvertableToTraceFormat>* arg_convertables,
138  unsigned int flags) {
139  return 0;
140  }
141  virtual uint64_t AddTraceEventWithTimestamp(
142  char phase, const uint8_t* category_enabled_flag, const char* name,
143  const char* scope, uint64_t id, uint64_t bind_id, int32_t num_args,
144  const char** arg_names, const uint8_t* arg_types,
145  const uint64_t* arg_values,
146  std::unique_ptr<ConvertableToTraceFormat>* arg_convertables,
147  unsigned int flags, int64_t timestamp) {
148  return 0;
149  }
150 
151  /**
152  * Sets the duration field of a COMPLETE trace event. It must be called with
153  * the handle returned from AddTraceEvent().
154  **/
155  virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
156  const char* name, uint64_t handle) {}
157 
159  public:
160  virtual ~TraceStateObserver() = default;
161  virtual void OnTraceEnabled() = 0;
162  virtual void OnTraceDisabled() = 0;
163  };
164 
165  /** Adds tracing state change observer. */
167 
168  /** Removes tracing state change observer. */
170 };
171 
172 /**
173  * A V8 memory page allocator.
174  *
175  * Can be implemented by an embedder to manage large host OS allocations.
176  */
178  public:
179  virtual ~PageAllocator() = default;
180 
181  /**
182  * Gets the page granularity for AllocatePages and FreePages. Addresses and
183  * lengths for those calls should be multiples of AllocatePageSize().
184  */
185  virtual size_t AllocatePageSize() = 0;
186 
187  /**
188  * Gets the page granularity for SetPermissions and ReleasePages. Addresses
189  * and lengths for those calls should be multiples of CommitPageSize().
190  */
191  virtual size_t CommitPageSize() = 0;
192 
193  /**
194  * Sets the random seed so that GetRandomMmapAddr() will generate repeatable
195  * sequences of random mmap addresses.
196  */
197  virtual void SetRandomMmapSeed(int64_t seed) = 0;
198 
199  /**
200  * Returns a randomized address, suitable for memory allocation under ASLR.
201  * The address will be aligned to AllocatePageSize.
202  */
203  virtual void* GetRandomMmapAddr() = 0;
204 
205  /**
206  * Memory permissions.
207  */
208  enum Permission {
212  // TODO(hpayer): Remove this flag. Memory should never be rwx.
215  };
216 
217  /**
218  * Allocates memory in range with the given alignment and permission.
219  */
220  virtual void* AllocatePages(void* address, size_t length, size_t alignment,
221  Permission permissions) = 0;
222 
223  /**
224  * Frees memory in a range that was allocated by a call to AllocatePages.
225  */
226  virtual bool FreePages(void* address, size_t length) = 0;
227 
228  /**
229  * Releases memory in a range that was allocated by a call to AllocatePages.
230  */
231  virtual bool ReleasePages(void* address, size_t length,
232  size_t new_length) = 0;
233 
234  /**
235  * Sets permissions on pages in an allocated range.
236  */
237  virtual bool SetPermissions(void* address, size_t length,
238  Permission permissions) = 0;
239 };
240 
241 /**
242  * V8 Platform abstraction layer.
243  *
244  * The embedder has to provide an implementation of this interface before
245  * initializing the rest of V8.
246  */
247 class Platform {
248  public:
249  virtual ~Platform() = default;
250 
251  /**
252  * Allows the embedder to manage memory page allocations.
253  */
255  // TODO(bbudge) Make this abstract after all embedders implement this.
256  return nullptr;
257  }
258 
259  /**
260  * Enables the embedder to respond in cases where V8 can't allocate large
261  * blocks of memory. V8 retries the failed allocation once after calling this
262  * method. On success, execution continues; otherwise V8 exits with a fatal
263  * error.
264  * Embedder overrides of this function must NOT call back into V8.
265  */
266  virtual void OnCriticalMemoryPressure() {
267  // TODO(bbudge) Remove this when embedders override the following method.
268  // See crbug.com/634547.
269  }
270 
271  /**
272  * Enables the embedder to respond in cases where V8 can't allocate large
273  * memory regions. The |length| parameter is the amount of memory needed.
274  * Returns true if memory is now available. Returns false if no memory could
275  * be made available. V8 will retry allocations until this method returns
276  * false.
277  *
278  * Embedder overrides of this function must NOT call back into V8.
279  */
280  virtual bool OnCriticalMemoryPressure(size_t length) { return false; }
281 
282  /**
283  * Gets the number of worker threads used by
284  * Call(BlockingTask)OnWorkerThread(). This can be used to estimate the number
285  * of tasks a work package should be split into. A return value of 0 means
286  * that there are no worker threads available. Note that a value of 0 won't
287  * prohibit V8 from posting tasks using |CallOnWorkerThread|.
288  */
289  virtual int NumberOfWorkerThreads() = 0;
290 
291  /**
292  * Returns a TaskRunner which can be used to post a task on the foreground.
293  * This function should only be called from a foreground thread.
294  */
295  virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner(
296  Isolate* isolate) = 0;
297 
298  /**
299  * Schedules a task to be invoked on a worker thread.
300  */
301  virtual void CallOnWorkerThread(std::unique_ptr<Task> task) = 0;
302 
303  /**
304  * Schedules a task that blocks the main thread to be invoked with
305  * high-priority on a worker thread.
306  */
307  virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr<Task> task) {
308  // Embedders may optionally override this to process these tasks in a high
309  // priority pool.
310  CallOnWorkerThread(std::move(task));
311  }
312 
313  /**
314  * Schedules a task to be invoked on a worker thread after |delay_in_seconds|
315  * expires.
316  */
317  virtual void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
318  double delay_in_seconds) = 0;
319 
320  /**
321  * Schedules a task to be invoked on a foreground thread wrt a specific
322  * |isolate|. Tasks posted for the same isolate should be execute in order of
323  * scheduling. The definition of "foreground" is opaque to V8.
324  */
325  virtual void CallOnForegroundThread(Isolate* isolate, Task* task) = 0;
326 
327  /**
328  * Schedules a task to be invoked on a foreground thread wrt a specific
329  * |isolate| after the given number of seconds |delay_in_seconds|.
330  * Tasks posted for the same isolate should be execute in order of
331  * scheduling. The definition of "foreground" is opaque to V8.
332  */
333  virtual void CallDelayedOnForegroundThread(Isolate* isolate, Task* task,
334  double delay_in_seconds) = 0;
335 
336  /**
337  * Schedules a task to be invoked on a foreground thread wrt a specific
338  * |isolate| when the embedder is idle.
339  * Requires that SupportsIdleTasks(isolate) is true.
340  * Idle tasks may be reordered relative to other task types and may be
341  * starved for an arbitrarily long time if no idle time is available.
342  * The definition of "foreground" is opaque to V8.
343  */
344  virtual void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) {
345  // This must be overriden if |IdleTasksEnabled()|.
346  abort();
347  }
348 
349  /**
350  * Returns true if idle tasks are enabled for the given |isolate|.
351  */
352  virtual bool IdleTasksEnabled(Isolate* isolate) {
353  return false;
354  }
355 
356  /**
357  * Monotonically increasing time in seconds from an arbitrary fixed point in
358  * the past. This function is expected to return at least
359  * millisecond-precision values. For this reason,
360  * it is recommended that the fixed point be no further in the past than
361  * the epoch.
362  **/
363  virtual double MonotonicallyIncreasingTime() = 0;
364 
365  /**
366  * Current wall-clock time in milliseconds since epoch.
367  * This function is expected to return at least millisecond-precision values.
368  */
369  virtual double CurrentClockTimeMillis() = 0;
370 
371  typedef void (*StackTracePrinter)();
372 
373  /**
374  * Returns a function pointer that print a stack trace of the current stack
375  * on invocation. Disables printing of the stack trace if nullptr.
376  */
377  virtual StackTracePrinter GetStackTracePrinter() { return nullptr; }
378 
379  /**
380  * Returns an instance of a v8::TracingController. This must be non-nullptr.
381  */
383 
384  protected:
385  /**
386  * Default implementation of current wall-clock time in milliseconds
387  * since epoch. Useful for implementing |CurrentClockTimeMillis| if
388  * nothing special needed.
389  */
390  static double SystemClockTimeMillis();
391 };
392 
393 } // namespace v8
394 
395 #endif // V8_V8_PLATFORM_H_