[PowerPC] Add support for TAR
[deliverable/binutils-gdb.git] / gdb / nat / fork-inferior.c
CommitLineData
2090129c
SDJ
1/* Fork a Unix child process, and set up to debug it, for GDB and GDBserver.
2
e2882c85 3 Copyright (C) 1990-2018 Free Software Foundation, Inc.
2090129c
SDJ
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program 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
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20#include "common-defs.h"
21#include "fork-inferior.h"
22#include "target/waitstatus.h"
23#include "filestuff.h"
24#include "target/target.h"
25#include "common-inferior.h"
26#include "common-gdbthread.h"
27#include "signals-state-save-restore.h"
d092c5a2 28#include "gdb_tilde_expand.h"
2090129c
SDJ
29#include <vector>
30
31extern char **environ;
32
33/* Default shell file to be used if 'startup-with-shell' is set but
34 $SHELL is not. */
35#define SHELL_FILE "/bin/sh"
36
37/* Build the argument vector for execv(3). */
38
39class execv_argv
40{
41public:
42 /* EXEC_FILE is the file to run. ALLARGS is a string containing the
43 arguments to the program. If starting with a shell, SHELL_FILE
44 is the shell to run. Otherwise, SHELL_FILE is NULL. */
45 execv_argv (const char *exec_file, const std::string &allargs,
46 const char *shell_file);
47
48 /* Return a pointer to the built argv, in the type expected by
49 execv. The result is (only) valid for as long as this execv_argv
50 object is live. We return a "char **" because that's the type
51 that the execv functions expect. Note that it is guaranteed that
52 the execv functions do not modify the argv[] array nor the
53 strings to which the array point. */
54 char **argv ()
55 {
56 return const_cast<char **> (&m_argv[0]);
57 }
58
59private:
d6541620 60 DISABLE_COPY_AND_ASSIGN (execv_argv);
2090129c
SDJ
61
62 /* Helper methods for constructing the argument vector. */
63
64 /* Used when building an argv for a straight execv call, without
65 going via the shell. */
66 void init_for_no_shell (const char *exec_file,
67 const std::string &allargs);
68
69 /* Used when building an argv for execing a shell that execs the
70 child program. */
71 void init_for_shell (const char *exec_file,
72 const std::string &allargs,
73 const char *shell_file);
74
75 /* The argument vector built. Holds non-owning pointers. Elements
76 either point to the strings passed to the execv_argv ctor, or
77 inside M_STORAGE. */
78 std::vector<const char *> m_argv;
79
80 /* Storage. In the no-shell case, this contains a copy of the
81 arguments passed to the ctor, split by '\0'. In the shell case,
82 this contains the quoted shell command. I.e., SHELL_COMMAND in
83 {"$SHELL" "-c", SHELL_COMMAND, NULL}. */
84 std::string m_storage;
85};
86
87/* Create argument vector for straight call to execvp. Breaks up
88 ALLARGS into an argument vector suitable for passing to execvp and
89 stores it in M_ARGV. E.g., on "run a b c d" this routine would get
90 as input the string "a b c d", and as output it would fill in
91 M_ARGV with the four arguments "a", "b", "c", "d". Each argument
92 in M_ARGV points to a substring of a copy of ALLARGS stored in
93 M_STORAGE. */
94
95void
96execv_argv::init_for_no_shell (const char *exec_file,
97 const std::string &allargs)
98{
99
100 /* Save/work with a copy stored in our storage. The pointers pushed
101 to M_ARGV point directly into M_STORAGE, which is modified in
102 place with the necessary NULL terminators. This avoids N heap
103 allocations and string dups when 1 is sufficient. */
104 std::string &args_copy = m_storage = allargs;
105
106 m_argv.push_back (exec_file);
107
108 for (size_t cur_pos = 0; cur_pos < args_copy.size ();)
109 {
110 /* Skip whitespace-like chars. */
111 std::size_t pos = args_copy.find_first_not_of (" \t\n", cur_pos);
112
113 if (pos != std::string::npos)
114 cur_pos = pos;
115
116 /* Find the position of the next separator. */
117 std::size_t next_sep = args_copy.find_first_of (" \t\n", cur_pos);
118
119 if (next_sep == std::string::npos)
120 {
121 /* No separator found, which means this is the last
122 argument. */
123 next_sep = args_copy.size ();
124 }
125 else
126 {
127 /* Replace the separator with a terminator. */
128 args_copy[next_sep++] = '\0';
129 }
130
131 m_argv.push_back (&args_copy[cur_pos]);
132
133 cur_pos = next_sep;
134 }
135
136 /* NULL-terminate the vector. */
137 m_argv.push_back (NULL);
138}
139
140/* When executing a command under the given shell, return true if the
141 '!' character should be escaped when embedded in a quoted
142 command-line argument. */
143
144static bool
145escape_bang_in_quoted_argument (const char *shell_file)
146{
147 size_t shell_file_len = strlen (shell_file);
148
149 /* Bang should be escaped only in C Shells. For now, simply check
150 that the shell name ends with 'csh', which covers at least csh
151 and tcsh. This should be good enough for now. */
152
153 if (shell_file_len < 3)
154 return false;
155
156 if (shell_file[shell_file_len - 3] == 'c'
157 && shell_file[shell_file_len - 2] == 's'
158 && shell_file[shell_file_len - 1] == 'h')
159 return true;
160
161 return false;
162}
163
164/* See declaration. */
165
166execv_argv::execv_argv (const char *exec_file,
167 const std::string &allargs,
168 const char *shell_file)
169{
170 if (shell_file == NULL)
171 init_for_no_shell (exec_file, allargs);
172 else
173 init_for_shell (exec_file, allargs, shell_file);
174}
175
176/* See declaration. */
177
178void
179execv_argv::init_for_shell (const char *exec_file,
180 const std::string &allargs,
181 const char *shell_file)
182{
183 const char *exec_wrapper = get_exec_wrapper ();
184
185 /* We're going to call a shell. */
186 bool escape_bang = escape_bang_in_quoted_argument (shell_file);
187
188 /* We need to build a new shell command string, and make argv point
189 to it. So build it in the storage. */
190 std::string &shell_command = m_storage;
191
192 shell_command = "exec ";
193
194 /* Add any exec wrapper. That may be a program name with arguments,
195 so the user must handle quoting. */
196 if (exec_wrapper != NULL)
197 {
198 shell_command += exec_wrapper;
199 shell_command += ' ';
200 }
201
202 /* Now add exec_file, quoting as necessary. */
203
204 /* Quoting in this style is said to work with all shells. But csh
205 on IRIX 4.0.1 can't deal with it. So we only quote it if we need
206 to. */
207 bool need_to_quote;
208 const char *p = exec_file;
209 while (1)
210 {
211 switch (*p)
212 {
213 case '\'':
214 case '!':
215 case '"':
216 case '(':
217 case ')':
218 case '$':
219 case '&':
220 case ';':
221 case '<':
222 case '>':
223 case ' ':
224 case '\n':
225 case '\t':
226 need_to_quote = true;
227 goto end_scan;
228
229 case '\0':
230 need_to_quote = false;
231 goto end_scan;
232
233 default:
234 break;
235 }
236 ++p;
237 }
238 end_scan:
239 if (need_to_quote)
240 {
241 shell_command += '\'';
242 for (p = exec_file; *p != '\0'; ++p)
243 {
244 if (*p == '\'')
245 shell_command += "'\\''";
246 else if (*p == '!' && escape_bang)
247 shell_command += "\\!";
248 else
249 shell_command += *p;
250 }
251 shell_command += '\'';
252 }
253 else
254 shell_command += exec_file;
255
256 shell_command += ' ' + allargs;
257
258 /* If we decided above to start up with a shell, we exec the shell.
259 "-c" says to interpret the next arg as a shell command to
260 execute, and this command is "exec <target-program> <args>". */
261 m_argv.reserve (4);
262 m_argv.push_back (shell_file);
263 m_argv.push_back ("-c");
264 m_argv.push_back (shell_command.c_str ());
265 m_argv.push_back (NULL);
266}
267
268/* Return the shell that must be used to startup the inferior. The
269 first attempt is the environment variable SHELL; if it is not set,
270 then we default to SHELL_FILE. */
271
272static const char *
273get_startup_shell ()
274{
87b240d4 275 const char *ret = getenv ("SHELL");
2090129c
SDJ
276 if (ret == NULL)
277 ret = SHELL_FILE;
278
279 return ret;
280}
281
282/* See nat/fork-inferior.h. */
283
284pid_t
285fork_inferior (const char *exec_file_arg, const std::string &allargs,
286 char **env, void (*traceme_fun) (),
287 void (*init_trace_fun) (int), void (*pre_trace_fun) (),
288 const char *shell_file_arg,
289 void (*exec_fun)(const char *file, char * const *argv,
290 char * const *env))
291{
292 pid_t pid;
293 /* Set debug_fork then attach to the child while it sleeps, to debug. */
294 int debug_fork = 0;
295 const char *shell_file;
296 const char *exec_file;
297 char **save_our_env;
298 int i;
299 int save_errno;
d092c5a2
SDJ
300 const char *inferior_cwd;
301 std::string expanded_inferior_cwd;
2090129c
SDJ
302
303 /* If no exec file handed to us, get it from the exec-file command
304 -- with a good, common error message if none is specified. */
305 if (exec_file_arg == NULL)
306 exec_file = get_exec_file (1);
307 else
308 exec_file = exec_file_arg;
309
310 /* 'startup_with_shell' is declared in inferior.h and bound to the
311 "set startup-with-shell" option. If 0, we'll just do a
312 fork/exec, no shell, so don't bother figuring out what shell. */
313 if (startup_with_shell)
314 {
315 shell_file = shell_file_arg;
316
317 /* Figure out what shell to start up the user program under. */
318 if (shell_file == NULL)
319 shell_file = get_startup_shell ();
320
321 gdb_assert (shell_file != NULL);
322 }
323 else
324 shell_file = NULL;
325
326 /* Build the argument vector. */
327 execv_argv child_argv (exec_file, allargs, shell_file);
328
329 /* Retain a copy of our environment variables, since the child will
330 replace the value of environ and if we're vforked, we have to
331 restore it. */
332 save_our_env = environ;
333
334 /* Perform any necessary actions regarding to TTY before the
335 fork/vfork call. */
336 prefork_hook (allargs.c_str ());
337
338 /* It is generally good practice to flush any possible pending stdio
339 output prior to doing a fork, to avoid the possibility of both
340 the parent and child flushing the same data after the fork. */
341 gdb_flush_out_err ();
342
d092c5a2
SDJ
343 /* Check if the user wants to set a different working directory for
344 the inferior. */
345 inferior_cwd = get_inferior_cwd ();
346
347 if (inferior_cwd != NULL)
348 {
349 /* Expand before forking because between fork and exec, the child
350 process may only execute async-signal-safe operations. */
351 expanded_inferior_cwd = gdb_tilde_expand (inferior_cwd);
352 inferior_cwd = expanded_inferior_cwd.c_str ();
353 }
354
2090129c
SDJ
355 /* If there's any initialization of the target layers that must
356 happen to prepare to handle the child we're about fork, do it
357 now... */
358 if (pre_trace_fun != NULL)
359 (*pre_trace_fun) ();
360
361 /* Create the child process. Since the child process is going to
362 exec(3) shortly afterwards, try to reduce the overhead by
363 calling vfork(2). However, if PRE_TRACE_FUN is non-null, it's
364 likely that this optimization won't work since there's too much
365 work to do between the vfork(2) and the exec(3). This is known
366 to be the case on ttrace(2)-based HP-UX, where some handshaking
367 between parent and child needs to happen between fork(2) and
368 exec(2). However, since the parent is suspended in the vforked
369 state, this doesn't work. Also note that the vfork(2) call might
370 actually be a call to fork(2) due to the fact that autoconf will
371 ``#define vfork fork'' on certain platforms. */
372#if !(defined(__UCLIBC__) && defined(HAS_NOMMU))
373 if (pre_trace_fun || debug_fork)
374 pid = fork ();
375 else
376#endif
377 pid = vfork ();
378
379 if (pid < 0)
380 perror_with_name (("vfork"));
381
382 if (pid == 0)
383 {
384 /* Close all file descriptors except those that gdb inherited
385 (usually 0/1/2), so they don't leak to the inferior. Note
386 that this closes the file descriptors of all secondary
387 UIs. */
388 close_most_fds ();
389
d092c5a2
SDJ
390 /* Change to the requested working directory if the user
391 requested it. */
392 if (inferior_cwd != NULL)
393 {
394 if (chdir (inferior_cwd) < 0)
395 trace_start_error_with_name (inferior_cwd);
396 }
397
2090129c
SDJ
398 if (debug_fork)
399 sleep (debug_fork);
400
401 /* Execute any necessary post-fork actions before we exec. */
402 postfork_child_hook ();
403
404 /* Changing the signal handlers for the inferior after
405 a vfork can also change them for the superior, so we don't mess
406 with signals here. See comments in
407 initialize_signals for how we get the right signal handlers
408 for the inferior. */
409
410 /* "Trace me, Dr. Memory!" */
411 (*traceme_fun) ();
412
413 /* The call above set this process (the "child") as debuggable
414 by the original gdb process (the "parent"). Since processes
415 (unlike people) can have only one parent, if you are debugging
416 gdb itself (and your debugger is thus _already_ the
417 controller/parent for this child), code from here on out is
418 undebuggable. Indeed, you probably got an error message
419 saying "not parent". Sorry; you'll have to use print
420 statements! */
421
422 restore_original_signals_state ();
423
424 /* There is no execlpe call, so we have to set the environment
425 for our child in the global variable. If we've vforked, this
426 clobbers the parent, but environ is restored a few lines down
427 in the parent. By the way, yes we do need to look down the
428 path to find $SHELL. Rich Pixley says so, and I agree. */
429 environ = env;
430
431 char **argv = child_argv.argv ();
432
433 if (exec_fun != NULL)
434 (*exec_fun) (argv[0], &argv[0], env);
435 else
436 execvp (argv[0], &argv[0]);
437
438 /* If we get here, it's an error. */
439 save_errno = errno;
440 warning ("Cannot exec %s", argv[0]);
441
442 for (i = 1; argv[i] != NULL; i++)
443 warning (" %s", argv[i]);
444
445 warning ("Error: %s\n", safe_strerror (save_errno));
446
447 _exit (0177);
448 }
449
450 /* Restore our environment in case a vforked child clob'd it. */
451 environ = save_our_env;
452
453 postfork_hook (pid);
454
455 /* Now that we have a child process, make it our target, and
456 initialize anything target-vector-specific that needs
457 initializing. */
458 if (init_trace_fun)
459 (*init_trace_fun) (pid);
460
461 /* We are now in the child process of interest, having exec'd the
462 correct program, and are poised at the first instruction of the
463 new program. */
464 return pid;
465}
466
467/* See nat/fork-inferior.h. */
468
469ptid_t
470startup_inferior (pid_t pid, int ntraps,
471 struct target_waitstatus *last_waitstatus,
472 ptid_t *last_ptid)
473{
474 int pending_execs = ntraps;
475 int terminal_initted = 0;
476 ptid_t resume_ptid;
477
478 if (startup_with_shell)
479 {
480 /* One trap extra for exec'ing the shell. */
481 pending_execs++;
482 }
483
484 if (target_supports_multi_process ())
f2907e49 485 resume_ptid = ptid_t (pid);
2090129c
SDJ
486 else
487 resume_ptid = minus_one_ptid;
488
489 /* The process was started by the fork that created it, but it will
490 have stopped one instruction after execing the shell. Here we
491 must get it up to actual execution of the real program. */
492 if (get_exec_wrapper () != NULL)
493 pending_execs++;
494
495 while (1)
496 {
497 enum gdb_signal resume_signal = GDB_SIGNAL_0;
498 ptid_t event_ptid;
499
500 struct target_waitstatus ws;
501 memset (&ws, 0, sizeof (ws));
502 event_ptid = target_wait (resume_ptid, &ws, 0);
503
504 if (last_waitstatus != NULL)
505 *last_waitstatus = ws;
506 if (last_ptid != NULL)
507 *last_ptid = event_ptid;
508
509 if (ws.kind == TARGET_WAITKIND_IGNORE)
510 /* The inferior didn't really stop, keep waiting. */
511 continue;
512
513 switch (ws.kind)
514 {
515 case TARGET_WAITKIND_SPURIOUS:
516 case TARGET_WAITKIND_LOADED:
517 case TARGET_WAITKIND_FORKED:
518 case TARGET_WAITKIND_VFORKED:
519 case TARGET_WAITKIND_SYSCALL_ENTRY:
520 case TARGET_WAITKIND_SYSCALL_RETURN:
521 /* Ignore gracefully during startup of the inferior. */
522 switch_to_thread (event_ptid);
523 break;
524
525 case TARGET_WAITKIND_SIGNALLED:
223ffa71 526 target_terminal::ours ();
2090129c
SDJ
527 target_mourn_inferior (event_ptid);
528 error (_("During startup program terminated with signal %s, %s."),
529 gdb_signal_to_name (ws.value.sig),
530 gdb_signal_to_string (ws.value.sig));
531 return resume_ptid;
532
533 case TARGET_WAITKIND_EXITED:
223ffa71 534 target_terminal::ours ();
2090129c
SDJ
535 target_mourn_inferior (event_ptid);
536 if (ws.value.integer)
537 error (_("During startup program exited with code %d."),
538 ws.value.integer);
539 else
540 error (_("During startup program exited normally."));
541 return resume_ptid;
542
543 case TARGET_WAITKIND_EXECD:
544 /* Handle EXEC signals as if they were SIGTRAP signals. */
545 xfree (ws.value.execd_pathname);
546 resume_signal = GDB_SIGNAL_TRAP;
547 switch_to_thread (event_ptid);
548 break;
549
550 case TARGET_WAITKIND_STOPPED:
551 resume_signal = ws.value.sig;
552 switch_to_thread (event_ptid);
553 break;
554 }
555
556 if (resume_signal != GDB_SIGNAL_TRAP)
557 {
558 /* Let shell child handle its own signals in its own way. */
559 target_continue (resume_ptid, resume_signal);
560 }
561 else
562 {
563 /* We handle SIGTRAP, however; it means child did an exec. */
564 if (!terminal_initted)
565 {
566 /* Now that the child has exec'd we know it has already
567 set its process group. On POSIX systems, tcsetpgrp
568 will fail with EPERM if we try it before the child's
569 setpgid. */
570
571 /* Set up the "saved terminal modes" of the inferior
572 based on what modes we are starting it with. */
223ffa71 573 target_terminal::init ();
2090129c
SDJ
574
575 /* Install inferior's terminal modes. */
223ffa71 576 target_terminal::inferior ();
2090129c
SDJ
577
578 terminal_initted = 1;
579 }
580
581 if (--pending_execs == 0)
582 break;
583
584 /* Just make it go on. */
585 target_continue_no_signal (resume_ptid);
586 }
587 }
588
589 return resume_ptid;
590}
591
592/* See nat/fork-inferior.h. */
593
594void
595trace_start_error (const char *fmt, ...)
596{
597 va_list ap;
598
599 va_start (ap, fmt);
600 warning ("Could not trace the inferior process.\nError: ");
601 vwarning (fmt, ap);
602 va_end (ap);
603
604 gdb_flush_out_err ();
605 _exit (0177);
606}
607
608/* See nat/fork-inferior.h. */
609
610void
611trace_start_error_with_name (const char *string)
612{
613 trace_start_error ("%s: %s", string, safe_strerror (errno));
614}
This page took 0.193515 seconds and 4 git commands to generate.