v8js_methods.cc 11 KB

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