NCDInterpreter.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /**
  2. * @file NCDInterpreter.c
  3. * @author Ambroz Bizjak <[email protected]>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <stdlib.h>
  32. #include <limits.h>
  33. #include <stdarg.h>
  34. #include <misc/offset.h>
  35. #include <misc/balloc.h>
  36. #include <misc/expstring.h>
  37. #include <base/BLog.h>
  38. #include <ncd/NCDConfigParser.h>
  39. #include <ncd/NCDSugar.h>
  40. #include <ncd/modules/modules.h>
  41. #include "NCDInterpreter.h"
  42. #include <generated/blog_channel_ncd.h>
  43. #define SSTATE_CHILD 0
  44. #define SSTATE_ADULT 1
  45. #define SSTATE_DYING 2
  46. #define SSTATE_FORGOTTEN 3
  47. #define PSTATE_WORKING 0
  48. #define PSTATE_UP 1
  49. #define PSTATE_WAITING 2
  50. #define PSTATE_TERMINATING 3
  51. struct statement {
  52. NCDModuleInst inst;
  53. NCDValMem args_mem;
  54. int mem_size;
  55. int i;
  56. };
  57. struct process {
  58. NCDInterpreter *interp;
  59. NCDInterpProcess *iprocess;
  60. NCDModuleProcess *module_process;
  61. BSmallTimer wait_timer;
  62. BSmallPending work_job;
  63. LinkedList1Node list_node; // node in processes
  64. int ap;
  65. int fp;
  66. int num_statements;
  67. int error;
  68. #ifndef NDEBUG
  69. int state;
  70. #endif
  71. struct statement statements[];
  72. };
  73. static void start_terminate (NCDInterpreter *interp, int exit_code);
  74. static char * implode_id_strings (NCDInterpreter *interp, const NCD_string_id_t *names, size_t num_names, char del);
  75. static int alloc_base_type_strings (NCDInterpreter *interp, const struct NCDModuleGroup *g);
  76. static int process_new (NCDInterpreter *interp, NCDInterpProcess *iprocess, NCDModuleProcess *module_process);
  77. static void process_free (struct process *p, NCDModuleProcess **out_mp);
  78. static void process_set_state (struct process *p, int state);
  79. static void process_start_terminating (struct process *p);
  80. static int process_have_child (struct process *p);
  81. static void process_assert_pointers (struct process *p);
  82. static void process_logfunc (struct process *p);
  83. static void process_log (struct process *p, int level, const char *fmt, ...);
  84. static void process_work_job_handler_working (struct process *p);
  85. static void process_work_job_handler_up (struct process *p);
  86. static void process_work_job_handler_waiting (struct process *p);
  87. static void process_work_job_handler_terminating (struct process *p);
  88. static int replace_placeholders_callback (void *arg, int plid, NCDValMem *mem, NCDValRef *out);
  89. static void process_advance (struct process *p);
  90. static void process_wait_timer_handler (BSmallTimer *timer);
  91. static int process_find_object (struct process *p, int pos, NCD_string_id_t name, NCDObject *out_object);
  92. static int process_resolve_object_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDObject *out_object);
  93. static int process_resolve_variable_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDValMem *mem, NCDValRef *out_value);
  94. static void statement_logfunc (struct statement *ps);
  95. static void statement_log (struct statement *ps, int level, const char *fmt, ...);
  96. static struct process * statement_process (struct statement *ps);
  97. static int statement_mem_is_allocated (struct statement *ps);
  98. static int statement_mem_size (struct statement *ps);
  99. static int statement_allocate_memory (struct statement *ps, int alloc_size);
  100. static void statement_instance_func_event (NCDModuleInst *inst, int event);
  101. static int statement_instance_func_getobj (NCDModuleInst *inst, NCD_string_id_t objname, NCDObject *out_object);
  102. static int statement_instance_func_initprocess (void *vinterp, NCDModuleProcess *mp, NCD_string_id_t template_name);
  103. static void statement_instance_logfunc (NCDModuleInst *inst);
  104. static void statement_instance_func_interp_exit (void *vinterp, int exit_code);
  105. static int statement_instance_func_interp_getargs (void *vinterp, NCDValMem *mem, NCDValRef *out_value);
  106. static btime_t statement_instance_func_interp_getretrytime (void *vinterp);
  107. static void process_moduleprocess_func_event (struct process *p, int event);
  108. static int process_moduleprocess_func_getobj (struct process *p, NCD_string_id_t name, NCDObject *out_object);
  109. int NCDInterpreter_Init (NCDInterpreter *o, const char *program, size_t program_len, struct NCDInterpreter_params params)
  110. {
  111. ASSERT(program);
  112. ASSERT(params.handler_finished);
  113. ASSERT(params.num_extra_args >= 0);
  114. ASSERT(params.reactor);
  115. #ifndef BADVPN_NO_PROCESS
  116. ASSERT(params.manager);
  117. #endif
  118. #ifndef BADVPN_NO_UDEV
  119. ASSERT(params.umanager);
  120. #endif
  121. #ifndef BADVPN_NO_RANDOM
  122. ASSERT(params.random2);
  123. #endif
  124. // set params
  125. o->params = params;
  126. // set not terminating
  127. o->terminating = 0;
  128. // init string index
  129. if (!NCDStringIndex_Init(&o->string_index)) {
  130. BLog(BLOG_ERROR, "NCDStringIndex_Init failed");
  131. goto fail0;
  132. }
  133. // init method index
  134. if (!NCDMethodIndex_Init(&o->method_index, &o->string_index)) {
  135. BLog(BLOG_ERROR, "NCDMethodIndex_Init failed");
  136. goto fail1;
  137. }
  138. // init module index
  139. if (!NCDModuleIndex_Init(&o->mindex)) {
  140. BLog(BLOG_ERROR, "NCDModuleIndex_Init failed");
  141. goto fail2;
  142. }
  143. // add module groups to index and allocate string id's for base_type's
  144. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  145. if (!NCDModuleIndex_AddGroup(&o->mindex, *g, &o->method_index)) {
  146. BLog(BLOG_ERROR, "NCDModuleIndex_AddGroup failed");
  147. goto fail3;
  148. }
  149. if (!alloc_base_type_strings(o, *g)) {
  150. goto fail3;
  151. }
  152. }
  153. // parse config file
  154. if (!NCDConfigParser_Parse((char *)program, program_len, &o->program)) {
  155. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  156. goto fail3;
  157. }
  158. // desugar
  159. if (!NCDSugar_Desugar(&o->program)) {
  160. BLog(BLOG_ERROR, "NCDSugar_Desugar failed");
  161. goto fail4;
  162. }
  163. // init placeholder database
  164. if (!NCDPlaceholderDb_Init(&o->placeholder_db, &o->string_index)) {
  165. BLog(BLOG_ERROR, "NCDPlaceholderDb_Init failed");
  166. goto fail4;
  167. }
  168. // init interp program
  169. if (!NCDInterpProg_Init(&o->iprogram, &o->program, &o->string_index, &o->placeholder_db, &o->mindex, &o->method_index)) {
  170. BLog(BLOG_ERROR, "NCDInterpProg_Init failed");
  171. goto fail5;
  172. }
  173. // init pointers to global resources in out struct NCDModuleInst_iparams.
  174. // Don't initialize any callback at this point as these must not be called
  175. // from globalinit functions of modules.
  176. o->module_iparams.reactor = params.reactor;
  177. #ifndef BADVPN_NO_PROCESS
  178. o->module_iparams.manager = params.manager;
  179. #endif
  180. #ifndef BADVPN_NO_UDEV
  181. o->module_iparams.umanager = params.umanager;
  182. #endif
  183. #ifndef BADVPN_NO_RANDOM
  184. o->module_iparams.random2 = params.random2;
  185. #endif
  186. o->module_iparams.string_index = &o->string_index;
  187. // init modules
  188. o->num_inited_modules = 0;
  189. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  190. // map strings
  191. if ((*g)->strings && !NCDStringIndex_GetRequests(&o->string_index, (*g)->strings)) {
  192. BLog(BLOG_ERROR, "NCDStringIndex_GetRequests failed for some module");
  193. goto fail6;
  194. }
  195. // call func_globalinit
  196. if ((*g)->func_globalinit && !(*g)->func_globalinit(&o->module_iparams)) {
  197. BLog(BLOG_ERROR, "globalinit failed for some module");
  198. goto fail6;
  199. }
  200. o->num_inited_modules++;
  201. }
  202. // init the rest of the module parameters structures
  203. o->module_params.func_event = statement_instance_func_event;
  204. o->module_params.func_getobj = statement_instance_func_getobj;
  205. o->module_params.logfunc = (BLog_logfunc)statement_instance_logfunc;
  206. o->module_params.iparams = &o->module_iparams;
  207. o->module_iparams.user = o;
  208. o->module_iparams.func_initprocess = statement_instance_func_initprocess;
  209. o->module_iparams.func_interp_exit = statement_instance_func_interp_exit;
  210. o->module_iparams.func_interp_getargs = statement_instance_func_interp_getargs;
  211. o->module_iparams.func_interp_getretrytime = statement_instance_func_interp_getretrytime;
  212. // init processes list
  213. LinkedList1_Init(&o->processes);
  214. // init processes
  215. for (NCDProcess *p = NCDProgram_FirstProcess(&o->program); p; p = NCDProgram_NextProcess(&o->program, p)) {
  216. if (NCDProcess_IsTemplate(p)) {
  217. continue;
  218. }
  219. // get string id for process name
  220. NCD_string_id_t name_id = NCDStringIndex_Lookup(&o->string_index, NCDProcess_Name(p));
  221. ASSERT(name_id >= 0)
  222. // find iprocess
  223. NCDInterpProcess *iprocess = NCDInterpProg_FindProcess(&o->iprogram, name_id);
  224. ASSERT(iprocess)
  225. if (!process_new(o, iprocess, NULL)) {
  226. BLog(BLOG_ERROR, "failed to initialize process, exiting");
  227. goto fail7;
  228. }
  229. }
  230. DebugObject_Init(&o->d_obj);
  231. return 1;
  232. fail7:;
  233. LinkedList1Node *ln;
  234. while (ln = LinkedList1_GetFirst(&o->processes)) {
  235. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  236. NCDModuleProcess *mp;
  237. process_free(p, &mp);
  238. ASSERT(!mp)
  239. }
  240. fail6:
  241. // free modules
  242. while (o->num_inited_modules-- > 0) {
  243. const struct NCDModuleGroup **g = &ncd_modules[o->num_inited_modules];
  244. if ((*g)->func_globalfree) {
  245. (*g)->func_globalfree();
  246. }
  247. }
  248. // free interp program
  249. NCDInterpProg_Free(&o->iprogram);
  250. fail5:
  251. // free placeholder database
  252. NCDPlaceholderDb_Free(&o->placeholder_db);
  253. fail4:
  254. // free program AST
  255. NCDProgram_Free(&o->program);
  256. fail3:
  257. // free module index
  258. NCDModuleIndex_Free(&o->mindex);
  259. fail2:
  260. // free method index
  261. NCDMethodIndex_Free(&o->method_index);
  262. fail1:
  263. // free string index
  264. NCDStringIndex_Free(&o->string_index);
  265. fail0:
  266. return 0;
  267. }
  268. void NCDInterpreter_Free (NCDInterpreter *o)
  269. {
  270. DebugObject_Free(&o->d_obj);
  271. // any process that exists must be completely uninitialized
  272. // free processes
  273. LinkedList1Node *ln;
  274. while (ln = LinkedList1_GetFirst(&o->processes)) {
  275. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  276. NCDModuleProcess *mp;
  277. process_free(p, &mp);
  278. ASSERT(!mp)
  279. }
  280. // free modules
  281. while (o->num_inited_modules-- > 0) {
  282. const struct NCDModuleGroup **g = &ncd_modules[o->num_inited_modules];
  283. if ((*g)->func_globalfree) {
  284. (*g)->func_globalfree();
  285. }
  286. }
  287. // free interp program
  288. NCDInterpProg_Free(&o->iprogram);
  289. // free placeholder database
  290. NCDPlaceholderDb_Free(&o->placeholder_db);
  291. // free program AST
  292. NCDProgram_Free(&o->program);
  293. // free module index
  294. NCDModuleIndex_Free(&o->mindex);
  295. // free method index
  296. NCDMethodIndex_Free(&o->method_index);
  297. // free string index
  298. NCDStringIndex_Free(&o->string_index);
  299. }
  300. void NCDInterpreter_RequestShutdown (NCDInterpreter *o, int exit_code)
  301. {
  302. DebugObject_Access(&o->d_obj);
  303. start_terminate(o, exit_code);
  304. }
  305. void start_terminate (NCDInterpreter *interp, int exit_code)
  306. {
  307. // remember exit code
  308. interp->main_exit_code = exit_code;
  309. // if we're already terminating, there's nothing to do
  310. if (interp->terminating) {
  311. return;
  312. }
  313. // set the terminating flag
  314. interp->terminating = 1;
  315. // if there are no processes, we're done
  316. if (LinkedList1_IsEmpty(&interp->processes)) {
  317. interp->params.handler_finished(interp->params.user, interp->main_exit_code);
  318. return;
  319. }
  320. // start terminating non-template processes
  321. for (LinkedList1Node *ln = LinkedList1_GetFirst(&interp->processes); ln; ln = LinkedList1Node_Next(ln)) {
  322. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  323. if (p->module_process) {
  324. continue;
  325. }
  326. process_start_terminating(p);
  327. }
  328. }
  329. char * implode_id_strings (NCDInterpreter *interp, const NCD_string_id_t *names, size_t num_names, char del)
  330. {
  331. ExpString str;
  332. if (!ExpString_Init(&str)) {
  333. goto fail0;
  334. }
  335. int is_first = 1;
  336. while (num_names > 0) {
  337. if (!is_first && !ExpString_AppendChar(&str, del)) {
  338. goto fail1;
  339. }
  340. const char *name_str = NCDStringIndex_Value(&interp->string_index, *names);
  341. if (!ExpString_Append(&str, name_str)) {
  342. goto fail1;
  343. }
  344. names++;
  345. num_names--;
  346. is_first = 0;
  347. }
  348. return ExpString_Get(&str);
  349. fail1:
  350. ExpString_Free(&str);
  351. fail0:
  352. return NULL;
  353. }
  354. int alloc_base_type_strings (NCDInterpreter *interp, const struct NCDModuleGroup *g)
  355. {
  356. for (struct NCDModule *m = g->modules; m->type; m++) {
  357. const char *type = (m->base_type ? m->base_type : m->type);
  358. ASSERT(type)
  359. m->base_type_id = NCDStringIndex_Get(&interp->string_index, type);
  360. if (m->base_type_id < 0) {
  361. BLog(BLOG_ERROR, "NCDStringIndex_Get failed");
  362. return 0;
  363. }
  364. }
  365. return 1;
  366. }
  367. int process_new (NCDInterpreter *interp, NCDInterpProcess *iprocess, NCDModuleProcess *module_process)
  368. {
  369. ASSERT(iprocess)
  370. // get number of statements
  371. int num_statements = NCDInterpProcess_NumStatements(iprocess);
  372. // get size of preallocated memory
  373. int mem_size = NCDInterpProcess_PreallocSize(iprocess);
  374. if (mem_size < 0) {
  375. goto fail0;
  376. }
  377. // start with size of process structure
  378. size_t alloc_size = sizeof(struct process);
  379. // add size of statements array
  380. if (num_statements > SIZE_MAX / sizeof(struct statement)) {
  381. goto fail0;
  382. }
  383. if (!BSizeAdd(&alloc_size, num_statements * sizeof(struct statement))) {
  384. goto fail0;
  385. }
  386. // align for preallocated memory
  387. if (!BSizeAlign(&alloc_size, BMAX_ALIGN)) {
  388. goto fail0;
  389. }
  390. size_t mem_off = alloc_size;
  391. // add size of preallocated memory
  392. if (mem_size > SIZE_MAX || !BSizeAdd(&alloc_size, mem_size)) {
  393. goto fail0;
  394. }
  395. // allocate memory
  396. struct process *p = BAlloc(alloc_size);
  397. if (!p) {
  398. goto fail0;
  399. }
  400. // set variables
  401. p->interp = interp;
  402. p->iprocess = iprocess;
  403. p->module_process = module_process;
  404. p->ap = 0;
  405. p->fp = 0;
  406. p->num_statements = num_statements;
  407. p->error = 0;
  408. // set module process handlers
  409. if (p->module_process) {
  410. NCDModuleProcess_Interp_SetHandlers(p->module_process, p,
  411. (NCDModuleProcess_interp_func_event)process_moduleprocess_func_event,
  412. (NCDModuleProcess_interp_func_getobj)process_moduleprocess_func_getobj);
  413. }
  414. // init statements
  415. char *mem = (char *)p + mem_off;
  416. for (int i = 0; i < num_statements; i++) {
  417. struct statement *ps = &p->statements[i];
  418. ps->i = i;
  419. ps->inst.istate = SSTATE_FORGOTTEN;
  420. ps->mem_size = NCDInterpProcess_StatementPreallocSize(iprocess, i);
  421. ps->inst.mem = mem + NCDInterpProcess_StatementPreallocOffset(iprocess, i);
  422. }
  423. // init timer
  424. BSmallTimer_Init(&p->wait_timer, process_wait_timer_handler);
  425. // set state, init work job
  426. process_set_state(p, PSTATE_WORKING);
  427. BSmallPending_Init(&p->work_job, BReactor_PendingGroup(interp->params.reactor), (BSmallPending_handler)process_work_job_handler_working, p);
  428. // insert to processes list
  429. LinkedList1_Append(&interp->processes, &p->list_node);
  430. // schedule work
  431. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(interp->params.reactor));
  432. return 1;
  433. fail0:
  434. BLog(BLOG_ERROR, "failed to allocate memory for process %s", NCDInterpProcess_Name(iprocess));
  435. return 0;
  436. }
  437. void process_set_state (struct process *p, int state)
  438. {
  439. #ifndef NDEBUG
  440. p->state = state;
  441. #endif
  442. }
  443. void process_free (struct process *p, NCDModuleProcess **out_mp)
  444. {
  445. ASSERT(p->ap == 0)
  446. ASSERT(p->fp == 0)
  447. ASSERT(out_mp)
  448. // give module process to caller so it can inform the process creator that the process has terminated
  449. *out_mp = p->module_process;
  450. // free statement memory
  451. for (int i = 0; i < p->num_statements; i++) {
  452. struct statement *ps = &p->statements[i];
  453. if (statement_mem_is_allocated(ps)) {
  454. free(ps->inst.mem);
  455. }
  456. }
  457. // remove from processes list
  458. LinkedList1_Remove(&p->interp->processes, &p->list_node);
  459. // free work job
  460. BSmallPending_Free(&p->work_job, BReactor_PendingGroup(p->interp->params.reactor));
  461. // free timer
  462. BReactor_RemoveSmallTimer(p->interp->params.reactor, &p->wait_timer);
  463. // free strucure
  464. BFree(p);
  465. }
  466. void process_start_terminating (struct process *p)
  467. {
  468. // set state terminating
  469. process_set_state(p, PSTATE_TERMINATING);
  470. BSmallPending_SetHandler(&p->work_job, (BSmallPending_handler)process_work_job_handler_terminating, p);
  471. // schedule work
  472. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(p->interp->params.reactor));
  473. }
  474. int process_have_child (struct process *p)
  475. {
  476. return (p->ap > 0 && p->statements[p->ap - 1].inst.istate == SSTATE_CHILD);
  477. }
  478. void process_assert_pointers (struct process *p)
  479. {
  480. ASSERT(p->ap <= p->num_statements)
  481. ASSERT(p->fp >= p->ap)
  482. ASSERT(p->fp <= p->num_statements)
  483. #ifndef NDEBUG
  484. // check AP
  485. for (int i = 0; i < p->ap; i++) {
  486. if (i == p->ap - 1) {
  487. ASSERT(p->statements[i].inst.istate == SSTATE_ADULT || p->statements[i].inst.istate == SSTATE_CHILD)
  488. } else {
  489. ASSERT(p->statements[i].inst.istate == SSTATE_ADULT)
  490. }
  491. }
  492. // check FP
  493. int fp = p->num_statements;
  494. while (fp > 0 && p->statements[fp - 1].inst.istate == SSTATE_FORGOTTEN) {
  495. fp--;
  496. }
  497. ASSERT(p->fp == fp)
  498. #endif
  499. }
  500. void process_logfunc (struct process *p)
  501. {
  502. BLog_Append("process %s: ", NCDInterpProcess_Name(p->iprocess));
  503. }
  504. void process_log (struct process *p, int level, const char *fmt, ...)
  505. {
  506. va_list vl;
  507. va_start(vl, fmt);
  508. BLog_LogViaFuncVarArg((BLog_logfunc)process_logfunc, p, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  509. va_end(vl);
  510. }
  511. void process_work_job_handler_working (struct process *p)
  512. {
  513. process_assert_pointers(p);
  514. ASSERT(p->state == PSTATE_WORKING)
  515. // cleaning up?
  516. if (p->ap < p->fp) {
  517. // order the last living statement to die, if needed
  518. struct statement *ps = &p->statements[p->fp - 1];
  519. if (ps->inst.istate != SSTATE_DYING) {
  520. statement_log(ps, BLOG_INFO, "killing");
  521. // set statement state DYING
  522. ps->inst.istate = SSTATE_DYING;
  523. // order it to die
  524. NCDModuleInst_Die(&ps->inst);
  525. return;
  526. }
  527. return;
  528. }
  529. // clean?
  530. if (process_have_child(p)) {
  531. ASSERT(p->ap > 0)
  532. ASSERT(p->ap <= p->num_statements)
  533. struct statement *ps = &p->statements[p->ap - 1];
  534. ASSERT(ps->inst.istate == SSTATE_CHILD)
  535. statement_log(ps, BLOG_INFO, "clean");
  536. // report clean
  537. NCDModuleInst_Clean(&ps->inst);
  538. return;
  539. }
  540. // advancing?
  541. if (p->ap < p->num_statements) {
  542. struct statement *ps = &p->statements[p->ap];
  543. ASSERT(ps->inst.istate == SSTATE_FORGOTTEN)
  544. if (p->error) {
  545. statement_log(ps, BLOG_INFO, "waiting after error");
  546. // clear error
  547. p->error = 0;
  548. // set wait timer
  549. BReactor_SetSmallTimer(p->interp->params.reactor, &p->wait_timer, BTIMER_SET_RELATIVE, p->interp->params.retry_time);
  550. } else {
  551. // advance
  552. process_advance(p);
  553. }
  554. return;
  555. }
  556. // we've finished
  557. process_log(p, BLOG_INFO, "victory");
  558. // set state up
  559. process_set_state(p, PSTATE_UP);
  560. BSmallPending_SetHandler(&p->work_job, (BSmallPending_handler)process_work_job_handler_up, p);
  561. // set module process up
  562. if (p->module_process) {
  563. NCDModuleProcess_Interp_Up(p->module_process);
  564. return;
  565. }
  566. }
  567. void process_work_job_handler_up (struct process *p)
  568. {
  569. process_assert_pointers(p);
  570. ASSERT(p->state == PSTATE_UP)
  571. ASSERT(p->ap < p->num_statements || process_have_child(p))
  572. // if we have module process, wait for its permission to continue
  573. if (p->module_process) {
  574. // set state waiting
  575. process_set_state(p, PSTATE_WAITING);
  576. BSmallPending_SetHandler(&p->work_job, (BSmallPending_handler)process_work_job_handler_waiting, p);
  577. // set module process down
  578. NCDModuleProcess_Interp_Down(p->module_process);
  579. return;
  580. }
  581. // set state working
  582. process_set_state(p, PSTATE_WORKING);
  583. BSmallPending_SetHandler(&p->work_job, (BSmallPending_handler)process_work_job_handler_working, p);
  584. // delegate the rest to the working handler
  585. process_work_job_handler_working(p);
  586. }
  587. void process_work_job_handler_waiting (struct process *p)
  588. {
  589. process_assert_pointers(p);
  590. ASSERT(p->state == PSTATE_WAITING)
  591. // do absolutely nothing. Having this no-op handler avoids a branch
  592. // in statement_instance_func_event().
  593. }
  594. void process_work_job_handler_terminating (struct process *p)
  595. {
  596. process_assert_pointers(p);
  597. ASSERT(p->state == PSTATE_TERMINATING)
  598. if (p->fp == 0) {
  599. NCDInterpreter *interp = p->interp;
  600. // free process
  601. NCDModuleProcess *mp;
  602. process_free(p, &mp);
  603. // if program is terminating amd there are no more processes, exit program
  604. if (interp->terminating && LinkedList1_IsEmpty(&interp->processes)) {
  605. ASSERT(!mp)
  606. interp->params.handler_finished(interp->params.user, interp->main_exit_code);
  607. return;
  608. }
  609. // inform the process creator that the process has terminated
  610. if (mp) {
  611. NCDModuleProcess_Interp_Terminated(mp);
  612. return;
  613. }
  614. return;
  615. }
  616. // order the last living statement to die, if needed
  617. struct statement *ps = &p->statements[p->fp - 1];
  618. ASSERT(ps->inst.istate != SSTATE_FORGOTTEN)
  619. if (ps->inst.istate != SSTATE_DYING) {
  620. statement_log(ps, BLOG_INFO, "killing");
  621. // set statement state DYING
  622. ps->inst.istate = SSTATE_DYING;
  623. // update AP
  624. if (p->ap > ps->i) {
  625. p->ap = ps->i;
  626. }
  627. // order it to die
  628. NCDModuleInst_Die(&ps->inst);
  629. return;
  630. }
  631. }
  632. int replace_placeholders_callback (void *arg, int plid, NCDValMem *mem, NCDValRef *out)
  633. {
  634. struct statement *ps = arg;
  635. ASSERT(plid >= 0)
  636. ASSERT(mem)
  637. ASSERT(out)
  638. struct process *p = statement_process(ps);
  639. const NCD_string_id_t *varnames;
  640. size_t num_names;
  641. NCDPlaceholderDb_GetVariable(&p->interp->placeholder_db, plid, &varnames, &num_names);
  642. return process_resolve_variable_expr(statement_process(ps), ps->i, varnames, num_names, mem, out);
  643. }
  644. void process_advance (struct process *p)
  645. {
  646. process_assert_pointers(p);
  647. ASSERT(p->ap == p->fp)
  648. ASSERT(!process_have_child(p))
  649. ASSERT(p->ap < p->num_statements)
  650. ASSERT(!p->error)
  651. ASSERT(!BSmallPending_IsSet(&p->work_job))
  652. ASSERT(p->state == PSTATE_WORKING)
  653. struct statement *ps = &p->statements[p->ap];
  654. ASSERT(ps->inst.istate == SSTATE_FORGOTTEN)
  655. statement_log(ps, BLOG_INFO, "initializing");
  656. // need to determine the module and object to use it on (if it's a method)
  657. const struct NCDModule *module;
  658. NCDObject object;
  659. NCDObject *object_ptr = NULL;
  660. // get object names, e.g. "my.cat" in "my.cat->meow();"
  661. // (or NULL if this is not a method statement)
  662. const NCD_string_id_t *objnames;
  663. size_t num_objnames;
  664. NCDInterpProcess_StatementObjNames(p->iprocess, p->ap, &objnames, &num_objnames);
  665. if (!objnames) {
  666. // not a method; module is already known by NCDInterpProcess
  667. module = NCDInterpProcess_StatementGetSimpleModule(p->iprocess, p->ap);
  668. if (!module) {
  669. statement_log(ps, BLOG_ERROR, "unknown simple statement: %s", NCDInterpProcess_StatementCmdName(p->iprocess, p->ap));
  670. goto fail0;
  671. }
  672. } else {
  673. // get object
  674. if (!process_resolve_object_expr(p, p->ap, objnames, num_objnames, &object)) {
  675. goto fail0;
  676. }
  677. object_ptr = &object;
  678. // get object type
  679. NCD_string_id_t object_type = NCDObject_Type(&object);
  680. if (object_type < 0) {
  681. statement_log(ps, BLOG_ERROR, "cannot call method on object with no type");
  682. goto fail0;
  683. }
  684. // find module based on type of object
  685. module = NCDInterpProcess_StatementGetMethodModule(p->iprocess, p->ap, object_type, &p->interp->method_index);
  686. if (!module) {
  687. const char *type_str = NCDStringIndex_Value(&p->interp->string_index, object_type);
  688. statement_log(ps, BLOG_ERROR, "unknown method statement: %s::%s", type_str, NCDInterpProcess_StatementCmdName(p->iprocess, p->ap));
  689. goto fail0;
  690. }
  691. }
  692. // register alloc size for future preallocations
  693. NCDInterpProcess_StatementBumpAllocSize(p->iprocess, p->ap, module->alloc_size);
  694. // copy arguments
  695. NCDValRef args;
  696. NCDValReplaceProg prog;
  697. if (!NCDInterpProcess_CopyStatementArgs(p->iprocess, ps->i, &ps->args_mem, &args, &prog)) {
  698. statement_log(ps, BLOG_ERROR, "NCDInterpProcess_CopyStatementArgs failed");
  699. goto fail0;
  700. }
  701. // replace placeholders with values of variables
  702. if (!NCDValReplaceProg_Execute(prog, &ps->args_mem, replace_placeholders_callback, ps)) {
  703. statement_log(ps, BLOG_ERROR, "failed to replace variables in arguments with values");
  704. goto fail1;
  705. }
  706. // allocate memory
  707. if (!statement_allocate_memory(ps, module->alloc_size)) {
  708. statement_log(ps, BLOG_ERROR, "failed to allocate memory");
  709. goto fail1;
  710. }
  711. // set statement state CHILD
  712. ps->inst.istate = SSTATE_CHILD;
  713. // increment AP
  714. p->ap++;
  715. // increment FP
  716. p->fp++;
  717. process_assert_pointers(p);
  718. // initialize module instance
  719. NCDModuleInst_Init(&ps->inst, module, object_ptr, args, &p->interp->module_params);
  720. return;
  721. fail1:
  722. NCDValMem_Free(&ps->args_mem);
  723. fail0:
  724. // set error
  725. p->error = 1;
  726. // schedule work to start the timer
  727. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(p->interp->params.reactor));
  728. }
  729. void process_wait_timer_handler (BSmallTimer *timer)
  730. {
  731. struct process *p = UPPER_OBJECT(timer, struct process, wait_timer);
  732. process_assert_pointers(p);
  733. ASSERT(!BSmallPending_IsSet(&p->work_job))
  734. // check if something happened that means we no longer need to retry
  735. if (p->ap != p->fp || process_have_child(p) || p->ap == p->num_statements) {
  736. return;
  737. }
  738. process_log(p, BLOG_INFO, "retrying");
  739. // advance. Note: the asserts for this are indeed satisfied, though this
  740. // it not trivial to prove.
  741. process_advance(p);
  742. }
  743. int process_find_object (struct process *p, int pos, NCD_string_id_t name, NCDObject *out_object)
  744. {
  745. ASSERT(pos >= 0)
  746. ASSERT(pos <= p->num_statements)
  747. ASSERT(out_object)
  748. int i = NCDInterpProcess_FindStatement(p->iprocess, pos, name);
  749. if (i >= 0) {
  750. struct statement *ps = &p->statements[i];
  751. ASSERT(i < p->num_statements)
  752. if (ps->inst.istate == SSTATE_FORGOTTEN) {
  753. process_log(p, BLOG_ERROR, "statement (%d) is uninitialized", i);
  754. return 0;
  755. }
  756. *out_object = NCDModuleInst_Object(&ps->inst);
  757. return 1;
  758. }
  759. if (p->module_process && NCDModuleProcess_Interp_GetSpecialObj(p->module_process, name, out_object)) {
  760. return 1;
  761. }
  762. return 0;
  763. }
  764. int process_resolve_object_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDObject *out_object)
  765. {
  766. ASSERT(pos >= 0)
  767. ASSERT(pos <= p->num_statements)
  768. ASSERT(names)
  769. ASSERT(num_names > 0)
  770. ASSERT(out_object)
  771. NCDObject object;
  772. if (!process_find_object(p, pos, names[0], &object)) {
  773. goto fail;
  774. }
  775. if (!NCDObject_ResolveObjExprCompact(&object, names + 1, num_names - 1, out_object)) {
  776. goto fail;
  777. }
  778. return 1;
  779. fail:;
  780. char *name = implode_id_strings(p->interp, names, num_names, '.');
  781. process_log(p, BLOG_ERROR, "failed to resolve object (%s) from position %zu", (name ? name : ""), pos);
  782. free(name);
  783. return 0;
  784. }
  785. int process_resolve_variable_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDValMem *mem, NCDValRef *out_value)
  786. {
  787. ASSERT(pos >= 0)
  788. ASSERT(pos <= p->num_statements)
  789. ASSERT(names)
  790. ASSERT(num_names > 0)
  791. ASSERT(mem)
  792. ASSERT(out_value)
  793. NCDObject object;
  794. if (!process_find_object(p, pos, names[0], &object)) {
  795. goto fail;
  796. }
  797. if (!NCDObject_ResolveVarExprCompact(&object, names + 1, num_names - 1, mem, out_value)) {
  798. goto fail;
  799. }
  800. return 1;
  801. fail:;
  802. char *name = implode_id_strings(p->interp, names, num_names, '.');
  803. process_log(p, BLOG_ERROR, "failed to resolve variable (%s) from position %zu", (name ? name : ""), pos);
  804. free(name);
  805. return 0;
  806. }
  807. void statement_logfunc (struct statement *ps)
  808. {
  809. process_logfunc(statement_process(ps));
  810. BLog_Append("statement %zu: ", ps->i);
  811. }
  812. void statement_log (struct statement *ps, int level, const char *fmt, ...)
  813. {
  814. if (!BLog_WouldLog(BLOG_CURRENT_CHANNEL, level)) {
  815. return;
  816. }
  817. va_list vl;
  818. va_start(vl, fmt);
  819. BLog_LogViaFuncVarArg((BLog_logfunc)statement_logfunc, ps, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  820. va_end(vl);
  821. }
  822. struct process * statement_process (struct statement *ps)
  823. {
  824. return UPPER_OBJECT(ps - ps->i, struct process, statements);
  825. }
  826. int statement_mem_is_allocated (struct statement *ps)
  827. {
  828. return (ps->mem_size < 0);
  829. }
  830. int statement_mem_size (struct statement *ps)
  831. {
  832. return (ps->mem_size >= 0 ? ps->mem_size : -ps->mem_size);
  833. }
  834. int statement_allocate_memory (struct statement *ps, int alloc_size)
  835. {
  836. ASSERT(alloc_size >= 0)
  837. if (alloc_size > statement_mem_size(ps)) {
  838. char *new_mem = malloc(alloc_size);
  839. if (!new_mem) {
  840. statement_log(ps, BLOG_ERROR, "malloc failed");
  841. return 0;
  842. }
  843. if (statement_mem_is_allocated(ps)) {
  844. free(ps->inst.mem);
  845. }
  846. ps->inst.mem = new_mem;
  847. ps->mem_size = -alloc_size;
  848. }
  849. return 1;
  850. }
  851. void statement_instance_func_event (NCDModuleInst *inst, int event)
  852. {
  853. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  854. ASSERT(ps->inst.istate == SSTATE_CHILD || ps->inst.istate == SSTATE_ADULT || ps->inst.istate == SSTATE_DYING)
  855. struct process *p = statement_process(ps);
  856. process_assert_pointers(p);
  857. // schedule work
  858. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(p->interp->params.reactor));
  859. switch (event) {
  860. case NCDMODULE_EVENT_UP: {
  861. ASSERT(ps->inst.istate == SSTATE_CHILD)
  862. statement_log(ps, BLOG_INFO, "up");
  863. // set state ADULT
  864. ps->inst.istate = SSTATE_ADULT;
  865. } break;
  866. case NCDMODULE_EVENT_DOWN: {
  867. ASSERT(ps->inst.istate == SSTATE_ADULT)
  868. statement_log(ps, BLOG_INFO, "down");
  869. // set state CHILD
  870. ps->inst.istate = SSTATE_CHILD;
  871. // clear error
  872. if (ps->i < p->ap) {
  873. p->error = 0;
  874. }
  875. // update AP
  876. if (p->ap > ps->i + 1) {
  877. p->ap = ps->i + 1;
  878. }
  879. } break;
  880. case NCDMODULE_EVENT_DEAD: {
  881. int is_error = NCDModuleInst_HaveError(&ps->inst);
  882. if (is_error) {
  883. statement_log(ps, BLOG_ERROR, "died with error");
  884. } else {
  885. statement_log(ps, BLOG_INFO, "died");
  886. }
  887. // free instance
  888. NCDModuleInst_Free(&ps->inst);
  889. // free arguments memory
  890. NCDValMem_Free(&ps->args_mem);
  891. // set state FORGOTTEN
  892. ps->inst.istate = SSTATE_FORGOTTEN;
  893. // set error
  894. if (is_error && ps->i < p->ap) {
  895. p->error = 1;
  896. }
  897. // update AP
  898. if (p->ap > ps->i) {
  899. p->ap = ps->i;
  900. }
  901. // update FP
  902. while (p->fp > 0 && p->statements[p->fp - 1].inst.istate == SSTATE_FORGOTTEN) {
  903. p->fp--;
  904. }
  905. } break;
  906. }
  907. }
  908. int statement_instance_func_getobj (NCDModuleInst *inst, NCD_string_id_t objname, NCDObject *out_object)
  909. {
  910. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  911. ASSERT(ps->inst.istate != SSTATE_FORGOTTEN)
  912. return process_find_object(statement_process(ps), ps->i, objname, out_object);
  913. }
  914. int statement_instance_func_initprocess (void *vinterp, NCDModuleProcess* mp, NCD_string_id_t template_name)
  915. {
  916. NCDInterpreter *interp = vinterp;
  917. // find process
  918. NCDInterpProcess *iprocess = NCDInterpProg_FindProcess(&interp->iprogram, template_name);
  919. if (!iprocess) {
  920. const char *str = NCDStringIndex_Value(&interp->string_index, template_name);
  921. BLog(BLOG_ERROR, "no template named %s", str);
  922. return 0;
  923. }
  924. // make sure it's a template
  925. if (!NCDInterpProcess_IsTemplate(iprocess)) {
  926. const char *str = NCDStringIndex_Value(&interp->string_index, template_name);
  927. BLog(BLOG_ERROR, "need template to create a process, but %s is a process", str);
  928. return 0;
  929. }
  930. // create process
  931. if (!process_new(interp, iprocess, mp)) {
  932. const char *str = NCDStringIndex_Value(&interp->string_index, template_name);
  933. BLog(BLOG_ERROR, "failed to create process from template %s", str);
  934. return 0;
  935. }
  936. if (BLog_WouldLog(BLOG_INFO, BLOG_CURRENT_CHANNEL)) {
  937. const char *str = NCDStringIndex_Value(&interp->string_index, template_name);
  938. BLog(BLOG_INFO, "created process from template %s", str);
  939. }
  940. return 1;
  941. }
  942. void statement_instance_logfunc (NCDModuleInst *inst)
  943. {
  944. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  945. ASSERT(ps->inst.istate != SSTATE_FORGOTTEN)
  946. statement_logfunc(ps);
  947. BLog_Append("module: ");
  948. }
  949. void statement_instance_func_interp_exit (void *vinterp, int exit_code)
  950. {
  951. NCDInterpreter *interp = vinterp;
  952. start_terminate(interp, exit_code);
  953. }
  954. int statement_instance_func_interp_getargs (void *vinterp, NCDValMem *mem, NCDValRef *out_value)
  955. {
  956. NCDInterpreter *interp = vinterp;
  957. *out_value = NCDVal_NewList(mem, interp->params.num_extra_args);
  958. if (NCDVal_IsInvalid(*out_value)) {
  959. BLog(BLOG_ERROR, "NCDVal_NewList failed");
  960. goto fail;
  961. }
  962. for (int i = 0; i < interp->params.num_extra_args; i++) {
  963. NCDValRef arg = NCDVal_NewString(mem, interp->params.extra_args[i]);
  964. if (NCDVal_IsInvalid(arg)) {
  965. BLog(BLOG_ERROR, "NCDVal_NewString failed");
  966. goto fail;
  967. }
  968. NCDVal_ListAppend(*out_value, arg);
  969. }
  970. return 1;
  971. fail:
  972. *out_value = NCDVal_NewInvalid();
  973. return 1;
  974. }
  975. btime_t statement_instance_func_interp_getretrytime (void *vinterp)
  976. {
  977. NCDInterpreter *interp = vinterp;
  978. return interp->params.retry_time;
  979. }
  980. void process_moduleprocess_func_event (struct process *p, int event)
  981. {
  982. ASSERT(p->module_process)
  983. switch (event) {
  984. case NCDMODULEPROCESS_INTERP_EVENT_CONTINUE: {
  985. ASSERT(p->state == PSTATE_WAITING)
  986. // set state working
  987. process_set_state(p, PSTATE_WORKING);
  988. BSmallPending_SetHandler(&p->work_job, (BSmallPending_handler)process_work_job_handler_working, p);
  989. // schedule work
  990. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(p->interp->params.reactor));
  991. } break;
  992. case NCDMODULEPROCESS_INTERP_EVENT_TERMINATE: {
  993. ASSERT(p->state != PSTATE_TERMINATING)
  994. process_log(p, BLOG_INFO, "process termination requested");
  995. // start terminating
  996. process_start_terminating(p);
  997. } break;
  998. default: ASSERT(0);
  999. }
  1000. }
  1001. int process_moduleprocess_func_getobj (struct process *p, NCD_string_id_t name, NCDObject *out_object)
  1002. {
  1003. ASSERT(p->module_process)
  1004. return process_find_object(p, p->num_statements, name, out_object);
  1005. }