sys_start_process.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. /**
  2. * @file sys_start_process.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. * @section DESCRIPTION
  30. *
  31. * Synopsis:
  32. * sys.start_process(list command, string mode)
  33. *
  34. * Variables:
  35. * is_error - "true" if there was an error starting the process, "false" if the process
  36. * has been started successfully
  37. *
  38. * Synopsis:
  39. * sys.start_process::wait()
  40. *
  41. * Variables:
  42. * exit_status - the exit code if the process terminated normally, -1 if it terminated
  43. * with a signal
  44. *
  45. * Synopsis:
  46. * sys.start_process::terminate()
  47. * sys.start_process::kill()
  48. *
  49. * Synopsis:
  50. * sys.start_process::read_pipe()
  51. *
  52. * Description:
  53. * Creates a read interface to the process's standard output. Data is read using the
  54. * read() method on this object. Read errors are reported implicitly by this statement
  55. * going down and the 'is_error' variable changing to "true".
  56. * When read_pipe() is initialized for a process, it takes ownership of the read pipe
  57. * to the process. When read_pipe() is requested to terminate, it will close the pipe.
  58. * Attempting to initialize read_pipe() on a process which was not started with 'r'
  59. * in the mode argument, or where another read_pipe() object has already taken ownership
  60. * of the read pipe, will result in throwing an error to the interpreter.
  61. *
  62. * Variables:
  63. * string is_error - "true" if there was a read error, "false" if not
  64. *
  65. * Synopsis:
  66. * sys.start_process::read_pipe::read()
  67. *
  68. * Description:
  69. * Reads some data. If a read error occurs, it is reported implicitly via the
  70. * read_pipe() object going down. If end of file is reached, this and any future read()
  71. * operations will indicate that via the 'not_eof' variable. It is guaranteed that after
  72. * EOF is reached, the read_pipe() object will not go down to report any errors.
  73. * WARNING: if a read() is requested to terminate before it has completed, the
  74. * read_pipe() will become unusable and any read() invocation after that will
  75. * throw an error to the interpreter.
  76. *
  77. * Variables:
  78. * string (empty) - data that was read, or an empty string on EOF
  79. * string not_eof - "true" is EOF was not reached, "false" if it was
  80. *
  81. * Synopsis:
  82. * sys.start_process::write_pipe()
  83. *
  84. * Description:
  85. * Creates a write interface to the process's standard input. Data is written using the
  86. * write() method on this object. Write errors are reported implicitly by this statement
  87. * going down and the ''is_error variable changing to "true".
  88. * When write_pipe() is initialized for a process, it takes ownership of the write pipe
  89. * to the process. When write_pipe() is requested to terminate, it will close the pipe
  90. * (unless the close() has been used).
  91. * Attempting to initialize write_pipe() on a process which was not started with 'w'
  92. * in the mode argument, or where another write_pipe() object has already taken ownership
  93. * of the write pope, will result in throwing an error to the interpreter.
  94. *
  95. * Variables:
  96. * string is_error - "true" if there was a write error, "false" if not
  97. *
  98. * Synopsis:
  99. * sys.start_process::write_pipe::write(string data)
  100. *
  101. * Description:
  102. * Writes the given data. If a write error occurs, it is reported implicitly via the
  103. * write_pipe() object going down.
  104. * WARNING: if a write() is requested to terminate before it has completed, the
  105. * write_pipe() will become unusable and any write() or close() invocation after
  106. * that will throw an error to the interpreter.
  107. *
  108. * Synopsis:
  109. * sys.start_process::write_pipe::close(string data)
  110. *
  111. * Description:
  112. * Closes the write pipe. This will make whatever is reading the other end of the pipe
  113. * encounter EOF after it has read any pending data. It is guaranteed that after the
  114. * pipe is closed, the write_pipe() object will not go down to report any errors.
  115. * After close() is performed, any further write() or close() calls are disallowed and
  116. * will throw errors to the interpreter.
  117. */
  118. #include <stdlib.h>
  119. #include <string.h>
  120. #include <stdio.h>
  121. #include <inttypes.h>
  122. #include <limits.h>
  123. #include <unistd.h>
  124. #include <misc/offset.h>
  125. #include <structure/LinkedList0.h>
  126. #include <system/BProcess.h>
  127. #include <system/BConnection.h>
  128. #include <ncd/NCDModule.h>
  129. #include <ncd/static_strings.h>
  130. #include <ncd/extra/NCDBuf.h>
  131. #include <ncd/extra/value_utils.h>
  132. #include <ncd/extra/build_cmdline.h>
  133. #include <generated/blog_channel_ncd_sys_start_process.h>
  134. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  135. #define READ_BUF_SIZE 8192
  136. #define PROCESS_STATE_ERROR 1
  137. #define PROCESS_STATE_RUNNING 2
  138. #define PROCESS_STATE_TERMINATED 3
  139. #define PROCESS_STATE_DYING 4
  140. #define READER_STATE_RUNNING 1
  141. #define READER_STATE_EOF 2
  142. #define READER_STATE_ERROR 3
  143. #define READER_STATE_ABORTED 4
  144. #define WRITER_STATE_RUNNING 1
  145. #define WRITER_STATE_CLOSED 2
  146. #define WRITER_STATE_ERROR 3
  147. #define WRITER_STATE_ABORTED 4
  148. struct process_instance {
  149. NCDModuleInst *i;
  150. BProcess process;
  151. LinkedList0 waits_list;
  152. int read_fd;
  153. int write_fd;
  154. int exit_status;
  155. int state;
  156. };
  157. struct wait_instance {
  158. NCDModuleInst *i;
  159. struct process_instance *pinst;
  160. LinkedList0Node waits_list_node;
  161. int exit_status;
  162. };
  163. struct read_pipe_instance {
  164. NCDModuleInst *i;
  165. int state;
  166. int read_fd;
  167. BConnection connection;
  168. NCDBufStore store;
  169. struct read_instance *read_inst;
  170. };
  171. struct read_instance {
  172. NCDModuleInst *i;
  173. struct read_pipe_instance *read_pipe_inst;
  174. NCDBuf *buf;
  175. size_t read_size;
  176. };
  177. struct write_pipe_instance {
  178. NCDModuleInst *i;
  179. int state;
  180. int write_fd;
  181. BConnection connection;
  182. struct write_instance *write_inst;
  183. };
  184. struct write_instance {
  185. NCDModuleInst *i;
  186. struct write_pipe_instance *write_pipe_inst;
  187. b_cstring cstr;
  188. size_t pos;
  189. };
  190. static int parse_mode (NCDModuleInst *i, NCDValRef mode_arg, int *out_read, int *out_write)
  191. {
  192. if (!NCDVal_IsString(mode_arg)) {
  193. ModuleLog(i, BLOG_ERROR, "mode argument must be a string");
  194. return 0;
  195. }
  196. *out_read = 0;
  197. *out_write = 0;
  198. b_cstring cstr = NCDVal_StringCstring(mode_arg);
  199. B_CSTRING_LOOP_CHARS(cstr, char_pos, ch, {
  200. if (ch == 'r') {
  201. *out_read = 1;
  202. }
  203. else if (ch == 'w') {
  204. *out_write = 1;
  205. }
  206. else {
  207. ModuleLog(i, BLOG_ERROR, "invalid character in mode argument");
  208. return 0;
  209. }
  210. })
  211. return 1;
  212. }
  213. static void process_free (struct process_instance *o)
  214. {
  215. // close write fd
  216. if (o->write_fd != -1) {
  217. if (close(o->write_fd) < 0) {
  218. ModuleLog(o->i, BLOG_ERROR, "close failed");
  219. }
  220. }
  221. // close read fd
  222. if (o->read_fd != -1) {
  223. if (close(o->read_fd) < 0) {
  224. ModuleLog(o->i, BLOG_ERROR, "close failed");
  225. }
  226. }
  227. NCDModuleInst_Backend_Dead(o->i);
  228. }
  229. static void process_handler (void *vo, int normally, uint8_t normally_exit_status)
  230. {
  231. struct process_instance *o = vo;
  232. ASSERT(o->state == PROCESS_STATE_RUNNING || o->state == PROCESS_STATE_DYING)
  233. ModuleLog(o->i, BLOG_INFO, "process terminated");
  234. // free process
  235. BProcess_Free(&o->process);
  236. // remember exit code
  237. o->exit_status = (!normally ? -1 : normally_exit_status);
  238. // finish waits
  239. LinkedList0Node *ln;
  240. while ((ln = LinkedList0_GetFirst(&o->waits_list))) {
  241. struct wait_instance *winst = UPPER_OBJECT(ln, struct wait_instance, waits_list_node);
  242. ASSERT(winst->pinst == o)
  243. LinkedList0_Remove(&o->waits_list, &winst->waits_list_node);
  244. winst->pinst = NULL;
  245. winst->exit_status = o->exit_status;
  246. NCDModuleInst_Backend_Up(winst->i);
  247. }
  248. // if we have been requested to die, then die now
  249. if (o->state == PROCESS_STATE_DYING) {
  250. process_free(o);
  251. return;
  252. }
  253. // set state
  254. o->state = PROCESS_STATE_TERMINATED;
  255. }
  256. static void process_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  257. {
  258. struct process_instance *o = vo;
  259. o->i = i;
  260. NCDModuleInst_Backend_PassMemToMethods(i);
  261. // check arguments
  262. NCDValRef command_arg;
  263. NCDValRef mode_arg;
  264. if (!NCDVal_ListRead(params->args, 2, &command_arg, &mode_arg)) {
  265. ModuleLog(i, BLOG_ERROR, "wrong arity");
  266. goto fail0;
  267. }
  268. // parse mode
  269. int is_read;
  270. int is_write;
  271. if (!parse_mode(i, mode_arg, &is_read, &is_write)) {
  272. goto fail0;
  273. }
  274. // prepare for creating pipes
  275. int fds[3];
  276. int fds_map[2];
  277. int num_fds = 0;
  278. int read_fd = -1;
  279. int write_fd = -1;
  280. // create read pipe
  281. if (is_read) {
  282. int pipefd[2];
  283. if (pipe(pipefd) < 0) {
  284. ModuleLog(i, BLOG_ERROR, "pipe failed");
  285. goto error1;
  286. }
  287. read_fd = pipefd[0];
  288. fds[num_fds] = pipefd[1];
  289. fds_map[num_fds++] = STDOUT_FILENO;
  290. }
  291. // create write pipe
  292. if (is_write) {
  293. int pipefd[2];
  294. if (pipe(pipefd) < 0) {
  295. ModuleLog(i, BLOG_ERROR, "pipe failed");
  296. goto error1;
  297. }
  298. write_fd = pipefd[1];
  299. fds[num_fds] = pipefd[0];
  300. fds_map[num_fds++] = STDIN_FILENO;
  301. }
  302. // terminate fds array
  303. fds[num_fds] = -1;
  304. // build process parameters struct
  305. struct BProcess_params p_params = {};
  306. p_params.fds = fds;
  307. p_params.fds_map = fds_map;
  308. // build command line
  309. char *exec;
  310. CmdLine cl;
  311. if (!ncd_build_cmdline(i, BLOG_CURRENT_CHANNEL, command_arg, &exec, &cl)) {
  312. goto error1;
  313. }
  314. // start process
  315. int res = BProcess_Init2(&o->process, i->params->iparams->manager, process_handler, o, exec, CmdLine_Get(&cl), p_params);
  316. CmdLine_Free(&cl);
  317. free(exec);
  318. if (!res) {
  319. ModuleLog(i, BLOG_ERROR, "BProcess_Init failed");
  320. goto error1;
  321. }
  322. // close child fds
  323. while (num_fds-- > 0) {
  324. if (close(fds[num_fds]) < 0) {
  325. ModuleLog(i, BLOG_ERROR, "close failed");
  326. }
  327. }
  328. // init waits list
  329. LinkedList0_Init(&o->waits_list);
  330. // remember our fds
  331. o->read_fd = read_fd;
  332. o->write_fd = write_fd;
  333. // set state
  334. o->state = PROCESS_STATE_RUNNING;
  335. // go up
  336. NCDModuleInst_Backend_Up(i);
  337. return;
  338. fail0:
  339. NCDModuleInst_Backend_DeadError(i);
  340. return;
  341. error1:
  342. if (write_fd != -1) {
  343. if (close(write_fd) < 0) {
  344. ModuleLog(i, BLOG_ERROR, "close failed");
  345. }
  346. }
  347. if (read_fd != -1) {
  348. if (close(read_fd) < 0) {
  349. ModuleLog(i, BLOG_ERROR, "close failed");
  350. }
  351. }
  352. while (num_fds-- > 0) {
  353. if (close(fds[num_fds]) < 0) {
  354. ModuleLog(i, BLOG_ERROR, "close failed");
  355. }
  356. }
  357. o->read_fd = -1;
  358. o->write_fd = -1;
  359. o->state = PROCESS_STATE_ERROR;
  360. NCDModuleInst_Backend_Up(i);
  361. }
  362. static void process_func_die (void *vo)
  363. {
  364. struct process_instance *o = vo;
  365. ASSERT(o->state != PROCESS_STATE_DYING)
  366. // if process is not running, die immediately
  367. if (o->state != PROCESS_STATE_RUNNING) {
  368. process_free(o);
  369. return;
  370. }
  371. ModuleLog(o->i, BLOG_INFO, "terminating process");
  372. // send termination signal
  373. BProcess_Terminate(&o->process);
  374. // set state
  375. o->state = PROCESS_STATE_DYING;
  376. }
  377. static int process_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  378. {
  379. struct process_instance *o = vo;
  380. if (name == NCD_STRING_IS_ERROR) {
  381. int is_error = (o->state == PROCESS_STATE_ERROR);
  382. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  383. return 1;
  384. }
  385. return 0;
  386. }
  387. static void wait_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  388. {
  389. struct wait_instance *o = vo;
  390. o->i = i;
  391. if (!NCDVal_ListRead(params->args, 0)) {
  392. ModuleLog(i, BLOG_ERROR, "wrong arity");
  393. goto fail0;
  394. }
  395. struct process_instance *pinst = params->method_user;
  396. if (pinst->state == PROCESS_STATE_ERROR) {
  397. ModuleLog(i, BLOG_ERROR, "wait() is disallowed after the process has failed to start");
  398. goto fail0;
  399. }
  400. if (pinst->state == PROCESS_STATE_TERMINATED) {
  401. // not waiting, set no pinst
  402. o->pinst = NULL;
  403. // remember exit code
  404. o->exit_status = pinst->exit_status;
  405. // go up
  406. NCDModuleInst_Backend_Up(i);
  407. } else {
  408. // waitint, set pinst
  409. o->pinst = pinst;
  410. // insert to waits list
  411. LinkedList0_Prepend(&pinst->waits_list, &o->waits_list_node);
  412. }
  413. return;
  414. fail0:
  415. NCDModuleInst_Backend_DeadError(i);
  416. }
  417. static void wait_func_die (void *vo)
  418. {
  419. struct wait_instance *o = vo;
  420. // remove from waits list
  421. if (o->pinst) {
  422. LinkedList0_Remove(&o->pinst->waits_list, &o->waits_list_node);
  423. }
  424. NCDModuleInst_Backend_Dead(o->i);
  425. }
  426. static int wait_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  427. {
  428. struct wait_instance *o = vo;
  429. ASSERT(!o->pinst)
  430. if (name == NCD_STRING_EXIT_STATUS) {
  431. if (o->exit_status == -1) {
  432. *out = NCDVal_NewString(mem, "-1");
  433. } else {
  434. *out = ncd_make_uintmax(mem, o->exit_status);
  435. }
  436. return 1;
  437. }
  438. return 0;
  439. }
  440. static void terminate_kill_new_common (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_kill)
  441. {
  442. if (!NCDVal_ListRead(params->args, 0)) {
  443. ModuleLog(i, BLOG_ERROR, "wrong arity");
  444. goto fail0;
  445. }
  446. struct process_instance *pinst = params->method_user;
  447. if (pinst->state == PROCESS_STATE_ERROR) {
  448. ModuleLog(i, BLOG_ERROR, "terminate()/kill() is disallowed after the process has failed to start");
  449. goto fail0;
  450. }
  451. if (pinst->state != PROCESS_STATE_TERMINATED) {
  452. if (is_kill) {
  453. BProcess_Kill(&pinst->process);
  454. } else {
  455. BProcess_Terminate(&pinst->process);
  456. }
  457. }
  458. NCDModuleInst_Backend_Up(i);
  459. return;
  460. fail0:
  461. NCDModuleInst_Backend_DeadError(i);
  462. }
  463. static void terminate_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  464. {
  465. terminate_kill_new_common(vo, i, params, 0);
  466. }
  467. static void kill_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  468. {
  469. terminate_kill_new_common(vo, i, params, 1);
  470. }
  471. static void read_pipe_free_connection (struct read_pipe_instance *o)
  472. {
  473. // disconnect read instance
  474. if (o->read_inst) {
  475. ASSERT(o->read_inst->read_pipe_inst == o)
  476. o->read_inst->read_pipe_inst = NULL;
  477. }
  478. // free store
  479. NCDBufStore_Free(&o->store);
  480. // free connection read interface
  481. BConnection_RecvAsync_Free(&o->connection);
  482. // free connection
  483. BConnection_Free(&o->connection);
  484. // close fd
  485. if (close(o->read_fd) < 0) {
  486. ModuleLog(o->i, BLOG_ERROR, "close failed");
  487. }
  488. }
  489. static void read_pipe_abort (struct read_pipe_instance *o)
  490. {
  491. ASSERT(o->state == READER_STATE_RUNNING)
  492. // release connection resources
  493. read_pipe_free_connection(o);
  494. // set state
  495. o->state = READER_STATE_ABORTED;
  496. }
  497. static void read_pipe_connection_handler (void *vo, int event)
  498. {
  499. struct read_pipe_instance *o = vo;
  500. ASSERT(o->state == READER_STATE_RUNNING)
  501. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  502. // if we have read operation, make it finish with eof
  503. if (o->read_inst) {
  504. ASSERT(o->read_inst->read_pipe_inst == o)
  505. ASSERT(o->read_inst->buf)
  506. o->read_inst->read_pipe_inst = NULL;
  507. o->read_inst->read_size = 0;
  508. NCDModuleInst_Backend_Up(o->read_inst->i);
  509. o->read_inst = NULL;
  510. }
  511. // free connection resources
  512. read_pipe_free_connection(o);
  513. // set state closed
  514. o->state = READER_STATE_EOF;
  515. return;
  516. }
  517. ModuleLog(o->i, BLOG_ERROR, "read pipe error");
  518. // free connection resources
  519. read_pipe_free_connection(o);
  520. // set state error
  521. o->state = READER_STATE_ERROR;
  522. // backtrack
  523. NCDModuleInst_Backend_DownUp(o->i);
  524. }
  525. static void read_pipe_recv_handler_done (void *vo, int data_len)
  526. {
  527. struct read_pipe_instance *o = vo;
  528. ASSERT(o->state == READER_STATE_RUNNING)
  529. ASSERT(o->read_inst)
  530. ASSERT(o->read_inst->read_pipe_inst == o)
  531. ASSERT(o->read_inst->buf)
  532. ASSERT(data_len > 0)
  533. ASSERT(data_len <= NCDBufStore_BufSize(&o->store))
  534. // finish read operation
  535. o->read_inst->read_pipe_inst = NULL;
  536. o->read_inst->read_size = data_len;
  537. NCDModuleInst_Backend_Up(o->read_inst->i);
  538. o->read_inst = NULL;
  539. }
  540. static void read_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  541. {
  542. struct read_pipe_instance *o = vo;
  543. o->i = i;
  544. NCDModuleInst_Backend_PassMemToMethods(i);
  545. if (!NCDVal_ListRead(params->args, 0)) {
  546. ModuleLog(i, BLOG_ERROR, "wrong arity");
  547. goto fail0;
  548. }
  549. struct process_instance *pinst = params->method_user;
  550. if (pinst->read_fd == -1) {
  551. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for reading or a read_pipe was already created");
  552. goto fail0;
  553. }
  554. // init connection
  555. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->read_fd), i->params->iparams->reactor, o, read_pipe_connection_handler)) {
  556. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  557. goto fail0;
  558. }
  559. // init connection read interface
  560. BConnection_RecvAsync_Init(&o->connection);
  561. // set recv done callback
  562. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), read_pipe_recv_handler_done, o);
  563. // init store
  564. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  565. // set variables
  566. o->state = READER_STATE_RUNNING;
  567. o->read_fd = pinst->read_fd;
  568. o->read_inst = NULL;
  569. // steal read fd from process instance
  570. pinst->read_fd = -1;
  571. // go up
  572. NCDModuleInst_Backend_Up(i);
  573. return;
  574. fail0:
  575. NCDModuleInst_Backend_DeadError(i);
  576. }
  577. static void read_pipe_func_die (void *vo)
  578. {
  579. struct read_pipe_instance *o = vo;
  580. // free connection resources
  581. if (o->state == READER_STATE_RUNNING) {
  582. read_pipe_free_connection(o);
  583. }
  584. NCDModuleInst_Backend_Dead(o->i);
  585. }
  586. static int read_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  587. {
  588. struct read_pipe_instance *o = vo;
  589. if (name == NCD_STRING_IS_ERROR) {
  590. int is_error = (o->state == READER_STATE_ERROR);
  591. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  592. return 1;
  593. }
  594. return 0;
  595. }
  596. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  597. {
  598. struct read_instance *o = vo;
  599. o->i = i;
  600. if (!NCDVal_ListRead(params->args, 0)) {
  601. ModuleLog(i, BLOG_ERROR, "wrong arity");
  602. goto fail0;
  603. }
  604. struct read_pipe_instance *read_pipe_inst = params->method_user;
  605. // check if a read error has already occured
  606. if (read_pipe_inst->state == READER_STATE_ERROR) {
  607. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read error has occured");
  608. goto fail0;
  609. }
  610. // check if the read_pipe has been aborted
  611. if (read_pipe_inst->state == READER_STATE_ABORTED) {
  612. ModuleLog(i, BLOG_ERROR, "read() is disallowed after a read() has been aborted");
  613. goto fail0;
  614. }
  615. // if EOF has already been encountered, complete the read immediately
  616. if (read_pipe_inst->state == READER_STATE_EOF) {
  617. o->buf = NULL;
  618. o->read_pipe_inst = NULL;
  619. o->read_size = 0;
  620. NCDModuleInst_Backend_Up(i);
  621. return;
  622. }
  623. ASSERT(read_pipe_inst->state == READER_STATE_RUNNING)
  624. // check if there's already a read in progress
  625. if (read_pipe_inst->read_inst) {
  626. ModuleLog(i, BLOG_ERROR, "read() is disallowed while another read() is in progress");
  627. goto fail0;
  628. }
  629. // get buffer
  630. o->buf = NCDBufStore_GetBuf(&read_pipe_inst->store);
  631. if (!o->buf) {
  632. ModuleLog(i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  633. goto fail0;
  634. }
  635. // set read_pipe
  636. o->read_pipe_inst = read_pipe_inst;
  637. // register read in read_pipe
  638. read_pipe_inst->read_inst = o;
  639. // receive
  640. size_t buf_size = NCDBufStore_BufSize(&read_pipe_inst->store);
  641. int to_read = (buf_size > INT_MAX ? INT_MAX : buf_size);
  642. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&read_pipe_inst->connection), (uint8_t *)NCDBuf_Data(o->buf), to_read);
  643. return;
  644. fail0:
  645. NCDModuleInst_Backend_DeadError(i);
  646. }
  647. static void read_func_die (void *vo)
  648. {
  649. struct read_instance *o = vo;
  650. // if we're receiving, abort read_pipe
  651. if (o->read_pipe_inst) {
  652. ASSERT(o->read_pipe_inst->state == READER_STATE_RUNNING)
  653. ASSERT(o->read_pipe_inst->read_inst == o)
  654. ASSERT(o->buf)
  655. read_pipe_abort(o->read_pipe_inst);
  656. }
  657. // release buffer
  658. if (o->buf) {
  659. NCDRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  660. }
  661. NCDModuleInst_Backend_Dead(o->i);
  662. }
  663. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  664. {
  665. struct read_instance *o = vo;
  666. ASSERT(!o->read_pipe_inst)
  667. ASSERT(!(o->read_size > 0) || o->buf)
  668. if (name == NCD_STRING_EMPTY) {
  669. if (o->read_size > 0) {
  670. *out = NCDVal_NewExternalString(mem, NCDBuf_Data(o->buf), o->read_size, NCDBuf_RefTarget(o->buf));
  671. } else {
  672. *out = NCDVal_NewIdString(mem, NCD_STRING_EMPTY, o->i->params->iparams->string_index);
  673. }
  674. return 1;
  675. }
  676. if (name == NCD_STRING_NOT_EOF) {
  677. int not_eof = (o->read_size > 0);
  678. *out = ncd_make_boolean(mem, not_eof, o->i->params->iparams->string_index);
  679. return 1;
  680. }
  681. return 0;
  682. }
  683. static void write_pipe_free_connection (struct write_pipe_instance *o)
  684. {
  685. // disconnect write instance
  686. if (o->write_inst) {
  687. ASSERT(o->write_inst->write_pipe_inst == o)
  688. o->write_inst->write_pipe_inst = NULL;
  689. }
  690. // free connection send interface
  691. BConnection_SendAsync_Free(&o->connection);
  692. // free connection
  693. BConnection_Free(&o->connection);
  694. // close fd
  695. if (close(o->write_fd) < 0) {
  696. ModuleLog(o->i, BLOG_ERROR, "close failed");
  697. }
  698. }
  699. static void write_pipe_abort (struct write_pipe_instance *o)
  700. {
  701. ASSERT(o->state == WRITER_STATE_RUNNING)
  702. // release connection resources
  703. write_pipe_free_connection(o);
  704. // set state
  705. o->state = WRITER_STATE_ABORTED;
  706. }
  707. static void write_pipe_close (struct write_pipe_instance *o)
  708. {
  709. ASSERT(o->state == WRITER_STATE_RUNNING)
  710. // release connection resources
  711. write_pipe_free_connection(o);
  712. // set state
  713. o->state = WRITER_STATE_CLOSED;
  714. }
  715. static void write_pipe_connection_handler (void *vo, int event)
  716. {
  717. struct write_pipe_instance *o = vo;
  718. ASSERT(o->state == WRITER_STATE_RUNNING)
  719. ModuleLog(o->i, BLOG_ERROR, "write pipe error");
  720. // free connection resources
  721. write_pipe_free_connection(o);
  722. // set state error
  723. o->state = WRITER_STATE_ERROR;
  724. // backtrack
  725. NCDModuleInst_Backend_DownUp(o->i);
  726. }
  727. static void write_pipe_send_handler_done (void *vo, int data_len)
  728. {
  729. struct write_pipe_instance *o = vo;
  730. ASSERT(o->state == WRITER_STATE_RUNNING)
  731. ASSERT(o->write_inst)
  732. ASSERT(o->write_inst->write_pipe_inst == o)
  733. ASSERT(data_len > 0)
  734. ASSERT(data_len <= o->write_inst->cstr.length - o->write_inst->pos)
  735. struct write_instance *wr = o->write_inst;
  736. // update write progress
  737. wr->pos += data_len;
  738. // if there is more data, start another write operation
  739. if (wr->pos < wr->cstr.length) {
  740. size_t chunk_length;
  741. const char *chunk_data = b_cstring_get(wr->cstr, wr->pos, wr->cstr.length - wr->pos, &chunk_length);
  742. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  743. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)chunk_data, to_send);
  744. return;
  745. }
  746. // finish write operation
  747. wr->write_pipe_inst = NULL;
  748. NCDModuleInst_Backend_Up(wr->i);
  749. o->write_inst = NULL;
  750. }
  751. static void write_pipe_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  752. {
  753. struct write_pipe_instance *o = vo;
  754. o->i = i;
  755. NCDModuleInst_Backend_PassMemToMethods(i);
  756. if (!NCDVal_ListRead(params->args, 0)) {
  757. ModuleLog(i, BLOG_ERROR, "wrong arity");
  758. goto fail0;
  759. }
  760. struct process_instance *pinst = params->method_user;
  761. if (pinst->write_fd == -1) {
  762. ModuleLog(i, BLOG_ERROR, "process did not start successfully, was not opened for writing or a write_pipe was already created");
  763. goto fail0;
  764. }
  765. // init connection
  766. if (!BConnection_Init(&o->connection, BConnection_source_pipe(pinst->write_fd), i->params->iparams->reactor, o, write_pipe_connection_handler)) {
  767. ModuleLog(i, BLOG_ERROR, "BConnection_Init failed");
  768. goto fail0;
  769. }
  770. // init connection send interface
  771. BConnection_SendAsync_Init(&o->connection);
  772. // set send done callback
  773. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), write_pipe_send_handler_done, o);
  774. // set variables
  775. o->state = WRITER_STATE_RUNNING;
  776. o->write_fd = pinst->write_fd;
  777. o->write_inst = NULL;
  778. // steal write fd from process instance
  779. pinst->write_fd = -1;
  780. // go up
  781. NCDModuleInst_Backend_Up(i);
  782. return;
  783. fail0:
  784. NCDModuleInst_Backend_DeadError(i);
  785. }
  786. static void write_pipe_func_die (void *vo)
  787. {
  788. struct write_pipe_instance *o = vo;
  789. // free connection resources
  790. if (o->state == WRITER_STATE_RUNNING) {
  791. write_pipe_free_connection(o);
  792. }
  793. NCDModuleInst_Backend_Dead(o->i);
  794. }
  795. static int write_pipe_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  796. {
  797. struct write_pipe_instance *o = vo;
  798. if (name == NCD_STRING_IS_ERROR) {
  799. int is_error = (o->state == WRITER_STATE_ERROR);
  800. *out = ncd_make_boolean(mem, is_error, o->i->params->iparams->string_index);
  801. return 1;
  802. }
  803. return 0;
  804. }
  805. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  806. {
  807. struct write_instance *o = vo;
  808. o->i = i;
  809. NCDValRef data_arg;
  810. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  811. ModuleLog(i, BLOG_ERROR, "wrong arity");
  812. goto fail0;
  813. }
  814. if (!NCDVal_IsString(data_arg)) {
  815. ModuleLog(i, BLOG_ERROR, "wrong type");
  816. goto fail0;
  817. }
  818. struct write_pipe_instance *write_pipe_inst = params->method_user;
  819. // check if a write error has already occured
  820. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  821. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write error has occured");
  822. goto fail0;
  823. }
  824. // check if the write_pipe has been aborted
  825. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  826. ModuleLog(i, BLOG_ERROR, "write() is disallowed after a write() has been aborted");
  827. goto fail0;
  828. }
  829. // check if the write_pipe has been aborted
  830. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  831. ModuleLog(i, BLOG_ERROR, "write() is disallowed after close() has been called");
  832. goto fail0;
  833. }
  834. ASSERT(write_pipe_inst->state == WRITER_STATE_RUNNING)
  835. // check if there's already a write in progress
  836. if (write_pipe_inst->write_inst) {
  837. ModuleLog(i, BLOG_ERROR, "write() is disallowed while another write() is in progress");
  838. goto fail0;
  839. }
  840. // initialize write progress state
  841. o->cstr = NCDVal_StringCstring(data_arg);
  842. o->pos = 0;
  843. // if there's nothing to send, go up immediately
  844. if (o->cstr.length == 0) {
  845. o->write_pipe_inst = NULL;
  846. NCDModuleInst_Backend_Up(i);
  847. return;
  848. }
  849. // set write_pipe
  850. o->write_pipe_inst = write_pipe_inst;
  851. // register write in write_pipe
  852. write_pipe_inst->write_inst = o;
  853. // start send operation
  854. size_t chunk_length;
  855. const char *chunk_data = b_cstring_get(o->cstr, o->pos, o->cstr.length - o->pos, &chunk_length);
  856. size_t to_send = (chunk_length > INT_MAX ? INT_MAX : chunk_length);
  857. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&write_pipe_inst->connection), (uint8_t *)chunk_data, to_send);
  858. return;
  859. fail0:
  860. NCDModuleInst_Backend_DeadError(i);
  861. }
  862. static void write_func_die (void *vo)
  863. {
  864. struct write_instance *o = vo;
  865. // if we're sending, abort write_pipe
  866. if (o->write_pipe_inst) {
  867. ASSERT(o->write_pipe_inst->state == WRITER_STATE_RUNNING)
  868. ASSERT(o->write_pipe_inst->write_inst == o)
  869. write_pipe_abort(o->write_pipe_inst);
  870. }
  871. NCDModuleInst_Backend_Dead(o->i);
  872. }
  873. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  874. {
  875. if (!NCDVal_ListRead(params->args, 0)) {
  876. ModuleLog(i, BLOG_ERROR, "wrong arity");
  877. goto fail0;
  878. }
  879. struct write_pipe_instance *write_pipe_inst = params->method_user;
  880. // check if a write error has already occured
  881. if (write_pipe_inst->state == WRITER_STATE_ERROR) {
  882. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write error has occured");
  883. goto fail0;
  884. }
  885. // check if the write_pipe has been aborted
  886. if (write_pipe_inst->state == WRITER_STATE_ABORTED) {
  887. ModuleLog(i, BLOG_ERROR, "close() is disallowed after a write() has been aborted");
  888. goto fail0;
  889. }
  890. // check if the write_pipe has been closed
  891. if (write_pipe_inst->state == WRITER_STATE_CLOSED) {
  892. ModuleLog(i, BLOG_ERROR, "close() is disallowed after close() has been called");
  893. goto fail0;
  894. }
  895. // close
  896. write_pipe_close(write_pipe_inst);
  897. // go up
  898. NCDModuleInst_Backend_Up(i);
  899. return;
  900. fail0:
  901. NCDModuleInst_Backend_DeadError(i);
  902. }
  903. static struct NCDModule modules[] = {
  904. {
  905. .type = "sys.start_process",
  906. .func_new2 = process_func_new,
  907. .func_die = process_func_die,
  908. .func_getvar2 = process_func_getvar,
  909. .alloc_size = sizeof(struct process_instance),
  910. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  911. }, {
  912. .type = "sys.start_process::wait",
  913. .func_new2 = wait_func_new,
  914. .func_die = wait_func_die,
  915. .func_getvar2 = wait_func_getvar,
  916. .alloc_size = sizeof(struct wait_instance),
  917. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  918. }, {
  919. .type = "sys.start_process::terminate",
  920. .func_new2 = terminate_func_new,
  921. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  922. }, {
  923. .type = "sys.start_process::kill",
  924. .func_new2 = kill_func_new,
  925. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  926. }, {
  927. .type = "sys.start_process::read_pipe",
  928. .func_new2 = read_pipe_func_new,
  929. .func_die = read_pipe_func_die,
  930. .func_getvar2 = read_pipe_func_getvar,
  931. .alloc_size = sizeof(struct read_pipe_instance),
  932. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  933. }, {
  934. .type = "sys.start_process::read_pipe::read",
  935. .func_new2 = read_func_new,
  936. .func_die = read_func_die,
  937. .func_getvar2 = read_func_getvar,
  938. .alloc_size = sizeof(struct read_instance),
  939. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  940. }, {
  941. .type = "sys.start_process::write_pipe",
  942. .func_new2 = write_pipe_func_new,
  943. .func_die = write_pipe_func_die,
  944. .func_getvar2 = write_pipe_func_getvar,
  945. .alloc_size = sizeof(struct write_pipe_instance),
  946. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  947. }, {
  948. .type = "sys.start_process::write_pipe::write",
  949. .func_new2 = write_func_new,
  950. .func_die = write_func_die,
  951. .alloc_size = sizeof(struct write_instance),
  952. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  953. }, {
  954. .type = "sys.start_process::write_pipe::close",
  955. .func_new2 = close_func_new,
  956. .flags = NCDMODULE_FLAG_ACCEPT_NON_CONTINUOUS_STRINGS
  957. }, {
  958. .type = NULL
  959. }
  960. };
  961. const struct NCDModuleGroup ncdmodule_sys_start_process = {
  962. .modules = modules
  963. };