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