1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 * Data Differential YATL (i.e. libtest) library
5 * Copyright (C) 2012 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.
38 #include <libtest/common.h>
40 using namespace libtest
;
53 #include <sys/types.h>
59 static char **environ
= NULL
;
68 std::string
print_argv(libtest::vchar_ptr_t
& built_argv
)
70 std::stringstream arg_buffer
;
72 for (vchar_ptr_t::iterator iter
= built_argv
.begin();
73 iter
== built_argv
.end();
76 arg_buffer
<< *iter
<< " ";
79 return arg_buffer
.str();
83 std::string
print_argv(char** argv
)
85 std::stringstream arg_buffer
;
87 for (char** ptr
= argv
; *ptr
; ++ptr
)
89 arg_buffer
<< *ptr
<< " ";
92 return arg_buffer
.str();
96 static Application::error_t
int_to_error_t(int arg
)
101 return Application::INVALID_POSIX_SPAWN
;
104 return Application::SUCCESS
;
107 return Application::FAILURE
;
110 return Application::UNKNOWN
;
117 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
118 _use_libtool(_use_libtool_arg
),
119 _use_valgrind(false),
121 _use_ptrcheck(false),
125 stdin_fd(STDIN_FILENO
),
126 stdout_fd(STDOUT_FILENO
),
127 stderr_fd(STDERR_FILENO
),
130 _app_exit_state(UNINITIALIZED
)
134 if (libtool() == NULL
)
136 fatal_message("libtool requested, but know libtool was found");
140 // Find just the name of the application with no path
142 size_t found
= arg
.find_last_of("/\\");
145 _exectuble_name
= arg
.substr(found
+1);
149 _exectuble_name
= arg
;
153 if (_use_libtool
and getenv("PWD"))
155 _exectuble_with_path
+= getenv("PWD");
156 _exectuble_with_path
+= "/";
158 _exectuble_with_path
+= _exectuble
;
161 Application::~Application()
167 Application::error_t
Application::run(const char *args
[])
172 _stdout_buffer
.clear();
173 _stderr_buffer
.clear();
175 posix_spawn_file_actions_t file_actions
;
176 posix_spawn_file_actions_init(&file_actions
);
178 stdin_fd
.dup_for_spawn(file_actions
);
179 stdout_fd
.dup_for_spawn(file_actions
);
180 stderr_fd
.dup_for_spawn(file_actions
);
182 posix_spawnattr_t spawnattr
;
183 posix_spawnattr_init(&spawnattr
);
187 // Child should not block signals
188 flags
|= POSIX_SPAWN_SETSIGMASK
;
193 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
195 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
196 // Use USEVFORK on linux
197 flags
|= POSIX_SPAWN_USEVFORK
;
200 flags
|= POSIX_SPAWN_SETPGROUP
;
201 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
203 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
210 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
211 std::fstream file_stream
;
212 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
214 _gdb_filename
= create_tmpfile(_exectuble_name
);
216 << "set logging redirect on" << std::endl
217 << "set logging file " << _gdb_filename
<< std::endl
218 << "set logging overwrite on" << std::endl
219 << "set logging on" << std::endl
220 << "set environment LIBTEST_IN_GDB=1" << std::endl
221 << "run " << arguments() << std::endl
222 << "thread apply all bt" << std::endl
223 << "quit" << std::endl
;
225 fatal_assert(file_stream
.good());
230 // libtool --mode=execute gdb -f -x binary
232 const_cast<char *>(libtool()),
233 const_cast<char *>("--mode=execute"),
234 const_cast<char *>("gdb"),
235 const_cast<char *>("-batch"),
236 const_cast<char *>("-f"),
237 const_cast<char *>("-x"),
238 const_cast<char *>(gdb_run_file
.c_str()),
239 const_cast<char *>(_exectuble_with_path
.c_str()),
242 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
248 const_cast<char *>("gdb"),
249 const_cast<char *>("-batch"),
250 const_cast<char *>("-f"),
251 const_cast<char *>("-x"),
252 const_cast<char *>(gdb_run_file
.c_str()),
253 const_cast<char *>(_exectuble_with_path
.c_str()),
255 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
260 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], NULL
);
263 posix_spawn_file_actions_destroy(&file_actions
);
264 posix_spawnattr_destroy(&spawnattr
);
266 stdin_fd
.close(Application::Pipe::READ
);
267 stdout_fd
.close(Application::Pipe::WRITE
);
268 stderr_fd
.close(Application::Pipe::WRITE
);
272 if (_will_fail
== false)
274 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
277 return Application::INVALID_POSIX_SPAWN
;
283 return Application::INVALID_POSIX_SPAWN
;
287 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
289 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
291 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
292 return Application::FAILURE
;
296 return Application::SUCCESS
;
299 bool Application::check() const
301 if (_pid
> 1 and kill(_pid
, 0) == 0)
309 void Application::murder()
314 while ((count
--) > 0 and check())
316 if (kill(_pid
, SIGTERM
) == 0)
322 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
329 // If for whatever reason it lives, kill it hard
332 Error
<< "using SIGKILL, things will likely go poorly from this point";
333 (void)kill(_pid
, SIGKILL
);
339 // false means that no data was returned
340 bool Application::slurp()
342 struct pollfd fds
[2];
343 fds
[0].fd
= stdout_fd
.fd();
344 fds
[0].events
= POLLRDNORM
;
346 fds
[1].fd
= stderr_fd
.fd();
347 fds
[1].events
= POLLRDNORM
;
351 if ((active_fd
= poll(fds
, 2, 0)) == -1)
354 switch ((error
= errno
))
356 #ifdef TARGET_OS_LINUX
364 fatal_message(strerror(error
));
368 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
372 fatal_message(strerror(error
));
384 bool data_was_read
= false;
385 if (fds
[0].revents
& POLLRDNORM
)
387 if (stdout_fd
.read(_stdout_buffer
) == true)
393 if (fds
[1].revents
& POLLRDNORM
)
395 if (stderr_fd
.read(_stderr_buffer
) == true)
401 return data_was_read
;
404 Application::error_t
Application::join()
406 pid_t waited_pid
= waitpid(_pid
, &_status
, 0);
408 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
411 What we are looking for here is how the exit status happened.
412 - 127 means that posix_spawn() itself had an error.
413 - 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.
414 - Finally something has happened that we don't currently understand.
416 if (WEXITSTATUS(_status
) == 127)
418 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
419 std::string
error_string("posix_spawn() failed pid:");
421 error_string
+= " name:";
422 error_string
+= built_argv
[0];
423 throw std::logic_error(error_string
);
425 else if WIFSIGNALED(_status
)
427 // memcached will die with SIGHUP
428 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
430 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
431 std::string
error_string(built_argv
[0]);
432 error_string
+= " was killed by signal ";
433 error_string
+= strsignal(WTERMSIG(_status
));
434 throw std::runtime_error(error_string
);
437 _app_exit_state
= Application::SIGTERM_KILLED
;
438 Error
<< "waitpid() application terminated at request"
440 << " name:" << built_argv
[0];
444 _app_exit_state
= Application::UNKNOWN
;
445 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
447 << " name:" << built_argv
[0];
450 else if (waited_pid
== _pid
and WIFEXITED(_status
))
452 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
454 else if (waited_pid
== -1)
456 _app_exit_state
= Application::UNKNOWN
;
457 Error
<< "waitpid() returned errno:" << strerror(errno
);
461 _app_exit_state
= Application::UNKNOWN
;
462 throw std::logic_error("waitpid() returned an unknown value");
465 return _app_exit_state
;
468 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
470 std::string
arg(name
);
472 _options
.push_back(std::make_pair(arg
, std::string()));
475 void Application::add_option(const std::string
& arg
)
477 _options
.push_back(std::make_pair(arg
, std::string()));
480 void Application::add_option(const std::string
& name
, const std::string
& value
)
482 _options
.push_back(std::make_pair(name
, value
));
485 Application::Pipe::Pipe(int arg
) :
494 int Application::Pipe::Pipe::fd()
496 if (_std_fd
== STDOUT_FILENO
)
498 return _pipe_fd
[READ
];
500 else if (_std_fd
== STDERR_FILENO
)
502 return _pipe_fd
[READ
];
505 return _pipe_fd
[WRITE
]; // STDIN_FILENO
509 bool Application::Pipe::read(libtest::vchar_t
& arg
)
511 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
513 bool data_was_read
= false;
516 char buffer
[1024]= { 0 };
517 while ((read_length
= ::read(_pipe_fd
[READ
], buffer
, sizeof(buffer
))))
519 if (read_length
== -1)
527 Error
<< strerror(errno
);
535 arg
.reserve(read_length
+1);
536 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
538 arg
.push_back(buffer
[x
]);
540 // @todo Suck up all errput code here
543 return data_was_read
;
546 void Application::Pipe::nonblock()
550 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
551 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
555 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
556 throw strerror(errno
);
562 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
563 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
567 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
568 throw strerror(errno
);
572 void Application::Pipe::reset()
577 #if defined(HAVE_PIPE2) && HAVE_PIPE2
578 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
580 if (pipe(_pipe_fd
) == -1)
583 fatal_message(strerror(errno
));
588 #if defined(HAVE_PIPE2) && HAVE_PIPE2
596 void Application::Pipe::cloexec()
598 //if (SOCK_CLOEXEC == 0)
605 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
606 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
610 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
611 throw strerror(errno
);
617 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
618 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
622 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
623 throw strerror(errno
);
629 Application::Pipe::~Pipe()
631 if (_pipe_fd
[0] != -1)
633 ::close(_pipe_fd
[0]);
636 if (_pipe_fd
[1] != -1)
638 ::close(_pipe_fd
[1]);
642 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
644 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
647 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
649 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
650 fatal_message(strerror(ret
));
653 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
655 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
656 fatal_message(strerror(ret
));
660 void Application::Pipe::close(const close_t
& arg
)
666 if (::close(_pipe_fd
[type
]) == -1)
668 Error
<< "close(" << strerror(errno
) << ")";
675 void Application::create_argv(const char *args
[])
681 built_argv
.push_back(strdup(libtool()));
682 built_argv
.push_back(strdup("--mode=execute"));
688 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
690 built_argv
.push_back(strdup("valgrind"));
691 built_argv
.push_back(strdup("--error-exitcode=1"));
692 built_argv
.push_back(strdup("--leak-check=yes"));
694 built_argv
.push_back(strdup("--show-reachable=yes"));
696 built_argv
.push_back(strdup("--track-fds=yes"));
698 built_argv
[x
++]= strdup("--track-origin=yes");
700 built_argv
.push_back(strdup("--malloc-fill=A5"));
701 built_argv
.push_back(strdup("--free-fill=DE"));
703 std::string log_file
= create_tmpfile("valgrind");
705 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
706 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
707 built_argv
.push_back(strdup(buffer
));
709 else if (_use_ptrcheck
)
712 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
714 built_argv
.push_back(strdup("valgrind"));
715 built_argv
.push_back(strdup("--error-exitcode=1"));
716 built_argv
.push_back(strdup("--tool=exp-ptrcheck"));
717 std::string log_file
= create_tmpfile("ptrcheck");
719 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
720 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
721 built_argv
.push_back(strdup(buffer
));
725 built_argv
.push_back(strdup("gdb"));
728 built_argv
.push_back(strdup(_exectuble_with_path
.c_str()));
730 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
732 built_argv
.push_back(strdup((*iter
).first
.c_str()));
733 if ((*iter
).second
.empty() == false)
735 built_argv
.push_back(strdup((*iter
).second
.c_str()));
741 for (const char **ptr
= args
; *ptr
; ++ptr
)
743 built_argv
.push_back(strdup(*ptr
));
746 built_argv
.push_back(NULL
);
749 std::string
Application::print()
751 return print_argv(built_argv
);
754 std::string
Application::arguments()
756 std::stringstream arg_buffer
;
758 for (size_t x
= (1 +_use_libtool
) ? 2 : 0;
759 x
< _argc
and built_argv
[x
];
762 arg_buffer
<< built_argv
[x
] << " ";
765 return arg_buffer
.str();
768 struct DeleteFromVector
771 void operator() ( T
* ptr
) const
777 void Application::delete_argv()
779 std::for_each(built_argv
.begin(), built_argv
.end(), DeleteFromVector());
786 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
788 Application
app(command
, use_libtool
);
790 Application::error_t ret
= app
.run(args
);
792 if (ret
!= Application::SUCCESS
)
797 return int(app
.join());
800 const char *gearmand_binary()
802 return GEARMAND_BINARY
;
805 const char *drizzled_binary()
807 return DRIZZLED_BINARY
;
810 } // namespace exec_cmdline