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 know 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], NULL
);
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)
283 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
286 return Application::INVALID_POSIX_SPAWN
;
292 return Application::INVALID_POSIX_SPAWN
;
296 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
298 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
300 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
301 return Application::FAILURE
;
305 return Application::SUCCESS
;
308 bool Application::check() const
310 if (_pid
> 1 and kill(_pid
, 0) == 0)
318 void Application::murder()
323 while ((count
--) > 0 and check())
325 if (kill(_pid
, SIGTERM
) == 0)
331 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
338 // If for whatever reason it lives, kill it hard
341 Error
<< "using SIGKILL, things will likely go poorly from this point";
342 (void)kill(_pid
, SIGKILL
);
348 // false means that no data was returned
349 bool Application::slurp()
351 struct pollfd fds
[2];
352 fds
[0].fd
= stdout_fd
.fd();
353 fds
[0].events
= POLLRDNORM
;
355 fds
[1].fd
= stderr_fd
.fd();
356 fds
[1].events
= POLLRDNORM
;
360 if ((active_fd
= poll(fds
, 2, 0)) == -1)
363 switch ((error
= errno
))
373 FATAL(strerror(error
));
377 FATAL("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
381 FATAL(strerror(error
));
393 bool data_was_read
= false;
394 if (fds
[0].revents
& POLLRDNORM
)
396 if (stdout_fd
.read(_stdout_buffer
) == true)
402 if (fds
[1].revents
& POLLRDNORM
)
404 if (stderr_fd
.read(_stderr_buffer
) == true)
410 return data_was_read
;
413 Application::error_t
Application::join()
415 pid_t waited_pid
= waitpid(_pid
, &_status
, WUNTRACED
);
417 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
420 What we are looking for here is how the exit status happened.
421 - 127 means that posix_spawn() itself had an error.
422 - 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.
423 - Finally something has happened that we don't currently understand.
425 if (WEXITSTATUS(_status
) == 127)
427 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
428 std::string
error_string("posix_spawn() failed pid:");
430 error_string
+= " name:";
431 error_string
+= print_argv(built_argv
);
432 if (stderr_result_length())
434 error_string
+= " stderr: ";
435 error_string
+= stderr_c_str();
437 throw std::logic_error(error_string
);
439 else if (WIFSIGNALED(_status
))
441 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
444 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
445 std::string
error_string(print_argv(built_argv
));
446 error_string
+= " was killed by signal ";
447 error_string
+= strsignal(WTERMSIG(_status
));
449 if (stdout_result_length())
451 error_string
+= " stdout: ";
452 error_string
+= stdout_c_str();
455 if (stderr_result_length())
457 error_string
+= " stderr: ";
458 error_string
+= stderr_c_str();
461 throw std::runtime_error(error_string
);
464 // If we terminted it on purpose then it counts as a success.
468 Out
<< "waitpid() application terminated at request"
470 << " name:" << built_argv
[0];
476 _app_exit_state
= Application::UNKNOWN
;
477 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
479 << " name:" << built_argv
[0];
482 else if (waited_pid
== _pid
and WIFEXITED(_status
))
484 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
486 else if (waited_pid
== -1)
488 std::string error_string
;
489 if (stdout_result_length())
491 error_string
+= " stdout: ";
492 error_string
+= stdout_c_str();
495 if (stderr_result_length())
497 error_string
+= " stderr: ";
498 error_string
+= stderr_c_str();
500 Error
<< "waitpid() returned errno:" << strerror(errno
) << " " << error_string
;
501 _app_exit_state
= Application::UNKNOWN
;
505 _app_exit_state
= Application::UNKNOWN
;
506 throw std::logic_error("waitpid() returned an unknown value");
509 return _app_exit_state
;
512 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
514 std::string
arg(name
);
516 _options
.push_back(std::make_pair(arg
, std::string()));
519 void Application::add_option(const std::string
& arg
)
521 _options
.push_back(std::make_pair(arg
, std::string()));
524 void Application::add_option(const std::string
& name
, const std::string
& value
)
526 _options
.push_back(std::make_pair(name
, value
));
529 Application::Pipe::Pipe(int arg
) :
538 int Application::Pipe::Pipe::fd()
540 if (_std_fd
== STDOUT_FILENO
)
542 return _pipe_fd
[READ
];
544 else if (_std_fd
== STDERR_FILENO
)
546 return _pipe_fd
[READ
];
549 return _pipe_fd
[WRITE
]; // STDIN_FILENO
553 bool Application::Pipe::read(libtest::vchar_t
& arg
)
555 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
557 bool data_was_read
= false;
559 libtest::vchar_t buffer
;
562 while ((read_length
= ::read(_pipe_fd
[READ
], &buffer
[0], buffer
.size())))
564 if (read_length
== -1)
572 Error
<< strerror(errno
);
580 arg
.reserve(read_length
+1);
581 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
583 arg
.push_back(buffer
[x
]);
585 // @todo Suck up all errput code here
588 return data_was_read
;
591 void Application::Pipe::nonblock()
596 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
597 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
601 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
602 throw strerror(errno
);
608 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
609 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
613 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
614 throw strerror(errno
);
618 void Application::Pipe::reset()
624 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
627 if (pipe(_pipe_fd
) == -1)
629 FATAL(strerror(errno
));
632 // Since either pipe2() was not found/called we set the pipe directly
640 void Application::Pipe::cloexec()
642 //if (SOCK_CLOEXEC == 0)
649 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
650 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
654 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
655 throw strerror(errno
);
661 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
662 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
666 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
667 throw strerror(errno
);
673 Application::Pipe::~Pipe()
675 if (_pipe_fd
[0] != -1)
677 ::close(_pipe_fd
[0]);
680 if (_pipe_fd
[1] != -1)
682 ::close(_pipe_fd
[1]);
686 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
688 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
691 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
693 FATAL("posix_spawn_file_actions_adddup2(%s)", strerror(ret
));
696 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
698 FATAL("posix_spawn_file_actions_addclose(%s)", strerror(ret
));
702 void Application::Pipe::close(const close_t
& arg
)
708 if (::close(_pipe_fd
[type
]) == -1)
710 Error
<< "close(" << strerror(errno
) << ")";
717 void Application::create_argv(const char *args
[])
723 vchar::append(built_argv
, libtool());
724 vchar::append(built_argv
, "--mode=execute");
730 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
732 vchar::append(built_argv
, "valgrind");
733 vchar::append(built_argv
, "--error-exitcode=1");
734 vchar::append(built_argv
, "--leak-check=yes");
736 vchar::append(built_argv
, "--show-reachable=yes"));
738 vchar::append(built_argv
, "--track-fds=yes");
740 built_argv
[x
++]= strdup("--track-origin=yes");
742 vchar::append(built_argv
, "--malloc-fill=A5");
743 vchar::append(built_argv
, "--free-fill=DE");
745 std::string log_file
= create_tmpfile("valgrind");
746 libtest::vchar_t buffer
;
748 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
749 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
750 vchar::append(built_argv
, &buffer
[0]);
752 else if (_use_ptrcheck
)
755 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
757 vchar::append(built_argv
, "valgrind");
758 vchar::append(built_argv
, "--error-exitcode=1");
759 vchar::append(built_argv
, "--tool=exp-ptrcheck");
760 std::string log_file
= create_tmpfile("ptrcheck");
761 libtest::vchar_t buffer
;
763 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
764 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
765 vchar::append(built_argv
, &buffer
[0]);
769 vchar::append(built_argv
, "gdb");
772 vchar::append(built_argv
, _exectuble_with_path
.c_str());
774 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
776 vchar::append(built_argv
, (*iter
).first
.c_str());
777 if ((*iter
).second
.empty() == false)
779 vchar::append(built_argv
, (*iter
).second
.c_str());
785 for (const char **ptr
= args
; *ptr
; ++ptr
)
787 vchar::append(built_argv
, *ptr
);
790 built_argv
.push_back(nullptr);
793 std::string
Application::print()
795 return print_argv(built_argv
);
798 std::string
Application::arguments()
800 std::stringstream arg_buffer
;
802 // Skip printing out the libtool reference
803 for (size_t x
= _use_libtool
? 2 : 0; x
< _argc
; ++x
)
807 arg_buffer
<< built_argv
[x
] << " ";
811 return arg_buffer
.str();
814 void Application::delete_argv()
816 std::for_each(built_argv
.begin(), built_argv
.end(), FreeFromVector());
823 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
825 Application
app(command
, use_libtool
);
827 Application::error_t ret
= app
.run(args
);
829 if (ret
!= Application::SUCCESS
)
834 return int(app
.join());
837 } // namespace exec_cmdline