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