ed2ef37471dd637e733b154f74a0fc2c424fc8c0
[external/binutils.git] / gdb / nto-procfs.c
1 /* Machine independent support for QNX Neutrino /proc (process file system)
2    for GDB.  Written by Colin Burgess at QNX Software Systems Limited.
3
4    Copyright (C) 2003-2018 Free Software Foundation, Inc.
5
6    Contributed by QNX Software Systems Ltd.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24
25 #include <fcntl.h>
26 #include <spawn.h>
27 #include <sys/debug.h>
28 #include <sys/procfs.h>
29 #include <sys/neutrino.h>
30 #include <sys/syspage.h>
31 #include <dirent.h>
32 #include <sys/netmgr.h>
33 #include <sys/auxv.h>
34
35 #include "gdbcore.h"
36 #include "inferior.h"
37 #include "target.h"
38 #include "objfiles.h"
39 #include "gdbthread.h"
40 #include "nto-tdep.h"
41 #include "command.h"
42 #include "regcache.h"
43 #include "solib.h"
44 #include "inf-child.h"
45 #include "common/filestuff.h"
46 #include "common/scoped_fd.h"
47
48 #define NULL_PID                0
49 #define _DEBUG_FLAG_TRACE       (_DEBUG_FLAG_TRACE_EXEC|_DEBUG_FLAG_TRACE_RD|\
50                 _DEBUG_FLAG_TRACE_WR|_DEBUG_FLAG_TRACE_MODIFY)
51
52 int ctl_fd;
53
54 static sighandler_t ofunc;
55
56 static procfs_run run;
57
58 /* Create the "native" and "procfs" targets.  */
59
60 struct nto_procfs_target : public inf_child_target
61 {
62   void open (const char *arg, int from_tty) override;
63
64   void attach (const char *, int) override = 0;
65
66   void post_attach (int);
67
68   void detach (inferior *, int) override;
69
70   void resume (ptid_t, int, enum gdb_signal) override;
71
72   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
73
74   void fetch_registers (struct regcache *, int) override;
75   void store_registers (struct regcache *, int) override;
76
77   enum target_xfer_status xfer_partial (enum target_object object,
78                                         const char *annex,
79                                         gdb_byte *readbuf,
80                                         const gdb_byte *writebuf,
81                                         ULONGEST offset, ULONGEST len,
82                                         ULONGEST *xfered_len) override;
83
84   void files_info () override;
85
86   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
87
88   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
89                          enum remove_bp_reason) override;
90
91   int can_use_hw_breakpoint (enum bptype, int, int) override;
92
93   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
94
95   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
96
97   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
98                          struct expression *) override;
99
100   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
101                          struct expression *) override;
102
103   bool stopped_by_watchpoint () override;
104
105   void kill () override;
106
107   void create_inferior (const char *, const std::string &,
108                         char **, int) override;
109
110   void mourn_inferior () override;
111
112   void pass_signals (int, unsigned char *) override;
113
114   bool thread_alive (ptid_t ptid) override;
115
116   void update_thread_list () override;
117
118   const char *pid_to_str (ptid_t) override;
119
120   void interrupt () override;
121
122   const char *extra_thread_info (struct thread_info *) override;
123
124   char *pid_to_exec_file (int pid) override;
125 };
126
127 /* For "target native".  */
128
129 static const target_info nto_native_target_info = {
130   "native",
131   N_("QNX Neutrino local process"),
132   N_("QNX Neutrino local process (started by the \"run\" command).")
133 };
134
135 class nto_procfs_target_native final : public nto_procfs_target
136 {
137   const target_info &info () const override
138   { return nto_native_target_info; }
139 };
140
141 /* For "target procfs <node>".  */
142
143 static const target_info nto_procfs_target_info = {
144   "procfs",
145   N_("QNX Neutrino local or remote process"),
146   N_("QNX Neutrino process.  target procfs NODE")
147 };
148
149 struct nto_procfs_target_procfs final : public nto_procfs_target
150 {
151   const target_info &info () const override
152   { return nto_procfs_target_info; }
153 };
154
155 static ptid_t do_attach (ptid_t ptid);
156
157 /* These two globals are only ever set in procfs_open_1, but are
158    referenced elsewhere.  'nto_procfs_node' is a flag used to say
159    whether we are local, or we should get the current node descriptor
160    for the remote QNX node.  */
161 static char *nodestr;
162 static unsigned nto_procfs_node = ND_LOCAL_NODE;
163
164 /* Return the current QNX Node, or error out.  This is a simple
165    wrapper for the netmgr_strtond() function.  The reason this
166    is required is because QNX node descriptors are transient so
167    we have to re-acquire them every time.  */
168 static unsigned
169 nto_node (void)
170 {
171   unsigned node;
172
173   if (ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) == 0
174       || nodestr == NULL)
175     return ND_LOCAL_NODE;
176
177   node = netmgr_strtond (nodestr, 0);
178   if (node == -1)
179     error (_("Lost the QNX node.  Debug session probably over."));
180
181   return (node);
182 }
183
184 static enum gdb_osabi
185 procfs_is_nto_target (bfd *abfd)
186 {
187   return GDB_OSABI_QNXNTO;
188 }
189
190 /* This is called when we call 'target native' or 'target procfs
191    <arg>' from the (gdb) prompt.  For QNX6 (nto), the only valid arg
192    will be a QNX node string, eg: "/net/some_node".  If arg is not a
193    valid QNX node, we will default to local.  */
194 void
195 nto_procfs_target::open (const char *arg, int from_tty)
196 {
197   char *endstr;
198   char buffer[50];
199   int total_size;
200   procfs_sysinfo *sysinfo;
201   char nto_procfs_path[PATH_MAX];
202
203   /* Offer to kill previous inferiors before opening this target.  */
204   target_preopen (from_tty);
205
206   nto_is_nto_target = procfs_is_nto_target;
207
208   /* Set the default node used for spawning to this one,
209      and only override it if there is a valid arg.  */
210
211   xfree (nodestr);
212   nodestr = NULL;
213
214   nto_procfs_node = ND_LOCAL_NODE;
215   nodestr = (arg != NULL) ? xstrdup (arg) : NULL;
216
217   init_thread_list ();
218
219   if (nodestr)
220     {
221       nto_procfs_node = netmgr_strtond (nodestr, &endstr);
222       if (nto_procfs_node == -1)
223         {
224           if (errno == ENOTSUP)
225             printf_filtered ("QNX Net Manager not found.\n");
226           printf_filtered ("Invalid QNX node %s: error %d (%s).\n", nodestr,
227                            errno, safe_strerror (errno));
228           xfree (nodestr);
229           nodestr = NULL;
230           nto_procfs_node = ND_LOCAL_NODE;
231         }
232       else if (*endstr)
233         {
234           if (*(endstr - 1) == '/')
235             *(endstr - 1) = 0;
236           else
237             *endstr = 0;
238         }
239     }
240   snprintf (nto_procfs_path, PATH_MAX - 1, "%s%s",
241             (nodestr != NULL) ? nodestr : "", "/proc");
242
243   scoped_fd fd (open (nto_procfs_path, O_RDONLY));
244   if (fd.get () == -1)
245     {
246       printf_filtered ("Error opening %s : %d (%s)\n", nto_procfs_path, errno,
247                        safe_strerror (errno));
248       error (_("Invalid procfs arg"));
249     }
250
251   sysinfo = (void *) buffer;
252   if (devctl (fd.get (), DCMD_PROC_SYSINFO, sysinfo, sizeof buffer, 0) != EOK)
253     {
254       printf_filtered ("Error getting size: %d (%s)\n", errno,
255                        safe_strerror (errno));
256       error (_("Devctl failed."));
257     }
258   else
259     {
260       total_size = sysinfo->total_size;
261       sysinfo = alloca (total_size);
262       if (sysinfo == NULL)
263         {
264           printf_filtered ("Memory error: %d (%s)\n", errno,
265                            safe_strerror (errno));
266           error (_("alloca failed."));
267         }
268       else
269         {
270           if (devctl (fd.get (), DCMD_PROC_SYSINFO, sysinfo, total_size, 0)
271               != EOK)
272             {
273               printf_filtered ("Error getting sysinfo: %d (%s)\n", errno,
274                                safe_strerror (errno));
275               error (_("Devctl failed."));
276             }
277           else
278             {
279               if (sysinfo->type !=
280                   nto_map_arch_to_cputype (gdbarch_bfd_arch_info
281                                            (target_gdbarch ())->arch_name))
282                 error (_("Invalid target CPU."));
283             }
284         }
285     }
286
287   inf_child_target::open (arg, from_tty);
288   printf_filtered ("Debugging using %s\n", nto_procfs_path);
289 }
290
291 static void
292 procfs_set_thread (ptid_t ptid)
293 {
294   pid_t tid;
295
296   tid = ptid.tid ();
297   devctl (ctl_fd, DCMD_PROC_CURTHREAD, &tid, sizeof (tid), 0);
298 }
299
300 /*  Return true if the thread TH is still alive.  */
301
302 bool
303 nto_procfs_target::thread_alive (ptid_t ptid)
304 {
305   pid_t tid;
306   pid_t pid;
307   procfs_status status;
308   int err;
309
310   tid = ptid.tid ();
311   pid = ptid.pid ();
312
313   if (kill (pid, 0) == -1)
314     return false;
315
316   status.tid = tid;
317   if ((err = devctl (ctl_fd, DCMD_PROC_TIDSTATUS,
318                      &status, sizeof (status), 0)) != EOK)
319     return false;
320
321   /* Thread is alive or dead but not yet joined,
322      or dead and there is an alive (or dead unjoined) thread with
323      higher tid.
324
325      If the tid is not the same as requested, requested tid is dead.  */
326   return (status.tid == tid) && (status.state != STATE_DEAD);
327 }
328
329 static void
330 update_thread_private_data_name (struct thread_info *new_thread,
331                                  const char *newname)
332 {
333   nto_thread_info *pti = get_nto_thread_info (new_thread);
334
335   gdb_assert (newname != NULL);
336   gdb_assert (new_thread != NULL);
337
338   if (pti)
339     {
340       pti = new nto_thread_info;
341       new_thread->priv.reset (pti);
342     }
343
344   pti->name = newname;
345 }
346
347 static void 
348 update_thread_private_data (struct thread_info *new_thread, 
349                             pthread_t tid, int state, int flags)
350 {
351   procfs_info pidinfo;
352   struct _thread_name *tn;
353   procfs_threadctl tctl;
354
355 #if _NTO_VERSION > 630
356   gdb_assert (new_thread != NULL);
357
358   if (devctl (ctl_fd, DCMD_PROC_INFO, &pidinfo,
359               sizeof(pidinfo), 0) != EOK)
360     return;
361
362   memset (&tctl, 0, sizeof (tctl));
363   tctl.cmd = _NTO_TCTL_NAME;
364   tn = (struct _thread_name *) (&tctl.data);
365
366   /* Fetch name for the given thread.  */
367   tctl.tid = tid;
368   tn->name_buf_len = sizeof (tctl.data) - sizeof (*tn);
369   tn->new_name_len = -1; /* Getting, not setting.  */
370   if (devctl (ctl_fd, DCMD_PROC_THREADCTL, &tctl, sizeof (tctl), NULL) != EOK)
371     tn->name_buf[0] = '\0';
372
373   tn->name_buf[_NTO_THREAD_NAME_MAX] = '\0';
374
375   update_thread_private_data_name (new_thread, tn->name_buf);
376
377   nto_thread_info *pti = get_nto_thread_info (new_thread);
378   pti->tid = tid;
379   pti->state = state;
380   pti->flags = flags;
381 #endif /* _NTO_VERSION */
382 }
383
384 void
385 nto_procfs_target::update_thread_list ()
386 {
387   procfs_status status;
388   pid_t pid;
389   ptid_t ptid;
390   pthread_t tid;
391   struct thread_info *new_thread;
392
393   if (ctl_fd == -1)
394     return;
395
396   prune_threads ();
397
398   pid = inferior_ptid.pid ();
399
400   status.tid = 1;
401
402   for (tid = 1;; ++tid)
403     {
404       if (status.tid == tid 
405           && (devctl (ctl_fd, DCMD_PROC_TIDSTATUS, &status, sizeof (status), 0)
406               != EOK))
407         break;
408       if (status.tid != tid)
409         /* The reason why this would not be equal is that devctl might have 
410            returned different tid, meaning the requested tid no longer exists
411            (e.g. thread exited).  */
412         continue;
413       ptid = ptid_t (pid, 0, tid);
414       new_thread = find_thread_ptid (ptid);
415       if (!new_thread)
416         new_thread = add_thread (ptid);
417       update_thread_private_data (new_thread, tid, status.state, 0);
418       status.tid++;
419     }
420   return;
421 }
422
423 static void
424 procfs_pidlist (const char *args, int from_tty)
425 {
426   struct dirent *dirp = NULL;
427   char buf[PATH_MAX];
428   procfs_info *pidinfo = NULL;
429   procfs_debuginfo *info = NULL;
430   procfs_status *status = NULL;
431   pid_t num_threads = 0;
432   pid_t pid;
433   char name[512];
434   char procfs_dir[PATH_MAX];
435
436   snprintf (procfs_dir, sizeof (procfs_dir), "%s%s",
437             (nodestr != NULL) ? nodestr : "", "/proc");
438
439   gdb_dir_up dp (opendir (procfs_dir));
440   if (dp == NULL)
441     {
442       fprintf_unfiltered (gdb_stderr, "failed to opendir \"%s\" - %d (%s)",
443                           procfs_dir, errno, safe_strerror (errno));
444       return;
445     }
446
447   /* Start scan at first pid.  */
448   rewinddir (dp.get ());
449
450   do
451     {
452       /* Get the right pid and procfs path for the pid.  */
453       do
454         {
455           dirp = readdir (dp.get ());
456           if (dirp == NULL)
457             return;
458           snprintf (buf, sizeof (buf), "%s%s/%s/as",
459                     (nodestr != NULL) ? nodestr : "",
460                     "/proc", dirp->d_name);
461           pid = atoi (dirp->d_name);
462         }
463       while (pid == 0);
464
465       /* Open the procfs path.  */
466       scoped_fd fd (open (buf, O_RDONLY));
467       if (fd.get () == -1)
468         {
469           fprintf_unfiltered (gdb_stderr, "failed to open %s - %d (%s)\n",
470                               buf, errno, safe_strerror (errno));
471           continue;
472         }
473
474       pidinfo = (procfs_info *) buf;
475       if (devctl (fd.get (), DCMD_PROC_INFO, pidinfo, sizeof (buf), 0) != EOK)
476         {
477           fprintf_unfiltered (gdb_stderr,
478                               "devctl DCMD_PROC_INFO failed - %d (%s)\n",
479                               errno, safe_strerror (errno));
480           break;
481         }
482       num_threads = pidinfo->num_threads;
483
484       info = (procfs_debuginfo *) buf;
485       if (devctl (fd.get (), DCMD_PROC_MAPDEBUG_BASE, info, sizeof (buf), 0)
486           != EOK)
487         strcpy (name, "unavailable");
488       else
489         strcpy (name, info->path);
490
491       /* Collect state info on all the threads.  */
492       status = (procfs_status *) buf;
493       for (status->tid = 1; status->tid <= num_threads; status->tid++)
494         {
495           const int err
496             = devctl (fd.get (), DCMD_PROC_TIDSTATUS, status, sizeof (buf), 0);
497           printf_filtered ("%s - %d", name, pid);
498           if (err == EOK && status->tid != 0)
499             printf_filtered ("/%d\n", status->tid);
500           else
501             {
502               printf_filtered ("\n");
503               break;
504             }
505         }
506     }
507   while (dirp != NULL);
508 }
509
510 static void
511 procfs_meminfo (const char *args, int from_tty)
512 {
513   procfs_mapinfo *mapinfos = NULL;
514   static int num_mapinfos = 0;
515   procfs_mapinfo *mapinfo_p, *mapinfo_p2;
516   int flags = ~0, err, num, i, j;
517
518   struct
519   {
520     procfs_debuginfo info;
521     char buff[_POSIX_PATH_MAX];
522   } map;
523
524   struct info
525   {
526     unsigned addr;
527     unsigned size;
528     unsigned flags;
529     unsigned debug_vaddr;
530     unsigned long long offset;
531   };
532
533   struct printinfo
534   {
535     unsigned long long ino;
536     unsigned dev;
537     struct info text;
538     struct info data;
539     char name[256];
540   } printme;
541
542   /* Get the number of map entrys.  */
543   err = devctl (ctl_fd, DCMD_PROC_MAPINFO, NULL, 0, &num);
544   if (err != EOK)
545     {
546       printf ("failed devctl num mapinfos - %d (%s)\n", err,
547               safe_strerror (err));
548       return;
549     }
550
551   mapinfos = XNEWVEC (procfs_mapinfo, num);
552
553   num_mapinfos = num;
554   mapinfo_p = mapinfos;
555
556   /* Fill the map entrys.  */
557   err = devctl (ctl_fd, DCMD_PROC_MAPINFO, mapinfo_p, num
558                 * sizeof (procfs_mapinfo), &num);
559   if (err != EOK)
560     {
561       printf ("failed devctl mapinfos - %d (%s)\n", err, safe_strerror (err));
562       xfree (mapinfos);
563       return;
564     }
565
566   num = std::min (num, num_mapinfos);
567
568   /* Run through the list of mapinfos, and store the data and text info
569      so we can print it at the bottom of the loop.  */
570   for (mapinfo_p = mapinfos, i = 0; i < num; i++, mapinfo_p++)
571     {
572       if (!(mapinfo_p->flags & flags))
573         mapinfo_p->ino = 0;
574
575       if (mapinfo_p->ino == 0)  /* Already visited.  */
576         continue;
577
578       map.info.vaddr = mapinfo_p->vaddr;
579
580       err = devctl (ctl_fd, DCMD_PROC_MAPDEBUG, &map, sizeof (map), 0);
581       if (err != EOK)
582         continue;
583
584       memset (&printme, 0, sizeof printme);
585       printme.dev = mapinfo_p->dev;
586       printme.ino = mapinfo_p->ino;
587       printme.text.addr = mapinfo_p->vaddr;
588       printme.text.size = mapinfo_p->size;
589       printme.text.flags = mapinfo_p->flags;
590       printme.text.offset = mapinfo_p->offset;
591       printme.text.debug_vaddr = map.info.vaddr;
592       strcpy (printme.name, map.info.path);
593
594       /* Check for matching data.  */
595       for (mapinfo_p2 = mapinfos, j = 0; j < num; j++, mapinfo_p2++)
596         {
597           if (mapinfo_p2->vaddr != mapinfo_p->vaddr
598               && mapinfo_p2->ino == mapinfo_p->ino
599               && mapinfo_p2->dev == mapinfo_p->dev)
600             {
601               map.info.vaddr = mapinfo_p2->vaddr;
602               err =
603                 devctl (ctl_fd, DCMD_PROC_MAPDEBUG, &map, sizeof (map), 0);
604               if (err != EOK)
605                 continue;
606
607               if (strcmp (map.info.path, printme.name))
608                 continue;
609
610               /* Lower debug_vaddr is always text, if nessessary, swap.  */
611               if ((int) map.info.vaddr < (int) printme.text.debug_vaddr)
612                 {
613                   memcpy (&(printme.data), &(printme.text),
614                           sizeof (printme.data));
615                   printme.text.addr = mapinfo_p2->vaddr;
616                   printme.text.size = mapinfo_p2->size;
617                   printme.text.flags = mapinfo_p2->flags;
618                   printme.text.offset = mapinfo_p2->offset;
619                   printme.text.debug_vaddr = map.info.vaddr;
620                 }
621               else
622                 {
623                   printme.data.addr = mapinfo_p2->vaddr;
624                   printme.data.size = mapinfo_p2->size;
625                   printme.data.flags = mapinfo_p2->flags;
626                   printme.data.offset = mapinfo_p2->offset;
627                   printme.data.debug_vaddr = map.info.vaddr;
628                 }
629               mapinfo_p2->ino = 0;
630             }
631         }
632       mapinfo_p->ino = 0;
633
634       printf_filtered ("%s\n", printme.name);
635       printf_filtered ("\ttext=%08x bytes @ 0x%08x\n", printme.text.size,
636                        printme.text.addr);
637       printf_filtered ("\t\tflags=%08x\n", printme.text.flags);
638       printf_filtered ("\t\tdebug=%08x\n", printme.text.debug_vaddr);
639       printf_filtered ("\t\toffset=%s\n", phex (printme.text.offset, 8));
640       if (printme.data.size)
641         {
642           printf_filtered ("\tdata=%08x bytes @ 0x%08x\n", printme.data.size,
643                            printme.data.addr);
644           printf_filtered ("\t\tflags=%08x\n", printme.data.flags);
645           printf_filtered ("\t\tdebug=%08x\n", printme.data.debug_vaddr);
646           printf_filtered ("\t\toffset=%s\n", phex (printme.data.offset, 8));
647         }
648       printf_filtered ("\tdev=0x%x\n", printme.dev);
649       printf_filtered ("\tino=0x%x\n", (unsigned int) printme.ino);
650     }
651   xfree (mapinfos);
652   return;
653 }
654
655 /* Print status information about what we're accessing.  */
656 void
657 nto_procfs_target::files_info ()
658 {
659   struct inferior *inf = current_inferior ();
660
661   printf_unfiltered ("\tUsing the running image of %s %s via %s.\n",
662                      inf->attach_flag ? "attached" : "child",
663                      target_pid_to_str (inferior_ptid),
664                      (nodestr != NULL) ? nodestr : "local node");
665 }
666
667 /* Target to_pid_to_exec_file implementation.  */
668
669 char *
670 nto_procfs_target::pid_to_exec_file (const int pid)
671 {
672   int proc_fd;
673   static char proc_path[PATH_MAX];
674   ssize_t rd;
675
676   /* Read exe file name.  */
677   snprintf (proc_path, sizeof (proc_path), "%s/proc/%d/exefile",
678             (nodestr != NULL) ? nodestr : "", pid);
679   proc_fd = open (proc_path, O_RDONLY);
680   if (proc_fd == -1)
681     return NULL;
682
683   rd = read (proc_fd, proc_path, sizeof (proc_path) - 1);
684   close (proc_fd);
685   if (rd <= 0)
686     {
687       proc_path[0] = '\0';
688       return NULL;
689     }
690   proc_path[rd] = '\0';
691   return proc_path;
692 }
693
694 /* Attach to process PID, then initialize for debugging it.  */
695 void
696 nto_procfs_target::attach (const char *args, int from_tty)
697 {
698   char *exec_file;
699   int pid;
700   struct inferior *inf;
701
702   pid = parse_pid_to_attach (args);
703
704   if (pid == getpid ())
705     error (_("Attaching GDB to itself is not a good idea..."));
706
707   if (from_tty)
708     {
709       exec_file = (char *) get_exec_file (0);
710
711       if (exec_file)
712         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
713                            target_pid_to_str (ptid_t (pid)));
714       else
715         printf_unfiltered ("Attaching to %s\n",
716                            target_pid_to_str (ptid_t (pid)));
717
718       gdb_flush (gdb_stdout);
719     }
720   inferior_ptid = do_attach (ptid_t (pid));
721   inf = current_inferior ();
722   inferior_appeared (inf, pid);
723   inf->attach_flag = 1;
724
725   if (!target_is_pushed (ops))
726     push_target (ops);
727
728   procfs_update_thread_list (ops);
729 }
730
731 void
732 nto_procfs_target::post_attach (pid_t pid)
733 {
734   if (exec_bfd)
735     solib_create_inferior_hook (0);
736 }
737
738 static ptid_t
739 do_attach (ptid_t ptid)
740 {
741   procfs_status status;
742   struct sigevent event;
743   char path[PATH_MAX];
744
745   snprintf (path, PATH_MAX - 1, "%s%s/%d/as",
746             (nodestr != NULL) ? nodestr : "", "/proc", ptid.pid ());
747   ctl_fd = open (path, O_RDWR);
748   if (ctl_fd == -1)
749     error (_("Couldn't open proc file %s, error %d (%s)"), path, errno,
750            safe_strerror (errno));
751   if (devctl (ctl_fd, DCMD_PROC_STOP, &status, sizeof (status), 0) != EOK)
752     error (_("Couldn't stop process"));
753
754   /* Define a sigevent for process stopped notification.  */
755   event.sigev_notify = SIGEV_SIGNAL_THREAD;
756   event.sigev_signo = SIGUSR1;
757   event.sigev_code = 0;
758   event.sigev_value.sival_ptr = NULL;
759   event.sigev_priority = -1;
760   devctl (ctl_fd, DCMD_PROC_EVENT, &event, sizeof (event), 0);
761
762   if (devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0) == EOK
763       && status.flags & _DEBUG_FLAG_STOPPED)
764     SignalKill (nto_node (), ptid.pid (), 0, SIGCONT, 0, 0);
765   nto_init_solib_absolute_prefix ();
766   return ptid_t (ptid.pid (), 0, status.tid);
767 }
768
769 /* Ask the user what to do when an interrupt is received.  */
770 static void
771 interrupt_query (void)
772 {
773   if (query (_("Interrupted while waiting for the program.\n\
774 Give up (and stop debugging it)? ")))
775     {
776       target_mourn_inferior (inferior_ptid);
777       quit ();
778     }
779 }
780
781 /* The user typed ^C twice.  */
782 static void
783 nto_handle_sigint_twice (int signo)
784 {
785   signal (signo, ofunc);
786   interrupt_query ();
787   signal (signo, nto_handle_sigint_twice);
788 }
789
790 static void
791 nto_handle_sigint (int signo)
792 {
793   /* If this doesn't work, try more severe steps.  */
794   signal (signo, nto_handle_sigint_twice);
795
796   target_interrupt ();
797 }
798
799 sptid_t
800 nto_procfs_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
801                          int options)
802 {
803   sigset_t set;
804   siginfo_t info;
805   procfs_status status;
806   static int exit_signo = 0;    /* To track signals that cause termination.  */
807
808   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
809
810   if (inferior_ptid == null_ptid)
811     {
812       ourstatus->kind = TARGET_WAITKIND_STOPPED;
813       ourstatus->value.sig = GDB_SIGNAL_0;
814       exit_signo = 0;
815       return null_ptid;
816     }
817
818   sigemptyset (&set);
819   sigaddset (&set, SIGUSR1);
820
821   devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
822   while (!(status.flags & _DEBUG_FLAG_ISTOP))
823     {
824       ofunc = signal (SIGINT, nto_handle_sigint);
825       sigwaitinfo (&set, &info);
826       signal (SIGINT, ofunc);
827       devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
828     }
829
830   nto_inferior_data (NULL)->stopped_flags = status.flags;
831   nto_inferior_data (NULL)->stopped_pc = status.ip;
832
833   if (status.flags & _DEBUG_FLAG_SSTEP)
834     {
835       ourstatus->kind = TARGET_WAITKIND_STOPPED;
836       ourstatus->value.sig = GDB_SIGNAL_TRAP;
837     }
838   /* Was it a breakpoint?  */
839   else if (status.flags & _DEBUG_FLAG_TRACE)
840     {
841       ourstatus->kind = TARGET_WAITKIND_STOPPED;
842       ourstatus->value.sig = GDB_SIGNAL_TRAP;
843     }
844   else if (status.flags & _DEBUG_FLAG_ISTOP)
845     {
846       switch (status.why)
847         {
848         case _DEBUG_WHY_SIGNALLED:
849           ourstatus->kind = TARGET_WAITKIND_STOPPED;
850           ourstatus->value.sig =
851             gdb_signal_from_host (status.info.si_signo);
852           exit_signo = 0;
853           break;
854         case _DEBUG_WHY_FAULTED:
855           ourstatus->kind = TARGET_WAITKIND_STOPPED;
856           if (status.info.si_signo == SIGTRAP)
857             {
858               ourstatus->value.sig = 0;
859               exit_signo = 0;
860             }
861           else
862             {
863               ourstatus->value.sig =
864                 gdb_signal_from_host (status.info.si_signo);
865               exit_signo = ourstatus->value.sig;
866             }
867           break;
868
869         case _DEBUG_WHY_TERMINATED:
870           {
871             int waitval = 0;
872
873             waitpid (inferior_ptid.pid (), &waitval, WNOHANG);
874             if (exit_signo)
875               {
876                 /* Abnormal death.  */
877                 ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
878                 ourstatus->value.sig = exit_signo;
879               }
880             else
881               {
882                 /* Normal death.  */
883                 ourstatus->kind = TARGET_WAITKIND_EXITED;
884                 ourstatus->value.integer = WEXITSTATUS (waitval);
885               }
886             exit_signo = 0;
887             break;
888           }
889
890         case _DEBUG_WHY_REQUESTED:
891           /* We are assuming a requested stop is due to a SIGINT.  */
892           ourstatus->kind = TARGET_WAITKIND_STOPPED;
893           ourstatus->value.sig = GDB_SIGNAL_INT;
894           exit_signo = 0;
895           break;
896         }
897     }
898
899   return ptid_t (status.pid, 0, status.tid);
900 }
901
902 /* Read the current values of the inferior's registers, both the
903    general register set and floating point registers (if supported)
904    and update gdb's idea of their current values.  */
905 void
906 nto_procfs_target::fetch_registers (struct regcache *regcache, int regno)
907 {
908   union
909   {
910     procfs_greg greg;
911     procfs_fpreg fpreg;
912     procfs_altreg altreg;
913   }
914   reg;
915   int regsize;
916
917   procfs_set_thread (regcache->ptid ());
918   if (devctl (ctl_fd, DCMD_PROC_GETGREG, &reg, sizeof (reg), &regsize) == EOK)
919     nto_supply_gregset (regcache, (char *) &reg.greg);
920   if (devctl (ctl_fd, DCMD_PROC_GETFPREG, &reg, sizeof (reg), &regsize)
921       == EOK)
922     nto_supply_fpregset (regcache, (char *) &reg.fpreg);
923   if (devctl (ctl_fd, DCMD_PROC_GETALTREG, &reg, sizeof (reg), &regsize)
924       == EOK)
925     nto_supply_altregset (regcache, (char *) &reg.altreg);
926 }
927
928 /* Helper for procfs_xfer_partial that handles memory transfers.
929    Arguments are like target_xfer_partial.  */
930
931 static enum target_xfer_status
932 procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
933                     ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
934 {
935   int nbytes;
936
937   if (lseek (ctl_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
938     return TARGET_XFER_E_IO;
939
940   if (writebuf != NULL)
941     nbytes = write (ctl_fd, writebuf, len);
942   else
943     nbytes = read (ctl_fd, readbuf, len);
944   if (nbytes <= 0)
945     return TARGET_XFER_E_IO;
946   *xfered_len = nbytes;
947   return TARGET_XFER_OK;
948 }
949
950 /* Target to_xfer_partial implementation.  */
951
952 enum target_xfer_status
953 nto_procfs_target::xfer_partial (enum target_object object,
954                                  const char *annex, gdb_byte *readbuf,
955                                  const gdb_byte *writebuf, ULONGEST offset,
956                                  ULONGEST len, ULONGEST *xfered_len)
957 {
958   switch (object)
959     {
960     case TARGET_OBJECT_MEMORY:
961       return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
962     case TARGET_OBJECT_AUXV:
963       if (readbuf != NULL)
964         {
965           int err;
966           CORE_ADDR initial_stack;
967           debug_process_t procinfo;
968           /* For 32-bit architecture, size of auxv_t is 8 bytes.  */
969           const unsigned int sizeof_auxv_t = sizeof (auxv_t);
970           const unsigned int sizeof_tempbuf = 20 * sizeof_auxv_t;
971           int tempread;
972           gdb_byte *const tempbuf = alloca (sizeof_tempbuf);
973
974           if (tempbuf == NULL)
975             return TARGET_XFER_E_IO;
976
977           err = devctl (ctl_fd, DCMD_PROC_INFO, &procinfo,
978                         sizeof procinfo, 0);
979           if (err != EOK)
980             return TARGET_XFER_E_IO;
981
982           initial_stack = procinfo.initial_stack;
983
984           /* procfs is always 'self-hosted', no byte-order manipulation.  */
985           tempread = nto_read_auxv_from_initial_stack (initial_stack, tempbuf,
986                                                        sizeof_tempbuf,
987                                                        sizeof (auxv_t));
988           tempread = std::min (tempread, len) - offset;
989           memcpy (readbuf, tempbuf + offset, tempread);
990           *xfered_len = tempread;
991           return tempread ? TARGET_XFER_OK : TARGET_XFER_EOF;
992         }
993         /* Fallthru */
994     default:
995       return this->beneath ()->xfer_partial (object, annex,
996                                              readbuf, writebuf, offset, len,
997                                              xfered_len);
998     }
999 }
1000
1001 /* Take a program previously attached to and detaches it.
1002    The program resumes execution and will no longer stop
1003    on signals, etc.  We'd better not have left any breakpoints
1004    in the program or it'll die when it hits one.  */
1005 void
1006 nto_procfs_target::detach (inferior *inf, int from_tty)
1007 {
1008   int pid;
1009
1010   target_announce_detach ();
1011
1012   if (siggnal)
1013     SignalKill (nto_node (), inferior_ptid.pid (), 0, 0, 0, 0);
1014
1015   close (ctl_fd);
1016   ctl_fd = -1;
1017
1018   pid = inferior_ptid.pid ();
1019   inferior_ptid = null_ptid;
1020   detach_inferior (pid);
1021   init_thread_list ();
1022   inf_child_maybe_unpush_target (ops);
1023 }
1024
1025 static int
1026 procfs_breakpoint (CORE_ADDR addr, int type, int size)
1027 {
1028   procfs_break brk;
1029
1030   brk.type = type;
1031   brk.addr = addr;
1032   brk.size = size;
1033   errno = devctl (ctl_fd, DCMD_PROC_BREAK, &brk, sizeof (brk), 0);
1034   if (errno != EOK)
1035     return 1;
1036   return 0;
1037 }
1038
1039 int
1040 nto_procfs_target::insert_breakpoint (struct gdbarch *gdbarch,
1041                                       struct bp_target_info *bp_tgt)
1042 {
1043   bp_tgt->placed_address = bp_tgt->reqstd_address;
1044   return procfs_breakpoint (bp_tgt->placed_address, _DEBUG_BREAK_EXEC, 0);
1045 }
1046
1047 int
1048 nto_procfs_target::remove_breakpoint (struct gdbarch *gdbarch,
1049                                       struct bp_target_info *bp_tgt,
1050                                       enum remove_bp_reason reason)
1051 {
1052   return procfs_breakpoint (bp_tgt->placed_address, _DEBUG_BREAK_EXEC, -1);
1053 }
1054
1055 int
1056 nto_procfs_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
1057                                          struct bp_target_info *bp_tgt)
1058 {
1059   bp_tgt->placed_address = bp_tgt->reqstd_address;
1060   return procfs_breakpoint (bp_tgt->placed_address,
1061                             _DEBUG_BREAK_EXEC | _DEBUG_BREAK_HW, 0);
1062 }
1063
1064 int
1065 nto_procfs_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
1066                                          struct bp_target_info *bp_tgt)
1067 {
1068   return procfs_breakpoint (bp_tgt->placed_address,
1069                             _DEBUG_BREAK_EXEC | _DEBUG_BREAK_HW, -1);
1070 }
1071
1072 void
1073 nto_procfs_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
1074 {
1075   int signal_to_pass;
1076   procfs_status status;
1077   sigset_t *run_fault = (sigset_t *) (void *) &run.fault;
1078
1079   if (inferior_ptid == null_ptid)
1080     return;
1081
1082   procfs_set_thread (ptid == minus_one_ptid ? inferior_ptid :
1083                      ptid);
1084
1085   run.flags = _DEBUG_RUN_FAULT | _DEBUG_RUN_TRACE;
1086   if (step)
1087     run.flags |= _DEBUG_RUN_STEP;
1088
1089   sigemptyset (run_fault);
1090   sigaddset (run_fault, FLTBPT);
1091   sigaddset (run_fault, FLTTRACE);
1092   sigaddset (run_fault, FLTILL);
1093   sigaddset (run_fault, FLTPRIV);
1094   sigaddset (run_fault, FLTBOUNDS);
1095   sigaddset (run_fault, FLTIOVF);
1096   sigaddset (run_fault, FLTIZDIV);
1097   sigaddset (run_fault, FLTFPE);
1098   /* Peter V will be changing this at some point.  */
1099   sigaddset (run_fault, FLTPAGE);
1100
1101   run.flags |= _DEBUG_RUN_ARM;
1102
1103   signal_to_pass = gdb_signal_to_host (signo);
1104
1105   if (signal_to_pass)
1106     {
1107       devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
1108       signal_to_pass = gdb_signal_to_host (signo);
1109       if (status.why & (_DEBUG_WHY_SIGNALLED | _DEBUG_WHY_FAULTED))
1110         {
1111           if (signal_to_pass != status.info.si_signo)
1112             {
1113               SignalKill (nto_node (), inferior_ptid.pid (), 0,
1114                           signal_to_pass, 0, 0);
1115               run.flags |= _DEBUG_RUN_CLRFLT | _DEBUG_RUN_CLRSIG;
1116             }
1117           else          /* Let it kill the program without telling us.  */
1118             sigdelset (&run.trace, signal_to_pass);
1119         }
1120     }
1121   else
1122     run.flags |= _DEBUG_RUN_CLRSIG | _DEBUG_RUN_CLRFLT;
1123
1124   errno = devctl (ctl_fd, DCMD_PROC_RUN, &run, sizeof (run), 0);
1125   if (errno != EOK)
1126     {
1127       perror (_("run error!\n"));
1128       return;
1129     }
1130 }
1131
1132 void
1133 nto_procfs_target::mourn_inferior ()
1134 {
1135   if (inferior_ptid != null_ptid)
1136     {
1137       SignalKill (nto_node (), inferior_ptid.pid (), 0, SIGKILL, 0, 0);
1138       close (ctl_fd);
1139     }
1140   inferior_ptid = null_ptid;
1141   init_thread_list ();
1142   inf_child_mourn_inferior (ops);
1143 }
1144
1145 /* This function breaks up an argument string into an argument
1146    vector suitable for passing to execvp().
1147    E.g., on "run a b c d" this routine would get as input
1148    the string "a b c d", and as output it would fill in argv with
1149    the four arguments "a", "b", "c", "d".  The only additional
1150    functionality is simple quoting.  The gdb command:
1151         run a "b c d" f
1152    will fill in argv with the three args "a", "b c d", "e".  */
1153 static void
1154 breakup_args (char *scratch, char **argv)
1155 {
1156   char *pp, *cp = scratch;
1157   char quoting = 0;
1158
1159   for (;;)
1160     {
1161       /* Scan past leading separators.  */
1162       quoting = 0;
1163       while (*cp == ' ' || *cp == '\t' || *cp == '\n')
1164         cp++;
1165
1166       /* Break if at end of string.  */
1167       if (*cp == '\0')
1168         break;
1169
1170       /* Take an arg.  */
1171       if (*cp == '"')
1172         {
1173           cp++;
1174           quoting = strchr (cp, '"') ? 1 : 0;
1175         }
1176
1177       *argv++ = cp;
1178
1179       /* Scan for next arg separator.  */
1180       pp = cp;
1181       if (quoting)
1182         cp = strchr (pp, '"');
1183       if ((cp == NULL) || (!quoting))
1184         cp = strchr (pp, ' ');
1185       if (cp == NULL)
1186         cp = strchr (pp, '\t');
1187       if (cp == NULL)
1188         cp = strchr (pp, '\n');
1189
1190       /* No separators => end of string => break.  */
1191       if (cp == NULL)
1192         {
1193           pp = cp;
1194           break;
1195         }
1196
1197       /* Replace the separator with a terminator.  */
1198       *cp++ = '\0';
1199     }
1200
1201   /* Execv requires a null-terminated arg vector.  */
1202   *argv = NULL;
1203 }
1204
1205 void
1206 nto_procfs_target::create_inferior (const char *exec_file,
1207                                     const std::string &allargs,
1208                                     char **env, int from_tty)
1209 {
1210   struct inheritance inherit;
1211   pid_t pid;
1212   int flags, errn;
1213   char **argv, *args;
1214   const char *in = "", *out = "", *err = "";
1215   int fd, fds[3];
1216   sigset_t set;
1217   const char *inferior_io_terminal = get_inferior_io_terminal ();
1218   struct inferior *inf;
1219
1220   argv = xmalloc ((allargs.size () / (unsigned) 2 + 2) *
1221                   sizeof (*argv));
1222   argv[0] = get_exec_file (1);
1223   if (!argv[0])
1224     {
1225       if (exec_file)
1226         argv[0] = exec_file;
1227       else
1228         return;
1229     }
1230
1231   args = xstrdup (allargs.c_str ());
1232   breakup_args (args, (exec_file != NULL) ? &argv[1] : &argv[0]);
1233
1234   argv = nto_parse_redirection (argv, &in, &out, &err);
1235
1236   fds[0] = STDIN_FILENO;
1237   fds[1] = STDOUT_FILENO;
1238   fds[2] = STDERR_FILENO;
1239
1240   /* If the user specified I/O via gdb's --tty= arg, use it, but only
1241      if the i/o is not also being specified via redirection.  */
1242   if (inferior_io_terminal)
1243     {
1244       if (!in[0])
1245         in = inferior_io_terminal;
1246       if (!out[0])
1247         out = inferior_io_terminal;
1248       if (!err[0])
1249         err = inferior_io_terminal;
1250     }
1251
1252   if (in[0])
1253     {
1254       fd = open (in, O_RDONLY);
1255       if (fd == -1)
1256         perror (in);
1257       else
1258         fds[0] = fd;
1259     }
1260   if (out[0])
1261     {
1262       fd = open (out, O_WRONLY);
1263       if (fd == -1)
1264         perror (out);
1265       else
1266         fds[1] = fd;
1267     }
1268   if (err[0])
1269     {
1270       fd = open (err, O_WRONLY);
1271       if (fd == -1)
1272         perror (err);
1273       else
1274         fds[2] = fd;
1275     }
1276
1277   /* Clear any pending SIGUSR1's but keep the behavior the same.  */
1278   signal (SIGUSR1, signal (SIGUSR1, SIG_IGN));
1279
1280   sigemptyset (&set);
1281   sigaddset (&set, SIGUSR1);
1282   sigprocmask (SIG_UNBLOCK, &set, NULL);
1283
1284   memset (&inherit, 0, sizeof (inherit));
1285
1286   if (ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) != 0)
1287     {
1288       inherit.nd = nto_node ();
1289       inherit.flags |= SPAWN_SETND;
1290       inherit.flags &= ~SPAWN_EXEC;
1291     }
1292   inherit.flags |= SPAWN_SETGROUP | SPAWN_HOLD;
1293   inherit.pgroup = SPAWN_NEWPGROUP;
1294   pid = spawnp (argv[0], 3, fds, &inherit, argv,
1295                 ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) == 0 ? env : 0);
1296   xfree (args);
1297
1298   sigprocmask (SIG_BLOCK, &set, NULL);
1299
1300   if (pid == -1)
1301     error (_("Error spawning %s: %d (%s)"), argv[0], errno,
1302            safe_strerror (errno));
1303
1304   if (fds[0] != STDIN_FILENO)
1305     close (fds[0]);
1306   if (fds[1] != STDOUT_FILENO)
1307     close (fds[1]);
1308   if (fds[2] != STDERR_FILENO)
1309     close (fds[2]);
1310
1311   inferior_ptid = do_attach (ptid_t (pid));
1312   procfs_update_thread_list (ops);
1313
1314   inf = current_inferior ();
1315   inferior_appeared (inf, pid);
1316   inf->attach_flag = 0;
1317
1318   flags = _DEBUG_FLAG_KLC;      /* Kill-on-Last-Close flag.  */
1319   errn = devctl (ctl_fd, DCMD_PROC_SET_FLAG, &flags, sizeof (flags), 0);
1320   if (errn != EOK)
1321     {
1322       /* FIXME: expected warning?  */
1323       /* warning( "Failed to set Kill-on-Last-Close flag: errno = %d(%s)\n",
1324          errn, strerror(errn) ); */
1325     }
1326   if (!target_is_pushed (ops))
1327     push_target (ops);
1328   target_terminal::init ();
1329
1330   if (exec_bfd != NULL
1331       || (symfile_objfile != NULL && symfile_objfile->obfd != NULL))
1332     solib_create_inferior_hook (0);
1333 }
1334
1335 void
1336 nto_procfs_target::interrupt ()
1337 {
1338   devctl (ctl_fd, DCMD_PROC_STOP, NULL, 0, 0);
1339 }
1340
1341 void
1342 nto_procfs_target::kill ()
1343 {
1344   target_mourn_inferior (inferior_ptid);
1345 }
1346
1347 /* Fill buf with regset and return devctl cmd to do the setting.  Return
1348    -1 if we fail to get the regset.  Store size of regset in regsize.  */
1349 static int
1350 get_regset (int regset, char *buf, int bufsize, int *regsize)
1351 {
1352   int dev_get, dev_set;
1353   switch (regset)
1354     {
1355     case NTO_REG_GENERAL:
1356       dev_get = DCMD_PROC_GETGREG;
1357       dev_set = DCMD_PROC_SETGREG;
1358       break;
1359
1360     case NTO_REG_FLOAT:
1361       dev_get = DCMD_PROC_GETFPREG;
1362       dev_set = DCMD_PROC_SETFPREG;
1363       break;
1364
1365     case NTO_REG_ALT:
1366       dev_get = DCMD_PROC_GETALTREG;
1367       dev_set = DCMD_PROC_SETALTREG;
1368       break;
1369
1370     case NTO_REG_SYSTEM:
1371     default:
1372       return -1;
1373     }
1374   if (devctl (ctl_fd, dev_get, buf, bufsize, regsize) != EOK)
1375     return -1;
1376
1377   return dev_set;
1378 }
1379
1380 void
1381 nto_procfs_target::store_registers (struct regcache *regcache, int regno)
1382 {
1383   union
1384   {
1385     procfs_greg greg;
1386     procfs_fpreg fpreg;
1387     procfs_altreg altreg;
1388   }
1389   reg;
1390   unsigned off;
1391   int len, regset, regsize, dev_set, err;
1392   char *data;
1393   ptid_t ptid = regcache->ptid ();
1394
1395   if (ptid == null_ptid)
1396     return;
1397   procfs_set_thread (ptid);
1398
1399   if (regno == -1)
1400     {
1401       for (regset = NTO_REG_GENERAL; regset < NTO_REG_END; regset++)
1402         {
1403           dev_set = get_regset (regset, (char *) &reg,
1404                                 sizeof (reg), &regsize);
1405           if (dev_set == -1)
1406             continue;
1407
1408           if (nto_regset_fill (regcache, regset, (char *) &reg) == -1)
1409             continue;
1410
1411           err = devctl (ctl_fd, dev_set, &reg, regsize, 0);
1412           if (err != EOK)
1413             fprintf_unfiltered (gdb_stderr,
1414                                 "Warning unable to write regset %d: %s\n",
1415                                 regno, safe_strerror (err));
1416         }
1417     }
1418   else
1419     {
1420       regset = nto_regset_id (regno);
1421       if (regset == -1)
1422         return;
1423
1424       dev_set = get_regset (regset, (char *) &reg, sizeof (reg), &regsize);
1425       if (dev_set == -1)
1426         return;
1427
1428       len = nto_register_area (regcache->arch (),
1429                                regno, regset, &off);
1430
1431       if (len < 1)
1432         return;
1433
1434       regcache->raw_collect (regno, (char *) &reg + off);
1435
1436       err = devctl (ctl_fd, dev_set, &reg, regsize, 0);
1437       if (err != EOK)
1438         fprintf_unfiltered (gdb_stderr,
1439                             "Warning unable to write regset %d: %s\n", regno,
1440                             safe_strerror (err));
1441     }
1442 }
1443
1444 /* Set list of signals to be handled in the target.  */
1445
1446 void
1447 nto_procfs_target::pass_signals (int numsigs, unsigned char *pass_signals)
1448 {
1449   int signo;
1450
1451   sigfillset (&run.trace);
1452
1453   for (signo = 1; signo < NSIG; signo++)
1454     {
1455       int target_signo = gdb_signal_from_host (signo);
1456       if (target_signo < numsigs && pass_signals[target_signo])
1457         sigdelset (&run.trace, signo);
1458     }
1459 }
1460
1461 char *
1462 nto_procfs_target::pid_to_str (ptid_t ptid)
1463 {
1464   static char buf[1024];
1465   int pid, tid, n;
1466   struct tidinfo *tip;
1467
1468   pid = ptid.pid ();
1469   tid = ptid.tid ();
1470
1471   n = snprintf (buf, 1023, "process %d", pid);
1472
1473 #if 0                           /* NYI */
1474   tip = procfs_thread_info (pid, tid);
1475   if (tip != NULL)
1476     snprintf (&buf[n], 1023, " (state = 0x%02x)", tip->state);
1477 #endif
1478
1479   return buf;
1480 }
1481
1482 /* to_can_run implementation for "target procfs".  Note this really
1483   means "can this target be the default run target", which there can
1484   be only one, and we make it be "target native" like other ports.
1485   "target procfs <node>" wouldn't make sense as default run target, as
1486   it needs <node>.  */
1487
1488 int
1489 nto_procfs_target::can_run ()
1490 {
1491   return 0;
1492 }
1493
1494 /* "target procfs".  */
1495 static nto_procfs_target_procfs nto_procfs_ops;
1496
1497 /* "target native".  */
1498 static nto_procfs_target_native nto_native_ops;
1499
1500 /* Create the "native" and "procfs" targets.  */
1501
1502 static void
1503 init_procfs_targets (void)
1504 {
1505   /* Register "target native".  This is the default run target.  */
1506   add_target (nto_native_target_info, inf_child_open_target);
1507   set_native_target (&nto_native_ops);
1508
1509   /* Register "target procfs <node>".  */
1510   add_target (nto_procfs_target_info, inf_child_open_target);
1511 }
1512
1513 #define OSTYPE_NTO 1
1514
1515 void
1516 _initialize_procfs (void)
1517 {
1518   sigset_t set;
1519
1520   init_procfs_targets ();
1521
1522   /* We use SIGUSR1 to gain control after we block waiting for a process.
1523      We use sigwaitevent to wait.  */
1524   sigemptyset (&set);
1525   sigaddset (&set, SIGUSR1);
1526   sigprocmask (SIG_BLOCK, &set, NULL);
1527
1528   /* Initially, make sure all signals are reported.  */
1529   sigfillset (&run.trace);
1530
1531   /* Stuff some information.  */
1532   nto_cpuinfo_flags = SYSPAGE_ENTRY (cpuinfo)->flags;
1533   nto_cpuinfo_valid = 1;
1534
1535   add_info ("pidlist", procfs_pidlist, _("pidlist"));
1536   add_info ("meminfo", procfs_meminfo, _("memory information"));
1537
1538   nto_is_nto_target = procfs_is_nto_target;
1539 }
1540
1541
1542 static int
1543 procfs_hw_watchpoint (int addr, int len, enum target_hw_bp_type type)
1544 {
1545   procfs_break brk;
1546
1547   switch (type)
1548     {
1549     case hw_read:
1550       brk.type = _DEBUG_BREAK_RD;
1551       break;
1552     case hw_access:
1553       brk.type = _DEBUG_BREAK_RW;
1554       break;
1555     default:                    /* Modify.  */
1556 /* FIXME: brk.type = _DEBUG_BREAK_RWM gives EINVAL for some reason.  */
1557       brk.type = _DEBUG_BREAK_RW;
1558     }
1559   brk.type |= _DEBUG_BREAK_HW;  /* Always ask for HW.  */
1560   brk.addr = addr;
1561   brk.size = len;
1562
1563   errno = devctl (ctl_fd, DCMD_PROC_BREAK, &brk, sizeof (brk), 0);
1564   if (errno != EOK)
1565     {
1566       perror (_("Failed to set hardware watchpoint"));
1567       return -1;
1568     }
1569   return 0;
1570 }
1571
1572 bool
1573 nto_procfs_target::can_use_hw_breakpoint (enum bptype type,
1574                                           int cnt, int othertype)
1575 {
1576   return 1;
1577 }
1578
1579 int
1580 nto_procfs_target::remove_hw_watchpoint (CORE_ADDR addr, int len,
1581                                          enum target_hw_bp_type type,
1582                                          struct expression *cond)
1583 {
1584   return procfs_hw_watchpoint (addr, -1, type);
1585 }
1586
1587 int
1588 nto_procfs_target::insert_hw_watchpoint (CORE_ADDR addr, int len,
1589                                          enum target_hw_bp_type type,
1590                                          struct expression *cond)
1591 {
1592   return procfs_hw_watchpoint (addr, len, type);
1593 }
1594
1595 bool
1596 nto_procfs_target::stopped_by_watchpoint ()
1597 {
1598   /* NOTE: nto_stopped_by_watchpoint will be called ONLY while we are
1599      stopped due to a SIGTRAP.  This assumes gdb works in 'all-stop' mode;
1600      future gdb versions will likely run in 'non-stop' mode in which case
1601      we will have to store/examine statuses per thread in question.
1602      Until then, this will work fine.  */
1603
1604   struct inferior *inf = current_inferior ();
1605   struct nto_inferior_data *inf_data;
1606
1607   gdb_assert (inf != NULL);
1608
1609   inf_data = nto_inferior_data (inf);
1610
1611   return inf_data->stopped_flags
1612          & (_DEBUG_FLAG_TRACE_RD
1613             | _DEBUG_FLAG_TRACE_WR
1614             | _DEBUG_FLAG_TRACE_MODIFY);
1615 }