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