v8js_methods.cc 16 KB

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