v8js_class.cc 32 KB

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