v8js_class.cc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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<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<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. HashTable *properties = zend_std_get_properties(getThis());
  413. zval *value;
  414. zend_string *member;
  415. ZEND_HASH_FOREACH_STR_KEY(properties, member) {
  416. zend_property_info *property_info = zend_get_property_info(c->std.ce, member, 1);
  417. if(property_info &&
  418. property_info != ZEND_WRONG_PROPERTY_INFO &&
  419. (property_info->flags & ZEND_ACC_PUBLIC)) {
  420. if (ZSTR_LEN(member) > std::numeric_limits<int>::max()) {
  421. zend_throw_exception(php_ce_v8js_exception,
  422. "Property name exceeds maximum supported length", 0);
  423. return;
  424. }
  425. v8::Local<v8::Name> key = V8JS_ZSYM(member);
  426. /* Write value to PHP JS object */
  427. value = OBJ_PROP(Z_OBJ_P(getThis()), property_info->offset);
  428. php_obj->DefineOwnProperty(context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  429. }
  430. } ZEND_HASH_FOREACH_END();
  431. /* Add pointer to zend object */
  432. php_obj->SetAlignedPointerInInternalField(1, Z_OBJ_P(getThis()));
  433. /* Export public methods */
  434. void *ptr;
  435. zend_string *key;
  436. ZEND_HASH_FOREACH_STR_KEY_PTR(&c->std.ce->function_table, key, ptr) {
  437. zend_function *method_ptr = reinterpret_cast<zend_function *>(ptr);
  438. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  439. /* Allow only public methods */
  440. continue;
  441. }
  442. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR)) != 0) {
  443. /* no __construct, __destruct(), or __clone() functions */
  444. continue;
  445. }
  446. /* hide (do not export) other PHP magic functions */
  447. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  448. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  449. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  450. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  451. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  452. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  453. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  454. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  455. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  456. IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME) ||
  457. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  458. continue;
  459. }
  460. const zend_function_entry *fe;
  461. for (fe = v8js_methods; fe->fname; fe ++) {
  462. if (strcmp(fe->fname, ZSTR_VAL(method_ptr->common.function_name)) == 0) {
  463. break;
  464. }
  465. }
  466. if(fe->fname) {
  467. /* Method belongs to \V8Js class itself, never export to V8, even if
  468. * it is overriden in a derived class. */
  469. continue;
  470. }
  471. if (ZSTR_LEN(method_ptr->common.function_name) > std::numeric_limits<int>::max()) {
  472. zend_throw_exception(php_ce_v8js_exception,
  473. "Method name exceeds maximum supported length", 0);
  474. return;
  475. }
  476. v8::Local<v8::String> method_name = V8JS_ZSYM(method_ptr->common.function_name);
  477. v8::Local<v8::FunctionTemplate> ft;
  478. ft = v8::FunctionTemplate::New(isolate, v8js_php_callback,
  479. v8::External::New((isolate), method_ptr));
  480. // @fixme add/check Signature v8::Signature::New((isolate), tmpl));
  481. v8js_function_tmpl_t *persistent_ft = &c->method_tmpls[method_ptr];
  482. persistent_ft->Reset(isolate, ft);
  483. php_obj->CreateDataProperty(context, method_name, ft->GetFunction(context).ToLocalChecked());
  484. } ZEND_HASH_FOREACH_END();
  485. }
  486. /* }}} */
  487. /* {{{ proto V8JS::__sleep()
  488. */
  489. PHP_METHOD(V8Js, __sleep)
  490. {
  491. zend_throw_exception(php_ce_v8js_exception,
  492. "You cannot serialize or unserialize V8Js instances", 0);
  493. RETURN_FALSE;
  494. }
  495. /* }}} */
  496. /* {{{ proto V8JS::__wakeup()
  497. */
  498. PHP_METHOD(V8Js, __wakeup)
  499. {
  500. zend_throw_exception(php_ce_v8js_exception,
  501. "You cannot serialize or unserialize V8Js instances", 0);
  502. RETURN_FALSE;
  503. }
  504. /* }}} */
  505. static void v8js_compile_script(zval *this_ptr, const zend_string *str, const zend_string *identifier, v8js_script **ret)
  506. {
  507. v8js_script *res = NULL;
  508. V8JS_BEGIN_CTX(c, this_ptr)
  509. /* Catch JS exceptions */
  510. v8::TryCatch try_catch(isolate);
  511. /* Set script identifier */
  512. if (identifier && ZSTR_LEN(identifier) > std::numeric_limits<int>::max()) {
  513. zend_throw_exception(php_ce_v8js_exception,
  514. "Script identifier exceeds maximum supported length", 0);
  515. return;
  516. }
  517. v8::Local<v8::String> sname = identifier
  518. ? V8JS_ZSTR(identifier)
  519. : V8JS_SYM("V8Js::compileString()");
  520. v8::ScriptOrigin origin(sname);
  521. if (ZSTR_LEN(str) > std::numeric_limits<int>::max()) {
  522. zend_throw_exception(php_ce_v8js_exception,
  523. "Script source exceeds maximum supported length", 0);
  524. return;
  525. }
  526. v8::Local<v8::String> source = V8JS_ZSTR(str);
  527. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(v8::Local<v8::Context>::New(isolate, c->context), source, &origin);
  528. /* Compile errors? */
  529. if (script.IsEmpty()) {
  530. v8js_throw_script_exception(c->isolate, &try_catch);
  531. return;
  532. }
  533. res = (v8js_script *)emalloc(sizeof(v8js_script));
  534. res->script = new v8::Persistent<v8::Script, v8::CopyablePersistentTraits<v8::Script>>(c->isolate, script.ToLocalChecked());
  535. v8::String::Utf8Value _sname(isolate, sname);
  536. res->name = estrndup(ToCString(_sname), _sname.length());
  537. res->ctx = c;
  538. *ret = res;
  539. return;
  540. }
  541. static void v8js_execute_script(zval *this_ptr, v8js_script *res, long flags, long time_limit, size_t memory_limit, zval **return_value)
  542. {
  543. v8js_ctx *c = Z_V8JS_CTX_OBJ_P(this_ptr);
  544. if (res->ctx != c) {
  545. zend_error(E_WARNING, "Script resource from wrong V8Js object passed");
  546. ZVAL_BOOL(*return_value, 0);
  547. return;
  548. }
  549. if (!c->in_execution && time_limit == 0) {
  550. time_limit = c->time_limit;
  551. }
  552. if (!c->in_execution && memory_limit == 0) {
  553. memory_limit = c->memory_limit;
  554. }
  555. /* std::function relies on its dtor to be executed, otherwise it leaks
  556. * some memory on bailout. */
  557. {
  558. std::function< v8::MaybeLocal<v8::Value>(v8::Isolate *) > v8_call = [c, res](v8::Isolate *isolate) {
  559. v8::Local<v8::Script> script = v8::Local<v8::Script>::New(isolate, *res->script);
  560. return script->Run(v8::Local<v8::Context>::New(isolate, c->context));
  561. };
  562. v8js_v8_call(c, return_value, flags, time_limit, memory_limit, v8_call);
  563. }
  564. if(V8JSG(fatal_error_abort)) {
  565. /* Check for fatal error marker possibly set by v8js_error_handler; just
  566. * rethrow the error since we're now out of V8. */
  567. zend_bailout();
  568. }
  569. }
  570. /* {{{ proto mixed V8Js::executeString(string script [, string identifier [, int flags]])
  571. */
  572. static PHP_METHOD(V8Js, executeString)
  573. {
  574. zend_string *str = NULL, *identifier = NULL;
  575. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  576. v8js_script *res = NULL;
  577. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|Slll", &str, &identifier, &flags, &time_limit, &memory_limit) == FAILURE) {
  578. return;
  579. }
  580. if (memory_limit < 0) {
  581. zend_throw_exception(php_ce_v8js_exception,
  582. "memory_limit must not be negative", 0);
  583. return;
  584. }
  585. v8js_compile_script(getThis(), str, identifier, &res);
  586. if (!res) {
  587. RETURN_FALSE;
  588. }
  589. zend_try {
  590. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  591. v8js_script_free(res);
  592. }
  593. zend_catch {
  594. v8js_script_free(res);
  595. zend_bailout();
  596. }
  597. zend_end_try()
  598. efree(res);
  599. }
  600. /* }}} */
  601. /* {{{ proto mixed V8Js::compileString(string script [, string identifier])
  602. */
  603. static PHP_METHOD(V8Js, compileString)
  604. {
  605. zend_string *str = NULL, *identifier = NULL;
  606. v8js_script *res = NULL;
  607. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|S", &str, &identifier) == FAILURE) {
  608. return;
  609. }
  610. v8js_compile_script(getThis(), str, identifier, &res);
  611. if (res) {
  612. RETVAL_RES(zend_register_resource(res, le_v8js_script));
  613. v8js_ctx *ctx;
  614. ctx = Z_V8JS_CTX_OBJ_P(getThis());
  615. ctx->script_objects.push_back(res);
  616. }
  617. }
  618. /* }}} */
  619. /* {{{ proto mixed V8Js::executeScript(resource script [, int flags]])
  620. */
  621. static PHP_METHOD(V8Js, executeScript)
  622. {
  623. long flags = V8JS_FLAG_NONE, time_limit = 0, memory_limit = 0;
  624. zval *zscript;
  625. v8js_script *res;
  626. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|lll", &zscript, &flags, &time_limit, &memory_limit) == FAILURE) {
  627. return;
  628. }
  629. if (memory_limit < 0) {
  630. zend_throw_exception(php_ce_v8js_exception,
  631. "memory_limit must not be negative", 0);
  632. return;
  633. }
  634. if((res = (v8js_script *)zend_fetch_resource(Z_RES_P(zscript), PHP_V8JS_SCRIPT_RES_NAME, le_v8js_script)) == NULL) {
  635. RETURN_FALSE;
  636. }
  637. v8js_execute_script(getThis(), res, flags, time_limit, static_cast<size_t>(memory_limit), &return_value);
  638. }
  639. /* }}} */
  640. /* {{{ proto mixed V8Js::checkString(string script)
  641. */
  642. static PHP_METHOD(V8Js, checkString)
  643. {
  644. zend_string *str = NULL;
  645. zend_string *identifier = zend_string_init("V8Js::checkString()", 19, 0);
  646. v8js_script *res = NULL;
  647. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
  648. return;
  649. }
  650. v8js_compile_script(getThis(), str, identifier, &res);
  651. zend_string_release(identifier);
  652. if (!res) {
  653. RETURN_FALSE;
  654. }
  655. v8js_script_free(res);
  656. efree(res);
  657. RETURN_TRUE;
  658. }
  659. /* }}} */
  660. /* {{{ proto mixed V8Js::getPendingException()
  661. */
  662. static PHP_METHOD(V8Js, getPendingException)
  663. {
  664. v8js_ctx *c;
  665. if (zend_parse_parameters_none() == FAILURE) {
  666. return;
  667. }
  668. c = Z_V8JS_CTX_OBJ_P(getThis());
  669. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  670. RETURN_ZVAL(&c->pending_exception, 1, 0);
  671. }
  672. }
  673. /* }}} */
  674. /* {{{ proto void V8Js::clearPendingException()
  675. */
  676. static PHP_METHOD(V8Js, clearPendingException)
  677. {
  678. v8js_ctx *c;
  679. if (zend_parse_parameters_none() == FAILURE) {
  680. return;
  681. }
  682. c = Z_V8JS_CTX_OBJ_P(getThis());
  683. if (Z_TYPE(c->pending_exception) == IS_OBJECT) {
  684. zval_ptr_dtor(&c->pending_exception);
  685. ZVAL_NULL(&c->pending_exception);
  686. }
  687. }
  688. /* }}} */
  689. /* {{{ proto void V8Js::setModuleNormaliser(string base, string module_id)
  690. */
  691. static PHP_METHOD(V8Js, setModuleNormaliser)
  692. {
  693. v8js_ctx *c;
  694. zval *callable;
  695. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  696. return;
  697. }
  698. c = Z_V8JS_CTX_OBJ_P(getThis());
  699. ZVAL_COPY(&c->module_normaliser, callable);
  700. }
  701. /* }}} */
  702. /* {{{ proto void V8Js::setModuleLoader(string module)
  703. */
  704. static PHP_METHOD(V8Js, setModuleLoader)
  705. {
  706. v8js_ctx *c;
  707. zval *callable;
  708. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
  709. return;
  710. }
  711. c = Z_V8JS_CTX_OBJ_P(getThis());
  712. ZVAL_COPY(&c->module_loader, callable);
  713. }
  714. /* }}} */
  715. /* {{{ proto void V8Js::setTimeLimit(int time_limit)
  716. */
  717. static PHP_METHOD(V8Js, setTimeLimit)
  718. {
  719. v8js_ctx *c;
  720. long time_limit = 0;
  721. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &time_limit) == FAILURE) {
  722. return;
  723. }
  724. c = Z_V8JS_CTX_OBJ_P(getThis());
  725. c->time_limit = time_limit;
  726. V8JSG(timer_mutex).lock();
  727. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  728. it != V8JSG(timer_stack).end(); it ++) {
  729. if((*it)->ctx == c && !(*it)->killed) {
  730. (*it)->time_limit = time_limit;
  731. // Calculate the time point when the time limit is exceeded
  732. std::chrono::milliseconds duration(time_limit);
  733. std::chrono::time_point<std::chrono::high_resolution_clock> from = std::chrono::high_resolution_clock::now();
  734. (*it)->time_point = from + duration;
  735. }
  736. }
  737. V8JSG(timer_mutex).unlock();
  738. if (c->in_execution && time_limit && !V8JSG(timer_thread)) {
  739. /* If timer thread is not started already and we now impose a time limit
  740. * finally install the timer. */
  741. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  742. }
  743. }
  744. /* }}} */
  745. /* {{{ proto void V8Js::setMemoryLimit(int memory_limit)
  746. */
  747. static PHP_METHOD(V8Js, setMemoryLimit)
  748. {
  749. v8js_ctx *c;
  750. long memory_limit = 0;
  751. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &memory_limit) == FAILURE) {
  752. return;
  753. }
  754. if (memory_limit < 0) {
  755. zend_throw_exception(php_ce_v8js_exception,
  756. "memory_limit must not be negative", 0);
  757. return;
  758. }
  759. c = Z_V8JS_CTX_OBJ_P(getThis());
  760. c->memory_limit = static_cast<size_t>(memory_limit);
  761. V8JSG(timer_mutex).lock();
  762. for (std::deque< v8js_timer_ctx* >::iterator it = V8JSG(timer_stack).begin();
  763. it != V8JSG(timer_stack).end(); it ++) {
  764. if((*it)->ctx == c && !(*it)->killed) {
  765. (*it)->memory_limit = static_cast<size_t>(memory_limit);
  766. }
  767. }
  768. V8JSG(timer_mutex).unlock();
  769. if (c->in_execution && memory_limit && !V8JSG(timer_thread)) {
  770. /* If timer thread is not started already and we now impose a memory limit
  771. * finally install the timer. */
  772. V8JSG(timer_thread) = new std::thread(v8js_timer_thread, ZEND_MODULE_GLOBALS_BULK(v8js));
  773. }
  774. }
  775. /* }}} */
  776. /* {{{ proto void V8Js::setAverageObjectSize(average_object_size)
  777. */
  778. static PHP_METHOD(V8Js, setAverageObjectSize)
  779. {
  780. v8js_ctx *c;
  781. long average_object_size = 0;
  782. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &average_object_size) == FAILURE) {
  783. return;
  784. }
  785. c = Z_V8JS_CTX_OBJ_P(getThis());
  786. c->average_object_size = average_object_size;
  787. }
  788. /* }}} */
  789. static void v8js_persistent_zval_ctor(zval *p) /* {{{ */
  790. {
  791. assert(Z_TYPE_P(p) == IS_STRING);
  792. Z_STR_P(p) = zend_string_dup(Z_STR_P(p), 1);
  793. }
  794. /* }}} */
  795. static void v8js_persistent_zval_dtor(zval *p) /* {{{ */
  796. {
  797. assert(Z_TYPE_P(p) == IS_STRING);
  798. if (!ZSTR_IS_INTERNED(Z_STR_P(p))) {
  799. free(Z_STR_P(p));
  800. }
  801. }
  802. /* }}} */
  803. static void v8js_script_free(v8js_script *res)
  804. {
  805. efree(res->name);
  806. delete res->script; // does Reset()
  807. }
  808. static void v8js_script_dtor(zend_resource *rsrc) /* {{{ */
  809. {
  810. v8js_script *res = (v8js_script *)rsrc->ptr;
  811. if (res) {
  812. if(res->ctx) {
  813. std::vector<v8js_script *>::iterator it = std::find(res->ctx->script_objects.begin(), res->ctx->script_objects.end(), res);
  814. res->ctx->script_objects.erase(it);
  815. }
  816. v8js_script_free(res);
  817. efree(res);
  818. }
  819. }
  820. /* }}} */
  821. static int v8js_register_extension(zend_string *name, zend_string *source, zval *deps_arr, zend_bool auto_enable) /* {{{ */
  822. {
  823. v8js_jsext *jsext = NULL;
  824. #ifdef ZTS
  825. v8js_process_globals.lock.lock();
  826. #endif
  827. if (!v8js_process_globals.extensions) {
  828. v8js_process_globals.extensions = (HashTable *) malloc(sizeof(HashTable));
  829. zend_hash_init(v8js_process_globals.extensions, 1, NULL, v8js_jsext_dtor, 1);
  830. } else if (zend_hash_exists(v8js_process_globals.extensions, name)) {
  831. #ifdef ZTS
  832. v8js_process_globals.lock.unlock();
  833. #endif
  834. return FAILURE;
  835. }
  836. jsext = (v8js_jsext *) calloc(1, sizeof(v8js_jsext));
  837. if (deps_arr) {
  838. jsext->deps_count = zend_hash_num_elements(Z_ARRVAL_P(deps_arr));
  839. if (v8js_create_ext_strarr(&jsext->deps, jsext->deps_count, Z_ARRVAL_P(deps_arr)) == FAILURE) {
  840. php_error_docref(NULL, E_WARNING, "Invalid dependency array passed");
  841. v8js_jsext_free_storage(jsext);
  842. #ifdef ZTS
  843. v8js_process_globals.lock.unlock();
  844. #endif
  845. return FAILURE;
  846. }
  847. }
  848. jsext->auto_enable = auto_enable;
  849. // Allocate a persistent string which will survive until module shutdown on both ZTS(Persistent) and NTS(Not interned, those would be cleaned up)
  850. // (zend_string_dup would return the original interned string, if interned, so we don't use that)
  851. jsext->name = zend_string_init(ZSTR_VAL(name), ZSTR_LEN(name), 1);
  852. jsext->source = zend_string_init(ZSTR_VAL(source), ZSTR_LEN(source), 1);
  853. if (jsext->deps) {
  854. jsext->deps_ht = (HashTable *) malloc(sizeof(HashTable));
  855. zend_hash_init(jsext->deps_ht, jsext->deps_count, NULL, v8js_persistent_zval_dtor, 1);
  856. zend_hash_copy(jsext->deps_ht, Z_ARRVAL_P(deps_arr), v8js_persistent_zval_ctor);
  857. }
  858. v8::Extension *extension = new v8::Extension(ZSTR_VAL(jsext->name), ZSTR_VAL(jsext->source), jsext->deps_count, jsext->deps);
  859. if (!zend_hash_add_ptr(v8js_process_globals.extensions, jsext->name, jsext)) {
  860. v8js_jsext_free_storage(jsext);
  861. #ifdef ZTS
  862. v8js_process_globals.lock.unlock();
  863. #endif
  864. return FAILURE;
  865. }
  866. #ifdef ZTS
  867. v8js_process_globals.lock.unlock();
  868. #endif
  869. extension->set_auto_enable(auto_enable ? true : false);
  870. v8::RegisterExtension(std::unique_ptr<v8::Extension>(extension));
  871. return SUCCESS;
  872. }
  873. /* }}} */
  874. /* ## Static methods ## */
  875. /* {{{ proto bool V8Js::registerExtension(string ext_name, string script [, array deps [, bool auto_enable]])
  876. */
  877. static PHP_METHOD(V8Js, registerExtension)
  878. {
  879. zend_string *ext_name, *script;
  880. zval *deps_arr = NULL;
  881. zend_bool auto_enable = 0;
  882. if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS|ab", &ext_name, &script, &deps_arr, &auto_enable) == FAILURE) {
  883. return;
  884. }
  885. if (!ZSTR_LEN(ext_name)) {
  886. php_error_docref(NULL, E_WARNING, "Extension name cannot be empty");
  887. } else if (!ZSTR_LEN(script)) {
  888. php_error_docref(NULL, E_WARNING, "Script cannot be empty");
  889. } else if (v8js_register_extension(ext_name, script, deps_arr, auto_enable) == SUCCESS) {
  890. RETURN_TRUE;
  891. }
  892. RETURN_FALSE;
  893. }
  894. /* }}} */
  895. /* {{{ proto array V8Js::getExtensions()
  896. */
  897. static PHP_METHOD(V8Js, getExtensions)
  898. {
  899. v8js_jsext *jsext;
  900. zend_string *key;
  901. zval *val, ext;
  902. if (zend_parse_parameters_none() == FAILURE) {
  903. return;
  904. }
  905. array_init(return_value);
  906. #ifdef ZTS
  907. v8js_process_globals.lock.lock();
  908. #endif
  909. if (v8js_process_globals.extensions) {
  910. ZEND_HASH_FOREACH_STR_KEY_VAL(v8js_process_globals.extensions, key, val) {
  911. if (key) {
  912. jsext = (v8js_jsext *) Z_PTR_P(val);
  913. array_init(&ext);
  914. add_assoc_bool_ex(&ext, ZEND_STRL("auto_enable"), jsext->auto_enable);
  915. if (jsext->deps_ht) {
  916. zval deps_arr;
  917. array_init(&deps_arr);
  918. zend_hash_copy(Z_ARRVAL_P(&deps_arr), jsext->deps_ht, (copy_ctor_func_t) zval_add_ref);
  919. add_assoc_zval_ex(&ext, ZEND_STRL("deps"), &deps_arr);
  920. }
  921. add_assoc_zval_ex(return_value, ZSTR_VAL(key), ZSTR_LEN(key), &ext);
  922. }
  923. } ZEND_HASH_FOREACH_END();
  924. }
  925. #ifdef ZTS
  926. v8js_process_globals.lock.unlock();
  927. #endif
  928. }
  929. /* }}} */
  930. static v8::StartupData createSnapshotDataBlob(v8::SnapshotCreator *snapshot_creator, zend_string *str) /* {{{ */
  931. {
  932. v8::Isolate *isolate = snapshot_creator->GetIsolate();
  933. {
  934. v8::HandleScope scope(isolate);
  935. v8::Local<v8::Context> context = v8::Context::New(isolate);
  936. v8::Context::Scope context_scope(context);
  937. v8::TryCatch try_catch(isolate);
  938. v8::Local<v8::String> source = V8JS_ZSTR(str);
  939. v8::MaybeLocal<v8::Script> script = v8::Script::Compile(context, source);
  940. if (script.IsEmpty() || script.ToLocalChecked()->Run(context).IsEmpty())
  941. {
  942. return {nullptr, 0};
  943. }
  944. snapshot_creator->SetDefaultContext(context);
  945. }
  946. return snapshot_creator->CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear);
  947. } /* }}} */
  948. /* {{{ proto string|bool V8Js::createSnapshot(string embed_source)
  949. */
  950. static PHP_METHOD(V8Js, createSnapshot)
  951. {
  952. zend_string *script;
  953. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &script) == FAILURE) {
  954. return;
  955. }
  956. if (!ZSTR_LEN(script)) {
  957. php_error_docref(NULL, E_WARNING, "Script cannot be empty");
  958. RETURN_FALSE;
  959. }
  960. /* Initialize V8, if not already done. */
  961. v8js_v8_init();
  962. v8::Isolate *isolate = v8::Isolate::Allocate();
  963. v8::SnapshotCreator snapshot_creator(isolate);
  964. v8::StartupData snapshot_blob = createSnapshotDataBlob(&snapshot_creator, script);
  965. if (!snapshot_blob.data) {
  966. php_error_docref(NULL, E_WARNING, "Failed to create V8 heap snapshot. Check $embed_source for errors.");
  967. RETURN_FALSE;
  968. }
  969. RETVAL_STRINGL(snapshot_blob.data, snapshot_blob.raw_size);
  970. delete[] snapshot_blob.data;
  971. }
  972. /* }}} */
  973. /* {{{ arginfo */
  974. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_construct, 0, 0, 0)
  975. ZEND_ARG_INFO(0, object_name)
  976. ZEND_ARG_INFO(0, variables)
  977. ZEND_ARG_INFO(0, extensions)
  978. ZEND_ARG_INFO(0, report_uncaught_exceptions)
  979. ZEND_ARG_INFO(0, snapshot_blob)
  980. ZEND_END_ARG_INFO()
  981. ZEND_BEGIN_ARG_INFO(arginfo_v8js_sleep, 0)
  982. ZEND_END_ARG_INFO()
  983. ZEND_BEGIN_ARG_INFO(arginfo_v8js_wakeup, 0)
  984. ZEND_END_ARG_INFO()
  985. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executestring, 0, 0, 1)
  986. ZEND_ARG_INFO(0, script)
  987. ZEND_ARG_INFO(0, identifier)
  988. ZEND_ARG_INFO(0, flags)
  989. ZEND_ARG_INFO(0, time_limit)
  990. ZEND_ARG_INFO(0, memory_limit)
  991. ZEND_END_ARG_INFO()
  992. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_compilestring, 0, 0, 1)
  993. ZEND_ARG_INFO(0, script)
  994. ZEND_ARG_INFO(0, identifier)
  995. ZEND_END_ARG_INFO()
  996. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_executescript, 0, 0, 1)
  997. ZEND_ARG_INFO(0, script)
  998. ZEND_ARG_INFO(0, flags)
  999. ZEND_ARG_INFO(0, time_limit)
  1000. ZEND_ARG_INFO(0, memory_limit)
  1001. ZEND_END_ARG_INFO()
  1002. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_checkstring, 0, 0, 1)
  1003. ZEND_ARG_INFO(0, script)
  1004. ZEND_END_ARG_INFO()
  1005. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getpendingexception, 0)
  1006. ZEND_END_ARG_INFO()
  1007. ZEND_BEGIN_ARG_INFO(arginfo_v8js_clearpendingexception, 0)
  1008. ZEND_END_ARG_INFO()
  1009. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmodulenormaliser, 0, 0, 2)
  1010. ZEND_ARG_INFO(0, base)
  1011. ZEND_ARG_INFO(0, module_id)
  1012. ZEND_END_ARG_INFO()
  1013. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmoduleloader, 0, 0, 1)
  1014. ZEND_ARG_INFO(0, callable)
  1015. ZEND_END_ARG_INFO()
  1016. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setaverageobjectsize, 0, 0, 1)
  1017. ZEND_ARG_INFO(0, average_object_size)
  1018. ZEND_END_ARG_INFO()
  1019. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_registerextension, 0, 0, 2)
  1020. ZEND_ARG_INFO(0, extension_name)
  1021. ZEND_ARG_INFO(0, script)
  1022. ZEND_ARG_INFO(0, dependencies)
  1023. ZEND_ARG_INFO(0, auto_enable)
  1024. ZEND_END_ARG_INFO()
  1025. ZEND_BEGIN_ARG_INFO(arginfo_v8js_getextensions, 0)
  1026. ZEND_END_ARG_INFO()
  1027. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_createsnapshot, 0, 0, 1)
  1028. ZEND_ARG_INFO(0, script)
  1029. ZEND_END_ARG_INFO()
  1030. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_settimelimit, 0, 0, 1)
  1031. ZEND_ARG_INFO(0, time_limit)
  1032. ZEND_END_ARG_INFO()
  1033. ZEND_BEGIN_ARG_INFO_EX(arginfo_v8js_setmemorylimit, 0, 0, 1)
  1034. ZEND_ARG_INFO(0, memory_limit)
  1035. ZEND_END_ARG_INFO()
  1036. const zend_function_entry v8js_methods[] = { /* {{{ */
  1037. PHP_ME(V8Js, __construct, arginfo_v8js_construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
  1038. PHP_ME(V8Js, __sleep, arginfo_v8js_sleep, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1039. PHP_ME(V8Js, __wakeup, arginfo_v8js_wakeup, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
  1040. PHP_ME(V8Js, executeString, arginfo_v8js_executestring, ZEND_ACC_PUBLIC)
  1041. PHP_ME(V8Js, compileString, arginfo_v8js_compilestring, ZEND_ACC_PUBLIC)
  1042. PHP_ME(V8Js, executeScript, arginfo_v8js_executescript, ZEND_ACC_PUBLIC)
  1043. PHP_ME(V8Js, checkString, arginfo_v8js_checkstring, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1044. PHP_ME(V8Js, getPendingException, arginfo_v8js_getpendingexception, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1045. PHP_ME(V8Js, clearPendingException, arginfo_v8js_clearpendingexception, ZEND_ACC_PUBLIC|ZEND_ACC_DEPRECATED)
  1046. PHP_ME(V8Js, setModuleNormaliser, arginfo_v8js_setmodulenormaliser, ZEND_ACC_PUBLIC)
  1047. PHP_ME(V8Js, setModuleLoader, arginfo_v8js_setmoduleloader, ZEND_ACC_PUBLIC)
  1048. PHP_ME(V8Js, setTimeLimit, arginfo_v8js_settimelimit, ZEND_ACC_PUBLIC)
  1049. PHP_ME(V8Js, setMemoryLimit, arginfo_v8js_setmemorylimit, ZEND_ACC_PUBLIC)
  1050. PHP_ME(V8Js, setAverageObjectSize, arginfo_v8js_setaverageobjectsize, ZEND_ACC_PUBLIC)
  1051. PHP_ME(V8Js, registerExtension, arginfo_v8js_registerextension, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_DEPRECATED)
  1052. PHP_ME(V8Js, getExtensions, arginfo_v8js_getextensions, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_DEPRECATED)
  1053. PHP_ME(V8Js, createSnapshot, arginfo_v8js_createsnapshot, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  1054. {NULL, NULL, NULL}
  1055. };
  1056. /* }}} */
  1057. /* V8Js object handlers */
  1058. static void v8js_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
  1059. {
  1060. V8JS_BEGIN_CTX(c, object)
  1061. /* Check whether member is public, if so, export to V8. */
  1062. zend_property_info *property_info = zend_get_property_info(c->std.ce, Z_STR_P(member), 1);
  1063. if(!property_info ||
  1064. (property_info != ZEND_WRONG_PROPERTY_INFO &&
  1065. (property_info->flags & ZEND_ACC_PUBLIC))) {
  1066. /* Global PHP JS object */
  1067. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1068. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1069. if (Z_STRLEN_P(member) > std::numeric_limits<int>::max()) {
  1070. zend_throw_exception(php_ce_v8js_exception,
  1071. "Property name exceeds maximum supported length", 0);
  1072. return;
  1073. }
  1074. /* Write value to PHP JS object */
  1075. v8::Local<v8::Name> key = V8JS_SYML(Z_STRVAL_P(member), static_cast<int>(Z_STRLEN_P(member)));
  1076. jsobj->DefineOwnProperty(v8_context, key, zval_to_v8js(value, isolate), v8::ReadOnly);
  1077. }
  1078. /* Write value to PHP object */
  1079. std_object_handlers.write_property(object, member, value, NULL);
  1080. }
  1081. /* }}} */
  1082. static void v8js_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
  1083. {
  1084. V8JS_BEGIN_CTX(c, object)
  1085. /* Global PHP JS object */
  1086. v8::Local<v8::String> object_name_js = v8::Local<v8::String>::New(isolate, c->object_name);
  1087. v8::Local<v8::Object> jsobj = V8JS_GLOBAL(isolate)->Get(v8_context, object_name_js).ToLocalChecked()->ToObject(v8_context).ToLocalChecked();
  1088. if (Z_STRLEN_P(member) > std::numeric_limits<int>::max()) {
  1089. zend_throw_exception(php_ce_v8js_exception,
  1090. "Property name exceeds maximum supported length", 0);
  1091. return;
  1092. }
  1093. /* Delete value from PHP JS object */
  1094. v8::Local<v8::Value> key = V8JS_SYML(Z_STRVAL_P(member), static_cast<int>(Z_STRLEN_P(member)));
  1095. jsobj->Delete(v8_context, key);
  1096. /* Unset from PHP object */
  1097. std_object_handlers.unset_property(object, member, NULL);
  1098. }
  1099. /* }}} */
  1100. PHP_MINIT_FUNCTION(v8js_class) /* {{{ */
  1101. {
  1102. zend_class_entry ce;
  1103. /* V8Js Class */
  1104. INIT_CLASS_ENTRY(ce, "V8Js", v8js_methods);
  1105. php_ce_v8js = zend_register_internal_class(&ce);
  1106. php_ce_v8js->create_object = v8js_new;
  1107. /* V8Js handlers */
  1108. memcpy(&v8js_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  1109. v8js_object_handlers.clone_obj = NULL;
  1110. v8js_object_handlers.write_property = v8js_write_property;
  1111. v8js_object_handlers.unset_property = v8js_unset_property;
  1112. /* V8Js Class Constants */
  1113. zend_declare_class_constant_string(php_ce_v8js, ZEND_STRL("V8_VERSION"), PHP_V8_VERSION);
  1114. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_NONE"), V8JS_FLAG_NONE);
  1115. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_FORCE_ARRAY"), V8JS_FLAG_FORCE_ARRAY);
  1116. zend_declare_class_constant_long(php_ce_v8js, ZEND_STRL("FLAG_PROPAGATE_PHP_EXCEPTIONS"), V8JS_FLAG_PROPAGATE_PHP_EXCEPTIONS);
  1117. le_v8js_script = zend_register_list_destructors_ex(v8js_script_dtor, NULL, PHP_V8JS_SCRIPT_RES_NAME, module_number);
  1118. return SUCCESS;
  1119. } /* }}} */
  1120. /*
  1121. * Local variables:
  1122. * tab-width: 4
  1123. * c-basic-offset: 4
  1124. * indent-tabs-mode: t
  1125. * End:
  1126. * vim600: noet sw=4 ts=4 fdm=marker
  1127. * vim<600: noet sw=4 ts=4
  1128. */