v8js_class.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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. /* {{{ Extension container */
  51. struct v8js_jsext {
  52. zend_bool auto_enable;
  53. HashTable *deps_ht;
  54. const char **deps;
  55. int deps_count;
  56. zend_string *name;
  57. zend_string *source;
  58. };
  59. /* }}} */
  60. #ifdef USE_INTERNAL_ALLOCATOR
  61. class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
  62. public:
  63. virtual void* Allocate(size_t length) {
  64. void* data = AllocateUninitialized(length);
  65. return data == NULL ? data : memset(data, 0, length);
  66. }
  67. virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
  68. virtual void Free(void* data, size_t) { free(data); }
  69. };
  70. #endif /** USE_INTERNAL_ALLOCATOR */
  71. static void v8js_free_storage(zend_object *object) /* {{{ */
  72. {
  73. v8js_ctx *c = v8js_ctx_fetch_object(object);
  74. zend_object_std_dtor(&c->std);
  75. zval_ptr_dtor(&c->pending_exception);
  76. zval_ptr_dtor(&c->module_normaliser);
  77. zval_ptr_dtor(&c->module_loader);
  78. /* Delete PHP global object from JavaScript */
  79. if (!c->context.IsEmpty()) {
  80. v8::Locker locker(c->isolate);
  81. v8::Isolate::Scope isolate_scope(c->isolate);
  82. v8::HandleScope handle_scope(c->isolate);
  83. v8::Local<v8::Context> v8_context = v8::Local<v8::Context>::New(c->isolate, c->context);
  84. v8::Context::Scope context_scope(v8_context);
  85. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(c->isolate, c->object_name);
  86. V8JS_GLOBAL(c->isolate)->Delete(v8_context, object_name_js);
  87. }
  88. c->object_name.Reset();
  89. c->object_name.~Persistent();
  90. c->global_template.Reset();
  91. c->global_template.~Persistent();
  92. c->array_tmpl.Reset();
  93. c->array_tmpl.~Persistent();
  94. /* Clear persistent call_impl & method_tmpls templates */
  95. for (std::map<v8js_function_tmpl_t *, v8js_function_tmpl_t>::iterator it = c->call_impls.begin();
  96. it != c->call_impls.end(); ++it) {
  97. // No need to free it->first, as it is stored in c->template_cache and freed below
  98. it->second.Reset();
  99. }
  100. c->call_impls.~map();
  101. for (std::map<std::pair<zend_class_entry *, zend_function *>, v8js_function_tmpl_t>::iterator it = c->method_tmpls.begin();
  102. it != c->method_tmpls.end(); ++it) {
  103. it->second.Reset();
  104. }
  105. c->method_tmpls.~map();
  106. /* Clear persistent handles in template cache */
  107. for (std::map<const zend_string *,v8js_function_tmpl_t>::iterator it = c->template_cache.begin();
  108. it != c->template_cache.end(); ++it) {
  109. it->second.Reset();
  110. }
  111. c->template_cache.~map();
  112. /* Clear contexts */
  113. for (std::vector<v8js_accessor_ctx*>::iterator it = c->accessor_list.begin();
  114. it != c->accessor_list.end(); ++it) {
  115. v8js_accessor_ctx_dtor(*it);
  116. }
  117. c->accessor_list.~vector();
  118. /* Clear global object, dispose context */
  119. if (!c->context.IsEmpty()) {
  120. c->context.Reset();
  121. }
  122. c->context.~Persistent();
  123. /* Dispose yet undisposed weak refs */
  124. for (std::map<zend_object *, v8js_persistent_obj_t>::iterator it = c->weak_objects.begin();
  125. it != c->weak_objects.end(); ++it) {
  126. zend_object *object = it->first;
  127. zval value;
  128. ZVAL_OBJ(&value, object);
  129. zval_ptr_dtor(&value);
  130. c->isolate->AdjustAmountOfExternalAllocatedMemory(-c->average_object_size);
  131. it->second.Reset();
  132. }
  133. c->weak_objects.~map();
  134. for (std::map<v8js_function_tmpl_t *, v8js_persistent_obj_t>::iterator it = c->weak_closures.begin();
  135. it != c->weak_closures.end(); ++it) {
  136. v8js_function_tmpl_t *persist_tpl_ = it->first;
  137. persist_tpl_->Reset();
  138. delete persist_tpl_;
  139. it->second.Reset();
  140. }
  141. c->weak_closures.~map();
  142. for (std::list<v8js_v8object *>::iterator it = c->v8js_v8objects.begin();
  143. it != c->v8js_v8objects.end(); it ++) {
  144. (*it)->v8obj.Reset();
  145. (*it)->ctx = NULL;
  146. }
  147. c->v8js_v8objects.~list();
  148. for (std::vector<v8js_script *>::iterator it = c->script_objects.begin();
  149. it != c->script_objects.end(); it ++) {
  150. (*it)->ctx = NULL;
  151. (*it)->script->Reset();
  152. }
  153. c->script_objects.~vector();
  154. /* Clear persistent handles in module cache */
  155. for (std::map<char *, v8js_persistent_value_t>::iterator it = c->modules_loaded.begin();
  156. it != c->modules_loaded.end(); ++it) {
  157. efree(it->first);
  158. it->second.Reset();
  159. }
  160. c->modules_loaded.~map();
  161. if(c->isolate) {
  162. /* c->isolate is initialized by V8Js::__construct, but __wakeup calls
  163. * are not fully constructed and hence this would cause a NPE. */
  164. c->isolate->Dispose();
  165. }
  166. if(c->tz != NULL) {
  167. free(c->tz);
  168. }
  169. c->modules_stack.~vector();
  170. zval_ptr_dtor(&c->zval_snapshot_blob);
  171. #ifndef USE_INTERNAL_ALLOCATOR
  172. delete c->create_params.array_buffer_allocator;
  173. #endif
  174. }
  175. /* }}} */
  176. static zend_object* v8js_new(zend_class_entry *ce) /* {{{ */
  177. {
  178. v8js_ctx *c;
  179. c = (v8js_ctx *) ecalloc(1, sizeof(*c) + zend_object_properties_size(ce));
  180. zend_object_std_init(&c->std, ce);
  181. object_properties_init(&c->std, ce);
  182. c->std.handlers = &v8js_object_handlers;
  183. new(&c->object_name) v8::Persistent<v8::String>();
  184. new(&c->context) v8::Persistent<v8::Context>();
  185. new(&c->global_template) v8::Persistent<v8::FunctionTemplate>();
  186. new(&c->array_tmpl) v8::Persistent<v8::FunctionTemplate>();
  187. new(&c->modules_stack) std::vector<char*>();
  188. new(&c->modules_loaded) std::map<char *, v8js_persistent_value_t, cmp_str>;
  189. new(&c->template_cache) std::map<const zend_string *,v8js_function_tmpl_t>();
  190. new(&c->accessor_list) std::vector<v8js_accessor_ctx *>();
  191. new(&c->weak_closures) std::map<v8js_function_tmpl_t *, v8js_persistent_obj_t>();
  192. new(&c->weak_objects) std::map<zend_object *, v8js_persistent_obj_t>();
  193. new(&c->call_impls) std::map<v8js_function_tmpl_t *, v8js_function_tmpl_t>();
  194. new(&c->method_tmpls) std::map<std::pair<zend_class_entry *, zend_function *>, v8js_function_tmpl_t>();
  195. new(&c->v8js_v8objects) std::list<v8js_v8object *>();
  196. new(&c->script_objects) std::vector<v8js_script *>();
  197. // @fixme following is const, run on startup
  198. v8js_object_handlers.offset = XtOffsetOf(struct v8js_ctx, std);
  199. v8js_object_handlers.free_obj = v8js_free_storage;
  200. c->average_object_size = 1024;
  201. return &c->std;
  202. }
  203. /* }}} */
  204. static void v8js_free_ext_strarr(const char **arr, int count) /* {{{ */
  205. {
  206. int i;
  207. if (arr) {
  208. for (i = 0; i < count; i++) {
  209. if (arr[i]) {
  210. free((void *) arr[i]);
  211. }
  212. }
  213. free(arr);
  214. }
  215. }
  216. /* }}} */
  217. static void v8js_jsext_free_storage(v8js_jsext *jsext) /* {{{ */
  218. {
  219. if (jsext->deps_ht) {
  220. zend_hash_destroy(jsext->deps_ht);
  221. free(jsext->deps_ht);
  222. }
  223. if (jsext->deps) {
  224. v8js_free_ext_strarr(jsext->deps, jsext->deps_count);
  225. }
  226. // Free the persisted non-interned strings we allocated.
  227. if (jsext->name) {
  228. zend_string_release(jsext->name);
  229. }
  230. if (jsext->source) {
  231. zend_string_release(jsext->source);
  232. }
  233. free(jsext);
  234. }
  235. /* }}} */
  236. static void v8js_jsext_dtor(zval *zv) /* {{{ */
  237. {
  238. v8js_jsext_free_storage(reinterpret_cast<v8js_jsext *>(Z_PTR_P(zv)));
  239. }
  240. /* }}} */
  241. static int v8js_create_ext_strarr(const char ***retval, int count, HashTable *ht) /* {{{ */
  242. {
  243. const char **exts = NULL;
  244. HashPosition pos;
  245. zval *tmp;
  246. int i = 0;
  247. exts = (const char **) calloc(1, count * sizeof(char *));
  248. zend_hash_internal_pointer_reset_ex(ht, &pos);
  249. while ((tmp = zend_hash_get_current_data_ex(ht, &pos))) {
  250. if (Z_TYPE_P(tmp) == IS_STRING) {
  251. exts[i++] = zend_strndup(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
  252. } else {
  253. v8js_free_ext_strarr(exts, i);
  254. return FAILURE;
  255. }
  256. zend_hash_move_forward_ex(ht, &pos);
  257. }
  258. *retval = exts;
  259. return SUCCESS;
  260. }
  261. /* }}} */
  262. static void v8js_fatal_error_handler(const char *location, const char *message) /* {{{ */
  263. {
  264. if (location) {
  265. zend_error(E_WARNING, "Fatal V8 error in %s: %s", location, message);
  266. } else {
  267. zend_error(E_WARNING, "Fatal V8 error: %s", message);
  268. }
  269. }
  270. /* }}} */
  271. #define IS_MAGIC_FUNC(mname) \
  272. ((ZSTR_LEN(key) == sizeof(mname) - 1) && \
  273. !strncasecmp(ZSTR_VAL(key), mname, ZSTR_LEN(key)))
  274. /* {{{ proto void V8Js::__construct([string object_name [, array variables [, array extensions [, bool report_uncaught_exceptions [, string snapshot_blob]]]]])
  275. __construct for V8Js */
  276. static PHP_METHOD(V8Js, __construct)
  277. {
  278. zend_string *object_name = NULL;
  279. zend_bool report_uncaught = 1;
  280. zval *vars_arr = NULL, *exts_arr = NULL;
  281. const char **exts = NULL;
  282. int exts_count = 0;
  283. zval *snapshot_blob = NULL;
  284. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(getThis())
  285. if (!c->context.IsEmpty()) {
  286. /* called __construct() twice, bail out */
  287. return;
  288. }
  289. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|Saabz", &object_name, &vars_arr, &exts_arr, &report_uncaught, &snapshot_blob) == FAILURE) {
  290. return;
  291. }
  292. /* Initialize V8 */
  293. v8js_v8_init();
  294. /* Throw PHP exception if uncaught exceptions exist */
  295. c->report_uncaught = report_uncaught;
  296. ZVAL_NULL(&c->pending_exception);
  297. c->in_execution = 0;
  298. if (report_uncaught != 1) {
  299. php_error_docref(NULL, E_DEPRECATED, "Disabling exception reporting is deprecated, $report_uncaught_exceptions != true");
  300. }
  301. new (&c->create_params) v8::Isolate::CreateParams();
  302. #ifdef USE_INTERNAL_ALLOCATOR
  303. static ArrayBufferAllocator array_buffer_allocator;
  304. c->create_params.array_buffer_allocator = &array_buffer_allocator;
  305. #else
  306. c->create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  307. #endif
  308. new (&c->snapshot_blob) v8::StartupData();
  309. if (snapshot_blob) {
  310. if (Z_TYPE_P(snapshot_blob) == IS_STRING) {
  311. ZVAL_COPY(&c->zval_snapshot_blob, snapshot_blob);
  312. if (Z_STRLEN_P(snapshot_blob) > std::numeric_limits<int>::max()) {
  313. zend_throw_exception(php_ce_v8js_exception,
  314. "Snapshot size exceeds maximum supported length", 0);
  315. return;
  316. }
  317. c->snapshot_blob.data = Z_STRVAL_P(snapshot_blob);
  318. c->snapshot_blob.raw_size = static_cast<int>(Z_STRLEN_P(snapshot_blob));
  319. c->create_params.snapshot_blob = &c->snapshot_blob;
  320. } else {
  321. php_error_docref(NULL, E_WARNING, "Argument snapshot_blob expected to be of string type");
  322. }
  323. }
  324. c->isolate = v8::Isolate::New(c->create_params);
  325. c->isolate->SetData(0, c);
  326. c->time_limit = 0;
  327. c->time_limit_hit = false;
  328. c->memory_limit = 0;
  329. c->memory_limit_hit = false;
  330. ZVAL_NULL(&c->module_normaliser);
  331. ZVAL_NULL(&c->module_loader);
  332. /* Include extensions used by this context */
  333. /* Note: Extensions registered with auto_enable do not need to be added separately like this. */
  334. if (exts_arr)
  335. {
  336. exts_count = zend_hash_num_elements(Z_ARRVAL_P(exts_arr));
  337. if (exts_count != 0) {
  338. php_error_docref(NULL, E_DEPRECATED, "Use of extensions is deprecated, $extensions array passed");
  339. }
  340. if (v8js_create_ext_strarr(&exts, exts_count, Z_ARRVAL_P(exts_arr)) == FAILURE) {
  341. zend_throw_exception(php_ce_v8js_exception,
  342. "Invalid extensions array passed", 0);
  343. return;
  344. }
  345. }
  346. /* Declare configuration for extensions */
  347. v8::ExtensionConfiguration extension_conf(exts_count, exts);
  348. // Isolate execution
  349. v8::Isolate *isolate = c->isolate;
  350. v8::Locker locker(isolate);
  351. v8::Isolate::Scope isolate_scope(isolate);
  352. /* Handle scope */
  353. v8::HandleScope handle_scope(isolate);
  354. /* Redirect fatal errors to PHP error handler */
  355. isolate->SetFatalErrorHandler(v8js_fatal_error_handler);
  356. /* Create global template for global object */
  357. // Now we are using multiple isolates this needs to be created for every context
  358. v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(c->isolate);
  359. c->global_template.Reset(isolate, global_template);
  360. /* Register builtin methods */
  361. v8js_register_methods(global_template, c);
  362. /* Create context */
  363. v8::Local<v8::Context> context = v8::Context::New(isolate, &extension_conf, global_template);
  364. if (exts) {
  365. v8js_free_ext_strarr(exts, exts_count);
  366. }
  367. /* If extensions have errors, context will be empty. (NOTE: This is V8 stuff, they expect the passed sources to compile :) */
  368. if (context.IsEmpty()) {
  369. zend_throw_exception(php_ce_v8js_exception,
  370. "Failed to create V8 context. "
  371. "Check that registered extensions do not have errors.", 0);
  372. return;
  373. }
  374. context->SetAlignedPointerInEmbedderData(1, c);
  375. context->Global()->Set(context, V8JS_SYM("global"), context->Global());
  376. c->context.Reset(isolate, context);
  377. /* Enter context */
  378. v8::Context::Scope context_scope(context);
  379. /* Create the PHP container object's function template */
  380. v8::Local<v8::FunctionTemplate> php_obj_t = v8::FunctionTemplate::New(isolate, 0);
  381. /* Set class name for PHP object */
  382. zend_class_entry *ce = Z_OBJCE_P(getThis());
  383. if (ZSTR_LEN(ce->name) > std::numeric_limits<int>::max()) {
  384. zend_throw_exception(php_ce_v8js_exception,
  385. "PHP object class name exceeds maximum supported length", 0);
  386. return;
  387. }
  388. php_obj_t->SetClassName(V8JS_SYML(ZSTR_VAL(ce->name), static_cast<int>(ZSTR_LEN(ce->name))));
  389. /* Register Get accessor for passed variables */
  390. if (vars_arr && zend_hash_num_elements(Z_ARRVAL_P(vars_arr)) > 0) {
  391. v8js_register_accessors(&c->accessor_list, php_obj_t, vars_arr, isolate);
  392. }
  393. /* Set name for the PHP JS object */
  394. v8::Local<v8::String> object_name_js;
  395. if (object_name && ZSTR_LEN(object_name)) {
  396. if (ZSTR_LEN(object_name) > std::numeric_limits<int>::max()) {
  397. zend_throw_exception(php_ce_v8js_exception,
  398. "PHP JS object class name exceeds maximum supported length", 0);
  399. return;
  400. }
  401. object_name_js = V8JS_ZSYM(object_name);
  402. }
  403. else {
  404. object_name_js = V8JS_SYM("PHP");
  405. }
  406. c->object_name.Reset(isolate, object_name_js);
  407. /* Add the PHP object into global object */
  408. php_obj_t->InstanceTemplate()->SetInternalFieldCount(2);
  409. v8::Local<v8::Object> php_obj = php_obj_t->InstanceTemplate()->NewInstance(context).ToLocalChecked();
  410. V8JS_GLOBAL(isolate)->DefineOwnProperty(context, object_name_js, php_obj, v8::ReadOnly);
  411. /* Export public property values */
  412. #if (PHP_MAJOR_VERSION < 8)
  413. HashTable *properties = zend_std_get_properties(getThis());
  414. #else
  415. HashTable *properties = zend_std_get_properties(Z_OBJ_P(getThis()));
  416. #endif
  417. zval *value;
  418. zend_string *member;
  419. ZEND_HASH_FOREACH_STR_KEY(properties, member) {
  420. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1);
  421. if(property_info &&
  422. property_info != ZEND_WRONG_PROPERTY_INFO &&
  423. (property_info->flags & ZEND_ACC_PUBLIC)) {
  424. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  425. zend_throw_exception(php_ce_v8js_exception,
  426. "Property name exceeds maximum supported length", 0);
  427. return;
  428. }
  429. v8::Local<v8::Name> key = V8JS_ZSYM(member);
  430. /* Write value to PHP JS object */
  431. value = OBJ_PROP(Z_OBJ_P(getThis()), property_info->offset);
  432. php_obj->DefineOwnProperty(context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  433. }
  434. } ZEND_HASH_FOREACH_END();
  435. /* Add pointer to zend object */
  436. php_obj->SetAlignedPointerInInternalField(1, Z_OBJ_P(getThis()));
  437. /* Export public methods */
  438. void *ptr;
  439. zend_string *key;
  440. ZEND_HASH_FOREACH_STR_KEY_PTR(&c->std.ce->function_table, key, ptr) {
  441. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  442. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  443. /* Allow only public methods */
  444. continue;
  445. }
  446. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  447. /* no __construct, __destruct(), or __clone() functions */
  448. continue;
  449. }
  450. /* hide (do not export) other PHP magic functions */
  451. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  452. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  453. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  454. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  455. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  456. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  457. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  458. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  459. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  460. IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME) ||
  461. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  462. continue;
  463. }
  464. const zend_function_entry *fe;
  465. for (fe = v8js_methods; fe->fname; fe ++) {
  466. if (strcmp(fe->fname, ZSTR_VAL(method_ptr->common.function_name)) == 0) {
  467. break;
  468. }
  469. }
  470. if(fe->fname) {
  471. /* Method belongs to \V8Js class itself, never export to V8, even if
  472. * it is overriden in a derived class. */
  473. continue;
  474. }
  475. if (ZSTR_LEN(method_ptr->common.function_name) > std::numeric_limits<int>::max()) {
  476. zend_throw_exception(php_ce_v8js_exception,
  477. "Method name exceeds maximum supported length", 0);
  478. return;
  479. }
  480. v8::Local<v8::String> method_name = V8JS_ZSYM(method_ptr->common.function_name);
  481. v8::Local<v8::FunctionTemplate> ft;
  482. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  483. v8::External::New((isolate), method_ptr));
  484. // @fixme add/check Signature v8::Signature::New((isolate), tmpl));
  485. v8js_function_tmpl_t *persistent_ft = &c->method_tmpls[std::make_pair(ce, method_ptr)];
  486. persistent_ft->Reset(isolate, ft);
  487. php_obj->CreateDataProperty(context, method_name, ft->GetFunction(context).ToLocalChecked());
  488. } ZEND_HASH_FOREACH_END();
  489. }
  490. /* }}} */
  491. /* {{{ proto V8JS::__sleep()
  492. */
  493. PHP_METHOD(V8Js, __sleep)
  494. {
  495. zend_throw_exception(php_ce_v8js_exception,
  496. "You cannot serialize or unserialize V8Js instances", 0);
  497. RETURN_FALSE;
  498. }
  499. /* }}} */
  500. /* {{{ proto V8JS::__wakeup()
  501. */
  502. PHP_METHOD(V8Js, __wakeup)
  503. {
  504. zend_throw_exception(php_ce_v8js_exception,
  505. "You cannot serialize or unserialize V8Js instances", 0);
  506. RETURN_FALSE;
  507. }
  508. /* }}} */
  509. static void v8js_compile_script(zval *this_ptr, const zend_string *str, const zend_string *identifier, v8js_script **ret)
  510. {
  511. v8js_script *res = NULL;
  512. V8JS_BEGIN_CTX(c, this_ptr)
  513. /* Catch JS exceptions */
  514. v8::TryCatch try_catch(isolate);
  515. /* Set script identifier */
  516. if (identifier && ZSTR_LEN(identifier) > std::numeric_limits<int>::max()) {
  517. zend_throw_exception(php_ce_v8js_exception,
  518. "Script identifier exceeds maximum supported length", 0);
  519. return;
  520. }
  521. v8::Local<v8::String> sname = identifier
  522. ? V8JS_ZSTR(identifier)
  523. : V8JS_SYM("V8Js::compileString()");
  524. v8::ScriptOrigin origin(sname);
  525. if (ZSTR_LEN(str) > std::numeric_limits<int>::max()) {
  526. zend_throw_exception(php_ce_v8js_exception,
  527. "Script source exceeds maximum supported length", 0);
  528. return;
  529. }
  530. v8::Local<v8::String> source = V8JS_ZSTR(str);
  531. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(v8::Local<v8::Context>::New(isolate, c->context), source, &origin);
  532. /* Compile errors? */
  533. if (script.IsEmpty()) {
  534. v8js_throw_script_exception(c->isolate, &try_catch);
  535. return;
  536. }
  537. res = (v8js_script *)emalloc(sizeof(v8js_script));
  538. res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script.ToLocalChecked());
  539. v8::String::Utf8Value _sname(isolate, sname);
  540. res->name = estrndup(ToCString(_sname), _sname.length());
  541. res->ctx = c;
  542. *ret = res;
  543. return;
  544. }
  545. static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, size_t memory_limit, zval **return_value)
  546. {
  547. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(this_ptr);
  548. if (res->ctx != c) {
  549. zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
  550. ZVAL_BOOL(*return_value, 0);
  551. return;
  552. }
  553. if (!c->in_execution && time_limit == 0) {
  554. time_limit = c->time_limit;
  555. }
  556. if (!c->in_execution && memory_limit == 0) {
  557. memory_limit = c->memory_limit;
  558. }
  559. /* std::function relies on its dtor to be executed, otherwise it leaks
  560. * some memory on bailout. */
  561. {
  562. std::function< v8::MaybeLocal<v8::Value>(v8::Isolate *) > v8_call = [c, res](v8::Isolate *isolate) {
  563. v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
  564. return script->Run(v8::Local<v8::Context>::New(isolate, c->context));
  565. };
  566. v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call);
  567. }
  568. if(V8JSG(fatal_error_abort)) {
  569. /* Check for fatal error marker possibly set by v8js_error_handler; just
  570. * rethrow the error since we're now out of V8. */
  571. zend_bailout();
  572. }
  573. }
  574. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  575. */
  576. static PHP_METHOD(V8Js, executeString)
  577. {
  578. zend_string *str = NULL, *identifier = NULL;
  579. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  580. v8js_script *res = NULL;
  581. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|Slll", &str, &identifier, &flags, &time_limit, &memory_limit) == FAILURE) {
  582. return;
  583. }
  584. if (memory_limit < 0) {
  585. zend_throw_exception(php_ce_v8js_exception,
  586. "memory_limit must not be negative", 0);
  587. return;
  588. }
  589. v8js_compile_script(getThis(), str, identifier, &res);
  590. if (!res) {
  591. RETURN_FALSE;
  592. }
  593. zend_try {
  594. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  595. v8js_script_free(res);
  596. }
  597. zend_catch {
  598. v8js_script_free(res);
  599. zend_bailout();
  600. }
  601. zend_end_try()
  602. efree(res);
  603. }
  604. /* }}} */
  605. /* {{{ proto mixed V8Js::compileString(string script [, string identifier])
  606. */
  607. static PHP_METHOD(V8Js, compileString)
  608. {
  609. zend_string *str = NULL, *identifier = NULL;
  610. v8js_script *res = NULL;
  611. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|S", &str, &identifier) == FAILURE) {
  612. return;
  613. }
  614. v8js_compile_script(getThis(), str, identifier, &res);
  615. if (res) {
  616. RETVAL_RES(zend_register_resource(res, le_v8js_script));
  617. v8js_ctx *ctx;
  618. ctx = Z_V8JS_CTX_OBJ_P(getThis());
  619. ctx->script_objects.push_back(res);
  620. }
  621. }
  622. /* }}} */
  623. /* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
  624. */
  625. static PHP_METHOD(V8Js, executeScript)
  626. {
  627. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  628. zval *zscript;
  629. v8js_script *res;
  630. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
  631. return;
  632. }
  633. if (memory_limit < 0) {
  634. zend_throw_exception(php_ce_v8js_exception,
  635. "memory_limit must not be negative", 0);
  636. return;
  637. }
  638. if((res = (v8js_script *)zend_fetch_resource(Z_RES_P(zscript), PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script)) == NULL) {
  639. RETURN_FALSE;
  640. }
  641. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  642. }
  643. /* }}} */
  644. /* {{{ proto mixed V8Js::checkString(string script)
  645. */
  646. static PHP_METHOD(V8Js, checkString)
  647. {
  648. zend_string *str = NULL;
  649. zend_string *identifier = zend_string_init("V8Js::checkString()", 19, 0);
  650. v8js_script *res = NULL;
  651. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
  652. return;
  653. }
  654. v8js_compile_script(getThis(), str, identifier, &res);
  655. zend_string_release(identifier);
  656. if (!res) {
  657. RETURN_FALSE;
  658. }
  659. v8js_script_free(res);
  660. efree(res);
  661. RETURN_TRUE;
  662. }
  663. /* }}} */
  664. /* {{{ proto mixed V8Js::getPendingException()
  665. */
  666. static PHP_METHOD(V8Js, getPendingException)
  667. {
  668. v8js_ctx *c;
  669. if (zend_parse_parameters_none() == FAILURE) {
  670. return;
  671. }
  672. c = Z_V8JS_CTX_OBJ_P(getThis());
  673. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  674. RETURN_ZVAL(&c->pending_exception, 1, 0);
  675. }
  676. }
  677. /* }}} */
  678. /* {{{ proto void V8Js::clearPendingException()
  679. */
  680. static PHP_METHOD(V8Js, clearPendingException)
  681. {
  682. v8js_ctx *c;
  683. if (zend_parse_parameters_none() == FAILURE) {
  684. return;
  685. }
  686. c = Z_V8JS_CTX_OBJ_P(getThis());
  687. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  688. zval_ptr_dtor(&c->pending_exception);
  689. ZVAL_NULL(&c->pending_exception);
  690. }
  691. }
  692. /* }}} */
  693. /* {{{ proto void V8Js::setModuleNormaliser(string base, string module_id)
  694. */
  695. static PHP_METHOD(V8Js, setModuleNormaliser)
  696. {
  697. v8js_ctx *c;
  698. zval *callable;
  699. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  700. return;
  701. }
  702. c = Z_V8JS_CTX_OBJ_P(getThis());
  703. ZVAL_COPY(&c->module_normaliser, callable);
  704. }
  705. /* }}} */
  706. /* {{{ proto void V8Js::setModuleLoader(string module)
  707. */
  708. static PHP_METHOD(V8Js, setModuleLoader)
  709. {
  710. v8js_ctx *c;
  711. zval *callable;
  712. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  713. return;
  714. }
  715. c = Z_V8JS_CTX_OBJ_P(getThis());
  716. ZVAL_COPY(&c->module_loader, callable);
  717. }
  718. /* }}} */
  719. /* {{{ proto void V8Js::setTimeLimit(int time_limit)
  720. */
  721. static PHP_METHOD(V8Js, setTimeLimit)
  722. {
  723. v8js_ctx *c;
  724. long time_limit = 0;
  725. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &time_limit) == FAILURE) {
  726. return;
  727. }
  728. c = Z_V8JS_CTX_OBJ_P(getThis());
  729. c->time_limit = time_limit;
  730. V8JSG(timer_mutex).lock();
  731. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  732. it != V8JSG(timer_stack).end(); it ++) {
  733. if((*it)->ctx == c && !(*it)->killed) {
  734. (*it)->time_limit = time_limit;
  735. // Calculate the time point when the time limit is exceeded
  736. std::chrono::milliseconds duration(time_limit);
  737. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  738. (*it)->time_point = from + duration;
  739. }
  740. }
  741. V8JSG(timer_mutex).unlock();
  742. if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
  743. /* If timer thread is not started already and we now impose a time limit
  744. * finally install the timer. */
  745. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  746. }
  747. }
  748. /* }}} */
  749. /* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
  750. */
  751. static PHP_METHOD(V8Js, setMemoryLimit)
  752. {
  753. v8js_ctx *c;
  754. long memory_limit = 0;
  755. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &memory_limit) == FAILURE) {
  756. return;
  757. }
  758. if (memory_limit < 0) {
  759. zend_throw_exception(php_ce_v8js_exception,
  760. "memory_limit must not be negative", 0);
  761. return;
  762. }
  763. c = Z_V8JS_CTX_OBJ_P(getThis());
  764. c->memory_limit = static_cast<size_t>(memory_limit);
  765. V8JSG(timer_mutex).lock();
  766. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  767. it != V8JSG(timer_stack).end(); it ++) {
  768. if((*it)->ctx == c && !(*it)->killed) {
  769. (*it)->memory_limit = static_cast<size_t>(memory_limit);
  770. }
  771. }
  772. V8JSG(timer_mutex).unlock();
  773. if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
  774. /* If timer thread is not started already and we now impose a memory limit
  775. * finally install the timer. */
  776. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  777. }
  778. }
  779. /* }}} */
  780. /* {{{ proto void V8Js::setAverageObjectSize(average_object_size)
  781. */
  782. static PHP_METHOD(V8Js, setAverageObjectSize)
  783. {
  784. v8js_ctx *c;
  785. long average_object_size = 0;
  786. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &average_object_size) == FAILURE) {
  787. return;
  788. }
  789. c = Z_V8JS_CTX_OBJ_P(getThis());
  790. c->average_object_size = average_object_size;
  791. }
  792. /* }}} */
  793. static void v8js_persistent_zval_ctor(zval *p) /* {{{ */
  794. {
  795. assert(Z_TYPE_P(p) == IS_STRING);
  796. Z_STR_P(p) = zend_string_dup(Z_STR_P(p), 1);
  797. }
  798. /* }}} */
  799. static void v8js_persistent_zval_dtor(zval *p) /* {{{ */
  800. {
  801. assert(Z_TYPE_P(p) == IS_STRING);
  802. if (!ZSTR_IS_INTERNED(Z_STR_P(p))) {
  803. free(Z_STR_P(p));
  804. }
  805. }
  806. /* }}} */
  807. static void v8js_script_free(v8js_script *res)
  808. {
  809. efree(res->name);
  810. delete res->script; // does Reset()
  811. }
  812. static void v8js_script_dtor(zend_resource *rsrc) /* {{{ */
  813. {
  814. v8js_script *res = (v8js_script *)rsrc->ptr;
  815. if (res) {
  816. if(res->ctx) {
  817. std::vector<v8js_script *>::iterator it = std::find(res->ctx->script_objects.begin(), res->ctx->script_objects.end(), res);
  818. res->ctx->script_objects.erase(it);
  819. }
  820. v8js_script_free(res);
  821. efree(res);
  822. }
  823. }
  824. /* }}} */
  825. static int v8js_register_extension(zend_string *name, zend_string *source, zval *deps_arr, zend_bool auto_enable) /* {{{ */
  826. {
  827. v8js_jsext *jsext = NULL;
  828. #ifdef ZTS
  829. v8js_process_globals.lock.lock();
  830. #endif
  831. if (!v8js_process_globals.extensions) {
  832. v8js_process_globals.extensions = (HashTable *) malloc(sizeof(HashTable));
  833. zend_hash_init(v8js_process_globals.extensions, 1, NULL, v8js_jsext_dtor, 1);
  834. } else if (zend_hash_exists(v8js_process_globals.extensions, name)) {
  835. #ifdef ZTS
  836. v8js_process_globals.lock.unlock();
  837. #endif
  838. return FAILURE;
  839. }
  840. jsext = (v8js_jsext *) calloc(1, sizeof(v8js_jsext));
  841. if (deps_arr) {
  842. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  843. if (v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  844. php_error_docref(NULL, E_WARNING, "Invalid dependency array passed");
  845. v8js_jsext_free_storage(jsext);
  846. #ifdef ZTS
  847. v8js_process_globals.lock.unlock();
  848. #endif
  849. return FAILURE;
  850. }
  851. }
  852. jsext->auto_enable = auto_enable;
  853. // Allocate a persistent string which will survive until module shutdown on both ZTS(Persistent) and NTS(Not interned, those would be cleaned up)
  854. // (zend_string_dup would return the original interned string, if interned, so we don't use that)
  855. jsext->name = zend_string_init(ZSTR_VAL(name), ZSTR_LEN(name), 1);
  856. jsext->source = zend_string_init(ZSTR_VAL(source), ZSTR_LEN(source), 1);
  857. if (jsext->deps) {
  858. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  859. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, v8js_persistent_zval_dtor, 1);
  860. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), v8js_persistent_zval_ctor);
  861. }
  862. v8::Extension *extension = new v8::Extension(ZSTR_VAL(jsext->name), ZSTR_VAL(jsext->source), jsext->deps_count, jsext->deps);
  863. if (!zend_hash_add_ptr(v8js_process_globals.extensions, jsext->name, jsext)) {
  864. v8js_jsext_free_storage(jsext);
  865. #ifdef ZTS
  866. v8js_process_globals.lock.unlock();
  867. #endif
  868. return FAILURE;
  869. }
  870. #ifdef ZTS
  871. v8js_process_globals.lock.unlock();
  872. #endif
  873. extension->set_auto_enable(auto_enable ? true : false);
  874. v8::RegisterExtension(std::unique_ptr<v8::Extension>(extension));
  875. return SUCCESS;
  876. }
  877. /* }}} */
  878. /* ## Static methods ## */
  879. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  880. */
  881. static PHP_METHOD(V8Js, registerExtension)
  882. {
  883. zend_string *ext_name, *script;
  884. zval *deps_arr = NULL;
  885. zend_bool auto_enable = 0;
  886. if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS|ab", &ext_name, &script, &deps_arr, &auto_enable) == FAILURE) {
  887. return;
  888. }
  889. if (!ZSTR_LEN(ext_name)) {
  890. php_error_docref(NULL, E_WARNING, "Extension name cannot be empty");
  891. } else if (!ZSTR_LEN(script)) {
  892. php_error_docref(NULL, E_WARNING, "Script cannot be empty");
  893. } else if (v8js_register_extension(ext_name, script, deps_arr, auto_enable) == SUCCESS) {
  894. RETURN_TRUE;
  895. }
  896. RETURN_FALSE;
  897. }
  898. /* }}} */
  899. /* {{{ proto array V8Js::getExtensions()
  900. */
  901. static PHP_METHOD(V8Js, getExtensions)
  902. {
  903. v8js_jsext *jsext;
  904. zend_string *key;
  905. zval *val, ext;
  906. if (zend_parse_parameters_none() == FAILURE) {
  907. return;
  908. }
  909. array_init(return_value);
  910. #ifdef ZTS
  911. v8js_process_globals.lock.lock();
  912. #endif
  913. if (v8js_process_globals.extensions) {
  914. ZEND_HASH_FOREACH_STR_KEY_VAL(v8js_process_globals.extensions, key, val) {
  915. if (key) {
  916. jsext = (v8js_jsext *) Z_PTR_P(val);
  917. array_init(&ext);
  918. add_assoc_bool_ex(&ext, ZEND_STRL("auto_enable"), jsext->auto_enable);
  919. if (jsext->deps_ht) {
  920. zval deps_arr;
  921. array_init(&deps_arr);
  922. zend_hash_copy(Z_ARRVAL_P(&deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref);
  923. add_assoc_zval_ex(&ext, ZEND_STRL("deps"), &deps_arr);
  924. }
  925. add_assoc_zval_ex(return_value, ZSTR_VAL(key), ZSTR_LEN(key), &ext);
  926. }
  927. } ZEND_HASH_FOREACH_END();
  928. }
  929. #ifdef ZTS
  930. v8js_process_globals.lock.unlock();
  931. #endif
  932. }
  933. /* }}} */
  934. static v8::StartupData createSnapshotDataBlob(v8::SnapshotCreator *snapshot_creator, zend_string *str) /* {{{ */
  935. {
  936. v8::Isolate *isolate = snapshot_creator->GetIsolate();
  937. {
  938. v8::HandleScope scope(isolate);
  939. v8::Local<v8::Context> context = v8::Context::New(isolate);
  940. v8::Context::Scope context_scope(context);
  941. v8::TryCatch try_catch(isolate);
  942. v8::Local<v8::String> source = V8JS_ZSTR(str);
  943. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(context, source);
  944. if (script.IsEmpty() || script.ToLocalChecked()->Run(context).IsEmpty())
  945. {
  946. return {nullptr, 0};
  947. }
  948. snapshot_creator->SetDefaultContext(context);
  949. }
  950. return snapshot_creator->CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear);
  951. } /* }}} */
  952. /* {{{ proto string|bool V8Js::createSnapshot(string embed_source)
  953. */
  954. static PHP_METHOD(V8Js, createSnapshot)
  955. {
  956. zend_string *script;
  957. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &script) == FAILURE) {
  958. return;
  959. }
  960. if (!ZSTR_LEN(script)) {
  961. php_error_docref(NULL, E_WARNING, "Script cannot be empty");
  962. RETURN_FALSE;
  963. }
  964. /* Initialize V8, if not already done. */
  965. v8js_v8_init();
  966. v8::Isolate *isolate = v8::Isolate::Allocate();
  967. v8::SnapshotCreator snapshot_creator(isolate);
  968. v8::StartupData snapshot_blob = createSnapshotDataBlob(&snapshot_creator, script);
  969. if (!snapshot_blob.data) {
  970. php_error_docref(NULL, E_WARNING, "Failed to create V8 heap snapshot. Check $embed_source for errors.");
  971. RETURN_FALSE;
  972. }
  973. RETVAL_STRINGL(snapshot_blob.data, snapshot_blob.raw_size);
  974. delete[] snapshot_blob.data;
  975. }
  976. /* }}} */
  977. /* {{{ arginfo */
  978. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  979. ZEND_ARG_INFO(0, object_name)
  980. ZEND_ARG_INFO(0, variables)
  981. ZEND_ARG_INFO(0, extensions)
  982. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  983. ZEND_ARG_INFO(0, snapshot_blob)
  984. ZEND_END_ARG_INFO()
  985. ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
  986. ZEND_END_ARG_INFO()
  987. ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
  988. ZEND_END_ARG_INFO()
  989. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  990. ZEND_ARG_INFO(0, script)
  991. ZEND_ARG_INFO(0, identifier)
  992. ZEND_ARG_INFO(0, flags)
  993. ZEND_ARG_INFO(0, time_limit)
  994. ZEND_ARG_INFO(0, memory_limit)
  995. ZEND_END_ARG_INFO()
  996. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
  997. ZEND_ARG_INFO(0, script)
  998. ZEND_ARG_INFO(0, identifier)
  999. ZEND_END_ARG_INFO()
  1000. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
  1001. ZEND_ARG_INFO(0, script)
  1002. ZEND_ARG_INFO(0, flags)
  1003. ZEND_ARG_INFO(0, time_limit)
  1004. ZEND_ARG_INFO(0, memory_limit)
  1005. ZEND_END_ARG_INFO()
  1006. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  1007. ZEND_ARG_INFO(0, script)
  1008. ZEND_END_ARG_INFO()
  1009. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  1010. ZEND_END_ARG_INFO()
  1011. ZEND_BEGIN_ARG_INFO(arginfo_v8js_clearpendingexception, 0)
  1012. ZEND_END_ARG_INFO()
  1013. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmodulenormaliser, 0, 0, 2)
  1014. ZEND_ARG_INFO(0, base)
  1015. ZEND_ARG_INFO(0, module_id)
  1016. ZEND_END_ARG_INFO()
  1017. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  1018. ZEND_ARG_INFO(0, callable)
  1019. ZEND_END_ARG_INFO()
  1020. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setaverageobjectsize, 0, 0, 1)
  1021. ZEND_ARG_INFO(0, average_object_size)
  1022. ZEND_END_ARG_INFO()
  1023. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  1024. ZEND_ARG_INFO(0, extension_name)
  1025. ZEND_ARG_INFO(0, script)
  1026. ZEND_ARG_INFO(0, dependencies)
  1027. ZEND_ARG_INFO(0, auto_enable)
  1028. ZEND_END_ARG_INFO()
  1029. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  1030. ZEND_END_ARG_INFO()
  1031. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_createsnapshot, 0, 0, 1)
  1032. ZEND_ARG_INFO(0, script)
  1033. ZEND_END_ARG_INFO()
  1034. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
  1035. ZEND_ARG_INFO(0, time_limit)
  1036. ZEND_END_ARG_INFO()
  1037. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
  1038. ZEND_ARG_INFO(0, memory_limit)
  1039. ZEND_END_ARG_INFO()
  1040. const zend_function_entry v8js_methods[] = { /* {{{ */
  1041. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  1042. PHP_ME(V8Js, __sleep, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1043. PHP_ME(V8Js, __wakeup, arginfo_v8js_wakeup, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1044. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  1045. PHP_ME(V8Js, compileString, arginfo_v8js_compilestring, ZEND_ACC_PUBLIC)
  1046. PHP_ME(V8Js, executeScript, arginfo_v8js_executescript, ZEND_ACC_PUBLIC)
  1047. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1048. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1049. PHP_ME(V8Js, clearPendingException, arginfo_v8js_clearpendingexception, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1050. PHP_ME(V8Js, setModuleNormaliser, arginfo_v8js_setmodulenormaliser, ZEND_ACC_PUBLIC)
  1051. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  1052. PHP_ME(V8Js, setTimeLimit, arginfo_v8js_settimelimit, ZEND_ACC_PUBLIC)
  1053. PHP_ME(V8Js, setMemoryLimit, arginfo_v8js_setmemorylimit, ZEND_ACC_PUBLIC)
  1054. PHP_ME(V8Js, setAverageObjectSize, arginfo_v8js_setaverageobjectsize, ZEND_ACC_PUBLIC)
  1055. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_DEPRECATED)
  1056. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_DEPRECATED)
  1057. PHP_ME(V8Js, createSnapshot, arginfo_v8js_createsnapshot, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  1058. {NULL, NULL, NULL}
  1059. };
  1060. /* }}} */
  1061. /* V8Js object handlers */
  1062. #if PHP_VERSION_ID >= 80000
  1063. static SINCE74(zval*, void) v8js_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot) /* {{{ */
  1064. {
  1065. v8js_ctx *c = Z_V8JS_CTX_OBJ(object);
  1066. V8JS_CTX_PROLOGUE_EX(c, SINCE74(value,));
  1067. /* Check whether member is public, if so, export to V8. */
  1068. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1);
  1069. if(!property_info ||
  1070. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  1071. (property_info->flags & ZEND_ACC_PUBLIC))) {
  1072. /* Global PHP JS object */
  1073. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1074. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1075. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  1076. zend_throw_exception(php_ce_v8js_exception,
  1077. "Property name exceeds maximum supported length", 0);
  1078. return SINCE74(value,);
  1079. }
  1080. /* Write value to PHP JS object */
  1081. v8::Local<v8::Name> key = V8JS_SYML(ZSTR_VAL(member), static_cast<int>(ZSTR_LEN(member)));
  1082. jsobj->DefineOwnProperty(v8_context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  1083. }
  1084. #else
  1085. static SINCE74(zval*, void) v8js_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
  1086. {
  1087. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(object);
  1088. V8JS_CTX_PROLOGUE_EX(c, SINCE74(value,));
  1089. /* Check whether member is public, if so, export to V8. */
  1090. zend_property_info *property_info = zend_get_property_info(c->std.ce, Z_STR_P(member), 1);
  1091. if(!property_info ||
  1092. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  1093. (property_info->flags & ZEND_ACC_PUBLIC))) {
  1094. /* Global PHP JS object */
  1095. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1096. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1097. if (Z_STRLEN_P(member) > std::numeric_limits<int>::max()) {
  1098. zend_throw_exception(php_ce_v8js_exception,
  1099. "Property name exceeds maximum supported length", 0);
  1100. return SINCE74(value,);
  1101. }
  1102. /* Write value to PHP JS object */
  1103. v8::Local<v8::Name> key = V8JS_SYML(Z_STRVAL_P(member), static_cast<int>(Z_STRLEN_P(member)));
  1104. jsobj->DefineOwnProperty(v8_context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  1105. }
  1106. #endif
  1107. /* Write value to PHP object */
  1108. SINCE74(return,) std_object_handlers.write_property(object, member, value, NULL);
  1109. }
  1110. /* }}} */
  1111. #if PHP_VERSION_ID >= 80000
  1112. static void v8js_unset_property(zend_object *object, zend_string *member, void **cache_slot) /* {{{ */
  1113. {
  1114. V8JS_BEGIN_CTX_OBJ(c, object)
  1115. /* Global PHP JS object */
  1116. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1117. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1118. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  1119. zend_throw_exception(php_ce_v8js_exception,
  1120. "Property name exceeds maximum supported length", 0);
  1121. return;
  1122. }
  1123. /* Delete value from PHP JS object */
  1124. v8::Local<v8::Value> key = V8JS_SYML(ZSTR_VAL(member), static_cast<int>(ZSTR_LEN(member)));
  1125. #else
  1126. static void v8js_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
  1127. {
  1128. V8JS_BEGIN_CTX(c, object)
  1129. /* Global PHP JS object */
  1130. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1131. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1132. if (Z_STRLEN_P(member) > std::numeric_limits<int>::max()) {
  1133. zend_throw_exception(php_ce_v8js_exception,
  1134. "Property name exceeds maximum supported length", 0);
  1135. return;
  1136. }
  1137. /* Delete value from PHP JS object */
  1138. v8::Local<v8::Value> key = V8JS_SYML(Z_STRVAL_P(member), static_cast<int>(Z_STRLEN_P(member)));
  1139. #endif
  1140. jsobj->Delete(v8_context, key);
  1141. /* Unset from PHP object */
  1142. std_object_handlers.unset_property(object, member, NULL);
  1143. }
  1144. /* }}} */
  1145. PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
  1146. {
  1147. zend_class_entry ce;
  1148. /* V8Js Class */
  1149. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  1150. php_ce_v8js = zend_register_internal_class(&ce);
  1151. php_ce_v8js->create_object = v8js_new;
  1152. /* V8Js handlers */
  1153. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  1154. v8js_object_handlers.clone_obj = NULL;
  1155. v8js_object_handlers.write_property = v8js_write_property;
  1156. v8js_object_handlers.unset_property = v8js_unset_property;
  1157. /* V8Js Class Constants */
  1158. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION);
  1159. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE);
  1160. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY);
  1161. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_PROPAGATE_PHP_EXCEPTIONS"), V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS);
  1162. le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
  1163. return SUCCESS;
  1164. } /* }}} */
  1165. /*
  1166. * Local variables:
  1167. * tab-width: 4
  1168. * c-basic-offset: 4
  1169. * indent-tabs-mode: t
  1170. * End:
  1171. * vim600: noet sw=4 ts=4 fdm=marker
  1172. * vim<600: noet sw=4 ts=4
  1173. */