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();
82 arg_buffer
<< *iter
<< " ";
85 return arg_buffer
.str();
89 std::string
print_argv(char** argv
)
91 std::stringstream arg_buffer
;
93 for (char** ptr
= argv
; *ptr
; ++ptr
)
95 arg_buffer
<< *ptr
<< " ";
98 return arg_buffer
.str();
102 static Application::error_t
int_to_error_t(int arg
)
107 return Application::INVALID_POSIX_SPAWN
;
110 return Application::SUCCESS
;
113 return Application::FAILURE
;
116 return Application::UNKNOWN
;
123 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
124 _use_libtool(_use_libtool_arg
),
125 _use_valgrind(false),
127 _use_ptrcheck(false),
131 stdin_fd(STDIN_FILENO
),
132 stdout_fd(STDOUT_FILENO
),
133 stderr_fd(STDERR_FILENO
),
136 _app_exit_state(UNINITIALIZED
)
140 if (libtool() == NULL
)
142 FATAL("libtool requested, but know libtool was found");
146 // Find just the name of the application with no path
148 size_t found
= arg
.find_last_of("/\\");
151 _exectuble_name
= arg
.substr(found
+1);
155 _exectuble_name
= arg
;
159 if (_use_libtool
and getenv("PWD"))
161 _exectuble_with_path
+= getenv("PWD");
162 _exectuble_with_path
+= "/";
164 _exectuble_with_path
+= _exectuble
;
167 Application::~Application()
173 Application::error_t
Application::run(const char *args
[])
178 _stdout_buffer
.clear();
179 _stderr_buffer
.clear();
181 posix_spawn_file_actions_t file_actions
;
182 posix_spawn_file_actions_init(&file_actions
);
184 stdin_fd
.dup_for_spawn(file_actions
);
185 stdout_fd
.dup_for_spawn(file_actions
);
186 stderr_fd
.dup_for_spawn(file_actions
);
188 posix_spawnattr_t spawnattr
;
189 posix_spawnattr_init(&spawnattr
);
193 // Child should not block signals
194 flags
|= POSIX_SPAWN_SETSIGMASK
;
199 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
201 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
202 // Use USEVFORK on linux
203 flags
|= POSIX_SPAWN_USEVFORK
;
206 flags
|= POSIX_SPAWN_SETPGROUP
;
207 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
209 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
216 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
217 std::fstream file_stream
;
218 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
220 _gdb_filename
= create_tmpfile(_exectuble_name
);
222 << "set logging redirect on" << std::endl
223 << "set logging file " << _gdb_filename
<< std::endl
224 << "set logging overwrite on" << std::endl
225 << "set logging on" << std::endl
226 << "set environment LIBTEST_IN_GDB=1" << std::endl
227 << "run " << arguments() << std::endl
228 << "thread apply all bt" << std::endl
229 << "quit" << std::endl
;
231 fatal_assert(file_stream
.good());
236 // libtool --mode=execute gdb -f -x binary
238 const_cast<char *>(libtool()),
239 const_cast<char *>("--mode=execute"),
240 const_cast<char *>("gdb"),
241 const_cast<char *>("-batch"),
242 const_cast<char *>("-f"),
243 const_cast<char *>("-x"),
244 const_cast<char *>(gdb_run_file
.c_str()),
245 const_cast<char *>(_exectuble_with_path
.c_str()),
248 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
254 const_cast<char *>("gdb"),
255 const_cast<char *>("-batch"),
256 const_cast<char *>("-f"),
257 const_cast<char *>("-x"),
258 const_cast<char *>(gdb_run_file
.c_str()),
259 const_cast<char *>(_exectuble_with_path
.c_str()),
261 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
266 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], NULL
);
269 posix_spawn_file_actions_destroy(&file_actions
);
270 posix_spawnattr_destroy(&spawnattr
);
272 stdin_fd
.close(Application::Pipe::READ
);
273 stdout_fd
.close(Application::Pipe::WRITE
);
274 stderr_fd
.close(Application::Pipe::WRITE
);
278 if (_will_fail
== false)
280 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
283 return Application::INVALID_POSIX_SPAWN
;
289 return Application::INVALID_POSIX_SPAWN
;
293 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
295 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
297 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
298 return Application::FAILURE
;
302 return Application::SUCCESS
;
305 bool Application::check() const
307 if (_pid
> 1 and kill(_pid
, 0) == 0)
315 void Application::murder()
320 while ((count
--) > 0 and check())
322 if (kill(_pid
, SIGTERM
) == 0)
328 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
335 // If for whatever reason it lives, kill it hard
338 Error
<< "using SIGKILL, things will likely go poorly from this point";
339 (void)kill(_pid
, SIGKILL
);
345 // false means that no data was returned
346 bool Application::slurp()
348 struct pollfd fds
[2];
349 fds
[0].fd
= stdout_fd
.fd();
350 fds
[0].events
= POLLRDNORM
;
352 fds
[1].fd
= stderr_fd
.fd();
353 fds
[1].events
= POLLRDNORM
;
357 if ((active_fd
= poll(fds
, 2, 0)) == -1)
360 switch ((error
= errno
))
362 #ifdef TARGET_OS_LINUX
370 FATAL(strerror(error
));
374 FATAL("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
378 FATAL(strerror(error
));
390 bool data_was_read
= false;
391 if (fds
[0].revents
& POLLRDNORM
)
393 if (stdout_fd
.read(_stdout_buffer
) == true)
399 if (fds
[1].revents
& POLLRDNORM
)
401 if (stderr_fd
.read(_stderr_buffer
) == true)
407 return data_was_read
;
410 Application::error_t
Application::join()
412 pid_t waited_pid
= waitpid(_pid
, &_status
, 0);
414 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
417 What we are looking for here is how the exit status happened.
418 - 127 means that posix_spawn() itself had an error.
419 - 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.
420 - Finally something has happened that we don't currently understand.
422 if (WEXITSTATUS(_status
) == 127)
424 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
425 std::string
error_string("posix_spawn() failed pid:");
427 error_string
+= " name:";
428 error_string
+= print_argv(built_argv
);
429 if (stderr_result_length())
431 error_string
+= " stderr: ";
432 error_string
+= stderr_c_str();
434 throw std::logic_error(error_string
);
436 else if (WIFSIGNALED(_status
))
438 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
441 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
442 std::string
error_string(print_argv(built_argv
));
443 error_string
+= " was killed by signal ";
444 error_string
+= strsignal(WTERMSIG(_status
));
446 if (stdout_result_length())
448 error_string
+= " stdout: ";
449 error_string
+= stdout_c_str();
452 if (stderr_result_length())
454 error_string
+= " stderr: ";
455 error_string
+= stderr_c_str();
458 throw std::runtime_error(error_string
);
461 // If we terminted it on purpose then it counts as a success.
465 Out
<< "waitpid() application terminated at request"
467 << " name:" << built_argv
[0];
473 _app_exit_state
= Application::UNKNOWN
;
474 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
476 << " name:" << built_argv
[0];
479 else if (waited_pid
== _pid
and WIFEXITED(_status
))
481 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
483 else if (waited_pid
== -1)
485 std::string error_string
;
486 if (stdout_result_length())
488 error_string
+= " stdout: ";
489 error_string
+= stdout_c_str();
492 if (stderr_result_length())
494 error_string
+= " stderr: ";
495 error_string
+= stderr_c_str();
497 Error
<< "waitpid() returned errno:" << strerror(errno
) << " " << error_string
;
498 _app_exit_state
= Application::UNKNOWN
;
502 _app_exit_state
= Application::UNKNOWN
;
503 throw std::logic_error("waitpid() returned an unknown value");
506 return _app_exit_state
;
509 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
511 std::string
arg(name
);
513 _options
.push_back(std::make_pair(arg
, std::string()));
516 void Application::add_option(const std::string
& arg
)
518 _options
.push_back(std::make_pair(arg
, std::string()));
521 void Application::add_option(const std::string
& name
, const std::string
& value
)
523 _options
.push_back(std::make_pair(name
, value
));
526 Application::Pipe::Pipe(int arg
) :
535 int Application::Pipe::Pipe::fd()
537 if (_std_fd
== STDOUT_FILENO
)
539 return _pipe_fd
[READ
];
541 else if (_std_fd
== STDERR_FILENO
)
543 return _pipe_fd
[READ
];
546 return _pipe_fd
[WRITE
]; // STDIN_FILENO
550 bool Application::Pipe::read(libtest::vchar_t
& arg
)
552 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
554 bool data_was_read
= false;
556 libtest::vchar_t buffer
;
559 while ((read_length
= ::read(_pipe_fd
[READ
], &buffer
[0], buffer
.size())))
561 if (read_length
== -1)
569 Error
<< strerror(errno
);
577 arg
.reserve(read_length
+1);
578 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
580 arg
.push_back(buffer
[x
]);
582 // @todo Suck up all errput code here
585 return data_was_read
;
588 void Application::Pipe::nonblock()
593 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
594 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
598 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
599 throw strerror(errno
);
605 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
606 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
610 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
611 throw strerror(errno
);
615 void Application::Pipe::reset()
621 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
624 if (pipe(_pipe_fd
) == -1)
626 FATAL(strerror(errno
));
629 // Since either pipe2() was not found/called we set the pipe directly
637 void Application::Pipe::cloexec()
639 //if (SOCK_CLOEXEC == 0)
646 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
647 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
651 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
652 throw strerror(errno
);
658 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
659 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
663 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
664 throw strerror(errno
);
670 Application::Pipe::~Pipe()
672 if (_pipe_fd
[0] != -1)
674 ::close(_pipe_fd
[0]);
677 if (_pipe_fd
[1] != -1)
679 ::close(_pipe_fd
[1]);
683 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
685 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
688 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
690 FATAL("posix_spawn_file_actions_adddup2(%s)", strerror(ret
));
693 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
695 FATAL("posix_spawn_file_actions_addclose(%s)", strerror(ret
));
699 void Application::Pipe::close(const close_t
& arg
)
705 if (::close(_pipe_fd
[type
]) == -1)
707 Error
<< "close(" << strerror(errno
) << ")";
714 void Application::create_argv(const char *args
[])
720 vchar::append(built_argv
, libtool());
721 vchar::append(built_argv
, "--mode=execute");
727 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
729 vchar::append(built_argv
, "valgrind");
730 vchar::append(built_argv
, "--error-exitcode=1");
731 vchar::append(built_argv
, "--leak-check=yes");
733 vchar::append(built_argv
, "--show-reachable=yes"));
735 vchar::append(built_argv
, "--track-fds=yes");
737 built_argv
[x
++]= strdup("--track-origin=yes");
739 vchar::append(built_argv
, "--malloc-fill=A5");
740 vchar::append(built_argv
, "--free-fill=DE");
742 std::string log_file
= create_tmpfile("valgrind");
743 libtest::vchar_t buffer
;
745 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
746 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
747 vchar::append(built_argv
, &buffer
[0]);
749 else if (_use_ptrcheck
)
752 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
754 vchar::append(built_argv
, "valgrind");
755 vchar::append(built_argv
, "--error-exitcode=1");
756 vchar::append(built_argv
, "--tool=exp-ptrcheck");
757 std::string log_file
= create_tmpfile("ptrcheck");
758 libtest::vchar_t buffer
;
760 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
761 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
762 vchar::append(built_argv
, &buffer
[0]);
766 vchar::append(built_argv
, "gdb");
769 vchar::append(built_argv
, _exectuble_with_path
.c_str());
771 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
773 vchar::append(built_argv
, (*iter
).first
.c_str());
774 if ((*iter
).second
.empty() == false)
776 vchar::append(built_argv
, (*iter
).second
.c_str());
782 for (const char **ptr
= args
; *ptr
; ++ptr
)
784 vchar::append(built_argv
, *ptr
);
787 built_argv
.push_back(NULL
);
790 std::string
Application::print()
792 return print_argv(built_argv
);
795 std::string
Application::arguments()
797 std::stringstream arg_buffer
;
799 // Skip printing out the libtool reference
800 for (size_t x
= _use_libtool
? 2 : 0; x
< _argc
; ++x
)
804 arg_buffer
<< built_argv
[x
] << " ";
808 return arg_buffer
.str();
811 void Application::delete_argv()
813 std::for_each(built_argv
.begin(), built_argv
.end(), FreeFromVector());
820 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
822 Application
app(command
, use_libtool
);
824 Application::error_t ret
= app
.run(args
);
826 if (ret
!= Application::SUCCESS
)
831 return int(app
.join());
834 } // namespace exec_cmdline