v8js_v8.cc 9.2 KB

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