[gdb/dap] Fix exit race
[binutils-gdb.git] / gdbserver / netbsd-low.cc
blobbcb1bd97170fbd03eb144bbba93a7258d13fee99
1 /* Copyright (C) 2020-2024 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 (int pid, CORE_ADDR offset,
585 unsigned char *myaddr, unsigned int len)
587 return netbsd_read_auxv (pid, (void *) (intptr_t) offset, myaddr, len);
590 bool
591 netbsd_process_target::supports_z_point_type (char z_type)
593 switch (z_type)
595 case Z_PACKET_SW_BP:
596 return true;
597 case Z_PACKET_HW_BP:
598 case Z_PACKET_WRITE_WP:
599 case Z_PACKET_READ_WP:
600 case Z_PACKET_ACCESS_WP:
601 default:
602 return false; /* Not supported. */
606 /* Insert {break/watch}point at address ADDR. SIZE is not used. */
609 netbsd_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
610 int size, struct raw_breakpoint *bp)
612 switch (type)
614 case raw_bkpt_type_sw:
615 return insert_memory_breakpoint (bp);
616 case raw_bkpt_type_hw:
617 case raw_bkpt_type_write_wp:
618 case raw_bkpt_type_read_wp:
619 case raw_bkpt_type_access_wp:
620 default:
621 return 1; /* Not supported. */
625 /* Remove {break/watch}point at address ADDR. SIZE is not used. */
628 netbsd_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
629 int size, struct raw_breakpoint *bp)
631 switch (type)
633 case raw_bkpt_type_sw:
634 return remove_memory_breakpoint (bp);
635 case raw_bkpt_type_hw:
636 case raw_bkpt_type_write_wp:
637 case raw_bkpt_type_read_wp:
638 case raw_bkpt_type_access_wp:
639 default:
640 return 1; /* Not supported. */
644 /* Implement the stopped_by_sw_breakpoint target_ops method. */
646 bool
647 netbsd_process_target::stopped_by_sw_breakpoint ()
649 ptrace_siginfo_t psi;
650 pid_t pid = current_process ()->pid;
652 if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
653 perror_with_name (("ptrace"));
655 return psi.psi_siginfo.si_signo == SIGTRAP &&
656 psi.psi_siginfo.si_code == TRAP_BRKPT;
659 /* Implement the supports_stopped_by_sw_breakpoint target_ops method. */
661 bool
662 netbsd_process_target::supports_stopped_by_sw_breakpoint ()
664 return true;
667 /* Implement the supports_qxfer_siginfo target_ops method. */
669 bool
670 netbsd_process_target::supports_qxfer_siginfo ()
672 return true;
675 /* Implement the qxfer_siginfo target_ops method. */
678 netbsd_process_target::qxfer_siginfo (const char *annex, unsigned char *readbuf,
679 unsigned const char *writebuf,
680 CORE_ADDR offset, int len)
682 if (current_thread == nullptr)
683 return -1;
685 pid_t pid = current_process ()->pid;
687 return netbsd_nat::qxfer_siginfo(pid, annex, readbuf, writebuf, offset, len);
690 /* Implement the supports_non_stop target_ops method. */
692 bool
693 netbsd_process_target::supports_non_stop ()
695 return false;
698 /* Implement the supports_multi_process target_ops method. */
700 bool
701 netbsd_process_target::supports_multi_process ()
703 return true;
706 /* Check if fork events are supported. */
708 bool
709 netbsd_process_target::supports_fork_events ()
711 return false;
714 /* Check if vfork events are supported. */
716 bool
717 netbsd_process_target::supports_vfork_events ()
719 return false;
722 /* Check if exec events are supported. */
724 bool
725 netbsd_process_target::supports_exec_events ()
727 return true;
730 /* Implement the supports_disable_randomization target_ops method. */
732 bool
733 netbsd_process_target::supports_disable_randomization ()
735 return false;
738 /* Extract &phdr and num_phdr in the inferior. Return 0 on success. */
740 template <typename T>
741 int get_phdr_phnum_from_proc_auxv (const pid_t pid,
742 CORE_ADDR *phdr_memaddr, int *num_phdr)
744 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
745 Aux64Info, Aux32Info>::type auxv_type;
746 const size_t auxv_size = sizeof (auxv_type);
747 const size_t auxv_buf_size = 128 * sizeof (auxv_type);
749 std::vector<char> auxv_buf;
750 auxv_buf.resize (auxv_buf_size);
752 netbsd_read_auxv (pid, nullptr, auxv_buf.data (), auxv_buf_size);
754 *phdr_memaddr = 0;
755 *num_phdr = 0;
757 for (char *buf = auxv_buf.data ();
758 buf < (auxv_buf.data () + auxv_buf_size);
759 buf += auxv_size)
761 auxv_type *const aux = (auxv_type *) buf;
763 switch (aux->a_type)
765 case AT_PHDR:
766 *phdr_memaddr = aux->a_v;
767 break;
768 case AT_PHNUM:
769 *num_phdr = aux->a_v;
770 break;
773 if (*phdr_memaddr != 0 && *num_phdr != 0)
774 break;
777 if (*phdr_memaddr == 0 || *num_phdr == 0)
779 warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
780 "phdr_memaddr = %s, phdr_num = %d",
781 core_addr_to_string (*phdr_memaddr), *num_phdr);
782 return 2;
785 return 0;
788 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present. */
790 template <typename T>
791 static CORE_ADDR
792 get_dynamic (const pid_t pid)
794 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
795 Elf64_Phdr, Elf32_Phdr>::type phdr_type;
796 const int phdr_size = sizeof (phdr_type);
798 CORE_ADDR phdr_memaddr;
799 int num_phdr;
800 if (get_phdr_phnum_from_proc_auxv<T> (pid, &phdr_memaddr, &num_phdr))
801 return 0;
803 std::vector<unsigned char> phdr_buf;
804 phdr_buf.resize (num_phdr * phdr_size);
806 if (netbsd_nat::read_memory (pid, phdr_buf.data (), phdr_memaddr,
807 phdr_buf.size (), nullptr))
808 return 0;
810 /* Compute relocation: it is expected to be 0 for "regular" executables,
811 non-zero for PIE ones. */
812 CORE_ADDR relocation = -1;
813 for (int i = 0; relocation == -1 && i < num_phdr; i++)
815 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
817 if (p->p_type == PT_PHDR)
818 relocation = phdr_memaddr - p->p_vaddr;
821 if (relocation == -1)
823 /* PT_PHDR is optional, but necessary for PIE in general. Fortunately
824 any real world executables, including PIE executables, have always
825 PT_PHDR present. PT_PHDR is not present in some shared libraries or
826 in fpc (Free Pascal 2.4) binaries but neither of those have a need for
827 or present DT_DEBUG anyway (fpc binaries are statically linked).
829 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
831 GDB could find RELOCATION also from AT_ENTRY - e_entry. */
833 return 0;
836 for (int i = 0; i < num_phdr; i++)
838 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
840 if (p->p_type == PT_DYNAMIC)
841 return p->p_vaddr + relocation;
844 return 0;
847 /* Return &_r_debug in the inferior, or -1 if not present. Return value
848 can be 0 if the inferior does not yet have the library list initialized.
849 We look for DT_MIPS_RLD_MAP first. MIPS executables use this instead of
850 DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too. */
852 template <typename T>
853 static CORE_ADDR
854 get_r_debug (const pid_t pid)
856 typedef typename std::conditional<sizeof(T) == sizeof(int64_t),
857 Elf64_Dyn, Elf32_Dyn>::type dyn_type;
858 const int dyn_size = sizeof (dyn_type);
859 unsigned char buf[sizeof (dyn_type)]; /* The larger of the two. */
860 CORE_ADDR map = -1;
862 CORE_ADDR dynamic_memaddr = get_dynamic<T> (pid);
863 if (dynamic_memaddr == 0)
864 return map;
866 while (netbsd_nat::read_memory (pid, buf, dynamic_memaddr, dyn_size, nullptr)
867 == 0)
869 dyn_type *const dyn = (dyn_type *) buf;
870 #if defined DT_MIPS_RLD_MAP
871 union
873 T map;
874 unsigned char buf[sizeof (T)];
876 rld_map;
878 if (dyn->d_tag == DT_MIPS_RLD_MAP)
880 if (netbsd_nat::read_memory (pid, rld_map.buf, dyn->d_un.d_val,
881 sizeof (rld_map.buf), nullptr) == 0)
882 return rld_map.map;
883 else
884 break;
886 #endif /* DT_MIPS_RLD_MAP */
888 if (dyn->d_tag == DT_DEBUG && map == -1)
889 map = dyn->d_un.d_val;
891 if (dyn->d_tag == DT_NULL)
892 break;
894 dynamic_memaddr += dyn_size;
897 return map;
900 /* Read one pointer from MEMADDR in the inferior. */
902 static int
903 read_one_ptr (const pid_t pid, CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
905 /* Go through a union so this works on either big or little endian
906 hosts, when the inferior's pointer size is smaller than the size
907 of CORE_ADDR. It is assumed the inferior's endianness is the
908 same of the superior's. */
910 union
912 CORE_ADDR core_addr;
913 unsigned int ui;
914 unsigned char uc;
915 } addr;
917 int ret = netbsd_nat::read_memory (pid, &addr.uc, memaddr, ptr_size, nullptr);
918 if (ret == 0)
920 if (ptr_size == sizeof (CORE_ADDR))
921 *ptr = addr.core_addr;
922 else if (ptr_size == sizeof (unsigned int))
923 *ptr = addr.ui;
924 else
925 gdb_assert_not_reached ("unhandled pointer size");
927 return ret;
930 /* Construct qXfer:libraries-svr4:read reply. */
932 template <typename T>
934 netbsd_qxfer_libraries_svr4 (const pid_t pid, const char *annex,
935 unsigned char *readbuf,
936 unsigned const char *writebuf,
937 CORE_ADDR offset, int len)
939 struct link_map_offsets
941 /* Offset and size of r_debug.r_version. */
942 int r_version_offset;
944 /* Offset and size of r_debug.r_map. */
945 int r_map_offset;
947 /* Offset to l_addr field in struct link_map. */
948 int l_addr_offset;
950 /* Offset to l_name field in struct link_map. */
951 int l_name_offset;
953 /* Offset to l_ld field in struct link_map. */
954 int l_ld_offset;
956 /* Offset to l_next field in struct link_map. */
957 int l_next_offset;
959 /* Offset to l_prev field in struct link_map. */
960 int l_prev_offset;
963 static const struct link_map_offsets lmo_32bit_offsets =
965 0, /* r_version offset. */
966 4, /* r_debug.r_map offset. */
967 0, /* l_addr offset in link_map. */
968 4, /* l_name offset in link_map. */
969 8, /* l_ld offset in link_map. */
970 12, /* l_next offset in link_map. */
971 16 /* l_prev offset in link_map. */
974 static const struct link_map_offsets lmo_64bit_offsets =
976 0, /* r_version offset. */
977 8, /* r_debug.r_map offset. */
978 0, /* l_addr offset in link_map. */
979 8, /* l_name offset in link_map. */
980 16, /* l_ld offset in link_map. */
981 24, /* l_next offset in link_map. */
982 32 /* l_prev offset in link_map. */
985 CORE_ADDR lm_addr = 0, lm_prev = 0;
986 CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
987 int header_done = 0;
989 const struct link_map_offsets *lmo
990 = ((sizeof (T) == sizeof (int64_t))
991 ? &lmo_64bit_offsets : &lmo_32bit_offsets);
992 int ptr_size = sizeof (T);
994 while (annex[0] != '\0')
996 const char *sep = strchr (annex, '=');
997 if (sep == nullptr)
998 break;
1000 int name_len = sep - annex;
1001 CORE_ADDR *addrp;
1002 if (name_len == 5 && startswith (annex, "start"))
1003 addrp = &lm_addr;
1004 else if (name_len == 4 && startswith (annex, "prev"))
1005 addrp = &lm_prev;
1006 else
1008 annex = strchr (sep, ';');
1009 if (annex == nullptr)
1010 break;
1011 annex++;
1012 continue;
1015 annex = decode_address_to_semicolon (addrp, sep + 1);
1018 if (lm_addr == 0)
1020 CORE_ADDR r_debug = get_r_debug<T> (pid);
1022 /* We failed to find DT_DEBUG. Such situation will not change
1023 for this inferior - do not retry it. Report it to GDB as
1024 E01, see for the reasons at the GDB solib-svr4.c side. */
1025 if (r_debug == (CORE_ADDR) -1)
1026 return -1;
1028 if (r_debug != 0)
1030 CORE_ADDR map_offset = r_debug + lmo->r_map_offset;
1031 if (read_one_ptr (pid, map_offset, &lm_addr, ptr_size) != 0)
1032 warning ("unable to read r_map from %s",
1033 core_addr_to_string (map_offset));
1037 std::string document = "<library-list-svr4 version=\"1.0\"";
1039 while (lm_addr
1040 && read_one_ptr (pid, lm_addr + lmo->l_name_offset,
1041 &l_name, ptr_size) == 0
1042 && read_one_ptr (pid, lm_addr + lmo->l_addr_offset,
1043 &l_addr, ptr_size) == 0
1044 && read_one_ptr (pid, lm_addr + lmo->l_ld_offset,
1045 &l_ld, ptr_size) == 0
1046 && read_one_ptr (pid, lm_addr + lmo->l_prev_offset,
1047 &l_prev, ptr_size) == 0
1048 && read_one_ptr (pid, lm_addr + lmo->l_next_offset,
1049 &l_next, ptr_size) == 0)
1051 if (lm_prev != l_prev)
1053 warning ("Corrupted shared library list: 0x%lx != 0x%lx",
1054 (long) lm_prev, (long) l_prev);
1055 break;
1058 /* Ignore the first entry even if it has valid name as the first entry
1059 corresponds to the main executable. The first entry should not be
1060 skipped if the dynamic loader was loaded late by a static executable
1061 (see solib-svr4.c parameter ignore_first). But in such case the main
1062 executable does not have PT_DYNAMIC present and this function already
1063 exited above due to failed get_r_debug. */
1064 if (lm_prev == 0)
1065 string_appendf (document, " main-lm=\"0x%lx\"",
1066 (unsigned long) lm_addr);
1067 else
1069 unsigned char libname[PATH_MAX];
1071 /* Not checking for error because reading may stop before
1072 we've got PATH_MAX worth of characters. */
1073 libname[0] = '\0';
1074 netbsd_nat::read_memory (pid, libname, l_name, sizeof (libname) - 1,
1075 nullptr);
1076 libname[sizeof (libname) - 1] = '\0';
1077 if (libname[0] != '\0')
1079 if (!header_done)
1081 /* Terminate `<library-list-svr4'. */
1082 document += '>';
1083 header_done = 1;
1086 string_appendf (document, "<library name=\"");
1087 xml_escape_text_append (document, (char *) libname);
1088 string_appendf (document, "\" lm=\"0x%lx\" "
1089 "l_addr=\"0x%lx\" l_ld=\"0x%lx\"/>",
1090 (unsigned long) lm_addr, (unsigned long) l_addr,
1091 (unsigned long) l_ld);
1095 lm_prev = lm_addr;
1096 lm_addr = l_next;
1099 if (!header_done)
1101 /* Empty list; terminate `<library-list-svr4'. */
1102 document += "/>";
1104 else
1105 document += "</library-list-svr4>";
1107 int document_len = document.length ();
1108 if (offset < document_len)
1109 document_len -= offset;
1110 else
1111 document_len = 0;
1112 if (len > document_len)
1113 len = document_len;
1115 memcpy (readbuf, document.data () + offset, len);
1117 return len;
1120 /* Return true if FILE is a 64-bit ELF file,
1121 false if the file is not a 64-bit ELF file,
1122 and error if the file is not accessible or doesn't exist. */
1124 static bool
1125 elf_64_file_p (const char *file)
1127 int fd = gdb::handle_eintr (-1, ::open, file, O_RDONLY);
1128 if (fd < 0)
1129 perror_with_name (("open"));
1131 Elf64_Ehdr header;
1132 ssize_t ret = gdb::handle_eintr (-1, ::read, fd, &header, sizeof (header));
1133 if (ret == -1)
1134 perror_with_name (("read"));
1135 gdb::handle_eintr (-1, ::close, fd);
1136 if (ret != sizeof (header))
1137 error ("Cannot read ELF file header: %s", file);
1139 if (header.e_ident[EI_MAG0] != ELFMAG0
1140 || header.e_ident[EI_MAG1] != ELFMAG1
1141 || header.e_ident[EI_MAG2] != ELFMAG2
1142 || header.e_ident[EI_MAG3] != ELFMAG3)
1143 error ("Unrecognized ELF file header: %s", file);
1145 return header.e_ident[EI_CLASS] == ELFCLASS64;
1148 /* Construct qXfer:libraries-svr4:read reply. */
1151 netbsd_process_target::qxfer_libraries_svr4 (const char *annex,
1152 unsigned char *readbuf,
1153 unsigned const char *writebuf,
1154 CORE_ADDR offset, int len)
1156 if (writebuf != nullptr)
1157 return -2;
1158 if (readbuf == nullptr)
1159 return -1;
1161 struct process_info *proc = current_process ();
1162 pid_t pid = proc->pid;
1163 bool is_elf64 = elf_64_file_p (netbsd_nat::pid_to_exec_file (pid));
1165 if (is_elf64)
1166 return netbsd_qxfer_libraries_svr4<int64_t> (pid, annex, readbuf,
1167 writebuf, offset, len);
1168 else
1169 return netbsd_qxfer_libraries_svr4<int32_t> (pid, annex, readbuf,
1170 writebuf, offset, len);
1173 /* Implement the supports_qxfer_libraries_svr4 target_ops method. */
1175 bool
1176 netbsd_process_target::supports_qxfer_libraries_svr4 ()
1178 return true;
1181 /* Return the name of a file that can be opened to get the symbols for
1182 the child process identified by PID. */
1184 const char *
1185 netbsd_process_target::pid_to_exec_file (pid_t pid)
1187 return netbsd_nat::pid_to_exec_file (pid);
1190 /* Implementation of the target_ops method "supports_pid_to_exec_file". */
1192 bool
1193 netbsd_process_target::supports_pid_to_exec_file ()
1195 return true;
1198 /* Implementation of the target_ops method "supports_hardware_single_step". */
1199 bool
1200 netbsd_process_target::supports_hardware_single_step ()
1202 return true;
1205 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1207 const gdb_byte *
1208 netbsd_process_target::sw_breakpoint_from_kind (int kind, int *size)
1210 static gdb_byte brkpt[PTRACE_BREAKPOINT_SIZE] = {*PTRACE_BREAKPOINT};
1212 *size = PTRACE_BREAKPOINT_SIZE;
1214 return brkpt;
1217 /* Implement the thread_name target_ops method. */
1219 const char *
1220 netbsd_process_target::thread_name (ptid_t ptid)
1222 return netbsd_nat::thread_name (ptid);
1225 /* Implement the supports_catch_syscall target_ops method. */
1227 bool
1228 netbsd_process_target::supports_catch_syscall ()
1230 return true;
1233 /* Implement the supports_read_auxv target_ops method. */
1235 bool
1236 netbsd_process_target::supports_read_auxv ()
1238 return true;
1241 void
1242 initialize_low ()
1244 set_target_ops (the_netbsd_target);