cmdline.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
  2. *
  3. * Data Differential YATL (i.e. libtest) library
  4. *
  5. * Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * * Redistributions in binary form must reproduce the above
  15. * copyright notice, this list of conditions and the following disclaimer
  16. * in the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * * The names of its contributors may not be used to endorse or
  20. * promote products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. *
  35. */
  36. #include "libtest/yatlcon.h"
  37. #include "libtest/common.h"
  38. using namespace libtest;
  39. #include <cstdlib>
  40. #include <cstring>
  41. #include <cerrno>
  42. #include <fcntl.h>
  43. #include <fstream>
  44. #include <memory>
  45. #ifdef HAVE_POLL_H
  46. # include <poll.h>
  47. #endif
  48. #ifdef HAVE_SPAWN_H
  49. # include <spawn.h>
  50. #endif
  51. #include <sstream>
  52. #include <string>
  53. #include <sys/stat.h>
  54. #include <sys/types.h>
  55. #include <unistd.h>
  56. #include <algorithm>
  57. #include <stdexcept>
  58. #if defined(__APPLE__) && __APPLE__
  59. # include <crt_externs.h>
  60. # define environ (*_NSGetEnviron ())
  61. #elif !defined(_GNU_SOURCE)
  62. extern char **environ= NULL;
  63. #endif
  64. #ifndef FD_CLOEXEC
  65. # define FD_CLOEXEC 0
  66. #endif
  67. namespace {
  68. std::string print_argv(libtest::vchar_ptr_t& built_argv)
  69. {
  70. std::stringstream arg_buffer;
  71. for (vchar_ptr_t::iterator iter= built_argv.begin();
  72. iter != built_argv.end();
  73. ++iter)
  74. {
  75. if (*iter)
  76. {
  77. arg_buffer << *iter << " ";
  78. }
  79. }
  80. return arg_buffer.str();
  81. }
  82. #if 0
  83. std::string print_argv(char** argv)
  84. {
  85. std::stringstream arg_buffer;
  86. for (char** ptr= argv; *ptr; ++ptr)
  87. {
  88. arg_buffer << *ptr << " ";
  89. }
  90. return arg_buffer.str();
  91. }
  92. #endif
  93. static Application::error_t int_to_error_t(int arg)
  94. {
  95. switch (arg)
  96. {
  97. case 127:
  98. return Application::INVALID_POSIX_SPAWN;
  99. case 0:
  100. return Application::SUCCESS;
  101. case 1:
  102. return Application::FAILURE;
  103. default:
  104. return Application::UNKNOWN;
  105. }
  106. }
  107. }
  108. namespace libtest {
  109. Application::Application(const std::string& arg, const bool _use_libtool_arg) :
  110. _use_libtool(_use_libtool_arg),
  111. _use_valgrind(false),
  112. _use_gdb(false),
  113. _use_ptrcheck(false),
  114. _will_fail(false),
  115. _argc(0),
  116. _exectuble(arg),
  117. stdin_fd(STDIN_FILENO),
  118. stdout_fd(STDOUT_FILENO),
  119. stderr_fd(STDERR_FILENO),
  120. _pid(-1),
  121. _status(0),
  122. _app_exit_state(UNINITIALIZED)
  123. {
  124. if (_use_libtool)
  125. {
  126. if (libtool() == NULL)
  127. {
  128. FATAL("libtool requested, but know libtool was found");
  129. }
  130. }
  131. // Find just the name of the application with no path
  132. {
  133. size_t found= arg.find_last_of("/\\");
  134. if (found)
  135. {
  136. _exectuble_name= arg.substr(found +1);
  137. }
  138. else
  139. {
  140. _exectuble_name= arg;
  141. }
  142. }
  143. if (_use_libtool and getenv("PWD"))
  144. {
  145. _exectuble_with_path+= getenv("PWD");
  146. _exectuble_with_path+= "/";
  147. }
  148. _exectuble_with_path+= _exectuble;
  149. }
  150. Application::~Application()
  151. {
  152. murder();
  153. delete_argv();
  154. }
  155. Application::error_t Application::run(const char *args[])
  156. {
  157. stdin_fd.reset();
  158. stdout_fd.reset();
  159. stderr_fd.reset();
  160. _stdout_buffer.clear();
  161. _stderr_buffer.clear();
  162. posix_spawn_file_actions_t file_actions;
  163. posix_spawn_file_actions_init(&file_actions);
  164. stdin_fd.dup_for_spawn(file_actions);
  165. stdout_fd.dup_for_spawn(file_actions);
  166. stderr_fd.dup_for_spawn(file_actions);
  167. posix_spawnattr_t spawnattr;
  168. posix_spawnattr_init(&spawnattr);
  169. short flags= 0;
  170. // Child should not block signals
  171. flags |= POSIX_SPAWN_SETSIGMASK;
  172. sigset_t mask;
  173. sigemptyset(&mask);
  174. fatal_assert(posix_spawnattr_setsigmask(&spawnattr, &mask) == 0);
  175. #if defined(POSIX_SPAWN_USEVFORK) || defined(__GLIBC__)
  176. // Use USEVFORK where appropriate
  177. flags |= POSIX_SPAWN_USEVFORK;
  178. #endif
  179. flags |= POSIX_SPAWN_SETPGROUP;
  180. fatal_assert(posix_spawnattr_setpgroup(&spawnattr, 0) == 0);
  181. fatal_assert(posix_spawnattr_setflags(&spawnattr, flags) == 0);
  182. create_argv(args);
  183. int spawn_ret;
  184. if (_use_gdb)
  185. {
  186. std::string gdb_run_file= create_tmpfile(_exectuble_name);
  187. std::fstream file_stream;
  188. file_stream.open(gdb_run_file.c_str(), std::fstream::out | std::fstream::trunc);
  189. _gdb_filename= create_tmpfile(_exectuble_name);
  190. file_stream
  191. << "set logging redirect on" << std::endl
  192. << "set logging file " << _gdb_filename << std::endl
  193. << "set logging overwrite on" << std::endl
  194. << "set logging on" << std::endl
  195. << "set environment LIBTEST_IN_GDB=1" << std::endl
  196. << "run " << arguments() << std::endl
  197. << "thread apply all bt" << std::endl
  198. << "quit" << std::endl;
  199. fatal_assert(file_stream.good());
  200. file_stream.close();
  201. if (_use_libtool)
  202. {
  203. // libtool --mode=execute gdb -f -x binary
  204. char *argv[]= {
  205. const_cast<char *>(libtool()),
  206. const_cast<char *>("--mode=execute"),
  207. const_cast<char *>("gdb"),
  208. const_cast<char *>("-batch"),
  209. const_cast<char *>("-f"),
  210. const_cast<char *>("-x"),
  211. const_cast<char *>(gdb_run_file.c_str()),
  212. const_cast<char *>(_exectuble_with_path.c_str()),
  213. 0};
  214. spawn_ret= posix_spawnp(&_pid, libtool(), &file_actions, &spawnattr, argv, environ);
  215. }
  216. else
  217. {
  218. // gdb binary
  219. char *argv[]= {
  220. const_cast<char *>("gdb"),
  221. const_cast<char *>("-batch"),
  222. const_cast<char *>("-f"),
  223. const_cast<char *>("-x"),
  224. const_cast<char *>(gdb_run_file.c_str()),
  225. const_cast<char *>(_exectuble_with_path.c_str()),
  226. 0};
  227. spawn_ret= posix_spawnp(&_pid, "gdb", &file_actions, &spawnattr, argv, environ);
  228. }
  229. }
  230. else
  231. {
  232. spawn_ret= posix_spawn(&_pid, built_argv[0], &file_actions, &spawnattr, &built_argv[0], NULL);
  233. }
  234. posix_spawn_file_actions_destroy(&file_actions);
  235. posix_spawnattr_destroy(&spawnattr);
  236. stdin_fd.close(Application::Pipe::READ);
  237. stdout_fd.close(Application::Pipe::WRITE);
  238. stderr_fd.close(Application::Pipe::WRITE);
  239. if (spawn_ret != 0)
  240. {
  241. if (_will_fail == false)
  242. {
  243. Error << strerror(spawn_ret) << "(" << spawn_ret << ")";
  244. }
  245. _pid= -1;
  246. return Application::INVALID_POSIX_SPAWN;
  247. }
  248. assert(_pid != -1);
  249. if (_pid == -1)
  250. {
  251. return Application::INVALID_POSIX_SPAWN;
  252. }
  253. #if 0
  254. app_thread_st* _app_thread= new app_thread_st(_pid, _status, built_argv[0], _app_exit_state);
  255. int error;
  256. if ((error= pthread_create(&_thread, NULL, &app_thread, _app_thread)) != 0)
  257. {
  258. Error << "pthread_create() died during pthread_create(" << strerror(error) << ")";
  259. return Application::FAILURE;
  260. }
  261. #endif
  262. return Application::SUCCESS;
  263. }
  264. bool Application::check() const
  265. {
  266. if (_pid > 1 and kill(_pid, 0) == 0)
  267. {
  268. return true;
  269. }
  270. return false;
  271. }
  272. void Application::murder()
  273. {
  274. if (check())
  275. {
  276. int count= 5;
  277. while ((count--) > 0 and check())
  278. {
  279. if (kill(_pid, SIGTERM) == 0)
  280. {
  281. join();
  282. }
  283. else
  284. {
  285. Error << "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno);
  286. continue;
  287. }
  288. break;
  289. }
  290. // If for whatever reason it lives, kill it hard
  291. if (check())
  292. {
  293. Error << "using SIGKILL, things will likely go poorly from this point";
  294. (void)kill(_pid, SIGKILL);
  295. }
  296. }
  297. slurp();
  298. }
  299. // false means that no data was returned
  300. bool Application::slurp()
  301. {
  302. struct pollfd fds[2];
  303. fds[0].fd= stdout_fd.fd();
  304. fds[0].events= POLLRDNORM;
  305. fds[0].revents= 0;
  306. fds[1].fd= stderr_fd.fd();
  307. fds[1].events= POLLRDNORM;
  308. fds[1].revents= 0;
  309. int active_fd;
  310. if ((active_fd= poll(fds, 2, 0)) == -1)
  311. {
  312. int error;
  313. switch ((error= errno))
  314. {
  315. #ifdef __linux
  316. case ERESTART:
  317. #endif
  318. case EINTR:
  319. break;
  320. case EFAULT:
  321. case ENOMEM:
  322. FATAL(strerror(error));
  323. break;
  324. case EINVAL:
  325. FATAL("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
  326. break;
  327. default:
  328. FATAL(strerror(error));
  329. break;
  330. }
  331. return false;
  332. }
  333. if (active_fd == 0)
  334. {
  335. return false;
  336. }
  337. bool data_was_read= false;
  338. if (fds[0].revents)
  339. {
  340. if (fds[0].revents & POLLRDNORM)
  341. {
  342. if (stdout_fd.read(_stdout_buffer) == true)
  343. {
  344. data_was_read= true;
  345. }
  346. }
  347. if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL))
  348. {
  349. stdout_fd.close();
  350. if (fds[0].revents & POLLERR)
  351. {
  352. Error << "getsockopt(stdout)";
  353. }
  354. }
  355. }
  356. if (fds[1].revents)
  357. {
  358. if (fds[1].revents & POLLRDNORM)
  359. {
  360. if (stderr_fd.read(_stderr_buffer) == true)
  361. {
  362. data_was_read= true;
  363. }
  364. }
  365. if (fds[1].revents & (POLLERR | POLLHUP | POLLNVAL))
  366. {
  367. stderr_fd.close();
  368. if (fds[1].revents & POLLERR)
  369. {
  370. Error << "getsockopt(stderr)";
  371. }
  372. }
  373. }
  374. return data_was_read;
  375. }
  376. #pragma GCC diagnostic push
  377. #pragma GCC diagnostic ignored "-Wunreachable-code"
  378. Application::error_t Application::join()
  379. {
  380. if (waitpid(_pid, &_status, 0) == -1)
  381. {
  382. std::string error_string;
  383. if (stdout_result_length())
  384. {
  385. error_string+= " stdout: ";
  386. error_string+= stdout_c_str();
  387. }
  388. if (stderr_result_length())
  389. {
  390. error_string+= " stderr: ";
  391. error_string+= stderr_c_str();
  392. }
  393. Error << "waitpid() returned errno:" << strerror(errno) << " " << error_string;
  394. return Application::UNKNOWN;
  395. }
  396. slurp();
  397. if (WIFEXITED(_status) == false)
  398. {
  399. /*
  400. What we are looking for here is how the exit status happened.
  401. - 127 means that posix_spawn() itself had an error.
  402. - If WEXITSTATUS is positive we need to see if it is a signal that we sent to kill the process. If not something bad happened in the process itself.
  403. - Finally something has happened that we don't currently understand.
  404. */
  405. if (WEXITSTATUS(_status) == 127)
  406. {
  407. _app_exit_state= Application::INVALID_POSIX_SPAWN;
  408. std::string error_string("posix_spawn() failed pid:");
  409. error_string+= _pid;
  410. error_string+= " name:";
  411. error_string+= print_argv(built_argv);
  412. if (stderr_result_length())
  413. {
  414. error_string+= " stderr: ";
  415. error_string+= stderr_c_str();
  416. }
  417. throw std::logic_error(error_string);
  418. }
  419. else if (WIFSIGNALED(_status))
  420. {
  421. if (WTERMSIG(_status) != SIGTERM and WTERMSIG(_status) != SIGHUP)
  422. {
  423. slurp();
  424. _app_exit_state= Application::INVALID_POSIX_SPAWN;
  425. std::string error_string(print_argv(built_argv));
  426. error_string+= " was killed by signal ";
  427. error_string+= strsignal(WTERMSIG(_status));
  428. if (stdout_result_length())
  429. {
  430. error_string+= " stdout: ";
  431. error_string+= stdout_c_str();
  432. }
  433. if (stderr_result_length())
  434. {
  435. error_string+= " stderr: ";
  436. error_string+= stderr_c_str();
  437. }
  438. throw std::runtime_error(error_string);
  439. }
  440. // If we terminted it on purpose then it counts as a success.
  441. #if defined(DEBUG)
  442. if (DEBUG)
  443. {
  444. Out << "waitpid() application terminated at request"
  445. << " pid:" << _pid
  446. << " name:" << built_argv[0];
  447. }
  448. #endif
  449. }
  450. else
  451. {
  452. _app_exit_state= Application::UNKNOWN;
  453. Error << "Unknown logic state at exit:" << WEXITSTATUS(_status)
  454. << " pid:" << _pid
  455. << " name:" << built_argv[0];
  456. }
  457. }
  458. else if (WIFEXITED(_status))
  459. {
  460. return int_to_error_t(WEXITSTATUS(_status));
  461. }
  462. else
  463. {
  464. _app_exit_state= Application::UNKNOWN;
  465. throw std::logic_error("waitpid() returned an unknown value");
  466. }
  467. return _app_exit_state;
  468. }
  469. #pragma GCC diagnostic pop
  470. void Application::add_long_option(const std::string& name, const std::string& option_value)
  471. {
  472. std::string arg(name);
  473. arg+= option_value;
  474. _options.push_back(std::make_pair(arg, std::string()));
  475. }
  476. void Application::add_option(const std::string& arg)
  477. {
  478. _options.push_back(std::make_pair(arg, std::string()));
  479. }
  480. void Application::add_option(const std::string& name, const std::string& value)
  481. {
  482. _options.push_back(std::make_pair(name, value));
  483. }
  484. Application::Pipe::Pipe(int arg) :
  485. _std_fd(arg)
  486. {
  487. _pipe_fd[READ]= -1;
  488. _pipe_fd[WRITE]= -1;
  489. _open[READ]= false;
  490. _open[WRITE]= false;
  491. }
  492. int Application::Pipe::Pipe::fd()
  493. {
  494. if (_std_fd == STDOUT_FILENO)
  495. {
  496. return _pipe_fd[READ];
  497. }
  498. else if (_std_fd == STDERR_FILENO)
  499. {
  500. return _pipe_fd[READ];
  501. }
  502. return _pipe_fd[WRITE]; // STDIN_FILENO
  503. }
  504. void Application::Pipe::Pipe::close()
  505. {
  506. if (_std_fd == STDOUT_FILENO)
  507. {
  508. ::close(_pipe_fd[READ]);
  509. _pipe_fd[READ]= -1;
  510. }
  511. else if (_std_fd == STDERR_FILENO)
  512. {
  513. ::close(_pipe_fd[READ]);
  514. _pipe_fd[READ]= -1;
  515. }
  516. else
  517. {
  518. ::close(_pipe_fd[WRITE]);
  519. _pipe_fd[WRITE]= -1;
  520. }
  521. }
  522. bool Application::Pipe::read(libtest::vchar_t& arg)
  523. {
  524. fatal_assert(_std_fd == STDOUT_FILENO or _std_fd == STDERR_FILENO);
  525. bool data_was_read= false;
  526. libtest::vchar_t buffer;
  527. buffer.resize(1024);
  528. ssize_t read_length;
  529. while ((read_length= ::read(_pipe_fd[READ], &buffer[0], buffer.size())))
  530. {
  531. if (read_length == -1)
  532. {
  533. switch(errno)
  534. {
  535. case EAGAIN:
  536. break;
  537. default:
  538. Error << strerror(errno);
  539. break;
  540. }
  541. break;
  542. }
  543. data_was_read= true;
  544. arg.reserve(read_length +1);
  545. for (size_t x= 0; x < size_t(read_length); ++x)
  546. {
  547. arg.push_back(buffer[x]);
  548. }
  549. // @todo Suck up all errput code here
  550. }
  551. return data_was_read;
  552. }
  553. void Application::Pipe::nonblock()
  554. {
  555. int flags;
  556. do
  557. {
  558. flags= fcntl(_pipe_fd[READ], F_GETFL, 0);
  559. } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
  560. if (flags == -1)
  561. {
  562. Error << "fcntl(F_GETFL) " << strerror(errno);
  563. throw std::runtime_error(strerror(errno));
  564. }
  565. int rval;
  566. do
  567. {
  568. rval= fcntl(_pipe_fd[READ], F_SETFL, flags | O_NONBLOCK);
  569. } while (rval == -1 and (errno == EINTR or errno == EAGAIN));
  570. if (rval == -1)
  571. {
  572. Error << "fcntl(F_SETFL) " << strerror(errno);
  573. throw std::runtime_error(strerror(errno));
  574. }
  575. }
  576. void Application::Pipe::reset()
  577. {
  578. close(READ);
  579. close(WRITE);
  580. #ifdef HAVE_PIPE2
  581. if (pipe2(_pipe_fd, O_NONBLOCK|O_CLOEXEC) == -1)
  582. #endif
  583. {
  584. if (pipe(_pipe_fd) == -1)
  585. {
  586. FATAL(strerror(errno));
  587. }
  588. // Since either pipe2() was not found/called we set the pipe directly
  589. nonblock();
  590. cloexec();
  591. }
  592. _open[0]= true;
  593. _open[1]= true;
  594. }
  595. void Application::Pipe::cloexec()
  596. {
  597. //if (SOCK_CLOEXEC == 0)
  598. {
  599. if (FD_CLOEXEC)
  600. {
  601. int flags;
  602. do
  603. {
  604. flags= fcntl(_pipe_fd[WRITE], F_GETFD, 0);
  605. } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
  606. if (flags == -1)
  607. {
  608. Error << "fcntl(F_GETFD) " << strerror(errno);
  609. throw std::runtime_error(strerror(errno));
  610. }
  611. int rval;
  612. do
  613. {
  614. rval= fcntl(_pipe_fd[WRITE], F_SETFD, flags | FD_CLOEXEC);
  615. } while (rval == -1 && (errno == EINTR or errno == EAGAIN));
  616. if (rval == -1)
  617. {
  618. Error << "fcntl(F_SETFD) " << strerror(errno);
  619. throw std::runtime_error(strerror(errno));
  620. }
  621. }
  622. }
  623. }
  624. Application::Pipe::~Pipe()
  625. {
  626. if (_pipe_fd[0] != -1)
  627. {
  628. ::close(_pipe_fd[0]);
  629. }
  630. if (_pipe_fd[1] != -1)
  631. {
  632. ::close(_pipe_fd[1]);
  633. }
  634. }
  635. void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t& file_actions)
  636. {
  637. int type= STDIN_FILENO == _std_fd ? 0 : 1;
  638. int ret;
  639. if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _pipe_fd[type], _std_fd )) < 0)
  640. {
  641. FATAL("posix_spawn_file_actions_adddup2(%s)", strerror(ret));
  642. }
  643. if ((ret= posix_spawn_file_actions_addclose(&file_actions, _pipe_fd[type])) < 0)
  644. {
  645. FATAL("posix_spawn_file_actions_addclose(%s)", strerror(ret));
  646. }
  647. }
  648. void Application::Pipe::close(const close_t& arg)
  649. {
  650. int type= int(arg);
  651. if (_open[type])
  652. {
  653. if (::close(_pipe_fd[type]) == -1)
  654. {
  655. Error << "close(" << strerror(errno) << ")";
  656. }
  657. _open[type]= false;
  658. _pipe_fd[type]= -1;
  659. }
  660. }
  661. void Application::create_argv(const char *args[])
  662. {
  663. delete_argv();
  664. if (_use_libtool)
  665. {
  666. assert(libtool());
  667. vchar::append(built_argv, libtool());
  668. vchar::append(built_argv, "--mode=execute");
  669. }
  670. if (_use_valgrind)
  671. {
  672. /*
  673. valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
  674. */
  675. vchar::append(built_argv, "valgrind");
  676. vchar::append(built_argv, "--error-exitcode=1");
  677. vchar::append(built_argv, "--leak-check=yes");
  678. #if 0
  679. vchar::append(built_argv, "--show-reachable=yes"));
  680. vchar::append(built_argv, "--track-fds=yes");
  681. #endif
  682. #if 0
  683. built_argv[x++]= strdup("--track-origin=yes");
  684. #endif
  685. vchar::append(built_argv, "--malloc-fill=A5");
  686. vchar::append(built_argv, "--free-fill=DE");
  687. vchar::append(built_argv, "--xml=yes");
  688. if (getenv("VALGRIND_HOME"))
  689. {
  690. libtest::vchar_t buffer;
  691. buffer.resize(1024);
  692. int length= snprintf(&buffer[0], buffer.size(), "--xml-file=%s/cmd-%%p.xml", getenv("VALGRIND_HOME"));
  693. fatal_assert(length > 0 and size_t(length) < buffer.size());
  694. vchar::append(built_argv, &buffer[0]);
  695. }
  696. else
  697. {
  698. vchar::append(built_argv, "--xml-file=var/tmp/valgrind-cmd-%p.xml");
  699. }
  700. std::string log_file= create_tmpfile("valgrind");
  701. libtest::vchar_t buffer;
  702. buffer.resize(1024);
  703. int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
  704. fatal_assert(length > 0 and size_t(length) < buffer.size());
  705. vchar::append(built_argv, &buffer[0]);
  706. }
  707. else if (_use_ptrcheck)
  708. {
  709. /*
  710. valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
  711. */
  712. vchar::append(built_argv, "valgrind");
  713. vchar::append(built_argv, "--error-exitcode=1");
  714. vchar::append(built_argv, "--tool=exp-ptrcheck");
  715. std::string log_file= create_tmpfile("ptrcheck");
  716. libtest::vchar_t buffer;
  717. buffer.resize(1024);
  718. int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
  719. fatal_assert(length > 0 and size_t(length) < buffer.size());
  720. vchar::append(built_argv, &buffer[0]);
  721. }
  722. else if (_use_gdb)
  723. {
  724. vchar::append(built_argv, "gdb");
  725. }
  726. vchar::append(built_argv, _exectuble_with_path.c_str());
  727. for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
  728. {
  729. vchar::append(built_argv, (*iter).first.c_str());
  730. if ((*iter).second.empty() == false)
  731. {
  732. vchar::append(built_argv, (*iter).second.c_str());
  733. }
  734. }
  735. if (args)
  736. {
  737. for (const char **ptr= args; *ptr; ++ptr)
  738. {
  739. vchar::append(built_argv, *ptr);
  740. }
  741. }
  742. built_argv.push_back(NULL);
  743. }
  744. std::string Application::print()
  745. {
  746. return print_argv(built_argv);
  747. }
  748. std::string Application::arguments()
  749. {
  750. std::stringstream arg_buffer;
  751. // Skip printing out the libtool reference
  752. for (size_t x= _use_libtool ? 2 : 0; x < _argc; ++x)
  753. {
  754. if (built_argv[x])
  755. {
  756. arg_buffer << built_argv[x] << " ";
  757. }
  758. }
  759. return arg_buffer.str();
  760. }
  761. void Application::delete_argv()
  762. {
  763. std::for_each(built_argv.begin(), built_argv.end(), FreeFromVector());
  764. built_argv.clear();
  765. _argc= 0;
  766. }
  767. int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
  768. {
  769. Application app(command, use_libtool);
  770. Application::error_t ret= app.run(args);
  771. if (ret != Application::SUCCESS)
  772. {
  773. return int(ret);
  774. }
  775. return int(app.join());
  776. }
  777. } // namespace exec_cmdline