Osx fixes.
[awesomized/libmemcached] / libtest / cmdline.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * libtest
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <config.h>
23 #include <libtest/common.h>
24
25 using namespace libtest;
26
27 #include <cstdlib>
28 #include <cstring>
29 #include <cerrno>
30 #include <fcntl.h>
31 #include <fstream>
32 #include <memory>
33 #include <poll.h>
34 #include <spawn.h>
35 #include <sstream>
36 #include <string>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39
40 extern "C" {
41 static int exited_successfully(int status)
42 {
43 if (status == 0)
44 {
45 return EXIT_SUCCESS;
46 }
47
48 if (WIFEXITED(status) == true)
49 {
50 return WEXITSTATUS(status);
51 }
52 else if (WIFSIGNALED(status) == true)
53 {
54 return WTERMSIG(status);
55 }
56
57 return EXIT_FAILURE;
58 }
59 }
60
61 namespace {
62
63 std::string print_argv(char * * & built_argv, const size_t& argc)
64 {
65 std::stringstream arg_buffer;
66
67 for (size_t x= 0; x < argc; x++)
68 {
69 arg_buffer << built_argv[x] << " ";
70 }
71
72 return arg_buffer.str();
73 }
74
75 std::string print_argv(char** argv)
76 {
77 std::stringstream arg_buffer;
78
79 for (char** ptr= argv; *ptr; ptr++)
80 {
81 arg_buffer << *ptr << " ";
82 }
83
84 return arg_buffer.str();
85 }
86
87 static Application::error_t int_to_error_t(int arg)
88 {
89 switch (arg)
90 {
91 case 127:
92 return Application::INVALID;
93
94 case 0:
95 return Application::SUCCESS;
96
97 default:
98 case 1:
99 return Application::FAILURE;
100 }
101 }
102 }
103
104 namespace libtest {
105
106 Application::Application(const std::string& arg, const bool _use_libtool_arg) :
107 _use_libtool(_use_libtool_arg),
108 _use_valgrind(false),
109 _use_gdb(false),
110 _argc(0),
111 _exectuble(arg),
112 built_argv(NULL),
113 _pid(-1)
114 {
115 if (_use_libtool)
116 {
117 if (libtool() == NULL)
118 {
119 throw "libtool requested, but know libtool was found";
120 }
121 }
122
123 // Find just the name of the application with no path
124 {
125 size_t found= arg.find_last_of("/\\");
126 if (found)
127 {
128 _exectuble_name= arg.substr(found +1);
129 }
130 else
131 {
132 _exectuble_name= arg;
133 }
134 }
135
136 if (_use_libtool and getenv("PWD"))
137 {
138 _exectuble_with_path+= getenv("PWD");
139 _exectuble_with_path+= "/";
140 }
141 _exectuble_with_path+= _exectuble;
142 }
143
144 Application::~Application()
145 {
146 delete_argv();
147 }
148
149 Application::error_t Application::run(const char *args[])
150 {
151 stdin_fd.reset();
152 stdout_fd.reset();
153 stderr_fd.reset();
154 _stdout_buffer.clear();
155 _stderr_buffer.clear();
156
157 posix_spawn_file_actions_t file_actions;
158 posix_spawn_file_actions_init(&file_actions);
159
160 stdin_fd.dup_for_spawn(Application::Pipe::READ, file_actions, STDIN_FILENO);
161 stdout_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDOUT_FILENO);
162 stderr_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDERR_FILENO);
163
164 create_argv(args);
165
166 int spawn_ret;
167 if (_use_gdb)
168 {
169 std::string gdb_run_file= create_tmpfile(_exectuble_name);
170 std::fstream file_stream;
171 file_stream.open(gdb_run_file.c_str(), std::fstream::out | std::fstream::trunc);
172
173 _gdb_filename= create_tmpfile(_exectuble_name);
174 file_stream
175 << "set logging redirect on" << std::endl
176 << "set logging file " << _gdb_filename << std::endl
177 << "set logging overwrite on" << std::endl
178 << "set logging on" << std::endl
179 << "set environment LIBTEST_IN_GDB=1" << std::endl
180 << "run " << arguments() << std::endl
181 << "thread apply all bt" << std::endl
182 << "quit" << std::endl;
183
184 fatal_assert(file_stream.good());
185 file_stream.close();
186
187 if (_use_libtool)
188 {
189 // libtool --mode=execute gdb -f -x binary
190 char *argv[]= {
191 const_cast<char *>(libtool()),
192 const_cast<char *>("--mode=execute"),
193 const_cast<char *>("gdb"),
194 const_cast<char *>("-batch"),
195 const_cast<char *>("-f"),
196 const_cast<char *>("-x"),
197 const_cast<char *>(gdb_run_file.c_str()),
198 const_cast<char *>(_exectuble_with_path.c_str()),
199 0};
200
201 spawn_ret= posix_spawnp(&_pid, libtool(), &file_actions, NULL, argv, NULL);
202 }
203 else
204 {
205 // gdb binary
206 char *argv[]= {
207 const_cast<char *>("gdb"),
208 const_cast<char *>("-batch"),
209 const_cast<char *>("-f"),
210 const_cast<char *>("-x"),
211 const_cast<char *>(gdb_run_file.c_str()),
212 const_cast<char *>(_exectuble_with_path.c_str()),
213 0};
214 spawn_ret= posix_spawnp(&_pid, "gdb", &file_actions, NULL, argv, NULL);
215 }
216 }
217 else
218 {
219 if (_use_libtool)
220 {
221 spawn_ret= posix_spawn(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
222 }
223 else
224 {
225 spawn_ret= posix_spawnp(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
226 }
227 }
228
229 posix_spawn_file_actions_destroy(&file_actions);
230
231 stdin_fd.close(Application::Pipe::READ);
232 stdout_fd.close(Application::Pipe::WRITE);
233 stderr_fd.close(Application::Pipe::WRITE);
234
235 if (spawn_ret)
236 {
237 return Application::INVALID;
238 }
239
240 return Application::SUCCESS;
241 }
242
243 bool Application::check() const
244 {
245 Error << "Testing " << _exectuble;
246 if (kill(_pid, 0) == 0)
247 {
248 return true;
249 }
250
251 return false;
252 }
253
254 void Application::murder()
255 {
256 slurp();
257 kill(_pid, SIGTERM);
258 }
259
260 // false means that no data was returned
261 bool Application::slurp()
262 {
263 struct pollfd fds[2];
264 fds[0].fd= stdout_fd.fd()[0];
265 fds[0].events= POLLIN;
266 fds[0].revents= 0;
267 fds[1].fd= stderr_fd.fd()[0];
268 fds[1].events= POLLIN;
269 fds[1].revents= 0;
270
271 int active_fd;
272 if ((active_fd= poll(fds, 2, 400)) == -1)
273 {
274 int error;
275 switch ((error= errno))
276 {
277 #ifdef TARGET_OS_LINUX
278 case ERESTART:
279 #endif
280 case EINTR:
281 break;
282
283 case EFAULT:
284 case ENOMEM:
285 fatal_message(strerror(error));
286 break;
287
288 case EINVAL:
289 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
290 break;
291
292 default:
293 fatal_message(strerror(error));
294 break;
295 }
296 }
297
298 if (active_fd == 0)
299 {
300 return false;
301 }
302
303 if (fds[0].revents & POLLIN)
304 {
305 ssize_t read_length;
306 char buffer[1024]= { 0 };
307 while ((read_length= ::read(stdout_fd.fd()[0], buffer, sizeof(buffer))))
308 {
309 if (read_length == -1)
310 {
311 switch(errno)
312 {
313 case EAGAIN:
314 continue;
315
316 default:
317 Error << strerror(errno);
318 break;
319 }
320
321 break;
322 }
323 _stdout_buffer.reserve(read_length +1);
324 for (size_t x= 0; x < read_length; x++)
325 {
326 _stdout_buffer.push_back(buffer[x]);
327 }
328 // @todo Suck up all output code here
329 }
330 }
331
332 if (fds[1].revents & POLLIN)
333 {
334 stderr_fd.nonblock();
335
336 ssize_t read_length;
337 char buffer[1024]= { 0 };
338 while ((read_length= ::read(stderr_fd.fd()[0], buffer, sizeof(buffer))))
339 {
340 if (read_length == -1)
341 {
342 switch(errno)
343 {
344 case EAGAIN:
345 continue;
346
347 default:
348 Error << strerror(errno);
349 break;
350 }
351
352 break;
353 }
354 _stderr_buffer.reserve(read_length +1);
355 for (size_t x= 0; x < read_length; x++)
356 {
357 _stderr_buffer.push_back(buffer[x]);
358 }
359 // @todo Suck up all errput code here
360 }
361 }
362
363 return true;
364 }
365
366 Application::error_t Application::wait()
367 {
368 fatal_assert(_pid != -1);
369
370 slurp();
371
372 error_t exit_code= FAILURE;
373 {
374 int status= 0;
375 pid_t waited_pid;
376 if ((waited_pid= waitpid(_pid, &status, 0)) == -1)
377 {
378 switch (errno)
379 {
380 case ECHILD:
381 exit_code= Application::SUCCESS;
382 break;
383
384 default:
385 Error << "Error occured while waitpid(" << strerror(errno) << ") on pid " << int(_pid);
386 }
387 }
388 else
389 {
390 if (waited_pid != _pid)
391 {
392 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Pid mismatch, %d != %d", int(waited_pid), int(_pid));
393 }
394 exit_code= int_to_error_t(exited_successfully(status));
395 }
396 }
397
398 #if 0
399 if (exit_code == Application::INVALID)
400 {
401 Error << print_argv(built_argv, _argc);
402 }
403 #endif
404
405 return exit_code;
406 }
407
408 void Application::add_long_option(const std::string& name, const std::string& option_value)
409 {
410 std::string arg(name);
411 arg+= option_value;
412 _options.push_back(std::make_pair(arg, std::string()));
413 }
414
415 void Application::add_option(const std::string& arg)
416 {
417 _options.push_back(std::make_pair(arg, std::string()));
418 }
419
420 void Application::add_option(const std::string& name, const std::string& value)
421 {
422 _options.push_back(std::make_pair(name, value));
423 }
424
425 Application::Pipe::Pipe()
426 {
427 _fd[0]= -1;
428 _fd[1]= -1;
429 _open[0]= false;
430 _open[1]= false;
431 }
432
433 void Application::Pipe::nonblock()
434 {
435 int ret;
436 if ((ret= fcntl(_fd[0], F_GETFL, 0)) == -1)
437 {
438 Error << "fcntl(F_GETFL) " << strerror(errno);
439 throw strerror(errno);
440 }
441
442 if ((ret= fcntl(_fd[0], F_SETFL, ret | O_NONBLOCK)) == -1)
443 {
444 Error << "fcntl(F_SETFL) " << strerror(errno);
445 throw strerror(errno);
446 }
447 }
448
449 void Application::Pipe::reset()
450 {
451 close(READ);
452 close(WRITE);
453
454 if (pipe(_fd) == -1)
455 {
456 throw strerror(errno);
457 }
458 _open[0]= true;
459 _open[1]= true;
460
461 if (0)
462 {
463 nonblock();
464 }
465 }
466
467 Application::Pipe::~Pipe()
468 {
469 close(READ);
470 close(WRITE);
471 }
472
473 void Application::Pipe::dup_for_spawn(const close_t& arg, posix_spawn_file_actions_t& file_actions, const int newfildes)
474 {
475 int type= int(arg);
476
477 int ret;
478 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _fd[type], newfildes )) < 0)
479 {
480 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
481 throw strerror(ret);
482 }
483
484 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _fd[type])) < 0)
485 {
486 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
487 throw strerror(ret);
488 }
489 }
490
491 void Application::Pipe::close(const close_t& arg)
492 {
493 int type= int(arg);
494
495 if (_open[type])
496 {
497 int ret;
498 if (::close(_fd[type]) == -1)
499 {
500 Error << "close(" << strerror(errno) << ")";
501 }
502 _open[type]= false;
503 _fd[type]= -1;
504 }
505 }
506
507 void Application::create_argv(const char *args[])
508 {
509 _argc= 2 +_use_libtool ? 2 : 0; // +1 for the command, +2 for libtool/mode=execute, +1 for the NULL
510
511 if (_use_libtool)
512 {
513 _argc+= 2; // +2 for libtool --mode=execute
514 }
515
516 /*
517 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
518 */
519 if (_use_valgrind)
520 {
521 _argc+= 7;
522 }
523 else if (_use_gdb) // gdb
524 {
525 _argc+= 1;
526 }
527
528 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
529 {
530 _argc++;
531 if ((*iter).second.empty() == false)
532 {
533 _argc++;
534 }
535 }
536
537 if (args)
538 {
539 for (const char **ptr= args; *ptr; ++ptr)
540 {
541 _argc++;
542 }
543 }
544
545 delete_argv();
546 built_argv= new char * [_argc];
547
548 size_t x= 0;
549 if (_use_libtool)
550 {
551 assert(libtool());
552 built_argv[x++]= strdup(libtool());
553 built_argv[x++]= strdup("--mode=execute");
554 }
555
556 if (_use_valgrind)
557 {
558 /*
559 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
560 */
561 built_argv[x++]= strdup("valgrind");
562 built_argv[x++]= strdup("--error-exitcode=1");
563 built_argv[x++]= strdup("--leak-check=yes");
564 built_argv[x++]= strdup("--show-reachable=yes");
565 built_argv[x++]= strdup("--track-fds=yes");
566 built_argv[x++]= strdup("--malloc-fill=A5");
567 built_argv[x++]= strdup("--free-fill=DE");
568 }
569 else if (_use_gdb)
570 {
571 built_argv[x++]= strdup("gdb");
572 }
573
574 built_argv[x++]= strdup(_exectuble_with_path.c_str());
575
576 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
577 {
578 built_argv[x++]= strdup((*iter).first.c_str());
579 if ((*iter).second.empty() == false)
580 {
581 built_argv[x++]= strdup((*iter).second.c_str());
582 }
583 }
584
585 if (args)
586 {
587 for (const char **ptr= args; *ptr; ++ptr)
588 {
589 built_argv[x++]= strdup(*ptr);
590 }
591 }
592 built_argv[_argc -1]= NULL;
593 }
594
595 std::string Application::print()
596 {
597 return print_argv(built_argv, _argc);
598 }
599
600 std::string Application::arguments()
601 {
602 std::stringstream arg_buffer;
603
604 for (size_t x= 1 + _use_libtool ? 2 : 0;
605 x < _argc and built_argv[x];
606 x++)
607 {
608 arg_buffer << built_argv[x] << " ";
609 }
610
611 return arg_buffer.str();
612 }
613
614 void Application::delete_argv()
615 {
616 if (built_argv)
617 {
618 for (size_t x= 0; x < _argc; x++)
619 {
620 if (built_argv[x])
621 {
622 ::free(built_argv[x]);
623 }
624 }
625 delete[] built_argv;
626 built_argv= NULL;
627 _argc= 0;
628 }
629 }
630
631
632 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
633 {
634 Application app(command, use_libtool);
635
636 Application::error_t ret= app.run(args);
637
638 if (ret != Application::SUCCESS)
639 {
640 return int(ret);
641 }
642
643 return int(app.wait());
644 }
645
646 const char *gearmand_binary()
647 {
648 return GEARMAND_BINARY;
649 }
650
651 } // namespace exec_cmdline