8a882376e6944d11db4251c23be339960f3e97e2
[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 #include "ansidecl.h" /* For ATTRIBUTE_PACKED, must be bug in external.h.  */
23 #include "elf/common.h"
24 #include "elf/external.h"
25
26 #include <sys/wait.h>
27 #include <stdio.h>
28 #include <sys/param.h>
29 #include <sys/ptrace.h>
30 #include <signal.h>
31 #include <sys/ioctl.h>
32 #include <fcntl.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <sys/syscall.h>
38 #include <sched.h>
39 #include <ctype.h>
40 #include <pwd.h>
41 #include <sys/types.h>
42 #include <dirent.h>
43 #include <sys/stat.h>
44 #include <sys/vfs.h>
45
46 #ifndef SPUFS_MAGIC
47 #define SPUFS_MAGIC 0x23c9b64e
48 #endif
49
50 #ifndef PTRACE_GETSIGINFO
51 # define PTRACE_GETSIGINFO 0x4202
52 # define PTRACE_SETSIGINFO 0x4203
53 #endif
54
55 #ifndef O_LARGEFILE
56 #define O_LARGEFILE 0
57 #endif
58
59 /* If the system headers did not provide the constants, hard-code the normal
60    values.  */
61 #ifndef PTRACE_EVENT_FORK
62
63 #define PTRACE_SETOPTIONS       0x4200
64 #define PTRACE_GETEVENTMSG      0x4201
65
66 /* options set using PTRACE_SETOPTIONS */
67 #define PTRACE_O_TRACESYSGOOD   0x00000001
68 #define PTRACE_O_TRACEFORK      0x00000002
69 #define PTRACE_O_TRACEVFORK     0x00000004
70 #define PTRACE_O_TRACECLONE     0x00000008
71 #define PTRACE_O_TRACEEXEC      0x00000010
72 #define PTRACE_O_TRACEVFORKDONE 0x00000020
73 #define PTRACE_O_TRACEEXIT      0x00000040
74
75 /* Wait extended result codes for the above trace options.  */
76 #define PTRACE_EVENT_FORK       1
77 #define PTRACE_EVENT_VFORK      2
78 #define PTRACE_EVENT_CLONE      3
79 #define PTRACE_EVENT_EXEC       4
80 #define PTRACE_EVENT_VFORK_DONE 5
81 #define PTRACE_EVENT_EXIT       6
82
83 #endif /* PTRACE_EVENT_FORK */
84
85 /* We can't always assume that this flag is available, but all systems
86    with the ptrace event handlers also have __WALL, so it's safe to use
87    in some contexts.  */
88 #ifndef __WALL
89 #define __WALL          0x40000000 /* Wait for any child.  */
90 #endif
91
92 #ifdef __UCLIBC__
93 #if !(defined(__UCLIBC_HAS_MMU__) || defined(__ARCH_HAS_MMU__))
94 #define HAS_NOMMU
95 #endif
96 #endif
97
98 /* ``all_threads'' is keyed by the LWP ID, which we use as the GDB protocol
99    representation of the thread ID.
100
101    ``all_lwps'' is keyed by the process ID - which on Linux is (presently)
102    the same as the LWP ID.
103
104    ``all_processes'' is keyed by the "overall process ID", which
105    GNU/Linux calls tgid, "thread group ID".  */
106
107 struct inferior_list all_lwps;
108
109 /* A list of all unknown processes which receive stop signals.  Some other
110    process will presumably claim each of these as forked children
111    momentarily.  */
112
113 struct inferior_list stopped_pids;
114
115 /* FIXME this is a bit of a hack, and could be removed.  */
116 int stopping_threads;
117
118 /* FIXME make into a target method?  */
119 int using_threads = 1;
120
121 /* This flag is true iff we've just created or attached to our first
122    inferior but it has not stopped yet.  As soon as it does, we need
123    to call the low target's arch_setup callback.  Doing this only on
124    the first inferior avoids reinializing the architecture on every
125    inferior, and avoids messing with the register caches of the
126    already running inferiors.  NOTE: this assumes all inferiors under
127    control of gdbserver have the same architecture.  */
128 static int new_inferior;
129
130 static void linux_resume_one_lwp (struct lwp_info *lwp,
131                                   int step, int signal, siginfo_t *info);
132 static void linux_resume (struct thread_resume *resume_info, size_t n);
133 static void stop_all_lwps (void);
134 static int linux_wait_for_event (ptid_t ptid, int *wstat, int options);
135 static int check_removed_breakpoint (struct lwp_info *event_child);
136 static void *add_lwp (ptid_t ptid);
137 static int my_waitpid (int pid, int *status, int flags);
138 static int linux_stopped_by_watchpoint (void);
139 static void mark_lwp_dead (struct lwp_info *lwp, int wstat);
140
141 struct pending_signals
142 {
143   int signal;
144   siginfo_t info;
145   struct pending_signals *prev;
146 };
147
148 #define PTRACE_ARG3_TYPE long
149 #define PTRACE_XFER_TYPE long
150
151 #ifdef HAVE_LINUX_REGSETS
152 static char *disabled_regsets;
153 static int num_regsets;
154 #endif
155
156 /* The read/write ends of the pipe registered as waitable file in the
157    event loop.  */
158 static int linux_event_pipe[2] = { -1, -1 };
159
160 /* True if we're currently in async mode.  */
161 #define target_is_async_p() (linux_event_pipe[0] != -1)
162
163 static void send_sigstop (struct inferior_list_entry *entry);
164 static void wait_for_sigstop (struct inferior_list_entry *entry);
165
166 /* Accepts an integer PID; Returns a string representing a file that
167    can be opened to get info for the child process.
168    Space for the result is malloc'd, caller must free.  */
169
170 char *
171 linux_child_pid_to_exec_file (int pid)
172 {
173   char *name1, *name2;
174
175   name1 = xmalloc (MAXPATHLEN);
176   name2 = xmalloc (MAXPATHLEN);
177   memset (name2, 0, MAXPATHLEN);
178
179   sprintf (name1, "/proc/%d/exe", pid);
180   if (readlink (name1, name2, MAXPATHLEN) > 0)
181     {
182       free (name1);
183       return name2;
184     }
185   else
186     {
187       free (name2);
188       return name1;
189     }
190 }
191
192 /* Return non-zero if HEADER is a 64-bit ELF file.  */
193
194 static int
195 elf_64_header_p (const Elf64_External_Ehdr *header)
196 {
197   return (header->e_ident[EI_MAG0] == ELFMAG0
198           && header->e_ident[EI_MAG1] == ELFMAG1
199           && header->e_ident[EI_MAG2] == ELFMAG2
200           && header->e_ident[EI_MAG3] == ELFMAG3
201           && header->e_ident[EI_CLASS] == ELFCLASS64);
202 }
203
204 /* Return non-zero if FILE is a 64-bit ELF file,
205    zero if the file is not a 64-bit ELF file,
206    and -1 if the file is not accessible or doesn't exist.  */
207
208 int
209 elf_64_file_p (const char *file)
210 {
211   Elf64_External_Ehdr header;
212   int fd;
213
214   fd = open (file, O_RDONLY);
215   if (fd < 0)
216     return -1;
217
218   if (read (fd, &header, sizeof (header)) != sizeof (header))
219     {
220       close (fd);
221       return 0;
222     }
223   close (fd);
224
225   return elf_64_header_p (&header);
226 }
227
228 static void
229 delete_lwp (struct lwp_info *lwp)
230 {
231   remove_thread (get_lwp_thread (lwp));
232   remove_inferior (&all_lwps, &lwp->head);
233   free (lwp->arch_private);
234   free (lwp);
235 }
236
237 /* Add a process to the common process list, and set its private
238    data.  */
239
240 static struct process_info *
241 linux_add_process (int pid, int attached)
242 {
243   struct process_info *proc;
244
245   /* Is this the first process?  If so, then set the arch.  */
246   if (all_processes.head == NULL)
247     new_inferior = 1;
248
249   proc = add_process (pid, attached);
250   proc->private = xcalloc (1, sizeof (*proc->private));
251
252   if (the_low_target.new_process != NULL)
253     proc->private->arch_private = the_low_target.new_process ();
254
255   return proc;
256 }
257
258 /* Remove a process from the common process list,
259    also freeing all private data.  */
260
261 static void
262 linux_remove_process (struct process_info *process)
263 {
264   struct process_info_private *priv = process->private;
265
266 #ifdef USE_THREAD_DB
267   thread_db_free (process);
268 #endif
269
270   free (priv->arch_private);
271   free (priv);
272   remove_process (process);
273 }
274
275 /* Handle a GNU/Linux extended wait response.  If we see a clone
276    event, we need to add the new LWP to our list (and not report the
277    trap to higher layers).  */
278
279 static void
280 handle_extended_wait (struct lwp_info *event_child, int wstat)
281 {
282   int event = wstat >> 16;
283   struct lwp_info *new_lwp;
284
285   if (event == PTRACE_EVENT_CLONE)
286     {
287       ptid_t ptid;
288       unsigned long new_pid;
289       int ret, status = W_STOPCODE (SIGSTOP);
290
291       ptrace (PTRACE_GETEVENTMSG, lwpid_of (event_child), 0, &new_pid);
292
293       /* If we haven't already seen the new PID stop, wait for it now.  */
294       if (! pull_pid_from_list (&stopped_pids, new_pid))
295         {
296           /* The new child has a pending SIGSTOP.  We can't affect it until it
297              hits the SIGSTOP, but we're already attached.  */
298
299           ret = my_waitpid (new_pid, &status, __WALL);
300
301           if (ret == -1)
302             perror_with_name ("waiting for new child");
303           else if (ret != new_pid)
304             warning ("wait returned unexpected PID %d", ret);
305           else if (!WIFSTOPPED (status))
306             warning ("wait returned unexpected status 0x%x", status);
307         }
308
309       ptrace (PTRACE_SETOPTIONS, new_pid, 0, PTRACE_O_TRACECLONE);
310
311       ptid = ptid_build (pid_of (event_child), new_pid, 0);
312       new_lwp = (struct lwp_info *) add_lwp (ptid);
313       add_thread (ptid, new_lwp);
314
315       /* Either we're going to immediately resume the new thread
316          or leave it stopped.  linux_resume_one_lwp is a nop if it
317          thinks the thread is currently running, so set this first
318          before calling linux_resume_one_lwp.  */
319       new_lwp->stopped = 1;
320
321       /* Normally we will get the pending SIGSTOP.  But in some cases
322          we might get another signal delivered to the group first.
323          If we do get another signal, be sure not to lose it.  */
324       if (WSTOPSIG (status) == SIGSTOP)
325         {
326           if (! stopping_threads)
327             linux_resume_one_lwp (new_lwp, 0, 0, NULL);
328         }
329       else
330         {
331           new_lwp->stop_expected = 1;
332           if (stopping_threads)
333             {
334               new_lwp->status_pending_p = 1;
335               new_lwp->status_pending = status;
336             }
337           else
338             /* Pass the signal on.  This is what GDB does - except
339                shouldn't we really report it instead?  */
340             linux_resume_one_lwp (new_lwp, 0, WSTOPSIG (status), NULL);
341         }
342
343       /* Always resume the current thread.  If we are stopping
344          threads, it will have a pending SIGSTOP; we may as well
345          collect it now.  */
346       linux_resume_one_lwp (event_child, event_child->stepping, 0, NULL);
347     }
348 }
349
350 /* This function should only be called if the process got a SIGTRAP.
351    The SIGTRAP could mean several things.
352
353    On i386, where decr_pc_after_break is non-zero:
354    If we were single-stepping this process using PTRACE_SINGLESTEP,
355    we will get only the one SIGTRAP (even if the instruction we
356    stepped over was a breakpoint).  The value of $eip will be the
357    next instruction.
358    If we continue the process using PTRACE_CONT, we will get a
359    SIGTRAP when we hit a breakpoint.  The value of $eip will be
360    the instruction after the breakpoint (i.e. needs to be
361    decremented).  If we report the SIGTRAP to GDB, we must also
362    report the undecremented PC.  If we cancel the SIGTRAP, we
363    must resume at the decremented PC.
364
365    (Presumably, not yet tested) On a non-decr_pc_after_break machine
366    with hardware or kernel single-step:
367    If we single-step over a breakpoint instruction, our PC will
368    point at the following instruction.  If we continue and hit a
369    breakpoint instruction, our PC will point at the breakpoint
370    instruction.  */
371
372 static CORE_ADDR
373 get_stop_pc (void)
374 {
375   CORE_ADDR stop_pc = (*the_low_target.get_pc) ();
376
377   if (! get_thread_lwp (current_inferior)->stepping)
378     stop_pc -= the_low_target.decr_pc_after_break;
379
380   if (debug_threads)
381     fprintf (stderr, "stop pc is 0x%lx\n", (long) stop_pc);
382
383   return stop_pc;
384 }
385
386 static void *
387 add_lwp (ptid_t ptid)
388 {
389   struct lwp_info *lwp;
390
391   lwp = (struct lwp_info *) xmalloc (sizeof (*lwp));
392   memset (lwp, 0, sizeof (*lwp));
393
394   lwp->head.id = ptid;
395
396   if (the_low_target.new_thread != NULL)
397     lwp->arch_private = the_low_target.new_thread ();
398
399   add_inferior_to_list (&all_lwps, &lwp->head);
400
401   return lwp;
402 }
403
404 /* Start an inferior process and returns its pid.
405    ALLARGS is a vector of program-name and args. */
406
407 static int
408 linux_create_inferior (char *program, char **allargs)
409 {
410   struct lwp_info *new_lwp;
411   int pid;
412   ptid_t ptid;
413
414 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
415   pid = vfork ();
416 #else
417   pid = fork ();
418 #endif
419   if (pid < 0)
420     perror_with_name ("fork");
421
422   if (pid == 0)
423     {
424       ptrace (PTRACE_TRACEME, 0, 0, 0);
425
426       signal (__SIGRTMIN + 1, SIG_DFL);
427
428       setpgid (0, 0);
429
430       execv (program, allargs);
431       if (errno == ENOENT)
432         execvp (program, allargs);
433
434       fprintf (stderr, "Cannot exec %s: %s.\n", program,
435                strerror (errno));
436       fflush (stderr);
437       _exit (0177);
438     }
439
440   linux_add_process (pid, 0);
441
442   ptid = ptid_build (pid, pid, 0);
443   new_lwp = add_lwp (ptid);
444   add_thread (ptid, new_lwp);
445   new_lwp->must_set_ptrace_flags = 1;
446
447   return pid;
448 }
449
450 /* Attach to an inferior process.  */
451
452 static void
453 linux_attach_lwp_1 (unsigned long lwpid, int initial)
454 {
455   ptid_t ptid;
456   struct lwp_info *new_lwp;
457
458   if (ptrace (PTRACE_ATTACH, lwpid, 0, 0) != 0)
459     {
460       if (!initial)
461         {
462           /* If we fail to attach to an LWP, just warn.  */
463           fprintf (stderr, "Cannot attach to lwp %ld: %s (%d)\n", lwpid,
464                    strerror (errno), errno);
465           fflush (stderr);
466           return;
467         }
468       else
469         /* If we fail to attach to a process, report an error.  */
470         error ("Cannot attach to lwp %ld: %s (%d)\n", lwpid,
471                strerror (errno), errno);
472     }
473
474   if (initial)
475     /* NOTE/FIXME: This lwp might have not been the tgid.  */
476     ptid = ptid_build (lwpid, lwpid, 0);
477   else
478     {
479       /* Note that extracting the pid from the current inferior is
480          safe, since we're always called in the context of the same
481          process as this new thread.  */
482       int pid = pid_of (get_thread_lwp (current_inferior));
483       ptid = ptid_build (pid, lwpid, 0);
484     }
485
486   new_lwp = (struct lwp_info *) add_lwp (ptid);
487   add_thread (ptid, new_lwp);
488
489   /* We need to wait for SIGSTOP before being able to make the next
490      ptrace call on this LWP.  */
491   new_lwp->must_set_ptrace_flags = 1;
492
493   /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
494      brings it to a halt.
495
496      There are several cases to consider here:
497
498      1) gdbserver has already attached to the process and is being notified
499         of a new thread that is being created.
500         In this case we should ignore that SIGSTOP and resume the process.
501         This is handled below by setting stop_expected = 1.
502
503      2) This is the first thread (the process thread), and we're attaching
504         to it via attach_inferior.
505         In this case we want the process thread to stop.
506         This is handled by having linux_attach clear stop_expected after
507         we return.
508         ??? If the process already has several threads we leave the other
509         threads running.
510
511      3) GDB is connecting to gdbserver and is requesting an enumeration of all
512         existing threads.
513         In this case we want the thread to stop.
514         FIXME: This case is currently not properly handled.
515         We should wait for the SIGSTOP but don't.  Things work apparently
516         because enough time passes between when we ptrace (ATTACH) and when
517         gdb makes the next ptrace call on the thread.
518
519      On the other hand, if we are currently trying to stop all threads, we
520      should treat the new thread as if we had sent it a SIGSTOP.  This works
521      because we are guaranteed that the add_lwp call above added us to the
522      end of the list, and so the new thread has not yet reached
523      wait_for_sigstop (but will).  */
524   if (! stopping_threads)
525     new_lwp->stop_expected = 1;
526 }
527
528 void
529 linux_attach_lwp (unsigned long lwpid)
530 {
531   linux_attach_lwp_1 (lwpid, 0);
532 }
533
534 int
535 linux_attach (unsigned long pid)
536 {
537   struct lwp_info *lwp;
538
539   linux_attach_lwp_1 (pid, 1);
540
541   linux_add_process (pid, 1);
542
543   if (!non_stop)
544     {
545       /* Don't ignore the initial SIGSTOP if we just attached to this
546          process.  It will be collected by wait shortly.  */
547       lwp = (struct lwp_info *) find_inferior_id (&all_lwps,
548                                                   ptid_build (pid, pid, 0));
549       lwp->stop_expected = 0;
550     }
551
552   return 0;
553 }
554
555 struct counter
556 {
557   int pid;
558   int count;
559 };
560
561 static int
562 second_thread_of_pid_p (struct inferior_list_entry *entry, void *args)
563 {
564   struct counter *counter = args;
565
566   if (ptid_get_pid (entry->id) == counter->pid)
567     {
568       if (++counter->count > 1)
569         return 1;
570     }
571
572   return 0;
573 }
574
575 static int
576 last_thread_of_process_p (struct thread_info *thread)
577 {
578   ptid_t ptid = ((struct inferior_list_entry *)thread)->id;
579   int pid = ptid_get_pid (ptid);
580   struct counter counter = { pid , 0 };
581
582   return (find_inferior (&all_threads,
583                          second_thread_of_pid_p, &counter) == NULL);
584 }
585
586 /* Kill the inferior lwp.  */
587
588 static int
589 linux_kill_one_lwp (struct inferior_list_entry *entry, void *args)
590 {
591   struct thread_info *thread = (struct thread_info *) entry;
592   struct lwp_info *lwp = get_thread_lwp (thread);
593   int wstat;
594   int pid = * (int *) args;
595
596   if (ptid_get_pid (entry->id) != pid)
597     return 0;
598
599   /* We avoid killing the first thread here, because of a Linux kernel (at
600      least 2.6.0-test7 through 2.6.8-rc4) bug; if we kill the parent before
601      the children get a chance to be reaped, it will remain a zombie
602      forever.  */
603
604   if (lwpid_of (lwp) == pid)
605     {
606       if (debug_threads)
607         fprintf (stderr, "lkop: is last of process %s\n",
608                  target_pid_to_str (entry->id));
609       return 0;
610     }
611
612   /* If we're killing a running inferior, make sure it is stopped
613      first, as PTRACE_KILL will not work otherwise.  */
614   if (!lwp->stopped)
615     send_sigstop (&lwp->head);
616
617   do
618     {
619       ptrace (PTRACE_KILL, lwpid_of (lwp), 0, 0);
620
621       /* Make sure it died.  The loop is most likely unnecessary.  */
622       pid = linux_wait_for_event (lwp->head.id, &wstat, __WALL);
623     } while (pid > 0 && WIFSTOPPED (wstat));
624
625   return 0;
626 }
627
628 static int
629 linux_kill (int pid)
630 {
631   struct process_info *process;
632   struct lwp_info *lwp;
633   struct thread_info *thread;
634   int wstat;
635   int lwpid;
636
637   process = find_process_pid (pid);
638   if (process == NULL)
639     return -1;
640
641   find_inferior (&all_threads, linux_kill_one_lwp, &pid);
642
643   /* See the comment in linux_kill_one_lwp.  We did not kill the first
644      thread in the list, so do so now.  */
645   lwp = find_lwp_pid (pid_to_ptid (pid));
646   thread = get_lwp_thread (lwp);
647
648   if (debug_threads)
649     fprintf (stderr, "lk_1: killing lwp %ld, for pid: %d\n",
650              lwpid_of (lwp), pid);
651
652   /* If we're killing a running inferior, make sure it is stopped
653      first, as PTRACE_KILL will not work otherwise.  */
654   if (!lwp->stopped)
655     send_sigstop (&lwp->head);
656
657   do
658     {
659       ptrace (PTRACE_KILL, lwpid_of (lwp), 0, 0);
660
661       /* Make sure it died.  The loop is most likely unnecessary.  */
662       lwpid = linux_wait_for_event (lwp->head.id, &wstat, __WALL);
663     } while (lwpid > 0 && WIFSTOPPED (wstat));
664
665   delete_lwp (lwp);
666   linux_remove_process (process);
667   return 0;
668 }
669
670 static int
671 linux_detach_one_lwp (struct inferior_list_entry *entry, void *args)
672 {
673   struct thread_info *thread = (struct thread_info *) entry;
674   struct lwp_info *lwp = get_thread_lwp (thread);
675   int pid = * (int *) args;
676
677   if (ptid_get_pid (entry->id) != pid)
678     return 0;
679
680   /* If we're detaching from a running inferior, make sure it is
681      stopped first, as PTRACE_DETACH will not work otherwise.  */
682   if (!lwp->stopped)
683     {
684       int lwpid = lwpid_of (lwp);
685
686       stopping_threads = 1;
687       send_sigstop (&lwp->head);
688
689       /* If this detects a new thread through a clone event, the new
690          thread is appended to the end of the lwp list, so we'll
691          eventually detach from it.  */
692       wait_for_sigstop (&lwp->head);
693       stopping_threads = 0;
694
695       /* If LWP exits while we're trying to stop it, there's nothing
696          left to do.  */
697       lwp = find_lwp_pid (pid_to_ptid (lwpid));
698       if (lwp == NULL)
699         return 0;
700     }
701
702   /* Make sure the process isn't stopped at a breakpoint that's
703      no longer there.  */
704   check_removed_breakpoint (lwp);
705
706   /* If this process is stopped but is expecting a SIGSTOP, then make
707      sure we take care of that now.  This isn't absolutely guaranteed
708      to collect the SIGSTOP, but is fairly likely to.  */
709   if (lwp->stop_expected)
710     {
711       int wstat;
712       /* Clear stop_expected, so that the SIGSTOP will be reported.  */
713       lwp->stop_expected = 0;
714       if (lwp->stopped)
715         linux_resume_one_lwp (lwp, 0, 0, NULL);
716       linux_wait_for_event (lwp->head.id, &wstat, __WALL);
717     }
718
719   /* Flush any pending changes to the process's registers.  */
720   regcache_invalidate_one ((struct inferior_list_entry *)
721                            get_lwp_thread (lwp));
722
723   /* Finally, let it resume.  */
724   ptrace (PTRACE_DETACH, lwpid_of (lwp), 0, 0);
725
726   delete_lwp (lwp);
727   return 0;
728 }
729
730 static int
731 any_thread_of (struct inferior_list_entry *entry, void *args)
732 {
733   int *pid_p = args;
734
735   if (ptid_get_pid (entry->id) == *pid_p)
736     return 1;
737
738   return 0;
739 }
740
741 static int
742 linux_detach (int pid)
743 {
744   struct process_info *process;
745
746   process = find_process_pid (pid);
747   if (process == NULL)
748     return -1;
749
750   current_inferior =
751     (struct thread_info *) find_inferior (&all_threads, any_thread_of, &pid);
752
753   delete_all_breakpoints ();
754   find_inferior (&all_threads, linux_detach_one_lwp, &pid);
755   linux_remove_process (process);
756   return 0;
757 }
758
759 static void
760 linux_join (int pid)
761 {
762   int status, ret;
763   struct process_info *process;
764
765   process = find_process_pid (pid);
766   if (process == NULL)
767     return;
768
769   do {
770     ret = my_waitpid (pid, &status, 0);
771     if (WIFEXITED (status) || WIFSIGNALED (status))
772       break;
773   } while (ret != -1 || errno != ECHILD);
774 }
775
776 /* Return nonzero if the given thread is still alive.  */
777 static int
778 linux_thread_alive (ptid_t ptid)
779 {
780   struct lwp_info *lwp = find_lwp_pid (ptid);
781
782   /* We assume we always know if a thread exits.  If a whole process
783      exited but we still haven't been able to report it to GDB, we'll
784      hold on to the last lwp of the dead process.  */
785   if (lwp != NULL)
786     return !lwp->dead;
787   else
788     return 0;
789 }
790
791 /* Return nonzero if this process stopped at a breakpoint which
792    no longer appears to be inserted.  Also adjust the PC
793    appropriately to resume where the breakpoint used to be.  */
794 static int
795 check_removed_breakpoint (struct lwp_info *event_child)
796 {
797   CORE_ADDR stop_pc;
798   struct thread_info *saved_inferior;
799
800   if (event_child->pending_is_breakpoint == 0)
801     return 0;
802
803   if (debug_threads)
804     fprintf (stderr, "Checking for breakpoint in lwp %ld.\n",
805              lwpid_of (event_child));
806
807   saved_inferior = current_inferior;
808   current_inferior = get_lwp_thread (event_child);
809
810   stop_pc = get_stop_pc ();
811
812   /* If the PC has changed since we stopped, then we shouldn't do
813      anything.  This happens if, for instance, GDB handled the
814      decr_pc_after_break subtraction itself.  */
815   if (stop_pc != event_child->pending_stop_pc)
816     {
817       if (debug_threads)
818         fprintf (stderr, "Ignoring, PC was changed.  Old PC was 0x%08llx\n",
819                  event_child->pending_stop_pc);
820
821       event_child->pending_is_breakpoint = 0;
822       current_inferior = saved_inferior;
823       return 0;
824     }
825
826   /* If the breakpoint is still there, we will report hitting it.  */
827   if ((*the_low_target.breakpoint_at) (stop_pc))
828     {
829       if (debug_threads)
830         fprintf (stderr, "Ignoring, breakpoint is still present.\n");
831       current_inferior = saved_inferior;
832       return 0;
833     }
834
835   if (debug_threads)
836     fprintf (stderr, "Removed breakpoint.\n");
837
838   /* For decr_pc_after_break targets, here is where we perform the
839      decrement.  We go immediately from this function to resuming,
840      and can not safely call get_stop_pc () again.  */
841   if (the_low_target.set_pc != NULL)
842     {
843       if (debug_threads)
844         fprintf (stderr, "Set pc to 0x%lx\n", (long) stop_pc);
845       (*the_low_target.set_pc) (stop_pc);
846     }
847
848   /* We consumed the pending SIGTRAP.  */
849   event_child->pending_is_breakpoint = 0;
850   event_child->status_pending_p = 0;
851   event_child->status_pending = 0;
852
853   current_inferior = saved_inferior;
854   return 1;
855 }
856
857 /* Return 1 if this lwp has an interesting status pending.  This
858    function may silently resume an inferior lwp.  */
859 static int
860 status_pending_p (struct inferior_list_entry *entry, void *arg)
861 {
862   struct lwp_info *lwp = (struct lwp_info *) entry;
863   ptid_t ptid = * (ptid_t *) arg;
864
865   /* Check if we're only interested in events from a specific process
866      or its lwps.  */
867   if (!ptid_equal (minus_one_ptid, ptid)
868       && ptid_get_pid (ptid) != ptid_get_pid (lwp->head.id))
869     return 0;
870
871   if (lwp->status_pending_p && !lwp->suspended)
872     if (check_removed_breakpoint (lwp))
873       {
874         /* This thread was stopped at a breakpoint, and the breakpoint
875            is now gone.  We were told to continue (or step...) all threads,
876            so GDB isn't trying to single-step past this breakpoint.
877            So instead of reporting the old SIGTRAP, pretend we got to
878            the breakpoint just after it was removed instead of just
879            before; resume the process.  */
880         linux_resume_one_lwp (lwp, 0, 0, NULL);
881         return 0;
882       }
883
884   return (lwp->status_pending_p && !lwp->suspended);
885 }
886
887 static int
888 same_lwp (struct inferior_list_entry *entry, void *data)
889 {
890   ptid_t ptid = *(ptid_t *) data;
891   int lwp;
892
893   if (ptid_get_lwp (ptid) != 0)
894     lwp = ptid_get_lwp (ptid);
895   else
896     lwp = ptid_get_pid (ptid);
897
898   if (ptid_get_lwp (entry->id) == lwp)
899     return 1;
900
901   return 0;
902 }
903
904 struct lwp_info *
905 find_lwp_pid (ptid_t ptid)
906 {
907   return (struct lwp_info*) find_inferior (&all_lwps, same_lwp, &ptid);
908 }
909
910 static struct lwp_info *
911 linux_wait_for_lwp (ptid_t ptid, int *wstatp, int options)
912 {
913   int ret;
914   int to_wait_for = -1;
915   struct lwp_info *child = NULL;
916
917   if (debug_threads)
918     fprintf (stderr, "linux_wait_for_lwp: %s\n", target_pid_to_str (ptid));
919
920   if (ptid_equal (ptid, minus_one_ptid))
921     to_wait_for = -1;                   /* any child */
922   else
923     to_wait_for = ptid_get_lwp (ptid);  /* this lwp only */
924
925   options |= __WALL;
926
927 retry:
928
929   ret = my_waitpid (to_wait_for, wstatp, options);
930   if (ret == 0 || (ret == -1 && errno == ECHILD && (options & WNOHANG)))
931     return NULL;
932   else if (ret == -1)
933     perror_with_name ("waitpid");
934
935   if (debug_threads
936       && (!WIFSTOPPED (*wstatp)
937           || (WSTOPSIG (*wstatp) != 32
938               && WSTOPSIG (*wstatp) != 33)))
939     fprintf (stderr, "Got an event from %d (%x)\n", ret, *wstatp);
940
941   child = find_lwp_pid (pid_to_ptid (ret));
942
943   /* If we didn't find a process, one of two things presumably happened:
944      - A process we started and then detached from has exited.  Ignore it.
945      - A process we are controlling has forked and the new child's stop
946      was reported to us by the kernel.  Save its PID.  */
947   if (child == NULL && WIFSTOPPED (*wstatp))
948     {
949       add_pid_to_list (&stopped_pids, ret);
950       goto retry;
951     }
952   else if (child == NULL)
953     goto retry;
954
955   child->stopped = 1;
956   child->pending_is_breakpoint = 0;
957
958   child->last_status = *wstatp;
959
960   /* Architecture-specific setup after inferior is running.
961      This needs to happen after we have attached to the inferior
962      and it is stopped for the first time, but before we access
963      any inferior registers.  */
964   if (new_inferior)
965     {
966       the_low_target.arch_setup ();
967 #ifdef HAVE_LINUX_REGSETS
968       memset (disabled_regsets, 0, num_regsets);
969 #endif
970       new_inferior = 0;
971     }
972
973   if (debug_threads
974       && WIFSTOPPED (*wstatp)
975       && the_low_target.get_pc != NULL)
976     {
977       struct thread_info *saved_inferior = current_inferior;
978       CORE_ADDR pc;
979
980       current_inferior = (struct thread_info *)
981         find_inferior_id (&all_threads, child->head.id);
982       pc = (*the_low_target.get_pc) ();
983       fprintf (stderr, "linux_wait_for_lwp: pc is 0x%lx\n", (long) pc);
984       current_inferior = saved_inferior;
985     }
986
987   return child;
988 }
989
990 /* Wait for an event from child PID.  If PID is -1, wait for any
991    child.  Store the stop status through the status pointer WSTAT.
992    OPTIONS is passed to the waitpid call.  Return 0 if no child stop
993    event was found and OPTIONS contains WNOHANG.  Return the PID of
994    the stopped child otherwise.  */
995
996 static int
997 linux_wait_for_event_1 (ptid_t ptid, int *wstat, int options)
998 {
999   CORE_ADDR stop_pc;
1000   struct lwp_info *event_child = NULL;
1001   int bp_status;
1002   struct lwp_info *requested_child = NULL;
1003
1004   /* Check for a lwp with a pending status.  */
1005   /* It is possible that the user changed the pending task's registers since
1006      it stopped.  We correctly handle the change of PC if we hit a breakpoint
1007      (in check_removed_breakpoint); signals should be reported anyway.  */
1008
1009   if (ptid_equal (ptid, minus_one_ptid)
1010       || ptid_equal (pid_to_ptid (ptid_get_pid (ptid)), ptid))
1011     {
1012       event_child = (struct lwp_info *)
1013         find_inferior (&all_lwps, status_pending_p, &ptid);
1014       if (debug_threads && event_child)
1015         fprintf (stderr, "Got a pending child %ld\n", lwpid_of (event_child));
1016     }
1017   else
1018     {
1019       requested_child = find_lwp_pid (ptid);
1020       if (requested_child->status_pending_p
1021           && !check_removed_breakpoint (requested_child))
1022         event_child = requested_child;
1023     }
1024
1025   if (event_child != NULL)
1026     {
1027       if (debug_threads)
1028         fprintf (stderr, "Got an event from pending child %ld (%04x)\n",
1029                  lwpid_of (event_child), event_child->status_pending);
1030       *wstat = event_child->status_pending;
1031       event_child->status_pending_p = 0;
1032       event_child->status_pending = 0;
1033       current_inferior = get_lwp_thread (event_child);
1034       return lwpid_of (event_child);
1035     }
1036
1037   /* We only enter this loop if no process has a pending wait status.  Thus
1038      any action taken in response to a wait status inside this loop is
1039      responding as soon as we detect the status, not after any pending
1040      events.  */
1041   while (1)
1042     {
1043       event_child = linux_wait_for_lwp (ptid, wstat, options);
1044
1045       if ((options & WNOHANG) && event_child == NULL)
1046         return 0;
1047
1048       if (event_child == NULL)
1049         error ("event from unknown child");
1050
1051       current_inferior = get_lwp_thread (event_child);
1052
1053       /* Check for thread exit.  */
1054       if (! WIFSTOPPED (*wstat))
1055         {
1056           if (debug_threads)
1057             fprintf (stderr, "LWP %ld exiting\n", lwpid_of (event_child));
1058
1059           /* If the last thread is exiting, just return.  */
1060           if (last_thread_of_process_p (current_inferior))
1061             {
1062               if (debug_threads)
1063                 fprintf (stderr, "LWP %ld is last lwp of process\n",
1064                          lwpid_of (event_child));
1065               return lwpid_of (event_child);
1066             }
1067
1068           delete_lwp (event_child);
1069
1070           if (!non_stop)
1071             {
1072               current_inferior = (struct thread_info *) all_threads.head;
1073               if (debug_threads)
1074                 fprintf (stderr, "Current inferior is now %ld\n",
1075                          lwpid_of (get_thread_lwp (current_inferior)));
1076             }
1077           else
1078             {
1079               current_inferior = NULL;
1080               if (debug_threads)
1081                 fprintf (stderr, "Current inferior is now <NULL>\n");
1082             }
1083
1084           /* If we were waiting for this particular child to do something...
1085              well, it did something.  */
1086           if (requested_child != NULL)
1087             return lwpid_of (event_child);
1088
1089           /* Wait for a more interesting event.  */
1090           continue;
1091         }
1092
1093       if (event_child->must_set_ptrace_flags)
1094         {
1095           ptrace (PTRACE_SETOPTIONS, lwpid_of (event_child),
1096                   0, PTRACE_O_TRACECLONE);
1097           event_child->must_set_ptrace_flags = 0;
1098         }
1099
1100       if (WIFSTOPPED (*wstat)
1101           && WSTOPSIG (*wstat) == SIGSTOP
1102           && event_child->stop_expected)
1103         {
1104           if (debug_threads)
1105             fprintf (stderr, "Expected stop.\n");
1106           event_child->stop_expected = 0;
1107           linux_resume_one_lwp (event_child, event_child->stepping, 0, NULL);
1108           continue;
1109         }
1110
1111       if (WIFSTOPPED (*wstat) && WSTOPSIG (*wstat) == SIGTRAP
1112           && *wstat >> 16 != 0)
1113         {
1114           handle_extended_wait (event_child, *wstat);
1115           continue;
1116         }
1117
1118       /* If GDB is not interested in this signal, don't stop other
1119          threads, and don't report it to GDB.  Just resume the
1120          inferior right away.  We do this for threading-related
1121          signals as well as any that GDB specifically requested we
1122          ignore.  But never ignore SIGSTOP if we sent it ourselves,
1123          and do not ignore signals when stepping - they may require
1124          special handling to skip the signal handler.  */
1125       /* FIXME drow/2002-06-09: Get signal numbers from the inferior's
1126          thread library?  */
1127       if (WIFSTOPPED (*wstat)
1128           && !event_child->stepping
1129           && (
1130 #ifdef USE_THREAD_DB
1131               (current_process ()->private->thread_db != NULL
1132                && (WSTOPSIG (*wstat) == __SIGRTMIN
1133                    || WSTOPSIG (*wstat) == __SIGRTMIN + 1))
1134               ||
1135 #endif
1136               (pass_signals[target_signal_from_host (WSTOPSIG (*wstat))]
1137                && (WSTOPSIG (*wstat) != SIGSTOP || !stopping_threads))))
1138         {
1139           siginfo_t info, *info_p;
1140
1141           if (debug_threads)
1142             fprintf (stderr, "Ignored signal %d for LWP %ld.\n",
1143                      WSTOPSIG (*wstat), lwpid_of (event_child));
1144
1145           if (ptrace (PTRACE_GETSIGINFO, lwpid_of (event_child), 0, &info) == 0)
1146             info_p = &info;
1147           else
1148             info_p = NULL;
1149           linux_resume_one_lwp (event_child,
1150                                 event_child->stepping,
1151                                 WSTOPSIG (*wstat), info_p);
1152           continue;
1153         }
1154
1155       /* If this event was not handled above, and is not a SIGTRAP, report
1156          it.  */
1157       if (!WIFSTOPPED (*wstat) || WSTOPSIG (*wstat) != SIGTRAP)
1158         return lwpid_of (event_child);
1159
1160       /* If this target does not support breakpoints, we simply report the
1161          SIGTRAP; it's of no concern to us.  */
1162       if (the_low_target.get_pc == NULL)
1163         return lwpid_of (event_child);
1164
1165       stop_pc = get_stop_pc ();
1166
1167       /* bp_reinsert will only be set if we were single-stepping.
1168          Notice that we will resume the process after hitting
1169          a gdbserver breakpoint; single-stepping to/over one
1170          is not supported (yet).  */
1171       if (event_child->bp_reinsert != 0)
1172         {
1173           if (debug_threads)
1174             fprintf (stderr, "Reinserted breakpoint.\n");
1175           reinsert_breakpoint (event_child->bp_reinsert);
1176           event_child->bp_reinsert = 0;
1177
1178           /* Clear the single-stepping flag and SIGTRAP as we resume.  */
1179           linux_resume_one_lwp (event_child, 0, 0, NULL);
1180           continue;
1181         }
1182
1183       bp_status = check_breakpoints (stop_pc);
1184
1185       if (bp_status != 0)
1186         {
1187           if (debug_threads)
1188             fprintf (stderr, "Hit a gdbserver breakpoint.\n");
1189
1190           /* We hit one of our own breakpoints.  We mark it as a pending
1191              breakpoint, so that check_removed_breakpoint () will do the PC
1192              adjustment for us at the appropriate time.  */
1193           event_child->pending_is_breakpoint = 1;
1194           event_child->pending_stop_pc = stop_pc;
1195
1196           /* We may need to put the breakpoint back.  We continue in the event
1197              loop instead of simply replacing the breakpoint right away,
1198              in order to not lose signals sent to the thread that hit the
1199              breakpoint.  Unfortunately this increases the window where another
1200              thread could sneak past the removed breakpoint.  For the current
1201              use of server-side breakpoints (thread creation) this is
1202              acceptable; but it needs to be considered before this breakpoint
1203              mechanism can be used in more general ways.  For some breakpoints
1204              it may be necessary to stop all other threads, but that should
1205              be avoided where possible.
1206
1207              If breakpoint_reinsert_addr is NULL, that means that we can
1208              use PTRACE_SINGLESTEP on this platform.  Uninsert the breakpoint,
1209              mark it for reinsertion, and single-step.
1210
1211              Otherwise, call the target function to figure out where we need
1212              our temporary breakpoint, create it, and continue executing this
1213              process.  */
1214
1215           /* NOTE: we're lifting breakpoints in non-stop mode.  This
1216              is currently only used for thread event breakpoints, so
1217              it isn't that bad as long as we have PTRACE_EVENT_CLONE
1218              events.  */
1219           if (bp_status == 2)
1220             /* No need to reinsert.  */
1221             linux_resume_one_lwp (event_child, 0, 0, NULL);
1222           else if (the_low_target.breakpoint_reinsert_addr == NULL)
1223             {
1224               event_child->bp_reinsert = stop_pc;
1225               uninsert_breakpoint (stop_pc);
1226               linux_resume_one_lwp (event_child, 1, 0, NULL);
1227             }
1228           else
1229             {
1230               reinsert_breakpoint_by_bp
1231                 (stop_pc, (*the_low_target.breakpoint_reinsert_addr) ());
1232               linux_resume_one_lwp (event_child, 0, 0, NULL);
1233             }
1234
1235           continue;
1236         }
1237
1238       if (debug_threads)
1239         fprintf (stderr, "Hit a non-gdbserver breakpoint.\n");
1240
1241       /* If we were single-stepping, we definitely want to report the
1242          SIGTRAP.  Although the single-step operation has completed,
1243          do not clear clear the stepping flag yet; we need to check it
1244          in wait_for_sigstop.  */
1245       if (event_child->stepping)
1246         return lwpid_of (event_child);
1247
1248       /* A SIGTRAP that we can't explain.  It may have been a breakpoint.
1249          Check if it is a breakpoint, and if so mark the process information
1250          accordingly.  This will handle both the necessary fiddling with the
1251          PC on decr_pc_after_break targets and suppressing extra threads
1252          hitting a breakpoint if two hit it at once and then GDB removes it
1253          after the first is reported.  Arguably it would be better to report
1254          multiple threads hitting breakpoints simultaneously, but the current
1255          remote protocol does not allow this.  */
1256       if ((*the_low_target.breakpoint_at) (stop_pc))
1257         {
1258           event_child->pending_is_breakpoint = 1;
1259           event_child->pending_stop_pc = stop_pc;
1260         }
1261
1262       return lwpid_of (event_child);
1263     }
1264
1265   /* NOTREACHED */
1266   return 0;
1267 }
1268
1269 static int
1270 linux_wait_for_event (ptid_t ptid, int *wstat, int options)
1271 {
1272   ptid_t wait_ptid;
1273
1274   if (ptid_is_pid (ptid))
1275     {
1276       /* A request to wait for a specific tgid.  This is not possible
1277          with waitpid, so instead, we wait for any child, and leave
1278          children we're not interested in right now with a pending
1279          status to report later.  */
1280       wait_ptid = minus_one_ptid;
1281     }
1282   else
1283     wait_ptid = ptid;
1284
1285   while (1)
1286     {
1287       int event_pid;
1288
1289       event_pid = linux_wait_for_event_1 (wait_ptid, wstat, options);
1290
1291       if (event_pid > 0
1292           && ptid_is_pid (ptid) && ptid_get_pid (ptid) != event_pid)
1293         {
1294           struct lwp_info *event_child = find_lwp_pid (pid_to_ptid (event_pid));
1295
1296           if (! WIFSTOPPED (*wstat))
1297             mark_lwp_dead (event_child, *wstat);
1298           else
1299             {
1300               event_child->status_pending_p = 1;
1301               event_child->status_pending = *wstat;
1302             }
1303         }
1304       else
1305         return event_pid;
1306     }
1307 }
1308
1309 /* Wait for process, returns status.  */
1310
1311 static ptid_t
1312 linux_wait_1 (ptid_t ptid,
1313               struct target_waitstatus *ourstatus, int target_options)
1314 {
1315   int w;
1316   struct thread_info *thread = NULL;
1317   struct lwp_info *lwp = NULL;
1318   int options;
1319   int pid;
1320
1321   /* Translate generic target options into linux options.  */
1322   options = __WALL;
1323   if (target_options & TARGET_WNOHANG)
1324     options |= WNOHANG;
1325
1326 retry:
1327   ourstatus->kind = TARGET_WAITKIND_IGNORE;
1328
1329   /* If we were only supposed to resume one thread, only wait for
1330      that thread - if it's still alive.  If it died, however - which
1331      can happen if we're coming from the thread death case below -
1332      then we need to make sure we restart the other threads.  We could
1333      pick a thread at random or restart all; restarting all is less
1334      arbitrary.  */
1335   if (!non_stop
1336       && !ptid_equal (cont_thread, null_ptid)
1337       && !ptid_equal (cont_thread, minus_one_ptid))
1338     {
1339       thread = (struct thread_info *) find_inferior_id (&all_threads,
1340                                                         cont_thread);
1341
1342       /* No stepping, no signal - unless one is pending already, of course.  */
1343       if (thread == NULL)
1344         {
1345           struct thread_resume resume_info;
1346           resume_info.thread = minus_one_ptid;
1347           resume_info.kind = resume_continue;
1348           resume_info.sig = 0;
1349           linux_resume (&resume_info, 1);
1350         }
1351       else
1352         ptid = cont_thread;
1353     }
1354
1355   pid = linux_wait_for_event (ptid, &w, options);
1356   if (pid == 0) /* only if TARGET_WNOHANG */
1357     return null_ptid;
1358
1359   lwp = get_thread_lwp (current_inferior);
1360
1361   /* If we are waiting for a particular child, and it exited,
1362      linux_wait_for_event will return its exit status.  Similarly if
1363      the last child exited.  If this is not the last child, however,
1364      do not report it as exited until there is a 'thread exited' response
1365      available in the remote protocol.  Instead, just wait for another event.
1366      This should be safe, because if the thread crashed we will already
1367      have reported the termination signal to GDB; that should stop any
1368      in-progress stepping operations, etc.
1369
1370      Report the exit status of the last thread to exit.  This matches
1371      LinuxThreads' behavior.  */
1372
1373   if (last_thread_of_process_p (current_inferior))
1374     {
1375       if (WIFEXITED (w) || WIFSIGNALED (w))
1376         {
1377           int pid = pid_of (lwp);
1378           struct process_info *process = find_process_pid (pid);
1379
1380           delete_lwp (lwp);
1381           linux_remove_process (process);
1382
1383           current_inferior = NULL;
1384
1385           if (WIFEXITED (w))
1386             {
1387               ourstatus->kind = TARGET_WAITKIND_EXITED;
1388               ourstatus->value.integer = WEXITSTATUS (w);
1389
1390               if (debug_threads)
1391                 fprintf (stderr, "\nChild exited with retcode = %x \n", WEXITSTATUS (w));
1392             }
1393           else
1394             {
1395               ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1396               ourstatus->value.sig = target_signal_from_host (WTERMSIG (w));
1397
1398               if (debug_threads)
1399                 fprintf (stderr, "\nChild terminated with signal = %x \n", WTERMSIG (w));
1400
1401             }
1402
1403           return pid_to_ptid (pid);
1404         }
1405     }
1406   else
1407     {
1408       if (!WIFSTOPPED (w))
1409         goto retry;
1410     }
1411
1412   /* In all-stop, stop all threads.  Be careful to only do this if
1413      we're about to report an event to GDB.  */
1414   if (!non_stop)
1415     stop_all_lwps ();
1416
1417   ourstatus->kind = TARGET_WAITKIND_STOPPED;
1418
1419   if (lwp->suspended && WSTOPSIG (w) == SIGSTOP)
1420     {
1421       /* A thread that has been requested to stop by GDB with vCont;t,
1422          and it stopped cleanly, so report as SIG0.  The use of
1423          SIGSTOP is an implementation detail.  */
1424       ourstatus->value.sig = TARGET_SIGNAL_0;
1425     }
1426   else if (lwp->suspended && WSTOPSIG (w) != SIGSTOP)
1427     {
1428       /* A thread that has been requested to stop by GDB with vCont;t,
1429          but, it stopped for other reasons.  Set stop_expected so the
1430          pending SIGSTOP is ignored and the LWP is resumed.  */
1431       lwp->stop_expected = 1;
1432       ourstatus->value.sig = target_signal_from_host (WSTOPSIG (w));
1433     }
1434   else
1435     {
1436       ourstatus->value.sig = target_signal_from_host (WSTOPSIG (w));
1437     }
1438
1439   if (debug_threads)
1440     fprintf (stderr, "linux_wait ret = %s, %d, %d\n",
1441              target_pid_to_str (lwp->head.id),
1442              ourstatus->kind,
1443              ourstatus->value.sig);
1444
1445   return lwp->head.id;
1446 }
1447
1448 /* Get rid of any pending event in the pipe.  */
1449 static void
1450 async_file_flush (void)
1451 {
1452   int ret;
1453   char buf;
1454
1455   do
1456     ret = read (linux_event_pipe[0], &buf, 1);
1457   while (ret >= 0 || (ret == -1 && errno == EINTR));
1458 }
1459
1460 /* Put something in the pipe, so the event loop wakes up.  */
1461 static void
1462 async_file_mark (void)
1463 {
1464   int ret;
1465
1466   async_file_flush ();
1467
1468   do
1469     ret = write (linux_event_pipe[1], "+", 1);
1470   while (ret == 0 || (ret == -1 && errno == EINTR));
1471
1472   /* Ignore EAGAIN.  If the pipe is full, the event loop will already
1473      be awakened anyway.  */
1474 }
1475
1476 static ptid_t
1477 linux_wait (ptid_t ptid,
1478             struct target_waitstatus *ourstatus, int target_options)
1479 {
1480   ptid_t event_ptid;
1481
1482   if (debug_threads)
1483     fprintf (stderr, "linux_wait: [%s]\n", target_pid_to_str (ptid));
1484
1485   /* Flush the async file first.  */
1486   if (target_is_async_p ())
1487     async_file_flush ();
1488
1489   event_ptid = linux_wait_1 (ptid, ourstatus, target_options);
1490
1491   /* If at least one stop was reported, there may be more.  A single
1492      SIGCHLD can signal more than one child stop.  */
1493   if (target_is_async_p ()
1494       && (target_options & TARGET_WNOHANG) != 0
1495       && !ptid_equal (event_ptid, null_ptid))
1496     async_file_mark ();
1497
1498   return event_ptid;
1499 }
1500
1501 /* Send a signal to an LWP.  For LinuxThreads, kill is enough; however, if
1502    thread groups are in use, we need to use tkill.  */
1503
1504 static int
1505 kill_lwp (unsigned long lwpid, int signo)
1506 {
1507   static int tkill_failed;
1508
1509   errno = 0;
1510
1511 #ifdef SYS_tkill
1512   if (!tkill_failed)
1513     {
1514       int ret = syscall (SYS_tkill, lwpid, signo);
1515       if (errno != ENOSYS)
1516         return ret;
1517       errno = 0;
1518       tkill_failed = 1;
1519     }
1520 #endif
1521
1522   return kill (lwpid, signo);
1523 }
1524
1525 static void
1526 send_sigstop (struct inferior_list_entry *entry)
1527 {
1528   struct lwp_info *lwp = (struct lwp_info *) entry;
1529   int pid;
1530
1531   if (lwp->stopped)
1532     return;
1533
1534   pid = lwpid_of (lwp);
1535
1536   /* If we already have a pending stop signal for this process, don't
1537      send another.  */
1538   if (lwp->stop_expected)
1539     {
1540       if (debug_threads)
1541         fprintf (stderr, "Have pending sigstop for lwp %d\n", pid);
1542
1543       /* We clear the stop_expected flag so that wait_for_sigstop
1544          will receive the SIGSTOP event (instead of silently resuming and
1545          waiting again).  It'll be reset below.  */
1546       lwp->stop_expected = 0;
1547       return;
1548     }
1549
1550   if (debug_threads)
1551     fprintf (stderr, "Sending sigstop to lwp %d\n", pid);
1552
1553   kill_lwp (pid, SIGSTOP);
1554 }
1555
1556 static void
1557 mark_lwp_dead (struct lwp_info *lwp, int wstat)
1558 {
1559   /* It's dead, really.  */
1560   lwp->dead = 1;
1561
1562   /* Store the exit status for later.  */
1563   lwp->status_pending_p = 1;
1564   lwp->status_pending = wstat;
1565
1566   /* So that check_removed_breakpoint doesn't try to figure out if
1567      this is stopped at a breakpoint.  */
1568   lwp->pending_is_breakpoint = 0;
1569
1570   /* Prevent trying to stop it.  */
1571   lwp->stopped = 1;
1572
1573   /* No further stops are expected from a dead lwp.  */
1574   lwp->stop_expected = 0;
1575 }
1576
1577 static void
1578 wait_for_sigstop (struct inferior_list_entry *entry)
1579 {
1580   struct lwp_info *lwp = (struct lwp_info *) entry;
1581   struct thread_info *saved_inferior;
1582   int wstat;
1583   ptid_t saved_tid;
1584   ptid_t ptid;
1585
1586   if (lwp->stopped)
1587     return;
1588
1589   saved_inferior = current_inferior;
1590   if (saved_inferior != NULL)
1591     saved_tid = ((struct inferior_list_entry *) saved_inferior)->id;
1592   else
1593     saved_tid = null_ptid; /* avoid bogus unused warning */
1594
1595   ptid = lwp->head.id;
1596
1597   linux_wait_for_event (ptid, &wstat, __WALL);
1598
1599   /* If we stopped with a non-SIGSTOP signal, save it for later
1600      and record the pending SIGSTOP.  If the process exited, just
1601      return.  */
1602   if (WIFSTOPPED (wstat)
1603       && WSTOPSIG (wstat) != SIGSTOP)
1604     {
1605       if (debug_threads)
1606         fprintf (stderr, "LWP %ld stopped with non-sigstop status %06x\n",
1607                  lwpid_of (lwp), wstat);
1608
1609       /* Do not leave a pending single-step finish to be reported to
1610          the client.  The client will give us a new action for this
1611          thread, possibly a continue request --- otherwise, the client
1612          would consider this pending SIGTRAP reported later a spurious
1613          signal.  */
1614       if (WSTOPSIG (wstat) == SIGTRAP
1615           && lwp->stepping
1616           && !linux_stopped_by_watchpoint ())
1617         {
1618           if (debug_threads)
1619             fprintf (stderr, "  single-step SIGTRAP ignored\n");
1620         }
1621       else
1622         {
1623           lwp->status_pending_p = 1;
1624           lwp->status_pending = wstat;
1625         }
1626       lwp->stop_expected = 1;
1627     }
1628   else if (!WIFSTOPPED (wstat))
1629     {
1630       if (debug_threads)
1631         fprintf (stderr, "Process %ld exited while stopping LWPs\n",
1632                  lwpid_of (lwp));
1633
1634       /* Leave this status pending for the next time we're able to
1635          report it.  In the mean time, we'll report this lwp as dead
1636          to GDB, so GDB doesn't try to read registers and memory from
1637          it.  */
1638       mark_lwp_dead (lwp, wstat);
1639     }
1640
1641   if (saved_inferior == NULL || linux_thread_alive (saved_tid))
1642     current_inferior = saved_inferior;
1643   else
1644     {
1645       if (debug_threads)
1646         fprintf (stderr, "Previously current thread died.\n");
1647
1648       if (non_stop)
1649         {
1650           /* We can't change the current inferior behind GDB's back,
1651              otherwise, a subsequent command may apply to the wrong
1652              process.  */
1653           current_inferior = NULL;
1654         }
1655       else
1656         {
1657           /* Set a valid thread as current.  */
1658           set_desired_inferior (0);
1659         }
1660     }
1661 }
1662
1663 static void
1664 stop_all_lwps (void)
1665 {
1666   stopping_threads = 1;
1667   for_each_inferior (&all_lwps, send_sigstop);
1668   for_each_inferior (&all_lwps, wait_for_sigstop);
1669   stopping_threads = 0;
1670 }
1671
1672 /* Resume execution of the inferior process.
1673    If STEP is nonzero, single-step it.
1674    If SIGNAL is nonzero, give it that signal.  */
1675
1676 static void
1677 linux_resume_one_lwp (struct lwp_info *lwp,
1678                       int step, int signal, siginfo_t *info)
1679 {
1680   struct thread_info *saved_inferior;
1681
1682   if (lwp->stopped == 0)
1683     return;
1684
1685   /* If we have pending signals or status, and a new signal, enqueue the
1686      signal.  Also enqueue the signal if we are waiting to reinsert a
1687      breakpoint; it will be picked up again below.  */
1688   if (signal != 0
1689       && (lwp->status_pending_p || lwp->pending_signals != NULL
1690           || lwp->bp_reinsert != 0))
1691     {
1692       struct pending_signals *p_sig;
1693       p_sig = xmalloc (sizeof (*p_sig));
1694       p_sig->prev = lwp->pending_signals;
1695       p_sig->signal = signal;
1696       if (info == NULL)
1697         memset (&p_sig->info, 0, sizeof (siginfo_t));
1698       else
1699         memcpy (&p_sig->info, info, sizeof (siginfo_t));
1700       lwp->pending_signals = p_sig;
1701     }
1702
1703   if (lwp->status_pending_p && !check_removed_breakpoint (lwp))
1704     return;
1705
1706   saved_inferior = current_inferior;
1707   current_inferior = get_lwp_thread (lwp);
1708
1709   if (debug_threads)
1710     fprintf (stderr, "Resuming lwp %ld (%s, signal %d, stop %s)\n",
1711              lwpid_of (lwp), step ? "step" : "continue", signal,
1712              lwp->stop_expected ? "expected" : "not expected");
1713
1714   /* This bit needs some thinking about.  If we get a signal that
1715      we must report while a single-step reinsert is still pending,
1716      we often end up resuming the thread.  It might be better to
1717      (ew) allow a stack of pending events; then we could be sure that
1718      the reinsert happened right away and not lose any signals.
1719
1720      Making this stack would also shrink the window in which breakpoints are
1721      uninserted (see comment in linux_wait_for_lwp) but not enough for
1722      complete correctness, so it won't solve that problem.  It may be
1723      worthwhile just to solve this one, however.  */
1724   if (lwp->bp_reinsert != 0)
1725     {
1726       if (debug_threads)
1727         fprintf (stderr, "  pending reinsert at %08lx", (long)lwp->bp_reinsert);
1728       if (step == 0)
1729         fprintf (stderr, "BAD - reinserting but not stepping.\n");
1730       step = 1;
1731
1732       /* Postpone any pending signal.  It was enqueued above.  */
1733       signal = 0;
1734     }
1735
1736   check_removed_breakpoint (lwp);
1737
1738   if (debug_threads && the_low_target.get_pc != NULL)
1739     {
1740       CORE_ADDR pc = (*the_low_target.get_pc) ();
1741       fprintf (stderr, "  resuming from pc 0x%lx\n", (long) pc);
1742     }
1743
1744   /* If we have pending signals, consume one unless we are trying to reinsert
1745      a breakpoint.  */
1746   if (lwp->pending_signals != NULL && lwp->bp_reinsert == 0)
1747     {
1748       struct pending_signals **p_sig;
1749
1750       p_sig = &lwp->pending_signals;
1751       while ((*p_sig)->prev != NULL)
1752         p_sig = &(*p_sig)->prev;
1753
1754       signal = (*p_sig)->signal;
1755       if ((*p_sig)->info.si_signo != 0)
1756         ptrace (PTRACE_SETSIGINFO, lwpid_of (lwp), 0, &(*p_sig)->info);
1757
1758       free (*p_sig);
1759       *p_sig = NULL;
1760     }
1761
1762   if (the_low_target.prepare_to_resume != NULL)
1763     the_low_target.prepare_to_resume (lwp);
1764
1765   regcache_invalidate_one ((struct inferior_list_entry *)
1766                            get_lwp_thread (lwp));
1767   errno = 0;
1768   lwp->stopped = 0;
1769   lwp->stepping = step;
1770   ptrace (step ? PTRACE_SINGLESTEP : PTRACE_CONT, lwpid_of (lwp), 0, signal);
1771
1772   current_inferior = saved_inferior;
1773   if (errno)
1774     {
1775       /* ESRCH from ptrace either means that the thread was already
1776          running (an error) or that it is gone (a race condition).  If
1777          it's gone, we will get a notification the next time we wait,
1778          so we can ignore the error.  We could differentiate these
1779          two, but it's tricky without waiting; the thread still exists
1780          as a zombie, so sending it signal 0 would succeed.  So just
1781          ignore ESRCH.  */
1782       if (errno == ESRCH)
1783         return;
1784
1785       perror_with_name ("ptrace");
1786     }
1787 }
1788
1789 struct thread_resume_array
1790 {
1791   struct thread_resume *resume;
1792   size_t n;
1793 };
1794
1795 /* This function is called once per thread.  We look up the thread
1796    in RESUME_PTR, and mark the thread with a pointer to the appropriate
1797    resume request.
1798
1799    This algorithm is O(threads * resume elements), but resume elements
1800    is small (and will remain small at least until GDB supports thread
1801    suspension).  */
1802 static int
1803 linux_set_resume_request (struct inferior_list_entry *entry, void *arg)
1804 {
1805   struct lwp_info *lwp;
1806   struct thread_info *thread;
1807   int ndx;
1808   struct thread_resume_array *r;
1809
1810   thread = (struct thread_info *) entry;
1811   lwp = get_thread_lwp (thread);
1812   r = arg;
1813
1814   for (ndx = 0; ndx < r->n; ndx++)
1815     {
1816       ptid_t ptid = r->resume[ndx].thread;
1817       if (ptid_equal (ptid, minus_one_ptid)
1818           || ptid_equal (ptid, entry->id)
1819           || (ptid_is_pid (ptid)
1820               && (ptid_get_pid (ptid) == pid_of (lwp)))
1821           || (ptid_get_lwp (ptid) == -1
1822               && (ptid_get_pid (ptid) == pid_of (lwp))))
1823         {
1824           lwp->resume = &r->resume[ndx];
1825           return 0;
1826         }
1827     }
1828
1829   /* No resume action for this thread.  */
1830   lwp->resume = NULL;
1831
1832   return 0;
1833 }
1834
1835
1836 /* Set *FLAG_P if this lwp has an interesting status pending.  */
1837 static int
1838 resume_status_pending_p (struct inferior_list_entry *entry, void *flag_p)
1839 {
1840   struct lwp_info *lwp = (struct lwp_info *) entry;
1841
1842   /* LWPs which will not be resumed are not interesting, because
1843      we might not wait for them next time through linux_wait.  */
1844   if (lwp->resume == NULL)
1845     return 0;
1846
1847   /* If this thread has a removed breakpoint, we won't have any
1848      events to report later, so check now.  check_removed_breakpoint
1849      may clear status_pending_p.  We avoid calling check_removed_breakpoint
1850      for any thread that we are not otherwise going to resume - this
1851      lets us preserve stopped status when two threads hit a breakpoint.
1852      GDB removes the breakpoint to single-step a particular thread
1853      past it, then re-inserts it and resumes all threads.  We want
1854      to report the second thread without resuming it in the interim.  */
1855   if (lwp->status_pending_p)
1856     check_removed_breakpoint (lwp);
1857
1858   if (lwp->status_pending_p)
1859     * (int *) flag_p = 1;
1860
1861   return 0;
1862 }
1863
1864 /* This function is called once per thread.  We check the thread's resume
1865    request, which will tell us whether to resume, step, or leave the thread
1866    stopped; and what signal, if any, it should be sent.
1867
1868    For threads which we aren't explicitly told otherwise, we preserve
1869    the stepping flag; this is used for stepping over gdbserver-placed
1870    breakpoints.
1871
1872    If pending_flags was set in any thread, we queue any needed
1873    signals, since we won't actually resume.  We already have a pending
1874    event to report, so we don't need to preserve any step requests;
1875    they should be re-issued if necessary.  */
1876
1877 static int
1878 linux_resume_one_thread (struct inferior_list_entry *entry, void *arg)
1879 {
1880   struct lwp_info *lwp;
1881   struct thread_info *thread;
1882   int step;
1883   int pending_flag = * (int *) arg;
1884
1885   thread = (struct thread_info *) entry;
1886   lwp = get_thread_lwp (thread);
1887
1888   if (lwp->resume == NULL)
1889     return 0;
1890
1891   if (lwp->resume->kind == resume_stop)
1892     {
1893       if (debug_threads)
1894         fprintf (stderr, "suspending LWP %ld\n", lwpid_of (lwp));
1895
1896       if (!lwp->stopped)
1897         {
1898           if (debug_threads)
1899             fprintf (stderr, "running -> suspending LWP %ld\n", lwpid_of (lwp));
1900
1901           lwp->suspended = 1;
1902           send_sigstop (&lwp->head);
1903         }
1904       else
1905         {
1906           if (debug_threads)
1907             {
1908               if (lwp->suspended)
1909                 fprintf (stderr, "already stopped/suspended LWP %ld\n",
1910                          lwpid_of (lwp));
1911               else
1912                 fprintf (stderr, "already stopped/not suspended LWP %ld\n",
1913                          lwpid_of (lwp));
1914             }
1915
1916           /* Make sure we leave the LWP suspended, so we don't try to
1917              resume it without GDB telling us to.  FIXME: The LWP may
1918              have been stopped in an internal event that was not meant
1919              to be notified back to GDB (e.g., gdbserver breakpoint),
1920              so we should be reporting a stop event in that case
1921              too.  */
1922           lwp->suspended = 1;
1923         }
1924
1925       /* For stop requests, we're done.  */
1926       lwp->resume = NULL;
1927       return 0;
1928     }
1929   else
1930     lwp->suspended = 0;
1931
1932   /* If this thread which is about to be resumed has a pending status,
1933      then don't resume any threads - we can just report the pending
1934      status.  Make sure to queue any signals that would otherwise be
1935      sent.  In all-stop mode, we do this decision based on if *any*
1936      thread has a pending status.  */
1937   if (non_stop)
1938     resume_status_pending_p (&lwp->head, &pending_flag);
1939
1940   if (!pending_flag)
1941     {
1942       if (debug_threads)
1943         fprintf (stderr, "resuming LWP %ld\n", lwpid_of (lwp));
1944
1945       if (ptid_equal (lwp->resume->thread, minus_one_ptid)
1946           && lwp->stepping
1947           && lwp->pending_is_breakpoint)
1948         step = 1;
1949       else
1950         step = (lwp->resume->kind == resume_step);
1951
1952       linux_resume_one_lwp (lwp, step, lwp->resume->sig, NULL);
1953     }
1954   else
1955     {
1956       if (debug_threads)
1957         fprintf (stderr, "leaving LWP %ld stopped\n", lwpid_of (lwp));
1958
1959       /* If we have a new signal, enqueue the signal.  */
1960       if (lwp->resume->sig != 0)
1961         {
1962           struct pending_signals *p_sig;
1963           p_sig = xmalloc (sizeof (*p_sig));
1964           p_sig->prev = lwp->pending_signals;
1965           p_sig->signal = lwp->resume->sig;
1966           memset (&p_sig->info, 0, sizeof (siginfo_t));
1967
1968           /* If this is the same signal we were previously stopped by,
1969              make sure to queue its siginfo.  We can ignore the return
1970              value of ptrace; if it fails, we'll skip
1971              PTRACE_SETSIGINFO.  */
1972           if (WIFSTOPPED (lwp->last_status)
1973               && WSTOPSIG (lwp->last_status) == lwp->resume->sig)
1974             ptrace (PTRACE_GETSIGINFO, lwpid_of (lwp), 0, &p_sig->info);
1975
1976           lwp->pending_signals = p_sig;
1977         }
1978     }
1979
1980   lwp->resume = NULL;
1981   return 0;
1982 }
1983
1984 static void
1985 linux_resume (struct thread_resume *resume_info, size_t n)
1986 {
1987   int pending_flag;
1988   struct thread_resume_array array = { resume_info, n };
1989
1990   find_inferior (&all_threads, linux_set_resume_request, &array);
1991
1992   /* If there is a thread which would otherwise be resumed, which
1993      has a pending status, then don't resume any threads - we can just
1994      report the pending status.  Make sure to queue any signals
1995      that would otherwise be sent.  In non-stop mode, we'll apply this
1996      logic to each thread individually.  */
1997   pending_flag = 0;
1998   if (!non_stop)
1999     find_inferior (&all_lwps, resume_status_pending_p, &pending_flag);
2000
2001   if (debug_threads)
2002     {
2003       if (pending_flag)
2004         fprintf (stderr, "Not resuming, pending status\n");
2005       else
2006         fprintf (stderr, "Resuming, no pending status\n");
2007     }
2008
2009   find_inferior (&all_threads, linux_resume_one_thread, &pending_flag);
2010 }
2011
2012 #ifdef HAVE_LINUX_USRREGS
2013
2014 int
2015 register_addr (int regnum)
2016 {
2017   int addr;
2018
2019   if (regnum < 0 || regnum >= the_low_target.num_regs)
2020     error ("Invalid register number %d.", regnum);
2021
2022   addr = the_low_target.regmap[regnum];
2023
2024   return addr;
2025 }
2026
2027 /* Fetch one register.  */
2028 static void
2029 fetch_register (int regno)
2030 {
2031   CORE_ADDR regaddr;
2032   int i, size;
2033   char *buf;
2034   int pid;
2035
2036   if (regno >= the_low_target.num_regs)
2037     return;
2038   if ((*the_low_target.cannot_fetch_register) (regno))
2039     return;
2040
2041   regaddr = register_addr (regno);
2042   if (regaddr == -1)
2043     return;
2044
2045   pid = lwpid_of (get_thread_lwp (current_inferior));
2046   size = ((register_size (regno) + sizeof (PTRACE_XFER_TYPE) - 1)
2047           & - sizeof (PTRACE_XFER_TYPE));
2048   buf = alloca (size);
2049   for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
2050     {
2051       errno = 0;
2052       *(PTRACE_XFER_TYPE *) (buf + i) =
2053         ptrace (PTRACE_PEEKUSER, pid, (PTRACE_ARG3_TYPE) regaddr, 0);
2054       regaddr += sizeof (PTRACE_XFER_TYPE);
2055       if (errno != 0)
2056         {
2057           /* Warning, not error, in case we are attached; sometimes the
2058              kernel doesn't let us at the registers.  */
2059           char *err = strerror (errno);
2060           char *msg = alloca (strlen (err) + 128);
2061           sprintf (msg, "reading register %d: %s", regno, err);
2062           error (msg);
2063           goto error_exit;
2064         }
2065     }
2066
2067   if (the_low_target.supply_ptrace_register)
2068     the_low_target.supply_ptrace_register (regno, buf);
2069   else
2070     supply_register (regno, buf);
2071
2072 error_exit:;
2073 }
2074
2075 /* Fetch all registers, or just one, from the child process.  */
2076 static void
2077 usr_fetch_inferior_registers (int regno)
2078 {
2079   if (regno == -1)
2080     for (regno = 0; regno < the_low_target.num_regs; regno++)
2081       fetch_register (regno);
2082   else
2083     fetch_register (regno);
2084 }
2085
2086 /* Store our register values back into the inferior.
2087    If REGNO is -1, do this for all registers.
2088    Otherwise, REGNO specifies which register (so we can save time).  */
2089 static void
2090 usr_store_inferior_registers (int regno)
2091 {
2092   CORE_ADDR regaddr;
2093   int i, size;
2094   char *buf;
2095   int pid;
2096
2097   if (regno >= 0)
2098     {
2099       if (regno >= the_low_target.num_regs)
2100         return;
2101
2102       if ((*the_low_target.cannot_store_register) (regno) == 1)
2103         return;
2104
2105       regaddr = register_addr (regno);
2106       if (regaddr == -1)
2107         return;
2108       errno = 0;
2109       size = (register_size (regno) + sizeof (PTRACE_XFER_TYPE) - 1)
2110              & - sizeof (PTRACE_XFER_TYPE);
2111       buf = alloca (size);
2112       memset (buf, 0, size);
2113
2114       if (the_low_target.collect_ptrace_register)
2115         the_low_target.collect_ptrace_register (regno, buf);
2116       else
2117         collect_register (regno, buf);
2118
2119       pid = lwpid_of (get_thread_lwp (current_inferior));
2120       for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
2121         {
2122           errno = 0;
2123           ptrace (PTRACE_POKEUSER, pid, (PTRACE_ARG3_TYPE) regaddr,
2124                   *(PTRACE_XFER_TYPE *) (buf + i));
2125           if (errno != 0)
2126             {
2127               /* At this point, ESRCH should mean the process is
2128                  already gone, in which case we simply ignore attempts
2129                  to change its registers.  See also the related
2130                  comment in linux_resume_one_lwp.  */
2131               if (errno == ESRCH)
2132                 return;
2133
2134               if ((*the_low_target.cannot_store_register) (regno) == 0)
2135                 {
2136                   char *err = strerror (errno);
2137                   char *msg = alloca (strlen (err) + 128);
2138                   sprintf (msg, "writing register %d: %s",
2139                            regno, err);
2140                   error (msg);
2141                   return;
2142                 }
2143             }
2144           regaddr += sizeof (PTRACE_XFER_TYPE);
2145         }
2146     }
2147   else
2148     for (regno = 0; regno < the_low_target.num_regs; regno++)
2149       usr_store_inferior_registers (regno);
2150 }
2151 #endif /* HAVE_LINUX_USRREGS */
2152
2153
2154
2155 #ifdef HAVE_LINUX_REGSETS
2156
2157 static int
2158 regsets_fetch_inferior_registers ()
2159 {
2160   struct regset_info *regset;
2161   int saw_general_regs = 0;
2162   int pid;
2163
2164   regset = target_regsets;
2165
2166   pid = lwpid_of (get_thread_lwp (current_inferior));
2167   while (regset->size >= 0)
2168     {
2169       void *buf;
2170       int res;
2171
2172       if (regset->size == 0 || disabled_regsets[regset - target_regsets])
2173         {
2174           regset ++;
2175           continue;
2176         }
2177
2178       buf = xmalloc (regset->size);
2179 #ifndef __sparc__
2180       res = ptrace (regset->get_request, pid, 0, buf);
2181 #else
2182       res = ptrace (regset->get_request, pid, buf, 0);
2183 #endif
2184       if (res < 0)
2185         {
2186           if (errno == EIO)
2187             {
2188               /* If we get EIO on a regset, do not try it again for
2189                  this process.  */
2190               disabled_regsets[regset - target_regsets] = 1;
2191               free (buf);
2192               continue;
2193             }
2194           else
2195             {
2196               char s[256];
2197               sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%d",
2198                        pid);
2199               perror (s);
2200             }
2201         }
2202       else if (regset->type == GENERAL_REGS)
2203         saw_general_regs = 1;
2204       regset->store_function (buf);
2205       regset ++;
2206       free (buf);
2207     }
2208   if (saw_general_regs)
2209     return 0;
2210   else
2211     return 1;
2212 }
2213
2214 static int
2215 regsets_store_inferior_registers ()
2216 {
2217   struct regset_info *regset;
2218   int saw_general_regs = 0;
2219   int pid;
2220
2221   regset = target_regsets;
2222
2223   pid = lwpid_of (get_thread_lwp (current_inferior));
2224   while (regset->size >= 0)
2225     {
2226       void *buf;
2227       int res;
2228
2229       if (regset->size == 0 || disabled_regsets[regset - target_regsets])
2230         {
2231           regset ++;
2232           continue;
2233         }
2234
2235       buf = xmalloc (regset->size);
2236
2237       /* First fill the buffer with the current register set contents,
2238          in case there are any items in the kernel's regset that are
2239          not in gdbserver's regcache.  */
2240 #ifndef __sparc__
2241       res = ptrace (regset->get_request, pid, 0, buf);
2242 #else
2243       res = ptrace (regset->get_request, pid, buf, 0);
2244 #endif
2245
2246       if (res == 0)
2247         {
2248           /* Then overlay our cached registers on that.  */
2249           regset->fill_function (buf);
2250
2251           /* Only now do we write the register set.  */
2252 #ifndef __sparc__
2253           res = ptrace (regset->set_request, pid, 0, buf);
2254 #else
2255           res = ptrace (regset->set_request, pid, buf, 0);
2256 #endif
2257         }
2258
2259       if (res < 0)
2260         {
2261           if (errno == EIO)
2262             {
2263               /* If we get EIO on a regset, do not try it again for
2264                  this process.  */
2265               disabled_regsets[regset - target_regsets] = 1;
2266               free (buf);
2267               continue;
2268             }
2269           else if (errno == ESRCH)
2270             {
2271               /* At this point, ESRCH should mean the process is
2272                  already gone, in which case we simply ignore attempts
2273                  to change its registers.  See also the related
2274                  comment in linux_resume_one_lwp.  */
2275               free (buf);
2276               return 0;
2277             }
2278           else
2279             {
2280               perror ("Warning: ptrace(regsets_store_inferior_registers)");
2281             }
2282         }
2283       else if (regset->type == GENERAL_REGS)
2284         saw_general_regs = 1;
2285       regset ++;
2286       free (buf);
2287     }
2288   if (saw_general_regs)
2289     return 0;
2290   else
2291     return 1;
2292   return 0;
2293 }
2294
2295 #endif /* HAVE_LINUX_REGSETS */
2296
2297
2298 void
2299 linux_fetch_registers (int regno)
2300 {
2301 #ifdef HAVE_LINUX_REGSETS
2302   if (regsets_fetch_inferior_registers () == 0)
2303     return;
2304 #endif
2305 #ifdef HAVE_LINUX_USRREGS
2306   usr_fetch_inferior_registers (regno);
2307 #endif
2308 }
2309
2310 void
2311 linux_store_registers (int regno)
2312 {
2313 #ifdef HAVE_LINUX_REGSETS
2314   if (regsets_store_inferior_registers () == 0)
2315     return;
2316 #endif
2317 #ifdef HAVE_LINUX_USRREGS
2318   usr_store_inferior_registers (regno);
2319 #endif
2320 }
2321
2322
2323 /* Copy LEN bytes from inferior's memory starting at MEMADDR
2324    to debugger memory starting at MYADDR.  */
2325
2326 static int
2327 linux_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
2328 {
2329   register int i;
2330   /* Round starting address down to longword boundary.  */
2331   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2332   /* Round ending address up; get number of longwords that makes.  */
2333   register int count
2334     = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
2335       / sizeof (PTRACE_XFER_TYPE);
2336   /* Allocate buffer of that many longwords.  */
2337   register PTRACE_XFER_TYPE *buffer
2338     = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2339   int fd;
2340   char filename[64];
2341   int pid = lwpid_of (get_thread_lwp (current_inferior));
2342
2343   /* Try using /proc.  Don't bother for one word.  */
2344   if (len >= 3 * sizeof (long))
2345     {
2346       /* We could keep this file open and cache it - possibly one per
2347          thread.  That requires some juggling, but is even faster.  */
2348       sprintf (filename, "/proc/%d/mem", pid);
2349       fd = open (filename, O_RDONLY | O_LARGEFILE);
2350       if (fd == -1)
2351         goto no_proc;
2352
2353       /* If pread64 is available, use it.  It's faster if the kernel
2354          supports it (only one syscall), and it's 64-bit safe even on
2355          32-bit platforms (for instance, SPARC debugging a SPARC64
2356          application).  */
2357 #ifdef HAVE_PREAD64
2358       if (pread64 (fd, myaddr, len, memaddr) != len)
2359 #else
2360       if (lseek (fd, memaddr, SEEK_SET) == -1 || read (fd, memaddr, len) != len)
2361 #endif
2362         {
2363           close (fd);
2364           goto no_proc;
2365         }
2366
2367       close (fd);
2368       return 0;
2369     }
2370
2371  no_proc:
2372   /* Read all the longwords */
2373   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
2374     {
2375       errno = 0;
2376       buffer[i] = ptrace (PTRACE_PEEKTEXT, pid, (PTRACE_ARG3_TYPE) addr, 0);
2377       if (errno)
2378         return errno;
2379     }
2380
2381   /* Copy appropriate bytes out of the buffer.  */
2382   memcpy (myaddr,
2383           (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
2384           len);
2385
2386   return 0;
2387 }
2388
2389 /* Copy LEN bytes of data from debugger memory at MYADDR
2390    to inferior's memory at MEMADDR.
2391    On failure (cannot write the inferior)
2392    returns the value of errno.  */
2393
2394 static int
2395 linux_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
2396 {
2397   register int i;
2398   /* Round starting address down to longword boundary.  */
2399   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2400   /* Round ending address up; get number of longwords that makes.  */
2401   register int count
2402   = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1) / sizeof (PTRACE_XFER_TYPE);
2403   /* Allocate buffer of that many longwords.  */
2404   register PTRACE_XFER_TYPE *buffer = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2405   int pid = lwpid_of (get_thread_lwp (current_inferior));
2406
2407   if (debug_threads)
2408     {
2409       /* Dump up to four bytes.  */
2410       unsigned int val = * (unsigned int *) myaddr;
2411       if (len == 1)
2412         val = val & 0xff;
2413       else if (len == 2)
2414         val = val & 0xffff;
2415       else if (len == 3)
2416         val = val & 0xffffff;
2417       fprintf (stderr, "Writing %0*x to 0x%08lx\n", 2 * ((len < 4) ? len : 4),
2418                val, (long)memaddr);
2419     }
2420
2421   /* Fill start and end extra bytes of buffer with existing memory data.  */
2422
2423   buffer[0] = ptrace (PTRACE_PEEKTEXT, pid, (PTRACE_ARG3_TYPE) addr, 0);
2424
2425   if (count > 1)
2426     {
2427       buffer[count - 1]
2428         = ptrace (PTRACE_PEEKTEXT, pid,
2429                   (PTRACE_ARG3_TYPE) (addr + (count - 1)
2430                                       * sizeof (PTRACE_XFER_TYPE)),
2431                   0);
2432     }
2433
2434   /* Copy data to be written over corresponding part of buffer */
2435
2436   memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), myaddr, len);
2437
2438   /* Write the entire buffer.  */
2439
2440   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
2441     {
2442       errno = 0;
2443       ptrace (PTRACE_POKETEXT, pid, (PTRACE_ARG3_TYPE) addr, buffer[i]);
2444       if (errno)
2445         return errno;
2446     }
2447
2448   return 0;
2449 }
2450
2451 static int linux_supports_tracefork_flag;
2452
2453 /* Helper functions for linux_test_for_tracefork, called via clone ().  */
2454
2455 static int
2456 linux_tracefork_grandchild (void *arg)
2457 {
2458   _exit (0);
2459 }
2460
2461 #define STACK_SIZE 4096
2462
2463 static int
2464 linux_tracefork_child (void *arg)
2465 {
2466   ptrace (PTRACE_TRACEME, 0, 0, 0);
2467   kill (getpid (), SIGSTOP);
2468 #ifdef __ia64__
2469   __clone2 (linux_tracefork_grandchild, arg, STACK_SIZE,
2470             CLONE_VM | SIGCHLD, NULL);
2471 #else
2472   clone (linux_tracefork_grandchild, arg + STACK_SIZE,
2473          CLONE_VM | SIGCHLD, NULL);
2474 #endif
2475   _exit (0);
2476 }
2477
2478 /* Wrapper function for waitpid which handles EINTR, and emulates
2479    __WALL for systems where that is not available.  */
2480
2481 static int
2482 my_waitpid (int pid, int *status, int flags)
2483 {
2484   int ret, out_errno;
2485
2486   if (debug_threads)
2487     fprintf (stderr, "my_waitpid (%d, 0x%x)\n", pid, flags);
2488
2489   if (flags & __WALL)
2490     {
2491       sigset_t block_mask, org_mask, wake_mask;
2492       int wnohang;
2493
2494       wnohang = (flags & WNOHANG) != 0;
2495       flags &= ~(__WALL | __WCLONE);
2496       flags |= WNOHANG;
2497
2498       /* Block all signals while here.  This avoids knowing about
2499          LinuxThread's signals.  */
2500       sigfillset (&block_mask);
2501       sigprocmask (SIG_BLOCK, &block_mask, &org_mask);
2502
2503       /* ... except during the sigsuspend below.  */
2504       sigemptyset (&wake_mask);
2505
2506       while (1)
2507         {
2508           /* Since all signals are blocked, there's no need to check
2509              for EINTR here.  */
2510           ret = waitpid (pid, status, flags);
2511           out_errno = errno;
2512
2513           if (ret == -1 && out_errno != ECHILD)
2514             break;
2515           else if (ret > 0)
2516             break;
2517
2518           if (flags & __WCLONE)
2519             {
2520               /* We've tried both flavors now.  If WNOHANG is set,
2521                  there's nothing else to do, just bail out.  */
2522               if (wnohang)
2523                 break;
2524
2525               if (debug_threads)
2526                 fprintf (stderr, "blocking\n");
2527
2528               /* Block waiting for signals.  */
2529               sigsuspend (&wake_mask);
2530             }
2531
2532           flags ^= __WCLONE;
2533         }
2534
2535       sigprocmask (SIG_SETMASK, &org_mask, NULL);
2536     }
2537   else
2538     {
2539       do
2540         ret = waitpid (pid, status, flags);
2541       while (ret == -1 && errno == EINTR);
2542       out_errno = errno;
2543     }
2544
2545   if (debug_threads)
2546     fprintf (stderr, "my_waitpid (%d, 0x%x): status(%x), %d\n",
2547              pid, flags, status ? *status : -1, ret);
2548
2549   errno = out_errno;
2550   return ret;
2551 }
2552
2553 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.  Make
2554    sure that we can enable the option, and that it had the desired
2555    effect.  */
2556
2557 static void
2558 linux_test_for_tracefork (void)
2559 {
2560   int child_pid, ret, status;
2561   long second_pid;
2562   char *stack = xmalloc (STACK_SIZE * 4);
2563
2564   linux_supports_tracefork_flag = 0;
2565
2566   /* Use CLONE_VM instead of fork, to support uClinux (no MMU).  */
2567 #ifdef __ia64__
2568   child_pid = __clone2 (linux_tracefork_child, stack, STACK_SIZE,
2569                         CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
2570 #else
2571   child_pid = clone (linux_tracefork_child, stack + STACK_SIZE,
2572                      CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
2573 #endif
2574   if (child_pid == -1)
2575     perror_with_name ("clone");
2576
2577   ret = my_waitpid (child_pid, &status, 0);
2578   if (ret == -1)
2579     perror_with_name ("waitpid");
2580   else if (ret != child_pid)
2581     error ("linux_test_for_tracefork: waitpid: unexpected result %d.", ret);
2582   if (! WIFSTOPPED (status))
2583     error ("linux_test_for_tracefork: waitpid: unexpected status %d.", status);
2584
2585   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
2586   if (ret != 0)
2587     {
2588       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
2589       if (ret != 0)
2590         {
2591           warning ("linux_test_for_tracefork: failed to kill child");
2592           return;
2593         }
2594
2595       ret = my_waitpid (child_pid, &status, 0);
2596       if (ret != child_pid)
2597         warning ("linux_test_for_tracefork: failed to wait for killed child");
2598       else if (!WIFSIGNALED (status))
2599         warning ("linux_test_for_tracefork: unexpected wait status 0x%x from "
2600                  "killed child", status);
2601
2602       return;
2603     }
2604
2605   ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
2606   if (ret != 0)
2607     warning ("linux_test_for_tracefork: failed to resume child");
2608
2609   ret = my_waitpid (child_pid, &status, 0);
2610
2611   if (ret == child_pid && WIFSTOPPED (status)
2612       && status >> 16 == PTRACE_EVENT_FORK)
2613     {
2614       second_pid = 0;
2615       ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
2616       if (ret == 0 && second_pid != 0)
2617         {
2618           int second_status;
2619
2620           linux_supports_tracefork_flag = 1;
2621           my_waitpid (second_pid, &second_status, 0);
2622           ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
2623           if (ret != 0)
2624             warning ("linux_test_for_tracefork: failed to kill second child");
2625           my_waitpid (second_pid, &status, 0);
2626         }
2627     }
2628   else
2629     warning ("linux_test_for_tracefork: unexpected result from waitpid "
2630              "(%d, status 0x%x)", ret, status);
2631
2632   do
2633     {
2634       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
2635       if (ret != 0)
2636         warning ("linux_test_for_tracefork: failed to kill child");
2637       my_waitpid (child_pid, &status, 0);
2638     }
2639   while (WIFSTOPPED (status));
2640
2641   free (stack);
2642 }
2643
2644
2645 static void
2646 linux_look_up_symbols (void)
2647 {
2648 #ifdef USE_THREAD_DB
2649   struct process_info *proc = current_process ();
2650
2651   if (proc->private->thread_db != NULL)
2652     return;
2653
2654   thread_db_init (!linux_supports_tracefork_flag);
2655 #endif
2656 }
2657
2658 static void
2659 linux_request_interrupt (void)
2660 {
2661   extern unsigned long signal_pid;
2662
2663   if (!ptid_equal (cont_thread, null_ptid)
2664       && !ptid_equal (cont_thread, minus_one_ptid))
2665     {
2666       struct lwp_info *lwp;
2667       int lwpid;
2668
2669       lwp = get_thread_lwp (current_inferior);
2670       lwpid = lwpid_of (lwp);
2671       kill_lwp (lwpid, SIGINT);
2672     }
2673   else
2674     kill_lwp (signal_pid, SIGINT);
2675 }
2676
2677 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
2678    to debugger memory starting at MYADDR.  */
2679
2680 static int
2681 linux_read_auxv (CORE_ADDR offset, unsigned char *myaddr, unsigned int len)
2682 {
2683   char filename[PATH_MAX];
2684   int fd, n;
2685   int pid = lwpid_of (get_thread_lwp (current_inferior));
2686
2687   snprintf (filename, sizeof filename, "/proc/%d/auxv", pid);
2688
2689   fd = open (filename, O_RDONLY);
2690   if (fd < 0)
2691     return -1;
2692
2693   if (offset != (CORE_ADDR) 0
2694       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
2695     n = -1;
2696   else
2697     n = read (fd, myaddr, len);
2698
2699   close (fd);
2700
2701   return n;
2702 }
2703
2704 /* These breakpoint and watchpoint related wrapper functions simply
2705    pass on the function call if the target has registered a
2706    corresponding function.  */
2707
2708 static int
2709 linux_insert_point (char type, CORE_ADDR addr, int len)
2710 {
2711   if (the_low_target.insert_point != NULL)
2712     return the_low_target.insert_point (type, addr, len);
2713   else
2714     /* Unsupported (see target.h).  */
2715     return 1;
2716 }
2717
2718 static int
2719 linux_remove_point (char type, CORE_ADDR addr, int len)
2720 {
2721   if (the_low_target.remove_point != NULL)
2722     return the_low_target.remove_point (type, addr, len);
2723   else
2724     /* Unsupported (see target.h).  */
2725     return 1;
2726 }
2727
2728 static int
2729 linux_stopped_by_watchpoint (void)
2730 {
2731   if (the_low_target.stopped_by_watchpoint != NULL)
2732     return the_low_target.stopped_by_watchpoint ();
2733   else
2734     return 0;
2735 }
2736
2737 static CORE_ADDR
2738 linux_stopped_data_address (void)
2739 {
2740   if (the_low_target.stopped_data_address != NULL)
2741     return the_low_target.stopped_data_address ();
2742   else
2743     return 0;
2744 }
2745
2746 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
2747 #if defined(__mcoldfire__)
2748 /* These should really be defined in the kernel's ptrace.h header.  */
2749 #define PT_TEXT_ADDR 49*4
2750 #define PT_DATA_ADDR 50*4
2751 #define PT_TEXT_END_ADDR  51*4
2752 #endif
2753
2754 /* Under uClinux, programs are loaded at non-zero offsets, which we need
2755    to tell gdb about.  */
2756
2757 static int
2758 linux_read_offsets (CORE_ADDR *text_p, CORE_ADDR *data_p)
2759 {
2760 #if defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) && defined(PT_TEXT_END_ADDR)
2761   unsigned long text, text_end, data;
2762   int pid = lwpid_of (get_thread_lwp (current_inferior));
2763
2764   errno = 0;
2765
2766   text = ptrace (PTRACE_PEEKUSER, pid, (long)PT_TEXT_ADDR, 0);
2767   text_end = ptrace (PTRACE_PEEKUSER, pid, (long)PT_TEXT_END_ADDR, 0);
2768   data = ptrace (PTRACE_PEEKUSER, pid, (long)PT_DATA_ADDR, 0);
2769
2770   if (errno == 0)
2771     {
2772       /* Both text and data offsets produced at compile-time (and so
2773          used by gdb) are relative to the beginning of the program,
2774          with the data segment immediately following the text segment.
2775          However, the actual runtime layout in memory may put the data
2776          somewhere else, so when we send gdb a data base-address, we
2777          use the real data base address and subtract the compile-time
2778          data base-address from it (which is just the length of the
2779          text segment).  BSS immediately follows data in both
2780          cases.  */
2781       *text_p = text;
2782       *data_p = data - (text_end - text);
2783
2784       return 1;
2785     }
2786 #endif
2787  return 0;
2788 }
2789 #endif
2790
2791 static int
2792 linux_qxfer_osdata (const char *annex,
2793                     unsigned char *readbuf, unsigned const char *writebuf,
2794                     CORE_ADDR offset, int len)
2795 {
2796   /* We make the process list snapshot when the object starts to be
2797      read.  */
2798   static const char *buf;
2799   static long len_avail = -1;
2800   static struct buffer buffer;
2801
2802   DIR *dirp;
2803
2804   if (strcmp (annex, "processes") != 0)
2805     return 0;
2806
2807   if (!readbuf || writebuf)
2808     return 0;
2809
2810   if (offset == 0)
2811     {
2812       if (len_avail != -1 && len_avail != 0)
2813        buffer_free (&buffer);
2814       len_avail = 0;
2815       buf = NULL;
2816       buffer_init (&buffer);
2817       buffer_grow_str (&buffer, "<osdata type=\"processes\">");
2818
2819       dirp = opendir ("/proc");
2820       if (dirp)
2821        {
2822          struct dirent *dp;
2823          while ((dp = readdir (dirp)) != NULL)
2824            {
2825              struct stat statbuf;
2826              char procentry[sizeof ("/proc/4294967295")];
2827
2828              if (!isdigit (dp->d_name[0])
2829                  || strlen (dp->d_name) > sizeof ("4294967295") - 1)
2830                continue;
2831
2832              sprintf (procentry, "/proc/%s", dp->d_name);
2833              if (stat (procentry, &statbuf) == 0
2834                  && S_ISDIR (statbuf.st_mode))
2835                {
2836                  char pathname[128];
2837                  FILE *f;
2838                  char cmd[MAXPATHLEN + 1];
2839                  struct passwd *entry;
2840
2841                  sprintf (pathname, "/proc/%s/cmdline", dp->d_name);
2842                  entry = getpwuid (statbuf.st_uid);
2843
2844                  if ((f = fopen (pathname, "r")) != NULL)
2845                    {
2846                      size_t len = fread (cmd, 1, sizeof (cmd) - 1, f);
2847                      if (len > 0)
2848                        {
2849                          int i;
2850                          for (i = 0; i < len; i++)
2851                            if (cmd[i] == '\0')
2852                              cmd[i] = ' ';
2853                          cmd[len] = '\0';
2854
2855                          buffer_xml_printf (
2856                            &buffer,
2857                            "<item>"
2858                            "<column name=\"pid\">%s</column>"
2859                            "<column name=\"user\">%s</column>"
2860                            "<column name=\"command\">%s</column>"
2861                            "</item>",
2862                            dp->d_name,
2863                            entry ? entry->pw_name : "?",
2864                            cmd);
2865                        }
2866                      fclose (f);
2867                    }
2868                }
2869            }
2870
2871          closedir (dirp);
2872        }
2873       buffer_grow_str0 (&buffer, "</osdata>\n");
2874       buf = buffer_finish (&buffer);
2875       len_avail = strlen (buf);
2876     }
2877
2878   if (offset >= len_avail)
2879     {
2880       /* Done.  Get rid of the data.  */
2881       buffer_free (&buffer);
2882       buf = NULL;
2883       len_avail = 0;
2884       return 0;
2885     }
2886
2887   if (len > len_avail - offset)
2888     len = len_avail - offset;
2889   memcpy (readbuf, buf + offset, len);
2890
2891   return len;
2892 }
2893
2894 /* Convert a native/host siginfo object, into/from the siginfo in the
2895    layout of the inferiors' architecture.  */
2896
2897 static void
2898 siginfo_fixup (struct siginfo *siginfo, void *inf_siginfo, int direction)
2899 {
2900   int done = 0;
2901
2902   if (the_low_target.siginfo_fixup != NULL)
2903     done = the_low_target.siginfo_fixup (siginfo, inf_siginfo, direction);
2904
2905   /* If there was no callback, or the callback didn't do anything,
2906      then just do a straight memcpy.  */
2907   if (!done)
2908     {
2909       if (direction == 1)
2910         memcpy (siginfo, inf_siginfo, sizeof (struct siginfo));
2911       else
2912         memcpy (inf_siginfo, siginfo, sizeof (struct siginfo));
2913     }
2914 }
2915
2916 static int
2917 linux_xfer_siginfo (const char *annex, unsigned char *readbuf,
2918                     unsigned const char *writebuf, CORE_ADDR offset, int len)
2919 {
2920   int pid;
2921   struct siginfo siginfo;
2922   char inf_siginfo[sizeof (struct siginfo)];
2923
2924   if (current_inferior == NULL)
2925     return -1;
2926
2927   pid = lwpid_of (get_thread_lwp (current_inferior));
2928
2929   if (debug_threads)
2930     fprintf (stderr, "%s siginfo for lwp %d.\n",
2931              readbuf != NULL ? "Reading" : "Writing",
2932              pid);
2933
2934   if (offset > sizeof (siginfo))
2935     return -1;
2936
2937   if (ptrace (PTRACE_GETSIGINFO, pid, 0, &siginfo) != 0)
2938     return -1;
2939
2940   /* When GDBSERVER is built as a 64-bit application, ptrace writes into
2941      SIGINFO an object with 64-bit layout.  Since debugging a 32-bit
2942      inferior with a 64-bit GDBSERVER should look the same as debugging it
2943      with a 32-bit GDBSERVER, we need to convert it.  */
2944   siginfo_fixup (&siginfo, inf_siginfo, 0);
2945
2946   if (offset + len > sizeof (siginfo))
2947     len = sizeof (siginfo) - offset;
2948
2949   if (readbuf != NULL)
2950     memcpy (readbuf, inf_siginfo + offset, len);
2951   else
2952     {
2953       memcpy (inf_siginfo + offset, writebuf, len);
2954
2955       /* Convert back to ptrace layout before flushing it out.  */
2956       siginfo_fixup (&siginfo, inf_siginfo, 1);
2957
2958       if (ptrace (PTRACE_SETSIGINFO, pid, 0, &siginfo) != 0)
2959         return -1;
2960     }
2961
2962   return len;
2963 }
2964
2965 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
2966    so we notice when children change state; as the handler for the
2967    sigsuspend in my_waitpid.  */
2968
2969 static void
2970 sigchld_handler (int signo)
2971 {
2972   int old_errno = errno;
2973
2974   if (debug_threads)
2975     /* fprintf is not async-signal-safe, so call write directly.  */
2976     write (2, "sigchld_handler\n", sizeof ("sigchld_handler\n") - 1);
2977
2978   if (target_is_async_p ())
2979     async_file_mark (); /* trigger a linux_wait */
2980
2981   errno = old_errno;
2982 }
2983
2984 static int
2985 linux_supports_non_stop (void)
2986 {
2987   return 1;
2988 }
2989
2990 static int
2991 linux_async (int enable)
2992 {
2993   int previous = (linux_event_pipe[0] != -1);
2994
2995   if (previous != enable)
2996     {
2997       sigset_t mask;
2998       sigemptyset (&mask);
2999       sigaddset (&mask, SIGCHLD);
3000
3001       sigprocmask (SIG_BLOCK, &mask, NULL);
3002
3003       if (enable)
3004         {
3005           if (pipe (linux_event_pipe) == -1)
3006             fatal ("creating event pipe failed.");
3007
3008           fcntl (linux_event_pipe[0], F_SETFL, O_NONBLOCK);
3009           fcntl (linux_event_pipe[1], F_SETFL, O_NONBLOCK);
3010
3011           /* Register the event loop handler.  */
3012           add_file_handler (linux_event_pipe[0],
3013                             handle_target_event, NULL);
3014
3015           /* Always trigger a linux_wait.  */
3016           async_file_mark ();
3017         }
3018       else
3019         {
3020           delete_file_handler (linux_event_pipe[0]);
3021
3022           close (linux_event_pipe[0]);
3023           close (linux_event_pipe[1]);
3024           linux_event_pipe[0] = -1;
3025           linux_event_pipe[1] = -1;
3026         }
3027
3028       sigprocmask (SIG_UNBLOCK, &mask, NULL);
3029     }
3030
3031   return previous;
3032 }
3033
3034 static int
3035 linux_start_non_stop (int nonstop)
3036 {
3037   /* Register or unregister from event-loop accordingly.  */
3038   linux_async (nonstop);
3039   return 0;
3040 }
3041
3042 static int
3043 linux_supports_multi_process (void)
3044 {
3045   return 1;
3046 }
3047
3048
3049 /* Enumerate spufs IDs for process PID.  */
3050 static int
3051 spu_enumerate_spu_ids (long pid, unsigned char *buf, CORE_ADDR offset, int len)
3052 {
3053   int pos = 0;
3054   int written = 0;
3055   char path[128];
3056   DIR *dir;
3057   struct dirent *entry;
3058
3059   sprintf (path, "/proc/%ld/fd", pid);
3060   dir = opendir (path);
3061   if (!dir)
3062     return -1;
3063
3064   rewinddir (dir);
3065   while ((entry = readdir (dir)) != NULL)
3066     {
3067       struct stat st;
3068       struct statfs stfs;
3069       int fd;
3070
3071       fd = atoi (entry->d_name);
3072       if (!fd)
3073         continue;
3074
3075       sprintf (path, "/proc/%ld/fd/%d", pid, fd);
3076       if (stat (path, &st) != 0)
3077         continue;
3078       if (!S_ISDIR (st.st_mode))
3079         continue;
3080
3081       if (statfs (path, &stfs) != 0)
3082         continue;
3083       if (stfs.f_type != SPUFS_MAGIC)
3084         continue;
3085
3086       if (pos >= offset && pos + 4 <= offset + len)
3087         {
3088           *(unsigned int *)(buf + pos - offset) = fd;
3089           written += 4;
3090         }
3091       pos += 4;
3092     }
3093
3094   closedir (dir);
3095   return written;
3096 }
3097
3098 /* Implements the to_xfer_partial interface for the TARGET_OBJECT_SPU
3099    object type, using the /proc file system.  */
3100 static int
3101 linux_qxfer_spu (const char *annex, unsigned char *readbuf,
3102                  unsigned const char *writebuf,
3103                  CORE_ADDR offset, int len)
3104 {
3105   long pid = lwpid_of (get_thread_lwp (current_inferior));
3106   char buf[128];
3107   int fd = 0;
3108   int ret = 0;
3109
3110   if (!writebuf && !readbuf)
3111     return -1;
3112
3113   if (!*annex)
3114     {
3115       if (!readbuf)
3116         return -1;
3117       else
3118         return spu_enumerate_spu_ids (pid, readbuf, offset, len);
3119     }
3120
3121   sprintf (buf, "/proc/%ld/fd/%s", pid, annex);
3122   fd = open (buf, writebuf? O_WRONLY : O_RDONLY);
3123   if (fd <= 0)
3124     return -1;
3125
3126   if (offset != 0
3127       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
3128     {
3129       close (fd);
3130       return 0;
3131     }
3132
3133   if (writebuf)
3134     ret = write (fd, writebuf, (size_t) len);
3135   else
3136     ret = read (fd, readbuf, (size_t) len);
3137
3138   close (fd);
3139   return ret;
3140 }
3141
3142 static struct target_ops linux_target_ops = {
3143   linux_create_inferior,
3144   linux_attach,
3145   linux_kill,
3146   linux_detach,
3147   linux_join,
3148   linux_thread_alive,
3149   linux_resume,
3150   linux_wait,
3151   linux_fetch_registers,
3152   linux_store_registers,
3153   linux_read_memory,
3154   linux_write_memory,
3155   linux_look_up_symbols,
3156   linux_request_interrupt,
3157   linux_read_auxv,
3158   linux_insert_point,
3159   linux_remove_point,
3160   linux_stopped_by_watchpoint,
3161   linux_stopped_data_address,
3162 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
3163   linux_read_offsets,
3164 #else
3165   NULL,
3166 #endif
3167 #ifdef USE_THREAD_DB
3168   thread_db_get_tls_address,
3169 #else
3170   NULL,
3171 #endif
3172   linux_qxfer_spu,
3173   hostio_last_error_from_errno,
3174   linux_qxfer_osdata,
3175   linux_xfer_siginfo,
3176   linux_supports_non_stop,
3177   linux_async,
3178   linux_start_non_stop,
3179   linux_supports_multi_process,
3180 #ifdef USE_THREAD_DB
3181   thread_db_handle_monitor_command
3182 #else
3183   NULL
3184 #endif
3185 };
3186
3187 static void
3188 linux_init_signals ()
3189 {
3190   /* FIXME drow/2002-06-09: As above, we should check with LinuxThreads
3191      to find what the cancel signal actually is.  */
3192   signal (__SIGRTMIN+1, SIG_IGN);
3193 }
3194
3195 void
3196 initialize_low (void)
3197 {
3198   struct sigaction sigchld_action;
3199   memset (&sigchld_action, 0, sizeof (sigchld_action));
3200   set_target_ops (&linux_target_ops);
3201   set_breakpoint_data (the_low_target.breakpoint,
3202                        the_low_target.breakpoint_len);
3203   linux_init_signals ();
3204   linux_test_for_tracefork ();
3205 #ifdef HAVE_LINUX_REGSETS
3206   for (num_regsets = 0; target_regsets[num_regsets].size >= 0; num_regsets++)
3207     ;
3208   disabled_regsets = xmalloc (num_regsets);
3209 #endif
3210
3211   sigchld_action.sa_handler = sigchld_handler;
3212   sigemptyset (&sigchld_action.sa_mask);
3213   sigchld_action.sa_flags = SA_RESTART;
3214   sigaction (SIGCHLD, &sigchld_action, NULL);
3215 }