v8js_v8.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. /* Set V8 command line flags (must be done before V8::Initialize()!) */
  62. if (v8js_process_globals.v8_flags) {
  63. size_t flags_len = strlen(v8js_process_globals.v8_flags);
  64. if (flags_len > std::numeric_limits<int>::max()) {
  65. zend_throw_exception(php_ce_v8js_exception,
  66. "Length of V8 flags exceeds maximum supported length", 0);
  67. }
  68. else {
  69. v8::V8::SetFlagsFromString(v8js_process_globals.v8_flags, static_cast<int>(flags_len));
  70. }
  71. }
  72. #if PHP_V8_API_VERSION >= 5003178
  73. /* Initialize ICU, call introduced in V8 5.3.178 */
  74. if (v8js_process_globals.icudtl_dat_path != NULL && v8js_process_globals.icudtl_dat_path[0] != 0) {
  75. v8::V8::InitializeICUDefaultLocation(nullptr, v8js_process_globals.icudtl_dat_path);
  76. }
  77. #ifdef PHP_V8_EXEC_PATH
  78. else {
  79. v8::V8::InitializeICUDefaultLocation(PHP_V8_EXEC_PATH, nullptr);
  80. }
  81. #endif
  82. #endif /* PHP_V8_API_VERSION >= 5003178 */
  83. /* Initialize V8 */
  84. v8::V8::Initialize();
  85. #ifdef ZTS
  86. v8js_process_globals.v8_initialized = 1;
  87. v8js_process_globals.lock.unlock();
  88. #endif
  89. }
  90. /* }}} */
  91. /**
  92. * Prepare V8 call trampoline with time & memory limit, exception handling, etc.
  93. *
  94. * The caller MUST check V8JSG(fatal_error_abort) and trigger further bailout
  95. * either immediately after this function returns (or possibly after freeing
  96. * heap allocated memory).
  97. */
  98. void v8js_v8_call(v8js_ctx *c, zval **return_value,
  99. long flags, long time_limit, size_t memory_limit,
  100. std::function< v8::MaybeLocal<v8::Value>(v8::Isolate *) >& v8_call) /* {{{ */
  101. {
  102. char *tz = NULL;
  103. // hold extra reference on v8 instance as long as we call into V8 (issue #472)
  104. zend_object *obj = v8js_ctx_to_zend_object(c);
  105. zval zv_v8inst;
  106. ZVAL_OBJ(&zv_v8inst, obj);
  107. Z_ADDREF_P(&zv_v8inst);
  108. {
  109. V8JS_CTX_PROLOGUE(c);
  110. V8JSG(timer_mutex).lock();
  111. c->time_limit_hit = false;
  112. c->memory_limit_hit = false;
  113. V8JSG(timer_mutex).unlock();
  114. /* Catch JS exceptions */
  115. v8::TryCatch try_catch(isolate);
  116. /* Set flags for runtime use */
  117. c->flags = flags;
  118. /* Check if timezone has been changed and notify V8 */
  119. tz = getenv("TZ");
  120. if (tz != NULL) {
  121. if (c->tz == NULL) {
  122. c->tz = strdup(tz);
  123. }
  124. else if (strcmp(c->tz, tz) != 0) {
  125. c->isolate->DateTimeConfigurationChangeNotification(v8::Isolate::TimeZoneDetection::kRedetect);
  126. free(c->tz);
  127. c->tz = strdup(tz);
  128. }
  129. }
  130. if (time_limit > 0 || memory_limit > 0) {
  131. // If timer thread is not running then start it
  132. if (!V8JSG(timer_thread)) {
  133. // If not, start timer thread
  134. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  135. }
  136. }
  137. /* Always pass the timer to the stack so there can be follow-up changes to
  138. * the time & memory limit. */
  139. v8js_timer_push(time_limit, memory_limit, c);
  140. /* Execute script */
  141. c->in_execution++;
  142. v8::MaybeLocal<v8::Value> result = v8_call(c->isolate);
  143. c->in_execution--;
  144. /* Pop our context from the stack and read (possibly updated) limits
  145. * into local variables. */
  146. V8JSG(timer_mutex).lock();
  147. v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
  148. V8JSG(timer_stack).pop_front();
  149. V8JSG(timer_mutex).unlock();
  150. time_limit = timer_ctx->time_limit;
  151. memory_limit = timer_ctx->memory_limit;
  152. efree(timer_ctx);
  153. if(!V8JSG(fatal_error_abort)) {
  154. char exception_string[64];
  155. if (c->time_limit_hit) {
  156. // Execution has been terminated due to time limit
  157. sprintf(exception_string, "Script time limit of %lu milliseconds exceeded", time_limit);
  158. zend_throw_exception(php_ce_v8js_time_limit_exception, exception_string, 0);
  159. zval_ptr_dtor(&zv_v8inst);
  160. return;
  161. }
  162. if (memory_limit && !c->memory_limit_hit) {
  163. // Re-check memory limit (very short executions might never be hit by timer thread)
  164. v8::HeapStatistics hs;
  165. isolate->GetHeapStatistics(&hs);
  166. if (hs.used_heap_size() > memory_limit) {
  167. isolate->LowMemoryNotification();
  168. isolate->GetHeapStatistics(&hs);
  169. if (hs.used_heap_size() > memory_limit) {
  170. c->memory_limit_hit = true;
  171. }
  172. }
  173. }
  174. if (c->memory_limit_hit) {
  175. // Execution has been terminated due to memory limit
  176. sprintf(exception_string, "Script memory limit of %lu bytes exceeded", memory_limit);
  177. zend_throw_exception(php_ce_v8js_memory_limit_exception, exception_string, 0);
  178. zval_ptr_dtor(&zv_v8inst);
  179. return;
  180. }
  181. if (!try_catch.CanContinue()) {
  182. // At this point we can't re-throw the exception
  183. zval_ptr_dtor(&zv_v8inst);
  184. return;
  185. }
  186. /* There was pending exception left from earlier executions -> throw to PHP */
  187. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  188. zend_throw_exception_object(&c->pending_exception);
  189. ZVAL_NULL(&c->pending_exception);
  190. }
  191. /* Handle runtime JS exceptions */
  192. if (try_catch.HasCaught()) {
  193. /* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
  194. if (c->in_execution < 1) {
  195. /* Report immediately if report_uncaught is true */
  196. if (c->report_uncaught) {
  197. v8js_throw_script_exception(c->isolate, &try_catch);
  198. zval_ptr_dtor(&zv_v8inst);
  199. return;
  200. }
  201. /* Exception thrown from JS, preserve it for future execution */
  202. if (result.IsEmpty()) {
  203. v8js_create_script_exception(&c->pending_exception, c->isolate, &try_catch);
  204. zval_ptr_dtor(&zv_v8inst);
  205. return;
  206. }
  207. }
  208. /* Rethrow back to JS */
  209. try_catch.ReThrow();
  210. zval_ptr_dtor(&zv_v8inst);
  211. return;
  212. }
  213. /* Convert V8 value to PHP value */
  214. if (return_value && !result.IsEmpty()) {
  215. v8js_to_zval(result.ToLocalChecked(), *return_value, flags, c->isolate);
  216. }
  217. }
  218. }
  219. zval_ptr_dtor(&zv_v8inst);
  220. }
  221. /* }}} */
  222. void v8js_terminate_execution(v8::Isolate *isolate) /* {{{ */
  223. {
  224. if(isolate->IsExecutionTerminating()) {
  225. /* Execution already terminating, needn't trigger it again and
  226. * especially must not execute the spinning loop (which would cause
  227. * crashes in V8 itself, at least with 4.2 and 4.3 version lines). */
  228. return;
  229. }
  230. /* Unfortunately just calling TerminateExecution on the isolate is not
  231. * enough, since v8 just marks the thread as "to be aborted" and doesn't
  232. * immediately do so. Hence we enter an endless loop after signalling
  233. * termination, so we definitely don't execute JS code after the exit()
  234. * statement. */
  235. v8::Locker locker(isolate);
  236. v8::Isolate::Scope isolate_scope(isolate);
  237. v8::HandleScope handle_scope(isolate);
  238. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  239. v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, ctx->context);
  240. v8::Local<v8::String> source = V8JS_STR("for(;;);");
  241. v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked();
  242. isolate->TerminateExecution();
  243. script->Run(context);
  244. }
  245. /* }}} */
  246. int v8js_get_properties_hash(v8::Local<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate) /* {{{ */
  247. {
  248. v8js_ctx *ctx = (v8js_ctx *) isolate->GetData(0);
  249. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(isolate, ctx->context);
  250. v8::Local<v8::Object> jsObj;
  251. v8::Local<v8::Array> jsKeys;
  252. if (!jsValue->ToObject(v8_context).ToLocal(&jsObj)
  253. || !jsObj->GetPropertyNames(v8_context).ToLocal(&jsKeys)) {
  254. return FAILURE;
  255. }
  256. for (unsigned i = 0; i < jsKeys->Length(); i++)
  257. {
  258. v8::Local<v8::Value> jsKeySlot;
  259. v8::Local<v8::String> jsKey;
  260. if (!jsKeys->Get(v8_context, i).ToLocal(&jsKeySlot)
  261. || !jsKeySlot->ToString(v8_context).ToLocal(&jsKey)) {
  262. continue;
  263. }
  264. /* Skip any prototype properties */
  265. if (!jsObj->HasOwnProperty(isolate->GetEnteredOrMicrotaskContext(), jsKey).FromMaybe(false)
  266. && !jsObj->HasRealNamedProperty(v8_context, jsKey).FromMaybe(false)
  267. && !jsObj->HasRealNamedCallbackProperty(v8_context, jsKey).FromMaybe(false)) {
  268. continue;
  269. }
  270. v8::Local<v8::Value> jsVal;
  271. if (!jsObj->Get(v8_context, jsKey).ToLocal(&jsVal)) {
  272. continue;
  273. }
  274. v8::String::Utf8Value cstr(isolate, jsKey);
  275. zend_string *key = zend_string_init(ToCString(cstr), cstr.length(), 0);
  276. zval value;
  277. ZVAL_UNDEF(&value);
  278. v8::Local<v8::Object> jsValObject;
  279. if (jsVal->IsObject() && jsVal->ToObject(v8_context).ToLocal(&jsValObject) && jsValObject->InternalFieldCount() == 2) {
  280. /* This is a PHP object, passed to JS and back. */
  281. zend_object *object = reinterpret_cast<zend_object *>(jsValObject->GetAlignedPointerFromInternalField(1));
  282. ZVAL_OBJ(&value, object);
  283. Z_ADDREF_P(&value);
  284. }
  285. else {
  286. if (v8js_to_zval(jsVal, &value, flags, isolate) == FAILURE) {
  287. zval_ptr_dtor(&value);
  288. return FAILURE;
  289. }
  290. }
  291. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  292. zend_symtable_update(retval, key, &value);
  293. } else {
  294. zend_hash_update(retval, key, &value);
  295. }
  296. zend_string_release(key);
  297. }
  298. return SUCCESS;
  299. }
  300. /* }}} */
  301. /*
  302. * Local variables:
  303. * tab-width: 4
  304. * c-basic-offset: 4
  305. * indent-tabs-mode: t
  306. * End:
  307. * vim600: noet sw=4 ts=4 fdm=marker
  308. * vim<600: noet sw=4 ts=4
  309. */