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.
37 #include "mem_config.h"
38 #include "libtest/common.h"
40 using namespace libtest
;
57 #include <sys/types.h>
63 static char **environ
= NULL
;
72 std::string
print_argv(libtest::vchar_ptr_t
& built_argv
)
74 std::stringstream arg_buffer
;
76 for (vchar_ptr_t::iterator iter
= built_argv
.begin();
77 iter
== built_argv
.end();
80 arg_buffer
<< *iter
<< " ";
83 return arg_buffer
.str();
87 std::string
print_argv(char** argv
)
89 std::stringstream arg_buffer
;
91 for (char** ptr
= argv
; *ptr
; ++ptr
)
93 arg_buffer
<< *ptr
<< " ";
96 return arg_buffer
.str();
100 static Application::error_t
int_to_error_t(int arg
)
105 return Application::INVALID_POSIX_SPAWN
;
108 return Application::SUCCESS
;
111 return Application::FAILURE
;
114 return Application::UNKNOWN
;
121 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
122 _use_libtool(_use_libtool_arg
),
123 _use_valgrind(false),
125 _use_ptrcheck(false),
129 stdin_fd(STDIN_FILENO
),
130 stdout_fd(STDOUT_FILENO
),
131 stderr_fd(STDERR_FILENO
),
134 _app_exit_state(UNINITIALIZED
)
138 if (libtool() == NULL
)
140 fatal_message("libtool requested, but know libtool was found");
144 // Find just the name of the application with no path
146 size_t found
= arg
.find_last_of("/\\");
149 _exectuble_name
= arg
.substr(found
+1);
153 _exectuble_name
= arg
;
157 if (_use_libtool
and getenv("PWD"))
159 _exectuble_with_path
+= getenv("PWD");
160 _exectuble_with_path
+= "/";
162 _exectuble_with_path
+= _exectuble
;
165 Application::~Application()
171 Application::error_t
Application::run(const char *args
[])
176 _stdout_buffer
.clear();
177 _stderr_buffer
.clear();
179 posix_spawn_file_actions_t file_actions
;
180 posix_spawn_file_actions_init(&file_actions
);
182 stdin_fd
.dup_for_spawn(file_actions
);
183 stdout_fd
.dup_for_spawn(file_actions
);
184 stderr_fd
.dup_for_spawn(file_actions
);
186 posix_spawnattr_t spawnattr
;
187 posix_spawnattr_init(&spawnattr
);
191 // Child should not block signals
192 flags
|= POSIX_SPAWN_SETSIGMASK
;
197 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
199 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
200 // Use USEVFORK on linux
201 flags
|= POSIX_SPAWN_USEVFORK
;
204 flags
|= POSIX_SPAWN_SETPGROUP
;
205 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
207 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
214 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
215 std::fstream file_stream
;
216 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
218 _gdb_filename
= create_tmpfile(_exectuble_name
);
220 << "set logging redirect on" << std::endl
221 << "set logging file " << _gdb_filename
<< std::endl
222 << "set logging overwrite on" << std::endl
223 << "set logging on" << std::endl
224 << "set environment LIBTEST_IN_GDB=1" << std::endl
225 << "run " << arguments() << std::endl
226 << "thread apply all bt" << std::endl
227 << "quit" << std::endl
;
229 fatal_assert(file_stream
.good());
234 // libtool --mode=execute gdb -f -x binary
236 const_cast<char *>(libtool()),
237 const_cast<char *>("--mode=execute"),
238 const_cast<char *>("gdb"),
239 const_cast<char *>("-batch"),
240 const_cast<char *>("-f"),
241 const_cast<char *>("-x"),
242 const_cast<char *>(gdb_run_file
.c_str()),
243 const_cast<char *>(_exectuble_with_path
.c_str()),
246 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
252 const_cast<char *>("gdb"),
253 const_cast<char *>("-batch"),
254 const_cast<char *>("-f"),
255 const_cast<char *>("-x"),
256 const_cast<char *>(gdb_run_file
.c_str()),
257 const_cast<char *>(_exectuble_with_path
.c_str()),
259 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
264 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], NULL
);
267 posix_spawn_file_actions_destroy(&file_actions
);
268 posix_spawnattr_destroy(&spawnattr
);
270 stdin_fd
.close(Application::Pipe::READ
);
271 stdout_fd
.close(Application::Pipe::WRITE
);
272 stderr_fd
.close(Application::Pipe::WRITE
);
276 if (_will_fail
== false)
278 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
281 return Application::INVALID_POSIX_SPAWN
;
287 return Application::INVALID_POSIX_SPAWN
;
291 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
293 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
295 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
296 return Application::FAILURE
;
300 return Application::SUCCESS
;
303 bool Application::check() const
305 if (_pid
> 1 and kill(_pid
, 0) == 0)
313 void Application::murder()
318 while ((count
--) > 0 and check())
320 if (kill(_pid
, SIGTERM
) == 0)
326 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
333 // If for whatever reason it lives, kill it hard
336 Error
<< "using SIGKILL, things will likely go poorly from this point";
337 (void)kill(_pid
, SIGKILL
);
343 // false means that no data was returned
344 bool Application::slurp()
346 struct pollfd fds
[2];
347 fds
[0].fd
= stdout_fd
.fd();
348 fds
[0].events
= POLLRDNORM
;
350 fds
[1].fd
= stderr_fd
.fd();
351 fds
[1].events
= POLLRDNORM
;
355 if ((active_fd
= poll(fds
, 2, 0)) == -1)
358 switch ((error
= errno
))
360 #ifdef TARGET_OS_LINUX
368 fatal_message(strerror(error
));
372 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
376 fatal_message(strerror(error
));
388 bool data_was_read
= false;
389 if (fds
[0].revents
& POLLRDNORM
)
391 if (stdout_fd
.read(_stdout_buffer
) == true)
397 if (fds
[1].revents
& POLLRDNORM
)
399 if (stderr_fd
.read(_stderr_buffer
) == true)
405 return data_was_read
;
408 Application::error_t
Application::join()
410 pid_t waited_pid
= waitpid(_pid
, &_status
, 0);
412 if (waited_pid
== _pid
and WIFEXITED(_status
) == false)
415 What we are looking for here is how the exit status happened.
416 - 127 means that posix_spawn() itself had an error.
417 - 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.
418 - Finally something has happened that we don't currently understand.
420 if (WEXITSTATUS(_status
) == 127)
422 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
423 std::string
error_string("posix_spawn() failed pid:");
425 error_string
+= " name:";
426 error_string
+= built_argv
[0];
427 throw std::logic_error(error_string
);
429 else if WIFSIGNALED(_status
)
431 if (WTERMSIG(_status
) != SIGTERM
and WTERMSIG(_status
) != SIGHUP
)
433 _app_exit_state
= Application::INVALID_POSIX_SPAWN
;
434 std::string
error_string(built_argv
[0]);
435 error_string
+= " was killed by signal ";
436 error_string
+= strsignal(WTERMSIG(_status
));
437 throw std::runtime_error(error_string
);
440 // If we terminted it on purpose then it counts as a success.
441 Out
<< "waitpid() application terminated at request"
443 << " name:" << built_argv
[0];
447 _app_exit_state
= Application::UNKNOWN
;
448 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
450 << " name:" << built_argv
[0];
453 else if (waited_pid
== _pid
and WIFEXITED(_status
))
455 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
457 else if (waited_pid
== -1)
459 _app_exit_state
= Application::UNKNOWN
;
460 Error
<< "waitpid() returned errno:" << strerror(errno
);
464 _app_exit_state
= Application::UNKNOWN
;
465 throw std::logic_error("waitpid() returned an unknown value");
468 return _app_exit_state
;
471 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
473 std::string
arg(name
);
475 _options
.push_back(std::make_pair(arg
, std::string()));
478 void Application::add_option(const std::string
& arg
)
480 _options
.push_back(std::make_pair(arg
, std::string()));
483 void Application::add_option(const std::string
& name
, const std::string
& value
)
485 _options
.push_back(std::make_pair(name
, value
));
488 Application::Pipe::Pipe(int arg
) :
497 int Application::Pipe::Pipe::fd()
499 if (_std_fd
== STDOUT_FILENO
)
501 return _pipe_fd
[READ
];
503 else if (_std_fd
== STDERR_FILENO
)
505 return _pipe_fd
[READ
];
508 return _pipe_fd
[WRITE
]; // STDIN_FILENO
512 bool Application::Pipe::read(libtest::vchar_t
& arg
)
514 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
516 bool data_was_read
= false;
519 char buffer
[1024]= { 0 };
520 while ((read_length
= ::read(_pipe_fd
[READ
], buffer
, sizeof(buffer
))))
522 if (read_length
== -1)
530 Error
<< strerror(errno
);
538 arg
.reserve(read_length
+1);
539 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
541 arg
.push_back(buffer
[x
]);
543 // @todo Suck up all errput code here
546 return data_was_read
;
549 void Application::Pipe::nonblock()
553 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
554 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
558 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
559 throw strerror(errno
);
565 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
566 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
570 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
571 throw strerror(errno
);
575 void Application::Pipe::reset()
580 #if defined(HAVE_PIPE2) && HAVE_PIPE2
581 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
583 if (pipe(_pipe_fd
) == -1)
586 fatal_message(strerror(errno
));
591 #if defined(HAVE_PIPE2) && HAVE_PIPE2
599 void Application::Pipe::cloexec()
601 //if (SOCK_CLOEXEC == 0)
608 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
609 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
613 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
614 throw strerror(errno
);
620 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
621 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
625 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
626 throw strerror(errno
);
632 Application::Pipe::~Pipe()
634 if (_pipe_fd
[0] != -1)
636 ::close(_pipe_fd
[0]);
639 if (_pipe_fd
[1] != -1)
641 ::close(_pipe_fd
[1]);
645 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
647 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
650 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
652 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
653 fatal_message(strerror(ret
));
656 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
658 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
659 fatal_message(strerror(ret
));
663 void Application::Pipe::close(const close_t
& arg
)
669 if (::close(_pipe_fd
[type
]) == -1)
671 Error
<< "close(" << strerror(errno
) << ")";
678 void Application::create_argv(const char *args
[])
684 built_argv
.push_back(strdup(libtool()));
685 built_argv
.push_back(strdup("--mode=execute"));
691 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
693 built_argv
.push_back(strdup("valgrind"));
694 built_argv
.push_back(strdup("--error-exitcode=1"));
695 built_argv
.push_back(strdup("--leak-check=yes"));
697 built_argv
.push_back(strdup("--show-reachable=yes"));
699 built_argv
.push_back(strdup("--track-fds=yes"));
701 built_argv
[x
++]= strdup("--track-origin=yes");
703 built_argv
.push_back(strdup("--malloc-fill=A5"));
704 built_argv
.push_back(strdup("--free-fill=DE"));
706 std::string log_file
= create_tmpfile("valgrind");
708 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
709 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
710 built_argv
.push_back(strdup(buffer
));
712 else if (_use_ptrcheck
)
715 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
717 built_argv
.push_back(strdup("valgrind"));
718 built_argv
.push_back(strdup("--error-exitcode=1"));
719 built_argv
.push_back(strdup("--tool=exp-ptrcheck"));
720 std::string log_file
= create_tmpfile("ptrcheck");
722 int length
= snprintf(buffer
, sizeof(buffer
), "--log-file=%s", log_file
.c_str());
723 fatal_assert(length
> 0 and size_t(length
) < sizeof(buffer
));
724 built_argv
.push_back(strdup(buffer
));
728 built_argv
.push_back(strdup("gdb"));
731 built_argv
.push_back(strdup(_exectuble_with_path
.c_str()));
733 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
735 built_argv
.push_back(strdup((*iter
).first
.c_str()));
736 if ((*iter
).second
.empty() == false)
738 built_argv
.push_back(strdup((*iter
).second
.c_str()));
744 for (const char **ptr
= args
; *ptr
; ++ptr
)
746 built_argv
.push_back(strdup(*ptr
));
749 built_argv
.push_back(NULL
);
752 std::string
Application::print()
754 return print_argv(built_argv
);
757 std::string
Application::arguments()
759 std::stringstream arg_buffer
;
761 for (size_t x
= (1 +_use_libtool
) ? 2 : 0;
762 x
< _argc
and built_argv
[x
];
765 arg_buffer
<< built_argv
[x
] << " ";
768 return arg_buffer
.str();
771 struct DeleteFromVector
774 void operator() ( T
* ptr
) const
780 void Application::delete_argv()
782 std::for_each(built_argv
.begin(), built_argv
.end(), DeleteFromVector());
789 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
791 Application
app(command
, use_libtool
);
793 Application::error_t ret
= app
.run(args
);
795 if (ret
!= Application::SUCCESS
)
800 return int(app
.join());
803 const char *gearmand_binary()
805 return GEARMAND_BINARY
;
808 const char *drizzled_binary()
810 return DRIZZLED_BINARY
;
813 } // namespace exec_cmdline