v8js_methods.cc 10 KB

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