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 "libtest/yatlcon.h"
39 #include "libtest/common.h"
41 using namespace libtest
;
58 #include <sys/types.h>
64 static char **environ
= NULL
;
73 std::string
print_argv(libtest::vchar_ptr_t
& built_argv
)
75 std::stringstream arg_buffer
;
77 for (vchar_ptr_t::iterator iter
= built_argv
.begin();
78 iter
!= built_argv
.end();
81 arg_buffer
<< *iter
<< " ";
84 return arg_buffer
.str();
88 std::string
print_argv(char** argv
)
90 std::stringstream arg_buffer
;
92 for (char** ptr
= argv
; *ptr
; ++ptr
)
94 arg_buffer
<< *ptr
<< " ";
97 return arg_buffer
.str();
101 static Application::error_t
int_to_error_t(int arg
)
106 return Application::INVALID_POSIX_SPAWN
;
109 return Application::SUCCESS
;
112 return Application::FAILURE
;
115 return Application::UNKNOWN
;
122 Application::Application(const std::string
& arg
, const bool _use_libtool_arg
) :
123 _use_libtool(_use_libtool_arg
),
124 _use_valgrind(false),
126 _use_ptrcheck(false),
130 stdin_fd(STDIN_FILENO
),
131 stdout_fd(STDOUT_FILENO
),
132 stderr_fd(STDERR_FILENO
),
135 _app_exit_state(UNINITIALIZED
)
139 if (libtool() == NULL
)
141 fatal_message("libtool requested, but know libtool was found");
145 // Find just the name of the application with no path
147 size_t found
= arg
.find_last_of("/\\");
150 _exectuble_name
= arg
.substr(found
+1);
154 _exectuble_name
= arg
;
158 if (_use_libtool
and getenv("PWD"))
160 _exectuble_with_path
+= getenv("PWD");
161 _exectuble_with_path
+= "/";
163 _exectuble_with_path
+= _exectuble
;
166 Application::~Application()
172 Application::error_t
Application::run(const char *args
[])
177 _stdout_buffer
.clear();
178 _stderr_buffer
.clear();
180 posix_spawn_file_actions_t file_actions
;
181 posix_spawn_file_actions_init(&file_actions
);
183 stdin_fd
.dup_for_spawn(file_actions
);
184 stdout_fd
.dup_for_spawn(file_actions
);
185 stderr_fd
.dup_for_spawn(file_actions
);
187 posix_spawnattr_t spawnattr
;
188 posix_spawnattr_init(&spawnattr
);
192 // Child should not block signals
193 flags
|= POSIX_SPAWN_SETSIGMASK
;
198 fatal_assert(posix_spawnattr_setsigmask(&spawnattr
, &mask
) == 0);
200 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
201 // Use USEVFORK on linux
202 flags
|= POSIX_SPAWN_USEVFORK
;
205 flags
|= POSIX_SPAWN_SETPGROUP
;
206 fatal_assert(posix_spawnattr_setpgroup(&spawnattr
, 0) == 0);
208 fatal_assert(posix_spawnattr_setflags(&spawnattr
, flags
) == 0);
215 std::string gdb_run_file
= create_tmpfile(_exectuble_name
);
216 std::fstream file_stream
;
217 file_stream
.open(gdb_run_file
.c_str(), std::fstream::out
| std::fstream::trunc
);
219 _gdb_filename
= create_tmpfile(_exectuble_name
);
221 << "set logging redirect on" << std::endl
222 << "set logging file " << _gdb_filename
<< std::endl
223 << "set logging overwrite on" << std::endl
224 << "set logging on" << std::endl
225 << "set environment LIBTEST_IN_GDB=1" << std::endl
226 << "run " << arguments() << std::endl
227 << "thread apply all bt" << std::endl
228 << "quit" << std::endl
;
230 fatal_assert(file_stream
.good());
235 // libtool --mode=execute gdb -f -x binary
237 const_cast<char *>(libtool()),
238 const_cast<char *>("--mode=execute"),
239 const_cast<char *>("gdb"),
240 const_cast<char *>("-batch"),
241 const_cast<char *>("-f"),
242 const_cast<char *>("-x"),
243 const_cast<char *>(gdb_run_file
.c_str()),
244 const_cast<char *>(_exectuble_with_path
.c_str()),
247 spawn_ret
= posix_spawnp(&_pid
, libtool(), &file_actions
, &spawnattr
, argv
, environ
);
253 const_cast<char *>("gdb"),
254 const_cast<char *>("-batch"),
255 const_cast<char *>("-f"),
256 const_cast<char *>("-x"),
257 const_cast<char *>(gdb_run_file
.c_str()),
258 const_cast<char *>(_exectuble_with_path
.c_str()),
260 spawn_ret
= posix_spawnp(&_pid
, "gdb", &file_actions
, &spawnattr
, argv
, environ
);
265 spawn_ret
= posix_spawn(&_pid
, built_argv
[0], &file_actions
, &spawnattr
, &built_argv
[0], NULL
);
268 posix_spawn_file_actions_destroy(&file_actions
);
269 posix_spawnattr_destroy(&spawnattr
);
271 stdin_fd
.close(Application::Pipe::READ
);
272 stdout_fd
.close(Application::Pipe::WRITE
);
273 stderr_fd
.close(Application::Pipe::WRITE
);
277 if (_will_fail
== false)
279 Error
<< strerror(spawn_ret
) << "(" << spawn_ret
<< ")";
282 return Application::INVALID_POSIX_SPAWN
;
288 return Application::INVALID_POSIX_SPAWN
;
292 app_thread_st
* _app_thread
= new app_thread_st(_pid
, _status
, built_argv
[0], _app_exit_state
);
294 if ((error
= pthread_create(&_thread
, NULL
, &app_thread
, _app_thread
)) != 0)
296 Error
<< "pthread_create() died during pthread_create(" << strerror(error
) << ")";
297 return Application::FAILURE
;
301 return Application::SUCCESS
;
304 bool Application::check() const
306 if (_pid
> 1 and kill(_pid
, 0) == 0)
314 void Application::murder()
319 while ((count
--) > 0 and check())
321 if (kill(_pid
, SIGTERM
) == 0)
327 Error
<< "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno
);
334 // If for whatever reason it lives, kill it hard
337 Error
<< "using SIGKILL, things will likely go poorly from this point";
338 (void)kill(_pid
, SIGKILL
);
344 // false means that no data was returned
345 bool Application::slurp()
347 struct pollfd fds
[2];
348 fds
[0].fd
= stdout_fd
.fd();
349 fds
[0].events
= POLLRDNORM
;
351 fds
[1].fd
= stderr_fd
.fd();
352 fds
[1].events
= POLLRDNORM
;
356 if ((active_fd
= poll(fds
, 2, 0)) == -1)
359 switch ((error
= errno
))
361 #ifdef TARGET_OS_LINUX
369 fatal_message(strerror(error
));
373 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
377 fatal_message(strerror(error
));
389 bool data_was_read
= false;
390 if (fds
[0].revents
& POLLRDNORM
)
392 if (stdout_fd
.read(_stdout_buffer
) == true)
398 if (fds
[1].revents
& POLLRDNORM
)
400 if (stderr_fd
.read(_stderr_buffer
) == true)
406 return data_was_read
;
409 Application::error_t
Application::join()
411 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.
444 Out
<< "waitpid() application terminated at request"
446 << " name:" << built_argv
[0];
452 _app_exit_state
= Application::UNKNOWN
;
453 Error
<< "Unknown logic state at exit:" << WEXITSTATUS(_status
)
455 << " name:" << built_argv
[0];
458 else if (waited_pid
== _pid
and WIFEXITED(_status
))
460 _app_exit_state
= int_to_error_t(WEXITSTATUS(_status
));
462 else if (waited_pid
== -1)
464 _app_exit_state
= Application::UNKNOWN
;
465 Error
<< "waitpid() returned errno:" << strerror(errno
);
469 _app_exit_state
= Application::UNKNOWN
;
470 throw std::logic_error("waitpid() returned an unknown value");
473 return _app_exit_state
;
476 void Application::add_long_option(const std::string
& name
, const std::string
& option_value
)
478 std::string
arg(name
);
480 _options
.push_back(std::make_pair(arg
, std::string()));
483 void Application::add_option(const std::string
& arg
)
485 _options
.push_back(std::make_pair(arg
, std::string()));
488 void Application::add_option(const std::string
& name
, const std::string
& value
)
490 _options
.push_back(std::make_pair(name
, value
));
493 Application::Pipe::Pipe(int arg
) :
502 int Application::Pipe::Pipe::fd()
504 if (_std_fd
== STDOUT_FILENO
)
506 return _pipe_fd
[READ
];
508 else if (_std_fd
== STDERR_FILENO
)
510 return _pipe_fd
[READ
];
513 return _pipe_fd
[WRITE
]; // STDIN_FILENO
517 bool Application::Pipe::read(libtest::vchar_t
& arg
)
519 fatal_assert(_std_fd
== STDOUT_FILENO
or _std_fd
== STDERR_FILENO
);
521 bool data_was_read
= false;
523 libtest::vchar_t buffer
;
526 while ((read_length
= ::read(_pipe_fd
[READ
], &buffer
[0], buffer
.size())))
528 if (read_length
== -1)
536 Error
<< strerror(errno
);
544 arg
.reserve(read_length
+1);
545 for (size_t x
= 0; x
< size_t(read_length
); ++x
)
547 arg
.push_back(buffer
[x
]);
549 // @todo Suck up all errput code here
552 return data_was_read
;
555 void Application::Pipe::nonblock()
559 flags
= fcntl(_pipe_fd
[READ
], F_GETFL
, 0);
560 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
564 Error
<< "fcntl(F_GETFL) " << strerror(errno
);
565 throw strerror(errno
);
571 rval
= fcntl(_pipe_fd
[READ
], F_SETFL
, flags
| O_NONBLOCK
);
572 } while (rval
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
576 Error
<< "fcntl(F_SETFL) " << strerror(errno
);
577 throw strerror(errno
);
581 void Application::Pipe::reset()
586 #if defined(HAVE_PIPE2) && HAVE_PIPE2
587 if (pipe2(_pipe_fd
, O_NONBLOCK
|O_CLOEXEC
) == -1)
589 if (pipe(_pipe_fd
) == -1)
592 fatal_message(strerror(errno
));
597 #if defined(HAVE_PIPE2) && HAVE_PIPE2
606 void Application::Pipe::cloexec()
608 //if (SOCK_CLOEXEC == 0)
615 flags
= fcntl(_pipe_fd
[WRITE
], F_GETFD
, 0);
616 } while (flags
== -1 and (errno
== EINTR
or errno
== EAGAIN
));
620 Error
<< "fcntl(F_GETFD) " << strerror(errno
);
621 throw strerror(errno
);
627 rval
= fcntl(_pipe_fd
[WRITE
], F_SETFD
, flags
| FD_CLOEXEC
);
628 } while (rval
== -1 && (errno
== EINTR
or errno
== EAGAIN
));
632 Error
<< "fcntl(F_SETFD) " << strerror(errno
);
633 throw strerror(errno
);
639 Application::Pipe::~Pipe()
641 if (_pipe_fd
[0] != -1)
643 ::close(_pipe_fd
[0]);
646 if (_pipe_fd
[1] != -1)
648 ::close(_pipe_fd
[1]);
652 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t
& file_actions
)
654 int type
= STDIN_FILENO
== _std_fd
? 0 : 1;
657 if ((ret
= posix_spawn_file_actions_adddup2(&file_actions
, _pipe_fd
[type
], _std_fd
)) < 0)
659 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
660 fatal_message(strerror(ret
));
663 if ((ret
= posix_spawn_file_actions_addclose(&file_actions
, _pipe_fd
[type
])) < 0)
665 Error
<< "posix_spawn_file_actions_adddup2(" << strerror(ret
) << ")";
666 fatal_message(strerror(ret
));
670 void Application::Pipe::close(const close_t
& arg
)
676 if (::close(_pipe_fd
[type
]) == -1)
678 Error
<< "close(" << strerror(errno
) << ")";
685 void Application::create_argv(const char *args
[])
691 vchar::append(built_argv
, libtool());
692 vchar::append(built_argv
, "--mode=execute");
698 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
700 vchar::append(built_argv
, "valgrind");
701 vchar::append(built_argv
, "--error-exitcode=1");
702 vchar::append(built_argv
, "--leak-check=yes");
704 vchar::append(built_argv
, "--show-reachable=yes"));
706 vchar::append(built_argv
, "--track-fds=yes");
708 built_argv
[x
++]= strdup("--track-origin=yes");
710 vchar::append(built_argv
, "--malloc-fill=A5");
711 vchar::append(built_argv
, "--free-fill=DE");
713 std::string log_file
= create_tmpfile("valgrind");
714 libtest::vchar_t buffer
;
716 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
717 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
718 vchar::append(built_argv
, &buffer
[0]);
720 else if (_use_ptrcheck
)
723 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
725 vchar::append(built_argv
, "valgrind");
726 vchar::append(built_argv
, "--error-exitcode=1");
727 vchar::append(built_argv
, "--tool=exp-ptrcheck");
728 std::string log_file
= create_tmpfile("ptrcheck");
729 libtest::vchar_t buffer
;
731 int length
= snprintf(&buffer
[0], buffer
.size(), "--log-file=%s", log_file
.c_str());
732 fatal_assert(length
> 0 and size_t(length
) < buffer
.size());
733 vchar::append(built_argv
, &buffer
[0]);
737 vchar::append(built_argv
, "gdb");
740 vchar::append(built_argv
, _exectuble_with_path
.c_str());
742 for (Options::const_iterator iter
= _options
.begin(); iter
!= _options
.end(); ++iter
)
744 vchar::append(built_argv
, (*iter
).first
.c_str());
745 if ((*iter
).second
.empty() == false)
747 vchar::append(built_argv
, (*iter
).second
.c_str());
753 for (const char **ptr
= args
; *ptr
; ++ptr
)
755 vchar::append(built_argv
, *ptr
);
758 built_argv
.push_back(NULL
);
761 std::string
Application::print()
763 return print_argv(built_argv
);
766 std::string
Application::arguments()
768 std::stringstream arg_buffer
;
770 // Skip printing out the libtool reference
771 for (size_t x
= _use_libtool
? 2 : 0; x
< _argc
; ++x
)
775 arg_buffer
<< built_argv
[x
] << " ";
779 return arg_buffer
.str();
782 void Application::delete_argv()
784 std::for_each(built_argv
.begin(), built_argv
.end(), FreeFromVector());
791 int exec_cmdline(const std::string
& command
, const char *args
[], bool use_libtool
)
793 Application
app(command
, use_libtool
);
795 Application::error_t ret
= app
.run(args
);
797 if (ret
!= Application::SUCCESS
)
802 return int(app
.join());
805 const char *gearmand_binary()
807 return GEARMAND_BINARY
;
810 const char *drizzled_binary()
812 return DRIZZLED_BINARY
;
815 } // namespace exec_cmdline