v8js_v8.cc 9.8 KB

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