v8js_methods.cc 17 KB

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