v8js_methods.cc 11 KB

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