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
;
51 #include <sys/types.h>
57 static char **environ
= NULL
;
66 std::string
print_argv(libtest::vchar_ptr_t
& built_argv
)
68 std::stringstream arg_buffer
;
70 for (vchar_ptr_t::iterator iter
= built_argv
.begin();
71 iter
== built_argv
.end();
74 arg_buffer
<< *iter
<< " ";
77 return arg_buffer
.str();
81 std::string
print_argv(char** argv
)
83 std::stringstream arg_buffer
;
85 for (char** ptr
= argv
; *ptr
; ++ptr
)
87 arg_buffer
<< *ptr
<< " ";
90 return arg_buffer
.str();
94 static Application::error_t
int_to_error_t(int arg
)
99 return Application::INVALID_POSIX_SPAWN
;
102 return Application::SUCCESS
;
105 return Application::FAILURE
;
108 return Application::UNKNOWN
;
115 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
116 _use_libtool(_use_libtool_arg
),
117 _use_valgrind(false),
119 _use_ptrcheck(false),
123 stdin_fd(STDIN_FILENO
),
124 stdout_fd(STDOUT_FILENO
),
125 stderr_fd(STDERR_FILENO
),
128 _app_exit_state(UNINITIALIZED
)
132 if (libtool() == NULL
)
134 fatal_message("libtool requested, but know libtool was found");
138 // Find just the name of the application with no path
140 size_t found
= arg
.find_last_of("/\\");
143 _exectuble_name
= arg
.substr(found
+1);
147 _exectuble_name
= arg
;
151 if (_use_libtool
and getenv("PWD"))
153 _exectuble_with_path
+= getenv("PWD");
154 _exectuble_with_path
+= "/";
156 _exectuble_with_path
+= _exectuble
;
159 Application::~Application()
165 Application::error_t
Application::run(const char *args
[])
170 _stdout_buffer
.clear();
171 _stderr_buffer
.clear();
173 posix_spawn_file_actions_t file_actions
;
174 posix_spawn_file_actions_init(&file_actions
);
176 stdin_fd
.dup_for_spawn(file_actions
);
177 stdout_fd
.dup_for_spawn(file_actions
);
178 stderr_fd
.dup_for_spawn(file_actions
);
180 posix_spawnattr_t spawnattr
;
181 posix_spawnattr_init(&spawnattr
);
185 // Child should not block signals
186 flags
|= POSIX_SPAWN_SETSIGMASK
;
191 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
193 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
194 // Use USEVFORK on linux
195 flags
|= POSIX_SPAWN_USEVFORK
;
198 flags
|= POSIX_SPAWN_SETPGROUP
;
199 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
201 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
208 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
209 std::fstream file_stream
;
210 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
212 _gdb_filename
= create_tmpfile(_exectuble_name
);
214 << "set logging redirect on" << std::endl
215 << "set logging file " << _gdb_filename
<< std::endl
216 << "set logging overwrite on" << std::endl
217 << "set logging on" << std::endl
218 << "set environment LIBTEST_IN_GDB=1" << std::endl
219 << "run " << arguments() << std::endl
220 << "thread apply all bt" << std::endl
221 << "quit" << std::endl
;
223 fatal_assert(file_stream
.good());
228 // libtool --mode=execute gdb -f -x binary
230 const_cast<char *>(libtool()),
231 const_cast<char *>("--mode=execute"),
232 const_cast<char *>("gdb"),
233 const_cast<char *>("-batch"),
234 const_cast<char *>("-f"),
235 const_cast<char *>("-x"),
236 const_cast<char *>(gdb_run_file
.c_str()),
237 const_cast<char *>(_exectuble_with_path
.c_str()),
240 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
246 const_cast<char *>("gdb"),
247 const_cast<char *>("-batch"),
248 const_cast<char *>("-f"),
249 const_cast<char *>("-x"),
250 const_cast<char *>(gdb_run_file
.c_str()),
251 const_cast<char *>(_exectuble_with_path
.c_str()),
253 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
258 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], NULL
);
261 posix_spawn_file_actions_destroy(&file_actions
);
262 posix_spawnattr_destroy(&spawnattr
);
264 stdin_fd
.close(Application::Pipe::READ
);
265 stdout_fd
.close(Application::Pipe::WRITE
);
266 stderr_fd
.close(Application::Pipe::WRITE
);
270 if (_will_fail
== false)
272 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
275 return Application::INVALID_POSIX_SPAWN
;
281 return Application::INVALID_POSIX_SPAWN
;
285 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
287 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
289 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
290 return Application::FAILURE
;
294 return Application::SUCCESS
;
297 bool Application::check() const
299 if (_pid
> 1 and kill(_pid
, 0) == 0)
307 void Application::murder()
312 while ((count
--) > 0 and check())
314 if (kill(_pid
, SIGTERM
) == 0)
320 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
327 // If for whatever reason it lives, kill it hard
330 Error
<< "using SIGKILL, things will likely go poorly from this point";
331 (void)kill(_pid
, SIGKILL
);
337 // false means that no data was returned
338 bool Application::slurp()
340 struct pollfd fds
[2];
341 fds
[0].fd
= stdout_fd
.fd();
342 fds
[0].events
= POLLRDNORM
;
344 fds
[1].fd
= stderr_fd
.fd();
345 fds
[1].events
= POLLRDNORM
;
349 if ((active_fd
= poll(fds
, 2, 0)) == -1)
352 switch ((error
= errno
))
354 #ifdef TARGET_OS_LINUX
362 fatal_message(strerror(error
));
366 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
370 fatal_message(strerror(error
));
382 bool data_was_read
= false;
383 if (fds
[0].revents
& POLLRDNORM
)
385 if (stdout_fd
.read(_stdout_buffer
) == true)
391 if (fds
[1].revents
& POLLRDNORM
)
393 if (stderr_fd
.read(_stderr_buffer
) == true)
399 return data_was_read
;
402 Application::error_t
Application::join()
404 pid_t waited_pid
= waitpid(_pid
, &_status
, 0);
406 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
409 What we are looking for here is how the exit status happened.
410 - 127 means that posix_spawn() itself had an error.
411 - 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.
412 - Finally something has happened that we don't currently understand.
414 if (WEXITSTATUS(_status
) == 127)
416 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
417 std::string
error_string("posix_spawn() failed pid:");
419 error_string
+= " name:";
420 error_string
+= built_argv
[0];
421 throw std::logic_error(error_string
);
423 else if WIFSIGNALED(_status
)
425 // memcached will die with SIGHUP
426 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
428 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
429 std::string
error_string(built_argv
[0]);
430 error_string
+= " was killed by signal ";
431 error_string
+= strsignal(WTERMSIG(_status
));
432 throw std::runtime_error(error_string
);
435 _app_exit_state
= Application::SIGTERM_KILLED
;
436 Out
<< "waitpid() application terminated at request"
438 << " name:" << built_argv
[0];
442 _app_exit_state
= Application::UNKNOWN
;
443 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
445 << " name:" << built_argv
[0];
448 else if (waited_pid
== _pid
and WIFEXITED(_status
))
450 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
452 else if (waited_pid
== -1)
454 _app_exit_state
= Application::UNKNOWN
;
455 Error
<< "waitpid() returned errno:" << strerror(errno
);
459 _app_exit_state
= Application::UNKNOWN
;
460 throw std::logic_error("waitpid() returned an unknown value");
463 return _app_exit_state
;
466 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
468 std::string
arg(name
);
470 _options
.push_back(std::make_pair(arg
, std::string()));
473 void Application::add_option(const std::string
& arg
)
475 _options
.push_back(std::make_pair(arg
, std::string()));
478 void Application::add_option(const std::string
& name
, const std::string
& value
)
480 _options
.push_back(std::make_pair(name
, value
));
483 Application::Pipe::Pipe(int arg
) :
492 int Application::Pipe::Pipe::fd()
494 if (_std_fd
== STDOUT_FILENO
)
496 return _pipe_fd
[READ
];
498 else if (_std_fd
== STDERR_FILENO
)
500 return _pipe_fd
[READ
];
503 return _pipe_fd
[WRITE
]; // STDIN_FILENO
507 bool Application::Pipe::read(libtest::vchar_t
& arg
)
509 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
511 bool data_was_read
= false;
514 char buffer
[1024]= { 0 };
515 while ((read_length
= ::read(_pipe_fd
[READ
], buffer
, sizeof(buffer
))))
517 if (read_length
== -1)
525 Error
<< strerror(errno
);
533 arg
.reserve(read_length
+1);
534 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
536 arg
.push_back(buffer
[x
]);
538 // @todo Suck up all errput code here
541 return data_was_read
;
544 void Application::Pipe::nonblock()
548 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
549 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
553 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
554 throw strerror(errno
);
560 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
561 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
565 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
566 throw strerror(errno
);
570 void Application::Pipe::reset()
575 #if defined(HAVE_PIPE2) && HAVE_PIPE2
576 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
578 if (pipe(_pipe_fd
) == -1)
581 fatal_message(strerror(errno
));
586 #if defined(HAVE_PIPE2) && HAVE_PIPE2
594 void Application::Pipe::cloexec()
596 //if (SOCK_CLOEXEC == 0)
603 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
604 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
608 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
609 throw strerror(errno
);
615 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
616 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
620 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
621 throw strerror(errno
);
627 Application::Pipe::~Pipe()
629 if (_pipe_fd
[0] != -1)
631 ::close(_pipe_fd
[0]);
634 if (_pipe_fd
[1] != -1)
636 ::close(_pipe_fd
[1]);
640 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
642 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
645 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
647 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
648 fatal_message(strerror(ret
));
651 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
653 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
654 fatal_message(strerror(ret
));
658 void Application::Pipe::close(const close_t
& arg
)
664 if (::close(_pipe_fd
[type
]) == -1)
666 Error
<< "close(" << strerror(errno
) << ")";
673 void Application::create_argv(const char *args
[])
679 built_argv
.push_back(strdup(libtool()));
680 built_argv
.push_back(strdup("--mode=execute"));
686 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
688 built_argv
.push_back(strdup("valgrind"));
689 built_argv
.push_back(strdup("--error-exitcode=1"));
690 built_argv
.push_back(strdup("--leak-check=yes"));
692 built_argv
.push_back(strdup("--show-reachable=yes"));
694 built_argv
.push_back(strdup("--track-fds=yes"));
696 built_argv
[x
++]= strdup("--track-origin=yes");
698 built_argv
.push_back(strdup("--malloc-fill=A5"));
699 built_argv
.push_back(strdup("--free-fill=DE"));
701 std::string log_file
= create_tmpfile("valgrind");
703 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
704 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
705 built_argv
.push_back(strdup(buffer
));
707 else if (_use_ptrcheck
)
710 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
712 built_argv
.push_back(strdup("valgrind"));
713 built_argv
.push_back(strdup("--error-exitcode=1"));
714 built_argv
.push_back(strdup("--tool=exp-ptrcheck"));
715 std::string log_file
= create_tmpfile("ptrcheck");
717 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
718 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
719 built_argv
.push_back(strdup(buffer
));
723 built_argv
.push_back(strdup("gdb"));
726 built_argv
.push_back(strdup(_exectuble_with_path
.c_str()));
728 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
730 built_argv
.push_back(strdup((*iter
).first
.c_str()));
731 if ((*iter
).second
.empty() == false)
733 built_argv
.push_back(strdup((*iter
).second
.c_str()));
739 for (const char **ptr
= args
; *ptr
; ++ptr
)
741 built_argv
.push_back(strdup(*ptr
));
744 built_argv
.push_back(NULL
);
747 std::string
Application::print()
749 return print_argv(built_argv
);
752 std::string
Application::arguments()
754 std::stringstream arg_buffer
;
756 for (size_t x
= (1 +_use_libtool
) ? 2 : 0;
757 x
< _argc
and built_argv
[x
];
760 arg_buffer
<< built_argv
[x
] << " ";
763 return arg_buffer
.str();
766 struct DeleteFromVector
769 void operator() ( T
* ptr
) const
775 void Application::delete_argv()
777 std::for_each(built_argv
.begin(), built_argv
.end(), DeleteFromVector());
784 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
786 Application
app(command
, use_libtool
);
788 Application::error_t ret
= app
.run(args
);
790 if (ret
!= Application::SUCCESS
)
795 return int(app
.join());
798 const char *gearmand_binary()
800 return GEARMAND_BINARY
;
803 const char *drizzled_binary()
805 return DRIZZLED_BINARY
;
808 } // namespace exec_cmdline