NCDInterpreter.c 37 KB

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