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