v8js_methods.cc 12 KB

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