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