gdbserver: replace direct assignments to current_thread
[binutils-gdb.git] / gdbserver / netbsd-low.cc
1 /* Copyright (C) 2020-2021 Free Software Foundation, Inc.
2
3 This file is part of GDB.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17
18 #include "server.h"
19 #include "target.h"
20 #include "netbsd-low.h"
21 #include "nat/netbsd-nat.h"
22
23 #include <sys/param.h>
24 #include <sys/types.h>
25
26 #include <sys/ptrace.h>
27 #include <sys/sysctl.h>
28
29 #include <limits.h>
30 #include <unistd.h>
31 #include <signal.h>
32
33 #include <elf.h>
34
35 #include <type_traits>
36
37 #include "gdbsupport/eintr.h"
38 #include "gdbsupport/gdb_wait.h"
39 #include "gdbsupport/filestuff.h"
40 #include "gdbsupport/common-inferior.h"
41 #include "nat/fork-inferior.h"
42 #include "hostio.h"
43
44 int using_threads = 1;
45
46 /* Callback used by fork_inferior to start tracing the inferior. */
47
48 static void
49 netbsd_ptrace_fun ()
50 {
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"));
55
56 if (ptrace (PT_TRACE_ME, 0, nullptr, 0) < 0)
57 trace_start_error_with_name (("ptrace"));
58
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 ())
63 {
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)
72 {
73 /* Errors ignored. */
74 }
75 }
76 }
77
78 /* Implement the create_inferior method of the target_ops vector. */
79
80 int
81 netbsd_process_target::create_inferior (const char *program,
82 const std::vector<char *> &program_args)
83 {
84 std::string str_program_args = construct_inferior_arguments (program_args);
85
86 pid_t pid = fork_inferior (program, str_program_args.c_str (),
87 get_environ ()->envp (), netbsd_ptrace_fun,
88 nullptr, nullptr, nullptr, nullptr);
89
90 add_process (pid, 0);
91
92 post_fork_inferior (pid, program);
93
94 return pid;
95 }
96
97 /* Implement the post_create_inferior target_ops method. */
98
99 void
100 netbsd_process_target::post_create_inferior ()
101 {
102 pid_t pid = current_process ()->pid;
103 netbsd_nat::enable_proc_events (pid);
104
105 low_arch_setup ();
106 }
107
108 /* Implement the attach target_ops method. */
109
110 int
111 netbsd_process_target::attach (unsigned long pid)
112 {
113 /* Unimplemented. */
114 return -1;
115 }
116
117 /* Returns true if GDB is interested in any child syscalls. */
118
119 static bool
120 gdb_catching_syscalls_p (pid_t pid)
121 {
122 struct process_info *proc = find_process_pid (pid);
123 return !proc->syscalls_to_catch.empty ();
124 }
125
126 /* Implement the resume target_ops method. */
127
128 void
129 netbsd_process_target::resume (struct thread_resume *resume_info, size_t n)
130 {
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;
134
135 if (resume_ptid == minus_one_ptid)
136 resume_ptid = ptid_of (current_thread);
137
138 const pid_t pid = resume_ptid.pid ();
139 const lwpid_t lwp = resume_ptid.lwp ();
140 regcache_invalidate_pid (pid);
141
142 auto fn
143 = [&] (ptid_t ptid)
144 {
145 if (step)
146 {
147 if (ptid.lwp () == lwp || n != 1)
148 {
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"));
153 }
154 else
155 {
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"));
160 }
161 }
162 else
163 {
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"));
168 }
169 };
170
171 netbsd_nat::for_each_thread (pid, fn);
172
173 int request = gdb_catching_syscalls_p (pid) ? PT_CONTINUE : PT_SYSCALL;
174
175 errno = 0;
176 ptrace (request, pid, (void *)1, signal);
177 if (errno)
178 perror_with_name (("ptrace"));
179 }
180
181 /* Returns true if GDB is interested in the reported SYSNO syscall. */
182
183 static bool
184 netbsd_catch_this_syscall (int sysno)
185 {
186 struct process_info *proc = current_process ();
187
188 if (proc->syscalls_to_catch.empty ())
189 return false;
190
191 if (proc->syscalls_to_catch[0] == ANY_SYSCALL)
192 return true;
193
194 for (int iter : proc->syscalls_to_catch)
195 if (iter == sysno)
196 return true;
197
198 return false;
199 }
200
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. */
204
205 static void
206 netbsd_store_waitstatus (struct target_waitstatus *ourstatus, int hoststatus)
207 {
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)));
214 }
215
216 /* Implement a safe wrapper around waitpid(). */
217
218 static pid_t
219 netbsd_waitpid (ptid_t ptid, struct target_waitstatus *ourstatus,
220 target_wait_flags target_options)
221 {
222 int status;
223 int options = (target_options & TARGET_WNOHANG) ? WNOHANG : 0;
224
225 pid_t pid
226 = gdb::handle_eintr (-1, ::waitpid, ptid.pid (), &status, options);
227
228 if (pid == -1)
229 perror_with_name (_("Child process unexpectedly missing"));
230
231 netbsd_store_waitstatus (ourstatus, status);
232 return pid;
233 }
234
235
236 /* Implement the wait target_ops method.
237
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. */
241
242 static ptid_t
243 netbsd_wait (ptid_t ptid, struct target_waitstatus *ourstatus,
244 target_wait_flags target_options)
245 {
246 pid_t pid = netbsd_waitpid (ptid, ourstatus, target_options);
247 ptid_t wptid = ptid_t (pid);
248
249 if (pid == 0)
250 {
251 gdb_assert (target_options & TARGET_WNOHANG);
252 ourstatus->set_ignore ();
253 return null_ptid;
254 }
255
256 gdb_assert (pid != -1);
257
258 /* If the child stopped, keep investigating its status. */
259 if (ourstatus->kind () != TARGET_WAITKIND_STOPPED)
260 return wptid;
261
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"));
266
267 /* Pick child's siginfo_t. */
268 siginfo_t *si = &psi.psi_siginfo;
269
270 lwpid_t lwp = psi.psi_lwpid;
271
272 int signo = si->si_signo;
273 const int code = si->si_code;
274
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);
278
279 /* Bail out on non-debugger oriented signals. */
280 if (signo != SIGTRAP)
281 return wptid;
282
283 /* Stop examining non-debugger oriented SIGTRAP codes. */
284 if (code <= SI_USER || code == SI_NOINFO)
285 return wptid;
286
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"));
292
293 if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_EXIT)
294 {
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
303 {
304 /* NetBSD does not store an LWP exit status. */
305 ourstatus->set_thread_exited (0);
306
307 remove_thread (thr);
308 }
309 return wptid;
310 }
311
312 if (find_thread_ptid (ptid_t (pid)))
313 switch_to_thread (find_thread_ptid (wptid));
314
315 if (code == TRAP_LWP && pst.pe_report_event == PTRACE_LWP_CREATE)
316 {
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
324 {
325 add_thread (wptid, NULL);
326 ourstatus->set_thread_created ();
327 }
328 return wptid;
329 }
330
331 if (code == TRAP_EXEC)
332 {
333 ourstatus->set_execd
334 (make_unique_xstrdup (netbsd_nat::pid_to_exec_file (pid)));
335 return wptid;
336 }
337
338 if (code == TRAP_TRACE)
339 return wptid;
340
341 if (code == TRAP_SCE || code == TRAP_SCX)
342 {
343 int sysnum = si->si_sysnum;
344
345 if (!netbsd_catch_this_syscall(sysnum))
346 {
347 /* If the core isn't interested in this event, ignore it. */
348 ourstatus->set_spurious ();
349 return wptid;
350 }
351
352 if (code == TRAP_SCE)
353 ourstatus->set_syscall_entry (sysnum);
354 else
355 ourstatus->set_syscall_return (sysnum);
356
357 return wptid;
358 }
359
360 if (code == TRAP_BRKPT)
361 {
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;
371 }
372
373 /* Unclassified SIGTRAP event. */
374 ourstatus->set_spurious ();
375 return wptid;
376 }
377
378 /* Implement the wait target_ops method. */
379
380 ptid_t
381 netbsd_process_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
382 target_wait_flags target_options)
383 {
384 while (true)
385 {
386 ptid_t wptid = netbsd_wait (ptid, ourstatus, target_options);
387
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);
396
397 switch (ourstatus->kind ())
398 {
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"));
422 }
423 }
424 }
425
426 /* Implement the kill target_ops method. */
427
428 int
429 netbsd_process_target::kill (process_info *process)
430 {
431 pid_t pid = process->pid;
432 if (ptrace (PT_KILL, pid, nullptr, 0) == -1)
433 return -1;
434
435 int status;
436 if (gdb::handle_eintr (-1, ::waitpid, pid, &status, 0) == -1)
437 return -1;
438 mourn (process);
439 return 0;
440 }
441
442 /* Implement the detach target_ops method. */
443
444 int
445 netbsd_process_target::detach (process_info *process)
446 {
447 pid_t pid = process->pid;
448
449 ptrace (PT_DETACH, pid, (void *) 1, 0);
450 mourn (process);
451 return 0;
452 }
453
454 /* Implement the mourn target_ops method. */
455
456 void
457 netbsd_process_target::mourn (struct process_info *proc)
458 {
459 for_each_thread (proc->pid, remove_thread);
460
461 remove_process (proc);
462 }
463
464 /* Implement the join target_ops method. */
465
466 void
467 netbsd_process_target::join (int pid)
468 {
469 /* The PT_DETACH is sufficient to detach from the process.
470 So no need to do anything extra. */
471 }
472
473 /* Implement the thread_alive target_ops method. */
474
475 bool
476 netbsd_process_target::thread_alive (ptid_t ptid)
477 {
478 return netbsd_nat::thread_alive (ptid);
479 }
480
481 /* Implement the fetch_registers target_ops method. */
482
483 void
484 netbsd_process_target::fetch_registers (struct regcache *regcache, int regno)
485 {
486 const netbsd_regset_info *regset = get_regs_info ();
487 ptid_t inferior_ptid = ptid_of (current_thread);
488
489 while (regset->size >= 0)
490 {
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++;
499 }
500 }
501
502 /* Implement the store_registers target_ops method. */
503
504 void
505 netbsd_process_target::store_registers (struct regcache *regcache, int regno)
506 {
507 const netbsd_regset_info *regset = get_regs_info ();
508 ptid_t inferior_ptid = ptid_of (current_thread);
509
510 while (regset->size >= 0)
511 {
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"));
518
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++;
527 }
528 }
529
530 /* Implement the read_memory target_ops method. */
531
532 int
533 netbsd_process_target::read_memory (CORE_ADDR memaddr, unsigned char *myaddr,
534 int size)
535 {
536 pid_t pid = current_process ()->pid;
537 return netbsd_nat::read_memory (pid, myaddr, memaddr, size, nullptr);
538 }
539
540 /* Implement the write_memory target_ops method. */
541
542 int
543 netbsd_process_target::write_memory (CORE_ADDR memaddr,
544 const unsigned char *myaddr, int size)
545 {
546 pid_t pid = current_process ()->pid;
547 return netbsd_nat::write_memory (pid, myaddr, memaddr, size, nullptr);
548 }
549
550 /* Implement the request_interrupt target_ops method. */
551
552 void
553 netbsd_process_target::request_interrupt ()
554 {
555 ptid_t inferior_ptid = ptid_of (get_first_thread ());
556
557 ::kill (inferior_ptid.pid (), SIGINT);
558 }
559
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. */
563
564 static size_t
565 netbsd_read_auxv(pid_t pid, void *offs, void *addr, size_t len)
566 {
567 struct ptrace_io_desc pio;
568
569 pio.piod_op = PIOD_READ_AUXV;
570 pio.piod_offs = offs;
571 pio.piod_addr = addr;
572 pio.piod_len = len;
573
574 if (ptrace (PT_IO, pid, &pio, 0) == -1)
575 perror_with_name (("ptrace"));
576
577 return pio.piod_len;
578 }
579
580 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
581 to debugger memory starting at MYADDR. */
582
583 int
584 netbsd_process_target::read_auxv (CORE_ADDR offset,
585 unsigned char *myaddr, unsigned int len)
586 {
587 pid_t pid = pid_of (current_thread);
588
589 return netbsd_read_auxv (pid, (void *) (intptr_t) offset, myaddr, len);
590 }
591
592 bool
593 netbsd_process_target::supports_z_point_type (char z_type)
594 {
595 switch (z_type)
596 {
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. */
605 }
606 }
607
608 /* Insert {break/watch}point at address ADDR. SIZE is not used. */
609
610 int
611 netbsd_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
612 int size, struct raw_breakpoint *bp)
613 {
614 switch (type)
615 {
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. */
624 }
625 }
626
627 /* Remove {break/watch}point at address ADDR. SIZE is not used. */
628
629 int
630 netbsd_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
631 int size, struct raw_breakpoint *bp)
632 {
633 switch (type)
634 {
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. */
643 }
644 }
645
646 /* Implement the stopped_by_sw_breakpoint target_ops method. */
647
648 bool
649 netbsd_process_target::stopped_by_sw_breakpoint ()
650 {
651 ptrace_siginfo_t psi;
652 pid_t pid = current_process ()->pid;
653
654 if (ptrace (PT_GET_SIGINFO, pid, &psi, sizeof (psi)) == -1)
655 perror_with_name (("ptrace"));
656
657 return psi.psi_siginfo.si_signo == SIGTRAP &&
658 psi.psi_siginfo.si_code == TRAP_BRKPT;
659 }
660
661 /* Implement the supports_stopped_by_sw_breakpoint target_ops method. */
662
663 bool
664 netbsd_process_target::supports_stopped_by_sw_breakpoint ()
665 {
666 return true;
667 }
668
669 /* Implement the supports_qxfer_siginfo target_ops method. */
670
671 bool
672 netbsd_process_target::supports_qxfer_siginfo ()
673 {
674 return true;
675 }
676
677 /* Implement the qxfer_siginfo target_ops method. */
678
679 int
680 netbsd_process_target::qxfer_siginfo (const char *annex, unsigned char *readbuf,
681 unsigned const char *writebuf,
682 CORE_ADDR offset, int len)
683 {
684 if (current_thread == nullptr)
685 return -1;
686
687 pid_t pid = current_process ()->pid;
688
689 return netbsd_nat::qxfer_siginfo(pid, annex, readbuf, writebuf, offset, len);
690 }
691
692 /* Implement the supports_non_stop target_ops method. */
693
694 bool
695 netbsd_process_target::supports_non_stop ()
696 {
697 return false;
698 }
699
700 /* Implement the supports_multi_process target_ops method. */
701
702 bool
703 netbsd_process_target::supports_multi_process ()
704 {
705 return true;
706 }
707
708 /* Check if fork events are supported. */
709
710 bool
711 netbsd_process_target::supports_fork_events ()
712 {
713 return false;
714 }
715
716 /* Check if vfork events are supported. */
717
718 bool
719 netbsd_process_target::supports_vfork_events ()
720 {
721 return false;
722 }
723
724 /* Check if exec events are supported. */
725
726 bool
727 netbsd_process_target::supports_exec_events ()
728 {
729 return true;
730 }
731
732 /* Implement the supports_disable_randomization target_ops method. */
733
734 bool
735 netbsd_process_target::supports_disable_randomization ()
736 {
737 return false;
738 }
739
740 /* Extract &phdr and num_phdr in the inferior. Return 0 on success. */
741
742 template <typename T>
743 int get_phdr_phnum_from_proc_auxv (const pid_t pid,
744 CORE_ADDR *phdr_memaddr, int *num_phdr)
745 {
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);
750
751 std::vector<char> auxv_buf;
752 auxv_buf.resize (auxv_buf_size);
753
754 netbsd_read_auxv (pid, nullptr, auxv_buf.data (), auxv_buf_size);
755
756 *phdr_memaddr = 0;
757 *num_phdr = 0;
758
759 for (char *buf = auxv_buf.data ();
760 buf < (auxv_buf.data () + auxv_buf_size);
761 buf += auxv_size)
762 {
763 auxv_type *const aux = (auxv_type *) buf;
764
765 switch (aux->a_type)
766 {
767 case AT_PHDR:
768 *phdr_memaddr = aux->a_v;
769 break;
770 case AT_PHNUM:
771 *num_phdr = aux->a_v;
772 break;
773 }
774
775 if (*phdr_memaddr != 0 && *num_phdr != 0)
776 break;
777 }
778
779 if (*phdr_memaddr == 0 || *num_phdr == 0)
780 {
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;
785 }
786
787 return 0;
788 }
789
790 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present. */
791
792 template <typename T>
793 static CORE_ADDR
794 get_dynamic (const pid_t pid)
795 {
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);
799
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;
804
805 std::vector<unsigned char> phdr_buf;
806 phdr_buf.resize (num_phdr * phdr_size);
807
808 if (netbsd_nat::read_memory (pid, phdr_buf.data (), phdr_memaddr,
809 phdr_buf.size (), nullptr))
810 return 0;
811
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++)
816 {
817 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
818
819 if (p->p_type == PT_PHDR)
820 relocation = phdr_memaddr - p->p_vaddr;
821 }
822
823 if (relocation == -1)
824 {
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).
830
831 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
832
833 GDB could find RELOCATION also from AT_ENTRY - e_entry. */
834
835 return 0;
836 }
837
838 for (int i = 0; i < num_phdr; i++)
839 {
840 phdr_type *const p = (phdr_type *) (phdr_buf.data () + i * phdr_size);
841
842 if (p->p_type == PT_DYNAMIC)
843 return p->p_vaddr + relocation;
844 }
845
846 return 0;
847 }
848
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. */
853
854 template <typename T>
855 static CORE_ADDR
856 get_r_debug (const pid_t pid)
857 {
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;
863
864 CORE_ADDR dynamic_memaddr = get_dynamic<T> (pid);
865 if (dynamic_memaddr == 0)
866 return map;
867
868 while (netbsd_nat::read_memory (pid, buf, dynamic_memaddr, dyn_size, nullptr)
869 == 0)
870 {
871 dyn_type *const dyn = (dyn_type *) buf;
872 #if defined DT_MIPS_RLD_MAP
873 union
874 {
875 T map;
876 unsigned char buf[sizeof (T)];
877 }
878 rld_map;
879
880 if (dyn->d_tag == DT_MIPS_RLD_MAP)
881 {
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;
887 }
888 #endif /* DT_MIPS_RLD_MAP */
889
890 if (dyn->d_tag == DT_DEBUG && map == -1)
891 map = dyn->d_un.d_val;
892
893 if (dyn->d_tag == DT_NULL)
894 break;
895
896 dynamic_memaddr += dyn_size;
897 }
898
899 return map;
900 }
901
902 /* Read one pointer from MEMADDR in the inferior. */
903
904 static int
905 read_one_ptr (const pid_t pid, CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
906 {
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. */
911
912 union
913 {
914 CORE_ADDR core_addr;
915 unsigned int ui;
916 unsigned char uc;
917 } addr;
918
919 int ret = netbsd_nat::read_memory (pid, &addr.uc, memaddr, ptr_size, nullptr);
920 if (ret == 0)
921 {
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");
928 }
929 return ret;
930 }
931
932 /* Construct qXfer:libraries-svr4:read reply. */
933
934 template <typename T>
935 int
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)
940 {
941 struct link_map_offsets
942 {
943 /* Offset and size of r_debug.r_version. */
944 int r_version_offset;
945
946 /* Offset and size of r_debug.r_map. */
947 int r_map_offset;
948
949 /* Offset to l_addr field in struct link_map. */
950 int l_addr_offset;
951
952 /* Offset to l_name field in struct link_map. */
953 int l_name_offset;
954
955 /* Offset to l_ld field in struct link_map. */
956 int l_ld_offset;
957
958 /* Offset to l_next field in struct link_map. */
959 int l_next_offset;
960
961 /* Offset to l_prev field in struct link_map. */
962 int l_prev_offset;
963 };
964
965 static const struct link_map_offsets lmo_32bit_offsets =
966 {
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. */
974 };
975
976 static const struct link_map_offsets lmo_64bit_offsets =
977 {
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. */
985 };
986
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;
990
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);
995
996 while (annex[0] != '\0')
997 {
998 const char *sep = strchr (annex, '=');
999 if (sep == nullptr)
1000 break;
1001
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
1009 {
1010 annex = strchr (sep, ';');
1011 if (annex == nullptr)
1012 break;
1013 annex++;
1014 continue;
1015 }
1016
1017 annex = decode_address_to_semicolon (addrp, sep + 1);
1018 }
1019
1020 if (lm_addr == 0)
1021 {
1022 CORE_ADDR r_debug = get_r_debug<T> (pid);
1023
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;
1029
1030 if (r_debug != 0)
1031 {
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));
1036 }
1037 }
1038
1039 std::string document = "<library-list-svr4 version=\"1.0\"";
1040
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)
1052 {
1053 if (lm_prev != l_prev)
1054 {
1055 warning ("Corrupted shared library list: 0x%lx != 0x%lx",
1056 (long) lm_prev, (long) l_prev);
1057 break;
1058 }
1059
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
1070 {
1071 unsigned char libname[PATH_MAX];
1072
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')
1080 {
1081 if (!header_done)
1082 {
1083 /* Terminate `<library-list-svr4'. */
1084 document += '>';
1085 header_done = 1;
1086 }
1087
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);
1094 }
1095 }
1096
1097 lm_prev = lm_addr;
1098 lm_addr = l_next;
1099 }
1100
1101 if (!header_done)
1102 {
1103 /* Empty list; terminate `<library-list-svr4'. */
1104 document += "/>";
1105 }
1106 else
1107 document += "</library-list-svr4>";
1108
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;
1116
1117 memcpy (readbuf, document.data () + offset, len);
1118
1119 return len;
1120 }
1121
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. */
1125
1126 static bool
1127 elf_64_file_p (const char *file)
1128 {
1129 int fd = gdb::handle_eintr (-1, ::open, file, O_RDONLY);
1130 if (fd < 0)
1131 perror_with_name (("open"));
1132
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);
1140
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);
1146
1147 return header.e_ident[EI_CLASS] == ELFCLASS64;
1148 }
1149
1150 /* Construct qXfer:libraries-svr4:read reply. */
1151
1152 int
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)
1157 {
1158 if (writebuf != nullptr)
1159 return -2;
1160 if (readbuf == nullptr)
1161 return -1;
1162
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));
1166
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);
1173 }
1174
1175 /* Implement the supports_qxfer_libraries_svr4 target_ops method. */
1176
1177 bool
1178 netbsd_process_target::supports_qxfer_libraries_svr4 ()
1179 {
1180 return true;
1181 }
1182
1183 /* Return the name of a file that can be opened to get the symbols for
1184 the child process identified by PID. */
1185
1186 const char *
1187 netbsd_process_target::pid_to_exec_file (pid_t pid)
1188 {
1189 return netbsd_nat::pid_to_exec_file (pid);
1190 }
1191
1192 /* Implementation of the target_ops method "supports_pid_to_exec_file". */
1193
1194 bool
1195 netbsd_process_target::supports_pid_to_exec_file ()
1196 {
1197 return true;
1198 }
1199
1200 /* Implementation of the target_ops method "supports_hardware_single_step". */
1201 bool
1202 netbsd_process_target::supports_hardware_single_step ()
1203 {
1204 return true;
1205 }
1206
1207 /* Implementation of the target_ops method "sw_breakpoint_from_kind". */
1208
1209 const gdb_byte *
1210 netbsd_process_target::sw_breakpoint_from_kind (int kind, int *size)
1211 {
1212 static gdb_byte brkpt[PTRACE_BREAKPOINT_SIZE] = {*PTRACE_BREAKPOINT};
1213
1214 *size = PTRACE_BREAKPOINT_SIZE;
1215
1216 return brkpt;
1217 }
1218
1219 /* Implement the thread_name target_ops method. */
1220
1221 const char *
1222 netbsd_process_target::thread_name (ptid_t ptid)
1223 {
1224 return netbsd_nat::thread_name (ptid);
1225 }
1226
1227 /* Implement the supports_catch_syscall target_ops method. */
1228
1229 bool
1230 netbsd_process_target::supports_catch_syscall ()
1231 {
1232 return true;
1233 }
1234
1235 /* Implement the supports_read_auxv target_ops method. */
1236
1237 bool
1238 netbsd_process_target::supports_read_auxv ()
1239 {
1240 return true;
1241 }
1242
1243 void
1244 initialize_low ()
1245 {
1246 set_target_ops (the_netbsd_target);
1247 }