v8js_methods.cc 11 KB

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