v8js_v8.cc 9.1 KB

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