v8js_methods.cc 12 KB

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