OSDN Git Service

d033a7db6ec990d568440554a7c4ddcd1ffa9964
[pf3gnuchains/pf3gnuchains3x.git] / gdb / gdbserver / linux-low.c
1 /* Low level interface to ptrace, for the remote server for GDB.
2    Copyright (C) 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3    2006, 2007 Free Software Foundation, Inc.
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 "server.h"
21 #include "linux-low.h"
22
23 #include <sys/wait.h>
24 #include <stdio.h>
25 #include <sys/param.h>
26 #include <sys/dir.h>
27 #include <sys/ptrace.h>
28 #include <sys/user.h>
29 #include <signal.h>
30 #include <sys/ioctl.h>
31 #include <fcntl.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <sys/syscall.h>
37 #include <sched.h>
38
39 #ifndef PTRACE_GETSIGINFO
40 # define PTRACE_GETSIGINFO 0x4202
41 # define PTRACE_SETSIGINFO 0x4203
42 #endif
43
44 #ifndef O_LARGEFILE
45 #define O_LARGEFILE 0
46 #endif
47
48 /* If the system headers did not provide the constants, hard-code the normal
49    values.  */
50 #ifndef PTRACE_EVENT_FORK
51
52 #define PTRACE_SETOPTIONS       0x4200
53 #define PTRACE_GETEVENTMSG      0x4201
54
55 /* options set using PTRACE_SETOPTIONS */
56 #define PTRACE_O_TRACESYSGOOD   0x00000001
57 #define PTRACE_O_TRACEFORK      0x00000002
58 #define PTRACE_O_TRACEVFORK     0x00000004
59 #define PTRACE_O_TRACECLONE     0x00000008
60 #define PTRACE_O_TRACEEXEC      0x00000010
61 #define PTRACE_O_TRACEVFORKDONE 0x00000020
62 #define PTRACE_O_TRACEEXIT      0x00000040
63
64 /* Wait extended result codes for the above trace options.  */
65 #define PTRACE_EVENT_FORK       1
66 #define PTRACE_EVENT_VFORK      2
67 #define PTRACE_EVENT_CLONE      3
68 #define PTRACE_EVENT_EXEC       4
69 #define PTRACE_EVENT_VFORK_DONE 5
70 #define PTRACE_EVENT_EXIT       6
71
72 #endif /* PTRACE_EVENT_FORK */
73
74 /* We can't always assume that this flag is available, but all systems
75    with the ptrace event handlers also have __WALL, so it's safe to use
76    in some contexts.  */
77 #ifndef __WALL
78 #define __WALL          0x40000000 /* Wait for any child.  */
79 #endif
80
81 #ifdef __UCLIBC__
82 #if !(defined(__UCLIBC_HAS_MMU__) || defined(__ARCH_HAS_MMU__))
83 #define HAS_NOMMU
84 #endif
85 #endif
86
87 /* ``all_threads'' is keyed by the LWP ID, which we use as the GDB protocol
88    representation of the thread ID.
89
90    ``all_processes'' is keyed by the process ID - which on Linux is (presently)
91    the same as the LWP ID.  */
92
93 struct inferior_list all_processes;
94
95 /* A list of all unknown processes which receive stop signals.  Some other
96    process will presumably claim each of these as forked children
97    momentarily.  */
98
99 struct inferior_list stopped_pids;
100
101 /* FIXME this is a bit of a hack, and could be removed.  */
102 int stopping_threads;
103
104 /* FIXME make into a target method?  */
105 int using_threads = 1;
106 static int thread_db_active;
107
108 static int must_set_ptrace_flags;
109
110 static void linux_resume_one_process (struct inferior_list_entry *entry,
111                                       int step, int signal, siginfo_t *info);
112 static void linux_resume (struct thread_resume *resume_info);
113 static void stop_all_processes (void);
114 static int linux_wait_for_event (struct thread_info *child);
115 static int check_removed_breakpoint (struct process_info *event_child);
116 static void *add_process (unsigned long pid);
117
118 struct pending_signals
119 {
120   int signal;
121   siginfo_t info;
122   struct pending_signals *prev;
123 };
124
125 #define PTRACE_ARG3_TYPE long
126 #define PTRACE_XFER_TYPE long
127
128 #ifdef HAVE_LINUX_REGSETS
129 static int use_regsets_p = 1;
130 #endif
131
132 #define pid_of(proc) ((proc)->head.id)
133
134 /* FIXME: Delete eventually.  */
135 #define inferior_pid (pid_of (get_thread_process (current_inferior)))
136
137 static void
138 handle_extended_wait (struct process_info *event_child, int wstat)
139 {
140   int event = wstat >> 16;
141   struct process_info *new_process;
142
143   if (event == PTRACE_EVENT_CLONE)
144     {
145       unsigned long new_pid;
146       int ret, status;
147
148       ptrace (PTRACE_GETEVENTMSG, inferior_pid, 0, &new_pid);
149
150       /* If we haven't already seen the new PID stop, wait for it now.  */
151       if (! pull_pid_from_list (&stopped_pids, new_pid))
152         {
153           /* The new child has a pending SIGSTOP.  We can't affect it until it
154              hits the SIGSTOP, but we're already attached.  */
155
156           do {
157             ret = waitpid (new_pid, &status, __WALL);
158           } while (ret == -1 && errno == EINTR);
159
160           if (ret == -1)
161             perror_with_name ("waiting for new child");
162           else if (ret != new_pid)
163             warning ("wait returned unexpected PID %d", ret);
164           else if (!WIFSTOPPED (status))
165             warning ("wait returned unexpected status 0x%x", status);
166         }
167
168       ptrace (PTRACE_SETOPTIONS, new_pid, 0, PTRACE_O_TRACECLONE);
169
170       new_process = (struct process_info *) add_process (new_pid);
171       add_thread (new_pid, new_process, new_pid);
172       new_thread_notify (thread_id_to_gdb_id (new_process->lwpid));
173
174       /* Normally we will get the pending SIGSTOP.  But in some cases
175          we might get another signal delivered to the group first.
176          If we do, be sure not to lose it.  */
177       if (WSTOPSIG (status) == SIGSTOP)
178         {
179           if (stopping_threads)
180             new_process->stopped = 1;
181           else
182             ptrace (PTRACE_CONT, new_pid, 0, 0);
183         }
184       else
185         {
186           new_process->stop_expected = 1;
187           if (stopping_threads)
188             {
189               new_process->stopped = 1;
190               new_process->status_pending_p = 1;
191               new_process->status_pending = status;
192             }
193           else
194             /* Pass the signal on.  This is what GDB does - except
195                shouldn't we really report it instead?  */
196             ptrace (PTRACE_CONT, new_pid, 0, WSTOPSIG (status));
197         }
198
199       /* Always resume the current thread.  If we are stopping
200          threads, it will have a pending SIGSTOP; we may as well
201          collect it now.  */
202       linux_resume_one_process (&event_child->head,
203                                 event_child->stepping, 0, NULL);
204     }
205 }
206
207 /* This function should only be called if the process got a SIGTRAP.
208    The SIGTRAP could mean several things.
209
210    On i386, where decr_pc_after_break is non-zero:
211    If we were single-stepping this process using PTRACE_SINGLESTEP,
212    we will get only the one SIGTRAP (even if the instruction we
213    stepped over was a breakpoint).  The value of $eip will be the
214    next instruction.
215    If we continue the process using PTRACE_CONT, we will get a
216    SIGTRAP when we hit a breakpoint.  The value of $eip will be
217    the instruction after the breakpoint (i.e. needs to be
218    decremented).  If we report the SIGTRAP to GDB, we must also
219    report the undecremented PC.  If we cancel the SIGTRAP, we
220    must resume at the decremented PC.
221
222    (Presumably, not yet tested) On a non-decr_pc_after_break machine
223    with hardware or kernel single-step:
224    If we single-step over a breakpoint instruction, our PC will
225    point at the following instruction.  If we continue and hit a
226    breakpoint instruction, our PC will point at the breakpoint
227    instruction.  */
228
229 static CORE_ADDR
230 get_stop_pc (void)
231 {
232   CORE_ADDR stop_pc = (*the_low_target.get_pc) ();
233
234   if (get_thread_process (current_inferior)->stepping)
235     return stop_pc;
236   else
237     return stop_pc - the_low_target.decr_pc_after_break;
238 }
239
240 static void *
241 add_process (unsigned long pid)
242 {
243   struct process_info *process;
244
245   process = (struct process_info *) malloc (sizeof (*process));
246   memset (process, 0, sizeof (*process));
247
248   process->head.id = pid;
249   process->lwpid = pid;
250
251   add_inferior_to_list (&all_processes, &process->head);
252
253   return process;
254 }
255
256 /* Start an inferior process and returns its pid.
257    ALLARGS is a vector of program-name and args. */
258
259 static int
260 linux_create_inferior (char *program, char **allargs)
261 {
262   void *new_process;
263   int pid;
264
265 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
266   pid = vfork ();
267 #else
268   pid = fork ();
269 #endif
270   if (pid < 0)
271     perror_with_name ("fork");
272
273   if (pid == 0)
274     {
275       ptrace (PTRACE_TRACEME, 0, 0, 0);
276
277       signal (__SIGRTMIN + 1, SIG_DFL);
278
279       setpgid (0, 0);
280
281       execv (program, allargs);
282       if (errno == ENOENT)
283         execvp (program, allargs);
284
285       fprintf (stderr, "Cannot exec %s: %s.\n", program,
286                strerror (errno));
287       fflush (stderr);
288       _exit (0177);
289     }
290
291   new_process = add_process (pid);
292   add_thread (pid, new_process, pid);
293   must_set_ptrace_flags = 1;
294
295   return pid;
296 }
297
298 /* Attach to an inferior process.  */
299
300 void
301 linux_attach_lwp (unsigned long pid)
302 {
303   struct process_info *new_process;
304
305   if (ptrace (PTRACE_ATTACH, pid, 0, 0) != 0)
306     {
307       fprintf (stderr, "Cannot attach to process %ld: %s (%d)\n", pid,
308                strerror (errno), errno);
309       fflush (stderr);
310
311       /* If we fail to attach to an LWP, just return.  */
312       if (all_threads.head == NULL)
313         _exit (0177);
314       return;
315     }
316
317   ptrace (PTRACE_SETOPTIONS, pid, 0, PTRACE_O_TRACECLONE);
318
319   new_process = (struct process_info *) add_process (pid);
320   add_thread (pid, new_process, pid);
321   new_thread_notify (thread_id_to_gdb_id (new_process->lwpid));
322
323   /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
324      brings it to a halt.  We should ignore that SIGSTOP and resume the process
325      (unless this is the first process, in which case the flag will be cleared
326      in linux_attach).
327
328      On the other hand, if we are currently trying to stop all threads, we
329      should treat the new thread as if we had sent it a SIGSTOP.  This works
330      because we are guaranteed that add_process added us to the end of the
331      list, and so the new thread has not yet reached wait_for_sigstop (but
332      will).  */
333   if (! stopping_threads)
334     new_process->stop_expected = 1;
335 }
336
337 int
338 linux_attach (unsigned long pid)
339 {
340   struct process_info *process;
341
342   linux_attach_lwp (pid);
343
344   /* Don't ignore the initial SIGSTOP if we just attached to this process.
345      It will be collected by wait shortly.  */
346   process = (struct process_info *) find_inferior_id (&all_processes, pid);
347   process->stop_expected = 0;
348
349   return 0;
350 }
351
352 /* Kill the inferior process.  Make us have no inferior.  */
353
354 static void
355 linux_kill_one_process (struct inferior_list_entry *entry)
356 {
357   struct thread_info *thread = (struct thread_info *) entry;
358   struct process_info *process = get_thread_process (thread);
359   int wstat;
360
361   /* We avoid killing the first thread here, because of a Linux kernel (at
362      least 2.6.0-test7 through 2.6.8-rc4) bug; if we kill the parent before
363      the children get a chance to be reaped, it will remain a zombie
364      forever.  */
365   if (entry == all_threads.head)
366     return;
367
368   do
369     {
370       ptrace (PTRACE_KILL, pid_of (process), 0, 0);
371
372       /* Make sure it died.  The loop is most likely unnecessary.  */
373       wstat = linux_wait_for_event (thread);
374     } while (WIFSTOPPED (wstat));
375 }
376
377 static void
378 linux_kill (void)
379 {
380   struct thread_info *thread = (struct thread_info *) all_threads.head;
381   struct process_info *process;
382   int wstat;
383
384   if (thread == NULL)
385     return;
386
387   for_each_inferior (&all_threads, linux_kill_one_process);
388
389   /* See the comment in linux_kill_one_process.  We did not kill the first
390      thread in the list, so do so now.  */
391   process = get_thread_process (thread);
392   do
393     {
394       ptrace (PTRACE_KILL, pid_of (process), 0, 0);
395
396       /* Make sure it died.  The loop is most likely unnecessary.  */
397       wstat = linux_wait_for_event (thread);
398     } while (WIFSTOPPED (wstat));
399 }
400
401 static void
402 linux_detach_one_process (struct inferior_list_entry *entry)
403 {
404   struct thread_info *thread = (struct thread_info *) entry;
405   struct process_info *process = get_thread_process (thread);
406
407   /* Make sure the process isn't stopped at a breakpoint that's
408      no longer there.  */
409   check_removed_breakpoint (process);
410
411   /* If this process is stopped but is expecting a SIGSTOP, then make
412      sure we take care of that now.  This isn't absolutely guaranteed
413      to collect the SIGSTOP, but is fairly likely to.  */
414   if (process->stop_expected)
415     {
416       /* Clear stop_expected, so that the SIGSTOP will be reported.  */
417       process->stop_expected = 0;
418       if (process->stopped)
419         linux_resume_one_process (&process->head, 0, 0, NULL);
420       linux_wait_for_event (thread);
421     }
422
423   /* Flush any pending changes to the process's registers.  */
424   regcache_invalidate_one ((struct inferior_list_entry *)
425                            get_process_thread (process));
426
427   /* Finally, let it resume.  */
428   ptrace (PTRACE_DETACH, pid_of (process), 0, 0);
429 }
430
431 static int
432 linux_detach (void)
433 {
434   delete_all_breakpoints ();
435   for_each_inferior (&all_threads, linux_detach_one_process);
436   clear_inferiors ();
437   return 0;
438 }
439
440 static void
441 linux_join (void)
442 {
443   extern unsigned long signal_pid;
444   int status, ret;
445
446   do {
447     ret = waitpid (signal_pid, &status, 0);
448     if (WIFEXITED (status) || WIFSIGNALED (status))
449       break;
450   } while (ret != -1 || errno != ECHILD);
451 }
452
453 /* Return nonzero if the given thread is still alive.  */
454 static int
455 linux_thread_alive (unsigned long lwpid)
456 {
457   if (find_inferior_id (&all_threads, lwpid) != NULL)
458     return 1;
459   else
460     return 0;
461 }
462
463 /* Return nonzero if this process stopped at a breakpoint which
464    no longer appears to be inserted.  Also adjust the PC
465    appropriately to resume where the breakpoint used to be.  */
466 static int
467 check_removed_breakpoint (struct process_info *event_child)
468 {
469   CORE_ADDR stop_pc;
470   struct thread_info *saved_inferior;
471
472   if (event_child->pending_is_breakpoint == 0)
473     return 0;
474
475   if (debug_threads)
476     fprintf (stderr, "Checking for breakpoint in process %ld.\n",
477              event_child->lwpid);
478
479   saved_inferior = current_inferior;
480   current_inferior = get_process_thread (event_child);
481
482   stop_pc = get_stop_pc ();
483
484   /* If the PC has changed since we stopped, then we shouldn't do
485      anything.  This happens if, for instance, GDB handled the
486      decr_pc_after_break subtraction itself.  */
487   if (stop_pc != event_child->pending_stop_pc)
488     {
489       if (debug_threads)
490         fprintf (stderr, "Ignoring, PC was changed.  Old PC was 0x%08llx\n",
491                  event_child->pending_stop_pc);
492
493       event_child->pending_is_breakpoint = 0;
494       current_inferior = saved_inferior;
495       return 0;
496     }
497
498   /* If the breakpoint is still there, we will report hitting it.  */
499   if ((*the_low_target.breakpoint_at) (stop_pc))
500     {
501       if (debug_threads)
502         fprintf (stderr, "Ignoring, breakpoint is still present.\n");
503       current_inferior = saved_inferior;
504       return 0;
505     }
506
507   if (debug_threads)
508     fprintf (stderr, "Removed breakpoint.\n");
509
510   /* For decr_pc_after_break targets, here is where we perform the
511      decrement.  We go immediately from this function to resuming,
512      and can not safely call get_stop_pc () again.  */
513   if (the_low_target.set_pc != NULL)
514     (*the_low_target.set_pc) (stop_pc);
515
516   /* We consumed the pending SIGTRAP.  */
517   event_child->pending_is_breakpoint = 0;
518   event_child->status_pending_p = 0;
519   event_child->status_pending = 0;
520
521   current_inferior = saved_inferior;
522   return 1;
523 }
524
525 /* Return 1 if this process has an interesting status pending.  This function
526    may silently resume an inferior process.  */
527 static int
528 status_pending_p (struct inferior_list_entry *entry, void *dummy)
529 {
530   struct process_info *process = (struct process_info *) entry;
531
532   if (process->status_pending_p)
533     if (check_removed_breakpoint (process))
534       {
535         /* This thread was stopped at a breakpoint, and the breakpoint
536            is now gone.  We were told to continue (or step...) all threads,
537            so GDB isn't trying to single-step past this breakpoint.
538            So instead of reporting the old SIGTRAP, pretend we got to
539            the breakpoint just after it was removed instead of just
540            before; resume the process.  */
541         linux_resume_one_process (&process->head, 0, 0, NULL);
542         return 0;
543       }
544
545   return process->status_pending_p;
546 }
547
548 static void
549 linux_wait_for_process (struct process_info **childp, int *wstatp)
550 {
551   int ret;
552   int to_wait_for = -1;
553
554   if (*childp != NULL)
555     to_wait_for = (*childp)->lwpid;
556
557 retry:
558   while (1)
559     {
560       ret = waitpid (to_wait_for, wstatp, WNOHANG);
561
562       if (ret == -1)
563         {
564           if (errno != ECHILD)
565             perror_with_name ("waitpid");
566         }
567       else if (ret > 0)
568         break;
569
570       ret = waitpid (to_wait_for, wstatp, WNOHANG | __WCLONE);
571
572       if (ret == -1)
573         {
574           if (errno != ECHILD)
575             perror_with_name ("waitpid (WCLONE)");
576         }
577       else if (ret > 0)
578         break;
579
580       usleep (1000);
581     }
582
583   if (debug_threads
584       && (!WIFSTOPPED (*wstatp)
585           || (WSTOPSIG (*wstatp) != 32
586               && WSTOPSIG (*wstatp) != 33)))
587     fprintf (stderr, "Got an event from %d (%x)\n", ret, *wstatp);
588
589   if (to_wait_for == -1)
590     *childp = (struct process_info *) find_inferior_id (&all_processes, ret);
591
592   /* If we didn't find a process, one of two things presumably happened:
593      - A process we started and then detached from has exited.  Ignore it.
594      - A process we are controlling has forked and the new child's stop
595      was reported to us by the kernel.  Save its PID.  */
596   if (*childp == NULL && WIFSTOPPED (*wstatp))
597     {
598       add_pid_to_list (&stopped_pids, ret);
599       goto retry;
600     }
601   else if (*childp == NULL)
602     goto retry;
603
604   (*childp)->stopped = 1;
605   (*childp)->pending_is_breakpoint = 0;
606
607   (*childp)->last_status = *wstatp;
608
609   if (debug_threads
610       && WIFSTOPPED (*wstatp))
611     {
612       current_inferior = (struct thread_info *)
613         find_inferior_id (&all_threads, (*childp)->lwpid);
614       /* For testing only; i386_stop_pc prints out a diagnostic.  */
615       if (the_low_target.get_pc != NULL)
616         get_stop_pc ();
617     }
618 }
619
620 static int
621 linux_wait_for_event (struct thread_info *child)
622 {
623   CORE_ADDR stop_pc;
624   struct process_info *event_child;
625   int wstat;
626   int bp_status;
627
628   /* Check for a process with a pending status.  */
629   /* It is possible that the user changed the pending task's registers since
630      it stopped.  We correctly handle the change of PC if we hit a breakpoint
631      (in check_removed_breakpoint); signals should be reported anyway.  */
632   if (child == NULL)
633     {
634       event_child = (struct process_info *)
635         find_inferior (&all_processes, status_pending_p, NULL);
636       if (debug_threads && event_child)
637         fprintf (stderr, "Got a pending child %ld\n", event_child->lwpid);
638     }
639   else
640     {
641       event_child = get_thread_process (child);
642       if (event_child->status_pending_p
643           && check_removed_breakpoint (event_child))
644         event_child = NULL;
645     }
646
647   if (event_child != NULL)
648     {
649       if (event_child->status_pending_p)
650         {
651           if (debug_threads)
652             fprintf (stderr, "Got an event from pending child %ld (%04x)\n",
653                      event_child->lwpid, event_child->status_pending);
654           wstat = event_child->status_pending;
655           event_child->status_pending_p = 0;
656           event_child->status_pending = 0;
657           current_inferior = get_process_thread (event_child);
658           return wstat;
659         }
660     }
661
662   /* We only enter this loop if no process has a pending wait status.  Thus
663      any action taken in response to a wait status inside this loop is
664      responding as soon as we detect the status, not after any pending
665      events.  */
666   while (1)
667     {
668       if (child == NULL)
669         event_child = NULL;
670       else
671         event_child = get_thread_process (child);
672
673       linux_wait_for_process (&event_child, &wstat);
674
675       if (event_child == NULL)
676         error ("event from unknown child");
677
678       current_inferior = (struct thread_info *)
679         find_inferior_id (&all_threads, event_child->lwpid);
680
681       /* Check for thread exit.  */
682       if (! WIFSTOPPED (wstat))
683         {
684           if (debug_threads)
685             fprintf (stderr, "LWP %ld exiting\n", event_child->head.id);
686
687           /* If the last thread is exiting, just return.  */
688           if (all_threads.head == all_threads.tail)
689             return wstat;
690
691           dead_thread_notify (thread_id_to_gdb_id (event_child->lwpid));
692
693           remove_inferior (&all_processes, &event_child->head);
694           free (event_child);
695           remove_thread (current_inferior);
696           current_inferior = (struct thread_info *) all_threads.head;
697
698           /* If we were waiting for this particular child to do something...
699              well, it did something.  */
700           if (child != NULL)
701             return wstat;
702
703           /* Wait for a more interesting event.  */
704           continue;
705         }
706
707       if (WIFSTOPPED (wstat)
708           && WSTOPSIG (wstat) == SIGSTOP
709           && event_child->stop_expected)
710         {
711           if (debug_threads)
712             fprintf (stderr, "Expected stop.\n");
713           event_child->stop_expected = 0;
714           linux_resume_one_process (&event_child->head,
715                                     event_child->stepping, 0, NULL);
716           continue;
717         }
718
719       if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGTRAP
720           && wstat >> 16 != 0)
721         {
722           handle_extended_wait (event_child, wstat);
723           continue;
724         }
725
726       /* If GDB is not interested in this signal, don't stop other
727          threads, and don't report it to GDB.  Just resume the
728          inferior right away.  We do this for threading-related
729          signals as well as any that GDB specifically requested we
730          ignore.  But never ignore SIGSTOP if we sent it ourselves,
731          and do not ignore signals when stepping - they may require
732          special handling to skip the signal handler.  */
733       /* FIXME drow/2002-06-09: Get signal numbers from the inferior's
734          thread library?  */
735       if (WIFSTOPPED (wstat)
736           && !event_child->stepping
737           && (
738 #ifdef USE_THREAD_DB
739               (thread_db_active && (WSTOPSIG (wstat) == __SIGRTMIN
740                                     || WSTOPSIG (wstat) == __SIGRTMIN + 1))
741               ||
742 #endif
743               (pass_signals[target_signal_from_host (WSTOPSIG (wstat))]
744                && (WSTOPSIG (wstat) != SIGSTOP || !stopping_threads))))
745         {
746           siginfo_t info, *info_p;
747
748           if (debug_threads)
749             fprintf (stderr, "Ignored signal %d for LWP %ld.\n",
750                      WSTOPSIG (wstat), event_child->head.id);
751
752           if (ptrace (PTRACE_GETSIGINFO, event_child->lwpid, 0, &info) == 0)
753             info_p = &info;
754           else
755             info_p = NULL;
756           linux_resume_one_process (&event_child->head,
757                                     event_child->stepping,
758                                     WSTOPSIG (wstat), info_p);
759           continue;
760         }
761
762       /* If this event was not handled above, and is not a SIGTRAP, report
763          it.  */
764       if (!WIFSTOPPED (wstat) || WSTOPSIG (wstat) != SIGTRAP)
765         return wstat;
766
767       /* If this target does not support breakpoints, we simply report the
768          SIGTRAP; it's of no concern to us.  */
769       if (the_low_target.get_pc == NULL)
770         return wstat;
771
772       stop_pc = get_stop_pc ();
773
774       /* bp_reinsert will only be set if we were single-stepping.
775          Notice that we will resume the process after hitting
776          a gdbserver breakpoint; single-stepping to/over one
777          is not supported (yet).  */
778       if (event_child->bp_reinsert != 0)
779         {
780           if (debug_threads)
781             fprintf (stderr, "Reinserted breakpoint.\n");
782           reinsert_breakpoint (event_child->bp_reinsert);
783           event_child->bp_reinsert = 0;
784
785           /* Clear the single-stepping flag and SIGTRAP as we resume.  */
786           linux_resume_one_process (&event_child->head, 0, 0, NULL);
787           continue;
788         }
789
790       bp_status = check_breakpoints (stop_pc);
791
792       if (bp_status != 0)
793         {
794           if (debug_threads)
795             fprintf (stderr, "Hit a gdbserver breakpoint.\n");
796
797           /* We hit one of our own breakpoints.  We mark it as a pending
798              breakpoint, so that check_removed_breakpoint () will do the PC
799              adjustment for us at the appropriate time.  */
800           event_child->pending_is_breakpoint = 1;
801           event_child->pending_stop_pc = stop_pc;
802
803           /* We may need to put the breakpoint back.  We continue in the event
804              loop instead of simply replacing the breakpoint right away,
805              in order to not lose signals sent to the thread that hit the
806              breakpoint.  Unfortunately this increases the window where another
807              thread could sneak past the removed breakpoint.  For the current
808              use of server-side breakpoints (thread creation) this is
809              acceptable; but it needs to be considered before this breakpoint
810              mechanism can be used in more general ways.  For some breakpoints
811              it may be necessary to stop all other threads, but that should
812              be avoided where possible.
813
814              If breakpoint_reinsert_addr is NULL, that means that we can
815              use PTRACE_SINGLESTEP on this platform.  Uninsert the breakpoint,
816              mark it for reinsertion, and single-step.
817
818              Otherwise, call the target function to figure out where we need
819              our temporary breakpoint, create it, and continue executing this
820              process.  */
821           if (bp_status == 2)
822             /* No need to reinsert.  */
823             linux_resume_one_process (&event_child->head, 0, 0, NULL);
824           else if (the_low_target.breakpoint_reinsert_addr == NULL)
825             {
826               event_child->bp_reinsert = stop_pc;
827               uninsert_breakpoint (stop_pc);
828               linux_resume_one_process (&event_child->head, 1, 0, NULL);
829             }
830           else
831             {
832               reinsert_breakpoint_by_bp
833                 (stop_pc, (*the_low_target.breakpoint_reinsert_addr) ());
834               linux_resume_one_process (&event_child->head, 0, 0, NULL);
835             }
836
837           continue;
838         }
839
840       if (debug_threads)
841         fprintf (stderr, "Hit a non-gdbserver breakpoint.\n");
842
843       /* If we were single-stepping, we definitely want to report the
844          SIGTRAP.  The single-step operation has completed, so also
845          clear the stepping flag; in general this does not matter,
846          because the SIGTRAP will be reported to the client, which
847          will give us a new action for this thread, but clear it for
848          consistency anyway.  It's safe to clear the stepping flag
849          because the only consumer of get_stop_pc () after this point
850          is check_removed_breakpoint, and pending_is_breakpoint is not
851          set.  It might be wiser to use a step_completed flag instead.  */
852       if (event_child->stepping)
853         {
854           event_child->stepping = 0;
855           return wstat;
856         }
857
858       /* A SIGTRAP that we can't explain.  It may have been a breakpoint.
859          Check if it is a breakpoint, and if so mark the process information
860          accordingly.  This will handle both the necessary fiddling with the
861          PC on decr_pc_after_break targets and suppressing extra threads
862          hitting a breakpoint if two hit it at once and then GDB removes it
863          after the first is reported.  Arguably it would be better to report
864          multiple threads hitting breakpoints simultaneously, but the current
865          remote protocol does not allow this.  */
866       if ((*the_low_target.breakpoint_at) (stop_pc))
867         {
868           event_child->pending_is_breakpoint = 1;
869           event_child->pending_stop_pc = stop_pc;
870         }
871
872       return wstat;
873     }
874
875   /* NOTREACHED */
876   return 0;
877 }
878
879 /* Wait for process, returns status.  */
880
881 static unsigned char
882 linux_wait (char *status)
883 {
884   int w;
885   struct thread_info *child = NULL;
886
887 retry:
888   /* If we were only supposed to resume one thread, only wait for
889      that thread - if it's still alive.  If it died, however - which
890      can happen if we're coming from the thread death case below -
891      then we need to make sure we restart the other threads.  We could
892      pick a thread at random or restart all; restarting all is less
893      arbitrary.  */
894   if (cont_thread != 0 && cont_thread != -1)
895     {
896       child = (struct thread_info *) find_inferior_id (&all_threads,
897                                                        cont_thread);
898
899       /* No stepping, no signal - unless one is pending already, of course.  */
900       if (child == NULL)
901         {
902           struct thread_resume resume_info;
903           resume_info.thread = -1;
904           resume_info.step = resume_info.sig = resume_info.leave_stopped = 0;
905           linux_resume (&resume_info);
906         }
907     }
908
909   w = linux_wait_for_event (child);
910   stop_all_processes ();
911
912   if (must_set_ptrace_flags)
913     {
914       ptrace (PTRACE_SETOPTIONS, inferior_pid, 0, PTRACE_O_TRACECLONE);
915       must_set_ptrace_flags = 0;
916     }
917
918   /* If we are waiting for a particular child, and it exited,
919      linux_wait_for_event will return its exit status.  Similarly if
920      the last child exited.  If this is not the last child, however,
921      do not report it as exited until there is a 'thread exited' response
922      available in the remote protocol.  Instead, just wait for another event.
923      This should be safe, because if the thread crashed we will already
924      have reported the termination signal to GDB; that should stop any
925      in-progress stepping operations, etc.
926
927      Report the exit status of the last thread to exit.  This matches
928      LinuxThreads' behavior.  */
929
930   if (all_threads.head == all_threads.tail)
931     {
932       if (WIFEXITED (w))
933         {
934           fprintf (stderr, "\nChild exited with retcode = %x \n", WEXITSTATUS (w));
935           *status = 'W';
936           clear_inferiors ();
937           free (all_processes.head);
938           all_processes.head = all_processes.tail = NULL;
939           return WEXITSTATUS (w);
940         }
941       else if (!WIFSTOPPED (w))
942         {
943           fprintf (stderr, "\nChild terminated with signal = %x \n", WTERMSIG (w));
944           *status = 'X';
945           clear_inferiors ();
946           free (all_processes.head);
947           all_processes.head = all_processes.tail = NULL;
948           return target_signal_from_host (WTERMSIG (w));
949         }
950     }
951   else
952     {
953       if (!WIFSTOPPED (w))
954         goto retry;
955     }
956
957   *status = 'T';
958   return target_signal_from_host (WSTOPSIG (w));
959 }
960
961 /* Send a signal to an LWP.  For LinuxThreads, kill is enough; however, if
962    thread groups are in use, we need to use tkill.  */
963
964 static int
965 kill_lwp (unsigned long lwpid, int signo)
966 {
967   static int tkill_failed;
968
969   errno = 0;
970
971 #ifdef SYS_tkill
972   if (!tkill_failed)
973     {
974       int ret = syscall (SYS_tkill, lwpid, signo);
975       if (errno != ENOSYS)
976         return ret;
977       errno = 0;
978       tkill_failed = 1;
979     }
980 #endif
981
982   return kill (lwpid, signo);
983 }
984
985 static void
986 send_sigstop (struct inferior_list_entry *entry)
987 {
988   struct process_info *process = (struct process_info *) entry;
989
990   if (process->stopped)
991     return;
992
993   /* If we already have a pending stop signal for this process, don't
994      send another.  */
995   if (process->stop_expected)
996     {
997       if (debug_threads)
998         fprintf (stderr, "Have pending sigstop for process %ld\n",
999                  process->lwpid);
1000
1001       /* We clear the stop_expected flag so that wait_for_sigstop
1002          will receive the SIGSTOP event (instead of silently resuming and
1003          waiting again).  It'll be reset below.  */
1004       process->stop_expected = 0;
1005       return;
1006     }
1007
1008   if (debug_threads)
1009     fprintf (stderr, "Sending sigstop to process %ld\n", process->head.id);
1010
1011   kill_lwp (process->head.id, SIGSTOP);
1012 }
1013
1014 static void
1015 wait_for_sigstop (struct inferior_list_entry *entry)
1016 {
1017   struct process_info *process = (struct process_info *) entry;
1018   struct thread_info *saved_inferior, *thread;
1019   int wstat;
1020   unsigned long saved_tid;
1021
1022   if (process->stopped)
1023     return;
1024
1025   saved_inferior = current_inferior;
1026   saved_tid = ((struct inferior_list_entry *) saved_inferior)->id;
1027   thread = (struct thread_info *) find_inferior_id (&all_threads,
1028                                                     process->lwpid);
1029   wstat = linux_wait_for_event (thread);
1030
1031   /* If we stopped with a non-SIGSTOP signal, save it for later
1032      and record the pending SIGSTOP.  If the process exited, just
1033      return.  */
1034   if (WIFSTOPPED (wstat)
1035       && WSTOPSIG (wstat) != SIGSTOP)
1036     {
1037       if (debug_threads)
1038         fprintf (stderr, "LWP %ld stopped with non-sigstop status %06x\n",
1039                  process->lwpid, wstat);
1040       process->status_pending_p = 1;
1041       process->status_pending = wstat;
1042       process->stop_expected = 1;
1043     }
1044
1045   if (linux_thread_alive (saved_tid))
1046     current_inferior = saved_inferior;
1047   else
1048     {
1049       if (debug_threads)
1050         fprintf (stderr, "Previously current thread died.\n");
1051
1052       /* Set a valid thread as current.  */
1053       set_desired_inferior (0);
1054     }
1055 }
1056
1057 static void
1058 stop_all_processes (void)
1059 {
1060   stopping_threads = 1;
1061   for_each_inferior (&all_processes, send_sigstop);
1062   for_each_inferior (&all_processes, wait_for_sigstop);
1063   stopping_threads = 0;
1064 }
1065
1066 /* Resume execution of the inferior process.
1067    If STEP is nonzero, single-step it.
1068    If SIGNAL is nonzero, give it that signal.  */
1069
1070 static void
1071 linux_resume_one_process (struct inferior_list_entry *entry,
1072                           int step, int signal, siginfo_t *info)
1073 {
1074   struct process_info *process = (struct process_info *) entry;
1075   struct thread_info *saved_inferior;
1076
1077   if (process->stopped == 0)
1078     return;
1079
1080   /* If we have pending signals or status, and a new signal, enqueue the
1081      signal.  Also enqueue the signal if we are waiting to reinsert a
1082      breakpoint; it will be picked up again below.  */
1083   if (signal != 0
1084       && (process->status_pending_p || process->pending_signals != NULL
1085           || process->bp_reinsert != 0))
1086     {
1087       struct pending_signals *p_sig;
1088       p_sig = malloc (sizeof (*p_sig));
1089       p_sig->prev = process->pending_signals;
1090       p_sig->signal = signal;
1091       if (info == NULL)
1092         memset (&p_sig->info, 0, sizeof (siginfo_t));
1093       else
1094         memcpy (&p_sig->info, info, sizeof (siginfo_t));
1095       process->pending_signals = p_sig;
1096     }
1097
1098   if (process->status_pending_p && !check_removed_breakpoint (process))
1099     return;
1100
1101   saved_inferior = current_inferior;
1102   current_inferior = get_process_thread (process);
1103
1104   if (debug_threads)
1105     fprintf (stderr, "Resuming process %ld (%s, signal %d, stop %s)\n", inferior_pid,
1106              step ? "step" : "continue", signal,
1107              process->stop_expected ? "expected" : "not expected");
1108
1109   /* This bit needs some thinking about.  If we get a signal that
1110      we must report while a single-step reinsert is still pending,
1111      we often end up resuming the thread.  It might be better to
1112      (ew) allow a stack of pending events; then we could be sure that
1113      the reinsert happened right away and not lose any signals.
1114
1115      Making this stack would also shrink the window in which breakpoints are
1116      uninserted (see comment in linux_wait_for_process) but not enough for
1117      complete correctness, so it won't solve that problem.  It may be
1118      worthwhile just to solve this one, however.  */
1119   if (process->bp_reinsert != 0)
1120     {
1121       if (debug_threads)
1122         fprintf (stderr, "  pending reinsert at %08lx", (long)process->bp_reinsert);
1123       if (step == 0)
1124         fprintf (stderr, "BAD - reinserting but not stepping.\n");
1125       step = 1;
1126
1127       /* Postpone any pending signal.  It was enqueued above.  */
1128       signal = 0;
1129     }
1130
1131   check_removed_breakpoint (process);
1132
1133   if (debug_threads && the_low_target.get_pc != NULL)
1134     {
1135       fprintf (stderr, "  ");
1136       (*the_low_target.get_pc) ();
1137     }
1138
1139   /* If we have pending signals, consume one unless we are trying to reinsert
1140      a breakpoint.  */
1141   if (process->pending_signals != NULL && process->bp_reinsert == 0)
1142     {
1143       struct pending_signals **p_sig;
1144
1145       p_sig = &process->pending_signals;
1146       while ((*p_sig)->prev != NULL)
1147         p_sig = &(*p_sig)->prev;
1148
1149       signal = (*p_sig)->signal;
1150       if ((*p_sig)->info.si_signo != 0)
1151         ptrace (PTRACE_SETSIGINFO, process->lwpid, 0, &(*p_sig)->info);
1152
1153       free (*p_sig);
1154       *p_sig = NULL;
1155     }
1156
1157   regcache_invalidate_one ((struct inferior_list_entry *)
1158                            get_process_thread (process));
1159   errno = 0;
1160   process->stopped = 0;
1161   process->stepping = step;
1162   ptrace (step ? PTRACE_SINGLESTEP : PTRACE_CONT, process->lwpid, 0, signal);
1163
1164   current_inferior = saved_inferior;
1165   if (errno)
1166     perror_with_name ("ptrace");
1167 }
1168
1169 static struct thread_resume *resume_ptr;
1170
1171 /* This function is called once per thread.  We look up the thread
1172    in RESUME_PTR, and mark the thread with a pointer to the appropriate
1173    resume request.
1174
1175    This algorithm is O(threads * resume elements), but resume elements
1176    is small (and will remain small at least until GDB supports thread
1177    suspension).  */
1178 static void
1179 linux_set_resume_request (struct inferior_list_entry *entry)
1180 {
1181   struct process_info *process;
1182   struct thread_info *thread;
1183   int ndx;
1184
1185   thread = (struct thread_info *) entry;
1186   process = get_thread_process (thread);
1187
1188   ndx = 0;
1189   while (resume_ptr[ndx].thread != -1 && resume_ptr[ndx].thread != entry->id)
1190     ndx++;
1191
1192   process->resume = &resume_ptr[ndx];
1193 }
1194
1195 /* This function is called once per thread.  We check the thread's resume
1196    request, which will tell us whether to resume, step, or leave the thread
1197    stopped; and what signal, if any, it should be sent.  For threads which
1198    we aren't explicitly told otherwise, we preserve the stepping flag; this
1199    is used for stepping over gdbserver-placed breakpoints.  */
1200
1201 static void
1202 linux_continue_one_thread (struct inferior_list_entry *entry)
1203 {
1204   struct process_info *process;
1205   struct thread_info *thread;
1206   int step;
1207
1208   thread = (struct thread_info *) entry;
1209   process = get_thread_process (thread);
1210
1211   if (process->resume->leave_stopped)
1212     return;
1213
1214   if (process->resume->thread == -1)
1215     step = process->stepping || process->resume->step;
1216   else
1217     step = process->resume->step;
1218
1219   linux_resume_one_process (&process->head, step, process->resume->sig, NULL);
1220
1221   process->resume = NULL;
1222 }
1223
1224 /* This function is called once per thread.  We check the thread's resume
1225    request, which will tell us whether to resume, step, or leave the thread
1226    stopped; and what signal, if any, it should be sent.  We queue any needed
1227    signals, since we won't actually resume.  We already have a pending event
1228    to report, so we don't need to preserve any step requests; they should
1229    be re-issued if necessary.  */
1230
1231 static void
1232 linux_queue_one_thread (struct inferior_list_entry *entry)
1233 {
1234   struct process_info *process;
1235   struct thread_info *thread;
1236
1237   thread = (struct thread_info *) entry;
1238   process = get_thread_process (thread);
1239
1240   if (process->resume->leave_stopped)
1241     return;
1242
1243   /* If we have a new signal, enqueue the signal.  */
1244   if (process->resume->sig != 0)
1245     {
1246       struct pending_signals *p_sig;
1247       p_sig = malloc (sizeof (*p_sig));
1248       p_sig->prev = process->pending_signals;
1249       p_sig->signal = process->resume->sig;
1250       memset (&p_sig->info, 0, sizeof (siginfo_t));
1251
1252       /* If this is the same signal we were previously stopped by,
1253          make sure to queue its siginfo.  We can ignore the return
1254          value of ptrace; if it fails, we'll skip
1255          PTRACE_SETSIGINFO.  */
1256       if (WIFSTOPPED (process->last_status)
1257           && WSTOPSIG (process->last_status) == process->resume->sig)
1258         ptrace (PTRACE_GETSIGINFO, process->lwpid, 0, &p_sig->info);
1259
1260       process->pending_signals = p_sig;
1261     }
1262
1263   process->resume = NULL;
1264 }
1265
1266 /* Set DUMMY if this process has an interesting status pending.  */
1267 static int
1268 resume_status_pending_p (struct inferior_list_entry *entry, void *flag_p)
1269 {
1270   struct process_info *process = (struct process_info *) entry;
1271
1272   /* Processes which will not be resumed are not interesting, because
1273      we might not wait for them next time through linux_wait.  */
1274   if (process->resume->leave_stopped)
1275     return 0;
1276
1277   /* If this thread has a removed breakpoint, we won't have any
1278      events to report later, so check now.  check_removed_breakpoint
1279      may clear status_pending_p.  We avoid calling check_removed_breakpoint
1280      for any thread that we are not otherwise going to resume - this
1281      lets us preserve stopped status when two threads hit a breakpoint.
1282      GDB removes the breakpoint to single-step a particular thread
1283      past it, then re-inserts it and resumes all threads.  We want
1284      to report the second thread without resuming it in the interim.  */
1285   if (process->status_pending_p)
1286     check_removed_breakpoint (process);
1287
1288   if (process->status_pending_p)
1289     * (int *) flag_p = 1;
1290
1291   return 0;
1292 }
1293
1294 static void
1295 linux_resume (struct thread_resume *resume_info)
1296 {
1297   int pending_flag;
1298
1299   /* Yes, the use of a global here is rather ugly.  */
1300   resume_ptr = resume_info;
1301
1302   for_each_inferior (&all_threads, linux_set_resume_request);
1303
1304   /* If there is a thread which would otherwise be resumed, which
1305      has a pending status, then don't resume any threads - we can just
1306      report the pending status.  Make sure to queue any signals
1307      that would otherwise be sent.  */
1308   pending_flag = 0;
1309   find_inferior (&all_processes, resume_status_pending_p, &pending_flag);
1310
1311   if (debug_threads)
1312     {
1313       if (pending_flag)
1314         fprintf (stderr, "Not resuming, pending status\n");
1315       else
1316         fprintf (stderr, "Resuming, no pending status\n");
1317     }
1318
1319   if (pending_flag)
1320     for_each_inferior (&all_threads, linux_queue_one_thread);
1321   else
1322     for_each_inferior (&all_threads, linux_continue_one_thread);
1323 }
1324
1325 #ifdef HAVE_LINUX_USRREGS
1326
1327 int
1328 register_addr (int regnum)
1329 {
1330   int addr;
1331
1332   if (regnum < 0 || regnum >= the_low_target.num_regs)
1333     error ("Invalid register number %d.", regnum);
1334
1335   addr = the_low_target.regmap[regnum];
1336
1337   return addr;
1338 }
1339
1340 /* Fetch one register.  */
1341 static void
1342 fetch_register (int regno)
1343 {
1344   CORE_ADDR regaddr;
1345   int i, size;
1346   char *buf;
1347
1348   if (regno >= the_low_target.num_regs)
1349     return;
1350   if ((*the_low_target.cannot_fetch_register) (regno))
1351     return;
1352
1353   regaddr = register_addr (regno);
1354   if (regaddr == -1)
1355     return;
1356   size = (register_size (regno) + sizeof (PTRACE_XFER_TYPE) - 1)
1357          & - sizeof (PTRACE_XFER_TYPE);
1358   buf = alloca (size);
1359   for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
1360     {
1361       errno = 0;
1362       *(PTRACE_XFER_TYPE *) (buf + i) =
1363         ptrace (PTRACE_PEEKUSER, inferior_pid, (PTRACE_ARG3_TYPE) regaddr, 0);
1364       regaddr += sizeof (PTRACE_XFER_TYPE);
1365       if (errno != 0)
1366         {
1367           /* Warning, not error, in case we are attached; sometimes the
1368              kernel doesn't let us at the registers.  */
1369           char *err = strerror (errno);
1370           char *msg = alloca (strlen (err) + 128);
1371           sprintf (msg, "reading register %d: %s", regno, err);
1372           error (msg);
1373           goto error_exit;
1374         }
1375     }
1376   if (the_low_target.left_pad_xfer
1377       && register_size (regno) < sizeof (PTRACE_XFER_TYPE))
1378     supply_register (regno, (buf + sizeof (PTRACE_XFER_TYPE)
1379                              - register_size (regno)));
1380   else
1381     supply_register (regno, buf);
1382
1383 error_exit:;
1384 }
1385
1386 /* Fetch all registers, or just one, from the child process.  */
1387 static void
1388 usr_fetch_inferior_registers (int regno)
1389 {
1390   if (regno == -1 || regno == 0)
1391     for (regno = 0; regno < the_low_target.num_regs; regno++)
1392       fetch_register (regno);
1393   else
1394     fetch_register (regno);
1395 }
1396
1397 /* Store our register values back into the inferior.
1398    If REGNO is -1, do this for all registers.
1399    Otherwise, REGNO specifies which register (so we can save time).  */
1400 static void
1401 usr_store_inferior_registers (int regno)
1402 {
1403   CORE_ADDR regaddr;
1404   int i, size;
1405   char *buf;
1406
1407   if (regno >= 0)
1408     {
1409       if (regno >= the_low_target.num_regs)
1410         return;
1411
1412       if ((*the_low_target.cannot_store_register) (regno) == 1)
1413         return;
1414
1415       regaddr = register_addr (regno);
1416       if (regaddr == -1)
1417         return;
1418       errno = 0;
1419       size = (register_size (regno) + sizeof (PTRACE_XFER_TYPE) - 1)
1420              & - sizeof (PTRACE_XFER_TYPE);
1421       buf = alloca (size);
1422       memset (buf, 0, size);
1423       if (the_low_target.left_pad_xfer
1424           && register_size (regno) < sizeof (PTRACE_XFER_TYPE))
1425         collect_register (regno, (buf + sizeof (PTRACE_XFER_TYPE)
1426                                   - register_size (regno)));
1427       else
1428         collect_register (regno, buf);
1429       for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
1430         {
1431           errno = 0;
1432           ptrace (PTRACE_POKEUSER, inferior_pid, (PTRACE_ARG3_TYPE) regaddr,
1433                   *(PTRACE_XFER_TYPE *) (buf + i));
1434           if (errno != 0)
1435             {
1436               if ((*the_low_target.cannot_store_register) (regno) == 0)
1437                 {
1438                   char *err = strerror (errno);
1439                   char *msg = alloca (strlen (err) + 128);
1440                   sprintf (msg, "writing register %d: %s",
1441                            regno, err);
1442                   error (msg);
1443                   return;
1444                 }
1445             }
1446           regaddr += sizeof (PTRACE_XFER_TYPE);
1447         }
1448     }
1449   else
1450     for (regno = 0; regno < the_low_target.num_regs; regno++)
1451       usr_store_inferior_registers (regno);
1452 }
1453 #endif /* HAVE_LINUX_USRREGS */
1454
1455
1456
1457 #ifdef HAVE_LINUX_REGSETS
1458
1459 static int
1460 regsets_fetch_inferior_registers ()
1461 {
1462   struct regset_info *regset;
1463   int saw_general_regs = 0;
1464
1465   regset = target_regsets;
1466
1467   while (regset->size >= 0)
1468     {
1469       void *buf;
1470       int res;
1471
1472       if (regset->size == 0)
1473         {
1474           regset ++;
1475           continue;
1476         }
1477
1478       buf = malloc (regset->size);
1479       res = ptrace (regset->get_request, inferior_pid, 0, buf);
1480       if (res < 0)
1481         {
1482           if (errno == EIO)
1483             {
1484               /* If we get EIO on the first regset, do not try regsets again.
1485                  If we get EIO on a later regset, disable that regset.  */
1486               if (regset == target_regsets)
1487                 {
1488                   use_regsets_p = 0;
1489                   return -1;
1490                 }
1491               else
1492                 {
1493                   regset->size = 0;
1494                   continue;
1495                 }
1496             }
1497           else
1498             {
1499               char s[256];
1500               sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%ld",
1501                        inferior_pid);
1502               perror (s);
1503             }
1504         }
1505       else if (regset->type == GENERAL_REGS)
1506         saw_general_regs = 1;
1507       regset->store_function (buf);
1508       regset ++;
1509     }
1510   if (saw_general_regs)
1511     return 0;
1512   else
1513     return 1;
1514 }
1515
1516 static int
1517 regsets_store_inferior_registers ()
1518 {
1519   struct regset_info *regset;
1520   int saw_general_regs = 0;
1521
1522   regset = target_regsets;
1523
1524   while (regset->size >= 0)
1525     {
1526       void *buf;
1527       int res;
1528
1529       if (regset->size == 0)
1530         {
1531           regset ++;
1532           continue;
1533         }
1534
1535       buf = malloc (regset->size);
1536
1537       /* First fill the buffer with the current register set contents,
1538          in case there are any items in the kernel's regset that are
1539          not in gdbserver's regcache.  */
1540       res = ptrace (regset->get_request, inferior_pid, 0, buf);
1541
1542       if (res == 0)
1543         {
1544           /* Then overlay our cached registers on that.  */
1545           regset->fill_function (buf);
1546
1547           /* Only now do we write the register set.  */
1548           res = ptrace (regset->set_request, inferior_pid, 0, buf);
1549         }
1550
1551       if (res < 0)
1552         {
1553           if (errno == EIO)
1554             {
1555               /* If we get EIO on the first regset, do not try regsets again.
1556                  If we get EIO on a later regset, disable that regset.  */
1557               if (regset == target_regsets)
1558                 {
1559                   use_regsets_p = 0;
1560                   return -1;
1561                 }
1562               else
1563                 {
1564                   regset->size = 0;
1565                   continue;
1566                 }
1567             }
1568           else
1569             {
1570               perror ("Warning: ptrace(regsets_store_inferior_registers)");
1571             }
1572         }
1573       else if (regset->type == GENERAL_REGS)
1574         saw_general_regs = 1;
1575       regset ++;
1576       free (buf);
1577     }
1578   if (saw_general_regs)
1579     return 0;
1580   else
1581     return 1;
1582   return 0;
1583 }
1584
1585 #endif /* HAVE_LINUX_REGSETS */
1586
1587
1588 void
1589 linux_fetch_registers (int regno)
1590 {
1591 #ifdef HAVE_LINUX_REGSETS
1592   if (use_regsets_p)
1593     {
1594       if (regsets_fetch_inferior_registers () == 0)
1595         return;
1596     }
1597 #endif
1598 #ifdef HAVE_LINUX_USRREGS
1599   usr_fetch_inferior_registers (regno);
1600 #endif
1601 }
1602
1603 void
1604 linux_store_registers (int regno)
1605 {
1606 #ifdef HAVE_LINUX_REGSETS
1607   if (use_regsets_p)
1608     {
1609       if (regsets_store_inferior_registers () == 0)
1610         return;
1611     }
1612 #endif
1613 #ifdef HAVE_LINUX_USRREGS
1614   usr_store_inferior_registers (regno);
1615 #endif
1616 }
1617
1618
1619 /* Copy LEN bytes from inferior's memory starting at MEMADDR
1620    to debugger memory starting at MYADDR.  */
1621
1622 static int
1623 linux_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1624 {
1625   register int i;
1626   /* Round starting address down to longword boundary.  */
1627   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
1628   /* Round ending address up; get number of longwords that makes.  */
1629   register int count
1630     = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
1631       / sizeof (PTRACE_XFER_TYPE);
1632   /* Allocate buffer of that many longwords.  */
1633   register PTRACE_XFER_TYPE *buffer
1634     = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
1635   int fd;
1636   char filename[64];
1637
1638   /* Try using /proc.  Don't bother for one word.  */
1639   if (len >= 3 * sizeof (long))
1640     {
1641       /* We could keep this file open and cache it - possibly one per
1642          thread.  That requires some juggling, but is even faster.  */
1643       sprintf (filename, "/proc/%ld/mem", inferior_pid);
1644       fd = open (filename, O_RDONLY | O_LARGEFILE);
1645       if (fd == -1)
1646         goto no_proc;
1647
1648       /* If pread64 is available, use it.  It's faster if the kernel
1649          supports it (only one syscall), and it's 64-bit safe even on
1650          32-bit platforms (for instance, SPARC debugging a SPARC64
1651          application).  */
1652 #ifdef HAVE_PREAD64
1653       if (pread64 (fd, myaddr, len, memaddr) != len)
1654 #else
1655       if (lseek (fd, memaddr, SEEK_SET) == -1 || read (fd, memaddr, len) != len)
1656 #endif
1657         {
1658           close (fd);
1659           goto no_proc;
1660         }
1661
1662       close (fd);
1663       return 0;
1664     }
1665
1666  no_proc:
1667   /* Read all the longwords */
1668   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
1669     {
1670       errno = 0;
1671       buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid, (PTRACE_ARG3_TYPE) addr, 0);
1672       if (errno)
1673         return errno;
1674     }
1675
1676   /* Copy appropriate bytes out of the buffer.  */
1677   memcpy (myaddr, (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
1678
1679   return 0;
1680 }
1681
1682 /* Copy LEN bytes of data from debugger memory at MYADDR
1683    to inferior's memory at MEMADDR.
1684    On failure (cannot write the inferior)
1685    returns the value of errno.  */
1686
1687 static int
1688 linux_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1689 {
1690   register int i;
1691   /* Round starting address down to longword boundary.  */
1692   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
1693   /* Round ending address up; get number of longwords that makes.  */
1694   register int count
1695   = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1) / sizeof (PTRACE_XFER_TYPE);
1696   /* Allocate buffer of that many longwords.  */
1697   register PTRACE_XFER_TYPE *buffer = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
1698   extern int errno;
1699
1700   if (debug_threads)
1701     {
1702       fprintf (stderr, "Writing %02x to %08lx\n", (unsigned)myaddr[0], (long)memaddr);
1703     }
1704
1705   /* Fill start and end extra bytes of buffer with existing memory data.  */
1706
1707   buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
1708                       (PTRACE_ARG3_TYPE) addr, 0);
1709
1710   if (count > 1)
1711     {
1712       buffer[count - 1]
1713         = ptrace (PTRACE_PEEKTEXT, inferior_pid,
1714                   (PTRACE_ARG3_TYPE) (addr + (count - 1)
1715                                       * sizeof (PTRACE_XFER_TYPE)),
1716                   0);
1717     }
1718
1719   /* Copy data to be written over corresponding part of buffer */
1720
1721   memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), myaddr, len);
1722
1723   /* Write the entire buffer.  */
1724
1725   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
1726     {
1727       errno = 0;
1728       ptrace (PTRACE_POKETEXT, inferior_pid, (PTRACE_ARG3_TYPE) addr, buffer[i]);
1729       if (errno)
1730         return errno;
1731     }
1732
1733   return 0;
1734 }
1735
1736 static int linux_supports_tracefork_flag;
1737
1738 /* Helper functions for linux_test_for_tracefork, called via clone ().  */
1739
1740 static int
1741 linux_tracefork_grandchild (void *arg)
1742 {
1743   _exit (0);
1744 }
1745
1746 #define STACK_SIZE 4096
1747
1748 static int
1749 linux_tracefork_child (void *arg)
1750 {
1751   ptrace (PTRACE_TRACEME, 0, 0, 0);
1752   kill (getpid (), SIGSTOP);
1753 #ifdef __ia64__
1754   __clone2 (linux_tracefork_grandchild, arg, STACK_SIZE,
1755             CLONE_VM | SIGCHLD, NULL);
1756 #else
1757   clone (linux_tracefork_grandchild, arg + STACK_SIZE,
1758          CLONE_VM | SIGCHLD, NULL);
1759 #endif
1760   _exit (0);
1761 }
1762
1763 /* Wrapper function for waitpid which handles EINTR.  */
1764
1765 static int
1766 my_waitpid (int pid, int *status, int flags)
1767 {
1768   int ret;
1769   do
1770     {
1771       ret = waitpid (pid, status, flags);
1772     }
1773   while (ret == -1 && errno == EINTR);
1774
1775   return ret;
1776 }
1777
1778 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.  Make
1779    sure that we can enable the option, and that it had the desired
1780    effect.  */
1781
1782 static void
1783 linux_test_for_tracefork (void)
1784 {
1785   int child_pid, ret, status;
1786   long second_pid;
1787   char *stack = malloc (STACK_SIZE * 4);
1788
1789   linux_supports_tracefork_flag = 0;
1790
1791   /* Use CLONE_VM instead of fork, to support uClinux (no MMU).  */
1792 #ifdef __ia64__
1793   child_pid = __clone2 (linux_tracefork_child, stack, STACK_SIZE,
1794                         CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
1795 #else
1796   child_pid = clone (linux_tracefork_child, stack + STACK_SIZE,
1797                      CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
1798 #endif
1799   if (child_pid == -1)
1800     perror_with_name ("clone");
1801
1802   ret = my_waitpid (child_pid, &status, 0);
1803   if (ret == -1)
1804     perror_with_name ("waitpid");
1805   else if (ret != child_pid)
1806     error ("linux_test_for_tracefork: waitpid: unexpected result %d.", ret);
1807   if (! WIFSTOPPED (status))
1808     error ("linux_test_for_tracefork: waitpid: unexpected status %d.", status);
1809
1810   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
1811   if (ret != 0)
1812     {
1813       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
1814       if (ret != 0)
1815         {
1816           warning ("linux_test_for_tracefork: failed to kill child");
1817           return;
1818         }
1819
1820       ret = my_waitpid (child_pid, &status, 0);
1821       if (ret != child_pid)
1822         warning ("linux_test_for_tracefork: failed to wait for killed child");
1823       else if (!WIFSIGNALED (status))
1824         warning ("linux_test_for_tracefork: unexpected wait status 0x%x from "
1825                  "killed child", status);
1826
1827       return;
1828     }
1829
1830   ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
1831   if (ret != 0)
1832     warning ("linux_test_for_tracefork: failed to resume child");
1833
1834   ret = my_waitpid (child_pid, &status, 0);
1835
1836   if (ret == child_pid && WIFSTOPPED (status)
1837       && status >> 16 == PTRACE_EVENT_FORK)
1838     {
1839       second_pid = 0;
1840       ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
1841       if (ret == 0 && second_pid != 0)
1842         {
1843           int second_status;
1844
1845           linux_supports_tracefork_flag = 1;
1846           my_waitpid (second_pid, &second_status, 0);
1847           ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
1848           if (ret != 0)
1849             warning ("linux_test_for_tracefork: failed to kill second child");
1850           my_waitpid (second_pid, &status, 0);
1851         }
1852     }
1853   else
1854     warning ("linux_test_for_tracefork: unexpected result from waitpid "
1855              "(%d, status 0x%x)", ret, status);
1856
1857   do
1858     {
1859       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
1860       if (ret != 0)
1861         warning ("linux_test_for_tracefork: failed to kill child");
1862       my_waitpid (child_pid, &status, 0);
1863     }
1864   while (WIFSTOPPED (status));
1865
1866   free (stack);
1867 }
1868
1869
1870 static void
1871 linux_look_up_symbols (void)
1872 {
1873 #ifdef USE_THREAD_DB
1874   if (thread_db_active)
1875     return;
1876
1877   thread_db_active = thread_db_init (!linux_supports_tracefork_flag);
1878 #endif
1879 }
1880
1881 static void
1882 linux_request_interrupt (void)
1883 {
1884   extern unsigned long signal_pid;
1885
1886   if (cont_thread != 0 && cont_thread != -1)
1887     {
1888       struct process_info *process;
1889
1890       process = get_thread_process (current_inferior);
1891       kill_lwp (process->lwpid, SIGINT);
1892     }
1893   else
1894     kill_lwp (signal_pid, SIGINT);
1895 }
1896
1897 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
1898    to debugger memory starting at MYADDR.  */
1899
1900 static int
1901 linux_read_auxv (CORE_ADDR offset, unsigned char *myaddr, unsigned int len)
1902 {
1903   char filename[PATH_MAX];
1904   int fd, n;
1905
1906   snprintf (filename, sizeof filename, "/proc/%ld/auxv", inferior_pid);
1907
1908   fd = open (filename, O_RDONLY);
1909   if (fd < 0)
1910     return -1;
1911
1912   if (offset != (CORE_ADDR) 0
1913       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
1914     n = -1;
1915   else
1916     n = read (fd, myaddr, len);
1917
1918   close (fd);
1919
1920   return n;
1921 }
1922
1923 /* These watchpoint related wrapper functions simply pass on the function call
1924    if the target has registered a corresponding function.  */
1925
1926 static int
1927 linux_insert_watchpoint (char type, CORE_ADDR addr, int len)
1928 {
1929   if (the_low_target.insert_watchpoint != NULL)
1930     return the_low_target.insert_watchpoint (type, addr, len);
1931   else
1932     /* Unsupported (see target.h).  */
1933     return 1;
1934 }
1935
1936 static int
1937 linux_remove_watchpoint (char type, CORE_ADDR addr, int len)
1938 {
1939   if (the_low_target.remove_watchpoint != NULL)
1940     return the_low_target.remove_watchpoint (type, addr, len);
1941   else
1942     /* Unsupported (see target.h).  */
1943     return 1;
1944 }
1945
1946 static int
1947 linux_stopped_by_watchpoint (void)
1948 {
1949   if (the_low_target.stopped_by_watchpoint != NULL)
1950     return the_low_target.stopped_by_watchpoint ();
1951   else
1952     return 0;
1953 }
1954
1955 static CORE_ADDR
1956 linux_stopped_data_address (void)
1957 {
1958   if (the_low_target.stopped_data_address != NULL)
1959     return the_low_target.stopped_data_address ();
1960   else
1961     return 0;
1962 }
1963
1964 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
1965 #if defined(__mcoldfire__)
1966 /* These should really be defined in the kernel's ptrace.h header.  */
1967 #define PT_TEXT_ADDR 49*4
1968 #define PT_DATA_ADDR 50*4
1969 #define PT_TEXT_END_ADDR  51*4
1970 #endif
1971
1972 /* Under uClinux, programs are loaded at non-zero offsets, which we need
1973    to tell gdb about.  */
1974
1975 static int
1976 linux_read_offsets (CORE_ADDR *text_p, CORE_ADDR *data_p)
1977 {
1978 #if defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) && defined(PT_TEXT_END_ADDR)
1979   unsigned long text, text_end, data;
1980   int pid = get_thread_process (current_inferior)->head.id;
1981
1982   errno = 0;
1983
1984   text = ptrace (PTRACE_PEEKUSER, pid, (long)PT_TEXT_ADDR, 0);
1985   text_end = ptrace (PTRACE_PEEKUSER, pid, (long)PT_TEXT_END_ADDR, 0);
1986   data = ptrace (PTRACE_PEEKUSER, pid, (long)PT_DATA_ADDR, 0);
1987
1988   if (errno == 0)
1989     {
1990       /* Both text and data offsets produced at compile-time (and so
1991          used by gdb) are relative to the beginning of the program,
1992          with the data segment immediately following the text segment.
1993          However, the actual runtime layout in memory may put the data
1994          somewhere else, so when we send gdb a data base-address, we
1995          use the real data base address and subtract the compile-time
1996          data base-address from it (which is just the length of the
1997          text segment).  BSS immediately follows data in both
1998          cases.  */
1999       *text_p = text;
2000       *data_p = data - (text_end - text);
2001       
2002       return 1;
2003     }
2004 #endif
2005  return 0;
2006 }
2007 #endif
2008
2009 static const char *
2010 linux_arch_string (void)
2011 {
2012   return the_low_target.arch_string;
2013 }
2014
2015 static struct target_ops linux_target_ops = {
2016   linux_create_inferior,
2017   linux_attach,
2018   linux_kill,
2019   linux_detach,
2020   linux_join,
2021   linux_thread_alive,
2022   linux_resume,
2023   linux_wait,
2024   linux_fetch_registers,
2025   linux_store_registers,
2026   linux_read_memory,
2027   linux_write_memory,
2028   linux_look_up_symbols,
2029   linux_request_interrupt,
2030   linux_read_auxv,
2031   linux_insert_watchpoint,
2032   linux_remove_watchpoint,
2033   linux_stopped_by_watchpoint,
2034   linux_stopped_data_address,
2035 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
2036   linux_read_offsets,
2037 #else
2038   NULL,
2039 #endif
2040 #ifdef USE_THREAD_DB
2041   thread_db_get_tls_address,
2042 #else
2043   NULL,
2044 #endif
2045   linux_arch_string,
2046 };
2047
2048 static void
2049 linux_init_signals ()
2050 {
2051   /* FIXME drow/2002-06-09: As above, we should check with LinuxThreads
2052      to find what the cancel signal actually is.  */
2053   signal (__SIGRTMIN+1, SIG_IGN);
2054 }
2055
2056 void
2057 initialize_low (void)
2058 {
2059   thread_db_active = 0;
2060   set_target_ops (&linux_target_ops);
2061   set_breakpoint_data (the_low_target.breakpoint,
2062                        the_low_target.breakpoint_len);
2063   init_registers ();
2064   linux_init_signals ();
2065   linux_test_for_tracefork ();
2066 }