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 */ 90 class ConvertableToTraceFormat { 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 */ 108 class TracingController { 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 **/ GetCategoryGroupEnabled(const char * name)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 */ 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)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 } 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)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 **/ UpdateTraceEventDuration(const uint8_t * category_enabled_flag,const char * name,uint64_t handle)155 virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, 156 const char* name, uint64_t handle) {} 157 158 class TraceStateObserver { 159 public: 160 virtual ~TraceStateObserver() = default; 161 virtual void OnTraceEnabled() = 0; 162 virtual void OnTraceDisabled() = 0; 163 }; 164 165 /** Adds tracing state change observer. */ AddTraceStateObserver(TraceStateObserver *)166 virtual void AddTraceStateObserver(TraceStateObserver*) {} 167 168 /** Removes tracing state change observer. */ RemoveTraceStateObserver(TraceStateObserver *)169 virtual void RemoveTraceStateObserver(TraceStateObserver*) {} 170 }; 171 172 /** 173 * A V8 memory page allocator. 174 * 175 * Can be implemented by an embedder to manage large host OS allocations. 176 */ 177 class PageAllocator { 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 { 209 kNoAccess, 210 kRead, 211 kReadWrite, 212 // TODO(hpayer): Remove this flag. Memory should never be rwx. 213 kReadWriteExecute, 214 kReadExecute 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 /** 250 * This enum is used to indicate whether a task is potentially long running, 251 * or causes a long wait. The embedder might want to use this hint to decide 252 * whether to execute the task on a dedicated thread. 253 */ 254 enum ExpectedRuntime { 255 kShortRunningTask, 256 kLongRunningTask 257 }; 258 259 virtual ~Platform() = default; 260 261 /** 262 * Allows the embedder to manage memory page allocations. 263 */ GetPageAllocator()264 virtual PageAllocator* GetPageAllocator() { 265 // TODO(bbudge) Make this abstract after all embedders implement this. 266 return nullptr; 267 } 268 269 /** 270 * Enables the embedder to respond in cases where V8 can't allocate large 271 * blocks of memory. V8 retries the failed allocation once after calling this 272 * method. On success, execution continues; otherwise V8 exits with a fatal 273 * error. 274 * Embedder overrides of this function must NOT call back into V8. 275 */ OnCriticalMemoryPressure()276 virtual void OnCriticalMemoryPressure() { 277 // TODO(bbudge) Remove this when embedders override the following method. 278 // See crbug.com/634547. 279 } 280 281 /** 282 * Enables the embedder to respond in cases where V8 can't allocate large 283 * memory regions. The |length| parameter is the amount of memory needed. 284 * Returns true if memory is now available. Returns false if no memory could 285 * be made available. V8 will retry allocations until this method returns 286 * false. 287 * 288 * Embedder overrides of this function must NOT call back into V8. 289 */ OnCriticalMemoryPressure(size_t length)290 virtual bool OnCriticalMemoryPressure(size_t length) { return false; } 291 292 /** 293 * Gets the number of worker threads used by GetWorkerThreadsTaskRunner() and 294 * CallOnWorkerThread(). This can be used to estimate the number of tasks a 295 * work package should be split into. A return value of 0 means that there are 296 * no worker threads available. Note that a value of 0 won't prohibit V8 from 297 * posting tasks using |CallOnWorkerThread|. 298 */ NumberOfWorkerThreads()299 virtual int NumberOfWorkerThreads() { 300 return static_cast<int>(NumberOfAvailableBackgroundThreads()); 301 } 302 303 /** 304 * Deprecated. Use NumberOfWorkerThreads() instead. 305 * TODO(gab): Remove this when all embedders override 306 * NumberOfWorkerThreads() instead. 307 */ 308 V8_DEPRECATE_SOON( 309 "NumberOfAvailableBackgroundThreads() is deprecated, use " 310 "NumberOfAvailableBackgroundThreads() instead.", 311 virtual size_t NumberOfAvailableBackgroundThreads()) { 312 return 0; 313 } 314 315 /** 316 * Returns a TaskRunner which can be used to post a task on the foreground. 317 * This function should only be called from a foreground thread. 318 */ GetForegroundTaskRunner(Isolate * isolate)319 virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner( 320 Isolate* isolate) { 321 // TODO(ahaas): Make this function abstract after it got implemented on all 322 // platforms. 323 return {}; 324 } 325 326 /** 327 * Returns a TaskRunner which can be used to post a task on a background. 328 * This function should only be called from a foreground thread. 329 */ 330 V8_DEPRECATE_SOON( 331 "GetBackgroundTaskRunner() is deprecated, use " 332 "GetWorkerThreadsTaskRunner() " 333 "instead.", 334 virtual std::shared_ptr<v8::TaskRunner> GetBackgroundTaskRunner( 335 Isolate* isolate)) { 336 // TODO(gab): Remove this method when all embedders have moved to 337 // GetWorkerThreadsTaskRunner(). 338 339 // An implementation needs to be provided here because this is called by the 340 // default GetWorkerThreadsTaskRunner() implementation below. In practice 341 // however, all code either: 342 // - Overrides GetWorkerThreadsTaskRunner() (thus not making this call) -- 343 // i.e. all v8 code. 344 // - Overrides this method (thus not making this call) -- i.e. all 345 // unadapted embedders. 346 abort(); 347 } 348 349 /** 350 * Returns a TaskRunner which can be used to post async tasks on a worker. 351 * This function should only be called from a foreground thread. 352 */ GetWorkerThreadsTaskRunner(Isolate * isolate)353 virtual std::shared_ptr<v8::TaskRunner> GetWorkerThreadsTaskRunner( 354 Isolate* isolate) { 355 // TODO(gab): Make this function abstract after it got implemented on all 356 // platforms. 357 return GetBackgroundTaskRunner(isolate); 358 } 359 360 /** 361 * Schedules a task to be invoked on a background thread. |expected_runtime| 362 * indicates that the task will run a long time. The Platform implementation 363 * takes ownership of |task|. There is no guarantee about order of execution 364 * of tasks wrt order of scheduling, nor is there a guarantee about the 365 * thread the task will be run on. 366 */ 367 V8_DEPRECATE_SOON( 368 "ExpectedRuntime is deprecated, use CallOnWorkerThread() instead.", 369 virtual void CallOnBackgroundThread(Task* task, 370 ExpectedRuntime expected_runtime)) { 371 // An implementation needs to be provided here because this is called by the 372 // default implementation below. In practice however, all code either: 373 // - Overrides the new method (thus not making this call) -- i.e. all v8 374 // code. 375 // - Overrides this method (thus not making this call) -- i.e. all 376 // unadapted embedders. 377 abort(); 378 } 379 380 /** 381 * Schedules a task to be invoked on a worker thread. 382 * TODO(gab): Make pure virtual when all embedders override this instead of 383 * CallOnBackgroundThread(). 384 */ CallOnWorkerThread(std::unique_ptr<Task> task)385 virtual void CallOnWorkerThread(std::unique_ptr<Task> task) { 386 CallOnBackgroundThread(task.release(), kShortRunningTask); 387 } 388 389 /** 390 * Schedules a task that blocks the main thread to be invoked with 391 * high-priority on a worker thread. 392 */ CallBlockingTaskOnWorkerThread(std::unique_ptr<Task> task)393 virtual void CallBlockingTaskOnWorkerThread(std::unique_ptr<Task> task) { 394 // Embedders may optionally override this to process these tasks in a high 395 // priority pool. 396 CallOnWorkerThread(std::move(task)); 397 } 398 399 /** 400 * Schedules a task to be invoked on a foreground thread wrt a specific 401 * |isolate|. Tasks posted for the same isolate should be execute in order of 402 * scheduling. The definition of "foreground" is opaque to V8. 403 */ 404 virtual void CallOnForegroundThread(Isolate* isolate, Task* task) = 0; 405 406 /** 407 * Schedules a task to be invoked on a foreground thread wrt a specific 408 * |isolate| after the given number of seconds |delay_in_seconds|. 409 * Tasks posted for the same isolate should be execute in order of 410 * scheduling. The definition of "foreground" is opaque to V8. 411 */ 412 virtual void CallDelayedOnForegroundThread(Isolate* isolate, Task* task, 413 double delay_in_seconds) = 0; 414 415 /** 416 * Schedules a task to be invoked on a foreground thread wrt a specific 417 * |isolate| when the embedder is idle. 418 * Requires that SupportsIdleTasks(isolate) is true. 419 * Idle tasks may be reordered relative to other task types and may be 420 * starved for an arbitrarily long time if no idle time is available. 421 * The definition of "foreground" is opaque to V8. 422 */ CallIdleOnForegroundThread(Isolate * isolate,IdleTask * task)423 virtual void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) { 424 // TODO(ulan): Make this function abstract after V8 roll in Chromium. 425 } 426 427 /** 428 * Returns true if idle tasks are enabled for the given |isolate|. 429 */ IdleTasksEnabled(Isolate * isolate)430 virtual bool IdleTasksEnabled(Isolate* isolate) { 431 // TODO(ulan): Make this function abstract after V8 roll in Chromium. 432 return false; 433 } 434 435 /** 436 * Monotonically increasing time in seconds from an arbitrary fixed point in 437 * the past. This function is expected to return at least 438 * millisecond-precision values. For this reason, 439 * it is recommended that the fixed point be no further in the past than 440 * the epoch. 441 **/ 442 virtual double MonotonicallyIncreasingTime() = 0; 443 444 /** 445 * Current wall-clock time in milliseconds since epoch. 446 * This function is expected to return at least millisecond-precision values. 447 */ 448 virtual double CurrentClockTimeMillis() = 0; 449 450 typedef void (*StackTracePrinter)(); 451 452 /** 453 * Returns a function pointer that print a stack trace of the current stack 454 * on invocation. Disables printing of the stack trace if nullptr. 455 */ GetStackTracePrinter()456 virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } 457 458 /** 459 * Returns an instance of a v8::TracingController. This must be non-nullptr. 460 */ 461 virtual TracingController* GetTracingController() = 0; 462 463 protected: 464 /** 465 * Default implementation of current wall-clock time in milliseconds 466 * since epoch. Useful for implementing |CurrentClockTimeMillis| if 467 * nothing special needed. 468 */ 469 static double SystemClockTimeMillis(); 470 }; 471 472 } // namespace v8 473 474 #endif // V8_V8_PLATFORM_H_ 475