v8js_v8.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 7 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2016 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. | Author: Stefan Siegl <[email protected]> |
  12. +----------------------------------------------------------------------+
  13. */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. #include "php_v8js_macros.h"
  18. #include "v8js_v8.h"
  19. #include "v8js_timer.h"
  20. #include "v8js_exceptions.h"
  21. extern "C" {
  22. #include "ext/date/php_date.h"
  23. #include "ext/standard/php_string.h"
  24. #include "zend_interfaces.h"
  25. #include "zend_closures.h"
  26. #include "zend_exceptions.h"
  27. }
  28. #include <libplatform/libplatform.h>
  29. void v8js_v8_init() /* {{{ */
  30. {
  31. /* Run only once; thread-local test first */
  32. if (V8JSG(v8_initialized)) {
  33. return;
  34. }
  35. /* Set thread-local flag, that V8 was initialized. */
  36. V8JSG(v8_initialized) = 1;
  37. #ifdef ZTS
  38. v8js_process_globals.lock.lock();
  39. if(v8js_process_globals.v8_initialized) {
  40. /* V8 already has been initialized by another thread */
  41. v8js_process_globals.lock.unlock();
  42. return;
  43. }
  44. #endif
  45. #if defined(PHP_V8_SNAPSHOT_BLOB_PATH)
  46. #if !defined(PHP_V8_NATIVES_BLOB_PATH)
  47. /* Newer V8 version don't have a natives blob anymore. */
  48. v8::V8::InitializeExternalStartupDataFromFile(
  49. PHP_V8_SNAPSHOT_BLOB_PATH
  50. );
  51. #else
  52. /* V8 doesn't work without startup data, load it. */
  53. v8::V8::InitializeExternalStartupData(
  54. PHP_V8_NATIVES_BLOB_PATH,
  55. PHP_V8_SNAPSHOT_BLOB_PATH
  56. );
  57. #endif
  58. #endif
  59. v8js_process_globals.v8_platform = v8::platform::NewDefaultPlatform();
  60. v8::V8::InitializePlatform(v8js_process_globals.v8_platform.get());
  61. #ifdef V8_HAS_INITIALIZE_SANDBOX
  62. v8::V8::InitializeSandbox();
  63. #endif
  64. /* Set V8 command line flags (must be done before V8::Initialize()!) */
  65. if (v8js_process_globals.v8_flags) {
  66. size_t flags_len = strlen(v8js_process_globals.v8_flags);
  67. if (flags_len > std::numeric_limits<int>::max()) {
  68. zend_throw_exception(php_ce_v8js_exception,
  69. "Length of V8 flags exceeds maximum supported length", 0);
  70. }
  71. else {
  72. v8::V8::SetFlagsFromString(v8js_process_globals.v8_flags, static_cast<int>(flags_len));
  73. }
  74. }
  75. #if PHP_V8_API_VERSION >= 5003178
  76. /* Initialize ICU, call introduced in V8 5.3.178 */
  77. if (v8js_process_globals.icudtl_dat_path != NULL && v8js_process_globals.icudtl_dat_path[0] != 0) {
  78. v8::V8::InitializeICUDefaultLocation(nullptr, v8js_process_globals.icudtl_dat_path);
  79. }
  80. #ifdef PHP_V8_EXEC_PATH
  81. else {
  82. v8::V8::InitializeICUDefaultLocation(PHP_V8_EXEC_PATH, nullptr);
  83. }
  84. #endif
  85. #endif /* PHP_V8_API_VERSION >= 5003178 */
  86. /* Initialize V8 */
  87. v8::V8::Initialize();
  88. #ifdef ZTS
  89. v8js_process_globals.v8_initialized = 1;
  90. v8js_process_globals.lock.unlock();
  91. #endif
  92. }
  93. /* }}} */
  94. /**
  95. * Prepare V8 call trampoline with time & memory limit, exception handling, etc.
  96. *
  97. * The caller MUST check V8JSG(fatal_error_abort) and trigger further bailout
  98. * either immediately after this function returns (or possibly after freeing
  99. * heap allocated memory).
  100. */
  101. void v8js_v8_call(v8js_ctx *c, zval **return_value,
  102. long flags, long time_limit, size_t memory_limit,
  103. std::function< v8::MaybeLocal<v8::Value>(v8::Isolate *) >& v8_call) /* {{{ */
  104. {
  105. char *tz = NULL;
  106. // hold extra reference on v8 instance as long as we call into V8 (issue #472)
  107. zend_object *obj = v8js_ctx_to_zend_object(c);
  108. zval zv_v8inst;
  109. ZVAL_OBJ(&zv_v8inst, obj);
  110. Z_ADDREF_P(&zv_v8inst);
  111. {
  112. V8JS_CTX_PROLOGUE(c);
  113. V8JSG(timer_mutex).lock();
  114. c->time_limit_hit = false;
  115. c->memory_limit_hit = false;
  116. V8JSG(timer_mutex).unlock();
  117. /* Catch JS exceptions */
  118. v8::TryCatch try_catch(isolate);
  119. /* Set flags for runtime use */
  120. c->flags = flags;
  121. /* Check if timezone has been changed and notify V8 */
  122. tz = getenv("TZ");
  123. if (tz != NULL) {
  124. if (c->tz == NULL) {
  125. c->tz = strdup(tz);
  126. }
  127. else if (strcmp(c->tz, tz) != 0) {
  128. c->isolate->DateTimeConfigurationChangeNotification(v8::Isolate::TimeZoneDetection::kRedetect);
  129. free(c->tz);
  130. c->tz = strdup(tz);
  131. }
  132. }
  133. if (time_limit > 0 || memory_limit > 0) {
  134. // If timer thread is not running then start it
  135. if (!V8JSG(timer_thread)) {
  136. // If not, start timer thread
  137. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  138. }
  139. }
  140. /* Always pass the timer to the stack so there can be follow-up changes to
  141. * the time & memory limit. */
  142. v8js_timer_push(time_limit, memory_limit, c);
  143. /* Execute script */
  144. c->in_execution++;
  145. v8::MaybeLocal<v8::Value> result = v8_call(c->isolate);
  146. c->in_execution--;
  147. /* Pop our context from the stack and read (possibly updated) limits
  148. * into local variables. */
  149. V8JSG(timer_mutex).lock();
  150. v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
  151. V8JSG(timer_stack).pop_front();
  152. V8JSG(timer_mutex).unlock();
  153. time_limit = timer_ctx->time_limit;
  154. memory_limit = timer_ctx->memory_limit;
  155. efree(timer_ctx);
  156. if(!V8JSG(fatal_error_abort)) {
  157. char exception_string[64];
  158. if (c->time_limit_hit) {
  159. // Execution has been terminated due to time limit
  160. sprintf(exception_string, "Script time limit of %lu milliseconds exceeded", time_limit);
  161. zend_throw_exception(php_ce_v8js_time_limit_exception, exception_string, 0);
  162. zval_ptr_dtor(&zv_v8inst);
  163. return;
  164. }
  165. if (memory_limit && !c->memory_limit_hit) {
  166. // Re-check memory limit (very short executions might never be hit by timer thread)
  167. v8::HeapStatistics hs;
  168. isolate->GetHeapStatistics(&hs);
  169. if (hs.used_heap_size() > memory_limit) {
  170. isolate->LowMemoryNotification();
  171. isolate->GetHeapStatistics(&hs);
  172. if (hs.used_heap_size() > memory_limit) {
  173. c->memory_limit_hit = true;
  174. }
  175. }
  176. }
  177. if (c->memory_limit_hit) {
  178. // Execution has been terminated due to memory limit
  179. sprintf(exception_string, "Script memory limit of %lu bytes exceeded", memory_limit);
  180. zend_throw_exception(php_ce_v8js_memory_limit_exception, exception_string, 0);
  181. zval_ptr_dtor(&zv_v8inst);
  182. return;
  183. }
  184. if (!try_catch.CanContinue()) {
  185. // At this point we can't re-throw the exception
  186. zval_ptr_dtor(&zv_v8inst);
  187. return;
  188. }
  189. /* Handle runtime JS exceptions */
  190. if (try_catch.HasCaught()) {
  191. /* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
  192. if (c->in_execution < 1) {
  193. v8js_throw_script_exception(c->isolate, &try_catch);
  194. zval_ptr_dtor(&zv_v8inst);
  195. return;
  196. }
  197. /* Rethrow back to JS */
  198. try_catch.ReThrow();
  199. zval_ptr_dtor(&zv_v8inst);
  200. return;
  201. }
  202. /* Convert V8 value to PHP value */
  203. if (return_value && !result.IsEmpty()) {
  204. v8js_to_zval(result.ToLocalChecked(), *return_value, flags, c->isolate);
  205. }
  206. }
  207. }
  208. zval_ptr_dtor(&zv_v8inst);
  209. }
  210. /* }}} */
  211. void v8js_terminate_execution(v8::Isolate *isolate) /* {{{ */
  212. {
  213. if(isolate->IsExecutionTerminating()) {
  214. /* Execution already terminating, needn't trigger it again and
  215. * especially must not execute the spinning loop (which would cause
  216. * crashes in V8 itself, at least with 4.2 and 4.3 version lines). */
  217. return;
  218. }
  219. /* Unfortunately just calling TerminateExecution on the isolate is not
  220. * enough, since v8 just marks the thread as "to be aborted" and doesn't
  221. * immediately do so. Hence we enter an endless loop after signalling
  222. * termination, so we definitely don't execute JS code after the exit()
  223. * statement. */
  224. v8::Locker locker(isolate);
  225. v8::Isolate::Scope isolate_scope(isolate);
  226. v8::HandleScope handle_scope(isolate);
  227. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  228. v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, ctx->context);
  229. v8::Local<v8::String> source = V8JS_STR("for(;;);");
  230. v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked();
  231. isolate->TerminateExecution();
  232. script->Run(context);
  233. }
  234. /* }}} */
  235. int v8js_get_properties_hash(v8::Local<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate) /* {{{ */
  236. {
  237. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  238. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  239. v8::Local<v8::Object> jsObj;
  240. v8::Local<v8::Array> jsKeys;
  241. if (!jsValue->ToObject(v8_context).ToLocal(&jsObj)
  242. || !jsObj->GetPropertyNames(v8_context).ToLocal(&jsKeys)) {
  243. return FAILURE;
  244. }
  245. for (unsigned i = 0; i < jsKeys->Length(); i++)
  246. {
  247. v8::Local<v8::Value> jsKeySlot;
  248. v8::Local<v8::String> jsKey;
  249. if (!jsKeys->Get(v8_context, i).ToLocal(&jsKeySlot)
  250. || !jsKeySlot->ToString(v8_context).ToLocal(&jsKey)) {
  251. continue;
  252. }
  253. /* Skip any prototype properties */
  254. if (!jsObj->HasOwnProperty(isolate->GetEnteredOrMicrotaskContext(), jsKey).FromMaybe(false)
  255. && !jsObj->HasRealNamedProperty(v8_context, jsKey).FromMaybe(false)
  256. && !jsObj->HasRealNamedCallbackProperty(v8_context, jsKey).FromMaybe(false)) {
  257. continue;
  258. }
  259. v8::Local<v8::Value> jsVal;
  260. if (!jsObj->Get(v8_context, jsKey).ToLocal(&jsVal)) {
  261. continue;
  262. }
  263. v8::String::Utf8Value cstr(isolate, jsKey);
  264. zend_string *key = zend_string_init(ToCString(cstr), cstr.length(), 0);
  265. zval value;
  266. ZVAL_UNDEF(&value);
  267. v8::Local<v8::Object> jsValObject;
  268. if (jsVal->IsObject() && !jsVal->IsArrayBufferView() && !jsVal->IsArrayBuffer()
  269. && jsVal->ToObject(v8_context).ToLocal(&jsValObject) && (jsValObject->InternalFieldCount() == 2)) {
  270. /* This is a PHP object, passed to JS and back. */
  271. zend_object *object = reinterpret_cast<zend_object *>(jsValObject->GetAlignedPointerFromInternalField(1));
  272. ZVAL_OBJ(&value, object);
  273. Z_ADDREF_P(&value);
  274. }
  275. else {
  276. if (v8js_to_zval(jsVal, &value, flags, isolate) == FAILURE) {
  277. zval_ptr_dtor(&value);
  278. return FAILURE;
  279. }
  280. }
  281. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  282. zend_symtable_update(retval, key, &value);
  283. } else {
  284. zend_hash_update(retval, key, &value);
  285. }
  286. zend_string_release(key);
  287. }
  288. return SUCCESS;
  289. }
  290. /* }}} */
  291. /*
  292. * Local variables:
  293. * tab-width: 4
  294. * c-basic-offset: 4
  295. * indent-tabs-mode: t
  296. * End:
  297. * vim600: noet sw=4 ts=4 fdm=marker
  298. * vim<600: noet sw=4 ts=4
  299. */