Automatic date update in version.in
[binutils-gdb.git] / gdbserver / netbsd-low.cc
blobf05bcd4e173fb7522b106fd90c2b717bfcccb3a9
1 /* Copyright (C) 2020-2022 Free Software Foundation, Inc.
3 This file is part of GDB.
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.
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.
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/>. */
18 #include "server.h"
19 #include "target.h"
20 #include "netbsd-low.h"
21 #include "nat/netbsd-nat.h"
23 #include <sys/param.h>
24 #include <sys/types.h>
26 #include <sys/ptrace.h>
27 #include <sys/sysctl.h>
29 #include <limits.h>
30 #include <unistd.h>
31 #include <signal.h>
33 #include <elf.h>
35 #include <type_traits>
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"
44 int using_threads = 1;
46 /* Callback used by fork_inferior to start tracing the inferior. */
48 static void
49 netbsd_ptrace_fun ()
51 /* Switch child to its own process group so that signals won't
52 directly affect GDBserver. */
53 if (setpgid (0, 0) < 0)
54 trace_start_error_with_name (("setpgid"));
56 if (ptrace (PT_TRACE_ME, 0, nullptr, 0) < 0)
57 trace_start_error_with_name (("ptrace"));
59 /* If GDBserver is connected to gdb via stdio, redirect the inferior's
60 stdout to stderr so that inferior i/o doesn't corrupt the connection.
61 Also, redirect stdin to /dev/null. */
62 if (remote_connection_is_stdio ())
64 if (close (0) < 0)
65 trace_start_error_with_name (("close"));
66 if (open ("/dev/null", O_RDONLY) < 0)
67 trace_start_error_with_name (("open"));
68 if (dup2 (2, 1) < 0)
69 trace_start_error_with_name (("dup2"));
70 if (write (2, "stdin/stdout redirected\n",
71 sizeof ("stdin/stdout redirected\n") - 1) < 0)
73 /* Errors ignored. */
78 /* Implement the create_inferior method of the target_ops vector. */
80 int
81 netbsd_process_target::create_inferior (const char *program,
82 const std::vector<char *> &program_args)
84 std::string str_program_args = construct_inferior_arguments (program_args);
86 pid_t pid = fork_inferior (program, str_program_args.c_str (),
87 get_environ ()->envp (), netbsd_ptrace_fun,
88 nullptr, nullptr, nullptr, nullptr);
90 add_process (pid, 0);
92 post_fork_inferior (pid, program);
94 return pid;
97 /* Implement the post_create_inferior target_ops method. */
99 void
100 netbsd_process_target::post_create_inferior ()
102 pid_t pid = current_process ()->pid;
103 netbsd_nat::enable_proc_events (pid);
105 low_arch_setup ();
108 /* Implement the attach target_ops method. */
111 netbsd_process_target::attach (unsigned long pid)
113 /* Unimplemented. */
114 return -1;
117 /* Returns true if GDB is interested in any child syscalls. */
119 static bool
120 gdb_catching_syscalls_p (pid_t pid)
122 struct process_info *proc = find_process_pid (pid);
123 return !proc->syscalls_to_catch.empty ();
126 /* Implement the resume target_ops method. */
128 void
129 netbsd_process_target::resume (struct thread_resume *resume_info, size_t n)
131 ptid_t resume_ptid = resume_info[0].thread;
132 const int signal = resume_info[0].sig;
133 const bool step = resume_info[0].kind == resume_step;
135 if (resume_ptid == minus_one_ptid)
136 resume_ptid = ptid_of (current_thread);
138 const pid_t pid = resume_ptid.pid ();
139 const lwpid_t lwp = resume_ptid.lwp ();
140 regcache_invalidate_pid (pid);
142 auto fn
143 = [&] (ptid_t ptid)
145 if (step)
147 if (ptid.lwp () == lwp || n != 1)
149 if (ptrace (PT_SETSTEP, pid, NULL, ptid.lwp ()) == -1)
150 perror_with_name (("ptrace"));
151 if (ptrace (PT_RESUME, pid, NULL, ptid.lwp ()) == -1)
152 perror_with_name (("ptrace"));
154 else
156 if (ptrace (PT_CLEARSTEP, pid, NULL, ptid.lwp ()) == -1)
157 perror_with_name (("ptrace"));
158 if (ptrace (PT_SUSPEND, pid, NULL, ptid.lwp ()) == -1)
159 perror_with_name (("ptrace"));
162 else
164 if (ptrace (PT_CLEARSTEP, pid, NULL, ptid.lwp ()) == -1)
165 perror_with_name (("ptrace"));
166 if (ptrace (PT_RESUME, pid, NULL, ptid.lwp ()) == -1)
167 perror_with_name (("ptrace"));
171 netbsd_nat::for_each_thread (pid, fn);
173 int request = gdb_catching_syscalls_p (pid) ? PT_CONTINUE : PT_SYSCALL;
175 errno = 0;
176 ptrace (request, pid, (void *)1, signal);
177 if (errno)
178 perror_with_name (("ptrace"));
181 /* Returns true if GDB is interested in the reported SYSNO syscall. */
183 static bool
184 netbsd_catch_this_syscall (int sysno)
186 struct process_info *proc = current_process ();
188 if (proc->syscalls_to_catch.empty ())
189 return false;
191 if (proc->syscalls_to_catch[0] == ANY_SYSCALL)
192 return true;
194 for (int iter : proc->syscalls_to_catch)
195 if (iter == sysno)
196 return true;
198 return false;
201 /* Helper function for child_wait and the derivatives of child_wait.
202 HOSTSTATUS is the waitstatus from wait() or the equivalent; store our
203 translation of that in OURSTATUS. */
205 static void
206 netbsd_store_waitstatus (struct target_waitstatus *ourstatus, int hoststatus)
208 if (WIFEXITED (hoststatus))
209 ourstatus->set_exited (WEXITSTATUS (hoststatus));
210 else if (!WIFSTOPPED (hoststatus))
211 ourstatus->set_signalled (gdb_signal_from_host (WTERMSIG (hoststatus)));
212 else
213 ourstatus->set_stopped (gdb_signal_from_host (WSTOPSIG (hoststatus)));
216 /* Implement a safe wrapper around waitpid(). */
218 static pid_t
219 netbsd_waitpid (ptid_t ptid, struct target_waitstatus *ourstatus,
220 target_wait_flags target_options)
222 int status;
223 int options = (target_options & TARGET_WNOHANG) ? WNOHANG : 0;
225 pid_t pid
226 = gdb::handle_eintr (-1, ::waitpid, ptid.pid (), &status, options);
228 if (pid == -1)
229 perror_with_name (_("Child process unexpectedly missing"));
231 netbsd_store_waitstatus (ourstatus, status);
232 return pid;
236 /* Implement the wait target_ops method.
238 Wait for the child specified by PTID to do something. Return the
239 process ID of the child, or MINUS_ONE_PTID in case of error; store
240 the status in *OURSTATUS. */
242 static ptid_t
243 netbsd_wait (ptid_t ptid, struct target_waitstatus *ourstatus,
244 target_wait_flags target_options)
246 pid_t pid = netbsd_waitpid (ptid, ourstatus, target_options);
247 ptid_t wptid = ptid_t (pid);
249 if (pid == 0)
251 gdb_assert (target_options & TARGET_WNOHANG);
252 ourstatus->set_ignore ();
253 return null_ptid;
256 gdb_assert (pid != -1);
258 /* If the child stopped, keep investigating its status. */
259 if (ourstatus->kind () != TARGET_WAITKIND_STOPPED)
260 return wptid;
262 /* Extract the event and thread that received a signal. */
263 ptrace_siginfo_t psi;
264 if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
265 perror_with_name (("ptrace"));
267 /* Pick child's siginfo_t. */
268 siginfo_t *si = &psi.psi_siginfo;
270 lwpid_t lwp = psi.psi_lwpid;
272 int signo = si->si_signo;
273 const int code = si->si_code;
275 /* Construct PTID with a specified thread that received the event.
276 If a signal was targeted to the whole process, lwp is 0. */
277 wptid = ptid_t (pid, lwp, 0);
279 /* Bail out on non-debugger oriented signals. */
280 if (signo != SIGTRAP)
281 return wptid;
283 /* Stop examining non-debugger oriented SIGTRAP codes. */
284 if (code <= SI_USER || code == SI_NOINFO)
285 return wptid;
287 /* Process state for threading events. */
288 ptrace_state_t pst = {};
289 if (code == TRAP_LWP)
290 if (ptrace (PT_GET_PROCESS_STATE, pid, &pst, sizeof (pst)) == -1)
291 perror_with_name (("ptrace"));
293 if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_EXIT)
295 /* If GDB attaches to a multi-threaded process, exiting
296 threads might be skipped during post_attach that
297 have not yet reported their PTRACE_LWP_EXIT event.
298 Ignore exited events for an unknown LWP. */
299 thread_info *thr = find_thread_ptid (wptid);
300 if (thr == nullptr)
301 ourstatus->set_spurious ();
302 else
304 /* NetBSD does not store an LWP exit status. */
305 ourstatus->set_thread_exited (0);
307 remove_thread (thr);
309 return wptid;
312 if (find_thread_ptid (ptid_t (pid)))
313 switch_to_thread (find_thread_ptid (wptid));
315 if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_CREATE)
317 /* If GDB attaches to a multi-threaded process, newborn
318 threads might be added by nbsd_add_threads that have
319 not yet reported their PTRACE_LWP_CREATE event. Ignore
320 born events for an already-known LWP. */
321 if (find_thread_ptid (wptid))
322 ourstatus->set_spurious ();
323 else
325 add_thread (wptid, NULL);
326 ourstatus->set_thread_created ();
328 return wptid;
331 if (code == TRAP_EXEC)
333 ourstatus->set_execd
334 (make_unique_xstrdup (netbsd_nat::pid_to_exec_file (pid)));
335 return wptid;
338 if (code == TRAP_TRACE)
339 return wptid;
341 if (code == TRAP_SCE || code == TRAP_SCX)
343 int sysnum = si->si_sysnum;
345 if (!netbsd_catch_this_syscall(sysnum))
347 /* If the core isn't interested in this event, ignore it. */
348 ourstatus->set_spurious ();
349 return wptid;
352 if (code == TRAP_SCE)
353 ourstatus->set_syscall_entry (sysnum);
354 else
355 ourstatus->set_syscall_return (sysnum);
357 return wptid;
360 if (code == TRAP_BRKPT)
362 #ifdef PTRACE_BREAKPOINT_ADJ
363 CORE_ADDR pc;
364 struct reg r;
365 ptrace (PT_GETREGS, pid, &r, psi.psi_lwpid);
366 pc = PTRACE_REG_PC (&r);
367 PTRACE_REG_SET_PC (&r, pc - PTRACE_BREAKPOINT_ADJ);
368 ptrace (PT_SETREGS, pid, &r, psi.psi_lwpid);
369 #endif
370 return wptid;
373 /* Unclassified SIGTRAP event. */
374 ourstatus->set_spurious ();
375 return wptid;
378 /* Implement the wait target_ops method. */
380 ptid_t
381 netbsd_process_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
382 target_wait_flags target_options)
384 while (true)
386 ptid_t wptid = netbsd_wait (ptid, ourstatus, target_options);
388 /* Register thread in the gdbcore if a thread was not reported earlier.
389 This is required after ::create_inferior, when the gdbcore does not
390 know about the first internal thread.
391 This may also happen on attach, when an event is registered on a thread
392 that was not fully initialized during the attach stage. */
393 if (wptid.lwp () != 0 && !find_thread_ptid (wptid)
394 && ourstatus->kind () != TARGET_WAITKIND_THREAD_EXITED)
395 add_thread (wptid, nullptr);
397 switch (ourstatus->kind ())
399 case TARGET_WAITKIND_EXITED:
400 case TARGET_WAITKIND_STOPPED:
401 case TARGET_WAITKIND_SIGNALLED:
402 case TARGET_WAITKIND_FORKED:
403 case TARGET_WAITKIND_VFORKED:
404 case TARGET_WAITKIND_EXECD:
405 case TARGET_WAITKIND_VFORK_DONE:
406 case TARGET_WAITKIND_SYSCALL_ENTRY:
407 case TARGET_WAITKIND_SYSCALL_RETURN:
408 /* Pass the result to the generic code. */
409 return wptid;
410 case TARGET_WAITKIND_THREAD_CREATED:
411 case TARGET_WAITKIND_THREAD_EXITED:
412 /* The core needlessly stops on these events. */
413 /* FALLTHROUGH */
414 case TARGET_WAITKIND_SPURIOUS:
415 /* Spurious events are unhandled by the gdbserver core. */
416 if (ptrace (PT_CONTINUE, current_process ()->pid, (void *) 1, 0)
417 == -1)
418 perror_with_name (("ptrace"));
419 break;
420 default:
421 error (("Unknown stopped status"));
426 /* Implement the kill target_ops method. */
429 netbsd_process_target::kill (process_info *process)
431 pid_t pid = process->pid;
432 if (ptrace (PT_KILL, pid, nullptr, 0) == -1)
433 return -1;
435 int status;
436 if (gdb::handle_eintr (-1, ::waitpid, pid, &status, 0) == -1)
437 return -1;
438 mourn (process);
439 return 0;
442 /* Implement the detach target_ops method. */
445 netbsd_process_target::detach (process_info *process)
447 pid_t pid = process->pid;
449 ptrace (PT_DETACH, pid, (void *) 1, 0);
450 mourn (process);
451 return 0;
454 /* Implement the mourn target_ops method. */
456 void
457 netbsd_process_target::mourn (struct process_info *proc)
459 for_each_thread (proc->pid, remove_thread);
461 remove_process (proc);
464 /* Implement the join target_ops method. */
466 void
467 netbsd_process_target::join (int pid)
469 /* The PT_DETACH is sufficient to detach from the process.
470 So no need to do anything extra. */
473 /* Implement the thread_alive target_ops method. */
475 bool
476 netbsd_process_target::thread_alive (ptid_t ptid)
478 return netbsd_nat::thread_alive (ptid);
481 /* Implement the fetch_registers target_ops method. */
483 void
484 netbsd_process_target::fetch_registers (struct regcache *regcache, int regno)
486 const netbsd_regset_info *regset = get_regs_info ();
487 ptid_t inferior_ptid = ptid_of (current_thread);
489 while (regset->size >= 0)
491 std::vector<char> buf;
492 buf.resize (regset->size);
493 int res = ptrace (regset->get_request, inferior_ptid.pid (), buf.data (),
494 inferior_ptid.lwp ());
495 if (res == -1)
496 perror_with_name (("ptrace"));
497 regset->store_function (regcache, buf.data ());
498 regset++;
502 /* Implement the store_registers target_ops method. */
504 void
505 netbsd_process_target::store_registers (struct regcache *regcache, int regno)
507 const netbsd_regset_info *regset = get_regs_info ();
508 ptid_t inferior_ptid = ptid_of (current_thread);
510 while (regset->size >= 0)
512 std::vector<char> buf;
513 buf.resize (regset->size);
514 int res = ptrace (regset->get_request, inferior_ptid.pid (), buf.data (),
515 inferior_ptid.lwp ());
516 if (res == -1)
517 perror_with_name (("ptrace"));
519 /* Then overlay our cached registers on that. */
520 regset->fill_function (regcache, buf.data ());
521 /* Only now do we write the register set. */
522 res = ptrace (regset->set_request, inferior_ptid.pid (), buf. data (),
523 inferior_ptid.lwp ());
524 if (res == -1)
525 perror_with_name (("ptrace"));
526 regset++;
530 /* Implement the read_memory target_ops method. */
533 netbsd_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
534 int size)
536 pid_t pid = current_process ()->pid;
537 return netbsd_nat::read_memory (pid, myaddr, memaddr, size, nullptr);
540 /* Implement the write_memory target_ops method. */
543 netbsd_process_target::write_memory (CORE_ADDR memaddr,
544 const unsigned char *myaddr, int size)
546 pid_t pid = current_process ()->pid;
547 return netbsd_nat::write_memory (pid, myaddr, memaddr, size, nullptr);
550 /* Implement the request_interrupt target_ops method. */
552 void
553 netbsd_process_target::request_interrupt ()
555 ptid_t inferior_ptid = ptid_of (get_first_thread ());
557 ::kill (inferior_ptid.pid (), SIGINT);
560 /* Read the AUX Vector for the specified PID, wrapping the ptrace(2) call
561 with the PIOD_READ_AUXV operation and using the PT_IO standard input
562 and output arguments. */
564 static size_t
565 netbsd_read_auxv(pid_t pid, void *offs, void *addr, size_t len)
567 struct ptrace_io_desc pio;
569 pio.piod_op = PIOD_READ_AUXV;
570 pio.piod_offs = offs;
571 pio.piod_addr = addr;
572 pio.piod_len = len;
574 if (ptrace (PT_IO, pid, &pio, 0) == -1)
575 perror_with_name (("ptrace"));
577 return pio.piod_len;
580 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
581 to debugger memory starting at MYADDR. */
584 netbsd_process_target::read_auxv (CORE_ADDR offset,
585 unsigned char *myaddr, unsigned int len)
587 pid_t pid = pid_of (current_thread);
589 return netbsd_read_auxv (pid, (void *) (intptr_t) offset, myaddr, len);
592 bool
593 netbsd_process_target::supports_z_point_type (char z_type)
595 switch (z_type)
597 case Z_PACKET_SW_BP:
598 return true;
599 case Z_PACKET_HW_BP:
600 case Z_PACKET_WRITE_WP:
601 case Z_PACKET_READ_WP:
602 case Z_PACKET_ACCESS_WP:
603 default:
604 return false; /* Not supported. */
608 /* Insert {break/watch}point at address ADDR. SIZE is not used. */
611 netbsd_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
612 int size, struct raw_breakpoint *bp)
614 switch (type)
616 case raw_bkpt_type_sw:
617 return insert_memory_breakpoint (bp);
618 case raw_bkpt_type_hw:
619 case raw_bkpt_type_write_wp:
620 case raw_bkpt_type_read_wp:
621 case raw_bkpt_type_access_wp:
622 default:
623 return 1; /* Not supported. */
627 /* Remove {break/watch}point at address ADDR. SIZE is not used. */
630 netbsd_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
631 int size, struct raw_breakpoint *bp)
633 switch (type)
635 case raw_bkpt_type_sw:
636 return remove_memory_breakpoint (bp);
637 case raw_bkpt_type_hw:
638 case raw_bkpt_type_write_wp:
639 case raw_bkpt_type_read_wp:
640 case raw_bkpt_type_access_wp:
641 default:
642 return 1; /* Not supported. */
646 /* Implement the stopped_by_sw_breakpoint target_ops method. */
648 bool
649 netbsd_process_target::stopped_by_sw_breakpoint ()
651 ptrace_siginfo_t psi;
652 pid_t pid = current_process ()->pid;
654 if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
655 perror_with_name (("ptrace"));
657 return psi.psi_siginfo.si_signo == SIGTRAP &&
658 psi.psi_siginfo.si_code == TRAP_BRKPT;
661 /* Implement the supports_stopped_by_sw_breakpoint target_ops method. */
663 bool
664 netbsd_process_target::supports_stopped_by_sw_breakpoint ()
666 return true;
669 /* Implement the supports_qxfer_siginfo target_ops method. */
671 bool
672 netbsd_process_target::supports_qxfer_siginfo ()
674 return true;
677 /* Implement the qxfer_siginfo target_ops method. */
680 netbsd_process_target::qxfer_siginfo (const char *annex, unsigned char *readbuf,
681 unsigned const char *writebuf,
682 CORE_ADDR offset, int len)
684 if (current_thread == nullptr)
685 return -1;
687 pid_t pid = current_process ()->pid;
689 return netbsd_nat::qxfer_siginfo(pid, annex, readbuf, writebuf, offset, len);
692 /* Implement the supports_non_stop target_ops method. */
694 bool
695 netbsd_process_target::supports_non_stop ()
697 return false;
700 /* Implement the supports_multi_process target_ops method. */
702 bool
703 netbsd_process_target::supports_multi_process ()
705 return true;
708 /* Check if fork events are supported. */
710 bool
711 netbsd_process_target::supports_fork_events ()
713 return false;
716 /* Check if vfork events are supported. */
718 bool
719 netbsd_process_target::supports_vfork_events ()
721 return false;
724 /* Check if exec events are supported. */
726 bool
727 netbsd_process_target::supports_exec_events ()
729 return true;
732 /* Implement the supports_disable_randomization target_ops method. */
734 bool
735 netbsd_process_target::supports_disable_randomization ()
737 return false;
740 /* Extract &phdr and num_phdr in the inferior. Return 0 on success. */
742 template <typename T>
743 int get_phdr_phnum_from_proc_auxv (const pid_t pid,
744 CORE_ADDR *phdr_memaddr, int *num_phdr)
746 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
747 Aux64Info, Aux32Info>::type auxv_type;
748 const size_t auxv_size = sizeof (auxv_type);
749 const size_t auxv_buf_size = 128 * sizeof (auxv_type);
751 std::vector<char> auxv_buf;
752 auxv_buf.resize (auxv_buf_size);
754 netbsd_read_auxv (pid, nullptr, auxv_buf.data (), auxv_buf_size);
756 *phdr_memaddr = 0;
757 *num_phdr = 0;
759 for (char *buf = auxv_buf.data ();
760 buf < (auxv_buf.data () + auxv_buf_size);
761 buf += auxv_size)
763 auxv_type *const aux = (auxv_type *) buf;
765 switch (aux->a_type)
767 case AT_PHDR:
768 *phdr_memaddr = aux->a_v;
769 break;
770 case AT_PHNUM:
771 *num_phdr = aux->a_v;
772 break;
775 if (*phdr_memaddr != 0 && *num_phdr != 0)
776 break;
779 if (*phdr_memaddr == 0 || *num_phdr == 0)
781 warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
782 "phdr_memaddr = %s, phdr_num = %d",
783 core_addr_to_string (*phdr_memaddr), *num_phdr);
784 return 2;
787 return 0;
790 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present. */
792 template <typename T>
793 static CORE_ADDR
794 get_dynamic (const pid_t pid)
796 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
797 Elf64_Phdr, Elf32_Phdr>::type phdr_type;
798 const int phdr_size = sizeof (phdr_type);
800 CORE_ADDR phdr_memaddr;
801 int num_phdr;
802 if (get_phdr_phnum_from_proc_auxv<T> (pid, &phdr_memaddr, &num_phdr))
803 return 0;
805 std::vector<unsigned char> phdr_buf;
806 phdr_buf.resize (num_phdr * phdr_size);
808 if (netbsd_nat::read_memory (pid, phdr_buf.data (), phdr_memaddr,
809 phdr_buf.size (), nullptr))
810 return 0;
812 /* Compute relocation: it is expected to be 0 for "regular" executables,
813 non-zero for PIE ones. */
814 CORE_ADDR relocation = -1;
815 for (int i = 0; relocation == -1 && i < num_phdr; i++)
817 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
819 if (p->p_type == PT_PHDR)
820 relocation = phdr_memaddr - p->p_vaddr;
823 if (relocation == -1)
825 /* PT_PHDR is optional, but necessary for PIE in general. Fortunately
826 any real world executables, including PIE executables, have always
827 PT_PHDR present. PT_PHDR is not present in some shared libraries or
828 in fpc (Free Pascal 2.4) binaries but neither of those have a need for
829 or present DT_DEBUG anyway (fpc binaries are statically linked).
831 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
833 GDB could find RELOCATION also from AT_ENTRY - e_entry. */
835 return 0;
838 for (int i = 0; i < num_phdr; i++)
840 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
842 if (p->p_type == PT_DYNAMIC)
843 return p->p_vaddr + relocation;
846 return 0;
849 /* Return &_r_debug in the inferior, or -1 if not present. Return value
850 can be 0 if the inferior does not yet have the library list initialized.
851 We look for DT_MIPS_RLD_MAP first. MIPS executables use this instead of
852 DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too. */
854 template <typename T>
855 static CORE_ADDR
856 get_r_debug (const pid_t pid)
858 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
859 Elf64_Dyn, Elf32_Dyn>::type dyn_type;
860 const int dyn_size = sizeof (dyn_type);
861 unsigned char buf[sizeof (dyn_type)]; /* The larger of the two. */
862 CORE_ADDR map = -1;
864 CORE_ADDR dynamic_memaddr = get_dynamic<T> (pid);
865 if (dynamic_memaddr == 0)
866 return map;
868 while (netbsd_nat::read_memory (pid, buf, dynamic_memaddr, dyn_size, nullptr)
869 == 0)
871 dyn_type *const dyn = (dyn_type *) buf;
872 #if defined DT_MIPS_RLD_MAP
873 union
875 T map;
876 unsigned char buf[sizeof (T)];
878 rld_map;
880 if (dyn->d_tag == DT_MIPS_RLD_MAP)
882 if (netbsd_nat::read_memory (pid, rld_map.buf, dyn->d_un.d_val,
883 sizeof (rld_map.buf), nullptr) == 0)
884 return rld_map.map;
885 else
886 break;
888 #endif /* DT_MIPS_RLD_MAP */
890 if (dyn->d_tag == DT_DEBUG && map == -1)
891 map = dyn->d_un.d_val;
893 if (dyn->d_tag == DT_NULL)
894 break;
896 dynamic_memaddr += dyn_size;
899 return map;
902 /* Read one pointer from MEMADDR in the inferior. */
904 static int
905 read_one_ptr (const pid_t pid, CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
907 /* Go through a union so this works on either big or little endian
908 hosts, when the inferior's pointer size is smaller than the size
909 of CORE_ADDR. It is assumed the inferior's endianness is the
910 same of the superior's. */
912 union
914 CORE_ADDR core_addr;
915 unsigned int ui;
916 unsigned char uc;
917 } addr;
919 int ret = netbsd_nat::read_memory (pid, &addr.uc, memaddr, ptr_size, nullptr);
920 if (ret == 0)
922 if (ptr_size == sizeof (CORE_ADDR))
923 *ptr = addr.core_addr;
924 else if (ptr_size == sizeof (unsigned int))
925 *ptr = addr.ui;
926 else
927 gdb_assert_not_reached ("unhandled pointer size");
929 return ret;
932 /* Construct qXfer:libraries-svr4:read reply. */
934 template <typename T>
936 netbsd_qxfer_libraries_svr4 (const pid_t pid, const char *annex,
937 unsigned char *readbuf,
938 unsigned const char *writebuf,
939 CORE_ADDR offset, int len)
941 struct link_map_offsets
943 /* Offset and size of r_debug.r_version. */
944 int r_version_offset;
946 /* Offset and size of r_debug.r_map. */
947 int r_map_offset;
949 /* Offset to l_addr field in struct link_map. */
950 int l_addr_offset;
952 /* Offset to l_name field in struct link_map. */
953 int l_name_offset;
955 /* Offset to l_ld field in struct link_map. */
956 int l_ld_offset;
958 /* Offset to l_next field in struct link_map. */
959 int l_next_offset;
961 /* Offset to l_prev field in struct link_map. */
962 int l_prev_offset;
965 static const struct link_map_offsets lmo_32bit_offsets =
967 0, /* r_version offset. */
968 4, /* r_debug.r_map offset. */
969 0, /* l_addr offset in link_map. */
970 4, /* l_name offset in link_map. */
971 8, /* l_ld offset in link_map. */
972 12, /* l_next offset in link_map. */
973 16 /* l_prev offset in link_map. */
976 static const struct link_map_offsets lmo_64bit_offsets =
978 0, /* r_version offset. */
979 8, /* r_debug.r_map offset. */
980 0, /* l_addr offset in link_map. */
981 8, /* l_name offset in link_map. */
982 16, /* l_ld offset in link_map. */
983 24, /* l_next offset in link_map. */
984 32 /* l_prev offset in link_map. */
987 CORE_ADDR lm_addr = 0, lm_prev = 0;
988 CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
989 int header_done = 0;
991 const struct link_map_offsets *lmo
992 = ((sizeof (T) == sizeof (int64_t))
993 ? &lmo_64bit_offsets : &lmo_32bit_offsets);
994 int ptr_size = sizeof (T);
996 while (annex[0] != '\0')
998 const char *sep = strchr (annex, '=');
999 if (sep == nullptr)
1000 break;
1002 int name_len = sep - annex;
1003 CORE_ADDR *addrp;
1004 if (name_len == 5 && startswith (annex, "start"))
1005 addrp = &lm_addr;
1006 else if (name_len == 4 && startswith (annex, "prev"))
1007 addrp = &lm_prev;
1008 else
1010 annex = strchr (sep, ';');
1011 if (annex == nullptr)
1012 break;
1013 annex++;
1014 continue;
1017 annex = decode_address_to_semicolon (addrp, sep + 1);
1020 if (lm_addr == 0)
1022 CORE_ADDR r_debug = get_r_debug<T> (pid);
1024 /* We failed to find DT_DEBUG. Such situation will not change
1025 for this inferior - do not retry it. Report it to GDB as
1026 E01, see for the reasons at the GDB solib-svr4.c side. */
1027 if (r_debug == (CORE_ADDR) -1)
1028 return -1;
1030 if (r_debug != 0)
1032 CORE_ADDR map_offset = r_debug + lmo->r_map_offset;
1033 if (read_one_ptr (pid, map_offset, &lm_addr, ptr_size) != 0)
1034 warning ("unable to read r_map from %s",
1035 core_addr_to_string (map_offset));
1039 std::string document = "<library-list-svr4 version=\"1.0\"";
1041 while (lm_addr
1042 && read_one_ptr (pid, lm_addr + lmo->l_name_offset,
1043 &l_name, ptr_size) == 0
1044 && read_one_ptr (pid, lm_addr + lmo->l_addr_offset,
1045 &l_addr, ptr_size) == 0
1046 && read_one_ptr (pid, lm_addr + lmo->l_ld_offset,
1047 &l_ld, ptr_size) == 0
1048 && read_one_ptr (pid, lm_addr + lmo->l_prev_offset,
1049 &l_prev, ptr_size) == 0
1050 && read_one_ptr (pid, lm_addr + lmo->l_next_offset,
1051 &l_next, ptr_size) == 0)
1053 if (lm_prev != l_prev)
1055 warning ("Corrupted shared library list: 0x%lx != 0x%lx",
1056 (long) lm_prev, (long) l_prev);
1057 break;
1060 /* Ignore the first entry even if it has valid name as the first entry
1061 corresponds to the main executable. The first entry should not be
1062 skipped if the dynamic loader was loaded late by a static executable
1063 (see solib-svr4.c parameter ignore_first). But in such case the main
1064 executable does not have PT_DYNAMIC present and this function already
1065 exited above due to failed get_r_debug. */
1066 if (lm_prev == 0)
1067 string_appendf (document, " main-lm=\"0x%lx\"",
1068 (unsigned long) lm_addr);
1069 else
1071 unsigned char libname[PATH_MAX];
1073 /* Not checking for error because reading may stop before
1074 we've got PATH_MAX worth of characters. */
1075 libname[0] = '\0';
1076 netbsd_nat::read_memory (pid, libname, l_name, sizeof (libname) - 1,
1077 nullptr);
1078 libname[sizeof (libname) - 1] = '\0';
1079 if (libname[0] != '\0')
1081 if (!header_done)
1083 /* Terminate `<library-list-svr4'. */
1084 document += '>';
1085 header_done = 1;
1088 string_appendf (document, "<library name=\"");
1089 xml_escape_text_append (&document, (char *) libname);
1090 string_appendf (document, "\" lm=\"0x%lx\" "
1091 "l_addr=\"0x%lx\" l_ld=\"0x%lx\"/>",
1092 (unsigned long) lm_addr, (unsigned long) l_addr,
1093 (unsigned long) l_ld);
1097 lm_prev = lm_addr;
1098 lm_addr = l_next;
1101 if (!header_done)
1103 /* Empty list; terminate `<library-list-svr4'. */
1104 document += "/>";
1106 else
1107 document += "</library-list-svr4>";
1109 int document_len = document.length ();
1110 if (offset < document_len)
1111 document_len -= offset;
1112 else
1113 document_len = 0;
1114 if (len > document_len)
1115 len = document_len;
1117 memcpy (readbuf, document.data () + offset, len);
1119 return len;
1122 /* Return true if FILE is a 64-bit ELF file,
1123 false if the file is not a 64-bit ELF file,
1124 and error if the file is not accessible or doesn't exist. */
1126 static bool
1127 elf_64_file_p (const char *file)
1129 int fd = gdb::handle_eintr (-1, ::open, file, O_RDONLY);
1130 if (fd < 0)
1131 perror_with_name (("open"));
1133 Elf64_Ehdr header;
1134 ssize_t ret = gdb::handle_eintr (-1, ::read, fd, &header, sizeof (header));
1135 if (ret == -1)
1136 perror_with_name (("read"));
1137 gdb::handle_eintr (-1, ::close, fd);
1138 if (ret != sizeof (header))
1139 error ("Cannot read ELF file header: %s", file);
1141 if (header.e_ident[EI_MAG0] != ELFMAG0
1142 || header.e_ident[EI_MAG1] != ELFMAG1
1143 || header.e_ident[EI_MAG2] != ELFMAG2
1144 || header.e_ident[EI_MAG3] != ELFMAG3)
1145 error ("Unrecognized ELF file header: %s", file);
1147 return header.e_ident[EI_CLASS] == ELFCLASS64;
1150 /* Construct qXfer:libraries-svr4:read reply. */
1153 netbsd_process_target::qxfer_libraries_svr4 (const char *annex,
1154 unsigned char *readbuf,
1155 unsigned const char *writebuf,
1156 CORE_ADDR offset, int len)
1158 if (writebuf != nullptr)
1159 return -2;
1160 if (readbuf == nullptr)
1161 return -1;
1163 struct process_info *proc = current_process ();
1164 pid_t pid = proc->pid;
1165 bool is_elf64 = elf_64_file_p (netbsd_nat::pid_to_exec_file (pid));
1167 if (is_elf64)
1168 return netbsd_qxfer_libraries_svr4<int64_t> (pid, annex, readbuf,
1169 writebuf, offset, len);
1170 else
1171 return netbsd_qxfer_libraries_svr4<int32_t> (pid, annex, readbuf,
1172 writebuf, offset, len);
1175 /* Implement the supports_qxfer_libraries_svr4 target_ops method. */
1177 bool
1178 netbsd_process_target::supports_qxfer_libraries_svr4 ()
1180 return true;
1183 /* Return the name of a file that can be opened to get the symbols for
1184 the child process identified by PID. */
1186 const char *
1187 netbsd_process_target::pid_to_exec_file (pid_t pid)
1189 return netbsd_nat::pid_to_exec_file (pid);
1192 /* Implementation of the target_ops method "supports_pid_to_exec_file". */
1194 bool
1195 netbsd_process_target::supports_pid_to_exec_file ()
1197 return true;
1200 /* Implementation of the target_ops method "supports_hardware_single_step". */
1201 bool
1202 netbsd_process_target::supports_hardware_single_step ()
1204 return true;
1207 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1209 const gdb_byte *
1210 netbsd_process_target::sw_breakpoint_from_kind (int kind, int *size)
1212 static gdb_byte brkpt[PTRACE_BREAKPOINT_SIZE] = {*PTRACE_BREAKPOINT};
1214 *size = PTRACE_BREAKPOINT_SIZE;
1216 return brkpt;
1219 /* Implement the thread_name target_ops method. */
1221 const char *
1222 netbsd_process_target::thread_name (ptid_t ptid)
1224 return netbsd_nat::thread_name (ptid);
1227 /* Implement the supports_catch_syscall target_ops method. */
1229 bool
1230 netbsd_process_target::supports_catch_syscall ()
1232 return true;
1235 /* Implement the supports_read_auxv target_ops method. */
1237 bool
1238 netbsd_process_target::supports_read_auxv ()
1240 return true;
1243 void
1244 initialize_low ()
1246 set_target_ops (the_netbsd_target);