v8js_methods.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. void split_terms(char *identifier, std::vector<char *> &terms)
  153. {
  154. char *term = (char *)malloc(PATH_MAX), *ptr = term;
  155. // Initialise the term string
  156. *term = 0;
  157. while (*identifier > 0) {
  158. if (*identifier == '/') {
  159. if (strlen(term) > 0) {
  160. // Terminate term string and add to terms vector
  161. *ptr++ = 0;
  162. terms.push_back(strdup(term));
  163. // Reset term string
  164. memset(term, 0, strlen(term));
  165. ptr = term;
  166. }
  167. } else {
  168. *ptr++ = *identifier;
  169. }
  170. identifier++;
  171. }
  172. if (strlen(term) > 0) {
  173. // Terminate term string and add to terms vector
  174. *ptr++ = 0;
  175. terms.push_back(strdup(term));
  176. }
  177. if (term > 0) {
  178. free(term);
  179. }
  180. }
  181. void normalize_identifier(char *identifier, char *normalised)
  182. {
  183. std::vector<char *> terms;
  184. split_terms(identifier, terms);
  185. std::vector<char *> normalised_terms;
  186. for (std::vector<char *>::iterator it = terms.begin(); it != terms.end(); it++) {
  187. char *term = *it;
  188. if (!strcmp(term, "..")) {
  189. normalised_terms.pop_back();
  190. } else if (strcmp(term, ".")) {
  191. normalised_terms.push_back(term);
  192. }
  193. }
  194. // Initialise the normalised string
  195. *normalised = 0;
  196. for (std::vector<char *>::iterator it = normalised_terms.begin(); it != normalised_terms.end(); it++) {
  197. char *term = *it;
  198. if (strlen(normalised) > 0) {
  199. strcat(normalised, "/");
  200. }
  201. strcat(normalised, term);
  202. }
  203. }
  204. V8JS_METHOD(require)
  205. {
  206. v8::String::Utf8Value module_name_v8(args[0]);
  207. // Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector
  208. char *module_name = strdup(ToCString(module_name_v8));
  209. char *normalised_module_identifier = (char *)malloc(strlen(module_name));
  210. normalize_identifier(module_name, normalised_module_identifier);
  211. // Check for module cyclic dependencies
  212. for (std::vector<char *>::iterator it = modules_stack.begin(); it != modules_stack.end(); ++it)
  213. {
  214. if (!strcmp(*it, normalised_module_identifier)) {
  215. return v8::ThrowException(v8::String::New("Module cyclic dependency"));
  216. }
  217. }
  218. // If we have already loaded and cached this module then use it
  219. if (modules_loaded.count(normalised_module_identifier) > 0) {
  220. return modules_loaded[normalised_module_identifier];
  221. }
  222. // Get the extension context
  223. v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(args.Data());
  224. php_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());
  225. // Check that we have a module loader
  226. if (c->module_loader == NULL) {
  227. return v8::ThrowException(v8::String::New("No module loader"));
  228. }
  229. // Callback to PHP to load the module code
  230. zval module_code;
  231. zval *module_name_zend;
  232. MAKE_STD_ZVAL(module_name_zend);
  233. ZVAL_STRING(module_name_zend, normalised_module_identifier, 1);
  234. zval* params[] = { module_name_zend };
  235. if (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {
  236. return v8::ThrowException(v8::String::New("Module loader callback failed"));
  237. }
  238. // Check if an exception was thrown
  239. if (EG(exception)) {
  240. // Clear the PHP exception and throw it in V8 instead
  241. zend_clear_exception(TSRMLS_CC);
  242. return v8::ThrowException(v8::String::New("Module loader callback exception 456"));
  243. }
  244. // Convert the return value to string
  245. if (Z_TYPE(module_code) != IS_STRING) {
  246. convert_to_string(&module_code);
  247. }
  248. // Check that some code has been returned
  249. if (!strlen(Z_STRVAL(module_code))) {
  250. return v8::ThrowException(v8::String::New("Module loader callback did not return code"));
  251. }
  252. // Create a template for the global object and set the built-in global functions
  253. v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
  254. global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
  255. global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
  256. // Add the exports object in which the module returns its API
  257. v8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
  258. v8::Handle<v8::Object> exports = exports_template->NewInstance();
  259. global->Set(v8::String::New("exports"), exports);
  260. // Each module gets its own context so different modules do not affect each other
  261. v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
  262. // Catch JS exceptions
  263. v8::TryCatch try_catch;
  264. // Enter the module context
  265. v8::Context::Scope scope(context);
  266. v8::HandleScope handle_scope;
  267. // Set script identifier
  268. v8::Local<v8::String> sname = V8JS_SYM("require");
  269. v8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));
  270. // Create and compile script
  271. v8::Local<v8::Script> script = v8::Script::New(source, sname);
  272. // The script will be empty if there are compile errors
  273. if (script.IsEmpty()) {
  274. return v8::ThrowException(v8::String::New("Module script compile failed"));
  275. }
  276. // Add this module to the stack
  277. modules_stack.push_back(normalised_module_identifier);
  278. // Run script
  279. v8::Local<v8::Value> result = script->Run();
  280. // Remove this module from the stack
  281. modules_stack.pop_back();
  282. // Script possibly terminated, return immediately
  283. if (!try_catch.CanContinue()) {
  284. return v8::ThrowException(v8::String::New("Module script compile failed"));
  285. }
  286. // Handle runtime JS exceptions
  287. if (try_catch.HasCaught()) {
  288. // Rethrow the exception back to JS
  289. return try_catch.ReThrow();
  290. }
  291. // Cache the module so it doesn't need to be compiled and run again
  292. modules_loaded[normalised_module_identifier] = handle_scope.Close(exports);
  293. return modules_loaded[normalised_module_identifier];
  294. }
  295. void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) /* {{{ */
  296. {
  297. global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);
  298. global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);
  299. global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
  300. global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);
  301. global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
  302. }
  303. /* }}} */
  304. /*
  305. * Local variables:
  306. * tab-width: 4
  307. * c-basic-offset: 4
  308. * End:
  309. * vim600: noet sw=4 ts=4 fdm=marker
  310. * vim<600: noet sw=4 ts=4
  311. */