gdb/gdbserver/linux-low.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Low level interface to ptrace, for the remote server for GDB.
  2.    Copyright (C) 1995-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "server.h"
  15. #include "linux-low.h"
  16. #include "nat/linux-osdata.h"
  17. #include "agent.h"

  18. #include "nat/linux-nat.h"
  19. #include "nat/linux-waitpid.h"
  20. #include "gdb_wait.h"
  21. #include <sys/ptrace.h>
  22. #include "nat/linux-ptrace.h"
  23. #include "nat/linux-procfs.h"
  24. #include <signal.h>
  25. #include <sys/ioctl.h>
  26. #include <fcntl.h>
  27. #include <unistd.h>
  28. #include <sys/syscall.h>
  29. #include <sched.h>
  30. #include <ctype.h>
  31. #include <pwd.h>
  32. #include <sys/types.h>
  33. #include <dirent.h>
  34. #include <sys/stat.h>
  35. #include <sys/vfs.h>
  36. #include <sys/uio.h>
  37. #include "filestuff.h"
  38. #include "tracepoint.h"
  39. #include "hostio.h"
  40. #ifndef ELFMAG0
  41. /* Don't include <linux/elf.h> here.  If it got included by gdb_proc_service.h
  42.    then ELFMAG0 will have been defined.  If it didn't get included by
  43.    gdb_proc_service.h then including it will likely introduce a duplicate
  44.    definition of elf_fpregset_t.  */
  45. #include <elf.h>
  46. #endif

  47. #ifndef SPUFS_MAGIC
  48. #define SPUFS_MAGIC 0x23c9b64e
  49. #endif

  50. #ifdef HAVE_PERSONALITY
  51. # include <sys/personality.h>
  52. # if !HAVE_DECL_ADDR_NO_RANDOMIZE
  53. #  define ADDR_NO_RANDOMIZE 0x0040000
  54. # endif
  55. #endif

  56. #ifndef O_LARGEFILE
  57. #define O_LARGEFILE 0
  58. #endif

  59. #ifndef W_STOPCODE
  60. #define W_STOPCODE(sig) ((sig) << 8 | 0x7f)
  61. #endif

  62. /* This is the kernel's hard limit.  Not to be confused with
  63.    SIGRTMIN.  */
  64. #ifndef __SIGRTMIN
  65. #define __SIGRTMIN 32
  66. #endif

  67. /* Some targets did not define these ptrace constants from the start,
  68.    so gdbserver defines them locally here.  In the future, these may
  69.    be removed after they are added to asm/ptrace.h.  */
  70. #if !(defined(PT_TEXT_ADDR) \
  71.       || defined(PT_DATA_ADDR) \
  72.       || defined(PT_TEXT_END_ADDR))
  73. #if defined(__mcoldfire__)
  74. /* These are still undefined in 3.10 kernels.  */
  75. #define PT_TEXT_ADDR 49*4
  76. #define PT_DATA_ADDR 50*4
  77. #define PT_TEXT_END_ADDR  51*4
  78. /* BFIN already defines these since at least 2.6.32 kernels.  */
  79. #elif defined(BFIN)
  80. #define PT_TEXT_ADDR 220
  81. #define PT_TEXT_END_ADDR 224
  82. #define PT_DATA_ADDR 228
  83. /* These are still undefined in 3.10 kernels.  */
  84. #elif defined(__TMS320C6X__)
  85. #define PT_TEXT_ADDR     (0x10000*4)
  86. #define PT_DATA_ADDR     (0x10004*4)
  87. #define PT_TEXT_END_ADDR (0x10008*4)
  88. #endif
  89. #endif

  90. #ifdef HAVE_LINUX_BTRACE
  91. # include "nat/linux-btrace.h"
  92. #endif

  93. #ifndef HAVE_ELF32_AUXV_T
  94. /* Copied from glibc's elf.h.  */
  95. typedef struct
  96. {
  97.   uint32_t a_type;                /* Entry type */
  98.   union
  99.     {
  100.       uint32_t a_val;                /* Integer value */
  101.       /* We use to have pointer elements added here.  We cannot do that,
  102.          though, since it does not work when using 32-bit definitions
  103.          on 64-bit platforms and vice versa.  */
  104.     } a_un;
  105. } Elf32_auxv_t;
  106. #endif

  107. #ifndef HAVE_ELF64_AUXV_T
  108. /* Copied from glibc's elf.h.  */
  109. typedef struct
  110. {
  111.   uint64_t a_type;                /* Entry type */
  112.   union
  113.     {
  114.       uint64_t a_val;                /* Integer value */
  115.       /* We use to have pointer elements added here.  We cannot do that,
  116.          though, since it does not work when using 32-bit definitions
  117.          on 64-bit platforms and vice versa.  */
  118.     } a_un;
  119. } Elf64_auxv_t;
  120. #endif

  121. /* A list of all unknown processes which receive stop signals.  Some
  122.    other process will presumably claim each of these as forked
  123.    children momentarily.  */

  124. struct simple_pid_list
  125. {
  126.   /* The process ID.  */
  127.   int pid;

  128.   /* The status as reported by waitpid.  */
  129.   int status;

  130.   /* Next in chain.  */
  131.   struct simple_pid_list *next;
  132. };
  133. struct simple_pid_list *stopped_pids;

  134. /* Trivial list manipulation functions to keep track of a list of new
  135.    stopped processes.  */

  136. static void
  137. add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
  138. {
  139.   struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));

  140.   new_pid->pid = pid;
  141.   new_pid->status = status;
  142.   new_pid->next = *listp;
  143.   *listp = new_pid;
  144. }

  145. static int
  146. pull_pid_from_list (struct simple_pid_list **listp, int pid, int *statusp)
  147. {
  148.   struct simple_pid_list **p;

  149.   for (p = listp; *p != NULL; p = &(*p)->next)
  150.     if ((*p)->pid == pid)
  151.       {
  152.         struct simple_pid_list *next = (*p)->next;

  153.         *statusp = (*p)->status;
  154.         xfree (*p);
  155.         *p = next;
  156.         return 1;
  157.       }
  158.   return 0;
  159. }

  160. enum stopping_threads_kind
  161.   {
  162.     /* Not stopping threads presently.  */
  163.     NOT_STOPPING_THREADS,

  164.     /* Stopping threads.  */
  165.     STOPPING_THREADS,

  166.     /* Stopping and suspending threads.  */
  167.     STOPPING_AND_SUSPENDING_THREADS
  168.   };

  169. /* This is set while stop_all_lwps is in effect.  */
  170. enum stopping_threads_kind stopping_threads = NOT_STOPPING_THREADS;

  171. /* FIXME make into a target method?  */
  172. int using_threads = 1;

  173. /* True if we're presently stabilizing threads (moving them out of
  174.    jump pads).  */
  175. static int stabilizing_threads;

  176. static void linux_resume_one_lwp (struct lwp_info *lwp,
  177.                                   int step, int signal, siginfo_t *info);
  178. static void linux_resume (struct thread_resume *resume_info, size_t n);
  179. static void stop_all_lwps (int suspend, struct lwp_info *except);
  180. static void unstop_all_lwps (int unsuspend, struct lwp_info *except);
  181. static int linux_wait_for_event_filtered (ptid_t wait_ptid, ptid_t filter_ptid,
  182.                                           int *wstat, int options);
  183. static int linux_wait_for_event (ptid_t ptid, int *wstat, int options);
  184. static struct lwp_info *add_lwp (ptid_t ptid);
  185. static int linux_stopped_by_watchpoint (void);
  186. static void mark_lwp_dead (struct lwp_info *lwp, int wstat);
  187. static void proceed_all_lwps (void);
  188. static int finish_step_over (struct lwp_info *lwp);
  189. static int kill_lwp (unsigned long lwpid, int signo);

  190. /* When the event-loop is doing a step-over, this points at the thread
  191.    being stepped.  */
  192. ptid_t step_over_bkpt;

  193. /* True if the low target can hardware single-step.  Such targets
  194.    don't need a BREAKPOINT_REINSERT_ADDR callback.  */

  195. static int
  196. can_hardware_single_step (void)
  197. {
  198.   return (the_low_target.breakpoint_reinsert_addr == NULL);
  199. }

  200. /* True if the low target supports memory breakpoints.  If so, we'll
  201.    have a GET_PC implementation.  */

  202. static int
  203. supports_breakpoints (void)
  204. {
  205.   return (the_low_target.get_pc != NULL);
  206. }

  207. /* Returns true if this target can support fast tracepoints.  This
  208.    does not mean that the in-process agent has been loaded in the
  209.    inferior.  */

  210. static int
  211. supports_fast_tracepoints (void)
  212. {
  213.   return the_low_target.install_fast_tracepoint_jump_pad != NULL;
  214. }

  215. /* True if LWP is stopped in its stepping range.  */

  216. static int
  217. lwp_in_step_range (struct lwp_info *lwp)
  218. {
  219.   CORE_ADDR pc = lwp->stop_pc;

  220.   return (pc >= lwp->step_range_start && pc < lwp->step_range_end);
  221. }

  222. struct pending_signals
  223. {
  224.   int signal;
  225.   siginfo_t info;
  226.   struct pending_signals *prev;
  227. };

  228. /* The read/write ends of the pipe registered as waitable file in the
  229.    event loop.  */
  230. static int linux_event_pipe[2] = { -1, -1 };

  231. /* True if we're currently in async mode.  */
  232. #define target_is_async_p() (linux_event_pipe[0] != -1)

  233. static void send_sigstop (struct lwp_info *lwp);
  234. static void wait_for_sigstop (void);

  235. /* Return non-zero if HEADER is a 64-bit ELF file.  */

  236. static int
  237. elf_64_header_p (const Elf64_Ehdr *header, unsigned int *machine)
  238. {
  239.   if (header->e_ident[EI_MAG0] == ELFMAG0
  240.       && header->e_ident[EI_MAG1] == ELFMAG1
  241.       && header->e_ident[EI_MAG2] == ELFMAG2
  242.       && header->e_ident[EI_MAG3] == ELFMAG3)
  243.     {
  244.       *machine = header->e_machine;
  245.       return header->e_ident[EI_CLASS] == ELFCLASS64;

  246.     }
  247.   *machine = EM_NONE;
  248.   return -1;
  249. }

  250. /* Return non-zero if FILE is a 64-bit ELF file,
  251.    zero if the file is not a 64-bit ELF file,
  252.    and -1 if the file is not accessible or doesn't exist.  */

  253. static int
  254. elf_64_file_p (const char *file, unsigned int *machine)
  255. {
  256.   Elf64_Ehdr header;
  257.   int fd;

  258.   fd = open (file, O_RDONLY);
  259.   if (fd < 0)
  260.     return -1;

  261.   if (read (fd, &header, sizeof (header)) != sizeof (header))
  262.     {
  263.       close (fd);
  264.       return 0;
  265.     }
  266.   close (fd);

  267.   return elf_64_header_p (&header, machine);
  268. }

  269. /* Accepts an integer PID; Returns true if the executable PID is
  270.    running is a 64-bit ELF file..  */

  271. int
  272. linux_pid_exe_is_elf_64_file (int pid, unsigned int *machine)
  273. {
  274.   char file[PATH_MAX];

  275.   sprintf (file, "/proc/%d/exe", pid);
  276.   return elf_64_file_p (file, machine);
  277. }

  278. static void
  279. delete_lwp (struct lwp_info *lwp)
  280. {
  281.   struct thread_info *thr = get_lwp_thread (lwp);

  282.   if (debug_threads)
  283.     debug_printf ("deleting %ld\n", lwpid_of (thr));

  284.   remove_thread (thr);
  285.   free (lwp->arch_private);
  286.   free (lwp);
  287. }

  288. /* Add a process to the common process list, and set its private
  289.    data.  */

  290. static struct process_info *
  291. linux_add_process (int pid, int attached)
  292. {
  293.   struct process_info *proc;

  294.   proc = add_process (pid, attached);
  295.   proc->private = xcalloc (1, sizeof (*proc->private));

  296.   /* Set the arch when the first LWP stops.  */
  297.   proc->private->new_inferior = 1;

  298.   if (the_low_target.new_process != NULL)
  299.     proc->private->arch_private = the_low_target.new_process ();

  300.   return proc;
  301. }

  302. static CORE_ADDR get_pc (struct lwp_info *lwp);

  303. /* Handle a GNU/Linux extended wait response.  If we see a clone
  304.    event, we need to add the new LWP to our list (and not report the
  305.    trap to higher layers).  */

  306. static void
  307. handle_extended_wait (struct lwp_info *event_child, int wstat)
  308. {
  309.   int event = linux_ptrace_get_extended_event (wstat);
  310.   struct thread_info *event_thr = get_lwp_thread (event_child);
  311.   struct lwp_info *new_lwp;

  312.   if (event == PTRACE_EVENT_CLONE)
  313.     {
  314.       ptid_t ptid;
  315.       unsigned long new_pid;
  316.       int ret, status;

  317.       ptrace (PTRACE_GETEVENTMSG, lwpid_of (event_thr), (PTRACE_TYPE_ARG3) 0,
  318.               &new_pid);

  319.       /* If we haven't already seen the new PID stop, wait for it now.  */
  320.       if (!pull_pid_from_list (&stopped_pids, new_pid, &status))
  321.         {
  322.           /* The new child has a pending SIGSTOP.  We can't affect it until it
  323.              hits the SIGSTOP, but we're already attached.  */

  324.           ret = my_waitpid (new_pid, &status, __WALL);

  325.           if (ret == -1)
  326.             perror_with_name ("waiting for new child");
  327.           else if (ret != new_pid)
  328.             warning ("wait returned unexpected PID %d", ret);
  329.           else if (!WIFSTOPPED (status))
  330.             warning ("wait returned unexpected status 0x%x", status);
  331.         }

  332.       if (debug_threads)
  333.         debug_printf ("HEW: Got clone event "
  334.                       "from LWP %ld, new child is LWP %ld\n",
  335.                       lwpid_of (event_thr), new_pid);

  336.       ptid = ptid_build (pid_of (event_thr), new_pid, 0);
  337.       new_lwp = add_lwp (ptid);

  338.       /* Either we're going to immediately resume the new thread
  339.          or leave it stopped.  linux_resume_one_lwp is a nop if it
  340.          thinks the thread is currently running, so set this first
  341.          before calling linux_resume_one_lwp.  */
  342.       new_lwp->stopped = 1;

  343.      /* If we're suspending all threads, leave this one suspended
  344.         too.  */
  345.       if (stopping_threads == STOPPING_AND_SUSPENDING_THREADS)
  346.         new_lwp->suspended = 1;

  347.       /* Normally we will get the pending SIGSTOP.  But in some cases
  348.          we might get another signal delivered to the group first.
  349.          If we do get another signal, be sure not to lose it.  */
  350.       if (WSTOPSIG (status) == SIGSTOP)
  351.         {
  352.           if (stopping_threads == NOT_STOPPING_THREADS)
  353.             linux_resume_one_lwp (new_lwp, 0, 0, NULL);
  354.         }
  355.       else
  356.         {
  357.           new_lwp->stop_expected = 1;

  358.           if (stopping_threads != NOT_STOPPING_THREADS)
  359.             {
  360.               new_lwp->status_pending_p = 1;
  361.               new_lwp->status_pending = status;
  362.             }
  363.           else
  364.             /* Pass the signal on.  This is what GDB does - except
  365.                shouldn't we really report it instead?  */
  366.             linux_resume_one_lwp (new_lwp, 0, WSTOPSIG (status), NULL);
  367.         }

  368.       /* Always resume the current thread.  If we are stopping
  369.          threads, it will have a pending SIGSTOP; we may as well
  370.          collect it now.  */
  371.       linux_resume_one_lwp (event_child, event_child->stepping, 0, NULL);
  372.     }
  373. }

  374. /* Return the PC as read from the regcache of LWP, without any
  375.    adjustment.  */

  376. static CORE_ADDR
  377. get_pc (struct lwp_info *lwp)
  378. {
  379.   struct thread_info *saved_thread;
  380.   struct regcache *regcache;
  381.   CORE_ADDR pc;

  382.   if (the_low_target.get_pc == NULL)
  383.     return 0;

  384.   saved_thread = current_thread;
  385.   current_thread = get_lwp_thread (lwp);

  386.   regcache = get_thread_regcache (current_thread, 1);
  387.   pc = (*the_low_target.get_pc) (regcache);

  388.   if (debug_threads)
  389.     debug_printf ("pc is 0x%lx\n", (long) pc);

  390.   current_thread = saved_thread;
  391.   return pc;
  392. }

  393. /* This function should only be called if LWP got a SIGTRAP.
  394.    The SIGTRAP could mean several things.

  395.    On i386, where decr_pc_after_break is non-zero:

  396.    If we were single-stepping this process using PTRACE_SINGLESTEP, we
  397.    will get only the one SIGTRAP.  The value of $eip will be the next
  398.    instruction.  If the instruction we stepped over was a breakpoint,
  399.    we need to decrement the PC.

  400.    If we continue the process using PTRACE_CONT, we will get a
  401.    SIGTRAP when we hit a breakpoint.  The value of $eip will be
  402.    the instruction after the breakpoint (i.e. needs to be
  403.    decremented).  If we report the SIGTRAP to GDB, we must also
  404.    report the undecremented PC.  If the breakpoint is removed, we
  405.    must resume at the decremented PC.

  406.    On a non-decr_pc_after_break machine with hardware or kernel
  407.    single-step:

  408.    If we either single-step a breakpoint instruction, or continue and
  409.    hit a breakpoint instruction, our PC will point at the breakpoint
  410.    instruction.  */

  411. static int
  412. check_stopped_by_breakpoint (struct lwp_info *lwp)
  413. {
  414.   CORE_ADDR pc;
  415.   CORE_ADDR sw_breakpoint_pc;
  416.   struct thread_info *saved_thread;

  417.   if (the_low_target.get_pc == NULL)
  418.     return 0;

  419.   pc = get_pc (lwp);
  420.   sw_breakpoint_pc = pc - the_low_target.decr_pc_after_break;

  421.   /* breakpoint_at reads from the current thread.  */
  422.   saved_thread = current_thread;
  423.   current_thread = get_lwp_thread (lwp);

  424.   /* We may have just stepped a breakpoint instruction.  E.g., in
  425.      non-stop mode, GDB first tells the thread A to step a range, and
  426.      then the user inserts a breakpoint inside the range.  In that
  427.      case, we need to report the breakpoint PC.  But, when we're
  428.      trying to step past one of our own breakpoints, that happens to
  429.      have been placed on top of a permanent breakpoint instruction, we
  430.      shouldn't adjust the PC, otherwise the program would keep
  431.      trapping the permanent breakpoint forever.  */
  432.   if ((!lwp->stepping
  433.        || (!ptid_equal (ptid_of (current_thread), step_over_bkpt)
  434.            && lwp->stop_pc == sw_breakpoint_pc))
  435.       && (*the_low_target.breakpoint_at) (sw_breakpoint_pc))
  436.     {
  437.       if (debug_threads)
  438.         {
  439.           struct thread_info *thr = get_lwp_thread (lwp);

  440.           debug_printf ("CSBB: %s stopped by software breakpoint\n",
  441.                         target_pid_to_str (ptid_of (thr)));
  442.         }

  443.       /* Back up the PC if necessary.  */
  444.       if (pc != sw_breakpoint_pc)
  445.         {
  446.           struct regcache *regcache
  447.             = get_thread_regcache (current_thread, 1);
  448.           (*the_low_target.set_pc) (regcache, sw_breakpoint_pc);
  449.         }

  450.       lwp->stop_pc = sw_breakpoint_pc;
  451.       lwp->stop_reason = LWP_STOPPED_BY_SW_BREAKPOINT;
  452.       current_thread = saved_thread;
  453.       return 1;
  454.     }

  455.   if (hardware_breakpoint_inserted_here (pc))
  456.     {
  457.       if (debug_threads)
  458.         {
  459.           struct thread_info *thr = get_lwp_thread (lwp);

  460.           debug_printf ("CSBB: %s stopped by hardware breakpoint\n",
  461.                         target_pid_to_str (ptid_of (thr)));
  462.         }

  463.       lwp->stop_pc = pc;
  464.       lwp->stop_reason = LWP_STOPPED_BY_HW_BREAKPOINT;
  465.       current_thread = saved_thread;
  466.       return 1;
  467.     }

  468.   current_thread = saved_thread;
  469.   return 0;
  470. }

  471. static struct lwp_info *
  472. add_lwp (ptid_t ptid)
  473. {
  474.   struct lwp_info *lwp;

  475.   lwp = (struct lwp_info *) xmalloc (sizeof (*lwp));
  476.   memset (lwp, 0, sizeof (*lwp));

  477.   if (the_low_target.new_thread != NULL)
  478.     lwp->arch_private = the_low_target.new_thread ();

  479.   lwp->thread = add_thread (ptid, lwp);

  480.   return lwp;
  481. }

  482. /* Start an inferior process and returns its pid.
  483.    ALLARGS is a vector of program-name and args. */

  484. static int
  485. linux_create_inferior (char *program, char **allargs)
  486. {
  487. #ifdef HAVE_PERSONALITY
  488.   int personality_orig = 0, personality_set = 0;
  489. #endif
  490.   struct lwp_info *new_lwp;
  491.   int pid;
  492.   ptid_t ptid;

  493. #ifdef HAVE_PERSONALITY
  494.   if (disable_randomization)
  495.     {
  496.       errno = 0;
  497.       personality_orig = personality (0xffffffff);
  498.       if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
  499.         {
  500.           personality_set = 1;
  501.           personality (personality_orig | ADDR_NO_RANDOMIZE);
  502.         }
  503.       if (errno != 0 || (personality_set
  504.                          && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
  505.         warning ("Error disabling address space randomization: %s",
  506.                  strerror (errno));
  507.     }
  508. #endif

  509. #if defined(__UCLIBC__) && defined(HAS_NOMMU)
  510.   pid = vfork ();
  511. #else
  512.   pid = fork ();
  513. #endif
  514.   if (pid < 0)
  515.     perror_with_name ("fork");

  516.   if (pid == 0)
  517.     {
  518.       close_most_fds ();
  519.       ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);

  520. #ifndef __ANDROID__ /* Bionic doesn't use SIGRTMIN the way glibc does.  */
  521.       signal (__SIGRTMIN + 1, SIG_DFL);
  522. #endif

  523.       setpgid (0, 0);

  524.       /* If gdbserver is connected to gdb via stdio, redirect the inferior's
  525.          stdout to stderr so that inferior i/o doesn't corrupt the connection.
  526.          Also, redirect stdin to /dev/null.  */
  527.       if (remote_connection_is_stdio ())
  528.         {
  529.           close (0);
  530.           open ("/dev/null", O_RDONLY);
  531.           dup2 (2, 1);
  532.           if (write (2, "stdin/stdout redirected\n",
  533.                      sizeof ("stdin/stdout redirected\n") - 1) < 0)
  534.             {
  535.               /* Errors ignored.  */;
  536.             }
  537.         }

  538.       execv (program, allargs);
  539.       if (errno == ENOENT)
  540.         execvp (program, allargs);

  541.       fprintf (stderr, "Cannot exec %s: %s.\n", program,
  542.                strerror (errno));
  543.       fflush (stderr);
  544.       _exit (0177);
  545.     }

  546. #ifdef HAVE_PERSONALITY
  547.   if (personality_set)
  548.     {
  549.       errno = 0;
  550.       personality (personality_orig);
  551.       if (errno != 0)
  552.         warning ("Error restoring address space randomization: %s",
  553.                  strerror (errno));
  554.     }
  555. #endif

  556.   linux_add_process (pid, 0);

  557.   ptid = ptid_build (pid, pid, 0);
  558.   new_lwp = add_lwp (ptid);
  559.   new_lwp->must_set_ptrace_flags = 1;

  560.   return pid;
  561. }

  562. /* Attach to an inferior process.  Returns 0 on success, ERRNO on
  563.    error.  */

  564. int
  565. linux_attach_lwp (ptid_t ptid)
  566. {
  567.   struct lwp_info *new_lwp;
  568.   int lwpid = ptid_get_lwp (ptid);

  569.   if (ptrace (PTRACE_ATTACH, lwpid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0)
  570.       != 0)
  571.     return errno;

  572.   new_lwp = add_lwp (ptid);

  573.   /* We need to wait for SIGSTOP before being able to make the next
  574.      ptrace call on this LWP.  */
  575.   new_lwp->must_set_ptrace_flags = 1;

  576.   if (linux_proc_pid_is_stopped (lwpid))
  577.     {
  578.       if (debug_threads)
  579.         debug_printf ("Attached to a stopped process\n");

  580.       /* The process is definitely stopped.  It is in a job control
  581.          stop, unless the kernel predates the TASK_STOPPED /
  582.          TASK_TRACED distinction, in which case it might be in a
  583.          ptrace stop.  Make sure it is in a ptrace stop; from there we
  584.          can kill it, signal it, et cetera.

  585.          First make sure there is a pending SIGSTOP.  Since we are
  586.          already attached, the process can not transition from stopped
  587.          to running without a PTRACE_CONT; so we know this signal will
  588.          go into the queue.  The SIGSTOP generated by PTRACE_ATTACH is
  589.          probably already in the queue (unless this kernel is old
  590.          enough to use TASK_STOPPED for ptrace stops); but since
  591.          SIGSTOP is not an RT signal, it can only be queued once.  */
  592.       kill_lwp (lwpid, SIGSTOP);

  593.       /* Finally, resume the stopped process.  This will deliver the
  594.          SIGSTOP (or a higher priority signal, just like normal
  595.          PTRACE_ATTACH), which we'll catch later on.  */
  596.       ptrace (PTRACE_CONT, lwpid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
  597.     }

  598.   /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
  599.      brings it to a halt.

  600.      There are several cases to consider here:

  601.      1) gdbserver has already attached to the process and is being notified
  602.         of a new thread that is being created.
  603.         In this case we should ignore that SIGSTOP and resume the
  604.         process.  This is handled below by setting stop_expected = 1,
  605.         and the fact that add_thread sets last_resume_kind ==
  606.         resume_continue.

  607.      2) This is the first thread (the process thread), and we're attaching
  608.         to it via attach_inferior.
  609.         In this case we want the process thread to stop.
  610.         This is handled by having linux_attach set last_resume_kind ==
  611.         resume_stop after we return.

  612.         If the pid we are attaching to is also the tgid, we attach to and
  613.         stop all the existing threads.  Otherwise, we attach to pid and
  614.         ignore any other threads in the same group as this pid.

  615.      3) GDB is connecting to gdbserver and is requesting an enumeration of all
  616.         existing threads.
  617.         In this case we want the thread to stop.
  618.         FIXME: This case is currently not properly handled.
  619.         We should wait for the SIGSTOP but don't.  Things work apparently
  620.         because enough time passes between when we ptrace (ATTACH) and when
  621.         gdb makes the next ptrace call on the thread.

  622.      On the other hand, if we are currently trying to stop all threads, we
  623.      should treat the new thread as if we had sent it a SIGSTOP.  This works
  624.      because we are guaranteed that the add_lwp call above added us to the
  625.      end of the list, and so the new thread has not yet reached
  626.      wait_for_sigstop (but will).  */
  627.   new_lwp->stop_expected = 1;

  628.   return 0;
  629. }

  630. /* Callback for linux_proc_attach_tgid_threads.  Attach to PTID if not
  631.    already attached.  Returns true if a new LWP is found, false
  632.    otherwise.  */

  633. static int
  634. attach_proc_task_lwp_callback (ptid_t ptid)
  635. {
  636.   /* Is this a new thread?  */
  637.   if (find_thread_ptid (ptid) == NULL)
  638.     {
  639.       int lwpid = ptid_get_lwp (ptid);
  640.       int err;

  641.       if (debug_threads)
  642.         debug_printf ("Found new lwp %d\n", lwpid);

  643.       err = linux_attach_lwp (ptid);

  644.       /* Be quiet if we simply raced with the thread exiting.  EPERM
  645.          is returned if the thread's task still exists, and is marked
  646.          as exited or zombie, as well as other conditions, so in that
  647.          case, confirm the status in /proc/PID/status.  */
  648.       if (err == ESRCH
  649.           || (err == EPERM && linux_proc_pid_is_gone (lwpid)))
  650.         {
  651.           if (debug_threads)
  652.             {
  653.               debug_printf ("Cannot attach to lwp %d: "
  654.                             "thread is gone (%d: %s)\n",
  655.                             lwpid, err, strerror (err));
  656.             }
  657.         }
  658.       else if (err != 0)
  659.         {
  660.           warning (_("Cannot attach to lwp %d: %s"),
  661.                    lwpid,
  662.                    linux_ptrace_attach_fail_reason_string (ptid, err));
  663.         }

  664.       return 1;
  665.     }
  666.   return 0;
  667. }

  668. /* Attach to PID.  If PID is the tgid, attach to it and all
  669.    of its threads.  */

  670. static int
  671. linux_attach (unsigned long pid)
  672. {
  673.   ptid_t ptid = ptid_build (pid, pid, 0);
  674.   int err;

  675.   /* Attach to PID.  We will check for other threads
  676.      soon.  */
  677.   err = linux_attach_lwp (ptid);
  678.   if (err != 0)
  679.     error ("Cannot attach to process %ld: %s",
  680.            pid, linux_ptrace_attach_fail_reason_string (ptid, err));

  681.   linux_add_process (pid, 1);

  682.   if (!non_stop)
  683.     {
  684.       struct thread_info *thread;

  685.      /* Don't ignore the initial SIGSTOP if we just attached to this
  686.         process.  It will be collected by wait shortly.  */
  687.       thread = find_thread_ptid (ptid_build (pid, pid, 0));
  688.       thread->last_resume_kind = resume_stop;
  689.     }

  690.   /* We must attach to every LWP.  If /proc is mounted, use that to
  691.      find them now.  On the one hand, the inferior may be using raw
  692.      clone instead of using pthreads.  On the other hand, even if it
  693.      is using pthreads, GDB may not be connected yet (thread_db needs
  694.      to do symbol lookups, through qSymbol).  Also, thread_db walks
  695.      structures in the inferior's address space to find the list of
  696.      threads/LWPs, and those structures may well be corrupted.  Note
  697.      that once thread_db is loaded, we'll still use it to list threads
  698.      and associate pthread info with each LWP.  */
  699.   linux_proc_attach_tgid_threads (pid, attach_proc_task_lwp_callback);
  700.   return 0;
  701. }

  702. struct counter
  703. {
  704.   int pid;
  705.   int count;
  706. };

  707. static int
  708. second_thread_of_pid_p (struct inferior_list_entry *entry, void *args)
  709. {
  710.   struct counter *counter = args;

  711.   if (ptid_get_pid (entry->id) == counter->pid)
  712.     {
  713.       if (++counter->count > 1)
  714.         return 1;
  715.     }

  716.   return 0;
  717. }

  718. static int
  719. last_thread_of_process_p (int pid)
  720. {
  721.   struct counter counter = { pid , 0 };

  722.   return (find_inferior (&all_threads,
  723.                          second_thread_of_pid_p, &counter) == NULL);
  724. }

  725. /* Kill LWP.  */

  726. static void
  727. linux_kill_one_lwp (struct lwp_info *lwp)
  728. {
  729.   struct thread_info *thr = get_lwp_thread (lwp);
  730.   int pid = lwpid_of (thr);

  731.   /* PTRACE_KILL is unreliable.  After stepping into a signal handler,
  732.      there is no signal context, and ptrace(PTRACE_KILL) (or
  733.      ptrace(PTRACE_CONT, SIGKILL), pretty much the same) acts like
  734.      ptrace(CONT, pid, 0,0) and just resumes the tracee.  A better
  735.      alternative is to kill with SIGKILL.  We only need one SIGKILL
  736.      per process, not one for each thread.  But since we still support
  737.      linuxthreads, and we also support debugging programs using raw
  738.      clone without CLONE_THREAD, we send one for each thread.  For
  739.      years, we used PTRACE_KILL only, so we're being a bit paranoid
  740.      about some old kernels where PTRACE_KILL might work better
  741.      (dubious if there are any such, but that's why it's paranoia), so
  742.      we try SIGKILL first, PTRACE_KILL second, and so we're fine
  743.      everywhere.  */

  744.   errno = 0;
  745.   kill_lwp (pid, SIGKILL);
  746.   if (debug_threads)
  747.     {
  748.       int save_errno = errno;

  749.       debug_printf ("LKL:  kill_lwp (SIGKILL) %s, 0, 0 (%s)\n",
  750.                     target_pid_to_str (ptid_of (thr)),
  751.                     save_errno ? strerror (save_errno) : "OK");
  752.     }

  753.   errno = 0;
  754.   ptrace (PTRACE_KILL, pid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
  755.   if (debug_threads)
  756.     {
  757.       int save_errno = errno;

  758.       debug_printf ("LKL:  PTRACE_KILL %s, 0, 0 (%s)\n",
  759.                     target_pid_to_str (ptid_of (thr)),
  760.                     save_errno ? strerror (save_errno) : "OK");
  761.     }
  762. }

  763. /* Kill LWP and wait for it to die.  */

  764. static void
  765. kill_wait_lwp (struct lwp_info *lwp)
  766. {
  767.   struct thread_info *thr = get_lwp_thread (lwp);
  768.   int pid = ptid_get_pid (ptid_of (thr));
  769.   int lwpid = ptid_get_lwp (ptid_of (thr));
  770.   int wstat;
  771.   int res;

  772.   if (debug_threads)
  773.     debug_printf ("kwl: killing lwp %d, for pid: %d\n", lwpid, pid);

  774.   do
  775.     {
  776.       linux_kill_one_lwp (lwp);

  777.       /* Make sure it died.  Notes:

  778.          - The loop is most likely unnecessary.

  779.          - We don't use linux_wait_for_event as that could delete lwps
  780.            while we're iterating over them.  We're not interested in
  781.            any pending status at this point, only in making sure all
  782.            wait status on the kernel side are collected until the
  783.            process is reaped.

  784.          - We don't use __WALL here as the __WALL emulation relies on
  785.            SIGCHLD, and killing a stopped process doesn't generate
  786.            one, nor an exit status.
  787.       */
  788.       res = my_waitpid (lwpid, &wstat, 0);
  789.       if (res == -1 && errno == ECHILD)
  790.         res = my_waitpid (lwpid, &wstat, __WCLONE);
  791.     } while (res > 0 && WIFSTOPPED (wstat));

  792.   gdb_assert (res > 0);
  793. }

  794. /* Callback for `find_inferior'.  Kills an lwp of a given process,
  795.    except the leader.  */

  796. static int
  797. kill_one_lwp_callback (struct inferior_list_entry *entry, void *args)
  798. {
  799.   struct thread_info *thread = (struct thread_info *) entry;
  800.   struct lwp_info *lwp = get_thread_lwp (thread);
  801.   int pid = * (int *) args;

  802.   if (ptid_get_pid (entry->id) != pid)
  803.     return 0;

  804.   /* We avoid killing the first thread here, because of a Linux kernel (at
  805.      least 2.6.0-test7 through 2.6.8-rc4) bug; if we kill the parent before
  806.      the children get a chance to be reaped, it will remain a zombie
  807.      forever.  */

  808.   if (lwpid_of (thread) == pid)
  809.     {
  810.       if (debug_threads)
  811.         debug_printf ("lkop: is last of process %s\n",
  812.                       target_pid_to_str (entry->id));
  813.       return 0;
  814.     }

  815.   kill_wait_lwp (lwp);
  816.   return 0;
  817. }

  818. static int
  819. linux_kill (int pid)
  820. {
  821.   struct process_info *process;
  822.   struct lwp_info *lwp;

  823.   process = find_process_pid (pid);
  824.   if (process == NULL)
  825.     return -1;

  826.   /* If we're killing a running inferior, make sure it is stopped
  827.      first, as PTRACE_KILL will not work otherwise.  */
  828.   stop_all_lwps (0, NULL);

  829.   find_inferior (&all_threads, kill_one_lwp_callback , &pid);

  830.   /* See the comment in linux_kill_one_lwp.  We did not kill the first
  831.      thread in the list, so do so now.  */
  832.   lwp = find_lwp_pid (pid_to_ptid (pid));

  833.   if (lwp == NULL)
  834.     {
  835.       if (debug_threads)
  836.         debug_printf ("lk_1: cannot find lwp for pid: %d\n",
  837.                       pid);
  838.     }
  839.   else
  840.     kill_wait_lwp (lwp);

  841.   the_target->mourn (process);

  842.   /* Since we presently can only stop all lwps of all processes, we
  843.      need to unstop lwps of other processes.  */
  844.   unstop_all_lwps (0, NULL);
  845.   return 0;
  846. }

  847. /* Get pending signal of THREAD, for detaching purposes.  This is the
  848.    signal the thread last stopped for, which we need to deliver to the
  849.    thread when detaching, otherwise, it'd be suppressed/lost.  */

  850. static int
  851. get_detach_signal (struct thread_info *thread)
  852. {
  853.   enum gdb_signal signo = GDB_SIGNAL_0;
  854.   int status;
  855.   struct lwp_info *lp = get_thread_lwp (thread);

  856.   if (lp->status_pending_p)
  857.     status = lp->status_pending;
  858.   else
  859.     {
  860.       /* If the thread had been suspended by gdbserver, and it stopped
  861.          cleanly, then it'll have stopped with SIGSTOP.  But we don't
  862.          want to deliver that SIGSTOP.  */
  863.       if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
  864.           || thread->last_status.value.sig == GDB_SIGNAL_0)
  865.         return 0;

  866.       /* Otherwise, we may need to deliver the signal we
  867.          intercepted.  */
  868.       status = lp->last_status;
  869.     }

  870.   if (!WIFSTOPPED (status))
  871.     {
  872.       if (debug_threads)
  873.         debug_printf ("GPS: lwp %s hasn't stopped: no pending signal\n",
  874.                       target_pid_to_str (ptid_of (thread)));
  875.       return 0;
  876.     }

  877.   /* Extended wait statuses aren't real SIGTRAPs.  */
  878.   if (WSTOPSIG (status) == SIGTRAP && linux_is_extended_waitstatus (status))
  879.     {
  880.       if (debug_threads)
  881.         debug_printf ("GPS: lwp %s had stopped with extended "
  882.                       "status: no pending signal\n",
  883.                       target_pid_to_str (ptid_of (thread)));
  884.       return 0;
  885.     }

  886.   signo = gdb_signal_from_host (WSTOPSIG (status));

  887.   if (program_signals_p && !program_signals[signo])
  888.     {
  889.       if (debug_threads)
  890.         debug_printf ("GPS: lwp %s had signal %s, but it is in nopass state\n",
  891.                       target_pid_to_str (ptid_of (thread)),
  892.                       gdb_signal_to_string (signo));
  893.       return 0;
  894.     }
  895.   else if (!program_signals_p
  896.            /* If we have no way to know which signals GDB does not
  897.               want to have passed to the program, assume
  898.               SIGTRAP/SIGINT, which is GDB's default.  */
  899.            && (signo == GDB_SIGNAL_TRAP || signo == GDB_SIGNAL_INT))
  900.     {
  901.       if (debug_threads)
  902.         debug_printf ("GPS: lwp %s had signal %s, "
  903.                       "but we don't know if we should pass it. "
  904.                       "Default to not.\n",
  905.                       target_pid_to_str (ptid_of (thread)),
  906.                       gdb_signal_to_string (signo));
  907.       return 0;
  908.     }
  909.   else
  910.     {
  911.       if (debug_threads)
  912.         debug_printf ("GPS: lwp %s has pending signal %s: delivering it.\n",
  913.                       target_pid_to_str (ptid_of (thread)),
  914.                       gdb_signal_to_string (signo));

  915.       return WSTOPSIG (status);
  916.     }
  917. }

  918. static int
  919. linux_detach_one_lwp (struct inferior_list_entry *entry, void *args)
  920. {
  921.   struct thread_info *thread = (struct thread_info *) entry;
  922.   struct lwp_info *lwp = get_thread_lwp (thread);
  923.   int pid = * (int *) args;
  924.   int sig;

  925.   if (ptid_get_pid (entry->id) != pid)
  926.     return 0;

  927.   /* If there is a pending SIGSTOP, get rid of it.  */
  928.   if (lwp->stop_expected)
  929.     {
  930.       if (debug_threads)
  931.         debug_printf ("Sending SIGCONT to %s\n",
  932.                       target_pid_to_str (ptid_of (thread)));

  933.       kill_lwp (lwpid_of (thread), SIGCONT);
  934.       lwp->stop_expected = 0;
  935.     }

  936.   /* Flush any pending changes to the process's registers.  */
  937.   regcache_invalidate_thread (thread);

  938.   /* Pass on any pending signal for this thread.  */
  939.   sig = get_detach_signal (thread);

  940.   /* Finally, let it resume.  */
  941.   if (the_low_target.prepare_to_resume != NULL)
  942.     the_low_target.prepare_to_resume (lwp);
  943.   if (ptrace (PTRACE_DETACH, lwpid_of (thread), (PTRACE_TYPE_ARG3) 0,
  944.               (PTRACE_TYPE_ARG4) (long) sig) < 0)
  945.     error (_("Can't detach %s: %s"),
  946.            target_pid_to_str (ptid_of (thread)),
  947.            strerror (errno));

  948.   delete_lwp (lwp);
  949.   return 0;
  950. }

  951. static int
  952. linux_detach (int pid)
  953. {
  954.   struct process_info *process;

  955.   process = find_process_pid (pid);
  956.   if (process == NULL)
  957.     return -1;

  958.   /* Stop all threads before detaching.  First, ptrace requires that
  959.      the thread is stopped to sucessfully detach.  Second, thread_db
  960.      may need to uninstall thread event breakpoints from memory, which
  961.      only works with a stopped process anyway.  */
  962.   stop_all_lwps (0, NULL);

  963. #ifdef USE_THREAD_DB
  964.   thread_db_detach (process);
  965. #endif

  966.   /* Stabilize threads (move out of jump pads).  */
  967.   stabilize_threads ();

  968.   find_inferior (&all_threads, linux_detach_one_lwp, &pid);

  969.   the_target->mourn (process);

  970.   /* Since we presently can only stop all lwps of all processes, we
  971.      need to unstop lwps of other processes.  */
  972.   unstop_all_lwps (0, NULL);
  973.   return 0;
  974. }

  975. /* Remove all LWPs that belong to process PROC from the lwp list.  */

  976. static int
  977. delete_lwp_callback (struct inferior_list_entry *entry, void *proc)
  978. {
  979.   struct thread_info *thread = (struct thread_info *) entry;
  980.   struct lwp_info *lwp = get_thread_lwp (thread);
  981.   struct process_info *process = proc;

  982.   if (pid_of (thread) == pid_of (process))
  983.     delete_lwp (lwp);

  984.   return 0;
  985. }

  986. static void
  987. linux_mourn (struct process_info *process)
  988. {
  989.   struct process_info_private *priv;

  990. #ifdef USE_THREAD_DB
  991.   thread_db_mourn (process);
  992. #endif

  993.   find_inferior (&all_threads, delete_lwp_callback, process);

  994.   /* Freeing all private data.  */
  995.   priv = process->private;
  996.   free (priv->arch_private);
  997.   free (priv);
  998.   process->private = NULL;

  999.   remove_process (process);
  1000. }

  1001. static void
  1002. linux_join (int pid)
  1003. {
  1004.   int status, ret;

  1005.   do {
  1006.     ret = my_waitpid (pid, &status, 0);
  1007.     if (WIFEXITED (status) || WIFSIGNALED (status))
  1008.       break;
  1009.   } while (ret != -1 || errno != ECHILD);
  1010. }

  1011. /* Return nonzero if the given thread is still alive.  */
  1012. static int
  1013. linux_thread_alive (ptid_t ptid)
  1014. {
  1015.   struct lwp_info *lwp = find_lwp_pid (ptid);

  1016.   /* We assume we always know if a thread exits.  If a whole process
  1017.      exited but we still haven't been able to report it to GDB, we'll
  1018.      hold on to the last lwp of the dead process.  */
  1019.   if (lwp != NULL)
  1020.     return !lwp->dead;
  1021.   else
  1022.     return 0;
  1023. }

  1024. /* Return 1 if this lwp still has an interesting status pending.  If
  1025.    not (e.g., it had stopped for a breakpoint that is gone), return
  1026.    false.  */

  1027. static int
  1028. thread_still_has_status_pending_p (struct thread_info *thread)
  1029. {
  1030.   struct lwp_info *lp = get_thread_lwp (thread);

  1031.   if (!lp->status_pending_p)
  1032.     return 0;

  1033.   /* If we got a `vCont;t', but we haven't reported a stop yet, do
  1034.      report any status pending the LWP may have.  */
  1035.   if (thread->last_resume_kind == resume_stop
  1036.       && thread->last_status.kind != TARGET_WAITKIND_IGNORE)
  1037.     return 0;

  1038.   if (thread->last_resume_kind != resume_stop
  1039.       && (lp->stop_reason == LWP_STOPPED_BY_SW_BREAKPOINT
  1040.           || lp->stop_reason == LWP_STOPPED_BY_HW_BREAKPOINT))
  1041.     {
  1042.       struct thread_info *saved_thread;
  1043.       CORE_ADDR pc;
  1044.       int discard = 0;

  1045.       gdb_assert (lp->last_status != 0);

  1046.       pc = get_pc (lp);

  1047.       saved_thread = current_thread;
  1048.       current_thread = thread;

  1049.       if (pc != lp->stop_pc)
  1050.         {
  1051.           if (debug_threads)
  1052.             debug_printf ("PC of %ld changed\n",
  1053.                           lwpid_of (thread));
  1054.           discard = 1;
  1055.         }
  1056.       else if (lp->stop_reason == LWP_STOPPED_BY_SW_BREAKPOINT
  1057.                && !(*the_low_target.breakpoint_at) (pc))
  1058.         {
  1059.           if (debug_threads)
  1060.             debug_printf ("previous SW breakpoint of %ld gone\n",
  1061.                           lwpid_of (thread));
  1062.           discard = 1;
  1063.         }
  1064.       else if (lp->stop_reason == LWP_STOPPED_BY_HW_BREAKPOINT
  1065.                && !hardware_breakpoint_inserted_here (pc))
  1066.         {
  1067.           if (debug_threads)
  1068.             debug_printf ("previous HW breakpoint of %ld gone\n",
  1069.                           lwpid_of (thread));
  1070.           discard = 1;
  1071.         }

  1072.       current_thread = saved_thread;

  1073.       if (discard)
  1074.         {
  1075.           if (debug_threads)
  1076.             debug_printf ("discarding pending breakpoint status\n");
  1077.           lp->status_pending_p = 0;
  1078.           return 0;
  1079.         }
  1080.     }

  1081.   return 1;
  1082. }

  1083. /* Return 1 if this lwp has an interesting status pending.  */
  1084. static int
  1085. status_pending_p_callback (struct inferior_list_entry *entry, void *arg)
  1086. {
  1087.   struct thread_info *thread = (struct thread_info *) entry;
  1088.   struct lwp_info *lp = get_thread_lwp (thread);
  1089.   ptid_t ptid = * (ptid_t *) arg;

  1090.   /* Check if we're only interested in events from a specific process
  1091.      or its lwps.  */
  1092.   if (!ptid_equal (minus_one_ptid, ptid)
  1093.       && ptid_get_pid (ptid) != ptid_get_pid (thread->entry.id))
  1094.     return 0;

  1095.   if (lp->status_pending_p
  1096.       && !thread_still_has_status_pending_p (thread))
  1097.     {
  1098.       linux_resume_one_lwp (lp, lp->stepping, GDB_SIGNAL_0, NULL);
  1099.       return 0;
  1100.     }

  1101.   return lp->status_pending_p;
  1102. }

  1103. static int
  1104. same_lwp (struct inferior_list_entry *entry, void *data)
  1105. {
  1106.   ptid_t ptid = *(ptid_t *) data;
  1107.   int lwp;

  1108.   if (ptid_get_lwp (ptid) != 0)
  1109.     lwp = ptid_get_lwp (ptid);
  1110.   else
  1111.     lwp = ptid_get_pid (ptid);

  1112.   if (ptid_get_lwp (entry->id) == lwp)
  1113.     return 1;

  1114.   return 0;
  1115. }

  1116. struct lwp_info *
  1117. find_lwp_pid (ptid_t ptid)
  1118. {
  1119.   struct inferior_list_entry *thread
  1120.     = find_inferior (&all_threads, same_lwp, &ptid);

  1121.   if (thread == NULL)
  1122.     return NULL;

  1123.   return get_thread_lwp ((struct thread_info *) thread);
  1124. }

  1125. /* Return the number of known LWPs in the tgid given by PID.  */

  1126. static int
  1127. num_lwps (int pid)
  1128. {
  1129.   struct inferior_list_entry *inf, *tmp;
  1130.   int count = 0;

  1131.   ALL_INFERIORS (&all_threads, inf, tmp)
  1132.     {
  1133.       if (ptid_get_pid (inf->id) == pid)
  1134.         count++;
  1135.     }

  1136.   return count;
  1137. }

  1138. /* Detect zombie thread group leaders, and "exit" them.  We can't reap
  1139.    their exits until all other threads in the group have exited.  */

  1140. static void
  1141. check_zombie_leaders (void)
  1142. {
  1143.   struct process_info *proc, *tmp;

  1144.   ALL_PROCESSES (proc, tmp)
  1145.     {
  1146.       pid_t leader_pid = pid_of (proc);
  1147.       struct lwp_info *leader_lp;

  1148.       leader_lp = find_lwp_pid (pid_to_ptid (leader_pid));

  1149.       if (debug_threads)
  1150.         debug_printf ("leader_pid=%d, leader_lp!=NULL=%d, "
  1151.                       "num_lwps=%d, zombie=%d\n",
  1152.                       leader_pid, leader_lp!= NULL, num_lwps (leader_pid),
  1153.                       linux_proc_pid_is_zombie (leader_pid));

  1154.       if (leader_lp != NULL
  1155.           /* Check if there are other threads in the group, as we may
  1156.              have raced with the inferior simply exiting.  */
  1157.           && !last_thread_of_process_p (leader_pid)
  1158.           && linux_proc_pid_is_zombie (leader_pid))
  1159.         {
  1160.           /* A leader zombie can mean one of two things:

  1161.              - It exited, and there's an exit status pending
  1162.              available, or only the leader exited (not the whole
  1163.              program).  In the latter case, we can't waitpid the
  1164.              leader's exit status until all other threads are gone.

  1165.              - There are 3 or more threads in the group, and a thread
  1166.              other than the leader exec'd.  On an exec, the Linux
  1167.              kernel destroys all other threads (except the execing
  1168.              one) in the thread group, and resets the execing thread's
  1169.              tid to the tgid.  No exit notification is sent for the
  1170.              execing thread -- from the ptracer's perspective, it
  1171.              appears as though the execing thread just vanishes.
  1172.              Until we reap all other threads except the leader and the
  1173.              execing thread, the leader will be zombie, and the
  1174.              execing thread will be in `D (disc sleep)'.  As soon as
  1175.              all other threads are reaped, the execing thread changes
  1176.              it's tid to the tgid, and the previous (zombie) leader
  1177.              vanishes, giving place to the "new" leader.  We could try
  1178.              distinguishing the exit and exec cases, by waiting once
  1179.              more, and seeing if something comes out, but it doesn't
  1180.              sound useful.  The previous leader _does_ go away, and
  1181.              we'll re-add the new one once we see the exec event
  1182.              (which is just the same as what would happen if the
  1183.              previous leader did exit voluntarily before some other
  1184.              thread execs).  */

  1185.           if (debug_threads)
  1186.             fprintf (stderr,
  1187.                      "CZL: Thread group leader %d zombie "
  1188.                      "(it exited, or another thread execd).\n",
  1189.                      leader_pid);

  1190.           delete_lwp (leader_lp);
  1191.         }
  1192.     }
  1193. }

  1194. /* Callback for `find_inferior'.  Returns the first LWP that is not
  1195.    stopped.  ARG is a PTID filter.  */

  1196. static int
  1197. not_stopped_callback (struct inferior_list_entry *entry, void *arg)
  1198. {
  1199.   struct thread_info *thr = (struct thread_info *) entry;
  1200.   struct lwp_info *lwp;
  1201.   ptid_t filter = *(ptid_t *) arg;

  1202.   if (!ptid_match (ptid_of (thr), filter))
  1203.     return 0;

  1204.   lwp = get_thread_lwp (thr);
  1205.   if (!lwp->stopped)
  1206.     return 1;

  1207.   return 0;
  1208. }

  1209. /* This function should only be called if the LWP got a SIGTRAP.

  1210.    Handle any tracepoint steps or hits.  Return true if a tracepoint
  1211.    event was handled, 0 otherwise.  */

  1212. static int
  1213. handle_tracepoints (struct lwp_info *lwp)
  1214. {
  1215.   struct thread_info *tinfo = get_lwp_thread (lwp);
  1216.   int tpoint_related_event = 0;

  1217.   gdb_assert (lwp->suspended == 0);

  1218.   /* If this tracepoint hit causes a tracing stop, we'll immediately
  1219.      uninsert tracepoints.  To do this, we temporarily pause all
  1220.      threads, unpatch away, and then unpause threads.  We need to make
  1221.      sure the unpausing doesn't resume LWP too.  */
  1222.   lwp->suspended++;

  1223.   /* And we need to be sure that any all-threads-stopping doesn't try
  1224.      to move threads out of the jump pads, as it could deadlock the
  1225.      inferior (LWP could be in the jump pad, maybe even holding the
  1226.      lock.)  */

  1227.   /* Do any necessary step collect actions.  */
  1228.   tpoint_related_event |= tracepoint_finished_step (tinfo, lwp->stop_pc);

  1229.   tpoint_related_event |= handle_tracepoint_bkpts (tinfo, lwp->stop_pc);

  1230.   /* See if we just hit a tracepoint and do its main collect
  1231.      actions.  */
  1232.   tpoint_related_event |= tracepoint_was_hit (tinfo, lwp->stop_pc);

  1233.   lwp->suspended--;

  1234.   gdb_assert (lwp->suspended == 0);
  1235.   gdb_assert (!stabilizing_threads || lwp->collecting_fast_tracepoint);

  1236.   if (tpoint_related_event)
  1237.     {
  1238.       if (debug_threads)
  1239.         debug_printf ("got a tracepoint event\n");
  1240.       return 1;
  1241.     }

  1242.   return 0;
  1243. }

  1244. /* Convenience wrapper.  Returns true if LWP is presently collecting a
  1245.    fast tracepoint.  */

  1246. static int
  1247. linux_fast_tracepoint_collecting (struct lwp_info *lwp,
  1248.                                   struct fast_tpoint_collect_status *status)
  1249. {
  1250.   CORE_ADDR thread_area;
  1251.   struct thread_info *thread = get_lwp_thread (lwp);

  1252.   if (the_low_target.get_thread_area == NULL)
  1253.     return 0;

  1254.   /* Get the thread area address.  This is used to recognize which
  1255.      thread is which when tracing with the in-process agent library.
  1256.      We don't read anything from the address, and treat it as opaque;
  1257.      it's the address itself that we assume is unique per-thread.  */
  1258.   if ((*the_low_target.get_thread_area) (lwpid_of (thread), &thread_area) == -1)
  1259.     return 0;

  1260.   return fast_tracepoint_collecting (thread_area, lwp->stop_pc, status);
  1261. }

  1262. /* The reason we resume in the caller, is because we want to be able
  1263.    to pass lwp->status_pending as WSTAT, and we need to clear
  1264.    status_pending_p before resuming, otherwise, linux_resume_one_lwp
  1265.    refuses to resume.  */

  1266. static int
  1267. maybe_move_out_of_jump_pad (struct lwp_info *lwp, int *wstat)
  1268. {
  1269.   struct thread_info *saved_thread;

  1270.   saved_thread = current_thread;
  1271.   current_thread = get_lwp_thread (lwp);

  1272.   if ((wstat == NULL
  1273.        || (WIFSTOPPED (*wstat) && WSTOPSIG (*wstat) != SIGTRAP))
  1274.       && supports_fast_tracepoints ()
  1275.       && agent_loaded_p ())
  1276.     {
  1277.       struct fast_tpoint_collect_status status;
  1278.       int r;

  1279.       if (debug_threads)
  1280.         debug_printf ("Checking whether LWP %ld needs to move out of the "
  1281.                       "jump pad.\n",
  1282.                       lwpid_of (current_thread));

  1283.       r = linux_fast_tracepoint_collecting (lwp, &status);

  1284.       if (wstat == NULL
  1285.           || (WSTOPSIG (*wstat) != SIGILL
  1286.               && WSTOPSIG (*wstat) != SIGFPE
  1287.               && WSTOPSIG (*wstat) != SIGSEGV
  1288.               && WSTOPSIG (*wstat) != SIGBUS))
  1289.         {
  1290.           lwp->collecting_fast_tracepoint = r;

  1291.           if (r != 0)
  1292.             {
  1293.               if (r == 1 && lwp->exit_jump_pad_bkpt == NULL)
  1294.                 {
  1295.                   /* Haven't executed the original instruction yet.
  1296.                      Set breakpoint there, and wait till it's hit,
  1297.                      then single-step until exiting the jump pad.  */
  1298.                   lwp->exit_jump_pad_bkpt
  1299.                     = set_breakpoint_at (status.adjusted_insn_addr, NULL);
  1300.                 }

  1301.               if (debug_threads)
  1302.                 debug_printf ("Checking whether LWP %ld needs to move out of "
  1303.                               "the jump pad...it does\n",
  1304.                               lwpid_of (current_thread));
  1305.               current_thread = saved_thread;

  1306.               return 1;
  1307.             }
  1308.         }
  1309.       else
  1310.         {
  1311.           /* If we get a synchronous signal while collecting, *and*
  1312.              while executing the (relocated) original instruction,
  1313.              reset the PC to point at the tpoint address, before
  1314.              reporting to GDB.  Otherwise, it's an IPA lib bug: just
  1315.              report the signal to GDB, and pray for the best.  */

  1316.           lwp->collecting_fast_tracepoint = 0;

  1317.           if (r != 0
  1318.               && (status.adjusted_insn_addr <= lwp->stop_pc
  1319.                   && lwp->stop_pc < status.adjusted_insn_addr_end))
  1320.             {
  1321.               siginfo_t info;
  1322.               struct regcache *regcache;

  1323.               /* The si_addr on a few signals references the address
  1324.                  of the faulting instruction.  Adjust that as
  1325.                  well.  */
  1326.               if ((WSTOPSIG (*wstat) == SIGILL
  1327.                    || WSTOPSIG (*wstat) == SIGFPE
  1328.                    || WSTOPSIG (*wstat) == SIGBUS
  1329.                    || WSTOPSIG (*wstat) == SIGSEGV)
  1330.                   && ptrace (PTRACE_GETSIGINFO, lwpid_of (current_thread),
  1331.                              (PTRACE_TYPE_ARG3) 0, &info) == 0
  1332.                   /* Final check just to make sure we don't clobber
  1333.                      the siginfo of non-kernel-sent signals.  */
  1334.                   && (uintptr_t) info.si_addr == lwp->stop_pc)
  1335.                 {
  1336.                   info.si_addr = (void *) (uintptr_t) status.tpoint_addr;
  1337.                   ptrace (PTRACE_SETSIGINFO, lwpid_of (current_thread),
  1338.                           (PTRACE_TYPE_ARG3) 0, &info);
  1339.                 }

  1340.               regcache = get_thread_regcache (current_thread, 1);
  1341.               (*the_low_target.set_pc) (regcache, status.tpoint_addr);
  1342.               lwp->stop_pc = status.tpoint_addr;

  1343.               /* Cancel any fast tracepoint lock this thread was
  1344.                  holding.  */
  1345.               force_unlock_trace_buffer ();
  1346.             }

  1347.           if (lwp->exit_jump_pad_bkpt != NULL)
  1348.             {
  1349.               if (debug_threads)
  1350.                 debug_printf ("Cancelling fast exit-jump-pad: removing bkpt. "
  1351.                               "stopping all threads momentarily.\n");

  1352.               stop_all_lwps (1, lwp);

  1353.               delete_breakpoint (lwp->exit_jump_pad_bkpt);
  1354.               lwp->exit_jump_pad_bkpt = NULL;

  1355.               unstop_all_lwps (1, lwp);

  1356.               gdb_assert (lwp->suspended >= 0);
  1357.             }
  1358.         }
  1359.     }

  1360.   if (debug_threads)
  1361.     debug_printf ("Checking whether LWP %ld needs to move out of the "
  1362.                   "jump pad...no\n",
  1363.                   lwpid_of (current_thread));

  1364.   current_thread = saved_thread;
  1365.   return 0;
  1366. }

  1367. /* Enqueue one signal in the "signals to report later when out of the
  1368.    jump pad" list.  */

  1369. static void
  1370. enqueue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
  1371. {
  1372.   struct pending_signals *p_sig;
  1373.   struct thread_info *thread = get_lwp_thread (lwp);

  1374.   if (debug_threads)
  1375.     debug_printf ("Deferring signal %d for LWP %ld.\n",
  1376.                   WSTOPSIG (*wstat), lwpid_of (thread));

  1377.   if (debug_threads)
  1378.     {
  1379.       struct pending_signals *sig;

  1380.       for (sig = lwp->pending_signals_to_report;
  1381.            sig != NULL;
  1382.            sig = sig->prev)
  1383.         debug_printf ("   Already queued %d\n",
  1384.                       sig->signal);

  1385.       debug_printf ("   (no more currently queued signals)\n");
  1386.     }

  1387.   /* Don't enqueue non-RT signals if they are already in the deferred
  1388.      queue.  (SIGSTOP being the easiest signal to see ending up here
  1389.      twice)  */
  1390.   if (WSTOPSIG (*wstat) < __SIGRTMIN)
  1391.     {
  1392.       struct pending_signals *sig;

  1393.       for (sig = lwp->pending_signals_to_report;
  1394.            sig != NULL;
  1395.            sig = sig->prev)
  1396.         {
  1397.           if (sig->signal == WSTOPSIG (*wstat))
  1398.             {
  1399.               if (debug_threads)
  1400.                 debug_printf ("Not requeuing already queued non-RT signal %d"
  1401.                               " for LWP %ld\n",
  1402.                               sig->signal,
  1403.                               lwpid_of (thread));
  1404.               return;
  1405.             }
  1406.         }
  1407.     }

  1408.   p_sig = xmalloc (sizeof (*p_sig));
  1409.   p_sig->prev = lwp->pending_signals_to_report;
  1410.   p_sig->signal = WSTOPSIG (*wstat);
  1411.   memset (&p_sig->info, 0, sizeof (siginfo_t));
  1412.   ptrace (PTRACE_GETSIGINFO, lwpid_of (thread), (PTRACE_TYPE_ARG3) 0,
  1413.           &p_sig->info);

  1414.   lwp->pending_signals_to_report = p_sig;
  1415. }

  1416. /* Dequeue one signal from the "signals to report later when out of
  1417.    the jump pad" list.  */

  1418. static int
  1419. dequeue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
  1420. {
  1421.   struct thread_info *thread = get_lwp_thread (lwp);

  1422.   if (lwp->pending_signals_to_report != NULL)
  1423.     {
  1424.       struct pending_signals **p_sig;

  1425.       p_sig = &lwp->pending_signals_to_report;
  1426.       while ((*p_sig)->prev != NULL)
  1427.         p_sig = &(*p_sig)->prev;

  1428.       *wstat = W_STOPCODE ((*p_sig)->signal);
  1429.       if ((*p_sig)->info.si_signo != 0)
  1430.         ptrace (PTRACE_SETSIGINFO, lwpid_of (thread), (PTRACE_TYPE_ARG3) 0,
  1431.                 &(*p_sig)->info);
  1432.       free (*p_sig);
  1433.       *p_sig = NULL;

  1434.       if (debug_threads)
  1435.         debug_printf ("Reporting deferred signal %d for LWP %ld.\n",
  1436.                       WSTOPSIG (*wstat), lwpid_of (thread));

  1437.       if (debug_threads)
  1438.         {
  1439.           struct pending_signals *sig;

  1440.           for (sig = lwp->pending_signals_to_report;
  1441.                sig != NULL;
  1442.                sig = sig->prev)
  1443.             debug_printf ("   Still queued %d\n",
  1444.                           sig->signal);

  1445.           debug_printf ("   (no more queued signals)\n");
  1446.         }

  1447.       return 1;
  1448.     }

  1449.   return 0;
  1450. }

  1451. /* Return true if the event in LP may be caused by breakpoint.  */

  1452. static int
  1453. wstatus_maybe_breakpoint (int wstatus)
  1454. {
  1455.   return (WIFSTOPPED (wstatus)
  1456.           && (WSTOPSIG (wstatus) == SIGTRAP
  1457.               /* SIGILL and SIGSEGV are also treated as traps in case a
  1458.                  breakpoint is inserted at the current PC.  */
  1459.               || WSTOPSIG (wstatus) == SIGILL
  1460.               || WSTOPSIG (wstatus) == SIGSEGV));
  1461. }

  1462. /* Fetch the possibly triggered data watchpoint info and store it in
  1463.    CHILD.

  1464.    On some archs, like x86, that use debug registers to set
  1465.    watchpoints, it's possible that the way to know which watched
  1466.    address trapped, is to check the register that is used to select
  1467.    which address to watch.  Problem is, between setting the watchpoint
  1468.    and reading back which data address trapped, the user may change
  1469.    the set of watchpoints, and, as a consequence, GDB changes the
  1470.    debug registers in the inferior.  To avoid reading back a stale
  1471.    stopped-data-address when that happens, we cache in LP the fact
  1472.    that a watchpoint trapped, and the corresponding data address, as
  1473.    soon as we see CHILD stop with a SIGTRAP.  If GDB changes the debug
  1474.    registers meanwhile, we have the cached data we can rely on.  */

  1475. static int
  1476. check_stopped_by_watchpoint (struct lwp_info *child)
  1477. {
  1478.   if (the_low_target.stopped_by_watchpoint != NULL)
  1479.     {
  1480.       struct thread_info *saved_thread;

  1481.       saved_thread = current_thread;
  1482.       current_thread = get_lwp_thread (child);

  1483.       if (the_low_target.stopped_by_watchpoint ())
  1484.         {
  1485.           child->stop_reason = LWP_STOPPED_BY_WATCHPOINT;

  1486.           if (the_low_target.stopped_data_address != NULL)
  1487.             child->stopped_data_address
  1488.               = the_low_target.stopped_data_address ();
  1489.           else
  1490.             child->stopped_data_address = 0;
  1491.         }

  1492.       current_thread = saved_thread;
  1493.     }

  1494.   return child->stop_reason == LWP_STOPPED_BY_WATCHPOINT;
  1495. }

  1496. /* Do low-level handling of the event, and check if we should go on
  1497.    and pass it to caller code.  Return the affected lwp if we are, or
  1498.    NULL otherwise.  */

  1499. static struct lwp_info *
  1500. linux_low_filter_event (int lwpid, int wstat)
  1501. {
  1502.   struct lwp_info *child;
  1503.   struct thread_info *thread;
  1504.   int have_stop_pc = 0;

  1505.   child = find_lwp_pid (pid_to_ptid (lwpid));

  1506.   /* If we didn't find a process, one of two things presumably happened:
  1507.      - A process we started and then detached from has exited.  Ignore it.
  1508.      - A process we are controlling has forked and the new child's stop
  1509.      was reported to us by the kernel.  Save its PID.  */
  1510.   if (child == NULL && WIFSTOPPED (wstat))
  1511.     {
  1512.       add_to_pid_list (&stopped_pids, lwpid, wstat);
  1513.       return NULL;
  1514.     }
  1515.   else if (child == NULL)
  1516.     return NULL;

  1517.   thread = get_lwp_thread (child);

  1518.   child->stopped = 1;

  1519.   child->last_status = wstat;

  1520.   /* Check if the thread has exited.  */
  1521.   if ((WIFEXITED (wstat) || WIFSIGNALED (wstat)))
  1522.     {
  1523.       if (debug_threads)
  1524.         debug_printf ("LLFE: %d exited.\n", lwpid);
  1525.       if (num_lwps (pid_of (thread)) > 1)
  1526.         {

  1527.           /* If there is at least one more LWP, then the exit signal was
  1528.              not the end of the debugged application and should be
  1529.              ignored.  */
  1530.           delete_lwp (child);
  1531.           return NULL;
  1532.         }
  1533.       else
  1534.         {
  1535.           /* This was the last lwp in the process.  Since events are
  1536.              serialized to GDB core, and we can't report this one
  1537.              right now, but GDB core and the other target layers will
  1538.              want to be notified about the exit code/signal, leave the
  1539.              status pending for the next time we're able to report
  1540.              it.  */
  1541.           mark_lwp_dead (child, wstat);
  1542.           return child;
  1543.         }
  1544.     }

  1545.   gdb_assert (WIFSTOPPED (wstat));

  1546.   if (WIFSTOPPED (wstat))
  1547.     {
  1548.       struct process_info *proc;

  1549.       /* Architecture-specific setup after inferior is running.  This
  1550.          needs to happen after we have attached to the inferior and it
  1551.          is stopped for the first time, but before we access any
  1552.          inferior registers.  */
  1553.       proc = find_process_pid (pid_of (thread));
  1554.       if (proc->private->new_inferior)
  1555.         {
  1556.           struct thread_info *saved_thread;

  1557.           saved_thread = current_thread;
  1558.           current_thread = thread;

  1559.           the_low_target.arch_setup ();

  1560.           current_thread = saved_thread;

  1561.           proc->private->new_inferior = 0;
  1562.         }
  1563.     }

  1564.   if (WIFSTOPPED (wstat) && child->must_set_ptrace_flags)
  1565.     {
  1566.       struct process_info *proc = find_process_pid (pid_of (thread));

  1567.       linux_enable_event_reporting (lwpid, proc->attached);
  1568.       child->must_set_ptrace_flags = 0;
  1569.     }

  1570.   /* Be careful to not overwrite stop_pc until
  1571.      check_stopped_by_breakpoint is called.  */
  1572.   if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGTRAP
  1573.       && linux_is_extended_waitstatus (wstat))
  1574.     {
  1575.       child->stop_pc = get_pc (child);
  1576.       handle_extended_wait (child, wstat);
  1577.       return NULL;
  1578.     }

  1579.   if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGTRAP
  1580.       && check_stopped_by_watchpoint (child))
  1581.     ;
  1582.   else if (WIFSTOPPED (wstat) && wstatus_maybe_breakpoint (wstat))
  1583.     {
  1584.       if (check_stopped_by_breakpoint (child))
  1585.         have_stop_pc = 1;
  1586.     }

  1587.   if (!have_stop_pc)
  1588.     child->stop_pc = get_pc (child);

  1589.   if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGSTOP
  1590.       && child->stop_expected)
  1591.     {
  1592.       if (debug_threads)
  1593.         debug_printf ("Expected stop.\n");
  1594.       child->stop_expected = 0;

  1595.       if (thread->last_resume_kind == resume_stop)
  1596.         {
  1597.           /* We want to report the stop to the core.  Treat the
  1598.              SIGSTOP as a normal event.  */
  1599.         }
  1600.       else if (stopping_threads != NOT_STOPPING_THREADS)
  1601.         {
  1602.           /* Stopping threads.  We don't want this SIGSTOP to end up
  1603.              pending.  */
  1604.           return NULL;
  1605.         }
  1606.       else
  1607.         {
  1608.           /* Filter out the event.  */
  1609.           linux_resume_one_lwp (child, child->stepping, 0, NULL);
  1610.           return NULL;
  1611.         }
  1612.     }

  1613.   child->status_pending_p = 1;
  1614.   child->status_pending = wstat;
  1615.   return child;
  1616. }

  1617. /* Wait for an event from child(ren) WAIT_PTID, and return any that
  1618.    match FILTER_PTID (leaving others pending).  The PTIDs can be:
  1619.    minus_one_ptid, to specify any child; a pid PTID, specifying all
  1620.    lwps of a thread group; or a PTID representing a single lwp.  Store
  1621.    the stop status through the status pointer WSTAT.  OPTIONS is
  1622.    passed to the waitpid call.  Return 0 if no event was found and
  1623.    OPTIONS contains WNOHANG.  Return -1 if no unwaited-for children
  1624.    was found.  Return the PID of the stopped child otherwise.  */

  1625. static int
  1626. linux_wait_for_event_filtered (ptid_t wait_ptid, ptid_t filter_ptid,
  1627.                                int *wstatp, int options)
  1628. {
  1629.   struct thread_info *event_thread;
  1630.   struct lwp_info *event_child, *requested_child;
  1631.   sigset_t block_mask, prev_mask;

  1632. retry:
  1633.   /* N.B. event_thread points to the thread_info struct that contains
  1634.      event_child.  Keep them in sync.  */
  1635.   event_thread = NULL;
  1636.   event_child = NULL;
  1637.   requested_child = NULL;

  1638.   /* Check for a lwp with a pending status.  */

  1639.   if (ptid_equal (filter_ptid, minus_one_ptid) || ptid_is_pid (filter_ptid))
  1640.     {
  1641.       event_thread = (struct thread_info *)
  1642.         find_inferior (&all_threads, status_pending_p_callback, &filter_ptid);
  1643.       if (event_thread != NULL)
  1644.         event_child = get_thread_lwp (event_thread);
  1645.       if (debug_threads && event_thread)
  1646.         debug_printf ("Got a pending child %ld\n", lwpid_of (event_thread));
  1647.     }
  1648.   else if (!ptid_equal (filter_ptid, null_ptid))
  1649.     {
  1650.       requested_child = find_lwp_pid (filter_ptid);

  1651.       if (stopping_threads == NOT_STOPPING_THREADS
  1652.           && requested_child->status_pending_p
  1653.           && requested_child->collecting_fast_tracepoint)
  1654.         {
  1655.           enqueue_one_deferred_signal (requested_child,
  1656.                                        &requested_child->status_pending);
  1657.           requested_child->status_pending_p = 0;
  1658.           requested_child->status_pending = 0;
  1659.           linux_resume_one_lwp (requested_child, 0, 0, NULL);
  1660.         }

  1661.       if (requested_child->suspended
  1662.           && requested_child->status_pending_p)
  1663.         {
  1664.           internal_error (__FILE__, __LINE__,
  1665.                           "requesting an event out of a"
  1666.                           " suspended child?");
  1667.         }

  1668.       if (requested_child->status_pending_p)
  1669.         {
  1670.           event_child = requested_child;
  1671.           event_thread = get_lwp_thread (event_child);
  1672.         }
  1673.     }

  1674.   if (event_child != NULL)
  1675.     {
  1676.       if (debug_threads)
  1677.         debug_printf ("Got an event from pending child %ld (%04x)\n",
  1678.                       lwpid_of (event_thread), event_child->status_pending);
  1679.       *wstatp = event_child->status_pending;
  1680.       event_child->status_pending_p = 0;
  1681.       event_child->status_pending = 0;
  1682.       current_thread = event_thread;
  1683.       return lwpid_of (event_thread);
  1684.     }

  1685.   /* But if we don't find a pending event, we'll have to wait.

  1686.      We only enter this loop if no process has a pending wait status.
  1687.      Thus any action taken in response to a wait status inside this
  1688.      loop is responding as soon as we detect the status, not after any
  1689.      pending events.  */

  1690.   /* Make sure SIGCHLD is blocked until the sigsuspend below.  Block
  1691.      all signals while here.  */
  1692.   sigfillset (&block_mask);
  1693.   sigprocmask (SIG_BLOCK, &block_mask, &prev_mask);

  1694.   /* Always pull all events out of the kernel.  We'll randomly select
  1695.      an event LWP out of all that have events, to prevent
  1696.      starvation.  */
  1697.   while (event_child == NULL)
  1698.     {
  1699.       pid_t ret = 0;

  1700.       /* Always use -1 and WNOHANG, due to couple of a kernel/ptrace
  1701.          quirks:

  1702.          - If the thread group leader exits while other threads in the
  1703.            thread group still exist, waitpid(TGID, ...) hangs.  That
  1704.            waitpid won't return an exit status until the other threads
  1705.            in the group are reaped.

  1706.          - When a non-leader thread execs, that thread just vanishes
  1707.            without reporting an exit (so we'd hang if we waited for it
  1708.            explicitly in that case).  The exec event is reported to
  1709.            the TGID pid (although we don't currently enable exec
  1710.            events).  */
  1711.       errno = 0;
  1712.       ret = my_waitpid (-1, wstatp, options | WNOHANG);

  1713.       if (debug_threads)
  1714.         debug_printf ("LWFE: waitpid(-1, ...) returned %d, %s\n",
  1715.                       ret, errno ? strerror (errno) : "ERRNO-OK");

  1716.       if (ret > 0)
  1717.         {
  1718.           if (debug_threads)
  1719.             {
  1720.               debug_printf ("LLW: waitpid %ld received %s\n",
  1721.                             (long) ret, status_to_str (*wstatp));
  1722.             }

  1723.           /* Filter all events.  IOW, leave all events pending.  We'll
  1724.              randomly select an event LWP out of all that have events
  1725.              below.  */
  1726.           linux_low_filter_event (ret, *wstatp);
  1727.           /* Retry until nothing comes out of waitpid.  A single
  1728.              SIGCHLD can indicate more than one child stopped.  */
  1729.           continue;
  1730.         }

  1731.       /* Now that we've pulled all events out of the kernel, check if
  1732.          there's any LWP with a status to report to the core.  */
  1733.       event_thread = (struct thread_info *)
  1734.         find_inferior (&all_threads, status_pending_p_callback, &filter_ptid);
  1735.       if (event_thread != NULL)
  1736.         {
  1737.           event_child = get_thread_lwp (event_thread);
  1738.           *wstatp = event_child->status_pending;
  1739.           event_child->status_pending_p = 0;
  1740.           event_child->status_pending = 0;
  1741.           break;
  1742.         }

  1743.       /* Check for zombie thread group leaders.  Those can't be reaped
  1744.          until all other threads in the thread group are.  */
  1745.       check_zombie_leaders ();

  1746.       /* If there are no resumed children left in the set of LWPs we
  1747.          want to wait for, bail.  We can't just block in
  1748.          waitpid/sigsuspend, because lwps might have been left stopped
  1749.          in trace-stop state, and we'd be stuck forever waiting for
  1750.          their status to change (which would only happen if we resumed
  1751.          them).  Even if WNOHANG is set, this return code is preferred
  1752.          over 0 (below), as it is more detailed.  */
  1753.       if ((find_inferior (&all_threads,
  1754.                           not_stopped_callback,
  1755.                           &wait_ptid) == NULL))
  1756.         {
  1757.           if (debug_threads)
  1758.             debug_printf ("LLW: exit (no unwaited-for LWP)\n");
  1759.           sigprocmask (SIG_SETMASK, &prev_mask, NULL);
  1760.           return -1;
  1761.         }

  1762.       /* No interesting event to report to the caller.  */
  1763.       if ((options & WNOHANG))
  1764.         {
  1765.           if (debug_threads)
  1766.             debug_printf ("WNOHANG set, no event found\n");

  1767.           sigprocmask (SIG_SETMASK, &prev_mask, NULL);
  1768.           return 0;
  1769.         }

  1770.       /* Block until we get an event reported with SIGCHLD.  */
  1771.       if (debug_threads)
  1772.         debug_printf ("sigsuspend'ing\n");

  1773.       sigsuspend (&prev_mask);
  1774.       sigprocmask (SIG_SETMASK, &prev_mask, NULL);
  1775.       goto retry;
  1776.     }

  1777.   sigprocmask (SIG_SETMASK, &prev_mask, NULL);

  1778.   current_thread = event_thread;

  1779.   /* Check for thread exit.  */
  1780.   if (! WIFSTOPPED (*wstatp))
  1781.     {
  1782.       gdb_assert (last_thread_of_process_p (pid_of (event_thread)));

  1783.       if (debug_threads)
  1784.         debug_printf ("LWP %d is the last lwp of process.  "
  1785.                       "Process %ld exiting.\n",
  1786.                       pid_of (event_thread), lwpid_of (event_thread));
  1787.       return lwpid_of (event_thread);
  1788.     }

  1789.   return lwpid_of (event_thread);
  1790. }

  1791. /* Wait for an event from child(ren) PTID.  PTIDs can be:
  1792.    minus_one_ptid, to specify any child; a pid PTID, specifying all
  1793.    lwps of a thread group; or a PTID representing a single lwp.  Store
  1794.    the stop status through the status pointer WSTAT.  OPTIONS is
  1795.    passed to the waitpid call.  Return 0 if no event was found and
  1796.    OPTIONS contains WNOHANG.  Return -1 if no unwaited-for children
  1797.    was found.  Return the PID of the stopped child otherwise.  */

  1798. static int
  1799. linux_wait_for_event (ptid_t ptid, int *wstatp, int options)
  1800. {
  1801.   return linux_wait_for_event_filtered (ptid, ptid, wstatp, options);
  1802. }

  1803. /* Count the LWP's that have had events.  */

  1804. static int
  1805. count_events_callback (struct inferior_list_entry *entry, void *data)
  1806. {
  1807.   struct thread_info *thread = (struct thread_info *) entry;
  1808.   int *count = data;

  1809.   gdb_assert (count != NULL);

  1810.   /* Count only resumed LWPs that have an event pending. */
  1811.   if (thread->last_status.kind == TARGET_WAITKIND_IGNORE
  1812.       && thread->last_resume_kind != resume_stop
  1813.       && thread->status_pending_p)
  1814.     (*count)++;

  1815.   return 0;
  1816. }

  1817. /* Select the LWP (if any) that is currently being single-stepped.  */

  1818. static int
  1819. select_singlestep_lwp_callback (struct inferior_list_entry *entry, void *data)
  1820. {
  1821.   struct thread_info *thread = (struct thread_info *) entry;
  1822.   struct lwp_info *lp = get_thread_lwp (thread);

  1823.   if (thread->last_status.kind == TARGET_WAITKIND_IGNORE
  1824.       && thread->last_resume_kind == resume_step
  1825.       && lp->status_pending_p)
  1826.     return 1;
  1827.   else
  1828.     return 0;
  1829. }

  1830. /* Select the Nth LWP that has had a SIGTRAP event that should be
  1831.    reported to GDB.  */

  1832. static int
  1833. select_event_lwp_callback (struct inferior_list_entry *entry, void *data)
  1834. {
  1835.   struct thread_info *thread = (struct thread_info *) entry;
  1836.   int *selector = data;

  1837.   gdb_assert (selector != NULL);

  1838.   /* Select only resumed LWPs that have an event pending. */
  1839.   if (thread->last_resume_kind != resume_stop
  1840.       && thread->last_status.kind == TARGET_WAITKIND_IGNORE
  1841.       && thread->status_pending_p)
  1842.     if ((*selector)-- == 0)
  1843.       return 1;

  1844.   return 0;
  1845. }

  1846. /* Select one LWP out of those that have events pending.  */

  1847. static void
  1848. select_event_lwp (struct lwp_info **orig_lp)
  1849. {
  1850.   int num_events = 0;
  1851.   int random_selector;
  1852.   struct thread_info *event_thread = NULL;

  1853.   /* In all-stop, give preference to the LWP that is being
  1854.      single-stepped.  There will be at most one, and it's the LWP that
  1855.      the core is most interested in.  If we didn't do this, then we'd
  1856.      have to handle pending step SIGTRAPs somehow in case the core
  1857.      later continues the previously-stepped thread, otherwise we'd
  1858.      report the pending SIGTRAP, and the core, not having stepped the
  1859.      thread, wouldn't understand what the trap was for, and therefore
  1860.      would report it to the user as a random signal.  */
  1861.   if (!non_stop)
  1862.     {
  1863.       event_thread
  1864.         = (struct thread_info *) find_inferior (&all_threads,
  1865.                                                 select_singlestep_lwp_callback,
  1866.                                                 NULL);
  1867.       if (event_thread != NULL)
  1868.         {
  1869.           if (debug_threads)
  1870.             debug_printf ("SEL: Select single-step %s\n",
  1871.                           target_pid_to_str (ptid_of (event_thread)));
  1872.         }
  1873.     }
  1874.   if (event_thread == NULL)
  1875.     {
  1876.       /* No single-stepping LWP.  Select one at random, out of those
  1877.          which have had SIGTRAP events.  */

  1878.       /* First see how many SIGTRAP events we have.  */
  1879.       find_inferior (&all_threads, count_events_callback, &num_events);

  1880.       /* Now randomly pick a LWP out of those that have had a SIGTRAP.  */
  1881.       random_selector = (int)
  1882.         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));

  1883.       if (debug_threads && num_events > 1)
  1884.         debug_printf ("SEL: Found %d SIGTRAP events, selecting #%d\n",
  1885.                       num_events, random_selector);

  1886.       event_thread
  1887.         = (struct thread_info *) find_inferior (&all_threads,
  1888.                                                 select_event_lwp_callback,
  1889.                                                 &random_selector);
  1890.     }

  1891.   if (event_thread != NULL)
  1892.     {
  1893.       struct lwp_info *event_lp = get_thread_lwp (event_thread);

  1894.       /* Switch the event LWP.  */
  1895.       *orig_lp = event_lp;
  1896.     }
  1897. }

  1898. /* Decrement the suspend count of an LWP.  */

  1899. static int
  1900. unsuspend_one_lwp (struct inferior_list_entry *entry, void *except)
  1901. {
  1902.   struct thread_info *thread = (struct thread_info *) entry;
  1903.   struct lwp_info *lwp = get_thread_lwp (thread);

  1904.   /* Ignore EXCEPT.  */
  1905.   if (lwp == except)
  1906.     return 0;

  1907.   lwp->suspended--;

  1908.   gdb_assert (lwp->suspended >= 0);
  1909.   return 0;
  1910. }

  1911. /* Decrement the suspend count of all LWPs, except EXCEPT, if non
  1912.    NULL.  */

  1913. static void
  1914. unsuspend_all_lwps (struct lwp_info *except)
  1915. {
  1916.   find_inferior (&all_threads, unsuspend_one_lwp, except);
  1917. }

  1918. static void move_out_of_jump_pad_callback (struct inferior_list_entry *entry);
  1919. static int stuck_in_jump_pad_callback (struct inferior_list_entry *entry,
  1920.                                        void *data);
  1921. static int lwp_running (struct inferior_list_entry *entry, void *data);
  1922. static ptid_t linux_wait_1 (ptid_t ptid,
  1923.                             struct target_waitstatus *ourstatus,
  1924.                             int target_options);

  1925. /* Stabilize threads (move out of jump pads).

  1926.    If a thread is midway collecting a fast tracepoint, we need to
  1927.    finish the collection and move it out of the jump pad before
  1928.    reporting the signal.

  1929.    This avoids recursion while collecting (when a signal arrives
  1930.    midway, and the signal handler itself collects), which would trash
  1931.    the trace buffer.  In case the user set a breakpoint in a signal
  1932.    handler, this avoids the backtrace showing the jump pad, etc..
  1933.    Most importantly, there are certain things we can't do safely if
  1934.    threads are stopped in a jump pad (or in its callee's).  For
  1935.    example:

  1936.      - starting a new trace runA thread still collecting the
  1937.    previous run, could trash the trace buffer when resumed.  The trace
  1938.    buffer control structures would have been reset but the thread had
  1939.    no way to tell.  The thread could even midway memcpy'ing to the
  1940.    buffer, which would mean that when resumed, it would clobber the
  1941.    trace buffer that had been set for a new run.

  1942.      - we can't rewrite/reuse the jump pads for new tracepoints
  1943.    safely.  Say you do tstart while a thread is stopped midway while
  1944.    collecting.  When the thread is later resumed, it finishes the
  1945.    collection, and returns to the jump pad, to execute the original
  1946.    instruction that was under the tracepoint jump at the time the
  1947.    older run had been started.  If the jump pad had been rewritten
  1948.    since for something else in the new run, the thread would now
  1949.    execute the wrong / random instructions.  */

  1950. static void
  1951. linux_stabilize_threads (void)
  1952. {
  1953.   struct thread_info *saved_thread;
  1954.   struct thread_info *thread_stuck;

  1955.   thread_stuck
  1956.     = (struct thread_info *) find_inferior (&all_threads,
  1957.                                             stuck_in_jump_pad_callback,
  1958.                                             NULL);
  1959.   if (thread_stuck != NULL)
  1960.     {
  1961.       if (debug_threads)
  1962.         debug_printf ("can't stabilize, LWP %ld is stuck in jump pad\n",
  1963.                       lwpid_of (thread_stuck));
  1964.       return;
  1965.     }

  1966.   saved_thread = current_thread;

  1967.   stabilizing_threads = 1;

  1968.   /* Kick 'em all.  */
  1969.   for_each_inferior (&all_threads, move_out_of_jump_pad_callback);

  1970.   /* Loop until all are stopped out of the jump pads.  */
  1971.   while (find_inferior (&all_threads, lwp_running, NULL) != NULL)
  1972.     {
  1973.       struct target_waitstatus ourstatus;
  1974.       struct lwp_info *lwp;
  1975.       int wstat;

  1976.       /* Note that we go through the full wait even loop.  While
  1977.          moving threads out of jump pad, we need to be able to step
  1978.          over internal breakpoints and such.  */
  1979.       linux_wait_1 (minus_one_ptid, &ourstatus, 0);

  1980.       if (ourstatus.kind == TARGET_WAITKIND_STOPPED)
  1981.         {
  1982.           lwp = get_thread_lwp (current_thread);

  1983.           /* Lock it.  */
  1984.           lwp->suspended++;

  1985.           if (ourstatus.value.sig != GDB_SIGNAL_0
  1986.               || current_thread->last_resume_kind == resume_stop)
  1987.             {
  1988.               wstat = W_STOPCODE (gdb_signal_to_host (ourstatus.value.sig));
  1989.               enqueue_one_deferred_signal (lwp, &wstat);
  1990.             }
  1991.         }
  1992.     }

  1993.   find_inferior (&all_threads, unsuspend_one_lwp, NULL);

  1994.   stabilizing_threads = 0;

  1995.   current_thread = saved_thread;

  1996.   if (debug_threads)
  1997.     {
  1998.       thread_stuck
  1999.         = (struct thread_info *) find_inferior (&all_threads,
  2000.                                                 stuck_in_jump_pad_callback,
  2001.                                                 NULL);
  2002.       if (thread_stuck != NULL)
  2003.         debug_printf ("couldn't stabilize, LWP %ld got stuck in jump pad\n",
  2004.                       lwpid_of (thread_stuck));
  2005.     }
  2006. }

  2007. static void async_file_mark (void);

  2008. /* Convenience function that is called when the kernel reports an
  2009.    event that is not passed out to GDB.  */

  2010. static ptid_t
  2011. ignore_event (struct target_waitstatus *ourstatus)
  2012. {
  2013.   /* If we got an event, there may still be others, as a single
  2014.      SIGCHLD can indicate more than one child stopped.  This forces
  2015.      another target_wait call.  */
  2016.   async_file_mark ();

  2017.   ourstatus->kind = TARGET_WAITKIND_IGNORE;
  2018.   return null_ptid;
  2019. }

  2020. /* Wait for process, returns status.  */

  2021. static ptid_t
  2022. linux_wait_1 (ptid_t ptid,
  2023.               struct target_waitstatus *ourstatus, int target_options)
  2024. {
  2025.   int w;
  2026.   struct lwp_info *event_child;
  2027.   int options;
  2028.   int pid;
  2029.   int step_over_finished;
  2030.   int bp_explains_trap;
  2031.   int maybe_internal_trap;
  2032.   int report_to_gdb;
  2033.   int trace_event;
  2034.   int in_step_range;

  2035.   if (debug_threads)
  2036.     {
  2037.       debug_enter ();
  2038.       debug_printf ("linux_wait_1: [%s]\n", target_pid_to_str (ptid));
  2039.     }

  2040.   /* Translate generic target options into linux options.  */
  2041.   options = __WALL;
  2042.   if (target_options & TARGET_WNOHANG)
  2043.     options |= WNOHANG;

  2044.   bp_explains_trap = 0;
  2045.   trace_event = 0;
  2046.   in_step_range = 0;
  2047.   ourstatus->kind = TARGET_WAITKIND_IGNORE;

  2048.   if (ptid_equal (step_over_bkpt, null_ptid))
  2049.     pid = linux_wait_for_event (ptid, &w, options);
  2050.   else
  2051.     {
  2052.       if (debug_threads)
  2053.         debug_printf ("step_over_bkpt set [%s], doing a blocking wait\n",
  2054.                       target_pid_to_str (step_over_bkpt));
  2055.       pid = linux_wait_for_event (step_over_bkpt, &w, options & ~WNOHANG);
  2056.     }

  2057.   if (pid == 0)
  2058.     {
  2059.       gdb_assert (target_options & TARGET_WNOHANG);

  2060.       if (debug_threads)
  2061.         {
  2062.           debug_printf ("linux_wait_1 ret = null_ptid, "
  2063.                         "TARGET_WAITKIND_IGNORE\n");
  2064.           debug_exit ();
  2065.         }

  2066.       ourstatus->kind = TARGET_WAITKIND_IGNORE;
  2067.       return null_ptid;
  2068.     }
  2069.   else if (pid == -1)
  2070.     {
  2071.       if (debug_threads)
  2072.         {
  2073.           debug_printf ("linux_wait_1 ret = null_ptid, "
  2074.                         "TARGET_WAITKIND_NO_RESUMED\n");
  2075.           debug_exit ();
  2076.         }

  2077.       ourstatus->kind = TARGET_WAITKIND_NO_RESUMED;
  2078.       return null_ptid;
  2079.     }

  2080.   event_child = get_thread_lwp (current_thread);

  2081.   /* linux_wait_for_event only returns an exit status for the last
  2082.      child of a process.  Report it.  */
  2083.   if (WIFEXITED (w) || WIFSIGNALED (w))
  2084.     {
  2085.       if (WIFEXITED (w))
  2086.         {
  2087.           ourstatus->kind = TARGET_WAITKIND_EXITED;
  2088.           ourstatus->value.integer = WEXITSTATUS (w);

  2089.           if (debug_threads)
  2090.             {
  2091.               debug_printf ("linux_wait_1 ret = %s, exited with "
  2092.                             "retcode %d\n",
  2093.                             target_pid_to_str (ptid_of (current_thread)),
  2094.                             WEXITSTATUS (w));
  2095.               debug_exit ();
  2096.             }
  2097.         }
  2098.       else
  2099.         {
  2100.           ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
  2101.           ourstatus->value.sig = gdb_signal_from_host (WTERMSIG (w));

  2102.           if (debug_threads)
  2103.             {
  2104.               debug_printf ("linux_wait_1 ret = %s, terminated with "
  2105.                             "signal %d\n",
  2106.                             target_pid_to_str (ptid_of (current_thread)),
  2107.                             WTERMSIG (w));
  2108.               debug_exit ();
  2109.             }
  2110.         }

  2111.       return ptid_of (current_thread);
  2112.     }

  2113.   /* If this event was not handled before, and is not a SIGTRAP, we
  2114.      report it.  SIGILL and SIGSEGV are also treated as traps in case
  2115.      a breakpoint is inserted at the current PC.  If this target does
  2116.      not support internal breakpoints at all, we also report the
  2117.      SIGTRAP without further processing; it's of no concern to us.  */
  2118.   maybe_internal_trap
  2119.     = (supports_breakpoints ()
  2120.        && (WSTOPSIG (w) == SIGTRAP
  2121.            || ((WSTOPSIG (w) == SIGILL
  2122.                 || WSTOPSIG (w) == SIGSEGV)
  2123.                && (*the_low_target.breakpoint_at) (event_child->stop_pc))));

  2124.   if (maybe_internal_trap)
  2125.     {
  2126.       /* Handle anything that requires bookkeeping before deciding to
  2127.          report the event or continue waiting.  */

  2128.       /* First check if we can explain the SIGTRAP with an internal
  2129.          breakpoint, or if we should possibly report the event to GDB.
  2130.          Do this before anything that may remove or insert a
  2131.          breakpoint.  */
  2132.       bp_explains_trap = breakpoint_inserted_here (event_child->stop_pc);

  2133.       /* We have a SIGTRAP, possibly a step-over dance has just
  2134.          finished.  If so, tweak the state machine accordingly,
  2135.          reinsert breakpoints and delete any reinsert (software
  2136.          single-step) breakpoints.  */
  2137.       step_over_finished = finish_step_over (event_child);

  2138.       /* Now invoke the callbacks of any internal breakpoints there.  */
  2139.       check_breakpoints (event_child->stop_pc);

  2140.       /* Handle tracepoint data collecting.  This may overflow the
  2141.          trace buffer, and cause a tracing stop, removing
  2142.          breakpoints.  */
  2143.       trace_event = handle_tracepoints (event_child);

  2144.       if (bp_explains_trap)
  2145.         {
  2146.           /* If we stepped or ran into an internal breakpoint, we've
  2147.              already handled it.  So next time we resume (from this
  2148.              PC), we should step over it.  */
  2149.           if (debug_threads)
  2150.             debug_printf ("Hit a gdbserver breakpoint.\n");

  2151.           if (breakpoint_here (event_child->stop_pc))
  2152.             event_child->need_step_over = 1;
  2153.         }
  2154.     }
  2155.   else
  2156.     {
  2157.       /* We have some other signal, possibly a step-over dance was in
  2158.          progress, and it should be cancelled too.  */
  2159.       step_over_finished = finish_step_over (event_child);
  2160.     }

  2161.   /* We have all the data we need.  Either report the event to GDB, or
  2162.      resume threads and keep waiting for more.  */

  2163.   /* If we're collecting a fast tracepoint, finish the collection and
  2164.      move out of the jump pad before delivering a signal.  See
  2165.      linux_stabilize_threads.  */

  2166.   if (WIFSTOPPED (w)
  2167.       && WSTOPSIG (w) != SIGTRAP
  2168.       && supports_fast_tracepoints ()
  2169.       && agent_loaded_p ())
  2170.     {
  2171.       if (debug_threads)
  2172.         debug_printf ("Got signal %d for LWP %ld.  Check if we need "
  2173.                       "to defer or adjust it.\n",
  2174.                       WSTOPSIG (w), lwpid_of (current_thread));

  2175.       /* Allow debugging the jump pad itself.  */
  2176.       if (current_thread->last_resume_kind != resume_step
  2177.           && maybe_move_out_of_jump_pad (event_child, &w))
  2178.         {
  2179.           enqueue_one_deferred_signal (event_child, &w);

  2180.           if (debug_threads)
  2181.             debug_printf ("Signal %d for LWP %ld deferred (in jump pad)\n",
  2182.                           WSTOPSIG (w), lwpid_of (current_thread));

  2183.           linux_resume_one_lwp (event_child, 0, 0, NULL);

  2184.           return ignore_event (ourstatus);
  2185.         }
  2186.     }

  2187.   if (event_child->collecting_fast_tracepoint)
  2188.     {
  2189.       if (debug_threads)
  2190.         debug_printf ("LWP %ld was trying to move out of the jump pad (%d). "
  2191.                       "Check if we're already there.\n",
  2192.                       lwpid_of (current_thread),
  2193.                       event_child->collecting_fast_tracepoint);

  2194.       trace_event = 1;

  2195.       event_child->collecting_fast_tracepoint
  2196.         = linux_fast_tracepoint_collecting (event_child, NULL);

  2197.       if (event_child->collecting_fast_tracepoint != 1)
  2198.         {
  2199.           /* No longer need this breakpoint.  */
  2200.           if (event_child->exit_jump_pad_bkpt != NULL)
  2201.             {
  2202.               if (debug_threads)
  2203.                 debug_printf ("No longer need exit-jump-pad bkpt; removing it."
  2204.                               "stopping all threads momentarily.\n");

  2205.               /* Other running threads could hit this breakpoint.
  2206.                  We don't handle moribund locations like GDB does,
  2207.                  instead we always pause all threads when removing
  2208.                  breakpoints, so that any step-over or
  2209.                  decr_pc_after_break adjustment is always taken
  2210.                  care of while the breakpoint is still
  2211.                  inserted.  */
  2212.               stop_all_lwps (1, event_child);

  2213.               delete_breakpoint (event_child->exit_jump_pad_bkpt);
  2214.               event_child->exit_jump_pad_bkpt = NULL;

  2215.               unstop_all_lwps (1, event_child);

  2216.               gdb_assert (event_child->suspended >= 0);
  2217.             }
  2218.         }

  2219.       if (event_child->collecting_fast_tracepoint == 0)
  2220.         {
  2221.           if (debug_threads)
  2222.             debug_printf ("fast tracepoint finished "
  2223.                           "collecting successfully.\n");

  2224.           /* We may have a deferred signal to report.  */
  2225.           if (dequeue_one_deferred_signal (event_child, &w))
  2226.             {
  2227.               if (debug_threads)
  2228.                 debug_printf ("dequeued one signal.\n");
  2229.             }
  2230.           else
  2231.             {
  2232.               if (debug_threads)
  2233.                 debug_printf ("no deferred signals.\n");

  2234.               if (stabilizing_threads)
  2235.                 {
  2236.                   ourstatus->kind = TARGET_WAITKIND_STOPPED;
  2237.                   ourstatus->value.sig = GDB_SIGNAL_0;

  2238.                   if (debug_threads)
  2239.                     {
  2240.                       debug_printf ("linux_wait_1 ret = %s, stopped "
  2241.                                     "while stabilizing threads\n",
  2242.                                     target_pid_to_str (ptid_of (current_thread)));
  2243.                       debug_exit ();
  2244.                     }

  2245.                   return ptid_of (current_thread);
  2246.                 }
  2247.             }
  2248.         }
  2249.     }

  2250.   /* Check whether GDB would be interested in this event.  */

  2251.   /* If GDB is not interested in this signal, don't stop other
  2252.      threads, and don't report it to GDB.  Just resume the inferior
  2253.      right away.  We do this for threading-related signals as well as
  2254.      any that GDB specifically requested we ignore.  But never ignore
  2255.      SIGSTOP if we sent it ourselves, and do not ignore signals when
  2256.      stepping - they may require special handling to skip the signal
  2257.      handler.  */
  2258.   /* FIXME drow/2002-06-09: Get signal numbers from the inferior's
  2259.      thread library?  */
  2260.   if (WIFSTOPPED (w)
  2261.       && current_thread->last_resume_kind != resume_step
  2262.       && (
  2263. #if defined (USE_THREAD_DB) && !defined (__ANDROID__)
  2264.           (current_process ()->private->thread_db != NULL
  2265.            && (WSTOPSIG (w) == __SIGRTMIN
  2266.                || WSTOPSIG (w) == __SIGRTMIN + 1))
  2267.           ||
  2268. #endif
  2269.           (pass_signals[gdb_signal_from_host (WSTOPSIG (w))]
  2270.            && !(WSTOPSIG (w) == SIGSTOP
  2271.                 && current_thread->last_resume_kind == resume_stop))))
  2272.     {
  2273.       siginfo_t info, *info_p;

  2274.       if (debug_threads)
  2275.         debug_printf ("Ignored signal %d for LWP %ld.\n",
  2276.                       WSTOPSIG (w), lwpid_of (current_thread));

  2277.       if (ptrace (PTRACE_GETSIGINFO, lwpid_of (current_thread),
  2278.                   (PTRACE_TYPE_ARG3) 0, &info) == 0)
  2279.         info_p = &info;
  2280.       else
  2281.         info_p = NULL;
  2282.       linux_resume_one_lwp (event_child, event_child->stepping,
  2283.                             WSTOPSIG (w), info_p);
  2284.       return ignore_event (ourstatus);
  2285.     }

  2286.   /* Note that all addresses are always "out of the step range" when
  2287.      there's no range to begin with.  */
  2288.   in_step_range = lwp_in_step_range (event_child);

  2289.   /* If GDB wanted this thread to single step, and the thread is out
  2290.      of the step range, we always want to report the SIGTRAP, and let
  2291.      GDB handle it.  Watchpoints should always be reported.  So should
  2292.      signals we can't explain.  A SIGTRAP we can't explain could be a
  2293.      GDB breakpoint --- we may or not support Z0 breakpoints.  If we
  2294.      do, we're be able to handle GDB breakpoints on top of internal
  2295.      breakpoints, by handling the internal breakpoint and still
  2296.      reporting the event to GDB.  If we don't, we're out of luck, GDB
  2297.      won't see the breakpoint hit.  */
  2298.   report_to_gdb = (!maybe_internal_trap
  2299.                    || (current_thread->last_resume_kind == resume_step
  2300.                        && !in_step_range)
  2301.                    || event_child->stop_reason == LWP_STOPPED_BY_WATCHPOINT
  2302.                    || (!step_over_finished && !in_step_range
  2303.                        && !bp_explains_trap && !trace_event)
  2304.                    || (gdb_breakpoint_here (event_child->stop_pc)
  2305.                        && gdb_condition_true_at_breakpoint (event_child->stop_pc)
  2306.                        && gdb_no_commands_at_breakpoint (event_child->stop_pc)));

  2307.   run_breakpoint_commands (event_child->stop_pc);

  2308.   /* We found no reason GDB would want us to stop.  We either hit one
  2309.      of our own breakpoints, or finished an internal step GDB
  2310.      shouldn't know about.  */
  2311.   if (!report_to_gdb)
  2312.     {
  2313.       if (debug_threads)
  2314.         {
  2315.           if (bp_explains_trap)
  2316.             debug_printf ("Hit a gdbserver breakpoint.\n");
  2317.           if (step_over_finished)
  2318.             debug_printf ("Step-over finished.\n");
  2319.           if (trace_event)
  2320.             debug_printf ("Tracepoint event.\n");
  2321.           if (lwp_in_step_range (event_child))
  2322.             debug_printf ("Range stepping pc 0x%s [0x%s, 0x%s).\n",
  2323.                           paddress (event_child->stop_pc),
  2324.                           paddress (event_child->step_range_start),
  2325.                           paddress (event_child->step_range_end));
  2326.         }

  2327.       /* We're not reporting this breakpoint to GDB, so apply the
  2328.          decr_pc_after_break adjustment to the inferior's regcache
  2329.          ourselves.  */

  2330.       if (the_low_target.set_pc != NULL)
  2331.         {
  2332.           struct regcache *regcache
  2333.             = get_thread_regcache (current_thread, 1);
  2334.           (*the_low_target.set_pc) (regcache, event_child->stop_pc);
  2335.         }

  2336.       /* We may have finished stepping over a breakpoint.  If so,
  2337.          we've stopped and suspended all LWPs momentarily except the
  2338.          stepping one.  This is where we resume them all again.  We're
  2339.          going to keep waiting, so use proceed, which handles stepping
  2340.          over the next breakpoint.  */
  2341.       if (debug_threads)
  2342.         debug_printf ("proceeding all threads.\n");

  2343.       if (step_over_finished)
  2344.         unsuspend_all_lwps (event_child);

  2345.       proceed_all_lwps ();
  2346.       return ignore_event (ourstatus);
  2347.     }

  2348.   if (debug_threads)
  2349.     {
  2350.       if (current_thread->last_resume_kind == resume_step)
  2351.         {
  2352.           if (event_child->step_range_start == event_child->step_range_end)
  2353.             debug_printf ("GDB wanted to single-step, reporting event.\n");
  2354.           else if (!lwp_in_step_range (event_child))
  2355.             debug_printf ("Out of step range, reporting event.\n");
  2356.         }
  2357.       if (event_child->stop_reason == LWP_STOPPED_BY_WATCHPOINT)
  2358.         debug_printf ("Stopped by watchpoint.\n");
  2359.       else if (gdb_breakpoint_here (event_child->stop_pc))
  2360.         debug_printf ("Stopped by GDB breakpoint.\n");
  2361.       if (debug_threads)
  2362.         debug_printf ("Hit a non-gdbserver trap event.\n");
  2363.     }

  2364.   /* Alright, we're going to report a stop.  */

  2365.   if (!stabilizing_threads)
  2366.     {
  2367.       /* In all-stop, stop all threads.  */
  2368.       if (!non_stop)
  2369.         stop_all_lwps (0, NULL);

  2370.       /* If we're not waiting for a specific LWP, choose an event LWP
  2371.          from among those that have had events.  Giving equal priority
  2372.          to all LWPs that have had events helps prevent
  2373.          starvation.  */
  2374.       if (ptid_equal (ptid, minus_one_ptid))
  2375.         {
  2376.           event_child->status_pending_p = 1;
  2377.           event_child->status_pending = w;

  2378.           select_event_lwp (&event_child);

  2379.           /* current_thread and event_child must stay in sync.  */
  2380.           current_thread = get_lwp_thread (event_child);

  2381.           event_child->status_pending_p = 0;
  2382.           w = event_child->status_pending;
  2383.         }

  2384.       if (step_over_finished)
  2385.         {
  2386.           if (!non_stop)
  2387.             {
  2388.               /* If we were doing a step-over, all other threads but
  2389.                  the stepping one had been paused in start_step_over,
  2390.                  with their suspend counts incremented.  We don't want
  2391.                  to do a full unstop/unpause, because we're in
  2392.                  all-stop mode (so we want threads stopped), but we
  2393.                  still need to unsuspend the other threads, to
  2394.                  decrement their `suspended' count back.  */
  2395.               unsuspend_all_lwps (event_child);
  2396.             }
  2397.           else
  2398.             {
  2399.               /* If we just finished a step-over, then all threads had
  2400.                  been momentarily paused.  In all-stop, that's fine,
  2401.                  we want threads stopped by now anyway.  In non-stop,
  2402.                  we need to re-resume threads that GDB wanted to be
  2403.                  running.  */
  2404.               unstop_all_lwps (1, event_child);
  2405.             }
  2406.         }

  2407.       /* Stabilize threads (move out of jump pads).  */
  2408.       if (!non_stop)
  2409.         stabilize_threads ();
  2410.     }
  2411.   else
  2412.     {
  2413.       /* If we just finished a step-over, then all threads had been
  2414.          momentarily paused.  In all-stop, that's fine, we want
  2415.          threads stopped by now anyway.  In non-stop, we need to
  2416.          re-resume threads that GDB wanted to be running.  */
  2417.       if (step_over_finished)
  2418.         unstop_all_lwps (1, event_child);
  2419.     }

  2420.   ourstatus->kind = TARGET_WAITKIND_STOPPED;

  2421.   /* Now that we've selected our final event LWP, un-adjust its PC if
  2422.      it was a software breakpoint.  */
  2423.   if (event_child->stop_reason == LWP_STOPPED_BY_SW_BREAKPOINT)
  2424.     {
  2425.       int decr_pc = the_low_target.decr_pc_after_break;

  2426.       if (decr_pc != 0)
  2427.         {
  2428.           struct regcache *regcache
  2429.             = get_thread_regcache (current_thread, 1);
  2430.           (*the_low_target.set_pc) (regcache, event_child->stop_pc + decr_pc);
  2431.         }
  2432.     }

  2433.   if (current_thread->last_resume_kind == resume_stop
  2434.       && WSTOPSIG (w) == SIGSTOP)
  2435.     {
  2436.       /* A thread that has been requested to stop by GDB with vCont;t,
  2437.          and it stopped cleanly, so report as SIG0.  The use of
  2438.          SIGSTOP is an implementation detail.  */
  2439.       ourstatus->value.sig = GDB_SIGNAL_0;
  2440.     }
  2441.   else if (current_thread->last_resume_kind == resume_stop
  2442.            && WSTOPSIG (w) != SIGSTOP)
  2443.     {
  2444.       /* A thread that has been requested to stop by GDB with vCont;t,
  2445.          but, it stopped for other reasons.  */
  2446.       ourstatus->value.sig = gdb_signal_from_host (WSTOPSIG (w));
  2447.     }
  2448.   else
  2449.     {
  2450.       ourstatus->value.sig = gdb_signal_from_host (WSTOPSIG (w));
  2451.     }

  2452.   gdb_assert (ptid_equal (step_over_bkpt, null_ptid));

  2453.   if (debug_threads)
  2454.     {
  2455.       debug_printf ("linux_wait_1 ret = %s, %d, %d\n",
  2456.                     target_pid_to_str (ptid_of (current_thread)),
  2457.                     ourstatus->kind, ourstatus->value.sig);
  2458.       debug_exit ();
  2459.     }

  2460.   return ptid_of (current_thread);
  2461. }

  2462. /* Get rid of any pending event in the pipe.  */
  2463. static void
  2464. async_file_flush (void)
  2465. {
  2466.   int ret;
  2467.   char buf;

  2468.   do
  2469.     ret = read (linux_event_pipe[0], &buf, 1);
  2470.   while (ret >= 0 || (ret == -1 && errno == EINTR));
  2471. }

  2472. /* Put something in the pipe, so the event loop wakes up.  */
  2473. static void
  2474. async_file_mark (void)
  2475. {
  2476.   int ret;

  2477.   async_file_flush ();

  2478.   do
  2479.     ret = write (linux_event_pipe[1], "+", 1);
  2480.   while (ret == 0 || (ret == -1 && errno == EINTR));

  2481.   /* Ignore EAGAIN.  If the pipe is full, the event loop will already
  2482.      be awakened anyway.  */
  2483. }

  2484. static ptid_t
  2485. linux_wait (ptid_t ptid,
  2486.             struct target_waitstatus *ourstatus, int target_options)
  2487. {
  2488.   ptid_t event_ptid;

  2489.   /* Flush the async file first.  */
  2490.   if (target_is_async_p ())
  2491.     async_file_flush ();

  2492.   do
  2493.     {
  2494.       event_ptid = linux_wait_1 (ptid, ourstatus, target_options);
  2495.     }
  2496.   while ((target_options & TARGET_WNOHANG) == 0
  2497.          && ptid_equal (event_ptid, null_ptid)
  2498.          && ourstatus->kind == TARGET_WAITKIND_IGNORE);

  2499.   /* If at least one stop was reported, there may be more.  A single
  2500.      SIGCHLD can signal more than one child stop.  */
  2501.   if (target_is_async_p ()
  2502.       && (target_options & TARGET_WNOHANG) != 0
  2503.       && !ptid_equal (event_ptid, null_ptid))
  2504.     async_file_mark ();

  2505.   return event_ptid;
  2506. }

  2507. /* Send a signal to an LWP.  */

  2508. static int
  2509. kill_lwp (unsigned long lwpid, int signo)
  2510. {
  2511.   /* Use tkill, if possible, in case we are using nptl threads.  If tkill
  2512.      fails, then we are not using nptl threads and we should be using kill.  */

  2513. #ifdef __NR_tkill
  2514.   {
  2515.     static int tkill_failed;

  2516.     if (!tkill_failed)
  2517.       {
  2518.         int ret;

  2519.         errno = 0;
  2520.         ret = syscall (__NR_tkill, lwpid, signo);
  2521.         if (errno != ENOSYS)
  2522.           return ret;
  2523.         tkill_failed = 1;
  2524.       }
  2525.   }
  2526. #endif

  2527.   return kill (lwpid, signo);
  2528. }

  2529. void
  2530. linux_stop_lwp (struct lwp_info *lwp)
  2531. {
  2532.   send_sigstop (lwp);
  2533. }

  2534. static void
  2535. send_sigstop (struct lwp_info *lwp)
  2536. {
  2537.   int pid;

  2538.   pid = lwpid_of (get_lwp_thread (lwp));

  2539.   /* If we already have a pending stop signal for this process, don't
  2540.      send another.  */
  2541.   if (lwp->stop_expected)
  2542.     {
  2543.       if (debug_threads)
  2544.         debug_printf ("Have pending sigstop for lwp %d\n", pid);

  2545.       return;
  2546.     }

  2547.   if (debug_threads)
  2548.     debug_printf ("Sending sigstop to lwp %d\n", pid);

  2549.   lwp->stop_expected = 1;
  2550.   kill_lwp (pid, SIGSTOP);
  2551. }

  2552. static int
  2553. send_sigstop_callback (struct inferior_list_entry *entry, void *except)
  2554. {
  2555.   struct thread_info *thread = (struct thread_info *) entry;
  2556.   struct lwp_info *lwp = get_thread_lwp (thread);

  2557.   /* Ignore EXCEPT.  */
  2558.   if (lwp == except)
  2559.     return 0;

  2560.   if (lwp->stopped)
  2561.     return 0;

  2562.   send_sigstop (lwp);
  2563.   return 0;
  2564. }

  2565. /* Increment the suspend count of an LWP, and stop it, if not stopped
  2566.    yet.  */
  2567. static int
  2568. suspend_and_send_sigstop_callback (struct inferior_list_entry *entry,
  2569.                                    void *except)
  2570. {
  2571.   struct thread_info *thread = (struct thread_info *) entry;
  2572.   struct lwp_info *lwp = get_thread_lwp (thread);

  2573.   /* Ignore EXCEPT.  */
  2574.   if (lwp == except)
  2575.     return 0;

  2576.   lwp->suspended++;

  2577.   return send_sigstop_callback (entry, except);
  2578. }

  2579. static void
  2580. mark_lwp_dead (struct lwp_info *lwp, int wstat)
  2581. {
  2582.   /* It's dead, really.  */
  2583.   lwp->dead = 1;

  2584.   /* Store the exit status for later.  */
  2585.   lwp->status_pending_p = 1;
  2586.   lwp->status_pending = wstat;

  2587.   /* Prevent trying to stop it.  */
  2588.   lwp->stopped = 1;

  2589.   /* No further stops are expected from a dead lwp.  */
  2590.   lwp->stop_expected = 0;
  2591. }

  2592. /* Wait for all children to stop for the SIGSTOPs we just queued.  */

  2593. static void
  2594. wait_for_sigstop (void)
  2595. {
  2596.   struct thread_info *saved_thread;
  2597.   ptid_t saved_tid;
  2598.   int wstat;
  2599.   int ret;

  2600.   saved_thread = current_thread;
  2601.   if (saved_thread != NULL)
  2602.     saved_tid = saved_thread->entry.id;
  2603.   else
  2604.     saved_tid = null_ptid; /* avoid bogus unused warning */

  2605.   if (debug_threads)
  2606.     debug_printf ("wait_for_sigstop: pulling events\n");

  2607.   /* Passing NULL_PTID as filter indicates we want all events to be
  2608.      left pending.  Eventually this returns when there are no
  2609.      unwaited-for children left.  */
  2610.   ret = linux_wait_for_event_filtered (minus_one_ptid, null_ptid,
  2611.                                        &wstat, __WALL);
  2612.   gdb_assert (ret == -1);

  2613.   if (saved_thread == NULL || linux_thread_alive (saved_tid))
  2614.     current_thread = saved_thread;
  2615.   else
  2616.     {
  2617.       if (debug_threads)
  2618.         debug_printf ("Previously current thread died.\n");

  2619.       if (non_stop)
  2620.         {
  2621.           /* We can't change the current inferior behind GDB's back,
  2622.              otherwise, a subsequent command may apply to the wrong
  2623.              process.  */
  2624.           current_thread = NULL;
  2625.         }
  2626.       else
  2627.         {
  2628.           /* Set a valid thread as current.  */
  2629.           set_desired_thread (0);
  2630.         }
  2631.     }
  2632. }

  2633. /* Returns true if LWP ENTRY is stopped in a jump pad, and we can't
  2634.    move it out, because we need to report the stop event to GDB.  For
  2635.    example, if the user puts a breakpoint in the jump pad, it's
  2636.    because she wants to debug it.  */

  2637. static int
  2638. stuck_in_jump_pad_callback (struct inferior_list_entry *entry, void *data)
  2639. {
  2640.   struct thread_info *thread = (struct thread_info *) entry;
  2641.   struct lwp_info *lwp = get_thread_lwp (thread);

  2642.   gdb_assert (lwp->suspended == 0);
  2643.   gdb_assert (lwp->stopped);

  2644.   /* Allow debugging the jump pad, gdb_collect, etc..  */
  2645.   return (supports_fast_tracepoints ()
  2646.           && agent_loaded_p ()
  2647.           && (gdb_breakpoint_here (lwp->stop_pc)
  2648.               || lwp->stop_reason == LWP_STOPPED_BY_WATCHPOINT
  2649.               || thread->last_resume_kind == resume_step)
  2650.           && linux_fast_tracepoint_collecting (lwp, NULL));
  2651. }

  2652. static void
  2653. move_out_of_jump_pad_callback (struct inferior_list_entry *entry)
  2654. {
  2655.   struct thread_info *thread = (struct thread_info *) entry;
  2656.   struct lwp_info *lwp = get_thread_lwp (thread);
  2657.   int *wstat;

  2658.   gdb_assert (lwp->suspended == 0);
  2659.   gdb_assert (lwp->stopped);

  2660.   wstat = lwp->status_pending_p ? &lwp->status_pending : NULL;

  2661.   /* Allow debugging the jump pad, gdb_collect, etc.  */
  2662.   if (!gdb_breakpoint_here (lwp->stop_pc)
  2663.       && lwp->stop_reason != LWP_STOPPED_BY_WATCHPOINT
  2664.       && thread->last_resume_kind != resume_step
  2665.       && maybe_move_out_of_jump_pad (lwp, wstat))
  2666.     {
  2667.       if (debug_threads)
  2668.         debug_printf ("LWP %ld needs stabilizing (in jump pad)\n",
  2669.                       lwpid_of (thread));

  2670.       if (wstat)
  2671.         {
  2672.           lwp->status_pending_p = 0;
  2673.           enqueue_one_deferred_signal (lwp, wstat);

  2674.           if (debug_threads)
  2675.             debug_printf ("Signal %d for LWP %ld deferred "
  2676.                           "(in jump pad)\n",
  2677.                           WSTOPSIG (*wstat), lwpid_of (thread));
  2678.         }

  2679.       linux_resume_one_lwp (lwp, 0, 0, NULL);
  2680.     }
  2681.   else
  2682.     lwp->suspended++;
  2683. }

  2684. static int
  2685. lwp_running (struct inferior_list_entry *entry, void *data)
  2686. {
  2687.   struct thread_info *thread = (struct thread_info *) entry;
  2688.   struct lwp_info *lwp = get_thread_lwp (thread);

  2689.   if (lwp->dead)
  2690.     return 0;
  2691.   if (lwp->stopped)
  2692.     return 0;
  2693.   return 1;
  2694. }

  2695. /* Stop all lwps that aren't stopped yet, except EXCEPT, if not NULL.
  2696.    If SUSPEND, then also increase the suspend count of every LWP,
  2697.    except EXCEPT.  */

  2698. static void
  2699. stop_all_lwps (int suspend, struct lwp_info *except)
  2700. {
  2701.   /* Should not be called recursively.  */
  2702.   gdb_assert (stopping_threads == NOT_STOPPING_THREADS);

  2703.   if (debug_threads)
  2704.     {
  2705.       debug_enter ();
  2706.       debug_printf ("stop_all_lwps (%s, except=%s)\n",
  2707.                     suspend ? "stop-and-suspend" : "stop",
  2708.                     except != NULL
  2709.                     ? target_pid_to_str (ptid_of (get_lwp_thread (except)))
  2710.                     : "none");
  2711.     }

  2712.   stopping_threads = (suspend
  2713.                       ? STOPPING_AND_SUSPENDING_THREADS
  2714.                       : STOPPING_THREADS);

  2715.   if (suspend)
  2716.     find_inferior (&all_threads, suspend_and_send_sigstop_callback, except);
  2717.   else
  2718.     find_inferior (&all_threads, send_sigstop_callback, except);
  2719.   wait_for_sigstop ();
  2720.   stopping_threads = NOT_STOPPING_THREADS;

  2721.   if (debug_threads)
  2722.     {
  2723.       debug_printf ("stop_all_lwps done, setting stopping_threads "
  2724.                     "back to !stopping\n");
  2725.       debug_exit ();
  2726.     }
  2727. }

  2728. /* Resume execution of the inferior process.
  2729.    If STEP is nonzero, single-step it.
  2730.    If SIGNAL is nonzero, give it that signal.  */

  2731. static void
  2732. linux_resume_one_lwp (struct lwp_info *lwp,
  2733.                       int step, int signal, siginfo_t *info)
  2734. {
  2735.   struct thread_info *thread = get_lwp_thread (lwp);
  2736.   struct thread_info *saved_thread;
  2737.   int fast_tp_collecting;

  2738.   if (lwp->stopped == 0)
  2739.     return;

  2740.   fast_tp_collecting = lwp->collecting_fast_tracepoint;

  2741.   gdb_assert (!stabilizing_threads || fast_tp_collecting);

  2742.   /* Cancel actions that rely on GDB not changing the PC (e.g., the
  2743.      user used the "jump" command, or "set $pc = foo").  */
  2744.   if (lwp->stop_pc != get_pc (lwp))
  2745.     {
  2746.       /* Collecting 'while-stepping' actions doesn't make sense
  2747.          anymore.  */
  2748.       release_while_stepping_state_list (thread);
  2749.     }

  2750.   /* If we have pending signals or status, and a new signal, enqueue the
  2751.      signal.  Also enqueue the signal if we are waiting to reinsert a
  2752.      breakpoint; it will be picked up again below.  */
  2753.   if (signal != 0
  2754.       && (lwp->status_pending_p
  2755.           || lwp->pending_signals != NULL
  2756.           || lwp->bp_reinsert != 0
  2757.           || fast_tp_collecting))
  2758.     {
  2759.       struct pending_signals *p_sig;
  2760.       p_sig = xmalloc (sizeof (*p_sig));
  2761.       p_sig->prev = lwp->pending_signals;
  2762.       p_sig->signal = signal;
  2763.       if (info == NULL)
  2764.         memset (&p_sig->info, 0, sizeof (siginfo_t));
  2765.       else
  2766.         memcpy (&p_sig->info, info, sizeof (siginfo_t));
  2767.       lwp->pending_signals = p_sig;
  2768.     }

  2769.   if (lwp->status_pending_p)
  2770.     {
  2771.       if (debug_threads)
  2772.         debug_printf ("Not resuming lwp %ld (%s, signal %d, stop %s);"
  2773.                       " has pending status\n",
  2774.                       lwpid_of (thread), step ? "step" : "continue", signal,
  2775.                       lwp->stop_expected ? "expected" : "not expected");
  2776.       return;
  2777.     }

  2778.   saved_thread = current_thread;
  2779.   current_thread = thread;

  2780.   if (debug_threads)
  2781.     debug_printf ("Resuming lwp %ld (%s, signal %d, stop %s)\n",
  2782.                   lwpid_of (thread), step ? "step" : "continue", signal,
  2783.                   lwp->stop_expected ? "expected" : "not expected");

  2784.   /* This bit needs some thinking about.  If we get a signal that
  2785.      we must report while a single-step reinsert is still pending,
  2786.      we often end up resuming the thread.  It might be better to
  2787.      (ew) allow a stack of pending events; then we could be sure that
  2788.      the reinsert happened right away and not lose any signals.

  2789.      Making this stack would also shrink the window in which breakpoints are
  2790.      uninserted (see comment in linux_wait_for_lwp) but not enough for
  2791.      complete correctness, so it won't solve that problem.  It may be
  2792.      worthwhile just to solve this one, however.  */
  2793.   if (lwp->bp_reinsert != 0)
  2794.     {
  2795.       if (debug_threads)
  2796.         debug_printf (pending reinsert at 0x%s\n",
  2797.                       paddress (lwp->bp_reinsert));

  2798.       if (can_hardware_single_step ())
  2799.         {
  2800.           if (fast_tp_collecting == 0)
  2801.             {
  2802.               if (step == 0)
  2803.                 fprintf (stderr, "BAD - reinserting but not stepping.\n");
  2804.               if (lwp->suspended)
  2805.                 fprintf (stderr, "BAD - reinserting and suspended(%d).\n",
  2806.                          lwp->suspended);
  2807.             }

  2808.           step = 1;
  2809.         }

  2810.       /* Postpone any pending signal.  It was enqueued above.  */
  2811.       signal = 0;
  2812.     }

  2813.   if (fast_tp_collecting == 1)
  2814.     {
  2815.       if (debug_threads)
  2816.         debug_printf ("lwp %ld wants to get out of fast tracepoint jump pad"
  2817.                       " (exit-jump-pad-bkpt)\n",
  2818.                       lwpid_of (thread));

  2819.       /* Postpone any pending signal.  It was enqueued above.  */
  2820.       signal = 0;
  2821.     }
  2822.   else if (fast_tp_collecting == 2)
  2823.     {
  2824.       if (debug_threads)
  2825.         debug_printf ("lwp %ld wants to get out of fast tracepoint jump pad"
  2826.                       " single-stepping\n",
  2827.                       lwpid_of (thread));

  2828.       if (can_hardware_single_step ())
  2829.         step = 1;
  2830.       else
  2831.         {
  2832.           internal_error (__FILE__, __LINE__,
  2833.                           "moving out of jump pad single-stepping"
  2834.                           " not implemented on this target");
  2835.         }

  2836.       /* Postpone any pending signal.  It was enqueued above.  */
  2837.       signal = 0;
  2838.     }

  2839.   /* If we have while-stepping actions in this thread set it stepping.
  2840.      If we have a signal to deliver, it may or may not be set to
  2841.      SIG_IGN, we don't know.  Assume so, and allow collecting
  2842.      while-stepping into a signal handlerA possible smart thing to
  2843.      do would be to set an internal breakpoint at the signal return
  2844.      address, continue, and carry on catching this while-stepping
  2845.      action only when that breakpoint is hit.  A future
  2846.      enhancement.  */
  2847.   if (thread->while_stepping != NULL
  2848.       && can_hardware_single_step ())
  2849.     {
  2850.       if (debug_threads)
  2851.         debug_printf ("lwp %ld has a while-stepping action -> forcing step.\n",
  2852.                       lwpid_of (thread));
  2853.       step = 1;
  2854.     }

  2855.   if (the_low_target.get_pc != NULL)
  2856.     {
  2857.       struct regcache *regcache = get_thread_regcache (current_thread, 1);

  2858.       lwp->stop_pc = (*the_low_target.get_pc) (regcache);

  2859.       if (debug_threads)
  2860.         {
  2861.           debug_printf (%s from pc 0x%lx\n", step ? "step" : "continue",
  2862.                         (long) lwp->stop_pc);
  2863.         }
  2864.     }

  2865.   /* If we have pending signals, consume one unless we are trying to
  2866.      reinsert a breakpoint or we're trying to finish a fast tracepoint
  2867.      collect.  */
  2868.   if (lwp->pending_signals != NULL
  2869.       && lwp->bp_reinsert == 0
  2870.       && fast_tp_collecting == 0)
  2871.     {
  2872.       struct pending_signals **p_sig;

  2873.       p_sig = &lwp->pending_signals;
  2874.       while ((*p_sig)->prev != NULL)
  2875.         p_sig = &(*p_sig)->prev;

  2876.       signal = (*p_sig)->signal;
  2877.       if ((*p_sig)->info.si_signo != 0)
  2878.         ptrace (PTRACE_SETSIGINFO, lwpid_of (thread), (PTRACE_TYPE_ARG3) 0,
  2879.                 &(*p_sig)->info);

  2880.       free (*p_sig);
  2881.       *p_sig = NULL;
  2882.     }

  2883.   if (the_low_target.prepare_to_resume != NULL)
  2884.     the_low_target.prepare_to_resume (lwp);

  2885.   regcache_invalidate_thread (thread);
  2886.   errno = 0;
  2887.   lwp->stopped = 0;
  2888.   lwp->stop_reason = LWP_STOPPED_BY_NO_REASON;
  2889.   lwp->stepping = step;
  2890.   ptrace (step ? PTRACE_SINGLESTEP : PTRACE_CONT, lwpid_of (thread),
  2891.           (PTRACE_TYPE_ARG3) 0,
  2892.           /* Coerce to a uintptr_t first to avoid potential gcc warning
  2893.              of coercing an 8 byte integer to a 4 byte pointer.  */
  2894.           (PTRACE_TYPE_ARG4) (uintptr_t) signal);

  2895.   current_thread = saved_thread;
  2896.   if (errno)
  2897.     {
  2898.       /* ESRCH from ptrace either means that the thread was already
  2899.          running (an error) or that it is gone (a race condition).  If
  2900.          it's gone, we will get a notification the next time we wait,
  2901.          so we can ignore the error.  We could differentiate these
  2902.          two, but it's tricky without waiting; the thread still exists
  2903.          as a zombie, so sending it signal 0 would succeed.  So just
  2904.          ignore ESRCH.  */
  2905.       if (errno == ESRCH)
  2906.         return;

  2907.       perror_with_name ("ptrace");
  2908.     }
  2909. }

  2910. struct thread_resume_array
  2911. {
  2912.   struct thread_resume *resume;
  2913.   size_t n;
  2914. };

  2915. /* This function is called once per thread via find_inferior.
  2916.    ARG is a pointer to a thread_resume_array struct.
  2917.    We look up the thread specified by ENTRY in ARG, and mark the thread
  2918.    with a pointer to the appropriate resume request.

  2919.    This algorithm is O(threads * resume elements), but resume elements
  2920.    is small (and will remain small at least until GDB supports thread
  2921.    suspension).  */

  2922. static int
  2923. linux_set_resume_request (struct inferior_list_entry *entry, void *arg)
  2924. {
  2925.   struct thread_info *thread = (struct thread_info *) entry;
  2926.   struct lwp_info *lwp = get_thread_lwp (thread);
  2927.   int ndx;
  2928.   struct thread_resume_array *r;

  2929.   r = arg;

  2930.   for (ndx = 0; ndx < r->n; ndx++)
  2931.     {
  2932.       ptid_t ptid = r->resume[ndx].thread;
  2933.       if (ptid_equal (ptid, minus_one_ptid)
  2934.           || ptid_equal (ptid, entry->id)
  2935.           /* Handle both 'pPID' and 'pPID.-1' as meaning 'all threads
  2936.              of PID'.  */
  2937.           || (ptid_get_pid (ptid) == pid_of (thread)
  2938.               && (ptid_is_pid (ptid)
  2939.                   || ptid_get_lwp (ptid) == -1)))
  2940.         {
  2941.           if (r->resume[ndx].kind == resume_stop
  2942.               && thread->last_resume_kind == resume_stop)
  2943.             {
  2944.               if (debug_threads)
  2945.                 debug_printf ("already %s LWP %ld at GDB's request\n",
  2946.                               (thread->last_status.kind
  2947.                                == TARGET_WAITKIND_STOPPED)
  2948.                               ? "stopped"
  2949.                               : "stopping",
  2950.                               lwpid_of (thread));

  2951.               continue;
  2952.             }

  2953.           lwp->resume = &r->resume[ndx];
  2954.           thread->last_resume_kind = lwp->resume->kind;

  2955.           lwp->step_range_start = lwp->resume->step_range_start;
  2956.           lwp->step_range_end = lwp->resume->step_range_end;

  2957.           /* If we had a deferred signal to report, dequeue one now.
  2958.              This can happen if LWP gets more than one signal while
  2959.              trying to get out of a jump pad.  */
  2960.           if (lwp->stopped
  2961.               && !lwp->status_pending_p
  2962.               && dequeue_one_deferred_signal (lwp, &lwp->status_pending))
  2963.             {
  2964.               lwp->status_pending_p = 1;

  2965.               if (debug_threads)
  2966.                 debug_printf ("Dequeueing deferred signal %d for LWP %ld, "
  2967.                               "leaving status pending.\n",
  2968.                               WSTOPSIG (lwp->status_pending),
  2969.                               lwpid_of (thread));
  2970.             }

  2971.           return 0;
  2972.         }
  2973.     }

  2974.   /* No resume action for this thread.  */
  2975.   lwp->resume = NULL;

  2976.   return 0;
  2977. }

  2978. /* find_inferior callback for linux_resume.
  2979.    Set *FLAG_P if this lwp has an interesting status pending.  */

  2980. static int
  2981. resume_status_pending_p (struct inferior_list_entry *entry, void *flag_p)
  2982. {
  2983.   struct thread_info *thread = (struct thread_info *) entry;
  2984.   struct lwp_info *lwp = get_thread_lwp (thread);

  2985.   /* LWPs which will not be resumed are not interesting, because
  2986.      we might not wait for them next time through linux_wait.  */
  2987.   if (lwp->resume == NULL)
  2988.     return 0;

  2989.   if (thread_still_has_status_pending_p (thread))
  2990.     * (int *) flag_p = 1;

  2991.   return 0;
  2992. }

  2993. /* Return 1 if this lwp that GDB wants running is stopped at an
  2994.    internal breakpoint that we need to step over.  It assumes that any
  2995.    required STOP_PC adjustment has already been propagated to the
  2996.    inferior's regcache.  */

  2997. static int
  2998. need_step_over_p (struct inferior_list_entry *entry, void *dummy)
  2999. {
  3000.   struct thread_info *thread = (struct thread_info *) entry;
  3001.   struct lwp_info *lwp = get_thread_lwp (thread);
  3002.   struct thread_info *saved_thread;
  3003.   CORE_ADDR pc;

  3004.   /* LWPs which will not be resumed are not interesting, because we
  3005.      might not wait for them next time through linux_wait.  */

  3006.   if (!lwp->stopped)
  3007.     {
  3008.       if (debug_threads)
  3009.         debug_printf ("Need step over [LWP %ld]? Ignoring, not stopped\n",
  3010.                       lwpid_of (thread));
  3011.       return 0;
  3012.     }

  3013.   if (thread->last_resume_kind == resume_stop)
  3014.     {
  3015.       if (debug_threads)
  3016.         debug_printf ("Need step over [LWP %ld]? Ignoring, should remain"
  3017.                       " stopped\n",
  3018.                       lwpid_of (thread));
  3019.       return 0;
  3020.     }

  3021.   gdb_assert (lwp->suspended >= 0);

  3022.   if (lwp->suspended)
  3023.     {
  3024.       if (debug_threads)
  3025.         debug_printf ("Need step over [LWP %ld]? Ignoring, suspended\n",
  3026.                       lwpid_of (thread));
  3027.       return 0;
  3028.     }

  3029.   if (!lwp->need_step_over)
  3030.     {
  3031.       if (debug_threads)
  3032.         debug_printf ("Need step over [LWP %ld]? No\n", lwpid_of (thread));
  3033.     }

  3034.   if (lwp->status_pending_p)
  3035.     {
  3036.       if (debug_threads)
  3037.         debug_printf ("Need step over [LWP %ld]? Ignoring, has pending"
  3038.                       " status.\n",
  3039.                       lwpid_of (thread));
  3040.       return 0;
  3041.     }

  3042.   /* Note: PC, not STOP_PC.  Either GDB has adjusted the PC already,
  3043.      or we have.  */
  3044.   pc = get_pc (lwp);

  3045.   /* If the PC has changed since we stopped, then don't do anything,
  3046.      and let the breakpoint/tracepoint be hit.  This happens if, for
  3047.      instance, GDB handled the decr_pc_after_break subtraction itself,
  3048.      GDB is OOL stepping this thread, or the user has issued a "jump"
  3049.      command, or poked thread's registers herself.  */
  3050.   if (pc != lwp->stop_pc)
  3051.     {
  3052.       if (debug_threads)
  3053.         debug_printf ("Need step over [LWP %ld]? Cancelling, PC was changed. "
  3054.                       "Old stop_pc was 0x%s, PC is now 0x%s\n",
  3055.                       lwpid_of (thread),
  3056.                       paddress (lwp->stop_pc), paddress (pc));

  3057.       lwp->need_step_over = 0;
  3058.       return 0;
  3059.     }

  3060.   saved_thread = current_thread;
  3061.   current_thread = thread;

  3062.   /* We can only step over breakpoints we know about.  */
  3063.   if (breakpoint_here (pc) || fast_tracepoint_jump_here (pc))
  3064.     {
  3065.       /* Don't step over a breakpoint that GDB expects to hit
  3066.          though.  If the condition is being evaluated on the target's side
  3067.          and it evaluate to false, step over this breakpoint as well.  */
  3068.       if (gdb_breakpoint_here (pc)
  3069.           && gdb_condition_true_at_breakpoint (pc)
  3070.           && gdb_no_commands_at_breakpoint (pc))
  3071.         {
  3072.           if (debug_threads)
  3073.             debug_printf ("Need step over [LWP %ld]? yes, but found"
  3074.                           " GDB breakpoint at 0x%s; skipping step over\n",
  3075.                           lwpid_of (thread), paddress (pc));

  3076.           current_thread = saved_thread;
  3077.           return 0;
  3078.         }
  3079.       else
  3080.         {
  3081.           if (debug_threads)
  3082.             debug_printf ("Need step over [LWP %ld]? yes, "
  3083.                           "found breakpoint at 0x%s\n",
  3084.                           lwpid_of (thread), paddress (pc));

  3085.           /* We've found an lwp that needs stepping over --- return 1 so
  3086.              that find_inferior stops looking.  */
  3087.           current_thread = saved_thread;

  3088.           /* If the step over is cancelled, this is set again.  */
  3089.           lwp->need_step_over = 0;
  3090.           return 1;
  3091.         }
  3092.     }

  3093.   current_thread = saved_thread;

  3094.   if (debug_threads)
  3095.     debug_printf ("Need step over [LWP %ld]? No, no breakpoint found"
  3096.                   " at 0x%s\n",
  3097.                   lwpid_of (thread), paddress (pc));

  3098.   return 0;
  3099. }

  3100. /* Start a step-over operation on LWP.  When LWP stopped at a
  3101.    breakpoint, to make progress, we need to remove the breakpoint out
  3102.    of the way.  If we let other threads run while we do that, they may
  3103.    pass by the breakpoint location and miss hitting it.  To avoid
  3104.    that, a step-over momentarily stops all threads while LWP is
  3105.    single-stepped while the breakpoint is temporarily uninserted from
  3106.    the inferior.  When the single-step finishes, we reinsert the
  3107.    breakpoint, and let all threads that are supposed to be running,
  3108.    run again.

  3109.    On targets that don't support hardware single-step, we don't
  3110.    currently support full software single-stepping.  Instead, we only
  3111.    support stepping over the thread event breakpoint, by asking the
  3112.    low target where to place a reinsert breakpoint.  Since this
  3113.    routine assumes the breakpoint being stepped over is a thread event
  3114.    breakpoint, it usually assumes the return address of the current
  3115.    function is a good enough place to set the reinsert breakpoint.  */

  3116. static int
  3117. start_step_over (struct lwp_info *lwp)
  3118. {
  3119.   struct thread_info *thread = get_lwp_thread (lwp);
  3120.   struct thread_info *saved_thread;
  3121.   CORE_ADDR pc;
  3122.   int step;

  3123.   if (debug_threads)
  3124.     debug_printf ("Starting step-over on LWP %ld.  Stopping all threads\n",
  3125.                   lwpid_of (thread));

  3126.   stop_all_lwps (1, lwp);
  3127.   gdb_assert (lwp->suspended == 0);

  3128.   if (debug_threads)
  3129.     debug_printf ("Done stopping all threads for step-over.\n");

  3130.   /* Note, we should always reach here with an already adjusted PC,
  3131.      either by GDB (if we're resuming due to GDB's request), or by our
  3132.      caller, if we just finished handling an internal breakpoint GDB
  3133.      shouldn't care about.  */
  3134.   pc = get_pc (lwp);

  3135.   saved_thread = current_thread;
  3136.   current_thread = thread;

  3137.   lwp->bp_reinsert = pc;
  3138.   uninsert_breakpoints_at (pc);
  3139.   uninsert_fast_tracepoint_jumps_at (pc);

  3140.   if (can_hardware_single_step ())
  3141.     {
  3142.       step = 1;
  3143.     }
  3144.   else
  3145.     {
  3146.       CORE_ADDR raddr = (*the_low_target.breakpoint_reinsert_addr) ();
  3147.       set_reinsert_breakpoint (raddr);
  3148.       step = 0;
  3149.     }

  3150.   current_thread = saved_thread;

  3151.   linux_resume_one_lwp (lwp, step, 0, NULL);

  3152.   /* Require next event from this LWP.  */
  3153.   step_over_bkpt = thread->entry.id;
  3154.   return 1;
  3155. }

  3156. /* Finish a step-over.  Reinsert the breakpoint we had uninserted in
  3157.    start_step_over, if still there, and delete any reinsert
  3158.    breakpoints we've set, on non hardware single-step targets.  */

  3159. static int
  3160. finish_step_over (struct lwp_info *lwp)
  3161. {
  3162.   if (lwp->bp_reinsert != 0)
  3163.     {
  3164.       if (debug_threads)
  3165.         debug_printf ("Finished step over.\n");

  3166.       /* Reinsert any breakpoint at LWP->BP_REINSERT.  Note that there
  3167.          may be no breakpoint to reinsert there by now.  */
  3168.       reinsert_breakpoints_at (lwp->bp_reinsert);
  3169.       reinsert_fast_tracepoint_jumps_at (lwp->bp_reinsert);

  3170.       lwp->bp_reinsert = 0;

  3171.       /* Delete any software-single-step reinsert breakpoints.  No
  3172.          longer needed.  We don't have to worry about other threads
  3173.          hitting this trap, and later not being able to explain it,
  3174.          because we were stepping over a breakpoint, and we hold all
  3175.          threads but LWP stopped while doing that.  */
  3176.       if (!can_hardware_single_step ())
  3177.         delete_reinsert_breakpoints ();

  3178.       step_over_bkpt = null_ptid;
  3179.       return 1;
  3180.     }
  3181.   else
  3182.     return 0;
  3183. }

  3184. /* This function is called once per thread.  We check the thread's resume
  3185.    request, which will tell us whether to resume, step, or leave the thread
  3186.    stopped; and what signal, if any, it should be sent.

  3187.    For threads which we aren't explicitly told otherwise, we preserve
  3188.    the stepping flag; this is used for stepping over gdbserver-placed
  3189.    breakpoints.

  3190.    If pending_flags was set in any thread, we queue any needed
  3191.    signals, since we won't actually resume.  We already have a pending
  3192.    event to report, so we don't need to preserve any step requests;
  3193.    they should be re-issued if necessary.  */

  3194. static int
  3195. linux_resume_one_thread (struct inferior_list_entry *entry, void *arg)
  3196. {
  3197.   struct thread_info *thread = (struct thread_info *) entry;
  3198.   struct lwp_info *lwp = get_thread_lwp (thread);
  3199.   int step;
  3200.   int leave_all_stopped = * (int *) arg;
  3201.   int leave_pending;

  3202.   if (lwp->resume == NULL)
  3203.     return 0;

  3204.   if (lwp->resume->kind == resume_stop)
  3205.     {
  3206.       if (debug_threads)
  3207.         debug_printf ("resume_stop request for LWP %ld\n", lwpid_of (thread));

  3208.       if (!lwp->stopped)
  3209.         {
  3210.           if (debug_threads)
  3211.             debug_printf ("stopping LWP %ld\n", lwpid_of (thread));

  3212.           /* Stop the thread, and wait for the event asynchronously,
  3213.              through the event loop.  */
  3214.           send_sigstop (lwp);
  3215.         }
  3216.       else
  3217.         {
  3218.           if (debug_threads)
  3219.             debug_printf ("already stopped LWP %ld\n",
  3220.                           lwpid_of (thread));

  3221.           /* The LWP may have been stopped in an internal event that
  3222.              was not meant to be notified back to GDB (e.g., gdbserver
  3223.              breakpoint), so we should be reporting a stop event in
  3224.              this case too.  */

  3225.           /* If the thread already has a pending SIGSTOP, this is a
  3226.              no-op.  Otherwise, something later will presumably resume
  3227.              the thread and this will cause it to cancel any pending
  3228.              operation, due to last_resume_kind == resume_stop.  If
  3229.              the thread already has a pending status to report, we
  3230.              will still report it the next time we wait - see
  3231.              status_pending_p_callback.  */

  3232.           /* If we already have a pending signal to report, then
  3233.              there's no need to queue a SIGSTOP, as this means we're
  3234.              midway through moving the LWP out of the jumppad, and we
  3235.              will report the pending signal as soon as that is
  3236.              finished.  */
  3237.           if (lwp->pending_signals_to_report == NULL)
  3238.             send_sigstop (lwp);
  3239.         }

  3240.       /* For stop requests, we're done.  */
  3241.       lwp->resume = NULL;
  3242.       thread->last_status.kind = TARGET_WAITKIND_IGNORE;
  3243.       return 0;
  3244.     }

  3245.   /* If this thread which is about to be resumed has a pending status,
  3246.      then don't resume any threads - we can just report the pending
  3247.      status.  Make sure to queue any signals that would otherwise be
  3248.      sent.  In all-stop mode, we do this decision based on if *any*
  3249.      thread has a pending status.  If there's a thread that needs the
  3250.      step-over-breakpoint dance, then don't resume any other thread
  3251.      but that particular one.  */
  3252.   leave_pending = (lwp->status_pending_p || leave_all_stopped);

  3253.   if (!leave_pending)
  3254.     {
  3255.       if (debug_threads)
  3256.         debug_printf ("resuming LWP %ld\n", lwpid_of (thread));

  3257.       step = (lwp->resume->kind == resume_step);
  3258.       linux_resume_one_lwp (lwp, step, lwp->resume->sig, NULL);
  3259.     }
  3260.   else
  3261.     {
  3262.       if (debug_threads)
  3263.         debug_printf ("leaving LWP %ld stopped\n", lwpid_of (thread));

  3264.       /* If we have a new signal, enqueue the signal.  */
  3265.       if (lwp->resume->sig != 0)
  3266.         {
  3267.           struct pending_signals *p_sig;
  3268.           p_sig = xmalloc (sizeof (*p_sig));
  3269.           p_sig->prev = lwp->pending_signals;
  3270.           p_sig->signal = lwp->resume->sig;
  3271.           memset (&p_sig->info, 0, sizeof (siginfo_t));

  3272.           /* If this is the same signal we were previously stopped by,
  3273.              make sure to queue its siginfo.  We can ignore the return
  3274.              value of ptrace; if it fails, we'll skip
  3275.              PTRACE_SETSIGINFO.  */
  3276.           if (WIFSTOPPED (lwp->last_status)
  3277.               && WSTOPSIG (lwp->last_status) == lwp->resume->sig)
  3278.             ptrace (PTRACE_GETSIGINFO, lwpid_of (thread), (PTRACE_TYPE_ARG3) 0,
  3279.                     &p_sig->info);

  3280.           lwp->pending_signals = p_sig;
  3281.         }
  3282.     }

  3283.   thread->last_status.kind = TARGET_WAITKIND_IGNORE;
  3284.   lwp->resume = NULL;
  3285.   return 0;
  3286. }

  3287. static void
  3288. linux_resume (struct thread_resume *resume_info, size_t n)
  3289. {
  3290.   struct thread_resume_array array = { resume_info, n };
  3291.   struct thread_info *need_step_over = NULL;
  3292.   int any_pending;
  3293.   int leave_all_stopped;

  3294.   if (debug_threads)
  3295.     {
  3296.       debug_enter ();
  3297.       debug_printf ("linux_resume:\n");
  3298.     }

  3299.   find_inferior (&all_threads, linux_set_resume_request, &array);

  3300.   /* If there is a thread which would otherwise be resumed, which has
  3301.      a pending status, then don't resume any threads - we can just
  3302.      report the pending status.  Make sure to queue any signals that
  3303.      would otherwise be sent.  In non-stop mode, we'll apply this
  3304.      logic to each thread individually.  We consume all pending events
  3305.      before considering to start a step-over (in all-stop).  */
  3306.   any_pending = 0;
  3307.   if (!non_stop)
  3308.     find_inferior (&all_threads, resume_status_pending_p, &any_pending);

  3309.   /* If there is a thread which would otherwise be resumed, which is
  3310.      stopped at a breakpoint that needs stepping over, then don't
  3311.      resume any threads - have it step over the breakpoint with all
  3312.      other threads stopped, then resume all threads again.  Make sure
  3313.      to queue any signals that would otherwise be delivered or
  3314.      queued.  */
  3315.   if (!any_pending && supports_breakpoints ())
  3316.     need_step_over
  3317.       = (struct thread_info *) find_inferior (&all_threads,
  3318.                                               need_step_over_p, NULL);

  3319.   leave_all_stopped = (need_step_over != NULL || any_pending);

  3320.   if (debug_threads)
  3321.     {
  3322.       if (need_step_over != NULL)
  3323.         debug_printf ("Not resuming all, need step over\n");
  3324.       else if (any_pending)
  3325.         debug_printf ("Not resuming, all-stop and found "
  3326.                       "an LWP with pending status\n");
  3327.       else
  3328.         debug_printf ("Resuming, no pending status or step over needed\n");
  3329.     }

  3330.   /* Even if we're leaving threads stopped, queue all signals we'd
  3331.      otherwise deliver.  */
  3332.   find_inferior (&all_threads, linux_resume_one_thread, &leave_all_stopped);

  3333.   if (need_step_over)
  3334.     start_step_over (get_thread_lwp (need_step_over));

  3335.   if (debug_threads)
  3336.     {
  3337.       debug_printf ("linux_resume done\n");
  3338.       debug_exit ();
  3339.     }
  3340. }

  3341. /* This function is called once per thread.  We check the thread's
  3342.    last resume request, which will tell us whether to resume, step, or
  3343.    leave the thread stopped.  Any signal the client requested to be
  3344.    delivered has already been enqueued at this point.

  3345.    If any thread that GDB wants running is stopped at an internal
  3346.    breakpoint that needs stepping over, we start a step-over operation
  3347.    on that particular thread, and leave all others stopped.  */

  3348. static int
  3349. proceed_one_lwp (struct inferior_list_entry *entry, void *except)
  3350. {
  3351.   struct thread_info *thread = (struct thread_info *) entry;
  3352.   struct lwp_info *lwp = get_thread_lwp (thread);
  3353.   int step;

  3354.   if (lwp == except)
  3355.     return 0;

  3356.   if (debug_threads)
  3357.     debug_printf ("proceed_one_lwp: lwp %ld\n", lwpid_of (thread));

  3358.   if (!lwp->stopped)
  3359.     {
  3360.       if (debug_threads)
  3361.         debug_printf ("   LWP %ld already running\n", lwpid_of (thread));
  3362.       return 0;
  3363.     }

  3364.   if (thread->last_resume_kind == resume_stop
  3365.       && thread->last_status.kind != TARGET_WAITKIND_IGNORE)
  3366.     {
  3367.       if (debug_threads)
  3368.         debug_printf ("   client wants LWP to remain %ld stopped\n",
  3369.                       lwpid_of (thread));
  3370.       return 0;
  3371.     }

  3372.   if (lwp->status_pending_p)
  3373.     {
  3374.       if (debug_threads)
  3375.         debug_printf ("   LWP %ld has pending status, leaving stopped\n",
  3376.                       lwpid_of (thread));
  3377.       return 0;
  3378.     }

  3379.   gdb_assert (lwp->suspended >= 0);

  3380.   if (lwp->suspended)
  3381.     {
  3382.       if (debug_threads)
  3383.         debug_printf ("   LWP %ld is suspended\n", lwpid_of (thread));
  3384.       return 0;
  3385.     }

  3386.   if (thread->last_resume_kind == resume_stop
  3387.       && lwp->pending_signals_to_report == NULL
  3388.       && lwp->collecting_fast_tracepoint == 0)
  3389.     {
  3390.       /* We haven't reported this LWP as stopped yet (otherwise, the
  3391.          last_status.kind check above would catch it, and we wouldn't
  3392.          reach here.  This LWP may have been momentarily paused by a
  3393.          stop_all_lwps call while handling for example, another LWP's
  3394.          step-over.  In that case, the pending expected SIGSTOP signal
  3395.          that was queued at vCont;t handling time will have already
  3396.          been consumed by wait_for_sigstop, and so we need to requeue
  3397.          another one here.  Note that if the LWP already has a SIGSTOP
  3398.          pending, this is a no-op.  */

  3399.       if (debug_threads)
  3400.         debug_printf ("Client wants LWP %ld to stop. "
  3401.                       "Making sure it has a SIGSTOP pending\n",
  3402.                       lwpid_of (thread));

  3403.       send_sigstop (lwp);
  3404.     }

  3405.   step = thread->last_resume_kind == resume_step;
  3406.   linux_resume_one_lwp (lwp, step, 0, NULL);
  3407.   return 0;
  3408. }

  3409. static int
  3410. unsuspend_and_proceed_one_lwp (struct inferior_list_entry *entry, void *except)
  3411. {
  3412.   struct thread_info *thread = (struct thread_info *) entry;
  3413.   struct lwp_info *lwp = get_thread_lwp (thread);

  3414.   if (lwp == except)
  3415.     return 0;

  3416.   lwp->suspended--;
  3417.   gdb_assert (lwp->suspended >= 0);

  3418.   return proceed_one_lwp (entry, except);
  3419. }

  3420. /* When we finish a step-over, set threads running again.  If there's
  3421.    another thread that may need a step-over, now's the time to start
  3422.    it.  Eventually, we'll move all threads past their breakpoints.  */

  3423. static void
  3424. proceed_all_lwps (void)
  3425. {
  3426.   struct thread_info *need_step_over;

  3427.   /* If there is a thread which would otherwise be resumed, which is
  3428.      stopped at a breakpoint that needs stepping over, then don't
  3429.      resume any threads - have it step over the breakpoint with all
  3430.      other threads stopped, then resume all threads again.  */

  3431.   if (supports_breakpoints ())
  3432.     {
  3433.       need_step_over
  3434.         = (struct thread_info *) find_inferior (&all_threads,
  3435.                                                 need_step_over_p, NULL);

  3436.       if (need_step_over != NULL)
  3437.         {
  3438.           if (debug_threads)
  3439.             debug_printf ("proceed_all_lwps: found "
  3440.                           "thread %ld needing a step-over\n",
  3441.                           lwpid_of (need_step_over));

  3442.           start_step_over (get_thread_lwp (need_step_over));
  3443.           return;
  3444.         }
  3445.     }

  3446.   if (debug_threads)
  3447.     debug_printf ("Proceeding, no step-over needed\n");

  3448.   find_inferior (&all_threads, proceed_one_lwp, NULL);
  3449. }

  3450. /* Stopped LWPs that the client wanted to be running, that don't have
  3451.    pending statuses, are set to run again, except for EXCEPT, if not
  3452.    NULL.  This undoes a stop_all_lwps call.  */

  3453. static void
  3454. unstop_all_lwps (int unsuspend, struct lwp_info *except)
  3455. {
  3456.   if (debug_threads)
  3457.     {
  3458.       debug_enter ();
  3459.       if (except)
  3460.         debug_printf ("unstopping all lwps, except=(LWP %ld)\n",
  3461.                       lwpid_of (get_lwp_thread (except)));
  3462.       else
  3463.         debug_printf ("unstopping all lwps\n");
  3464.     }

  3465.   if (unsuspend)
  3466.     find_inferior (&all_threads, unsuspend_and_proceed_one_lwp, except);
  3467.   else
  3468.     find_inferior (&all_threads, proceed_one_lwp, except);

  3469.   if (debug_threads)
  3470.     {
  3471.       debug_printf ("unstop_all_lwps done\n");
  3472.       debug_exit ();
  3473.     }
  3474. }


  3475. #ifdef HAVE_LINUX_REGSETS

  3476. #define use_linux_regsets 1

  3477. /* Returns true if REGSET has been disabled.  */

  3478. static int
  3479. regset_disabled (struct regsets_info *info, struct regset_info *regset)
  3480. {
  3481.   return (info->disabled_regsets != NULL
  3482.           && info->disabled_regsets[regset - info->regsets]);
  3483. }

  3484. /* Disable REGSET.  */

  3485. static void
  3486. disable_regset (struct regsets_info *info, struct regset_info *regset)
  3487. {
  3488.   int dr_offset;

  3489.   dr_offset = regset - info->regsets;
  3490.   if (info->disabled_regsets == NULL)
  3491.     info->disabled_regsets = xcalloc (1, info->num_regsets);
  3492.   info->disabled_regsets[dr_offset] = 1;
  3493. }

  3494. static int
  3495. regsets_fetch_inferior_registers (struct regsets_info *regsets_info,
  3496.                                   struct regcache *regcache)
  3497. {
  3498.   struct regset_info *regset;
  3499.   int saw_general_regs = 0;
  3500.   int pid;
  3501.   struct iovec iov;

  3502.   pid = lwpid_of (current_thread);
  3503.   for (regset = regsets_info->regsets; regset->size >= 0; regset++)
  3504.     {
  3505.       void *buf, *data;
  3506.       int nt_type, res;

  3507.       if (regset->size == 0 || regset_disabled (regsets_info, regset))
  3508.         continue;

  3509.       buf = xmalloc (regset->size);

  3510.       nt_type = regset->nt_type;
  3511.       if (nt_type)
  3512.         {
  3513.           iov.iov_base = buf;
  3514.           iov.iov_len = regset->size;
  3515.           data = (void *) &iov;
  3516.         }
  3517.       else
  3518.         data = buf;

  3519. #ifndef __sparc__
  3520.       res = ptrace (regset->get_request, pid,
  3521.                     (PTRACE_TYPE_ARG3) (long) nt_type, data);
  3522. #else
  3523.       res = ptrace (regset->get_request, pid, data, nt_type);
  3524. #endif
  3525.       if (res < 0)
  3526.         {
  3527.           if (errno == EIO)
  3528.             {
  3529.               /* If we get EIO on a regset, do not try it again for
  3530.                  this process mode.  */
  3531.               disable_regset (regsets_info, regset);
  3532.             }
  3533.           else if (errno == ENODATA)
  3534.             {
  3535.               /* ENODATA may be returned if the regset is currently
  3536.                  not "active".  This can happen in normal operation,
  3537.                  so suppress the warning in this case.  */
  3538.             }
  3539.           else
  3540.             {
  3541.               char s[256];
  3542.               sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%d",
  3543.                        pid);
  3544.               perror (s);
  3545.             }
  3546.         }
  3547.       else
  3548.         {
  3549.           if (regset->type == GENERAL_REGS)
  3550.             saw_general_regs = 1;
  3551.           regset->store_function (regcache, buf);
  3552.         }
  3553.       free (buf);
  3554.     }
  3555.   if (saw_general_regs)
  3556.     return 0;
  3557.   else
  3558.     return 1;
  3559. }

  3560. static int
  3561. regsets_store_inferior_registers (struct regsets_info *regsets_info,
  3562.                                   struct regcache *regcache)
  3563. {
  3564.   struct regset_info *regset;
  3565.   int saw_general_regs = 0;
  3566.   int pid;
  3567.   struct iovec iov;

  3568.   pid = lwpid_of (current_thread);
  3569.   for (regset = regsets_info->regsets; regset->size >= 0; regset++)
  3570.     {
  3571.       void *buf, *data;
  3572.       int nt_type, res;

  3573.       if (regset->size == 0 || regset_disabled (regsets_info, regset)
  3574.           || regset->fill_function == NULL)
  3575.         continue;

  3576.       buf = xmalloc (regset->size);

  3577.       /* First fill the buffer with the current register set contents,
  3578.          in case there are any items in the kernel's regset that are
  3579.          not in gdbserver's regcache.  */

  3580.       nt_type = regset->nt_type;
  3581.       if (nt_type)
  3582.         {
  3583.           iov.iov_base = buf;
  3584.           iov.iov_len = regset->size;
  3585.           data = (void *) &iov;
  3586.         }
  3587.       else
  3588.         data = buf;

  3589. #ifndef __sparc__
  3590.       res = ptrace (regset->get_request, pid,
  3591.                     (PTRACE_TYPE_ARG3) (long) nt_type, data);
  3592. #else
  3593.       res = ptrace (regset->get_request, pid, data, nt_type);
  3594. #endif

  3595.       if (res == 0)
  3596.         {
  3597.           /* Then overlay our cached registers on that.  */
  3598.           regset->fill_function (regcache, buf);

  3599.           /* Only now do we write the register set.  */
  3600. #ifndef __sparc__
  3601.           res = ptrace (regset->set_request, pid,
  3602.                         (PTRACE_TYPE_ARG3) (long) nt_type, data);
  3603. #else
  3604.           res = ptrace (regset->set_request, pid, data, nt_type);
  3605. #endif
  3606.         }

  3607.       if (res < 0)
  3608.         {
  3609.           if (errno == EIO)
  3610.             {
  3611.               /* If we get EIO on a regset, do not try it again for
  3612.                  this process mode.  */
  3613.               disable_regset (regsets_info, regset);
  3614.             }
  3615.           else if (errno == ESRCH)
  3616.             {
  3617.               /* At this point, ESRCH should mean the process is
  3618.                  already gone, in which case we simply ignore attempts
  3619.                  to change its registers.  See also the related
  3620.                  comment in linux_resume_one_lwp.  */
  3621.               free (buf);
  3622.               return 0;
  3623.             }
  3624.           else
  3625.             {
  3626.               perror ("Warning: ptrace(regsets_store_inferior_registers)");
  3627.             }
  3628.         }
  3629.       else if (regset->type == GENERAL_REGS)
  3630.         saw_general_regs = 1;
  3631.       free (buf);
  3632.     }
  3633.   if (saw_general_regs)
  3634.     return 0;
  3635.   else
  3636.     return 1;
  3637. }

  3638. #else /* !HAVE_LINUX_REGSETS */

  3639. #define use_linux_regsets 0
  3640. #define regsets_fetch_inferior_registers(regsets_info, regcache) 1
  3641. #define regsets_store_inferior_registers(regsets_info, regcache) 1

  3642. #endif

  3643. /* Return 1 if register REGNO is supported by one of the regset ptrace
  3644.    calls or 0 if it has to be transferred individually.  */

  3645. static int
  3646. linux_register_in_regsets (const struct regs_info *regs_info, int regno)
  3647. {
  3648.   unsigned char mask = 1 << (regno % 8);
  3649.   size_t index = regno / 8;

  3650.   return (use_linux_regsets
  3651.           && (regs_info->regset_bitmap == NULL
  3652.               || (regs_info->regset_bitmap[index] & mask) != 0));
  3653. }

  3654. #ifdef HAVE_LINUX_USRREGS

  3655. int
  3656. register_addr (const struct usrregs_info *usrregs, int regnum)
  3657. {
  3658.   int addr;

  3659.   if (regnum < 0 || regnum >= usrregs->num_regs)
  3660.     error ("Invalid register number %d.", regnum);

  3661.   addr = usrregs->regmap[regnum];

  3662.   return addr;
  3663. }

  3664. /* Fetch one register.  */
  3665. static void
  3666. fetch_register (const struct usrregs_info *usrregs,
  3667.                 struct regcache *regcache, int regno)
  3668. {
  3669.   CORE_ADDR regaddr;
  3670.   int i, size;
  3671.   char *buf;
  3672.   int pid;

  3673.   if (regno >= usrregs->num_regs)
  3674.     return;
  3675.   if ((*the_low_target.cannot_fetch_register) (regno))
  3676.     return;

  3677.   regaddr = register_addr (usrregs, regno);
  3678.   if (regaddr == -1)
  3679.     return;

  3680.   size = ((register_size (regcache->tdesc, regno)
  3681.            + sizeof (PTRACE_XFER_TYPE) - 1)
  3682.           & -sizeof (PTRACE_XFER_TYPE));
  3683.   buf = alloca (size);

  3684.   pid = lwpid_of (current_thread);
  3685.   for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
  3686.     {
  3687.       errno = 0;
  3688.       *(PTRACE_XFER_TYPE *) (buf + i) =
  3689.         ptrace (PTRACE_PEEKUSER, pid,
  3690.                 /* Coerce to a uintptr_t first to avoid potential gcc warning
  3691.                    of coercing an 8 byte integer to a 4 byte pointer.  */
  3692.                 (PTRACE_TYPE_ARG3) (uintptr_t) regaddr, (PTRACE_TYPE_ARG4) 0);
  3693.       regaddr += sizeof (PTRACE_XFER_TYPE);
  3694.       if (errno != 0)
  3695.         error ("reading register %d: %s", regno, strerror (errno));
  3696.     }

  3697.   if (the_low_target.supply_ptrace_register)
  3698.     the_low_target.supply_ptrace_register (regcache, regno, buf);
  3699.   else
  3700.     supply_register (regcache, regno, buf);
  3701. }

  3702. /* Store one register.  */
  3703. static void
  3704. store_register (const struct usrregs_info *usrregs,
  3705.                 struct regcache *regcache, int regno)
  3706. {
  3707.   CORE_ADDR regaddr;
  3708.   int i, size;
  3709.   char *buf;
  3710.   int pid;

  3711.   if (regno >= usrregs->num_regs)
  3712.     return;
  3713.   if ((*the_low_target.cannot_store_register) (regno))
  3714.     return;

  3715.   regaddr = register_addr (usrregs, regno);
  3716.   if (regaddr == -1)
  3717.     return;

  3718.   size = ((register_size (regcache->tdesc, regno)
  3719.            + sizeof (PTRACE_XFER_TYPE) - 1)
  3720.           & -sizeof (PTRACE_XFER_TYPE));
  3721.   buf = alloca (size);
  3722.   memset (buf, 0, size);

  3723.   if (the_low_target.collect_ptrace_register)
  3724.     the_low_target.collect_ptrace_register (regcache, regno, buf);
  3725.   else
  3726.     collect_register (regcache, regno, buf);

  3727.   pid = lwpid_of (current_thread);
  3728.   for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
  3729.     {
  3730.       errno = 0;
  3731.       ptrace (PTRACE_POKEUSER, pid,
  3732.             /* Coerce to a uintptr_t first to avoid potential gcc warning
  3733.                about coercing an 8 byte integer to a 4 byte pointer.  */
  3734.               (PTRACE_TYPE_ARG3) (uintptr_t) regaddr,
  3735.               (PTRACE_TYPE_ARG4) *(PTRACE_XFER_TYPE *) (buf + i));
  3736.       if (errno != 0)
  3737.         {
  3738.           /* At this point, ESRCH should mean the process is
  3739.              already gone, in which case we simply ignore attempts
  3740.              to change its registers.  See also the related
  3741.              comment in linux_resume_one_lwp.  */
  3742.           if (errno == ESRCH)
  3743.             return;

  3744.           if ((*the_low_target.cannot_store_register) (regno) == 0)
  3745.             error ("writing register %d: %s", regno, strerror (errno));
  3746.         }
  3747.       regaddr += sizeof (PTRACE_XFER_TYPE);
  3748.     }
  3749. }

  3750. /* Fetch all registers, or just one, from the child process.
  3751.    If REGNO is -1, do this for all registers, skipping any that are
  3752.    assumed to have been retrieved by regsets_fetch_inferior_registers,
  3753.    unless ALL is non-zero.
  3754.    Otherwise, REGNO specifies which register (so we can save time).  */
  3755. static void
  3756. usr_fetch_inferior_registers (const struct regs_info *regs_info,
  3757.                               struct regcache *regcache, int regno, int all)
  3758. {
  3759.   struct usrregs_info *usr = regs_info->usrregs;

  3760.   if (regno == -1)
  3761.     {
  3762.       for (regno = 0; regno < usr->num_regs; regno++)
  3763.         if (all || !linux_register_in_regsets (regs_info, regno))
  3764.           fetch_register (usr, regcache, regno);
  3765.     }
  3766.   else
  3767.     fetch_register (usr, regcache, regno);
  3768. }

  3769. /* Store our register values back into the inferior.
  3770.    If REGNO is -1, do this for all registers, skipping any that are
  3771.    assumed to have been saved by regsets_store_inferior_registers,
  3772.    unless ALL is non-zero.
  3773.    Otherwise, REGNO specifies which register (so we can save time).  */
  3774. static void
  3775. usr_store_inferior_registers (const struct regs_info *regs_info,
  3776.                               struct regcache *regcache, int regno, int all)
  3777. {
  3778.   struct usrregs_info *usr = regs_info->usrregs;

  3779.   if (regno == -1)
  3780.     {
  3781.       for (regno = 0; regno < usr->num_regs; regno++)
  3782.         if (all || !linux_register_in_regsets (regs_info, regno))
  3783.           store_register (usr, regcache, regno);
  3784.     }
  3785.   else
  3786.     store_register (usr, regcache, regno);
  3787. }

  3788. #else /* !HAVE_LINUX_USRREGS */

  3789. #define usr_fetch_inferior_registers(regs_info, regcache, regno, all) do {} while (0)
  3790. #define usr_store_inferior_registers(regs_info, regcache, regno, all) do {} while (0)

  3791. #endif


  3792. void
  3793. linux_fetch_registers (struct regcache *regcache, int regno)
  3794. {
  3795.   int use_regsets;
  3796.   int all = 0;
  3797.   const struct regs_info *regs_info = (*the_low_target.regs_info) ();

  3798.   if (regno == -1)
  3799.     {
  3800.       if (the_low_target.fetch_register != NULL
  3801.           && regs_info->usrregs != NULL)
  3802.         for (regno = 0; regno < regs_info->usrregs->num_regs; regno++)
  3803.           (*the_low_target.fetch_register) (regcache, regno);

  3804.       all = regsets_fetch_inferior_registers (regs_info->regsets_info, regcache);
  3805.       if (regs_info->usrregs != NULL)
  3806.         usr_fetch_inferior_registers (regs_info, regcache, -1, all);
  3807.     }
  3808.   else
  3809.     {
  3810.       if (the_low_target.fetch_register != NULL
  3811.           && (*the_low_target.fetch_register) (regcache, regno))
  3812.         return;

  3813.       use_regsets = linux_register_in_regsets (regs_info, regno);
  3814.       if (use_regsets)
  3815.         all = regsets_fetch_inferior_registers (regs_info->regsets_info,
  3816.                                                 regcache);
  3817.       if ((!use_regsets || all) && regs_info->usrregs != NULL)
  3818.         usr_fetch_inferior_registers (regs_info, regcache, regno, 1);
  3819.     }
  3820. }

  3821. void
  3822. linux_store_registers (struct regcache *regcache, int regno)
  3823. {
  3824.   int use_regsets;
  3825.   int all = 0;
  3826.   const struct regs_info *regs_info = (*the_low_target.regs_info) ();

  3827.   if (regno == -1)
  3828.     {
  3829.       all = regsets_store_inferior_registers (regs_info->regsets_info,
  3830.                                               regcache);
  3831.       if (regs_info->usrregs != NULL)
  3832.         usr_store_inferior_registers (regs_info, regcache, regno, all);
  3833.     }
  3834.   else
  3835.     {
  3836.       use_regsets = linux_register_in_regsets (regs_info, regno);
  3837.       if (use_regsets)
  3838.         all = regsets_store_inferior_registers (regs_info->regsets_info,
  3839.                                                 regcache);
  3840.       if ((!use_regsets || all) && regs_info->usrregs != NULL)
  3841.         usr_store_inferior_registers (regs_info, regcache, regno, 1);
  3842.     }
  3843. }


  3844. /* Copy LEN bytes from inferior's memory starting at MEMADDR
  3845.    to debugger memory starting at MYADDR.  */

  3846. static int
  3847. linux_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
  3848. {
  3849.   int pid = lwpid_of (current_thread);
  3850.   register PTRACE_XFER_TYPE *buffer;
  3851.   register CORE_ADDR addr;
  3852.   register int count;
  3853.   char filename[64];
  3854.   register int i;
  3855.   int ret;
  3856.   int fd;

  3857.   /* Try using /proc.  Don't bother for one word.  */
  3858.   if (len >= 3 * sizeof (long))
  3859.     {
  3860.       int bytes;

  3861.       /* We could keep this file open and cache it - possibly one per
  3862.          thread.  That requires some juggling, but is even faster.  */
  3863.       sprintf (filename, "/proc/%d/mem", pid);
  3864.       fd = open (filename, O_RDONLY | O_LARGEFILE);
  3865.       if (fd == -1)
  3866.         goto no_proc;

  3867.       /* If pread64 is available, use it.  It's faster if the kernel
  3868.          supports it (only one syscall), and it's 64-bit safe even on
  3869.          32-bit platforms (for instance, SPARC debugging a SPARC64
  3870.          application).  */
  3871. #ifdef HAVE_PREAD64
  3872.       bytes = pread64 (fd, myaddr, len, memaddr);
  3873. #else
  3874.       bytes = -1;
  3875.       if (lseek (fd, memaddr, SEEK_SET) != -1)
  3876.         bytes = read (fd, myaddr, len);
  3877. #endif

  3878.       close (fd);
  3879.       if (bytes == len)
  3880.         return 0;

  3881.       /* Some data was read, we'll try to get the rest with ptrace.  */
  3882.       if (bytes > 0)
  3883.         {
  3884.           memaddr += bytes;
  3885.           myaddr += bytes;
  3886.           len -= bytes;
  3887.         }
  3888.     }

  3889. no_proc:
  3890.   /* Round starting address down to longword boundary.  */
  3891.   addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
  3892.   /* Round ending address up; get number of longwords that makes.  */
  3893.   count = ((((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
  3894.            / sizeof (PTRACE_XFER_TYPE));
  3895.   /* Allocate buffer of that many longwords.  */
  3896.   buffer = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));

  3897.   /* Read all the longwords */
  3898.   errno = 0;
  3899.   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
  3900.     {
  3901.       /* Coerce the 3rd arg to a uintptr_t first to avoid potential gcc warning
  3902.          about coercing an 8 byte integer to a 4 byte pointer.  */
  3903.       buffer[i] = ptrace (PTRACE_PEEKTEXT, pid,
  3904.                           (PTRACE_TYPE_ARG3) (uintptr_t) addr,
  3905.                           (PTRACE_TYPE_ARG4) 0);
  3906.       if (errno)
  3907.         break;
  3908.     }
  3909.   ret = errno;

  3910.   /* Copy appropriate bytes out of the buffer.  */
  3911.   if (i > 0)
  3912.     {
  3913.       i *= sizeof (PTRACE_XFER_TYPE);
  3914.       i -= memaddr & (sizeof (PTRACE_XFER_TYPE) - 1);
  3915.       memcpy (myaddr,
  3916.               (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
  3917.               i < len ? i : len);
  3918.     }

  3919.   return ret;
  3920. }

  3921. /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
  3922.    memory at MEMADDR.  On failure (cannot write to the inferior)
  3923.    returns the value of errno.  Always succeeds if LEN is zero.  */

  3924. static int
  3925. linux_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
  3926. {
  3927.   register int i;
  3928.   /* Round starting address down to longword boundary.  */
  3929.   register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
  3930.   /* Round ending address up; get number of longwords that makes.  */
  3931.   register int count
  3932.     = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
  3933.     / sizeof (PTRACE_XFER_TYPE);

  3934.   /* Allocate buffer of that many longwords.  */
  3935.   register PTRACE_XFER_TYPE *buffer = (PTRACE_XFER_TYPE *)
  3936.     alloca (count * sizeof (PTRACE_XFER_TYPE));

  3937.   int pid = lwpid_of (current_thread);

  3938.   if (len == 0)
  3939.     {
  3940.       /* Zero length write always succeeds.  */
  3941.       return 0;
  3942.     }

  3943.   if (debug_threads)
  3944.     {
  3945.       /* Dump up to four bytes.  */
  3946.       unsigned int val = * (unsigned int *) myaddr;
  3947.       if (len == 1)
  3948.         val = val & 0xff;
  3949.       else if (len == 2)
  3950.         val = val & 0xffff;
  3951.       else if (len == 3)
  3952.         val = val & 0xffffff;
  3953.       debug_printf ("Writing %0*x to 0x%08lx\n", 2 * ((len < 4) ? len : 4),
  3954.                     val, (long)memaddr);
  3955.     }

  3956.   /* Fill start and end extra bytes of buffer with existing memory data.  */

  3957.   errno = 0;
  3958.   /* Coerce the 3rd arg to a uintptr_t first to avoid potential gcc warning
  3959.      about coercing an 8 byte integer to a 4 byte pointer.  */
  3960.   buffer[0] = ptrace (PTRACE_PEEKTEXT, pid,
  3961.                       (PTRACE_TYPE_ARG3) (uintptr_t) addr,
  3962.                       (PTRACE_TYPE_ARG4) 0);
  3963.   if (errno)
  3964.     return errno;

  3965.   if (count > 1)
  3966.     {
  3967.       errno = 0;
  3968.       buffer[count - 1]
  3969.         = ptrace (PTRACE_PEEKTEXT, pid,
  3970.                   /* Coerce to a uintptr_t first to avoid potential gcc warning
  3971.                      about coercing an 8 byte integer to a 4 byte pointer.  */
  3972.                   (PTRACE_TYPE_ARG3) (uintptr_t) (addr + (count - 1)
  3973.                                                   * sizeof (PTRACE_XFER_TYPE)),
  3974.                   (PTRACE_TYPE_ARG4) 0);
  3975.       if (errno)
  3976.         return errno;
  3977.     }

  3978.   /* Copy data to be written over corresponding part of buffer.  */

  3979.   memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
  3980.           myaddr, len);

  3981.   /* Write the entire buffer.  */

  3982.   for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
  3983.     {
  3984.       errno = 0;
  3985.       ptrace (PTRACE_POKETEXT, pid,
  3986.               /* Coerce to a uintptr_t first to avoid potential gcc warning
  3987.                  about coercing an 8 byte integer to a 4 byte pointer.  */
  3988.               (PTRACE_TYPE_ARG3) (uintptr_t) addr,
  3989.               (PTRACE_TYPE_ARG4) buffer[i]);
  3990.       if (errno)
  3991.         return errno;
  3992.     }

  3993.   return 0;
  3994. }

  3995. static void
  3996. linux_look_up_symbols (void)
  3997. {
  3998. #ifdef USE_THREAD_DB
  3999.   struct process_info *proc = current_process ();

  4000.   if (proc->private->thread_db != NULL)
  4001.     return;

  4002.   /* If the kernel supports tracing clones, then we don't need to
  4003.      use the magic thread event breakpoint to learn about
  4004.      threads.  */
  4005.   thread_db_init (!linux_supports_traceclone ());
  4006. #endif
  4007. }

  4008. static void
  4009. linux_request_interrupt (void)
  4010. {
  4011.   extern unsigned long signal_pid;

  4012.   /* Send a SIGINT to the process group.  This acts just like the user
  4013.      typed a ^C on the controlling terminal.  */
  4014.   kill (-signal_pid, SIGINT);
  4015. }

  4016. /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
  4017.    to debugger memory starting at MYADDR.  */

  4018. static int
  4019. linux_read_auxv (CORE_ADDR offset, unsigned char *myaddr, unsigned int len)
  4020. {
  4021.   char filename[PATH_MAX];
  4022.   int fd, n;
  4023.   int pid = lwpid_of (current_thread);

  4024.   xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);

  4025.   fd = open (filename, O_RDONLY);
  4026.   if (fd < 0)
  4027.     return -1;

  4028.   if (offset != (CORE_ADDR) 0
  4029.       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
  4030.     n = -1;
  4031.   else
  4032.     n = read (fd, myaddr, len);

  4033.   close (fd);

  4034.   return n;
  4035. }

  4036. /* These breakpoint and watchpoint related wrapper functions simply
  4037.    pass on the function call if the target has registered a
  4038.    corresponding function.  */

  4039. static int
  4040. linux_supports_z_point_type (char z_type)
  4041. {
  4042.   return (the_low_target.supports_z_point_type != NULL
  4043.           && the_low_target.supports_z_point_type (z_type));
  4044. }

  4045. static int
  4046. linux_insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
  4047.                     int size, struct raw_breakpoint *bp)
  4048. {
  4049.   if (the_low_target.insert_point != NULL)
  4050.     return the_low_target.insert_point (type, addr, size, bp);
  4051.   else
  4052.     /* Unsupported (see target.h).  */
  4053.     return 1;
  4054. }

  4055. static int
  4056. linux_remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
  4057.                     int size, struct raw_breakpoint *bp)
  4058. {
  4059.   if (the_low_target.remove_point != NULL)
  4060.     return the_low_target.remove_point (type, addr, size, bp);
  4061.   else
  4062.     /* Unsupported (see target.h).  */
  4063.     return 1;
  4064. }

  4065. static int
  4066. linux_stopped_by_watchpoint (void)
  4067. {
  4068.   struct lwp_info *lwp = get_thread_lwp (current_thread);

  4069.   return lwp->stop_reason == LWP_STOPPED_BY_WATCHPOINT;
  4070. }

  4071. static CORE_ADDR
  4072. linux_stopped_data_address (void)
  4073. {
  4074.   struct lwp_info *lwp = get_thread_lwp (current_thread);

  4075.   return lwp->stopped_data_address;
  4076. }

  4077. #if defined(__UCLIBC__) && defined(HAS_NOMMU)              \
  4078.     && defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) \
  4079.     && defined(PT_TEXT_END_ADDR)

  4080. /* This is only used for targets that define PT_TEXT_ADDR,
  4081.    PT_DATA_ADDR and PT_TEXT_END_ADDR.  If those are not defined, supposedly
  4082.    the target has different ways of acquiring this information, like
  4083.    loadmaps.  */

  4084. /* Under uClinux, programs are loaded at non-zero offsets, which we need
  4085.    to tell gdb about.  */

  4086. static int
  4087. linux_read_offsets (CORE_ADDR *text_p, CORE_ADDR *data_p)
  4088. {
  4089.   unsigned long text, text_end, data;
  4090.   int pid = lwpid_of (get_thread_lwp (current_thread));

  4091.   errno = 0;

  4092.   text = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_TEXT_ADDR,
  4093.                  (PTRACE_TYPE_ARG4) 0);
  4094.   text_end = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_TEXT_END_ADDR,
  4095.                      (PTRACE_TYPE_ARG4) 0);
  4096.   data = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_DATA_ADDR,
  4097.                  (PTRACE_TYPE_ARG4) 0);

  4098.   if (errno == 0)
  4099.     {
  4100.       /* Both text and data offsets produced at compile-time (and so
  4101.          used by gdb) are relative to the beginning of the program,
  4102.          with the data segment immediately following the text segment.
  4103.          However, the actual runtime layout in memory may put the data
  4104.          somewhere else, so when we send gdb a data base-address, we
  4105.          use the real data base address and subtract the compile-time
  4106.          data base-address from it (which is just the length of the
  4107.          text segment).  BSS immediately follows data in both
  4108.          cases.  */
  4109.       *text_p = text;
  4110.       *data_p = data - (text_end - text);

  4111.       return 1;
  4112.     }
  4113. return 0;
  4114. }
  4115. #endif

  4116. static int
  4117. linux_qxfer_osdata (const char *annex,
  4118.                     unsigned char *readbuf, unsigned const char *writebuf,
  4119.                     CORE_ADDR offset, int len)
  4120. {
  4121.   return linux_common_xfer_osdata (annex, readbuf, offset, len);
  4122. }

  4123. /* Convert a native/host siginfo object, into/from the siginfo in the
  4124.    layout of the inferiors' architecture.  */

  4125. static void
  4126. siginfo_fixup (siginfo_t *siginfo, void *inf_siginfo, int direction)
  4127. {
  4128.   int done = 0;

  4129.   if (the_low_target.siginfo_fixup != NULL)
  4130.     done = the_low_target.siginfo_fixup (siginfo, inf_siginfo, direction);

  4131.   /* If there was no callback, or the callback didn't do anything,
  4132.      then just do a straight memcpy.  */
  4133.   if (!done)
  4134.     {
  4135.       if (direction == 1)
  4136.         memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
  4137.       else
  4138.         memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
  4139.     }
  4140. }

  4141. static int
  4142. linux_xfer_siginfo (const char *annex, unsigned char *readbuf,
  4143.                     unsigned const char *writebuf, CORE_ADDR offset, int len)
  4144. {
  4145.   int pid;
  4146.   siginfo_t siginfo;
  4147.   char inf_siginfo[sizeof (siginfo_t)];

  4148.   if (current_thread == NULL)
  4149.     return -1;

  4150.   pid = lwpid_of (current_thread);

  4151.   if (debug_threads)
  4152.     debug_printf ("%s siginfo for lwp %d.\n",
  4153.                   readbuf != NULL ? "Reading" : "Writing",
  4154.                   pid);

  4155.   if (offset >= sizeof (siginfo))
  4156.     return -1;

  4157.   if (ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo) != 0)
  4158.     return -1;

  4159.   /* When GDBSERVER is built as a 64-bit application, ptrace writes into
  4160.      SIGINFO an object with 64-bit layout.  Since debugging a 32-bit
  4161.      inferior with a 64-bit GDBSERVER should look the same as debugging it
  4162.      with a 32-bit GDBSERVER, we need to convert it.  */
  4163.   siginfo_fixup (&siginfo, inf_siginfo, 0);

  4164.   if (offset + len > sizeof (siginfo))
  4165.     len = sizeof (siginfo) - offset;

  4166.   if (readbuf != NULL)
  4167.     memcpy (readbuf, inf_siginfo + offset, len);
  4168.   else
  4169.     {
  4170.       memcpy (inf_siginfo + offset, writebuf, len);

  4171.       /* Convert back to ptrace layout before flushing it out.  */
  4172.       siginfo_fixup (&siginfo, inf_siginfo, 1);

  4173.       if (ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo) != 0)
  4174.         return -1;
  4175.     }

  4176.   return len;
  4177. }

  4178. /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
  4179.    so we notice when children change state; as the handler for the
  4180.    sigsuspend in my_waitpid.  */

  4181. static void
  4182. sigchld_handler (int signo)
  4183. {
  4184.   int old_errno = errno;

  4185.   if (debug_threads)
  4186.     {
  4187.       do
  4188.         {
  4189.           /* fprintf is not async-signal-safe, so call write
  4190.              directly.  */
  4191.           if (write (2, "sigchld_handler\n",
  4192.                      sizeof ("sigchld_handler\n") - 1) < 0)
  4193.             break; /* just ignore */
  4194.         } while (0);
  4195.     }

  4196.   if (target_is_async_p ())
  4197.     async_file_mark (); /* trigger a linux_wait */

  4198.   errno = old_errno;
  4199. }

  4200. static int
  4201. linux_supports_non_stop (void)
  4202. {
  4203.   return 1;
  4204. }

  4205. static int
  4206. linux_async (int enable)
  4207. {
  4208.   int previous = target_is_async_p ();

  4209.   if (debug_threads)
  4210.     debug_printf ("linux_async (%d), previous=%d\n",
  4211.                   enable, previous);

  4212.   if (previous != enable)
  4213.     {
  4214.       sigset_t mask;
  4215.       sigemptyset (&mask);
  4216.       sigaddset (&mask, SIGCHLD);

  4217.       sigprocmask (SIG_BLOCK, &mask, NULL);

  4218.       if (enable)
  4219.         {
  4220.           if (pipe (linux_event_pipe) == -1)
  4221.             {
  4222.               linux_event_pipe[0] = -1;
  4223.               linux_event_pipe[1] = -1;
  4224.               sigprocmask (SIG_UNBLOCK, &mask, NULL);

  4225.               warning ("creating event pipe failed.");
  4226.               return previous;
  4227.             }

  4228.           fcntl (linux_event_pipe[0], F_SETFL, O_NONBLOCK);
  4229.           fcntl (linux_event_pipe[1], F_SETFL, O_NONBLOCK);

  4230.           /* Register the event loop handler.  */
  4231.           add_file_handler (linux_event_pipe[0],
  4232.                             handle_target_event, NULL);

  4233.           /* Always trigger a linux_wait.  */
  4234.           async_file_mark ();
  4235.         }
  4236.       else
  4237.         {
  4238.           delete_file_handler (linux_event_pipe[0]);

  4239.           close (linux_event_pipe[0]);
  4240.           close (linux_event_pipe[1]);
  4241.           linux_event_pipe[0] = -1;
  4242.           linux_event_pipe[1] = -1;
  4243.         }

  4244.       sigprocmask (SIG_UNBLOCK, &mask, NULL);
  4245.     }

  4246.   return previous;
  4247. }

  4248. static int
  4249. linux_start_non_stop (int nonstop)
  4250. {
  4251.   /* Register or unregister from event-loop accordingly.  */
  4252.   linux_async (nonstop);

  4253.   if (target_is_async_p () != (nonstop != 0))
  4254.     return -1;

  4255.   return 0;
  4256. }

  4257. static int
  4258. linux_supports_multi_process (void)
  4259. {
  4260.   return 1;
  4261. }

  4262. static int
  4263. linux_supports_disable_randomization (void)
  4264. {
  4265. #ifdef HAVE_PERSONALITY
  4266.   return 1;
  4267. #else
  4268.   return 0;
  4269. #endif
  4270. }

  4271. static int
  4272. linux_supports_agent (void)
  4273. {
  4274.   return 1;
  4275. }

  4276. static int
  4277. linux_supports_range_stepping (void)
  4278. {
  4279.   if (*the_low_target.supports_range_stepping == NULL)
  4280.     return 0;

  4281.   return (*the_low_target.supports_range_stepping) ();
  4282. }

  4283. /* Enumerate spufs IDs for process PID.  */
  4284. static int
  4285. spu_enumerate_spu_ids (long pid, unsigned char *buf, CORE_ADDR offset, int len)
  4286. {
  4287.   int pos = 0;
  4288.   int written = 0;
  4289.   char path[128];
  4290.   DIR *dir;
  4291.   struct dirent *entry;

  4292.   sprintf (path, "/proc/%ld/fd", pid);
  4293.   dir = opendir (path);
  4294.   if (!dir)
  4295.     return -1;

  4296.   rewinddir (dir);
  4297.   while ((entry = readdir (dir)) != NULL)
  4298.     {
  4299.       struct stat st;
  4300.       struct statfs stfs;
  4301.       int fd;

  4302.       fd = atoi (entry->d_name);
  4303.       if (!fd)
  4304.         continue;

  4305.       sprintf (path, "/proc/%ld/fd/%d", pid, fd);
  4306.       if (stat (path, &st) != 0)
  4307.         continue;
  4308.       if (!S_ISDIR (st.st_mode))
  4309.         continue;

  4310.       if (statfs (path, &stfs) != 0)
  4311.         continue;
  4312.       if (stfs.f_type != SPUFS_MAGIC)
  4313.         continue;

  4314.       if (pos >= offset && pos + 4 <= offset + len)
  4315.         {
  4316.           *(unsigned int *)(buf + pos - offset) = fd;
  4317.           written += 4;
  4318.         }
  4319.       pos += 4;
  4320.     }

  4321.   closedir (dir);
  4322.   return written;
  4323. }

  4324. /* Implements the to_xfer_partial interface for the TARGET_OBJECT_SPU
  4325.    object type, using the /proc file system.  */
  4326. static int
  4327. linux_qxfer_spu (const char *annex, unsigned char *readbuf,
  4328.                  unsigned const char *writebuf,
  4329.                  CORE_ADDR offset, int len)
  4330. {
  4331.   long pid = lwpid_of (current_thread);
  4332.   char buf[128];
  4333.   int fd = 0;
  4334.   int ret = 0;

  4335.   if (!writebuf && !readbuf)
  4336.     return -1;

  4337.   if (!*annex)
  4338.     {
  4339.       if (!readbuf)
  4340.         return -1;
  4341.       else
  4342.         return spu_enumerate_spu_ids (pid, readbuf, offset, len);
  4343.     }

  4344.   sprintf (buf, "/proc/%ld/fd/%s", pid, annex);
  4345.   fd = open (buf, writebuf? O_WRONLY : O_RDONLY);
  4346.   if (fd <= 0)
  4347.     return -1;

  4348.   if (offset != 0
  4349.       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
  4350.     {
  4351.       close (fd);
  4352.       return 0;
  4353.     }

  4354.   if (writebuf)
  4355.     ret = write (fd, writebuf, (size_t) len);
  4356.   else
  4357.     ret = read (fd, readbuf, (size_t) len);

  4358.   close (fd);
  4359.   return ret;
  4360. }

  4361. #if defined PT_GETDSBT || defined PTRACE_GETFDPIC
  4362. struct target_loadseg
  4363. {
  4364.   /* Core address to which the segment is mapped.  */
  4365.   Elf32_Addr addr;
  4366.   /* VMA recorded in the program header.  */
  4367.   Elf32_Addr p_vaddr;
  4368.   /* Size of this segment in memory.  */
  4369.   Elf32_Word p_memsz;
  4370. };

  4371. # if defined PT_GETDSBT
  4372. struct target_loadmap
  4373. {
  4374.   /* Protocol version number, must be zero.  */
  4375.   Elf32_Word version;
  4376.   /* Pointer to the DSBT table, its size, and the DSBT index.  */
  4377.   unsigned *dsbt_table;
  4378.   unsigned dsbt_size, dsbt_index;
  4379.   /* Number of segments in this map.  */
  4380.   Elf32_Word nsegs;
  4381.   /* The actual memory map.  */
  4382.   struct target_loadseg segs[/*nsegs*/];
  4383. };
  4384. #  define LINUX_LOADMAP                PT_GETDSBT
  4385. #  define LINUX_LOADMAP_EXEC        PTRACE_GETDSBT_EXEC
  4386. #  define LINUX_LOADMAP_INTERP        PTRACE_GETDSBT_INTERP
  4387. # else
  4388. struct target_loadmap
  4389. {
  4390.   /* Protocol version number, must be zero.  */
  4391.   Elf32_Half version;
  4392.   /* Number of segments in this map.  */
  4393.   Elf32_Half nsegs;
  4394.   /* The actual memory map.  */
  4395.   struct target_loadseg segs[/*nsegs*/];
  4396. };
  4397. #  define LINUX_LOADMAP                PTRACE_GETFDPIC
  4398. #  define LINUX_LOADMAP_EXEC        PTRACE_GETFDPIC_EXEC
  4399. #  define LINUX_LOADMAP_INTERP        PTRACE_GETFDPIC_INTERP
  4400. # endif

  4401. static int
  4402. linux_read_loadmap (const char *annex, CORE_ADDR offset,
  4403.                     unsigned char *myaddr, unsigned int len)
  4404. {
  4405.   int pid = lwpid_of (current_thread);
  4406.   int addr = -1;
  4407.   struct target_loadmap *data = NULL;
  4408.   unsigned int actual_length, copy_length;

  4409.   if (strcmp (annex, "exec") == 0)
  4410.     addr = (int) LINUX_LOADMAP_EXEC;
  4411.   else if (strcmp (annex, "interp") == 0)
  4412.     addr = (int) LINUX_LOADMAP_INTERP;
  4413.   else
  4414.     return -1;

  4415.   if (ptrace (LINUX_LOADMAP, pid, addr, &data) != 0)
  4416.     return -1;

  4417.   if (data == NULL)
  4418.     return -1;

  4419.   actual_length = sizeof (struct target_loadmap)
  4420.     + sizeof (struct target_loadseg) * data->nsegs;

  4421.   if (offset < 0 || offset > actual_length)
  4422.     return -1;

  4423.   copy_length = actual_length - offset < len ? actual_length - offset : len;
  4424.   memcpy (myaddr, (char *) data + offset, copy_length);
  4425.   return copy_length;
  4426. }
  4427. #else
  4428. # define linux_read_loadmap NULL
  4429. #endif /* defined PT_GETDSBT || defined PTRACE_GETFDPIC */

  4430. static void
  4431. linux_process_qsupported (const char *query)
  4432. {
  4433.   if (the_low_target.process_qsupported != NULL)
  4434.     the_low_target.process_qsupported (query);
  4435. }

  4436. static int
  4437. linux_supports_tracepoints (void)
  4438. {
  4439.   if (*the_low_target.supports_tracepoints == NULL)
  4440.     return 0;

  4441.   return (*the_low_target.supports_tracepoints) ();
  4442. }

  4443. static CORE_ADDR
  4444. linux_read_pc (struct regcache *regcache)
  4445. {
  4446.   if (the_low_target.get_pc == NULL)
  4447.     return 0;

  4448.   return (*the_low_target.get_pc) (regcache);
  4449. }

  4450. static void
  4451. linux_write_pc (struct regcache *regcache, CORE_ADDR pc)
  4452. {
  4453.   gdb_assert (the_low_target.set_pc != NULL);

  4454.   (*the_low_target.set_pc) (regcache, pc);
  4455. }

  4456. static int
  4457. linux_thread_stopped (struct thread_info *thread)
  4458. {
  4459.   return get_thread_lwp (thread)->stopped;
  4460. }

  4461. /* This exposes stop-all-threads functionality to other modules.  */

  4462. static void
  4463. linux_pause_all (int freeze)
  4464. {
  4465.   stop_all_lwps (freeze, NULL);
  4466. }

  4467. /* This exposes unstop-all-threads functionality to other gdbserver
  4468.    modules.  */

  4469. static void
  4470. linux_unpause_all (int unfreeze)
  4471. {
  4472.   unstop_all_lwps (unfreeze, NULL);
  4473. }

  4474. static int
  4475. linux_prepare_to_access_memory (void)
  4476. {
  4477.   /* Neither ptrace nor /proc/PID/mem allow accessing memory through a
  4478.      running LWP.  */
  4479.   if (non_stop)
  4480.     linux_pause_all (1);
  4481.   return 0;
  4482. }

  4483. static void
  4484. linux_done_accessing_memory (void)
  4485. {
  4486.   /* Neither ptrace nor /proc/PID/mem allow accessing memory through a
  4487.      running LWP.  */
  4488.   if (non_stop)
  4489.     linux_unpause_all (1);
  4490. }

  4491. static int
  4492. linux_install_fast_tracepoint_jump_pad (CORE_ADDR tpoint, CORE_ADDR tpaddr,
  4493.                                         CORE_ADDR collector,
  4494.                                         CORE_ADDR lockaddr,
  4495.                                         ULONGEST orig_size,
  4496.                                         CORE_ADDR *jump_entry,
  4497.                                         CORE_ADDR *trampoline,
  4498.                                         ULONGEST *trampoline_size,
  4499.                                         unsigned char *jjump_pad_insn,
  4500.                                         ULONGEST *jjump_pad_insn_size,
  4501.                                         CORE_ADDR *adjusted_insn_addr,
  4502.                                         CORE_ADDR *adjusted_insn_addr_end,
  4503.                                         char *err)
  4504. {
  4505.   return (*the_low_target.install_fast_tracepoint_jump_pad)
  4506.     (tpoint, tpaddr, collector, lockaddr, orig_size,
  4507.      jump_entry, trampoline, trampoline_size,
  4508.      jjump_pad_insn, jjump_pad_insn_size,
  4509.      adjusted_insn_addr, adjusted_insn_addr_end,
  4510.      err);
  4511. }

  4512. static struct emit_ops *
  4513. linux_emit_ops (void)
  4514. {
  4515.   if (the_low_target.emit_ops != NULL)
  4516.     return (*the_low_target.emit_ops) ();
  4517.   else
  4518.     return NULL;
  4519. }

  4520. static int
  4521. linux_get_min_fast_tracepoint_insn_len (void)
  4522. {
  4523.   return (*the_low_target.get_min_fast_tracepoint_insn_len) ();
  4524. }

  4525. /* Extract &phdr and num_phdr in the inferior.  Return 0 on success.  */

  4526. static int
  4527. get_phdr_phnum_from_proc_auxv (const int pid, const int is_elf64,
  4528.                                CORE_ADDR *phdr_memaddr, int *num_phdr)
  4529. {
  4530.   char filename[PATH_MAX];
  4531.   int fd;
  4532.   const int auxv_size = is_elf64
  4533.     ? sizeof (Elf64_auxv_t) : sizeof (Elf32_auxv_t);
  4534.   char buf[sizeof (Elf64_auxv_t)];  /* The larger of the two.  */

  4535.   xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);

  4536.   fd = open (filename, O_RDONLY);
  4537.   if (fd < 0)
  4538.     return 1;

  4539.   *phdr_memaddr = 0;
  4540.   *num_phdr = 0;
  4541.   while (read (fd, buf, auxv_size) == auxv_size
  4542.          && (*phdr_memaddr == 0 || *num_phdr == 0))
  4543.     {
  4544.       if (is_elf64)
  4545.         {
  4546.           Elf64_auxv_t *const aux = (Elf64_auxv_t *) buf;

  4547.           switch (aux->a_type)
  4548.             {
  4549.             case AT_PHDR:
  4550.               *phdr_memaddr = aux->a_un.a_val;
  4551.               break;
  4552.             case AT_PHNUM:
  4553.               *num_phdr = aux->a_un.a_val;
  4554.               break;
  4555.             }
  4556.         }
  4557.       else
  4558.         {
  4559.           Elf32_auxv_t *const aux = (Elf32_auxv_t *) buf;

  4560.           switch (aux->a_type)
  4561.             {
  4562.             case AT_PHDR:
  4563.               *phdr_memaddr = aux->a_un.a_val;
  4564.               break;
  4565.             case AT_PHNUM:
  4566.               *num_phdr = aux->a_un.a_val;
  4567.               break;
  4568.             }
  4569.         }
  4570.     }

  4571.   close (fd);

  4572.   if (*phdr_memaddr == 0 || *num_phdr == 0)
  4573.     {
  4574.       warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
  4575.                "phdr_memaddr = %ld, phdr_num = %d",
  4576.                (long) *phdr_memaddr, *num_phdr);
  4577.       return 2;
  4578.     }

  4579.   return 0;
  4580. }

  4581. /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present.  */

  4582. static CORE_ADDR
  4583. get_dynamic (const int pid, const int is_elf64)
  4584. {
  4585.   CORE_ADDR phdr_memaddr, relocation;
  4586.   int num_phdr, i;
  4587.   unsigned char *phdr_buf;
  4588.   const int phdr_size = is_elf64 ? sizeof (Elf64_Phdr) : sizeof (Elf32_Phdr);

  4589.   if (get_phdr_phnum_from_proc_auxv (pid, is_elf64, &phdr_memaddr, &num_phdr))
  4590.     return 0;

  4591.   gdb_assert (num_phdr < 100);  /* Basic sanity check.  */
  4592.   phdr_buf = alloca (num_phdr * phdr_size);

  4593.   if (linux_read_memory (phdr_memaddr, phdr_buf, num_phdr * phdr_size))
  4594.     return 0;

  4595.   /* Compute relocation: it is expected to be 0 for "regular" executables,
  4596.      non-zero for PIE ones.  */
  4597.   relocation = -1;
  4598.   for (i = 0; relocation == -1 && i < num_phdr; i++)
  4599.     if (is_elf64)
  4600.       {
  4601.         Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);

  4602.         if (p->p_type == PT_PHDR)
  4603.           relocation = phdr_memaddr - p->p_vaddr;
  4604.       }
  4605.     else
  4606.       {
  4607.         Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);

  4608.         if (p->p_type == PT_PHDR)
  4609.           relocation = phdr_memaddr - p->p_vaddr;
  4610.       }

  4611.   if (relocation == -1)
  4612.     {
  4613.       /* PT_PHDR is optional, but necessary for PIE in general.  Fortunately
  4614.          any real world executables, including PIE executables, have always
  4615.          PT_PHDR present.  PT_PHDR is not present in some shared libraries or
  4616.          in fpc (Free Pascal 2.4) binaries but neither of those have a need for
  4617.          or present DT_DEBUG anyway (fpc binaries are statically linked).

  4618.          Therefore if there exists DT_DEBUG there is always also PT_PHDR.

  4619.          GDB could find RELOCATION also from AT_ENTRY - e_entry.  */

  4620.       return 0;
  4621.     }

  4622.   for (i = 0; i < num_phdr; i++)
  4623.     {
  4624.       if (is_elf64)
  4625.         {
  4626.           Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);

  4627.           if (p->p_type == PT_DYNAMIC)
  4628.             return p->p_vaddr + relocation;
  4629.         }
  4630.       else
  4631.         {
  4632.           Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);

  4633.           if (p->p_type == PT_DYNAMIC)
  4634.             return p->p_vaddr + relocation;
  4635.         }
  4636.     }

  4637.   return 0;
  4638. }

  4639. /* Return &_r_debug in the inferior, or -1 if not present.  Return value
  4640.    can be 0 if the inferior does not yet have the library list initialized.
  4641.    We look for DT_MIPS_RLD_MAP first.  MIPS executables use this instead of
  4642.    DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too.  */

  4643. static CORE_ADDR
  4644. get_r_debug (const int pid, const int is_elf64)
  4645. {
  4646.   CORE_ADDR dynamic_memaddr;
  4647.   const int dyn_size = is_elf64 ? sizeof (Elf64_Dyn) : sizeof (Elf32_Dyn);
  4648.   unsigned char buf[sizeof (Elf64_Dyn)];  /* The larger of the two.  */
  4649.   CORE_ADDR map = -1;

  4650.   dynamic_memaddr = get_dynamic (pid, is_elf64);
  4651.   if (dynamic_memaddr == 0)
  4652.     return map;

  4653.   while (linux_read_memory (dynamic_memaddr, buf, dyn_size) == 0)
  4654.     {
  4655.       if (is_elf64)
  4656.         {
  4657.           Elf64_Dyn *const dyn = (Elf64_Dyn *) buf;
  4658. #ifdef DT_MIPS_RLD_MAP
  4659.           union
  4660.             {
  4661.               Elf64_Xword map;
  4662.               unsigned char buf[sizeof (Elf64_Xword)];
  4663.             }
  4664.           rld_map;

  4665.           if (dyn->d_tag == DT_MIPS_RLD_MAP)
  4666.             {
  4667.               if (linux_read_memory (dyn->d_un.d_val,
  4668.                                      rld_map.buf, sizeof (rld_map.buf)) == 0)
  4669.                 return rld_map.map;
  4670.               else
  4671.                 break;
  4672.             }
  4673. #endif        /* DT_MIPS_RLD_MAP */

  4674.           if (dyn->d_tag == DT_DEBUG && map == -1)
  4675.             map = dyn->d_un.d_val;

  4676.           if (dyn->d_tag == DT_NULL)
  4677.             break;
  4678.         }
  4679.       else
  4680.         {
  4681.           Elf32_Dyn *const dyn = (Elf32_Dyn *) buf;
  4682. #ifdef DT_MIPS_RLD_MAP
  4683.           union
  4684.             {
  4685.               Elf32_Word map;
  4686.               unsigned char buf[sizeof (Elf32_Word)];
  4687.             }
  4688.           rld_map;

  4689.           if (dyn->d_tag == DT_MIPS_RLD_MAP)
  4690.             {
  4691.               if (linux_read_memory (dyn->d_un.d_val,
  4692.                                      rld_map.buf, sizeof (rld_map.buf)) == 0)
  4693.                 return rld_map.map;
  4694.               else
  4695.                 break;
  4696.             }
  4697. #endif        /* DT_MIPS_RLD_MAP */

  4698.           if (dyn->d_tag == DT_DEBUG && map == -1)
  4699.             map = dyn->d_un.d_val;

  4700.           if (dyn->d_tag == DT_NULL)
  4701.             break;
  4702.         }

  4703.       dynamic_memaddr += dyn_size;
  4704.     }

  4705.   return map;
  4706. }

  4707. /* Read one pointer from MEMADDR in the inferior.  */

  4708. static int
  4709. read_one_ptr (CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
  4710. {
  4711.   int ret;

  4712.   /* Go through a union so this works on either big or little endian
  4713.      hosts, when the inferior's pointer size is smaller than the size
  4714.      of CORE_ADDR.  It is assumed the inferior's endianness is the
  4715.      same of the superior's.  */
  4716.   union
  4717.   {
  4718.     CORE_ADDR core_addr;
  4719.     unsigned int ui;
  4720.     unsigned char uc;
  4721.   } addr;

  4722.   ret = linux_read_memory (memaddr, &addr.uc, ptr_size);
  4723.   if (ret == 0)
  4724.     {
  4725.       if (ptr_size == sizeof (CORE_ADDR))
  4726.         *ptr = addr.core_addr;
  4727.       else if (ptr_size == sizeof (unsigned int))
  4728.         *ptr = addr.ui;
  4729.       else
  4730.         gdb_assert_not_reached ("unhandled pointer size");
  4731.     }
  4732.   return ret;
  4733. }

  4734. struct link_map_offsets
  4735.   {
  4736.     /* Offset and size of r_debug.r_version.  */
  4737.     int r_version_offset;

  4738.     /* Offset and size of r_debug.r_map.  */
  4739.     int r_map_offset;

  4740.     /* Offset to l_addr field in struct link_map.  */
  4741.     int l_addr_offset;

  4742.     /* Offset to l_name field in struct link_map.  */
  4743.     int l_name_offset;

  4744.     /* Offset to l_ld field in struct link_map.  */
  4745.     int l_ld_offset;

  4746.     /* Offset to l_next field in struct link_map.  */
  4747.     int l_next_offset;

  4748.     /* Offset to l_prev field in struct link_map.  */
  4749.     int l_prev_offset;
  4750.   };

  4751. /* Construct qXfer:libraries-svr4:read reply.  */

  4752. static int
  4753. linux_qxfer_libraries_svr4 (const char *annex, unsigned char *readbuf,
  4754.                             unsigned const char *writebuf,
  4755.                             CORE_ADDR offset, int len)
  4756. {
  4757.   char *document;
  4758.   unsigned document_len;
  4759.   struct process_info_private *const priv = current_process ()->private;
  4760.   char filename[PATH_MAX];
  4761.   int pid, is_elf64;

  4762.   static const struct link_map_offsets lmo_32bit_offsets =
  4763.     {
  4764.       0,     /* r_version offset. */
  4765.       4,     /* r_debug.r_map offset.  */
  4766.       0,     /* l_addr offset in link_map.  */
  4767.       4,     /* l_name offset in link_map.  */
  4768.       8,     /* l_ld offset in link_map.  */
  4769.       12,    /* l_next offset in link_map.  */
  4770.       16     /* l_prev offset in link_map.  */
  4771.     };

  4772.   static const struct link_map_offsets lmo_64bit_offsets =
  4773.     {
  4774.       0,     /* r_version offset. */
  4775.       8,     /* r_debug.r_map offset.  */
  4776.       0,     /* l_addr offset in link_map.  */
  4777.       8,     /* l_name offset in link_map.  */
  4778.       16,    /* l_ld offset in link_map.  */
  4779.       24,    /* l_next offset in link_map.  */
  4780.       32     /* l_prev offset in link_map.  */
  4781.     };
  4782.   const struct link_map_offsets *lmo;
  4783.   unsigned int machine;
  4784.   int ptr_size;
  4785.   CORE_ADDR lm_addr = 0, lm_prev = 0;
  4786.   int allocated = 1024;
  4787.   char *p;
  4788.   CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
  4789.   int header_done = 0;

  4790.   if (writebuf != NULL)
  4791.     return -2;
  4792.   if (readbuf == NULL)
  4793.     return -1;

  4794.   pid = lwpid_of (current_thread);
  4795.   xsnprintf (filename, sizeof filename, "/proc/%d/exe", pid);
  4796.   is_elf64 = elf_64_file_p (filename, &machine);
  4797.   lmo = is_elf64 ? &lmo_64bit_offsets : &lmo_32bit_offsets;
  4798.   ptr_size = is_elf64 ? 8 : 4;

  4799.   while (annex[0] != '\0')
  4800.     {
  4801.       const char *sep;
  4802.       CORE_ADDR *addrp;
  4803.       int len;

  4804.       sep = strchr (annex, '=');
  4805.       if (sep == NULL)
  4806.         break;

  4807.       len = sep - annex;
  4808.       if (len == 5 && strncmp (annex, "start", 5) == 0)
  4809.         addrp = &lm_addr;
  4810.       else if (len == 4 && strncmp (annex, "prev", 4) == 0)
  4811.         addrp = &lm_prev;
  4812.       else
  4813.         {
  4814.           annex = strchr (sep, ';');
  4815.           if (annex == NULL)
  4816.             break;
  4817.           annex++;
  4818.           continue;
  4819.         }

  4820.       annex = decode_address_to_semicolon (addrp, sep + 1);
  4821.     }

  4822.   if (lm_addr == 0)
  4823.     {
  4824.       int r_version = 0;

  4825.       if (priv->r_debug == 0)
  4826.         priv->r_debug = get_r_debug (pid, is_elf64);

  4827.       /* We failed to find DT_DEBUG.  Such situation will not change
  4828.          for this inferior - do not retry it.  Report it to GDB as
  4829.          E01, see for the reasons at the GDB solib-svr4.c side.  */
  4830.       if (priv->r_debug == (CORE_ADDR) -1)
  4831.         return -1;

  4832.       if (priv->r_debug != 0)
  4833.         {
  4834.           if (linux_read_memory (priv->r_debug + lmo->r_version_offset,
  4835.                                  (unsigned char *) &r_version,
  4836.                                  sizeof (r_version)) != 0
  4837.               || r_version != 1)
  4838.             {
  4839.               warning ("unexpected r_debug version %d", r_version);
  4840.             }
  4841.           else if (read_one_ptr (priv->r_debug + lmo->r_map_offset,
  4842.                                  &lm_addr, ptr_size) != 0)
  4843.             {
  4844.               warning ("unable to read r_map from 0x%lx",
  4845.                        (long) priv->r_debug + lmo->r_map_offset);
  4846.             }
  4847.         }
  4848.     }

  4849.   document = xmalloc (allocated);
  4850.   strcpy (document, "<library-list-svr4 version=\"1.0\"");
  4851.   p = document + strlen (document);

  4852.   while (lm_addr
  4853.          && read_one_ptr (lm_addr + lmo->l_name_offset,
  4854.                           &l_name, ptr_size) == 0
  4855.          && read_one_ptr (lm_addr + lmo->l_addr_offset,
  4856.                           &l_addr, ptr_size) == 0
  4857.          && read_one_ptr (lm_addr + lmo->l_ld_offset,
  4858.                           &l_ld, ptr_size) == 0
  4859.          && read_one_ptr (lm_addr + lmo->l_prev_offset,
  4860.                           &l_prev, ptr_size) == 0
  4861.          && read_one_ptr (lm_addr + lmo->l_next_offset,
  4862.                           &l_next, ptr_size) == 0)
  4863.     {
  4864.       unsigned char libname[PATH_MAX];

  4865.       if (lm_prev != l_prev)
  4866.         {
  4867.           warning ("Corrupted shared library list: 0x%lx != 0x%lx",
  4868.                    (long) lm_prev, (long) l_prev);
  4869.           break;
  4870.         }

  4871.       /* Ignore the first entry even if it has valid name as the first entry
  4872.          corresponds to the main executable.  The first entry should not be
  4873.          skipped if the dynamic loader was loaded late by a static executable
  4874.          (see solib-svr4.c parameter ignore_first).  But in such case the main
  4875.          executable does not have PT_DYNAMIC present and this function already
  4876.          exited above due to failed get_r_debug.  */
  4877.       if (lm_prev == 0)
  4878.         {
  4879.           sprintf (p, " main-lm=\"0x%lx\"", (unsigned long) lm_addr);
  4880.           p = p + strlen (p);
  4881.         }
  4882.       else
  4883.         {
  4884.           /* Not checking for error because reading may stop before
  4885.              we've got PATH_MAX worth of characters.  */
  4886.           libname[0] = '\0';
  4887.           linux_read_memory (l_name, libname, sizeof (libname) - 1);
  4888.           libname[sizeof (libname) - 1] = '\0';
  4889.           if (libname[0] != '\0')
  4890.             {
  4891.               /* 6x the size for xml_escape_text below.  */
  4892.               size_t len = 6 * strlen ((char *) libname);
  4893.               char *name;

  4894.               if (!header_done)
  4895.                 {
  4896.                   /* Terminate `<library-list-svr4'.  */
  4897.                   *p++ = '>';
  4898.                   header_done = 1;
  4899.                 }

  4900.               while (allocated < p - document + len + 200)
  4901.                 {
  4902.                   /* Expand to guarantee sufficient storage.  */
  4903.                   uintptr_t document_len = p - document;

  4904.                   document = xrealloc (document, 2 * allocated);
  4905.                   allocated *= 2;
  4906.                   p = document + document_len;
  4907.                 }

  4908.               name = xml_escape_text ((char *) libname);
  4909.               p += sprintf (p, "<library name=\"%s\" lm=\"0x%lx\" "
  4910.                             "l_addr=\"0x%lx\" l_ld=\"0x%lx\"/>",
  4911.                             name, (unsigned long) lm_addr,
  4912.                             (unsigned long) l_addr, (unsigned long) l_ld);
  4913.               free (name);
  4914.             }
  4915.         }

  4916.       lm_prev = lm_addr;
  4917.       lm_addr = l_next;
  4918.     }

  4919.   if (!header_done)
  4920.     {
  4921.       /* Empty list; terminate `<library-list-svr4'.  */
  4922.       strcpy (p, "/>");
  4923.     }
  4924.   else
  4925.     strcpy (p, "</library-list-svr4>");

  4926.   document_len = strlen (document);
  4927.   if (offset < document_len)
  4928.     document_len -= offset;
  4929.   else
  4930.     document_len = 0;
  4931.   if (len > document_len)
  4932.     len = document_len;

  4933.   memcpy (readbuf, document + offset, len);
  4934.   xfree (document);

  4935.   return len;
  4936. }

  4937. #ifdef HAVE_LINUX_BTRACE

  4938. /* See to_enable_btrace target method.  */

  4939. static struct btrace_target_info *
  4940. linux_low_enable_btrace (ptid_t ptid)
  4941. {
  4942.   struct btrace_target_info *tinfo;

  4943.   tinfo = linux_enable_btrace (ptid);

  4944.   if (tinfo != NULL)
  4945.     {
  4946.       struct thread_info *thread = find_thread_ptid (ptid);
  4947.       struct regcache *regcache = get_thread_regcache (thread, 0);

  4948.       tinfo->ptr_bits = register_size (regcache->tdesc, 0) * 8;
  4949.     }

  4950.   return tinfo;
  4951. }

  4952. /* See to_disable_btrace target method.  */

  4953. static int
  4954. linux_low_disable_btrace (struct btrace_target_info *tinfo)
  4955. {
  4956.   enum btrace_error err;

  4957.   err = linux_disable_btrace (tinfo);
  4958.   return (err == BTRACE_ERR_NONE ? 0 : -1);
  4959. }

  4960. /* See to_read_btrace target method.  */

  4961. static int
  4962. linux_low_read_btrace (struct btrace_target_info *tinfo, struct buffer *buffer,
  4963.                        int type)
  4964. {
  4965.   VEC (btrace_block_s) *btrace;
  4966.   struct btrace_block *block;
  4967.   enum btrace_error err;
  4968.   int i;

  4969.   btrace = NULL;
  4970.   err = linux_read_btrace (&btrace, tinfo, type);
  4971.   if (err != BTRACE_ERR_NONE)
  4972.     {
  4973.       if (err == BTRACE_ERR_OVERFLOW)
  4974.         buffer_grow_str0 (buffer, "E.Overflow.");
  4975.       else
  4976.         buffer_grow_str0 (buffer, "E.Generic Error.");

  4977.       return -1;
  4978.     }

  4979.   buffer_grow_str (buffer, "<!DOCTYPE btrace SYSTEM \"btrace.dtd\">\n");
  4980.   buffer_grow_str (buffer, "<btrace version=\"1.0\">\n");

  4981.   for (i = 0; VEC_iterate (btrace_block_s, btrace, i, block); i++)
  4982.     buffer_xml_printf (buffer, "<block begin=\"0x%s\" end=\"0x%s\"/>\n",
  4983.                        paddress (block->begin), paddress (block->end));

  4984.   buffer_grow_str0 (buffer, "</btrace>\n");

  4985.   VEC_free (btrace_block_s, btrace);

  4986.   return 0;
  4987. }
  4988. #endif /* HAVE_LINUX_BTRACE */

  4989. static struct target_ops linux_target_ops = {
  4990.   linux_create_inferior,
  4991.   linux_attach,
  4992.   linux_kill,
  4993.   linux_detach,
  4994.   linux_mourn,
  4995.   linux_join,
  4996.   linux_thread_alive,
  4997.   linux_resume,
  4998.   linux_wait,
  4999.   linux_fetch_registers,
  5000.   linux_store_registers,
  5001.   linux_prepare_to_access_memory,
  5002.   linux_done_accessing_memory,
  5003.   linux_read_memory,
  5004.   linux_write_memory,
  5005.   linux_look_up_symbols,
  5006.   linux_request_interrupt,
  5007.   linux_read_auxv,
  5008.   linux_supports_z_point_type,
  5009.   linux_insert_point,
  5010.   linux_remove_point,
  5011.   linux_stopped_by_watchpoint,
  5012.   linux_stopped_data_address,
  5013. #if defined(__UCLIBC__) && defined(HAS_NOMMU)              \
  5014.     && defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) \
  5015.     && defined(PT_TEXT_END_ADDR)
  5016.   linux_read_offsets,
  5017. #else
  5018.   NULL,
  5019. #endif
  5020. #ifdef USE_THREAD_DB
  5021.   thread_db_get_tls_address,
  5022. #else
  5023.   NULL,
  5024. #endif
  5025.   linux_qxfer_spu,
  5026.   hostio_last_error_from_errno,
  5027.   linux_qxfer_osdata,
  5028.   linux_xfer_siginfo,
  5029.   linux_supports_non_stop,
  5030.   linux_async,
  5031.   linux_start_non_stop,
  5032.   linux_supports_multi_process,
  5033. #ifdef USE_THREAD_DB
  5034.   thread_db_handle_monitor_command,
  5035. #else
  5036.   NULL,
  5037. #endif
  5038.   linux_common_core_of_thread,
  5039.   linux_read_loadmap,
  5040.   linux_process_qsupported,
  5041.   linux_supports_tracepoints,
  5042.   linux_read_pc,
  5043.   linux_write_pc,
  5044.   linux_thread_stopped,
  5045.   NULL,
  5046.   linux_pause_all,
  5047.   linux_unpause_all,
  5048.   linux_stabilize_threads,
  5049.   linux_install_fast_tracepoint_jump_pad,
  5050.   linux_emit_ops,
  5051.   linux_supports_disable_randomization,
  5052.   linux_get_min_fast_tracepoint_insn_len,
  5053.   linux_qxfer_libraries_svr4,
  5054.   linux_supports_agent,
  5055. #ifdef HAVE_LINUX_BTRACE
  5056.   linux_supports_btrace,
  5057.   linux_low_enable_btrace,
  5058.   linux_low_disable_btrace,
  5059.   linux_low_read_btrace,
  5060. #else
  5061.   NULL,
  5062.   NULL,
  5063.   NULL,
  5064.   NULL,
  5065. #endif
  5066.   linux_supports_range_stepping,
  5067. };

  5068. static void
  5069. linux_init_signals ()
  5070. {
  5071.   /* FIXME drow/2002-06-09: As above, we should check with LinuxThreads
  5072.      to find what the cancel signal actually is.  */
  5073. #ifndef __ANDROID__ /* Bionic doesn't use SIGRTMIN the way glibc does.  */
  5074.   signal (__SIGRTMIN+1, SIG_IGN);
  5075. #endif
  5076. }

  5077. #ifdef HAVE_LINUX_REGSETS
  5078. void
  5079. initialize_regsets_info (struct regsets_info *info)
  5080. {
  5081.   for (info->num_regsets = 0;
  5082.        info->regsets[info->num_regsets].size >= 0;
  5083.        info->num_regsets++)
  5084.     ;
  5085. }
  5086. #endif

  5087. void
  5088. initialize_low (void)
  5089. {
  5090.   struct sigaction sigchld_action;
  5091.   memset (&sigchld_action, 0, sizeof (sigchld_action));
  5092.   set_target_ops (&linux_target_ops);
  5093.   set_breakpoint_data (the_low_target.breakpoint,
  5094.                        the_low_target.breakpoint_len);
  5095.   linux_init_signals ();
  5096.   linux_ptrace_init_warnings ();

  5097.   sigchld_action.sa_handler = sigchld_handler;
  5098.   sigemptyset (&sigchld_action.sa_mask);
  5099.   sigchld_action.sa_flags = SA_RESTART;
  5100.   sigaction (SIGCHLD, &sigchld_action, NULL);

  5101.   initialize_low_arch ();
  5102. }