v8js_v8.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  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. extern "C" {
  18. #include "php.h"
  19. #include "ext/date/php_date.h"
  20. #include "ext/standard/php_string.h"
  21. #include "zend_interfaces.h"
  22. #include "zend_closures.h"
  23. #include "zend_exceptions.h"
  24. }
  25. #if !defined(_WIN32) && PHP_V8_API_VERSION >= 3029036
  26. #include <libplatform/libplatform.h>
  27. #endif
  28. #include "php_v8js_macros.h"
  29. #include "v8js_v8.h"
  30. #include "v8js_timer.h"
  31. #include "v8js_exceptions.h"
  32. #if defined(PHP_V8_USE_EXTERNAL_STARTUP_DATA) && PHP_V8_API_VERSION < 4006076
  33. /* Old V8 version, requires startup data but has no
  34. * (internal/API) means to let it be loaded. */
  35. static v8::StartupData natives_;
  36. static v8::StartupData snapshot_;
  37. static void v8js_v8_load_startup_data(const char* blob_file,
  38. v8::StartupData* startup_data,
  39. void (*setter_fn)(v8::StartupData*)) {
  40. startup_data->data = NULL;
  41. startup_data->raw_size = 0;
  42. if (!blob_file) {
  43. return;
  44. }
  45. FILE* file = fopen(blob_file, "rb");
  46. if (!file) {
  47. return;
  48. }
  49. fseek(file, 0, SEEK_END);
  50. startup_data->raw_size = static_cast<int>(ftell(file));
  51. rewind(file);
  52. startup_data->data = new char[startup_data->raw_size];
  53. int read_size = static_cast<int>(fread(const_cast<char*>(startup_data->data),
  54. 1, startup_data->raw_size, file));
  55. fclose(file);
  56. if (startup_data->raw_size == read_size) {
  57. (*setter_fn)(startup_data);
  58. }
  59. }
  60. #endif
  61. void v8js_v8_init(TSRMLS_D) /* {{{ */
  62. {
  63. /* Run only once; thread-local test first */
  64. if (V8JSG(v8_initialized)) {
  65. return;
  66. }
  67. /* Set thread-local flag, that V8 was initialized. */
  68. V8JSG(v8_initialized) = 1;
  69. #ifdef ZTS
  70. v8js_process_globals.lock.lock();
  71. if(v8js_process_globals.v8_initialized) {
  72. /* V8 already has been initialized by another thread */
  73. v8js_process_globals.lock.unlock();
  74. return;
  75. }
  76. #endif
  77. #ifdef PHP_V8_USE_EXTERNAL_STARTUP_DATA
  78. /* V8 doesn't work without startup data, load it. */
  79. #if PHP_V8_API_VERSION >= 4006076
  80. v8::V8::InitializeExternalStartupData(
  81. PHP_V8_NATIVES_BLOB_PATH,
  82. PHP_V8_SNAPSHOT_BLOB_PATH
  83. );
  84. #else
  85. v8js_v8_load_startup_data(PHP_V8_NATIVES_BLOB_PATH, &natives_, v8::V8::SetNativesDataBlob);
  86. v8js_v8_load_startup_data(PHP_V8_SNAPSHOT_BLOB_PATH, &snapshot_, v8::V8::SetSnapshotDataBlob);
  87. #endif
  88. #endif
  89. #if !defined(_WIN32) && PHP_V8_API_VERSION >= 3029036
  90. v8js_process_globals.v8_platform = v8::platform::CreateDefaultPlatform();
  91. v8::V8::InitializePlatform(v8js_process_globals.v8_platform);
  92. #endif
  93. /* Set V8 command line flags (must be done before V8::Initialize()!) */
  94. if (v8js_process_globals.v8_flags) {
  95. v8::V8::SetFlagsFromString(v8js_process_globals.v8_flags,
  96. strlen(v8js_process_globals.v8_flags));
  97. }
  98. /* Initialize V8 */
  99. v8::V8::Initialize();
  100. #ifdef ZTS
  101. v8js_process_globals.v8_initialized = 1;
  102. v8js_process_globals.lock.unlock();
  103. #endif
  104. }
  105. /* }}} */
  106. void v8js_v8_call(v8js_ctx *c, zval **return_value,
  107. long flags, long time_limit, long memory_limit,
  108. std::function< v8::Local<v8::Value>(v8::Isolate *) >& v8_call TSRMLS_DC) /* {{{ */
  109. {
  110. char *tz = NULL;
  111. V8JS_CTX_PROLOGUE(c);
  112. V8JSG(timer_mutex).lock();
  113. c->time_limit_hit = false;
  114. c->memory_limit_hit = false;
  115. V8JSG(timer_mutex).unlock();
  116. /* Catch JS exceptions */
  117. v8::TryCatch try_catch;
  118. /* Set flags for runtime use */
  119. c->flags = flags;
  120. /* Check if timezone has been changed and notify V8 */
  121. tz = getenv("TZ");
  122. if (tz != NULL) {
  123. if (c->tz == NULL) {
  124. c->tz = strdup(tz);
  125. }
  126. else if (strcmp(c->tz, tz) != 0) {
  127. v8::Date::DateTimeConfigurationChangeNotification(c->isolate);
  128. free(c->tz);
  129. c->tz = strdup(tz);
  130. }
  131. }
  132. if (time_limit > 0 || memory_limit > 0) {
  133. // If timer thread is not running then start it
  134. if (!V8JSG(timer_thread)) {
  135. // If not, start timer thread
  136. V8JSG(timer_thread) = new std::thread(v8js_timer_thread TSRMLS_CC);
  137. }
  138. }
  139. /* Always pass the timer to the stack so there can be follow-up changes to
  140. * the time & memory limit. */
  141. v8js_timer_push(time_limit, memory_limit, c TSRMLS_CC);
  142. /* Execute script */
  143. c->in_execution++;
  144. v8::Local<v8::Value> result = v8_call(c->isolate);
  145. c->in_execution--;
  146. /* Pop our context from the stack and read (possibly updated) limits
  147. * into local variables. */
  148. V8JSG(timer_mutex).lock();
  149. v8js_timer_ctx *timer_ctx = V8JSG(timer_stack).front();
  150. V8JSG(timer_stack).pop_front();
  151. V8JSG(timer_mutex).unlock();
  152. time_limit = timer_ctx->time_limit;
  153. memory_limit = timer_ctx->memory_limit;
  154. efree(timer_ctx);
  155. /* Check for fatal error marker possibly set by v8js_error_handler; just
  156. * rethrow the error since we're now out of V8. */
  157. if(V8JSG(fatal_error_abort)) {
  158. zend_bailout();
  159. }
  160. char exception_string[64];
  161. if (c->time_limit_hit) {
  162. // Execution has been terminated due to time limit
  163. sprintf(exception_string, "Script time limit of %lu milliseconds exceeded", time_limit);
  164. zend_throw_exception(php_ce_v8js_time_limit_exception, exception_string, 0 TSRMLS_CC);
  165. return;
  166. }
  167. if (memory_limit && !c->memory_limit_hit) {
  168. // Re-check memory limit (very short executions might never be hit by timer thread)
  169. v8::HeapStatistics hs;
  170. isolate->GetHeapStatistics(&hs);
  171. if (hs.used_heap_size() > memory_limit) {
  172. #if PHP_V8_API_VERSION >= 3028036
  173. isolate->LowMemoryNotification();
  174. #else
  175. v8::V8::LowMemoryNotification();
  176. #endif
  177. isolate->GetHeapStatistics(&hs);
  178. if (hs.used_heap_size() > memory_limit) {
  179. c->memory_limit_hit = true;
  180. }
  181. }
  182. }
  183. if (c->memory_limit_hit) {
  184. // Execution has been terminated due to memory limit
  185. sprintf(exception_string, "Script memory limit of %lu bytes exceeded", memory_limit);
  186. zend_throw_exception(php_ce_v8js_memory_limit_exception, exception_string, 0 TSRMLS_CC);
  187. return;
  188. }
  189. if (!try_catch.CanContinue()) {
  190. // At this point we can't re-throw the exception
  191. return;
  192. }
  193. /* There was pending exception left from earlier executions -> throw to PHP */
  194. if (c->pending_exception) {
  195. zend_throw_exception_object(c->pending_exception TSRMLS_CC);
  196. c->pending_exception = NULL;
  197. }
  198. /* Handle runtime JS exceptions */
  199. if (try_catch.HasCaught()) {
  200. /* Pending exceptions are set only in outer caller, inner caller exceptions are always rethrown */
  201. if (c->in_execution < 1) {
  202. /* Report immediately if report_uncaught is true */
  203. if (c->report_uncaught) {
  204. v8js_throw_script_exception(c->isolate, &try_catch TSRMLS_CC);
  205. return;
  206. }
  207. /* Exception thrown from JS, preserve it for future execution */
  208. if (result.IsEmpty()) {
  209. MAKE_STD_ZVAL(c->pending_exception);
  210. v8js_create_script_exception(c->pending_exception, c->isolate, &try_catch TSRMLS_CC);
  211. return;
  212. }
  213. }
  214. /* Rethrow back to JS */
  215. try_catch.ReThrow();
  216. return;
  217. }
  218. /* Convert V8 value to PHP value */
  219. if (!result.IsEmpty()) {
  220. v8js_to_zval(result, *return_value, flags, c->isolate TSRMLS_CC);
  221. }
  222. }
  223. /* }}} */
  224. void v8js_terminate_execution(v8::Isolate *isolate) /* {{{ */
  225. {
  226. if(v8::V8::IsExecutionTerminating(isolate)) {
  227. /* Execution already terminating, needn't trigger it again and
  228. * especially must not execute the spinning loop (which would cause
  229. * crashes in V8 itself, at least with 4.2 and 4.3 version lines). */
  230. return;
  231. }
  232. /* Unfortunately just calling TerminateExecution on the isolate is not
  233. * enough, since v8 just marks the thread as "to be aborted" and doesn't
  234. * immediately do so. Hence we enter an endless loop after signalling
  235. * termination, so we definitely don't execute JS code after the exit()
  236. * statement. */
  237. v8::Locker locker(isolate);
  238. v8::Isolate::Scope isolate_scope(isolate);
  239. v8::HandleScope handle_scope(isolate);
  240. v8::Local<v8::String> source = V8JS_STR("for(;;);");
  241. v8::Local<v8::Script> script = v8::Script::Compile(source);
  242. v8::V8::TerminateExecution(isolate);
  243. script->Run();
  244. }
  245. /* }}} */
  246. int v8js_get_properties_hash(v8::Handle<v8::Value> jsValue, HashTable *retval, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  247. {
  248. v8::Local<v8::Object> jsObj = jsValue->ToObject();
  249. if (!jsObj.IsEmpty()) {
  250. v8::Local<v8::Array> jsKeys = jsObj->GetPropertyNames();
  251. for (unsigned i = 0; i < jsKeys->Length(); i++)
  252. {
  253. v8::Local<v8::String> jsKey = jsKeys->Get(i)->ToString();
  254. /* Skip any prototype properties */
  255. if (!jsObj->HasOwnProperty(jsKey) && !jsObj->HasRealNamedProperty(jsKey) && !jsObj->HasRealNamedCallbackProperty(jsKey)) {
  256. continue;
  257. }
  258. v8::Local<v8::Value> jsVal = jsObj->Get(jsKey);
  259. v8::String::Utf8Value cstr(jsKey);
  260. const char *key = ToCString(cstr);
  261. zval *value = NULL;
  262. v8::Local<v8::Value> php_object;
  263. if (jsVal->IsObject()) {
  264. php_object = v8::Local<v8::Object>::Cast(jsVal)->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  265. }
  266. if (!php_object.IsEmpty()) {
  267. /* This is a PHP object, passed to JS and back. */
  268. value = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  269. Z_ADDREF_P(value);
  270. }
  271. else {
  272. MAKE_STD_ZVAL(value);
  273. if (v8js_to_zval(jsVal, value, flags, isolate TSRMLS_CC) == FAILURE) {
  274. zval_ptr_dtor(&value);
  275. return FAILURE;
  276. }
  277. }
  278. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  279. zend_symtable_update(retval, key, strlen(key) + 1, (void *)&value, sizeof(zval *), NULL);
  280. } else {
  281. zend_hash_update(retval, key, strlen(key) + 1, (void *) &value, sizeof(zval *), NULL);
  282. }
  283. }
  284. return SUCCESS;
  285. }
  286. return FAILURE;
  287. }
  288. /* }}} */
  289. /*
  290. * Local variables:
  291. * tab-width: 4
  292. * c-basic-offset: 4
  293. * End:
  294. * vim600: noet sw=4 ts=4 fdm=marker
  295. * vim<600: noet sw=4 ts=4
  296. */