rh.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #include "rh.h"
  2. #include "mem.h"
  3. #include "monolog.h"
  4. #include "state.h"
  5. #include <string.h>
  6. #include <stdarg.h>
  7. #include <mruby.h>
  8. #include <mruby/error.h>
  9. #include <mruby/variable.h>
  10. #include "esh.h"
  11. #include "config.h"
  12. /* Debugging level for console output. */
  13. #define LOG_CONSOLE(FORMAT, ...) LOG_LEVEL("CONSOLE", FORMAT, __VA_ARGS__)
  14. #define LOG_ENABLE_CONSOLE() LOG_ENABLE(CONSOLE)
  15. #define LOG_DISABLE_CONSOLE() LOG_DISABLE(CONSOLE)
  16. /* Amount of parameters a mruby function can be called with using _va functions */
  17. #define RH_ARGS_MAX 64
  18. /*
  19. * RH contains helper functions for the mruby ruby interpreter.
  20. */
  21. /*
  22. * Converts C like arguments to an array of mruby mrb_values.
  23. * Returns amount of arguments parsed, negative on failure.
  24. *
  25. * Format specifier characters for the format argument:
  26. *
  27. * z: String from null terminated C string [char*]
  28. * s: String [char*, int]
  29. * Y: sYmbol from null terminated C string [char*]
  30. * y: symbol [char*, int]
  31. *
  32. * f: Float [double]
  33. * i: Integer [int]
  34. * b: Boolean [int]
  35. * 0: nil
  36. * Other characters: Error. Will return -(index or erroneous character) .
  37. */
  38. int rh_args_va(Ruby * ruby, mrb_value * values, int size, char * format, va_list list) {
  39. int ch; int index;
  40. int i; double d; const char * str;
  41. index = 0;
  42. for (ch = (*format) ; (ch) && (index < size) ; format++ , ch = (*format)) {
  43. mrb_value val;
  44. int error = FALSE;
  45. switch(ch) {
  46. case 's':
  47. str = va_arg(list, const char*);
  48. i = va_arg(list, int);
  49. val = mrb_str_new(ruby, str, i);
  50. break;
  51. case 'z':
  52. str = va_arg(list, const char*);
  53. val = mrb_str_new_cstr(ruby, str);
  54. break;
  55. case 'y':
  56. str = va_arg(list, const char*);
  57. i = va_arg(list, int);
  58. val = mrb_symbol_value(mrb_intern(ruby, str, (size_t)i));
  59. break;
  60. case 'Y':
  61. str = va_arg(list, const char*);
  62. val = mrb_symbol_value(mrb_intern_cstr(ruby, str));
  63. break;
  64. case 'i':
  65. i = va_arg(list, int);
  66. val = mrb_fixnum_value(i);
  67. break;
  68. case 'f':
  69. d = va_arg(list, double);
  70. val = mrb_float_value(ruby, d);
  71. break;
  72. case 'b':
  73. i = va_arg(list, int);
  74. val = ( i ? mrb_true_value() : mrb_false_value());
  75. break;
  76. case '0':
  77. val = mrb_nil_value();
  78. break;
  79. default:
  80. error = TRUE;
  81. break;
  82. }
  83. if (error) {
  84. return -index;
  85. }
  86. values[index] = val;
  87. index ++;
  88. }
  89. return index;
  90. }
  91. /* strdup isn't ANSI C, just posix... :p so we need our own version.*/
  92. char *rh_strdup(const char *str) {
  93. char * res = malloc(strlen(str) + 1);
  94. if(res) { strcpy(res, str); }
  95. return res;
  96. }
  97. /* Helps convert C values to mruby values in an array. */
  98. int rh_args(Ruby * ruby, mrb_value * values, int size, char * format, ...) {
  99. int res;
  100. va_list list;
  101. va_start(list, format);
  102. res = rh_args_va(ruby, values, size, format, list);
  103. va_end(list);
  104. return res;
  105. }
  106. /** Calulates the execption string. Result only tempoarily available..
  107. XXX: check if this doesn't leak memory... you must free the results manually.
  108. */
  109. char * rh_exceptionstring(Ruby * self) {
  110. char * result;
  111. mrb_value value;
  112. mrb_value backtrace;
  113. mrb_value backtrace_str;
  114. if (!self->exc) return NULL;
  115. //
  116. /* XXX: Too bad, the backtrace doesn't seem to be filled in for some reason...
  117. * Should figure out how to fix this.
  118. */
  119. mrb_print_backtrace(self);
  120. backtrace = // mrb_get_backtrace(self);
  121. mrb_funcall(self, mrb_obj_value(self->exc), "backtrace", 0);
  122. backtrace_str = mrb_funcall(self, backtrace, "join", 1, mrb_str_new_lit(self, "\n"));
  123. LOG_ERROR("backtrace: %s\n", mrb_string_value_cstr(self, &backtrace_str));
  124. value = mrb_funcall(self, mrb_obj_value(self->exc), "inspect", 0);
  125. // reset exception since we have it's string value.
  126. // Does this leak memory or not???
  127. self->exc = NULL;
  128. return rh_strdup(mrb_string_value_cstr(self, &value));
  129. }
  130. /** Allocates and initialzes a new ruby state. */
  131. Ruby * rh_new() {
  132. Ruby * self = mrb_open();
  133. /*mrb_define_method(self, self->kernel_module,
  134. "path", tr_Path, ARGS_REQ(1));*/
  135. return self;
  136. }
  137. /** Frees a ruby state. */
  138. Ruby * rh_free(Ruby * self) {
  139. mrb_close(self);
  140. return NULL;
  141. }
  142. /** Returns an mrb_value that contains the value of object.inspect.
  143. */
  144. mrb_value rh_inspect(mrb_state *mrb, mrb_value obj) {
  145. return mrb_inspect(mrb, obj);
  146. }
  147. char * rh_inspect_cstr(mrb_state *mrb, mrb_value value) {
  148. mrb_value res = rh_inspect(mrb, value);
  149. /* XXX: check that it's not modified anywere or export the const? */
  150. return (char *) mrb_string_value_cstr(mrb, &res);
  151. }
  152. /* Does the actual reporting depending on the current state of
  153. ruby and the returned value. */
  154. int rh_make_report(Ruby * self, mrb_value v) {
  155. int res = 0;
  156. char * str;
  157. /* Report exceptions */
  158. str = rh_exceptionstring(self);
  159. if(str) {
  160. LOG_WARNING("mruby exception: %s\n", str);
  161. free(str);
  162. return 0;
  163. }
  164. /* Report result value if it's not nil on debug and console levels.
  165. */
  166. if (!mrb_nil_p(v)) {
  167. str = rh_inspect_cstr(self, v);
  168. LOG_DEBUG("mruby result: %s\n", str);
  169. LOG_CONSOLE("-> %s\n", str);
  170. return 0;
  171. }
  172. return 0;
  173. }
  174. /* Runs a file and reports any errors over the monolog logging system. */
  175. int rh_run_file(Ruby * self, const char * filename, FILE * file) {
  176. int res;
  177. char * str;
  178. mrbc_context * c ;
  179. mrb_value v;
  180. int ai;
  181. ai = mrb_gc_arena_save(self);
  182. c = mrbc_context_new(self);
  183. mrbc_filename(self, c, filename);
  184. v = mrb_load_file_cxt(self, file, c);
  185. mrbc_context_free(self, c);
  186. /* Report exceptions */
  187. res = rh_make_report(self, v);
  188. mrb_gc_arena_restore(self, ai);
  189. return res;
  190. }
  191. int rh_run_filename(Ruby * self, const char * filename) {
  192. FILE * file = fopen(filename, "rt");
  193. int res;
  194. if (!file) {
  195. LOG_ERROR("No such ruby file: %s\n", filename);
  196. return -1;
  197. }
  198. res = rh_run_file(self, filename, file);
  199. fclose(file);
  200. return 0;
  201. }
  202. /**
  203. * Executes a ruby file in Eruta's data/script directory with reporting.
  204. * Returns -2 if the file was not found.
  205. * Returns -3 if the path wasn't found.
  206. */
  207. int rh_run_script(Ruby * self, const char * filename) {
  208. struct woesb path = {0};
  209. int runres;
  210. if (!woesb_new_join(&path, MRB_WOE_CONFIG(self)->data_dir, "/script/", filename, NULL)) {
  211. woesb_free(&path);
  212. LOG_ERROR("Out of memory when joining path.\n");
  213. return -3;
  214. }
  215. if (strstr(path.text, "..")) {
  216. woesb_free(&path);
  217. LOG_ERROR("Path may not contain '..' \n");
  218. return -4;
  219. }
  220. runres = rh_run_filename(self, path.text);
  221. woesb_free(&path);
  222. return runres;
  223. }
  224. /* Executes a ruby command string.
  225. Errors are reported to the reporter callback if it isn't NULL. */
  226. int rh_dostring(Ruby * self, const char * command) {
  227. int res = 0;
  228. char * str;
  229. mrb_value v;
  230. int ai;
  231. ai = mrb_gc_arena_save(self);
  232. #ifdef RH_USE_CONTEXT
  233. mrbc_context * c = mrbc_context_new(self);
  234. mrbc_filename(self, c, "command");
  235. v = mrb_load_string_cxt(self, command, c);
  236. mrbc_context_free(self, c);
  237. #else
  238. v = mrb_load_string(self, command);
  239. #endif
  240. /* Report exceptions */
  241. res = rh_make_report(self, v);
  242. /* mrb GC area seems to be an area for 1024 "new" objects for the generational
  243. * GC. It can overflow if a lot of new objects are generated
  244. * (say exceptions, etc) on the C side. To prevent this the area must be saved
  245. * and restored anywhere many ruby objects may have been generated.
  246. * It seems that here too this is needed.
  247. */
  248. mrb_gc_arena_restore(self, ai);
  249. return res;
  250. }
  251. /* Executes a ruby function with parameters.
  252. Errors are reported to the reporter callback if it isn't NULL. */
  253. mrb_value rh_run_function_args(Ruby * self, mrb_value rubyself, char * funcname,
  254. int argc, mrb_value * argv) {
  255. int res = 0;
  256. char * str;
  257. mrb_value v;
  258. mrb_sym symname = mrb_intern_cstr(self, funcname);
  259. int ai;
  260. if(!mrb_respond_to(self, rubyself, symname)) {
  261. return mrb_nil_value();
  262. }
  263. ai = mrb_gc_arena_save(self);
  264. v = mrb_funcall_argv(self, rubyself, symname, argc, argv);
  265. res = rh_make_report(self, v);
  266. mrb_gc_arena_restore(self, ai);
  267. return v;
  268. }
  269. /** Runs a function in the ruby interpreter, with C arguments according to the
  270. * given format string, logging results and errors back to
  271. * the reporter. The limit is RH_ARGS_MAX arguments.
  272. */
  273. mrb_value
  274. rh_run_function_va(Ruby * self, mrb_value rubyself, char * funcname,
  275. char * format, va_list list) {
  276. mrb_value argv[RH_ARGS_MAX];
  277. int argc;
  278. argc = rh_args_va(self, argv, RH_ARGS_MAX, format, list);
  279. if (argc < 0) return mrb_nil_value();
  280. return rh_run_function_args(self, rubyself, funcname, argc, argv);
  281. }
  282. /** Runs a function in the ruby interpreter, under the toplevel self.
  283. * This logs results and errors using monolog.h interfaces.
  284. */
  285. mrb_value rh_run_toplevel_args(Ruby * ruby, char * name, int argc, mrb_value * argv) {
  286. return rh_run_function_args(ruby, mrb_top_self(ruby), name, argc, argv);
  287. }
  288. /** Runs a function in the ruby interpreter, under the toplevel self.
  289. * This logs results and errors using monolog.h interfaces.
  290. */
  291. mrb_value rh_run_toplevel_va(Ruby * ruby, char * name, char * format, va_list list) {
  292. return rh_run_function_va(ruby, mrb_top_self(ruby), name, format, list);
  293. }
  294. /** Runs a function in the ruby interpreter, logging results and errors
  295. * using monolog.h interfaces.
  296. */
  297. mrb_value rh_run_function(Ruby * ruby, mrb_value rubyself,
  298. char * name, char * format, ...) {
  299. mrb_value res;
  300. va_list list;
  301. va_start(list, format);
  302. res = rh_run_function_va(ruby, rubyself, name, format, list);
  303. va_end(list);
  304. return res;
  305. }
  306. /** Runs a function in the ruby interpreter, under the toplevel self.
  307. * This logs results and errors using monolog.h interfaces.
  308. */
  309. mrb_value rh_run_toplevel(Ruby * ruby, char * name, char * format, ...) {
  310. mrb_value res;
  311. va_list list;
  312. va_start(list, format);
  313. res = rh_run_function_va(ruby, mrb_top_self(ruby), name, format, list);
  314. va_end(list);
  315. return res;
  316. }
  317. /* Calls a function, doesn't log anything. */
  318. mrb_value rh_simple_funcall(Ruby * ruby, char * name) {
  319. int ai;
  320. Ruby * mrb = (Ruby *) ruby;
  321. mrb_value args[16];
  322. ai = mrb_gc_arena_save(mrb);
  323. LOG("GC Area: %d\n", ai);
  324. // if(ai> 99) exit(0);
  325. mrb_value v = mrb_funcall_argv(mrb, mrb_top_self(mrb), mrb_intern_cstr(mrb, name),
  326. 0, args);
  327. if (mrb->exc) {
  328. if (!mrb_undef_p(v)) {
  329. mrb_p(mrb, mrb_obj_value(mrb->exc));
  330. }
  331. return mrb_nil_value();
  332. }
  333. mrb_gc_arena_restore(mrb, 0);
  334. return v;
  335. }
  336. /* Maybe wrap this too?
  337. mrb_value mrb_funcall_argv(mrb_state*, mrb_value, mrb_sym, int, mrb_value*);
  338. */
  339. /* Converts and mrb_value to a C boolean as per the ruby interpretation. */
  340. int rh_tobool(mrb_value v) {
  341. if (mrb_nil_p(v)) return FALSE;
  342. return mrb_bool(v);
  343. }
  344. /* Documentation for mrb_get_args
  345. retrieve arguments from mrb_state.
  346. mrb_get_args(mrb, format, ...)
  347. returns number of arguments parsed.
  348. format specifiers:
  349. o: Object [mrb_value]
  350. S: String [mrb_value]
  351. A: Array [mrb_value]
  352. H: Hash [mrb_value]
  353. s: String [char*,int]
  354. z: String [char*]
  355. a: Array [mrb_value*,int]
  356. f: Float [mrb_float]
  357. i: Integer [mrb_int]
  358. n: Symbol [mrb_sym]
  359. &: Block [mrb_value]
  360. *: rest argument [mrb_value*,int]
  361. |: optional
  362. */
  363. /* Stores a pointer in the mrb state. Handy to avoid having to use global
  364. * variables o,n the C side. It's done by adding a ruby global variable
  365. * with a name that cannot be used from the mruby side. */
  366. void * rh_store_pointer(mrb_state * mrb, const char * name, void * ptr) {
  367. struct woesb hname;
  368. mrb_value val;
  369. mrb_sym rname;
  370. if (!woesb_new_join(&hname, "--", name, "--", NULL)) {
  371. woesb_free(&hname);
  372. LOG_ERROR("Out of memory when making hidden name.\n");
  373. return NULL;
  374. }
  375. rname = mrb_intern_cstr(mrb, hname.text);
  376. val = mrb_cptr_value(mrb, ptr);
  377. mrb_gv_set(mrb, rname, val);
  378. woesb_free(&hname);
  379. return ptr;
  380. }
  381. /** Fetches a previously stored pointer. */
  382. void * rh_fetch_pointer(mrb_state * mrb, const char * name) {
  383. struct woesb hname;
  384. mrb_value val;
  385. mrb_sym rname;
  386. if (!woesb_new_join(&hname, "--", name, "--", NULL)) {
  387. woesb_free(&hname);
  388. LOG_ERROR("Out of memory when making hidden name.\n");
  389. return NULL;
  390. }
  391. rname = mrb_intern_cstr(mrb, hname.text);
  392. val = mrb_gv_get(mrb, rname);
  393. woesb_free(&hname);
  394. return mrb_cptr(val);
  395. }
  396. /* Tries to (re-)load the main ruby file, output to console. */
  397. int rh_load_main() {
  398. return -1; /*rh_run_script(woe_global_ruby, "main.rb"); */
  399. }