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