v8js_methods.cc 12 KB

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