v8js_methods.cc 12 KB

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