]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - gnu/usr.bin/gdb/gdbserver/fbsd-low.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / gnu / usr.bin / gdb / gdbserver / fbsd-low.c
1 /* Low level interface to ptrace, for the remote server for GDB.
2    Copyright 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004
3    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 2 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, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #include <sys/cdefs.h>
23 __FBSDID("$FreeBSD$");
24
25 #include "server.h"
26 #include "fbsd-low.h"
27
28 #include <sys/wait.h>
29 #include <sys/param.h>
30 #include <sys/ptrace.h>
31 #include <sys/user.h>
32 #include <sys/ioctl.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <signal.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41
42 /* ``all_threads'' is keyed by the LWP ID - it should be the thread ID instead,
43    however.  This requires changing the ID in place when we go from !using_threads
44    to using_threads, immediately.
45
46    ``all_processes'' is keyed by the process ID - which on Linux is (presently)
47    the same as the LWP ID.  */
48
49 struct inferior_list all_processes;
50
51 /* FIXME this is a bit of a hack, and could be removed.  */
52 int stopping_threads;
53
54 /* FIXME make into a target method?  */
55 int using_threads;
56
57 static void fbsd_resume_one_process (struct inferior_list_entry *entry,
58                                       int step, int signal);
59 static void fbsd_resume (struct thread_resume *resume_info);
60 static void stop_all_processes (void);
61 static int fbsd_wait_for_event (struct thread_info *child);
62
63 struct pending_signals
64 {
65   int signal;
66   struct pending_signals *prev;
67 };
68
69 #define PTRACE_ARG3_TYPE caddr_t
70 #define PTRACE_XFER_TYPE int
71
72 int debug_threads = 0;
73
74 #define pid_of(proc) ((proc)->head.id)
75
76 /* FIXME: Delete eventually.  */
77 #define inferior_pid (pid_of (get_thread_process (current_inferior)))
78
79 /* This function should only be called if the process got a SIGTRAP.
80    The SIGTRAP could mean several things.
81
82    On i386, where decr_pc_after_break is non-zero:
83    If we were single-stepping this process using PT_STEP,
84    we will get only the one SIGTRAP (even if the instruction we
85    stepped over was a breakpoint).  The value of $eip will be the
86    next instruction.
87    If we continue the process using PTRACE_CONT, we will get a
88    SIGTRAP when we hit a breakpoint.  The value of $eip will be
89    the instruction after the breakpoint (i.e. needs to be
90    decremented).  If we report the SIGTRAP to GDB, we must also
91    report the undecremented PC.  If we cancel the SIGTRAP, we
92    must resume at the decremented PC.
93
94    (Presumably, not yet tested) On a non-decr_pc_after_break machine
95    with hardware or kernel single-step:
96    If we single-step over a breakpoint instruction, our PC will
97    point at the following instruction.  If we continue and hit a
98    breakpoint instruction, our PC will point at the breakpoint
99    instruction.  */
100
101 static CORE_ADDR
102 get_stop_pc (void)
103 {
104   CORE_ADDR stop_pc = (*the_low_target.get_pc) ();
105
106   if (get_thread_process (current_inferior)->stepping)
107     return stop_pc;
108   else
109     return stop_pc - the_low_target.decr_pc_after_break;
110 }
111
112 static void *
113 add_process (int pid)
114 {
115   struct process_info *process;
116
117   process = (struct process_info *) malloc (sizeof (*process));
118   memset (process, 0, sizeof (*process));
119
120   process->head.id = pid;
121
122   /* Default to tid == lwpid == pid.  */
123   process->tid = pid;
124   process->lwpid = pid;
125
126   add_inferior_to_list (&all_processes, &process->head);
127
128   return process;
129 }
130
131 /* Start an inferior process and returns its pid.
132    ALLARGS is a vector of program-name and args. */
133
134 static int
135 fbsd_create_inferior (char *program, char **allargs)
136 {
137   void *new_process;
138   int pid;
139
140   pid = vfork ();
141   if (pid < 0)
142     perror_with_name ("vfork");
143
144   if (pid == 0)
145     {
146       ptrace (PT_TRACE_ME, 0, 0, 0);
147
148       setpgid (0, 0);
149
150       execv (program, allargs);
151
152       fprintf (stderr, "Cannot exec %s: %s.\n", program,
153                strerror (errno));
154       fflush (stderr);
155       _exit (0177);
156     }
157
158   new_process = add_process (pid);
159   add_thread (pid, new_process);
160
161   return pid;
162 }
163
164 /* Attach to an inferior process.  */
165
166 void
167 fbsd_attach_lwp (int pid, int tid)
168 {
169   struct process_info *new_process;
170
171   if (ptrace (PT_ATTACH, pid, 0, 0) != 0)
172     {
173       fprintf (stderr, "Cannot attach to process %d: %s (%d)\n", pid,
174                strerror (errno), errno);
175       fflush (stderr);
176
177       /* If we fail to attach to an LWP, just return.  */
178       if (!using_threads)
179         _exit (0177);
180       return;
181     }
182
183   new_process = (struct process_info *) add_process (pid);
184   add_thread (tid, new_process);
185
186   /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
187      brings it to a halt.  We should ignore that SIGSTOP and resume the process
188      (unless this is the first process, in which case the flag will be cleared
189      in fbsd_attach).
190
191      On the other hand, if we are currently trying to stop all threads, we
192      should treat the new thread as if we had sent it a SIGSTOP.  This works
193      because we are guaranteed that add_process added us to the end of the
194      list, and so the new thread has not yet reached wait_for_sigstop (but
195      will).  */
196   if (! stopping_threads)
197     new_process->stop_expected = 1;
198 }
199
200 int
201 fbsd_attach (int pid)
202 {
203   struct process_info *process;
204
205   fbsd_attach_lwp (pid, pid);
206
207   /* Don't ignore the initial SIGSTOP if we just attached to this process.  */
208   process = (struct process_info *) find_inferior_id (&all_processes, pid);
209   process->stop_expected = 0;
210
211   return 0;
212 }
213
214 /* Kill the inferior process.  Make us have no inferior.  */
215
216 static void
217 fbsd_kill_one_process (struct inferior_list_entry *entry)
218 {
219   struct thread_info *thread = (struct thread_info *) entry;
220   struct process_info *process = get_thread_process (thread);
221   int wstat;
222
223   do
224     {
225       ptrace (PT_KILL, pid_of (process), 0, 0);
226
227       /* Make sure it died.  The loop is most likely unnecessary.  */
228       wstat = fbsd_wait_for_event (thread);
229     } while (WIFSTOPPED (wstat));
230 }
231
232 static void
233 fbsd_kill (void)
234 {
235   for_each_inferior (&all_threads, fbsd_kill_one_process);
236 }
237
238 static void
239 fbsd_detach_one_process (struct inferior_list_entry *entry)
240 {
241   struct thread_info *thread = (struct thread_info *) entry;
242   struct process_info *process = get_thread_process (thread);
243
244   ptrace (PT_DETACH, pid_of (process), 0, 0);
245 }
246
247 static void
248 fbsd_detach (void)
249 {
250   for_each_inferior (&all_threads, fbsd_detach_one_process);
251 }
252
253 /* Return nonzero if the given thread is still alive.  */
254 static int
255 fbsd_thread_alive (int tid)
256 {
257   if (find_inferior_id (&all_threads, tid) != NULL)
258     return 1;
259   else
260     return 0;
261 }
262
263 /* Return nonzero if this process stopped at a breakpoint which
264    no longer appears to be inserted.  Also adjust the PC
265    appropriately to resume where the breakpoint used to be.  */
266 static int
267 check_removed_breakpoint (struct process_info *event_child)
268 {
269   CORE_ADDR stop_pc;
270   struct thread_info *saved_inferior;
271
272   if (event_child->pending_is_breakpoint == 0)
273     return 0;
274
275   if (debug_threads)
276     fprintf (stderr, "Checking for breakpoint.\n");
277
278   saved_inferior = current_inferior;
279   current_inferior = get_process_thread (event_child);
280
281   stop_pc = get_stop_pc ();
282
283   /* If the PC has changed since we stopped, then we shouldn't do
284      anything.  This happens if, for instance, GDB handled the
285      decr_pc_after_break subtraction itself.  */
286   if (stop_pc != event_child->pending_stop_pc)
287     {
288       if (debug_threads)
289         fprintf (stderr, "Ignoring, PC was changed.\n");
290
291       event_child->pending_is_breakpoint = 0;
292       current_inferior = saved_inferior;
293       return 0;
294     }
295
296   /* If the breakpoint is still there, we will report hitting it.  */
297   if ((*the_low_target.breakpoint_at) (stop_pc))
298     {
299       if (debug_threads)
300         fprintf (stderr, "Ignoring, breakpoint is still present.\n");
301       current_inferior = saved_inferior;
302       return 0;
303     }
304
305   if (debug_threads)
306     fprintf (stderr, "Removed breakpoint.\n");
307
308   /* For decr_pc_after_break targets, here is where we perform the
309      decrement.  We go immediately from this function to resuming,
310      and can not safely call get_stop_pc () again.  */
311   if (the_low_target.set_pc != NULL)
312     (*the_low_target.set_pc) (stop_pc);
313
314   /* We consumed the pending SIGTRAP.  */
315   event_child->pending_is_breakpoint = 0;
316   event_child->status_pending_p = 0;
317   event_child->status_pending = 0;
318
319   current_inferior = saved_inferior;
320   return 1;
321 }
322
323 /* Return 1 if this process has an interesting status pending.  This function
324    may silently resume an inferior process.  */
325 static int
326 status_pending_p (struct inferior_list_entry *entry, void *dummy)
327 {
328   struct process_info *process = (struct process_info *) entry;
329
330   if (process->status_pending_p)
331     if (check_removed_breakpoint (process))
332       {
333         /* This thread was stopped at a breakpoint, and the breakpoint
334            is now gone.  We were told to continue (or step...) all threads,
335            so GDB isn't trying to single-step past this breakpoint.
336            So instead of reporting the old SIGTRAP, pretend we got to
337            the breakpoint just after it was removed instead of just
338            before; resume the process.  */
339         fbsd_resume_one_process (&process->head, 0, 0);
340         return 0;
341       }
342
343   return process->status_pending_p;
344 }
345
346 static void
347 fbsd_wait_for_process (struct process_info **childp, int *wstatp)
348 {
349   int ret;
350   int to_wait_for = -1;
351
352   if (*childp != NULL)
353     to_wait_for = (*childp)->lwpid;
354
355   while (1)
356     {
357       ret = waitpid (to_wait_for, wstatp, WNOHANG);
358
359       if (ret == -1)
360         {
361           if (errno != ECHILD)
362             perror_with_name ("waitpid");
363         }
364       else if (ret > 0)
365         break;
366
367       usleep (1000);
368     }
369
370   if (debug_threads
371       && (!WIFSTOPPED (*wstatp)
372           || (WSTOPSIG (*wstatp) != 32
373               && WSTOPSIG (*wstatp) != 33)))
374     fprintf (stderr, "Got an event from %d (%x)\n", ret, *wstatp);
375
376   if (to_wait_for == -1)
377     *childp = (struct process_info *) find_inferior_id (&all_processes, ret);
378
379   (*childp)->stopped = 1;
380   (*childp)->pending_is_breakpoint = 0;
381
382   if (debug_threads
383       && WIFSTOPPED (*wstatp))
384     {
385       current_inferior = (struct thread_info *)
386         find_inferior_id (&all_threads, (*childp)->tid);
387       /* For testing only; i386_stop_pc prints out a diagnostic.  */
388       if (the_low_target.get_pc != NULL)
389         get_stop_pc ();
390     }
391 }
392
393 static int
394 fbsd_wait_for_event (struct thread_info *child)
395 {
396   CORE_ADDR stop_pc;
397   struct process_info *event_child;
398   int wstat;
399
400   /* Check for a process with a pending status.  */
401   /* It is possible that the user changed the pending task's registers since
402      it stopped.  We correctly handle the change of PC if we hit a breakpoint
403      (in check_removed_breakpoint); signals should be reported anyway.  */
404   if (child == NULL)
405     {
406       event_child = (struct process_info *)
407         find_inferior (&all_processes, status_pending_p, NULL);
408       if (debug_threads && event_child)
409         fprintf (stderr, "Got a pending child %d\n", event_child->lwpid);
410     }
411   else
412     {
413       event_child = get_thread_process (child);
414       if (event_child->status_pending_p
415           && check_removed_breakpoint (event_child))
416         event_child = NULL;
417     }
418
419   if (event_child != NULL)
420     {
421       if (event_child->status_pending_p)
422         {
423           if (debug_threads)
424             fprintf (stderr, "Got an event from pending child %d (%04x)\n",
425                      event_child->lwpid, event_child->status_pending);
426           wstat = event_child->status_pending;
427           event_child->status_pending_p = 0;
428           event_child->status_pending = 0;
429           current_inferior = get_process_thread (event_child);
430           return wstat;
431         }
432     }
433
434   /* We only enter this loop if no process has a pending wait status.  Thus
435      any action taken in response to a wait status inside this loop is
436      responding as soon as we detect the status, not after any pending
437      events.  */
438   while (1)
439     {
440       if (child == NULL)
441         event_child = NULL;
442       else
443         event_child = get_thread_process (child);
444
445       fbsd_wait_for_process (&event_child, &wstat);
446
447       if (event_child == NULL)
448         error ("event from unknown child");
449
450       current_inferior = (struct thread_info *)
451         find_inferior_id (&all_threads, event_child->tid);
452
453       if (using_threads)
454         {
455           /* Check for thread exit.  */
456           if (! WIFSTOPPED (wstat))
457             {
458               if (debug_threads)
459                 fprintf (stderr, "Thread %d (LWP %d) exiting\n",
460                          event_child->tid, event_child->head.id);
461
462               /* If the last thread is exiting, just return.  */
463               if (all_threads.head == all_threads.tail)
464                 return wstat;
465
466               dead_thread_notify (event_child->tid);
467
468               remove_inferior (&all_processes, &event_child->head);
469               free (event_child);
470               remove_thread (current_inferior);
471               current_inferior = (struct thread_info *) all_threads.head;
472
473               /* If we were waiting for this particular child to do something...
474                  well, it did something.  */
475               if (child != NULL)
476                 return wstat;
477
478               /* Wait for a more interesting event.  */
479               continue;
480             }
481
482           if (WIFSTOPPED (wstat)
483               && WSTOPSIG (wstat) == SIGSTOP
484               && event_child->stop_expected)
485             {
486               if (debug_threads)
487                 fprintf (stderr, "Expected stop.\n");
488               event_child->stop_expected = 0;
489               fbsd_resume_one_process (&event_child->head,
490                                         event_child->stepping, 0);
491               continue;
492             }
493
494           /* FIXME drow/2002-06-09: Get signal numbers from the inferior's
495              thread library?  */
496           if (WIFSTOPPED (wstat))
497             {
498               if (debug_threads)
499                 fprintf (stderr, "Ignored signal %d for %d (LWP %d).\n",
500                          WSTOPSIG (wstat), event_child->tid,
501                          event_child->head.id);
502               fbsd_resume_one_process (&event_child->head,
503                                         event_child->stepping,
504                                         WSTOPSIG (wstat));
505               continue;
506             }
507         }
508
509       /* If this event was not handled above, and is not a SIGTRAP, report
510          it.  */
511       if (!WIFSTOPPED (wstat) || WSTOPSIG (wstat) != SIGTRAP)
512         return wstat;
513
514       /* If this target does not support breakpoints, we simply report the
515          SIGTRAP; it's of no concern to us.  */
516       if (the_low_target.get_pc == NULL)
517         return wstat;
518
519       stop_pc = get_stop_pc ();
520
521       /* bp_reinsert will only be set if we were single-stepping.
522          Notice that we will resume the process after hitting
523          a gdbserver breakpoint; single-stepping to/over one
524          is not supported (yet).  */
525       if (event_child->bp_reinsert != 0)
526         {
527           if (debug_threads)
528             fprintf (stderr, "Reinserted breakpoint.\n");
529           reinsert_breakpoint (event_child->bp_reinsert);
530           event_child->bp_reinsert = 0;
531
532           /* Clear the single-stepping flag and SIGTRAP as we resume.  */
533           fbsd_resume_one_process (&event_child->head, 0, 0);
534           continue;
535         }
536
537       if (debug_threads)
538         fprintf (stderr, "Hit a (non-reinsert) breakpoint.\n");
539
540       if (check_breakpoints (stop_pc) != 0)
541         {
542           /* We hit one of our own breakpoints.  We mark it as a pending
543              breakpoint, so that check_removed_breakpoint () will do the PC
544              adjustment for us at the appropriate time.  */
545           event_child->pending_is_breakpoint = 1;
546           event_child->pending_stop_pc = stop_pc;
547
548           /* Now we need to put the breakpoint back.  We continue in the event
549              loop instead of simply replacing the breakpoint right away,
550              in order to not lose signals sent to the thread that hit the
551              breakpoint.  Unfortunately this increases the window where another
552              thread could sneak past the removed breakpoint.  For the current
553              use of server-side breakpoints (thread creation) this is
554              acceptable; but it needs to be considered before this breakpoint
555              mechanism can be used in more general ways.  For some breakpoints
556              it may be necessary to stop all other threads, but that should
557              be avoided where possible.
558
559              If breakpoint_reinsert_addr is NULL, that means that we can
560              use PT_STEP on this platform.  Uninsert the breakpoint,
561              mark it for reinsertion, and single-step.
562
563              Otherwise, call the target function to figure out where we need
564              our temporary breakpoint, create it, and continue executing this
565              process.  */
566           if (the_low_target.breakpoint_reinsert_addr == NULL)
567             {
568               event_child->bp_reinsert = stop_pc;
569               uninsert_breakpoint (stop_pc);
570               fbsd_resume_one_process (&event_child->head, 1, 0);
571             }
572           else
573             {
574               reinsert_breakpoint_by_bp
575                 (stop_pc, (*the_low_target.breakpoint_reinsert_addr) ());
576               fbsd_resume_one_process (&event_child->head, 0, 0);
577             }
578
579           continue;
580         }
581
582       /* If we were single-stepping, we definitely want to report the
583          SIGTRAP.  The single-step operation has completed, so also
584          clear the stepping flag; in general this does not matter,
585          because the SIGTRAP will be reported to the client, which
586          will give us a new action for this thread, but clear it for
587          consistency anyway.  It's safe to clear the stepping flag
588          because the only consumer of get_stop_pc () after this point
589          is check_removed_breakpoint, and pending_is_breakpoint is not
590          set.  It might be wiser to use a step_completed flag instead.  */
591       if (event_child->stepping)
592         {
593           event_child->stepping = 0;
594           return wstat;
595         }
596
597       /* A SIGTRAP that we can't explain.  It may have been a breakpoint.
598          Check if it is a breakpoint, and if so mark the process information
599          accordingly.  This will handle both the necessary fiddling with the
600          PC on decr_pc_after_break targets and suppressing extra threads
601          hitting a breakpoint if two hit it at once and then GDB removes it
602          after the first is reported.  Arguably it would be better to report
603          multiple threads hitting breakpoints simultaneously, but the current
604          remote protocol does not allow this.  */
605       if ((*the_low_target.breakpoint_at) (stop_pc))
606         {
607           event_child->pending_is_breakpoint = 1;
608           event_child->pending_stop_pc = stop_pc;
609         }
610
611       return wstat;
612     }
613
614   /* NOTREACHED */
615   return 0;
616 }
617
618 /* Wait for process, returns status.  */
619
620 static unsigned char
621 fbsd_wait (char *status)
622 {
623   int w;
624   struct thread_info *child = NULL;
625
626 retry:
627   /* If we were only supposed to resume one thread, only wait for
628      that thread - if it's still alive.  If it died, however - which
629      can happen if we're coming from the thread death case below -
630      then we need to make sure we restart the other threads.  We could
631      pick a thread at random or restart all; restarting all is less
632      arbitrary.  */
633   if (cont_thread > 0)
634     {
635       child = (struct thread_info *) find_inferior_id (&all_threads,
636                                                        cont_thread);
637
638       /* No stepping, no signal - unless one is pending already, of course.  */
639       if (child == NULL)
640         {
641           struct thread_resume resume_info;
642           resume_info.thread = -1;
643           resume_info.step = resume_info.sig = resume_info.leave_stopped = 0;
644           fbsd_resume (&resume_info);
645         }
646     }
647
648   enable_async_io ();
649   unblock_async_io ();
650   w = fbsd_wait_for_event (child);
651   stop_all_processes ();
652   disable_async_io ();
653
654   /* If we are waiting for a particular child, and it exited,
655      fbsd_wait_for_event will return its exit status.  Similarly if
656      the last child exited.  If this is not the last child, however,
657      do not report it as exited until there is a 'thread exited' response
658      available in the remote protocol.  Instead, just wait for another event.
659      This should be safe, because if the thread crashed we will already
660      have reported the termination signal to GDB; that should stop any
661      in-progress stepping operations, etc.
662
663      Report the exit status of the last thread to exit.  This matches
664      LinuxThreads' behavior.  */
665
666   if (all_threads.head == all_threads.tail)
667     {
668       if (WIFEXITED (w))
669         {
670           fprintf (stderr, "\nChild exited with retcode = %x \n", WEXITSTATUS (w));
671           *status = 'W';
672           clear_inferiors ();
673           free (all_processes.head);
674           all_processes.head = all_processes.tail = NULL;
675           return ((unsigned char) WEXITSTATUS (w));
676         }
677       else if (!WIFSTOPPED (w))
678         {
679           fprintf (stderr, "\nChild terminated with signal = %x \n", WTERMSIG (w));
680           *status = 'X';
681           clear_inferiors ();
682           free (all_processes.head);
683           all_processes.head = all_processes.tail = NULL;
684           return ((unsigned char) WTERMSIG (w));
685         }
686     }
687   else
688     {
689       if (!WIFSTOPPED (w))
690         goto retry;
691     }
692
693   *status = 'T';
694   return ((unsigned char) WSTOPSIG (w));
695 }
696
697 static void
698 send_sigstop (struct inferior_list_entry *entry)
699 {
700   struct process_info *process = (struct process_info *) entry;
701
702   if (process->stopped)
703     return;
704
705   /* If we already have a pending stop signal for this process, don't
706      send another.  */
707   if (process->stop_expected)
708     {
709       process->stop_expected = 0;
710       return;
711     }
712
713   if (debug_threads)
714     fprintf (stderr, "Sending sigstop to process %d\n", process->head.id);
715
716   kill (process->head.id, SIGSTOP);
717   process->sigstop_sent = 1;
718 }
719
720 static void
721 wait_for_sigstop (struct inferior_list_entry *entry)
722 {
723   struct process_info *process = (struct process_info *) entry;
724   struct thread_info *saved_inferior, *thread;
725   int wstat, saved_tid;
726
727   if (process->stopped)
728     return;
729
730   saved_inferior = current_inferior;
731   saved_tid = ((struct inferior_list_entry *) saved_inferior)->id;
732   thread = (struct thread_info *) find_inferior_id (&all_threads,
733                                                     process->tid);
734   wstat = fbsd_wait_for_event (thread);
735
736   /* If we stopped with a non-SIGSTOP signal, save it for later
737      and record the pending SIGSTOP.  If the process exited, just
738      return.  */
739   if (WIFSTOPPED (wstat)
740       && WSTOPSIG (wstat) != SIGSTOP)
741     {
742       if (debug_threads)
743         fprintf (stderr, "Stopped with non-sigstop signal\n");
744       process->status_pending_p = 1;
745       process->status_pending = wstat;
746       process->stop_expected = 1;
747     }
748
749   if (fbsd_thread_alive (saved_tid))
750     current_inferior = saved_inferior;
751   else
752     {
753       if (debug_threads)
754         fprintf (stderr, "Previously current thread died.\n");
755
756       /* Set a valid thread as current.  */
757       set_desired_inferior (0);
758     }
759 }
760
761 static void
762 stop_all_processes (void)
763 {
764   stopping_threads = 1;
765   for_each_inferior (&all_processes, send_sigstop);
766   for_each_inferior (&all_processes, wait_for_sigstop);
767   stopping_threads = 0;
768 }
769
770 /* Resume execution of the inferior process.
771    If STEP is nonzero, single-step it.
772    If SIGNAL is nonzero, give it that signal.  */
773
774 static void
775 fbsd_resume_one_process (struct inferior_list_entry *entry,
776                           int step, int signal)
777 {
778   struct process_info *process = (struct process_info *) entry;
779   struct thread_info *saved_inferior;
780
781   if (process->stopped == 0)
782     return;
783
784   /* If we have pending signals or status, and a new signal, enqueue the
785      signal.  Also enqueue the signal if we are waiting to reinsert a
786      breakpoint; it will be picked up again below.  */
787   if (signal != 0
788       && (process->status_pending_p || process->pending_signals != NULL
789           || process->bp_reinsert != 0))
790     {
791       struct pending_signals *p_sig;
792       p_sig = malloc (sizeof (*p_sig));
793       p_sig->prev = process->pending_signals;
794       p_sig->signal = signal;
795       process->pending_signals = p_sig;
796     }
797
798   if (process->status_pending_p && !check_removed_breakpoint (process))
799     return;
800
801   saved_inferior = current_inferior;
802   current_inferior = get_process_thread (process);
803
804   if (debug_threads)
805     fprintf (stderr, "Resuming process %d (%s, signal %d, stop %s)\n", inferior_pid,
806              step ? "step" : "continue", signal,
807              process->stop_expected ? "expected" : "not expected");
808
809   /* This bit needs some thinking about.  If we get a signal that
810      we must report while a single-step reinsert is still pending,
811      we often end up resuming the thread.  It might be better to
812      (ew) allow a stack of pending events; then we could be sure that
813      the reinsert happened right away and not lose any signals.
814
815      Making this stack would also shrink the window in which breakpoints are
816      uninserted (see comment in fbsd_wait_for_process) but not enough for
817      complete correctness, so it won't solve that problem.  It may be
818      worthwhile just to solve this one, however.  */
819   if (process->bp_reinsert != 0)
820     {
821       if (debug_threads)
822         fprintf (stderr, "  pending reinsert at %08lx", (long)process->bp_reinsert);
823       if (step == 0)
824         fprintf (stderr, "BAD - reinserting but not stepping.\n");
825       step = 1;
826
827       /* Postpone any pending signal.  It was enqueued above.  */
828       signal = 0;
829     }
830
831   check_removed_breakpoint (process);
832
833   if (debug_threads && the_low_target.get_pc != NULL)
834     {
835       fprintf (stderr, "  ");
836       (long) (*the_low_target.get_pc) ();
837     }
838
839   /* If we have pending signals, consume one unless we are trying to reinsert
840      a breakpoint.  */
841   if (process->pending_signals != NULL && process->bp_reinsert == 0)
842     {
843       struct pending_signals **p_sig;
844
845       p_sig = &process->pending_signals;
846       while ((*p_sig)->prev != NULL)
847         p_sig = &(*p_sig)->prev;
848
849       signal = (*p_sig)->signal;
850       free (*p_sig);
851       *p_sig = NULL;
852     }
853
854   regcache_invalidate_one ((struct inferior_list_entry *)
855                            get_process_thread (process));
856   errno = 0;
857   process->stopped = 0;
858   process->stepping = step;
859   ptrace (step ? PT_STEP : PT_CONTINUE, process->lwpid, (PTRACE_ARG3_TYPE) 1, signal);
860
861   current_inferior = saved_inferior;
862   if (errno)
863     perror_with_name ("ptrace");
864 }
865
866 static struct thread_resume *resume_ptr;
867
868 /* This function is called once per thread.  We look up the thread
869    in RESUME_PTR, and mark the thread with a pointer to the appropriate
870    resume request.
871
872    This algorithm is O(threads * resume elements), but resume elements
873    is small (and will remain small at least until GDB supports thread
874    suspension).  */
875 static void
876 fbsd_set_resume_request (struct inferior_list_entry *entry)
877 {
878   struct process_info *process;
879   struct thread_info *thread;
880   int ndx;
881
882   thread = (struct thread_info *) entry;
883   process = get_thread_process (thread);
884
885   ndx = 0;
886   while (resume_ptr[ndx].thread != -1 && resume_ptr[ndx].thread != entry->id)
887     ndx++;
888
889   process->resume = &resume_ptr[ndx];
890 }
891
892 /* This function is called once per thread.  We check the thread's resume
893    request, which will tell us whether to resume, step, or leave the thread
894    stopped; and what signal, if any, it should be sent.  For threads which
895    we aren't explicitly told otherwise, we preserve the stepping flag; this
896    is used for stepping over gdbserver-placed breakpoints.  */
897
898 static void
899 fbsd_continue_one_thread (struct inferior_list_entry *entry)
900 {
901   struct process_info *process;
902   struct thread_info *thread;
903   int step;
904
905   thread = (struct thread_info *) entry;
906   process = get_thread_process (thread);
907
908   if (process->resume->leave_stopped)
909     return;
910
911   if (process->resume->thread == -1)
912     step = process->stepping || process->resume->step;
913   else
914     step = process->resume->step;
915
916   fbsd_resume_one_process (&process->head, step, process->resume->sig);
917
918   process->resume = NULL;
919 }
920
921 /* This function is called once per thread.  We check the thread's resume
922    request, which will tell us whether to resume, step, or leave the thread
923    stopped; and what signal, if any, it should be sent.  We queue any needed
924    signals, since we won't actually resume.  We already have a pending event
925    to report, so we don't need to preserve any step requests; they should
926    be re-issued if necessary.  */
927
928 static void
929 fbsd_queue_one_thread (struct inferior_list_entry *entry)
930 {
931   struct process_info *process;
932   struct thread_info *thread;
933
934   thread = (struct thread_info *) entry;
935   process = get_thread_process (thread);
936
937   if (process->resume->leave_stopped)
938     return;
939
940   /* If we have a new signal, enqueue the signal.  */
941   if (process->resume->sig != 0)
942     {
943       struct pending_signals *p_sig;
944       p_sig = malloc (sizeof (*p_sig));
945       p_sig->prev = process->pending_signals;
946       p_sig->signal = process->resume->sig;
947       process->pending_signals = p_sig;
948     }
949
950   process->resume = NULL;
951 }
952
953 /* Set DUMMY if this process has an interesting status pending.  */
954 static int
955 resume_status_pending_p (struct inferior_list_entry *entry, void *flag_p)
956 {
957   struct process_info *process = (struct process_info *) entry;
958
959   /* Processes which will not be resumed are not interesting, because
960      we might not wait for them next time through fbsd_wait.  */
961   if (process->resume->leave_stopped)
962     return 0;
963
964   /* If this thread has a removed breakpoint, we won't have any
965      events to report later, so check now.  check_removed_breakpoint
966      may clear status_pending_p.  We avoid calling check_removed_breakpoint
967      for any thread that we are not otherwise going to resume - this
968      lets us preserve stopped status when two threads hit a breakpoint.
969      GDB removes the breakpoint to single-step a particular thread
970      past it, then re-inserts it and resumes all threads.  We want
971      to report the second thread without resuming it in the interim.  */
972   if (process->status_pending_p)
973     check_removed_breakpoint (process);
974
975   if (process->status_pending_p)
976     * (int *) flag_p = 1;
977
978   return 0;
979 }
980
981 static void
982 fbsd_resume (struct thread_resume *resume_info)
983 {
984   int pending_flag;
985
986   /* Yes, the use of a global here is rather ugly.  */
987   resume_ptr = resume_info;
988
989   for_each_inferior (&all_threads, fbsd_set_resume_request);
990
991   /* If there is a thread which would otherwise be resumed, which
992      has a pending status, then don't resume any threads - we can just
993      report the pending status.  Make sure to queue any signals
994      that would otherwise be sent.  */
995   pending_flag = 0;
996   find_inferior (&all_processes, resume_status_pending_p, &pending_flag);
997
998   if (debug_threads)
999     {
1000       if (pending_flag)
1001         fprintf (stderr, "Not resuming, pending status\n");
1002       else
1003         fprintf (stderr, "Resuming, no pending status\n");
1004     }
1005
1006   if (pending_flag)
1007     for_each_inferior (&all_threads, fbsd_queue_one_thread);
1008   else
1009     {
1010       block_async_io ();
1011       enable_async_io ();
1012       for_each_inferior (&all_threads, fbsd_continue_one_thread);
1013     }
1014 }
1015
1016
1017 static int
1018 regsets_fetch_inferior_registers ()
1019 {
1020   struct regset_info *regset;
1021
1022   regset = target_regsets;
1023
1024   while (regset->size >= 0)
1025     {
1026       void *buf;
1027       int res;
1028
1029       if (regset->size == 0)
1030         {
1031           regset ++;
1032           continue;
1033         }
1034
1035       buf = malloc (regset->size);
1036       res = ptrace (regset->get_request, inferior_pid, (PTRACE_ARG3_TYPE) buf, 0);
1037       if (res < 0)
1038         {
1039           char s[256];
1040           sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%d",
1041                    inferior_pid);
1042           perror (s);
1043         }
1044       regset->store_function (buf);
1045       regset ++;
1046     }
1047   return 0;
1048 }
1049
1050 static int
1051 regsets_store_inferior_registers ()
1052 {
1053   struct regset_info *regset;
1054
1055   regset = target_regsets;
1056
1057   while (regset->size >= 0)
1058     {
1059       void *buf;
1060       int res;
1061
1062       if (regset->size == 0)
1063         {
1064           regset ++;
1065           continue;
1066         }
1067
1068       buf = malloc (regset->size);
1069       regset->fill_function (buf);
1070       res = ptrace (regset->set_request, inferior_pid, (PTRACE_ARG3_TYPE) buf, 0);
1071       if (res < 0)
1072         {
1073           perror ("Warning: ptrace(regsets_store_inferior_registers)");
1074         }
1075       regset ++;
1076       free (buf);
1077     }
1078   return 0;
1079 }
1080
1081 void
1082 fbsd_fetch_registers (int regno)
1083 {
1084       regsets_fetch_inferior_registers ();
1085 }
1086
1087 void
1088 fbsd_store_registers (int regno)
1089 {
1090       regsets_store_inferior_registers ();
1091 }
1092
1093
1094 /* Copy LEN bytes from inferior's memory starting at MEMADDR
1095    to debugger memory starting at MYADDR.  */
1096
1097 static int
1098 fbsd_read_memory (CORE_ADDR memaddr, char *myaddr, int len)
1099 {
1100   register int i;
1101   /* Round starting address down to longword boundary.  */
1102   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
1103   /* Round ending address up; get number of longwords that makes.  */
1104   register int count
1105     = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
1106       / sizeof (PTRACE_XFER_TYPE);
1107   /* Allocate buffer of that many longwords.  */
1108   register PTRACE_XFER_TYPE *buffer
1109     = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
1110
1111   /* Read all the longwords */
1112   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
1113     {
1114       errno = 0;
1115       buffer[i] = ptrace (PT_READ_D, inferior_pid, (PTRACE_ARG3_TYPE) (intptr_t)addr, 0);
1116       if (errno)
1117         return errno;
1118     }
1119
1120   /* Copy appropriate bytes out of the buffer.  */
1121   memcpy (myaddr, (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
1122
1123   return 0;
1124 }
1125
1126 /* Copy LEN bytes of data from debugger memory at MYADDR
1127    to inferior's memory at MEMADDR.
1128    On failure (cannot write the inferior)
1129    returns the value of errno.  */
1130
1131 static int
1132 fbsd_write_memory (CORE_ADDR memaddr, const char *myaddr, int len)
1133 {
1134   register int i;
1135   /* Round starting address down to longword boundary.  */
1136   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
1137   /* Round ending address up; get number of longwords that makes.  */
1138   register int count
1139   = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1) / sizeof (PTRACE_XFER_TYPE);
1140   /* Allocate buffer of that many longwords.  */
1141   register PTRACE_XFER_TYPE *buffer = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
1142   extern int errno;
1143
1144   if (debug_threads)
1145     {
1146       fprintf (stderr, "Writing %02x to %08lx\n", (unsigned)myaddr[0], (long)memaddr);
1147     }
1148
1149   /* Fill start and end extra bytes of buffer with existing memory data.  */
1150
1151   buffer[0] = ptrace (PT_READ_D, inferior_pid,
1152                       (PTRACE_ARG3_TYPE) (intptr_t)addr, 0);
1153
1154   if (count > 1)
1155     {
1156       buffer[count - 1]
1157         = ptrace (PT_READ_D, inferior_pid,
1158                   (PTRACE_ARG3_TYPE) (intptr_t) (addr + (count - 1)
1159                                       * sizeof (PTRACE_XFER_TYPE)),
1160                   0);
1161     }
1162
1163   /* Copy data to be written over corresponding part of buffer */
1164
1165   memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), myaddr, len);
1166
1167   /* Write the entire buffer.  */
1168
1169   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
1170     {
1171       errno = 0;
1172       ptrace (PT_WRITE_D, inferior_pid, (PTRACE_ARG3_TYPE) (intptr_t)addr, buffer[i]);
1173       if (errno)
1174         return errno;
1175     }
1176
1177   return 0;
1178 }
1179
1180 static void
1181 fbsd_look_up_symbols (void)
1182 {
1183 #ifdef USE_THREAD_DB
1184   if (using_threads)
1185     return;
1186
1187   using_threads = thread_db_init ();
1188 #endif
1189 }
1190
1191 static void
1192 fbsd_send_signal (int signum)
1193 {
1194   extern int signal_pid;
1195
1196   if (cont_thread > 0)
1197     {
1198       struct process_info *process;
1199
1200       process = get_thread_process (current_inferior);
1201       kill (process->lwpid, signum);
1202     }
1203   else
1204     kill (signal_pid, signum);
1205 }
1206
1207 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
1208    to debugger memory starting at MYADDR.  */
1209
1210 static int
1211 fbsd_read_auxv (CORE_ADDR offset, char *myaddr, unsigned int len)
1212 {
1213   char filename[PATH_MAX];
1214   int fd, n;
1215
1216   snprintf (filename, sizeof filename, "/proc/%d/auxv", inferior_pid);
1217
1218   fd = open (filename, O_RDONLY);
1219   if (fd < 0)
1220     return -1;
1221
1222   if (offset != (CORE_ADDR) 0
1223       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
1224     n = -1;
1225   else
1226     n = read (fd, myaddr, len);
1227
1228   close (fd);
1229
1230   return n;
1231 }
1232
1233 \f
1234 static struct target_ops fbsd_target_ops = {
1235   fbsd_create_inferior,
1236   fbsd_attach,
1237   fbsd_kill,
1238   fbsd_detach,
1239   fbsd_thread_alive,
1240   fbsd_resume,
1241   fbsd_wait,
1242   fbsd_fetch_registers,
1243   fbsd_store_registers,
1244   fbsd_read_memory,
1245   fbsd_write_memory,
1246   fbsd_look_up_symbols,
1247   fbsd_send_signal,
1248   fbsd_read_auxv,
1249 };
1250
1251 static void
1252 fbsd_init_signals ()
1253 {
1254 }
1255
1256 void
1257 initialize_low (void)
1258 {
1259   using_threads = 0;
1260   set_target_ops (&fbsd_target_ops);
1261   set_breakpoint_data (the_low_target.breakpoint,
1262                        the_low_target.breakpoint_len);
1263   init_registers ();
1264   fbsd_init_signals ();
1265 }