xref: /netbsd-src/external/gpl3/gdb/dist/gdbserver/netbsd-low.cc (revision 7d62b00eb9ad855ffcd7da46b41e23feb5476fac)
1 /* Copyright (C) 2020 Free Software Foundation, Inc.
2 
3    This file is part of GDB.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17 
18 #include "server.h"
19 #include "target.h"
20 #include "netbsd-low.h"
21 #include "nat/netbsd-nat.h"
22 
23 #include <sys/param.h>
24 #include <sys/types.h>
25 
26 #include <sys/ptrace.h>
27 #include <sys/sysctl.h>
28 
29 #include <limits.h>
30 #include <unistd.h>
31 #include <signal.h>
32 
33 #include <elf.h>
34 
35 #include <type_traits>
36 
37 #include "gdbsupport/eintr.h"
38 #include "gdbsupport/gdb_wait.h"
39 #include "gdbsupport/filestuff.h"
40 #include "gdbsupport/common-inferior.h"
41 #include "nat/fork-inferior.h"
42 #include "hostio.h"
43 
44 int using_threads = 1;
45 
46 const struct target_desc *netbsd_tdesc;
47 
48 /* Call add_process with the given parameters, and initialize
49    the process' private data.  */
50 
51 static void
52 netbsd_add_process (int pid, int attached)
53 {
54   struct process_info *proc = add_process (pid, attached);
55   proc->tdesc = netbsd_tdesc;
56   proc->priv = nullptr;
57 }
58 
59 /* Callback used by fork_inferior to start tracing the inferior.  */
60 
61 static void
62 netbsd_ptrace_fun ()
63 {
64   /* Switch child to its own process group so that signals won't
65      directly affect GDBserver. */
66   if (setpgid (0, 0) < 0)
67     trace_start_error_with_name (("setpgid"));
68 
69   if (ptrace (PT_TRACE_ME, 0, nullptr, 0) < 0)
70     trace_start_error_with_name (("ptrace"));
71 
72   /* If GDBserver is connected to gdb via stdio, redirect the inferior's
73      stdout to stderr so that inferior i/o doesn't corrupt the connection.
74      Also, redirect stdin to /dev/null.  */
75   if (remote_connection_is_stdio ())
76     {
77       if (close (0) < 0)
78 	trace_start_error_with_name (("close"));
79       if (open ("/dev/null", O_RDONLY) < 0)
80 	trace_start_error_with_name (("open"));
81       if (dup2 (2, 1) < 0)
82 	trace_start_error_with_name (("dup2"));
83       if (write (2, "stdin/stdout redirected\n",
84 		 sizeof ("stdin/stdout redirected\n") - 1) < 0)
85 	{
86 	  /* Errors ignored.  */
87 	}
88     }
89 }
90 
91 /* Implement the create_inferior method of the target_ops vector.  */
92 
93 int
94 netbsd_process_target::create_inferior (const char *program,
95 					const std::vector<char *> &program_args)
96 {
97   std::string str_program_args = construct_inferior_arguments (program_args);
98 
99   pid_t pid = fork_inferior (program, str_program_args.c_str (),
100 			     get_environ ()->envp (), netbsd_ptrace_fun,
101 			     nullptr, nullptr, nullptr, nullptr);
102 
103   netbsd_add_process (pid, 0);
104 
105   post_fork_inferior (pid, program);
106 
107   return pid;
108 }
109 
110 /* Implement the post_create_inferior target_ops method.  */
111 
112 void
113 netbsd_process_target::post_create_inferior ()
114 {
115   pid_t pid = current_process ()->pid;
116   netbsd_nat::enable_proc_events (pid);
117 }
118 
119 /* Implement the attach target_ops method.  */
120 
121 int
122 netbsd_process_target::attach (unsigned long pid)
123 {
124   /* Unimplemented.  */
125   return -1;
126 }
127 
128 /* Returns true if GDB is interested in any child syscalls.  */
129 
130 static bool
131 gdb_catching_syscalls_p (pid_t pid)
132 {
133   struct process_info *proc = find_process_pid (pid);
134   return !proc->syscalls_to_catch.empty ();
135 }
136 
137 /* Implement the resume target_ops method.  */
138 
139 void
140 netbsd_process_target::resume (struct thread_resume *resume_info, size_t n)
141 {
142   ptid_t resume_ptid = resume_info[0].thread;
143   const int signal = resume_info[0].sig;
144   const bool step = resume_info[0].kind == resume_step;
145 
146   if (resume_ptid == minus_one_ptid)
147     resume_ptid = ptid_of (current_thread);
148 
149   const pid_t pid = resume_ptid.pid ();
150   const lwpid_t lwp = resume_ptid.lwp ();
151   regcache_invalidate_pid (pid);
152 
153   auto fn
154     = [&] (ptid_t ptid)
155       {
156 	if (step)
157 	  {
158 	    if (ptid.lwp () == lwp || n != 1)
159 	      {
160 		if (ptrace (PT_SETSTEP, pid, NULL, ptid.lwp ()) == -1)
161 		  perror_with_name (("ptrace"));
162 		if (ptrace (PT_RESUME, pid, NULL, ptid.lwp ()) == -1)
163 		  perror_with_name (("ptrace"));
164 	      }
165 	    else
166 	      {
167 		if (ptrace (PT_CLEARSTEP, pid, NULL, ptid.lwp ()) == -1)
168 		  perror_with_name (("ptrace"));
169 		if (ptrace (PT_SUSPEND, pid, NULL, ptid.lwp ()) == -1)
170 		  perror_with_name (("ptrace"));
171 	      }
172 	  }
173 	else
174 	  {
175 	    if (ptrace (PT_CLEARSTEP, pid, NULL, ptid.lwp ()) == -1)
176 	      perror_with_name (("ptrace"));
177 	    if (ptrace (PT_RESUME, pid, NULL, ptid.lwp ()) == -1)
178 	      perror_with_name (("ptrace"));
179 	  }
180       };
181 
182   netbsd_nat::for_each_thread (pid, fn);
183 
184   int request = gdb_catching_syscalls_p (pid) ? PT_CONTINUE : PT_SYSCALL;
185 
186   errno = 0;
187   ptrace (request, pid, (void *)1, signal);
188   if (errno)
189     perror_with_name (("ptrace"));
190 }
191 
192 /* Returns true if GDB is interested in the reported SYSNO syscall.  */
193 
194 static bool
195 netbsd_catch_this_syscall (int sysno)
196 {
197   struct process_info *proc = current_process ();
198 
199   if (proc->syscalls_to_catch.empty ())
200     return false;
201 
202   if (proc->syscalls_to_catch[0] == ANY_SYSCALL)
203     return true;
204 
205   for (int iter : proc->syscalls_to_catch)
206     if (iter == sysno)
207       return true;
208 
209   return false;
210 }
211 
212 /* Helper function for child_wait and the derivatives of child_wait.
213    HOSTSTATUS is the waitstatus from wait() or the equivalent; store our
214    translation of that in OURSTATUS.  */
215 
216 static void
217 netbsd_store_waitstatus (struct target_waitstatus *ourstatus, int hoststatus)
218 {
219   if (WIFEXITED (hoststatus))
220     {
221       ourstatus->kind = TARGET_WAITKIND_EXITED;
222       ourstatus->value.integer = WEXITSTATUS (hoststatus);
223     }
224   else if (!WIFSTOPPED (hoststatus))
225     {
226       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
227       ourstatus->value.sig = gdb_signal_from_host (WTERMSIG (hoststatus));
228     }
229   else
230     {
231       ourstatus->kind = TARGET_WAITKIND_STOPPED;
232       ourstatus->value.sig = gdb_signal_from_host (WSTOPSIG (hoststatus));
233     }
234 }
235 
236 /* Implement a safe wrapper around waitpid().  */
237 
238 static pid_t
239 netbsd_waitpid (ptid_t ptid, struct target_waitstatus *ourstatus, int options)
240 {
241   int status;
242 
243   pid_t pid
244     = gdb::handle_eintr<int> (-1, ::waitpid, ptid.pid (), &status, options);
245 
246   if (pid == -1)
247     perror_with_name (_("Child process unexpectedly missing"));
248 
249   netbsd_store_waitstatus (ourstatus, status);
250   return pid;
251 }
252 
253 
254 /* Implement the wait target_ops method.
255 
256    Wait for the child specified by PTID to do something.  Return the
257    process ID of the child, or MINUS_ONE_PTID in case of error; store
258    the status in *OURSTATUS.  */
259 
260 static ptid_t
261 netbsd_wait (ptid_t ptid, struct target_waitstatus *ourstatus,
262 	     int target_options)
263 {
264   pid_t pid = netbsd_waitpid (ptid, ourstatus, target_options);
265   ptid_t wptid = ptid_t (pid);
266 
267   if (pid == 0)
268     {
269       gdb_assert (target_options & TARGET_WNOHANG);
270       ourstatus->kind = TARGET_WAITKIND_IGNORE;
271       return null_ptid;
272     }
273 
274   gdb_assert (pid != -1);
275 
276   /* If the child stopped, keep investigating its status.  */
277   if (ourstatus->kind != TARGET_WAITKIND_STOPPED)
278     return wptid;
279 
280   /* Extract the event and thread that received a signal.  */
281   ptrace_siginfo_t psi;
282   if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
283     perror_with_name (("ptrace"));
284 
285   /* Pick child's siginfo_t.  */
286   siginfo_t *si = &psi.psi_siginfo;
287 
288   lwpid_t lwp = psi.psi_lwpid;
289 
290   int signo = si->si_signo;
291   const int code = si->si_code;
292 
293   /* Construct PTID with a specified thread that received the event.
294      If a signal was targeted to the whole process, lwp is 0.  */
295   wptid = ptid_t (pid, lwp, 0);
296 
297   /* Bail out on non-debugger oriented signals.  */
298   if (signo != SIGTRAP)
299     return wptid;
300 
301   /* Stop examining non-debugger oriented SIGTRAP codes.  */
302   if (code <= SI_USER || code == SI_NOINFO)
303     return wptid;
304 
305   /* Process state for threading events.  */
306   ptrace_state_t pst = {};
307   if (code == TRAP_LWP)
308     if (ptrace (PT_GET_PROCESS_STATE, pid, &pst, sizeof (pst)) == -1)
309       perror_with_name (("ptrace"));
310 
311   if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_EXIT)
312     {
313       /* If GDB attaches to a multi-threaded process, exiting
314 	 threads might be skipped during post_attach that
315 	 have not yet reported their PTRACE_LWP_EXIT event.
316 	 Ignore exited events for an unknown LWP.  */
317       thread_info *thr = find_thread_ptid (wptid);
318       if (thr == nullptr)
319 	  ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
320       else
321 	{
322 	  ourstatus->kind = TARGET_WAITKIND_THREAD_EXITED;
323 	  /* NetBSD does not store an LWP exit status.  */
324 	  ourstatus->value.integer = 0;
325 
326 	  remove_thread (thr);
327 	}
328       return wptid;
329     }
330 
331   if (find_thread_ptid (ptid_t (pid)))
332     current_thread = find_thread_ptid (wptid);
333 
334   if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_CREATE)
335     {
336       /* If GDB attaches to a multi-threaded process, newborn
337 	 threads might be added by nbsd_add_threads that have
338 	 not yet reported their PTRACE_LWP_CREATE event.  Ignore
339 	 born events for an already-known LWP.  */
340       if (find_thread_ptid (wptid))
341 	  ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
342       else
343 	{
344 	  add_thread (wptid, NULL);
345 	  ourstatus->kind = TARGET_WAITKIND_THREAD_CREATED;
346 	}
347       return wptid;
348     }
349 
350   if (code == TRAP_EXEC)
351     {
352       ourstatus->kind = TARGET_WAITKIND_EXECD;
353       ourstatus->value.execd_pathname
354 	= xstrdup (netbsd_nat::pid_to_exec_file (pid));
355       return wptid;
356     }
357 
358   if (code == TRAP_TRACE)
359       return wptid;
360 
361   if (code == TRAP_SCE || code == TRAP_SCX)
362     {
363       int sysnum = si->si_sysnum;
364 
365       if (!netbsd_catch_this_syscall(sysnum))
366 	{
367 	  /* If the core isn't interested in this event, ignore it.  */
368 	  ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
369 	  return wptid;
370 	}
371 
372       ourstatus->kind
373 	= ((code == TRAP_SCE) ? TARGET_WAITKIND_SYSCALL_ENTRY :
374 	   TARGET_WAITKIND_SYSCALL_RETURN);
375       ourstatus->value.syscall_number = sysnum;
376       return wptid;
377     }
378 
379   if (code == TRAP_BRKPT)
380     {
381 #ifdef PTRACE_BREAKPOINT_ADJ
382       CORE_ADDR pc;
383       struct reg r;
384       ptrace (PT_GETREGS, pid, &r, psi.psi_lwpid);
385       pc = PTRACE_REG_PC (&r);
386       PTRACE_REG_SET_PC (&r, pc - PTRACE_BREAKPOINT_ADJ);
387       ptrace (PT_SETREGS, pid, &r, psi.psi_lwpid);
388 #endif
389       return wptid;
390     }
391 
392   /* Unclassified SIGTRAP event.  */
393   ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
394   return wptid;
395 }
396 
397 /* Implement the wait target_ops method.  */
398 
399 ptid_t
400 netbsd_process_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
401 			     int target_options)
402 {
403   while (true)
404     {
405       ptid_t wptid = netbsd_wait (ptid, ourstatus, target_options);
406 
407       /* Register thread in the gdbcore if a thread was not reported earlier.
408 	 This is required after ::create_inferior, when the gdbcore does not
409 	 know about the first internal thread.
410 	 This may also happen on attach, when an event is registered on a thread
411 	 that was not fully initialized during the attach stage.  */
412       if (wptid.lwp () != 0 && !find_thread_ptid (wptid)
413 	  && ourstatus->kind != TARGET_WAITKIND_THREAD_EXITED)
414 	add_thread (wptid, nullptr);
415 
416       switch (ourstatus->kind)
417 	{
418 	case TARGET_WAITKIND_EXITED:
419 	case TARGET_WAITKIND_STOPPED:
420 	case TARGET_WAITKIND_SIGNALLED:
421 	case TARGET_WAITKIND_FORKED:
422 	case TARGET_WAITKIND_VFORKED:
423 	case TARGET_WAITKIND_EXECD:
424 	case TARGET_WAITKIND_VFORK_DONE:
425 	case TARGET_WAITKIND_SYSCALL_ENTRY:
426 	case TARGET_WAITKIND_SYSCALL_RETURN:
427 	  /* Pass the result to the generic code.  */
428 	  return wptid;
429 	case TARGET_WAITKIND_THREAD_CREATED:
430 	case TARGET_WAITKIND_THREAD_EXITED:
431 	  /* The core needlessly stops on these events.  */
432 	  /* FALLTHROUGH */
433 	case TARGET_WAITKIND_SPURIOUS:
434 	  /* Spurious events are unhandled by the gdbserver core.  */
435 	  if (ptrace (PT_CONTINUE, current_process ()->pid, (void *) 1, 0)
436 	      == -1)
437 	    perror_with_name (("ptrace"));
438 	  break;
439 	default:
440 	  error (("Unknown stopped status"));
441 	}
442     }
443 }
444 
445 /* Implement the kill target_ops method.  */
446 
447 int
448 netbsd_process_target::kill (process_info *process)
449 {
450   pid_t pid = process->pid;
451   if (ptrace (PT_KILL, pid, nullptr, 0) == -1)
452     return -1;
453 
454   int status;
455   if (gdb::handle_eintr<int> (-1, ::waitpid, pid, &status, 0) == -1)
456     return -1;
457   mourn (process);
458   return 0;
459 }
460 
461 /* Implement the detach target_ops method.  */
462 
463 int
464 netbsd_process_target::detach (process_info *process)
465 {
466   pid_t pid = process->pid;
467 
468   ptrace (PT_DETACH, pid, (void *) 1, 0);
469   mourn (process);
470   return 0;
471 }
472 
473 /* Implement the mourn target_ops method.  */
474 
475 void
476 netbsd_process_target::mourn (struct process_info *proc)
477 {
478   for_each_thread (proc->pid, remove_thread);
479 
480   remove_process (proc);
481 }
482 
483 /* Implement the join target_ops method.  */
484 
485 void
486 netbsd_process_target::join (int pid)
487 {
488   /* The PT_DETACH is sufficient to detach from the process.
489      So no need to do anything extra.  */
490 }
491 
492 /* Implement the thread_alive target_ops method.  */
493 
494 bool
495 netbsd_process_target::thread_alive (ptid_t ptid)
496 {
497   return netbsd_nat::thread_alive (ptid);
498 }
499 
500 /* Implement the fetch_registers target_ops method.  */
501 
502 void
503 netbsd_process_target::fetch_registers (struct regcache *regcache, int regno)
504 {
505   struct netbsd_regset_info *regset = netbsd_target_regsets;
506   ptid_t inferior_ptid = ptid_of (current_thread);
507 
508   while (regset->size >= 0)
509     {
510       std::vector<char> buf;
511       buf.resize (regset->size);
512       int res = ptrace (regset->get_request, inferior_ptid.pid (), buf.data (),
513 			inferior_ptid.lwp ());
514       if (res == -1)
515 	perror_with_name (("ptrace"));
516       regset->store_function (regcache, buf.data ());
517       regset++;
518     }
519 }
520 
521 /* Implement the store_registers target_ops method.  */
522 
523 void
524 netbsd_process_target::store_registers (struct regcache *regcache, int regno)
525 {
526   struct netbsd_regset_info *regset = netbsd_target_regsets;
527   ptid_t inferior_ptid = ptid_of (current_thread);
528 
529   while (regset->size >= 0)
530     {
531       std::vector<char> buf;
532       buf.resize (regset->size);
533       int res = ptrace (regset->get_request, inferior_ptid.pid (), buf.data (),
534 			inferior_ptid.lwp ());
535       if (res == -1)
536 	perror_with_name (("ptrace"));
537 
538       /* Then overlay our cached registers on that.  */
539       regset->fill_function (regcache, buf.data ());
540       /* Only now do we write the register set.  */
541       res = ptrace (regset->set_request, inferior_ptid.pid (), buf. data (),
542 		    inferior_ptid.lwp ());
543       if (res == -1)
544 	perror_with_name (("ptrace"));
545       regset++;
546     }
547 }
548 
549 /* Implement the read_memory target_ops method.  */
550 
551 int
552 netbsd_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
553 				    int size)
554 {
555   struct ptrace_io_desc io;
556   io.piod_op = PIOD_READ_D;
557   io.piod_len = size;
558 
559   pid_t pid = current_process ()->pid;
560 
561   int bytes_read = 0;
562 
563   if (size == 0)
564     {
565       /* Zero length write always succeeds.  */
566       return 0;
567     }
568   do
569     {
570       io.piod_offs = (void *)(memaddr + bytes_read);
571       io.piod_addr = myaddr + bytes_read;
572 
573       int rv = ptrace (PT_IO, pid, &io, 0);
574       if (rv == -1)
575 	return errno;
576       if (io.piod_len == 0)
577 	return 0;
578 
579       bytes_read += io.piod_len;
580       io.piod_len = size - bytes_read;
581     }
582   while (bytes_read < size);
583 
584   return 0;
585 }
586 
587 /* Implement the write_memory target_ops method.  */
588 
589 int
590 netbsd_process_target::write_memory (CORE_ADDR memaddr,
591 				     const unsigned char *myaddr, int size)
592 {
593   struct ptrace_io_desc io;
594   io.piod_op = PIOD_WRITE_D;
595   io.piod_len = size;
596 
597   pid_t pid = current_process ()->pid;
598 
599   int bytes_written = 0;
600 
601   if (size == 0)
602     {
603       /* Zero length write always succeeds.  */
604       return 0;
605     }
606 
607   do
608     {
609       io.piod_addr = (void *)(myaddr + bytes_written);
610       io.piod_offs = (void *)(memaddr + bytes_written);
611 
612       int rv = ptrace (PT_IO, pid, &io, 0);
613       if (rv == -1)
614 	return errno;
615       if (io.piod_len == 0)
616 	return 0;
617 
618       bytes_written += io.piod_len;
619       io.piod_len = size - bytes_written;
620     }
621   while (bytes_written < size);
622 
623   return 0;
624 }
625 
626 /* Implement the request_interrupt target_ops method.  */
627 
628 void
629 netbsd_process_target::request_interrupt ()
630 {
631   ptid_t inferior_ptid = ptid_of (get_first_thread ());
632 
633   ::kill (inferior_ptid.pid(), SIGINT);
634 }
635 
636 /* Read the AUX Vector for the specified PID, wrapping the ptrace(2) call
637    with the PIOD_READ_AUXV operation and using the PT_IO standard input
638    and output arguments.  */
639 
640 static size_t
641 netbsd_read_auxv(pid_t pid, void *offs, void *addr, size_t len)
642 {
643   struct ptrace_io_desc pio;
644 
645   pio.piod_op = PIOD_READ_AUXV;
646   pio.piod_offs = offs;
647   pio.piod_addr = addr;
648   pio.piod_len = len;
649 
650   if (ptrace (PT_IO, pid, &pio, 0) == -1)
651     perror_with_name (("ptrace"));
652 
653   return pio.piod_len;
654 }
655 
656 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
657    to debugger memory starting at MYADDR.  */
658 
659 int
660 netbsd_process_target::read_auxv (CORE_ADDR offset,
661 				  unsigned char *myaddr, unsigned int len)
662 {
663   pid_t pid = pid_of (current_thread);
664 
665   return netbsd_read_auxv (pid, (void *) (intptr_t) offset, myaddr, len);
666 }
667 
668 bool
669 netbsd_process_target::supports_z_point_type (char z_type)
670 {
671   switch (z_type)
672     {
673     case Z_PACKET_SW_BP:
674       return true;
675     case Z_PACKET_HW_BP:
676     case Z_PACKET_WRITE_WP:
677     case Z_PACKET_READ_WP:
678     case Z_PACKET_ACCESS_WP:
679     default:
680       return false; /* Not supported.  */
681     }
682 }
683 
684 /* Insert {break/watch}point at address ADDR.  SIZE is not used.  */
685 
686 int
687 netbsd_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
688 		     int size, struct raw_breakpoint *bp)
689 {
690   switch (type)
691     {
692     case raw_bkpt_type_sw:
693       return insert_memory_breakpoint (bp);
694     case raw_bkpt_type_hw:
695     case raw_bkpt_type_write_wp:
696     case raw_bkpt_type_read_wp:
697     case raw_bkpt_type_access_wp:
698     default:
699       return 1; /* Not supported.  */
700     }
701 }
702 
703 /* Remove {break/watch}point at address ADDR.  SIZE is not used.  */
704 
705 int
706 netbsd_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
707 				     int size, struct raw_breakpoint *bp)
708 {
709   switch (type)
710     {
711     case raw_bkpt_type_sw:
712       return remove_memory_breakpoint (bp);
713     case raw_bkpt_type_hw:
714     case raw_bkpt_type_write_wp:
715     case raw_bkpt_type_read_wp:
716     case raw_bkpt_type_access_wp:
717     default:
718       return 1; /* Not supported.  */
719     }
720 }
721 
722 /* Implement the stopped_by_sw_breakpoint target_ops method.  */
723 
724 bool
725 netbsd_process_target::stopped_by_sw_breakpoint ()
726 {
727   ptrace_siginfo_t psi;
728   pid_t pid = current_process ()->pid;
729 
730   if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
731     perror_with_name (("ptrace"));
732 
733   return psi.psi_siginfo.si_signo == SIGTRAP &&
734 	 psi.psi_siginfo.si_code == TRAP_BRKPT;
735 }
736 
737 /* Implement the supports_stopped_by_sw_breakpoint target_ops method.  */
738 
739 bool
740 netbsd_process_target::supports_stopped_by_sw_breakpoint ()
741 {
742   return true;
743 }
744 
745 /* Implement the supports_qxfer_siginfo target_ops method.  */
746 
747 bool
748 netbsd_process_target::supports_qxfer_siginfo ()
749 {
750   return true;
751 }
752 
753 /* Implement the qxfer_siginfo target_ops method.  */
754 
755 int
756 netbsd_process_target::qxfer_siginfo (const char *annex, unsigned char *readbuf,
757 				      unsigned const char *writebuf,
758 				      CORE_ADDR offset, int len)
759 {
760   if (current_thread == nullptr)
761     return -1;
762 
763   pid_t pid = current_process ()->pid;
764 
765   return netbsd_nat::qxfer_siginfo(pid, annex, readbuf, writebuf, offset, len);
766 }
767 
768 /* Implement the supports_non_stop target_ops method.  */
769 
770 bool
771 netbsd_process_target::supports_non_stop ()
772 {
773   return false;
774 }
775 
776 /* Implement the supports_multi_process target_ops method.  */
777 
778 bool
779 netbsd_process_target::supports_multi_process ()
780 {
781   return true;
782 }
783 
784 /* Check if fork events are supported.  */
785 
786 bool
787 netbsd_process_target::supports_fork_events ()
788 {
789   return false;
790 }
791 
792 /* Check if vfork events are supported.  */
793 
794 bool
795 netbsd_process_target::supports_vfork_events ()
796 {
797   return false;
798 }
799 
800 /* Check if exec events are supported.  */
801 
802 bool
803 netbsd_process_target::supports_exec_events ()
804 {
805   return true;
806 }
807 
808 /* Implement the supports_disable_randomization target_ops method.  */
809 
810 bool
811 netbsd_process_target::supports_disable_randomization ()
812 {
813   return false;
814 }
815 
816 /* Extract &phdr and num_phdr in the inferior.  Return 0 on success.  */
817 
818 template <typename T>
819 int get_phdr_phnum_from_proc_auxv (const pid_t pid,
820 				   CORE_ADDR *phdr_memaddr, int *num_phdr)
821 {
822   typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
823 				    Aux64Info, Aux32Info>::type auxv_type;
824   const size_t auxv_size = sizeof (auxv_type);
825   const size_t auxv_buf_size = 128 * sizeof (auxv_type);
826 
827   std::vector<char> auxv_buf;
828   auxv_buf.resize (auxv_buf_size);
829 
830   netbsd_read_auxv (pid, nullptr, auxv_buf.data (), auxv_buf_size);
831 
832   *phdr_memaddr = 0;
833   *num_phdr = 0;
834 
835   for (char *buf = auxv_buf.data ();
836        buf < (auxv_buf.data () + auxv_buf_size);
837        buf += auxv_size)
838     {
839       auxv_type *const aux = (auxv_type *) buf;
840 
841       switch (aux->a_type)
842 	{
843 	case AT_PHDR:
844 	  *phdr_memaddr = aux->a_v;
845 	  break;
846 	case AT_PHNUM:
847 	  *num_phdr = aux->a_v;
848 	  break;
849 	}
850 
851       if (*phdr_memaddr != 0 && *num_phdr != 0)
852 	break;
853     }
854 
855   if (*phdr_memaddr == 0 || *num_phdr == 0)
856     {
857       warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
858 	       "phdr_memaddr = %s, phdr_num = %d",
859 	       core_addr_to_string (*phdr_memaddr), *num_phdr);
860       return 2;
861     }
862 
863   return 0;
864 }
865 
866 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present.  */
867 
868 template <typename T>
869 static CORE_ADDR
870 get_dynamic (netbsd_process_target *target, const pid_t pid)
871 {
872   typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
873 				    Elf64_Phdr, Elf32_Phdr>::type phdr_type;
874   const int phdr_size = sizeof (phdr_type);
875 
876   CORE_ADDR phdr_memaddr;
877   int num_phdr;
878   if (get_phdr_phnum_from_proc_auxv<T> (pid, &phdr_memaddr, &num_phdr))
879     return 0;
880 
881   std::vector<unsigned char> phdr_buf;
882   phdr_buf.resize (num_phdr * phdr_size);
883 
884   if (target->read_memory (phdr_memaddr, phdr_buf.data (), phdr_buf.size ()))
885     return 0;
886 
887   /* Compute relocation: it is expected to be 0 for "regular" executables,
888      non-zero for PIE ones.  */
889   CORE_ADDR relocation = -1;
890   for (int i = 0; relocation == -1 && i < num_phdr; i++)
891     {
892       phdr_type *const p = (phdr_type *) (phdr_buf.data() + i * phdr_size);
893 
894       if (p->p_type == PT_PHDR)
895 	relocation = phdr_memaddr - p->p_vaddr;
896     }
897 
898   if (relocation == -1)
899     {
900       /* PT_PHDR is optional, but necessary for PIE in general.  Fortunately
901 	 any real world executables, including PIE executables, have always
902 	 PT_PHDR present.  PT_PHDR is not present in some shared libraries or
903 	 in fpc (Free Pascal 2.4) binaries but neither of those have a need for
904 	 or present DT_DEBUG anyway (fpc binaries are statically linked).
905 
906 	 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
907 
908 	 GDB could find RELOCATION also from AT_ENTRY - e_entry.  */
909 
910       return 0;
911     }
912 
913   for (int i = 0; i < num_phdr; i++)
914     {
915       phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
916 
917       if (p->p_type == PT_DYNAMIC)
918 	return p->p_vaddr + relocation;
919     }
920 
921   return 0;
922 }
923 
924 /* Return &_r_debug in the inferior, or -1 if not present.  Return value
925    can be 0 if the inferior does not yet have the library list initialized.
926    We look for DT_MIPS_RLD_MAP first.  MIPS executables use this instead of
927    DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too.  */
928 
929 template <typename T>
930 static CORE_ADDR
931 get_r_debug (netbsd_process_target *target, const int pid)
932 {
933   typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
934 				    Elf64_Dyn, Elf32_Dyn>::type dyn_type;
935   const int dyn_size = sizeof (dyn_type);
936   unsigned char buf[sizeof (dyn_type)];  /* The larger of the two.  */
937   CORE_ADDR map = -1;
938 
939   CORE_ADDR dynamic_memaddr = get_dynamic<T> (target, pid);
940   if (dynamic_memaddr == 0)
941     return map;
942 
943   while (target->read_memory (dynamic_memaddr, buf, dyn_size) == 0)
944     {
945       dyn_type *const dyn = (dyn_type *) buf;
946 #if defined DT_MIPS_RLD_MAP
947       union
948       {
949 	T map;
950 	unsigned char buf[sizeof (T)];
951       }
952       rld_map;
953 
954       if (dyn->d_tag == DT_MIPS_RLD_MAP)
955 	{
956 	  if (read_memory (dyn->d_un.d_val,
957 			   rld_map.buf, sizeof (rld_map.buf)) == 0)
958 	    return rld_map.map;
959 	  else
960 	    break;
961 	}
962 #endif  /* DT_MIPS_RLD_MAP */
963 
964       if (dyn->d_tag == DT_DEBUG && map == -1)
965 	map = dyn->d_un.d_val;
966 
967       if (dyn->d_tag == DT_NULL)
968 	break;
969 
970       dynamic_memaddr += dyn_size;
971     }
972 
973   return map;
974 }
975 
976 /* Read one pointer from MEMADDR in the inferior.  */
977 
978 static int
979 read_one_ptr (netbsd_process_target *target, CORE_ADDR memaddr, CORE_ADDR *ptr,
980 	      int ptr_size)
981 {
982   /* Go through a union so this works on either big or little endian
983      hosts, when the inferior's pointer size is smaller than the size
984      of CORE_ADDR.  It is assumed the inferior's endianness is the
985      same of the superior's.  */
986 
987   union
988   {
989     CORE_ADDR core_addr;
990     unsigned int ui;
991     unsigned char uc;
992   } addr;
993 
994   int ret = target->read_memory (memaddr, &addr.uc, ptr_size);
995   if (ret == 0)
996     {
997       if (ptr_size == sizeof (CORE_ADDR))
998 	*ptr = addr.core_addr;
999       else if (ptr_size == sizeof (unsigned int))
1000 	*ptr = addr.ui;
1001       else
1002 	gdb_assert_not_reached ("unhandled pointer size");
1003     }
1004   return ret;
1005 }
1006 
1007 /* Construct qXfer:libraries-svr4:read reply.  */
1008 
1009 template <typename T>
1010 int
1011 netbsd_qxfer_libraries_svr4 (netbsd_process_target *target,
1012 			     const pid_t pid, const char *annex,
1013 			     unsigned char *readbuf,
1014 			     unsigned const char *writebuf,
1015 			     CORE_ADDR offset, int len)
1016 {
1017   struct link_map_offsets
1018   {
1019     /* Offset and size of r_debug.r_version.  */
1020     int r_version_offset;
1021 
1022     /* Offset and size of r_debug.r_map.  */
1023     int r_map_offset;
1024 
1025     /* Offset to l_addr field in struct link_map.  */
1026     int l_addr_offset;
1027 
1028     /* Offset to l_name field in struct link_map.  */
1029     int l_name_offset;
1030 
1031     /* Offset to l_ld field in struct link_map.  */
1032     int l_ld_offset;
1033 
1034     /* Offset to l_next field in struct link_map.  */
1035     int l_next_offset;
1036 
1037     /* Offset to l_prev field in struct link_map.  */
1038     int l_prev_offset;
1039   };
1040 
1041   static const struct link_map_offsets lmo_32bit_offsets =
1042     {
1043       0,     /* r_version offset. */
1044       4,     /* r_debug.r_map offset.  */
1045       0,     /* l_addr offset in link_map.  */
1046       4,     /* l_name offset in link_map.  */
1047       8,     /* l_ld offset in link_map.  */
1048       12,    /* l_next offset in link_map.  */
1049       16     /* l_prev offset in link_map.  */
1050     };
1051 
1052   static const struct link_map_offsets lmo_64bit_offsets =
1053     {
1054       0,     /* r_version offset. */
1055       8,     /* r_debug.r_map offset.  */
1056       0,     /* l_addr offset in link_map.  */
1057       8,     /* l_name offset in link_map.  */
1058       16,    /* l_ld offset in link_map.  */
1059       24,    /* l_next offset in link_map.  */
1060       32     /* l_prev offset in link_map.  */
1061     };
1062 
1063   CORE_ADDR lm_addr = 0, lm_prev = 0;
1064   CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
1065   int header_done = 0;
1066 
1067   const struct link_map_offsets *lmo
1068     = ((sizeof (T) == sizeof (int64_t))
1069        ? &lmo_64bit_offsets : &lmo_32bit_offsets);
1070   int ptr_size = sizeof (T);
1071 
1072   while (annex[0] != '\0')
1073     {
1074       const char *sep = strchr (annex, '=');
1075       if (sep == nullptr)
1076 	break;
1077 
1078       int name_len = sep - annex;
1079       CORE_ADDR *addrp;
1080       if (name_len == 5 && startswith (annex, "start"))
1081 	addrp = &lm_addr;
1082       else if (name_len == 4 && startswith (annex, "prev"))
1083 	addrp = &lm_prev;
1084       else
1085 	{
1086 	  annex = strchr (sep, ';');
1087 	  if (annex == nullptr)
1088 	    break;
1089 	  annex++;
1090 	  continue;
1091 	}
1092 
1093       annex = decode_address_to_semicolon (addrp, sep + 1);
1094     }
1095 
1096   if (lm_addr == 0)
1097     {
1098       CORE_ADDR r_debug = get_r_debug<T> (target, pid);
1099 
1100       /* We failed to find DT_DEBUG.  Such situation will not change
1101 	 for this inferior - do not retry it.  Report it to GDB as
1102 	 E01, see for the reasons at the GDB solib-svr4.c side.  */
1103       if (r_debug == (CORE_ADDR) -1)
1104 	return -1;
1105 
1106       if (r_debug != 0)
1107 	{
1108 	  CORE_ADDR map_offset = r_debug + lmo->r_map_offset;
1109 	  if (read_one_ptr (target, map_offset, &lm_addr, ptr_size) != 0)
1110 	    warning ("unable to read r_map from %s",
1111 		     core_addr_to_string (map_offset));
1112 	}
1113     }
1114 
1115   std::string document = "<library-list-svr4 version=\"1.0\"";
1116 
1117   while (lm_addr
1118 	 && read_one_ptr (target, lm_addr + lmo->l_name_offset,
1119 			  &l_name, ptr_size) == 0
1120 	 && read_one_ptr (target, lm_addr + lmo->l_addr_offset,
1121 			  &l_addr, ptr_size) == 0
1122 	 && read_one_ptr (target, lm_addr + lmo->l_ld_offset,
1123 			  &l_ld, ptr_size) == 0
1124 	 && read_one_ptr (target, lm_addr + lmo->l_prev_offset,
1125 			  &l_prev, ptr_size) == 0
1126 	 && read_one_ptr (target, lm_addr + lmo->l_next_offset,
1127 			  &l_next, ptr_size) == 0)
1128     {
1129       if (lm_prev != l_prev)
1130 	{
1131 	  warning ("Corrupted shared library list: 0x%lx != 0x%lx",
1132 		   (long) lm_prev, (long) l_prev);
1133 	  break;
1134 	}
1135 
1136       /* Ignore the first entry even if it has valid name as the first entry
1137 	 corresponds to the main executable.  The first entry should not be
1138 	 skipped if the dynamic loader was loaded late by a static executable
1139 	 (see solib-svr4.c parameter ignore_first).  But in such case the main
1140 	 executable does not have PT_DYNAMIC present and this function already
1141 	 exited above due to failed get_r_debug.  */
1142       if (lm_prev == 0)
1143 	string_appendf (document, " main-lm=\"0x%lx\"",
1144 			(unsigned long) lm_addr);
1145       else
1146 	{
1147 	  unsigned char libname[PATH_MAX];
1148 
1149 	  /* Not checking for error because reading may stop before
1150 	     we've got PATH_MAX worth of characters.  */
1151 	  libname[0] = '\0';
1152 	  target->read_memory (l_name, libname, sizeof (libname) - 1);
1153 	  libname[sizeof (libname) - 1] = '\0';
1154 	  if (libname[0] != '\0')
1155 	    {
1156 	      if (!header_done)
1157 		{
1158 		  /* Terminate `<library-list-svr4'.  */
1159 		  document += '>';
1160 		  header_done = 1;
1161 		}
1162 
1163 	      string_appendf (document, "<library name=\"");
1164 	      xml_escape_text_append (&document, (char *) libname);
1165 	      string_appendf (document, "\" lm=\"0x%lx\" "
1166 			      "l_addr=\"0x%lx\" l_ld=\"0x%lx\"/>",
1167 			      (unsigned long) lm_addr, (unsigned long) l_addr,
1168 			      (unsigned long) l_ld);
1169 	    }
1170 	}
1171 
1172       lm_prev = lm_addr;
1173       lm_addr = l_next;
1174     }
1175 
1176   if (!header_done)
1177     {
1178       /* Empty list; terminate `<library-list-svr4'.  */
1179       document += "/>";
1180     }
1181   else
1182     document += "</library-list-svr4>";
1183 
1184   int document_len = document.length ();
1185   if (offset < document_len)
1186     document_len -= offset;
1187   else
1188     document_len = 0;
1189   if (len > document_len)
1190     len = document_len;
1191 
1192   memcpy (readbuf, document.data () + offset, len);
1193 
1194   return len;
1195 }
1196 
1197 /* Return true if FILE is a 64-bit ELF file,
1198    false if the file is not a 64-bit ELF file,
1199    and error if the file is not accessible or doesn't exist.  */
1200 
1201 static bool
1202 elf_64_file_p (const char *file)
1203 {
1204   int fd = gdb::handle_eintr<int> (-1, ::open, file, O_RDONLY);
1205   if (fd < 0)
1206     perror_with_name (("open"));
1207 
1208   Elf64_Ehdr header;
1209   ssize_t ret = gdb::handle_eintr<ssize_t> (-1, ::read, fd, &header, sizeof (header));
1210   if (ret == -1)
1211     perror_with_name (("read"));
1212   gdb::handle_eintr<int> (-1, ::close, fd);
1213   if (ret != sizeof (header))
1214     error ("Cannot read ELF file header: %s", file);
1215 
1216   if (header.e_ident[EI_MAG0] != ELFMAG0
1217       || header.e_ident[EI_MAG1] != ELFMAG1
1218       || header.e_ident[EI_MAG2] != ELFMAG2
1219       || header.e_ident[EI_MAG3] != ELFMAG3)
1220     error ("Unrecognized ELF file header: %s", file);
1221 
1222   return header.e_ident[EI_CLASS] == ELFCLASS64;
1223 }
1224 
1225 /* Construct qXfer:libraries-svr4:read reply.  */
1226 
1227 int
1228 netbsd_process_target::qxfer_libraries_svr4 (const char *annex,
1229 					     unsigned char *readbuf,
1230 					     unsigned const char *writebuf,
1231 					     CORE_ADDR offset, int len)
1232 {
1233   if (writebuf != nullptr)
1234     return -2;
1235   if (readbuf == nullptr)
1236     return -1;
1237 
1238   struct process_info *proc = current_process ();
1239   pid_t pid = proc->pid;
1240   bool is_elf64 = elf_64_file_p (netbsd_nat::pid_to_exec_file (pid));
1241 
1242   if (is_elf64)
1243     return netbsd_qxfer_libraries_svr4<int64_t> (this, pid, annex, readbuf,
1244 						 writebuf, offset, len);
1245   else
1246     return netbsd_qxfer_libraries_svr4<int32_t> (this, pid, annex, readbuf,
1247 						 writebuf, offset, len);
1248 }
1249 
1250 /* Implement the supports_qxfer_libraries_svr4 target_ops method.  */
1251 
1252 bool
1253 netbsd_process_target::supports_qxfer_libraries_svr4 ()
1254 {
1255   return true;
1256 }
1257 
1258 /* Return the name of a file that can be opened to get the symbols for
1259    the child process identified by PID.  */
1260 
1261 char *
1262 netbsd_process_target::pid_to_exec_file (pid_t pid)
1263 {
1264   return const_cast<char *> (netbsd_nat::pid_to_exec_file (pid));
1265 }
1266 
1267 /* Implementation of the target_ops method "supports_pid_to_exec_file".  */
1268 
1269 bool
1270 netbsd_process_target::supports_pid_to_exec_file ()
1271 {
1272   return true;
1273 }
1274 
1275 /* Implementation of the target_ops method "supports_hardware_single_step".  */
1276 bool
1277 netbsd_process_target::supports_hardware_single_step ()
1278 {
1279   return true;
1280 }
1281 
1282 /* Implementation of the target_ops method "sw_breakpoint_from_kind".  */
1283 
1284 const gdb_byte *
1285 netbsd_process_target::sw_breakpoint_from_kind (int kind, int *size)
1286 {
1287   static gdb_byte brkpt[PTRACE_BREAKPOINT_SIZE] = {*PTRACE_BREAKPOINT};
1288 
1289   *size = PTRACE_BREAKPOINT_SIZE;
1290 
1291   return brkpt;
1292 }
1293 
1294 /* Implement the thread_name target_ops method.  */
1295 
1296 const char *
1297 netbsd_process_target::thread_name (ptid_t ptid)
1298 {
1299   return netbsd_nat::thread_name (ptid);
1300 }
1301 
1302 /* Implement the supports_catch_syscall target_ops method.  */
1303 
1304 bool
1305 netbsd_process_target::supports_catch_syscall ()
1306 {
1307   return true;
1308 }
1309 
1310 /* Implement the supports_read_auxv target_ops method.  */
1311 
1312 bool
1313 netbsd_process_target::supports_read_auxv ()
1314 {
1315   return true;
1316 }
1317 
1318 /* The NetBSD target ops object.  */
1319 
1320 static netbsd_process_target the_netbsd_target;
1321 
1322 void
1323 initialize_low ()
1324 {
1325   set_target_ops (&the_netbsd_target);
1326   the_low_target.arch_setup ();
1327 }
1328