v8js_class.cc 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 7 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2017 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 <functional>
  18. #include <algorithm>
  19. #include "php_v8js_macros.h"
  20. #include "v8js_v8.h"
  21. #include "v8js_exceptions.h"
  22. #include "v8js_v8object_class.h"
  23. #include "v8js_object_export.h"
  24. #include "v8js_timer.h"
  25. extern "C" {
  26. #include "php.h"
  27. #include "ext/date/php_date.h"
  28. #include "ext/standard/php_string.h"
  29. #include "zend_interfaces.h"
  30. #include "zend_closures.h"
  31. #include "ext/spl/spl_exceptions.h"
  32. #include "zend_exceptions.h"
  33. }
  34. #define PHP_V8JS_SCRIPT_RES_NAME "V8Js script"
  35. /* {{{ Class Entries */
  36. static zend_class_entry *php_ce_v8js;
  37. /* }}} */
  38. /* {{{ Object Handlers */
  39. static zend_object_handlers v8js_object_handlers;
  40. /* }}} */
  41. /* Forward declare v8js_methods, actually "static" but not possible in C++ */
  42. extern const zend_function_entry v8js_methods[];
  43. typedef struct _v8js_script {
  44. char *name;
  45. v8js_ctx *ctx;
  46. v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>> *script;
  47. } v8js_script;
  48. static void v8js_script_free(v8js_script *res);
  49. int le_v8js_script;
  50. #ifdef USE_INTERNAL_ALLOCATOR
  51. class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
  52. public:
  53. virtual void* Allocate(size_t length) {
  54. void* data = AllocateUninitialized(length);
  55. return data == NULL ? data : memset(data, 0, length);
  56. }
  57. virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
  58. virtual void Free(void* data, size_t) { free(data); }
  59. };
  60. #endif /** USE_INTERNAL_ALLOCATOR */
  61. static void v8js_free_storage(zend_object *object) /* {{{ */
  62. {
  63. v8js_ctx *c = v8js_ctx_fetch_object(object);
  64. zend_object_std_dtor(&c->std);
  65. zval_ptr_dtor(&c->module_normaliser);
  66. zval_ptr_dtor(&c->module_loader);
  67. /* Delete PHP global object from JavaScript */
  68. if (!c->context.IsEmpty()) {
  69. v8::Locker locker(c->isolate);
  70. v8::Isolate::Scope isolate_scope(c->isolate);
  71. v8::HandleScope handle_scope(c->isolate);
  72. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(c->isolate, c->context);
  73. v8::Context::Scope context_scope(v8_context);
  74. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(c->isolate, c->object_name);
  75. V8JS_GLOBAL(c->isolate)->Delete(v8_context, object_name_js);
  76. }
  77. c->object_name.Reset();
  78. c->object_name.~Persistent();
  79. c->global_template.Reset();
  80. c->global_template.~Persistent();
  81. c->array_tmpl.Reset();
  82. c->array_tmpl.~Persistent();
  83. /* Clear persistent call_impl & method_tmpls templates */
  84. for (std::map<v8js_function_tmpl_t *, v8js_function_tmpl_t>::iterator it = c->call_impls.begin();
  85. it != c->call_impls.end(); ++it) {
  86. // No need to free it->first, as it is stored in c->template_cache and freed below
  87. it->second.Reset();
  88. }
  89. c->call_impls.~map();
  90. for (std::map<std::pair<zend_class_entry *, zend_function *>, v8js_function_tmpl_t>::iterator it = c->method_tmpls.begin();
  91. it != c->method_tmpls.end(); ++it) {
  92. it->second.Reset();
  93. }
  94. c->method_tmpls.~map();
  95. /* Clear persistent handles in template cache */
  96. for (std::map<const zend_string *,v8js_function_tmpl_t>::iterator it = c->template_cache.begin();
  97. it != c->template_cache.end(); ++it) {
  98. it->second.Reset();
  99. }
  100. c->template_cache.~map();
  101. /* Clear contexts */
  102. for (std::vector<v8js_accessor_ctx*>::iterator it = c->accessor_list.begin();
  103. it != c->accessor_list.end(); ++it) {
  104. v8js_accessor_ctx_dtor(*it);
  105. }
  106. c->accessor_list.~vector();
  107. /* Clear global object, dispose context */
  108. if (!c->context.IsEmpty()) {
  109. c->context.Reset();
  110. }
  111. c->context.~Persistent();
  112. /* Dispose yet undisposed weak refs */
  113. for (std::map<zend_object *, v8js_persistent_obj_t>::iterator it = c->weak_objects.begin();
  114. it != c->weak_objects.end(); ++it) {
  115. zend_object *object = it->first;
  116. zval value;
  117. ZVAL_OBJ(&value, object);
  118. zval_ptr_dtor(&value);
  119. c->isolate->AdjustAmountOfExternalAllocatedMemory(-c->average_object_size);
  120. it->second.Reset();
  121. }
  122. c->weak_objects.~map();
  123. for (std::map<v8js_function_tmpl_t *, v8js_persistent_obj_t>::iterator it = c->weak_closures.begin();
  124. it != c->weak_closures.end(); ++it) {
  125. v8js_function_tmpl_t *persist_tpl_ = it->first;
  126. persist_tpl_->Reset();
  127. delete persist_tpl_;
  128. it->second.Reset();
  129. }
  130. c->weak_closures.~map();
  131. for (std::list<v8js_v8object *>::iterator it = c->v8js_v8objects.begin();
  132. it != c->v8js_v8objects.end(); it ++) {
  133. (*it)->v8obj.Reset();
  134. (*it)->ctx = NULL;
  135. }
  136. c->v8js_v8objects.~list();
  137. for (std::vector<v8js_script *>::iterator it = c->script_objects.begin();
  138. it != c->script_objects.end(); it ++) {
  139. (*it)->ctx = NULL;
  140. (*it)->script->Reset();
  141. }
  142. c->script_objects.~vector();
  143. /* Clear persistent handles in module cache */
  144. for (std::map<char *, v8js_persistent_value_t>::iterator it = c->modules_loaded.begin();
  145. it != c->modules_loaded.end(); ++it) {
  146. efree(it->first);
  147. it->second.Reset();
  148. }
  149. c->modules_loaded.~map();
  150. if(c->isolate) {
  151. /* c->isolate is initialized by V8Js::__construct, but __wakeup calls
  152. * are not fully constructed and hence this would cause a NPE. */
  153. c->isolate->Dispose();
  154. }
  155. if(c->tz != NULL) {
  156. free(c->tz);
  157. }
  158. c->modules_stack.~vector();
  159. zval_ptr_dtor(&c->zval_snapshot_blob);
  160. #ifndef USE_INTERNAL_ALLOCATOR
  161. delete c->create_params.array_buffer_allocator;
  162. #endif
  163. }
  164. /* }}} */
  165. static zend_object* v8js_new(zend_class_entry *ce) /* {{{ */
  166. {
  167. v8js_ctx *c;
  168. c = (v8js_ctx *) ecalloc(1, sizeof(*c) + zend_object_properties_size(ce));
  169. zend_object_std_init(&c->std, ce);
  170. object_properties_init(&c->std, ce);
  171. c->std.handlers = &v8js_object_handlers;
  172. new(&c->object_name) v8::Persistent<v8::String>();
  173. new(&c->context) v8::Persistent<v8::Context>();
  174. new(&c->global_template) v8::Persistent<v8::FunctionTemplate>();
  175. new(&c->array_tmpl) v8::Persistent<v8::FunctionTemplate>();
  176. new(&c->modules_stack) std::vector<char*>();
  177. new(&c->modules_loaded) std::map<char *, v8js_persistent_value_t, cmp_str>;
  178. new(&c->template_cache) std::map<const zend_string *,v8js_function_tmpl_t>();
  179. new(&c->accessor_list) std::vector<v8js_accessor_ctx *>();
  180. new(&c->weak_closures) std::map<v8js_function_tmpl_t *, v8js_persistent_obj_t>();
  181. new(&c->weak_objects) std::map<zend_object *, v8js_persistent_obj_t>();
  182. new(&c->call_impls) std::map<v8js_function_tmpl_t *, v8js_function_tmpl_t>();
  183. new(&c->method_tmpls) std::map<std::pair<zend_class_entry *, zend_function *>, v8js_function_tmpl_t>();
  184. new(&c->v8js_v8objects) std::list<v8js_v8object *>();
  185. new(&c->script_objects) std::vector<v8js_script *>();
  186. // @fixme following is const, run on startup
  187. v8js_object_handlers.offset = XtOffsetOf(struct v8js_ctx, std);
  188. v8js_object_handlers.free_obj = v8js_free_storage;
  189. c->average_object_size = 1024;
  190. return &c->std;
  191. }
  192. /* }}} */
  193. static void v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
  194. {
  195. if (location) {
  196. zend_error(E_WARNING, "Fatal V8 error in %s: %s", location, message);
  197. } else {
  198. zend_error(E_WARNING, "Fatal V8 error: %s", message);
  199. }
  200. }
  201. /* }}} */
  202. #define IS_MAGIC_FUNC(mname) \
  203. ((ZSTR_LEN(key) == sizeof(mname) - 1) && \
  204. !strncasecmp(ZSTR_VAL(key), mname, ZSTR_LEN(key)))
  205. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, string snapshot_blob]]])
  206. __construct for V8Js */
  207. static PHP_METHOD(V8Js, __construct)
  208. {
  209. zend_string *object_name = NULL;
  210. zval *vars_arr = NULL;
  211. zval *snapshot_blob = NULL;
  212. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(getThis())
  213. if (!c->context.IsEmpty()) {
  214. /* called __construct() twice, bail out */
  215. return;
  216. }
  217. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!az", &object_name, &vars_arr, &snapshot_blob) == FAILURE) {
  218. return;
  219. }
  220. /* Initialize V8 */
  221. v8js_v8_init();
  222. /* Throw PHP exception if uncaught exceptions exist */
  223. c->in_execution = 0;
  224. new (&c->create_params) v8::Isolate::CreateParams();
  225. #ifdef USE_INTERNAL_ALLOCATOR
  226. static ArrayBufferAllocator array_buffer_allocator;
  227. c->create_params.array_buffer_allocator = &array_buffer_allocator;
  228. #else
  229. c->create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  230. #endif
  231. new (&c->snapshot_blob) v8::StartupData();
  232. if (snapshot_blob) {
  233. if (Z_TYPE_P(snapshot_blob) == IS_STRING) {
  234. ZVAL_COPY(&c->zval_snapshot_blob, snapshot_blob);
  235. if (Z_STRLEN_P(snapshot_blob) > std::numeric_limits<int>::max()) {
  236. zend_throw_exception(php_ce_v8js_exception,
  237. "Snapshot size exceeds maximum supported length", 0);
  238. return;
  239. }
  240. c->snapshot_blob.data = Z_STRVAL_P(snapshot_blob);
  241. c->snapshot_blob.raw_size = static_cast<int>(Z_STRLEN_P(snapshot_blob));
  242. c->create_params.snapshot_blob = &c->snapshot_blob;
  243. } else {
  244. php_error_docref(NULL, E_WARNING, "Argument snapshot_blob expected to be of string type");
  245. }
  246. }
  247. c->isolate = v8::Isolate::New(c->create_params);
  248. c->isolate->SetData(0, c);
  249. c->time_limit = 0;
  250. c->time_limit_hit = false;
  251. c->memory_limit = 0;
  252. c->memory_limit_hit = false;
  253. ZVAL_NULL(&c->module_normaliser);
  254. ZVAL_NULL(&c->module_loader);
  255. // Isolate execution
  256. v8::Isolate *isolate = c->isolate;
  257. v8::Locker locker(isolate);
  258. v8::Isolate::Scope isolate_scope(isolate);
  259. /* Handle scope */
  260. v8::HandleScope handle_scope(isolate);
  261. /* Redirect fatal errors to PHP error handler */
  262. isolate->SetFatalErrorHandler(v8js_fatal_error_handler);
  263. /* Create global template for global object */
  264. // Now we are using multiple isolates this needs to be created for every context
  265. v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(c->isolate);
  266. c->global_template.Reset(isolate, global_template);
  267. /* Register builtin methods */
  268. v8js_register_methods(global_template, c);
  269. /* Create context */
  270. v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global_template);
  271. if (context.IsEmpty()) {
  272. zend_throw_exception(php_ce_v8js_exception, "Failed to create V8 context.", 0);
  273. return;
  274. }
  275. context->SetAlignedPointerInEmbedderData(1, c);
  276. context->Global()->Set(context, V8JS_SYM("global"), context->Global());
  277. c->context.Reset(isolate, context);
  278. /* Enter context */
  279. v8::Context::Scope context_scope(context);
  280. /* Create the PHP container object's function template */
  281. v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New(isolate, 0);
  282. /* Set class name for PHP object */
  283. zend_class_entry *ce = Z_OBJCE_P(getThis());
  284. if (ZSTR_LEN(ce->name) > std::numeric_limits<int>::max()) {
  285. zend_throw_exception(php_ce_v8js_exception,
  286. "PHP object class name exceeds maximum supported length", 0);
  287. return;
  288. }
  289. php_obj_t->SetClassName(V8JS_SYML(ZSTR_VAL(ce->name), static_cast<int>(ZSTR_LEN(ce->name))));
  290. /* Register Get accessor for passed variables */
  291. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  292. v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate);
  293. }
  294. /* Set name for the PHP JS object */
  295. v8::Local<v8::String> object_name_js;
  296. if (object_name && ZSTR_LEN(object_name)) {
  297. if (ZSTR_LEN(object_name) > std::numeric_limits<int>::max()) {
  298. zend_throw_exception(php_ce_v8js_exception,
  299. "PHP JS object class name exceeds maximum supported length", 0);
  300. return;
  301. }
  302. object_name_js = V8JS_ZSYM(object_name);
  303. }
  304. else {
  305. object_name_js = V8JS_SYM("PHP");
  306. }
  307. c->object_name.Reset(isolate, object_name_js);
  308. /* Add the PHP object into global object */
  309. php_obj_t->InstanceTemplate()->SetInternalFieldCount(2);
  310. v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance(context).ToLocalChecked();
  311. V8JS_GLOBAL(isolate)->DefineOwnProperty(context, object_name_js, php_obj, v8::ReadOnly);
  312. /* Export public property values */
  313. HashTable *properties = zend_std_get_properties(Z_OBJ_P(getThis()));
  314. zval *value;
  315. zend_string *member;
  316. ZEND_HASH_FOREACH_STR_KEY(properties, member) {
  317. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1);
  318. if(property_info &&
  319. property_info != ZEND_WRONG_PROPERTY_INFO &&
  320. (property_info->flags & ZEND_ACC_PUBLIC)) {
  321. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  322. zend_throw_exception(php_ce_v8js_exception,
  323. "Property name exceeds maximum supported length", 0);
  324. return;
  325. }
  326. v8::Local<v8::Name> key = V8JS_ZSYM(member);
  327. /* Write value to PHP JS object */
  328. value = OBJ_PROP(Z_OBJ_P(getThis()), property_info->offset);
  329. php_obj->DefineOwnProperty(context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  330. }
  331. } ZEND_HASH_FOREACH_END();
  332. /* Add pointer to zend object */
  333. php_obj->SetAlignedPointerInInternalField(1, Z_OBJ_P(getThis()));
  334. /* Export public methods */
  335. void *ptr;
  336. zend_string *key;
  337. ZEND_HASH_FOREACH_STR_KEY_PTR(&c->std.ce->function_table, key, ptr) {
  338. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  339. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  340. /* Allow only public methods */
  341. continue;
  342. }
  343. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  344. /* no __construct, __destruct(), or __clone() functions */
  345. continue;
  346. }
  347. /* hide (do not export) other PHP magic functions */
  348. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  349. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  350. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  351. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  352. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  353. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  354. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  355. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  356. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  357. IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME) ||
  358. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  359. continue;
  360. }
  361. const zend_function_entry *fe;
  362. for (fe = v8js_methods; fe->fname; fe ++) {
  363. if (strcmp(fe->fname, ZSTR_VAL(method_ptr->common.function_name)) == 0) {
  364. break;
  365. }
  366. }
  367. if(fe->fname) {
  368. /* Method belongs to \V8Js class itself, never export to V8, even if
  369. * it is overriden in a derived class. */
  370. continue;
  371. }
  372. if (ZSTR_LEN(method_ptr->common.function_name) > std::numeric_limits<int>::max()) {
  373. zend_throw_exception(php_ce_v8js_exception,
  374. "Method name exceeds maximum supported length", 0);
  375. return;
  376. }
  377. v8::Local<v8::String> method_name = V8JS_ZSYM(method_ptr->common.function_name);
  378. v8::Local<v8::FunctionTemplate> ft;
  379. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  380. v8::External::New((isolate), method_ptr));
  381. // @fixme add/check Signature v8::Signature::New((isolate), tmpl));
  382. v8js_function_tmpl_t *persistent_ft = &c->method_tmpls[std::make_pair(ce, method_ptr)];
  383. persistent_ft->Reset(isolate, ft);
  384. php_obj->CreateDataProperty(context, method_name, ft->GetFunction(context).ToLocalChecked());
  385. } ZEND_HASH_FOREACH_END();
  386. }
  387. /* }}} */
  388. /* {{{ proto V8JS::__sleep()
  389. */
  390. PHP_METHOD(V8Js, __sleep)
  391. {
  392. zend_throw_exception(php_ce_v8js_exception,
  393. "You cannot serialize or unserialize V8Js instances", 0);
  394. RETURN_FALSE;
  395. }
  396. /* }}} */
  397. /* {{{ proto V8JS::__wakeup()
  398. */
  399. PHP_METHOD(V8Js, __wakeup)
  400. {
  401. zend_throw_exception(php_ce_v8js_exception,
  402. "You cannot serialize or unserialize V8Js instances", 0);
  403. RETURN_FALSE;
  404. }
  405. /* }}} */
  406. static void v8js_compile_script(zval *this_ptr, const zend_string *str, const zend_string *identifier, v8js_script **ret)
  407. {
  408. v8js_script *res = NULL;
  409. V8JS_BEGIN_CTX(c, this_ptr)
  410. /* Catch JS exceptions */
  411. v8::TryCatch try_catch(isolate);
  412. /* Set script identifier */
  413. if (identifier && ZSTR_LEN(identifier) > std::numeric_limits<int>::max()) {
  414. zend_throw_exception(php_ce_v8js_exception,
  415. "Script identifier exceeds maximum supported length", 0);
  416. return;
  417. }
  418. v8::Local<v8::String> sname = identifier
  419. ? V8JS_ZSTR(identifier)
  420. : V8JS_SYM("V8Js::compileString()");
  421. v8::ScriptOrigin origin(sname);
  422. if (ZSTR_LEN(str) > std::numeric_limits<int>::max()) {
  423. zend_throw_exception(php_ce_v8js_exception,
  424. "Script source exceeds maximum supported length", 0);
  425. return;
  426. }
  427. v8::Local<v8::String> source = V8JS_ZSTR(str);
  428. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(v8::Local<v8::Context>::New(isolate, c->context), source, &origin);
  429. /* Compile errors? */
  430. if (script.IsEmpty()) {
  431. v8js_throw_script_exception(c->isolate, &try_catch);
  432. return;
  433. }
  434. res = (v8js_script *)emalloc(sizeof(v8js_script));
  435. res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script.ToLocalChecked());
  436. v8::String::Utf8Value _sname(isolate, sname);
  437. res->name = estrndup(ToCString(_sname), _sname.length());
  438. res->ctx = c;
  439. *ret = res;
  440. return;
  441. }
  442. static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, size_t memory_limit, zval **return_value)
  443. {
  444. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(this_ptr);
  445. if (res->ctx != c) {
  446. zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
  447. ZVAL_BOOL(*return_value, 0);
  448. return;
  449. }
  450. if (!c->in_execution && time_limit == 0) {
  451. time_limit = c->time_limit;
  452. }
  453. if (!c->in_execution && memory_limit == 0) {
  454. memory_limit = c->memory_limit;
  455. }
  456. /* std::function relies on its dtor to be executed, otherwise it leaks
  457. * some memory on bailout. */
  458. {
  459. std::function< v8::MaybeLocal<v8::Value>(v8::Isolate *) > v8_call = [c, res](v8::Isolate *isolate) {
  460. v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
  461. return script->Run(v8::Local<v8::Context>::New(isolate, c->context));
  462. };
  463. v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call);
  464. }
  465. if(V8JSG(fatal_error_abort)) {
  466. /* Check for fatal error marker possibly set by v8js_error_handler; just
  467. * rethrow the error since we're now out of V8. */
  468. zend_bailout();
  469. }
  470. }
  471. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  472. */
  473. static PHP_METHOD(V8Js, executeString)
  474. {
  475. zend_string *str = NULL, *identifier = NULL;
  476. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  477. v8js_script *res = NULL;
  478. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|S!lll", &str, &identifier, &flags, &time_limit, &memory_limit) == FAILURE) {
  479. return;
  480. }
  481. if (memory_limit < 0) {
  482. zend_throw_exception(php_ce_v8js_exception,
  483. "memory_limit must not be negative", 0);
  484. return;
  485. }
  486. v8js_compile_script(getThis(), str, identifier, &res);
  487. if (!res) {
  488. RETURN_FALSE;
  489. }
  490. zend_try {
  491. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  492. v8js_script_free(res);
  493. }
  494. zend_catch {
  495. v8js_script_free(res);
  496. zend_bailout();
  497. }
  498. zend_end_try()
  499. efree(res);
  500. }
  501. /* }}} */
  502. /* {{{ proto mixed V8Js::compileString(string script [, string identifier])
  503. */
  504. static PHP_METHOD(V8Js, compileString)
  505. {
  506. zend_string *str = NULL, *identifier = NULL;
  507. v8js_script *res = NULL;
  508. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|S", &str, &identifier) == FAILURE) {
  509. return;
  510. }
  511. v8js_compile_script(getThis(), str, identifier, &res);
  512. if (res) {
  513. RETVAL_RES(zend_register_resource(res, le_v8js_script));
  514. v8js_ctx *ctx;
  515. ctx = Z_V8JS_CTX_OBJ_P(getThis());
  516. ctx->script_objects.push_back(res);
  517. }
  518. }
  519. /* }}} */
  520. /* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
  521. */
  522. static PHP_METHOD(V8Js, executeScript)
  523. {
  524. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  525. zval *zscript;
  526. v8js_script *res;
  527. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
  528. return;
  529. }
  530. if (memory_limit < 0) {
  531. zend_throw_exception(php_ce_v8js_exception,
  532. "memory_limit must not be negative", 0);
  533. return;
  534. }
  535. if((res = (v8js_script *)zend_fetch_resource(Z_RES_P(zscript), PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script)) == NULL) {
  536. RETURN_FALSE;
  537. }
  538. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  539. }
  540. /* }}} */
  541. /* {{{ proto mixed V8Js::checkString(string script)
  542. */
  543. static PHP_METHOD(V8Js, checkString)
  544. {
  545. zend_string *str = NULL;
  546. zend_string *identifier = zend_string_init("V8Js::checkString()", 19, 0);
  547. v8js_script *res = NULL;
  548. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
  549. return;
  550. }
  551. v8js_compile_script(getThis(), str, identifier, &res);
  552. zend_string_release(identifier);
  553. if (!res) {
  554. RETURN_FALSE;
  555. }
  556. v8js_script_free(res);
  557. efree(res);
  558. RETURN_TRUE;
  559. }
  560. /* }}} */
  561. /* {{{ proto void V8Js::setModuleNormaliser(string base, string module_id)
  562. */
  563. static PHP_METHOD(V8Js, setModuleNormaliser)
  564. {
  565. v8js_ctx *c;
  566. zval *callable;
  567. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  568. return;
  569. }
  570. c = Z_V8JS_CTX_OBJ_P(getThis());
  571. ZVAL_COPY(&c->module_normaliser, callable);
  572. }
  573. /* }}} */
  574. /* {{{ proto void V8Js::setModuleLoader(string module)
  575. */
  576. static PHP_METHOD(V8Js, setModuleLoader)
  577. {
  578. v8js_ctx *c;
  579. zval *callable;
  580. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  581. return;
  582. }
  583. c = Z_V8JS_CTX_OBJ_P(getThis());
  584. ZVAL_COPY(&c->module_loader, callable);
  585. }
  586. /* }}} */
  587. /* {{{ proto void V8Js::setTimeLimit(int time_limit)
  588. */
  589. static PHP_METHOD(V8Js, setTimeLimit)
  590. {
  591. v8js_ctx *c;
  592. long time_limit = 0;
  593. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &time_limit) == FAILURE) {
  594. return;
  595. }
  596. c = Z_V8JS_CTX_OBJ_P(getThis());
  597. c->time_limit = time_limit;
  598. V8JSG(timer_mutex).lock();
  599. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  600. it != V8JSG(timer_stack).end(); it ++) {
  601. if((*it)->ctx == c && !(*it)->killed) {
  602. (*it)->time_limit = time_limit;
  603. // Calculate the time point when the time limit is exceeded
  604. std::chrono::milliseconds duration(time_limit);
  605. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  606. (*it)->time_point = from + duration;
  607. }
  608. }
  609. V8JSG(timer_mutex).unlock();
  610. if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
  611. /* If timer thread is not started already and we now impose a time limit
  612. * finally install the timer. */
  613. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  614. }
  615. }
  616. /* }}} */
  617. /* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
  618. */
  619. static PHP_METHOD(V8Js, setMemoryLimit)
  620. {
  621. v8js_ctx *c;
  622. long memory_limit = 0;
  623. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &memory_limit) == FAILURE) {
  624. return;
  625. }
  626. if (memory_limit < 0) {
  627. zend_throw_exception(php_ce_v8js_exception,
  628. "memory_limit must not be negative", 0);
  629. return;
  630. }
  631. c = Z_V8JS_CTX_OBJ_P(getThis());
  632. c->memory_limit = static_cast<size_t>(memory_limit);
  633. V8JSG(timer_mutex).lock();
  634. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  635. it != V8JSG(timer_stack).end(); it ++) {
  636. if((*it)->ctx == c && !(*it)->killed) {
  637. (*it)->memory_limit = static_cast<size_t>(memory_limit);
  638. }
  639. }
  640. V8JSG(timer_mutex).unlock();
  641. if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
  642. /* If timer thread is not started already and we now impose a memory limit
  643. * finally install the timer. */
  644. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  645. }
  646. }
  647. /* }}} */
  648. /* {{{ proto void V8Js::setAverageObjectSize(average_object_size)
  649. */
  650. static PHP_METHOD(V8Js, setAverageObjectSize)
  651. {
  652. v8js_ctx *c;
  653. long average_object_size = 0;
  654. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &average_object_size) == FAILURE) {
  655. return;
  656. }
  657. c = Z_V8JS_CTX_OBJ_P(getThis());
  658. c->average_object_size = average_object_size;
  659. }
  660. /* }}} */
  661. static void v8js_persistent_zval_ctor(zval *p) /* {{{ */
  662. {
  663. assert(Z_TYPE_P(p) == IS_STRING);
  664. Z_STR_P(p) = zend_string_dup(Z_STR_P(p), 1);
  665. }
  666. /* }}} */
  667. static void v8js_persistent_zval_dtor(zval *p) /* {{{ */
  668. {
  669. assert(Z_TYPE_P(p) == IS_STRING);
  670. if (!ZSTR_IS_INTERNED(Z_STR_P(p))) {
  671. free(Z_STR_P(p));
  672. }
  673. }
  674. /* }}} */
  675. static void v8js_script_free(v8js_script *res)
  676. {
  677. efree(res->name);
  678. delete res->script; // does Reset()
  679. }
  680. static void v8js_script_dtor(zend_resource *rsrc) /* {{{ */
  681. {
  682. v8js_script *res = (v8js_script *)rsrc->ptr;
  683. if (res) {
  684. if(res->ctx) {
  685. std::vector<v8js_script *>::iterator it = std::find(res->ctx->script_objects.begin(), res->ctx->script_objects.end(), res);
  686. res->ctx->script_objects.erase(it);
  687. }
  688. v8js_script_free(res);
  689. efree(res);
  690. }
  691. }
  692. /* }}} */
  693. /* ## Static methods ## */
  694. static v8::StartupData createSnapshotDataBlob(v8::SnapshotCreator *snapshot_creator, zend_string *str) /* {{{ */
  695. {
  696. v8::Isolate *isolate = snapshot_creator->GetIsolate();
  697. {
  698. v8::HandleScope scope(isolate);
  699. v8::Local<v8::Context> context = v8::Context::New(isolate);
  700. v8::Context::Scope context_scope(context);
  701. v8::TryCatch try_catch(isolate);
  702. v8::Local<v8::String> source = V8JS_ZSTR(str);
  703. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(context, source);
  704. if (script.IsEmpty() || script.ToLocalChecked()->Run(context).IsEmpty())
  705. {
  706. return {nullptr, 0};
  707. }
  708. snapshot_creator->SetDefaultContext(context);
  709. }
  710. return snapshot_creator->CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear);
  711. } /* }}} */
  712. /* {{{ proto string|bool V8Js::createSnapshot(string embed_source)
  713. */
  714. static PHP_METHOD(V8Js, createSnapshot)
  715. {
  716. zend_string *script;
  717. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &script) == FAILURE) {
  718. return;
  719. }
  720. if (!ZSTR_LEN(script)) {
  721. php_error_docref(NULL, E_WARNING, "Script cannot be empty");
  722. RETURN_FALSE;
  723. }
  724. /* Initialize V8, if not already done. */
  725. v8js_v8_init();
  726. v8::Isolate *isolate = v8::Isolate::Allocate();
  727. v8::SnapshotCreator snapshot_creator(isolate);
  728. v8::StartupData snapshot_blob = createSnapshotDataBlob(&snapshot_creator, script);
  729. if (!snapshot_blob.data) {
  730. php_error_docref(NULL, E_WARNING, "Failed to create V8 heap snapshot. Check $embed_source for errors.");
  731. RETURN_FALSE;
  732. }
  733. RETVAL_STRINGL(snapshot_blob.data, snapshot_blob.raw_size);
  734. delete[] snapshot_blob.data;
  735. }
  736. /* }}} */
  737. /* {{{ arginfo */
  738. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  739. ZEND_ARG_INFO(0, object_name)
  740. ZEND_ARG_INFO(0, variables)
  741. ZEND_ARG_INFO(0, snapshot_blob)
  742. ZEND_END_ARG_INFO()
  743. ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
  744. ZEND_END_ARG_INFO()
  745. ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
  746. ZEND_END_ARG_INFO()
  747. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  748. ZEND_ARG_INFO(0, script)
  749. ZEND_ARG_INFO(0, identifier)
  750. ZEND_ARG_INFO(0, flags)
  751. ZEND_ARG_INFO(0, time_limit)
  752. ZEND_ARG_INFO(0, memory_limit)
  753. ZEND_END_ARG_INFO()
  754. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
  755. ZEND_ARG_INFO(0, script)
  756. ZEND_ARG_INFO(0, identifier)
  757. ZEND_END_ARG_INFO()
  758. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
  759. ZEND_ARG_INFO(0, script)
  760. ZEND_ARG_INFO(0, flags)
  761. ZEND_ARG_INFO(0, time_limit)
  762. ZEND_ARG_INFO(0, memory_limit)
  763. ZEND_END_ARG_INFO()
  764. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  765. ZEND_ARG_INFO(0, script)
  766. ZEND_END_ARG_INFO()
  767. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmodulenormaliser, 0, 0, 2)
  768. ZEND_ARG_INFO(0, base)
  769. ZEND_ARG_INFO(0, module_id)
  770. ZEND_END_ARG_INFO()
  771. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  772. ZEND_ARG_INFO(0, callable)
  773. ZEND_END_ARG_INFO()
  774. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setaverageobjectsize, 0, 0, 1)
  775. ZEND_ARG_INFO(0, average_object_size)
  776. ZEND_END_ARG_INFO()
  777. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_createsnapshot, 0, 0, 1)
  778. ZEND_ARG_INFO(0, script)
  779. ZEND_END_ARG_INFO()
  780. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
  781. ZEND_ARG_INFO(0, time_limit)
  782. ZEND_END_ARG_INFO()
  783. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
  784. ZEND_ARG_INFO(0, memory_limit)
  785. ZEND_END_ARG_INFO()
  786. const zend_function_entry v8js_methods[] = { /* {{{ */
  787. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  788. PHP_ME(V8Js, __sleep, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  789. PHP_ME(V8Js, __wakeup, arginfo_v8js_wakeup, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  790. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  791. PHP_ME(V8Js, compileString, arginfo_v8js_compilestring, ZEND_ACC_PUBLIC)
  792. PHP_ME(V8Js, executeScript, arginfo_v8js_executescript, ZEND_ACC_PUBLIC)
  793. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  794. PHP_ME(V8Js, setModuleNormaliser, arginfo_v8js_setmodulenormaliser, ZEND_ACC_PUBLIC)
  795. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  796. PHP_ME(V8Js, setTimeLimit, arginfo_v8js_settimelimit, ZEND_ACC_PUBLIC)
  797. PHP_ME(V8Js, setMemoryLimit, arginfo_v8js_setmemorylimit, ZEND_ACC_PUBLIC)
  798. PHP_ME(V8Js, setAverageObjectSize, arginfo_v8js_setaverageobjectsize, ZEND_ACC_PUBLIC)
  799. PHP_ME(V8Js, createSnapshot, arginfo_v8js_createsnapshot, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  800. {NULL, NULL, NULL}
  801. };
  802. /* }}} */
  803. /* V8Js object handlers */
  804. static zval* v8js_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot) /* {{{ */
  805. {
  806. v8js_ctx *c = Z_V8JS_CTX_OBJ(object);
  807. V8JS_CTX_PROLOGUE_EX(c, value);
  808. /* Check whether member is public, if so, export to V8. */
  809. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1);
  810. if(!property_info ||
  811. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  812. (property_info->flags & ZEND_ACC_PUBLIC))) {
  813. /* Global PHP JS object */
  814. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  815. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  816. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  817. zend_throw_exception(php_ce_v8js_exception,
  818. "Property name exceeds maximum supported length", 0);
  819. return value;
  820. }
  821. /* Write value to PHP JS object */
  822. v8::Local<v8::Name> key = V8JS_SYML(ZSTR_VAL(member), static_cast<int>(ZSTR_LEN(member)));
  823. jsobj->DefineOwnProperty(v8_context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  824. }
  825. /* Write value to PHP object */
  826. return std_object_handlers.write_property(object, member, value, NULL);
  827. }
  828. /* }}} */
  829. static void v8js_unset_property(zend_object *object, zend_string *member, void **cache_slot) /* {{{ */
  830. {
  831. V8JS_BEGIN_CTX_OBJ(c, object);
  832. /* Global PHP JS object */
  833. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  834. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  835. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  836. zend_throw_exception(php_ce_v8js_exception,
  837. "Property name exceeds maximum supported length", 0);
  838. return;
  839. }
  840. /* Delete value from PHP JS object */
  841. v8::Local<v8::Value> key = V8JS_SYML(ZSTR_VAL(member), static_cast<int>(ZSTR_LEN(member)));
  842. jsobj->Delete(v8_context, key);
  843. /* Unset from PHP object */
  844. std_object_handlers.unset_property(object, member, NULL);
  845. }
  846. /* }}} */
  847. PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
  848. {
  849. zend_class_entry ce;
  850. /* V8Js Class */
  851. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  852. php_ce_v8js = zend_register_internal_class(&ce);
  853. php_ce_v8js->create_object = v8js_new;
  854. /* V8Js handlers */
  855. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  856. v8js_object_handlers.clone_obj = NULL;
  857. v8js_object_handlers.write_property = v8js_write_property;
  858. v8js_object_handlers.unset_property = v8js_unset_property;
  859. /* V8Js Class Constants */
  860. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION);
  861. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE);
  862. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY);
  863. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_PROPAGATE_PHP_EXCEPTIONS"), V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS);
  864. le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
  865. return SUCCESS;
  866. } /* }}} */
  867. /*
  868. * Local variables:
  869. * tab-width: 4
  870. * c-basic-offset: 4
  871. * indent-tabs-mode: t
  872. * End:
  873. * vim600: noet sw=4 ts=4 fdm=marker
  874. * vim<600: noet sw=4 ts=4
  875. */