NCDInterpreter.c 38 KB

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