v8js_methods.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2013 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. +----------------------------------------------------------------------+
  12. */
  13. #ifdef HAVE_CONFIG_H
  14. #include "config.h"
  15. #endif
  16. #include "php_v8js_macros.h"
  17. extern "C" {
  18. #include "zend_exceptions.h"
  19. }
  20. /* Forward declarations */
  21. void v8js_commonjs_normalise_identifier(char *base, char *identifier, char *normalised_path, char *module_name);
  22. /* global.exit - terminate execution */
  23. V8JS_METHOD(exit) /* {{{ */
  24. {
  25. v8::Isolate *isolate = info.GetIsolate();
  26. /* Unfortunately just calling TerminateExecution on the isolate is not
  27. * enough, since v8 just marks the thread as "to be aborted" and doesn't
  28. * immediately do so. Hence we enter an endless loop after signalling
  29. * termination, so we definitely don't execute JS code after the exit()
  30. * statement. */
  31. v8::Locker locker(isolate);
  32. v8::Isolate::Scope isolate_scope(isolate);
  33. v8::HandleScope handle_scope(isolate);
  34. v8::Local<v8::String> source = V8JS_STR("for(;;);");
  35. v8::Local<v8::Script> script = v8::Script::Compile(source);
  36. v8::V8::TerminateExecution(isolate);
  37. script->Run();
  38. }
  39. /* }}} */
  40. /* global.sleep - sleep for passed seconds */
  41. V8JS_METHOD(sleep) /* {{{ */
  42. {
  43. php_sleep(info[0]->Int32Value());
  44. }
  45. /* }}} */
  46. /* global.print - php print() */
  47. V8JS_METHOD(print) /* {{{ */
  48. {
  49. v8::Isolate *isolate = info.GetIsolate();
  50. int ret = 0;
  51. V8JS_TSRMLS_FETCH();
  52. for (int i = 0; i < info.Length(); i++) {
  53. v8::String::Utf8Value str(info[i]);
  54. const char *cstr = ToCString(str);
  55. ret = PHPWRITE(cstr, strlen(cstr));
  56. }
  57. info.GetReturnValue().Set(V8JS_INT(ret));
  58. }
  59. /* }}} */
  60. static void v8js_dumper(v8::Isolate *isolate, v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
  61. {
  62. if (level > 1) {
  63. php_printf("%*c", (level - 1) * 2, ' ');
  64. }
  65. if (var.IsEmpty())
  66. {
  67. php_printf("<empty>\n");
  68. return;
  69. }
  70. if (var->IsNull() || var->IsUndefined() /* PHP compat */)
  71. {
  72. php_printf("NULL\n");
  73. return;
  74. }
  75. if (var->IsInt32())
  76. {
  77. php_printf("int(%ld)\n", (long) var->IntegerValue());
  78. return;
  79. }
  80. if (var->IsUint32())
  81. {
  82. php_printf("int(%lu)\n", (unsigned long) var->IntegerValue());
  83. return;
  84. }
  85. if (var->IsNumber())
  86. {
  87. php_printf("float(%f)\n", var->NumberValue());
  88. return;
  89. }
  90. if (var->IsBoolean())
  91. {
  92. php_printf("bool(%s)\n", var->BooleanValue() ? "true" : "false");
  93. return;
  94. }
  95. v8::TryCatch try_catch; /* object.toString() can throw an exception */
  96. v8::Local<v8::String> details = var->ToDetailString();
  97. if (try_catch.HasCaught()) {
  98. details = V8JS_SYM("<toString threw exception>");
  99. }
  100. v8::String::Utf8Value str(details);
  101. const char *valstr = ToCString(str);
  102. size_t valstr_len = details->ToString()->Utf8Length();
  103. if (var->IsString())
  104. {
  105. php_printf("string(%zu) \"", valstr_len, valstr);
  106. PHPWRITE(valstr, valstr_len);
  107. php_printf("\"\n");
  108. }
  109. else if (var->IsDate())
  110. {
  111. // fake the fields of a PHP DateTime
  112. php_printf("Date(%s)\n", valstr);
  113. }
  114. else if (var->IsRegExp())
  115. {
  116. php_printf("regexp(%s)\n", valstr);
  117. }
  118. else if (var->IsArray())
  119. {
  120. v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);
  121. uint32_t length = array->Length();
  122. php_printf("array(%d) {\n", length);
  123. for (unsigned i = 0; i < length; i++) {
  124. php_printf("%*c[%d] =>\n", level * 2, ' ', i);
  125. v8js_dumper(isolate, array->Get(i), level + 1 TSRMLS_CC);
  126. }
  127. if (level > 1) {
  128. php_printf("%*c", (level - 1) * 2, ' ');
  129. }
  130. ZEND_PUTS("}\n");
  131. }
  132. else if (var->IsObject())
  133. {
  134. v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);
  135. V8JS_GET_CLASS_NAME(cname, object);
  136. int hash = object->GetIdentityHash();
  137. if (var->IsFunction())
  138. {
  139. v8::String::Utf8Value csource(object->ToString());
  140. php_printf("object(Closure)#%d {\n%*c%s\n", hash, level * 2 + 2, ' ', ToCString(csource));
  141. }
  142. else
  143. {
  144. v8::Local<v8::Array> keys = object->GetOwnPropertyNames();
  145. uint32_t length = keys->Length();
  146. if (strcmp(ToCString(cname), "Array") == 0 ||
  147. strcmp(ToCString(cname), "V8Object") == 0) {
  148. php_printf("array");
  149. } else {
  150. php_printf("object(%s)#%d", ToCString(cname), hash);
  151. }
  152. php_printf(" (%d) {\n", length);
  153. for (unsigned i = 0; i < length; i++) {
  154. v8::Local<v8::String> key = keys->Get(i)->ToString();
  155. v8::String::Utf8Value kname(key);
  156. php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
  157. v8js_dumper(isolate, object->Get(key), level + 1 TSRMLS_CC);
  158. }
  159. }
  160. if (level > 1) {
  161. php_printf("%*c", (level - 1) * 2, ' ');
  162. }
  163. ZEND_PUTS("}\n");
  164. }
  165. else /* null, undefined, etc. */
  166. {
  167. php_printf("<%s>\n", valstr);
  168. }
  169. }
  170. /* }}} */
  171. /* global.var_dump - Dump JS values */
  172. V8JS_METHOD(var_dump) /* {{{ */
  173. {
  174. v8::Isolate *isolate = info.GetIsolate();
  175. V8JS_TSRMLS_FETCH();
  176. for (int i = 0; i < info.Length(); i++) {
  177. v8js_dumper(isolate, info[i], 1 TSRMLS_CC);
  178. }
  179. info.GetReturnValue().Set(V8JS_NULL);
  180. }
  181. /* }}} */
  182. V8JS_METHOD(require)
  183. {
  184. v8::Isolate *isolate = info.GetIsolate();
  185. V8JS_TSRMLS_FETCH();
  186. // Get the extension context
  187. v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(info.Data());
  188. v8js_ctx *c = static_cast<v8js_ctx*>(data->Value());
  189. // Check that we have a module loader
  190. if (c->module_loader == NULL) {
  191. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("No module loader")));
  192. return;
  193. }
  194. v8::String::Utf8Value module_id_v8(info[0]);
  195. // Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector
  196. char *module_id = estrdup(ToCString(module_id_v8));
  197. char *normalised_path = (char *)emalloc(PATH_MAX);
  198. char *module_name = (char *)emalloc(PATH_MAX);
  199. v8js_commonjs_normalise_identifier(c->modules_base.back(), module_id, normalised_path, module_name);
  200. efree(module_id);
  201. char *normalised_module_id = (char *)emalloc(strlen(normalised_path)+1+strlen(module_name)+1);
  202. *normalised_module_id = 0;
  203. if (strlen(normalised_path) > 0) {
  204. strcat(normalised_module_id, normalised_path);
  205. strcat(normalised_module_id, "/");
  206. }
  207. strcat(normalised_module_id, module_name);
  208. efree(module_name);
  209. // Check for module cyclic dependencies
  210. for (std::vector<char *>::iterator it = c->modules_stack.begin(); it != c->modules_stack.end(); ++it)
  211. {
  212. if (!strcmp(*it, normalised_module_id)) {
  213. efree(normalised_module_id);
  214. efree(normalised_path);
  215. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module cyclic dependency")));
  216. return;
  217. }
  218. }
  219. // If we have already loaded and cached this module then use it
  220. if (c->modules_loaded.count(normalised_module_id) > 0) {
  221. efree(normalised_module_id);
  222. efree(normalised_path);
  223. v8::Persistent<v8::Object> newobj;
  224. newobj.Reset(isolate, c->modules_loaded[normalised_module_id]);
  225. info.GetReturnValue().Set(newobj);
  226. return;
  227. }
  228. // Callback to PHP to load the module code
  229. zval *module_code;
  230. zval *normalised_path_zend;
  231. MAKE_STD_ZVAL(normalised_path_zend);
  232. ZVAL_STRING(normalised_path_zend, normalised_module_id, 1);
  233. zval **params[1] = {&normalised_path_zend};
  234. if (FAILURE == call_user_function_ex(EG(function_table), NULL, c->module_loader, &module_code, 1, params, 0, NULL TSRMLS_CC)) {
  235. zval_ptr_dtor(&normalised_path_zend);
  236. efree(normalised_module_id);
  237. efree(normalised_path);
  238. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module loader callback failed")));
  239. return;
  240. }
  241. zval_ptr_dtor(&normalised_path_zend);
  242. // Check if an exception was thrown
  243. if (EG(exception)) {
  244. efree(normalised_module_id);
  245. efree(normalised_path);
  246. // Clear the PHP exception and throw it in V8 instead
  247. zend_clear_exception(TSRMLS_C);
  248. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module loader callback exception")));
  249. return;
  250. }
  251. // Convert the return value to string
  252. if (Z_TYPE_P(module_code) != IS_STRING) {
  253. convert_to_string(module_code);
  254. }
  255. // Check that some code has been returned
  256. if (Z_STRLEN_P(module_code)==0) {
  257. zval_ptr_dtor(&module_code);
  258. efree(normalised_module_id);
  259. efree(normalised_path);
  260. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module loader callback did not return code")));
  261. return;
  262. }
  263. // Create a template for the global object and set the built-in global functions
  264. v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
  265. global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(isolate, V8JS_MN(print)), v8::ReadOnly);
  266. global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(isolate, V8JS_MN(sleep)), v8::ReadOnly);
  267. global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(isolate, V8JS_MN(require), v8::External::New(isolate, c)), v8::ReadOnly);
  268. // Add the exports object in which the module can return its API
  269. v8::Local<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
  270. v8::Local<v8::Object> exports = exports_template->NewInstance();
  271. global->Set(V8JS_SYM("exports"), exports);
  272. // Add the module object in which the module can have more fine-grained control over what it can return
  273. v8::Handle<v8::ObjectTemplate> module_template = v8::ObjectTemplate::New();
  274. v8::Handle<v8::Object> module = module_template->NewInstance();
  275. module->Set(V8JS_SYM("id"), V8JS_STR(normalised_module_id));
  276. global->Set(V8JS_SYM("module"), module);
  277. // Each module gets its own context so different modules do not affect each other
  278. v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, v8::Context::New(isolate, NULL, global));
  279. // Catch JS exceptions
  280. v8::TryCatch try_catch;
  281. v8::Locker locker(isolate);
  282. v8::Isolate::Scope isolate_scope(isolate);
  283. v8::HandleScope handle_scope(isolate);
  284. // Enter the module context
  285. v8::Context::Scope scope(context);
  286. // Set script identifier
  287. v8::Local<v8::String> sname = V8JS_SYM("require");
  288. v8::Local<v8::String> source = V8JS_STRL(Z_STRVAL_P(module_code), Z_STRLEN_P(module_code));
  289. zval_ptr_dtor(&module_code);
  290. // Create and compile script
  291. v8::Local<v8::Script> script = v8::Script::Compile(source, sname);
  292. // The script will be empty if there are compile errors
  293. if (script.IsEmpty()) {
  294. efree(normalised_module_id);
  295. efree(normalised_path);
  296. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module script compile failed")));
  297. return;
  298. }
  299. // Add this module and path to the stack
  300. c->modules_stack.push_back(normalised_module_id);
  301. c->modules_base.push_back(normalised_path);
  302. // Run script
  303. v8::Local<v8::Value> result = script->Run();
  304. // Remove this module and path from the stack
  305. c->modules_stack.pop_back();
  306. c->modules_base.pop_back();
  307. efree(normalised_path);
  308. // Script possibly terminated, return immediately
  309. if (!try_catch.CanContinue()) {
  310. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Module script compile failed")));
  311. efree(normalised_module_id);
  312. return;
  313. }
  314. // Handle runtime JS exceptions
  315. if (try_catch.HasCaught()) {
  316. // Rethrow the exception back to JS
  317. info.GetReturnValue().Set(try_catch.ReThrow());
  318. efree(normalised_module_id);
  319. return;
  320. }
  321. v8::Handle<v8::Object> newobj;
  322. // Cache the module so it doesn't need to be compiled and run again
  323. // Ensure compatibility with CommonJS implementations such as NodeJS by playing nicely with module.exports and exports
  324. if (module->Has(V8JS_SYM("exports")) && !module->Get(V8JS_SYM("exports"))->IsUndefined()) {
  325. // If module.exports has been set then we cache this arbitrary value...
  326. newobj = module->Get(V8JS_SYM("exports"))->ToObject();
  327. } else {
  328. // ...otherwise we cache the exports object itself
  329. newobj = exports;
  330. }
  331. c->modules_loaded[normalised_module_id].Reset(isolate, newobj);
  332. info.GetReturnValue().Set(newobj);
  333. efree(normalised_module_id);
  334. }
  335. void v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, v8js_ctx *c) /* {{{ */
  336. {
  337. v8::Isolate *isolate = c->isolate;
  338. global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(isolate, V8JS_MN(exit)), v8::ReadOnly);
  339. global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(isolate, V8JS_MN(sleep)), v8::ReadOnly);
  340. global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(isolate, V8JS_MN(print)), v8::ReadOnly);
  341. global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(isolate, V8JS_MN(var_dump)), v8::ReadOnly);
  342. c->modules_base.push_back("");
  343. global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(isolate, V8JS_MN(require), v8::External::New(isolate, c)), v8::ReadOnly);
  344. }
  345. /* }}} */
  346. /*
  347. * Local variables:
  348. * tab-width: 4
  349. * c-basic-offset: 4
  350. * End:
  351. * vim600: noet sw=4 ts=4 fdm=marker
  352. * vim<600: noet sw=4 ts=4
  353. */