OSDN Git Service

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