NCDInterpreter.c 37 KB

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