v8js_methods.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 "php_v8js_macros.h"
  18. #include "v8js_commonjs.h"
  19. #include "v8js_exceptions.h"
  20. extern "C" {
  21. #include "zend_exceptions.h"
  22. }
  23. /* global.exit - terminate execution */
  24. V8JS_METHOD(exit) /* {{{ */
  25. {
  26. v8::Isolate *isolate = info.GetIsolate();
  27. v8js_terminate_execution(isolate);
  28. }
  29. /* }}} */
  30. /* global.sleep - sleep for passed seconds */
  31. V8JS_METHOD(sleep) /* {{{ */
  32. {
  33. php_sleep(info[0]->Int32Value());
  34. }
  35. /* }}} */
  36. /* global.print - php print() */
  37. V8JS_METHOD(print) /* {{{ */
  38. {
  39. v8::Isolate *isolate = info.GetIsolate();
  40. zend_long ret = 0;
  41. for (int i = 0; i < info.Length(); i++) {
  42. v8::String::Utf8Value str(info[i]);
  43. const char *cstr = ToCString(str);
  44. ret = PHPWRITE(cstr, strlen(cstr));
  45. }
  46. info.GetReturnValue().Set(zend_long_to_v8js(ret, isolate));
  47. }
  48. /* }}} */
  49. static void v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int level) /* {{{ */
  50. {
  51. if (level > 1) {
  52. php_printf("%*c", (level - 1) * 2, ' ');
  53. }
  54. if (var.IsEmpty())
  55. {
  56. php_printf("<empty>\n");
  57. return;
  58. }
  59. if (var->IsNull() || var->IsUndefined() /* PHP compat */)
  60. {
  61. php_printf("NULL\n");
  62. return;
  63. }
  64. if (var->IsInt32())
  65. {
  66. php_printf("int(%ld)\n", (long) var->IntegerValue());
  67. return;
  68. }
  69. if (var->IsUint32())
  70. {
  71. php_printf("int(%lu)\n", (unsigned long) var->IntegerValue());
  72. return;
  73. }
  74. if (var->IsNumber())
  75. {
  76. php_printf("float(%f)\n", var->NumberValue());
  77. return;
  78. }
  79. if (var->IsBoolean())
  80. {
  81. php_printf("bool(%s)\n", var->BooleanValue() ? "true" : "false");
  82. return;
  83. }
  84. v8::TryCatch try_catch; /* object.toString() can throw an exception */
  85. v8::Local<v8::String> details;
  86. if(var->IsRegExp()) {
  87. v8::RegExp *re = v8::RegExp::Cast(*var);
  88. details = re->GetSource();
  89. }
  90. else {
  91. details = var->ToDetailString();
  92. if (try_catch.HasCaught()) {
  93. details = V8JS_SYM("<toString threw exception>");
  94. }
  95. }
  96. v8::String::Utf8Value str(details);
  97. const char *valstr = ToCString(str);
  98. size_t valstr_len = details->ToString()->Utf8Length();
  99. if (var->IsString())
  100. {
  101. php_printf("string(%zu) \"", valstr_len);
  102. PHPWRITE(valstr, valstr_len);
  103. php_printf("\"\n");
  104. }
  105. else if (var->IsDate())
  106. {
  107. // fake the fields of a PHP DateTime
  108. php_printf("Date(%s)\n", valstr);
  109. }
  110. else if (var->IsRegExp())
  111. {
  112. php_printf("regexp(/%s/)\n", valstr);
  113. }
  114. else if (var->IsArray())
  115. {
  116. v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);
  117. uint32_t length = array->Length();
  118. php_printf("array(%d) {\n", length);
  119. for (unsigned i = 0; i < length; i++) {
  120. php_printf("%*c[%d] =>\n", level * 2, ' ', i);
  121. v8js_dumper(isolate, array->Get(i), level + 1);
  122. }
  123. if (level > 1) {
  124. php_printf("%*c", (level - 1) * 2, ' ');
  125. }
  126. ZEND_PUTS("}\n");
  127. }
  128. else if (var->IsObject())
  129. {
  130. v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);
  131. V8JS_GET_CLASS_NAME(cname, object);
  132. int hash = object->GetIdentityHash();
  133. if (var->IsFunction() && strcmp(ToCString(cname), "Closure") != 0)
  134. {
  135. v8::String::Utf8Value csource(object->ToString());
  136. php_printf("object(Closure)#%d {\n%*c%s\n", hash, level * 2 + 2, ' ', ToCString(csource));
  137. }
  138. else
  139. {
  140. v8::Local<v8::Array> keys = object->GetOwnPropertyNames();
  141. uint32_t length = keys->Length();
  142. if (strcmp(ToCString(cname), "Array") == 0 ||
  143. strcmp(ToCString(cname), "V8Object") == 0) {
  144. php_printf("array");
  145. } else {
  146. php_printf("object(%s)#%d", ToCString(cname), hash);
  147. }
  148. php_printf(" (%d) {\n", length);
  149. for (unsigned i = 0; i < length; i++) {
  150. v8::Local<v8::String> key = keys->Get(i)->ToString();
  151. v8::String::Utf8Value kname(key);
  152. php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
  153. v8js_dumper(isolate, object->Get(key), level + 1);
  154. }
  155. }
  156. if (level > 1) {
  157. php_printf("%*c", (level - 1) * 2, ' ');
  158. }
  159. ZEND_PUTS("}\n");
  160. }
  161. else /* null, undefined, etc. */
  162. {
  163. php_printf("<%s>\n", valstr);
  164. }
  165. }
  166. /* }}} */
  167. /* global.var_dump - Dump JS values */
  168. V8JS_METHOD(var_dump) /* {{{ */
  169. {
  170. v8::Isolate *isolate = info.GetIsolate();
  171. for (int i = 0; i < info.Length(); i++) {
  172. v8js_dumper(isolate, info[i], 1);
  173. }
  174. info.GetReturnValue().Set(V8JS_NULL);
  175. }
  176. /* }}} */
  177. V8JS_METHOD(require)
  178. {
  179. v8::Isolate *isolate = info.GetIsolate();
  180. // Get the extension context
  181. v8::Local<v8::External> data = v8::Local<v8::External>::Cast(info.Data());
  182. v8js_ctx *c = static_cast<v8js_ctx*>(data->Value());
  183. // Check that we have a module loader
  184. if(Z_TYPE(c->module_loader) == IS_NULL) {
  185. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("No module loader")));
  186. return;
  187. }
  188. v8::String::Utf8Value module_id_v8(info[0]);
  189. const char *module_id = ToCString(module_id_v8);
  190. char *normalised_path, *module_name;
  191. if (Z_TYPE(c->module_normaliser) == IS_NULL) {
  192. // No custom normalisation routine registered, use internal one
  193. normalised_path = (char *)emalloc(PATH_MAX);
  194. module_name = (char *)emalloc(PATH_MAX);
  195. v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);
  196. }
  197. else {
  198. // Call custom normaliser
  199. int call_result;
  200. zval params[2];
  201. zval normaliser_result;
  202. zend_try {
  203. {
  204. isolate->Exit();
  205. v8::Unlocker unlocker(isolate);
  206. ZVAL_STRING(&params[0], c->modules_base.back());
  207. ZVAL_STRING(&params[1], module_id);
  208. call_result = call_user_function_ex(EG(function_table), NULL, &c->module_normaliser,
  209. &normaliser_result, 2, params, 0, NULL);
  210. }
  211. isolate->Enter();
  212. if (call_result == FAILURE) {
  213. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module normaliser callback failed")));
  214. }
  215. }
  216. zend_catch {
  217. v8js_terminate_execution(isolate);
  218. V8JSG(fatal_error_abort) = 1;
  219. call_result = FAILURE;
  220. }
  221. zend_end_try();
  222. zval_ptr_dtor(&params[0]);
  223. zval_ptr_dtor(&params[1]);
  224. if(call_result == FAILURE) {
  225. return;
  226. }
  227. // Check if an exception was thrown
  228. if (EG(exception)) {
  229. // Clear the PHP exception and throw it in V8 instead
  230. zend_clear_exception();
  231. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module normaliser callback exception")));
  232. return;
  233. }
  234. if (Z_TYPE(normaliser_result) != IS_ARRAY) {
  235. zval_ptr_dtor(&normaliser_result);
  236. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module normaliser didn't return an array")));
  237. return;
  238. }
  239. HashTable *ht = HASH_OF(&normaliser_result);
  240. int num_elements = zend_hash_num_elements(ht);
  241. if(num_elements != 2) {
  242. zval_ptr_dtor(&normaliser_result);
  243. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module normaliser expected to return array of 2 strings")));
  244. return;
  245. }
  246. zval *data;
  247. ulong index = 0;
  248. ZEND_HASH_FOREACH_VAL(ht, data) {
  249. if (Z_TYPE_P(data) != IS_STRING) {
  250. convert_to_string(data);
  251. }
  252. switch(index++) {
  253. case 0: // normalised path
  254. normalised_path = estrndup(Z_STRVAL_P(data), Z_STRLEN_P(data));
  255. break;
  256. case 1: // normalised module id
  257. module_name = estrndup(Z_STRVAL_P(data), Z_STRLEN_P(data));
  258. break;
  259. }
  260. }
  261. ZEND_HASH_FOREACH_END();
  262. zval_ptr_dtor(&normaliser_result);
  263. }
  264. char *normalised_module_id = (char *)emalloc(strlen(normalised_path)+1+strlen(module_name)+1);
  265. *normalised_module_id = 0;
  266. if (strlen(normalised_path) > 0) {
  267. strcat(normalised_module_id, normalised_path);
  268. strcat(normalised_module_id, "/");
  269. }
  270. strcat(normalised_module_id, module_name);
  271. efree(module_name);
  272. // Check for module cyclic dependencies
  273. for (std::vector<char *>::iterator it = c->modules_stack.begin(); it != c->modules_stack.end(); ++it)
  274. {
  275. if (!strcmp(*it, normalised_module_id)) {
  276. efree(normalised_module_id);
  277. efree(normalised_path);
  278. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module cyclic dependency")));
  279. return;
  280. }
  281. }
  282. // If we have already loaded and cached this module then use it
  283. if (c->modules_loaded.count(normalised_module_id) > 0) {
  284. v8::Persistent<v8::Object> newobj;
  285. newobj.Reset(isolate, c->modules_loaded[normalised_module_id]);
  286. info.GetReturnValue().Set(newobj);
  287. efree(normalised_module_id);
  288. efree(normalised_path);
  289. return;
  290. }
  291. // Callback to PHP to load the module code
  292. zval module_code;
  293. int call_result;
  294. zval params[1];
  295. {
  296. isolate->Exit();
  297. v8::Unlocker unlocker(isolate);
  298. zend_try {
  299. ZVAL_STRING(&params[0], normalised_module_id);
  300. call_result = call_user_function_ex(EG(function_table), NULL, &c->module_loader, &module_code, 1, params, 0, NULL);
  301. }
  302. zend_catch {
  303. v8js_terminate_execution(isolate);
  304. V8JSG(fatal_error_abort) = 1;
  305. }
  306. zend_end_try();
  307. }
  308. isolate->Enter();
  309. if (V8JSG(fatal_error_abort)) {
  310. call_result = FAILURE;
  311. }
  312. else if (call_result == FAILURE) {
  313. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module loader callback failed")));
  314. }
  315. zval_ptr_dtor(&params[0]);
  316. if (call_result == FAILURE) {
  317. efree(normalised_module_id);
  318. efree(normalised_path);
  319. return;
  320. }
  321. // Check if an exception was thrown
  322. if (EG(exception)) {
  323. efree(normalised_module_id);
  324. efree(normalised_path);
  325. // Clear the PHP exception and throw it in V8 instead
  326. zend_clear_exception();
  327. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module loader callback exception")));
  328. return;
  329. }
  330. // Convert the return value to string
  331. if (Z_TYPE(module_code) != IS_STRING) {
  332. convert_to_string(&module_code);
  333. }
  334. // Create a template for the global object and set the built-in global functions
  335. v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
  336. global_template->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(isolate, V8JS_MN(print)), v8::ReadOnly);
  337. global_template->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(isolate, V8JS_MN(var_dump)), v8::ReadOnly);
  338. global_template->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(isolate, V8JS_MN(sleep)), v8::ReadOnly);
  339. global_template->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(isolate, V8JS_MN(require), v8::External::New(isolate, c)), v8::ReadOnly);
  340. // Add the exports object in which the module can return its API
  341. v8::Local<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
  342. global_template->Set(V8JS_SYM("exports"), exports_template);
  343. // Add the module object in which the module can have more fine-grained control over what it can return
  344. v8::Local<v8::ObjectTemplate> module_template = v8::ObjectTemplate::New();
  345. module_template->Set(V8JS_SYM("id"), V8JS_STR(normalised_module_id));
  346. global_template->Set(V8JS_SYM("module"), module_template);
  347. // Each module gets its own context so different modules do not affect each other
  348. v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, v8::Context::New(isolate, NULL, global_template));
  349. // Catch JS exceptions
  350. v8::TryCatch try_catch;
  351. v8::Locker locker(isolate);
  352. v8::Isolate::Scope isolate_scope(isolate);
  353. v8::HandleScope handle_scope(isolate);
  354. // Enter the module context
  355. v8::Context::Scope scope(context);
  356. // Set script identifier
  357. v8::Local<v8::String> sname = V8JS_STR(normalised_module_id);
  358. if (Z_STRLEN(module_code) > std::numeric_limits<int>::max()) {
  359. zend_throw_exception(php_ce_v8js_exception,
  360. "Module code size exceeds maximum supported length", 0);
  361. return;
  362. }
  363. v8::Local<v8::String> source = V8JS_STRL(Z_STRVAL(module_code), static_cast<int>(Z_STRLEN(module_code)));
  364. zval_ptr_dtor(&module_code);
  365. // Create and compile script
  366. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  367. // The script will be empty if there are compile errors
  368. if (script.IsEmpty()) {
  369. efree(normalised_module_id);
  370. efree(normalised_path);
  371. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module script compile failed")));
  372. return;
  373. }
  374. // Add this module and path to the stack
  375. c->modules_stack.push_back(normalised_module_id);
  376. c->modules_base.push_back(normalised_path);
  377. // Run script
  378. script->Run();
  379. // Remove this module and path from the stack
  380. c->modules_stack.pop_back();
  381. c->modules_base.pop_back();
  382. efree(normalised_path);
  383. // Script possibly terminated, return immediately
  384. if (!try_catch.CanContinue()) {
  385. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module script compile failed")));
  386. efree(normalised_module_id);
  387. return;
  388. }
  389. // Handle runtime JS exceptions
  390. if (try_catch.HasCaught()) {
  391. // Rethrow the exception back to JS
  392. info.GetReturnValue().Set(try_catch.ReThrow());
  393. efree(normalised_module_id);
  394. return;
  395. }
  396. v8::Local<v8::Object> newobj;
  397. // Cache the module so it doesn't need to be compiled and run again
  398. // Ensure compatibility with CommonJS implementations such as NodeJS by playing nicely with module.exports and exports
  399. if (context->Global()->Has(V8JS_SYM("module"))
  400. && context->Global()->Get(V8JS_SYM("module"))->IsObject()
  401. && context->Global()->Get(V8JS_SYM("module"))->ToObject()->Has(V8JS_SYM("exports"))
  402. && context->Global()->Get(V8JS_SYM("module"))->ToObject()->Get(V8JS_SYM("exports"))->IsObject()) {
  403. // If module.exports has been set then we cache this arbitrary value...
  404. newobj = context->Global()->Get(V8JS_SYM("module"))->ToObject()->Get(V8JS_SYM("exports"))->ToObject();
  405. } else {
  406. // ...otherwise we cache the exports object itself
  407. newobj = context->Global()->Get(V8JS_SYM("exports"))->ToObject();
  408. }
  409. c->modules_loaded[normalised_module_id].Reset(isolate, newobj);
  410. info.GetReturnValue().Set(newobj);
  411. }
  412. void v8js_register_methods(v8::Local<v8::ObjectTemplate> global, v8js_ctx *c) /* {{{ */
  413. {
  414. v8::Isolate *isolate = c->isolate;
  415. global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(isolate, V8JS_MN(exit)), v8::ReadOnly);
  416. global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(isolate, V8JS_MN(sleep)), v8::ReadOnly);
  417. global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(isolate, V8JS_MN(print)), v8::ReadOnly);
  418. global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(isolate, V8JS_MN(var_dump)), v8::ReadOnly);
  419. c->modules_base.push_back("");
  420. global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(isolate, V8JS_MN(require), v8::External::New(isolate, c)), v8::ReadOnly);
  421. }
  422. /* }}} */
  423. /*
  424. * Local variables:
  425. * tab-width: 4
  426. * c-basic-offset: 4
  427. * indent-tabs-mode: t
  428. * End:
  429. * vim600: noet sw=4 ts=4 fdm=marker
  430. * vim<600: noet sw=4 ts=4
  431. */