diff --git a/android/libnode/bin/armeabi-v7a/libnode.so b/android/libnode/bin/armeabi-v7a/libnode.so index 397ce2d..ff2b327 100755 Binary files a/android/libnode/bin/armeabi-v7a/libnode.so and b/android/libnode/bin/armeabi-v7a/libnode.so differ diff --git a/android/libnode/bin/x86/libnode.so b/android/libnode/bin/x86/libnode.so index 8e79531..6df0f52 100755 Binary files a/android/libnode/bin/x86/libnode.so and b/android/libnode/bin/x86/libnode.so differ diff --git a/android/libnode/include/node/config.gypi b/android/libnode/include/node/config.gypi index 0a4a590..5906c9d 100644 --- a/android/libnode/include/node/config.gypi +++ b/android/libnode/include/node/config.gypi @@ -57,7 +57,6 @@ 'v8_promise_internal_field_count': 1, 'v8_random_seed': 0, 'v8_trace_maps': 0, - 'v8_use_snapshot': 'false', + 'v8_use_snapshot': 'true', 'want_separate_host_toolset': 0, - 'want_separate_host_toolset_mkpeephole': 0, 'xcode_version': '7.0'}} diff --git a/android/libnode/include/node/libplatform/libplatform.h b/android/libnode/include/node/libplatform/libplatform.h index e945045..b615088 100644 --- a/android/libnode/include/node/libplatform/libplatform.h +++ b/android/libnode/include/node/libplatform/libplatform.h @@ -30,12 +30,15 @@ enum class MessageLoopBehavior : bool { * If |idle_task_support| is enabled then the platform will accept idle * tasks (IdleTasksEnabled will return true) and will rely on the embedder * calling v8::platform::RunIdleTasks to process the idle tasks. + * If |tracing_controller| is nullptr, the default platform will create a + * v8::platform::TracingController instance and use it. */ V8_PLATFORM_EXPORT v8::Platform* CreateDefaultPlatform( int thread_pool_size = 0, IdleTaskSupport idle_task_support = IdleTaskSupport::kDisabled, InProcessStackDumping in_process_stack_dumping = - InProcessStackDumping::kEnabled); + InProcessStackDumping::kEnabled, + v8::TracingController* tracing_controller = nullptr); /** * Pumps the message loop for the given isolate. @@ -67,6 +70,8 @@ V8_PLATFORM_EXPORT void RunIdleTasks(v8::Platform* platform, * Attempts to set the tracing controller for the given platform. * * The |platform| has to be created using |CreateDefaultPlatform|. + * + * DEPRECATED: Will be removed soon. */ V8_PLATFORM_EXPORT void SetTracingController( v8::Platform* platform, diff --git a/android/libnode/include/node/libplatform/v8-tracing.h b/android/libnode/include/node/libplatform/v8-tracing.h index 902f8ea..8c1febf 100644 --- a/android/libnode/include/node/libplatform/v8-tracing.h +++ b/android/libnode/include/node/libplatform/v8-tracing.h @@ -209,7 +209,15 @@ class V8_PLATFORM_EXPORT TraceConfig { void operator=(const TraceConfig&) = delete; }; -class V8_PLATFORM_EXPORT TracingController { +#if defined(_MSC_VER) +#define V8_PLATFORM_NON_EXPORTED_BASE(code) \ + __pragma(warning(suppress : 4275)) code +#else +#define V8_PLATFORM_NON_EXPORTED_BASE(code) code +#endif // defined(_MSC_VER) + +class V8_PLATFORM_EXPORT TracingController + : public V8_PLATFORM_NON_EXPORTED_BASE(v8::TracingController) { public: enum Mode { DISABLED = 0, RECORDING_MODE }; @@ -227,25 +235,29 @@ class V8_PLATFORM_EXPORT TracingController { }; TracingController(); - ~TracingController(); + ~TracingController() override; void Initialize(TraceBuffer* trace_buffer); - const uint8_t* GetCategoryGroupEnabled(const char* category_group); - static const char* GetCategoryGroupName(const uint8_t* category_enabled_flag); + + // v8::TracingController implementation. + const uint8_t* GetCategoryGroupEnabled(const char* category_group) override; 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* arg_convertables, - unsigned int flags); + unsigned int flags) override; void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, - const char* name, uint64_t handle); + const char* name, uint64_t handle) override; + void AddTraceStateObserver( + v8::TracingController::TraceStateObserver* observer) override; + void RemoveTraceStateObserver( + v8::TracingController::TraceStateObserver* observer) override; void StartTracing(TraceConfig* trace_config); void StopTracing(); - void AddTraceStateObserver(Platform::TraceStateObserver* observer); - void RemoveTraceStateObserver(Platform::TraceStateObserver* observer); + static const char* GetCategoryGroupName(const uint8_t* category_enabled_flag); private: const uint8_t* GetCategoryGroupEnabledInternal(const char* category_group); @@ -255,7 +267,7 @@ class V8_PLATFORM_EXPORT TracingController { std::unique_ptr trace_buffer_; std::unique_ptr trace_config_; std::unique_ptr mutex_; - std::unordered_set observers_; + std::unordered_set observers_; Mode mode_ = DISABLED; // Disallow copy and assign @@ -263,6 +275,8 @@ class V8_PLATFORM_EXPORT TracingController { void operator=(const TracingController&) = delete; }; +#undef V8_PLATFORM_NON_EXPORTED_BASE + } // namespace tracing } // namespace platform } // namespace v8 diff --git a/android/libnode/include/node/node.h b/android/libnode/include/node/node.h index 269abdf..e7a59b2 100644 --- a/android/libnode/include/node/node.h +++ b/android/libnode/include/node/node.h @@ -169,10 +169,6 @@ NODE_EXTERN v8::Local MakeCallback( } // namespace node -#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" -#endif - #include #include @@ -595,10 +591,45 @@ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, const char* name, async_id trigger_async_id = -1); +NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1); + /* Emit the destroy() callback. */ NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, async_context asyncContext); +class InternalCallbackScope; + +/* This class works like `MakeCallback()` in that it sets up a specific + * asyncContext as the current one and informs the async_hooks and domains + * modules that this context is currently active. + * + * `MakeCallback()` is a wrapper around this class as well as + * `Function::Call()`. Either one of these mechanisms needs to be used for + * top-level calls into JavaScript (i.e. without any existing JS stack). + * + * This object should be stack-allocated to ensure that it is contained in a + * valid HandleScope. + */ +class NODE_EXTERN CallbackScope { + public: + CallbackScope(v8::Isolate* isolate, + v8::Local resource, + async_context asyncContext); + ~CallbackScope(); + + private: + InternalCallbackScope* private_; + v8::TryCatch try_catch_; + + void operator=(const CallbackScope&) = delete; + void operator=(CallbackScope&&) = delete; + CallbackScope(const CallbackScope&) = delete; + CallbackScope(CallbackScope&&) = delete; +}; + /* An API specific to emit before/after callbacks is unnecessary because * MakeCallback will automatically call them for you. * @@ -676,6 +707,16 @@ class AsyncResource { trigger_async_id); } + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1) + : isolate_(isolate), + resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, + trigger_async_id); + } + ~AsyncResource() { EmitAsyncDestroy(isolate_, async_context_); } @@ -724,6 +765,16 @@ class AsyncResource { async_id get_trigger_async_id() const { return async_context_.trigger_async_id; } + + protected: + class CallbackScope : public node::CallbackScope { + public: + explicit CallbackScope(AsyncResource* res) + : node::CallbackScope(res->isolate_, + res->resource_.Get(res->isolate_), + res->async_context_) {} + }; + private: v8::Isolate* isolate_; v8::Persistent resource_; diff --git a/android/libnode/include/node/node_api.h b/android/libnode/include/node/node_api.h index 0cf0ba0..a3a07a6 100644 --- a/android/libnode/include/node/node_api.h +++ b/android/libnode/include/node/node_api.h @@ -44,10 +44,8 @@ #endif -typedef void (*napi_addon_register_func)(napi_env env, - napi_value exports, - napi_value module, - void* priv); +typedef napi_value (*napi_addon_register_func)(napi_env env, + napi_value exports); typedef struct { int nm_version; @@ -102,6 +100,8 @@ typedef struct { #define NAPI_MODULE(modname, regfunc) \ NAPI_MODULE_X(modname, regfunc, NULL, 0) +#define NAPI_AUTO_LENGTH SIZE_MAX + EXTERN_C_START NAPI_EXTERN void napi_module_register(napi_module* mod); @@ -111,7 +111,9 @@ napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, - const char* message); + size_t location_len, + const char* message, + size_t message_len); // Getters for defined singletons NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); @@ -156,6 +158,7 @@ NAPI_EXTERN napi_status napi_create_symbol(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_create_function(napi_env env, const char* utf8name, + size_t length, napi_callback cb, void* data, napi_value* result); @@ -320,14 +323,6 @@ NAPI_EXTERN napi_status napi_instanceof(napi_env env, napi_value constructor, bool* result); -// Napi version of node::MakeCallback(...) -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); - // Methods to work with napi_callbacks // Gets all callback info in a single call. (Ugly, but faster.) @@ -340,12 +335,13 @@ NAPI_EXTERN napi_status napi_get_cb_info( napi_value* this_arg, // [out] Receives the JS 'this' arg for the call void** data); // [out] Receives the data pointer for the callback. -NAPI_EXTERN napi_status napi_is_construct_call(napi_env env, - napi_callback_info cbinfo, - bool* result); +NAPI_EXTERN napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result); NAPI_EXTERN napi_status napi_define_class(napi_env env, const char* utf8name, + size_t length, napi_callback constructor, void* data, size_t property_count, @@ -362,6 +358,9 @@ NAPI_EXTERN napi_status napi_wrap(napi_env env, NAPI_EXTERN napi_status napi_unwrap(napi_env env, napi_value js_object, void** result); +NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, + napi_value js_object, + void** result); NAPI_EXTERN napi_status napi_create_external(napi_env env, void* data, napi_finalize finalize_cb, @@ -521,6 +520,8 @@ NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, // Methods to manage simple async operations NAPI_EXTERN napi_status napi_create_async_work(napi_env env, + napi_value async_resource, + napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, @@ -532,6 +533,22 @@ NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, napi_async_work work); +// Methods for custom handling of async operations +NAPI_EXTERN napi_status napi_async_init(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result); + +NAPI_EXTERN napi_status napi_async_destroy(napi_env env, + napi_async_context async_context); + +NAPI_EXTERN napi_status napi_make_callback(napi_env env, + napi_async_context async_context, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result); // version management NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); @@ -540,6 +557,30 @@ NAPI_EXTERN napi_status napi_get_node_version(napi_env env, const napi_node_version** version); +// Promises +NAPI_EXTERN napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise); +NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution); +NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value rejection); +NAPI_EXTERN napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise); + +// Memory management +NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, + int64_t change_in_bytes, + int64_t* adjusted_value); + +// Runnig a script +NAPI_EXTERN napi_status napi_run_script(napi_env env, + napi_value script, + napi_value* result); + EXTERN_C_END #endif // SRC_NODE_API_H_ diff --git a/android/libnode/include/node/node_api_types.h b/android/libnode/include/node/node_api_types.h index 0bdc377..574cb6f 100644 --- a/android/libnode/include/node/node_api_types.h +++ b/android/libnode/include/node/node_api_types.h @@ -16,7 +16,9 @@ typedef struct napi_ref__ *napi_ref; typedef struct napi_handle_scope__ *napi_handle_scope; typedef struct napi_escapable_handle_scope__ *napi_escapable_handle_scope; typedef struct napi_callback_info__ *napi_callback_info; +typedef struct napi_async_context__ *napi_async_context; typedef struct napi_async_work__ *napi_async_work; +typedef struct napi_deferred__ *napi_deferred; typedef enum { napi_default = 0, diff --git a/android/libnode/include/node/node_version.h b/android/libnode/include/node/node_version.h index 8683a98..4605e38 100644 --- a/android/libnode/include/node/node_version.h +++ b/android/libnode/include/node/node_version.h @@ -23,7 +23,7 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 8 -#define NODE_MINOR_VERSION 4 +#define NODE_MINOR_VERSION 6 #define NODE_PATCH_VERSION 0 #define NODE_VERSION_IS_RELEASE 1 diff --git a/android/libnode/include/node/openssl/opensslconf.h b/android/libnode/include/node/openssl/opensslconf.h index 9b20fb6..1c89bab 100644 --- a/android/libnode/include/node/openssl/opensslconf.h +++ b/android/libnode/include/node/openssl/opensslconf.h @@ -37,6 +37,8 @@ | solaris | x64 | solaris64-x86_64-gcc | o | | freebsd | ia32 | BSD-x86 | o | | freebsd | x64 | BSD-x86_64 | o | + | netbsd | ia32 | BSD-x86 | o | + | netbsd | x64 | BSD-x86_64 | o | | openbsd | ia32 | BSD-x86 | - | | openbsd | x64 | BSD-x86_64 | - | | others | others | linux-elf | - | @@ -51,6 +53,7 @@ | mac | __APPLE__ && __MACH__ | | solaris | __sun | | freebsd | __FreeBSD__ | + | netbsd | __NetBSD__ | | openbsd | __OpenBSD__ | | linux (not andorid)| __linux__ && !__ANDROID__ | | android | __ANDROID__ | @@ -94,6 +97,11 @@ # define OPENSSL_LINUX 1 #endif +#undef OPENSSL_BSD +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) +# define OPENSSL_BSD 1 +#endif + #if defined(OPENSSL_LINUX) && defined(__i386__) # include "./archs/linux-elf/opensslconf.h" #elif defined(OPENSSL_LINUX) && defined(__ILP32__) @@ -112,9 +120,9 @@ # include "./archs/VC-WIN32/opensslconf.h" #elif defined(_WIN32) && defined(_M_X64) # include "./archs/VC-WIN64A/opensslconf.h" -#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__i386__) +#elif defined(OPENSSL_BSD) && defined(__i386__) # include "./archs/BSD-x86/opensslconf.h" -#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__x86_64__) +#elif defined(OPENSSL_BSD) && defined(__x86_64__) # include "./archs/BSD-x86_64/opensslconf.h" #elif defined(__sun) && defined(__i386__) # include "./archs/solaris-x86-gcc/opensslconf.h" diff --git a/android/libnode/include/node/pthread-barrier.h b/android/libnode/include/node/pthread-barrier.h index 900ebed..07db9b8 100644 --- a/android/libnode/include/node/pthread-barrier.h +++ b/android/libnode/include/node/pthread-barrier.h @@ -23,6 +23,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #endif #define PTHREAD_BARRIER_SERIAL_THREAD 0x12345 +#define UV__PTHREAD_BARRIER_FALLBACK 1 /* * To maintain ABI compatibility with diff --git a/android/libnode/include/node/uv-errno.h b/android/libnode/include/node/uv-errno.h index f137151..32bbc51 100644 --- a/android/libnode/include/node/uv-errno.h +++ b/android/libnode/include/node/uv-errno.h @@ -416,4 +416,10 @@ # define UV__EHOSTDOWN (-4031) #endif +#if defined(EREMOTEIO) && !defined(_WIN32) +# define UV__EREMOTEIO (-EREMOTEIO) +#else +# define UV__EREMOTEIO (-4030) +#endif + #endif /* UV_ERRNO_H_ */ diff --git a/android/libnode/include/node/uv-version.h b/android/libnode/include/node/uv-version.h index c80c40e..9b89149 100644 --- a/android/libnode/include/node/uv-version.h +++ b/android/libnode/include/node/uv-version.h @@ -31,7 +31,7 @@ */ #define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 13 +#define UV_VERSION_MINOR 14 #define UV_VERSION_PATCH 1 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/android/libnode/include/node/uv.h b/android/libnode/include/node/uv.h index f076094..eac63dd 100644 --- a/android/libnode/include/node/uv.h +++ b/android/libnode/include/node/uv.h @@ -140,6 +140,7 @@ extern "C" { XX(ENXIO, "no such device or address") \ XX(EMLINK, "too many links") \ XX(EHOSTDOWN, "host is down") \ + XX(EREMOTEIO, "remote I/O error") \ #define UV_HANDLE_TYPE_MAP(XX) \ XX(ASYNC, async) \ @@ -719,7 +720,8 @@ struct uv_poll_s { enum uv_poll_event { UV_READABLE = 1, UV_WRITABLE = 2, - UV_DISCONNECT = 4 + UV_DISCONNECT = 4, + UV_PRIORITIZED = 8 }; UV_EXTERN int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd); @@ -1112,7 +1114,8 @@ typedef enum { UV_FS_READLINK, UV_FS_CHOWN, UV_FS_FCHOWN, - UV_FS_REALPATH + UV_FS_REALPATH, + UV_FS_COPYFILE } uv_fs_type; /* uv_fs_t is a subclass of uv_req_t. */ @@ -1157,6 +1160,18 @@ UV_EXTERN int uv_fs_write(uv_loop_t* loop, unsigned int nbufs, int64_t offset, uv_fs_cb cb); +/* + * This flag can be used with uv_fs_copyfile() to return an error if the + * destination already exists. + */ +#define UV_FS_COPYFILE_EXCL 0x0001 + +UV_EXTERN int uv_fs_copyfile(uv_loop_t* loop, + uv_fs_t* req, + const char* path, + const char* new_path, + int flags, + uv_fs_cb cb); UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, diff --git a/android/libnode/include/node/v8-platform.h b/android/libnode/include/node/v8-platform.h index 8f6d804..3df78a8 100644 --- a/android/libnode/include/node/v8-platform.h +++ b/android/libnode/include/node/v8-platform.h @@ -52,6 +52,66 @@ class ConvertableToTraceFormat { virtual void AppendAsTraceFormat(std::string* out) const = 0; }; +/** + * V8 Tracing controller. + * + * Can be implemented by an embedder to record trace events from V8. + */ +class TracingController { + public: + virtual ~TracingController() = default; + + /** + * Called by TRACE_EVENT* macros, don't call this directly. + * The name parameter is a category group for example: + * TRACE_EVENT0("v8,parse", "V8.Parse") + * The pointer returned points to a value with zero or more of the bits + * defined in CategoryGroupEnabledFlags. + **/ + virtual const uint8_t* GetCategoryGroupEnabled(const char* name) { + static uint8_t no = 0; + return &no; + } + + /** + * Adds a trace event to the platform tracing system. This function call is + * usually the result of a TRACE_* macro from trace_event_common.h when + * tracing and the category of the particular trace are enabled. It is not + * advisable to call this function on its own; it is really only meant to be + * used by the trace macros. The returned handle can be used by + * UpdateTraceEventDuration to update the duration of COMPLETE events. + */ + 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* arg_convertables, + unsigned int flags) { + return 0; + } + + /** + * Sets the duration field of a COMPLETE trace event. It must be called with + * the handle returned from AddTraceEvent(). + **/ + virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, + const char* name, uint64_t handle) {} + + class TraceStateObserver { + public: + virtual ~TraceStateObserver() = default; + virtual void OnTraceEnabled() = 0; + virtual void OnTraceDisabled() = 0; + }; + + /** Adds tracing state change observer. */ + virtual void AddTraceStateObserver(TraceStateObserver*) {} + + /** Removes tracing state change observer. */ + virtual void RemoveTraceStateObserver(TraceStateObserver*) {} +}; + /** * V8 Platform abstraction layer. * @@ -135,6 +195,20 @@ class Platform { * the epoch. **/ virtual double MonotonicallyIncreasingTime() = 0; + typedef void (*StackTracePrinter)(); + + /** + * Returns a function pointer that print a stack trace of the current stack + * on invocation. Disables printing of the stack trace if nullptr. + */ + virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } + + /** + * Returns an instance of a v8::TracingController. This must be non-nullptr. + */ + virtual TracingController* GetTracingController() = 0; + + // DEPRECATED methods, use TracingController interface instead. /** * Called by TRACE_EVENT* macros, don't call this directly. @@ -200,26 +274,13 @@ class Platform { virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, const char* name, uint64_t handle) {} - class TraceStateObserver { - public: - virtual ~TraceStateObserver() = default; - virtual void OnTraceEnabled() = 0; - virtual void OnTraceDisabled() = 0; - }; + typedef v8::TracingController::TraceStateObserver TraceStateObserver; /** Adds tracing state change observer. */ virtual void AddTraceStateObserver(TraceStateObserver*) {} /** Removes tracing state change observer. */ virtual void RemoveTraceStateObserver(TraceStateObserver*) {} - - typedef void (*StackTracePrinter)(); - - /** - * Returns a function pointer that print a stack trace of the current stack - * on invocation. Disables printing of the stack trace if nullptr. - */ - virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } }; } // namespace v8 diff --git a/android/libnode/include/node/v8-version.h b/android/libnode/include/node/v8-version.h index 0889459..db9369f 100644 --- a/android/libnode/include/node/v8-version.h +++ b/android/libnode/include/node/v8-version.h @@ -10,8 +10,8 @@ // system so their names cannot be changed without changing the scripts. #define V8_MAJOR_VERSION 6 #define V8_MINOR_VERSION 0 -#define V8_BUILD_NUMBER 286 -#define V8_PATCH_LEVEL 52 +#define V8_BUILD_NUMBER 287 +#define V8_PATCH_LEVEL 53 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/android/src/main/cpp/rn-bridge.cpp b/android/src/main/cpp/rn-bridge.cpp index d7e2bb2..52410f8 100644 --- a/android/src/main/cpp/rn-bridge.cpp +++ b/android/src/main/cpp/rn-bridge.cpp @@ -232,13 +232,14 @@ napi_value Method_SendMessage(napi_env env, napi_callback_info info) { #define DECLARE_NAPI_METHOD(name, func) \ { name, 0, func, 0, 0, 0, napi_default, 0 } -void Init(napi_env env, napi_value exports, napi_value module, void* priv) { +napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor properties[] = { DECLARE_NAPI_METHOD("sendMessage", Method_SendMessage), DECLARE_NAPI_METHOD("registerListener", Method_RegisterListener), }; - status = napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties); + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); + return exports; } void rn_bridge_notify(const char *message) { diff --git a/ios/libnode.framework/Info.plist b/ios/libnode.framework/Info.plist index e93adca..3020901 100644 Binary files a/ios/libnode.framework/Info.plist and b/ios/libnode.framework/Info.plist differ diff --git a/ios/libnode.framework/libnode b/ios/libnode.framework/libnode index 29d8f14..5c0cbeb 100755 Binary files a/ios/libnode.framework/libnode and b/ios/libnode.framework/libnode differ diff --git a/ios/libnode/include/node/ChakraCommon.h b/ios/libnode/include/node/ChakraCommon.h new file mode 100644 index 0000000..74918b9 --- /dev/null +++ b/ios/libnode/include/node/ChakraCommon.h @@ -0,0 +1,2389 @@ +//------------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. +//------------------------------------------------------------------------------------------------------- +/// \mainpage Chakra Hosting API Reference +/// +/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can +/// also be hosted independently by other applications. This reference describes the APIs available +/// to applications to host Chakra. +/// +/// This file contains the common API set shared among all Chakra releases. For Windows-specific +/// releases, see chakrart.h. + +/// \file +/// \brief The base Chakra hosting API. +/// +/// This file contains a flat C API layer. This is the API exported by chakra.dll. + +#ifdef _MSC_VER +#pragma once +#endif // _MSC_VER + +#ifndef _CHAKRACOMMON_H_ +#define _CHAKRACOMMON_H_ + +// Platform specific code +#if defined(_WIN32) && defined(_MSC_VER) +#include + +// Header macros +#define CHAKRA_CALLBACK CALLBACK +#define CHAKRA_API STDAPI_(JsErrorCode) + +typedef DWORD_PTR ChakraCookie; +typedef BYTE* ChakraBytePtr; +#else // Non-Windows VC++ + +// SAL compat +#define _Return_type_success_(x) +#define _In_ +#define _In_z_ +#define _In_opt_ +#define _Inout_ +#define _Out_ +#define _Out_opt_ +#define _In_reads_(x) +#define _Pre_maybenull_ +#define _Pre_writable_byte_size_(byteLength) +#define _Outptr_result_buffer_(byteLength) +#define _Outptr_result_bytebuffer_(byteLength) +#define _Outptr_result_maybenull_ +#define _Outptr_result_z_ +#define _Ret_maybenull_ +#define _Out_writes_(size) +#define _Out_writes_to_opt_(byteLength, byteLength2) + +// Header macros +#ifdef __i386___ +#define CHAKRA_CALLBACK __attribute__((cdecl)) +#else // non-32 bit x86 doesn't have cdecl support +#define CHAKRA_CALLBACK +#endif // __i386__ + +#ifndef _WIN32 +#define SET_API_VISIBILITY __attribute__((visibility("default"))) +#else +#define SET_API_VISIBILITY +#endif + +#ifdef __cplusplus +#define CHAKRA_API extern "C" SET_API_VISIBILITY JsErrorCode +#else +#define CHAKRA_API extern SET_API_VISIBILITY JsErrorCode +#include +#endif + +#include // for size_t +#include // for uintptr_t +typedef uintptr_t ChakraCookie; +typedef unsigned char* ChakraBytePtr; + +// xplat-todo: try reduce usage of following types +#if !defined(__MSTYPES_DEFINED) +typedef uint32_t UINT32; +typedef int64_t INT64; +typedef void* HANDLE; +typedef unsigned char BYTE; +typedef BYTE byte; +typedef UINT32 DWORD; +typedef unsigned short WCHAR; +#endif + +#endif // defined(_WIN32) && defined(_MSC_VER) + +#if (defined(_MSC_VER) && _MSC_VER <= 1900) || (!defined(_MSC_VER) && __cplusplus <= 199711L) // !C++11 +typedef unsigned short uint16_t; +#endif + + /// + /// An error code returned from a Chakra hosting API. + /// + typedef _Return_type_success_(return == 0) enum _JsErrorCode + { + /// + /// Success error code. + /// + JsNoError = 0, + + /// + /// Category of errors that relates to incorrect usage of the API itself. + /// + JsErrorCategoryUsage = 0x10000, + /// + /// An argument to a hosting API was invalid. + /// + JsErrorInvalidArgument, + /// + /// An argument to a hosting API was null in a context where null is not allowed. + /// + JsErrorNullArgument, + /// + /// The hosting API requires that a context be current, but there is no current context. + /// + JsErrorNoCurrentContext, + /// + /// The engine is in an exception state and no APIs can be called until the exception is + /// cleared. + /// + JsErrorInExceptionState, + /// + /// A hosting API is not yet implemented. + /// + JsErrorNotImplemented, + /// + /// A hosting API was called on the wrong thread. + /// + JsErrorWrongThread, + /// + /// A runtime that is still in use cannot be disposed. + /// + JsErrorRuntimeInUse, + /// + /// A bad serialized script was used, or the serialized script was serialized by a + /// different version of the Chakra engine. + /// + JsErrorBadSerializedScript, + /// + /// The runtime is in a disabled state. + /// + JsErrorInDisabledState, + /// + /// Runtime does not support reliable script interruption. + /// + JsErrorCannotDisableExecution, + /// + /// A heap enumeration is currently underway in the script context. + /// + JsErrorHeapEnumInProgress, + /// + /// A hosting API that operates on object values was called with a non-object value. + /// + JsErrorArgumentNotObject, + /// + /// A script context is in the middle of a profile callback. + /// + JsErrorInProfileCallback, + /// + /// A thread service callback is currently underway. + /// + JsErrorInThreadServiceCallback, + /// + /// Scripts cannot be serialized in debug contexts. + /// + JsErrorCannotSerializeDebugScript, + /// + /// The context cannot be put into a debug state because it is already in a debug state. + /// + JsErrorAlreadyDebuggingContext, + /// + /// The context cannot start profiling because it is already profiling. + /// + JsErrorAlreadyProfilingContext, + /// + /// Idle notification given when the host did not enable idle processing. + /// + JsErrorIdleNotEnabled, + /// + /// The context did not accept the enqueue callback. + /// + JsCannotSetProjectionEnqueueCallback, + /// + /// Failed to start projection. + /// + JsErrorCannotStartProjection, + /// + /// The operation is not supported in an object before collect callback. + /// + JsErrorInObjectBeforeCollectCallback, + /// + /// Object cannot be unwrapped to IInspectable pointer. + /// + JsErrorObjectNotInspectable, + /// + /// A hosting API that operates on symbol property ids but was called with a non-symbol property id. + /// The error code is returned by JsGetSymbolFromPropertyId if the function is called with non-symbol property id. + /// + JsErrorPropertyNotSymbol, + /// + /// A hosting API that operates on string property ids but was called with a non-string property id. + /// The error code is returned by existing JsGetPropertyNamefromId if the function is called with non-string property id. + /// + JsErrorPropertyNotString, + /// + /// Module evaulation is called in wrong context. + /// + JsErrorInvalidContext, + /// + /// Module evaulation is called in wrong context. + /// + JsInvalidModuleHostInfoKind, + /// + /// Module was parsed already when JsParseModuleSource is called. + /// + JsErrorModuleParsed, + /// + /// Category of errors that relates to errors occurring within the engine itself. + /// + JsErrorCategoryEngine = 0x20000, + /// + /// The Chakra engine has run out of memory. + /// + JsErrorOutOfMemory, + /// + /// The Chakra engine failed to set the Floating Point Unit state. + /// + JsErrorBadFPUState, + + /// + /// Category of errors that relates to errors in a script. + /// + JsErrorCategoryScript = 0x30000, + /// + /// A JavaScript exception occurred while running a script. + /// + JsErrorScriptException, + /// + /// JavaScript failed to compile. + /// + JsErrorScriptCompile, + /// + /// A script was terminated due to a request to suspend a runtime. + /// + JsErrorScriptTerminated, + /// + /// A script was terminated because it tried to use eval or function and eval + /// was disabled. + /// + JsErrorScriptEvalDisabled, + + /// + /// Category of errors that are fatal and signify failure of the engine. + /// + JsErrorCategoryFatal = 0x40000, + /// + /// A fatal error in the engine has occurred. + /// + JsErrorFatal, + /// + /// A hosting API was called with object created on different javascript runtime. + /// + JsErrorWrongRuntime, + + /// + /// Category of errors that are related to failures during diagnostic operations. + /// + JsErrorCategoryDiagError = 0x50000, + /// + /// The object for which the debugging API was called was not found + /// + JsErrorDiagAlreadyInDebugMode, + /// + /// The debugging API can only be called when VM is in debug mode + /// + JsErrorDiagNotInDebugMode, + /// + /// The debugging API can only be called when VM is at a break + /// + JsErrorDiagNotAtBreak, + /// + /// Debugging API was called with an invalid handle. + /// + JsErrorDiagInvalidHandle, + /// + /// The object for which the debugging API was called was not found + /// + JsErrorDiagObjectNotFound, + /// + /// VM was unable to perfom the request action + /// + JsErrorDiagUnableToPerformAction, + } JsErrorCode; + + /// + /// A handle to a Chakra runtime. + /// + /// + /// + /// Each Chakra runtime has its own independent execution engine, JIT compiler, and garbage + /// collected heap. As such, each runtime is completely isolated from other runtimes. + /// + /// + /// Runtimes can be used on any thread, but only one thread can call into a runtime at any + /// time. + /// + /// + /// NOTE: A JsRuntimeHandle, unlike other object references in the Chakra hosting API, + /// is not garbage collected since it contains the garbage collected heap itself. A runtime + /// will continue to exist until JsDisposeRuntime is called. + /// + /// + typedef void *JsRuntimeHandle; + + /// + /// An invalid runtime handle. + /// +#ifdef __cplusplus + const JsRuntimeHandle JS_INVALID_RUNTIME_HANDLE = 0; +#else + #define JS_INVALID_RUNTIME_HANDLE (JsRuntimeHandle)0 +#endif + + /// + /// A reference to an object owned by the Chakra garbage collector. + /// + /// + /// A Chakra runtime will automatically track JsRef references as long as they are + /// stored in local variables or in parameters (i.e. on the stack). Storing a JsRef + /// somewhere other than on the stack requires calling JsAddRef and JsRelease to + /// manage the lifetime of the object, otherwise the garbage collector may free the object + /// while it is still in use. + /// + typedef void *JsRef; + + /// + /// An invalid reference. + /// +#ifdef __cplusplus + const JsRef JS_INVALID_REFERENCE = 0; +#else + #define JS_INVALID_REFERENCE (JsRef)0 +#endif + + /// + /// A reference to a script context. + /// + /// + /// + /// Each script context contains its own global object, distinct from the global object in + /// other script contexts. + /// + /// + /// Many Chakra hosting APIs require an "active" script context, which can be set using + /// JsSetCurrentContext. Chakra hosting APIs that require a current context to be set + /// will note that explicitly in their documentation. + /// + /// + typedef JsRef JsContextRef; + + /// + /// A reference to a JavaScript value. + /// + /// + /// A JavaScript value is one of the following types of values: undefined, null, Boolean, + /// string, number, or object. + /// + typedef JsRef JsValueRef; + + /// + /// A cookie that identifies a script for debugging purposes. + /// + typedef ChakraCookie JsSourceContext; + + /// + /// An empty source context. + /// +#ifdef __cplusplus + const JsSourceContext JS_SOURCE_CONTEXT_NONE = (JsSourceContext)-1; +#else + #define JS_SOURCE_CONTEXT_NONE (JsSourceContext)-1 +#endif + + /// + /// A property identifier. + /// + /// + /// Property identifiers are used to refer to properties of JavaScript objects instead of using + /// strings. + /// + typedef JsRef JsPropertyIdRef; + + /// + /// Attributes of a runtime. + /// + typedef enum _JsRuntimeAttributes + { + /// + /// No special attributes. + /// + JsRuntimeAttributeNone = 0x00000000, + /// + /// The runtime will not do any work (such as garbage collection) on background threads. + /// + JsRuntimeAttributeDisableBackgroundWork = 0x00000001, + /// + /// The runtime should support reliable script interruption. This increases the number of + /// places where the runtime will check for a script interrupt request at the cost of a + /// small amount of runtime performance. + /// + JsRuntimeAttributeAllowScriptInterrupt = 0x00000002, + /// + /// Host will call JsIdle, so enable idle processing. Otherwise, the runtime will + /// manage memory slightly more aggressively. + /// + JsRuntimeAttributeEnableIdleProcessing = 0x00000004, + /// + /// Runtime will not generate native code. + /// + JsRuntimeAttributeDisableNativeCodeGeneration = 0x00000008, + /// + /// Using eval or function constructor will throw an exception. + /// + JsRuntimeAttributeDisableEval = 0x00000010, + /// + /// Runtime will enable all experimental features. + /// + JsRuntimeAttributeEnableExperimentalFeatures = 0x00000020, + /// + /// Calling JsSetException will also dispatch the exception to the script debugger + /// (if any) giving the debugger a chance to break on the exception. + /// + JsRuntimeAttributeDispatchSetExceptionsToDebugger = 0x00000040 + } JsRuntimeAttributes; + + /// + /// The type of a typed JavaScript array. + /// + typedef enum _JsTypedArrayType + { + /// + /// An int8 array. + /// + JsArrayTypeInt8, + /// + /// An uint8 array. + /// + JsArrayTypeUint8, + /// + /// An uint8 clamped array. + /// + JsArrayTypeUint8Clamped, + /// + /// An int16 array. + /// + JsArrayTypeInt16, + /// + /// An uint16 array. + /// + JsArrayTypeUint16, + /// + /// An int32 array. + /// + JsArrayTypeInt32, + /// + /// An uint32 array. + /// + JsArrayTypeUint32, + /// + /// A float32 array. + /// + JsArrayTypeFloat32, + /// + /// A float64 array. + /// + JsArrayTypeFloat64 + } JsTypedArrayType; + + /// + /// Allocation callback event type. + /// + typedef enum _JsMemoryEventType + { + /// + /// Indicates a request for memory allocation. + /// + JsMemoryAllocate = 0, + /// + /// Indicates a memory freeing event. + /// + JsMemoryFree = 1, + /// + /// Indicates a failed allocation event. + /// + JsMemoryFailure = 2 + } JsMemoryEventType; + + /// + /// Attribute mask for JsParseScriptWithAttributes + /// + typedef enum _JsParseScriptAttributes { + /// + /// Default attribute + /// + JsParseScriptAttributeNone = 0x0, + /// + /// Specified script is internal and non-user code. Hidden from debugger + /// + JsParseScriptAttributeLibraryCode = 0x1, + /// + /// ChakraCore assumes ExternalArrayBuffer is Utf8 by default. + /// This one needs to be set for Utf16 + /// + JsParseScriptAttributeArrayBufferIsUtf16Encoded = 0x2, + } JsParseScriptAttributes; + + /// + /// Type enumeration of a JavaScript property + /// + typedef enum _JsPropertyIdType { + /// + /// Type enumeration of a JavaScript string property + /// + JsPropertyIdTypeString, + /// + /// Type enumeration of a JavaScript symbol property + /// + JsPropertyIdTypeSymbol + } JsPropertyIdType; + + /// + /// The JavaScript type of a JsValueRef. + /// + typedef enum _JsValueType + { + /// + /// The value is the undefined value. + /// + JsUndefined = 0, + /// + /// The value is the null value. + /// + JsNull = 1, + /// + /// The value is a JavaScript number value. + /// + JsNumber = 2, + /// + /// The value is a JavaScript string value. + /// + JsString = 3, + /// + /// The value is a JavaScript Boolean value. + /// + JsBoolean = 4, + /// + /// The value is a JavaScript object value. + /// + JsObject = 5, + /// + /// The value is a JavaScript function object value. + /// + JsFunction = 6, + /// + /// The value is a JavaScript error object value. + /// + JsError = 7, + /// + /// The value is a JavaScript array object value. + /// + JsArray = 8, + /// + /// The value is a JavaScript symbol value. + /// + JsSymbol = 9, + /// + /// The value is a JavaScript ArrayBuffer object value. + /// + JsArrayBuffer = 10, + /// + /// The value is a JavaScript typed array object value. + /// + JsTypedArray = 11, + /// + /// The value is a JavaScript DataView object value. + /// + JsDataView = 12, + } JsValueType; + + /// + /// User implemented callback routine for memory allocation events + /// + /// + /// Use JsSetRuntimeMemoryAllocationCallback to register this callback. + /// + /// + /// The state passed to JsSetRuntimeMemoryAllocationCallback. + /// + /// The type of type allocation event. + /// The size of the allocation. + /// + /// For the JsMemoryAllocate event, returning true allows the runtime to continue + /// with the allocation. Returning false indicates the allocation request is rejected. The + /// return value is ignored for other allocation events. + /// + typedef bool (CHAKRA_CALLBACK * JsMemoryAllocationCallback)(_In_opt_ void *callbackState, _In_ JsMemoryEventType allocationEvent, _In_ size_t allocationSize); + + /// + /// A callback called before collection. + /// + /// + /// Use JsSetBeforeCollectCallback to register this callback. + /// + /// The state passed to JsSetBeforeCollectCallback. + typedef void (CHAKRA_CALLBACK *JsBeforeCollectCallback)(_In_opt_ void *callbackState); + + /// + /// A callback called before collecting an object. + /// + /// + /// Use JsSetObjectBeforeCollectCallback to register this callback. + /// + /// The object to be collected. + /// The state passed to JsSetObjectBeforeCollectCallback. + typedef void (CHAKRA_CALLBACK *JsObjectBeforeCollectCallback)(_In_ JsRef ref, _In_opt_ void *callbackState); + + /// + /// A background work item callback. + /// + /// + /// This is passed to the host's thread service (if provided) to allow the host to + /// invoke the work item callback on the background thread of its choice. + /// + /// Data argument passed to the thread service. + typedef void (CHAKRA_CALLBACK *JsBackgroundWorkItemCallback)(_In_opt_ void *callbackState); + + /// + /// A thread service callback. + /// + /// + /// The host can specify a background thread service when calling JsCreateRuntime. If + /// specified, then background work items will be passed to the host using this callback. The + /// host is expected to either begin executing the background work item immediately and return + /// true or return false and the runtime will handle the work item in-thread. + /// + /// The callback for the background work item. + /// The data argument to be passed to the callback. + typedef bool (CHAKRA_CALLBACK *JsThreadServiceCallback)(_In_ JsBackgroundWorkItemCallback callback, _In_opt_ void *callbackState); + + /// + /// Called by the runtime when it is finished with all resources related to the script execution. + /// The caller should free the source if loaded, the byte code, and the context at this time. + /// + /// The context passed to Js[Parse|Run]SerializedScriptWithCallback + typedef void (CHAKRA_CALLBACK * JsSerializedScriptUnloadCallback)(_In_ JsSourceContext sourceContext); + + /// + /// A finalizer callback. + /// + /// + /// The external data that was passed in when creating the object being finalized. + /// + typedef void (CHAKRA_CALLBACK *JsFinalizeCallback)(_In_opt_ void *data); + + /// + /// A function callback. + /// + /// + /// A function object that represents the function being invoked. + /// + /// Indicates whether this is a regular call or a 'new' call. + /// The arguments to the call. + /// The number of arguments. + /// + /// The state passed to JsCreateFunction. + /// + /// The result of the call, if any. + typedef _Ret_maybenull_ JsValueRef(CHAKRA_CALLBACK * JsNativeFunction)(_In_ JsValueRef callee, _In_ bool isConstructCall, _In_ JsValueRef *arguments, _In_ unsigned short argumentCount, _In_opt_ void *callbackState); + + /// + /// A promise continuation callback. + /// + /// + /// The host can specify a promise continuation callback in JsSetPromiseContinuationCallback. If + /// a script creates a task to be run later, then the promise continuation callback will be called with + /// the task and the task should be put in a FIFO queue, to be run when the current script is + /// done executing. + /// + /// The task, represented as a JavaScript function. + /// The data argument to be passed to the callback. + typedef void (CHAKRA_CALLBACK *JsPromiseContinuationCallback)(_In_ JsValueRef task, _In_opt_ void *callbackState); + + /// + /// Creates a new runtime. + /// + /// The attributes of the runtime to be created. + /// The thread service for the runtime. Can be null. + /// The runtime created. + /// In the edge-mode binary, chakra.dll, this function lacks the runtimeVersion + /// parameter (compare to jsrt9.h). + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateRuntime( + _In_ JsRuntimeAttributes attributes, + _In_opt_ JsThreadServiceCallback threadService, + _Out_ JsRuntimeHandle *runtime); + + /// + /// Performs a full garbage collection. + /// + /// The runtime in which the garbage collection will be performed. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCollectGarbage( + _In_ JsRuntimeHandle runtime); + + /// + /// Disposes a runtime. + /// + /// + /// Once a runtime has been disposed, all resources owned by it are invalid and cannot be used. + /// If the runtime is active (i.e. it is set to be current on a particular thread), it cannot + /// be disposed. + /// + /// The runtime to dispose. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDisposeRuntime( + _In_ JsRuntimeHandle runtime); + + /// + /// Gets the current memory usage for a runtime. + /// + /// + /// Memory usage can be always be retrieved, regardless of whether or not the runtime is active + /// on another thread. + /// + /// The runtime whose memory usage is to be retrieved. + /// The runtime's current memory usage, in bytes. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetRuntimeMemoryUsage( + _In_ JsRuntimeHandle runtime, + _Out_ size_t *memoryUsage); + + /// + /// Gets the current memory limit for a runtime. + /// + /// + /// The memory limit of a runtime can be always be retrieved, regardless of whether or not the + /// runtime is active on another thread. + /// + /// The runtime whose memory limit is to be retrieved. + /// + /// The runtime's current memory limit, in bytes, or -1 if no limit has been set. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetRuntimeMemoryLimit( + _In_ JsRuntimeHandle runtime, + _Out_ size_t *memoryLimit); + + /// + /// Sets the current memory limit for a runtime. + /// + /// + /// + /// A memory limit will cause any operation which exceeds the limit to fail with an "out of + /// memory" error. Setting a runtime's memory limit to -1 means that the runtime has no memory + /// limit. New runtimes default to having no memory limit. If the new memory limit exceeds + /// current usage, the call will succeed and any future allocations in this runtime will fail + /// until the runtime's memory usage drops below the limit. + /// + /// + /// A runtime's memory limit can be always be set, regardless of whether or not the runtime is + /// active on another thread. + /// + /// + /// The runtime whose memory limit is to be set. + /// + /// The new runtime memory limit, in bytes, or -1 for no memory limit. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetRuntimeMemoryLimit( + _In_ JsRuntimeHandle runtime, + _In_ size_t memoryLimit); + + /// + /// Sets a memory allocation callback for specified runtime + /// + /// + /// + /// Registering a memory allocation callback will cause the runtime to call back to the host + /// whenever it acquires memory from, or releases memory to, the OS. The callback routine is + /// called before the runtime memory manager allocates a block of memory. The allocation will + /// be rejected if the callback returns false. The runtime memory manager will also invoke the + /// callback routine after freeing a block of memory, as well as after allocation failures. + /// + /// + /// The callback is invoked on the current runtime execution thread, therefore execution is + /// blocked until the callback completes. + /// + /// + /// The return value of the callback is not stored; previously rejected allocations will not + /// prevent the runtime from invoking the callback again later for new memory allocations. + /// + /// + /// The runtime for which to register the allocation callback. + /// + /// User provided state that will be passed back to the callback. + /// + /// + /// Memory allocation callback to be called for memory allocation events. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetRuntimeMemoryAllocationCallback( + _In_ JsRuntimeHandle runtime, + _In_opt_ void *callbackState, + _In_ JsMemoryAllocationCallback allocationCallback); + + /// + /// Sets a callback function that is called by the runtime before garbage collection. + /// + /// + /// + /// The callback is invoked on the current runtime execution thread, therefore execution is + /// blocked until the callback completes. + /// + /// + /// The callback can be used by hosts to prepare for garbage collection. For example, by + /// releasing unnecessary references on Chakra objects. + /// + /// + /// The runtime for which to register the allocation callback. + /// + /// User provided state that will be passed back to the callback. + /// + /// The callback function being set. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetRuntimeBeforeCollectCallback( + _In_ JsRuntimeHandle runtime, + _In_opt_ void *callbackState, + _In_ JsBeforeCollectCallback beforeCollectCallback); + + /// + /// Adds a reference to a garbage collected object. + /// + /// + /// This only needs to be called on JsRef handles that are not going to be stored + /// somewhere on the stack. Calling JsAddRef ensures that the object the JsRef + /// refers to will not be freed until JsRelease is called. + /// + /// The object to add a reference to. + /// The object's new reference count (can pass in null). + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsAddRef( + _In_ JsRef ref, + _Out_opt_ unsigned int *count); + + /// + /// Releases a reference to a garbage collected object. + /// + /// + /// Removes a reference to a JsRef handle that was created by JsAddRef. + /// + /// The object to add a reference to. + /// The object's new reference count (can pass in null). + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsRelease( + _In_ JsRef ref, + _Out_opt_ unsigned int *count); + + /// + /// Sets a callback function that is called by the runtime before garbage collection of + /// an object. + /// + /// + /// + /// The callback is invoked on the current runtime execution thread, therefore execution is + /// blocked until the callback completes. + /// + /// + /// The object for which to register the callback. + /// + /// User provided state that will be passed back to the callback. + /// + /// The callback function being set. Use null to clear + /// previously registered callback. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetObjectBeforeCollectCallback( + _In_ JsRef ref, + _In_opt_ void *callbackState, + _In_ JsObjectBeforeCollectCallback objectBeforeCollectCallback); + + /// + /// Creates a script context for running scripts. + /// + /// + /// Each script context has its own global object that is isolated from all other script + /// contexts. + /// + /// The runtime the script context is being created in. + /// The created script context. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateContext( + _In_ JsRuntimeHandle runtime, + _Out_ JsContextRef *newContext); + + /// + /// Gets the current script context on the thread. + /// + /// + /// The current script context on the thread, null if there is no current script context. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetCurrentContext( + _Out_ JsContextRef *currentContext); + + /// + /// Sets the current script context on the thread. + /// + /// The script context to make current. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetCurrentContext( + _In_ JsContextRef context); + + /// + /// Gets the script context that the object belongs to. + /// + /// The object to get the context from. + /// The context the object belongs to. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetContextOfObject( + _In_ JsValueRef object, + _Out_ JsContextRef *context); + + /// + /// Gets the internal data set on JsrtContext. + /// + /// The context to get the data from. + /// The pointer to the data where data will be returned. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetContextData( + _In_ JsContextRef context, + _Out_ void **data); + + /// + /// Sets the internal data of JsrtContext. + /// + /// The context to set the data to. + /// The pointer to the data to be set. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetContextData( + _In_ JsContextRef context, + _In_ void *data); + + /// + /// Gets the runtime that the context belongs to. + /// + /// The context to get the runtime from. + /// The runtime the context belongs to. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetRuntime( + _In_ JsContextRef context, + _Out_ JsRuntimeHandle *runtime); + + /// + /// Tells the runtime to do any idle processing it need to do. + /// + /// + /// + /// If idle processing has been enabled for the current runtime, calling JsIdle will + /// inform the current runtime that the host is idle and that the runtime can perform + /// memory cleanup tasks. + /// + /// + /// JsIdle can also return the number of system ticks until there will be more idle work + /// for the runtime to do. Calling JsIdle before this number of ticks has passed will do + /// no work. + /// + /// + /// Requires an active script context. + /// + /// + /// + /// The next system tick when there will be more idle work to do. Can be null. Returns the + /// maximum number of ticks if there no upcoming idle work to do. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsIdle( + _Out_opt_ unsigned int *nextIdleTick); + + /// + /// Gets the symbol associated with the property ID. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The property ID to get the symbol of. + /// The symbol associated with the property ID. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetSymbolFromPropertyId( + _In_ JsPropertyIdRef propertyId, + _Out_ JsValueRef *symbol); + + /// + /// Gets the type of property + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The property ID to get the type of. + /// The JsPropertyIdType of the given property ID + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetPropertyIdType( + _In_ JsPropertyIdRef propertyId, + _Out_ JsPropertyIdType* propertyIdType); + + + /// + /// Gets the property ID associated with the symbol. + /// + /// + /// + /// Property IDs are specific to a context and cannot be used across contexts. + /// + /// + /// Requires an active script context. + /// + /// + /// + /// The symbol whose property ID is being retrieved. + /// + /// The property ID for the given symbol. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetPropertyIdFromSymbol( + _In_ JsValueRef symbol, + _Out_ JsPropertyIdRef *propertyId); + + /// + /// Creates a Javascript symbol. + /// + /// + /// Requires an active script context. + /// + /// The string description of the symbol. Can be null. + /// The new symbol. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateSymbol( + _In_ JsValueRef description, + _Out_ JsValueRef *result); + + /// + /// Gets the list of all symbol properties on the object. + /// + /// + /// Requires an active script context. + /// + /// The object from which to get the property symbols. + /// An array of property symbols. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetOwnPropertySymbols( + _In_ JsValueRef object, + _Out_ JsValueRef *propertySymbols); + + /// + /// Gets the value of undefined in the current script context. + /// + /// + /// Requires an active script context. + /// + /// The undefined value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetUndefinedValue( + _Out_ JsValueRef *undefinedValue); + + /// + /// Gets the value of null in the current script context. + /// + /// + /// Requires an active script context. + /// + /// The null value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetNullValue( + _Out_ JsValueRef *nullValue); + + /// + /// Gets the value of true in the current script context. + /// + /// + /// Requires an active script context. + /// + /// The true value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetTrueValue( + _Out_ JsValueRef *trueValue); + + /// + /// Gets the value of false in the current script context. + /// + /// + /// Requires an active script context. + /// + /// The false value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetFalseValue( + _Out_ JsValueRef *falseValue); + + /// + /// Creates a Boolean value from a bool value. + /// + /// + /// Requires an active script context. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsBoolToBoolean( + _In_ bool value, + _Out_ JsValueRef *booleanValue); + + /// + /// Retrieves the bool value of a Boolean value. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsBooleanToBool( + _In_ JsValueRef value, + _Out_ bool *boolValue); + + /// + /// Converts the value to Boolean using standard JavaScript semantics. + /// + /// + /// Requires an active script context. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsConvertValueToBoolean( + _In_ JsValueRef value, + _Out_ JsValueRef *booleanValue); + + + /// + /// Gets the JavaScript type of a JsValueRef. + /// + /// The value whose type is to be returned. + /// The type of the value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetValueType( + _In_ JsValueRef value, + _Out_ JsValueType *type); + + /// + /// Creates a number value from a double value. + /// + /// + /// Requires an active script context. + /// + /// The double to convert to a number value. + /// The new number value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDoubleToNumber( + _In_ double doubleValue, + _Out_ JsValueRef *value); + + /// + /// Creates a number value from an int value. + /// + /// + /// Requires an active script context. + /// + /// The int to convert to a number value. + /// The new number value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsIntToNumber( + _In_ int intValue, + _Out_ JsValueRef *value); + + /// + /// Retrieves the double value of a number value. + /// + /// + /// This function retrieves the value of a number value. It will fail with + /// JsErrorInvalidArgument if the type of the value is not number. + /// + /// The number value to convert to a double value. + /// The double value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsNumberToDouble( + _In_ JsValueRef value, + _Out_ double *doubleValue); + + /// + /// Retrieves the int value of a number value. + /// + /// + /// This function retrieves the value of a number value and converts to an int value. + /// It will fail with JsErrorInvalidArgument if the type of the value is not number. + /// + /// The number value to convert to an int value. + /// The int value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsNumberToInt( + _In_ JsValueRef value, + _Out_ int *intValue); + + /// + /// Converts the value to number using standard JavaScript semantics. + /// + /// + /// Requires an active script context. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsConvertValueToNumber( + _In_ JsValueRef value, + _Out_ JsValueRef *numberValue); + + /// + /// Gets the length of a string value. + /// + /// The string value to get the length of. + /// The length of the string. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetStringLength( + _In_ JsValueRef stringValue, + _Out_ int *length); + + /// + /// Converts the value to string using standard JavaScript semantics. + /// + /// + /// Requires an active script context. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsConvertValueToString( + _In_ JsValueRef value, + _Out_ JsValueRef *stringValue); + + /// + /// Gets the global object in the current script context. + /// + /// + /// Requires an active script context. + /// + /// The global object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetGlobalObject( + _Out_ JsValueRef *globalObject); + + /// + /// Creates a new object. + /// + /// + /// Requires an active script context. + /// + /// The new object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateObject( + _Out_ JsValueRef *object); + + /// + /// Creates a new object that stores some external data. + /// + /// + /// Requires an active script context. + /// + /// External data that the object will represent. May be null. + /// + /// A callback for when the object is finalized. May be null. + /// + /// The new object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateExternalObject( + _In_opt_ void *data, + _In_opt_ JsFinalizeCallback finalizeCallback, + _Out_ JsValueRef *object); + + /// + /// Converts the value to object using standard JavaScript semantics. + /// + /// + /// Requires an active script context. + /// + /// The value to be converted. + /// The converted value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsConvertValueToObject( + _In_ JsValueRef value, + _Out_ JsValueRef *object); + + /// + /// Returns the prototype of an object. + /// + /// + /// Requires an active script context. + /// + /// The object whose prototype is to be returned. + /// The object's prototype. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetPrototype( + _In_ JsValueRef object, + _Out_ JsValueRef *prototypeObject); + + /// + /// Sets the prototype of an object. + /// + /// + /// Requires an active script context. + /// + /// The object whose prototype is to be changed. + /// The object's new prototype. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetPrototype( + _In_ JsValueRef object, + _In_ JsValueRef prototypeObject); + + /// + /// Performs JavaScript "instanceof" operator test. + /// + /// + /// Requires an active script context. + /// + /// The object to test. + /// The constructor function to test against. + /// Whether "object instanceof constructor" is true. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsInstanceOf( + _In_ JsValueRef object, + _In_ JsValueRef constructor, + _Out_ bool *result); + + /// + /// Returns a value that indicates whether an object is extensible or not. + /// + /// + /// Requires an active script context. + /// + /// The object to test. + /// Whether the object is extensible or not. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetExtensionAllowed( + _In_ JsValueRef object, + _Out_ bool *value); + + /// + /// Makes an object non-extensible. + /// + /// + /// Requires an active script context. + /// + /// The object to make non-extensible. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsPreventExtension( + _In_ JsValueRef object); + + /// + /// Gets an object's property. + /// + /// + /// Requires an active script context. + /// + /// The object that contains the property. + /// The ID of the property. + /// The value of the property. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _Out_ JsValueRef *value); + + /// + /// Gets a property descriptor for an object's own property. + /// + /// + /// Requires an active script context. + /// + /// The object that has the property. + /// The ID of the property. + /// The property descriptor. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetOwnPropertyDescriptor( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _Out_ JsValueRef *propertyDescriptor); + + /// + /// Gets the list of all properties on the object. + /// + /// + /// Requires an active script context. + /// + /// The object from which to get the property names. + /// An array of property names. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetOwnPropertyNames( + _In_ JsValueRef object, + _Out_ JsValueRef *propertyNames); + + /// + /// Puts an object's property. + /// + /// + /// Requires an active script context. + /// + /// The object that contains the property. + /// The ID of the property. + /// The new value of the property. + /// The property set should follow strict mode rules. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _In_ JsValueRef value, + _In_ bool useStrictRules); + + /// + /// Determines whether an object has a property. + /// + /// + /// Requires an active script context. + /// + /// The object that may contain the property. + /// The ID of the property. + /// Whether the object (or a prototype) has the property. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsHasProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _Out_ bool *hasProperty); + + /// + /// Deletes an object's property. + /// + /// + /// Requires an active script context. + /// + /// The object that contains the property. + /// The ID of the property. + /// The property set should follow strict mode rules. + /// Whether the property was deleted. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDeleteProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _In_ bool useStrictRules, + _Out_ JsValueRef *result); + + /// + /// Defines a new object's own property from a property descriptor. + /// + /// + /// Requires an active script context. + /// + /// The object that has the property. + /// The ID of the property. + /// The property descriptor. + /// Whether the property was defined. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDefineProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _In_ JsValueRef propertyDescriptor, + _Out_ bool *result); + + /// + /// Tests whether an object has a value at the specified index. + /// + /// + /// Requires an active script context. + /// + /// The object to operate on. + /// The index to test. + /// Whether the object has a value at the specified index. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsHasIndexedProperty( + _In_ JsValueRef object, + _In_ JsValueRef index, + _Out_ bool *result); + + /// + /// Retrieve the value at the specified index of an object. + /// + /// + /// Requires an active script context. + /// + /// The object to operate on. + /// The index to retrieve. + /// The retrieved value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetIndexedProperty( + _In_ JsValueRef object, + _In_ JsValueRef index, + _Out_ JsValueRef *result); + + /// + /// Set the value at the specified index of an object. + /// + /// + /// Requires an active script context. + /// + /// The object to operate on. + /// The index to set. + /// The value to set. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetIndexedProperty( + _In_ JsValueRef object, + _In_ JsValueRef index, + _In_ JsValueRef value); + + /// + /// Delete the value at the specified index of an object. + /// + /// + /// Requires an active script context. + /// + /// The object to operate on. + /// The index to delete. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDeleteIndexedProperty( + _In_ JsValueRef object, + _In_ JsValueRef index); + + /// + /// Determines whether an object has its indexed properties in external data. + /// + /// The object. + /// Whether the object has its indexed properties in external data. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsHasIndexedPropertiesExternalData( + _In_ JsValueRef object, + _Out_ bool* value); + + /// + /// Retrieves an object's indexed properties external data information. + /// + /// The object. + /// The external data back store for the object's indexed properties. + /// The array element type in external data. + /// The number of array elements in external data. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetIndexedPropertiesExternalData( + _In_ JsValueRef object, + _Out_ void** data, + _Out_ JsTypedArrayType* arrayType, + _Out_ unsigned int* elementLength); + + /// + /// Sets an object's indexed properties to external data. The external data will be used as back + /// store for the object's indexed properties and accessed like a typed array. + /// + /// + /// Requires an active script context. + /// + /// The object to operate on. + /// The external data to be used as back store for the object's indexed properties. + /// The array element type in external data. + /// The number of array elements in external data. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetIndexedPropertiesToExternalData( + _In_ JsValueRef object, + _In_ void* data, + _In_ JsTypedArrayType arrayType, + _In_ unsigned int elementLength); + + /// + /// Compare two JavaScript values for equality. + /// + /// + /// + /// This function is equivalent to the == operator in Javascript. + /// + /// + /// Requires an active script context. + /// + /// + /// The first object to compare. + /// The second object to compare. + /// Whether the values are equal. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsEquals( + _In_ JsValueRef object1, + _In_ JsValueRef object2, + _Out_ bool *result); + + /// + /// Compare two JavaScript values for strict equality. + /// + /// + /// + /// This function is equivalent to the === operator in Javascript. + /// + /// + /// Requires an active script context. + /// + /// + /// The first object to compare. + /// The second object to compare. + /// Whether the values are strictly equal. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsStrictEquals( + _In_ JsValueRef object1, + _In_ JsValueRef object2, + _Out_ bool *result); + + /// + /// Determines whether an object is an external object. + /// + /// The object. + /// Whether the object is an external object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsHasExternalData( + _In_ JsValueRef object, + _Out_ bool *value); + + /// + /// Retrieves the data from an external object. + /// + /// The external object. + /// + /// The external data stored in the object. Can be null if no external data is stored in the + /// object. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetExternalData( + _In_ JsValueRef object, + _Out_ void **externalData); + + /// + /// Sets the external data on an external object. + /// + /// The external object. + /// + /// The external data to be stored in the object. Can be null if no external data is + /// to be stored in the object. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetExternalData( + _In_ JsValueRef object, + _In_opt_ void *externalData); + + /// + /// Creates a Javascript array object. + /// + /// + /// Requires an active script context. + /// + /// The initial length of the array. + /// The new array object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateArray( + _In_ unsigned int length, + _Out_ JsValueRef *result); + + /// + /// Creates a Javascript ArrayBuffer object. + /// + /// + /// Requires an active script context. + /// + /// + /// The number of bytes in the ArrayBuffer. + /// + /// The new ArrayBuffer object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateArrayBuffer( + _In_ unsigned int byteLength, + _Out_ JsValueRef *result); + + /// + /// Creates a Javascript ArrayBuffer object to access external memory. + /// + /// Requires an active script context. + /// A pointer to the external memory. + /// The number of bytes in the external memory. + /// A callback for when the object is finalized. May be null. + /// User provided state that will be passed back to finalizeCallback. + /// The new ArrayBuffer object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateExternalArrayBuffer( + _Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data, + _In_ unsigned int byteLength, + _In_opt_ JsFinalizeCallback finalizeCallback, + _In_opt_ void *callbackState, + _Out_ JsValueRef *result); + + /// + /// Creates a Javascript typed array object. + /// + /// + /// + /// The baseArray can be an ArrayBuffer, another typed array, or a JavaScript + /// Array. The returned typed array will use the baseArray if it is an ArrayBuffer, or + /// otherwise create and use a copy of the underlying source array. + /// + /// + /// Requires an active script context. + /// + /// + /// The type of the array to create. + /// + /// The base array of the new array. Use JS_INVALID_REFERENCE if no base array. + /// + /// + /// The offset in bytes from the start of baseArray (ArrayBuffer) for result typed array to reference. + /// Only applicable when baseArray is an ArrayBuffer object. Must be 0 otherwise. + /// + /// + /// The number of elements in the array. Only applicable when creating a new typed array without + /// baseArray (baseArray is JS_INVALID_REFERENCE) or when baseArray is an ArrayBuffer object. + /// Must be 0 otherwise. + /// + /// The new typed array object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateTypedArray( + _In_ JsTypedArrayType arrayType, + _In_ JsValueRef baseArray, + _In_ unsigned int byteOffset, + _In_ unsigned int elementLength, + _Out_ JsValueRef *result); + + /// + /// Creates a Javascript DataView object. + /// + /// + /// Requires an active script context. + /// + /// + /// An existing ArrayBuffer object to use as the storage for the result DataView object. + /// + /// + /// The offset in bytes from the start of arrayBuffer for result DataView to reference. + /// + /// + /// The number of bytes in the ArrayBuffer for result DataView to reference. + /// + /// The new DataView object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateDataView( + _In_ JsValueRef arrayBuffer, + _In_ unsigned int byteOffset, + _In_ unsigned int byteLength, + _Out_ JsValueRef *result); + + /// + /// Obtains frequently used properties of a typed array. + /// + /// The typed array instance. + /// The type of the array. + /// The ArrayBuffer backstore of the array. + /// The offset in bytes from the start of arrayBuffer referenced by the array. + /// The number of bytes in the array. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetTypedArrayInfo( + _In_ JsValueRef typedArray, + _Out_opt_ JsTypedArrayType *arrayType, + _Out_opt_ JsValueRef *arrayBuffer, + _Out_opt_ unsigned int *byteOffset, + _Out_opt_ unsigned int *byteLength); + + /// + /// Obtains the underlying memory storage used by an ArrayBuffer. + /// + /// The ArrayBuffer instance. + /// + /// The ArrayBuffer's buffer. The lifetime of the buffer returned is the same as the lifetime of the + /// the ArrayBuffer. The buffer pointer does not count as a reference to the ArrayBuffer for the purpose + /// of garbage collection. + /// + /// The number of bytes in the buffer. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetArrayBufferStorage( + _In_ JsValueRef arrayBuffer, + _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer, + _Out_ unsigned int *bufferLength); + + /// + /// Obtains the underlying memory storage used by a typed array. + /// + /// The typed array instance. + /// + /// The array's buffer. The lifetime of the buffer returned is the same as the lifetime of the + /// the array. The buffer pointer does not count as a reference to the array for the purpose + /// of garbage collection. + /// + /// The number of bytes in the buffer. + /// The type of the array. + /// + /// The size of an element of the array. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetTypedArrayStorage( + _In_ JsValueRef typedArray, + _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer, + _Out_ unsigned int *bufferLength, + _Out_opt_ JsTypedArrayType *arrayType, + _Out_opt_ int *elementSize); + + /// + /// Obtains the underlying memory storage used by a DataView. + /// + /// The DataView instance. + /// + /// The DataView's buffer. The lifetime of the buffer returned is the same as the lifetime of the + /// the DataView. The buffer pointer does not count as a reference to the DataView for the purpose + /// of garbage collection. + /// + /// The number of bytes in the buffer. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetDataViewStorage( + _In_ JsValueRef dataView, + _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer, + _Out_ unsigned int *bufferLength); + + + /// + /// Invokes a function. + /// + /// + /// Requires thisArg as first argument of arguments. + /// Requires an active script context. + /// + /// The function to invoke. + /// The arguments to the call. + /// The number of arguments being passed in to the function. + /// The value returned from the function invocation, if any. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCallFunction( + _In_ JsValueRef function, + _In_reads_(argumentCount) JsValueRef *arguments, + _In_ unsigned short argumentCount, + _Out_opt_ JsValueRef *result); + + /// + /// Invokes a function as a constructor. + /// + /// + /// Requires an active script context. + /// + /// The function to invoke as a constructor. + /// The arguments to the call. + /// The number of arguments being passed in to the function. + /// The value returned from the function invocation. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsConstructObject( + _In_ JsValueRef function, + _In_reads_(argumentCount) JsValueRef *arguments, + _In_ unsigned short argumentCount, + _Out_ JsValueRef *result); + + /// + /// Creates a new JavaScript function. + /// + /// + /// Requires an active script context. + /// + /// The method to call when the function is invoked. + /// + /// User provided state that will be passed back to the callback. + /// + /// The new function object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateFunction( + _In_ JsNativeFunction nativeFunction, + _In_opt_ void *callbackState, + _Out_ JsValueRef *function); + + /// + /// Creates a new JavaScript function with name. + /// + /// + /// Requires an active script context. + /// + /// The name of this function that will be used for diagnostics and stringification purposes. + /// The method to call when the function is invoked. + /// + /// User provided state that will be passed back to the callback. + /// + /// The new function object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateNamedFunction( + _In_ JsValueRef name, + _In_ JsNativeFunction nativeFunction, + _In_opt_ void *callbackState, + _Out_ JsValueRef *function); + + /// + /// Creates a new JavaScript error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Creates a new JavaScript RangeError error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateRangeError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Creates a new JavaScript ReferenceError error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateReferenceError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Creates a new JavaScript SyntaxError error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateSyntaxError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Creates a new JavaScript TypeError error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateTypeError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Creates a new JavaScript URIError error object + /// + /// + /// Requires an active script context. + /// + /// Message for the error object. + /// The new error object. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsCreateURIError( + _In_ JsValueRef message, + _Out_ JsValueRef *error); + + /// + /// Determines whether the runtime of the current context is in an exception state. + /// + /// + /// + /// If a call into the runtime results in an exception (either as the result of running a + /// script or due to something like a conversion failure), the runtime is placed into an + /// "exception state." All calls into any context created by the runtime (except for the + /// exception APIs) will fail with JsErrorInExceptionState until the exception is + /// cleared. + /// + /// + /// If the runtime of the current context is in the exception state when a callback returns + /// into the engine, the engine will automatically rethrow the exception. + /// + /// + /// Requires an active script context. + /// + /// + /// + /// Whether the runtime of the current context is in the exception state. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsHasException( + _Out_ bool *hasException); + + /// + /// Returns the exception that caused the runtime of the current context to be in the + /// exception state and resets the exception state for that runtime. + /// + /// + /// + /// If the runtime of the current context is not in an exception state, this API will return + /// JsErrorInvalidArgument. If the runtime is disabled, this will return an exception + /// indicating that the script was terminated, but it will not clear the exception (the + /// exception will be cleared if the runtime is re-enabled using + /// JsEnableRuntimeExecution). + /// + /// + /// Requires an active script context. + /// + /// + /// The exception for the runtime of the current context. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetAndClearException( + _Out_ JsValueRef *exception); + + /// + /// Sets the runtime of the current context to an exception state. + /// + /// + /// + /// If the runtime of the current context is already in an exception state, this API will + /// return JsErrorInExceptionState. + /// + /// + /// Requires an active script context. + /// + /// + /// + /// The JavaScript exception to set for the runtime of the current context. + /// + /// + /// JsNoError if the engine was set into an exception state, a failure code otherwise. + /// + CHAKRA_API + JsSetException( + _In_ JsValueRef exception); + + /// + /// Suspends script execution and terminates any running scripts in a runtime. + /// + /// + /// + /// Calls to a suspended runtime will fail until JsEnableRuntimeExecution is called. + /// + /// + /// This API does not have to be called on the thread the runtime is active on. Although the + /// runtime will be set into a suspended state, an executing script may not be suspended + /// immediately; a running script will be terminated with an uncatchable exception as soon as + /// possible. + /// + /// + /// Suspending execution in a runtime that is already suspended is a no-op. + /// + /// + /// The runtime to be suspended. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsDisableRuntimeExecution( + _In_ JsRuntimeHandle runtime); + + /// + /// Enables script execution in a runtime. + /// + /// + /// Enabling script execution in a runtime that already has script execution enabled is a + /// no-op. + /// + /// The runtime to be enabled. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsEnableRuntimeExecution( + _In_ JsRuntimeHandle runtime); + + /// + /// Returns a value that indicates whether script execution is disabled in the runtime. + /// + /// Specifies the runtime to check if execution is disabled. + /// If execution is disabled, true, false otherwise. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsIsRuntimeExecutionDisabled( + _In_ JsRuntimeHandle runtime, + _Out_ bool *isDisabled); + + /// + /// Sets a promise continuation callback function that is called by the context when a task + /// needs to be queued for future execution + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The callback function being set. + /// + /// User provided state that will be passed back to the callback. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSetPromiseContinuationCallback( + _In_opt_ JsPromiseContinuationCallback promiseContinuationCallback, + _In_opt_ void *callbackState); + +#ifdef _WIN32 +#include "ChakraCommonWindows.h" +#endif // _WIN32 +#endif // _CHAKRACOMMON_H_ diff --git a/ios/libnode/include/node/ChakraCommonWindows.h b/ios/libnode/include/node/ChakraCommonWindows.h new file mode 100644 index 0000000..3c634a5 --- /dev/null +++ b/ios/libnode/include/node/ChakraCommonWindows.h @@ -0,0 +1,367 @@ +//------------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. +//------------------------------------------------------------------------------------------------------- + +#ifdef _MSC_VER +#pragma once +#endif // _MSC_VER + +#ifndef _CHAKRACOMMONWINDOWS_H_ +#define _CHAKRACOMMONWINDOWS_H_ + + /// + /// Called by the runtime to load the source code of the serialized script. + /// The caller must keep the script buffer valid until the JsSerializedScriptUnloadCallback. + /// This callback is only supported by the Win32 version of the API + /// + /// The context passed to Js[Parse|Run]SerializedScriptWithCallback + /// The script returned. + /// + /// true if the operation succeeded, false otherwise. + /// + typedef bool (CHAKRA_CALLBACK * JsSerializedScriptLoadSourceCallback)(_In_ JsSourceContext sourceContext, _Outptr_result_z_ const WCHAR** scriptBuffer); + + /// + /// Parses a script and returns a function representing the script. + /// + /// + /// Requires an active script context. + /// + /// The script to parse. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the script came from. + /// A function representing the script code. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsParseScript( + _In_z_ const wchar_t *script, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef *result); + + /// + /// Parses a script and returns a function representing the script. + /// + /// + /// Requires an active script context. + /// + /// The script to parse. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the script came from. + /// Attribute mask for parsing the script + /// A function representing the script code. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsParseScriptWithAttributes( + _In_z_ const wchar_t *script, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _In_ JsParseScriptAttributes parseAttributes, + _Out_ JsValueRef *result); + + /// + /// Executes a script. + /// + /// + /// Requires an active script context. + /// + /// The script to run. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the script came from. + /// The result of the script, if any. This parameter can be null. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsRunScript( + _In_z_ const wchar_t *script, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef *result); + + /// + /// Executes a module. + /// + /// + /// Requires an active script context. + /// + /// The module script to parse and execute. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the module script came from. + /// The result of executing the module script, if any. This parameter can be null. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsExperimentalApiRunModule( + _In_z_ const wchar_t *script, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef *result); + + /// + /// Serializes a parsed script to a buffer than can be reused. + /// + /// + /// + /// JsSerializeScript parses a script and then stores the parsed form of the script in a + /// runtime-independent format. The serialized script then can be deserialized in any + /// runtime without requiring the script to be re-parsed. + /// + /// + /// Requires an active script context. + /// + /// + /// The script to serialize. + /// The buffer to put the serialized script into. Can be null. + /// + /// On entry, the size of the buffer, in bytes; on exit, the size of the buffer, in bytes, + /// required to hold the serialized script. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsSerializeScript( + _In_z_ const wchar_t *script, + _Out_writes_to_opt_(*bufferSize, *bufferSize) BYTE *buffer, + _Inout_ unsigned int *bufferSize); + + /// + /// Parses a serialized script and returns a function representing the script. + /// Provides the ability to lazy load the script source only if/when it is needed. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The runtime will hold on to the buffer until all instances of any functions created from + /// the buffer are garbage collected. It will then call scriptUnloadCallback to inform the + /// caller it is safe to release. + /// + /// + /// Callback called when the source code of the script needs to be loaded. + /// Callback called when the serialized script and source code are no longer needed. + /// The serialized script. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// This context will passed into scriptLoadCallback and scriptUnloadCallback. + /// + /// The location the script came from. + /// A function representing the script code. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsParseSerializedScriptWithCallback( + _In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback, + _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback, + _In_ BYTE *buffer, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef * result); + + /// + /// Runs a serialized script. + /// Provides the ability to lazy load the script source only if/when it is needed. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The runtime will hold on to the buffer until all instances of any functions created from + /// the buffer are garbage collected. It will then call scriptUnloadCallback to inform the + /// caller it is safe to release. + /// + /// + /// Callback called when the source code of the script needs to be loaded. + /// Callback called when the serialized script and source code are no longer needed. + /// The serialized script. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// This context will passed into scriptLoadCallback and scriptUnloadCallback. + /// + /// The location the script came from. + /// + /// The result of running the script, if any. This parameter can be null. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsRunSerializedScriptWithCallback( + _In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback, + _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback, + _In_ BYTE *buffer, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_opt_ JsValueRef * result); + + /// + /// Parses a serialized script and returns a function representing the script. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The runtime will hold on to the buffer until all instances of any functions created from + /// the buffer are garbage collected. + /// + /// + /// The script to parse. + /// The serialized script. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the script came from. + /// A function representing the script code. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsParseSerializedScript( + _In_z_ const wchar_t *script, + _In_ BYTE *buffer, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef *result); + + /// + /// Runs a serialized script. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The runtime will hold on to the buffer until all instances of any functions created from + /// the buffer are garbage collected. + /// + /// + /// The source code of the serialized script. + /// The serialized script. + /// + /// A cookie identifying the script that can be used by debuggable script contexts. + /// + /// The location the script came from. + /// + /// The result of running the script, if any. This parameter can be null. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsRunSerializedScript( + _In_z_ const wchar_t *script, + _In_ BYTE *buffer, + _In_ JsSourceContext sourceContext, + _In_z_ const wchar_t *sourceUrl, + _Out_ JsValueRef *result); + + /// + /// Gets the property ID associated with the name. + /// + /// + /// + /// Property IDs are specific to a context and cannot be used across contexts. + /// + /// + /// Requires an active script context. + /// + /// + /// + /// The name of the property ID to get or create. The name may consist of only digits. + /// + /// The property ID in this runtime for the given name. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetPropertyIdFromName( + _In_z_ const wchar_t *name, + _Out_ JsPropertyIdRef *propertyId); + + /// + /// Gets the name associated with the property ID. + /// + /// + /// + /// Requires an active script context. + /// + /// + /// The returned buffer is valid as long as the runtime is alive and cannot be used + /// once the runtime has been disposed. + /// + /// + /// The property ID to get the name of. + /// The name associated with the property ID. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsGetPropertyNameFromId( + _In_ JsPropertyIdRef propertyId, + _Outptr_result_z_ const wchar_t **name); + + /// + /// Creates a string value from a string pointer. + /// + /// + /// Requires an active script context. + /// + /// The string pointer to convert to a string value. + /// The length of the string to convert. + /// The new string value. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsPointerToString( + _In_reads_(stringLength) const wchar_t *stringValue, + _In_ size_t stringLength, + _Out_ JsValueRef *value); + + /// + /// Retrieves the string pointer of a string value. + /// + /// + /// + /// This function retrieves the string pointer of a string value. It will fail with + /// JsErrorInvalidArgument if the type of the value is not string. The lifetime + /// of the string returned will be the same as the lifetime of the value it came from, however + /// the string pointer is not considered a reference to the value (and so will not keep it + /// from being collected). + /// + /// + /// Requires an active script context. + /// + /// + /// The string value to convert to a string pointer. + /// The string pointer. + /// The length of the string. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsStringToPointer( + _In_ JsValueRef value, + _Outptr_result_buffer_(*stringLength) const wchar_t **stringValue, + _Out_ size_t *stringLength); + +#endif // _CHAKRACOMMONWINDOWS_H_ diff --git a/ios/libnode/include/node/ChakraCore.h b/ios/libnode/include/node/ChakraCore.h new file mode 100644 index 0000000..5b4a55f --- /dev/null +++ b/ios/libnode/include/node/ChakraCore.h @@ -0,0 +1,743 @@ +//------------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. +//------------------------------------------------------------------------------------------------------- +/// \mainpage Chakra Hosting API Reference +/// +/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can +/// also be hosted independently by other applications. This reference describes the APIs available +/// to applications to host Chakra. +/// + +/// \file +/// \brief The Chakra Core hosting API. +/// +/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll. + +#ifdef _MSC_VER +#pragma once +#endif // _MSC_VER + +#ifndef _CHAKRACORE_H_ +#define _CHAKRACORE_H_ + +#if !defined(NTBUILD) && !defined(_CHAKRACOREBUILD) +#define _CHAKRACOREBUILD +#endif + +#include "ChakraCommon.h" +#include "ChakraDebug.h" + +// Begin ChakraCore only APIs +#ifdef _CHAKRACOREBUILD + +typedef void* JsModuleRecord; + +/// +/// A reference to an object owned by the SharedArrayBuffer. +/// +/// +/// This represents SharedContents which is heap allocated object, it can be passed through +/// different runtimes to share the underlying buffer. +/// +typedef void *JsSharedArrayBufferContentHandle; + +typedef enum JsParseModuleSourceFlags +{ + JsParseModuleSourceFlags_DataIsUTF16LE = 0x00000000, + JsParseModuleSourceFlags_DataIsUTF8 = 0x00000001 +} JsParseModuleSourceFlags; + +typedef enum JsModuleHostInfoKind +{ + JsModuleHostInfo_Exception = 0x01, + JsModuleHostInfo_HostDefined = 0x02, + JsModuleHostInfo_NotifyModuleReadyCallback = 0x3, + JsModuleHostInfo_FetchImportedModuleCallback = 0x4, + JsModuleHostInfo_FetchImportedModuleFromScriptCallback = 0x5 +} JsModuleHostInfoKind; + +/// +/// User implemented callback to fetch additional imported modules. +/// +/// +/// Notify the host to fetch the dependent module. This is the "import" part before HostResolveImportedModule in ES6 spec. +/// This notifies the host that the referencing module has the specified module dependency, and the host need to retrieve the module back. +/// +/// The referencing module that is requesting the dependency modules. +/// The specifier coming from the module source code. +/// The ModuleRecord of the dependent module. If the module was requested before from other source, return the +/// existing ModuleRecord, otherwise return a newly created ModuleRecord. +/// +/// true if the operation succeeded, false otherwise. +/// +typedef JsErrorCode(CHAKRA_CALLBACK * FetchImportedModuleCallBack)(_In_ JsModuleRecord referencingModule, _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord); + +/// +/// User implemented callback to get notification when the module is ready. +/// +/// +/// Notify the host after ModuleDeclarationInstantiation step (15.2.1.1.6.4) is finished. If there was error in the process, exceptionVar +/// holds the exception. Otherwise the referencingModule is ready and the host should schedule execution afterwards. +/// +/// The referencing module that have finished running ModuleDeclarationInstantiation step. +/// If nullptr, the module is successfully initialized and host should queue the execution job +/// otherwise it's the exception object. +/// +/// true if the operation succeeded, false otherwise. +/// +typedef JsErrorCode(CHAKRA_CALLBACK * FetchImportedModuleFromScriptCallBack)(_In_ JsSourceContext dwReferencingSourceContext, _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord); + +/// +/// User implemented callback to get notification when the module is ready. +/// +/// +/// Notify the host after ModuleDeclarationInstantiation step (15.2.1.1.6.4) is finished. If there was error in the process, exceptionVar +/// holds the exception. Otherwise the referencingModule is ready and the host should schedule execution afterwards. +/// +/// The referencing script that calls import() +/// If nullptr, the module is successfully initialized and host should queue the execution job +/// otherwise it's the exception object. +/// +/// true if the operation succeeded, false otherwise. +/// +typedef JsErrorCode(CHAKRA_CALLBACK * NotifyModuleReadyCallback)(_In_opt_ JsModuleRecord referencingModule, _In_opt_ JsValueRef exceptionVar); + +/// +/// Initialize a ModuleRecord from host +/// +/// +/// Bootstrap the module loading process by creating a new module record. +/// +/// The referencingModule as in HostResolveImportedModule (15.2.1.17). nullptr if this is the top level module. +/// The host normalized specifier. This is the key to a unique ModuleRecord. +/// The new ModuleRecord created. The host should not try to call this API twice with the same normalizedSpecifier. +/// chakra will return an existing ModuleRecord if the specifier was passed in before. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsInitializeModuleRecord( + _In_opt_ JsModuleRecord referencingModule, + _In_ JsValueRef normalizedSpecifier, + _Outptr_result_maybenull_ JsModuleRecord* moduleRecord); + +/// +/// Parse the module source +/// +/// +/// This is basically ParseModule operation in ES6 spec. It is slightly different in that the ModuleRecord was initialized earlier, and passed in as an argument. +/// +/// The ModuleRecord that holds the parse tree of the source code. +/// A cookie identifying the script that can be used by debuggable script contexts. +/// The source script to be parsed, but not executed in this code. +/// The source length of sourceText. The input might contain embedded null. +/// The type of the source code passed in. It could be UNICODE or utf8 at this time. +/// The error object if there is parse error. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsParseModuleSource( + _In_ JsModuleRecord requestModule, + _In_ JsSourceContext sourceContext, + _In_ BYTE* script, + _In_ unsigned int scriptLength, + _In_ JsParseModuleSourceFlags sourceFlag, + _Outptr_result_maybenull_ JsValueRef* exceptionValueRef); + +/// +/// Execute module code. +/// +/// +/// This method implements 15.2.1.1.6.5, "ModuleEvaluation" concrete method. +/// When this methid is called, the chakra engine should have notified the host that the module and all its dependent are ready to be executed. +/// One moduleRecord will be executed only once. Additional execution call on the same moduleRecord will fail. +/// +/// The module to be executed. +/// The return value of the module. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsModuleEvaluation( + _In_ JsModuleRecord requestModule, + _Outptr_result_maybenull_ JsValueRef* result); + +/// +/// Set the host info for the specified module. +/// +/// The request module. +/// The type of host info to be set. +/// The host info to be set. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsSetModuleHostInfo( + _In_ JsModuleRecord requestModule, + _In_ JsModuleHostInfoKind moduleHostInfo, + _In_ void* hostInfo); + +/// +/// Retrieve the host info for the specified module. +/// +/// The request module. +/// The type of host info to get. +/// The host info to be retrieved. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsGetModuleHostInfo( + _In_ JsModuleRecord requestModule, + _In_ JsModuleHostInfoKind moduleHostInfo, + _Outptr_result_maybenull_ void** hostInfo); + +/// +/// Returns metadata relating to the exception that caused the runtime of the current context +/// to be in the exception state and resets the exception state for that runtime. The metadata +/// includes a reference to the exception itself. +/// +/// +/// +/// If the runtime of the current context is not in an exception state, this API will return +/// JsErrorInvalidArgument. If the runtime is disabled, this will return an exception +/// indicating that the script was terminated, but it will not clear the exception (the +/// exception will be cleared if the runtime is re-enabled using +/// JsEnableRuntimeExecution). +/// +/// +/// The metadata value is a javascript object with the following properties: exception, the +/// thrown exception object; line, the 0 indexed line number where the exception was thrown; +/// column, the 0 indexed column number where the exception was thrown; length, the +/// source-length of the cause of the exception; source, a string containing the line of +/// source code where the exception was thrown; and url, a string containing the name of +/// the script file containing the code that threw the exception. +/// +/// +/// Requires an active script context. +/// +/// +/// The exception metadata for the runtime of the current context. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsGetAndClearExceptionWithMetadata( + _Out_ JsValueRef *metadata); + +/// +/// Called by the runtime to load the source code of the serialized script. +/// +/// The context passed to Js[Parse|Run]SerializedScriptCallback +/// The script returned. +/// +/// true if the operation succeeded, false otherwise. +/// +typedef bool (CHAKRA_CALLBACK * JsSerializedLoadScriptCallback) + (JsSourceContext sourceContext, _Out_ JsValueRef *value, + _Out_ JsParseScriptAttributes *parseAttributes); + +/// +/// Create JavascriptString variable from ASCII or Utf8 string +/// +/// +/// +/// Input string can be either ASCII or Utf8 +/// +/// +/// Pointer to string memory. +/// Number of bytes within the string +/// JsValueRef representing the JavascriptString +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCreateString( + _In_ const char *content, + _In_ size_t length, + _Out_ JsValueRef *value); + +/// +/// Create JavascriptString variable from Utf16 string +/// +/// +/// +/// Expects Utf16 string +/// +/// +/// Pointer to string memory. +/// Number of characters within the string +/// JsValueRef representing the JavascriptString +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCreateStringUtf16( + _In_ const uint16_t *content, + _In_ size_t length, + _Out_ JsValueRef *value); + +/// +/// Write JavascriptString value into C string buffer (Utf8) +/// +/// +/// +/// When size of the `buffer` is unknown, +/// `buffer` argument can be nullptr. +/// In that case, `length` argument will return the length needed. +/// +/// +/// JavascriptString value +/// Pointer to buffer +/// Buffer size +/// Total number of characters needed or written +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCopyString( + _In_ JsValueRef value, + _Out_opt_ char* buffer, + _In_ size_t bufferSize, + _Out_opt_ size_t* length); + +/// +/// Write string value into Utf16 string buffer +/// +/// +/// +/// When size of the `buffer` is unknown, +/// `buffer` argument can be nullptr. +/// In that case, `written` argument will return the length needed. +/// +/// +/// when start is out of range or < 0, returns JsErrorInvalidArgument +/// and `written` will be equal to 0. +/// If calculated length is 0 (It can be due to string length or `start` +/// and length combination), then `written` will be equal to 0 and call +/// returns JsNoError +/// +/// +/// JavascriptString value +/// start offset of buffer +/// length to be written +/// Pointer to buffer +/// Total number of characters written +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCopyStringUtf16( + _In_ JsValueRef value, + _In_ int start, + _In_ int length, + _Out_opt_ uint16_t* buffer, + _Out_opt_ size_t* written); + +/// +/// Parses a script and returns a function representing the script. +/// +/// +/// +/// Requires an active script context. +/// +/// +/// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. +/// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, +/// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. +/// +/// +/// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source +/// for better performance and smaller memory footprint. +/// +/// +/// The script to run. +/// +/// A cookie identifying the script that can be used by debuggable script contexts. +/// +/// The location the script came from. +/// Attribute mask for parsing the script +/// The result of the compiled script. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsParse( + _In_ JsValueRef script, + _In_ JsSourceContext sourceContext, + _In_ JsValueRef sourceUrl, + _In_ JsParseScriptAttributes parseAttributes, + _Out_ JsValueRef *result); + +/// +/// Executes a script. +/// +/// +/// +/// Requires an active script context. +/// +/// +/// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. +/// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, +/// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. +/// +/// +/// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source +/// for better performance and smaller memory footprint. +/// +/// +/// The script to run. +/// +/// A cookie identifying the script that can be used by debuggable script contexts. +/// +/// The location the script came from +/// Attribute mask for parsing the script +/// The result of the script, if any. This parameter can be null. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsRun( + _In_ JsValueRef script, + _In_ JsSourceContext sourceContext, + _In_ JsValueRef sourceUrl, + _In_ JsParseScriptAttributes parseAttributes, + _Out_ JsValueRef *result); + +/// +/// Creates the property ID associated with the name. +/// +/// +/// +/// Property IDs are specific to a context and cannot be used across contexts. +/// +/// +/// Requires an active script context. +/// +/// +/// +/// The name of the property ID to get or create. The name may consist of only digits. +/// The string is expected to be ASCII / utf8 encoded. +/// +/// length of the name in bytes +/// The property ID in this runtime for the given name. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCreatePropertyId( + _In_z_ const char *name, + _In_ size_t length, + _Out_ JsPropertyIdRef *propertyId); + +/// +/// Copies the name associated with the property ID into a buffer. +/// +/// +/// +/// Requires an active script context. +/// +/// +/// When size of the `buffer` is unknown, +/// `buffer` argument can be nullptr. +/// `length` argument will return the size needed. +/// +/// +/// The property ID to get the name of. +/// The buffer holding the name associated with the property ID, encoded as utf8 +/// Size of the buffer. +/// Total number of characters written or to be written +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCopyPropertyId( + _In_ JsPropertyIdRef propertyId, + _Out_ char* buffer, + _In_ size_t bufferSize, + _Out_ size_t* length); + +/// +/// Serializes a parsed script to a buffer than can be reused. +/// +/// +/// +/// JsSerializeScript parses a script and then stores the parsed form of the script in a +/// runtime-independent format. The serialized script then can be deserialized in any +/// runtime without requiring the script to be re-parsed. +/// +/// +/// Requires an active script context. +/// +/// +/// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. +/// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, +/// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. +/// +/// +/// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source +/// for better performance and smaller memory footprint. +/// +/// +/// The script to serialize +/// ArrayBuffer +/// Encoding for the script. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsSerialize( + _In_ JsValueRef script, + _Out_ JsValueRef *buffer, + _In_ JsParseScriptAttributes parseAttributes); + +/// +/// Parses a serialized script and returns a function representing the script. +/// Provides the ability to lazy load the script source only if/when it is needed. +/// +/// +/// +/// Requires an active script context. +/// +/// +/// The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer). +/// +/// Callback called when the source code of the script needs to be loaded. +/// This is an optional parameter, set to null if not needed. +/// +/// +/// A cookie identifying the script that can be used by debuggable script contexts. +/// This context will passed into scriptLoadCallback. +/// +/// The location the script came from. +/// A function representing the script code. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsParseSerialized( + _In_ JsValueRef buffer, + _In_ JsSerializedLoadScriptCallback scriptLoadCallback, + _In_ JsSourceContext sourceContext, + _In_ JsValueRef sourceUrl, + _Out_ JsValueRef *result); + +/// +/// Runs a serialized script. +/// Provides the ability to lazy load the script source only if/when it is needed. +/// +/// +/// +/// Requires an active script context. +/// +/// +/// The runtime will hold on to the buffer until all instances of any functions created from +/// the buffer are garbage collected. +/// +/// +/// The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer). +/// Callback called when the source code of the script needs to be loaded. +/// +/// A cookie identifying the script that can be used by debuggable script contexts. +/// This context will passed into scriptLoadCallback. +/// +/// The location the script came from. +/// +/// The result of running the script, if any. This parameter can be null. +/// +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsRunSerialized( + _In_ JsValueRef buffer, + _In_ JsSerializedLoadScriptCallback scriptLoadCallback, + _In_ JsSourceContext sourceContext, + _In_ JsValueRef sourceUrl, + _Out_ JsValueRef *result); + +/// +/// Creates a new JavaScript Promise object. +/// +/// +/// Requires an active script context. +/// +/// The new Promise object. +/// The function called to resolve the created Promise object. +/// The function called to reject the created Promise object. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCreatePromise( + _Out_ JsValueRef *promise, + _Out_ JsValueRef *resolveFunction, + _Out_ JsValueRef *rejectFunction); + +/// +/// A weak reference to a JavaScript value. +/// +/// +/// A value with only weak references is available for garbage-collection. A strong reference +/// to the value (JsValueRef) may be obtained from a weak reference if the value happens +/// to still be available. +/// +typedef JsRef JsWeakRef; + +/// +/// Creates a weak reference to a value. +/// +/// The value to be referenced. +/// Weak reference to the value. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsCreateWeakReference( + _In_ JsValueRef value, + _Out_ JsWeakRef* weakRef); + +/// +/// Gets a strong reference to the value referred to by a weak reference. +/// +/// A weak reference. +/// Reference to the value, or JS_INVALID_REFERENCE if the value is +/// no longer available. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsGetWeakReferenceValue( + _In_ JsWeakRef weakRef, + _Out_ JsValueRef* value); + +/// +/// Creates a Javascript SharedArrayBuffer object with shared content get from JsGetSharedArrayBufferContent. +/// +/// +/// Requires an active script context. +/// +/// +/// The storage object of a SharedArrayBuffer which can be shared between multiple thread. +/// +/// The new SharedArrayBuffer object. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsCreateSharedArrayBufferWithSharedContent( + _In_ JsSharedArrayBufferContentHandle sharedContents, + _Out_ JsValueRef *result); + +/// +/// Get the storage object from a SharedArrayBuffer. +/// +/// +/// Requires an active script context. +/// +/// The SharedArrayBuffer object. +/// +/// The storage object of a SharedArrayBuffer which can be shared between multiple thread. +/// User should call JsReleaseSharedArrayBufferContentHandle after finished using it. +/// +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsGetSharedArrayBufferContent( + _In_ JsValueRef sharedArrayBuffer, + _Out_ JsSharedArrayBufferContentHandle *sharedContents); + +/// +/// Decrease the reference count on a SharedArrayBuffer storage object. +/// +/// +/// Requires an active script context. +/// +/// +/// The storage object of a SharedArrayBuffer which can be shared between multiple thread. +/// +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsReleaseSharedArrayBufferContentHandle( + _In_ JsSharedArrayBufferContentHandle sharedContents); + +/// +/// Determines whether an object has a non-inherited property. +/// +/// +/// Requires an active script context. +/// +/// The object that may contain the property. +/// The ID of the property. +/// Whether the object has the non-inherited property. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsHasOwnProperty( + _In_ JsValueRef object, + _In_ JsPropertyIdRef propertyId, + _Out_ bool *hasOwnProperty); + +/// +/// Write JS string value into char string buffer without a null terminator +/// +/// +/// +/// When size of the `buffer` is unknown, +/// `buffer` argument can be nullptr. +/// In that case, `written` argument will return the length needed. +/// +/// +/// When start is out of range or < 0, returns JsErrorInvalidArgument +/// and `written` will be equal to 0. +/// If calculated length is 0 (It can be due to string length or `start` +/// and length combination), then `written` will be equal to 0 and call +/// returns JsNoError +/// +/// +/// The JS string `value` will be converted one utf16 code point at a time, +/// and if it has code points that do not fit in one byte, those values +/// will be truncated. +/// +/// +/// JavascriptString value +/// Start offset of buffer +/// Number of characters to be written +/// Pointer to buffer +/// Total number of characters written +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API +JsCopyStringOneByte( + _In_ JsValueRef value, + _In_ int start, + _In_ int length, + _Out_opt_ char* buffer, + _Out_opt_ size_t* written); + +/// +/// Obtains frequently used properties of a data view. +/// +/// The data view instance. +/// The ArrayBuffer backstore of the view. +/// The offset in bytes from the start of arrayBuffer referenced by the array. +/// The number of bytes in the array. +/// +/// The code JsNoError if the operation succeeded, a failure code otherwise. +/// +CHAKRA_API + JsGetDataViewInfo( + _In_ JsValueRef dataView, + _Out_opt_ JsValueRef *arrayBuffer, + _Out_opt_ unsigned int *byteOffset, + _Out_opt_ unsigned int *byteLength); + +#endif // _CHAKRACOREBUILD +#endif // _CHAKRACORE_H_ diff --git a/ios/libnode/include/node/ChakraCoreVersion.h b/ios/libnode/include/node/ChakraCoreVersion.h new file mode 100644 index 0000000..d4ca57e --- /dev/null +++ b/ios/libnode/include/node/ChakraCoreVersion.h @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. +//------------------------------------------------------------------------------------------------------- +#pragma once + +// NOTE: When changing this file, you may need to update the GUID in ByteCodeCacheReleaseFileVersion.h +// Please update the GUID when: +// * CHAKRA_CORE_VERSION_RELEASE is changed to 1 +// * CHAKRA_CORE_VERSION_RELEASE is currently set to 1 and the bytecode changes +// See notes below about ReleaseVersioningScheme. + +// -------------- +// VERSION NUMBER +// -------------- + +// ChakraCore version number definitions (used in ChakraCore binary metadata) +#define CHAKRA_CORE_MAJOR_VERSION 1 +#define CHAKRA_CORE_MINOR_VERSION 7 +#define CHAKRA_CORE_PATCH_VERSION 2 +#define CHAKRA_CORE_VERSION_RELEASE_QFE 0 // Redundant with PATCH_VERSION. Keep this value set to 0. + +// ------------- +// RELEASE FLAGS +// ------------- + +// NOTE: CHAKRA_CORE_VERSION_PRERELEASE can only be set to 1 when +// CHAKRA_CORE_VERSION_RELEASE is set to 1, or there is no effect. +// Here are the meanings of the various combinations: +// +// RELEASE** PRERELEASE +// DEVELOPMENT 0 0 +// 0 1 # INVALID but identical to DEVELOPMENT +// RELEASE** 1 0 # +// PRERELEASE 1 1 +// ** Release flags are not related to build type (e.g. x64_release) +// +// Unless otherwise noted, the code affected by these flags lies mostly in bin/CoreCommon.ver +// +// DEVELOPMENT: +// * Uses EngineeringVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) +// * Sets file flag VS_FF_PRIVATEBUILD +// * Adds "Private" to the file description +// +// RELEASE** and PRERELEASE (i.e. controlled by CHAKRA_CORE_VERSION_RELEASE flag): +// * Uses ReleaseVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) +// +// PRERELEASE (preparing for release but not yet ready to release): +// * Sets file flag VS_FF_PRERELEASE +// * Adds "Pre-release" to the file description +// +// RELEASE** (code is ready to release) +// * Sets neither of the file flags noted above +// * Does not add anything to the file description + +// ChakraCore RELEASE and PRERELEASE flags +#define CHAKRA_CORE_VERSION_RELEASE 1 +#define CHAKRA_CORE_VERSION_PRERELEASE 0 + +// Chakra RELEASE flag +// Mostly redundant with CHAKRA_CORE_VERSION_RELEASE, +// but semantically refers to Chakra rather than ChakraCore. +#define CHAKRA_VERSION_RELEASE 0 diff --git a/ios/libnode/include/node/ChakraDebug.h b/ios/libnode/include/node/ChakraDebug.h new file mode 100644 index 0000000..c9736d0 --- /dev/null +++ b/ios/libnode/include/node/ChakraDebug.h @@ -0,0 +1,1014 @@ +//------------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. +//------------------------------------------------------------------------------------------------------- +/// \mainpage Chakra Hosting Debugging API Reference +/// +/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can +/// also be hosted independently by other applications. This reference describes the APIs available +/// to applications to debug JavaScript. + +/// \file +/// \brief The Chakra hosting debugging API. +/// +/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll. + +#ifdef _MSC_VER +#pragma once +#endif // _MSC_VER + +#ifndef _CHAKRADEBUG_H_ +#define _CHAKRADEBUG_H_ + +#ifdef _WIN32 +//Other platforms already include and have this defined automatically +typedef __int64 int64_t; +typedef unsigned __int32 uint32_t; +#endif + + /// + /// Debug events reported from ChakraCore engine. + /// + typedef enum _JsDiagDebugEvent + { + /// + /// Indicates a new script being compiled, this includes script, eval, new function. + /// + JsDiagDebugEventSourceCompile = 0, + /// + /// Indicates compile error for a script. + /// + JsDiagDebugEventCompileError = 1, + /// + /// Indicates a break due to a breakpoint. + /// + JsDiagDebugEventBreakpoint = 2, + /// + /// Indicates a break after completion of step action. + /// + JsDiagDebugEventStepComplete = 3, + /// + /// Indicates a break due to debugger statement. + /// + JsDiagDebugEventDebuggerStatement = 4, + /// + /// Indicates a break due to async break. + /// + JsDiagDebugEventAsyncBreak = 5, + /// + /// Indicates a break due to a runtime script exception. + /// + JsDiagDebugEventRuntimeException = 6 + } JsDiagDebugEvent; + + /// + /// Break on Exception attributes. + /// + typedef enum _JsDiagBreakOnExceptionAttributes + { + /// + /// Don't break on any exception. + /// + JsDiagBreakOnExceptionAttributeNone = 0x0, + /// + /// Break on uncaught exception. + /// + JsDiagBreakOnExceptionAttributeUncaught = 0x1, + /// + /// Break on first chance exception. + /// + JsDiagBreakOnExceptionAttributeFirstChance = 0x2 + } JsDiagBreakOnExceptionAttributes; + + /// + /// Stepping types. + /// + typedef enum _JsDiagStepType + { + /// + /// Perform a step operation to next statement. + /// + JsDiagStepTypeStepIn = 0, + /// + /// Perform a step out from the current function. + /// + JsDiagStepTypeStepOut = 1, + /// + /// Perform a single step over after a debug break if the next statement is a function call, else behaves as a stepin. + /// + JsDiagStepTypeStepOver = 2, + /// + /// Perform a single step back to the previous statement (only applicable in TTD mode). + /// + JsDiagStepTypeStepBack = 3, + /// + /// Perform a reverse continue operation (only applicable in TTD mode). + /// + JsDiagStepTypeReverseContinue = 4, + /// + /// Perform a forward continue operation. Clears any existing step value. + /// + JsDiagStepTypeContinue = 5 + } JsDiagStepType; + + /// + /// User implemented callback routine for debug events. + /// + /// + /// Use JsDiagStartDebugging to register the callback. + /// + /// The type of JsDiagDebugEvent event. + /// Additional data related to the debug event. + /// The state passed to JsDiagStartDebugging. + typedef void (CHAKRA_CALLBACK * JsDiagDebugEventCallback)(_In_ JsDiagDebugEvent debugEvent, _In_ JsValueRef eventData, _In_opt_ void* callbackState); + + /// + /// Starts debugging in the given runtime. + /// + /// Runtime to put into debug mode. + /// Registers a callback to be called on every JsDiagDebugEvent. + /// User provided state that will be passed back to the callback. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The runtime should be active on the current thread and should not be in debug state. + /// + CHAKRA_API + JsDiagStartDebugging( + _In_ JsRuntimeHandle runtimeHandle, + _In_ JsDiagDebugEventCallback debugEventCallback, + _In_opt_ void* callbackState); + + /// + /// Stops debugging in the given runtime. + /// + /// Runtime to stop debugging. + /// User provided state that was passed in JsDiagStartDebugging. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The runtime should be active on the current thread and in debug state. + /// + CHAKRA_API + JsDiagStopDebugging( + _In_ JsRuntimeHandle runtimeHandle, + _Out_ void** callbackState); + + /// + /// Request the runtime to break on next JavaScript statement. + /// + /// Runtime to request break. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The runtime should be in debug state. This API can be called from another runtime. + /// + CHAKRA_API + JsDiagRequestAsyncBreak( + _In_ JsRuntimeHandle runtimeHandle); + + /// + /// List all breakpoints in the current runtime. + /// + /// Array of breakpoints. + /// + /// + /// [{ + /// "breakpointId" : 1, + /// "scriptId" : 1, + /// "line" : 0, + /// "column" : 62 + /// }] + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagGetBreakpoints( + _Out_ JsValueRef *breakpoints); + + /// + /// Sets breakpoint in the specified script at give location. + /// + /// Id of script from JsDiagGetScripts or JsDiagGetSource to put breakpoint. + /// 0 based line number to put breakpoint. + /// 0 based column number to put breakpoint. + /// Breakpoint object with id, line and column if success. + /// + /// + /// { + /// "breakpointId" : 1, + /// "line" : 2, + /// "column" : 4 + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagSetBreakpoint( + _In_ unsigned int scriptId, + _In_ unsigned int lineNumber, + _In_ unsigned int columnNumber, + _Out_ JsValueRef *breakpoint); + + /// + /// Remove a breakpoint. + /// + /// Breakpoint id returned from JsDiagSetBreakpoint. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagRemoveBreakpoint( + _In_ unsigned int breakpointId); + + /// + /// Sets break on exception handling. + /// + /// Runtime to set break on exception attributes. + /// Mask of JsDiagBreakOnExceptionAttributes to set. + /// + /// + /// If this API is not called the default value is set to JsDiagBreakOnExceptionAttributeUncaught in the runtime. + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The runtime should be in debug state. This API can be called from another runtime. + /// + CHAKRA_API + JsDiagSetBreakOnException( + _In_ JsRuntimeHandle runtimeHandle, + _In_ JsDiagBreakOnExceptionAttributes exceptionAttributes); + + /// + /// Gets break on exception setting. + /// + /// Runtime from which to get break on exception attributes, should be in debug mode. + /// Mask of JsDiagBreakOnExceptionAttributes. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The runtime should be in debug state. This API can be called from another runtime. + /// + CHAKRA_API + JsDiagGetBreakOnException( + _In_ JsRuntimeHandle runtimeHandle, + _Out_ JsDiagBreakOnExceptionAttributes* exceptionAttributes); + + /// + /// Sets the step type in the runtime after a debug break. + /// + /// + /// Requires to be at a debug break. + /// + /// Type of JsDiagStepType. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagSetStepType( + _In_ JsDiagStepType stepType); + + /// + /// Gets list of scripts. + /// + /// Array of script objects. + /// + /// + /// [{ + /// "scriptId" : 2, + /// "fileName" : "c:\\Test\\Test.js", + /// "lineCount" : 4, + /// "sourceLength" : 111 + /// }, { + /// "scriptId" : 3, + /// "parentScriptId" : 2, + /// "scriptType" : "eval code", + /// "lineCount" : 1, + /// "sourceLength" : 12 + /// }] + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagGetScripts( + _Out_ JsValueRef *scriptsArray); + + /// + /// Gets source for a specific script identified by scriptId from JsDiagGetScripts. + /// + /// Id of the script. + /// Source object. + /// + /// + /// { + /// "scriptId" : 1, + /// "fileName" : "c:\\Test\\Test.js", + /// "lineCount" : 12, + /// "sourceLength" : 15154, + /// "source" : "var x = 1;" + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagGetSource( + _In_ unsigned int scriptId, + _Out_ JsValueRef *source); + + /// + /// Gets the source information for a function object. + /// + /// JavaScript function. + /// Function position - scriptId, start line, start column, line number of first statement, column number of first statement. + /// + /// + /// { + /// "scriptId" : 1, + /// "fileName" : "c:\\Test\\Test.js", + /// "line" : 1, + /// "column" : 2, + /// "firstStatementLine" : 6, + /// "firstStatementColumn" : 0 + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// This API can be called when runtime is at a break or running. + /// + CHAKRA_API + JsDiagGetFunctionPosition( + _In_ JsValueRef function, + _Out_ JsValueRef *functionPosition); + + /// + /// Gets the stack trace information. + /// + /// Stack trace information. + /// + /// + /// [{ + /// "index" : 0, + /// "scriptId" : 2, + /// "line" : 3, + /// "column" : 0, + /// "sourceLength" : 9, + /// "sourceText" : "var x = 1", + /// "functionHandle" : 1 + /// }] + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagGetStackTrace( + _Out_ JsValueRef *stackTrace); + + /// + /// Gets the list of properties corresponding to the frame. + /// + /// Index of stack frame from JsDiagGetStackTrace. + /// Object of properties array (properties, scopes and globals). + /// + /// + /// propertyAttributes is a bit mask of + /// NONE = 0x1, + /// HAVE_CHILDRENS = 0x2, + /// READ_ONLY_VALUE = 0x4, + /// + /// + /// { + /// "thisObject": { + /// "name": "this", + /// "type" : "object", + /// "className" : "Object", + /// "display" : "{...}", + /// "propertyAttributes" : 1, + /// "handle" : 306 + /// }, + /// "exception" : { + /// "name" : "{exception}", + /// "type" : "object", + /// "display" : "'a' is undefined", + /// "className" : "Error", + /// "propertyAttributes" : 1, + /// "handle" : 307 + /// } + /// "arguments" : { + /// "name" : "arguments", + /// "type" : "object", + /// "display" : "{...}", + /// "className" : "Object", + /// "propertyAttributes" : 1, + /// "handle" : 190 + /// }, + /// "returnValue" : { + /// "name" : "[Return value]", + /// "type" : "undefined", + /// "propertyAttributes" : 0, + /// "handle" : 192 + /// }, + /// "functionCallsReturn" : [{ + /// "name" : "[foo1 returned]", + /// "type" : "number", + /// "value" : 1, + /// "propertyAttributes" : 2, + /// "handle" : 191 + /// } + /// ], + /// "locals" : [], + /// "scopes" : [{ + /// "index" : 0, + /// "handle" : 193 + /// } + /// ], + /// "globals" : { + /// "handle" : 194 + /// } + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagGetStackProperties( + _In_ unsigned int stackFrameIndex, + _Out_ JsValueRef *properties); + + /// + /// Gets the list of children of a handle. + /// + /// Handle of object. + /// 0-based from count of properties, usually 0. + /// Number of properties to return. + /// Array of properties. + /// Handle should be from objects returned from call to JsDiagGetStackProperties. + /// For scenarios where object have large number of properties totalCount can be used to control how many properties are given. + /// + /// + /// { + /// "totalPropertiesOfObject": 10, + /// "properties" : [{ + /// "name" : "__proto__", + /// "type" : "object", + /// "display" : "{...}", + /// "className" : "Object", + /// "propertyAttributes" : 1, + /// "handle" : 156 + /// } + /// ], + /// "debuggerOnlyProperties" : [{ + /// "name" : "[Map]", + /// "type" : "string", + /// "value" : "size = 0", + /// "propertyAttributes" : 2, + /// "handle" : 157 + /// } + /// ] + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagGetProperties( + _In_ unsigned int objectHandle, + _In_ unsigned int fromCount, + _In_ unsigned int totalCount, + _Out_ JsValueRef *propertiesObject); + + /// + /// Gets the object corresponding to handle. + /// + /// Handle of object. + /// Object corresponding to the handle. + /// + /// + /// { + /// "scriptId" : 24, + /// "line" : 1, + /// "column" : 63, + /// "name" : "foo", + /// "type" : "function", + /// "handle" : 2 + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagGetObjectFromHandle( + _In_ unsigned int objectHandle, + _Out_ JsValueRef *handleObject); + + /// + /// Evaluates an expression on given frame. + /// + /// + /// Javascript String or ArrayBuffer (incl. ExternalArrayBuffer). + /// + /// Index of stack frame on which to evaluate the expression. + /// + /// Defines how `expression` (JsValueRef) should be parsed. + /// - `JsParseScriptAttributeNone` when `expression` is a Utf8 encoded ArrayBuffer and/or a Javascript String (encoding independent) + /// - `JsParseScriptAttributeArrayBufferIsUtf16Encoded` when `expression` is Utf16 Encoded ArrayBuffer + /// - `JsParseScriptAttributeLibraryCode` has no use for this function and has similar effect with `JsParseScriptAttributeNone` + /// + /// Forces the result to contain the raw value of the expression result. + /// Result of evaluation. + /// + /// + /// evalResult when evaluating 'this' and return is JsNoError + /// { + /// "name" : "this", + /// "type" : "object", + /// "className" : "Object", + /// "display" : "{...}", + /// "propertyAttributes" : 1, + /// "handle" : 18 + /// } + /// + /// evalResult when evaluating a script which throws JavaScript error and return is JsErrorScriptException + /// { + /// "name" : "a.b.c", + /// "type" : "object", + /// "className" : "Error", + /// "display" : "'a' is undefined", + /// "propertyAttributes" : 1, + /// "handle" : 18 + /// } + /// + /// + /// + /// The code JsNoError if the operation succeeded, evalResult will contain the result + /// The code JsErrorScriptException if evaluate generated a JavaScript exception, evalResult will contain the error details + /// Other error code for invalid parameters or API was not called at break + /// + /// + /// The current runtime should be in debug state. This API can only be called when runtime is at a break. + /// + CHAKRA_API + JsDiagEvaluate( + _In_ JsValueRef expression, + _In_ unsigned int stackFrameIndex, + _In_ JsParseScriptAttributes parseAttributes, + _In_ bool forceSetValueProp, + _Out_ JsValueRef *evalResult); + + ///////////////////// + /// + /// TimeTravel move options as bit flag enum. + /// + typedef enum _JsTTDMoveModes + { + /// + /// Indicates no special actions needed for move. + /// + JsTTDMoveNone = 0x0, + + /// + /// Indicates that we want to move to the first event. + /// + JsTTDMoveFirstEvent = 0x1, + + /// + /// Indicates that we want to move to the last event. + /// + JsTTDMoveLastEvent = 0x2, + + /// + /// Indicates that we want to move to the kth event -- top 32 bits are event count. + /// + JsTTDMoveKthEvent = 0x4, + + /// + /// Indicates if we are doing the scan for a continue operation + /// + JsTTDMoveScanIntervalForContinue = 0x10, + + /// + /// Indicates if we are doing the scan for a continue operation and are in the time-segment where the active breakpoint was + /// + JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment = 0x20, + + /// + /// Indicates if we want to set break on entry or just run and let something else trigger breakpoints. + /// + JsTTDMoveBreakOnEntry = 0x100 + } JsTTDMoveMode; + + /// + /// A handle for URI's that TTD information is written to/read from. + /// + typedef void* JsTTDStreamHandle; + + /// + /// TTD API -- may change in future versions: + /// Construct a JsTTDStreamHandle that will be used to read/write the event log portion of the TTD data based on the uri + /// provided by JsTTDInitializeUriCallback. + /// + /// + /// Exactly one of read or write will be set to true. + /// + /// The length of the uri array that the host passed in for storing log info. + /// The URI that the host passed in for storing log info. + /// The length of the ascii name array that the host passed in for storing log info. + /// An optional ascii string giving a unique name to the resource that the JsTTDStreamHandle will be created for. + /// If the handle should be opened for reading. + /// If the handle should be opened for writing. + /// A JsTTDStreamHandle opened in read/write mode as specified. + typedef JsTTDStreamHandle (CHAKRA_CALLBACK *TTDOpenResourceStreamCallback)(_In_ size_t uriLength, _In_reads_(uriLength) const char* uri, _In_ size_t asciiNameLength, _In_reads_(asciiNameLength) const char* asciiResourceName, _In_ bool read, _In_ bool write); + + /// + /// TTD API -- may change in future versions: + /// A callback for reading data from a handle. + /// + /// The JsTTDStreamHandle to read the data from. + /// The buffer to place the data into. + /// The max number of bytes that should be read. + /// The actual number of bytes read and placed in the buffer. + /// true if the read was successful false otherwise. + typedef bool (CHAKRA_CALLBACK *JsTTDReadBytesFromStreamCallback)(_In_ JsTTDStreamHandle handle, _Out_writes_(size) byte* buff, _In_ size_t size, _Out_ size_t* readCount); + + /// + /// TTD API -- may change in future versions: + /// A callback for writing data to a handle. + /// + /// The JsTTDStreamHandle to write the data to. + /// The buffer to copy the data from. + /// The max number of bytes that should be written. + /// The actual number of bytes written to the HANDLE. + /// true if the write was successful false otherwise. + typedef bool (CHAKRA_CALLBACK *JsTTDWriteBytesToStreamCallback)(_In_ JsTTDStreamHandle handle, _In_reads_(size) const byte* buff, _In_ size_t size, _Out_ size_t* writtenCount); + + /// + /// TTD API -- may change in future versions: + /// Flush and close the stream represented by the HANDLE as needed. + /// + /// + /// Exactly one of read or write will be set to true. + /// + /// The JsTTDStreamHandle to close. + /// If the handle was opened for reading. + /// If the handle was opened for writing. + typedef void (CHAKRA_CALLBACK *JsTTDFlushAndCloseStreamCallback)(_In_ JsTTDStreamHandle handle, _In_ bool read, _In_ bool write); + + /// + /// TTD API -- may change in future versions: + /// Creates a new runtime in Record Mode. + /// + /// The attributes of the runtime to be created. + /// The interval to wait between snapshots (measured in millis). + /// The amount of history to maintain before discarding -- measured in number of snapshots and controls how far back in time a trace can be reversed. + /// The TTDOpenResourceStreamCallback function for generating a JsTTDStreamHandle to read/write serialized data. + /// The JsTTDWriteBytesToStreamCallback function for writing bytes to a JsTTDStreamHandle. + /// The JsTTDFlushAndCloseStreamCallback function for flushing and closing a JsTTDStreamHandle as needed. + /// The thread service for the runtime. Can be null. + /// The runtime created. + /// + /// See JsCreateRuntime for additional information. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsTTDCreateRecordRuntime( + _In_ JsRuntimeAttributes attributes, + _In_ size_t snapInterval, + _In_ size_t snapHistoryLength, + _In_ TTDOpenResourceStreamCallback openResourceStream, + _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, + _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream, + _In_opt_ JsThreadServiceCallback threadService, + _Out_ JsRuntimeHandle *runtime); + + /// + /// TTD API -- may change in future versions: + /// Creates a new runtime in Debug Mode. + /// + /// The attributes of the runtime to be created. + /// The uri where the recorded Time-Travel data should be loaded from. + /// A flag to enable addtional debugging operation support during replay. + /// The TTDOpenResourceStreamCallback function for generating a JsTTDStreamHandle to read/write serialized data. + /// The JsTTDReadBytesFromStreamCallback function for reading bytes from a JsTTDStreamHandle. + /// The JsTTDFlushAndCloseStreamCallback function for flushing and closing a JsTTDStreamHandle as needed. + /// The thread service for the runtime. Can be null. + /// The runtime created. + /// + /// See JsCreateRuntime for additional information. + /// + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API + JsTTDCreateReplayRuntime( + _In_ JsRuntimeAttributes attributes, + _In_reads_(infoUriCount) const char* infoUri, + _In_ size_t infoUriCount, + _In_ bool enableDebugging, + _In_ TTDOpenResourceStreamCallback openResourceStream, + _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, + _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream, + _In_opt_ JsThreadServiceCallback threadService, + _Out_ JsRuntimeHandle *runtime); + + /// + /// TTD API -- may change in future versions: + /// Creates a script context that takes the TTD mode from the log or explicitly is not in TTD mode (regular takes mode from currently active script). + /// + /// The runtime the script context is being created in. + /// Set to true to use runtime TTD mode false to explicitly be non-TTD context. + /// The created script context. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API JsTTDCreateContext( + _In_ JsRuntimeHandle runtimeHandle, + _In_ bool useRuntimeTTDMode, + _Out_ JsContextRef *newContext); + + /// + /// TTD API -- may change in future versions: + /// Notify the time-travel system that a context has been identified as dead by the gc (and is being de-allocated). + /// + /// The script context that is now dead. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + /// + CHAKRA_API JsTTDNotifyContextDestroy( + _In_ JsContextRef context); + + /// + /// TTD API -- may change in future versions: + /// Start Time-Travel record or replay at next turn of event loop. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDStart(); + + /// + /// TTD API -- may change in future versions: + /// Stop Time-Travel record or replay. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDStop(); + + /// + /// TTD API -- may change in future versions: + /// Pause Time-Travel recording before executing code on behalf of debugger or other diagnostic/telemetry. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDPauseTimeTravelBeforeRuntimeOperation(); + + /// + /// TTD API -- may change in future versions: + /// ReStart Time-Travel recording after executing code on behalf of debugger or other diagnostic/telemetry. + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDReStartTimeTravelAfterRuntimeOperation(); + + /// + /// TTD API -- may change in future versions: + /// Notify the Js runtime we are at a safe yield point in the event loop (i.e. no locals on the stack and we can proccess as desired). + /// + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDNotifyYield(); + + /// + /// TTD API -- may change in future versions: + /// Notify the TTD runtime that we are doing a weak add on a reference (we may use this in external API calls and the release will happen in a GC callback). + /// + /// The value we are adding the ref to. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDNotifyLongLivedReferenceAdd(_In_ JsValueRef value); + + /// + /// TTD API -- may change in future versions: + /// Notify the Js runtime the host is aborting the process and what the status code is. + /// + /// The exit status code. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDHostExit(_In_ int statusCode); + + /// + /// TTD API -- may change in future versions: + /// Notify the event log that the contents of one buffer have been copied to a second buffer. + /// + /// The buffer that was written into. + /// The first index modified. + /// The buffer that was copied from. + /// The first index copied. + /// The number of bytes copied. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDRawBufferCopySyncIndirect( + _In_ JsValueRef dst, + _In_ size_t dstIndex, + _In_ JsValueRef src, + _In_ size_t srcIndex, + _In_ size_t count); + + /// + /// TTD API -- may change in future versions: + /// Notify the event log that the contents of a naked byte* buffer passed to the host have been modified synchronously. + /// + /// The buffer that was modified. + /// The first index modified. + /// The number of bytes written. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDRawBufferModifySyncIndirect( + _In_ JsValueRef buffer, + _In_ size_t index, + _In_ size_t count); + + /// + /// TTD API -- may change in future versions: + /// Get info for notifying the TTD system that a raw buffer it shares with the host has been modified. + /// + /// The array buffer we want to monitor for contents modification. + /// The first position in the buffer that may be modified. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDRawBufferAsyncModificationRegister( + _In_ JsValueRef instance, + _In_ byte* initialModPos); + + /// + /// TTD API -- may change in future versions: + /// Notify the event log that the contents of a naked byte* buffer passed to the host have been modified asynchronously. + /// + /// One past the last modified position in the buffer. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDRawBufferAsyncModifyComplete( + _In_ byte* finalModPos); + + /// + /// TTD API -- may change in future versions: + /// A check for unimplmented TTD actions in the host. + /// This API is a TEMPORARY API while we complete the implementation of TTD support in the Node host and will be deleted once that is complete. + /// + /// The message to print if we should be catching this as a TTD operation. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDCheckAndAssertIfTTDRunning( + _In_ const char* msg); + + /// + /// TTD API -- may change in future versions: + /// Before calling JsTTDMoveToTopLevelEvent (which inflates a snapshot and replays) check to see if we want to reset the script context. + /// We reset the script context if the move will require inflating from a different snapshot that the last one. + /// + /// The runtime handle that the script is executing in. + /// Flags controlling the way the move it performed and how other parameters are interpreted. + /// When moveMode == JsTTDMoveKthEvent indicates which event, otherwise this parameter is ignored. + /// The event time we want to move to or -1 if not relevant. + /// Out parameter with the event time of the snapshot that we should inflate from. + /// Optional Out parameter with the snapshot time following the event. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API JsTTDGetSnapTimeTopLevelEventMove( + _In_ JsRuntimeHandle runtimeHandle, + _In_ JsTTDMoveMode moveMode, + _In_opt_ uint32_t kthEvent, + _Inout_ int64_t* targetEventTime, + _Out_ int64_t* targetStartSnapTime, + _Out_opt_ int64_t* targetEndSnapTime); + + /// + /// TTD API -- may change in future versions: + /// Get the snapshot interval that bounds the target event time. + /// + /// The runtime handle that the script is executing in. + /// The event time we want to get the interval for. + /// The snapshot time that comes before the desired event. + /// The snapshot time that comes after the desired event (-1 if the leg ends before a snapshot appears). + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API JsTTDGetSnapShotBoundInterval( + _In_ JsRuntimeHandle runtimeHandle, + _In_ int64_t targetEventTime, + _Out_ int64_t* startSnapTime, + _Out_ int64_t* endSnapTime); + + /// + /// TTD API -- may change in future versions: + /// Get the snapshot interval that precedes the one given by currentSnapStartTime (or -1 if there is no such interval). + /// + /// The runtime handle that the script is executing in. + /// The current snapshot interval start time. + /// The resulting previous snapshot interval start time or -1 if no such time. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API JsTTDGetPreviousSnapshotInterval( + _In_ JsRuntimeHandle runtimeHandle, + _In_ int64_t currentSnapStartTime, + _Out_ int64_t* previousSnapTime); + + /// + /// TTD API -- may change in future versions: + /// During debug operations some additional information is populated during replay. This runs the code between the given + /// snapshots to poulate this information which may be needed by the debugger to determine time-travel jump targets. + /// + /// The runtime handle that the script is executing in. + ///The snapshot time that we will start executing from.< / param> + ///The snapshot time that we will stop at (or -1 if we want to run to the end).< / param> + /// Additional flags for controling how the move is done. + /// The updated target event time set according to the moveMode (-1 if not found). + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API JsTTDPreExecuteSnapShotInterval( + _In_ JsRuntimeHandle runtimeHandle, + _In_ int64_t startSnapTime, + _In_ int64_t endSnapTime, + _In_ JsTTDMoveMode moveMode, + _Out_ int64_t* newTargetEventTime); + + /// + /// TTD API -- may change in future versions: + /// Move to the given top-level call event time (assuming JsTTDPrepContextsForTopLevelEventMove) was called previously to reset any script contexts. + /// This also computes the ready-to-run snapshot if needed. + /// + /// The runtime handle that the script is executing in. + /// Additional flags for controling how the move is done. + /// The event time that we will start executing from to move to the given target time. + /// The event that we want to move to. + /// The code JsNoError if the operation succeeded, a failure code otherwise. + CHAKRA_API + JsTTDMoveToTopLevelEvent( + _In_ JsRuntimeHandle runtimeHandle, + _In_ JsTTDMoveMode moveMode, + _In_ int64_t snapshotTime, + _In_ int64_t eventTime); + + /// + /// TTD API -- may change in future versions: + /// Execute from the current point in the log to the end returning the error code. + /// + /// Additional flags for controling how the move is done. + /// The event time that we should move to next or notification (-1) that replay has ended. + /// + /// If the debugger requested an abort the code is JsNoError -- rootEventTime is the target event time we need to move to and re - execute from. + /// If we aborted at the end of the replay log the code is JsNoError -- rootEventTime is -1. + /// If there was an unhandled script exception the code is JsErrorCategoryScript. + /// + CHAKRA_API + JsTTDReplayExecution( + _Inout_ JsTTDMoveMode* moveMode, + _Out_ int64_t* rootEventTime); + +#endif // _CHAKRADEBUG_H_ diff --git a/ios/libnode/include/node/base/logging.h b/ios/libnode/include/node/base/logging.h new file mode 100644 index 0000000..b74e27b --- /dev/null +++ b/ios/libnode/include/node/base/logging.h @@ -0,0 +1,131 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_BASE_LOGGING_H_ +#define DEPS_CHAKRASHIM_SRC_BASE_LOGGING_H_ + +#include +#include +#include + +#include "v8config.h" + +#if defined(__GNUC__) +#define PRINTF_FORMAT(format_param, dots_param) \ + __attribute__((format(printf, format_param, dots_param))) +#else +#define PRINTF_FORMAT(format_param, dots_param) +#endif + +extern "C" PRINTF_FORMAT(3, 4) +void V8_Fatal(const char* file, int line, const char* format, ...); + +#ifdef DEBUG +#define UNREACHABLE() \ + V8_Fatal(__FILE__, __LINE__, "unreachable code") +#else +#define UNREACHABLE() V8_Fatal("", 0, "unreachable code") +#endif + + +namespace v8 { +namespace base { + +// CHECK dies with a fatal error if condition is not true. It is *not* +// controlled by DEBUG, so the check will be executed regardless of +// compilation mode. +// +// We make sure CHECK et al. always evaluates their arguments, as +// doing CHECK(FunctionWithSideEffect()) is a common idiom. +#define CHECK(condition) \ + do { \ + if (V8_UNLIKELY(!(condition))) { \ + V8_Fatal(__FILE__, __LINE__, "Check failed: %s.", #condition); \ + } \ + } while (0) + + +#ifdef DEBUG + +// Helper macro for binary operators. +// Don't use this macro directly in your code, use CHECK_EQ et al below. +#define CHECK_OP(name, op, lhs, rhs) \ + do { \ + if (std::string* _msg = ::v8::base::Check##name##Impl( \ + (lhs), (rhs), #lhs " " #op " " #rhs)) { \ + V8_Fatal(__FILE__, __LINE__, "Check failed: %s.", _msg->c_str()); \ + delete _msg; \ + } \ + } while (0) + +#else + +// Make all CHECK functions discard their log strings to reduce code +// bloat for official release builds. +#define CHECK_OP(name, op, lhs, rhs) CHECK((lhs)op(rhs)) + +#endif + + +// Build the error message string. This is separate from the "Impl" +// function template because it is not performance critical and so can +// be out of line, while the "Impl" code should be inline. Caller +// takes ownership of the returned string. +template +std::string* MakeCheckOpString(Lhs const& lhs, Rhs const& rhs, + char const* msg) { + std::ostringstream ss; + ss << msg << " (" << lhs << " vs. " << rhs << ")"; + return new std::string(ss.str()); +} + +// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated +// in logging.cc. +#define DEFINE_MAKE_CHECK_OP_STRING(type) \ + extern template std::string* MakeCheckOpString( \ + type const&, type const&, char const*); + DEFINE_MAKE_CHECK_OP_STRING(unsigned long long) // NOLINT(runtime/int) +#undef DEFINE_MAKE_CHECK_OP_STRING + + +// Helper functions for CHECK_OP macro. +// The (int, int) specialization works around the issue that the compiler +// will not instantiate the template version of the function on values of +// unnamed enum type - see comment below. +// The (float, float) and (double, double) instantiations are explicitly +// externialized to ensure proper 32/64-bit comparisons on x86. +#define DEFINE_CHECK_OP_IMPL(NAME, op) \ + template \ + V8_INLINE std::string* Check##NAME##Impl(Lhs const& lhs, Rhs const& rhs, \ + char const* msg) { \ + return V8_LIKELY(lhs op rhs) ? nullptr : MakeCheckOpString(lhs, rhs, msg); \ + } \ + V8_INLINE std::string* Check##NAME##Impl(int lhs, int rhs, \ + char const* msg) { \ + return V8_LIKELY(lhs op rhs) ? nullptr : MakeCheckOpString(lhs, rhs, msg); \ + } \ + extern template std::string* Check##NAME##Impl( \ + float const& lhs, float const& rhs, char const* msg); \ + extern template std::string* Check##NAME##Impl( \ + double const& lhs, double const& rhs, char const* msg); + DEFINE_CHECK_OP_IMPL(LT, <) +#undef DEFINE_CHECK_OP_IMPL + +#define CHECK_LT(lhs, rhs) CHECK_OP(LT, <, lhs, rhs) + +} // namespace base +} // namespace v8 + + +// The DCHECK macro is equivalent to CHECK except that it only +// generates code in debug builds. +#ifdef DEBUG +#define DCHECK(condition) CHECK(condition) +#define DCHECK_LT(v1, v2) CHECK_LT(v1, v2) +#else +#define DCHECK(condition) ((void) 0) +#define DCHECK_LT(v1, v2) ((void) 0) +#endif + +#endif // DEPS_CHAKRASHIM_SRC_BASE_LOGGING_H_ diff --git a/ios/libnode/include/node/base/macros.h b/ios/libnode/include/node/base/macros.h new file mode 100644 index 0000000..1bfadfc --- /dev/null +++ b/ios/libnode/include/node/base/macros.h @@ -0,0 +1,51 @@ +// Copyright 2014 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_BASE_MACROS_H_ +#define DEPS_CHAKRASHIM_SRC_BASE_MACROS_H_ + +#include "logging.h" + +// The arraysize(arr) macro returns the # of elements in an array arr. +// The expression is a compile-time constant, and therefore can be +// used in defining new arrays, for example. If you use arraysize on +// a pointer by mistake, you will get a compile-time error. +#define arraysize(array) (sizeof(ArraySizeHelper(array))) + +// This template function declaration is used in defining arraysize. +// Note that the function doesn't need an implementation, as we only +// use its type. +template +char (&ArraySizeHelper(T (&array)[N]))[N]; + +#if !V8_CC_MSVC +// That gcc wants both of these prototypes seems mysterious. VC, for +// its part, can't decide which to use (another mystery). Matching of +// template overloads: the final frontier. +template +char (&ArraySizeHelper(const T (&array)[N]))[N]; +#endif + +// A macro to disallow the evil copy constructor and operator= functions +// This should be used in the private: declarations for a class +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + void operator=(const TypeName&) = delete + +// A macro to disallow all the implicit constructors, namely the +// default constructor, copy constructor and operator= functions. +// +// This should be used in the private: declarations for a class +// that wants to prevent anyone from instantiating it. This is +// especially useful for classes containing only static methods. +#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName() = delete; \ + DISALLOW_COPY_AND_ASSIGN(TypeName) + +// The USE(x) template is used to silence C++ compiler warnings +// issued for (yet) unused variables (typically parameters). +template +inline void USE(T) { } + +#endif // DEPS_CHAKRASHIM_SRC_BASE_MACROS_H_ diff --git a/ios/libnode/include/node/base/platform/platform.h b/ios/libnode/include/node/base/platform/platform.h new file mode 100644 index 0000000..165fab8 --- /dev/null +++ b/ios/libnode/include/node/base/platform/platform.h @@ -0,0 +1,51 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This module contains the platform-specific code. This make the rest of the +// code less dependent on operating system, compilers and runtime libraries. +// This module does specifically not deal with differences between different +// processor architecture. +// The platform classes have the same definition for all platforms. The +// implementation for a particular platform is put in platform_.cc. +// The build system then uses the implementation for the target platform. +// +// This design has been chosen because it is simple and fast. Alternatively, +// the platform dependent classes could have been implemented using abstract +// superclasses with virtual methods and having specializations for each +// platform. This design was rejected because it was more complicated and +// slower. It would require factory methods for selecting the right +// implementation and the overhead of virtual methods for performance +// sensitive like mutex locking/unlocking. + +#ifndef DEPS_CHAKRASHIM_SRC_BASE_PLATFORM_PLATFORM_H_ +#define DEPS_CHAKRASHIM_SRC_BASE_PLATFORM_PLATFORM_H_ + +#include +#include "src/base/macros.h" + +#if defined(__GNUC__) +#define PRINTF_FORMAT(format_param, dots_param) \ + __attribute__((format(printf, format_param, dots_param))) +#else +#define PRINTF_FORMAT(format_param, dots_param) +#endif + +namespace v8 { +namespace base { + +class OS { + public: + static PRINTF_FORMAT(1, 2) void PrintError(const char* format, ...); + static PRINTF_FORMAT(1, 0) void VPrintError(const char* format, va_list args); + static void Abort(); + static PRINTF_FORMAT(3, 4) int SNPrintF(char* str, int length, + const char* format, ...); + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(OS); +}; + +} // namespace base +} // namespace v8 + +#endif // DEPS_CHAKRASHIM_SRC_BASE_PLATFORM_PLATFORM_H_ diff --git a/ios/libnode/include/node/common.gypi b/ios/libnode/include/node/common.gypi index 6677274..498fc7e 100644 --- a/ios/libnode/include/node/common.gypi +++ b/ios/libnode/include/node/common.gypi @@ -10,6 +10,8 @@ 'component%': 'static_library', # NB. these names match with what V8 expects 'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way 'python%': 'python', + 'node_engine%': 'v8', + 'msvs_windows_target_platform_version': 'v10.0', # used for node_engine==chakracore 'node_shared%': 'false', 'force_dynamic_crt%': 0, @@ -38,9 +40,11 @@ ['GENERATOR=="ninja"', { 'OBJ_DIR': '<(PRODUCT_DIR)/obj', 'V8_BASE': '<(PRODUCT_DIR)/obj/deps/v8/src/libv8_base.a', + 'CHAKRASHIM_BASE': '<(PRODUCT_DIR)/obj/deps/chakrashim/libchakrashim.a', }, { 'OBJ_DIR%': '<(PRODUCT_DIR)/obj.target', 'V8_BASE%': '<(PRODUCT_DIR)/obj.target/deps/v8/src/libv8_base.a', + 'CHAKRASHIM_BASE': '<(PRODUCT_DIR)/obj.target/deps/chakrashim/libchakrashim.a', }], ['OS == "win"', { 'os_posix': 0, @@ -52,6 +56,7 @@ 'v8_postmortem_support%': 'true', }], ['OS== "mac"', { + 'CHAKRASHIM_BASE': '<(PRODUCT_DIR)/libchakrashim.a', 'OBJ_DIR%': '<(PRODUCT_DIR)/obj.target', 'V8_BASE': '<(PRODUCT_DIR)/libv8_base.a', }], @@ -68,7 +73,43 @@ ], }, + 'conditions': [ + ['node_engine=="v8"', { + 'target_defaults': { + 'defines': [ + 'NODE_ENGINE_V8', + ], + }, + 'variables': { + 'node_engine_include_dir%': 'deps/v8/include' + }, + }], + ['node_engine=="chakracore"', { + 'target_defaults': { + 'defines': [ + 'NODE_ENGINE_CHAKRACORE', + ], + 'conditions': [ + ['target_arch=="arm"', { + 'msvs_windows_target_platform_version': '<(msvs_windows_target_platform_version)', + }], + ], + }, + 'variables': { + 'node_engine_include_dir%': 'deps/chakrashim/include', + 'conditions': [ + ['OS == "win"', { + 'node_engine_libs': '-lchakracore.lib', + }, { + 'node_engine_libs': '', + }], + ], + }, + }], + ], + 'target_defaults': { + 'defines': ['NODE_ENGINE="<(node_engine)"'], 'default_configuration': 'Release', 'configurations': { 'Debug': { @@ -81,6 +122,9 @@ ['target_arch=="x64"', { 'msvs_configuration_platform': 'x64', }], + ['target_arch=="arm"', { + 'msvs_configuration_platform': 'ARM', + }], ['OS=="aix"', { 'cflags': [ '-gxcoff' ], 'ldflags': [ '-Wl,-bbigtoc' ], @@ -128,6 +172,9 @@ ['target_arch=="x64"', { 'msvs_configuration_platform': 'x64', }], + ['target_arch=="arm"', { + 'msvs_configuration_platform': 'ARM', + }], ['OS=="solaris"', { # pull in V8's postmortem metadata 'ldflags': [ '-Wl,-z,allextract' ] diff --git a/ios/libnode/include/node/config.gypi b/ios/libnode/include/node/config.gypi index 0a4a590..14837b8 100644 --- a/ios/libnode/include/node/config.gypi +++ b/ios/libnode/include/node/config.gypi @@ -5,6 +5,10 @@ 'include_dirs': [], 'libraries': []}, 'variables': { 'asan': 0, + 'chakracore_build_config': 'Release', + 'chakracore_lto_build_flags': [], + 'chakracore_parallel_build_flags': [], + 'chakracore_use_lto': 'false', 'coverage': 'false', 'debug_devtools': 'node', 'debug_http2': 'false', @@ -23,11 +27,12 @@ 'node_byteorder': 'little', 'node_enable_d8': 'false', 'node_enable_v8_vtunejit': 'false', + 'node_engine': 'chakracore', 'node_install_npm': 'true', 'node_module_version': 57, 'node_no_browser_globals': 'false', 'node_prefix': '/', - 'node_release_urlbase': 'https://nodejs.org/download/release/', + 'node_release_urlbase': 'https://nodejs.org/download/chakracore-release/', 'node_shared': 'false', 'node_shared_cares': 'false', 'node_shared_http_parser': 'false', @@ -35,7 +40,7 @@ 'node_shared_openssl': 'false', 'node_shared_zlib': 'false', 'node_tag': '', - 'node_use_bundled_v8': 'true', + 'node_use_bundled_v8': 'false', 'node_use_dtrace': 'true', 'node_use_etw': 'false', 'node_use_lttng': 'false', @@ -57,7 +62,6 @@ 'v8_promise_internal_field_count': 1, 'v8_random_seed': 0, 'v8_trace_maps': 0, - 'v8_use_snapshot': 'false', + 'v8_use_snapshot': 'true', 'want_separate_host_toolset': 0, - 'want_separate_host_toolset_mkpeephole': 0, 'xcode_version': '7.0'}} diff --git a/ios/libnode/include/node/inspector/inspected-context.h b/ios/libnode/include/node/inspector/inspected-context.h new file mode 100644 index 0000000..bf11555 --- /dev/null +++ b/ios/libnode/include/node/inspector/inspected-context.h @@ -0,0 +1,59 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_INSPECTED_CONTEXT_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_INSPECTED_CONTEXT_H_ + +#include "src/base/macros.h" +#include "src/inspector/string-16.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class InjectedScript; +class InjectedScriptHost; +class V8ContextInfo; +class V8InspectorImpl; + +class InspectedContext { + public: + ~InspectedContext(); + + v8::Local context() const; + int contextId() const { return m_contextId; } + int contextGroupId() const { return m_contextGroupId; } + String16 origin() const { return m_origin; } + String16 humanReadableName() const { return m_humanReadableName; } + String16 auxData() const { return m_auxData; } + + bool isReported() const { return m_reported; } + void setReported(bool reported) { m_reported = reported; } + + v8::Isolate* isolate() const; + V8InspectorImpl* inspector() const { return m_inspector; } + + private: + friend class V8InspectorImpl; + InspectedContext(V8InspectorImpl*, const V8ContextInfo&, int contextId); + static void weakCallback(const v8::WeakCallbackInfo&); + static void consoleWeakCallback( + const v8::WeakCallbackInfo&); + + V8InspectorImpl* m_inspector; + v8::Global m_context; + int m_contextId; + int m_contextGroupId; + const String16 m_origin; + const String16 m_humanReadableName; + const String16 m_auxData; + bool m_reported; + v8::Global m_console; + + DISALLOW_COPY_AND_ASSIGN(InspectedContext); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_INSPECTED_CONTEXT_H_ diff --git a/ios/libnode/include/node/inspector/java-script-call-frame.h b/ios/libnode/include/node/inspector/java-script-call-frame.h new file mode 100644 index 0000000..5ee4779 --- /dev/null +++ b/ios/libnode/include/node/inspector/java-script-call-frame.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_JAVA_SCRIPT_CALL_FRAME_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_JAVA_SCRIPT_CALL_FRAME_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/protocol-platform.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class JavaScriptCallFrame { + public: + static std::unique_ptr create(JsValueRef callFrame) { + return wrapUnique(new JavaScriptCallFrame(callFrame)); + } + ~JavaScriptCallFrame(); + + int sourceID() const; + int line() const; + int column() const; + int contextId() const; + + bool isAtReturn() const; + v8::Local details() const; + + v8::MaybeLocal evaluate(v8::Local expression, + bool returnByValue, bool* isError); + v8::MaybeLocal restart(); + v8::MaybeLocal setVariableValue(int scopeNumber, + v8::Local variableName, + v8::Local newValue); + + private: + explicit JavaScriptCallFrame(JsValueRef callFrame); + + JsValueRef const m_callFrame; + + DISALLOW_COPY_AND_ASSIGN(JavaScriptCallFrame); +}; + +using JavaScriptCallFrames = std::vector>; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_JAVA_SCRIPT_CALL_FRAME_H_ diff --git a/ios/libnode/include/node/inspector/protocol-platform.h b/ios/libnode/include/node/inspector/protocol-platform.h new file mode 100644 index 0000000..6f68e84 --- /dev/null +++ b/ios/libnode/include/node/inspector/protocol-platform.h @@ -0,0 +1,21 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_PROTOCOL_PLATFORM_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_PROTOCOL_PLATFORM_H_ + +#include + +#include "src/base/logging.h" + +namespace v8_inspector { + +template +std::unique_ptr wrapUnique(T* ptr) { + return std::unique_ptr(ptr); +} + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_PROTOCOL_PLATFORM_H_ diff --git a/ios/libnode/include/node/inspector/script-breakpoint.h b/ios/libnode/include/node/inspector/script-breakpoint.h new file mode 100644 index 0000000..811c064 --- /dev/null +++ b/ios/libnode/include/node/inspector/script-breakpoint.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * Copyright (C) 2009 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_SCRIPT_BREAKPOINT_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_SCRIPT_BREAKPOINT_H_ + +#include "src/inspector/string-16.h" + +namespace v8_inspector { + +struct ScriptBreakpoint { + ScriptBreakpoint() : ScriptBreakpoint(0, 0, String16()) {} + + ScriptBreakpoint(int lineNumber, int columnNumber, const String16& condition) + : lineNumber(lineNumber), + columnNumber(columnNumber), + condition(condition) {} + + int lineNumber; + int columnNumber; + String16 condition; +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_SCRIPT_BREAKPOINT_H_ diff --git a/ios/libnode/include/node/inspector/search-util.h b/ios/libnode/include/node/inspector/search-util.h new file mode 100644 index 0000000..5b7a25d --- /dev/null +++ b/ios/libnode/include/node/inspector/search-util.h @@ -0,0 +1,24 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_SEARCH_UTIL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_SEARCH_UTIL_H_ + +#include "src/inspector/protocol/Debugger.h" +#include "src/inspector/string-util.h" + +namespace v8_inspector { + +class V8InspectorSession; + +String16 findSourceURL(const String16& content, bool multiline); +String16 findSourceMapURL(const String16& content, bool multiline); +std::vector> +searchInTextByLinesImpl(V8InspectorSession*, const String16& text, + const String16& query, bool caseSensitive, + bool isRegex); + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_SEARCH_UTIL_H_ diff --git a/ios/libnode/include/node/inspector/string-16.h b/ios/libnode/include/node/inspector/string-16.h new file mode 100644 index 0000000..1f50ad6 --- /dev/null +++ b/ios/libnode/include/node/inspector/string-16.h @@ -0,0 +1,134 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_16_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_16_H_ + +#include +#include +#include +#include +#include +#include + +namespace v8_inspector { + +using UChar = uint16_t; + +class String16 { + public: + static const size_t kNotFound = static_cast(-1); + + String16() {} + String16(const String16& other) : m_impl(other.m_impl) {} + String16(const UChar* characters, size_t size) : m_impl(characters, size) {} + String16(const UChar* characters) // NOLINT(runtime/explicit) + : m_impl(characters) {} + String16(const char* characters) // NOLINT(runtime/explicit) + : String16(characters, std::strlen(characters)) {} + String16(const char* characters, size_t size) { + m_impl.resize(size); + for (size_t i = 0; i < size; ++i) m_impl[i] = characters[i]; + } + + static String16 fromInteger(int); + static String16 fromInteger(size_t); + static String16 fromDouble(double); + static String16 fromDoublePrecision3(double); + static String16 fromDoublePrecision6(double); + + int toInteger(bool* ok = nullptr) const; + String16 stripWhiteSpace() const; + const UChar* characters16() const { return m_impl.c_str(); } + size_t length() const { return m_impl.length(); } + bool isEmpty() const { return !m_impl.length(); } + UChar operator[](size_t index) const { return m_impl[index]; } + String16 substring(size_t pos, size_t len = UINT_MAX) const { + return String16(m_impl.substr(pos, len)); + } + size_t find(const String16& str, size_t start = 0) const { + return m_impl.find(str.m_impl, start); + } + size_t reverseFind(const String16& str, size_t start = UINT_MAX) const { + return m_impl.rfind(str.m_impl, start); + } + void swap(String16& other) { m_impl.swap(other.m_impl); } + + // Convenience methods. + std::string utf8() const; + static String16 fromUTF8(const char* stringStart, size_t length); + + const std::basic_string& impl() const { return m_impl; } + explicit String16(const std::basic_string& impl) : m_impl(impl) {} + + std::size_t hash() const { + if (!has_hash) { + size_t hash = 0; + for (size_t i = 0; i < length(); ++i) hash = 31 * hash + m_impl[i]; + hash_code = hash; + has_hash = true; + } + return hash_code; + } + + private: + std::basic_string m_impl; + mutable bool has_hash = false; + mutable std::size_t hash_code = 0; +}; + +inline bool operator==(const String16& a, const String16& b) { + return a.impl() == b.impl(); +} +inline bool operator<(const String16& a, const String16& b) { + return a.impl() < b.impl(); +} +inline bool operator!=(const String16& a, const String16& b) { + return a.impl() != b.impl(); +} +inline bool operator==(const String16& a, const char* b) { + return a.impl() == String16(b).impl(); +} +inline String16 operator+(const String16& a, const char* b) { + return String16(a.impl() + String16(b).impl()); +} +inline String16 operator+(const char* a, const String16& b) { + return String16(String16(a).impl() + b.impl()); +} +inline String16 operator+(const String16& a, const String16& b) { + return String16(a.impl() + b.impl()); +} + +class String16Builder { + public: + String16Builder(); + void append(const String16&); + void append(UChar); + void append(char); + void append(const UChar*, size_t); + void append(const char*, size_t); + String16 toString(); + void reserveCapacity(size_t); + + private: + std::vector m_buffer; +}; + +} // namespace v8_inspector + +#if !defined(__APPLE__) || defined(_LIBCPP_VERSION) + +namespace std { +template <> +struct hash { + std::size_t operator()(const v8_inspector::String16& string) const { + return string.hash(); + } +}; + +} // namespace std + +#endif // !defined(__APPLE__) || defined(_LIBCPP_VERSION) + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_16_H_ diff --git a/ios/libnode/include/node/inspector/string-util.h b/ios/libnode/include/node/inspector/string-util.h new file mode 100644 index 0000000..18b5dea --- /dev/null +++ b/ios/libnode/include/node/inspector/string-util.h @@ -0,0 +1,77 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_UTIL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_UTIL_H_ + +#include "src/base/macros.h" +#include "src/inspector/string-16.h" + +#include "include/v8-inspector.h" + +namespace v8_inspector { + +namespace protocol { + +class Value; + +using String = v8_inspector::String16; +using StringBuilder = v8_inspector::String16Builder; + +class StringUtil { + public: + static String substring(const String& s, size_t pos, size_t len) { + return s.substring(pos, len); + } + static String fromInteger(int number) { return String::fromInteger(number); } + static String fromInteger(size_t number) { + return String::fromInteger(number); + } + static String fromDouble(double number) { return String::fromDouble(number); } + static const size_t kNotFound = String::kNotFound; + static void builderReserve( + StringBuilder& builder, size_t capacity) { // NOLINT(runtime/references) + builder.reserveCapacity(capacity); + } +}; + +std::unique_ptr parseJSON(const StringView& json); +std::unique_ptr parseJSON(const String16& json); + +} // namespace protocol + +std::unique_ptr toProtocolValue(protocol::String* errorString, + v8::Local, + v8::Local, + int maxDepth = 1000); + +v8::Local toV8String(v8::Isolate*, const String16&); +v8::Local toV8StringInternalized(v8::Isolate*, const String16&); +v8::Local toV8StringInternalized(v8::Isolate*, const char*); +v8::Local toV8String(v8::Isolate*, const StringView&); +// TODO(dgozman): rename to toString16. +String16 toProtocolString(v8::Local); +String16 toProtocolStringWithTypeCheck(v8::Local); +String16 toString16(const StringView&); +StringView toStringView(const String16&); +std::unique_ptr toStringBuffer(const String16&); +bool stringViewStartsWith(const StringView&, const char*); + +class StringBufferImpl : public StringBuffer { + public: + // Destroys string's content. + static std::unique_ptr adopt(String16&); + const StringView& string() override { return m_string; } + + private: + explicit StringBufferImpl(String16&); + String16 m_owner; + StringView m_string; + + DISALLOW_COPY_AND_ASSIGN(StringBufferImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_STRING_UTIL_H_ diff --git a/ios/libnode/include/node/inspector/v8-console-agent-impl.h b/ios/libnode/include/node/inspector/v8-console-agent-impl.h new file mode 100644 index 0000000..9a93099 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-console-agent-impl.h @@ -0,0 +1,48 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_AGENT_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_AGENT_IMPL_H_ + +#include "src/base/macros.h" +#include "src/inspector/protocol/Console.h" +#include "src/inspector/protocol/Forward.h" + +namespace v8_inspector { + +class V8ConsoleMessage; +class V8InspectorSessionImpl; + +using protocol::ErrorString; + +class V8ConsoleAgentImpl : public protocol::Console::Backend { + public: + V8ConsoleAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, + protocol::DictionaryValue* state); + ~V8ConsoleAgentImpl() override; + + void enable(ErrorString*) override; + void disable(ErrorString*) override; + void clearMessages(ErrorString*) override; + + void restore(); + void messageAdded(V8ConsoleMessage*); + void reset(); + bool enabled(); + + private: + void reportAllMessages(); + bool reportMessage(V8ConsoleMessage*, bool generatePreview); + + V8InspectorSessionImpl* m_session; + protocol::DictionaryValue* m_state; + protocol::Console::Frontend m_frontend; + bool m_enabled; + + DISALLOW_COPY_AND_ASSIGN(V8ConsoleAgentImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_AGENT_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-console-message.h b/ios/libnode/include/node/inspector/v8-console-message.h new file mode 100644 index 0000000..33f0cdd --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-console-message.h @@ -0,0 +1,120 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_MESSAGE_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_MESSAGE_H_ + +#include +#include "include/v8.h" +#include "src/inspector/protocol/Console.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Runtime.h" + +namespace v8_inspector { + +class InspectedContext; +class V8InspectorImpl; +class V8InspectorSessionImpl; +class V8StackTraceImpl; + +enum class V8MessageOrigin { kConsole, kException, kRevokedException }; + +enum class ConsoleAPIType { + kLog, + kDebug, + kInfo, + kError, + kWarning, + kDir, + kDirXML, + kTable, + kTrace, + kStartGroup, + kStartGroupCollapsed, + kEndGroup, + kClear, + kAssert, + kTimeEnd, + kCount +}; + +class V8ConsoleMessage { + public: + ~V8ConsoleMessage(); + + static std::unique_ptr createForConsoleAPI( + double timestamp, ConsoleAPIType, + const std::vector>& arguments, + std::unique_ptr, InspectedContext*); + + static std::unique_ptr createForException( + double timestamp, const String16& detailedMessage, const String16& url, + unsigned lineNumber, unsigned columnNumber, + std::unique_ptr, int scriptId, v8::Isolate*, + const String16& message, int contextId, v8::Local exception, + unsigned exceptionId); + + static std::unique_ptr createForRevokedException( + double timestamp, const String16& message, unsigned revokedExceptionId); + + V8MessageOrigin origin() const; + void reportToFrontend(protocol::Console::Frontend*) const; + void reportToFrontend(protocol::Runtime::Frontend*, V8InspectorSessionImpl*, + bool generatePreview) const; + ConsoleAPIType type() const; + void contextDestroyed(int contextId); + + private: + V8ConsoleMessage(V8MessageOrigin, double timestamp, const String16& message); + + using Arguments = std::vector>>; + std::unique_ptr> + wrapArguments(V8InspectorSessionImpl*, bool generatePreview) const; + std::unique_ptr wrapException( + V8InspectorSessionImpl*, bool generatePreview) const; + void setLocation(const String16& url, unsigned lineNumber, + unsigned columnNumber, std::unique_ptr, + int scriptId); + + V8MessageOrigin m_origin; + double m_timestamp; + String16 m_message; + String16 m_url; + unsigned m_lineNumber; + unsigned m_columnNumber; + std::unique_ptr m_stackTrace; + int m_scriptId; + int m_contextId; + ConsoleAPIType m_type; + unsigned m_exceptionId; + unsigned m_revokedExceptionId; + Arguments m_arguments; + String16 m_detailedMessage; +}; + +class V8ConsoleMessageStorage { + public: + V8ConsoleMessageStorage(V8InspectorImpl*, int contextGroupId); + ~V8ConsoleMessageStorage(); + + int contextGroupId() { return m_contextGroupId; } + int expiredCount() { return m_expiredCount; } + const std::deque>& messages() const { + return m_messages; + } + + void addMessage(std::unique_ptr); + void contextDestroyed(int contextId); + void clear(); + + private: + V8InspectorImpl* m_inspector; + int m_contextGroupId; + int m_expiredCount; + std::deque> m_messages; +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_MESSAGE_H_ diff --git a/ios/libnode/include/node/inspector/v8-console.h b/ios/libnode/include/node/inspector/v8-console.h new file mode 100644 index 0000000..3f2badc --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-console.h @@ -0,0 +1,119 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_H_ + +#include "src/base/macros.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class InspectedContext; + +// Console API +// https://console.spec.whatwg.org/#console-interface +class V8Console { + public: + static v8::Local createConsole(InspectedContext*, + bool hasMemoryAttribute); + static void clearInspectedContextIfNeeded(v8::Local, + v8::Local console); + static v8::Local createCommandLineAPI(InspectedContext*); + + class CommandLineAPIScope { + public: + CommandLineAPIScope(v8::Local, + v8::Local commandLineAPI, + v8::Local global); + ~CommandLineAPIScope(); + + private: + static void accessorGetterCallback( + v8::Local, const v8::PropertyCallbackInfo&); + static void accessorSetterCallback(v8::Local, + v8::Local, + const v8::PropertyCallbackInfo&); + + v8::Local m_context; + v8::Local m_commandLineAPI; + v8::Local m_global; + v8::Local m_installedMethods; + bool m_cleanup; + + DISALLOW_COPY_AND_ASSIGN(CommandLineAPIScope); + }; + + private: + static void debugCallback(const v8::FunctionCallbackInfo&); + static void errorCallback(const v8::FunctionCallbackInfo&); + static void infoCallback(const v8::FunctionCallbackInfo&); + static void logCallback(const v8::FunctionCallbackInfo&); + static void warnCallback(const v8::FunctionCallbackInfo&); + static void dirCallback(const v8::FunctionCallbackInfo&); + static void dirxmlCallback(const v8::FunctionCallbackInfo&); + static void tableCallback(const v8::FunctionCallbackInfo&); + static void traceCallback(const v8::FunctionCallbackInfo&); + static void groupCallback(const v8::FunctionCallbackInfo&); + static void groupCollapsedCallback( + const v8::FunctionCallbackInfo&); + static void groupEndCallback(const v8::FunctionCallbackInfo&); + static void clearCallback(const v8::FunctionCallbackInfo&); + static void countCallback(const v8::FunctionCallbackInfo&); + static void assertCallback(const v8::FunctionCallbackInfo&); + static void markTimelineCallback(const v8::FunctionCallbackInfo&); + static void profileCallback(const v8::FunctionCallbackInfo&); + static void profileEndCallback(const v8::FunctionCallbackInfo&); + static void timelineCallback(const v8::FunctionCallbackInfo&); + static void timelineEndCallback(const v8::FunctionCallbackInfo&); + static void timeCallback(const v8::FunctionCallbackInfo&); + static void timeEndCallback(const v8::FunctionCallbackInfo&); + static void timeStampCallback(const v8::FunctionCallbackInfo&); + // TODO(foolip): There is no spec for the Memory Info API, see blink-dev: + // https://groups.google.com/a/chromium.org/d/msg/blink-dev/g5YRCGpC9vs/b4OJz71NmPwJ + static void memoryGetterCallback(const v8::FunctionCallbackInfo&); + static void memorySetterCallback(const v8::FunctionCallbackInfo&); + + // CommandLineAPI + static void keysCallback(const v8::FunctionCallbackInfo&); + static void valuesCallback(const v8::FunctionCallbackInfo&); + static void debugFunctionCallback(const v8::FunctionCallbackInfo&); + static void undebugFunctionCallback( + const v8::FunctionCallbackInfo&); + static void monitorFunctionCallback( + const v8::FunctionCallbackInfo&); + static void unmonitorFunctionCallback( + const v8::FunctionCallbackInfo&); + static void lastEvaluationResultCallback( + const v8::FunctionCallbackInfo&); + static void inspectCallback(const v8::FunctionCallbackInfo&); + static void copyCallback(const v8::FunctionCallbackInfo&); + static void inspectedObject(const v8::FunctionCallbackInfo&, + unsigned num); + static void inspectedObject0( + const v8::FunctionCallbackInfo& info) { + inspectedObject(info, 0); + } + static void inspectedObject1( + const v8::FunctionCallbackInfo& info) { + inspectedObject(info, 1); + } + static void inspectedObject2( + const v8::FunctionCallbackInfo& info) { + inspectedObject(info, 2); + } + static void inspectedObject3( + const v8::FunctionCallbackInfo& info) { + inspectedObject(info, 3); + } + static void inspectedObject4( + const v8::FunctionCallbackInfo& info) { + inspectedObject(info, 4); + } +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_CONSOLE_H_ diff --git a/ios/libnode/include/node/inspector/v8-debugger-agent-impl.h b/ios/libnode/include/node/inspector/v8-debugger-agent-impl.h new file mode 100644 index 0000000..fab921b --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-debugger-agent-impl.h @@ -0,0 +1,222 @@ +// Copyright 2015 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_AGENT_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_AGENT_IMPL_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/java-script-call-frame.h" +#include "src/inspector/protocol/Debugger.h" +#include "src/inspector/protocol/Forward.h" + +namespace v8_inspector { + +struct ScriptBreakpoint; +class V8Debugger; +class V8DebuggerScript; +class V8InspectorImpl; +class V8InspectorSessionImpl; +class V8Regex; + +using protocol::ErrorString; +using protocol::Maybe; + +class V8DebuggerAgentImpl : public protocol::Debugger::Backend { + public: + enum SkipPauseRequest { + RequestNoSkip, + RequestContinue, + RequestStepInto, + RequestStepOut, + RequestStepFrame + }; + + enum BreakpointSource { + UserBreakpointSource, + DebugCommandBreakpointSource, + MonitorCommandBreakpointSource + }; + + V8DebuggerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, + protocol::DictionaryValue* state); + ~V8DebuggerAgentImpl() override; + void restore(); + + // Part of the protocol. + void enable(ErrorString*) override; + void disable(ErrorString*) override; + void setBreakpointsActive(ErrorString*, bool active) override; + void setSkipAllPauses(ErrorString*, bool skip) override; + void setBreakpointByUrl( + ErrorString*, int lineNumber, const Maybe& optionalURL, + const Maybe& optionalURLRegex, + const Maybe& optionalColumnNumber, + const Maybe& optionalCondition, String16*, + std::unique_ptr>* locations) + override; + void setBreakpoint( + ErrorString*, std::unique_ptr, + const Maybe& optionalCondition, String16*, + std::unique_ptr* actualLocation) override; + void removeBreakpoint(ErrorString*, const String16& breakpointId) override; + void continueToLocation( + ErrorString*, std::unique_ptr) override; + void searchInContent( + ErrorString*, const String16& scriptId, const String16& query, + const Maybe& optionalCaseSensitive, + const Maybe& optionalIsRegex, + std::unique_ptr>*) + override; + void setScriptSource( + ErrorString*, const String16& inScriptId, const String16& inScriptSource, + const Maybe& dryRun, + Maybe>* optOutCallFrames, + Maybe* optOutStackChanged, + Maybe* optOutAsyncStackTrace, + Maybe* optOutCompileError) override; + void restartFrame( + ErrorString*, const String16& callFrameId, + std::unique_ptr>* + newCallFrames, + Maybe* asyncStackTrace) override; + void getScriptSource(ErrorString*, const String16& scriptId, + String16* scriptSource) override; + void pause(ErrorString*) override; + void resume(ErrorString*) override; + void stepOver(ErrorString*) override; + void stepInto(ErrorString*) override; + void stepOut(ErrorString*) override; + void setPauseOnExceptions(ErrorString*, const String16& pauseState) override; + void evaluateOnCallFrame( + ErrorString*, const String16& callFrameId, const String16& expression, + const Maybe& objectGroup, + const Maybe& includeCommandLineAPI, const Maybe& silent, + const Maybe& returnByValue, const Maybe& generatePreview, + std::unique_ptr* result, + Maybe*) override; + void setVariableValue( + ErrorString*, int scopeNumber, const String16& variableName, + std::unique_ptr newValue, + const String16& callFrame) override; + void setAsyncCallStackDepth(ErrorString*, int depth) override; + void setBlackboxPatterns( + ErrorString*, + std::unique_ptr> patterns) override; + void setBlackboxedRanges( + ErrorString*, const String16& scriptId, + std::unique_ptr> + positions) override; + + // Time travel implementations + void reverse(ErrorString*); + void stepBack(ErrorString*); + + bool enabled(); + + void setBreakpointAt(const String16& scriptId, int lineNumber, + int columnNumber, BreakpointSource, + const String16& condition = String16()); + void removeBreakpointAt(const String16& scriptId, int lineNumber, + int columnNumber, BreakpointSource); + void schedulePauseOnNextStatement( + const String16& breakReason, + std::unique_ptr data); + void cancelPauseOnNextStatement(); + void breakProgram(const String16& breakReason, + std::unique_ptr data); + void breakProgramOnException(const String16& breakReason, + std::unique_ptr data); + + void reset(); + + // Interface for V8InspectorImpl + SkipPauseRequest didPause(v8::Local, + v8::Local exception, + const std::vector& hitBreakpoints, + bool isPromiseRejection, bool isUncaught); + void didContinue(); + void didParseSource(std::unique_ptr, bool success); + void willExecuteScript(int scriptId); + void didExecuteScript(); + + v8::Isolate* isolate() { return m_isolate; } + + private: + bool checkEnabled(ErrorString*); + void enable(); + + SkipPauseRequest shouldSkipExceptionPause(JavaScriptCallFrame* topCallFrame); + SkipPauseRequest shouldSkipStepPause(JavaScriptCallFrame* topCallFrame); + + std::unique_ptr> + currentCallFrames(ErrorString*); + std::unique_ptr currentAsyncStackTrace(); + + std::unique_ptr resolveBreakpoint( + const String16& breakpointId, const String16& scriptId, + const ScriptBreakpoint&, BreakpointSource); + void removeBreakpoint(const String16& breakpointId); + bool assertPaused(ErrorString*); + void clearBreakDetails(); + + bool isCurrentCallStackEmptyOrBlackboxed(); + bool isTopPausedCallFrameBlackboxed(); + bool isCallFrameWithUnknownScriptOrBlackboxed(JavaScriptCallFrame*); + + bool setBlackboxPattern(ErrorString*, const String16& pattern); + + using ScriptsMap = + protocol::HashMap>; + using BreakpointIdToDebuggerBreakpointIdsMap = + protocol::HashMap>; + using DebugServerBreakpointToBreakpointIdAndSourceMap = + protocol::HashMap>; + + enum DebuggerStep { + StepInto = 0, + StepOver, + StepOut, + StepBack, + ReverseContinue, + NoStep + }; + + V8InspectorImpl* m_inspector; + V8Debugger* m_debugger; + V8InspectorSessionImpl* m_session; + bool m_enabled; + protocol::DictionaryValue* m_state; + protocol::Debugger::Frontend m_frontend; + v8::Isolate* m_isolate; + v8::Global m_pausedContext; + JavaScriptCallFrames m_pausedCallFrames; + ScriptsMap m_scripts; + BreakpointIdToDebuggerBreakpointIdsMap m_breakpointIdToDebuggerBreakpointIds; + DebugServerBreakpointToBreakpointIdAndSourceMap m_serverBreakpoints; + String16 m_continueToLocationBreakpointId; + String16 m_breakReason; + std::unique_ptr m_breakAuxData; + DebuggerStep m_scheduledDebuggerStep; + bool m_skipNextDebuggerStepOut; + bool m_javaScriptPauseScheduled; + bool m_steppingFromFramework; + bool m_pausingOnNativeEvent; + + int m_skippedStepFrameCount; + int m_recursionLevelForStepOut; + int m_recursionLevelForStepFrame; + bool m_skipAllPauses; + + std::unique_ptr m_blackboxPattern; + protocol::HashMap>> + m_blackboxedPositions; + + DISALLOW_COPY_AND_ASSIGN(V8DebuggerAgentImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_AGENT_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-debugger-script.h b/ios/libnode/include/node/inspector/v8-debugger-script.h new file mode 100644 index 0000000..b94010c --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-debugger-script.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_SCRIPT_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_SCRIPT_H_ + +#include "src/base/macros.h" +#include "src/inspector/string-16.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class V8DebuggerScript { + public: + V8DebuggerScript(v8::Isolate* isolate, + JsValueRef scriptData, + bool isLiveEdit); + ~V8DebuggerScript(); + + const String16& scriptId() const { return m_id; } + const String16& url() const { return m_url; } + bool hasSourceURL() const { return !m_sourceURL.isEmpty(); } + const String16& sourceURL() const; + const String16& sourceMappingURL() const { return m_sourceMappingURL; } + v8::Local source(v8::Isolate*) const; + const String16& hash() const { return m_hash; } + int startLine() const { return m_startLine; } + int startColumn() const { return m_startColumn; } + int endLine() const { return m_endLine; } + int endColumn() const { return m_endColumn; } + int executionContextId() const { return m_executionContextId; } + const String16& executionContextAuxData() const { + return m_executionContextAuxData; + } + bool isLiveEdit() const { return m_isLiveEdit; } + + void setSource(v8::Isolate*, v8::Local); + + private: + String16 m_id; + String16 m_url; + String16 m_sourceURL; + String16 m_sourceMappingURL; + v8::Global m_source; + String16 m_hash; + int m_startLine; + int m_startColumn; + int m_endLine; + int m_endColumn; + int m_executionContextId; + String16 m_executionContextAuxData; + bool m_isLiveEdit; + + DISALLOW_COPY_AND_ASSIGN(V8DebuggerScript); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_SCRIPT_H_ diff --git a/ios/libnode/include/node/inspector/v8-debugger.h b/ios/libnode/include/node/inspector/v8-debugger.h new file mode 100644 index 0000000..38a8b84 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-debugger.h @@ -0,0 +1,143 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/java-script-call-frame.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Runtime.h" +#include "src/inspector/v8-debugger-script.h" + +#include "include/v8-debug.h" +#include "include/v8-inspector.h" + +namespace v8_inspector { + +struct ScriptBreakpoint; +class V8DebuggerAgentImpl; +class V8InspectorImpl; +class V8StackTraceImpl; + +using protocol::ErrorString; + +class V8Debugger { + public: + V8Debugger(v8::Isolate*, V8InspectorImpl*); + ~V8Debugger(); + + static int contextId(v8::Local); + static int getGroupId(v8::Local); + int markContext(const V8ContextInfo&); + + bool enabled() const; + + String16 setBreakpoint(const String16& sourceID, const ScriptBreakpoint&, + int* actualLineNumber, int* actualColumnNumber); + void removeBreakpoint(const String16& breakpointId); + void setBreakpointsActivated(bool); + bool breakpointsActivated() const { return m_breakpointsActivated; } + + enum PauseOnExceptionsState { + DontPauseOnExceptions, + PauseOnAllExceptions, + PauseOnUncaughtExceptions + }; + PauseOnExceptionsState getPauseOnExceptionsState(); + void setPauseOnExceptionsState(PauseOnExceptionsState); + void setPauseOnNextStatement(bool); + bool canBreakProgram(); + void breakProgram(); + void continueProgram(); + void stepIntoStatement(); + void stepOverStatement(); + void stepOutOfFunction(); + void clearStepping(); + + // Time travel + void reverse(); + void stepBack(); + + bool setScriptSource(const String16& sourceID, + v8::Local newSource, bool dryRun, + ErrorString*, + protocol::Maybe*, + JavaScriptCallFrames* newCallFrames, + protocol::Maybe* stackChanged); + JavaScriptCallFrames currentCallFrames(int limit = 0); + + // Each script inherits debug data from v8::Context where it has been + // compiled. + // Only scripts whose debug data matches |contextGroupId| will be reported. + // Passing 0 will result in reporting all scripts. + void getCompiledScripts(int contextGroupId, + std::vector>&); + void enable(); + void disable(); + + bool isPaused(); + v8::Local pausedContext() { return m_pausedContext; } + + int maxAsyncCallChainDepth() { return m_maxAsyncCallStackDepth; } + V8StackTraceImpl* currentAsyncCallChain(); + void setAsyncCallStackDepth(V8DebuggerAgentImpl*, int); + std::unique_ptr createStackTrace(v8::Local); + std::unique_ptr captureStackTrace(bool fullStack); + + v8::MaybeLocal internalProperties(v8::Local, + v8::Local); + + void asyncTaskScheduled(const StringView& taskName, void* task, + bool recurring); + void asyncTaskScheduled(const String16& taskName, void* task, bool recurring); + void asyncTaskCanceled(void* task); + void asyncTaskStarted(void* task); + void asyncTaskFinished(void* task); + void allAsyncTasksCanceled(); + + void muteScriptParsedEvents(); + void unmuteScriptParsedEvents(); + + V8InspectorImpl* inspector() { return m_inspector; } + + private: + static void CHAKRA_CALLBACK JsDiagDebugEventHandler( + JsDiagDebugEvent debugEvent, + JsValueRef eventData, + void* callbackState); + + v8::Local debuggerContext() const; + + void DebugEventHandler( + JsDiagDebugEvent debugEvent, + JsValueRef eventData); + + void HandleSourceEvents(JsValueRef eventData, bool success); + void HandleBreak(JsValueRef eventData); + + void ClearBreakpoints(); + + v8::Isolate* m_isolate; + V8InspectorImpl* m_inspector; + int m_lastContextId; + int m_enableCount; + bool m_breakpointsActivated; + v8::Global m_debuggerContext; + v8::Local m_pausedContext; + bool m_runningNestedMessageLoop; + int m_ignoreScriptParsedEventsCounter; + + int m_maxAsyncCallStackDepth; + bool m_pauseOnNextStatement; + protocol::HashMap m_maxAsyncCallStackDepthMap; + + DISALLOW_COPY_AND_ASSIGN(V8Debugger); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_DEBUGGER_H_ diff --git a/ios/libnode/include/node/inspector/v8-function-call.h b/ios/libnode/include/node/inspector/v8-function-call.h new file mode 100644 index 0000000..9ce472b --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-function-call.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2009 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_FUNCTION_CALL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_FUNCTION_CALL_H_ + +#include "src/inspector/string-16.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class V8InspectorImpl; + +class V8FunctionCall { + public: + V8FunctionCall(V8InspectorImpl*, v8::Local, v8::Local, + const String16& name); + + void appendArgument(v8::Local); + void appendArgument(const String16&); + void appendArgument(int); + void appendArgument(bool); + + v8::Local call(bool& hadException, // NOLINT(runtime/references) + bool reportExceptions = true); + v8::Local callWithoutExceptionHandling(); + + protected: + V8InspectorImpl* m_inspector; + v8::Local m_context; + std::vector> m_arguments; + v8::Local m_name; + v8::Local m_value; +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_FUNCTION_CALL_H_ diff --git a/ios/libnode/include/node/inspector/v8-inspector-impl.h b/ios/libnode/include/node/inspector/v8-inspector-impl.h new file mode 100644 index 0000000..e5911f2 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-inspector-impl.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_IMPL_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/protocol/Protocol.h" + +#include "include/v8-debug.h" +#include "include/v8-inspector.h" + +namespace v8_inspector { + +class InspectedContext; +class V8ConsoleMessageStorage; +class V8Debugger; +class V8DebuggerAgentImpl; +class V8InspectorSessionImpl; +class V8RuntimeAgentImpl; +class V8StackTraceImpl; + +class V8InspectorImpl : public V8Inspector { + public: + V8InspectorImpl(v8::Isolate*, V8InspectorClient*); + ~V8InspectorImpl() override; + + v8::Isolate* isolate() const { return m_isolate; } + V8InspectorClient* client() { return m_client; } + V8Debugger* debugger() { return m_debugger.get(); } + + v8::MaybeLocal runCompiledScript(v8::Local, + v8::Local); + v8::MaybeLocal callFunction(v8::Local, + v8::Local, + v8::Local receiver, + int argc, v8::Local info[]); + v8::MaybeLocal compileAndRunInternalScript(v8::Local, + v8::Local); + v8::Local compileScript(v8::Local, + v8::Local, + const String16& fileName, + bool markAsInternal); + v8::Local regexContext(); + + // V8Inspector implementation. + std::unique_ptr connect(int contextGroupId, + V8Inspector::Channel*, + const StringView& state) override; + void contextCreated(const V8ContextInfo&) override; + void contextDestroyed(v8::Local) override; + void resetContextGroup(int contextGroupId) override; + void willExecuteScript(v8::Local, int scriptId) override; + void didExecuteScript(v8::Local) override; + unsigned exceptionThrown(v8::Local, const StringView& message, + v8::Local exception, + const StringView& detailedMessage, + const StringView& url, unsigned lineNumber, + unsigned columnNumber, std::unique_ptr, + int scriptId) override; + void exceptionRevoked(v8::Local, unsigned exceptionId, + const StringView& message) override; + std::unique_ptr createStackTrace( + v8::Local) override; + std::unique_ptr captureStackTrace(bool fullStack) override; + void asyncTaskScheduled(const StringView& taskName, void* task, + bool recurring) override; + void asyncTaskCanceled(void* task) override; + void asyncTaskStarted(void* task) override; + void asyncTaskFinished(void* task) override; + void allAsyncTasksCanceled() override; + + unsigned nextExceptionId() { return ++m_lastExceptionId; } + void enableStackCapturingIfNeeded(); + void disableStackCapturingIfNeeded(); + void muteExceptions(int contextGroupId); + void unmuteExceptions(int contextGroupId); + V8ConsoleMessageStorage* ensureConsoleMessageStorage(int contextGroupId); + bool hasConsoleMessageStorage(int contextGroupId); + using ContextByIdMap = + protocol::HashMap>; + void discardInspectedContext(int contextGroupId, int contextId); + const ContextByIdMap* contextGroup(int contextGroupId); + void disconnect(V8InspectorSessionImpl*); + V8InspectorSessionImpl* sessionForContextGroup(int contextGroupId); + InspectedContext* getContext(int groupId, int contextId) const; + V8DebuggerAgentImpl* enabledDebuggerAgentForGroup(int contextGroupId); + V8RuntimeAgentImpl* enabledRuntimeAgentForGroup(int contextGroupId); + + private: + v8::Isolate* m_isolate; + V8InspectorClient* m_client; + std::unique_ptr m_debugger; + v8::Global m_regexContext; + int m_capturingStackTracesCount; + unsigned m_lastExceptionId; + + using MuteExceptionsMap = protocol::HashMap; + MuteExceptionsMap m_muteExceptionsMap; + + using ContextsByGroupMap = + protocol::HashMap>; + ContextsByGroupMap m_contexts; + + using SessionMap = protocol::HashMap; + SessionMap m_sessions; + + using ConsoleStorageMap = + protocol::HashMap>; + ConsoleStorageMap m_consoleStorageMap; + + DISALLOW_COPY_AND_ASSIGN(V8InspectorImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-inspector-session-impl.h b/ios/libnode/include/node/inspector/v8-inspector-session-impl.h new file mode 100644 index 0000000..8356027 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-inspector-session-impl.h @@ -0,0 +1,96 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_SESSION_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_SESSION_IMPL_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Runtime.h" +#include "src/inspector/protocol/Schema.h" + +#include "include/v8-inspector.h" + +namespace v8_inspector { + +class RemoteObjectIdBase; +class V8ConsoleAgentImpl; +class V8DebuggerAgentImpl; +class V8InspectorImpl; +class V8RuntimeAgentImpl; +class V8SchemaAgentImpl; +class V8TimeTravelAgentImpl; + +using protocol::ErrorString; + +class V8InspectorSessionImpl : public V8InspectorSession, + public protocol::FrontendChannel { + public: + static std::unique_ptr create( + V8InspectorImpl*, int contextGroupId, V8Inspector::Channel*, + const StringView& state); + ~V8InspectorSessionImpl(); + + V8InspectorImpl* inspector() const { return m_inspector; } + V8ConsoleAgentImpl* consoleAgent() { return m_consoleAgent.get(); } + V8DebuggerAgentImpl* debuggerAgent() { return m_debuggerAgent.get(); } + V8SchemaAgentImpl* schemaAgent() { return m_schemaAgent.get(); } + V8RuntimeAgentImpl* runtimeAgent() { return m_runtimeAgent.get(); } + V8TimeTravelAgentImpl* timeTravelAgent() { return m_timeTravelAgent.get(); } + int contextGroupId() const { return m_contextGroupId; } + + void reset(); + void reportAllContexts(V8RuntimeAgentImpl*); + void setCustomObjectFormatterEnabled(bool); + std::vector> supportedDomainsImpl(); + + // V8InspectorSession implementation. + void dispatchProtocolMessage(const StringView& message) override; + std::unique_ptr stateJSON() override; + std::vector> supportedDomains() + override; + void schedulePauseOnNextStatement(const StringView& breakReason, + const StringView& breakDetails) override; + void cancelPauseOnNextStatement() override; + void breakProgram(const StringView& breakReason, + const StringView& breakDetails) override; + void setSkipAllPauses(bool) override; + void resume() override; + void stepOver() override; + std::vector> + searchInTextByLines(const StringView& text, const StringView& query, + bool caseSensitive, bool isRegex) override; + static const unsigned kInspectedObjectBufferSize = 5; + + private: + V8InspectorSessionImpl(V8InspectorImpl*, int contextGroupId, + V8Inspector::Channel*, const StringView& state); + protocol::DictionaryValue* agentState(const String16& name); + + // protocol::FrontendChannel implementation. + void sendProtocolResponse(int callId, const String16& message) override; + void sendProtocolNotification(const String16& message) override; + void flushProtocolNotifications() override; + + int m_contextGroupId; + V8InspectorImpl* m_inspector; + V8Inspector::Channel* m_channel; + + protocol::UberDispatcher m_dispatcher; + std::unique_ptr m_state; + + std::unique_ptr m_runtimeAgent; + std::unique_ptr m_debuggerAgent; + std::unique_ptr m_consoleAgent; + std::unique_ptr m_schemaAgent; + std::unique_ptr m_timeTravelAgent; + + DISALLOW_COPY_AND_ASSIGN(V8InspectorSessionImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INSPECTOR_SESSION_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-internal-value-type.h b/ios/libnode/include/node/inspector/v8-internal-value-type.h new file mode 100644 index 0000000..5d94c0d --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-internal-value-type.h @@ -0,0 +1,23 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INTERNAL_VALUE_TYPE_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INTERNAL_VALUE_TYPE_H_ + +#include "include/v8.h" + +namespace v8_inspector { + +enum class V8InternalValueType { kEntry, kLocation, kScope, kScopeList }; + +bool markAsInternal(v8::Local, v8::Local, + V8InternalValueType); +bool markArrayEntriesAsInternal(v8::Local, v8::Local, + V8InternalValueType); +v8::Local v8InternalValueTypeFrom(v8::Local, + v8::Local); + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_INTERNAL_VALUE_TYPE_H_ diff --git a/ios/libnode/include/node/inspector/v8-regex.h b/ios/libnode/include/node/inspector/v8-regex.h new file mode 100644 index 0000000..c2c4c09 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-regex.h @@ -0,0 +1,37 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_REGEX_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_REGEX_H_ + +#include "src/base/macros.h" +#include "src/inspector/string-16.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class V8InspectorImpl; + +enum MultilineMode { MultilineDisabled, MultilineEnabled }; + +class V8Regex { + public: + V8Regex(V8InspectorImpl*, const String16&, bool caseSensitive, + bool multiline = false); + int match(const String16&, int startFrom = 0, int* matchLength = 0) const; + bool isValid() const { return !m_regex.IsEmpty(); } + const String16& errorMessage() const { return m_errorMessage; } + + private: + V8InspectorImpl* m_inspector; + v8::Global m_regex; + String16 m_errorMessage; + + DISALLOW_COPY_AND_ASSIGN(V8Regex); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_REGEX_H_ diff --git a/ios/libnode/include/node/inspector/v8-runtime-agent-impl.h b/ios/libnode/include/node/inspector/v8-runtime-agent-impl.h new file mode 100644 index 0000000..09ec751 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-runtime-agent-impl.h @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_RUNTIME_AGENT_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_RUNTIME_AGENT_IMPL_H_ + +#include "src/base/macros.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Runtime.h" + +#include "include/v8.h" + +namespace v8_inspector { + +class InjectedScript; +class InspectedContext; +class RemoteObjectIdBase; +class V8ConsoleMessage; +class V8InspectorImpl; +class V8InspectorSessionImpl; + +using protocol::ErrorString; +using protocol::Maybe; + +class V8RuntimeAgentImpl : public protocol::Runtime::Backend { + public: + V8RuntimeAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, + protocol::DictionaryValue* state); + ~V8RuntimeAgentImpl() override; + void restore(); + + // Part of the protocol. + void enable(ErrorString*) override; + void disable(ErrorString*) override; + void evaluate(const String16& expression, const Maybe& objectGroup, + const Maybe& includeCommandLineAPI, + const Maybe& silent, const Maybe& executionContextId, + const Maybe& returnByValue, + const Maybe& generatePreview, + const Maybe& userGesture, const Maybe& awaitPromise, + std::unique_ptr) override; + void awaitPromise(const String16& promiseObjectId, + const Maybe& returnByValue, + const Maybe& generatePreview, + std::unique_ptr) override; + void callFunctionOn( + const String16& objectId, const String16& expression, + const Maybe>& + optionalArguments, + const Maybe& silent, const Maybe& returnByValue, + const Maybe& generatePreview, const Maybe& userGesture, + const Maybe& awaitPromise, + std::unique_ptr) override; + void releaseObject(ErrorString*, const String16& objectId) override; + void getProperties( + ErrorString*, const String16& objectId, const Maybe& ownProperties, + const Maybe& accessorPropertiesOnly, + const Maybe& generatePreview, + std::unique_ptr>* + result, + Maybe>* + internalProperties, + Maybe*) override; + void releaseObjectGroup(ErrorString*, const String16& objectGroup) override; + void runIfWaitingForDebugger(ErrorString*) override; + void setCustomObjectFormatterEnabled(ErrorString*, bool) override; + void discardConsoleEntries(ErrorString*) override; + void compileScript(ErrorString*, const String16& expression, + const String16& sourceURL, bool persistScript, + const Maybe& executionContextId, Maybe*, + Maybe*) override; + void runScript(const String16&, const Maybe& executionContextId, + const Maybe& objectGroup, const Maybe& silent, + const Maybe& includeCommandLineAPI, + const Maybe& returnByValue, + const Maybe& generatePreview, + const Maybe& awaitPromise, + std::unique_ptr) override; + + void reset(); + void reportExecutionContextCreated(InspectedContext*); + void reportExecutionContextDestroyed(InspectedContext*); + void inspect(std::unique_ptr objectToInspect, + std::unique_ptr hints); + void messageAdded(V8ConsoleMessage*); + bool enabled() const { return m_enabled; } + + private: + bool reportMessage(V8ConsoleMessage*, bool generatePreview); + + V8InspectorSessionImpl* m_session; + protocol::DictionaryValue* m_state; + protocol::Runtime::Frontend m_frontend; + V8InspectorImpl* m_inspector; + bool m_enabled; + + DISALLOW_COPY_AND_ASSIGN(V8RuntimeAgentImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_RUNTIME_AGENT_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-schema-agent-impl.h b/ios/libnode/include/node/inspector/v8-schema-agent-impl.h new file mode 100644 index 0000000..0c7ae09 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-schema-agent-impl.h @@ -0,0 +1,37 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_SCHEMA_AGENT_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_SCHEMA_AGENT_IMPL_H_ + +#include "src/base/macros.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Schema.h" + +namespace v8_inspector { + +class V8InspectorSessionImpl; + +using protocol::ErrorString; + +class V8SchemaAgentImpl : public protocol::Schema::Backend { + public: + V8SchemaAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, + protocol::DictionaryValue* state); + ~V8SchemaAgentImpl() override; + + void getDomains( + ErrorString*, + std::unique_ptr>*) override; + + private: + V8InspectorSessionImpl* m_session; + protocol::Schema::Frontend m_frontend; + + DISALLOW_COPY_AND_ASSIGN(V8SchemaAgentImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_SCHEMA_AGENT_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-stack-trace-impl.h b/ios/libnode/include/node/inspector/v8-stack-trace-impl.h new file mode 100644 index 0000000..ea87ee4 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-stack-trace-impl.h @@ -0,0 +1,99 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_STACK_TRACE_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_STACK_TRACE_IMPL_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/protocol/Forward.h" +#include "src/inspector/protocol/Runtime.h" + +#include "include/v8-inspector.h" + +namespace v8_inspector { + +class TracedValue; +class V8Debugger; + +// Note: async stack trace may have empty top stack with non-empty tail to +// indicate +// that current native-only state had some async story. +// On the other hand, any non-top async stack is guaranteed to be non-empty. +class V8StackTraceImpl final : public V8StackTrace { + public: + static const size_t maxCallStackSizeToCapture = 200; + + class Frame { + public: + Frame(); + Frame(const String16& functionName, const String16& scriptId, + const String16& scriptName, int lineNumber, int column = 0); + ~Frame(); + + const String16& functionName() const { return m_functionName; } + const String16& scriptId() const { return m_scriptId; } + const String16& sourceURL() const { return m_scriptName; } + int lineNumber() const { return m_lineNumber; } + int columnNumber() const { return m_columnNumber; } + Frame clone() const; + + private: + friend class V8StackTraceImpl; + std::unique_ptr buildInspectorObject() const; + void toTracedValue(TracedValue*) const; + + String16 m_functionName; + String16 m_scriptId; + String16 m_scriptName; + int m_lineNumber; + int m_columnNumber; + }; + + static void setCaptureStackTraceForUncaughtExceptions(v8::Isolate*, + bool capture); + static std::unique_ptr create( + V8Debugger*, int contextGroupId, v8::Local, + size_t maxStackSize, const String16& description = String16()); + static std::unique_ptr capture( + V8Debugger*, int contextGroupId, size_t maxStackSize, + const String16& description = String16()); + + // This method drops the async chain. Use cloneImpl() instead. + std::unique_ptr clone() override; + std::unique_ptr cloneImpl(); + std::unique_ptr buildInspectorObjectForTail( + V8Debugger*) const; + std::unique_ptr buildInspectorObjectImpl() + const; + ~V8StackTraceImpl() override; + + // V8StackTrace implementation. + bool isEmpty() const override { return !m_frames.size(); }; + StringView topSourceURL() const override; + int topLineNumber() const override; + int topColumnNumber() const override; + StringView topScriptId() const override; + StringView topFunctionName() const override; + std::unique_ptr buildInspectorObject() + const override; + std::unique_ptr toString() const override; + + private: + V8StackTraceImpl(int contextGroupId, const String16& description, + std::vector& frames, // NOLINT(runtime/references) + std::unique_ptr parent); + + int m_contextGroupId; + String16 m_description; + std::vector m_frames; + std::unique_ptr m_parent; + + DISALLOW_COPY_AND_ASSIGN(V8StackTraceImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_STACK_TRACE_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-timetravel-agent-impl.h b/ios/libnode/include/node/inspector/v8-timetravel-agent-impl.h new file mode 100644 index 0000000..b37780b --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-timetravel-agent-impl.h @@ -0,0 +1,46 @@ +// Copyright 2015 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_TIMETRAVEL_AGENT_IMPL_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_TIMETRAVEL_AGENT_IMPL_H_ + +#include + +#include "src/base/macros.h" +#include "src/inspector/protocol/TimeTravel.h" +#include "src/inspector/protocol/Forward.h" + +namespace v8_inspector { + +class V8Debugger; +class V8InspectorImpl; +class V8InspectorSessionImpl; + +using protocol::ErrorString; + +class V8TimeTravelAgentImpl : public protocol::TimeTravel::Backend { + public: + V8TimeTravelAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, + protocol::DictionaryValue* state); + ~V8TimeTravelAgentImpl() override; + + // Part of the protocol. + void reverse(ErrorString*) override; + void stepBack(ErrorString*) override; + + bool enabled(); + + private: + bool checkEnabled(ErrorString*); + + V8InspectorSessionImpl* m_session; + protocol::TimeTravel::Frontend m_frontend; + protocol::DictionaryValue* m_state; + + DISALLOW_COPY_AND_ASSIGN(V8TimeTravelAgentImpl); +}; + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_TIMETRAVEL_AGENT_IMPL_H_ diff --git a/ios/libnode/include/node/inspector/v8-value-copier.h b/ios/libnode/include/node/inspector/v8-value-copier.h new file mode 100644 index 0000000..ee8c698 --- /dev/null +++ b/ios/libnode/include/node/inspector/v8-value-copier.h @@ -0,0 +1,24 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_VALUE_COPIER_H_ +#define DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_VALUE_COPIER_H_ + +#include "include/v8.h" + +namespace v8_inspector { + +v8::MaybeLocal copyValueFromDebuggerContext( + v8::Isolate*, v8::Local debuggerContext, + v8::Local toContext, v8::Local); +v8::Maybe createDataProperty(v8::Local, + v8::Local, + v8::Local key, + v8::Local); +v8::Maybe createDataProperty(v8::Local, v8::Local, + int index, v8::Local); + +} // namespace v8_inspector + +#endif // DEPS_CHAKRASHIM_SRC_INSPECTOR_V8_VALUE_COPIER_H_ diff --git a/ios/libnode/include/node/jsrtcontextshim.h b/ios/libnode/include/node/jsrtcontextshim.h new file mode 100644 index 0000000..87fc3bb --- /dev/null +++ b/ios/libnode/include/node/jsrtcontextshim.h @@ -0,0 +1,174 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTCONTEXTSHIM_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTCONTEXTSHIM_H_ + +#include + +namespace jsrt { + +class IsolateShim; + +class ContextShim { + public: + // This has the same layout as v8::Context::Scope + class Scope { + private: + Scope * previous; + ContextShim * contextShim; + public: + explicit Scope(ContextShim * context); + ~Scope(); + + friend class IsolateShim; + }; + + // These global constructors will be cached + enum GlobalType { +#define DEFTYPE(T) T, +#include "jsrtcontextcachedobj.inc" + _TypeCount + }; + + // These prototype functions will be cached/shimmed + enum GlobalPrototypeFunction { +#define DEFMETHOD(T, M) T##_##M, +#include "jsrtcontextcachedobj.inc" + _FunctionCount + }; + + static ContextShim * New(IsolateShim * isolateShim, bool exposeGC, + bool useGlobalTTState, + JsValueRef globalObjectTemplateInstance); + ~ContextShim(); + void EnsureInitialized(); + + bool ExecuteChakraInspectorShimJS(JsValueRef * chakraDebugObject); + + IsolateShim * GetIsolateShim(); + JsContextRef GetContextRef(); + + JsValueRef GetTrue(); + JsValueRef GetFalse(); + JsValueRef GetUndefined(); + JsValueRef GetNull(); + JsValueRef GetZero(); + JsValueRef GetObjectConstructor(); + JsValueRef GetBooleanObjectConstructor(); + JsValueRef GetNumberObjectConstructor(); + JsValueRef GetStringObjectConstructor(); + JsValueRef GetDateConstructor(); + JsValueRef GetRegExpConstructor(); + JsValueRef GetProxyConstructor(); + JsValueRef GetMapConstructor(); + JsValueRef GetGlobalType(GlobalType index); + + JsValueRef GetToStringFunction(); + JsValueRef GetValueOfFunction(); + JsValueRef GetStringConcatFunction(); + JsValueRef GetArrayPushFunction(); + JsValueRef GetGlobalPrototypeFunction(GlobalPrototypeFunction index); + JsValueRef GetProxyOfGlobal(); + JsValueRef GetMapGetFunction(); + JsValueRef GetMapSetFunction(); + JsValueRef GetMapHasFunction(); + + void * GetAlignedPointerFromEmbedderData(int index); + void SetAlignedPointerInEmbedderData(int index, void * value); + void RunMicrotasks(); + + static ContextShim * GetCurrent(); + + private: + ContextShim(IsolateShim * isolateShim, JsContextRef context, bool exposeGC, + JsValueRef globalObjectTemplateInstance); + bool DoInitializeContextShim(); + bool InitializeBuiltIns(); + bool InitializeProxyOfGlobal(); + bool InitializeGlobalPrototypeFunctions(); + + template + bool InitializeBuiltIn(JsValueRef * builtInValue, Fn getBuiltIn); + bool InitializeBuiltIn(JsValueRef * builtInValue, const char* globalName); + bool InitializeGlobalTypes(); + bool KeepAlive(JsValueRef value); + JsValueRef GetCachedShimFunction(CachedPropertyIdRef id, JsValueRef* func); + bool ExposeGc(); + bool CheckConfigGlobalObjectTemplate(); + bool ExecuteChakraShimJS(); + + IsolateShim * isolateShim; + JsContextRef context; + bool initialized; + bool exposeGC; + JsValueRef keepAliveObject; + int builtInCount; + JsValueRef globalObjectTemplateInstance; + + JsValueRef trueRef; + JsValueRef falseRef; + JsValueRef undefinedRef; + JsValueRef nullRef; + JsValueRef zero; + JsValueRef globalConstructor[GlobalType::_TypeCount]; + JsValueRef globalObject; + JsValueRef proxyOfGlobal; + + JsValueRef globalPrototypeFunction[GlobalPrototypeFunction::_FunctionCount]; + JsValueRef getOwnPropertyDescriptorFunction; + + JsValueRef promiseContinuationFunction; + std::vector embedderData; + +#define DECLARE_CHAKRASHIM_FUNCTION_GETTER(F) \ + public: \ + JsValueRef Get##F##Function(); \ + private: \ + JsValueRef F##Function; \ + +#define DEF_IS_TYPE(F) DECLARE_CHAKRASHIM_FUNCTION_GETTER(F) +#include "jsrtcachedpropertyidref.inc" +#undef DEF_IS_TYPE + + DECLARE_CHAKRASHIM_FUNCTION_GETTER(cloneObject); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getPropertyNames); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getEnumerableNamedProperties); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getEnumerableIndexedProperties); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(createEnumerationIterator); + DECLARE_CHAKRASHIM_FUNCTION_GETTER + (createPropertyDescriptorsEnumerationIterator); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getNamedOwnKeys); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getIndexedOwnKeys); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getStackTrace); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getSymbolKeyFor); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getSymbolFor); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(ensureDebug); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(enqueueMicrotask); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(dequeueMicrotask); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getPropertyAttributes); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(getOwnPropertyNames); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(jsonParse); + DECLARE_CHAKRASHIM_FUNCTION_GETTER(jsonStringify); +}; + +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTCONTEXTSHIM_H_ diff --git a/ios/libnode/include/node/jsrtinspector.h b/ios/libnode/include/node/jsrtinspector.h new file mode 100644 index 0000000..9201709 --- /dev/null +++ b/ios/libnode/include/node/jsrtinspector.h @@ -0,0 +1,60 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTINSPECTOR_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTINSPECTOR_H_ + +#include + +namespace jsrt { + +class InspectorBreakQueue; + +class Inspector { + public: + static bool IsInspectorEnabled(); + static bool IsReplayDebugEnabled(); + static void StartDebugging(JsRuntimeHandle runtime); + static void RequestAsyncBreak(JsRuntimeHandle runtime, + v8::InterruptCallback callback, + void* data); + static void RequestAsyncBreak(v8::Isolate* isolate); + static void SetChakraDebugObject(JsValueRef chakraDebugObject); + static void SetDebugEventHandler(JsDiagDebugEventCallback callback, + void* callbackState); + static void RemoveBreakpoint(unsigned int breakpointId); + static void ClearBreakpoints(); + + private: + static void CHAKRA_CALLBACK JsDiagDebugEventHandler( + JsDiagDebugEvent debugEvent, + JsValueRef eventData, + void* callbackState); + static void InstallHostCallback(JsValueRef chakraDebugObject, + const char *name, + JsNativeFunction nativeFunction); + + static JsDiagDebugEventCallback s_callback; + static void* s_callbackState; + static std::unique_ptr s_breakQueue; +}; +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTINSPECTOR_H_ diff --git a/ios/libnode/include/node/jsrtinspectorhelpers.h b/ios/libnode/include/node/jsrtinspectorhelpers.h new file mode 100644 index 0000000..3e0f7f3 --- /dev/null +++ b/ios/libnode/include/node/jsrtinspectorhelpers.h @@ -0,0 +1,69 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTINSPECTORHELPERS_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTINSPECTORHELPERS_H_ + +#include + +namespace jsrt { + +class InspectorHelpers { + public: + static JsErrorCode TryCopyProperty(JsValueRef sourceObj, + JsPropertyIdRef sourceIdRef, + JsValueRef destObj, + JsPropertyIdRef destIdRef, + bool* wasCopied = nullptr); + static JsErrorCode TryCopyPropertyString(JsValueRef sourceObj, + JsPropertyIdRef sourceIdRef, + JsValueRef destObj, + JsPropertyIdRef destIdRef, + bool* wasCopied = nullptr); + + static v8::Local WrapEvaluateObject(JsValueRef sourceObject); + static v8::Local WrapCallFrameDetails(JsValueRef callFrame); + static v8::Local WrapRuntimeException(JsValueRef eventData); + static v8::Local WrapPropertiesArray(JsValueRef properties); + static v8::Local GetWrappedProperties(int handle); + static v8::Local GetWrappedStackLocals(JsValueRef stackProperties); + + static v8::Local EvaluateOnCallFrame(int ordinal, + JsValueRef expression, + bool returnByValue, + bool* isError = nullptr); + static v8::Local EvaluateOnCallFrame(JsValueRef callFrame, + JsValueRef expression, + bool returnByValue, + bool* isError = nullptr); + + static v8::Local GetScriptSource(unsigned int scriptId); + + static JsRuntimeHandle GetRuntimeFromIsolate(v8::Isolate* isolate); + + private: + static void WrapObject(JsValueRef obj, JsValueRef* wrappedObj); + static void WrapProperty(JsValueRef property, JsValueRef* wrappedProperty); + static v8::Local WrapException(JsValueRef exception); +}; + +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTINSPECTORHELPERS_H_ diff --git a/ios/libnode/include/node/jsrtisolateshim.h b/ios/libnode/include/node/jsrtisolateshim.h new file mode 100644 index 0000000..587113a --- /dev/null +++ b/ios/libnode/include/node/jsrtisolateshim.h @@ -0,0 +1,201 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_ + +#include "uv.h" +#include + +// CHAKRA-TODO : now that node is using libc++ for C++11 support can we remove +// all OSX_SDK_TR1 specialization? +#if !defined(OSX_SDK_TR1) && defined(__APPLE__) +#include +#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < MAC_OS_X_VERSION_10_9 +#define OSX_SDK_TR1 +#endif +#endif + +#include + +namespace v8 { + +class Isolate; +class TryCatch; +extern bool g_disableIdleGc; +} // namespace v8 + +namespace jsrt { + +enum CachedPropertyIdRef : int { +#define DEF(x, ...) x, +#include "jsrtcachedpropertyidref.inc" + Count +}; + +enum CachedSymbolPropertyIdRef { +#define DEFSYMBOL(x, ...) x, +#include "jsrtcachedpropertyidref.inc" + SymbolCount +}; + +class IsolateShim { + public: + v8::ArrayBuffer::Allocator* arrayBufferAllocator; + bool NewContext(JsContextRef * context, bool exposeGC, bool useGlobalTTState, + JsValueRef globalObjectTemplateInstance); + bool GetMemoryUsage(size_t * memoryUsage); + bool Dispose(); + bool IsDisposing(); + + static v8::Isolate * New(size_t optReplayUriLength, const char* optReplayUri, + bool doRecord, bool doReplay, bool doDebug, + uint32_t snapInterval, uint32_t snapHistoryLength); + + static v8::Isolate * GetCurrentAsIsolate(); + static IsolateShim * GetCurrent(); + static IsolateShim * FromIsolate(v8::Isolate * isolate); + static void DisposeAll(); + + static ContextShim * GetContextShim(JsContextRef contextRef); + JsRuntimeHandle GetRuntimeHandle(); + static ContextShim * GetContextShimOfObject(JsValueRef valueRef); + + void Enter(); + void Exit(); + + void PushScope(ContextShim::Scope * scope, JsContextRef contextRef); + void PushScope(ContextShim::Scope * scope, ContextShim * contextShim); + void PopScope(ContextShim::Scope * scope); + + // TTD_NODE + static bool RunSingleStepOfReverseMoveLoop(v8::Isolate* isolate, + uint64_t* moveMode, + int64_t* nextEventTime); + + ContextShim * GetCurrentContextShim(); + + // Symbols propertyIdRef + JsPropertyIdRef GetSelfSymbolPropertyIdRef(); + JsPropertyIdRef GetToStringTagSymbolPropertyIdRef(); + JsPropertyIdRef GetKeepAliveObjectSymbolPropertyIdRef(); + JsPropertyIdRef GetCachedSymbolPropertyIdRef( + CachedSymbolPropertyIdRef cachedSymbolPropertyIdRef); + + // String propertyIdRef + JsPropertyIdRef GetProxyTrapPropertyIdRef(ProxyTraps trap); + JsPropertyIdRef GetCachedPropertyIdRef( + CachedPropertyIdRef cachedPropertyIdRef); + + void RequestInterrupt(v8::InterruptCallback callback, void* data); + void DisableExecution(); + bool IsExeuctionDisabled(); + void EnableExecution(); + static inline bool IsIdleGcEnabled() { + return !v8::g_disableIdleGc; + } + + bool AddMessageListener(void * that); + void RemoveMessageListeners(void * that); + template + void ForEachMessageListener(Fn fn) { + for (auto i = messageListeners.begin(); i != messageListeners.end(); i++) { + fn(*i); + } + } + + JsValueRef GetChakraShimJsArrayBuffer(); + JsValueRef GetChakraInspectorShimJsArrayBuffer(); + + void SetData(unsigned int slot, void* data); + void* GetData(unsigned int slot); + + ContextShim* debugContext; + + inline uv_prepare_t* idleGc_prepare_handle() { + return &idleGc_prepare_handle_; + } + + inline uv_timer_t* idleGc_timer_handle() { + return &idleGc_timer_handle_; + } + + inline bool IsJsScriptExecuted() { + return jsScriptExecuted; + } + + inline void SetScriptExecuted() { + jsScriptExecuted = true; + } + inline void ResetScriptExecuted() { + jsScriptExecuted = false; + } + + inline void SetIsIdleGcScheduled() { + isIdleGcScheduled = true; + } + + inline void ResetIsIdleGcScheduled() { + isIdleGcScheduled = false; + } + + inline bool IsIdleGcScheduled() { + return isIdleGcScheduled; + } + + private: + // Construction/Destruction should go thru New/Dispose + explicit IsolateShim(JsRuntimeHandle runtime); + ~IsolateShim(); + static v8::Isolate * ToIsolate(IsolateShim * isolate); + static void CHAKRA_CALLBACK JsContextBeforeCollectCallback(JsRef contextRef, + void *data); + + JsRuntimeHandle runtime; + JsPropertyIdRef symbolPropertyIdRefs[CachedSymbolPropertyIdRef::SymbolCount]; + JsPropertyIdRef cachedPropertyIdRefs[CachedPropertyIdRef::Count]; + bool isDisposing; + + ContextShim::Scope * contextScopeStack; + IsolateShim ** prevnext; + IsolateShim * next; + + friend class v8::TryCatch; + v8::TryCatch * tryCatchStackTop; + + std::vector messageListeners; + + // Node only has 4 slots (internals::Internals::kNumIsolateDataSlots = 4) + void * embeddedData[4]; + + // CHAKRA-TODO: support multiple shims + static IsolateShim * s_isolateList; + + static THREAD_LOCAL IsolateShim * s_currentIsolate; + static THREAD_LOCAL IsolateShim * s_previousIsolate; + + uv_prepare_t idleGc_prepare_handle_; + uv_timer_t idleGc_timer_handle_; + bool jsScriptExecuted = false; + bool isIdleGcScheduled = false; +}; +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_ diff --git a/ios/libnode/include/node/jsrtproxyutils.h b/ios/libnode/include/node/jsrtproxyutils.h new file mode 100644 index 0000000..4d00ec3 --- /dev/null +++ b/ios/libnode/include/node/jsrtproxyutils.h @@ -0,0 +1,62 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTPROXYUTILS_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTPROXYUTILS_H_ + +#include "jsrtutils.h" + +namespace jsrt { +// Proxy Traps types, please see: +// http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies +// for more details regarding harmony proxies +enum ProxyTraps { + ApplyTrap, + ConstructTrap, + DefinePropertyTrap, + DeletePropertyTrap, + EnumerateTrap, + GetTrap, + GetOwnPropertyDescriptorTrap, + GetPrototypeOfTrap, + HasTrap, + IsExtensibleTrap, + OwnKeysTrap, + PreventExtensionsTrap, + SetTrap, + SetPrototypeOfTrap, + TrapCount +}; + +enum CachedPropertyIdRef: int; +CachedPropertyIdRef GetProxyTrapCachedPropertyIdRef(ProxyTraps trap); + +JsErrorCode CreateProxy( + JsValueRef target, + const JsNativeFunction config[ProxyTraps::TrapCount], + JsValueRef *result); + +JsErrorCode TryParseUInt32(JsValueRef strRef, + bool* isUInt32, + unsigned int *uint32Value); + +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTPROXYUTILS_H_ diff --git a/ios/libnode/include/node/jsrtutils.h b/ios/libnode/include/node/jsrtutils.h new file mode 100644 index 0000000..777c961 --- /dev/null +++ b/ios/libnode/include/node/jsrtutils.h @@ -0,0 +1,573 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_JSRTUTILS_H_ +#define DEPS_CHAKRASHIM_SRC_JSRTUTILS_H_ + +#include +#include +#include +#include +#include "v8.h" +#include "uv.h" + +#ifndef _countof +template +inline size_t _countof(T (&)[N]) { + return N; +} +#endif + +#ifndef BYTE +#define BYTE unsigned char +#endif + +#ifndef UNUSED +#define UNUSED(x) (void)(x) +#endif + +#ifndef _WIN32 +#define strnicmp strncasecmp +#define __debugbreak __builtin_trap +#endif + +#ifndef __APPLE__ + #if defined(_MSC_VER) && _MSC_VER <= 1800 // VS2013? + #define THREAD_LOCAL __declspec(thread) + #else // VS2015+, linux Clang etc. + #define THREAD_LOCAL thread_local + #endif // VS2013? +#else // __APPLE__ + #define THREAD_LOCAL _Thread_local +#endif + +#include "jsrtproxyutils.h" +#include "jsrtcontextshim.h" +#include "jsrtisolateshim.h" + +#define IfComFailError(v) \ + { \ + hr = (v) ; \ + if (FAILED(hr)) { \ + goto error; \ + } \ + } + +#define IfJsErrorRet(expr, ...) \ + { \ + JsErrorCode _error = (expr); \ + if (_error != JsNoError) { \ + return _error, ##__VA_ARGS__; \ + } \ + } + +#define CHAKRA_UNIMPLEMENTED() jsrt::Unimplemented(__FUNCTION__) +#define CHAKRA_UNIMPLEMENTED_(message) jsrt::Unimplemented(message) + +#define CHAKRA_VERIFY(expr) if (!(expr)) { \ + jsrt::Fatal("internal error %s(%d): %s", __FILE__, __LINE__, #expr); } + +#define CHAKRA_VERIFY_NOERROR(errorCode) if (errorCode != JsNoError) { \ + jsrt::Fatal("internal error %s(%d): %x", __FILE__, __LINE__, errorCode); } + +#ifdef DEBUG +#define CHAKRA_ASSERT(expr) assert(expr) +#else +#define CHAKRA_ASSERT(expr) +#endif + +namespace jsrt { + +// Similar to v8::String::Utf8Value but only operates on JS String. +class StringUtf8 { + public: + StringUtf8(); + ~StringUtf8(); + char *operator*() { return _str; } + operator const char *() const { return _str; } + int length() const { return static_cast(_length); } + JsErrorCode From(JsValueRef strRef); + // This just initializes length field. _str will remain uninitialized. + // Use `From()` to initialize _str and _length + JsErrorCode LengthFrom(JsValueRef strRef); + // Detach the underlying `_str`. The caller is responsible to free this + // buffer + char* Detach(); + + private: + // Disallow copying and assigning + StringUtf8(const StringUtf8&); + void operator=(const StringUtf8&); + + char* _str; + int _length; +}; + +JsErrorCode InitializePromise(); + +JsErrorCode UintToValue(uint32_t value, JsValueRef* result); + +JsErrorCode GetProperty(JsValueRef ref, + JsValueRef propName, + JsValueRef *result); + +JsErrorCode GetProperty(JsValueRef ref, + const char *propertyName, + JsValueRef *result); + +JsErrorCode GetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + JsValueRef *result); + +JsErrorCode GetProperty(JsValueRef ref, + JsPropertyIdRef propId, + bool *boolValue); + +JsErrorCode GetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + bool *boolValue); + +JsErrorCode GetProperty(JsValueRef ref, + JsPropertyIdRef propId, + int *intValue); + +JsErrorCode GetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + int *intValue); + +JsErrorCode SetProperty(JsValueRef ref, + JsValueRef propName, + JsValueRef propValue); + +JsErrorCode SetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + JsValueRef propValue); + +JsErrorCode SetProperty(JsValueRef ref, + const char *propertyName, + JsValueRef propValue); + +JsErrorCode SetProperty(JsValueRef ref, + JsPropertyIdRef propId, + bool boolValue); + +JsErrorCode SetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + bool boolValue); + +JsErrorCode SetProperty(JsValueRef ref, + JsPropertyIdRef propId, + const char *stringValue); + +JsErrorCode SetProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + const char *stringValue); + +JsErrorCode DeleteIndexedProperty(JsValueRef object, + unsigned int index); + +JsErrorCode DeleteProperty(JsValueRef ref, + JsValueRef propName, + JsValueRef* result); + +JsErrorCode GetOwnPropertyDescriptor(JsValueRef ref, + JsValueRef prop, + JsValueRef* result); + +JsErrorCode IsZero(JsValueRef value, + bool *result); + +JsErrorCode IsUndefined(JsValueRef value, + bool *result); + +JsErrorCode HasOwnProperty(JsValueRef object, + JsValueRef prop, + JsValueRef *result); + +JsErrorCode HasProperty(JsValueRef object, + JsValueRef prop, + bool *result); + +JsErrorCode HasProperty(JsValueRef object, + CachedPropertyIdRef cachedIdRef, + bool *result); + +JsErrorCode HasIndexedProperty(JsValueRef object, + unsigned int index, + bool *result); + +JsErrorCode GetEnumerableNamedProperties(JsValueRef object, + JsValueRef *result); + +JsErrorCode GetEnumerableIndexedProperties(JsValueRef object, + JsValueRef *result); + +JsErrorCode GetIndexedOwnKeys(JsValueRef object, + JsValueRef *result); + +JsErrorCode GetNamedOwnKeys(JsValueRef object, + JsValueRef *result); + +JsErrorCode CreateEnumerationIterator(JsValueRef enumeration, + JsValueRef *result); + +JsErrorCode CreatePropertyDescriptorsEnumerationIterator(JsValueRef enumeration, + JsValueRef *result); + +JsErrorCode ConcatArray(JsValueRef first, + JsValueRef second, + JsValueRef *result); + +JsErrorCode PushArray(JsValueRef array, + JsValueRef item, + JsValueRef *result); + +JsErrorCode CallProperty(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + JsValueRef *arguments, + unsigned short argumentCount, // NOLINT(runtime/int) + JsValueRef *result); + +JsErrorCode CallGetter(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + JsValueRef* result); + +JsErrorCode CallGetter(JsValueRef ref, + CachedPropertyIdRef cachedIdRef, + int* result); + +JsErrorCode GetPropertyOfGlobal(const char *propertyName, + JsValueRef *ref); + +JsErrorCode SetPropertyOfGlobal(const char *propertyName, + JsValueRef ref); + +JsValueRef GetNull(); + +JsValueRef GetUndefined(); + +JsValueRef GetTrue(); + +JsValueRef GetFalse(); + +JsErrorCode GetArrayLength(JsValueRef arrayRef, + unsigned int *arraySize); + +bool InstanceOf(JsValueRef first, + JsValueRef second); + +JsErrorCode CloneObject(JsValueRef source, + JsValueRef target, + bool cloneProtoype = false); + +JsErrorCode GetPropertyNames(JsValueRef object, + JsValueRef *namesArray); + +JsErrorCode AddExternalData(JsValueRef ref, + JsPropertyIdRef externalDataPropertyId, + void *data, + JsFinalizeCallback onObjectFinalize); + +JsErrorCode AddExternalData(JsValueRef ref, + void *data, + JsFinalizeCallback onObjectFinalize); + +JsErrorCode GetExternalData(JsValueRef ref, + JsPropertyIdRef idRef, + void **data); + +JsErrorCode GetExternalData(JsValueRef ref, + void **data); + +JsErrorCode CreateFunctionWithExternalData(JsNativeFunction, + void* data, + JsFinalizeCallback onObjectFinalize, + JsValueRef *function); + +JsErrorCode ToString(JsValueRef ref, + JsValueRef* strRef, StringUtf8* stringUtf8); + +JsErrorCode CreateString(const char *string, + JsValueRef *ref); + +JsErrorCode CreatePropertyId(const char *name, + JsValueRef *propertyIdRef); + +#define DEF_IS_TYPE(F) \ +JsErrorCode Call##F(JsValueRef value, \ +JsValueRef *resultRef); \ + +#include "jsrtcachedpropertyidref.inc" +#undef DEF_IS_TYPE + +JsValueRef CHAKRA_CALLBACK CollectGarbage( + JsValueRef callee, + bool isConstructCall, + JsValueRef *arguments, + unsigned short argumentCount, // NOLINT(runtime/int) + void *callbackState); + +// the possible values for the property descriptor options +enum PropertyDescriptorOptionValues { + True, + False, + None +}; + +PropertyDescriptorOptionValues GetPropertyDescriptorOptionValue(bool b); + +JsErrorCode CreatePropertyDescriptor( + PropertyDescriptorOptionValues writable, + PropertyDescriptorOptionValues enumerable, + PropertyDescriptorOptionValues configurable, + JsValueRef value, + JsValueRef getter, + JsValueRef setter, + JsValueRef *descriptor); + +JsErrorCode CreatePropertyDescriptor(v8::PropertyAttribute attributes, + JsValueRef value, + JsValueRef getter, + JsValueRef setter, + JsValueRef *descriptor); + +JsErrorCode DefineProperty(JsValueRef object, + const char * propertyName, + PropertyDescriptorOptionValues writable, + PropertyDescriptorOptionValues enumerable, + PropertyDescriptorOptionValues configurable, + JsValueRef value, + JsValueRef getter, + JsValueRef setter); + +JsErrorCode DefineProperty(JsValueRef object, + JsPropertyIdRef propertyIdRef, + PropertyDescriptorOptionValues writable, + PropertyDescriptorOptionValues enumerable, + PropertyDescriptorOptionValues configurable, + JsValueRef value, + JsValueRef getter, + JsValueRef setter); + +JsErrorCode GetPropertyIdFromName(JsValueRef nameRef, + JsPropertyIdRef *idRef); + +JsErrorCode GetPropertyIdFromValue(JsValueRef valueRef, + JsPropertyIdRef *idRef); + +JsErrorCode GetObjectConstructor(JsValueRef objectRef, + JsValueRef *constructorRef); + +JsErrorCode SetIndexedProperty(JsValueRef object, + unsigned int index, + JsValueRef value); + +JsErrorCode GetIndexedProperty(JsValueRef object, + unsigned int index, + JsValueRef *value); + +// CHAKRA-TODO : Currently Chakra's ParseScript doesn't support strictMode +// flag. As a workaround, prepend the script text with 'use strict'. +JsErrorCode ParseScript(StringUtf8 *script, + JsSourceContext sourceContext, + JsValueRef sourceUrl, + bool isStrictMode, + JsValueRef *result); + +JsErrorCode GetHiddenValuesTable(JsValueRef object, + JsPropertyIdRef* hiddenValueIdRef, + JsValueRef* hiddenValuesTable, + bool* isUndefined); + +JsErrorCode GetPrivate(JsValueRef object, JsValueRef key, + JsValueRef *result); + +JsErrorCode SetPrivate(JsValueRef object, JsValueRef key, + JsValueRef value); + +bool HasPrivate(JsValueRef object, JsValueRef key); + +bool DeletePrivate(JsValueRef object, JsValueRef key); + +void Unimplemented(const char * message); + +void Fatal(const char * format, ...); + +void ScheduleIdleGcTask(uint64_t timeoutInMilliSeconds = 1000); + +void PrepareIdleGC(uv_prepare_t* prepareHandler); + +void IdleGC(uv_timer_t *timerHandler); + +// Arguments buffer for JsCallFunction +template +class JsArguments { + private: + JsValueRef _local[STATIC_COUNT]; + JsValueRef* _args; + + public: + explicit JsArguments(int count) { + _args = count <= STATIC_COUNT ? _local : new JsValueRef[count]; + } + + ~JsArguments() { + if (_args != _local) { + delete [] _args; + } + } + + operator JsValueRef*() { + return _args; + } +}; + + +// Helpers for JsCallFunction/JsConstructObject with undefined as arg0 + +template +JsErrorCode CallFunction(const T& api, + JsValueRef func, + JsValueRef* result) { + JsValueRef args[] = { GetUndefined() }; + return api(func, args, _countof(args), result); +} + +template +JsErrorCode CallFunction(const T& api, + JsValueRef func, JsValueRef arg1, + JsValueRef* result) { + JsValueRef args[] = { GetUndefined(), arg1 }; + return api(func, args, _countof(args), result); +} + +template +JsErrorCode CallFunction(const T& api, + JsValueRef func, JsValueRef arg1, JsValueRef arg2, + JsValueRef* result) { + JsValueRef args[] = { GetUndefined(), arg1, arg2 }; + return api(func, args, _countof(args), result); +} + +template +JsErrorCode CallFunction(const T& api, + JsValueRef func, JsValueRef arg1, JsValueRef arg2, + JsValueRef arg3, JsValueRef* result) { + JsValueRef args[] = { GetUndefined(), arg1, arg2, arg3 }; + return api(func, args, _countof(args), result); +} + +inline JsErrorCode CallFunction(JsValueRef func, + JsValueRef* result) { + return CallFunction(JsCallFunction, func, result); +} + +inline JsErrorCode CallFunction(JsValueRef func, JsValueRef arg1, + JsValueRef* result) { + return CallFunction(JsCallFunction, func, arg1, result); +} + +inline JsErrorCode CallFunction(JsValueRef func, + JsValueRef arg1, JsValueRef arg2, + JsValueRef* result) { + return CallFunction(JsCallFunction, func, arg1, arg2, result); +} + +inline JsErrorCode CallFunction(JsValueRef func, + JsValueRef arg1, JsValueRef arg2, + JsValueRef arg3, JsValueRef* result) { + return CallFunction(JsCallFunction, func, arg1, arg2, arg3, result); +} + +inline JsErrorCode ConstructObject(JsValueRef func, + JsValueRef* result) { + return CallFunction(JsConstructObject, func, result); +} + +inline JsErrorCode ConstructObject(JsValueRef func, JsValueRef arg1, + JsValueRef* result) { + return CallFunction(JsConstructObject, func, arg1, result); +} + +inline JsErrorCode ConstructObject(JsValueRef func, + JsValueRef arg1, JsValueRef arg2, + JsValueRef* result) { + return CallFunction(JsConstructObject, func, arg1, arg2, result); +} + + +template +JsErrorCode ValueToNative(const JsConvertToValueFunc& JsConvertToValue, + const JsValueToNativeFunc& JsValueToNative, + JsValueRef value, T* nativeValue) { + JsErrorCode error; + + // If LIKELY, try JsValueToNative first. Likely to succeed. + if (LIKELY) { + error = JsValueToNative(value, nativeValue); + if (error != JsErrorInvalidArgument) { + return error; + } + } + + // Perform JS conversion first, then to native. + error = JsConvertToValue(value, &value); + if (error != JsNoError) { + return error; + } + return JsValueToNative(value, nativeValue); +} + +inline JsErrorCode ValueToBool(JsValueRef value, bool* boolValue) { + return ValueToNative( + JsConvertValueToBoolean, JsBooleanToBool, value, boolValue); +} + +inline JsErrorCode ValueToBoolLikely(JsValueRef value, bool* boolValue) { + return ValueToNative( + JsConvertValueToBoolean, JsBooleanToBool, value, boolValue); +} + +inline JsErrorCode ValueToInt(JsValueRef value, int* intValue) { + return ValueToNative( + JsConvertValueToNumber, JsNumberToInt, value, intValue); +} + +inline JsErrorCode ValueToIntLikely(JsValueRef value, int* intValue) { + return ValueToNative( + JsConvertValueToNumber, JsNumberToInt, value, intValue); +} + +inline JsErrorCode ValueToDouble(JsValueRef value, double* dblValue) { + return ValueToNative( + JsConvertValueToNumber, JsNumberToDouble, value, dblValue); +} + +inline JsErrorCode ValueToDoubleLikely(JsValueRef value, double* dblValue) { + return ValueToNative( + JsConvertValueToNumber, JsNumberToDouble, value, dblValue); +} + +} // namespace jsrt + +#endif // DEPS_CHAKRASHIM_SRC_JSRTUTILS_H_ diff --git a/ios/libnode/include/node/libplatform/libplatform-export.h b/ios/libnode/include/node/libplatform/libplatform-export.h deleted file mode 100644 index 1561843..0000000 --- a/ios/libnode/include/node/libplatform/libplatform-export.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ -#define V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ - -#if defined(_WIN32) - -#ifdef BUILDING_V8_PLATFORM_SHARED -#define V8_PLATFORM_EXPORT __declspec(dllexport) -#elif USING_V8_PLATFORM_SHARED -#define V8_PLATFORM_EXPORT __declspec(dllimport) -#else -#define V8_PLATFORM_EXPORT -#endif // BUILDING_V8_PLATFORM_SHARED - -#else // defined(_WIN32) - -// Setup for Linux shared library export. -#ifdef BUILDING_V8_PLATFORM_SHARED -#define V8_PLATFORM_EXPORT __attribute__((visibility("default"))) -#else -#define V8_PLATFORM_EXPORT -#endif - -#endif // defined(_WIN32) - -#endif // V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ diff --git a/ios/libnode/include/node/libplatform/libplatform.h b/ios/libnode/include/node/libplatform/libplatform.h index e945045..22ba5e0 100644 --- a/ios/libnode/include/node/libplatform/libplatform.h +++ b/ios/libnode/include/node/libplatform/libplatform.h @@ -1,76 +1,42 @@ // Copyright 2014 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_LIBPLATFORM_LIBPLATFORM_H_ #define V8_LIBPLATFORM_LIBPLATFORM_H_ -#include "libplatform/libplatform-export.h" #include "libplatform/v8-tracing.h" -#include "v8-platform.h" // NOLINT(build/include) +#include "include/v8-platform.h" namespace v8 { namespace platform { -enum class IdleTaskSupport { kDisabled, kEnabled }; -enum class InProcessStackDumping { kDisabled, kEnabled }; - -enum class MessageLoopBehavior : bool { - kDoNotWait = false, - kWaitForWork = true -}; - -/** - * Returns a new instance of the default v8::Platform implementation. - * - * The caller will take ownership of the returned pointer. |thread_pool_size| - * is the number of worker threads to allocate for background jobs. If a value - * of zero is passed, a suitable default based on the current number of - * processors online will be chosen. - * If |idle_task_support| is enabled then the platform will accept idle - * tasks (IdleTasksEnabled will return true) and will rely on the embedder - * calling v8::platform::RunIdleTasks to process the idle tasks. - */ -V8_PLATFORM_EXPORT v8::Platform* CreateDefaultPlatform( - int thread_pool_size = 0, - IdleTaskSupport idle_task_support = IdleTaskSupport::kDisabled, - InProcessStackDumping in_process_stack_dumping = - InProcessStackDumping::kEnabled); - -/** - * Pumps the message loop for the given isolate. - * - * The caller has to make sure that this is called from the right thread. - * Returns true if a task was executed, and false otherwise. Unless requested - * through the |behavior| parameter, this call does not block if no task is - * pending. The |platform| has to be created using |CreateDefaultPlatform|. - */ -V8_PLATFORM_EXPORT bool PumpMessageLoop( - v8::Platform* platform, v8::Isolate* isolate, - MessageLoopBehavior behavior = MessageLoopBehavior::kDoNotWait); - -V8_PLATFORM_EXPORT void EnsureEventLoopInitialized(v8::Platform* platform, - v8::Isolate* isolate); - -/** - * Runs pending idle tasks for at most |idle_time_in_seconds| seconds. - * - * The caller has to make sure that this is called from the right thread. - * This call does not block if no task is pending. The |platform| has to be - * created using |CreateDefaultPlatform|. - */ -V8_PLATFORM_EXPORT void RunIdleTasks(v8::Platform* platform, - v8::Isolate* isolate, - double idle_time_in_seconds); - -/** - * Attempts to set the tracing controller for the given platform. - * - * The |platform| has to be created using |CreateDefaultPlatform|. - */ -V8_PLATFORM_EXPORT void SetTracingController( - v8::Platform* platform, - v8::platform::tracing::TracingController* tracing_controller); +void SetTracingController( + v8::Platform* platform, + v8::platform::tracing::TracingController* tracing_controller); } // namespace platform } // namespace v8 diff --git a/ios/libnode/include/node/libplatform/v8-tracing.h b/ios/libnode/include/node/libplatform/v8-tracing.h index 902f8ea..ae2b965 100644 --- a/ios/libnode/include/node/libplatform/v8-tracing.h +++ b/ios/libnode/include/node/libplatform/v8-tracing.h @@ -7,24 +7,16 @@ #include #include -#include #include - -#include "libplatform/libplatform-export.h" -#include "v8-platform.h" // NOLINT(build/include) +#include "v8-platform.h" namespace v8 { - -namespace base { -class Mutex; -} // namespace base - namespace platform { namespace tracing { const int kTraceMaxNumArgs = 2; -class V8_PLATFORM_EXPORT TraceObject { +class TraceObject { public: union ArgValue { bool as_bool; @@ -37,22 +29,19 @@ class V8_PLATFORM_EXPORT TraceObject { TraceObject() {} ~TraceObject(); - void Initialize( - char phase, const uint8_t* category_enabled_flag, const char* name, - const char* scope, uint64_t id, uint64_t bind_id, int num_args, - const char** arg_names, const uint8_t* arg_types, - const uint64_t* arg_values, - std::unique_ptr* arg_convertables, - unsigned int flags); + void Initialize(char phase, const uint8_t* category_enabled_flag, + const char* name, const char* scope, uint64_t id, + uint64_t bind_id, int num_args, const char** arg_names, + const uint8_t* arg_types, const uint64_t* arg_values, + unsigned int flags); void UpdateDuration(); - void InitializeForTesting( - char phase, const uint8_t* category_enabled_flag, const char* name, - const char* scope, uint64_t id, uint64_t bind_id, int num_args, - const char** arg_names, const uint8_t* arg_types, - const uint64_t* arg_values, - std::unique_ptr* arg_convertables, - unsigned int flags, int pid, int tid, int64_t ts, int64_t tts, - uint64_t duration, uint64_t cpu_duration); + void InitializeForTesting(char phase, const uint8_t* category_enabled_flag, + const char* name, const char* scope, uint64_t id, + uint64_t bind_id, int num_args, + const char** arg_names, const uint8_t* arg_types, + const uint64_t* arg_values, unsigned int flags, + int pid, int tid, int64_t ts, int64_t tts, + uint64_t duration, uint64_t cpu_duration); int pid() const { return pid_; } int tid() const { return tid_; } @@ -68,9 +57,6 @@ class V8_PLATFORM_EXPORT TraceObject { const char** arg_names() { return arg_names_; } uint8_t* arg_types() { return arg_types_; } ArgValue* arg_values() { return arg_values_; } - std::unique_ptr* arg_convertables() { - return arg_convertables_; - } unsigned int flags() const { return flags_; } int64_t ts() { return ts_; } int64_t tts() { return tts_; } @@ -86,12 +72,10 @@ class V8_PLATFORM_EXPORT TraceObject { const uint8_t* category_enabled_flag_; uint64_t id_; uint64_t bind_id_; - int num_args_ = 0; + int num_args_; const char* arg_names_[kTraceMaxNumArgs]; uint8_t arg_types_[kTraceMaxNumArgs]; ArgValue arg_values_[kTraceMaxNumArgs]; - std::unique_ptr - arg_convertables_[kTraceMaxNumArgs]; char* parameter_copy_storage_ = nullptr; unsigned int flags_; int64_t ts_; @@ -104,7 +88,7 @@ class V8_PLATFORM_EXPORT TraceObject { void operator=(const TraceObject&) = delete; }; -class V8_PLATFORM_EXPORT TraceWriter { +class TraceWriter { public: TraceWriter() {} virtual ~TraceWriter() {} @@ -119,7 +103,7 @@ class V8_PLATFORM_EXPORT TraceWriter { void operator=(const TraceWriter&) = delete; }; -class V8_PLATFORM_EXPORT TraceBufferChunk { +class TraceBufferChunk { public: explicit TraceBufferChunk(uint32_t seq); @@ -143,7 +127,7 @@ class V8_PLATFORM_EXPORT TraceBufferChunk { void operator=(const TraceBufferChunk&) = delete; }; -class V8_PLATFORM_EXPORT TraceBuffer { +class TraceBuffer { public: TraceBuffer() {} virtual ~TraceBuffer() {} @@ -179,37 +163,46 @@ enum TraceRecordMode { ECHO_TO_CONSOLE, }; -class V8_PLATFORM_EXPORT TraceConfig { +class TraceConfig { public: typedef std::vector StringList; static TraceConfig* CreateDefaultTraceConfig(); - TraceConfig() : enable_systrace_(false), enable_argument_filter_(false) {} + TraceConfig() + : enable_sampling_(false), + enable_systrace_(false), + enable_argument_filter_(false) {} TraceRecordMode GetTraceRecordMode() const { return record_mode_; } + bool IsSamplingEnabled() const { return enable_sampling_; } bool IsSystraceEnabled() const { return enable_systrace_; } bool IsArgumentFilterEnabled() const { return enable_argument_filter_; } void SetTraceRecordMode(TraceRecordMode mode) { record_mode_ = mode; } + void EnableSampling() { enable_sampling_ = true; } void EnableSystrace() { enable_systrace_ = true; } void EnableArgumentFilter() { enable_argument_filter_ = true; } void AddIncludedCategory(const char* included_category); + void AddExcludedCategory(const char* excluded_category); bool IsCategoryGroupEnabled(const char* category_group) const; private: TraceRecordMode record_mode_; + bool enable_sampling_ : 1; bool enable_systrace_ : 1; bool enable_argument_filter_ : 1; StringList included_categories_; + StringList excluded_categories_; // Disallow copy and assign TraceConfig(const TraceConfig&) = delete; void operator=(const TraceConfig&) = delete; }; -class V8_PLATFORM_EXPORT TracingController { +class TracingController + : public v8::TracingController { public: enum Mode { DISABLED = 0, RECORDING_MODE }; @@ -226,27 +219,21 @@ class V8_PLATFORM_EXPORT TracingController { ENABLED_FOR_ETW_EXPORT = 1 << 3 }; - TracingController(); - ~TracingController(); + TracingController() {} void Initialize(TraceBuffer* trace_buffer); const uint8_t* GetCategoryGroupEnabled(const char* category_group); static const char* GetCategoryGroupName(const uint8_t* category_enabled_flag); - 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* arg_convertables, - unsigned int flags); + 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, unsigned int flags); void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, const char* name, uint64_t handle); void StartTracing(TraceConfig* trace_config); void StopTracing(); - void AddTraceStateObserver(Platform::TraceStateObserver* observer); - void RemoveTraceStateObserver(Platform::TraceStateObserver* observer); - private: const uint8_t* GetCategoryGroupEnabledInternal(const char* category_group); void UpdateCategoryGroupEnabledFlag(size_t category_index); @@ -254,8 +241,6 @@ class V8_PLATFORM_EXPORT TracingController { std::unique_ptr trace_buffer_; std::unique_ptr trace_config_; - std::unique_ptr mutex_; - std::unordered_set observers_; Mode mode_ = DISABLED; // Disallow copy and assign diff --git a/ios/libnode/include/node/node.h b/ios/libnode/include/node/node.h index 269abdf..2698672 100644 --- a/ios/libnode/include/node/node.h +++ b/ios/libnode/include/node/node.h @@ -96,6 +96,8 @@ // Forward-declare libuv loop struct uv_loop_s; +#include "chakra_ttd.h" + // Forward-declare these functions now to stop MSVS from becoming // terminally confused when it's done in node_internals.h namespace node { @@ -169,10 +171,6 @@ NODE_EXTERN v8::Local MakeCallback( } // namespace node -#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" -#endif - #include #include @@ -595,10 +593,45 @@ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, const char* name, async_id trigger_async_id = -1); +NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1); + /* Emit the destroy() callback. */ NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, async_context asyncContext); +class InternalCallbackScope; + +/* This class works like `MakeCallback()` in that it sets up a specific + * asyncContext as the current one and informs the async_hooks and domains + * modules that this context is currently active. + * + * `MakeCallback()` is a wrapper around this class as well as + * `Function::Call()`. Either one of these mechanisms needs to be used for + * top-level calls into JavaScript (i.e. without any existing JS stack). + * + * This object should be stack-allocated to ensure that it is contained in a + * valid HandleScope. + */ +class NODE_EXTERN CallbackScope { + public: + CallbackScope(v8::Isolate* isolate, + v8::Local resource, + async_context asyncContext); + ~CallbackScope(); + + private: + InternalCallbackScope* private_; + v8::TryCatch try_catch_; + + void operator=(const CallbackScope&) = delete; + void operator=(CallbackScope&&) = delete; + CallbackScope(const CallbackScope&) = delete; + CallbackScope(CallbackScope&&) = delete; +}; + /* An API specific to emit before/after callbacks is unnecessary because * MakeCallback will automatically call them for you. * @@ -676,6 +709,16 @@ class AsyncResource { trigger_async_id); } + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1) + : isolate_(isolate), + resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, + trigger_async_id); + } + ~AsyncResource() { EmitAsyncDestroy(isolate_, async_context_); } @@ -724,6 +767,16 @@ class AsyncResource { async_id get_trigger_async_id() const { return async_context_.trigger_async_id; } + + protected: + class CallbackScope : public node::CallbackScope { + public: + explicit CallbackScope(AsyncResource* res) + : node::CallbackScope(res->isolate_, + res->resource_.Get(res->isolate_), + res->async_context_) {} + }; + private: v8::Isolate* isolate_; v8::Persistent resource_; diff --git a/ios/libnode/include/node/node_api.h b/ios/libnode/include/node/node_api.h index 0cf0ba0..fbfef50 100644 --- a/ios/libnode/include/node/node_api.h +++ b/ios/libnode/include/node/node_api.h @@ -14,6 +14,8 @@ #include #include "node_api_types.h" +#define NAPI_VERSION 1 + #ifdef _WIN32 #ifdef BUILDING_NODE_EXTENSION #ifdef EXTERNAL_NAPI @@ -44,10 +46,8 @@ #endif -typedef void (*napi_addon_register_func)(napi_env env, - napi_value exports, - napi_value module, - void* priv); +typedef napi_value (*napi_addon_register_func)(napi_env env, + napi_value exports); typedef struct { int nm_version; @@ -102,6 +102,8 @@ typedef struct { #define NAPI_MODULE(modname, regfunc) \ NAPI_MODULE_X(modname, regfunc, NULL, 0) +#define NAPI_AUTO_LENGTH SIZE_MAX + EXTERN_C_START NAPI_EXTERN void napi_module_register(napi_module* mod); @@ -111,7 +113,9 @@ napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, - const char* message); + size_t location_len, + const char* message, + size_t message_len); // Getters for defined singletons NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); @@ -156,6 +160,7 @@ NAPI_EXTERN napi_status napi_create_symbol(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_create_function(napi_env env, const char* utf8name, + size_t length, napi_callback cb, void* data, napi_value* result); @@ -320,14 +325,6 @@ NAPI_EXTERN napi_status napi_instanceof(napi_env env, napi_value constructor, bool* result); -// Napi version of node::MakeCallback(...) -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); - // Methods to work with napi_callbacks // Gets all callback info in a single call. (Ugly, but faster.) @@ -340,12 +337,13 @@ NAPI_EXTERN napi_status napi_get_cb_info( napi_value* this_arg, // [out] Receives the JS 'this' arg for the call void** data); // [out] Receives the data pointer for the callback. -NAPI_EXTERN napi_status napi_is_construct_call(napi_env env, - napi_callback_info cbinfo, - bool* result); +NAPI_EXTERN napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result); NAPI_EXTERN napi_status napi_define_class(napi_env env, const char* utf8name, + size_t length, napi_callback constructor, void* data, size_t property_count, @@ -362,6 +360,9 @@ NAPI_EXTERN napi_status napi_wrap(napi_env env, NAPI_EXTERN napi_status napi_unwrap(napi_env env, napi_value js_object, void** result); +NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, + napi_value js_object, + void** result); NAPI_EXTERN napi_status napi_create_external(napi_env env, void* data, napi_finalize finalize_cb, @@ -521,6 +522,8 @@ NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, // Methods to manage simple async operations NAPI_EXTERN napi_status napi_create_async_work(napi_env env, + napi_value async_resource, + napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, @@ -532,6 +535,22 @@ NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, napi_async_work work); +// Methods for custom handling of async operations +NAPI_EXTERN napi_status napi_async_init(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result); + +NAPI_EXTERN napi_status napi_async_destroy(napi_env env, + napi_async_context async_context); + +NAPI_EXTERN napi_status napi_make_callback(napi_env env, + napi_async_context async_context, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result); // version management NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); @@ -540,6 +559,30 @@ NAPI_EXTERN napi_status napi_get_node_version(napi_env env, const napi_node_version** version); +// Promises +NAPI_EXTERN napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise); +NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution); +NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value rejection); +NAPI_EXTERN napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise); + +// Memory management +NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, + int64_t change_in_bytes, + int64_t* adjusted_value); + +// Runnig a script +NAPI_EXTERN napi_status napi_run_script(napi_env env, + napi_value script, + napi_value* result); + EXTERN_C_END #endif // SRC_NODE_API_H_ diff --git a/ios/libnode/include/node/node_api_types.h b/ios/libnode/include/node/node_api_types.h index 0bdc377..574cb6f 100644 --- a/ios/libnode/include/node/node_api_types.h +++ b/ios/libnode/include/node/node_api_types.h @@ -16,7 +16,9 @@ typedef struct napi_ref__ *napi_ref; typedef struct napi_handle_scope__ *napi_handle_scope; typedef struct napi_escapable_handle_scope__ *napi_escapable_handle_scope; typedef struct napi_callback_info__ *napi_callback_info; +typedef struct napi_async_context__ *napi_async_context; typedef struct napi_async_work__ *napi_async_work; +typedef struct napi_deferred__ *napi_deferred; typedef enum { napi_default = 0, diff --git a/ios/libnode/include/node/node_buffer.h b/ios/libnode/include/node/node_buffer.h index acf9b23..643f075 100644 --- a/ios/libnode/include/node/node_buffer.h +++ b/ios/libnode/include/node/node_buffer.h @@ -40,6 +40,24 @@ NODE_EXTERN bool HasInstance(v8::Local val); NODE_EXTERN bool HasInstance(v8::Local val); NODE_EXTERN char* Data(v8::Local val); NODE_EXTERN char* Data(v8::Local val); + +#if ENABLE_TTD_NODE +NODE_EXTERN void TTDAsyncModRegister(v8::Local val, + unsigned char* initialModPosition); +NODE_EXTERN void TTDAsyncModNotify(unsigned char* finalModPosition); +NODE_EXTERN void TTDSyncDataModNotify(v8::Local val, + unsigned int index, unsigned int count); +// Notify us that a native buffer access (which we don't currently +// understand/support) happened. +#define TTD_NATIVE_BUFFER_ACCESS_NOTIFY(X) \ + if (s_doTTRecord || s_doTTReplay) { \ + JsTTDCheckAndAssertIfTTDRunning( \ + "Unsupported raw buffer access -- investigate this!!!\n"); \ + } +#else +#define TTD_NATIVE_BUFFER_ACCESS_NOTIFY(X) +#endif + NODE_EXTERN size_t Length(v8::Local val); NODE_EXTERN size_t Length(v8::Local val); diff --git a/ios/libnode/include/node/node_version.h b/ios/libnode/include/node/node_version.h index 8683a98..4605e38 100644 --- a/ios/libnode/include/node/node_version.h +++ b/ios/libnode/include/node/node_version.h @@ -23,7 +23,7 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 8 -#define NODE_MINOR_VERSION 4 +#define NODE_MINOR_VERSION 6 #define NODE_PATCH_VERSION 0 #define NODE_VERSION_IS_RELEASE 1 diff --git a/ios/libnode/include/node/openssl/opensslconf.h b/ios/libnode/include/node/openssl/opensslconf.h index 9b20fb6..1c89bab 100644 --- a/ios/libnode/include/node/openssl/opensslconf.h +++ b/ios/libnode/include/node/openssl/opensslconf.h @@ -37,6 +37,8 @@ | solaris | x64 | solaris64-x86_64-gcc | o | | freebsd | ia32 | BSD-x86 | o | | freebsd | x64 | BSD-x86_64 | o | + | netbsd | ia32 | BSD-x86 | o | + | netbsd | x64 | BSD-x86_64 | o | | openbsd | ia32 | BSD-x86 | - | | openbsd | x64 | BSD-x86_64 | - | | others | others | linux-elf | - | @@ -51,6 +53,7 @@ | mac | __APPLE__ && __MACH__ | | solaris | __sun | | freebsd | __FreeBSD__ | + | netbsd | __NetBSD__ | | openbsd | __OpenBSD__ | | linux (not andorid)| __linux__ && !__ANDROID__ | | android | __ANDROID__ | @@ -94,6 +97,11 @@ # define OPENSSL_LINUX 1 #endif +#undef OPENSSL_BSD +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) +# define OPENSSL_BSD 1 +#endif + #if defined(OPENSSL_LINUX) && defined(__i386__) # include "./archs/linux-elf/opensslconf.h" #elif defined(OPENSSL_LINUX) && defined(__ILP32__) @@ -112,9 +120,9 @@ # include "./archs/VC-WIN32/opensslconf.h" #elif defined(_WIN32) && defined(_M_X64) # include "./archs/VC-WIN64A/opensslconf.h" -#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__i386__) +#elif defined(OPENSSL_BSD) && defined(__i386__) # include "./archs/BSD-x86/opensslconf.h" -#elif (defined(__FreeBSD__) || defined(__OpenBSD__)) && defined(__x86_64__) +#elif defined(OPENSSL_BSD) && defined(__x86_64__) # include "./archs/BSD-x86_64/opensslconf.h" #elif defined(__sun) && defined(__i386__) # include "./archs/solaris-x86-gcc/opensslconf.h" diff --git a/ios/libnode/include/node/pal/pal.h b/ios/libnode/include/node/pal/pal.h new file mode 100644 index 0000000..8feefa0 --- /dev/null +++ b/ios/libnode/include/node/pal/pal.h @@ -0,0 +1,30 @@ +// Copyright Microsoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and / or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#ifndef DEPS_CHAKRASHIM_SRC_PAL_PAL_H_ +#define DEPS_CHAKRASHIM_SRC_PAL_PAL_H_ + +#ifndef _WIN32 + +uint64_t GetTickCount(); + +#endif // !_WIN32 + +#endif // DEPS_CHAKRASHIM_SRC_PAL_PAL_H_ diff --git a/ios/libnode/include/node/pthread-barrier.h b/ios/libnode/include/node/pthread-barrier.h index 900ebed..07db9b8 100644 --- a/ios/libnode/include/node/pthread-barrier.h +++ b/ios/libnode/include/node/pthread-barrier.h @@ -23,6 +23,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #endif #define PTHREAD_BARRIER_SERIAL_THREAD 0x12345 +#define UV__PTHREAD_BARRIER_FALLBACK 1 /* * To maintain ABI compatibility with diff --git a/ios/libnode/include/node/uv-errno.h b/ios/libnode/include/node/uv-errno.h index f137151..32bbc51 100644 --- a/ios/libnode/include/node/uv-errno.h +++ b/ios/libnode/include/node/uv-errno.h @@ -416,4 +416,10 @@ # define UV__EHOSTDOWN (-4031) #endif +#if defined(EREMOTEIO) && !defined(_WIN32) +# define UV__EREMOTEIO (-EREMOTEIO) +#else +# define UV__EREMOTEIO (-4030) +#endif + #endif /* UV_ERRNO_H_ */ diff --git a/ios/libnode/include/node/uv-version.h b/ios/libnode/include/node/uv-version.h index c80c40e..9b89149 100644 --- a/ios/libnode/include/node/uv-version.h +++ b/ios/libnode/include/node/uv-version.h @@ -31,7 +31,7 @@ */ #define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 13 +#define UV_VERSION_MINOR 14 #define UV_VERSION_PATCH 1 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/ios/libnode/include/node/uv.h b/ios/libnode/include/node/uv.h index f076094..eac63dd 100644 --- a/ios/libnode/include/node/uv.h +++ b/ios/libnode/include/node/uv.h @@ -140,6 +140,7 @@ extern "C" { XX(ENXIO, "no such device or address") \ XX(EMLINK, "too many links") \ XX(EHOSTDOWN, "host is down") \ + XX(EREMOTEIO, "remote I/O error") \ #define UV_HANDLE_TYPE_MAP(XX) \ XX(ASYNC, async) \ @@ -719,7 +720,8 @@ struct uv_poll_s { enum uv_poll_event { UV_READABLE = 1, UV_WRITABLE = 2, - UV_DISCONNECT = 4 + UV_DISCONNECT = 4, + UV_PRIORITIZED = 8 }; UV_EXTERN int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd); @@ -1112,7 +1114,8 @@ typedef enum { UV_FS_READLINK, UV_FS_CHOWN, UV_FS_FCHOWN, - UV_FS_REALPATH + UV_FS_REALPATH, + UV_FS_COPYFILE } uv_fs_type; /* uv_fs_t is a subclass of uv_req_t. */ @@ -1157,6 +1160,18 @@ UV_EXTERN int uv_fs_write(uv_loop_t* loop, unsigned int nbufs, int64_t offset, uv_fs_cb cb); +/* + * This flag can be used with uv_fs_copyfile() to return an error if the + * destination already exists. + */ +#define UV_FS_COPYFILE_EXCL 0x0001 + +UV_EXTERN int uv_fs_copyfile(uv_loop_t* loop, + uv_fs_t* req, + const char* path, + const char* new_path, + int flags, + uv_fs_cb cb); UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, diff --git a/ios/libnode/include/node/v8-debug.h b/ios/libnode/include/node/v8-debug.h index 54c0f21..3d989fa 100644 --- a/ios/libnode/include/node/v8-debug.h +++ b/ios/libnode/include/node/v8-debug.h @@ -1,255 +1,94 @@ // Copyright 2008 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include -#ifndef V8_V8_DEBUG_H_ -#define V8_V8_DEBUG_H_ - -#include "v8.h" // NOLINT(build/include) - -/** - * ATTENTION: The debugger API exposed by this file is deprecated and will be - * removed by the end of 2017. Please use the V8 inspector declared - * in include/v8-inspector.h instead. - */ namespace v8 { -// Debug events which can occur in the V8 JavaScript engine. enum DebugEvent { Break = 1, Exception = 2, - AfterCompile = 3, - CompileError = 4, - AsyncTaskEvent = 5, + NewFunction = 3, + BeforeCompile = 4, + AfterCompile = 5, + CompileError = 6, + AsyncTaskEvent = 7, }; class V8_EXPORT Debug { public: - /** - * A client object passed to the v8 debugger whose ownership will be taken by - * it. v8 is always responsible for deleting the object. - */ class ClientData { - public: - virtual ~ClientData() {} }; - - /** - * A message object passed to the debug message handler. - */ class Message { public: - /** - * Check type of message. - */ - virtual bool IsEvent() const = 0; - virtual bool IsResponse() const = 0; - virtual DebugEvent GetEvent() const = 0; - - /** - * Indicate whether this is a response to a continue command which will - * start the VM running after this is processed. - */ - virtual bool WillStartRunning() const = 0; - - /** - * Access to execution state and event data. Don't store these cross - * callbacks as their content becomes invalid. These objects are from the - * debugger event that started the debug message loop. - */ - virtual Local GetExecutionState() const = 0; - virtual Local GetEventData() const = 0; - - /** - * Get the debugger protocol JSON. - */ - virtual Local GetJSON() const = 0; - - /** - * Get the context active when the debug event happened. Note this is not - * the current active context as the JavaScript part of the debugger is - * running in its own context which is entered at this point. - */ - virtual Local GetEventContext() const = 0; - - /** - * Client data passed with the corresponding request if any. This is the - * client_data data value passed into Debug::SendCommand along with the - * request that led to the message or NULL if the message is an event. The - * debugger takes ownership of the data and will delete it even if there is - * no message handler. - */ - virtual ClientData* GetClientData() const = 0; - - virtual Isolate* GetIsolate() const = 0; - virtual ~Message() {} + virtual Handle GetJSON() const = 0; + virtual Isolate* GetIsolate() const = 0; }; - /** - * An event details object passed to the debug event listener. - */ class EventDetails { - public: + public: /** - * Event type. - */ + * Event type. + */ virtual DebugEvent GetEvent() const = 0; /** - * Access to execution state and event data of the debug event. Don't store - * these cross callbacks as their content becomes invalid. - */ + * Access to execution state and event data of the debug event. Don't store + * these cross callbacks as their content becomes invalid. + */ virtual Local GetExecutionState() const = 0; virtual Local GetEventData() const = 0; - - /** - * Get the context active when the debug event happened. Note this is not - * the current active context as the JavaScript part of the debugger is - * running in its own context which is entered at this point. - */ virtual Local GetEventContext() const = 0; - - /** - * Client data passed with the corresponding callback when it was - * registered. - */ - virtual Local GetCallbackData() const = 0; - - /** - * This is now a dummy that returns nullptr. - */ - virtual ClientData* GetClientData() const = 0; - virtual Isolate* GetIsolate() const = 0; - virtual ~EventDetails() {} }; - /** - * Debug event callback function. - * - * \param event_details object providing information about the debug event - * - * A EventCallback does not take possession of the event data, - * and must not rely on the data persisting after the handler returns. - */ - typedef void (*EventCallback)(const EventDetails& event_details); - /** - * This is now a no-op. - */ + typedef void (*DebugMessageDispatchHandler)(); + typedef void(*EventCallback)(const EventDetails& event_details); typedef void (*MessageHandler)(const Message& message); - V8_DEPRECATED("No longer supported", static bool SetDebugEventListener( - Isolate* isolate, EventCallback that, - Local data = Local())); - - // Schedule a debugger break to happen when JavaScript code is run - // in the given isolate. - V8_DEPRECATED("No longer supported", - static void DebugBreak(Isolate* isolate)); - - // Remove scheduled debugger break in given isolate if it has not - // happened yet. - V8_DEPRECATED("No longer supported", - static void CancelDebugBreak(Isolate* isolate)); - - // Check if a debugger break is scheduled in the given isolate. - V8_DEPRECATED("No longer supported", - static bool CheckDebugBreak(Isolate* isolate)); - - // This is now a no-op. - V8_DEPRECATED("No longer supported", - static void SetMessageHandler(Isolate* isolate, - MessageHandler handler)); + static bool SetDebugEventListener(Isolate* isolate, EventCallback that, + Local data = Local()); + static void DebugBreak(Isolate *isolate = NULL) {} + static MaybeLocal GetMirror(Local context, + Handle obj) { + return MaybeLocal(); + } + static void ProcessDebugMessages(Isolate* isolate) {} + static Local GetDebugContext(Isolate* isolate); - // This is now a no-op. - V8_DEPRECATED("No longer supported", - static void SendCommand(Isolate* isolate, - const uint16_t* command, int length, - ClientData* client_data = NULL)); + static void EnableInspector(bool enableReplayDebug = false); - /** - * Run a JavaScript function in the debugger. - * \param fun the function to call - * \param data passed as second argument to the function - * With this call the debugger is entered and the function specified is called - * with the execution state as the first argument. This makes it possible to - * get access to information otherwise not available during normal JavaScript - * execution e.g. details on stack frames. Receiver of the function call will - * be the debugger context global object, however this is a subject to change. - * The following example shows a JavaScript function which when passed to - * v8::Debug::Call will return the current line of JavaScript execution. - * - * \code - * function frame_source_line(exec_state) { - * return exec_state.frame(0).sourceLine(); - * } - * \endcode - */ - V8_DEPRECATED("No longer supported", - static MaybeLocal Call( - Local context, v8::Local fun, - Local data = Local())); - - // This is now a no-op. - V8_DEPRECATED("No longer supported", - static void ProcessDebugMessages(Isolate* isolate)); - - /** - * Debugger is running in its own context which is entered while debugger - * messages are being dispatched. This is an explicit getter for this - * debugger context. Note that the content of the debugger context is subject - * to change. The Context exists only when the debugger is active, i.e. at - * least one DebugEventListener or MessageHandler is set. - */ - V8_DEPRECATED("Use v8-inspector", - static Local GetDebugContext(Isolate* isolate)); - - /** - * While in the debug context, this method returns the top-most non-debug - * context, if it exists. - */ - V8_DEPRECATED( - "No longer supported", - static MaybeLocal GetDebuggedContext(Isolate* isolate)); - - /** - * Enable/disable LiveEdit functionality for the given Isolate - * (default Isolate if not provided). V8 will abort if LiveEdit is - * unexpectedly used. LiveEdit is enabled by default. - */ - V8_DEPRECATED("No longer supported", - static void SetLiveEditEnabled(Isolate* isolate, bool enable)); - - /** - * Returns array of internal properties specific to the value type. Result has - * the following format: [, ,...,, ]. Result array - * will be allocated in the current context. - */ - V8_DEPRECATED("No longer supported", - static MaybeLocal GetInternalProperties( - Isolate* isolate, Local value)); - - /** - * Defines if the ES2015 tail call elimination feature is enabled or not. - * The change of this flag triggers deoptimization of all functions that - * contain calls at tail position. - */ - V8_DEPRECATED("No longer supported", - static bool IsTailCallEliminationEnabled(Isolate* isolate)); - V8_DEPRECATED("No longer supported", - static void SetTailCallEliminationEnabled(Isolate* isolate, - bool enabled)); + static void SetLiveEditEnabled(Isolate* isolate, bool enable); }; - } // namespace v8 - - -#undef EXPORT - - -#endif // V8_V8_DEBUG_H_ diff --git a/ios/libnode/include/node/v8-inspector.h b/ios/libnode/include/node/v8-inspector.h index 43bf3b4..6939b2f 100644 --- a/ios/libnode/include/node/v8-inspector.h +++ b/ios/libnode/include/node/v8-inspector.h @@ -85,8 +85,6 @@ class V8_EXPORT V8ContextInfo { StringView auxData; bool hasMemoryOnConsole; - static int executionContextId(v8::Local context); - private: // Disallow copying and allocating this one. enum NotNullTagEnum { NotNullLiteral }; @@ -119,14 +117,6 @@ class V8_EXPORT V8InspectorSession { public: virtual ~V8InspectorSession() {} - // Cross-context inspectable values (DOM nodes in different worlds, etc.). - class V8_EXPORT Inspectable { - public: - virtual v8::Local get(v8::Local) = 0; - virtual ~Inspectable() {} - }; - virtual void addInspectedObject(std::unique_ptr) = 0; - // Dispatching protocol messages. static bool canDispatchMethod(const StringView& method); virtual void dispatchProtocolMessage(const StringView& message) = 0; @@ -146,18 +136,10 @@ class V8_EXPORT V8InspectorSession { virtual std::vector> searchInTextByLines(const StringView& text, const StringView& query, bool caseSensitive, bool isRegex) = 0; - - // Remote objects. - virtual std::unique_ptr wrapObject( - v8::Local, v8::Local, - const StringView& groupName) = 0; - virtual bool unwrapObject(std::unique_ptr* error, - const StringView& objectId, v8::Local*, - v8::Local*, - std::unique_ptr* objectGroup) = 0; - virtual void releaseObjectGroup(const StringView&) = 0; }; +enum class V8ConsoleAPIType { kClear, kDebug, kLog, kInfo, kWarning, kError }; + class V8_EXPORT V8InspectorClient { public: virtual ~V8InspectorClient() {} @@ -189,8 +171,7 @@ class V8_EXPORT V8InspectorClient { virtual void installAdditionalCommandLineAPI(v8::Local, v8::Local) {} - virtual void consoleAPIMessage(int contextGroupId, - v8::Isolate::MessageErrorLevel level, + virtual void consoleAPIMessage(int contextGroupId, V8ConsoleAPIType, const StringView& message, const StringView& url, unsigned lineNumber, unsigned columnNumber, V8StackTrace*) {} @@ -202,7 +183,6 @@ class V8_EXPORT V8InspectorClient { virtual void consoleTime(const StringView& title) {} virtual void consoleTimeEnd(const StringView& title) {} virtual void consoleTimeStamp(const StringView& title) {} - virtual void consoleClear(int contextGroupId) {} virtual double currentTimeMS() { return 0; } typedef void (*TimerCallback)(void*); virtual void startRepeatingTimer(double, TimerCallback, void* data) {} @@ -224,8 +204,8 @@ class V8_EXPORT V8Inspector { virtual void resetContextGroup(int contextGroupId) = 0; // Various instrumentation. - virtual void idleStarted() = 0; - virtual void idleFinished() = 0; + virtual void willExecuteScript(v8::Local, int scriptId) = 0; + virtual void didExecuteScript(v8::Local) = 0; // Async stack traces instrumentation. virtual void asyncTaskScheduled(const StringView& taskName, void* task, diff --git a/ios/libnode/include/node/v8-platform.h b/ios/libnode/include/node/v8-platform.h index 8f6d804..cda8de4 100644 --- a/ios/libnode/include/node/v8-platform.h +++ b/ios/libnode/include/node/v8-platform.h @@ -1,70 +1,98 @@ // Copyright 2013 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_V8_PLATFORM_H_ #define V8_V8_PLATFORM_H_ -#include #include -#include #include +#include namespace v8 { class Isolate; -/** - * A Task represents a unit of work. - */ class Task { public: - virtual ~Task() = default; - + virtual ~Task() {} virtual void Run() = 0; }; /** - * An IdleTask represents a unit of work to be performed in idle time. - * The Run method is invoked with an argument that specifies the deadline in - * seconds returned by MonotonicallyIncreasingTime(). - * The idle task is expected to complete by this deadline. - */ -class IdleTask { - public: - virtual ~IdleTask() = default; - virtual void Run(double deadline_in_seconds) = 0; +* The interface represents complex arguments to trace events. +*/ +class ConvertableToTraceFormat { +public: + virtual ~ConvertableToTraceFormat() = default; + + /** + * Append the class info to the provided |out| string. The appended + * data must be a valid JSON object. Strings must be properly quoted, and + * escaped. There is no processing applied to the content after it is + * appended. + */ + virtual void AppendAsTraceFormat(std::string* out) const = 0; }; -/** - * The interface represents complex arguments to trace events. - */ -class ConvertableToTraceFormat { +class TracingController { public: - virtual ~ConvertableToTraceFormat() = default; - - /** - * Append the class info to the provided |out| string. The appended - * data must be a valid JSON object. Strings must be properly quoted, and - * escaped. There is no processing applied to the content after it is - * appended. - */ - virtual void AppendAsTraceFormat(std::string* out) const = 0; + virtual ~TracingController() = default; + + virtual const uint8_t* GetCategoryGroupEnabled(const char* name) { + static uint8_t no = 0; + return &no; + } + + 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* arg_convertables, + unsigned int flags) { + return 0; + } + + virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, + const char* name, uint64_t handle) {} + + class TraceStateObserver { + public: + virtual ~TraceStateObserver() = default; + virtual void OnTraceEnabled() = 0; + virtual void OnTraceDisabled() = 0; + }; + + virtual void AddTraceStateObserver(TraceStateObserver*) {} + virtual void RemoveTraceStateObserver(TraceStateObserver*) {} }; -/** - * V8 Platform abstraction layer. - * - * The embedder has to provide an implementation of this interface before - * initializing the rest of V8. - */ class Platform { public: - /** - * This enum is used to indicate whether a task is potentially long running, - * or causes a long wait. The embedder might want to use this hint to decide - * whether to execute the task on a dedicated thread. - */ enum ExpectedRuntime { kShortRunningTask, kLongRunningTask @@ -72,100 +100,35 @@ class Platform { virtual ~Platform() = default; - /** - * Gets the number of threads that are used to execute background tasks. Is - * used to estimate the number of tasks a work package should be split into. - * A return value of 0 means that there are no background threads available. - * Note that a value of 0 won't prohibit V8 from posting tasks using - * |CallOnBackgroundThread|. - */ virtual size_t NumberOfAvailableBackgroundThreads() { return 0; } - - /** - * Schedules a task to be invoked on a background thread. |expected_runtime| - * indicates that the task will run a long time. The Platform implementation - * takes ownership of |task|. There is no guarantee about order of execution - * of tasks wrt order of scheduling, nor is there a guarantee about the - * thread the task will be run on. - */ virtual void CallOnBackgroundThread(Task* task, ExpectedRuntime expected_runtime) = 0; - - /** - * Schedules a task to be invoked on a foreground thread wrt a specific - * |isolate|. Tasks posted for the same isolate should be execute in order of - * scheduling. The definition of "foreground" is opaque to V8. - */ virtual void CallOnForegroundThread(Isolate* isolate, Task* task) = 0; - - /** - * Schedules a task to be invoked on a foreground thread wrt a specific - * |isolate| after the given number of seconds |delay_in_seconds|. - * Tasks posted for the same isolate should be execute in order of - * scheduling. The definition of "foreground" is opaque to V8. - */ virtual void CallDelayedOnForegroundThread(Isolate* isolate, Task* task, double delay_in_seconds) = 0; - /** - * Schedules a task to be invoked on a foreground thread wrt a specific - * |isolate| when the embedder is idle. - * Requires that SupportsIdleTasks(isolate) is true. - * Idle tasks may be reordered relative to other task types and may be - * starved for an arbitrarily long time if no idle time is available. - * The definition of "foreground" is opaque to V8. - */ - virtual void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) { - // TODO(ulan): Make this function abstract after V8 roll in Chromium. - } - - /** - * Returns true if idle tasks are enabled for the given |isolate|. - */ virtual bool IdleTasksEnabled(Isolate* isolate) { - // TODO(ulan): Make this function abstract after V8 roll in Chromium. return false; } - /** - * Monotonically increasing time in seconds from an arbitrary fixed point in - * the past. This function is expected to return at least - * millisecond-precision values. For this reason, - * it is recommended that the fixed point be no further in the past than - * the epoch. - **/ virtual double MonotonicallyIncreasingTime() = 0; + typedef void(*StackTracePrinter)(); + + virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } + + virtual TracingController* GetTracingController() = 0; - /** - * Called by TRACE_EVENT* macros, don't call this directly. - * The name parameter is a category group for example: - * TRACE_EVENT0("v8,parse", "V8.Parse") - * The pointer returned points to a value with zero or more of the bits - * defined in CategoryGroupEnabledFlags. - **/ virtual const uint8_t* GetCategoryGroupEnabled(const char* name) { static uint8_t no = 0; return &no; } - /** - * Gets the category group name of the given category_enabled_flag pointer. - * Usually used while serliazing TRACE_EVENTs. - **/ virtual const char* GetCategoryGroupName( const uint8_t* category_enabled_flag) { static const char dummy[] = "dummy"; return dummy; } - /** - * Adds a trace event to the platform tracing system. This function call is - * usually the result of a TRACE_* macro from trace_event_common.h when - * tracing and the category of the particular trace are enabled. It is not - * advisable to call this function on its own; it is really only meant to be - * used by the trace macros. The returned handle can be used by - * UpdateTraceEventDuration to update the duration of COMPLETE events. - */ 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, @@ -174,14 +137,6 @@ class Platform { return 0; } - /** - * Adds a trace event to the platform tracing system. This function call is - * usually the result of a TRACE_* macro from trace_event_common.h when - * tracing and the category of the particular trace are enabled. It is not - * advisable to call this function on its own; it is really only meant to be - * used by the trace macros. The returned handle can be used by - * UpdateTraceEventDuration to update the duration of COMPLETE events. - */ 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, @@ -193,33 +148,12 @@ class Platform { num_args, arg_names, arg_types, arg_values, flags); } - /** - * Sets the duration field of a COMPLETE trace event. It must be called with - * the handle returned from AddTraceEvent(). - **/ virtual void UpdateTraceEventDuration(const uint8_t* category_enabled_flag, const char* name, uint64_t handle) {} - class TraceStateObserver { - public: - virtual ~TraceStateObserver() = default; - virtual void OnTraceEnabled() = 0; - virtual void OnTraceDisabled() = 0; - }; - - /** Adds tracing state change observer. */ + typedef v8::TracingController::TraceStateObserver TraceStateObserver; virtual void AddTraceStateObserver(TraceStateObserver*) {} - - /** Removes tracing state change observer. */ virtual void RemoveTraceStateObserver(TraceStateObserver*) {} - - typedef void (*StackTracePrinter)(); - - /** - * Returns a function pointer that print a stack trace of the current stack - * on invocation. Disables printing of the stack trace if nullptr. - */ - virtual StackTracePrinter GetStackTracePrinter() { return nullptr; } }; } // namespace v8 diff --git a/ios/libnode/include/node/v8-profiler.h b/ios/libnode/include/node/v8-profiler.h index b60d137..740b8f9 100644 --- a/ios/libnode/include/node/v8-profiler.h +++ b/ios/libnode/include/node/v8-profiler.h @@ -1,431 +1,46 @@ // Copyright 2010 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once +#include -#ifndef V8_V8_PROFILER_H_ -#define V8_V8_PROFILER_H_ - -#include -#include -#include "v8.h" // NOLINT(build/include) - -/** - * Profiler support for the V8 JavaScript engine. - */ namespace v8 { -class HeapGraphNode; struct HeapStatsUpdate; -typedef uint32_t SnapshotObjectId; - - -struct CpuProfileDeoptFrame { - int script_id; - size_t position; -}; - -} // namespace v8 - -#ifdef V8_OS_WIN -template class V8_EXPORT std::vector; -#endif - -namespace v8 { - -struct V8_EXPORT CpuProfileDeoptInfo { - /** A pointer to a static string owned by v8. */ - const char* deopt_reason; - std::vector stack; -}; - -} // namespace v8 - -#ifdef V8_OS_WIN -template class V8_EXPORT std::vector; -#endif - -namespace v8 { - -/** - * TracingCpuProfiler monitors tracing being enabled/disabled - * and emits CpuProfile trace events once v8.cpu_profiler tracing category - * is enabled. It has no overhead unless the category is enabled. - */ -class V8_EXPORT TracingCpuProfiler { - public: - static std::unique_ptr Create(Isolate*); - virtual ~TracingCpuProfiler() = default; - - protected: - TracingCpuProfiler() = default; -}; - -// TickSample captures the information collected for each sample. -struct TickSample { - // Internal profiling (with --prof + tools/$OS-tick-processor) wants to - // include the runtime function we're calling. Externally exposed tick - // samples don't care. - enum RecordCEntryFrame { kIncludeCEntryFrame, kSkipCEntryFrame }; - - TickSample() - : state(OTHER), - pc(nullptr), - external_callback_entry(nullptr), - frames_count(0), - has_external_callback(false), - update_stats(true) {} - - /** - * Initialize a tick sample from the isolate. - * \param isolate The isolate. - * \param state Execution state. - * \param record_c_entry_frame Include or skip the runtime function. - * \param update_stats Whether update the sample to the aggregated stats. - * \param use_simulator_reg_state When set to true and V8 is running under a - * simulator, the method will use the simulator - * register state rather than the one provided - * with |state| argument. Otherwise the method - * will use provided register |state| as is. - */ - void Init(Isolate* isolate, const v8::RegisterState& state, - RecordCEntryFrame record_c_entry_frame, bool update_stats, - bool use_simulator_reg_state = true); - /** - * Get a call stack sample from the isolate. - * \param isolate The isolate. - * \param state Register state. - * \param record_c_entry_frame Include or skip the runtime function. - * \param frames Caller allocated buffer to store stack frames. - * \param frames_limit Maximum number of frames to capture. The buffer must - * be large enough to hold the number of frames. - * \param sample_info The sample info is filled up by the function - * provides number of actual captured stack frames and - * the current VM state. - * \param use_simulator_reg_state When set to true and V8 is running under a - * simulator, the method will use the simulator - * register state rather than the one provided - * with |state| argument. Otherwise the method - * will use provided register |state| as is. - * \note GetStackSample is thread and signal safe and should only be called - * when the JS thread is paused or interrupted. - * Otherwise the behavior is undefined. - */ - static bool GetStackSample(Isolate* isolate, v8::RegisterState* state, - RecordCEntryFrame record_c_entry_frame, - void** frames, size_t frames_limit, - v8::SampleInfo* sample_info, - bool use_simulator_reg_state = true); - StateTag state; // The state of the VM. - void* pc; // Instruction pointer. - union { - void* tos; // Top stack value (*sp). - void* external_callback_entry; - }; - static const unsigned kMaxFramesCountLog2 = 8; - static const unsigned kMaxFramesCount = (1 << kMaxFramesCountLog2) - 1; - void* stack[kMaxFramesCount]; // Call stack. - unsigned frames_count : kMaxFramesCountLog2; // Number of captured frames. - bool has_external_callback : 1; - bool update_stats : 1; // Whether the sample should update aggregated stats. -}; - -/** - * CpuProfileNode represents a node in a call graph. - */ -class V8_EXPORT CpuProfileNode { - public: - struct LineTick { - /** The 1-based number of the source line where the function originates. */ - int line; - - /** The count of samples associated with the source line. */ - unsigned int hit_count; - }; - - /** Returns function name (empty string for anonymous functions.) */ - Local GetFunctionName() const; - - /** - * Returns function name (empty string for anonymous functions.) - * The string ownership is *not* passed to the caller. It stays valid until - * profile is deleted. The function is thread safe. - */ - const char* GetFunctionNameStr() const; - - /** Returns id of the script where function is located. */ - int GetScriptId() const; - - /** Returns resource name for script from where the function originates. */ - Local GetScriptResourceName() const; - - /** - * Returns resource name for script from where the function originates. - * The string ownership is *not* passed to the caller. It stays valid until - * profile is deleted. The function is thread safe. - */ - const char* GetScriptResourceNameStr() const; - - /** - * Returns the number, 1-based, of the line where the function originates. - * kNoLineNumberInfo if no line number information is available. - */ - int GetLineNumber() const; - - /** - * Returns 1-based number of the column where the function originates. - * kNoColumnNumberInfo if no column number information is available. - */ - int GetColumnNumber() const; - - /** - * Returns the number of the function's source lines that collect the samples. - */ - unsigned int GetHitLineCount() const; - - /** Returns the set of source lines that collect the samples. - * The caller allocates buffer and responsible for releasing it. - * True if all available entries are copied, otherwise false. - * The function copies nothing if buffer is not large enough. - */ - bool GetLineTicks(LineTick* entries, unsigned int length) const; - - /** Returns bailout reason for the function - * if the optimization was disabled for it. - */ - const char* GetBailoutReason() const; - - /** - * Returns the count of samples where the function was currently executing. - */ - unsigned GetHitCount() const; - - /** Returns function entry UID. */ - V8_DEPRECATE_SOON( - "Use GetScriptId, GetLineNumber, and GetColumnNumber instead.", - unsigned GetCallUid() const); - - /** Returns id of the node. The id is unique within the tree */ - unsigned GetNodeId() const; - - /** Returns child nodes count of the node. */ - int GetChildrenCount() const; - - /** Retrieves a child node by index. */ - const CpuProfileNode* GetChild(int index) const; - - /** Retrieves deopt infos for the node. */ - const std::vector& GetDeoptInfos() const; - - static const int kNoLineNumberInfo = Message::kNoLineNumberInfo; - static const int kNoColumnNumberInfo = Message::kNoColumnInfo; -}; - - -/** - * CpuProfile contains a CPU profile in a form of top-down call tree - * (from main() down to functions that do all the work). - */ -class V8_EXPORT CpuProfile { - public: - /** Returns CPU profile title. */ - Local GetTitle() const; - - /** Returns the root node of the top down call tree. */ - const CpuProfileNode* GetTopDownRoot() const; - - /** - * Returns number of samples recorded. The samples are not recorded unless - * |record_samples| parameter of CpuProfiler::StartCpuProfiling is true. - */ - int GetSamplesCount() const; - - /** - * Returns profile node corresponding to the top frame the sample at - * the given index. - */ - const CpuProfileNode* GetSample(int index) const; - - /** - * Returns the timestamp of the sample. The timestamp is the number of - * microseconds since some unspecified starting point. - * The point is equal to the starting point used by GetStartTime. - */ - int64_t GetSampleTimestamp(int index) const; - - /** - * Returns time when the profile recording was started (in microseconds) - * since some unspecified starting point. - */ - int64_t GetStartTime() const; - - /** - * Returns time when the profile recording was stopped (in microseconds) - * since some unspecified starting point. - * The point is equal to the starting point used by GetStartTime. - */ - int64_t GetEndTime() const; - - /** - * Deletes the profile and removes it from CpuProfiler's list. - * All pointers to nodes previously returned become invalid. - */ - void Delete(); -}; - -/** - * Interface for controlling CPU profiling. Instance of the - * profiler can be created using v8::CpuProfiler::New method. - */ +// NOT IMPLEMENTED class V8_EXPORT CpuProfiler { public: - /** - * Creates a new CPU profiler for the |isolate|. The isolate must be - * initialized. The profiler object must be disposed after use by calling - * |Dispose| method. - */ - static CpuProfiler* New(Isolate* isolate); - - /** - * Disposes the CPU profiler object. - */ - void Dispose(); - - /** - * Changes default CPU profiler sampling interval to the specified number - * of microseconds. Default interval is 1000us. This method must be called - * when there are no profiles being recorded. - */ - void SetSamplingInterval(int us); - - /** - * Starts collecting CPU profile. Title may be an empty string. It - * is allowed to have several profiles being collected at - * once. Attempts to start collecting several profiles with the same - * title are silently ignored. While collecting a profile, functions - * from all security contexts are included in it. The token-based - * filtering is only performed when querying for a profile. - * - * |record_samples| parameter controls whether individual samples should - * be recorded in addition to the aggregated tree. - */ - void StartProfiling(Local title, bool record_samples = false); - - /** - * Stops collecting CPU profile with a given title and returns it. - * If the title given is empty, finishes the last profile started. - */ - CpuProfile* StopProfiling(Local title); - - /** - * Force collection of a sample. Must be called on the VM thread. - * Recording the forced sample does not contribute to the aggregated - * profile statistics. - */ - void CollectSample(); - - /** - * Tells the profiler whether the embedder is idle. - */ - void SetIdle(bool is_idle); - - private: - CpuProfiler(); - ~CpuProfiler(); - CpuProfiler(const CpuProfiler&); - CpuProfiler& operator=(const CpuProfiler&); -}; - - -/** - * HeapSnapshotEdge represents a directed connection between heap - * graph nodes: from retainers to retained nodes. - */ -class V8_EXPORT HeapGraphEdge { - public: - enum Type { - kContextVariable = 0, // A variable from a function context. - kElement = 1, // An element of an array. - kProperty = 2, // A named object property. - kInternal = 3, // A link that can't be accessed from JS, - // thus, its name isn't a real property name - // (e.g. parts of a ConsString). - kHidden = 4, // A link that is needed for proper sizes - // calculation, but may be hidden from user. - kShortcut = 5, // A link that must not be followed during - // sizes calculation. - kWeak = 6 // A weak reference (ignored by the GC). - }; - - /** Returns edge type (see HeapGraphEdge::Type). */ - Type GetType() const; - - /** - * Returns edge name. This can be a variable name, an element index, or - * a property name. - */ - Local GetName() const; - - /** Returns origin node. */ - const HeapGraphNode* GetFromNode() const; - - /** Returns destination node. */ - const HeapGraphNode* GetToNode() const; + // void SetSamplingInterval(int us); + // void StartProfiling(Handle title, bool record_samples = false); + // CpuProfile* StopProfiling(Handle title); + void SetIdle(bool is_idle) {} }; - -/** - * HeapGraphNode represents a node in a heap graph. - */ -class V8_EXPORT HeapGraphNode { - public: - enum Type { - kHidden = 0, // Hidden node, may be filtered when shown to user. - kArray = 1, // An array of elements. - kString = 2, // A string. - kObject = 3, // A JS object (except for arrays and strings). - kCode = 4, // Compiled code. - kClosure = 5, // Function closure. - kRegExp = 6, // RegExp. - kHeapNumber = 7, // Number stored in the heap. - kNative = 8, // Native object (not from V8 heap). - kSynthetic = 9, // Synthetic object, usualy used for grouping - // snapshot items together. - kConsString = 10, // Concatenated string. A pair of pointers to strings. - kSlicedString = 11, // Sliced string. A fragment of another string. - kSymbol = 12 // A Symbol (ES6). - }; - - /** Returns node type (see HeapGraphNode::Type). */ - Type GetType() const; - - /** - * Returns node name. Depending on node's type this can be the name - * of the constructor (for objects), the name of the function (for - * closures), string value, or an empty string (for compiled code). - */ - Local GetName() const; - - /** - * Returns node id. For the same heap object, the id remains the same - * across all snapshots. - */ - SnapshotObjectId GetId() const; - - /** Returns node's own size, in bytes. */ - size_t GetShallowSize() const; - - /** Returns child nodes count of the node. */ - int GetChildrenCount() const; - - /** Retrieves a child by index. */ - const HeapGraphEdge* GetChild(int index) const; -}; - - -/** - * An interface for exporting data from V8, using "push" model. - */ class V8_EXPORT OutputStream { // NOLINT public: enum WriteResult { @@ -433,93 +48,26 @@ class V8_EXPORT OutputStream { // NOLINT kAbort = 1 }; virtual ~OutputStream() {} - /** Notify about the end of stream. */ virtual void EndOfStream() = 0; - /** Get preferred output chunk size. Called only once. */ virtual int GetChunkSize() { return 1024; } - /** - * Writes the next chunk of snapshot data into the stream. Writing - * can be stopped by returning kAbort as function result. EndOfStream - * will not be called in case writing was aborted. - */ virtual WriteResult WriteAsciiChunk(char* data, int size) = 0; - /** - * Writes the next chunk of heap stats data into the stream. Writing - * can be stopped by returning kAbort as function result. EndOfStream - * will not be called in case writing was aborted. - */ virtual WriteResult WriteHeapStatsChunk(HeapStatsUpdate* data, int count) { return kAbort; } }; - -/** - * HeapSnapshots record the state of the JS heap at some moment. - */ +// NOT IMPLEMENTED class V8_EXPORT HeapSnapshot { public: enum SerializationFormat { kJSON = 0 // See format description near 'Serialize' method. }; - /** Returns the root node of the heap graph. */ - const HeapGraphNode* GetRoot() const; - - /** Returns a node by its id. */ - const HeapGraphNode* GetNodeById(SnapshotObjectId id) const; - - /** Returns total nodes count in the snapshot. */ - int GetNodesCount() const; - - /** Returns a node by index. */ - const HeapGraphNode* GetNode(int index) const; - - /** Returns a max seen JS object Id. */ - SnapshotObjectId GetMaxSnapshotJSObjectId() const; - - /** - * Deletes the snapshot and removes it from HeapProfiler's list. - * All pointers to nodes, edges and paths previously returned become - * invalid. - */ - void Delete(); - - /** - * Prepare a serialized representation of the snapshot. The result - * is written into the stream provided in chunks of specified size. - * The total length of the serialized snapshot is unknown in - * advance, it can be roughly equal to JS heap size (that means, - * it can be really big - tens of megabytes). - * - * For the JSON format, heap contents are represented as an object - * with the following structure: - * - * { - * snapshot: { - * title: "...", - * uid: nnn, - * meta: { meta-info }, - * node_count: nnn, - * edge_count: nnn - * }, - * nodes: [nodes array], - * edges: [edges array], - * strings: [strings array] - * } - * - * Nodes reference strings, other nodes, and edges by their indexes - * in corresponding arrays. - */ + void Delete() { delete this; } void Serialize(OutputStream* stream, - SerializationFormat format = kJSON) const; + SerializationFormat format = kJSON) const {} }; - -/** - * An interface for reporting progress and controlling long-running - * activities. - */ class V8_EXPORT ActivityControl { // NOLINT public: enum ControlOption { @@ -527,376 +75,46 @@ class V8_EXPORT ActivityControl { // NOLINT kAbort = 1 }; virtual ~ActivityControl() {} - /** - * Notify about current progress. The activity can be stopped by - * returning kAbort as the callback result. - */ virtual ControlOption ReportProgressValue(int done, int total) = 0; }; - -/** - * AllocationProfile is a sampled profile of allocations done by the program. - * This is structured as a call-graph. - */ -class V8_EXPORT AllocationProfile { - public: - struct Allocation { - /** - * Size of the sampled allocation object. - */ - size_t size; - - /** - * The number of objects of such size that were sampled. - */ - unsigned int count; - }; - - /** - * Represents a node in the call-graph. - */ - struct Node { - /** - * Name of the function. May be empty for anonymous functions or if the - * script corresponding to this function has been unloaded. - */ - Local name; - - /** - * Name of the script containing the function. May be empty if the script - * name is not available, or if the script has been unloaded. - */ - Local script_name; - - /** - * id of the script where the function is located. May be equal to - * v8::UnboundScript::kNoScriptId in cases where the script doesn't exist. - */ - int script_id; - - /** - * Start position of the function in the script. - */ - int start_position; - - /** - * 1-indexed line number where the function starts. May be - * kNoLineNumberInfo if no line number information is available. - */ - int line_number; - - /** - * 1-indexed column number where the function starts. May be - * kNoColumnNumberInfo if no line number information is available. - */ - int column_number; - - /** - * List of callees called from this node for which we have sampled - * allocations. The lifetime of the children is scoped to the containing - * AllocationProfile. - */ - std::vector children; - - /** - * List of self allocations done by this node in the call-graph. - */ - std::vector allocations; - }; - - /** - * Returns the root node of the call-graph. The root node corresponds to an - * empty JS call-stack. The lifetime of the returned Node* is scoped to the - * containing AllocationProfile. - */ - virtual Node* GetRootNode() = 0; - - virtual ~AllocationProfile() {} - - static const int kNoLineNumberInfo = Message::kNoLineNumberInfo; - static const int kNoColumnNumberInfo = Message::kNoColumnInfo; -}; - - -/** - * Interface for controlling heap profiling. Instance of the - * profiler can be retrieved using v8::Isolate::GetHeapProfiler. - */ +// NOT IMPLEMENTED class V8_EXPORT HeapProfiler { public: - enum SamplingFlags { - kSamplingNoFlags = 0, - kSamplingForceGC = 1 << 0, - }; - - typedef std::unordered_set*> - RetainerChildren; - typedef std::vector> - RetainerGroups; - typedef std::vector*, - const v8::PersistentBase*>> - RetainerEdges; - - struct RetainerInfos { - RetainerGroups groups; - RetainerEdges edges; - }; - - /** - * Callback function invoked to retrieve all RetainerInfos from the embedder. - */ - typedef RetainerInfos (*GetRetainerInfosCallback)(v8::Isolate* isolate); - - /** - * Callback function invoked for obtaining RetainedObjectInfo for - * the given JavaScript wrapper object. It is prohibited to enter V8 - * while the callback is running: only getters on the handle and - * GetPointerFromInternalField on the objects are allowed. - */ - typedef RetainedObjectInfo* (*WrapperInfoCallback)(uint16_t class_id, - Local wrapper); - - /** Returns the number of snapshots taken. */ - int GetSnapshotCount(); - - /** Returns a snapshot by index. */ - const HeapSnapshot* GetHeapSnapshot(int index); - - /** - * Returns SnapshotObjectId for a heap object referenced by |value| if - * it has been seen by the heap profiler, kUnknownObjectId otherwise. - */ - SnapshotObjectId GetObjectId(Local value); + typedef RetainedObjectInfo *(*WrapperInfoCallback)( + uint16_t class_id, Handle wrapper); - /** - * Returns heap object with given SnapshotObjectId if the object is alive, - * otherwise empty handle is returned. - */ - Local FindObjectById(SnapshotObjectId id); - - /** - * Clears internal map from SnapshotObjectId to heap object. The new objects - * will not be added into it unless a heap snapshot is taken or heap object - * tracking is kicked off. - */ - void ClearObjectIds(); - - /** - * A constant for invalid SnapshotObjectId. GetSnapshotObjectId will return - * it in case heap profiler cannot find id for the object passed as - * parameter. HeapSnapshot::GetNodeById will always return NULL for such id. - */ - static const SnapshotObjectId kUnknownObjectId = 0; - - /** - * Callback interface for retrieving user friendly names of global objects. - */ class ObjectNameResolver { public: - /** - * Returns name to be used in the heap snapshot for given node. Returned - * string must stay alive until snapshot collection is completed. - */ virtual const char* GetName(Local object) = 0; protected: virtual ~ObjectNameResolver() {} }; - /** - * Takes a heap snapshot and returns it. - */ const HeapSnapshot* TakeHeapSnapshot( ActivityControl* control = NULL, - ObjectNameResolver* global_object_name_resolver = NULL); - - /** - * Starts tracking of heap objects population statistics. After calling - * this method, all heap objects relocations done by the garbage collector - * are being registered. - * - * |track_allocations| parameter controls whether stack trace of each - * allocation in the heap will be recorded and reported as part of - * HeapSnapshot. - */ - void StartTrackingHeapObjects(bool track_allocations = false); - - /** - * Adds a new time interval entry to the aggregated statistics array. The - * time interval entry contains information on the current heap objects - * population size. The method also updates aggregated statistics and - * reports updates for all previous time intervals via the OutputStream - * object. Updates on each time interval are provided as a stream of the - * HeapStatsUpdate structure instances. - * If |timestamp_us| is supplied, timestamp of the new entry will be written - * into it. The return value of the function is the last seen heap object Id. - * - * StartTrackingHeapObjects must be called before the first call to this - * method. - */ - SnapshotObjectId GetHeapStats(OutputStream* stream, - int64_t* timestamp_us = NULL); - - /** - * Stops tracking of heap objects population statistics, cleans up all - * collected data. StartHeapObjectsTracking must be called again prior to - * calling GetHeapStats next time. - */ - void StopTrackingHeapObjects(); - - /** - * Starts gathering a sampling heap profile. A sampling heap profile is - * similar to tcmalloc's heap profiler and Go's mprof. It samples object - * allocations and builds an online 'sampling' heap profile. At any point in - * time, this profile is expected to be a representative sample of objects - * currently live in the system. Each sampled allocation includes the stack - * trace at the time of allocation, which makes this really useful for memory - * leak detection. - * - * This mechanism is intended to be cheap enough that it can be used in - * production with minimal performance overhead. - * - * Allocations are sampled using a randomized Poisson process. On average, one - * allocation will be sampled every |sample_interval| bytes allocated. The - * |stack_depth| parameter controls the maximum number of stack frames to be - * captured on each allocation. - * - * NOTE: This is a proof-of-concept at this point. Right now we only sample - * newspace allocations. Support for paged space allocation (e.g. pre-tenured - * objects, large objects, code objects, etc.) and native allocations - * doesn't exist yet, but is anticipated in the future. - * - * Objects allocated before the sampling is started will not be included in - * the profile. - * - * Returns false if a sampling heap profiler is already running. - */ - bool StartSamplingHeapProfiler(uint64_t sample_interval = 512 * 1024, - int stack_depth = 16, - SamplingFlags flags = kSamplingNoFlags); - - /** - * Stops the sampling heap profile and discards the current profile. - */ - void StopSamplingHeapProfiler(); - - /** - * Returns the sampled profile of allocations allocated (and still live) since - * StartSamplingHeapProfiler was called. The ownership of the pointer is - * transfered to the caller. Returns nullptr if sampling heap profiler is not - * active. - */ - AllocationProfile* GetAllocationProfile(); - - /** - * Deletes all snapshots taken. All previously returned pointers to - * snapshots and their contents become invalid after this call. - */ - void DeleteAllHeapSnapshots(); + ObjectNameResolver* global_object_name_resolver = NULL) { + return new HeapSnapshot(); + } - /** Binds a callback to embedder's class ID. */ void SetWrapperClassInfoProvider( - uint16_t class_id, - WrapperInfoCallback callback); - - void SetGetRetainerInfosCallback(GetRetainerInfosCallback callback); - - /** - * Default value of persistent handle class ID. Must not be used to - * define a class. Can be used to reset a class of a persistent - * handle. - */ - static const uint16_t kPersistentHandleNoClassId = 0; - - /** Returns memory used for profiler internal data and snapshots. */ - size_t GetProfilerMemorySize(); - - private: - HeapProfiler(); - ~HeapProfiler(); - HeapProfiler(const HeapProfiler&); - HeapProfiler& operator=(const HeapProfiler&); + uint16_t class_id, WrapperInfoCallback callback) {} + void StartTrackingHeapObjects(bool track_allocations = false) {} }; -/** - * Interface for providing information about embedder's objects - * held by global handles. This information is reported in two ways: - * - * 1. When calling AddObjectGroup, an embedder may pass - * RetainedObjectInfo instance describing the group. To collect - * this information while taking a heap snapshot, V8 calls GC - * prologue and epilogue callbacks. - * - * 2. When a heap snapshot is collected, V8 additionally - * requests RetainedObjectInfos for persistent handles that - * were not previously reported via AddObjectGroup. - * - * Thus, if an embedder wants to provide information about native - * objects for heap snapshots, it can do it in a GC prologue - * handler, and / or by assigning wrapper class ids in the following way: - * - * 1. Bind a callback to class id by calling SetWrapperClassInfoProvider. - * 2. Call SetWrapperClassId on certain persistent handles. - * - * V8 takes ownership of RetainedObjectInfo instances passed to it and - * keeps them alive only during snapshot collection. Afterwards, they - * are freed by calling the Dispose class function. - */ -class V8_EXPORT RetainedObjectInfo { // NOLINT +// NOT IMPLEMENTED +class V8_EXPORT RetainedObjectInfo { public: - /** Called by V8 when it no longer needs an instance. */ virtual void Dispose() = 0; - - /** Returns whether two instances are equivalent. */ - virtual bool IsEquivalent(RetainedObjectInfo* other) = 0; - - /** - * Returns hash value for the instance. Equivalent instances - * must have the same hash value. - */ + virtual bool IsEquivalent(RetainedObjectInfo *other) = 0; virtual intptr_t GetHash() = 0; - - /** - * Returns human-readable label. It must be a null-terminated UTF-8 - * encoded string. V8 copies its contents during a call to GetLabel. - */ - virtual const char* GetLabel() = 0; - - /** - * Returns human-readable group label. It must be a null-terminated UTF-8 - * encoded string. V8 copies its contents during a call to GetGroupLabel. - * Heap snapshot generator will collect all the group names, create - * top level entries with these names and attach the objects to the - * corresponding top level group objects. There is a default - * implementation which is required because embedders don't have their - * own implementation yet. - */ - virtual const char* GetGroupLabel() { return GetLabel(); } - - /** - * Returns element count in case if a global handle retains - * a subgraph by holding one of its nodes. - */ - virtual intptr_t GetElementCount() { return -1; } - - /** Returns embedder's object size in bytes. */ - virtual intptr_t GetSizeInBytes() { return -1; } - - protected: - RetainedObjectInfo() {} - virtual ~RetainedObjectInfo() {} - - private: - RetainedObjectInfo(const RetainedObjectInfo&); - RetainedObjectInfo& operator=(const RetainedObjectInfo&); + virtual const char *GetLabel() = 0; + virtual const char *GetGroupLabel() { return nullptr; } + virtual intptr_t GetElementCount() { return 0; } + virtual intptr_t GetSizeInBytes() { return 0; } }; - -/** - * A struct for exporting HeapStats data from V8, using "push" model. - * See HeapProfiler::GetHeapStats. - */ struct HeapStatsUpdate { HeapStatsUpdate(uint32_t index, uint32_t count, uint32_t size) : index(index), count(count), size(size) { } @@ -905,8 +123,4 @@ struct HeapStatsUpdate { uint32_t size; // New value of size field for the interval with this index. }; - } // namespace v8 - - -#endif // V8_V8_PROFILER_H_ diff --git a/ios/libnode/include/node/v8-testing.h b/ios/libnode/include/node/v8-testing.h deleted file mode 100644 index f67bf25..0000000 --- a/ios/libnode/include/node/v8-testing.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2010 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_V8_TEST_H_ -#define V8_V8_TEST_H_ - -#include "v8.h" // NOLINT(build/include) - -/** - * Testing support for the V8 JavaScript engine. - */ -namespace v8 { - -class V8_EXPORT Testing { - public: - enum StressType { - kStressTypeOpt, - kStressTypeDeopt - }; - - /** - * Set the type of stressing to do. The default if not set is kStressTypeOpt. - */ - static void SetStressRunType(StressType type); - - /** - * Get the number of runs of a given test that is required to get the full - * stress coverage. - */ - static int GetStressRuns(); - - /** - * Indicate the number of the run which is about to start. The value of run - * should be between 0 and one less than the result from GetStressRuns() - */ - static void PrepareStressRun(int run); - - /** - * Force deoptimization of all functions. - */ - static void DeoptimizeAll(Isolate* isolate); -}; - - -} // namespace v8 - -#endif // V8_V8_TEST_H_ diff --git a/ios/libnode/include/node/v8-util.h b/ios/libnode/include/node/v8-util.h deleted file mode 100644 index a04a5e8..0000000 --- a/ios/libnode/include/node/v8-util.h +++ /dev/null @@ -1,655 +0,0 @@ -// Copyright 2014 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_UTIL_H_ -#define V8_UTIL_H_ - -#include "v8.h" // NOLINT(build/include) -#include -#include -#include - -/** - * Support for Persistent containers. - * - * C++11 embedders can use STL containers with Global values, - * but pre-C++11 does not support the required move semantic and hence - * may want these container classes. - */ -namespace v8 { - -typedef uintptr_t PersistentContainerValue; -static const uintptr_t kPersistentContainerNotFound = 0; -enum PersistentContainerCallbackType { - kNotWeak, - // These correspond to v8::WeakCallbackType - kWeakWithParameter, - kWeakWithInternalFields, - kWeak = kWeakWithParameter // For backwards compatibility. Deprecate. -}; - - -/** - * A default trait implemenation for PersistentValueMap which uses std::map - * as a backing map. - * - * Users will have to implement their own weak callbacks & dispose traits. - */ -template -class StdMapTraits { - public: - // STL map & related: - typedef std::map Impl; - typedef typename Impl::iterator Iterator; - - static bool Empty(Impl* impl) { return impl->empty(); } - static size_t Size(Impl* impl) { return impl->size(); } - static void Swap(Impl& a, Impl& b) { std::swap(a, b); } // NOLINT - static Iterator Begin(Impl* impl) { return impl->begin(); } - static Iterator End(Impl* impl) { return impl->end(); } - static K Key(Iterator it) { return it->first; } - static PersistentContainerValue Value(Iterator it) { return it->second; } - static PersistentContainerValue Set(Impl* impl, K key, - PersistentContainerValue value) { - std::pair res = impl->insert(std::make_pair(key, value)); - PersistentContainerValue old_value = kPersistentContainerNotFound; - if (!res.second) { - old_value = res.first->second; - res.first->second = value; - } - return old_value; - } - static PersistentContainerValue Get(Impl* impl, K key) { - Iterator it = impl->find(key); - if (it == impl->end()) return kPersistentContainerNotFound; - return it->second; - } - static PersistentContainerValue Remove(Impl* impl, K key) { - Iterator it = impl->find(key); - if (it == impl->end()) return kPersistentContainerNotFound; - PersistentContainerValue value = it->second; - impl->erase(it); - return value; - } -}; - - -/** - * A default trait implementation for PersistentValueMap, which inherits - * a std:map backing map from StdMapTraits and holds non-weak persistent - * objects and has no special Dispose handling. - * - * You should not derive from this class, since MapType depends on the - * surrounding class, and hence a subclass cannot simply inherit the methods. - */ -template -class DefaultPersistentValueMapTraits : public StdMapTraits { - public: - // Weak callback & friends: - static const PersistentContainerCallbackType kCallbackType = kNotWeak; - typedef PersistentValueMap > - MapType; - typedef void WeakCallbackDataType; - - static WeakCallbackDataType* WeakCallbackParameter( - MapType* map, const K& key, Local value) { - return NULL; - } - static MapType* MapFromWeakCallbackInfo( - const WeakCallbackInfo& data) { - return NULL; - } - static K KeyFromWeakCallbackInfo( - const WeakCallbackInfo& data) { - return K(); - } - static void DisposeCallbackData(WeakCallbackDataType* data) { } - static void Dispose(Isolate* isolate, Global value, K key) {} -}; - - -template -class DefaultGlobalMapTraits : public StdMapTraits { - private: - template - struct RemovePointer; - - public: - // Weak callback & friends: - static const PersistentContainerCallbackType kCallbackType = kNotWeak; - typedef GlobalValueMap > MapType; - typedef void WeakCallbackDataType; - - static WeakCallbackDataType* WeakCallbackParameter(MapType* map, const K& key, - Local value) { - return nullptr; - } - static MapType* MapFromWeakCallbackInfo( - const WeakCallbackInfo& data) { - return nullptr; - } - static K KeyFromWeakCallbackInfo( - const WeakCallbackInfo& data) { - return K(); - } - static void DisposeCallbackData(WeakCallbackDataType* data) {} - static void OnWeakCallback( - const WeakCallbackInfo& data) {} - static void Dispose(Isolate* isolate, Global value, K key) {} - // This is a second pass callback, so SetSecondPassCallback cannot be called. - static void DisposeWeak(const WeakCallbackInfo& data) {} - - private: - template - struct RemovePointer { - typedef T Type; - }; -}; - - -/** - * A map wrapper that allows using Global as a mapped value. - * C++11 embedders don't need this class, as they can use Global - * directly in std containers. - * - * The map relies on a backing map, whose type and accessors are described - * by the Traits class. The backing map will handle values of type - * PersistentContainerValue, with all conversion into and out of V8 - * handles being transparently handled by this class. - */ -template -class PersistentValueMapBase { - public: - Isolate* GetIsolate() { return isolate_; } - - /** - * Return size of the map. - */ - size_t Size() { return Traits::Size(&impl_); } - - /** - * Return whether the map holds weak persistents. - */ - bool IsWeak() { return Traits::kCallbackType != kNotWeak; } - - /** - * Get value stored in map. - */ - Local Get(const K& key) { - return Local::New(isolate_, FromVal(Traits::Get(&impl_, key))); - } - - /** - * Check whether a value is contained in the map. - */ - bool Contains(const K& key) { - return Traits::Get(&impl_, key) != kPersistentContainerNotFound; - } - - /** - * Get value stored in map and set it in returnValue. - * Return true if a value was found. - */ - bool SetReturnValue(const K& key, - ReturnValue returnValue) { - return SetReturnValueFromVal(&returnValue, Traits::Get(&impl_, key)); - } - - /** - * Call Isolate::SetReference with the given parent and the map value. - */ - void SetReference(const K& key, - const Persistent& parent) { - GetIsolate()->SetReference( - reinterpret_cast(parent.val_), - reinterpret_cast(FromVal(Traits::Get(&impl_, key)))); - } - - /** - * Call V8::RegisterExternallyReferencedObject with the map value for given - * key. - */ - void RegisterExternallyReferencedObject(K& key) { - assert(Contains(key)); - V8::RegisterExternallyReferencedObject( - reinterpret_cast(FromVal(Traits::Get(&impl_, key))), - reinterpret_cast(GetIsolate())); - } - - /** - * Return value for key and remove it from the map. - */ - Global Remove(const K& key) { - return Release(Traits::Remove(&impl_, key)).Pass(); - } - - /** - * Traverses the map repeatedly, - * in case side effects of disposal cause insertions. - **/ - void Clear() { - typedef typename Traits::Iterator It; - HandleScope handle_scope(isolate_); - // TODO(dcarney): figure out if this swap and loop is necessary. - while (!Traits::Empty(&impl_)) { - typename Traits::Impl impl; - Traits::Swap(impl_, impl); - for (It i = Traits::Begin(&impl); i != Traits::End(&impl); ++i) { - Traits::Dispose(isolate_, Release(Traits::Value(i)).Pass(), - Traits::Key(i)); - } - } - } - - /** - * Helper class for GetReference/SetWithReference. Do not use outside - * that context. - */ - class PersistentValueReference { - public: - PersistentValueReference() : value_(kPersistentContainerNotFound) { } - PersistentValueReference(const PersistentValueReference& other) - : value_(other.value_) { } - - Local NewLocal(Isolate* isolate) const { - return Local::New(isolate, FromVal(value_)); - } - bool IsEmpty() const { - return value_ == kPersistentContainerNotFound; - } - template - bool SetReturnValue(ReturnValue returnValue) { - return SetReturnValueFromVal(&returnValue, value_); - } - void Reset() { - value_ = kPersistentContainerNotFound; - } - void operator=(const PersistentValueReference& other) { - value_ = other.value_; - } - - private: - friend class PersistentValueMapBase; - friend class PersistentValueMap; - friend class GlobalValueMap; - - explicit PersistentValueReference(PersistentContainerValue value) - : value_(value) { } - - void operator=(PersistentContainerValue value) { - value_ = value; - } - - PersistentContainerValue value_; - }; - - /** - * Get a reference to a map value. This enables fast, repeated access - * to a value stored in the map while the map remains unchanged. - * - * Careful: This is potentially unsafe, so please use with care. - * The value will become invalid if the value for this key changes - * in the underlying map, as a result of Set or Remove for the same - * key; as a result of the weak callback for the same key; or as a - * result of calling Clear() or destruction of the map. - */ - PersistentValueReference GetReference(const K& key) { - return PersistentValueReference(Traits::Get(&impl_, key)); - } - - protected: - explicit PersistentValueMapBase(Isolate* isolate) : isolate_(isolate) {} - - ~PersistentValueMapBase() { Clear(); } - - Isolate* isolate() { return isolate_; } - typename Traits::Impl* impl() { return &impl_; } - - static V* FromVal(PersistentContainerValue v) { - return reinterpret_cast(v); - } - - static PersistentContainerValue ClearAndLeak(Global* persistent) { - V* v = persistent->val_; - persistent->val_ = 0; - return reinterpret_cast(v); - } - - static PersistentContainerValue Leak(Global* persistent) { - return reinterpret_cast(persistent->val_); - } - - /** - * Return a container value as Global and make sure the weak - * callback is properly disposed of. All remove functionality should go - * through this. - */ - static Global Release(PersistentContainerValue v) { - Global p; - p.val_ = FromVal(v); - if (Traits::kCallbackType != kNotWeak && p.IsWeak()) { - Traits::DisposeCallbackData( - p.template ClearWeak()); - } - return p.Pass(); - } - - void RemoveWeak(const K& key) { - Global p; - p.val_ = FromVal(Traits::Remove(&impl_, key)); - p.Reset(); - } - - private: - PersistentValueMapBase(PersistentValueMapBase&); - void operator=(PersistentValueMapBase&); - - static bool SetReturnValueFromVal(ReturnValue* returnValue, - PersistentContainerValue value) { - bool hasValue = value != kPersistentContainerNotFound; - if (hasValue) { - returnValue->SetInternal( - *reinterpret_cast(FromVal(value))); - } - return hasValue; - } - - Isolate* isolate_; - typename Traits::Impl impl_; -}; - - -template -class PersistentValueMap : public PersistentValueMapBase { - public: - explicit PersistentValueMap(Isolate* isolate) - : PersistentValueMapBase(isolate) {} - - typedef - typename PersistentValueMapBase::PersistentValueReference - PersistentValueReference; - - /** - * Put value into map. Depending on Traits::kIsWeak, the value will be held - * by the map strongly or weakly. - * Returns old value as Global. - */ - Global Set(const K& key, Local value) { - Global persistent(this->isolate(), value); - return SetUnique(key, &persistent); - } - - /** - * Put value into map, like Set(const K&, Local). - */ - Global Set(const K& key, Global value) { - return SetUnique(key, &value); - } - - /** - * Put the value into the map, and set the 'weak' callback when demanded - * by the Traits class. - */ - Global SetUnique(const K& key, Global* persistent) { - if (Traits::kCallbackType != kNotWeak) { - Local value(Local::New(this->isolate(), *persistent)); - persistent->template SetWeak( - Traits::WeakCallbackParameter(this, key, value), WeakCallback); - } - PersistentContainerValue old_value = - Traits::Set(this->impl(), key, this->ClearAndLeak(persistent)); - return this->Release(old_value).Pass(); - } - - /** - * Put a value into the map and update the reference. - * Restrictions of GetReference apply here as well. - */ - Global Set(const K& key, Global value, - PersistentValueReference* reference) { - *reference = this->Leak(&value); - return SetUnique(key, &value); - } - - private: - static void WeakCallback( - const WeakCallbackInfo& data) { - if (Traits::kCallbackType != kNotWeak) { - PersistentValueMap* persistentValueMap = - Traits::MapFromWeakCallbackInfo(data); - K key = Traits::KeyFromWeakCallbackInfo(data); - Traits::Dispose(data.GetIsolate(), - persistentValueMap->Remove(key).Pass(), key); - Traits::DisposeCallbackData(data.GetParameter()); - } - } -}; - - -template -class GlobalValueMap : public PersistentValueMapBase { - public: - explicit GlobalValueMap(Isolate* isolate) - : PersistentValueMapBase(isolate) {} - - typedef - typename PersistentValueMapBase::PersistentValueReference - PersistentValueReference; - - /** - * Put value into map. Depending on Traits::kIsWeak, the value will be held - * by the map strongly or weakly. - * Returns old value as Global. - */ - Global Set(const K& key, Local value) { - Global persistent(this->isolate(), value); - return SetUnique(key, &persistent); - } - - /** - * Put value into map, like Set(const K&, Local). - */ - Global Set(const K& key, Global value) { - return SetUnique(key, &value); - } - - /** - * Put the value into the map, and set the 'weak' callback when demanded - * by the Traits class. - */ - Global SetUnique(const K& key, Global* persistent) { - if (Traits::kCallbackType != kNotWeak) { - WeakCallbackType callback_type = - Traits::kCallbackType == kWeakWithInternalFields - ? WeakCallbackType::kInternalFields - : WeakCallbackType::kParameter; - Local value(Local::New(this->isolate(), *persistent)); - persistent->template SetWeak( - Traits::WeakCallbackParameter(this, key, value), OnWeakCallback, - callback_type); - } - PersistentContainerValue old_value = - Traits::Set(this->impl(), key, this->ClearAndLeak(persistent)); - return this->Release(old_value).Pass(); - } - - /** - * Put a value into the map and update the reference. - * Restrictions of GetReference apply here as well. - */ - Global Set(const K& key, Global value, - PersistentValueReference* reference) { - *reference = this->Leak(&value); - return SetUnique(key, &value); - } - - private: - static void OnWeakCallback( - const WeakCallbackInfo& data) { - if (Traits::kCallbackType != kNotWeak) { - auto map = Traits::MapFromWeakCallbackInfo(data); - K key = Traits::KeyFromWeakCallbackInfo(data); - map->RemoveWeak(key); - Traits::OnWeakCallback(data); - data.SetSecondPassCallback(SecondWeakCallback); - } - } - - static void SecondWeakCallback( - const WeakCallbackInfo& data) { - Traits::DisposeWeak(data); - } -}; - - -/** - * A map that uses Global as value and std::map as the backing - * implementation. Persistents are held non-weak. - * - * C++11 embedders don't need this class, as they can use - * Global directly in std containers. - */ -template > -class StdPersistentValueMap : public PersistentValueMap { - public: - explicit StdPersistentValueMap(Isolate* isolate) - : PersistentValueMap(isolate) {} -}; - - -/** - * A map that uses Global as value and std::map as the backing - * implementation. Globals are held non-weak. - * - * C++11 embedders don't need this class, as they can use - * Global directly in std containers. - */ -template > -class StdGlobalValueMap : public GlobalValueMap { - public: - explicit StdGlobalValueMap(Isolate* isolate) - : GlobalValueMap(isolate) {} -}; - - -class DefaultPersistentValueVectorTraits { - public: - typedef std::vector Impl; - - static void Append(Impl* impl, PersistentContainerValue value) { - impl->push_back(value); - } - static bool IsEmpty(const Impl* impl) { - return impl->empty(); - } - static size_t Size(const Impl* impl) { - return impl->size(); - } - static PersistentContainerValue Get(const Impl* impl, size_t i) { - return (i < impl->size()) ? impl->at(i) : kPersistentContainerNotFound; - } - static void ReserveCapacity(Impl* impl, size_t capacity) { - impl->reserve(capacity); - } - static void Clear(Impl* impl) { - impl->clear(); - } -}; - - -/** - * A vector wrapper that safely stores Global values. - * C++11 embedders don't need this class, as they can use Global - * directly in std containers. - * - * This class relies on a backing vector implementation, whose type and methods - * are described by the Traits class. The backing map will handle values of type - * PersistentContainerValue, with all conversion into and out of V8 - * handles being transparently handled by this class. - */ -template -class PersistentValueVector { - public: - explicit PersistentValueVector(Isolate* isolate) : isolate_(isolate) { } - - ~PersistentValueVector() { - Clear(); - } - - /** - * Append a value to the vector. - */ - void Append(Local value) { - Global persistent(isolate_, value); - Traits::Append(&impl_, ClearAndLeak(&persistent)); - } - - /** - * Append a persistent's value to the vector. - */ - void Append(Global persistent) { - Traits::Append(&impl_, ClearAndLeak(&persistent)); - } - - /** - * Are there any values in the vector? - */ - bool IsEmpty() const { - return Traits::IsEmpty(&impl_); - } - - /** - * How many elements are in the vector? - */ - size_t Size() const { - return Traits::Size(&impl_); - } - - /** - * Retrieve the i-th value in the vector. - */ - Local Get(size_t index) const { - return Local::New(isolate_, FromVal(Traits::Get(&impl_, index))); - } - - /** - * Remove all elements from the vector. - */ - void Clear() { - size_t length = Traits::Size(&impl_); - for (size_t i = 0; i < length; i++) { - Global p; - p.val_ = FromVal(Traits::Get(&impl_, i)); - } - Traits::Clear(&impl_); - } - - /** - * Reserve capacity in the vector. - * (Efficiency gains depend on the backing implementation.) - */ - void ReserveCapacity(size_t capacity) { - Traits::ReserveCapacity(&impl_, capacity); - } - - private: - static PersistentContainerValue ClearAndLeak(Global* persistent) { - V* v = persistent->val_; - persistent->val_ = 0; - return reinterpret_cast(v); - } - - static V* FromVal(PersistentContainerValue v) { - return reinterpret_cast(v); - } - - Isolate* isolate_; - typename Traits::Impl impl_; -}; - -} // namespace v8 - -#endif // V8_UTIL_H diff --git a/ios/libnode/include/node/v8-value-serializer-version.h b/ios/libnode/include/node/v8-value-serializer-version.h deleted file mode 100644 index c72911c..0000000 --- a/ios/libnode/include/node/v8-value-serializer-version.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * Compile-time constants. - * - * This header provides access to information about the value serializer at - * compile time, without declaring or defining any symbols that require linking - * to V8. - */ - -#ifndef INCLUDE_V8_VALUE_SERIALIZER_VERSION_H_ -#define INCLUDE_V8_VALUE_SERIALIZER_VERSION_H_ - -#include - -namespace v8 { - -constexpr uint32_t CurrentValueSerializerFormatVersion() { return 13; } - -} // namespace v8 - -#endif // INCLUDE_V8_VALUE_SERIALIZER_VERSION_H_ diff --git a/ios/libnode/include/node/v8-version-string.h b/ios/libnode/include/node/v8-version-string.h deleted file mode 100644 index 075282d..0000000 --- a/ios/libnode/include/node/v8-version-string.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_VERSION_STRING_H_ -#define V8_VERSION_STRING_H_ - -#include "v8-version.h" // NOLINT(build/include) - -// This is here rather than v8-version.h to keep that file simple and -// machine-processable. - -#if V8_IS_CANDIDATE_VERSION -#define V8_CANDIDATE_STRING " (candidate)" -#else -#define V8_CANDIDATE_STRING "" -#endif - -#define V8_SX(x) #x -#define V8_S(x) V8_SX(x) - -#if V8_PATCH_LEVEL > 0 -#define V8_VERSION_STRING \ - V8_S(V8_MAJOR_VERSION) \ - "." V8_S(V8_MINOR_VERSION) "." V8_S(V8_BUILD_NUMBER) "." V8_S( \ - V8_PATCH_LEVEL) V8_CANDIDATE_STRING -#else -#define V8_VERSION_STRING \ - V8_S(V8_MAJOR_VERSION) \ - "." V8_S(V8_MINOR_VERSION) "." V8_S(V8_BUILD_NUMBER) V8_CANDIDATE_STRING -#endif - -#endif // V8_VERSION_STRING_H_ diff --git a/ios/libnode/include/node/v8-version.h b/ios/libnode/include/node/v8-version.h index 0889459..ac423bf 100644 --- a/ios/libnode/include/node/v8-version.h +++ b/ios/libnode/include/node/v8-version.h @@ -8,10 +8,10 @@ // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. -#define V8_MAJOR_VERSION 6 -#define V8_MINOR_VERSION 0 -#define V8_BUILD_NUMBER 286 -#define V8_PATCH_LEVEL 52 +#define V8_MAJOR_VERSION 5 +#define V8_MINOR_VERSION 8 +#define V8_BUILD_NUMBER 283 +#define V8_PATCH_LEVEL 39 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/ios/libnode/include/node/v8.h b/ios/libnode/include/node/v8.h index 1b3117e..782687c 100644 --- a/ios/libnode/include/node/v8.h +++ b/ios/libnode/include/node/v8.h @@ -1,383 +1,399 @@ // Copyright 2012 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** \mainpage V8 API Reference Guide - * - * V8 is Google's open source JavaScript engine. - * - * This set of documents provides reference material generated from the - * V8 header file, include/v8.h. - * - * For other documentation see http://code.google.com/apis/v8/ - */ - -#ifndef INCLUDE_V8_H_ -#define INCLUDE_V8_H_ - -#include -#include -#include +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef DEPS_CHAKRASHIM_INCLUDE_V8_H_ +#define DEPS_CHAKRASHIM_INCLUDE_V8_H_ + +// Stops windows.h from including winsock.h (conflicting with winsock2.h). +#ifndef _WINSOCKAPI_ +#define _WINSOCKAPI_ +#endif + +#if defined(_M_ARM) +#define CHAKRA_MIN_WIN32_WINNT _WIN32_WINNT_WIN10 +#define CHAKRA_MIN_WIN32_WINNT_STR "_WIN32_WINNT_WIN10" +#else +#define CHAKRA_MIN_WIN32_WINNT _WIN32_WINNT_WIN7 +#define CHAKRA_MIN_WIN32_WINNT_STR "_WIN32_WINNT_WIN7" +#endif + +#if defined(_WIN32_WINNT) && (_WIN32_WINNT < CHAKRA_MIN_WIN32_WINNT) +#pragma message("warning: chakrashim requires minimum " \ + CHAKRA_MIN_WIN32_WINNT_STR \ + ". Redefine _WIN32_WINNT to " \ + CHAKRA_MIN_WIN32_WINNT_STR ".") +#undef _WIN32_WINNT +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT CHAKRA_MIN_WIN32_WINNT +#endif + +#ifndef USE_EDGEMODE_JSRT +#define USE_EDGEMODE_JSRT // Only works with edge JSRT +#endif + +#if !defined(OSX_SDK_TR1) && defined(__APPLE__) +#include +#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < MAC_OS_X_VERSION_10_9 +#define OSX_SDK_TR1 +#endif +#endif + #include -#include -#include - -#include "v8-version.h" // NOLINT(build/include) -#include "v8config.h" // NOLINT(build/include) - -// We reserve the V8_* prefix for macros defined in V8 public API and -// assume there are no name conflicts with the embedder's code. - -#ifdef V8_OS_WIN - -// Setup for Windows DLL export/import. When building the V8 DLL the -// BUILDING_V8_SHARED needs to be defined. When building a program which uses -// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 -// static library or building a program which uses the V8 static library neither -// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. -#ifdef BUILDING_V8_SHARED -# define V8_EXPORT __declspec(dllexport) -#elif USING_V8_SHARED -# define V8_EXPORT __declspec(dllimport) +#include "ChakraCore.h" +#include "v8-version.h" +#include "v8config.h" + +#ifdef _WIN32 +#ifdef BUILDING_CHAKRASHIM +#define V8_EXPORT __declspec(dllexport) #else -# define V8_EXPORT -#endif // BUILDING_V8_SHARED - -#else // V8_OS_WIN - -// Setup for Linux shared library export. -#if V8_HAS_ATTRIBUTE_VISIBILITY -# ifdef BUILDING_V8_SHARED -# define V8_EXPORT __attribute__ ((visibility("default"))) -# else -# define V8_EXPORT -# endif +#define V8_EXPORT __declspec(dllimport) +#endif +#else // !_WIN32 +#ifdef BUILDING_CHAKRASHIM +#define V8_EXPORT __attribute__ ((visibility("default"))) #else -# define V8_EXPORT +#define V8_EXPORT +#endif #endif -#endif // V8_OS_WIN +#define TYPE_CHECK(T, S) \ + while (false) { \ + *(static_cast(0)) = static_cast(0); \ + } + +// Used to allow n-api constructs access to shim internals +// This is a temporary workaround and should go away once +// node-core has less of a dependency on the shim +namespace uvimpl { +class Work; +}; -/** - * The v8 JavaScript engine. - */ namespace v8 { class AccessorSignature; class Array; -class ArrayBuffer; +class Value; +class External; +class Primitive; class Boolean; class BooleanObject; class Context; class CpuProfiler; -class Data; -class Date; -class External; +class EscapableHandleScope; class Function; class FunctionTemplate; class HeapProfiler; -class ImplementationUtilities; class Int32; class Integer; class Isolate; -template -class Maybe; +class Module; class Name; class Number; class NumberObject; class Object; -class ObjectOperationDescriptor; class ObjectTemplate; class Platform; -class Primitive; +class ResourceConstraints; +class RegExp; class Promise; class PropertyDescriptor; class Proxy; -class RawOperationDescriptor; class Script; -class SharedArrayBuffer; class Signature; class StartupData; class StackFrame; class StackTrace; class String; class StringObject; -class Symbol; -class SymbolObject; -class Private; class Uint32; -class Utils; -class Value; -class WasmCompiledModule; template class Local; -template -class MaybeLocal; -template class Eternal; -template class NonCopyablePersistentTraits; -template class PersistentBase; -template > -class Persistent; -template -class Global; -template class PersistentValueMap; -template -class PersistentValueMapBase; -template -class GlobalValueMap; -template class PersistentValueVector; -template class WeakCallbackObject; -class FunctionTemplate; -class ObjectTemplate; -template class FunctionCallbackInfo; -template class PropertyCallbackInfo; -class StackTrace; -class StackFrame; -class Isolate; -class CallHandlerHelper; -class EscapableHandleScope; -template class ReturnValue; +template class Maybe; +template class MaybeLocal; +template class NonCopyablePersistentTraits; +template class PersistentBase; +template > class Persistent; +template class FunctionCallbackInfo; +template class PropertyCallbackInfo; + +class JitCodeEvent; +class RetainedObjectInfo; -namespace internal { -class Arguments; -class Heap; -class HeapObject; -class Isolate; -class Object; -struct StreamedSource; -template class CustomArguments; -class PropertyCallbackArguments; -class FunctionCallbackArguments; -class GlobalHandles; -} // namespace internal +enum PropertyAttribute { + None = 0, + ReadOnly = 1 << 0, + DontEnum = 1 << 1, + DontDelete = 1 << 2, +}; + +enum ExternalArrayType { + kExternalInt8Array = 1, + kExternalUint8Array, + kExternalInt16Array, + kExternalUint16Array, + kExternalInt32Array, + kExternalUint32Array, + kExternalFloat32Array, + kExternalFloat64Array, + kExternalUint8ClampedArray, + + // Legacy constant names + kExternalByteArray = kExternalInt8Array, + kExternalUnsignedByteArray = kExternalUint8Array, + kExternalShortArray = kExternalInt16Array, + kExternalUnsignedShortArray = kExternalUint16Array, + kExternalIntArray = kExternalInt32Array, + kExternalUnsignedIntArray = kExternalUint32Array, + kExternalFloatArray = kExternalFloat32Array, + kExternalDoubleArray = kExternalFloat64Array, + kExternalPixelArray = kExternalUint8ClampedArray +}; + +enum AccessControl { + DEFAULT = 0, + ALL_CAN_READ = 1, + ALL_CAN_WRITE = 1 << 1, + PROHIBITS_OVERWRITING = 1 << 2, +}; -namespace debug { -class ConsoleCallArguments; -} // namespace debug +enum JitCodeEventOptions { + kJitCodeEventDefault = 0, + kJitCodeEventEnumExisting = 1, +}; -// --- Handles --- +enum class IntegrityLevel { kFrozen, kSealed }; + +typedef void (*AccessorGetterCallback)( + Local property, + const PropertyCallbackInfo& info); +typedef void (*AccessorNameGetterCallback)( + Local property, + const PropertyCallbackInfo& info); + +typedef void (*AccessorSetterCallback)( + Local property, + Local value, + const PropertyCallbackInfo& info); +typedef void (*AccessorNameSetterCallback)( + Local property, + Local value, + const PropertyCallbackInfo& info); + +typedef void (*NamedPropertyGetterCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*NamedPropertySetterCallback)( + Local property, + Local value, + const PropertyCallbackInfo& info); +typedef void (*NamedPropertyQueryCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*NamedPropertyDeleterCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*NamedPropertyEnumeratorCallback)( + const PropertyCallbackInfo& info); + +typedef void (*GenericNamedPropertyGetterCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*GenericNamedPropertySetterCallback)( + Local property, Local value, + const PropertyCallbackInfo& info); +typedef void (*GenericNamedPropertyQueryCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*GenericNamedPropertyDeleterCallback)( + Local property, const PropertyCallbackInfo& info); +typedef void (*GenericNamedPropertyEnumeratorCallback)( + const PropertyCallbackInfo& info); + +typedef void (*IndexedPropertyGetterCallback)( + uint32_t index, const PropertyCallbackInfo& info); +typedef void (*IndexedPropertySetterCallback)( + uint32_t index, Local value, const PropertyCallbackInfo& info); +typedef void (*IndexedPropertyQueryCallback)( + uint32_t index, const PropertyCallbackInfo& info); +typedef void (*IndexedPropertyDeleterCallback)( + uint32_t index, const PropertyCallbackInfo& info); +typedef void (*IndexedPropertyEnumeratorCallback)( + const PropertyCallbackInfo& info); + +typedef bool (*EntropySource)(unsigned char* buffer, size_t length); +typedef void (*FatalErrorCallback)(const char *location, const char *message); +typedef void (*JitCodeEventHandler)(const JitCodeEvent *event); -#define TYPE_CHECK(T, S) \ - while (false) { \ - *(static_cast(0)) = static_cast(0); \ - } -/** - * An object reference managed by the v8 garbage collector. - * - * All objects returned from v8 have to be tracked by the garbage - * collector so that it knows that the objects are still alive. Also, - * because the garbage collector may move objects, it is unsafe to - * point directly to an object. Instead, all objects are stored in - * handles which are known by the garbage collector and updated - * whenever an object moves. Handles should always be passed by value - * (except in cases like out-parameters) and they should never be - * allocated on the heap. - * - * There are two types of handles: local and persistent handles. - * - * Local handles are light-weight and transient and typically used in - * local operations. They are managed by HandleScopes. That means that a - * HandleScope must exist on the stack when they are created and that they are - * only valid inside of the HandleScope active during their creation. - * For passing a local handle to an outer HandleScope, an EscapableHandleScope - * and its Escape() method must be used. - * - * Persistent handles can be used when storing objects across several - * independent operations and have to be explicitly deallocated when they're no - * longer used. - * - * It is safe to extract the object stored in the handle by - * dereferencing the handle (for instance, to extract the Object* from - * a Local); the value will still be governed by a handle - * behind the scenes and the same rules apply to these values as to - * their handles. - */ template class Local { public: V8_INLINE Local() : val_(0) {} + template V8_INLINE Local(Local that) : val_(reinterpret_cast(*that)) { - /** - * This check fails when trying to convert between incompatible - * handles. For example, converting from a Local to a - * Local. - */ TYPE_CHECK(T, S); } - /** - * Returns true if the handle is empty. - */ V8_INLINE bool IsEmpty() const { return val_ == 0; } - - /** - * Sets the handle to be empty. IsEmpty() will then return true. - */ V8_INLINE void Clear() { val_ = 0; } - V8_INLINE T* operator->() const { return val_; } - V8_INLINE T* operator*() const { return val_; } - /** - * Checks whether two handles are the same. - * Returns true if both are empty, or if the objects - * to which they refer are identical. - * The handles' references are not checked. - */ template V8_INLINE bool operator==(const Local& that) const { - internal::Object** a = reinterpret_cast(this->val_); - internal::Object** b = reinterpret_cast(that.val_); - if (a == 0) return b == 0; - if (b == 0) return false; - return *a == *b; + return val_ == that.val_; } - template V8_INLINE bool operator==( - const PersistentBase& that) const { - internal::Object** a = reinterpret_cast(this->val_); - internal::Object** b = reinterpret_cast(that.val_); - if (a == 0) return b == 0; - if (b == 0) return false; - return *a == *b; + template + V8_INLINE bool operator==(const PersistentBase& that) const { + return val_ == that.val_; } - /** - * Checks whether two handles are different. - * Returns true if only one of the handles is empty, or if - * the objects to which they refer are different. - * The handles' references are not checked. - */ template V8_INLINE bool operator!=(const Local& that) const { return !operator==(that); } - template V8_INLINE bool operator!=( - const Persistent& that) const { + template + V8_INLINE bool operator!=(const PersistentBase& that) const { return !operator==(that); } - /** - * Cast a handle to a subclass, e.g. Local to Local. - * This is only valid if the handle actually refers to a value of the - * target type. - */ - template V8_INLINE static Local Cast(Local that) { -#ifdef V8_ENABLE_CHECKS - // If we're going to perform the type check then we have to check - // that the handle isn't empty before doing the checked cast. - if (that.IsEmpty()) return Local(); -#endif + template + V8_INLINE static Local Cast(Local that) { return Local(T::Cast(*that)); } - /** - * Calling this is equivalent to Local::Cast(). - * In particular, this is only valid if the handle actually refers to a value - * of the target type. - */ template - V8_INLINE Local As() const { + V8_INLINE Local As() { return Local::Cast(*this); } - /** - * Create a local handle for the content of another handle. - * The referee is kept alive by the local handle even when - * the original handle is destroyed/disposed. - */ V8_INLINE static Local New(Isolate* isolate, Local that); V8_INLINE static Local New(Isolate* isolate, const PersistentBase& that); private: - friend class Utils; - template friend class Eternal; - template friend class PersistentBase; - template friend class Persistent; - template friend class Local; - template - friend class MaybeLocal; - template friend class FunctionCallbackInfo; - template friend class PropertyCallbackInfo; - friend class String; - friend class Object; + friend struct AcessorExternalDataType; + friend class AccessorSignature; + friend class Array; + friend class ArrayBuffer; + friend class ArrayBufferView; + friend class Boolean; + friend class BooleanObject; friend class Context; - friend class Private; - template friend class internal::CustomArguments; - friend Local Undefined(Isolate* isolate); - friend Local Null(Isolate* isolate); - friend Local True(Isolate* isolate); - friend Local False(Isolate* isolate); + friend class Date; + friend class Debug; + friend class External; + friend class Function; + friend class FunctionCallbackData; + friend class FunctionTemplate; + friend class FunctionTemplateData; friend class HandleScope; - friend class EscapableHandleScope; - template - friend class PersistentValueMapBase; - template friend class PersistentValueVector; - template - friend class ReturnValue; - - explicit V8_INLINE Local(T* that) : val_(that) {} - V8_INLINE static Local New(Isolate* isolate, T* that); + friend class Integer; + friend class Map; + friend class Message; + friend class Number; + friend class NumberObject; + friend class Object; + friend class ObjectTemplate; + friend class Private; + friend class PropertyDescriptor; + friend class Proxy; + friend class RegExp; + friend class Signature; + friend class Script; + friend class StackFrame; + friend class StackTrace; + friend class String; + friend class StringObject; + friend class Symbol; + friend class SymbolObject; + friend class Utils; + friend class TryCatch; + friend class UnboundScript; + friend class Value; + friend class JSON; + friend class uvimpl::Work; + template friend class FunctionCallbackInfo; + template friend class MaybeLocal; + template friend class PersistentBase; + template friend class Persistent; + template friend class Local; + friend V8_EXPORT Local Undefined(Isolate* isolate); + friend V8_EXPORT Local Null(Isolate* isolate); + friend V8_EXPORT Local True(Isolate* isolate); + friend V8_EXPORT Local False(Isolate* isolate); + + explicit V8_INLINE Local(T* that) + : val_(that) {} + V8_INLINE static Local New(Isolate* isolate, T* that) { + return New(that); + } + + V8_INLINE Local(JsValueRef that) + : val_(static_cast(that)) {} + V8_INLINE Local(const PersistentBase& that) + : val_(that.val_) { + } + V8_INLINE static Local New(T* that); + V8_INLINE static Local New(JsValueRef ref) { + return New(static_cast(ref)); + } + T* val_; }; -#if !defined(V8_IMMINENT_DEPRECATION_WARNINGS) // Handle is an alias for Local for historical reasons. template using Handle = Local; -#endif -/** - * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether - * the Local<> is empty before it can be used. - * - * If an API method returns a MaybeLocal<>, the API method can potentially fail - * either because an exception is thrown, or because an exception is pending, - * e.g. because a previous API call threw an exception that hasn't been caught - * yet, or because a TerminateExecution exception was thrown. In that case, an - * empty MaybeLocal is returned. - */ template class MaybeLocal { public: - V8_INLINE MaybeLocal() : val_(nullptr) {} + MaybeLocal() : val_(nullptr) {} template - V8_INLINE MaybeLocal(Local that) - : val_(reinterpret_cast(*that)) { + MaybeLocal(Local that) // NOLINT(runtime/explicit) + : val_(reinterpret_cast(*that)) { TYPE_CHECK(T, S); } - V8_INLINE bool IsEmpty() const { return val_ == nullptr; } + bool IsEmpty() const { return val_ == nullptr; } - /** - * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty, - * |false| is returned and |out| is left untouched. - */ template - V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local* out) const { + bool ToLocal(Local* out) const { out->val_ = IsEmpty() ? nullptr : this->val_; return !IsEmpty(); } - /** - * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty, - * V8 will crash the process. - */ V8_INLINE Local ToLocalChecked(); - /** - * Converts this MaybeLocal<> to a Local<>, using a default value if this - * MaybeLocal<> is empty. - */ template - V8_INLINE Local FromMaybe(Local default_value) const { + Local FromMaybe(Local default_value) const { return IsEmpty() ? default_value : Local(val_); } @@ -385,29 +401,9 @@ class MaybeLocal { T* val_; }; -/** - * Eternal handles are set-once handles that live for the lifetime of the - * isolate. - */ -template class Eternal { - public: - V8_INLINE Eternal() : val_(nullptr) {} - template - V8_INLINE Eternal(Isolate* isolate, Local handle) : val_(nullptr) { - Set(isolate, handle); - } - // Can only be safely called if already set. - V8_INLINE Local Get(Isolate* isolate) const; - V8_INLINE bool IsEmpty() const { return val_ == nullptr; } - template V8_INLINE void Set(Isolate* isolate, Local handle); - - private: - T* val_; -}; - static const int kInternalFieldsInWeakCallback = 2; -static const int kEmbedderFieldsInWeakCallback = 2; + template class WeakCallbackInfo { @@ -415,91 +411,101 @@ class WeakCallbackInfo { typedef void (*Callback)(const WeakCallbackInfo& data); WeakCallbackInfo(Isolate* isolate, T* parameter, - void* embedder_fields[kEmbedderFieldsInWeakCallback], + void* internal_fields[kInternalFieldsInWeakCallback], Callback* callback) : isolate_(isolate), parameter_(parameter), callback_(callback) { - for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) { - embedder_fields_[i] = embedder_fields[i]; + for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) { + internal_fields_[i] = internal_fields[i]; } } V8_INLINE Isolate* GetIsolate() const { return isolate_; } V8_INLINE T* GetParameter() const { return parameter_; } - V8_INLINE void* GetInternalField(int index) const; - - V8_INLINE V8_DEPRECATED("use indexed version", - void* GetInternalField1() const) { - return embedder_fields_[0]; - } - V8_INLINE V8_DEPRECATED("use indexed version", - void* GetInternalField2() const) { - return embedder_fields_[1]; + V8_INLINE void* GetInternalField(int index) const { + return internal_fields_[index]; } - V8_DEPRECATED("Not realiable once SetSecondPassCallback() was used.", - bool IsFirstPass() const) { - return callback_ != nullptr; + V8_INLINE V8_DEPRECATE_SOON("use indexed version", + void* GetInternalField1()) const { + return internal_fields_[0]; + } + V8_INLINE V8_DEPRECATE_SOON("use indexed version", + void* GetInternalField2()) const { + return internal_fields_[1]; } - // When first called, the embedder MUST Reset() the Global which triggered the - // callback. The Global itself is unusable for anything else. No v8 other api - // calls may be called in the first callback. Should additional work be - // required, the embedder must set a second pass callback, which will be - // called after all the initial callbacks are processed. - // Calling SetSecondPassCallback on the second pass will immediately crash. + bool IsFirstPass() const { return callback_ != nullptr; } void SetSecondPassCallback(Callback callback) const { *callback_ = callback; } private: Isolate* isolate_; T* parameter_; Callback* callback_; - void* embedder_fields_[kEmbedderFieldsInWeakCallback]; + void* internal_fields_[kInternalFieldsInWeakCallback]; }; -// kParameter will pass a void* parameter back to the callback, kInternalFields -// will pass the first two internal fields back to the callback, kFinalizer -// will pass a void* parameter back, but is invoked before the object is -// actually collected, so it can be resurrected. In the last case, it is not -// possible to request a second pass callback. -enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer }; +template +class WeakCallbackData { + public: + typedef void (*Callback)(const WeakCallbackData& data); + + WeakCallbackData(Isolate* isolate, P* parameter, Local handle) + : isolate_(isolate), parameter_(parameter), handle_(handle) {} -/** - * An object reference that is independent of any handle scope. Where - * a Local handle only lives as long as the HandleScope in which it was - * allocated, a PersistentBase handle remains valid until it is explicitly - * disposed using Reset(). - * - * A persistent handle contains a reference to a storage cell within - * the V8 engine which holds an object value and which is updated by - * the garbage collector whenever the object is moved. A new storage - * cell can be created using the constructor or PersistentBase::Reset and - * existing handles can be disposed using PersistentBase::Reset. - * - */ -template class PersistentBase { + V8_INLINE Isolate* GetIsolate() const { return isolate_; } + V8_INLINE P* GetParameter() const { return parameter_; } + V8_INLINE Local GetValue() const { return handle_; } + + private: + Isolate* isolate_; + P* parameter_; + Local handle_; +}; + + +namespace chakrashim { +struct WeakReferenceCallbackWrapper { + void *parameters; + union { + WeakCallbackInfo::Callback infoCallback; + WeakCallbackData::Callback dataCallback; + }; + bool isWeakCallbackInfo; +}; + +// A helper method for setting an object with a WeakReferenceCallback. The +// callback will be called before the object is released. +V8_EXPORT void SetObjectWeakReferenceCallback( + JsValueRef object, + WeakCallbackInfo::Callback callback, + void* parameters, + WeakReferenceCallbackWrapper** weakWrapper); +V8_EXPORT void SetObjectWeakReferenceCallback( + JsValueRef object, + WeakCallbackData::Callback callback, + void* parameters, + WeakReferenceCallbackWrapper** weakWrapper); +// A helper method for turning off the WeakReferenceCallback that was set using +// the previous method +V8_EXPORT void ClearObjectWeakReferenceCallback(JsValueRef object, bool revive); +} // namespace chakrashim + +enum class WeakCallbackType { kParameter, kInternalFields }; + +template +class PersistentBase { public: - /** - * If non-empty, destroy the underlying storage cell - * IsEmpty() will return true after this call. - */ V8_INLINE void Reset(); - /** - * If non-empty, destroy the underlying storage cell - * and create a new one with the contents of other if other is non empty - */ + template - V8_INLINE void Reset(Isolate* isolate, const Local& other); + V8_INLINE void Reset(Isolate* isolate, const Handle& other); - /** - * If non-empty, destroy the underlying storage cell - * and create a new one with the contents of other if other is non empty - */ template V8_INLINE void Reset(Isolate* isolate, const PersistentBase& other); V8_INLINE bool IsEmpty() const { return val_ == NULL; } - V8_INLINE void Empty() { val_ = 0; } + V8_INLINE void Empty() { Reset(); } V8_INLINE Local Get(Isolate* isolate) const { return Local::New(isolate, *this); @@ -507,20 +513,12 @@ template class PersistentBase { template V8_INLINE bool operator==(const PersistentBase& that) const { - internal::Object** a = reinterpret_cast(this->val_); - internal::Object** b = reinterpret_cast(that.val_); - if (a == NULL) return b == NULL; - if (b == NULL) return false; - return *a == *b; + return val_ == that.val_; } template - V8_INLINE bool operator==(const Local& that) const { - internal::Object** a = reinterpret_cast(this->val_); - internal::Object** b = reinterpret_cast(that.val_); - if (a == NULL) return b == NULL; - if (b == NULL) return false; - return *a == *b; + V8_INLINE bool operator==(const Handle& that) const { + return val_ == that.val_; } template @@ -529,130 +527,68 @@ template class PersistentBase { } template - V8_INLINE bool operator!=(const Local& that) const { + V8_INLINE bool operator!=(const Handle& that) const { return !operator==(that); } - /** - * Install a finalization callback on this object. - * NOTE: There is no guarantee as to *when* or even *if* the callback is - * invoked. The invocation is performed solely on a best effort basis. - * As always, GC-based finalization should *not* be relied upon for any - * critical form of resource management! - */ + template + V8_INLINE V8_DEPRECATE_SOON( + "use WeakCallbackInfo version", + void SetWeak(P* parameter, + typename WeakCallbackData::Callback callback)); + template V8_INLINE void SetWeak(P* parameter, typename WeakCallbackInfo

::Callback callback, WeakCallbackType type); - /** - * Turns this handle into a weak phantom handle without finalization callback. - * The handle will be reset automatically when the garbage collector detects - * that the object is no longer reachable. - * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall - * returns how many phantom handles were reset by the garbage collector. - */ - V8_INLINE void SetWeak(); - template V8_INLINE P* ClearWeak(); - // TODO(dcarney): remove this. V8_INLINE void ClearWeak() { ClearWeak(); } - - /** - * Allows the embedder to tell the v8 garbage collector that a certain object - * is alive. Only allowed when the embedder is asked to trace its heap by - * EmbedderHeapTracer. - */ - V8_INLINE void RegisterExternalReference(Isolate* isolate) const; - - /** - * Marks the reference to this object independent. Garbage collector is free - * to ignore any object groups containing this object. Weak callback for an - * independent handle should not assume that it will be preceded by a global - * GC prologue callback or followed by a global GC epilogue callback. - */ V8_INLINE void MarkIndependent(); - - /** - * Marks the reference to this object as active. The scavenge garbage - * collection should not reclaim the objects marked as active. - * This bit is cleared after the each garbage collection pass. - */ - V8_INLINE void MarkActive(); - + V8_INLINE void MarkPartiallyDependent(); V8_INLINE bool IsIndependent() const; - - /** Checks if the handle holds the only reference to an object. */ V8_INLINE bool IsNearDeath() const; - - /** Returns true if the handle's reference is weak. */ V8_INLINE bool IsWeak() const; - - /** - * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface - * description in v8-profiler.h for details. - */ V8_INLINE void SetWrapperClassId(uint16_t class_id); - /** - * Returns the class ID previously assigned to this handle or 0 if no class ID - * was previously assigned. - */ - V8_INLINE uint16_t WrapperClassId() const; - - PersistentBase(const PersistentBase& other) = delete; // NOLINT - void operator=(const PersistentBase&) = delete; - private: - friend class Isolate; - friend class Utils; template friend class Local; + template friend class Global; template friend class Persistent; - template - friend class Global; - template friend class PersistentBase; - template friend class ReturnValue; - template - friend class PersistentValueMapBase; - template friend class PersistentValueVector; - friend class Object; + template friend class Global; - explicit V8_INLINE PersistentBase(T* val) : val_(val) {} + explicit V8_INLINE PersistentBase(T* val) + : val_(val), _weakWrapper(nullptr) {} + PersistentBase(PersistentBase& other) = delete; // NOLINT + void operator=(PersistentBase&) = delete; V8_INLINE static T* New(Isolate* isolate, T* that); + template + void SetWeakCommon(P* parameter, Callback callback); + T* val_; + chakrashim::WeakReferenceCallbackWrapper* _weakWrapper; }; -/** - * Default traits for Persistent. This class does not allow - * use of the copy constructor or assignment operator. - * At present kResetInDestructor is not set, but that will change in a future - * version. - */ template class NonCopyablePersistentTraits { public: typedef Persistent > NonCopyablePersistent; - static const bool kResetInDestructor = false; + static const bool kResetInDestructor = true; // chakra: changed to true! template V8_INLINE static void Copy(const Persistent& source, NonCopyablePersistent* dest) { Uncompilable(); } - // TODO(dcarney): come up with a good compile error here. template V8_INLINE static void Uncompilable() { TYPE_CHECK(O, Primitive); } }; -/** - * Helper class traits to allow copying and assignment of Persistent. - * This will clone the contents of storage cell, but not any of the flags, etc. - */ template struct CopyablePersistentTraits { typedef Persistent > CopyablePersistent; @@ -665,674 +601,321 @@ struct CopyablePersistentTraits { }; -/** - * A PersistentBase which allows copy and assignment. - * - * Copy, assignment and destructor behavior is controlled by the traits - * class M. - * - * Note: Persistent class hierarchy is subject to future changes. - */ -template class Persistent : public PersistentBase { +template +class Persistent : public PersistentBase { public: - /** - * A Persistent with no storage cell. - */ V8_INLINE Persistent() : PersistentBase(0) { } - /** - * Construct a Persistent from a Local. - * When the Local is non-empty, a new storage cell is created - * pointing to the same object, and no flags are set. - */ + template - V8_INLINE Persistent(Isolate* isolate, Local that) + V8_INLINE Persistent(Isolate* isolate, Handle that) : PersistentBase(PersistentBase::New(isolate, *that)) { TYPE_CHECK(T, S); } - /** - * Construct a Persistent from a Persistent. - * When the Persistent is non-empty, a new storage cell is created - * pointing to the same object, and no flags are set. - */ + template V8_INLINE Persistent(Isolate* isolate, const Persistent& that) : PersistentBase(PersistentBase::New(isolate, *that)) { TYPE_CHECK(T, S); } - /** - * The copy constructors and assignment operator create a Persistent - * exactly as the Persistent constructor, but the Copy function from the - * traits class is called, allowing the setting of flags based on the - * copied Persistent. - */ + V8_INLINE Persistent(const Persistent& that) : PersistentBase(0) { Copy(that); } + template V8_INLINE Persistent(const Persistent& that) : PersistentBase(0) { Copy(that); } + V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT Copy(that); return *this; } + template V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT Copy(that); return *this; } - /** - * The destructor will dispose the Persistent based on the - * kResetInDestructor flags in the traits class. Since not calling dispose - * can result in a memory leak, it is recommended to always set this flag. - */ + V8_INLINE ~Persistent() { if (M::kResetInDestructor) this->Reset(); } - // TODO(dcarney): this is pretty useless, fix or remove template - V8_INLINE static Persistent& Cast(const Persistent& that) { // NOLINT -#ifdef V8_ENABLE_CHECKS - // If we're going to perform the type check then we have to check - // that the handle isn't empty before doing the checked cast. - if (!that.IsEmpty()) T::Cast(*that); -#endif - return reinterpret_cast&>(const_cast&>(that)); + V8_INLINE static Persistent& Cast(Persistent& that) { // NOLINT + return reinterpret_cast&>(that); } - // TODO(dcarney): this is pretty useless, fix or remove template - V8_INLINE Persistent& As() const { // NOLINT + V8_INLINE Persistent& As() { // NOLINT return Persistent::Cast(*this); } private: - friend class Isolate; + friend class Object; + friend class ObjectTemplate; + friend class ObjectTemplateData; + friend class TemplateData; + friend class FunctionCallbackData; + friend class FunctionTemplate; + friend class FunctionTemplateData; friend class Utils; - template friend class Local; - template friend class Persistent; - template friend class ReturnValue; + template friend class Local; + template friend class ReturnValue; + + V8_INLINE Persistent(T* that) + : PersistentBase(PersistentBase::New(nullptr, that)) { } - explicit V8_INLINE Persistent(T* that) : PersistentBase(that) {} V8_INLINE T* operator*() const { return this->val_; } + V8_INLINE T* operator->() const { return this->val_; } + template V8_INLINE void Copy(const Persistent& that); + + template + V8_INLINE Persistent& operator=(const Local& other) { + this->Reset(nullptr, other); + return *this; + } + V8_INLINE Persistent& operator=(JsRef other) { + return operator=(Local(static_cast(other))); + } }; -/** - * A PersistentBase which has move semantics. - * - * Note: Persistent class hierarchy is subject to future changes. - */ template class Global : public PersistentBase { public: - /** - * A Global with no storage cell. - */ V8_INLINE Global() : PersistentBase(nullptr) {} - /** - * Construct a Global from a Local. - * When the Local is non-empty, a new storage cell is created - * pointing to the same object, and no flags are set. - */ + template - V8_INLINE Global(Isolate* isolate, Local that) - : PersistentBase(PersistentBase::New(isolate, *that)) { + V8_INLINE Global(Isolate* isolate, Handle that) + : PersistentBase(PersistentBase::New(isolate, *that)) { TYPE_CHECK(T, S); } - /** - * Construct a Global from a PersistentBase. - * When the Persistent is non-empty, a new storage cell is created - * pointing to the same object, and no flags are set. - */ + template V8_INLINE Global(Isolate* isolate, const PersistentBase& that) - : PersistentBase(PersistentBase::New(isolate, that.val_)) { + : PersistentBase(PersistentBase::New(isolate, that.val_)) { TYPE_CHECK(T, S); } - /** - * Move constructor. - */ - V8_INLINE Global(Global&& other) : PersistentBase(other.val_) { // NOLINT + + V8_INLINE Global(Global&& other) : PersistentBase(other.val_) { + this->_weakWrapper = other._weakWrapper; other.val_ = nullptr; + other._weakWrapper = nullptr; } + V8_INLINE ~Global() { this->Reset(); } - /** - * Move via assignment. - */ + template - V8_INLINE Global& operator=(Global&& rhs) { // NOLINT + V8_INLINE Global& operator=(Global&& rhs) { TYPE_CHECK(T, S); if (this != &rhs) { this->Reset(); this->val_ = rhs.val_; + this->_weakWrapper = rhs._weakWrapper; rhs.val_ = nullptr; + rhs._weakWrapper = nullptr; } return *this; } - /** - * Pass allows returning uniques from functions, etc. - */ - Global Pass() { return static_cast(*this); } // NOLINT - /* - * For compatibility with Chromium's base::Bind (base::Passed). - */ - typedef void MoveOnlyTypeForCPP03; + Global Pass() { return static_cast(*this); } + private: Global(const Global&) = delete; void operator=(const Global&) = delete; - - private: - template - friend class ReturnValue; - V8_INLINE T* operator*() const { return this->val_; } }; -// UniquePersistent is an alias for Global for historical reason. template -using UniquePersistent = Global; - - - /** - * A stack-allocated class that governs a number of local handles. - * After a handle scope has been created, all local handles will be - * allocated within that handle scope until either the handle scope is - * deleted or another handle scope is created. If there is already a - * handle scope and a new one is created, all allocations will take - * place in the new handle scope until it is deleted. After that, - * new handles will again be allocated in the original handle scope. - * - * After the handle scope of a local handle has been deleted the - * garbage collector will no longer track the object stored in the - * handle and may deallocate it. The behavior of accessing a handle - * for which the handle scope has been deleted is undefined. - */ -class V8_EXPORT HandleScope { +class Eternal : private Persistent { public: - explicit HandleScope(Isolate* isolate); - - ~HandleScope(); + Eternal() {} - /** - * Counts the number of allocated handles. - */ - static int NumberOfHandles(Isolate* isolate); + template + Eternal(Isolate* isolate, Local handle) { + Set(isolate, handle); + } - V8_INLINE Isolate* GetIsolate() const { - return reinterpret_cast(isolate_); + Local Get(Isolate* isolate) { + return Local::New(isolate, *this); } - HandleScope(const HandleScope&) = delete; - void operator=(const HandleScope&) = delete; - void* operator new(size_t size); - void operator delete(void*, size_t); + bool IsEmpty() const { + return Persistent::IsEmpty(); + } - protected: - V8_INLINE HandleScope() {} + template void Set(Isolate* isolate, Local handle) { + this->Reset(isolate, handle); + } +}; - void Initialize(Isolate* isolate); +// CHAKRA: Chakra's GC behavior does not exactly match up with V8's GC behavior. +// V8 uses a HandleScope to keep Local references alive, which means that as +// long as the HandleScope is on the stack, the Local references will not be +// collected. Chakra, on the other hand, directly walks the stack and has no +// HandleScope mechanism. It requires hosts to keep "local" references on the +// stack or else turn them into "persistent" references through +// JsAddRef/JsRelease. To paper over this difference, the bridge HandleScope +// will create a JS array and will hold that reference on the stack. Any local +// values created will then be added to that array. So the GC will see the array +// on the stack and then keep those local references alive. +class V8_EXPORT HandleScope { + public: + HandleScope(Isolate* isolate); + ~HandleScope(); - static internal::Object** CreateHandle(internal::Isolate* isolate, - internal::Object* value); + static int NumberOfHandles(Isolate* isolate); private: - // Uses heap_object to obtain the current Isolate. - static internal::Object** CreateHandle(internal::HeapObject* heap_object, - internal::Object* value); - - internal::Isolate* isolate_; - internal::Object** prev_next_; - internal::Object** prev_limit_; + friend class EscapableHandleScope; + template friend class Local; + static const int kOnStackLocals = 8; // Arbitrary number of refs on stack - // Local::New uses CreateHandle with an Isolate* parameter. - template friend class Local; + HandleScope *_prev; - // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with - // a HeapObject* in their shortcuts. - friend class Object; - friend class Context; -}; + // Save some refs on stack. 1st element on stack + // is the JavascriptArray where other refs go. + JsValueRef _locals[kOnStackLocals + 1]; + int _count; + JsContextRef _contextRef; + struct AddRefRecord { + JsRef _ref; + AddRefRecord * _next; + } *_addRefRecordHead; + bool AddLocal(JsValueRef value); + bool AddLocalContext(JsContextRef value); + bool AddLocalAddRef(JsRef value); -/** - * A HandleScope which first allocates a handle in the current scope - * which will be later filled with the escape value. - */ -class V8_EXPORT EscapableHandleScope : public HandleScope { - public: - explicit EscapableHandleScope(Isolate* isolate); - V8_INLINE ~EscapableHandleScope() {} + static HandleScope *GetCurrent(); - /** - * Pushes the value into the previous scope and returns a handle to it. - * Cannot be called twice. - */ template - V8_INLINE Local Escape(Local value) { - internal::Object** slot = - Escape(reinterpret_cast(*value)); - return Local(reinterpret_cast(slot)); - } - - EscapableHandleScope(const EscapableHandleScope&) = delete; - void operator=(const EscapableHandleScope&) = delete; - void* operator new(size_t size); - void operator delete(void*, size_t); - - private: - internal::Object** Escape(internal::Object** escape_value); - internal::Object** escape_slot_; + Local Close(Handle value); }; -/** - * A SealHandleScope acts like a handle scope in which no handle allocations - * are allowed. It can be useful for debugging handle leaks. - * Handles can be allocated within inner normal HandleScopes. - */ -class V8_EXPORT SealHandleScope { +class V8_EXPORT EscapableHandleScope : public HandleScope { public: - SealHandleScope(Isolate* isolate); - ~SealHandleScope(); + EscapableHandleScope(Isolate* isolate) : HandleScope(isolate) {} - SealHandleScope(const SealHandleScope&) = delete; - void operator=(const SealHandleScope&) = delete; - void* operator new(size_t size); - void operator delete(void*, size_t); - - private: - internal::Isolate* const isolate_; - internal::Object** prev_limit_; - int prev_sealed_level_; + template + Local Escape(Handle value) { return Close(value); } }; +typedef HandleScope SealHandleScope; -// --- Special objects --- - - -/** - * The superclass of values and API object templates. - */ class V8_EXPORT Data { - private: - Data(); -}; - - -/** - * The optional attributes of ScriptOrigin. - */ -class ScriptOriginOptions { public: - V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false, - bool is_opaque = false, bool is_wasm = false, - bool is_module = false) - : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) | - (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) | - (is_module ? kIsModule : 0)) {} - V8_INLINE ScriptOriginOptions(int flags) - : flags_(flags & - (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {} - - bool IsSharedCrossOrigin() const { - return (flags_ & kIsSharedCrossOrigin) != 0; - } - bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; } - bool IsWasm() const { return (flags_ & kIsWasm) != 0; } - bool IsModule() const { return (flags_ & kIsModule) != 0; } - - int Flags() const { return flags_; } - - private: - enum { - kIsSharedCrossOrigin = 1, - kIsOpaque = 1 << 1, - kIsWasm = 1 << 2, - kIsModule = 1 << 3 - }; - const int flags_; }; -/** - * The origin, within a file, of a script. - */ class ScriptOrigin { public: - V8_INLINE ScriptOrigin( - Local resource_name, - Local resource_line_offset = Local(), - Local resource_column_offset = Local(), - Local resource_is_shared_cross_origin = Local(), - Local script_id = Local(), - Local source_map_url = Local(), - Local resource_is_opaque = Local(), - Local is_wasm = Local(), - Local is_module = Local()); - - V8_INLINE Local ResourceName() const; - V8_INLINE Local ResourceLineOffset() const; - V8_INLINE Local ResourceColumnOffset() const; - /** - * Returns true for embedder's debugger scripts - */ - V8_INLINE Local ScriptID() const; - V8_INLINE Local SourceMapUrl() const; - V8_INLINE ScriptOriginOptions Options() const { return options_; } + explicit ScriptOrigin( + Local resource_name, + Local resource_line_offset = Local(), + Local resource_column_offset = Local(), + Local resource_is_shared_cross_origin = Local(), + Local script_id = Local(), + Local source_map_url = Local(), + Local resource_is_opaque = Local(), + Local is_wasm = Local(), + Local is_module = Local()) + : resource_name_(resource_name), + resource_line_offset_(resource_line_offset), + resource_column_offset_(resource_column_offset), + script_id_(script_id) {} + Local ResourceName() const { + return resource_name_; + } + Local ResourceLineOffset() const { + return resource_line_offset_; + } + Local ResourceColumnOffset() const { + return resource_column_offset_; + } + V8_INLINE Local ScriptID() const { + return script_id_; + } private: Local resource_name_; Local resource_line_offset_; Local resource_column_offset_; - ScriptOriginOptions options_; Local script_id_; - Local source_map_url_; }; - -/** - * A compiled JavaScript script, not yet tied to a Context. - */ class V8_EXPORT UnboundScript { public: - /** - * Binds the script to the currently entered context. - */ Local