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