sys_start_process.c 33 KB

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