]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/target.c
RISC-V: Tidy vendor core-v extension gas testcases
[thirdparty/binutils-gdb.git] / gdb / target.c
1 /* Select target systems and architectures at runtime for GDB.
2
3 Copyright (C) 1990-2024 Free Software Foundation, Inc.
4
5 Contributed by Cygnus Support.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22 #include "target.h"
23 #include "extract-store-integer.h"
24 #include "target-dcache.h"
25 #include "cli/cli-cmds.h"
26 #include "symtab.h"
27 #include "inferior.h"
28 #include "infrun.h"
29 #include "observable.h"
30 #include "bfd.h"
31 #include "symfile.h"
32 #include "objfiles.h"
33 #include "dcache.h"
34 #include <signal.h>
35 #include "regcache.h"
36 #include "gdbcore.h"
37 #include "target-descriptions.h"
38 #include "gdbthread.h"
39 #include "solib.h"
40 #include "exec.h"
41 #include "inline-frame.h"
42 #include "tracepoint.h"
43 #include "gdbsupport/fileio.h"
44 #include "gdbsupport/agent.h"
45 #include "auxv.h"
46 #include "target-debug.h"
47 #include "ui.h"
48 #include "event-top.h"
49 #include <algorithm>
50 #include "gdbsupport/byte-vector.h"
51 #include "gdbsupport/search.h"
52 #include "terminal.h"
53 #include <unordered_map>
54 #include "target-connection.h"
55 #include "valprint.h"
56 #include "cli/cli-decode.h"
57 #include "cli/cli-style.h"
58
59 static void generic_tls_error (void) ATTRIBUTE_NORETURN;
60
61 static void default_rcmd (struct target_ops *, const char *, struct ui_file *);
62
63 static int default_verify_memory (struct target_ops *self,
64 const gdb_byte *data,
65 CORE_ADDR memaddr, ULONGEST size);
66
67 static void tcomplain (void) ATTRIBUTE_NORETURN;
68
69 /* Mapping between target_info objects (which have address identity)
70 and corresponding open/factory function/callback. Each add_target
71 call adds one entry to this map, and registers a "target
72 TARGET_NAME" command that when invoked calls the factory registered
73 here. The target_info object is associated with the command via
74 the command's context. */
75 static std::unordered_map<const target_info *, target_open_ftype *>
76 target_factories;
77
78 /* The singleton debug target. */
79
80 static struct target_ops *the_debug_target;
81
82 /* Command list for target. */
83
84 static struct cmd_list_element *targetlist = NULL;
85
86 /* See target.h. */
87
88 bool trust_readonly = false;
89
90 /* Nonzero if we should show true memory content including
91 memory breakpoint inserted by gdb. */
92
93 static int show_memory_breakpoints = 0;
94
95 /* These globals control whether GDB attempts to perform these
96 operations; they are useful for targets that need to prevent
97 inadvertent disruption, such as in non-stop mode. */
98
99 bool may_write_registers = true;
100
101 bool may_write_memory = true;
102
103 bool may_insert_breakpoints = true;
104
105 bool may_insert_tracepoints = true;
106
107 bool may_insert_fast_tracepoints = true;
108
109 bool may_stop = true;
110
111 /* Non-zero if we want to see trace of target level stuff. */
112
113 static unsigned int targetdebug = 0;
114
115 /* Print a "target" debug statement with the function name prefix. */
116
117 #define target_debug_printf(fmt, ...) \
118 debug_prefixed_printf_cond (targetdebug > 0, "target", fmt, ##__VA_ARGS__)
119
120 /* Print a "target" debug statement without the function name prefix. */
121
122 #define target_debug_printf_nofunc(fmt, ...) \
123 debug_prefixed_printf_cond_nofunc (targetdebug > 0, "target", fmt, ##__VA_ARGS__)
124
125 static void
126 set_targetdebug (const char *args, int from_tty, struct cmd_list_element *c)
127 {
128 if (targetdebug)
129 current_inferior ()->push_target (the_debug_target);
130 else
131 current_inferior ()->unpush_target (the_debug_target);
132 }
133
134 static void
135 show_targetdebug (struct ui_file *file, int from_tty,
136 struct cmd_list_element *c, const char *value)
137 {
138 gdb_printf (file, _("Target debugging is %s.\n"), value);
139 }
140
141 int
142 target_has_memory ()
143 {
144 for (target_ops *t = current_inferior ()->top_target ();
145 t != NULL;
146 t = t->beneath ())
147 if (t->has_memory ())
148 return 1;
149
150 return 0;
151 }
152
153 int
154 target_has_stack ()
155 {
156 for (target_ops *t = current_inferior ()->top_target ();
157 t != NULL;
158 t = t->beneath ())
159 if (t->has_stack ())
160 return 1;
161
162 return 0;
163 }
164
165 int
166 target_has_registers ()
167 {
168 for (target_ops *t = current_inferior ()->top_target ();
169 t != NULL;
170 t = t->beneath ())
171 if (t->has_registers ())
172 return 1;
173
174 return 0;
175 }
176
177 bool
178 target_has_execution (inferior *inf)
179 {
180 if (inf == nullptr)
181 inf = current_inferior ();
182
183 for (target_ops *t = inf->top_target ();
184 t != nullptr;
185 t = inf->find_target_beneath (t))
186 if (t->has_execution (inf))
187 return true;
188
189 return false;
190 }
191
192 const char *
193 target_shortname ()
194 {
195 return current_inferior ()->top_target ()->shortname ();
196 }
197
198 /* See target.h. */
199
200 bool
201 target_attach_no_wait ()
202 {
203 return current_inferior ()->top_target ()->attach_no_wait ();
204 }
205
206 /* See target.h. */
207
208 void
209 target_post_attach (int pid)
210 {
211 return current_inferior ()->top_target ()->post_attach (pid);
212 }
213
214 /* See target.h. */
215
216 void
217 target_prepare_to_store (regcache *regcache)
218 {
219 return current_inferior ()->top_target ()->prepare_to_store (regcache);
220 }
221
222 /* See target.h. */
223
224 bool
225 target_supports_enable_disable_tracepoint ()
226 {
227 target_ops *target = current_inferior ()->top_target ();
228
229 return target->supports_enable_disable_tracepoint ();
230 }
231
232 bool
233 target_supports_string_tracing ()
234 {
235 return current_inferior ()->top_target ()->supports_string_tracing ();
236 }
237
238 /* See target.h. */
239
240 bool
241 target_supports_evaluation_of_breakpoint_conditions ()
242 {
243 target_ops *target = current_inferior ()->top_target ();
244
245 return target->supports_evaluation_of_breakpoint_conditions ();
246 }
247
248 /* See target.h. */
249
250 bool
251 target_supports_dumpcore ()
252 {
253 return current_inferior ()->top_target ()->supports_dumpcore ();
254 }
255
256 /* See target.h. */
257
258 void
259 target_dumpcore (const char *filename)
260 {
261 return current_inferior ()->top_target ()->dumpcore (filename);
262 }
263
264 /* See target.h. */
265
266 bool
267 target_can_run_breakpoint_commands ()
268 {
269 return current_inferior ()->top_target ()->can_run_breakpoint_commands ();
270 }
271
272 /* See target.h. */
273
274 void
275 target_files_info ()
276 {
277 return current_inferior ()->top_target ()->files_info ();
278 }
279
280 /* See target.h. */
281
282 int
283 target_insert_fork_catchpoint (int pid)
284 {
285 return current_inferior ()->top_target ()->insert_fork_catchpoint (pid);
286 }
287
288 /* See target.h. */
289
290 int
291 target_remove_fork_catchpoint (int pid)
292 {
293 return current_inferior ()->top_target ()->remove_fork_catchpoint (pid);
294 }
295
296 /* See target.h. */
297
298 int
299 target_insert_vfork_catchpoint (int pid)
300 {
301 return current_inferior ()->top_target ()->insert_vfork_catchpoint (pid);
302 }
303
304 /* See target.h. */
305
306 int
307 target_remove_vfork_catchpoint (int pid)
308 {
309 return current_inferior ()->top_target ()->remove_vfork_catchpoint (pid);
310 }
311
312 /* See target.h. */
313
314 int
315 target_insert_exec_catchpoint (int pid)
316 {
317 return current_inferior ()->top_target ()->insert_exec_catchpoint (pid);
318 }
319
320 /* See target.h. */
321
322 int
323 target_remove_exec_catchpoint (int pid)
324 {
325 return current_inferior ()->top_target ()->remove_exec_catchpoint (pid);
326 }
327
328 /* See target.h. */
329
330 int
331 target_set_syscall_catchpoint (int pid, bool needed, int any_count,
332 gdb::array_view<const int> syscall_counts)
333 {
334 target_ops *target = current_inferior ()->top_target ();
335
336 return target->set_syscall_catchpoint (pid, needed, any_count,
337 syscall_counts);
338 }
339
340 /* See target.h. */
341
342 void
343 target_rcmd (const char *command, struct ui_file *outbuf)
344 {
345 return current_inferior ()->top_target ()->rcmd (command, outbuf);
346 }
347
348 /* See target.h. */
349
350 bool
351 target_can_lock_scheduler ()
352 {
353 target_ops *target = current_inferior ()->top_target ();
354
355 return (target->get_thread_control_capabilities ()& tc_schedlock) != 0;
356 }
357
358 /* See target.h. */
359
360 bool
361 target_can_async_p ()
362 {
363 return target_can_async_p (current_inferior ()->top_target ());
364 }
365
366 /* See target.h. */
367
368 bool
369 target_can_async_p (struct target_ops *target)
370 {
371 if (!target_async_permitted)
372 return false;
373 return target->can_async_p ();
374 }
375
376 /* See target.h. */
377
378 bool
379 target_is_async_p ()
380 {
381 bool result = current_inferior ()->top_target ()->is_async_p ();
382 gdb_assert (target_async_permitted || !result);
383 return result;
384 }
385
386 exec_direction_kind
387 target_execution_direction ()
388 {
389 return current_inferior ()->top_target ()->execution_direction ();
390 }
391
392 /* See target.h. */
393
394 const char *
395 target_extra_thread_info (thread_info *tp)
396 {
397 return current_inferior ()->top_target ()->extra_thread_info (tp);
398 }
399
400 /* See target.h. */
401
402 const char *
403 target_pid_to_exec_file (int pid)
404 {
405 return current_inferior ()->top_target ()->pid_to_exec_file (pid);
406 }
407
408 /* See target.h. */
409
410 gdbarch *
411 target_thread_architecture (ptid_t ptid)
412 {
413 return current_inferior ()->top_target ()->thread_architecture (ptid);
414 }
415
416 /* See target.h. */
417
418 int
419 target_find_memory_regions (find_memory_region_ftype func, void *data)
420 {
421 return current_inferior ()->top_target ()->find_memory_regions (func, data);
422 }
423
424 /* See target.h. */
425
426 gdb::unique_xmalloc_ptr<char>
427 target_make_corefile_notes (bfd *bfd, int *size_p)
428 {
429 return current_inferior ()->top_target ()->make_corefile_notes (bfd, size_p);
430 }
431
432 gdb_byte *
433 target_get_bookmark (const char *args, int from_tty)
434 {
435 return current_inferior ()->top_target ()->get_bookmark (args, from_tty);
436 }
437
438 void
439 target_goto_bookmark (const gdb_byte *arg, int from_tty)
440 {
441 return current_inferior ()->top_target ()->goto_bookmark (arg, from_tty);
442 }
443
444 /* See target.h. */
445
446 bool
447 target_stopped_by_watchpoint ()
448 {
449 return current_inferior ()->top_target ()->stopped_by_watchpoint ();
450 }
451
452 /* See target.h. */
453
454 bool
455 target_stopped_by_sw_breakpoint ()
456 {
457 return current_inferior ()->top_target ()->stopped_by_sw_breakpoint ();
458 }
459
460 bool
461 target_supports_stopped_by_sw_breakpoint ()
462 {
463 target_ops *target = current_inferior ()->top_target ();
464
465 return target->supports_stopped_by_sw_breakpoint ();
466 }
467
468 bool
469 target_stopped_by_hw_breakpoint ()
470 {
471 return current_inferior ()->top_target ()->stopped_by_hw_breakpoint ();
472 }
473
474 bool
475 target_supports_stopped_by_hw_breakpoint ()
476 {
477 target_ops *target = current_inferior ()->top_target ();
478
479 return target->supports_stopped_by_hw_breakpoint ();
480 }
481
482 /* See target.h. */
483
484 bool
485 target_have_steppable_watchpoint ()
486 {
487 return current_inferior ()->top_target ()->have_steppable_watchpoint ();
488 }
489
490 /* See target.h. */
491
492 int
493 target_can_use_hardware_watchpoint (bptype type, int cnt, int othertype)
494 {
495 target_ops *target = current_inferior ()->top_target ();
496
497 return target->can_use_hw_breakpoint (type, cnt, othertype);
498 }
499
500 /* See target.h. */
501
502 int
503 target_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
504 {
505 target_ops *target = current_inferior ()->top_target ();
506
507 return target->region_ok_for_hw_watchpoint (addr, len);
508 }
509
510
511 int
512 target_can_do_single_step ()
513 {
514 return current_inferior ()->top_target ()->can_do_single_step ();
515 }
516
517 /* See target.h. */
518
519 int
520 target_insert_watchpoint (CORE_ADDR addr, int len, target_hw_bp_type type,
521 expression *cond)
522 {
523 target_ops *target = current_inferior ()->top_target ();
524
525 return target->insert_watchpoint (addr, len, type, cond);
526 }
527
528 /* See target.h. */
529
530 int
531 target_remove_watchpoint (CORE_ADDR addr, int len, target_hw_bp_type type,
532 expression *cond)
533 {
534 target_ops *target = current_inferior ()->top_target ();
535
536 return target->remove_watchpoint (addr, len, type, cond);
537 }
538
539 /* See target.h. */
540
541 int
542 target_insert_hw_breakpoint (gdbarch *gdbarch, bp_target_info *bp_tgt)
543 {
544 target_ops *target = current_inferior ()->top_target ();
545
546 return target->insert_hw_breakpoint (gdbarch, bp_tgt);
547 }
548
549 /* See target.h. */
550
551 int
552 target_remove_hw_breakpoint (gdbarch *gdbarch, bp_target_info *bp_tgt)
553 {
554 target_ops *target = current_inferior ()->top_target ();
555
556 return target->remove_hw_breakpoint (gdbarch, bp_tgt);
557 }
558
559 /* See target.h. */
560
561 bool
562 target_can_accel_watchpoint_condition (CORE_ADDR addr, int len, int type,
563 expression *cond)
564 {
565 target_ops *target = current_inferior ()->top_target ();
566
567 return target->can_accel_watchpoint_condition (addr, len, type, cond);
568 }
569
570 /* See target.h. */
571
572 bool
573 target_can_execute_reverse ()
574 {
575 return current_inferior ()->top_target ()->can_execute_reverse ();
576 }
577
578 ptid_t
579 target_get_ada_task_ptid (long lwp, ULONGEST tid)
580 {
581 return current_inferior ()->top_target ()->get_ada_task_ptid (lwp, tid);
582 }
583
584 bool
585 target_filesystem_is_local ()
586 {
587 return current_inferior ()->top_target ()->filesystem_is_local ();
588 }
589
590 void
591 target_trace_init ()
592 {
593 return current_inferior ()->top_target ()->trace_init ();
594 }
595
596 void
597 target_download_tracepoint (bp_location *location)
598 {
599 return current_inferior ()->top_target ()->download_tracepoint (location);
600 }
601
602 bool
603 target_can_download_tracepoint ()
604 {
605 return current_inferior ()->top_target ()->can_download_tracepoint ();
606 }
607
608 void
609 target_download_trace_state_variable (const trace_state_variable &tsv)
610 {
611 target_ops *target = current_inferior ()->top_target ();
612
613 return target->download_trace_state_variable (tsv);
614 }
615
616 void
617 target_enable_tracepoint (bp_location *loc)
618 {
619 return current_inferior ()->top_target ()->enable_tracepoint (loc);
620 }
621
622 void
623 target_disable_tracepoint (bp_location *loc)
624 {
625 return current_inferior ()->top_target ()->disable_tracepoint (loc);
626 }
627
628 void
629 target_trace_start ()
630 {
631 return current_inferior ()->top_target ()->trace_start ();
632 }
633
634 void
635 target_trace_set_readonly_regions ()
636 {
637 return current_inferior ()->top_target ()->trace_set_readonly_regions ();
638 }
639
640 int
641 target_get_trace_status (trace_status *ts)
642 {
643 return current_inferior ()->top_target ()->get_trace_status (ts);
644 }
645
646 void
647 target_get_tracepoint_status (tracepoint *tp, uploaded_tp *utp)
648 {
649 return current_inferior ()->top_target ()->get_tracepoint_status (tp, utp);
650 }
651
652 void
653 target_trace_stop ()
654 {
655 return current_inferior ()->top_target ()->trace_stop ();
656 }
657
658 int
659 target_trace_find (trace_find_type type, int num,
660 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
661 {
662 target_ops *target = current_inferior ()->top_target ();
663
664 return target->trace_find (type, num, addr1, addr2, tpp);
665 }
666
667 bool
668 target_get_trace_state_variable_value (int tsv, LONGEST *val)
669 {
670 target_ops *target = current_inferior ()->top_target ();
671
672 return target->get_trace_state_variable_value (tsv, val);
673 }
674
675 int
676 target_save_trace_data (const char *filename)
677 {
678 return current_inferior ()->top_target ()->save_trace_data (filename);
679 }
680
681 int
682 target_upload_tracepoints (uploaded_tp **utpp)
683 {
684 return current_inferior ()->top_target ()->upload_tracepoints (utpp);
685 }
686
687 int
688 target_upload_trace_state_variables (uploaded_tsv **utsvp)
689 {
690 target_ops *target = current_inferior ()->top_target ();
691
692 return target->upload_trace_state_variables (utsvp);
693 }
694
695 LONGEST
696 target_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
697 {
698 target_ops *target = current_inferior ()->top_target ();
699
700 return target->get_raw_trace_data (buf, offset, len);
701 }
702
703 int
704 target_get_min_fast_tracepoint_insn_len ()
705 {
706 target_ops *target = current_inferior ()->top_target ();
707
708 return target->get_min_fast_tracepoint_insn_len ();
709 }
710
711 void
712 target_set_disconnected_tracing (int val)
713 {
714 return current_inferior ()->top_target ()->set_disconnected_tracing (val);
715 }
716
717 void
718 target_set_circular_trace_buffer (int val)
719 {
720 return current_inferior ()->top_target ()->set_circular_trace_buffer (val);
721 }
722
723 void
724 target_set_trace_buffer_size (LONGEST val)
725 {
726 return current_inferior ()->top_target ()->set_trace_buffer_size (val);
727 }
728
729 bool
730 target_set_trace_notes (const char *user, const char *notes,
731 const char *stopnotes)
732 {
733 target_ops *target = current_inferior ()->top_target ();
734
735 return target->set_trace_notes (user, notes, stopnotes);
736 }
737
738 bool
739 target_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
740 {
741 return current_inferior ()->top_target ()->get_tib_address (ptid, addr);
742 }
743
744 void
745 target_set_permissions ()
746 {
747 return current_inferior ()->top_target ()->set_permissions ();
748 }
749
750 bool
751 target_static_tracepoint_marker_at (CORE_ADDR addr,
752 static_tracepoint_marker *marker)
753 {
754 target_ops *target = current_inferior ()->top_target ();
755
756 return target->static_tracepoint_marker_at (addr, marker);
757 }
758
759 std::vector<static_tracepoint_marker>
760 target_static_tracepoint_markers_by_strid (const char *marker_id)
761 {
762 target_ops *target = current_inferior ()->top_target ();
763
764 return target->static_tracepoint_markers_by_strid (marker_id);
765 }
766
767 traceframe_info_up
768 target_traceframe_info ()
769 {
770 return current_inferior ()->top_target ()->traceframe_info ();
771 }
772
773 bool
774 target_use_agent (bool use)
775 {
776 return current_inferior ()->top_target ()->use_agent (use);
777 }
778
779 bool
780 target_can_use_agent ()
781 {
782 return current_inferior ()->top_target ()->can_use_agent ();
783 }
784
785 bool
786 target_augmented_libraries_svr4_read ()
787 {
788 return current_inferior ()->top_target ()->augmented_libraries_svr4_read ();
789 }
790
791 bool
792 target_supports_memory_tagging ()
793 {
794 return current_inferior ()->top_target ()->supports_memory_tagging ();
795 }
796
797 bool
798 target_fetch_memtags (CORE_ADDR address, size_t len, gdb::byte_vector &tags,
799 int type)
800 {
801 return current_inferior ()->top_target ()->fetch_memtags (address, len, tags, type);
802 }
803
804 bool
805 target_store_memtags (CORE_ADDR address, size_t len,
806 const gdb::byte_vector &tags, int type)
807 {
808 return current_inferior ()->top_target ()->store_memtags (address, len, tags, type);
809 }
810
811 bool
812 target_is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
813 {
814 return current_inferior ()->top_target ()->is_address_tagged (gdbarch, address);
815 }
816
817 x86_xsave_layout
818 target_fetch_x86_xsave_layout ()
819 {
820 return current_inferior ()->top_target ()->fetch_x86_xsave_layout ();
821 }
822
823 void
824 target_log_command (const char *p)
825 {
826 return current_inferior ()->top_target ()->log_command (p);
827 }
828
829 /* This is used to implement the various target commands. */
830
831 static void
832 open_target (const char *args, int from_tty, struct cmd_list_element *command)
833 {
834 auto *ti = static_cast<target_info *> (command->context ());
835 target_open_ftype *func = target_factories[ti];
836
837 target_debug_printf_nofunc ("-> %s->open (...)", ti->shortname);
838 func (args, from_tty);
839 target_debug_printf_nofunc ("<- %s->open (%s, %d)", ti->shortname, args, from_tty);
840 }
841
842 /* See target.h. */
843
844 void
845 add_target (const target_info &t, target_open_ftype *func,
846 completer_ftype *completer)
847 {
848 struct cmd_list_element *c;
849
850 auto &func_slot = target_factories[&t];
851 if (func_slot != nullptr)
852 internal_error (_("target already added (\"%s\")."), t.shortname);
853 func_slot = func;
854
855 if (targetlist == NULL)
856 add_basic_prefix_cmd ("target", class_run, _("\
857 Connect to a target machine or process.\n\
858 The first argument is the type or protocol of the target machine.\n\
859 Remaining arguments are interpreted by the target protocol. For more\n\
860 information on the arguments for a particular protocol, type\n\
861 `help target ' followed by the protocol name."),
862 &targetlist, 0, &cmdlist);
863 c = add_cmd (t.shortname, no_class, t.doc, &targetlist);
864 c->set_context ((void *) &t);
865 c->func = open_target;
866 if (completer != NULL)
867 set_cmd_completer (c, completer);
868 }
869
870 /* See target.h. */
871
872 void
873 add_deprecated_target_alias (const target_info &tinfo, const char *alias)
874 {
875 struct cmd_list_element *c;
876
877 /* If we use add_alias_cmd, here, we do not get the deprecated warning,
878 see PR cli/15104. */
879 c = add_cmd (alias, no_class, tinfo.doc, &targetlist);
880 c->func = open_target;
881 c->set_context ((void *) &tinfo);
882 gdb::unique_xmalloc_ptr<char> alt
883 = xstrprintf ("target %s", tinfo.shortname);
884 deprecate_cmd (c, alt.release ());
885 }
886
887 /* Stub functions */
888
889 void
890 target_kill (void)
891 {
892
893 /* If the commit_resume_state of the to-be-killed-inferior's process stratum
894 is true, and this inferior is the last live inferior with resumed threads
895 of that target, then we want to leave commit_resume_state to false, as the
896 target won't have any resumed threads anymore. We achieve this with
897 this scoped_disable_commit_resumed. On construction, it will set the flag
898 to false. On destruction, it will only set it to true if there are resumed
899 threads left. */
900 scoped_disable_commit_resumed disable ("killing");
901 current_inferior ()->top_target ()->kill ();
902 }
903
904 void
905 target_load (const char *arg, int from_tty)
906 {
907 target_dcache_invalidate (current_program_space->aspace);
908 current_inferior ()->top_target ()->load (arg, from_tty);
909 }
910
911 /* Define it. */
912
913 target_terminal_state target_terminal::m_terminal_state
914 = target_terminal_state::is_ours;
915
916 /* See target/target.h. */
917
918 void
919 target_terminal::init (void)
920 {
921 current_inferior ()->top_target ()->terminal_init ();
922
923 m_terminal_state = target_terminal_state::is_ours;
924 }
925
926 /* See target/target.h. */
927
928 void
929 target_terminal::inferior (void)
930 {
931 struct ui *ui = current_ui;
932
933 /* A background resume (``run&'') should leave GDB in control of the
934 terminal. */
935 if (ui->prompt_state != PROMPT_BLOCKED)
936 return;
937
938 /* Since we always run the inferior in the main console (unless "set
939 inferior-tty" is in effect), when some UI other than the main one
940 calls target_terminal::inferior, then we leave the main UI's
941 terminal settings as is. */
942 if (ui != main_ui)
943 return;
944
945 /* If GDB is resuming the inferior in the foreground, install
946 inferior's terminal modes. */
947
948 struct inferior *inf = current_inferior ();
949
950 if (inf->terminal_state != target_terminal_state::is_inferior)
951 {
952 current_inferior ()->top_target ()->terminal_inferior ();
953 inf->terminal_state = target_terminal_state::is_inferior;
954 }
955
956 m_terminal_state = target_terminal_state::is_inferior;
957
958 /* If the user hit C-c before, pretend that it was hit right
959 here. */
960 if (check_quit_flag ())
961 target_pass_ctrlc ();
962 }
963
964 /* See target/target.h. */
965
966 void
967 target_terminal::restore_inferior (void)
968 {
969 struct ui *ui = current_ui;
970
971 /* See target_terminal::inferior(). */
972 if (ui->prompt_state != PROMPT_BLOCKED || ui != main_ui)
973 return;
974
975 /* Restore the terminal settings of inferiors that were in the
976 foreground but are now ours_for_output due to a temporary
977 target_target::ours_for_output() call. */
978
979 {
980 scoped_restore_current_inferior restore_inferior;
981
982 for (::inferior *inf : all_inferiors ())
983 {
984 if (inf->terminal_state == target_terminal_state::is_ours_for_output)
985 {
986 set_current_inferior (inf);
987 current_inferior ()->top_target ()->terminal_inferior ();
988 inf->terminal_state = target_terminal_state::is_inferior;
989 }
990 }
991 }
992
993 m_terminal_state = target_terminal_state::is_inferior;
994
995 /* If the user hit C-c before, pretend that it was hit right
996 here. */
997 if (check_quit_flag ())
998 target_pass_ctrlc ();
999 }
1000
1001 /* Switch terminal state to DESIRED_STATE, either is_ours, or
1002 is_ours_for_output. */
1003
1004 static void
1005 target_terminal_is_ours_kind (target_terminal_state desired_state)
1006 {
1007 scoped_restore_current_inferior restore_inferior;
1008
1009 /* Must do this in two passes. First, have all inferiors save the
1010 current terminal settings. Then, after all inferiors have add a
1011 chance to safely save the terminal settings, restore GDB's
1012 terminal settings. */
1013
1014 for (inferior *inf : all_inferiors ())
1015 {
1016 if (inf->terminal_state == target_terminal_state::is_inferior)
1017 {
1018 set_current_inferior (inf);
1019 current_inferior ()->top_target ()->terminal_save_inferior ();
1020 }
1021 }
1022
1023 for (inferior *inf : all_inferiors ())
1024 {
1025 /* Note we don't check is_inferior here like above because we
1026 need to handle 'is_ours_for_output -> is_ours' too. Careful
1027 to never transition from 'is_ours' to 'is_ours_for_output',
1028 though. */
1029 if (inf->terminal_state != target_terminal_state::is_ours
1030 && inf->terminal_state != desired_state)
1031 {
1032 set_current_inferior (inf);
1033 if (desired_state == target_terminal_state::is_ours)
1034 current_inferior ()->top_target ()->terminal_ours ();
1035 else if (desired_state == target_terminal_state::is_ours_for_output)
1036 current_inferior ()->top_target ()->terminal_ours_for_output ();
1037 else
1038 gdb_assert_not_reached ("unhandled desired state");
1039 inf->terminal_state = desired_state;
1040 }
1041 }
1042 }
1043
1044 /* See target/target.h. */
1045
1046 void
1047 target_terminal::ours ()
1048 {
1049 struct ui *ui = current_ui;
1050
1051 /* See target_terminal::inferior. */
1052 if (ui != main_ui)
1053 return;
1054
1055 if (m_terminal_state == target_terminal_state::is_ours)
1056 return;
1057
1058 target_terminal_is_ours_kind (target_terminal_state::is_ours);
1059 m_terminal_state = target_terminal_state::is_ours;
1060 }
1061
1062 /* See target/target.h. */
1063
1064 void
1065 target_terminal::ours_for_output ()
1066 {
1067 struct ui *ui = current_ui;
1068
1069 /* See target_terminal::inferior. */
1070 if (ui != main_ui)
1071 return;
1072
1073 if (!target_terminal::is_inferior ())
1074 return;
1075
1076 target_terminal_is_ours_kind (target_terminal_state::is_ours_for_output);
1077 target_terminal::m_terminal_state = target_terminal_state::is_ours_for_output;
1078 }
1079
1080 /* See target/target.h. */
1081
1082 void
1083 target_terminal::info (const char *arg, int from_tty)
1084 {
1085 current_inferior ()->top_target ()->terminal_info (arg, from_tty);
1086 }
1087
1088 /* See target.h. */
1089
1090 bool
1091 target_supports_terminal_ours (void)
1092 {
1093 /* The current top target is the target at the top of the target
1094 stack of the current inferior. While normally there's always an
1095 inferior, we must check for nullptr here because we can get here
1096 very early during startup, before the initial inferior is first
1097 created. */
1098 inferior *inf = current_inferior ();
1099
1100 if (inf == nullptr)
1101 return false;
1102 return inf->top_target ()->supports_terminal_ours ();
1103 }
1104
1105 static void
1106 tcomplain (void)
1107 {
1108 error (_("You can't do that when your target is `%s'"),
1109 current_inferior ()->top_target ()->shortname ());
1110 }
1111
1112 void
1113 noprocess (void)
1114 {
1115 error (_("You can't do that without a process to debug."));
1116 }
1117
1118 static void
1119 default_terminal_info (struct target_ops *self, const char *args, int from_tty)
1120 {
1121 gdb_printf (_("No saved terminal information.\n"));
1122 }
1123
1124 /* A default implementation for the to_get_ada_task_ptid target method.
1125
1126 This function builds the PTID by using both LWP and TID as part of
1127 the PTID lwp and tid elements. The pid used is the pid of the
1128 inferior_ptid. */
1129
1130 static ptid_t
1131 default_get_ada_task_ptid (struct target_ops *self, long lwp, ULONGEST tid)
1132 {
1133 return ptid_t (inferior_ptid.pid (), lwp, tid);
1134 }
1135
1136 static enum exec_direction_kind
1137 default_execution_direction (struct target_ops *self)
1138 {
1139 if (!target_can_execute_reverse ())
1140 return EXEC_FORWARD;
1141 else if (!target_can_async_p ())
1142 return EXEC_FORWARD;
1143 else
1144 gdb_assert_not_reached ("\
1145 to_execution_direction must be implemented for reverse async");
1146 }
1147
1148 /* See target.h. */
1149
1150 void
1151 target_ops_ref_policy::decref (target_ops *t)
1152 {
1153 t->decref ();
1154 if (t->refcount () == 0)
1155 {
1156 if (t->stratum () == process_stratum)
1157 connection_list_remove (as_process_stratum_target (t));
1158
1159 for (inferior *inf : all_inferiors ())
1160 gdb_assert (!inf->target_is_pushed (t));
1161
1162 fileio_handles_invalidate_target (t);
1163
1164 t->close ();
1165
1166 target_debug_printf_nofunc ("closing target");
1167 }
1168 }
1169
1170 /* See target.h. */
1171
1172 void
1173 target_stack::push (target_ops *t)
1174 {
1175 /* We must create a new reference first. It is possible that T is
1176 already pushed on this target stack, in which case we will first
1177 unpush it below, before re-pushing it. If we don't increment the
1178 reference count now, then when we unpush it, we might end up deleting
1179 T, which is not good. */
1180 auto ref = target_ops_ref::new_reference (t);
1181
1182 strata stratum = t->stratum ();
1183
1184 /* If there's already a target at this stratum, remove it. */
1185
1186 if (m_stack[stratum].get () != nullptr)
1187 unpush (m_stack[stratum].get ());
1188
1189 /* Now add the new one. */
1190 m_stack[stratum] = std::move (ref);
1191
1192 if (m_top < stratum)
1193 m_top = stratum;
1194
1195 if (stratum == process_stratum)
1196 connection_list_add (as_process_stratum_target (t));
1197 }
1198
1199 /* See target.h. */
1200
1201 bool
1202 target_stack::unpush (target_ops *t)
1203 {
1204 gdb_assert (t != NULL);
1205
1206 strata stratum = t->stratum ();
1207
1208 if (stratum == dummy_stratum)
1209 internal_error (_("Attempt to unpush the dummy target"));
1210
1211 /* Look for the specified target. Note that a target can only occur
1212 once in the target stack. */
1213
1214 if (m_stack[stratum] != t)
1215 {
1216 /* If T wasn't pushed, quit. Only open targets should be
1217 closed. */
1218 return false;
1219 }
1220
1221 if (m_top == stratum)
1222 m_top = this->find_beneath (t)->stratum ();
1223
1224 /* Move the target reference off the target stack, this sets the pointer
1225 held in m_stack to nullptr, and places the reference in ref. When
1226 ref goes out of scope its reference count will be decremented, which
1227 might cause the target to close.
1228
1229 We have to do it this way, and not just set the value in m_stack to
1230 nullptr directly, because doing so would decrement the reference
1231 count first, which might close the target, and closing the target
1232 does a check that the target is not on any inferiors target_stack. */
1233 auto ref = std::move (m_stack[stratum]);
1234
1235 return true;
1236 }
1237
1238 void
1239 target_unpusher::operator() (struct target_ops *ops) const
1240 {
1241 current_inferior ()->unpush_target (ops);
1242 }
1243
1244 /* Default implementation of to_get_thread_local_address. */
1245
1246 static void
1247 generic_tls_error (void)
1248 {
1249 throw_error (TLS_GENERIC_ERROR,
1250 _("Cannot find thread-local variables on this target"));
1251 }
1252
1253 /* Using the objfile specified in OBJFILE, find the address for the
1254 current thread's thread-local storage with offset OFFSET. */
1255 CORE_ADDR
1256 target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset)
1257 {
1258 volatile CORE_ADDR addr = 0;
1259 struct target_ops *target = current_inferior ()->top_target ();
1260 gdbarch *gdbarch = current_inferior ()->arch ();
1261
1262 /* If OBJFILE is a separate debug object file, look for the
1263 original object file. */
1264 if (objfile->separate_debug_objfile_backlink != NULL)
1265 objfile = objfile->separate_debug_objfile_backlink;
1266
1267 if (gdbarch_fetch_tls_load_module_address_p (gdbarch))
1268 {
1269 ptid_t ptid = inferior_ptid;
1270
1271 try
1272 {
1273 CORE_ADDR lm_addr;
1274
1275 /* Fetch the load module address for this objfile. */
1276 lm_addr = gdbarch_fetch_tls_load_module_address (gdbarch,
1277 objfile);
1278
1279 if (gdbarch_get_thread_local_address_p (gdbarch))
1280 addr = gdbarch_get_thread_local_address (gdbarch, ptid, lm_addr,
1281 offset);
1282 else
1283 addr = target->get_thread_local_address (ptid, lm_addr, offset);
1284 }
1285 /* If an error occurred, print TLS related messages here. Otherwise,
1286 throw the error to some higher catcher. */
1287 catch (const gdb_exception &ex)
1288 {
1289 int objfile_is_library = (objfile->flags & OBJF_SHARED);
1290
1291 switch (ex.error)
1292 {
1293 case TLS_NO_LIBRARY_SUPPORT_ERROR:
1294 error (_("Cannot find thread-local variables "
1295 "in this thread library."));
1296 break;
1297 case TLS_LOAD_MODULE_NOT_FOUND_ERROR:
1298 if (objfile_is_library)
1299 error (_("Cannot find shared library `%s' in dynamic"
1300 " linker's load module list"), objfile_name (objfile));
1301 else
1302 error (_("Cannot find executable file `%s' in dynamic"
1303 " linker's load module list"), objfile_name (objfile));
1304 break;
1305 case TLS_NOT_ALLOCATED_YET_ERROR:
1306 if (objfile_is_library)
1307 error (_("The inferior has not yet allocated storage for"
1308 " thread-local variables in\n"
1309 "the shared library `%s'\n"
1310 "for %s"),
1311 objfile_name (objfile),
1312 target_pid_to_str (ptid).c_str ());
1313 else
1314 error (_("The inferior has not yet allocated storage for"
1315 " thread-local variables in\n"
1316 "the executable `%s'\n"
1317 "for %s"),
1318 objfile_name (objfile),
1319 target_pid_to_str (ptid).c_str ());
1320 break;
1321 case TLS_GENERIC_ERROR:
1322 if (objfile_is_library)
1323 error (_("Cannot find thread-local storage for %s, "
1324 "shared library %s:\n%s"),
1325 target_pid_to_str (ptid).c_str (),
1326 objfile_name (objfile), ex.what ());
1327 else
1328 error (_("Cannot find thread-local storage for %s, "
1329 "executable file %s:\n%s"),
1330 target_pid_to_str (ptid).c_str (),
1331 objfile_name (objfile), ex.what ());
1332 break;
1333 default:
1334 throw;
1335 break;
1336 }
1337 }
1338 }
1339 else
1340 error (_("Cannot find thread-local variables on this target"));
1341
1342 return addr;
1343 }
1344
1345 const char *
1346 target_xfer_status_to_string (enum target_xfer_status status)
1347 {
1348 #define CASE(X) case X: return #X
1349 switch (status)
1350 {
1351 CASE(TARGET_XFER_E_IO);
1352 CASE(TARGET_XFER_UNAVAILABLE);
1353 default:
1354 return "<unknown>";
1355 }
1356 #undef CASE
1357 };
1358
1359
1360 const std::vector<target_section> *
1361 target_get_section_table (struct target_ops *target)
1362 {
1363 return target->get_section_table ();
1364 }
1365
1366 /* Find a section containing ADDR. */
1367
1368 const struct target_section *
1369 target_section_by_addr (struct target_ops *target, CORE_ADDR addr)
1370 {
1371 const std::vector<target_section> *table = target_get_section_table (target);
1372
1373 if (table == NULL)
1374 return NULL;
1375
1376 for (const target_section &secp : *table)
1377 {
1378 if (addr >= secp.addr && addr < secp.endaddr)
1379 return &secp;
1380 }
1381 return NULL;
1382 }
1383
1384 /* See target.h. */
1385
1386 const std::vector<target_section> *
1387 default_get_section_table ()
1388 {
1389 return &current_program_space->target_sections ();
1390 }
1391
1392 /* Helper for the memory xfer routines. Checks the attributes of the
1393 memory region of MEMADDR against the read or write being attempted.
1394 If the access is permitted returns true, otherwise returns false.
1395 REGION_P is an optional output parameter. If not-NULL, it is
1396 filled with a pointer to the memory region of MEMADDR. REG_LEN
1397 returns LEN trimmed to the end of the region. This is how much the
1398 caller can continue requesting, if the access is permitted. A
1399 single xfer request must not straddle memory region boundaries. */
1400
1401 static int
1402 memory_xfer_check_region (gdb_byte *readbuf, const gdb_byte *writebuf,
1403 ULONGEST memaddr, ULONGEST len, ULONGEST *reg_len,
1404 struct mem_region **region_p)
1405 {
1406 struct mem_region *region;
1407
1408 region = lookup_mem_region (memaddr);
1409
1410 if (region_p != NULL)
1411 *region_p = region;
1412
1413 switch (region->attrib.mode)
1414 {
1415 case MEM_RO:
1416 if (writebuf != NULL)
1417 return 0;
1418 break;
1419
1420 case MEM_WO:
1421 if (readbuf != NULL)
1422 return 0;
1423 break;
1424
1425 case MEM_FLASH:
1426 /* We only support writing to flash during "load" for now. */
1427 if (writebuf != NULL)
1428 error (_("Writing to flash memory forbidden in this context"));
1429 break;
1430
1431 case MEM_NONE:
1432 return 0;
1433 }
1434
1435 /* region->hi == 0 means there's no upper bound. */
1436 if (memaddr + len < region->hi || region->hi == 0)
1437 *reg_len = len;
1438 else
1439 *reg_len = region->hi - memaddr;
1440
1441 return 1;
1442 }
1443
1444 /* Read memory from more than one valid target. A core file, for
1445 instance, could have some of memory but delegate other bits to
1446 the target below it. So, we must manually try all targets. */
1447
1448 enum target_xfer_status
1449 raw_memory_xfer_partial (struct target_ops *ops, gdb_byte *readbuf,
1450 const gdb_byte *writebuf, ULONGEST memaddr, LONGEST len,
1451 ULONGEST *xfered_len)
1452 {
1453 enum target_xfer_status res;
1454
1455 do
1456 {
1457 res = ops->xfer_partial (TARGET_OBJECT_MEMORY, NULL,
1458 readbuf, writebuf, memaddr, len,
1459 xfered_len);
1460 if (res == TARGET_XFER_OK)
1461 break;
1462
1463 /* Stop if the target reports that the memory is not available. */
1464 if (res == TARGET_XFER_UNAVAILABLE)
1465 break;
1466
1467 /* Don't continue past targets which have all the memory.
1468 At one time, this code was necessary to read data from
1469 executables / shared libraries when data for the requested
1470 addresses weren't available in the core file. But now the
1471 core target handles this case itself. */
1472 if (ops->has_all_memory ())
1473 break;
1474
1475 ops = ops->beneath ();
1476 }
1477 while (ops != NULL);
1478
1479 /* The cache works at the raw memory level. Make sure the cache
1480 gets updated with raw contents no matter what kind of memory
1481 object was originally being written. Note we do write-through
1482 first, so that if it fails, we don't write to the cache contents
1483 that never made it to the target. */
1484 if (writebuf != NULL
1485 && inferior_ptid != null_ptid
1486 && target_dcache_init_p (current_program_space->aspace)
1487 && (stack_cache_enabled_p () || code_cache_enabled_p ()))
1488 {
1489 DCACHE *dcache = target_dcache_get (current_program_space->aspace);
1490
1491 /* Note that writing to an area of memory which wasn't present
1492 in the cache doesn't cause it to be loaded in. */
1493 dcache_update (dcache, res, memaddr, writebuf, *xfered_len);
1494 }
1495
1496 return res;
1497 }
1498
1499 /* Perform a partial memory transfer.
1500 For docs see target.h, to_xfer_partial. */
1501
1502 static enum target_xfer_status
1503 memory_xfer_partial_1 (struct target_ops *ops, enum target_object object,
1504 gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST memaddr,
1505 ULONGEST len, ULONGEST *xfered_len)
1506 {
1507 enum target_xfer_status res;
1508 ULONGEST reg_len;
1509 struct mem_region *region;
1510 struct inferior *inf;
1511
1512 /* For accesses to unmapped overlay sections, read directly from
1513 files. Must do this first, as MEMADDR may need adjustment. */
1514 if (readbuf != NULL && overlay_debugging)
1515 {
1516 struct obj_section *section = find_pc_overlay (memaddr);
1517
1518 if (pc_in_unmapped_range (memaddr, section))
1519 {
1520 const std::vector<target_section> *table = target_get_section_table (ops);
1521 const char *section_name = section->the_bfd_section->name;
1522
1523 memaddr = overlay_mapped_address (memaddr, section);
1524
1525 auto match_cb = [=] (const struct target_section *s)
1526 {
1527 return (strcmp (section_name, s->the_bfd_section->name) == 0);
1528 };
1529
1530 return section_table_xfer_memory_partial (readbuf, writebuf,
1531 memaddr, len, xfered_len,
1532 *table, match_cb);
1533 }
1534 }
1535
1536 /* Try the executable files, if "trust-readonly-sections" is set. */
1537 if (readbuf != NULL && trust_readonly)
1538 {
1539 const struct target_section *secp
1540 = target_section_by_addr (ops, memaddr);
1541 if (secp != NULL
1542 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
1543 {
1544 const std::vector<target_section> *table = target_get_section_table (ops);
1545 return section_table_xfer_memory_partial (readbuf, writebuf,
1546 memaddr, len, xfered_len,
1547 *table);
1548 }
1549 }
1550
1551 /* Try GDB's internal data cache. */
1552
1553 if (!memory_xfer_check_region (readbuf, writebuf, memaddr, len, &reg_len,
1554 &region))
1555 return TARGET_XFER_E_IO;
1556
1557 if (inferior_ptid != null_ptid)
1558 inf = current_inferior ();
1559 else
1560 inf = NULL;
1561
1562 if (inf != NULL
1563 && readbuf != NULL
1564 /* The dcache reads whole cache lines; that doesn't play well
1565 with reading from a trace buffer, because reading outside of
1566 the collected memory range fails. */
1567 && get_traceframe_number () == -1
1568 && (region->attrib.cache
1569 || (stack_cache_enabled_p () && object == TARGET_OBJECT_STACK_MEMORY)
1570 || (code_cache_enabled_p () && object == TARGET_OBJECT_CODE_MEMORY)))
1571 {
1572 DCACHE *dcache
1573 = target_dcache_get_or_init (current_program_space->aspace);
1574
1575 return dcache_read_memory_partial (ops, dcache, memaddr, readbuf,
1576 reg_len, xfered_len);
1577 }
1578
1579 /* If none of those methods found the memory we wanted, fall back
1580 to a target partial transfer. Normally a single call to
1581 to_xfer_partial is enough; if it doesn't recognize an object
1582 it will call the to_xfer_partial of the next target down.
1583 But for memory this won't do. Memory is the only target
1584 object which can be read from more than one valid target.
1585 A core file, for instance, could have some of memory but
1586 delegate other bits to the target below it. So, we must
1587 manually try all targets. */
1588
1589 res = raw_memory_xfer_partial (ops, readbuf, writebuf, memaddr, reg_len,
1590 xfered_len);
1591
1592 /* If we still haven't got anything, return the last error. We
1593 give up. */
1594 return res;
1595 }
1596
1597 /* Perform a partial memory transfer. For docs see target.h,
1598 to_xfer_partial. */
1599
1600 static enum target_xfer_status
1601 memory_xfer_partial (struct target_ops *ops, enum target_object object,
1602 gdb_byte *readbuf, const gdb_byte *writebuf,
1603 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
1604 {
1605 enum target_xfer_status res;
1606
1607 /* Zero length requests are ok and require no work. */
1608 if (len == 0)
1609 return TARGET_XFER_EOF;
1610
1611 memaddr = gdbarch_remove_non_address_bits (current_inferior ()->arch (),
1612 memaddr);
1613
1614 /* Fill in READBUF with breakpoint shadows, or WRITEBUF with
1615 breakpoint insns, thus hiding out from higher layers whether
1616 there are software breakpoints inserted in the code stream. */
1617 if (readbuf != NULL)
1618 {
1619 res = memory_xfer_partial_1 (ops, object, readbuf, NULL, memaddr, len,
1620 xfered_len);
1621
1622 if (res == TARGET_XFER_OK && !show_memory_breakpoints)
1623 breakpoint_xfer_memory (readbuf, NULL, NULL, memaddr, *xfered_len);
1624 }
1625 else
1626 {
1627 /* A large write request is likely to be partially satisfied
1628 by memory_xfer_partial_1. We will continually malloc
1629 and free a copy of the entire write request for breakpoint
1630 shadow handling even though we only end up writing a small
1631 subset of it. Cap writes to a limit specified by the target
1632 to mitigate this. */
1633 len = std::min (ops->get_memory_xfer_limit (), len);
1634
1635 gdb::byte_vector buf (writebuf, writebuf + len);
1636 breakpoint_xfer_memory (NULL, buf.data (), writebuf, memaddr, len);
1637 res = memory_xfer_partial_1 (ops, object, NULL, buf.data (), memaddr, len,
1638 xfered_len);
1639 }
1640
1641 return res;
1642 }
1643
1644 scoped_restore_tmpl<int>
1645 make_scoped_restore_show_memory_breakpoints (int show)
1646 {
1647 return make_scoped_restore (&show_memory_breakpoints, show);
1648 }
1649
1650 /* For docs see target.h, to_xfer_partial. */
1651
1652 enum target_xfer_status
1653 target_xfer_partial (struct target_ops *ops,
1654 enum target_object object, const char *annex,
1655 gdb_byte *readbuf, const gdb_byte *writebuf,
1656 ULONGEST offset, ULONGEST len,
1657 ULONGEST *xfered_len)
1658 {
1659 enum target_xfer_status retval;
1660
1661 /* Transfer is done when LEN is zero. */
1662 if (len == 0)
1663 return TARGET_XFER_EOF;
1664
1665 if (writebuf && !may_write_memory)
1666 error (_("Writing to memory is not allowed (addr %s, len %s)"),
1667 core_addr_to_string_nz (offset), plongest (len));
1668
1669 *xfered_len = 0;
1670
1671 /* If this is a memory transfer, let the memory-specific code
1672 have a look at it instead. Memory transfers are more
1673 complicated. */
1674 if (object == TARGET_OBJECT_MEMORY || object == TARGET_OBJECT_STACK_MEMORY
1675 || object == TARGET_OBJECT_CODE_MEMORY)
1676 retval = memory_xfer_partial (ops, object, readbuf,
1677 writebuf, offset, len, xfered_len);
1678 else if (object == TARGET_OBJECT_RAW_MEMORY)
1679 {
1680 /* Skip/avoid accessing the target if the memory region
1681 attributes block the access. Check this here instead of in
1682 raw_memory_xfer_partial as otherwise we'd end up checking
1683 this twice in the case of the memory_xfer_partial path is
1684 taken; once before checking the dcache, and another in the
1685 tail call to raw_memory_xfer_partial. */
1686 if (!memory_xfer_check_region (readbuf, writebuf, offset, len, &len,
1687 NULL))
1688 return TARGET_XFER_E_IO;
1689
1690 /* Request the normal memory object from other layers. */
1691 retval = raw_memory_xfer_partial (ops, readbuf, writebuf, offset, len,
1692 xfered_len);
1693 }
1694 else
1695 retval = ops->xfer_partial (object, annex, readbuf,
1696 writebuf, offset, len, xfered_len);
1697
1698 if (targetdebug)
1699 {
1700 const unsigned char *myaddr = NULL;
1701 std::string s
1702 = string_printf ("%s:target_xfer_partial "
1703 "(%d, %s, %s, %s, %s, %s) = %d, %s",
1704 ops->shortname (), (int) object,
1705 (annex ? annex : "(null)"),
1706 host_address_to_string (readbuf),
1707 host_address_to_string (writebuf),
1708 core_addr_to_string_nz (offset), pulongest (len),
1709 retval, pulongest (*xfered_len));
1710
1711 if (readbuf)
1712 myaddr = readbuf;
1713 if (writebuf)
1714 myaddr = writebuf;
1715 if (retval == TARGET_XFER_OK && myaddr != NULL)
1716 {
1717 int i;
1718
1719 string_appendf (s, ", bytes =");
1720 for (i = 0; i < *xfered_len; i++)
1721 {
1722 if ((((intptr_t) &(myaddr[i])) & 0xf) == 0)
1723 {
1724 if (targetdebug < 2 && i > 0)
1725 {
1726 string_appendf (s, " ...");
1727 break;
1728 }
1729
1730 target_debug_printf_nofunc ("%s", s.c_str ());
1731 s.clear();
1732 }
1733
1734 string_appendf (s, " %02x", myaddr[i] & 0xff);
1735 }
1736 }
1737
1738 target_debug_printf_nofunc ("%s", s.c_str ());
1739 }
1740
1741 /* Check implementations of to_xfer_partial update *XFERED_LEN
1742 properly. Do assertion after printing debug messages, so that we
1743 can find more clues on assertion failure from debugging messages. */
1744 if (retval == TARGET_XFER_OK || retval == TARGET_XFER_UNAVAILABLE)
1745 gdb_assert (*xfered_len > 0);
1746
1747 return retval;
1748 }
1749
1750 /* Read LEN bytes of target memory at address MEMADDR, placing the
1751 results in GDB's memory at MYADDR. Returns either 0 for success or
1752 -1 if any error occurs.
1753
1754 If an error occurs, no guarantee is made about the contents of the data at
1755 MYADDR. In particular, the caller should not depend upon partial reads
1756 filling the buffer with good data. There is no way for the caller to know
1757 how much good data might have been transfered anyway. Callers that can
1758 deal with partial reads should call target_read (which will retry until
1759 it makes no progress, and then return how much was transferred). */
1760
1761 int
1762 target_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1763 {
1764 if (target_read (current_inferior ()->top_target (),
1765 TARGET_OBJECT_MEMORY, NULL,
1766 myaddr, memaddr, len) == len)
1767 return 0;
1768 else
1769 return -1;
1770 }
1771
1772 /* See target/target.h. */
1773
1774 int
1775 target_read_uint32 (CORE_ADDR memaddr, uint32_t *result)
1776 {
1777 gdb_byte buf[4];
1778 int r;
1779
1780 r = target_read_memory (memaddr, buf, sizeof buf);
1781 if (r != 0)
1782 return r;
1783 *result = extract_unsigned_integer
1784 (buf, sizeof buf,
1785 gdbarch_byte_order (current_inferior ()->arch ()));
1786 return 0;
1787 }
1788
1789 /* Like target_read_memory, but specify explicitly that this is a read
1790 from the target's raw memory. That is, this read bypasses the
1791 dcache, breakpoint shadowing, etc. */
1792
1793 int
1794 target_read_raw_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1795 {
1796 if (target_read (current_inferior ()->top_target (),
1797 TARGET_OBJECT_RAW_MEMORY, NULL,
1798 myaddr, memaddr, len) == len)
1799 return 0;
1800 else
1801 return -1;
1802 }
1803
1804 /* Like target_read_memory, but specify explicitly that this is a read from
1805 the target's stack. This may trigger different cache behavior. */
1806
1807 int
1808 target_read_stack (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1809 {
1810 if (target_read (current_inferior ()->top_target (),
1811 TARGET_OBJECT_STACK_MEMORY, NULL,
1812 myaddr, memaddr, len) == len)
1813 return 0;
1814 else
1815 return -1;
1816 }
1817
1818 /* Like target_read_memory, but specify explicitly that this is a read from
1819 the target's code. This may trigger different cache behavior. */
1820
1821 int
1822 target_read_code (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1823 {
1824 if (target_read (current_inferior ()->top_target (),
1825 TARGET_OBJECT_CODE_MEMORY, NULL,
1826 myaddr, memaddr, len) == len)
1827 return 0;
1828 else
1829 return -1;
1830 }
1831
1832 /* Write LEN bytes from MYADDR to target memory at address MEMADDR.
1833 Returns either 0 for success or -1 if any error occurs. If an
1834 error occurs, no guarantee is made about how much data got written.
1835 Callers that can deal with partial writes should call
1836 target_write. */
1837
1838 int
1839 target_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1840 {
1841 if (target_write (current_inferior ()->top_target (),
1842 TARGET_OBJECT_MEMORY, NULL,
1843 myaddr, memaddr, len) == len)
1844 return 0;
1845 else
1846 return -1;
1847 }
1848
1849 /* Write LEN bytes from MYADDR to target raw memory at address
1850 MEMADDR. Returns either 0 for success or -1 if any error occurs.
1851 If an error occurs, no guarantee is made about how much data got
1852 written. Callers that can deal with partial writes should call
1853 target_write. */
1854
1855 int
1856 target_write_raw_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1857 {
1858 if (target_write (current_inferior ()->top_target (),
1859 TARGET_OBJECT_RAW_MEMORY, NULL,
1860 myaddr, memaddr, len) == len)
1861 return 0;
1862 else
1863 return -1;
1864 }
1865
1866 /* Fetch the target's memory map. */
1867
1868 std::vector<mem_region>
1869 target_memory_map (void)
1870 {
1871 target_ops *target = current_inferior ()->top_target ();
1872 std::vector<mem_region> result = target->memory_map ();
1873 if (result.empty ())
1874 return result;
1875
1876 std::sort (result.begin (), result.end ());
1877
1878 /* Check that regions do not overlap. Simultaneously assign
1879 a numbering for the "mem" commands to use to refer to
1880 each region. */
1881 mem_region *last_one = NULL;
1882 for (size_t ix = 0; ix < result.size (); ix++)
1883 {
1884 mem_region *this_one = &result[ix];
1885 this_one->number = ix;
1886
1887 if (last_one != NULL && last_one->hi > this_one->lo)
1888 {
1889 warning (_("Overlapping regions in memory map: ignoring"));
1890 return std::vector<mem_region> ();
1891 }
1892
1893 last_one = this_one;
1894 }
1895
1896 return result;
1897 }
1898
1899 void
1900 target_flash_erase (ULONGEST address, LONGEST length)
1901 {
1902 current_inferior ()->top_target ()->flash_erase (address, length);
1903 }
1904
1905 void
1906 target_flash_done (void)
1907 {
1908 current_inferior ()->top_target ()->flash_done ();
1909 }
1910
1911 static void
1912 show_trust_readonly (struct ui_file *file, int from_tty,
1913 struct cmd_list_element *c, const char *value)
1914 {
1915 gdb_printf (file,
1916 _("Mode for reading from readonly sections is %s.\n"),
1917 value);
1918 }
1919
1920 /* Target vector read/write partial wrapper functions. */
1921
1922 static enum target_xfer_status
1923 target_read_partial (struct target_ops *ops,
1924 enum target_object object,
1925 const char *annex, gdb_byte *buf,
1926 ULONGEST offset, ULONGEST len,
1927 ULONGEST *xfered_len)
1928 {
1929 return target_xfer_partial (ops, object, annex, buf, NULL, offset, len,
1930 xfered_len);
1931 }
1932
1933 static enum target_xfer_status
1934 target_write_partial (struct target_ops *ops,
1935 enum target_object object,
1936 const char *annex, const gdb_byte *buf,
1937 ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
1938 {
1939 return target_xfer_partial (ops, object, annex, NULL, buf, offset, len,
1940 xfered_len);
1941 }
1942
1943 /* Wrappers to perform the full transfer. */
1944
1945 /* For docs on target_read see target.h. */
1946
1947 LONGEST
1948 target_read (struct target_ops *ops,
1949 enum target_object object,
1950 const char *annex, gdb_byte *buf,
1951 ULONGEST offset, LONGEST len)
1952 {
1953 LONGEST xfered_total = 0;
1954 int unit_size = 1;
1955
1956 /* If we are reading from a memory object, find the length of an addressable
1957 unit for that architecture. */
1958 if (object == TARGET_OBJECT_MEMORY
1959 || object == TARGET_OBJECT_STACK_MEMORY
1960 || object == TARGET_OBJECT_CODE_MEMORY
1961 || object == TARGET_OBJECT_RAW_MEMORY)
1962 unit_size = gdbarch_addressable_memory_unit_size
1963 (current_inferior ()->arch ());
1964
1965 while (xfered_total < len)
1966 {
1967 ULONGEST xfered_partial;
1968 enum target_xfer_status status;
1969
1970 status = target_read_partial (ops, object, annex,
1971 buf + xfered_total * unit_size,
1972 offset + xfered_total, len - xfered_total,
1973 &xfered_partial);
1974
1975 /* Call an observer, notifying them of the xfer progress? */
1976 if (status == TARGET_XFER_EOF)
1977 return xfered_total;
1978 else if (status == TARGET_XFER_OK)
1979 {
1980 xfered_total += xfered_partial;
1981 QUIT;
1982 }
1983 else
1984 return TARGET_XFER_E_IO;
1985
1986 }
1987 return len;
1988 }
1989
1990 /* Assuming that the entire [begin, end) range of memory cannot be
1991 read, try to read whatever subrange is possible to read.
1992
1993 The function returns, in RESULT, either zero or one memory block.
1994 If there's a readable subrange at the beginning, it is completely
1995 read and returned. Any further readable subrange will not be read.
1996 Otherwise, if there's a readable subrange at the end, it will be
1997 completely read and returned. Any readable subranges before it
1998 (obviously, not starting at the beginning), will be ignored. In
1999 other cases -- either no readable subrange, or readable subrange(s)
2000 that is neither at the beginning, or end, nothing is returned.
2001
2002 The purpose of this function is to handle a read across a boundary
2003 of accessible memory in a case when memory map is not available.
2004 The above restrictions are fine for this case, but will give
2005 incorrect results if the memory is 'patchy'. However, supporting
2006 'patchy' memory would require trying to read every single byte,
2007 and it seems unacceptable solution. Explicit memory map is
2008 recommended for this case -- and target_read_memory_robust will
2009 take care of reading multiple ranges then. */
2010
2011 static void
2012 read_whatever_is_readable (struct target_ops *ops,
2013 const ULONGEST begin, const ULONGEST end,
2014 int unit_size,
2015 std::vector<memory_read_result> *result)
2016 {
2017 ULONGEST current_begin = begin;
2018 ULONGEST current_end = end;
2019 int forward;
2020 ULONGEST xfered_len;
2021
2022 /* If we previously failed to read 1 byte, nothing can be done here. */
2023 if (end - begin <= 1)
2024 return;
2025
2026 gdb::unique_xmalloc_ptr<gdb_byte> buf ((gdb_byte *) xmalloc (end - begin));
2027
2028 /* Check that either first or the last byte is readable, and give up
2029 if not. This heuristic is meant to permit reading accessible memory
2030 at the boundary of accessible region. */
2031 if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
2032 buf.get (), begin, 1, &xfered_len) == TARGET_XFER_OK)
2033 {
2034 forward = 1;
2035 ++current_begin;
2036 }
2037 else if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
2038 buf.get () + (end - begin) - 1, end - 1, 1,
2039 &xfered_len) == TARGET_XFER_OK)
2040 {
2041 forward = 0;
2042 --current_end;
2043 }
2044 else
2045 return;
2046
2047 /* Loop invariant is that the [current_begin, current_end) was previously
2048 found to be not readable as a whole.
2049
2050 Note loop condition -- if the range has 1 byte, we can't divide the range
2051 so there's no point trying further. */
2052 while (current_end - current_begin > 1)
2053 {
2054 ULONGEST first_half_begin, first_half_end;
2055 ULONGEST second_half_begin, second_half_end;
2056 LONGEST xfer;
2057 ULONGEST middle = current_begin + (current_end - current_begin) / 2;
2058
2059 if (forward)
2060 {
2061 first_half_begin = current_begin;
2062 first_half_end = middle;
2063 second_half_begin = middle;
2064 second_half_end = current_end;
2065 }
2066 else
2067 {
2068 first_half_begin = middle;
2069 first_half_end = current_end;
2070 second_half_begin = current_begin;
2071 second_half_end = middle;
2072 }
2073
2074 xfer = target_read (ops, TARGET_OBJECT_MEMORY, NULL,
2075 buf.get () + (first_half_begin - begin) * unit_size,
2076 first_half_begin,
2077 first_half_end - first_half_begin);
2078
2079 if (xfer == first_half_end - first_half_begin)
2080 {
2081 /* This half reads up fine. So, the error must be in the
2082 other half. */
2083 current_begin = second_half_begin;
2084 current_end = second_half_end;
2085 }
2086 else
2087 {
2088 /* This half is not readable. Because we've tried one byte, we
2089 know some part of this half if actually readable. Go to the next
2090 iteration to divide again and try to read.
2091
2092 We don't handle the other half, because this function only tries
2093 to read a single readable subrange. */
2094 current_begin = first_half_begin;
2095 current_end = first_half_end;
2096 }
2097 }
2098
2099 if (forward)
2100 {
2101 /* The [begin, current_begin) range has been read. */
2102 result->emplace_back (begin, current_end, std::move (buf));
2103 }
2104 else
2105 {
2106 /* The [current_end, end) range has been read. */
2107 LONGEST region_len = end - current_end;
2108
2109 gdb::unique_xmalloc_ptr<gdb_byte> data
2110 ((gdb_byte *) xmalloc (region_len * unit_size));
2111 memcpy (data.get (), buf.get () + (current_end - begin) * unit_size,
2112 region_len * unit_size);
2113 result->emplace_back (current_end, end, std::move (data));
2114 }
2115 }
2116
2117 std::vector<memory_read_result>
2118 read_memory_robust (struct target_ops *ops,
2119 const ULONGEST offset, const LONGEST len)
2120 {
2121 std::vector<memory_read_result> result;
2122 int unit_size
2123 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
2124
2125 LONGEST xfered_total = 0;
2126 while (xfered_total < len)
2127 {
2128 struct mem_region *region = lookup_mem_region (offset + xfered_total);
2129 LONGEST region_len;
2130
2131 /* If there is no explicit region, a fake one should be created. */
2132 gdb_assert (region);
2133
2134 if (region->hi == 0)
2135 region_len = len - xfered_total;
2136 else
2137 region_len = region->hi - offset;
2138
2139 if (region->attrib.mode == MEM_NONE || region->attrib.mode == MEM_WO)
2140 {
2141 /* Cannot read this region. Note that we can end up here only
2142 if the region is explicitly marked inaccessible, or
2143 'inaccessible-by-default' is in effect. */
2144 xfered_total += region_len;
2145 }
2146 else
2147 {
2148 LONGEST to_read = std::min (len - xfered_total, region_len);
2149 gdb::unique_xmalloc_ptr<gdb_byte> buffer
2150 ((gdb_byte *) xmalloc (to_read * unit_size));
2151
2152 LONGEST xfered_partial =
2153 target_read (ops, TARGET_OBJECT_MEMORY, NULL, buffer.get (),
2154 offset + xfered_total, to_read);
2155 /* Call an observer, notifying them of the xfer progress? */
2156 if (xfered_partial <= 0)
2157 {
2158 /* Got an error reading full chunk. See if maybe we can read
2159 some subrange. */
2160 read_whatever_is_readable (ops, offset + xfered_total,
2161 offset + xfered_total + to_read,
2162 unit_size, &result);
2163 xfered_total += to_read;
2164 }
2165 else
2166 {
2167 result.emplace_back (offset + xfered_total,
2168 offset + xfered_total + xfered_partial,
2169 std::move (buffer));
2170 xfered_total += xfered_partial;
2171 }
2172 QUIT;
2173 }
2174 }
2175
2176 return result;
2177 }
2178
2179
2180 /* An alternative to target_write with progress callbacks. */
2181
2182 LONGEST
2183 target_write_with_progress (struct target_ops *ops,
2184 enum target_object object,
2185 const char *annex, const gdb_byte *buf,
2186 ULONGEST offset, LONGEST len,
2187 void (*progress) (ULONGEST, void *), void *baton)
2188 {
2189 LONGEST xfered_total = 0;
2190 int unit_size = 1;
2191
2192 /* If we are writing to a memory object, find the length of an addressable
2193 unit for that architecture. */
2194 if (object == TARGET_OBJECT_MEMORY
2195 || object == TARGET_OBJECT_STACK_MEMORY
2196 || object == TARGET_OBJECT_CODE_MEMORY
2197 || object == TARGET_OBJECT_RAW_MEMORY)
2198 unit_size = gdbarch_addressable_memory_unit_size
2199 (current_inferior ()->arch ());
2200
2201 /* Give the progress callback a chance to set up. */
2202 if (progress)
2203 (*progress) (0, baton);
2204
2205 while (xfered_total < len)
2206 {
2207 ULONGEST xfered_partial;
2208 enum target_xfer_status status;
2209
2210 status = target_write_partial (ops, object, annex,
2211 buf + xfered_total * unit_size,
2212 offset + xfered_total, len - xfered_total,
2213 &xfered_partial);
2214
2215 if (status != TARGET_XFER_OK)
2216 return status == TARGET_XFER_EOF ? xfered_total : TARGET_XFER_E_IO;
2217
2218 if (progress)
2219 (*progress) (xfered_partial, baton);
2220
2221 xfered_total += xfered_partial;
2222 QUIT;
2223 }
2224 return len;
2225 }
2226
2227 /* For docs on target_write see target.h. */
2228
2229 LONGEST
2230 target_write (struct target_ops *ops,
2231 enum target_object object,
2232 const char *annex, const gdb_byte *buf,
2233 ULONGEST offset, LONGEST len)
2234 {
2235 return target_write_with_progress (ops, object, annex, buf, offset, len,
2236 NULL, NULL);
2237 }
2238
2239 /* Help for target_read_alloc and target_read_stralloc. See their comments
2240 for details. */
2241
2242 template <typename T>
2243 std::optional<gdb::def_vector<T>>
2244 target_read_alloc_1 (struct target_ops *ops, enum target_object object,
2245 const char *annex)
2246 {
2247 gdb::def_vector<T> buf;
2248 size_t buf_pos = 0;
2249 const int chunk = 4096;
2250
2251 /* This function does not have a length parameter; it reads the
2252 entire OBJECT). Also, it doesn't support objects fetched partly
2253 from one target and partly from another (in a different stratum,
2254 e.g. a core file and an executable). Both reasons make it
2255 unsuitable for reading memory. */
2256 gdb_assert (object != TARGET_OBJECT_MEMORY);
2257
2258 /* Start by reading up to 4K at a time. The target will throttle
2259 this number down if necessary. */
2260 while (1)
2261 {
2262 ULONGEST xfered_len;
2263 enum target_xfer_status status;
2264
2265 buf.resize (buf_pos + chunk);
2266
2267 status = target_read_partial (ops, object, annex,
2268 (gdb_byte *) &buf[buf_pos],
2269 buf_pos, chunk,
2270 &xfered_len);
2271
2272 if (status == TARGET_XFER_EOF)
2273 {
2274 /* Read all there was. */
2275 buf.resize (buf_pos);
2276 return buf;
2277 }
2278 else if (status != TARGET_XFER_OK)
2279 {
2280 /* An error occurred. */
2281 return {};
2282 }
2283
2284 buf_pos += xfered_len;
2285
2286 QUIT;
2287 }
2288 }
2289
2290 /* See target.h */
2291
2292 std::optional<gdb::byte_vector>
2293 target_read_alloc (struct target_ops *ops, enum target_object object,
2294 const char *annex)
2295 {
2296 return target_read_alloc_1<gdb_byte> (ops, object, annex);
2297 }
2298
2299 /* See target.h. */
2300
2301 std::optional<gdb::char_vector>
2302 target_read_stralloc (struct target_ops *ops, enum target_object object,
2303 const char *annex)
2304 {
2305 std::optional<gdb::char_vector> buf
2306 = target_read_alloc_1<char> (ops, object, annex);
2307
2308 if (!buf)
2309 return {};
2310
2311 if (buf->empty () || buf->back () != '\0')
2312 buf->push_back ('\0');
2313
2314 /* Check for embedded NUL bytes; but allow trailing NULs. */
2315 for (auto it = std::find (buf->begin (), buf->end (), '\0');
2316 it != buf->end (); it++)
2317 if (*it != '\0')
2318 {
2319 warning (_("target object %d, annex %s, "
2320 "contained unexpected null characters"),
2321 (int) object, annex ? annex : "(none)");
2322 break;
2323 }
2324
2325 return buf;
2326 }
2327
2328 /* Memory transfer methods. */
2329
2330 void
2331 get_target_memory (struct target_ops *ops, CORE_ADDR addr, gdb_byte *buf,
2332 LONGEST len)
2333 {
2334 /* This method is used to read from an alternate, non-current
2335 target. This read must bypass the overlay support (as symbols
2336 don't match this target), and GDB's internal cache (wrong cache
2337 for this target). */
2338 if (target_read (ops, TARGET_OBJECT_RAW_MEMORY, NULL, buf, addr, len)
2339 != len)
2340 memory_error (TARGET_XFER_E_IO, addr);
2341 }
2342
2343 ULONGEST
2344 get_target_memory_unsigned (struct target_ops *ops, CORE_ADDR addr,
2345 int len, enum bfd_endian byte_order)
2346 {
2347 gdb_byte buf[sizeof (ULONGEST)];
2348
2349 gdb_assert (len <= sizeof (buf));
2350 get_target_memory (ops, addr, buf, len);
2351 return extract_unsigned_integer (buf, len, byte_order);
2352 }
2353
2354 /* See target.h. */
2355
2356 int
2357 target_insert_breakpoint (struct gdbarch *gdbarch,
2358 struct bp_target_info *bp_tgt)
2359 {
2360 if (!may_insert_breakpoints)
2361 {
2362 warning (_("May not insert breakpoints"));
2363 return 1;
2364 }
2365
2366 target_ops *target = current_inferior ()->top_target ();
2367
2368 return target->insert_breakpoint (gdbarch, bp_tgt);
2369 }
2370
2371 /* See target.h. */
2372
2373 int
2374 target_remove_breakpoint (struct gdbarch *gdbarch,
2375 struct bp_target_info *bp_tgt,
2376 enum remove_bp_reason reason)
2377 {
2378 /* This is kind of a weird case to handle, but the permission might
2379 have been changed after breakpoints were inserted - in which case
2380 we should just take the user literally and assume that any
2381 breakpoints should be left in place. */
2382 if (!may_insert_breakpoints)
2383 {
2384 warning (_("May not remove breakpoints"));
2385 return 1;
2386 }
2387
2388 target_ops *target = current_inferior ()->top_target ();
2389
2390 return target->remove_breakpoint (gdbarch, bp_tgt, reason);
2391 }
2392
2393 static void
2394 info_target_command (const char *args, int from_tty)
2395 {
2396 int has_all_mem = 0;
2397
2398 if (current_program_space->symfile_object_file != NULL)
2399 {
2400 objfile *objf = current_program_space->symfile_object_file;
2401 gdb_printf (_("Symbols from \"%ps\".\n"),
2402 styled_string (file_name_style.style (),
2403 objfile_name (objf)));
2404 }
2405
2406 for (target_ops *t = current_inferior ()->top_target ();
2407 t != NULL;
2408 t = t->beneath ())
2409 {
2410 if (!t->has_memory ())
2411 continue;
2412
2413 if ((int) (t->stratum ()) <= (int) dummy_stratum)
2414 continue;
2415 if (has_all_mem)
2416 gdb_printf (_("\tWhile running this, "
2417 "GDB does not access memory from...\n"));
2418 gdb_printf ("%s:\n", t->longname ());
2419 t->files_info ();
2420 has_all_mem = t->has_all_memory ();
2421 }
2422 }
2423
2424 /* This function is called before any new inferior is created, e.g.
2425 by running a program, attaching, or connecting to a target.
2426 It cleans up any state from previous invocations which might
2427 change between runs. This is a subset of what target_preopen
2428 resets (things which might change between targets). */
2429
2430 void
2431 target_pre_inferior (int from_tty)
2432 {
2433 /* Clear out solib state. Otherwise the solib state of the previous
2434 inferior might have survived and is entirely wrong for the new
2435 target. This has been observed on GNU/Linux using glibc 2.3. How
2436 to reproduce:
2437
2438 bash$ ./foo&
2439 [1] 4711
2440 bash$ ./foo&
2441 [1] 4712
2442 bash$ gdb ./foo
2443 [...]
2444 (gdb) attach 4711
2445 (gdb) detach
2446 (gdb) attach 4712
2447 Cannot access memory at address 0xdeadbeef
2448 */
2449
2450 /* In some OSs, the shared library list is the same/global/shared
2451 across inferiors. If code is shared between processes, so are
2452 memory regions and features. */
2453 if (!gdbarch_has_global_solist (current_inferior ()->arch ()))
2454 {
2455 no_shared_libraries (NULL, from_tty);
2456
2457 invalidate_target_mem_regions ();
2458
2459 target_clear_description ();
2460 }
2461
2462 /* attach_flag may be set if the previous process associated with
2463 the inferior was attached to. */
2464 current_inferior ()->attach_flag = false;
2465
2466 current_inferior ()->highest_thread_num = 0;
2467
2468 update_previous_thread ();
2469
2470 agent_capability_invalidate ();
2471 }
2472
2473 /* This is to be called by the open routine before it does
2474 anything. */
2475
2476 void
2477 target_preopen (int from_tty)
2478 {
2479 dont_repeat ();
2480
2481 if (current_inferior ()->pid != 0)
2482 {
2483 if (!from_tty
2484 || !target_has_execution ()
2485 || query (_("A program is being debugged already. Kill it? ")))
2486 {
2487 /* Core inferiors actually should be detached, not
2488 killed. */
2489 if (target_has_execution ())
2490 target_kill ();
2491 else
2492 target_detach (current_inferior (), 0);
2493 }
2494 else
2495 error (_("Program not killed."));
2496 }
2497
2498 /* Release reference to old previous thread. */
2499 update_previous_thread ();
2500
2501 /* Calling target_kill may remove the target from the stack. But if
2502 it doesn't (which seems like a win for UDI), remove it now. */
2503 /* Leave the exec target, though. The user may be switching from a
2504 live process to a core of the same program. */
2505 current_inferior ()->pop_all_targets_above (file_stratum);
2506
2507 target_pre_inferior (from_tty);
2508 }
2509
2510 /* See target.h. */
2511
2512 void
2513 target_detach (inferior *inf, int from_tty)
2514 {
2515 /* Thread's don't need to be resumed until the end of this function. */
2516 scoped_disable_commit_resumed disable_commit_resumed ("detaching");
2517
2518 /* After we have detached, we will clear the register cache for this inferior
2519 by calling registers_changed_ptid. We must save the pid_ptid before
2520 detaching, as the target detach method will clear inf->pid. */
2521 ptid_t save_pid_ptid = ptid_t (inf->pid);
2522
2523 /* As long as some to_detach implementations rely on the current_inferior
2524 (either directly, or indirectly, like through reading memory), INF needs
2525 to be the current inferior. When that requirement will become no longer
2526 true, then we can remove this assertion. */
2527 gdb_assert (inf == current_inferior ());
2528
2529 prepare_for_detach ();
2530
2531 gdb::observers::inferior_pre_detach.notify (inf);
2532
2533 /* Hold a strong reference because detaching may unpush the
2534 target. */
2535 auto proc_target_ref = target_ops_ref::new_reference (inf->process_target ());
2536
2537 current_inferior ()->top_target ()->detach (inf, from_tty);
2538
2539 process_stratum_target *proc_target
2540 = as_process_stratum_target (proc_target_ref.get ());
2541
2542 registers_changed_ptid (proc_target, save_pid_ptid);
2543
2544 /* We have to ensure we have no frame cache left. Normally,
2545 registers_changed_ptid (save_pid_ptid) calls reinit_frame_cache when
2546 inferior_ptid matches save_pid_ptid, but in our case, it does not
2547 call it, as inferior_ptid has been reset. */
2548 reinit_frame_cache ();
2549
2550 disable_commit_resumed.reset_and_commit ();
2551 }
2552
2553 void
2554 target_disconnect (const char *args, int from_tty)
2555 {
2556 /* If we're in breakpoints-always-inserted mode or if breakpoints
2557 are global across processes, we have to remove them before
2558 disconnecting. */
2559 remove_breakpoints ();
2560
2561 current_inferior ()->top_target ()->disconnect (args, from_tty);
2562 }
2563
2564 /* See target/target.h. */
2565
2566 ptid_t
2567 target_wait (ptid_t ptid, struct target_waitstatus *status,
2568 target_wait_flags options)
2569 {
2570 target_ops *target = current_inferior ()->top_target ();
2571 process_stratum_target *proc_target = current_inferior ()->process_target ();
2572
2573 gdb_assert (!proc_target->commit_resumed_state);
2574
2575 if (!target_can_async_p (target))
2576 gdb_assert ((options & TARGET_WNOHANG) == 0);
2577
2578 try
2579 {
2580 gdb::observers::target_pre_wait.notify (ptid);
2581 ptid_t event_ptid = target->wait (ptid, status, options);
2582 gdb::observers::target_post_wait.notify (event_ptid);
2583 return event_ptid;
2584 }
2585 catch (...)
2586 {
2587 gdb::observers::target_post_wait.notify (null_ptid);
2588 throw;
2589 }
2590 }
2591
2592 /* See target.h. */
2593
2594 ptid_t
2595 default_target_wait (struct target_ops *ops,
2596 ptid_t ptid, struct target_waitstatus *status,
2597 target_wait_flags options)
2598 {
2599 status->set_ignore ();
2600 return minus_one_ptid;
2601 }
2602
2603 std::string
2604 target_pid_to_str (ptid_t ptid)
2605 {
2606 return current_inferior ()->top_target ()->pid_to_str (ptid);
2607 }
2608
2609 const char *
2610 target_thread_name (struct thread_info *info)
2611 {
2612 gdb_assert (info->inf == current_inferior ());
2613
2614 return current_inferior ()->top_target ()->thread_name (info);
2615 }
2616
2617 struct thread_info *
2618 target_thread_handle_to_thread_info (const gdb_byte *thread_handle,
2619 int handle_len,
2620 struct inferior *inf)
2621 {
2622 target_ops *target = current_inferior ()->top_target ();
2623
2624 return target->thread_handle_to_thread_info (thread_handle, handle_len, inf);
2625 }
2626
2627 /* See target.h. */
2628
2629 gdb::array_view<const gdb_byte>
2630 target_thread_info_to_thread_handle (struct thread_info *tip)
2631 {
2632 target_ops *target = current_inferior ()->top_target ();
2633
2634 return target->thread_info_to_thread_handle (tip);
2635 }
2636
2637 void
2638 target_resume (ptid_t scope_ptid, int step, enum gdb_signal signal)
2639 {
2640 process_stratum_target *curr_target = current_inferior ()->process_target ();
2641 gdb_assert (!curr_target->commit_resumed_state);
2642
2643 gdb_assert (inferior_ptid != null_ptid);
2644 gdb_assert (inferior_ptid.matches (scope_ptid));
2645
2646 target_dcache_invalidate (current_program_space->aspace);
2647
2648 current_inferior ()->top_target ()->resume (scope_ptid, step, signal);
2649
2650 registers_changed_ptid (curr_target, scope_ptid);
2651 /* We only set the internal executing state here. The user/frontend
2652 running state is set at a higher level. This also clears the
2653 thread's stop_pc as side effect. */
2654 set_executing (curr_target, scope_ptid, true);
2655 clear_inline_frame_state (curr_target, scope_ptid);
2656
2657 if (target_can_async_p ())
2658 target_async (true);
2659 }
2660
2661 /* See target.h. */
2662
2663 void
2664 target_commit_resumed ()
2665 {
2666 gdb_assert (current_inferior ()->process_target ()->commit_resumed_state);
2667 current_inferior ()->top_target ()->commit_resumed ();
2668 }
2669
2670 /* See target.h. */
2671
2672 bool
2673 target_has_pending_events ()
2674 {
2675 return current_inferior ()->top_target ()->has_pending_events ();
2676 }
2677
2678 void
2679 target_pass_signals (gdb::array_view<const unsigned char> pass_signals)
2680 {
2681 current_inferior ()->top_target ()->pass_signals (pass_signals);
2682 }
2683
2684 void
2685 target_program_signals (gdb::array_view<const unsigned char> program_signals)
2686 {
2687 current_inferior ()->top_target ()->program_signals (program_signals);
2688 }
2689
2690 static void
2691 default_follow_fork (struct target_ops *self, inferior *child_inf,
2692 ptid_t child_ptid, target_waitkind fork_kind,
2693 bool follow_child, bool detach_fork)
2694 {
2695 /* Some target returned a fork event, but did not know how to follow it. */
2696 internal_error (_("could not find a target to follow fork"));
2697 }
2698
2699 static void
2700 default_follow_clone (struct target_ops *self, ptid_t child_ptid)
2701 {
2702 /* Some target returned a clone event, but did not know how to follow it. */
2703 internal_error (_("could not find a target to follow clone"));
2704 }
2705
2706 /* See target.h. */
2707
2708 void
2709 target_follow_fork (inferior *child_inf, ptid_t child_ptid,
2710 target_waitkind fork_kind, bool follow_child,
2711 bool detach_fork)
2712 {
2713 target_ops *target = current_inferior ()->top_target ();
2714
2715 /* Check consistency between CHILD_INF, CHILD_PTID, FOLLOW_CHILD and
2716 DETACH_FORK. */
2717 if (child_inf != nullptr)
2718 {
2719 gdb_assert (follow_child || !detach_fork);
2720 gdb_assert (child_inf->pid == child_ptid.pid ());
2721 }
2722 else
2723 gdb_assert (!follow_child && detach_fork);
2724
2725 return target->follow_fork (child_inf, child_ptid, fork_kind, follow_child,
2726 detach_fork);
2727 }
2728
2729 /* See target.h. */
2730
2731 void
2732 target_follow_exec (inferior *follow_inf, ptid_t ptid,
2733 const char *execd_pathname)
2734 {
2735 current_inferior ()->top_target ()->follow_exec (follow_inf, ptid,
2736 execd_pathname);
2737 }
2738
2739 static void
2740 default_mourn_inferior (struct target_ops *self)
2741 {
2742 internal_error (_("could not find a target to follow mourn inferior"));
2743 }
2744
2745 void
2746 target_mourn_inferior (ptid_t ptid)
2747 {
2748 gdb_assert (ptid.pid () == inferior_ptid.pid ());
2749 current_inferior ()->top_target ()->mourn_inferior ();
2750 }
2751
2752 /* Look for a target which can describe architectural features, starting
2753 from TARGET. If we find one, return its description. */
2754
2755 const struct target_desc *
2756 target_read_description (struct target_ops *target)
2757 {
2758 return target->read_description ();
2759 }
2760
2761
2762 /* Default implementation of memory-searching. */
2763
2764 static int
2765 default_search_memory (struct target_ops *self,
2766 CORE_ADDR start_addr, ULONGEST search_space_len,
2767 const gdb_byte *pattern, ULONGEST pattern_len,
2768 CORE_ADDR *found_addrp)
2769 {
2770 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
2771 {
2772 return target_read (current_inferior ()->top_target (),
2773 TARGET_OBJECT_MEMORY, NULL,
2774 result, addr, len) == len;
2775 };
2776
2777 /* Start over from the top of the target stack. */
2778 return simple_search_memory (read_memory, start_addr, search_space_len,
2779 pattern, pattern_len, found_addrp);
2780 }
2781
2782 /* Search SEARCH_SPACE_LEN bytes beginning at START_ADDR for the
2783 sequence of bytes in PATTERN with length PATTERN_LEN.
2784
2785 The result is 1 if found, 0 if not found, and -1 if there was an error
2786 requiring halting of the search (e.g. memory read error).
2787 If the pattern is found the address is recorded in FOUND_ADDRP. */
2788
2789 int
2790 target_search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
2791 const gdb_byte *pattern, ULONGEST pattern_len,
2792 CORE_ADDR *found_addrp)
2793 {
2794 target_ops *target = current_inferior ()->top_target ();
2795
2796 return target->search_memory (start_addr, search_space_len, pattern,
2797 pattern_len, found_addrp);
2798 }
2799
2800 /* Look through the currently pushed targets. If none of them will
2801 be able to restart the currently running process, issue an error
2802 message. */
2803
2804 void
2805 target_require_runnable (void)
2806 {
2807 for (target_ops *t = current_inferior ()->top_target ();
2808 t != NULL;
2809 t = t->beneath ())
2810 {
2811 /* If this target knows how to create a new program, then
2812 assume we will still be able to after killing the current
2813 one. Either killing and mourning will not pop T, or else
2814 find_default_run_target will find it again. */
2815 if (t->can_create_inferior ())
2816 return;
2817
2818 /* Do not worry about targets at certain strata that can not
2819 create inferiors. Assume they will be pushed again if
2820 necessary, and continue to the process_stratum. */
2821 if (t->stratum () > process_stratum)
2822 continue;
2823
2824 error (_("The \"%s\" target does not support \"run\". "
2825 "Try \"help target\" or \"continue\"."),
2826 t->shortname ());
2827 }
2828
2829 /* This function is only called if the target is running. In that
2830 case there should have been a process_stratum target and it
2831 should either know how to create inferiors, or not... */
2832 internal_error (_("No targets found"));
2833 }
2834
2835 /* Whether GDB is allowed to fall back to the default run target for
2836 "run", "attach", etc. when no target is connected yet. */
2837 static bool auto_connect_native_target = true;
2838
2839 static void
2840 show_auto_connect_native_target (struct ui_file *file, int from_tty,
2841 struct cmd_list_element *c, const char *value)
2842 {
2843 gdb_printf (file,
2844 _("Whether GDB may automatically connect to the "
2845 "native target is %s.\n"),
2846 value);
2847 }
2848
2849 /* A pointer to the target that can respond to "run" or "attach".
2850 Native targets are always singletons and instantiated early at GDB
2851 startup. */
2852 static target_ops *the_native_target;
2853
2854 /* See target.h. */
2855
2856 void
2857 set_native_target (target_ops *target)
2858 {
2859 if (the_native_target != NULL)
2860 internal_error (_("native target already set (\"%s\")."),
2861 the_native_target->longname ());
2862
2863 the_native_target = target;
2864 }
2865
2866 /* See target.h. */
2867
2868 target_ops *
2869 get_native_target ()
2870 {
2871 return the_native_target;
2872 }
2873
2874 /* Look through the list of possible targets for a target that can
2875 execute a run or attach command without any other data. This is
2876 used to locate the default process stratum.
2877
2878 If DO_MESG is not NULL, the result is always valid (error() is
2879 called for errors); else, return NULL on error. */
2880
2881 static struct target_ops *
2882 find_default_run_target (const char *do_mesg)
2883 {
2884 if (auto_connect_native_target && the_native_target != NULL)
2885 return the_native_target;
2886
2887 if (do_mesg != NULL)
2888 error (_("Don't know how to %s. Try \"help target\"."), do_mesg);
2889 return NULL;
2890 }
2891
2892 /* See target.h. */
2893
2894 struct target_ops *
2895 find_attach_target (void)
2896 {
2897 /* If a target on the current stack can attach, use it. */
2898 for (target_ops *t = current_inferior ()->top_target ();
2899 t != NULL;
2900 t = t->beneath ())
2901 {
2902 if (t->can_attach ())
2903 return t;
2904 }
2905
2906 /* Otherwise, use the default run target for attaching. */
2907 return find_default_run_target ("attach");
2908 }
2909
2910 /* See target.h. */
2911
2912 struct target_ops *
2913 find_run_target (void)
2914 {
2915 /* If a target on the current stack can run, use it. */
2916 for (target_ops *t = current_inferior ()->top_target ();
2917 t != NULL;
2918 t = t->beneath ())
2919 {
2920 if (t->can_create_inferior ())
2921 return t;
2922 }
2923
2924 /* Otherwise, use the default run target. */
2925 return find_default_run_target ("run");
2926 }
2927
2928 bool
2929 target_ops::info_proc (const char *args, enum info_proc_what what)
2930 {
2931 return false;
2932 }
2933
2934 /* Implement the "info proc" command. */
2935
2936 int
2937 target_info_proc (const char *args, enum info_proc_what what)
2938 {
2939 struct target_ops *t;
2940
2941 /* If we're already connected to something that can get us OS
2942 related data, use it. Otherwise, try using the native
2943 target. */
2944 t = find_target_at (process_stratum);
2945 if (t == NULL)
2946 t = find_default_run_target (NULL);
2947
2948 for (; t != NULL; t = t->beneath ())
2949 {
2950 if (t->info_proc (args, what))
2951 {
2952 target_debug_printf_nofunc ("target_info_proc (\"%s\", %d)", args, what);
2953 return 1;
2954 }
2955 }
2956
2957 return 0;
2958 }
2959
2960 static int
2961 find_default_supports_disable_randomization (struct target_ops *self)
2962 {
2963 struct target_ops *t;
2964
2965 t = find_default_run_target (NULL);
2966 if (t != NULL)
2967 return t->supports_disable_randomization ();
2968 return 0;
2969 }
2970
2971 int
2972 target_supports_disable_randomization (void)
2973 {
2974 return current_inferior ()->top_target ()->supports_disable_randomization ();
2975 }
2976
2977 /* See target/target.h. */
2978
2979 int
2980 target_supports_multi_process (void)
2981 {
2982 return current_inferior ()->top_target ()->supports_multi_process ();
2983 }
2984
2985 /* See target.h. */
2986
2987 std::optional<gdb::char_vector>
2988 target_get_osdata (const char *type)
2989 {
2990 struct target_ops *t;
2991
2992 /* If we're already connected to something that can get us OS
2993 related data, use it. Otherwise, try using the native
2994 target. */
2995 t = find_target_at (process_stratum);
2996 if (t == NULL)
2997 t = find_default_run_target ("get OS data");
2998
2999 if (!t)
3000 return {};
3001
3002 return target_read_stralloc (t, TARGET_OBJECT_OSDATA, type);
3003 }
3004
3005 /* See target.h. */
3006
3007 target_ops *
3008 target_ops::beneath () const
3009 {
3010 return current_inferior ()->find_target_beneath (this);
3011 }
3012
3013 void
3014 target_ops::close ()
3015 {
3016 }
3017
3018 bool
3019 target_ops::can_attach ()
3020 {
3021 return 0;
3022 }
3023
3024 void
3025 target_ops::attach (const char *, int)
3026 {
3027 gdb_assert_not_reached ("target_ops::attach called");
3028 }
3029
3030 bool
3031 target_ops::can_create_inferior ()
3032 {
3033 return 0;
3034 }
3035
3036 void
3037 target_ops::create_inferior (const char *, const std::string &,
3038 char **, int)
3039 {
3040 gdb_assert_not_reached ("target_ops::create_inferior called");
3041 }
3042
3043 bool
3044 target_ops::can_run ()
3045 {
3046 return false;
3047 }
3048
3049 int
3050 target_can_run ()
3051 {
3052 for (target_ops *t = current_inferior ()->top_target ();
3053 t != NULL;
3054 t = t->beneath ())
3055 {
3056 if (t->can_run ())
3057 return 1;
3058 }
3059
3060 return 0;
3061 }
3062
3063 /* Target file operations. */
3064
3065 static struct target_ops *
3066 default_fileio_target (void)
3067 {
3068 struct target_ops *t;
3069
3070 /* If we're already connected to something that can perform
3071 file I/O, use it. Otherwise, try using the native target. */
3072 t = find_target_at (process_stratum);
3073 if (t != NULL)
3074 return t;
3075 return find_default_run_target ("file I/O");
3076 }
3077
3078 /* File handle for target file operations. */
3079
3080 struct fileio_fh_t
3081 {
3082 /* The target on which this file is open. NULL if the target is
3083 meanwhile closed while the handle is open. */
3084 target_ops *target;
3085
3086 /* The file descriptor on the target. */
3087 int target_fd;
3088
3089 /* Check whether this fileio_fh_t represents a closed file. */
3090 bool is_closed ()
3091 {
3092 return target_fd < 0;
3093 }
3094 };
3095
3096 /* Vector of currently open file handles. The value returned by
3097 target_fileio_open and passed as the FD argument to other
3098 target_fileio_* functions is an index into this vector. This
3099 vector's entries are never freed; instead, files are marked as
3100 closed, and the handle becomes available for reuse. */
3101 static std::vector<fileio_fh_t> fileio_fhandles;
3102
3103 /* Index into fileio_fhandles of the lowest handle that might be
3104 closed. This permits handle reuse without searching the whole
3105 list each time a new file is opened. */
3106 static int lowest_closed_fd;
3107
3108 /* See target.h. */
3109
3110 void
3111 fileio_handles_invalidate_target (target_ops *targ)
3112 {
3113 for (fileio_fh_t &fh : fileio_fhandles)
3114 if (fh.target == targ)
3115 fh.target = NULL;
3116 }
3117
3118 /* Acquire a target fileio file descriptor. */
3119
3120 static int
3121 acquire_fileio_fd (target_ops *target, int target_fd)
3122 {
3123 /* Search for closed handles to reuse. */
3124 for (; lowest_closed_fd < fileio_fhandles.size (); lowest_closed_fd++)
3125 {
3126 fileio_fh_t &fh = fileio_fhandles[lowest_closed_fd];
3127
3128 if (fh.is_closed ())
3129 break;
3130 }
3131
3132 /* Push a new handle if no closed handles were found. */
3133 if (lowest_closed_fd == fileio_fhandles.size ())
3134 fileio_fhandles.push_back (fileio_fh_t {target, target_fd});
3135 else
3136 fileio_fhandles[lowest_closed_fd] = {target, target_fd};
3137
3138 /* Should no longer be marked closed. */
3139 gdb_assert (!fileio_fhandles[lowest_closed_fd].is_closed ());
3140
3141 /* Return its index, and start the next lookup at
3142 the next index. */
3143 return lowest_closed_fd++;
3144 }
3145
3146 /* Release a target fileio file descriptor. */
3147
3148 static void
3149 release_fileio_fd (int fd, fileio_fh_t *fh)
3150 {
3151 fh->target_fd = -1;
3152 lowest_closed_fd = std::min (lowest_closed_fd, fd);
3153 }
3154
3155 /* Return a pointer to the fileio_fhandle_t corresponding to FD. */
3156
3157 static fileio_fh_t *
3158 fileio_fd_to_fh (int fd)
3159 {
3160 return &fileio_fhandles[fd];
3161 }
3162
3163
3164 /* Default implementations of file i/o methods. We don't want these
3165 to delegate automatically, because we need to know which target
3166 supported the method, in order to call it directly from within
3167 pread/pwrite, etc. */
3168
3169 int
3170 target_ops::fileio_open (struct inferior *inf, const char *filename,
3171 int flags, int mode, int warn_if_slow,
3172 fileio_error *target_errno)
3173 {
3174 *target_errno = FILEIO_ENOSYS;
3175 return -1;
3176 }
3177
3178 int
3179 target_ops::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
3180 ULONGEST offset, fileio_error *target_errno)
3181 {
3182 *target_errno = FILEIO_ENOSYS;
3183 return -1;
3184 }
3185
3186 int
3187 target_ops::fileio_pread (int fd, gdb_byte *read_buf, int len,
3188 ULONGEST offset, fileio_error *target_errno)
3189 {
3190 *target_errno = FILEIO_ENOSYS;
3191 return -1;
3192 }
3193
3194 int
3195 target_ops::fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno)
3196 {
3197 *target_errno = FILEIO_ENOSYS;
3198 return -1;
3199 }
3200
3201 int
3202 target_ops::fileio_close (int fd, fileio_error *target_errno)
3203 {
3204 *target_errno = FILEIO_ENOSYS;
3205 return -1;
3206 }
3207
3208 int
3209 target_ops::fileio_unlink (struct inferior *inf, const char *filename,
3210 fileio_error *target_errno)
3211 {
3212 *target_errno = FILEIO_ENOSYS;
3213 return -1;
3214 }
3215
3216 std::optional<std::string>
3217 target_ops::fileio_readlink (struct inferior *inf, const char *filename,
3218 fileio_error *target_errno)
3219 {
3220 *target_errno = FILEIO_ENOSYS;
3221 return {};
3222 }
3223
3224 /* See target.h. */
3225
3226 int
3227 target_fileio_open (struct inferior *inf, const char *filename,
3228 int flags, int mode, bool warn_if_slow, fileio_error *target_errno)
3229 {
3230 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3231 {
3232 int fd = t->fileio_open (inf, filename, flags, mode,
3233 warn_if_slow, target_errno);
3234
3235 if (fd == -1 && *target_errno == FILEIO_ENOSYS)
3236 continue;
3237
3238 if (fd < 0)
3239 fd = -1;
3240 else
3241 fd = acquire_fileio_fd (t, fd);
3242
3243 target_debug_printf_nofunc ("target_fileio_open (%d,%s,0x%x,0%o,%d) = %d (%d)",
3244 inf == NULL ? 0 : inf->num, filename, flags, mode,
3245 warn_if_slow, fd, fd != -1 ? 0 : *target_errno);
3246 return fd;
3247 }
3248
3249 *target_errno = FILEIO_ENOSYS;
3250 return -1;
3251 }
3252
3253 /* See target.h. */
3254
3255 int
3256 target_fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
3257 ULONGEST offset, fileio_error *target_errno)
3258 {
3259 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3260 int ret = -1;
3261
3262 if (fh->is_closed ())
3263 *target_errno = FILEIO_EBADF;
3264 else if (fh->target == NULL)
3265 *target_errno = FILEIO_EIO;
3266 else
3267 ret = fh->target->fileio_pwrite (fh->target_fd, write_buf,
3268 len, offset, target_errno);
3269
3270 target_debug_printf_nofunc ("target_fileio_pwrite (%d,...,%d,%s) = %d (%d)", fd,
3271 len, pulongest (offset), ret,
3272 ret != -1 ? 0 : *target_errno);
3273 return ret;
3274 }
3275
3276 /* See target.h. */
3277
3278 int
3279 target_fileio_pread (int fd, gdb_byte *read_buf, int len,
3280 ULONGEST offset, fileio_error *target_errno)
3281 {
3282 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3283 int ret = -1;
3284
3285 if (fh->is_closed ())
3286 *target_errno = FILEIO_EBADF;
3287 else if (fh->target == NULL)
3288 *target_errno = FILEIO_EIO;
3289 else
3290 ret = fh->target->fileio_pread (fh->target_fd, read_buf,
3291 len, offset, target_errno);
3292
3293 target_debug_printf_nofunc ("target_fileio_pread (%d,...,%d,%s) = %d (%d)", fd, len,
3294 pulongest (offset), ret, ret != -1 ? 0 : *target_errno);
3295 return ret;
3296 }
3297
3298 /* See target.h. */
3299
3300 int
3301 target_fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno)
3302 {
3303 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3304 int ret = -1;
3305
3306 if (fh->is_closed ())
3307 *target_errno = FILEIO_EBADF;
3308 else if (fh->target == NULL)
3309 *target_errno = FILEIO_EIO;
3310 else
3311 ret = fh->target->fileio_fstat (fh->target_fd, sb, target_errno);
3312
3313 target_debug_printf_nofunc ("target_fileio_fstat (%d) = %d (%d)", fd, ret,
3314 ret != -1 ? 0 : *target_errno);
3315 return ret;
3316 }
3317
3318 /* See target.h. */
3319
3320 int
3321 target_fileio_close (int fd, fileio_error *target_errno)
3322 {
3323 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3324 int ret = -1;
3325
3326 if (fh->is_closed ())
3327 *target_errno = FILEIO_EBADF;
3328 else
3329 {
3330 if (fh->target != NULL)
3331 ret = fh->target->fileio_close (fh->target_fd,
3332 target_errno);
3333 else
3334 ret = 0;
3335 release_fileio_fd (fd, fh);
3336 }
3337
3338 target_debug_printf_nofunc ("target_fileio_close (%d) = %d (%d)", fd, ret,
3339 ret != -1 ? 0 : *target_errno);
3340 return ret;
3341 }
3342
3343 /* See target.h. */
3344
3345 int
3346 target_fileio_unlink (struct inferior *inf, const char *filename,
3347 fileio_error *target_errno)
3348 {
3349 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3350 {
3351 int ret = t->fileio_unlink (inf, filename, target_errno);
3352
3353 if (ret == -1 && *target_errno == FILEIO_ENOSYS)
3354 continue;
3355
3356 target_debug_printf_nofunc ("target_fileio_unlink (%d,%s) = %d (%d)",
3357 inf == NULL ? 0 : inf->num, filename, ret,
3358 ret != -1 ? 0 : *target_errno);
3359 return ret;
3360 }
3361
3362 *target_errno = FILEIO_ENOSYS;
3363 return -1;
3364 }
3365
3366 /* See target.h. */
3367
3368 std::optional<std::string>
3369 target_fileio_readlink (struct inferior *inf, const char *filename,
3370 fileio_error *target_errno)
3371 {
3372 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3373 {
3374 std::optional<std::string> ret
3375 = t->fileio_readlink (inf, filename, target_errno);
3376
3377 if (!ret.has_value () && *target_errno == FILEIO_ENOSYS)
3378 continue;
3379
3380 target_debug_printf_nofunc ("target_fileio_readlink (%d,%s) = %s (%d)",
3381 inf == NULL ? 0 : inf->num, filename,
3382 ret ? ret->c_str () : "(nil)",
3383 ret ? 0 : *target_errno);
3384 return ret;
3385 }
3386
3387 *target_errno = FILEIO_ENOSYS;
3388 return {};
3389 }
3390
3391 /* Like scoped_fd, but specific to target fileio. */
3392
3393 class scoped_target_fd
3394 {
3395 public:
3396 explicit scoped_target_fd (int fd) noexcept
3397 : m_fd (fd)
3398 {
3399 }
3400
3401 ~scoped_target_fd ()
3402 {
3403 if (m_fd >= 0)
3404 {
3405 fileio_error target_errno;
3406
3407 target_fileio_close (m_fd, &target_errno);
3408 }
3409 }
3410
3411 DISABLE_COPY_AND_ASSIGN (scoped_target_fd);
3412
3413 int get () const noexcept
3414 {
3415 return m_fd;
3416 }
3417
3418 private:
3419 int m_fd;
3420 };
3421
3422 /* Read target file FILENAME, in the filesystem as seen by INF. If
3423 INF is NULL, use the filesystem seen by the debugger (GDB or, for
3424 remote targets, the remote stub). Store the result in *BUF_P and
3425 return the size of the transferred data. PADDING additional bytes
3426 are available in *BUF_P. This is a helper function for
3427 target_fileio_read_alloc; see the declaration of that function for
3428 more information. */
3429
3430 static LONGEST
3431 target_fileio_read_alloc_1 (struct inferior *inf, const char *filename,
3432 gdb_byte **buf_p, int padding)
3433 {
3434 size_t buf_alloc, buf_pos;
3435 gdb_byte *buf;
3436 LONGEST n;
3437 fileio_error target_errno;
3438
3439 scoped_target_fd fd (target_fileio_open (inf, filename, FILEIO_O_RDONLY,
3440 0700, false, &target_errno));
3441 if (fd.get () == -1)
3442 return -1;
3443
3444 /* Start by reading up to 4K at a time. The target will throttle
3445 this number down if necessary. */
3446 buf_alloc = 4096;
3447 buf = (gdb_byte *) xmalloc (buf_alloc);
3448 buf_pos = 0;
3449 while (1)
3450 {
3451 n = target_fileio_pread (fd.get (), &buf[buf_pos],
3452 buf_alloc - buf_pos - padding, buf_pos,
3453 &target_errno);
3454 if (n < 0)
3455 {
3456 /* An error occurred. */
3457 xfree (buf);
3458 return -1;
3459 }
3460 else if (n == 0)
3461 {
3462 /* Read all there was. */
3463 if (buf_pos == 0)
3464 xfree (buf);
3465 else
3466 *buf_p = buf;
3467 return buf_pos;
3468 }
3469
3470 buf_pos += n;
3471
3472 /* If the buffer is filling up, expand it. */
3473 if (buf_alloc < buf_pos * 2)
3474 {
3475 buf_alloc *= 2;
3476 buf = (gdb_byte *) xrealloc (buf, buf_alloc);
3477 }
3478
3479 QUIT;
3480 }
3481 }
3482
3483 /* See target.h. */
3484
3485 LONGEST
3486 target_fileio_read_alloc (struct inferior *inf, const char *filename,
3487 gdb_byte **buf_p)
3488 {
3489 return target_fileio_read_alloc_1 (inf, filename, buf_p, 0);
3490 }
3491
3492 /* See target.h. */
3493
3494 gdb::unique_xmalloc_ptr<char>
3495 target_fileio_read_stralloc (struct inferior *inf, const char *filename)
3496 {
3497 gdb_byte *buffer;
3498 char *bufstr;
3499 LONGEST i, transferred;
3500
3501 transferred = target_fileio_read_alloc_1 (inf, filename, &buffer, 1);
3502 bufstr = (char *) buffer;
3503
3504 if (transferred < 0)
3505 return gdb::unique_xmalloc_ptr<char> (nullptr);
3506
3507 if (transferred == 0)
3508 return make_unique_xstrdup ("");
3509
3510 bufstr[transferred] = 0;
3511
3512 /* Check for embedded NUL bytes; but allow trailing NULs. */
3513 for (i = strlen (bufstr); i < transferred; i++)
3514 if (bufstr[i] != 0)
3515 {
3516 warning (_("target file %s "
3517 "contained unexpected null characters"),
3518 filename);
3519 break;
3520 }
3521
3522 return gdb::unique_xmalloc_ptr<char> (bufstr);
3523 }
3524
3525
3526 static int
3527 default_region_ok_for_hw_watchpoint (struct target_ops *self,
3528 CORE_ADDR addr, int len)
3529 {
3530 gdbarch *arch = current_inferior ()->arch ();
3531 return (len <= gdbarch_ptr_bit (arch) / TARGET_CHAR_BIT);
3532 }
3533
3534 static int
3535 default_watchpoint_addr_within_range (struct target_ops *target,
3536 CORE_ADDR addr,
3537 CORE_ADDR start, int length)
3538 {
3539 return addr >= start && addr < start + length;
3540 }
3541
3542 /* See target.h. */
3543
3544 target_ops *
3545 target_stack::find_beneath (const target_ops *t) const
3546 {
3547 /* Look for a non-empty slot at stratum levels beneath T's. */
3548 for (int stratum = t->stratum () - 1; stratum >= 0; --stratum)
3549 if (m_stack[stratum].get () != NULL)
3550 return m_stack[stratum].get ();
3551
3552 return NULL;
3553 }
3554
3555 /* See target.h. */
3556
3557 struct target_ops *
3558 find_target_at (enum strata stratum)
3559 {
3560 return current_inferior ()->target_at (stratum);
3561 }
3562
3563 \f
3564
3565 /* See target.h */
3566
3567 void
3568 target_announce_detach (int from_tty)
3569 {
3570 pid_t pid;
3571 const char *exec_file;
3572
3573 if (!from_tty)
3574 return;
3575
3576 pid = inferior_ptid.pid ();
3577 exec_file = get_exec_file (0);
3578 if (exec_file == nullptr)
3579 gdb_printf ("Detaching from pid %s\n",
3580 target_pid_to_str (ptid_t (pid)).c_str ());
3581 else
3582 gdb_printf (_("Detaching from program: %ps, %s\n"),
3583 styled_string (file_name_style.style (), exec_file),
3584 target_pid_to_str (ptid_t (pid)).c_str ());
3585 }
3586
3587 /* See target.h */
3588
3589 void
3590 target_announce_attach (int from_tty, int pid)
3591 {
3592 if (!from_tty)
3593 return;
3594
3595 const char *exec_file = get_exec_file (0);
3596
3597 if (exec_file != nullptr)
3598 gdb_printf ("Attaching to program: %ps, %s\n",
3599 styled_string (file_name_style.style (), exec_file),
3600 target_pid_to_str (ptid_t (pid)).c_str ());
3601 else
3602 gdb_printf ("Attaching to %s\n",
3603 target_pid_to_str (ptid_t (pid)).c_str ());
3604 }
3605
3606 /* The inferior process has died. Long live the inferior! */
3607
3608 void
3609 generic_mourn_inferior (void)
3610 {
3611 inferior *inf = current_inferior ();
3612
3613 switch_to_no_thread ();
3614
3615 /* Mark breakpoints uninserted in case something tries to delete a
3616 breakpoint while we delete the inferior's threads (which would
3617 fail, since the inferior is long gone). */
3618 mark_breakpoints_out (inf->pspace);
3619
3620 if (inf->pid != 0)
3621 exit_inferior (inf);
3622
3623 /* Note this wipes step-resume breakpoints, so needs to be done
3624 after exit_inferior, which ends up referencing the step-resume
3625 breakpoints through clear_thread_inferior_resources. */
3626 breakpoint_init_inferior (inf, inf_exited);
3627
3628 registers_changed ();
3629
3630 reopen_exec_file ();
3631 reinit_frame_cache ();
3632
3633 if (deprecated_detach_hook)
3634 deprecated_detach_hook ();
3635 }
3636 \f
3637 /* Convert a normal process ID to a string. Returns the string in a
3638 static buffer. */
3639
3640 std::string
3641 normal_pid_to_str (ptid_t ptid)
3642 {
3643 return string_printf ("process %d", ptid.pid ());
3644 }
3645
3646 static std::string
3647 default_pid_to_str (struct target_ops *ops, ptid_t ptid)
3648 {
3649 return normal_pid_to_str (ptid);
3650 }
3651
3652 /* Error-catcher for target_find_memory_regions. */
3653 static int
3654 dummy_find_memory_regions (struct target_ops *self,
3655 find_memory_region_ftype ignore1, void *ignore2)
3656 {
3657 error (_("Command not implemented for this target."));
3658 return 0;
3659 }
3660
3661 /* Error-catcher for target_make_corefile_notes. */
3662 static gdb::unique_xmalloc_ptr<char>
3663 dummy_make_corefile_notes (struct target_ops *self,
3664 bfd *ignore1, int *ignore2)
3665 {
3666 error (_("Command not implemented for this target."));
3667 return NULL;
3668 }
3669
3670 #include "target-delegates.c"
3671
3672 /* The initial current target, so that there is always a semi-valid
3673 current target. */
3674
3675 static dummy_target the_dummy_target;
3676
3677 /* See target.h. */
3678
3679 target_ops *
3680 get_dummy_target ()
3681 {
3682 return &the_dummy_target;
3683 }
3684
3685 static const target_info dummy_target_info = {
3686 "None",
3687 N_("None"),
3688 ""
3689 };
3690
3691 strata
3692 dummy_target::stratum () const
3693 {
3694 return dummy_stratum;
3695 }
3696
3697 strata
3698 debug_target::stratum () const
3699 {
3700 return debug_stratum;
3701 }
3702
3703 const target_info &
3704 dummy_target::info () const
3705 {
3706 return dummy_target_info;
3707 }
3708
3709 const target_info &
3710 debug_target::info () const
3711 {
3712 return beneath ()->info ();
3713 }
3714
3715 \f
3716
3717 int
3718 target_thread_alive (ptid_t ptid)
3719 {
3720 return current_inferior ()->top_target ()->thread_alive (ptid);
3721 }
3722
3723 void
3724 target_update_thread_list (void)
3725 {
3726 current_inferior ()->top_target ()->update_thread_list ();
3727 }
3728
3729 void
3730 target_stop (ptid_t ptid)
3731 {
3732 process_stratum_target *proc_target = current_inferior ()->process_target ();
3733
3734 gdb_assert (!proc_target->commit_resumed_state);
3735
3736 if (!may_stop)
3737 {
3738 warning (_("May not interrupt or stop the target, ignoring attempt"));
3739 return;
3740 }
3741
3742 current_inferior ()->top_target ()->stop (ptid);
3743 }
3744
3745 void
3746 target_interrupt ()
3747 {
3748 if (!may_stop)
3749 {
3750 warning (_("May not interrupt or stop the target, ignoring attempt"));
3751 return;
3752 }
3753
3754 current_inferior ()->top_target ()->interrupt ();
3755 }
3756
3757 /* See target.h. */
3758
3759 void
3760 target_pass_ctrlc (void)
3761 {
3762 /* Pass the Ctrl-C to the first target that has a thread
3763 running. */
3764 for (inferior *inf : all_inferiors ())
3765 {
3766 target_ops *proc_target = inf->process_target ();
3767 if (proc_target == NULL)
3768 continue;
3769
3770 for (thread_info *thr : inf->non_exited_threads ())
3771 {
3772 /* A thread can be THREAD_STOPPED and executing, while
3773 running an infcall. */
3774 if (thr->state == THREAD_RUNNING || thr->executing ())
3775 {
3776 /* We can get here quite deep in target layers. Avoid
3777 switching thread context or anything that would
3778 communicate with the target (e.g., to fetch
3779 registers), or flushing e.g., the frame cache. We
3780 just switch inferior in order to be able to call
3781 through the target_stack. */
3782 scoped_restore_current_inferior restore_inferior;
3783 set_current_inferior (inf);
3784 current_inferior ()->top_target ()->pass_ctrlc ();
3785 return;
3786 }
3787 }
3788 }
3789 }
3790
3791 /* See target.h. */
3792
3793 void
3794 default_target_pass_ctrlc (struct target_ops *ops)
3795 {
3796 target_interrupt ();
3797 }
3798
3799 /* See target/target.h. */
3800
3801 void
3802 target_stop_and_wait (ptid_t ptid)
3803 {
3804 struct target_waitstatus status;
3805 bool was_non_stop = non_stop;
3806
3807 non_stop = true;
3808 target_stop (ptid);
3809
3810 target_wait (ptid, &status, 0);
3811
3812 non_stop = was_non_stop;
3813 }
3814
3815 /* See target/target.h. */
3816
3817 void
3818 target_continue_no_signal (ptid_t ptid)
3819 {
3820 target_resume (ptid, 0, GDB_SIGNAL_0);
3821 }
3822
3823 /* See target/target.h. */
3824
3825 void
3826 target_continue (ptid_t ptid, enum gdb_signal signal)
3827 {
3828 target_resume (ptid, 0, signal);
3829 }
3830
3831 /* Concatenate ELEM to LIST, a comma-separated list. */
3832
3833 static void
3834 str_comma_list_concat_elem (std::string *list, const char *elem)
3835 {
3836 if (!list->empty ())
3837 list->append (", ");
3838
3839 list->append (elem);
3840 }
3841
3842 /* Helper for target_options_to_string. If OPT is present in
3843 TARGET_OPTIONS, append the OPT_STR (string version of OPT) in RET.
3844 OPT is removed from TARGET_OPTIONS. */
3845
3846 static void
3847 do_option (target_wait_flags *target_options, std::string *ret,
3848 target_wait_flag opt, const char *opt_str)
3849 {
3850 if ((*target_options & opt) != 0)
3851 {
3852 str_comma_list_concat_elem (ret, opt_str);
3853 *target_options &= ~opt;
3854 }
3855 }
3856
3857 /* See target.h. */
3858
3859 std::string
3860 target_options_to_string (target_wait_flags target_options)
3861 {
3862 std::string ret;
3863
3864 #define DO_TARG_OPTION(OPT) \
3865 do_option (&target_options, &ret, OPT, #OPT)
3866
3867 DO_TARG_OPTION (TARGET_WNOHANG);
3868
3869 if (target_options != 0)
3870 str_comma_list_concat_elem (&ret, "unknown???");
3871
3872 return ret;
3873 }
3874
3875 void
3876 target_fetch_registers (struct regcache *regcache, int regno)
3877 {
3878 current_inferior ()->top_target ()->fetch_registers (regcache, regno);
3879 target_debug_printf ("%s", regcache->register_debug_string (regno).c_str ());
3880 }
3881
3882 void
3883 target_store_registers (struct regcache *regcache, int regno)
3884 {
3885 if (!may_write_registers)
3886 error (_("Writing to registers is not allowed (regno %d)"), regno);
3887
3888 current_inferior ()->top_target ()->store_registers (regcache, regno);
3889 target_debug_printf ("%s", regcache->register_debug_string (regno).c_str ());
3890 }
3891
3892 int
3893 target_core_of_thread (ptid_t ptid)
3894 {
3895 return current_inferior ()->top_target ()->core_of_thread (ptid);
3896 }
3897
3898 int
3899 simple_verify_memory (struct target_ops *ops,
3900 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
3901 {
3902 LONGEST total_xfered = 0;
3903
3904 while (total_xfered < size)
3905 {
3906 ULONGEST xfered_len;
3907 enum target_xfer_status status;
3908 gdb_byte buf[1024];
3909 ULONGEST howmuch = std::min<ULONGEST> (sizeof (buf), size - total_xfered);
3910
3911 status = target_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
3912 buf, NULL, lma + total_xfered, howmuch,
3913 &xfered_len);
3914 if (status == TARGET_XFER_OK
3915 && memcmp (data + total_xfered, buf, xfered_len) == 0)
3916 {
3917 total_xfered += xfered_len;
3918 QUIT;
3919 }
3920 else
3921 return 0;
3922 }
3923 return 1;
3924 }
3925
3926 /* Default implementation of memory verification. */
3927
3928 static int
3929 default_verify_memory (struct target_ops *self,
3930 const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
3931 {
3932 /* Start over from the top of the target stack. */
3933 return simple_verify_memory (current_inferior ()->top_target (),
3934 data, memaddr, size);
3935 }
3936
3937 int
3938 target_verify_memory (const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
3939 {
3940 target_ops *target = current_inferior ()->top_target ();
3941
3942 return target->verify_memory (data, memaddr, size);
3943 }
3944
3945 /* The documentation for this function is in its prototype declaration in
3946 target.h. */
3947
3948 int
3949 target_insert_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
3950 enum target_hw_bp_type rw)
3951 {
3952 target_ops *target = current_inferior ()->top_target ();
3953
3954 return target->insert_mask_watchpoint (addr, mask, rw);
3955 }
3956
3957 /* The documentation for this function is in its prototype declaration in
3958 target.h. */
3959
3960 int
3961 target_remove_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
3962 enum target_hw_bp_type rw)
3963 {
3964 target_ops *target = current_inferior ()->top_target ();
3965
3966 return target->remove_mask_watchpoint (addr, mask, rw);
3967 }
3968
3969 /* The documentation for this function is in its prototype declaration
3970 in target.h. */
3971
3972 int
3973 target_masked_watch_num_registers (CORE_ADDR addr, CORE_ADDR mask)
3974 {
3975 target_ops *target = current_inferior ()->top_target ();
3976
3977 return target->masked_watch_num_registers (addr, mask);
3978 }
3979
3980 /* The documentation for this function is in its prototype declaration
3981 in target.h. */
3982
3983 int
3984 target_ranged_break_num_registers (void)
3985 {
3986 return current_inferior ()->top_target ()->ranged_break_num_registers ();
3987 }
3988
3989 /* See target.h. */
3990
3991 struct btrace_target_info *
3992 target_enable_btrace (thread_info *tp, const struct btrace_config *conf)
3993 {
3994 return current_inferior ()->top_target ()->enable_btrace (tp, conf);
3995 }
3996
3997 /* See target.h. */
3998
3999 void
4000 target_disable_btrace (struct btrace_target_info *btinfo)
4001 {
4002 current_inferior ()->top_target ()->disable_btrace (btinfo);
4003 }
4004
4005 /* See target.h. */
4006
4007 void
4008 target_teardown_btrace (struct btrace_target_info *btinfo)
4009 {
4010 current_inferior ()->top_target ()->teardown_btrace (btinfo);
4011 }
4012
4013 /* See target.h. */
4014
4015 enum btrace_error
4016 target_read_btrace (struct btrace_data *btrace,
4017 struct btrace_target_info *btinfo,
4018 enum btrace_read_type type)
4019 {
4020 target_ops *target = current_inferior ()->top_target ();
4021
4022 return target->read_btrace (btrace, btinfo, type);
4023 }
4024
4025 /* See target.h. */
4026
4027 const struct btrace_config *
4028 target_btrace_conf (const struct btrace_target_info *btinfo)
4029 {
4030 return current_inferior ()->top_target ()->btrace_conf (btinfo);
4031 }
4032
4033 /* See target.h. */
4034
4035 void
4036 target_stop_recording (void)
4037 {
4038 current_inferior ()->top_target ()->stop_recording ();
4039 }
4040
4041 /* See target.h. */
4042
4043 void
4044 target_save_record (const char *filename)
4045 {
4046 current_inferior ()->top_target ()->save_record (filename);
4047 }
4048
4049 /* See target.h. */
4050
4051 int
4052 target_supports_delete_record ()
4053 {
4054 return current_inferior ()->top_target ()->supports_delete_record ();
4055 }
4056
4057 /* See target.h. */
4058
4059 void
4060 target_delete_record (void)
4061 {
4062 current_inferior ()->top_target ()->delete_record ();
4063 }
4064
4065 /* See target.h. */
4066
4067 enum record_method
4068 target_record_method (ptid_t ptid)
4069 {
4070 return current_inferior ()->top_target ()->record_method (ptid);
4071 }
4072
4073 /* See target.h. */
4074
4075 int
4076 target_record_is_replaying (ptid_t ptid)
4077 {
4078 return current_inferior ()->top_target ()->record_is_replaying (ptid);
4079 }
4080
4081 /* See target.h. */
4082
4083 int
4084 target_record_will_replay (ptid_t ptid, int dir)
4085 {
4086 return current_inferior ()->top_target ()->record_will_replay (ptid, dir);
4087 }
4088
4089 /* See target.h. */
4090
4091 void
4092 target_record_stop_replaying (void)
4093 {
4094 current_inferior ()->top_target ()->record_stop_replaying ();
4095 }
4096
4097 /* See target.h. */
4098
4099 void
4100 target_goto_record_begin (void)
4101 {
4102 current_inferior ()->top_target ()->goto_record_begin ();
4103 }
4104
4105 /* See target.h. */
4106
4107 void
4108 target_goto_record_end (void)
4109 {
4110 current_inferior ()->top_target ()->goto_record_end ();
4111 }
4112
4113 /* See target.h. */
4114
4115 void
4116 target_goto_record (ULONGEST insn)
4117 {
4118 current_inferior ()->top_target ()->goto_record (insn);
4119 }
4120
4121 /* See target.h. */
4122
4123 void
4124 target_insn_history (int size, gdb_disassembly_flags flags)
4125 {
4126 current_inferior ()->top_target ()->insn_history (size, flags);
4127 }
4128
4129 /* See target.h. */
4130
4131 void
4132 target_insn_history_from (ULONGEST from, int size,
4133 gdb_disassembly_flags flags)
4134 {
4135 current_inferior ()->top_target ()->insn_history_from (from, size, flags);
4136 }
4137
4138 /* See target.h. */
4139
4140 void
4141 target_insn_history_range (ULONGEST begin, ULONGEST end,
4142 gdb_disassembly_flags flags)
4143 {
4144 current_inferior ()->top_target ()->insn_history_range (begin, end, flags);
4145 }
4146
4147 /* See target.h. */
4148
4149 void
4150 target_call_history (int size, record_print_flags flags)
4151 {
4152 current_inferior ()->top_target ()->call_history (size, flags);
4153 }
4154
4155 /* See target.h. */
4156
4157 void
4158 target_call_history_from (ULONGEST begin, int size, record_print_flags flags)
4159 {
4160 current_inferior ()->top_target ()->call_history_from (begin, size, flags);
4161 }
4162
4163 /* See target.h. */
4164
4165 void
4166 target_call_history_range (ULONGEST begin, ULONGEST end, record_print_flags flags)
4167 {
4168 current_inferior ()->top_target ()->call_history_range (begin, end, flags);
4169 }
4170
4171 /* See target.h. */
4172
4173 const struct frame_unwind *
4174 target_get_unwinder (void)
4175 {
4176 return current_inferior ()->top_target ()->get_unwinder ();
4177 }
4178
4179 /* See target.h. */
4180
4181 const struct frame_unwind *
4182 target_get_tailcall_unwinder (void)
4183 {
4184 return current_inferior ()->top_target ()->get_tailcall_unwinder ();
4185 }
4186
4187 /* See target.h. */
4188
4189 void
4190 target_prepare_to_generate_core (void)
4191 {
4192 current_inferior ()->top_target ()->prepare_to_generate_core ();
4193 }
4194
4195 /* See target.h. */
4196
4197 void
4198 target_done_generating_core (void)
4199 {
4200 current_inferior ()->top_target ()->done_generating_core ();
4201 }
4202
4203 \f
4204
4205 static char targ_desc[] =
4206 "Names of targets and files being debugged.\nShows the entire \
4207 stack of targets currently in use (including the exec-file,\n\
4208 core-file, and process, if any), as well as the symbol file name.";
4209
4210 static void
4211 default_rcmd (struct target_ops *self, const char *command,
4212 struct ui_file *output)
4213 {
4214 error (_("\"monitor\" command not supported by this target."));
4215 }
4216
4217 static void
4218 do_monitor_command (const char *cmd, int from_tty)
4219 {
4220 target_rcmd (cmd, gdb_stdtarg);
4221 }
4222
4223 /* Erases all the memory regions marked as flash. CMD and FROM_TTY are
4224 ignored. */
4225
4226 void
4227 flash_erase_command (const char *cmd, int from_tty)
4228 {
4229 /* Used to communicate termination of flash operations to the target. */
4230 bool found_flash_region = false;
4231 gdbarch *gdbarch = current_inferior ()->arch ();
4232
4233 std::vector<mem_region> mem_regions = target_memory_map ();
4234
4235 /* Iterate over all memory regions. */
4236 for (const mem_region &m : mem_regions)
4237 {
4238 /* Is this a flash memory region? */
4239 if (m.attrib.mode == MEM_FLASH)
4240 {
4241 found_flash_region = true;
4242 target_flash_erase (m.lo, m.hi - m.lo);
4243
4244 ui_out_emit_tuple tuple_emitter (current_uiout, "erased-regions");
4245
4246 current_uiout->message (_("Erasing flash memory region at address "));
4247 current_uiout->field_core_addr ("address", gdbarch, m.lo);
4248 current_uiout->message (", size = ");
4249 current_uiout->field_string ("size", hex_string (m.hi - m.lo));
4250 current_uiout->message ("\n");
4251 }
4252 }
4253
4254 /* Did we do any flash operations? If so, we need to finalize them. */
4255 if (found_flash_region)
4256 target_flash_done ();
4257 else
4258 current_uiout->message (_("No flash memory regions found.\n"));
4259 }
4260
4261 /* Print the name of each layers of our target stack. */
4262
4263 static void
4264 maintenance_print_target_stack (const char *cmd, int from_tty)
4265 {
4266 gdb_printf (_("The current target stack is:\n"));
4267
4268 for (target_ops *t = current_inferior ()->top_target ();
4269 t != NULL;
4270 t = t->beneath ())
4271 {
4272 if (t->stratum () == debug_stratum)
4273 continue;
4274 gdb_printf (" - %s (%s)\n", t->shortname (), t->longname ());
4275 }
4276 }
4277
4278 /* See target.h. */
4279
4280 void
4281 target_async (bool enable)
4282 {
4283 /* If we are trying to enable async mode then it must be the case that
4284 async mode is possible for this target. */
4285 gdb_assert (!enable || target_can_async_p ());
4286 infrun_async (enable);
4287 current_inferior ()->top_target ()->async (enable);
4288 }
4289
4290 /* See target.h. */
4291
4292 void
4293 target_thread_events (bool enable)
4294 {
4295 current_inferior ()->top_target ()->thread_events (enable);
4296 }
4297
4298 /* See target.h. */
4299
4300 bool
4301 target_supports_set_thread_options (gdb_thread_options options)
4302 {
4303 inferior *inf = current_inferior ();
4304 return inf->top_target ()->supports_set_thread_options (options);
4305 }
4306
4307 /* Controls if targets can report that they can/are async. This is
4308 just for maintainers to use when debugging gdb. */
4309 bool target_async_permitted = true;
4310
4311 static void
4312 set_maint_target_async (bool permitted)
4313 {
4314 if (have_live_inferiors ())
4315 error (_("Cannot change this setting while the inferior is running."));
4316
4317 target_async_permitted = permitted;
4318 }
4319
4320 static bool
4321 get_maint_target_async ()
4322 {
4323 return target_async_permitted;
4324 }
4325
4326 static void
4327 show_maint_target_async (ui_file *file, int from_tty,
4328 cmd_list_element *c, const char *value)
4329 {
4330 gdb_printf (file,
4331 _("Controlling the inferior in "
4332 "asynchronous mode is %s.\n"), value);
4333 }
4334
4335 /* Return true if the target operates in non-stop mode even with "set
4336 non-stop off". */
4337
4338 static int
4339 target_always_non_stop_p (void)
4340 {
4341 return current_inferior ()->top_target ()->always_non_stop_p ();
4342 }
4343
4344 /* See target.h. */
4345
4346 bool
4347 target_is_non_stop_p ()
4348 {
4349 return ((non_stop
4350 || target_non_stop_enabled == AUTO_BOOLEAN_TRUE
4351 || (target_non_stop_enabled == AUTO_BOOLEAN_AUTO
4352 && target_always_non_stop_p ()))
4353 && target_can_async_p ());
4354 }
4355
4356 /* See target.h. */
4357
4358 bool
4359 exists_non_stop_target ()
4360 {
4361 if (target_is_non_stop_p ())
4362 return true;
4363
4364 scoped_restore_current_thread restore_thread;
4365
4366 for (inferior *inf : all_inferiors ())
4367 {
4368 switch_to_inferior_no_thread (inf);
4369 if (target_is_non_stop_p ())
4370 return true;
4371 }
4372
4373 return false;
4374 }
4375
4376 /* Controls if targets can report that they always run in non-stop
4377 mode. This is just for maintainers to use when debugging gdb. */
4378 enum auto_boolean target_non_stop_enabled = AUTO_BOOLEAN_AUTO;
4379
4380 /* Set callback for maint target-non-stop setting. */
4381
4382 static void
4383 set_maint_target_non_stop (auto_boolean enabled)
4384 {
4385 if (have_live_inferiors ())
4386 error (_("Cannot change this setting while the inferior is running."));
4387
4388 target_non_stop_enabled = enabled;
4389 }
4390
4391 /* Get callback for maint target-non-stop setting. */
4392
4393 static auto_boolean
4394 get_maint_target_non_stop ()
4395 {
4396 return target_non_stop_enabled;
4397 }
4398
4399 static void
4400 show_maint_target_non_stop (ui_file *file, int from_tty,
4401 cmd_list_element *c, const char *value)
4402 {
4403 if (target_non_stop_enabled == AUTO_BOOLEAN_AUTO)
4404 gdb_printf (file,
4405 _("Whether the target is always in non-stop mode "
4406 "is %s (currently %s).\n"), value,
4407 target_always_non_stop_p () ? "on" : "off");
4408 else
4409 gdb_printf (file,
4410 _("Whether the target is always in non-stop mode "
4411 "is %s.\n"), value);
4412 }
4413
4414 /* Temporary copies of permission settings. */
4415
4416 static bool may_write_registers_1 = true;
4417 static bool may_write_memory_1 = true;
4418 static bool may_insert_breakpoints_1 = true;
4419 static bool may_insert_tracepoints_1 = true;
4420 static bool may_insert_fast_tracepoints_1 = true;
4421 static bool may_stop_1 = true;
4422
4423 /* Make the user-set values match the real values again. */
4424
4425 void
4426 update_target_permissions (void)
4427 {
4428 may_write_registers_1 = may_write_registers;
4429 may_write_memory_1 = may_write_memory;
4430 may_insert_breakpoints_1 = may_insert_breakpoints;
4431 may_insert_tracepoints_1 = may_insert_tracepoints;
4432 may_insert_fast_tracepoints_1 = may_insert_fast_tracepoints;
4433 may_stop_1 = may_stop;
4434 }
4435
4436 /* The one function handles (most of) the permission flags in the same
4437 way. */
4438
4439 static void
4440 set_target_permissions (const char *args, int from_tty,
4441 struct cmd_list_element *c)
4442 {
4443 if (target_has_execution ())
4444 {
4445 update_target_permissions ();
4446 error (_("Cannot change this setting while the inferior is running."));
4447 }
4448
4449 /* Make the real values match the user-changed values. */
4450 may_insert_breakpoints = may_insert_breakpoints_1;
4451 may_insert_tracepoints = may_insert_tracepoints_1;
4452 may_insert_fast_tracepoints = may_insert_fast_tracepoints_1;
4453 may_stop = may_stop_1;
4454 update_observer_mode ();
4455 }
4456
4457 /* Set some permissions independently of observer mode. */
4458
4459 static void
4460 set_write_memory_registers_permission (const char *args, int from_tty,
4461 struct cmd_list_element *c)
4462 {
4463 /* Make the real values match the user-changed values. */
4464 may_write_memory = may_write_memory_1;
4465 may_write_registers = may_write_registers_1;
4466 update_observer_mode ();
4467 }
4468
4469 void _initialize_target ();
4470
4471 void
4472 _initialize_target ()
4473 {
4474 the_debug_target = new debug_target ();
4475
4476 add_info ("target", info_target_command, targ_desc);
4477 add_info ("files", info_target_command, targ_desc);
4478
4479 add_setshow_zuinteger_cmd ("target", class_maintenance, &targetdebug, _("\
4480 Set target debugging."), _("\
4481 Show target debugging."), _("\
4482 When non-zero, target debugging is enabled. Higher numbers are more\n\
4483 verbose."),
4484 set_targetdebug,
4485 show_targetdebug,
4486 &setdebuglist, &showdebuglist);
4487
4488 add_setshow_boolean_cmd ("trust-readonly-sections", class_support,
4489 &trust_readonly, _("\
4490 Set mode for reading from readonly sections."), _("\
4491 Show mode for reading from readonly sections."), _("\
4492 When this mode is on, memory reads from readonly sections (such as .text)\n\
4493 will be read from the object file instead of from the target. This will\n\
4494 result in significant performance improvement for remote targets."),
4495 NULL,
4496 show_trust_readonly,
4497 &setlist, &showlist);
4498
4499 add_com ("monitor", class_obscure, do_monitor_command,
4500 _("Send a command to the remote monitor (remote targets only)."));
4501
4502 add_cmd ("target-stack", class_maintenance, maintenance_print_target_stack,
4503 _("Print the name of each layer of the internal target stack."),
4504 &maintenanceprintlist);
4505
4506 add_setshow_boolean_cmd ("target-async", no_class,
4507 _("\
4508 Set whether gdb controls the inferior in asynchronous mode."), _("\
4509 Show whether gdb controls the inferior in asynchronous mode."), _("\
4510 Tells gdb whether to control the inferior in asynchronous mode."),
4511 set_maint_target_async,
4512 get_maint_target_async,
4513 show_maint_target_async,
4514 &maintenance_set_cmdlist,
4515 &maintenance_show_cmdlist);
4516
4517 add_setshow_auto_boolean_cmd ("target-non-stop", no_class,
4518 _("\
4519 Set whether gdb always controls the inferior in non-stop mode."), _("\
4520 Show whether gdb always controls the inferior in non-stop mode."), _("\
4521 Tells gdb whether to control the inferior in non-stop mode."),
4522 set_maint_target_non_stop,
4523 get_maint_target_non_stop,
4524 show_maint_target_non_stop,
4525 &maintenance_set_cmdlist,
4526 &maintenance_show_cmdlist);
4527
4528 add_setshow_boolean_cmd ("may-write-registers", class_support,
4529 &may_write_registers_1, _("\
4530 Set permission to write into registers."), _("\
4531 Show permission to write into registers."), _("\
4532 When this permission is on, GDB may write into the target's registers.\n\
4533 Otherwise, any sort of write attempt will result in an error."),
4534 set_write_memory_registers_permission, NULL,
4535 &setlist, &showlist);
4536
4537 add_setshow_boolean_cmd ("may-write-memory", class_support,
4538 &may_write_memory_1, _("\
4539 Set permission to write into target memory."), _("\
4540 Show permission to write into target memory."), _("\
4541 When this permission is on, GDB may write into the target's memory.\n\
4542 Otherwise, any sort of write attempt will result in an error."),
4543 set_write_memory_registers_permission, NULL,
4544 &setlist, &showlist);
4545
4546 add_setshow_boolean_cmd ("may-insert-breakpoints", class_support,
4547 &may_insert_breakpoints_1, _("\
4548 Set permission to insert breakpoints in the target."), _("\
4549 Show permission to insert breakpoints in the target."), _("\
4550 When this permission is on, GDB may insert breakpoints in the program.\n\
4551 Otherwise, any sort of insertion attempt will result in an error."),
4552 set_target_permissions, NULL,
4553 &setlist, &showlist);
4554
4555 add_setshow_boolean_cmd ("may-insert-tracepoints", class_support,
4556 &may_insert_tracepoints_1, _("\
4557 Set permission to insert tracepoints in the target."), _("\
4558 Show permission to insert tracepoints in the target."), _("\
4559 When this permission is on, GDB may insert tracepoints in the program.\n\
4560 Otherwise, any sort of insertion attempt will result in an error."),
4561 set_target_permissions, NULL,
4562 &setlist, &showlist);
4563
4564 add_setshow_boolean_cmd ("may-insert-fast-tracepoints", class_support,
4565 &may_insert_fast_tracepoints_1, _("\
4566 Set permission to insert fast tracepoints in the target."), _("\
4567 Show permission to insert fast tracepoints in the target."), _("\
4568 When this permission is on, GDB may insert fast tracepoints.\n\
4569 Otherwise, any sort of insertion attempt will result in an error."),
4570 set_target_permissions, NULL,
4571 &setlist, &showlist);
4572
4573 add_setshow_boolean_cmd ("may-interrupt", class_support,
4574 &may_stop_1, _("\
4575 Set permission to interrupt or signal the target."), _("\
4576 Show permission to interrupt or signal the target."), _("\
4577 When this permission is on, GDB may interrupt/stop the target's execution.\n\
4578 Otherwise, any attempt to interrupt or stop will be ignored."),
4579 set_target_permissions, NULL,
4580 &setlist, &showlist);
4581
4582 add_com ("flash-erase", no_class, flash_erase_command,
4583 _("Erase all flash memory regions."));
4584
4585 add_setshow_boolean_cmd ("auto-connect-native-target", class_support,
4586 &auto_connect_native_target, _("\
4587 Set whether GDB may automatically connect to the native target."), _("\
4588 Show whether GDB may automatically connect to the native target."), _("\
4589 When on, and GDB is not connected to a target yet, GDB\n\
4590 attempts \"run\" and other commands with the native target."),
4591 NULL, show_auto_connect_native_target,
4592 &setlist, &showlist);
4593 }