1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 * Data Differential YATL (i.e. libtest) library
5 * Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
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
19 * * The names of its contributors may not be used to endorse or
20 * promote products derived from this software without specific prior
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.
37 #include "libtest/yatlcon.h"
39 #include "libtest/common.h"
41 using namespace libtest
;
58 #include <sys/types.h>
65 static char **environ
= NULL
;
74 std::string
print_argv(libtest::vchar_ptr_t
& built_argv
)
76 std::stringstream arg_buffer
;
78 for (vchar_ptr_t::iterator iter
= built_argv
.begin();
79 iter
!= built_argv
.end();
84 arg_buffer
<< *iter
<< " ";
88 return arg_buffer
.str();
92 std::string
print_argv(char** argv
)
94 std::stringstream arg_buffer
;
96 for (char** ptr
= argv
; *ptr
; ++ptr
)
98 arg_buffer
<< *ptr
<< " ";
101 return arg_buffer
.str();
105 static Application::error_t
int_to_error_t(int arg
)
110 return Application::INVALID_POSIX_SPAWN
;
113 return Application::SUCCESS
;
116 return Application::FAILURE
;
119 return Application::UNKNOWN
;
126 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
127 _use_libtool(_use_libtool_arg
),
128 _use_valgrind(false),
130 _use_ptrcheck(false),
134 stdin_fd(STDIN_FILENO
),
135 stdout_fd(STDOUT_FILENO
),
136 stderr_fd(STDERR_FILENO
),
139 _app_exit_state(UNINITIALIZED
)
143 if (libtool() == NULL
)
145 FATAL("libtool requested, but no libtool was found");
149 // Find just the name of the application with no path
151 size_t found
= arg
.find_last_of("/\\");
154 _exectuble_name
= arg
.substr(found
+1);
158 _exectuble_name
= arg
;
162 if (_use_libtool
and getenv("PWD"))
164 _exectuble_with_path
+= getenv("PWD");
165 _exectuble_with_path
+= "/";
167 _exectuble_with_path
+= _exectuble
;
170 Application::~Application()
176 Application::error_t
Application::run(const char *args
[])
181 _stdout_buffer
.clear();
182 _stderr_buffer
.clear();
184 posix_spawn_file_actions_t file_actions
;
185 posix_spawn_file_actions_init(&file_actions
);
187 stdin_fd
.dup_for_spawn(file_actions
);
188 stdout_fd
.dup_for_spawn(file_actions
);
189 stderr_fd
.dup_for_spawn(file_actions
);
191 posix_spawnattr_t spawnattr
;
192 posix_spawnattr_init(&spawnattr
);
196 // Child should not block signals
197 flags
|= POSIX_SPAWN_SETSIGMASK
;
202 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
204 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
205 // Use USEVFORK on linux
206 flags
|= POSIX_SPAWN_USEVFORK
;
209 flags
|= POSIX_SPAWN_SETPGROUP
;
210 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
212 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
219 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
220 std::fstream file_stream
;
221 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
223 _gdb_filename
= create_tmpfile(_exectuble_name
);
225 << "set logging redirect on" << std::endl
226 << "set logging file " << _gdb_filename
<< std::endl
227 << "set logging overwrite on" << std::endl
228 << "set logging on" << std::endl
229 << "set environment LIBTEST_IN_GDB=1" << std::endl
230 << "run " << arguments() << std::endl
231 << "thread apply all bt" << std::endl
232 << "quit" << std::endl
;
234 fatal_assert(file_stream
.good());
239 // libtool --mode=execute gdb -f -x binary
241 const_cast<char *>(libtool()),
242 const_cast<char *>("--mode=execute"),
243 const_cast<char *>("gdb"),
244 const_cast<char *>("-batch"),
245 const_cast<char *>("-f"),
246 const_cast<char *>("-x"),
247 const_cast<char *>(gdb_run_file
.c_str()),
248 const_cast<char *>(_exectuble_with_path
.c_str()),
251 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
257 const_cast<char *>("gdb"),
258 const_cast<char *>("-batch"),
259 const_cast<char *>("-f"),
260 const_cast<char *>("-x"),
261 const_cast<char *>(gdb_run_file
.c_str()),
262 const_cast<char *>(_exectuble_with_path
.c_str()),
264 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
269 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], environ
);
272 posix_spawn_file_actions_destroy(&file_actions
);
273 posix_spawnattr_destroy(&spawnattr
);
275 stdin_fd
.close(Application::Pipe::READ
);
276 stdout_fd
.close(Application::Pipe::WRITE
);
277 stderr_fd
.close(Application::Pipe::WRITE
);
281 if (_will_fail
== false)
286 std::for_each(built_argv
.begin(), built_argv
.end()-1, [&sb
](const char *a
) {
292 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< "): " << sb
<< " cwd:" << getcwd(buf
, sizeof(buf
)-1);
295 return Application::INVALID_POSIX_SPAWN
;
301 return Application::INVALID_POSIX_SPAWN
;
305 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
307 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
309 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
310 return Application::FAILURE
;
314 return Application::SUCCESS
;
317 bool Application::check() const
319 if (_pid
> 1 and kill(_pid
, 0) == 0)
327 void Application::murder()
332 while ((count
--) > 0 and check())
334 if (kill(_pid
, SIGTERM
) == 0)
340 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
347 // If for whatever reason it lives, kill it hard
350 Error
<< "using SIGKILL, things will likely go poorly from this point";
351 (void)kill(_pid
, SIGKILL
);
357 // false means that no data was returned
358 bool Application::slurp()
360 struct pollfd fds
[2];
361 fds
[0].fd
= stdout_fd
.fd();
362 fds
[0].events
= POLLRDNORM
;
364 fds
[1].fd
= stderr_fd
.fd();
365 fds
[1].events
= POLLRDNORM
;
369 if ((active_fd
= poll(fds
, 2, 0)) == -1)
372 switch ((error
= errno
))
382 FATAL(strerror(error
));
386 FATAL("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
390 FATAL(strerror(error
));
402 bool data_was_read
= false;
403 if (fds
[0].revents
& POLLRDNORM
)
405 if (stdout_fd
.read(_stdout_buffer
) == true)
411 if (fds
[1].revents
& POLLRDNORM
)
413 if (stderr_fd
.read(_stderr_buffer
) == true)
419 return data_was_read
;
422 std::pair
<std::string
, std::string
> Application::output()
427 stdout_result().data(),
428 stdout_result().size()
431 stderr_result().data(),
432 stderr_result().size()
438 Application::error_t
Application::join()
440 pid_t waited_pid
= waitpid(_pid
, &_status
, WUNTRACED
);
442 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
445 What we are looking for here is how the exit status happened.
446 - 127 means that posix_spawn() itself had an error.
447 - 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.
448 - Finally something has happened that we don't currently understand.
450 if (WEXITSTATUS(_status
) == 127)
452 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
453 std::string
error_string("posix_spawn() failed pid:");
455 error_string
+= " name:";
456 error_string
+= print_argv(built_argv
);
457 if (stderr_result_length())
459 error_string
+= " stderr: ";
460 error_string
+= stderr_c_str();
462 throw std::logic_error(error_string
);
464 else if (WIFSIGNALED(_status
))
466 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
469 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
470 std::string
error_string(print_argv(built_argv
));
471 error_string
+= " was killed by signal ";
472 error_string
+= strsignal(WTERMSIG(_status
));
474 if (stdout_result_length())
476 error_string
+= " stdout: ";
477 error_string
+= stdout_c_str();
480 if (stderr_result_length())
482 error_string
+= " stderr: ";
483 error_string
+= stderr_c_str();
486 throw std::runtime_error(error_string
);
489 // If we terminted it on purpose then it counts as a success.
493 Out
<< "waitpid() application terminated at request"
495 << " name:" << built_argv
[0];
501 _app_exit_state
= Application::UNKNOWN
;
502 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
504 << " name:" << built_argv
[0];
507 else if (waited_pid
== _pid
and WIFEXITED(_status
))
509 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
511 else if (waited_pid
== -1)
513 std::string error_string
;
514 if (stdout_result_length())
516 error_string
+= " stdout: ";
517 error_string
+= stdout_c_str();
520 if (stderr_result_length())
522 error_string
+= " stderr: ";
523 error_string
+= stderr_c_str();
525 Error
<< "waitpid() returned errno:" << strerror(errno
) << " " << error_string
;
526 _app_exit_state
= Application::UNKNOWN
;
530 _app_exit_state
= Application::UNKNOWN
;
531 throw std::logic_error("waitpid() returned an unknown value");
534 return _app_exit_state
;
537 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
539 std::string
arg(name
);
541 _options
.push_back(std::make_pair(arg
, std::string()));
544 void Application::add_option(const std::string
& arg
)
546 _options
.push_back(std::make_pair(arg
, std::string()));
549 void Application::add_option(const std::string
& name
, const std::string
& value
)
551 _options
.push_back(std::make_pair(name
, value
));
554 Application::Pipe::Pipe(int arg
) :
563 int Application::Pipe::Pipe::fd()
565 if (_std_fd
== STDOUT_FILENO
)
567 return _pipe_fd
[READ
];
569 else if (_std_fd
== STDERR_FILENO
)
571 return _pipe_fd
[READ
];
574 return _pipe_fd
[WRITE
]; // STDIN_FILENO
578 bool Application::Pipe::read(libtest::vchar_t
& arg
)
580 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
582 bool data_was_read
= false;
584 libtest::vchar_t buffer
;
587 while ((read_length
= ::read(_pipe_fd
[READ
], &buffer
[0], buffer
.size())))
589 if (read_length
== -1)
597 Error
<< strerror(errno
);
605 arg
.reserve(read_length
+1);
606 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
608 arg
.push_back(buffer
[x
]);
610 // @todo Suck up all errput code here
613 return data_was_read
;
616 void Application::Pipe::nonblock()
621 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
622 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
626 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
627 throw strerror(errno
);
633 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
634 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
638 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
639 throw strerror(errno
);
643 void Application::Pipe::reset()
649 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
652 if (pipe(_pipe_fd
) == -1)
654 FATAL(strerror(errno
));
657 // Since either pipe2() was not found/called we set the pipe directly
665 void Application::Pipe::cloexec()
667 //if (SOCK_CLOEXEC == 0)
674 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
675 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
679 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
680 throw strerror(errno
);
686 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
687 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
691 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
692 throw strerror(errno
);
698 Application::Pipe::~Pipe()
700 if (_pipe_fd
[0] != -1)
702 ::close(_pipe_fd
[0]);
705 if (_pipe_fd
[1] != -1)
707 ::close(_pipe_fd
[1]);
711 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
713 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
716 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
718 FATAL("posix_spawn_file_actions_adddup2(%s)", strerror(ret
));
721 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
723 FATAL("posix_spawn_file_actions_addclose(%s)", strerror(ret
));
727 void Application::Pipe::close(const close_t
& arg
)
733 if (::close(_pipe_fd
[type
]) == -1)
735 Error
<< "close(" << strerror(errno
) << ")";
742 void Application::create_argv(const char *args
[])
748 vchar::append(built_argv
, libtool());
749 vchar::append(built_argv
, "--mode=execute");
755 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
757 vchar::append(built_argv
, "valgrind");
758 vchar::append(built_argv
, "--error-exitcode=1");
759 vchar::append(built_argv
, "--leak-check=yes");
761 vchar::append(built_argv
, "--show-reachable=yes"));
763 vchar::append(built_argv
, "--track-fds=yes");
765 built_argv
[x
++]= strdup("--track-origin=yes");
767 vchar::append(built_argv
, "--malloc-fill=A5");
768 vchar::append(built_argv
, "--free-fill=DE");
770 std::string log_file
= create_tmpfile("valgrind");
771 libtest::vchar_t buffer
;
773 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
774 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
775 vchar::append(built_argv
, &buffer
[0]);
777 else if (_use_ptrcheck
)
780 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
782 vchar::append(built_argv
, "valgrind");
783 vchar::append(built_argv
, "--error-exitcode=1");
784 vchar::append(built_argv
, "--tool=exp-ptrcheck");
785 std::string log_file
= create_tmpfile("ptrcheck");
786 libtest::vchar_t buffer
;
788 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
789 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
790 vchar::append(built_argv
, &buffer
[0]);
794 vchar::append(built_argv
, "gdb");
797 vchar::append(built_argv
, _exectuble_with_path
.c_str());
799 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
801 vchar::append(built_argv
, (*iter
).first
.c_str());
802 if ((*iter
).second
.empty() == false)
804 vchar::append(built_argv
, (*iter
).second
.c_str());
810 for (const char **ptr
= args
; *ptr
; ++ptr
)
812 vchar::append(built_argv
, *ptr
);
815 built_argv
.push_back(nullptr);
818 std::string
Application::print()
820 return print_argv(built_argv
);
823 std::string
Application::arguments()
825 std::stringstream arg_buffer
;
827 // Skip printing out the libtool reference
828 for (size_t x
= _use_libtool
? 2 : 0; x
< _argc
; ++x
)
832 arg_buffer
<< built_argv
[x
] << " ";
836 return arg_buffer
.str();
839 void Application::delete_argv()
841 std::for_each(built_argv
.begin(), built_argv
.end(), FreeFromVector());
848 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
850 Application
app(command
, use_libtool
);
852 Application::error_t ret
= app
.run(args
);
854 if (Application::SUCCESS
== ret
) {
858 if (ret
!= Application::SUCCESS
)
860 auto out
= app
.output();
861 Error
<< command
<< " stdout: " << out
.first
;
862 Error
<< command
<< " stderr: " << out
.second
;
868 } // namespace exec_cmdline