gdb/testsuite: fix gdb.trace/signal.exp on x86
[binutils-gdb/blckswan.git] / gdb / target.c
blob18e53aa5d2768638513173243d62ec1ac459a5c8
1 /* Select target systems and architectures at runtime for GDB.
3 Copyright (C) 1990-2022 Free Software Foundation, Inc.
5 Contributed by Cygnus Support.
7 This file is part of GDB.
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.
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.
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/>. */
22 #include "defs.h"
23 #include "target.h"
24 #include "target-dcache.h"
25 #include "gdbcmd.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 "gdb/fileio.h"
44 #include "gdbsupport/agent.h"
45 #include "auxv.h"
46 #include "target-debug.h"
47 #include "top.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"
58 static void generic_tls_error (void) ATTRIBUTE_NORETURN;
60 static void default_terminal_info (struct target_ops *, const char *, int);
62 static int default_watchpoint_addr_within_range (struct target_ops *,
63 CORE_ADDR, CORE_ADDR, int);
65 static int default_region_ok_for_hw_watchpoint (struct target_ops *,
66 CORE_ADDR, int);
68 static void default_rcmd (struct target_ops *, const char *, struct ui_file *);
70 static ptid_t default_get_ada_task_ptid (struct target_ops *self,
71 long lwp, ULONGEST tid);
73 static void default_mourn_inferior (struct target_ops *self);
75 static int default_search_memory (struct target_ops *ops,
76 CORE_ADDR start_addr,
77 ULONGEST search_space_len,
78 const gdb_byte *pattern,
79 ULONGEST pattern_len,
80 CORE_ADDR *found_addrp);
82 static int default_verify_memory (struct target_ops *self,
83 const gdb_byte *data,
84 CORE_ADDR memaddr, ULONGEST size);
86 static void tcomplain (void) ATTRIBUTE_NORETURN;
88 static struct target_ops *find_default_run_target (const char *);
90 static int dummy_find_memory_regions (struct target_ops *self,
91 find_memory_region_ftype ignore1,
92 void *ignore2);
94 static gdb::unique_xmalloc_ptr<char> dummy_make_corefile_notes
95 (struct target_ops *self, bfd *ignore1, int *ignore2);
97 static std::string default_pid_to_str (struct target_ops *ops, ptid_t ptid);
99 static enum exec_direction_kind default_execution_direction
100 (struct target_ops *self);
102 /* Mapping between target_info objects (which have address identity)
103 and corresponding open/factory function/callback. Each add_target
104 call adds one entry to this map, and registers a "target
105 TARGET_NAME" command that when invoked calls the factory registered
106 here. The target_info object is associated with the command via
107 the command's context. */
108 static std::unordered_map<const target_info *, target_open_ftype *>
109 target_factories;
111 /* The singleton debug target. */
113 static struct target_ops *the_debug_target;
115 /* Command list for target. */
117 static struct cmd_list_element *targetlist = NULL;
119 /* True if we should trust readonly sections from the
120 executable when reading memory. */
122 static bool trust_readonly = false;
124 /* Nonzero if we should show true memory content including
125 memory breakpoint inserted by gdb. */
127 static int show_memory_breakpoints = 0;
129 /* These globals control whether GDB attempts to perform these
130 operations; they are useful for targets that need to prevent
131 inadvertent disruption, such as in non-stop mode. */
133 bool may_write_registers = true;
135 bool may_write_memory = true;
137 bool may_insert_breakpoints = true;
139 bool may_insert_tracepoints = true;
141 bool may_insert_fast_tracepoints = true;
143 bool may_stop = true;
145 /* Non-zero if we want to see trace of target level stuff. */
147 static unsigned int targetdebug = 0;
149 static void
150 set_targetdebug (const char *args, int from_tty, struct cmd_list_element *c)
152 if (targetdebug)
153 current_inferior ()->push_target (the_debug_target);
154 else
155 current_inferior ()->unpush_target (the_debug_target);
158 static void
159 show_targetdebug (struct ui_file *file, int from_tty,
160 struct cmd_list_element *c, const char *value)
162 gdb_printf (file, _("Target debugging is %s.\n"), value);
166 target_has_memory ()
168 for (target_ops *t = current_inferior ()->top_target ();
169 t != NULL;
170 t = t->beneath ())
171 if (t->has_memory ())
172 return 1;
174 return 0;
178 target_has_stack ()
180 for (target_ops *t = current_inferior ()->top_target ();
181 t != NULL;
182 t = t->beneath ())
183 if (t->has_stack ())
184 return 1;
186 return 0;
190 target_has_registers ()
192 for (target_ops *t = current_inferior ()->top_target ();
193 t != NULL;
194 t = t->beneath ())
195 if (t->has_registers ())
196 return 1;
198 return 0;
201 bool
202 target_has_execution (inferior *inf)
204 if (inf == nullptr)
205 inf = current_inferior ();
207 for (target_ops *t = inf->top_target ();
208 t != nullptr;
209 t = inf->find_target_beneath (t))
210 if (t->has_execution (inf))
211 return true;
213 return false;
216 const char *
217 target_shortname ()
219 return current_inferior ()->top_target ()->shortname ();
222 /* See target.h. */
224 bool
225 target_attach_no_wait ()
227 return current_inferior ()->top_target ()->attach_no_wait ();
230 /* See target.h. */
232 void
233 target_post_attach (int pid)
235 return current_inferior ()->top_target ()->post_attach (pid);
238 /* See target.h. */
240 void
241 target_prepare_to_store (regcache *regcache)
243 return current_inferior ()->top_target ()->prepare_to_store (regcache);
246 /* See target.h. */
248 bool
249 target_supports_enable_disable_tracepoint ()
251 target_ops *target = current_inferior ()->top_target ();
253 return target->supports_enable_disable_tracepoint ();
256 bool
257 target_supports_string_tracing ()
259 return current_inferior ()->top_target ()->supports_string_tracing ();
262 /* See target.h. */
264 bool
265 target_supports_evaluation_of_breakpoint_conditions ()
267 target_ops *target = current_inferior ()->top_target ();
269 return target->supports_evaluation_of_breakpoint_conditions ();
272 /* See target.h. */
274 bool
275 target_supports_dumpcore ()
277 return current_inferior ()->top_target ()->supports_dumpcore ();
280 /* See target.h. */
282 void
283 target_dumpcore (const char *filename)
285 return current_inferior ()->top_target ()->dumpcore (filename);
288 /* See target.h. */
290 bool
291 target_can_run_breakpoint_commands ()
293 return current_inferior ()->top_target ()->can_run_breakpoint_commands ();
296 /* See target.h. */
298 void
299 target_files_info ()
301 return current_inferior ()->top_target ()->files_info ();
304 /* See target.h. */
307 target_insert_fork_catchpoint (int pid)
309 return current_inferior ()->top_target ()->insert_fork_catchpoint (pid);
312 /* See target.h. */
315 target_remove_fork_catchpoint (int pid)
317 return current_inferior ()->top_target ()->remove_fork_catchpoint (pid);
320 /* See target.h. */
323 target_insert_vfork_catchpoint (int pid)
325 return current_inferior ()->top_target ()->insert_vfork_catchpoint (pid);
328 /* See target.h. */
331 target_remove_vfork_catchpoint (int pid)
333 return current_inferior ()->top_target ()->remove_vfork_catchpoint (pid);
336 /* See target.h. */
339 target_insert_exec_catchpoint (int pid)
341 return current_inferior ()->top_target ()->insert_exec_catchpoint (pid);
344 /* See target.h. */
347 target_remove_exec_catchpoint (int pid)
349 return current_inferior ()->top_target ()->remove_exec_catchpoint (pid);
352 /* See target.h. */
355 target_set_syscall_catchpoint (int pid, bool needed, int any_count,
356 gdb::array_view<const int> syscall_counts)
358 target_ops *target = current_inferior ()->top_target ();
360 return target->set_syscall_catchpoint (pid, needed, any_count,
361 syscall_counts);
364 /* See target.h. */
366 void
367 target_rcmd (const char *command, struct ui_file *outbuf)
369 return current_inferior ()->top_target ()->rcmd (command, outbuf);
372 /* See target.h. */
374 bool
375 target_can_lock_scheduler ()
377 target_ops *target = current_inferior ()->top_target ();
379 return (target->get_thread_control_capabilities ()& tc_schedlock) != 0;
382 /* See target.h. */
384 bool
385 target_can_async_p ()
387 return target_can_async_p (current_inferior ()->top_target ());
390 /* See target.h. */
392 bool
393 target_can_async_p (struct target_ops *target)
395 if (!target_async_permitted)
396 return false;
397 return target->can_async_p ();
400 /* See target.h. */
402 bool
403 target_is_async_p ()
405 bool result = current_inferior ()->top_target ()->is_async_p ();
406 gdb_assert (target_async_permitted || !result);
407 return result;
410 exec_direction_kind
411 target_execution_direction ()
413 return current_inferior ()->top_target ()->execution_direction ();
416 /* See target.h. */
418 const char *
419 target_extra_thread_info (thread_info *tp)
421 return current_inferior ()->top_target ()->extra_thread_info (tp);
424 /* See target.h. */
426 const char *
427 target_pid_to_exec_file (int pid)
429 return current_inferior ()->top_target ()->pid_to_exec_file (pid);
432 /* See target.h. */
434 gdbarch *
435 target_thread_architecture (ptid_t ptid)
437 return current_inferior ()->top_target ()->thread_architecture (ptid);
440 /* See target.h. */
443 target_find_memory_regions (find_memory_region_ftype func, void *data)
445 return current_inferior ()->top_target ()->find_memory_regions (func, data);
448 /* See target.h. */
450 gdb::unique_xmalloc_ptr<char>
451 target_make_corefile_notes (bfd *bfd, int *size_p)
453 return current_inferior ()->top_target ()->make_corefile_notes (bfd, size_p);
456 gdb_byte *
457 target_get_bookmark (const char *args, int from_tty)
459 return current_inferior ()->top_target ()->get_bookmark (args, from_tty);
462 void
463 target_goto_bookmark (const gdb_byte *arg, int from_tty)
465 return current_inferior ()->top_target ()->goto_bookmark (arg, from_tty);
468 /* See target.h. */
470 bool
471 target_stopped_by_watchpoint ()
473 return current_inferior ()->top_target ()->stopped_by_watchpoint ();
476 /* See target.h. */
478 bool
479 target_stopped_by_sw_breakpoint ()
481 return current_inferior ()->top_target ()->stopped_by_sw_breakpoint ();
484 bool
485 target_supports_stopped_by_sw_breakpoint ()
487 target_ops *target = current_inferior ()->top_target ();
489 return target->supports_stopped_by_sw_breakpoint ();
492 bool
493 target_stopped_by_hw_breakpoint ()
495 return current_inferior ()->top_target ()->stopped_by_hw_breakpoint ();
498 bool
499 target_supports_stopped_by_hw_breakpoint ()
501 target_ops *target = current_inferior ()->top_target ();
503 return target->supports_stopped_by_hw_breakpoint ();
506 /* See target.h. */
508 bool
509 target_have_steppable_watchpoint ()
511 return current_inferior ()->top_target ()->have_steppable_watchpoint ();
514 /* See target.h. */
517 target_can_use_hardware_watchpoint (bptype type, int cnt, int othertype)
519 target_ops *target = current_inferior ()->top_target ();
521 return target->can_use_hw_breakpoint (type, cnt, othertype);
524 /* See target.h. */
527 target_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
529 target_ops *target = current_inferior ()->top_target ();
531 return target->region_ok_for_hw_watchpoint (addr, len);
536 target_can_do_single_step ()
538 return current_inferior ()->top_target ()->can_do_single_step ();
541 /* See target.h. */
544 target_insert_watchpoint (CORE_ADDR addr, int len, target_hw_bp_type type,
545 expression *cond)
547 target_ops *target = current_inferior ()->top_target ();
549 return target->insert_watchpoint (addr, len, type, cond);
552 /* See target.h. */
555 target_remove_watchpoint (CORE_ADDR addr, int len, target_hw_bp_type type,
556 expression *cond)
558 target_ops *target = current_inferior ()->top_target ();
560 return target->remove_watchpoint (addr, len, type, cond);
563 /* See target.h. */
566 target_insert_hw_breakpoint (gdbarch *gdbarch, bp_target_info *bp_tgt)
568 target_ops *target = current_inferior ()->top_target ();
570 return target->insert_hw_breakpoint (gdbarch, bp_tgt);
573 /* See target.h. */
576 target_remove_hw_breakpoint (gdbarch *gdbarch, bp_target_info *bp_tgt)
578 target_ops *target = current_inferior ()->top_target ();
580 return target->remove_hw_breakpoint (gdbarch, bp_tgt);
583 /* See target.h. */
585 bool
586 target_can_accel_watchpoint_condition (CORE_ADDR addr, int len, int type,
587 expression *cond)
589 target_ops *target = current_inferior ()->top_target ();
591 return target->can_accel_watchpoint_condition (addr, len, type, cond);
594 /* See target.h. */
596 bool
597 target_can_execute_reverse ()
599 return current_inferior ()->top_target ()->can_execute_reverse ();
602 ptid_t
603 target_get_ada_task_ptid (long lwp, ULONGEST tid)
605 return current_inferior ()->top_target ()->get_ada_task_ptid (lwp, tid);
608 bool
609 target_filesystem_is_local ()
611 return current_inferior ()->top_target ()->filesystem_is_local ();
614 void
615 target_trace_init ()
617 return current_inferior ()->top_target ()->trace_init ();
620 void
621 target_download_tracepoint (bp_location *location)
623 return current_inferior ()->top_target ()->download_tracepoint (location);
626 bool
627 target_can_download_tracepoint ()
629 return current_inferior ()->top_target ()->can_download_tracepoint ();
632 void
633 target_download_trace_state_variable (const trace_state_variable &tsv)
635 target_ops *target = current_inferior ()->top_target ();
637 return target->download_trace_state_variable (tsv);
640 void
641 target_enable_tracepoint (bp_location *loc)
643 return current_inferior ()->top_target ()->enable_tracepoint (loc);
646 void
647 target_disable_tracepoint (bp_location *loc)
649 return current_inferior ()->top_target ()->disable_tracepoint (loc);
652 void
653 target_trace_start ()
655 return current_inferior ()->top_target ()->trace_start ();
658 void
659 target_trace_set_readonly_regions ()
661 return current_inferior ()->top_target ()->trace_set_readonly_regions ();
665 target_get_trace_status (trace_status *ts)
667 return current_inferior ()->top_target ()->get_trace_status (ts);
670 void
671 target_get_tracepoint_status (breakpoint *tp, uploaded_tp *utp)
673 return current_inferior ()->top_target ()->get_tracepoint_status (tp, utp);
676 void
677 target_trace_stop ()
679 return current_inferior ()->top_target ()->trace_stop ();
683 target_trace_find (trace_find_type type, int num,
684 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
686 target_ops *target = current_inferior ()->top_target ();
688 return target->trace_find (type, num, addr1, addr2, tpp);
691 bool
692 target_get_trace_state_variable_value (int tsv, LONGEST *val)
694 target_ops *target = current_inferior ()->top_target ();
696 return target->get_trace_state_variable_value (tsv, val);
700 target_save_trace_data (const char *filename)
702 return current_inferior ()->top_target ()->save_trace_data (filename);
706 target_upload_tracepoints (uploaded_tp **utpp)
708 return current_inferior ()->top_target ()->upload_tracepoints (utpp);
712 target_upload_trace_state_variables (uploaded_tsv **utsvp)
714 target_ops *target = current_inferior ()->top_target ();
716 return target->upload_trace_state_variables (utsvp);
719 LONGEST
720 target_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
722 target_ops *target = current_inferior ()->top_target ();
724 return target->get_raw_trace_data (buf, offset, len);
728 target_get_min_fast_tracepoint_insn_len ()
730 target_ops *target = current_inferior ()->top_target ();
732 return target->get_min_fast_tracepoint_insn_len ();
735 void
736 target_set_disconnected_tracing (int val)
738 return current_inferior ()->top_target ()->set_disconnected_tracing (val);
741 void
742 target_set_circular_trace_buffer (int val)
744 return current_inferior ()->top_target ()->set_circular_trace_buffer (val);
747 void
748 target_set_trace_buffer_size (LONGEST val)
750 return current_inferior ()->top_target ()->set_trace_buffer_size (val);
753 bool
754 target_set_trace_notes (const char *user, const char *notes,
755 const char *stopnotes)
757 target_ops *target = current_inferior ()->top_target ();
759 return target->set_trace_notes (user, notes, stopnotes);
762 bool
763 target_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
765 return current_inferior ()->top_target ()->get_tib_address (ptid, addr);
768 void
769 target_set_permissions ()
771 return current_inferior ()->top_target ()->set_permissions ();
774 bool
775 target_static_tracepoint_marker_at (CORE_ADDR addr,
776 static_tracepoint_marker *marker)
778 target_ops *target = current_inferior ()->top_target ();
780 return target->static_tracepoint_marker_at (addr, marker);
783 std::vector<static_tracepoint_marker>
784 target_static_tracepoint_markers_by_strid (const char *marker_id)
786 target_ops *target = current_inferior ()->top_target ();
788 return target->static_tracepoint_markers_by_strid (marker_id);
791 traceframe_info_up
792 target_traceframe_info ()
794 return current_inferior ()->top_target ()->traceframe_info ();
797 bool
798 target_use_agent (bool use)
800 return current_inferior ()->top_target ()->use_agent (use);
803 bool
804 target_can_use_agent ()
806 return current_inferior ()->top_target ()->can_use_agent ();
809 bool
810 target_augmented_libraries_svr4_read ()
812 return current_inferior ()->top_target ()->augmented_libraries_svr4_read ();
815 bool
816 target_supports_memory_tagging ()
818 return current_inferior ()->top_target ()->supports_memory_tagging ();
821 bool
822 target_fetch_memtags (CORE_ADDR address, size_t len, gdb::byte_vector &tags,
823 int type)
825 return current_inferior ()->top_target ()->fetch_memtags (address, len, tags, type);
828 bool
829 target_store_memtags (CORE_ADDR address, size_t len,
830 const gdb::byte_vector &tags, int type)
832 return current_inferior ()->top_target ()->store_memtags (address, len, tags, type);
835 void
836 target_log_command (const char *p)
838 return current_inferior ()->top_target ()->log_command (p);
841 /* This is used to implement the various target commands. */
843 static void
844 open_target (const char *args, int from_tty, struct cmd_list_element *command)
846 auto *ti = static_cast<target_info *> (command->context ());
847 target_open_ftype *func = target_factories[ti];
849 if (targetdebug)
850 gdb_printf (gdb_stdlog, "-> %s->open (...)\n",
851 ti->shortname);
853 func (args, from_tty);
855 if (targetdebug)
856 gdb_printf (gdb_stdlog, "<- %s->open (%s, %d)\n",
857 ti->shortname, args, from_tty);
860 /* See target.h. */
862 void
863 add_target (const target_info &t, target_open_ftype *func,
864 completer_ftype *completer)
866 struct cmd_list_element *c;
868 auto &func_slot = target_factories[&t];
869 if (func_slot != nullptr)
870 internal_error (__FILE__, __LINE__,
871 _("target already added (\"%s\")."), t.shortname);
872 func_slot = func;
874 if (targetlist == NULL)
875 add_basic_prefix_cmd ("target", class_run, _("\
876 Connect to a target machine or process.\n\
877 The first argument is the type or protocol of the target machine.\n\
878 Remaining arguments are interpreted by the target protocol. For more\n\
879 information on the arguments for a particular protocol, type\n\
880 `help target ' followed by the protocol name."),
881 &targetlist, 0, &cmdlist);
882 c = add_cmd (t.shortname, no_class, t.doc, &targetlist);
883 c->set_context ((void *) &t);
884 c->func = open_target;
885 if (completer != NULL)
886 set_cmd_completer (c, completer);
889 /* See target.h. */
891 void
892 add_deprecated_target_alias (const target_info &tinfo, const char *alias)
894 struct cmd_list_element *c;
896 /* If we use add_alias_cmd, here, we do not get the deprecated warning,
897 see PR cli/15104. */
898 c = add_cmd (alias, no_class, tinfo.doc, &targetlist);
899 c->func = open_target;
900 c->set_context ((void *) &tinfo);
901 gdb::unique_xmalloc_ptr<char> alt
902 = xstrprintf ("target %s", tinfo.shortname);
903 deprecate_cmd (c, alt.release ());
906 /* Stub functions */
908 void
909 target_kill (void)
911 current_inferior ()->top_target ()->kill ();
914 void
915 target_load (const char *arg, int from_tty)
917 target_dcache_invalidate ();
918 current_inferior ()->top_target ()->load (arg, from_tty);
921 /* Define it. */
923 target_terminal_state target_terminal::m_terminal_state
924 = target_terminal_state::is_ours;
926 /* See target/target.h. */
928 void
929 target_terminal::init (void)
931 current_inferior ()->top_target ()->terminal_init ();
933 m_terminal_state = target_terminal_state::is_ours;
936 /* See target/target.h. */
938 void
939 target_terminal::inferior (void)
941 struct ui *ui = current_ui;
943 /* A background resume (``run&'') should leave GDB in control of the
944 terminal. */
945 if (ui->prompt_state != PROMPT_BLOCKED)
946 return;
948 /* Since we always run the inferior in the main console (unless "set
949 inferior-tty" is in effect), when some UI other than the main one
950 calls target_terminal::inferior, then we leave the main UI's
951 terminal settings as is. */
952 if (ui != main_ui)
953 return;
955 /* If GDB is resuming the inferior in the foreground, install
956 inferior's terminal modes. */
958 struct inferior *inf = current_inferior ();
960 if (inf->terminal_state != target_terminal_state::is_inferior)
962 current_inferior ()->top_target ()->terminal_inferior ();
963 inf->terminal_state = target_terminal_state::is_inferior;
966 m_terminal_state = target_terminal_state::is_inferior;
968 /* If the user hit C-c before, pretend that it was hit right
969 here. */
970 if (check_quit_flag ())
971 target_pass_ctrlc ();
974 /* See target/target.h. */
976 void
977 target_terminal::restore_inferior (void)
979 struct ui *ui = current_ui;
981 /* See target_terminal::inferior(). */
982 if (ui->prompt_state != PROMPT_BLOCKED || ui != main_ui)
983 return;
985 /* Restore the terminal settings of inferiors that were in the
986 foreground but are now ours_for_output due to a temporary
987 target_target::ours_for_output() call. */
990 scoped_restore_current_inferior restore_inferior;
992 for (::inferior *inf : all_inferiors ())
994 if (inf->terminal_state == target_terminal_state::is_ours_for_output)
996 set_current_inferior (inf);
997 current_inferior ()->top_target ()->terminal_inferior ();
998 inf->terminal_state = target_terminal_state::is_inferior;
1003 m_terminal_state = target_terminal_state::is_inferior;
1005 /* If the user hit C-c before, pretend that it was hit right
1006 here. */
1007 if (check_quit_flag ())
1008 target_pass_ctrlc ();
1011 /* Switch terminal state to DESIRED_STATE, either is_ours, or
1012 is_ours_for_output. */
1014 static void
1015 target_terminal_is_ours_kind (target_terminal_state desired_state)
1017 scoped_restore_current_inferior restore_inferior;
1019 /* Must do this in two passes. First, have all inferiors save the
1020 current terminal settings. Then, after all inferiors have add a
1021 chance to safely save the terminal settings, restore GDB's
1022 terminal settings. */
1024 for (inferior *inf : all_inferiors ())
1026 if (inf->terminal_state == target_terminal_state::is_inferior)
1028 set_current_inferior (inf);
1029 current_inferior ()->top_target ()->terminal_save_inferior ();
1033 for (inferior *inf : all_inferiors ())
1035 /* Note we don't check is_inferior here like above because we
1036 need to handle 'is_ours_for_output -> is_ours' too. Careful
1037 to never transition from 'is_ours' to 'is_ours_for_output',
1038 though. */
1039 if (inf->terminal_state != target_terminal_state::is_ours
1040 && inf->terminal_state != desired_state)
1042 set_current_inferior (inf);
1043 if (desired_state == target_terminal_state::is_ours)
1044 current_inferior ()->top_target ()->terminal_ours ();
1045 else if (desired_state == target_terminal_state::is_ours_for_output)
1046 current_inferior ()->top_target ()->terminal_ours_for_output ();
1047 else
1048 gdb_assert_not_reached ("unhandled desired state");
1049 inf->terminal_state = desired_state;
1054 /* See target/target.h. */
1056 void
1057 target_terminal::ours ()
1059 struct ui *ui = current_ui;
1061 /* See target_terminal::inferior. */
1062 if (ui != main_ui)
1063 return;
1065 if (m_terminal_state == target_terminal_state::is_ours)
1066 return;
1068 target_terminal_is_ours_kind (target_terminal_state::is_ours);
1069 m_terminal_state = target_terminal_state::is_ours;
1072 /* See target/target.h. */
1074 void
1075 target_terminal::ours_for_output ()
1077 struct ui *ui = current_ui;
1079 /* See target_terminal::inferior. */
1080 if (ui != main_ui)
1081 return;
1083 if (!target_terminal::is_inferior ())
1084 return;
1086 target_terminal_is_ours_kind (target_terminal_state::is_ours_for_output);
1087 target_terminal::m_terminal_state = target_terminal_state::is_ours_for_output;
1090 /* See target/target.h. */
1092 void
1093 target_terminal::info (const char *arg, int from_tty)
1095 current_inferior ()->top_target ()->terminal_info (arg, from_tty);
1098 /* See target.h. */
1100 bool
1101 target_supports_terminal_ours (void)
1103 /* The current top target is the target at the top of the target
1104 stack of the current inferior. While normally there's always an
1105 inferior, we must check for nullptr here because we can get here
1106 very early during startup, before the initial inferior is first
1107 created. */
1108 inferior *inf = current_inferior ();
1110 if (inf == nullptr)
1111 return false;
1112 return inf->top_target ()->supports_terminal_ours ();
1115 static void
1116 tcomplain (void)
1118 error (_("You can't do that when your target is `%s'"),
1119 current_inferior ()->top_target ()->shortname ());
1122 void
1123 noprocess (void)
1125 error (_("You can't do that without a process to debug."));
1128 static void
1129 default_terminal_info (struct target_ops *self, const char *args, int from_tty)
1131 gdb_printf (_("No saved terminal information.\n"));
1134 /* A default implementation for the to_get_ada_task_ptid target method.
1136 This function builds the PTID by using both LWP and TID as part of
1137 the PTID lwp and tid elements. The pid used is the pid of the
1138 inferior_ptid. */
1140 static ptid_t
1141 default_get_ada_task_ptid (struct target_ops *self, long lwp, ULONGEST tid)
1143 return ptid_t (inferior_ptid.pid (), lwp, tid);
1146 static enum exec_direction_kind
1147 default_execution_direction (struct target_ops *self)
1149 if (!target_can_execute_reverse ())
1150 return EXEC_FORWARD;
1151 else if (!target_can_async_p ())
1152 return EXEC_FORWARD;
1153 else
1154 gdb_assert_not_reached ("\
1155 to_execution_direction must be implemented for reverse async");
1158 /* See target.h. */
1160 void
1161 decref_target (target_ops *t)
1163 t->decref ();
1164 if (t->refcount () == 0)
1166 if (t->stratum () == process_stratum)
1167 connection_list_remove (as_process_stratum_target (t));
1168 target_close (t);
1172 /* See target.h. */
1174 void
1175 target_stack::push (target_ops *t)
1177 t->incref ();
1179 strata stratum = t->stratum ();
1181 if (stratum == process_stratum)
1182 connection_list_add (as_process_stratum_target (t));
1184 /* If there's already a target at this stratum, remove it. */
1186 if (m_stack[stratum] != NULL)
1187 unpush (m_stack[stratum]);
1189 /* Now add the new one. */
1190 m_stack[stratum] = t;
1192 if (m_top < stratum)
1193 m_top = stratum;
1196 /* See target.h. */
1198 bool
1199 target_stack::unpush (target_ops *t)
1201 gdb_assert (t != NULL);
1203 strata stratum = t->stratum ();
1205 if (stratum == dummy_stratum)
1206 internal_error (__FILE__, __LINE__,
1207 _("Attempt to unpush the dummy target"));
1209 /* Look for the specified target. Note that a target can only occur
1210 once in the target stack. */
1212 if (m_stack[stratum] != t)
1214 /* If T wasn't pushed, quit. Only open targets should be
1215 closed. */
1216 return false;
1219 /* Unchain the target. */
1220 m_stack[stratum] = NULL;
1222 if (m_top == stratum)
1223 m_top = this->find_beneath (t)->stratum ();
1225 /* Finally close the target, if there are no inferiors
1226 referencing this target still. Note we do this after unchaining,
1227 so any target method calls from within the target_close
1228 implementation don't end up in T anymore. Do leave the target
1229 open if we have are other inferiors referencing this target
1230 still. */
1231 decref_target (t);
1233 return true;
1236 /* Unpush TARGET and assert that it worked. */
1238 static void
1239 unpush_target_and_assert (struct target_ops *target)
1241 if (!current_inferior ()->unpush_target (target))
1243 gdb_printf (gdb_stderr,
1244 "pop_all_targets couldn't find target %s\n",
1245 target->shortname ());
1246 internal_error (__FILE__, __LINE__,
1247 _("failed internal consistency check"));
1251 void
1252 pop_all_targets_above (enum strata above_stratum)
1254 while ((int) (current_inferior ()->top_target ()->stratum ())
1255 > (int) above_stratum)
1256 unpush_target_and_assert (current_inferior ()->top_target ());
1259 /* See target.h. */
1261 void
1262 pop_all_targets_at_and_above (enum strata stratum)
1264 while ((int) (current_inferior ()->top_target ()->stratum ())
1265 >= (int) stratum)
1266 unpush_target_and_assert (current_inferior ()->top_target ());
1269 void
1270 pop_all_targets (void)
1272 pop_all_targets_above (dummy_stratum);
1275 void
1276 target_unpusher::operator() (struct target_ops *ops) const
1278 current_inferior ()->unpush_target (ops);
1281 /* Default implementation of to_get_thread_local_address. */
1283 static void
1284 generic_tls_error (void)
1286 throw_error (TLS_GENERIC_ERROR,
1287 _("Cannot find thread-local variables on this target"));
1290 /* Using the objfile specified in OBJFILE, find the address for the
1291 current thread's thread-local storage with offset OFFSET. */
1292 CORE_ADDR
1293 target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset)
1295 volatile CORE_ADDR addr = 0;
1296 struct target_ops *target = current_inferior ()->top_target ();
1297 struct gdbarch *gdbarch = target_gdbarch ();
1299 /* If OBJFILE is a separate debug object file, look for the
1300 original object file. */
1301 if (objfile->separate_debug_objfile_backlink != NULL)
1302 objfile = objfile->separate_debug_objfile_backlink;
1304 if (gdbarch_fetch_tls_load_module_address_p (gdbarch))
1306 ptid_t ptid = inferior_ptid;
1310 CORE_ADDR lm_addr;
1312 /* Fetch the load module address for this objfile. */
1313 lm_addr = gdbarch_fetch_tls_load_module_address (gdbarch,
1314 objfile);
1316 if (gdbarch_get_thread_local_address_p (gdbarch))
1317 addr = gdbarch_get_thread_local_address (gdbarch, ptid, lm_addr,
1318 offset);
1319 else
1320 addr = target->get_thread_local_address (ptid, lm_addr, offset);
1322 /* If an error occurred, print TLS related messages here. Otherwise,
1323 throw the error to some higher catcher. */
1324 catch (const gdb_exception &ex)
1326 int objfile_is_library = (objfile->flags & OBJF_SHARED);
1328 switch (ex.error)
1330 case TLS_NO_LIBRARY_SUPPORT_ERROR:
1331 error (_("Cannot find thread-local variables "
1332 "in this thread library."));
1333 break;
1334 case TLS_LOAD_MODULE_NOT_FOUND_ERROR:
1335 if (objfile_is_library)
1336 error (_("Cannot find shared library `%s' in dynamic"
1337 " linker's load module list"), objfile_name (objfile));
1338 else
1339 error (_("Cannot find executable file `%s' in dynamic"
1340 " linker's load module list"), objfile_name (objfile));
1341 break;
1342 case TLS_NOT_ALLOCATED_YET_ERROR:
1343 if (objfile_is_library)
1344 error (_("The inferior has not yet allocated storage for"
1345 " thread-local variables in\n"
1346 "the shared library `%s'\n"
1347 "for %s"),
1348 objfile_name (objfile),
1349 target_pid_to_str (ptid).c_str ());
1350 else
1351 error (_("The inferior has not yet allocated storage for"
1352 " thread-local variables in\n"
1353 "the executable `%s'\n"
1354 "for %s"),
1355 objfile_name (objfile),
1356 target_pid_to_str (ptid).c_str ());
1357 break;
1358 case TLS_GENERIC_ERROR:
1359 if (objfile_is_library)
1360 error (_("Cannot find thread-local storage for %s, "
1361 "shared library %s:\n%s"),
1362 target_pid_to_str (ptid).c_str (),
1363 objfile_name (objfile), ex.what ());
1364 else
1365 error (_("Cannot find thread-local storage for %s, "
1366 "executable file %s:\n%s"),
1367 target_pid_to_str (ptid).c_str (),
1368 objfile_name (objfile), ex.what ());
1369 break;
1370 default:
1371 throw;
1372 break;
1376 else
1377 error (_("Cannot find thread-local variables on this target"));
1379 return addr;
1382 const char *
1383 target_xfer_status_to_string (enum target_xfer_status status)
1385 #define CASE(X) case X: return #X
1386 switch (status)
1388 CASE(TARGET_XFER_E_IO);
1389 CASE(TARGET_XFER_UNAVAILABLE);
1390 default:
1391 return "<unknown>";
1393 #undef CASE
1397 const target_section_table *
1398 target_get_section_table (struct target_ops *target)
1400 return target->get_section_table ();
1403 /* Find a section containing ADDR. */
1405 const struct target_section *
1406 target_section_by_addr (struct target_ops *target, CORE_ADDR addr)
1408 const target_section_table *table = target_get_section_table (target);
1410 if (table == NULL)
1411 return NULL;
1413 for (const target_section &secp : *table)
1415 if (addr >= secp.addr && addr < secp.endaddr)
1416 return &secp;
1418 return NULL;
1421 /* See target.h. */
1423 const target_section_table *
1424 default_get_section_table ()
1426 return &current_program_space->target_sections ();
1429 /* Helper for the memory xfer routines. Checks the attributes of the
1430 memory region of MEMADDR against the read or write being attempted.
1431 If the access is permitted returns true, otherwise returns false.
1432 REGION_P is an optional output parameter. If not-NULL, it is
1433 filled with a pointer to the memory region of MEMADDR. REG_LEN
1434 returns LEN trimmed to the end of the region. This is how much the
1435 caller can continue requesting, if the access is permitted. A
1436 single xfer request must not straddle memory region boundaries. */
1438 static int
1439 memory_xfer_check_region (gdb_byte *readbuf, const gdb_byte *writebuf,
1440 ULONGEST memaddr, ULONGEST len, ULONGEST *reg_len,
1441 struct mem_region **region_p)
1443 struct mem_region *region;
1445 region = lookup_mem_region (memaddr);
1447 if (region_p != NULL)
1448 *region_p = region;
1450 switch (region->attrib.mode)
1452 case MEM_RO:
1453 if (writebuf != NULL)
1454 return 0;
1455 break;
1457 case MEM_WO:
1458 if (readbuf != NULL)
1459 return 0;
1460 break;
1462 case MEM_FLASH:
1463 /* We only support writing to flash during "load" for now. */
1464 if (writebuf != NULL)
1465 error (_("Writing to flash memory forbidden in this context"));
1466 break;
1468 case MEM_NONE:
1469 return 0;
1472 /* region->hi == 0 means there's no upper bound. */
1473 if (memaddr + len < region->hi || region->hi == 0)
1474 *reg_len = len;
1475 else
1476 *reg_len = region->hi - memaddr;
1478 return 1;
1481 /* Read memory from more than one valid target. A core file, for
1482 instance, could have some of memory but delegate other bits to
1483 the target below it. So, we must manually try all targets. */
1485 enum target_xfer_status
1486 raw_memory_xfer_partial (struct target_ops *ops, gdb_byte *readbuf,
1487 const gdb_byte *writebuf, ULONGEST memaddr, LONGEST len,
1488 ULONGEST *xfered_len)
1490 enum target_xfer_status res;
1494 res = ops->xfer_partial (TARGET_OBJECT_MEMORY, NULL,
1495 readbuf, writebuf, memaddr, len,
1496 xfered_len);
1497 if (res == TARGET_XFER_OK)
1498 break;
1500 /* Stop if the target reports that the memory is not available. */
1501 if (res == TARGET_XFER_UNAVAILABLE)
1502 break;
1504 /* Don't continue past targets which have all the memory.
1505 At one time, this code was necessary to read data from
1506 executables / shared libraries when data for the requested
1507 addresses weren't available in the core file. But now the
1508 core target handles this case itself. */
1509 if (ops->has_all_memory ())
1510 break;
1512 ops = ops->beneath ();
1514 while (ops != NULL);
1516 /* The cache works at the raw memory level. Make sure the cache
1517 gets updated with raw contents no matter what kind of memory
1518 object was originally being written. Note we do write-through
1519 first, so that if it fails, we don't write to the cache contents
1520 that never made it to the target. */
1521 if (writebuf != NULL
1522 && inferior_ptid != null_ptid
1523 && target_dcache_init_p ()
1524 && (stack_cache_enabled_p () || code_cache_enabled_p ()))
1526 DCACHE *dcache = target_dcache_get ();
1528 /* Note that writing to an area of memory which wasn't present
1529 in the cache doesn't cause it to be loaded in. */
1530 dcache_update (dcache, res, memaddr, writebuf, *xfered_len);
1533 return res;
1536 /* Perform a partial memory transfer.
1537 For docs see target.h, to_xfer_partial. */
1539 static enum target_xfer_status
1540 memory_xfer_partial_1 (struct target_ops *ops, enum target_object object,
1541 gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST memaddr,
1542 ULONGEST len, ULONGEST *xfered_len)
1544 enum target_xfer_status res;
1545 ULONGEST reg_len;
1546 struct mem_region *region;
1547 struct inferior *inf;
1549 /* For accesses to unmapped overlay sections, read directly from
1550 files. Must do this first, as MEMADDR may need adjustment. */
1551 if (readbuf != NULL && overlay_debugging)
1553 struct obj_section *section = find_pc_overlay (memaddr);
1555 if (pc_in_unmapped_range (memaddr, section))
1557 const target_section_table *table = target_get_section_table (ops);
1558 const char *section_name = section->the_bfd_section->name;
1560 memaddr = overlay_mapped_address (memaddr, section);
1562 auto match_cb = [=] (const struct target_section *s)
1564 return (strcmp (section_name, s->the_bfd_section->name) == 0);
1567 return section_table_xfer_memory_partial (readbuf, writebuf,
1568 memaddr, len, xfered_len,
1569 *table, match_cb);
1573 /* Try the executable files, if "trust-readonly-sections" is set. */
1574 if (readbuf != NULL && trust_readonly)
1576 const struct target_section *secp
1577 = target_section_by_addr (ops, memaddr);
1578 if (secp != NULL
1579 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
1581 const target_section_table *table = target_get_section_table (ops);
1582 return section_table_xfer_memory_partial (readbuf, writebuf,
1583 memaddr, len, xfered_len,
1584 *table);
1588 /* Try GDB's internal data cache. */
1590 if (!memory_xfer_check_region (readbuf, writebuf, memaddr, len, &reg_len,
1591 &region))
1592 return TARGET_XFER_E_IO;
1594 if (inferior_ptid != null_ptid)
1595 inf = current_inferior ();
1596 else
1597 inf = NULL;
1599 if (inf != NULL
1600 && readbuf != NULL
1601 /* The dcache reads whole cache lines; that doesn't play well
1602 with reading from a trace buffer, because reading outside of
1603 the collected memory range fails. */
1604 && get_traceframe_number () == -1
1605 && (region->attrib.cache
1606 || (stack_cache_enabled_p () && object == TARGET_OBJECT_STACK_MEMORY)
1607 || (code_cache_enabled_p () && object == TARGET_OBJECT_CODE_MEMORY)))
1609 DCACHE *dcache = target_dcache_get_or_init ();
1611 return dcache_read_memory_partial (ops, dcache, memaddr, readbuf,
1612 reg_len, xfered_len);
1615 /* If none of those methods found the memory we wanted, fall back
1616 to a target partial transfer. Normally a single call to
1617 to_xfer_partial is enough; if it doesn't recognize an object
1618 it will call the to_xfer_partial of the next target down.
1619 But for memory this won't do. Memory is the only target
1620 object which can be read from more than one valid target.
1621 A core file, for instance, could have some of memory but
1622 delegate other bits to the target below it. So, we must
1623 manually try all targets. */
1625 res = raw_memory_xfer_partial (ops, readbuf, writebuf, memaddr, reg_len,
1626 xfered_len);
1628 /* If we still haven't got anything, return the last error. We
1629 give up. */
1630 return res;
1633 /* Perform a partial memory transfer. For docs see target.h,
1634 to_xfer_partial. */
1636 static enum target_xfer_status
1637 memory_xfer_partial (struct target_ops *ops, enum target_object object,
1638 gdb_byte *readbuf, const gdb_byte *writebuf,
1639 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
1641 enum target_xfer_status res;
1643 /* Zero length requests are ok and require no work. */
1644 if (len == 0)
1645 return TARGET_XFER_EOF;
1647 memaddr = address_significant (target_gdbarch (), memaddr);
1649 /* Fill in READBUF with breakpoint shadows, or WRITEBUF with
1650 breakpoint insns, thus hiding out from higher layers whether
1651 there are software breakpoints inserted in the code stream. */
1652 if (readbuf != NULL)
1654 res = memory_xfer_partial_1 (ops, object, readbuf, NULL, memaddr, len,
1655 xfered_len);
1657 if (res == TARGET_XFER_OK && !show_memory_breakpoints)
1658 breakpoint_xfer_memory (readbuf, NULL, NULL, memaddr, *xfered_len);
1660 else
1662 /* A large write request is likely to be partially satisfied
1663 by memory_xfer_partial_1. We will continually malloc
1664 and free a copy of the entire write request for breakpoint
1665 shadow handling even though we only end up writing a small
1666 subset of it. Cap writes to a limit specified by the target
1667 to mitigate this. */
1668 len = std::min (ops->get_memory_xfer_limit (), len);
1670 gdb::byte_vector buf (writebuf, writebuf + len);
1671 breakpoint_xfer_memory (NULL, buf.data (), writebuf, memaddr, len);
1672 res = memory_xfer_partial_1 (ops, object, NULL, buf.data (), memaddr, len,
1673 xfered_len);
1676 return res;
1679 scoped_restore_tmpl<int>
1680 make_scoped_restore_show_memory_breakpoints (int show)
1682 return make_scoped_restore (&show_memory_breakpoints, show);
1685 /* For docs see target.h, to_xfer_partial. */
1687 enum target_xfer_status
1688 target_xfer_partial (struct target_ops *ops,
1689 enum target_object object, const char *annex,
1690 gdb_byte *readbuf, const gdb_byte *writebuf,
1691 ULONGEST offset, ULONGEST len,
1692 ULONGEST *xfered_len)
1694 enum target_xfer_status retval;
1696 /* Transfer is done when LEN is zero. */
1697 if (len == 0)
1698 return TARGET_XFER_EOF;
1700 if (writebuf && !may_write_memory)
1701 error (_("Writing to memory is not allowed (addr %s, len %s)"),
1702 core_addr_to_string_nz (offset), plongest (len));
1704 *xfered_len = 0;
1706 /* If this is a memory transfer, let the memory-specific code
1707 have a look at it instead. Memory transfers are more
1708 complicated. */
1709 if (object == TARGET_OBJECT_MEMORY || object == TARGET_OBJECT_STACK_MEMORY
1710 || object == TARGET_OBJECT_CODE_MEMORY)
1711 retval = memory_xfer_partial (ops, object, readbuf,
1712 writebuf, offset, len, xfered_len);
1713 else if (object == TARGET_OBJECT_RAW_MEMORY)
1715 /* Skip/avoid accessing the target if the memory region
1716 attributes block the access. Check this here instead of in
1717 raw_memory_xfer_partial as otherwise we'd end up checking
1718 this twice in the case of the memory_xfer_partial path is
1719 taken; once before checking the dcache, and another in the
1720 tail call to raw_memory_xfer_partial. */
1721 if (!memory_xfer_check_region (readbuf, writebuf, offset, len, &len,
1722 NULL))
1723 return TARGET_XFER_E_IO;
1725 /* Request the normal memory object from other layers. */
1726 retval = raw_memory_xfer_partial (ops, readbuf, writebuf, offset, len,
1727 xfered_len);
1729 else
1730 retval = ops->xfer_partial (object, annex, readbuf,
1731 writebuf, offset, len, xfered_len);
1733 if (targetdebug)
1735 const unsigned char *myaddr = NULL;
1737 gdb_printf (gdb_stdlog,
1738 "%s:target_xfer_partial "
1739 "(%d, %s, %s, %s, %s, %s) = %d, %s",
1740 ops->shortname (),
1741 (int) object,
1742 (annex ? annex : "(null)"),
1743 host_address_to_string (readbuf),
1744 host_address_to_string (writebuf),
1745 core_addr_to_string_nz (offset),
1746 pulongest (len), retval,
1747 pulongest (*xfered_len));
1749 if (readbuf)
1750 myaddr = readbuf;
1751 if (writebuf)
1752 myaddr = writebuf;
1753 if (retval == TARGET_XFER_OK && myaddr != NULL)
1755 int i;
1757 gdb_puts (", bytes =", gdb_stdlog);
1758 for (i = 0; i < *xfered_len; i++)
1760 if ((((intptr_t) &(myaddr[i])) & 0xf) == 0)
1762 if (targetdebug < 2 && i > 0)
1764 gdb_printf (gdb_stdlog, " ...");
1765 break;
1767 gdb_printf (gdb_stdlog, "\n");
1770 gdb_printf (gdb_stdlog, " %02x", myaddr[i] & 0xff);
1774 gdb_putc ('\n', gdb_stdlog);
1777 /* Check implementations of to_xfer_partial update *XFERED_LEN
1778 properly. Do assertion after printing debug messages, so that we
1779 can find more clues on assertion failure from debugging messages. */
1780 if (retval == TARGET_XFER_OK || retval == TARGET_XFER_UNAVAILABLE)
1781 gdb_assert (*xfered_len > 0);
1783 return retval;
1786 /* Read LEN bytes of target memory at address MEMADDR, placing the
1787 results in GDB's memory at MYADDR. Returns either 0 for success or
1788 -1 if any error occurs.
1790 If an error occurs, no guarantee is made about the contents of the data at
1791 MYADDR. In particular, the caller should not depend upon partial reads
1792 filling the buffer with good data. There is no way for the caller to know
1793 how much good data might have been transfered anyway. Callers that can
1794 deal with partial reads should call target_read (which will retry until
1795 it makes no progress, and then return how much was transferred). */
1798 target_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1800 if (target_read (current_inferior ()->top_target (),
1801 TARGET_OBJECT_MEMORY, NULL,
1802 myaddr, memaddr, len) == len)
1803 return 0;
1804 else
1805 return -1;
1808 /* See target/target.h. */
1811 target_read_uint32 (CORE_ADDR memaddr, uint32_t *result)
1813 gdb_byte buf[4];
1814 int r;
1816 r = target_read_memory (memaddr, buf, sizeof buf);
1817 if (r != 0)
1818 return r;
1819 *result = extract_unsigned_integer (buf, sizeof buf,
1820 gdbarch_byte_order (target_gdbarch ()));
1821 return 0;
1824 /* Like target_read_memory, but specify explicitly that this is a read
1825 from the target's raw memory. That is, this read bypasses the
1826 dcache, breakpoint shadowing, etc. */
1829 target_read_raw_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1831 if (target_read (current_inferior ()->top_target (),
1832 TARGET_OBJECT_RAW_MEMORY, NULL,
1833 myaddr, memaddr, len) == len)
1834 return 0;
1835 else
1836 return -1;
1839 /* Like target_read_memory, but specify explicitly that this is a read from
1840 the target's stack. This may trigger different cache behavior. */
1843 target_read_stack (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1845 if (target_read (current_inferior ()->top_target (),
1846 TARGET_OBJECT_STACK_MEMORY, NULL,
1847 myaddr, memaddr, len) == len)
1848 return 0;
1849 else
1850 return -1;
1853 /* Like target_read_memory, but specify explicitly that this is a read from
1854 the target's code. This may trigger different cache behavior. */
1857 target_read_code (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1859 if (target_read (current_inferior ()->top_target (),
1860 TARGET_OBJECT_CODE_MEMORY, NULL,
1861 myaddr, memaddr, len) == len)
1862 return 0;
1863 else
1864 return -1;
1867 /* Write LEN bytes from MYADDR to target memory at address MEMADDR.
1868 Returns either 0 for success or -1 if any error occurs. If an
1869 error occurs, no guarantee is made about how much data got written.
1870 Callers that can deal with partial writes should call
1871 target_write. */
1874 target_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1876 if (target_write (current_inferior ()->top_target (),
1877 TARGET_OBJECT_MEMORY, NULL,
1878 myaddr, memaddr, len) == len)
1879 return 0;
1880 else
1881 return -1;
1884 /* Write LEN bytes from MYADDR to target raw memory at address
1885 MEMADDR. Returns either 0 for success or -1 if any error occurs.
1886 If an error occurs, no guarantee is made about how much data got
1887 written. Callers that can deal with partial writes should call
1888 target_write. */
1891 target_write_raw_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1893 if (target_write (current_inferior ()->top_target (),
1894 TARGET_OBJECT_RAW_MEMORY, NULL,
1895 myaddr, memaddr, len) == len)
1896 return 0;
1897 else
1898 return -1;
1901 /* Fetch the target's memory map. */
1903 std::vector<mem_region>
1904 target_memory_map (void)
1906 target_ops *target = current_inferior ()->top_target ();
1907 std::vector<mem_region> result = target->memory_map ();
1908 if (result.empty ())
1909 return result;
1911 std::sort (result.begin (), result.end ());
1913 /* Check that regions do not overlap. Simultaneously assign
1914 a numbering for the "mem" commands to use to refer to
1915 each region. */
1916 mem_region *last_one = NULL;
1917 for (size_t ix = 0; ix < result.size (); ix++)
1919 mem_region *this_one = &result[ix];
1920 this_one->number = ix;
1922 if (last_one != NULL && last_one->hi > this_one->lo)
1924 warning (_("Overlapping regions in memory map: ignoring"));
1925 return std::vector<mem_region> ();
1928 last_one = this_one;
1931 return result;
1934 void
1935 target_flash_erase (ULONGEST address, LONGEST length)
1937 current_inferior ()->top_target ()->flash_erase (address, length);
1940 void
1941 target_flash_done (void)
1943 current_inferior ()->top_target ()->flash_done ();
1946 static void
1947 show_trust_readonly (struct ui_file *file, int from_tty,
1948 struct cmd_list_element *c, const char *value)
1950 gdb_printf (file,
1951 _("Mode for reading from readonly sections is %s.\n"),
1952 value);
1955 /* Target vector read/write partial wrapper functions. */
1957 static enum target_xfer_status
1958 target_read_partial (struct target_ops *ops,
1959 enum target_object object,
1960 const char *annex, gdb_byte *buf,
1961 ULONGEST offset, ULONGEST len,
1962 ULONGEST *xfered_len)
1964 return target_xfer_partial (ops, object, annex, buf, NULL, offset, len,
1965 xfered_len);
1968 static enum target_xfer_status
1969 target_write_partial (struct target_ops *ops,
1970 enum target_object object,
1971 const char *annex, const gdb_byte *buf,
1972 ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
1974 return target_xfer_partial (ops, object, annex, NULL, buf, offset, len,
1975 xfered_len);
1978 /* Wrappers to perform the full transfer. */
1980 /* For docs on target_read see target.h. */
1982 LONGEST
1983 target_read (struct target_ops *ops,
1984 enum target_object object,
1985 const char *annex, gdb_byte *buf,
1986 ULONGEST offset, LONGEST len)
1988 LONGEST xfered_total = 0;
1989 int unit_size = 1;
1991 /* If we are reading from a memory object, find the length of an addressable
1992 unit for that architecture. */
1993 if (object == TARGET_OBJECT_MEMORY
1994 || object == TARGET_OBJECT_STACK_MEMORY
1995 || object == TARGET_OBJECT_CODE_MEMORY
1996 || object == TARGET_OBJECT_RAW_MEMORY)
1997 unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
1999 while (xfered_total < len)
2001 ULONGEST xfered_partial;
2002 enum target_xfer_status status;
2004 status = target_read_partial (ops, object, annex,
2005 buf + xfered_total * unit_size,
2006 offset + xfered_total, len - xfered_total,
2007 &xfered_partial);
2009 /* Call an observer, notifying them of the xfer progress? */
2010 if (status == TARGET_XFER_EOF)
2011 return xfered_total;
2012 else if (status == TARGET_XFER_OK)
2014 xfered_total += xfered_partial;
2015 QUIT;
2017 else
2018 return TARGET_XFER_E_IO;
2021 return len;
2024 /* Assuming that the entire [begin, end) range of memory cannot be
2025 read, try to read whatever subrange is possible to read.
2027 The function returns, in RESULT, either zero or one memory block.
2028 If there's a readable subrange at the beginning, it is completely
2029 read and returned. Any further readable subrange will not be read.
2030 Otherwise, if there's a readable subrange at the end, it will be
2031 completely read and returned. Any readable subranges before it
2032 (obviously, not starting at the beginning), will be ignored. In
2033 other cases -- either no readable subrange, or readable subrange(s)
2034 that is neither at the beginning, or end, nothing is returned.
2036 The purpose of this function is to handle a read across a boundary
2037 of accessible memory in a case when memory map is not available.
2038 The above restrictions are fine for this case, but will give
2039 incorrect results if the memory is 'patchy'. However, supporting
2040 'patchy' memory would require trying to read every single byte,
2041 and it seems unacceptable solution. Explicit memory map is
2042 recommended for this case -- and target_read_memory_robust will
2043 take care of reading multiple ranges then. */
2045 static void
2046 read_whatever_is_readable (struct target_ops *ops,
2047 const ULONGEST begin, const ULONGEST end,
2048 int unit_size,
2049 std::vector<memory_read_result> *result)
2051 ULONGEST current_begin = begin;
2052 ULONGEST current_end = end;
2053 int forward;
2054 ULONGEST xfered_len;
2056 /* If we previously failed to read 1 byte, nothing can be done here. */
2057 if (end - begin <= 1)
2058 return;
2060 gdb::unique_xmalloc_ptr<gdb_byte> buf ((gdb_byte *) xmalloc (end - begin));
2062 /* Check that either first or the last byte is readable, and give up
2063 if not. This heuristic is meant to permit reading accessible memory
2064 at the boundary of accessible region. */
2065 if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
2066 buf.get (), begin, 1, &xfered_len) == TARGET_XFER_OK)
2068 forward = 1;
2069 ++current_begin;
2071 else if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
2072 buf.get () + (end - begin) - 1, end - 1, 1,
2073 &xfered_len) == TARGET_XFER_OK)
2075 forward = 0;
2076 --current_end;
2078 else
2079 return;
2081 /* Loop invariant is that the [current_begin, current_end) was previously
2082 found to be not readable as a whole.
2084 Note loop condition -- if the range has 1 byte, we can't divide the range
2085 so there's no point trying further. */
2086 while (current_end - current_begin > 1)
2088 ULONGEST first_half_begin, first_half_end;
2089 ULONGEST second_half_begin, second_half_end;
2090 LONGEST xfer;
2091 ULONGEST middle = current_begin + (current_end - current_begin) / 2;
2093 if (forward)
2095 first_half_begin = current_begin;
2096 first_half_end = middle;
2097 second_half_begin = middle;
2098 second_half_end = current_end;
2100 else
2102 first_half_begin = middle;
2103 first_half_end = current_end;
2104 second_half_begin = current_begin;
2105 second_half_end = middle;
2108 xfer = target_read (ops, TARGET_OBJECT_MEMORY, NULL,
2109 buf.get () + (first_half_begin - begin) * unit_size,
2110 first_half_begin,
2111 first_half_end - first_half_begin);
2113 if (xfer == first_half_end - first_half_begin)
2115 /* This half reads up fine. So, the error must be in the
2116 other half. */
2117 current_begin = second_half_begin;
2118 current_end = second_half_end;
2120 else
2122 /* This half is not readable. Because we've tried one byte, we
2123 know some part of this half if actually readable. Go to the next
2124 iteration to divide again and try to read.
2126 We don't handle the other half, because this function only tries
2127 to read a single readable subrange. */
2128 current_begin = first_half_begin;
2129 current_end = first_half_end;
2133 if (forward)
2135 /* The [begin, current_begin) range has been read. */
2136 result->emplace_back (begin, current_end, std::move (buf));
2138 else
2140 /* The [current_end, end) range has been read. */
2141 LONGEST region_len = end - current_end;
2143 gdb::unique_xmalloc_ptr<gdb_byte> data
2144 ((gdb_byte *) xmalloc (region_len * unit_size));
2145 memcpy (data.get (), buf.get () + (current_end - begin) * unit_size,
2146 region_len * unit_size);
2147 result->emplace_back (current_end, end, std::move (data));
2151 std::vector<memory_read_result>
2152 read_memory_robust (struct target_ops *ops,
2153 const ULONGEST offset, const LONGEST len)
2155 std::vector<memory_read_result> result;
2156 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
2158 LONGEST xfered_total = 0;
2159 while (xfered_total < len)
2161 struct mem_region *region = lookup_mem_region (offset + xfered_total);
2162 LONGEST region_len;
2164 /* If there is no explicit region, a fake one should be created. */
2165 gdb_assert (region);
2167 if (region->hi == 0)
2168 region_len = len - xfered_total;
2169 else
2170 region_len = region->hi - offset;
2172 if (region->attrib.mode == MEM_NONE || region->attrib.mode == MEM_WO)
2174 /* Cannot read this region. Note that we can end up here only
2175 if the region is explicitly marked inaccessible, or
2176 'inaccessible-by-default' is in effect. */
2177 xfered_total += region_len;
2179 else
2181 LONGEST to_read = std::min (len - xfered_total, region_len);
2182 gdb::unique_xmalloc_ptr<gdb_byte> buffer
2183 ((gdb_byte *) xmalloc (to_read * unit_size));
2185 LONGEST xfered_partial =
2186 target_read (ops, TARGET_OBJECT_MEMORY, NULL, buffer.get (),
2187 offset + xfered_total, to_read);
2188 /* Call an observer, notifying them of the xfer progress? */
2189 if (xfered_partial <= 0)
2191 /* Got an error reading full chunk. See if maybe we can read
2192 some subrange. */
2193 read_whatever_is_readable (ops, offset + xfered_total,
2194 offset + xfered_total + to_read,
2195 unit_size, &result);
2196 xfered_total += to_read;
2198 else
2200 result.emplace_back (offset + xfered_total,
2201 offset + xfered_total + xfered_partial,
2202 std::move (buffer));
2203 xfered_total += xfered_partial;
2205 QUIT;
2209 return result;
2213 /* An alternative to target_write with progress callbacks. */
2215 LONGEST
2216 target_write_with_progress (struct target_ops *ops,
2217 enum target_object object,
2218 const char *annex, const gdb_byte *buf,
2219 ULONGEST offset, LONGEST len,
2220 void (*progress) (ULONGEST, void *), void *baton)
2222 LONGEST xfered_total = 0;
2223 int unit_size = 1;
2225 /* If we are writing to a memory object, find the length of an addressable
2226 unit for that architecture. */
2227 if (object == TARGET_OBJECT_MEMORY
2228 || object == TARGET_OBJECT_STACK_MEMORY
2229 || object == TARGET_OBJECT_CODE_MEMORY
2230 || object == TARGET_OBJECT_RAW_MEMORY)
2231 unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
2233 /* Give the progress callback a chance to set up. */
2234 if (progress)
2235 (*progress) (0, baton);
2237 while (xfered_total < len)
2239 ULONGEST xfered_partial;
2240 enum target_xfer_status status;
2242 status = target_write_partial (ops, object, annex,
2243 buf + xfered_total * unit_size,
2244 offset + xfered_total, len - xfered_total,
2245 &xfered_partial);
2247 if (status != TARGET_XFER_OK)
2248 return status == TARGET_XFER_EOF ? xfered_total : TARGET_XFER_E_IO;
2250 if (progress)
2251 (*progress) (xfered_partial, baton);
2253 xfered_total += xfered_partial;
2254 QUIT;
2256 return len;
2259 /* For docs on target_write see target.h. */
2261 LONGEST
2262 target_write (struct target_ops *ops,
2263 enum target_object object,
2264 const char *annex, const gdb_byte *buf,
2265 ULONGEST offset, LONGEST len)
2267 return target_write_with_progress (ops, object, annex, buf, offset, len,
2268 NULL, NULL);
2271 /* Help for target_read_alloc and target_read_stralloc. See their comments
2272 for details. */
2274 template <typename T>
2275 gdb::optional<gdb::def_vector<T>>
2276 target_read_alloc_1 (struct target_ops *ops, enum target_object object,
2277 const char *annex)
2279 gdb::def_vector<T> buf;
2280 size_t buf_pos = 0;
2281 const int chunk = 4096;
2283 /* This function does not have a length parameter; it reads the
2284 entire OBJECT). Also, it doesn't support objects fetched partly
2285 from one target and partly from another (in a different stratum,
2286 e.g. a core file and an executable). Both reasons make it
2287 unsuitable for reading memory. */
2288 gdb_assert (object != TARGET_OBJECT_MEMORY);
2290 /* Start by reading up to 4K at a time. The target will throttle
2291 this number down if necessary. */
2292 while (1)
2294 ULONGEST xfered_len;
2295 enum target_xfer_status status;
2297 buf.resize (buf_pos + chunk);
2299 status = target_read_partial (ops, object, annex,
2300 (gdb_byte *) &buf[buf_pos],
2301 buf_pos, chunk,
2302 &xfered_len);
2304 if (status == TARGET_XFER_EOF)
2306 /* Read all there was. */
2307 buf.resize (buf_pos);
2308 return buf;
2310 else if (status != TARGET_XFER_OK)
2312 /* An error occurred. */
2313 return {};
2316 buf_pos += xfered_len;
2318 QUIT;
2322 /* See target.h */
2324 gdb::optional<gdb::byte_vector>
2325 target_read_alloc (struct target_ops *ops, enum target_object object,
2326 const char *annex)
2328 return target_read_alloc_1<gdb_byte> (ops, object, annex);
2331 /* See target.h. */
2333 gdb::optional<gdb::char_vector>
2334 target_read_stralloc (struct target_ops *ops, enum target_object object,
2335 const char *annex)
2337 gdb::optional<gdb::char_vector> buf
2338 = target_read_alloc_1<char> (ops, object, annex);
2340 if (!buf)
2341 return {};
2343 if (buf->empty () || buf->back () != '\0')
2344 buf->push_back ('\0');
2346 /* Check for embedded NUL bytes; but allow trailing NULs. */
2347 for (auto it = std::find (buf->begin (), buf->end (), '\0');
2348 it != buf->end (); it++)
2349 if (*it != '\0')
2351 warning (_("target object %d, annex %s, "
2352 "contained unexpected null characters"),
2353 (int) object, annex ? annex : "(none)");
2354 break;
2357 return buf;
2360 /* Memory transfer methods. */
2362 void
2363 get_target_memory (struct target_ops *ops, CORE_ADDR addr, gdb_byte *buf,
2364 LONGEST len)
2366 /* This method is used to read from an alternate, non-current
2367 target. This read must bypass the overlay support (as symbols
2368 don't match this target), and GDB's internal cache (wrong cache
2369 for this target). */
2370 if (target_read (ops, TARGET_OBJECT_RAW_MEMORY, NULL, buf, addr, len)
2371 != len)
2372 memory_error (TARGET_XFER_E_IO, addr);
2375 ULONGEST
2376 get_target_memory_unsigned (struct target_ops *ops, CORE_ADDR addr,
2377 int len, enum bfd_endian byte_order)
2379 gdb_byte buf[sizeof (ULONGEST)];
2381 gdb_assert (len <= sizeof (buf));
2382 get_target_memory (ops, addr, buf, len);
2383 return extract_unsigned_integer (buf, len, byte_order);
2386 /* See target.h. */
2389 target_insert_breakpoint (struct gdbarch *gdbarch,
2390 struct bp_target_info *bp_tgt)
2392 if (!may_insert_breakpoints)
2394 warning (_("May not insert breakpoints"));
2395 return 1;
2398 target_ops *target = current_inferior ()->top_target ();
2400 return target->insert_breakpoint (gdbarch, bp_tgt);
2403 /* See target.h. */
2406 target_remove_breakpoint (struct gdbarch *gdbarch,
2407 struct bp_target_info *bp_tgt,
2408 enum remove_bp_reason reason)
2410 /* This is kind of a weird case to handle, but the permission might
2411 have been changed after breakpoints were inserted - in which case
2412 we should just take the user literally and assume that any
2413 breakpoints should be left in place. */
2414 if (!may_insert_breakpoints)
2416 warning (_("May not remove breakpoints"));
2417 return 1;
2420 target_ops *target = current_inferior ()->top_target ();
2422 return target->remove_breakpoint (gdbarch, bp_tgt, reason);
2425 static void
2426 info_target_command (const char *args, int from_tty)
2428 int has_all_mem = 0;
2430 if (current_program_space->symfile_object_file != NULL)
2432 objfile *objf = current_program_space->symfile_object_file;
2433 gdb_printf (_("Symbols from \"%s\".\n"),
2434 objfile_name (objf));
2437 for (target_ops *t = current_inferior ()->top_target ();
2438 t != NULL;
2439 t = t->beneath ())
2441 if (!t->has_memory ())
2442 continue;
2444 if ((int) (t->stratum ()) <= (int) dummy_stratum)
2445 continue;
2446 if (has_all_mem)
2447 gdb_printf (_("\tWhile running this, "
2448 "GDB does not access memory from...\n"));
2449 gdb_printf ("%s:\n", t->longname ());
2450 t->files_info ();
2451 has_all_mem = t->has_all_memory ();
2455 /* This function is called before any new inferior is created, e.g.
2456 by running a program, attaching, or connecting to a target.
2457 It cleans up any state from previous invocations which might
2458 change between runs. This is a subset of what target_preopen
2459 resets (things which might change between targets). */
2461 void
2462 target_pre_inferior (int from_tty)
2464 /* Clear out solib state. Otherwise the solib state of the previous
2465 inferior might have survived and is entirely wrong for the new
2466 target. This has been observed on GNU/Linux using glibc 2.3. How
2467 to reproduce:
2469 bash$ ./foo&
2470 [1] 4711
2471 bash$ ./foo&
2472 [1] 4712
2473 bash$ gdb ./foo
2474 [...]
2475 (gdb) attach 4711
2476 (gdb) detach
2477 (gdb) attach 4712
2478 Cannot access memory at address 0xdeadbeef
2481 /* In some OSs, the shared library list is the same/global/shared
2482 across inferiors. If code is shared between processes, so are
2483 memory regions and features. */
2484 if (!gdbarch_has_global_solist (target_gdbarch ()))
2486 no_shared_libraries (NULL, from_tty);
2488 invalidate_target_mem_regions ();
2490 target_clear_description ();
2493 /* attach_flag may be set if the previous process associated with
2494 the inferior was attached to. */
2495 current_inferior ()->attach_flag = 0;
2497 current_inferior ()->highest_thread_num = 0;
2499 agent_capability_invalidate ();
2502 /* This is to be called by the open routine before it does
2503 anything. */
2505 void
2506 target_preopen (int from_tty)
2508 dont_repeat ();
2510 if (current_inferior ()->pid != 0)
2512 if (!from_tty
2513 || !target_has_execution ()
2514 || query (_("A program is being debugged already. Kill it? ")))
2516 /* Core inferiors actually should be detached, not
2517 killed. */
2518 if (target_has_execution ())
2519 target_kill ();
2520 else
2521 target_detach (current_inferior (), 0);
2523 else
2524 error (_("Program not killed."));
2527 /* Calling target_kill may remove the target from the stack. But if
2528 it doesn't (which seems like a win for UDI), remove it now. */
2529 /* Leave the exec target, though. The user may be switching from a
2530 live process to a core of the same program. */
2531 pop_all_targets_above (file_stratum);
2533 target_pre_inferior (from_tty);
2536 /* See target.h. */
2538 void
2539 target_detach (inferior *inf, int from_tty)
2541 /* After we have detached, we will clear the register cache for this inferior
2542 by calling registers_changed_ptid. We must save the pid_ptid before
2543 detaching, as the target detach method will clear inf->pid. */
2544 ptid_t save_pid_ptid = ptid_t (inf->pid);
2546 /* As long as some to_detach implementations rely on the current_inferior
2547 (either directly, or indirectly, like through target_gdbarch or by
2548 reading memory), INF needs to be the current inferior. When that
2549 requirement will become no longer true, then we can remove this
2550 assertion. */
2551 gdb_assert (inf == current_inferior ());
2553 prepare_for_detach ();
2555 /* Hold a strong reference because detaching may unpush the
2556 target. */
2557 auto proc_target_ref = target_ops_ref::new_reference (inf->process_target ());
2559 current_inferior ()->top_target ()->detach (inf, from_tty);
2561 process_stratum_target *proc_target
2562 = as_process_stratum_target (proc_target_ref.get ());
2564 registers_changed_ptid (proc_target, save_pid_ptid);
2566 /* We have to ensure we have no frame cache left. Normally,
2567 registers_changed_ptid (save_pid_ptid) calls reinit_frame_cache when
2568 inferior_ptid matches save_pid_ptid, but in our case, it does not
2569 call it, as inferior_ptid has been reset. */
2570 reinit_frame_cache ();
2573 void
2574 target_disconnect (const char *args, int from_tty)
2576 /* If we're in breakpoints-always-inserted mode or if breakpoints
2577 are global across processes, we have to remove them before
2578 disconnecting. */
2579 remove_breakpoints ();
2581 current_inferior ()->top_target ()->disconnect (args, from_tty);
2584 /* See target/target.h. */
2586 ptid_t
2587 target_wait (ptid_t ptid, struct target_waitstatus *status,
2588 target_wait_flags options)
2590 target_ops *target = current_inferior ()->top_target ();
2591 process_stratum_target *proc_target = current_inferior ()->process_target ();
2593 gdb_assert (!proc_target->commit_resumed_state);
2595 if (!target_can_async_p (target))
2596 gdb_assert ((options & TARGET_WNOHANG) == 0);
2600 gdb::observers::target_pre_wait.notify (ptid);
2601 ptid_t event_ptid = target->wait (ptid, status, options);
2602 gdb::observers::target_post_wait.notify (event_ptid);
2603 return event_ptid;
2605 catch (...)
2607 gdb::observers::target_post_wait.notify (null_ptid);
2608 throw;
2612 /* See target.h. */
2614 ptid_t
2615 default_target_wait (struct target_ops *ops,
2616 ptid_t ptid, struct target_waitstatus *status,
2617 target_wait_flags options)
2619 status->set_ignore ();
2620 return minus_one_ptid;
2623 std::string
2624 target_pid_to_str (ptid_t ptid)
2626 return current_inferior ()->top_target ()->pid_to_str (ptid);
2629 const char *
2630 target_thread_name (struct thread_info *info)
2632 gdb_assert (info->inf == current_inferior ());
2634 return current_inferior ()->top_target ()->thread_name (info);
2637 struct thread_info *
2638 target_thread_handle_to_thread_info (const gdb_byte *thread_handle,
2639 int handle_len,
2640 struct inferior *inf)
2642 target_ops *target = current_inferior ()->top_target ();
2644 return target->thread_handle_to_thread_info (thread_handle, handle_len, inf);
2647 /* See target.h. */
2649 gdb::byte_vector
2650 target_thread_info_to_thread_handle (struct thread_info *tip)
2652 target_ops *target = current_inferior ()->top_target ();
2654 return target->thread_info_to_thread_handle (tip);
2657 void
2658 target_resume (ptid_t scope_ptid, int step, enum gdb_signal signal)
2660 process_stratum_target *curr_target = current_inferior ()->process_target ();
2661 gdb_assert (!curr_target->commit_resumed_state);
2663 gdb_assert (inferior_ptid != null_ptid);
2664 gdb_assert (inferior_ptid.matches (scope_ptid));
2666 target_dcache_invalidate ();
2668 current_inferior ()->top_target ()->resume (scope_ptid, step, signal);
2670 registers_changed_ptid (curr_target, scope_ptid);
2671 /* We only set the internal executing state here. The user/frontend
2672 running state is set at a higher level. This also clears the
2673 thread's stop_pc as side effect. */
2674 set_executing (curr_target, scope_ptid, true);
2675 clear_inline_frame_state (curr_target, scope_ptid);
2677 if (target_can_async_p ())
2678 target_async (1);
2681 /* See target.h. */
2683 void
2684 target_commit_resumed ()
2686 gdb_assert (current_inferior ()->process_target ()->commit_resumed_state);
2687 current_inferior ()->top_target ()->commit_resumed ();
2690 /* See target.h. */
2692 bool
2693 target_has_pending_events ()
2695 return current_inferior ()->top_target ()->has_pending_events ();
2698 void
2699 target_pass_signals (gdb::array_view<const unsigned char> pass_signals)
2701 current_inferior ()->top_target ()->pass_signals (pass_signals);
2704 void
2705 target_program_signals (gdb::array_view<const unsigned char> program_signals)
2707 current_inferior ()->top_target ()->program_signals (program_signals);
2710 static void
2711 default_follow_fork (struct target_ops *self, inferior *child_inf,
2712 ptid_t child_ptid, target_waitkind fork_kind,
2713 bool follow_child, bool detach_fork)
2715 /* Some target returned a fork event, but did not know how to follow it. */
2716 internal_error (__FILE__, __LINE__,
2717 _("could not find a target to follow fork"));
2720 /* See target.h. */
2722 void
2723 target_follow_fork (inferior *child_inf, ptid_t child_ptid,
2724 target_waitkind fork_kind, bool follow_child,
2725 bool detach_fork)
2727 target_ops *target = current_inferior ()->top_target ();
2729 /* Check consistency between CHILD_INF, CHILD_PTID, FOLLOW_CHILD and
2730 DETACH_FORK. */
2731 if (child_inf != nullptr)
2733 gdb_assert (follow_child || !detach_fork);
2734 gdb_assert (child_inf->pid == child_ptid.pid ());
2736 else
2737 gdb_assert (!follow_child && detach_fork);
2739 return target->follow_fork (child_inf, child_ptid, fork_kind, follow_child,
2740 detach_fork);
2743 /* See target.h. */
2745 void
2746 target_follow_exec (inferior *follow_inf, ptid_t ptid,
2747 const char *execd_pathname)
2749 current_inferior ()->top_target ()->follow_exec (follow_inf, ptid,
2750 execd_pathname);
2753 static void
2754 default_mourn_inferior (struct target_ops *self)
2756 internal_error (__FILE__, __LINE__,
2757 _("could not find a target to follow mourn inferior"));
2760 void
2761 target_mourn_inferior (ptid_t ptid)
2763 gdb_assert (ptid.pid () == inferior_ptid.pid ());
2764 current_inferior ()->top_target ()->mourn_inferior ();
2766 /* We no longer need to keep handles on any of the object files.
2767 Make sure to release them to avoid unnecessarily locking any
2768 of them while we're not actually debugging. */
2769 bfd_cache_close_all ();
2772 /* Look for a target which can describe architectural features, starting
2773 from TARGET. If we find one, return its description. */
2775 const struct target_desc *
2776 target_read_description (struct target_ops *target)
2778 return target->read_description ();
2782 /* Default implementation of memory-searching. */
2784 static int
2785 default_search_memory (struct target_ops *self,
2786 CORE_ADDR start_addr, ULONGEST search_space_len,
2787 const gdb_byte *pattern, ULONGEST pattern_len,
2788 CORE_ADDR *found_addrp)
2790 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
2792 return target_read (current_inferior ()->top_target (),
2793 TARGET_OBJECT_MEMORY, NULL,
2794 result, addr, len) == len;
2797 /* Start over from the top of the target stack. */
2798 return simple_search_memory (read_memory, start_addr, search_space_len,
2799 pattern, pattern_len, found_addrp);
2802 /* Search SEARCH_SPACE_LEN bytes beginning at START_ADDR for the
2803 sequence of bytes in PATTERN with length PATTERN_LEN.
2805 The result is 1 if found, 0 if not found, and -1 if there was an error
2806 requiring halting of the search (e.g. memory read error).
2807 If the pattern is found the address is recorded in FOUND_ADDRP. */
2810 target_search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
2811 const gdb_byte *pattern, ULONGEST pattern_len,
2812 CORE_ADDR *found_addrp)
2814 target_ops *target = current_inferior ()->top_target ();
2816 return target->search_memory (start_addr, search_space_len, pattern,
2817 pattern_len, found_addrp);
2820 /* Look through the currently pushed targets. If none of them will
2821 be able to restart the currently running process, issue an error
2822 message. */
2824 void
2825 target_require_runnable (void)
2827 for (target_ops *t = current_inferior ()->top_target ();
2828 t != NULL;
2829 t = t->beneath ())
2831 /* If this target knows how to create a new program, then
2832 assume we will still be able to after killing the current
2833 one. Either killing and mourning will not pop T, or else
2834 find_default_run_target will find it again. */
2835 if (t->can_create_inferior ())
2836 return;
2838 /* Do not worry about targets at certain strata that can not
2839 create inferiors. Assume they will be pushed again if
2840 necessary, and continue to the process_stratum. */
2841 if (t->stratum () > process_stratum)
2842 continue;
2844 error (_("The \"%s\" target does not support \"run\". "
2845 "Try \"help target\" or \"continue\"."),
2846 t->shortname ());
2849 /* This function is only called if the target is running. In that
2850 case there should have been a process_stratum target and it
2851 should either know how to create inferiors, or not... */
2852 internal_error (__FILE__, __LINE__, _("No targets found"));
2855 /* Whether GDB is allowed to fall back to the default run target for
2856 "run", "attach", etc. when no target is connected yet. */
2857 static bool auto_connect_native_target = true;
2859 static void
2860 show_auto_connect_native_target (struct ui_file *file, int from_tty,
2861 struct cmd_list_element *c, const char *value)
2863 gdb_printf (file,
2864 _("Whether GDB may automatically connect to the "
2865 "native target is %s.\n"),
2866 value);
2869 /* A pointer to the target that can respond to "run" or "attach".
2870 Native targets are always singletons and instantiated early at GDB
2871 startup. */
2872 static target_ops *the_native_target;
2874 /* See target.h. */
2876 void
2877 set_native_target (target_ops *target)
2879 if (the_native_target != NULL)
2880 internal_error (__FILE__, __LINE__,
2881 _("native target already set (\"%s\")."),
2882 the_native_target->longname ());
2884 the_native_target = target;
2887 /* See target.h. */
2889 target_ops *
2890 get_native_target ()
2892 return the_native_target;
2895 /* Look through the list of possible targets for a target that can
2896 execute a run or attach command without any other data. This is
2897 used to locate the default process stratum.
2899 If DO_MESG is not NULL, the result is always valid (error() is
2900 called for errors); else, return NULL on error. */
2902 static struct target_ops *
2903 find_default_run_target (const char *do_mesg)
2905 if (auto_connect_native_target && the_native_target != NULL)
2906 return the_native_target;
2908 if (do_mesg != NULL)
2909 error (_("Don't know how to %s. Try \"help target\"."), do_mesg);
2910 return NULL;
2913 /* See target.h. */
2915 struct target_ops *
2916 find_attach_target (void)
2918 /* If a target on the current stack can attach, use it. */
2919 for (target_ops *t = current_inferior ()->top_target ();
2920 t != NULL;
2921 t = t->beneath ())
2923 if (t->can_attach ())
2924 return t;
2927 /* Otherwise, use the default run target for attaching. */
2928 return find_default_run_target ("attach");
2931 /* See target.h. */
2933 struct target_ops *
2934 find_run_target (void)
2936 /* If a target on the current stack can run, use it. */
2937 for (target_ops *t = current_inferior ()->top_target ();
2938 t != NULL;
2939 t = t->beneath ())
2941 if (t->can_create_inferior ())
2942 return t;
2945 /* Otherwise, use the default run target. */
2946 return find_default_run_target ("run");
2949 bool
2950 target_ops::info_proc (const char *args, enum info_proc_what what)
2952 return false;
2955 /* Implement the "info proc" command. */
2958 target_info_proc (const char *args, enum info_proc_what what)
2960 struct target_ops *t;
2962 /* If we're already connected to something that can get us OS
2963 related data, use it. Otherwise, try using the native
2964 target. */
2965 t = find_target_at (process_stratum);
2966 if (t == NULL)
2967 t = find_default_run_target (NULL);
2969 for (; t != NULL; t = t->beneath ())
2971 if (t->info_proc (args, what))
2973 if (targetdebug)
2974 gdb_printf (gdb_stdlog,
2975 "target_info_proc (\"%s\", %d)\n", args, what);
2977 return 1;
2981 return 0;
2984 static int
2985 find_default_supports_disable_randomization (struct target_ops *self)
2987 struct target_ops *t;
2989 t = find_default_run_target (NULL);
2990 if (t != NULL)
2991 return t->supports_disable_randomization ();
2992 return 0;
2996 target_supports_disable_randomization (void)
2998 return current_inferior ()->top_target ()->supports_disable_randomization ();
3001 /* See target/target.h. */
3004 target_supports_multi_process (void)
3006 return current_inferior ()->top_target ()->supports_multi_process ();
3009 /* See target.h. */
3011 gdb::optional<gdb::char_vector>
3012 target_get_osdata (const char *type)
3014 struct target_ops *t;
3016 /* If we're already connected to something that can get us OS
3017 related data, use it. Otherwise, try using the native
3018 target. */
3019 t = find_target_at (process_stratum);
3020 if (t == NULL)
3021 t = find_default_run_target ("get OS data");
3023 if (!t)
3024 return {};
3026 return target_read_stralloc (t, TARGET_OBJECT_OSDATA, type);
3029 /* Determine the current address space of thread PTID. */
3031 struct address_space *
3032 target_thread_address_space (ptid_t ptid)
3034 struct address_space *aspace;
3036 aspace = current_inferior ()->top_target ()->thread_address_space (ptid);
3037 gdb_assert (aspace != NULL);
3039 return aspace;
3042 /* See target.h. */
3044 target_ops *
3045 target_ops::beneath () const
3047 return current_inferior ()->find_target_beneath (this);
3050 void
3051 target_ops::close ()
3055 bool
3056 target_ops::can_attach ()
3058 return 0;
3061 void
3062 target_ops::attach (const char *, int)
3064 gdb_assert_not_reached ("target_ops::attach called");
3067 bool
3068 target_ops::can_create_inferior ()
3070 return 0;
3073 void
3074 target_ops::create_inferior (const char *, const std::string &,
3075 char **, int)
3077 gdb_assert_not_reached ("target_ops::create_inferior called");
3080 bool
3081 target_ops::can_run ()
3083 return false;
3087 target_can_run ()
3089 for (target_ops *t = current_inferior ()->top_target ();
3090 t != NULL;
3091 t = t->beneath ())
3093 if (t->can_run ())
3094 return 1;
3097 return 0;
3100 /* Target file operations. */
3102 static struct target_ops *
3103 default_fileio_target (void)
3105 struct target_ops *t;
3107 /* If we're already connected to something that can perform
3108 file I/O, use it. Otherwise, try using the native target. */
3109 t = find_target_at (process_stratum);
3110 if (t != NULL)
3111 return t;
3112 return find_default_run_target ("file I/O");
3115 /* File handle for target file operations. */
3117 struct fileio_fh_t
3119 /* The target on which this file is open. NULL if the target is
3120 meanwhile closed while the handle is open. */
3121 target_ops *target;
3123 /* The file descriptor on the target. */
3124 int target_fd;
3126 /* Check whether this fileio_fh_t represents a closed file. */
3127 bool is_closed ()
3129 return target_fd < 0;
3133 /* Vector of currently open file handles. The value returned by
3134 target_fileio_open and passed as the FD argument to other
3135 target_fileio_* functions is an index into this vector. This
3136 vector's entries are never freed; instead, files are marked as
3137 closed, and the handle becomes available for reuse. */
3138 static std::vector<fileio_fh_t> fileio_fhandles;
3140 /* Index into fileio_fhandles of the lowest handle that might be
3141 closed. This permits handle reuse without searching the whole
3142 list each time a new file is opened. */
3143 static int lowest_closed_fd;
3145 /* See target.h. */
3147 void
3148 fileio_handles_invalidate_target (target_ops *targ)
3150 for (fileio_fh_t &fh : fileio_fhandles)
3151 if (fh.target == targ)
3152 fh.target = NULL;
3155 /* Acquire a target fileio file descriptor. */
3157 static int
3158 acquire_fileio_fd (target_ops *target, int target_fd)
3160 /* Search for closed handles to reuse. */
3161 for (; lowest_closed_fd < fileio_fhandles.size (); lowest_closed_fd++)
3163 fileio_fh_t &fh = fileio_fhandles[lowest_closed_fd];
3165 if (fh.is_closed ())
3166 break;
3169 /* Push a new handle if no closed handles were found. */
3170 if (lowest_closed_fd == fileio_fhandles.size ())
3171 fileio_fhandles.push_back (fileio_fh_t {target, target_fd});
3172 else
3173 fileio_fhandles[lowest_closed_fd] = {target, target_fd};
3175 /* Should no longer be marked closed. */
3176 gdb_assert (!fileio_fhandles[lowest_closed_fd].is_closed ());
3178 /* Return its index, and start the next lookup at
3179 the next index. */
3180 return lowest_closed_fd++;
3183 /* Release a target fileio file descriptor. */
3185 static void
3186 release_fileio_fd (int fd, fileio_fh_t *fh)
3188 fh->target_fd = -1;
3189 lowest_closed_fd = std::min (lowest_closed_fd, fd);
3192 /* Return a pointer to the fileio_fhandle_t corresponding to FD. */
3194 static fileio_fh_t *
3195 fileio_fd_to_fh (int fd)
3197 return &fileio_fhandles[fd];
3201 /* Default implementations of file i/o methods. We don't want these
3202 to delegate automatically, because we need to know which target
3203 supported the method, in order to call it directly from within
3204 pread/pwrite, etc. */
3207 target_ops::fileio_open (struct inferior *inf, const char *filename,
3208 int flags, int mode, int warn_if_slow,
3209 int *target_errno)
3211 *target_errno = FILEIO_ENOSYS;
3212 return -1;
3216 target_ops::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
3217 ULONGEST offset, int *target_errno)
3219 *target_errno = FILEIO_ENOSYS;
3220 return -1;
3224 target_ops::fileio_pread (int fd, gdb_byte *read_buf, int len,
3225 ULONGEST offset, int *target_errno)
3227 *target_errno = FILEIO_ENOSYS;
3228 return -1;
3232 target_ops::fileio_fstat (int fd, struct stat *sb, int *target_errno)
3234 *target_errno = FILEIO_ENOSYS;
3235 return -1;
3239 target_ops::fileio_close (int fd, int *target_errno)
3241 *target_errno = FILEIO_ENOSYS;
3242 return -1;
3246 target_ops::fileio_unlink (struct inferior *inf, const char *filename,
3247 int *target_errno)
3249 *target_errno = FILEIO_ENOSYS;
3250 return -1;
3253 gdb::optional<std::string>
3254 target_ops::fileio_readlink (struct inferior *inf, const char *filename,
3255 int *target_errno)
3257 *target_errno = FILEIO_ENOSYS;
3258 return {};
3261 /* See target.h. */
3264 target_fileio_open (struct inferior *inf, const char *filename,
3265 int flags, int mode, bool warn_if_slow, int *target_errno)
3267 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3269 int fd = t->fileio_open (inf, filename, flags, mode,
3270 warn_if_slow, target_errno);
3272 if (fd == -1 && *target_errno == FILEIO_ENOSYS)
3273 continue;
3275 if (fd < 0)
3276 fd = -1;
3277 else
3278 fd = acquire_fileio_fd (t, fd);
3280 if (targetdebug)
3281 gdb_printf (gdb_stdlog,
3282 "target_fileio_open (%d,%s,0x%x,0%o,%d)"
3283 " = %d (%d)\n",
3284 inf == NULL ? 0 : inf->num,
3285 filename, flags, mode,
3286 warn_if_slow, fd,
3287 fd != -1 ? 0 : *target_errno);
3288 return fd;
3291 *target_errno = FILEIO_ENOSYS;
3292 return -1;
3295 /* See target.h. */
3298 target_fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
3299 ULONGEST offset, int *target_errno)
3301 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3302 int ret = -1;
3304 if (fh->is_closed ())
3305 *target_errno = EBADF;
3306 else if (fh->target == NULL)
3307 *target_errno = EIO;
3308 else
3309 ret = fh->target->fileio_pwrite (fh->target_fd, write_buf,
3310 len, offset, target_errno);
3312 if (targetdebug)
3313 gdb_printf (gdb_stdlog,
3314 "target_fileio_pwrite (%d,...,%d,%s) "
3315 "= %d (%d)\n",
3316 fd, len, pulongest (offset),
3317 ret, ret != -1 ? 0 : *target_errno);
3318 return ret;
3321 /* See target.h. */
3324 target_fileio_pread (int fd, gdb_byte *read_buf, int len,
3325 ULONGEST offset, int *target_errno)
3327 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3328 int ret = -1;
3330 if (fh->is_closed ())
3331 *target_errno = EBADF;
3332 else if (fh->target == NULL)
3333 *target_errno = EIO;
3334 else
3335 ret = fh->target->fileio_pread (fh->target_fd, read_buf,
3336 len, offset, target_errno);
3338 if (targetdebug)
3339 gdb_printf (gdb_stdlog,
3340 "target_fileio_pread (%d,...,%d,%s) "
3341 "= %d (%d)\n",
3342 fd, len, pulongest (offset),
3343 ret, ret != -1 ? 0 : *target_errno);
3344 return ret;
3347 /* See target.h. */
3350 target_fileio_fstat (int fd, struct stat *sb, int *target_errno)
3352 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3353 int ret = -1;
3355 if (fh->is_closed ())
3356 *target_errno = EBADF;
3357 else if (fh->target == NULL)
3358 *target_errno = EIO;
3359 else
3360 ret = fh->target->fileio_fstat (fh->target_fd, sb, target_errno);
3362 if (targetdebug)
3363 gdb_printf (gdb_stdlog,
3364 "target_fileio_fstat (%d) = %d (%d)\n",
3365 fd, ret, ret != -1 ? 0 : *target_errno);
3366 return ret;
3369 /* See target.h. */
3372 target_fileio_close (int fd, int *target_errno)
3374 fileio_fh_t *fh = fileio_fd_to_fh (fd);
3375 int ret = -1;
3377 if (fh->is_closed ())
3378 *target_errno = EBADF;
3379 else
3381 if (fh->target != NULL)
3382 ret = fh->target->fileio_close (fh->target_fd,
3383 target_errno);
3384 else
3385 ret = 0;
3386 release_fileio_fd (fd, fh);
3389 if (targetdebug)
3390 gdb_printf (gdb_stdlog,
3391 "target_fileio_close (%d) = %d (%d)\n",
3392 fd, ret, ret != -1 ? 0 : *target_errno);
3393 return ret;
3396 /* See target.h. */
3399 target_fileio_unlink (struct inferior *inf, const char *filename,
3400 int *target_errno)
3402 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3404 int ret = t->fileio_unlink (inf, filename, target_errno);
3406 if (ret == -1 && *target_errno == FILEIO_ENOSYS)
3407 continue;
3409 if (targetdebug)
3410 gdb_printf (gdb_stdlog,
3411 "target_fileio_unlink (%d,%s)"
3412 " = %d (%d)\n",
3413 inf == NULL ? 0 : inf->num, filename,
3414 ret, ret != -1 ? 0 : *target_errno);
3415 return ret;
3418 *target_errno = FILEIO_ENOSYS;
3419 return -1;
3422 /* See target.h. */
3424 gdb::optional<std::string>
3425 target_fileio_readlink (struct inferior *inf, const char *filename,
3426 int *target_errno)
3428 for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3430 gdb::optional<std::string> ret
3431 = t->fileio_readlink (inf, filename, target_errno);
3433 if (!ret.has_value () && *target_errno == FILEIO_ENOSYS)
3434 continue;
3436 if (targetdebug)
3437 gdb_printf (gdb_stdlog,
3438 "target_fileio_readlink (%d,%s)"
3439 " = %s (%d)\n",
3440 inf == NULL ? 0 : inf->num,
3441 filename, ret ? ret->c_str () : "(nil)",
3442 ret ? 0 : *target_errno);
3443 return ret;
3446 *target_errno = FILEIO_ENOSYS;
3447 return {};
3450 /* Like scoped_fd, but specific to target fileio. */
3452 class scoped_target_fd
3454 public:
3455 explicit scoped_target_fd (int fd) noexcept
3456 : m_fd (fd)
3460 ~scoped_target_fd ()
3462 if (m_fd >= 0)
3464 int target_errno;
3466 target_fileio_close (m_fd, &target_errno);
3470 DISABLE_COPY_AND_ASSIGN (scoped_target_fd);
3472 int get () const noexcept
3474 return m_fd;
3477 private:
3478 int m_fd;
3481 /* Read target file FILENAME, in the filesystem as seen by INF. If
3482 INF is NULL, use the filesystem seen by the debugger (GDB or, for
3483 remote targets, the remote stub). Store the result in *BUF_P and
3484 return the size of the transferred data. PADDING additional bytes
3485 are available in *BUF_P. This is a helper function for
3486 target_fileio_read_alloc; see the declaration of that function for
3487 more information. */
3489 static LONGEST
3490 target_fileio_read_alloc_1 (struct inferior *inf, const char *filename,
3491 gdb_byte **buf_p, int padding)
3493 size_t buf_alloc, buf_pos;
3494 gdb_byte *buf;
3495 LONGEST n;
3496 int target_errno;
3498 scoped_target_fd fd (target_fileio_open (inf, filename, FILEIO_O_RDONLY,
3499 0700, false, &target_errno));
3500 if (fd.get () == -1)
3501 return -1;
3503 /* Start by reading up to 4K at a time. The target will throttle
3504 this number down if necessary. */
3505 buf_alloc = 4096;
3506 buf = (gdb_byte *) xmalloc (buf_alloc);
3507 buf_pos = 0;
3508 while (1)
3510 n = target_fileio_pread (fd.get (), &buf[buf_pos],
3511 buf_alloc - buf_pos - padding, buf_pos,
3512 &target_errno);
3513 if (n < 0)
3515 /* An error occurred. */
3516 xfree (buf);
3517 return -1;
3519 else if (n == 0)
3521 /* Read all there was. */
3522 if (buf_pos == 0)
3523 xfree (buf);
3524 else
3525 *buf_p = buf;
3526 return buf_pos;
3529 buf_pos += n;
3531 /* If the buffer is filling up, expand it. */
3532 if (buf_alloc < buf_pos * 2)
3534 buf_alloc *= 2;
3535 buf = (gdb_byte *) xrealloc (buf, buf_alloc);
3538 QUIT;
3542 /* See target.h. */
3544 LONGEST
3545 target_fileio_read_alloc (struct inferior *inf, const char *filename,
3546 gdb_byte **buf_p)
3548 return target_fileio_read_alloc_1 (inf, filename, buf_p, 0);
3551 /* See target.h. */
3553 gdb::unique_xmalloc_ptr<char>
3554 target_fileio_read_stralloc (struct inferior *inf, const char *filename)
3556 gdb_byte *buffer;
3557 char *bufstr;
3558 LONGEST i, transferred;
3560 transferred = target_fileio_read_alloc_1 (inf, filename, &buffer, 1);
3561 bufstr = (char *) buffer;
3563 if (transferred < 0)
3564 return gdb::unique_xmalloc_ptr<char> (nullptr);
3566 if (transferred == 0)
3567 return make_unique_xstrdup ("");
3569 bufstr[transferred] = 0;
3571 /* Check for embedded NUL bytes; but allow trailing NULs. */
3572 for (i = strlen (bufstr); i < transferred; i++)
3573 if (bufstr[i] != 0)
3575 warning (_("target file %s "
3576 "contained unexpected null characters"),
3577 filename);
3578 break;
3581 return gdb::unique_xmalloc_ptr<char> (bufstr);
3585 static int
3586 default_region_ok_for_hw_watchpoint (struct target_ops *self,
3587 CORE_ADDR addr, int len)
3589 return (len <= gdbarch_ptr_bit (target_gdbarch ()) / TARGET_CHAR_BIT);
3592 static int
3593 default_watchpoint_addr_within_range (struct target_ops *target,
3594 CORE_ADDR addr,
3595 CORE_ADDR start, int length)
3597 return addr >= start && addr < start + length;
3600 /* See target.h. */
3602 target_ops *
3603 target_stack::find_beneath (const target_ops *t) const
3605 /* Look for a non-empty slot at stratum levels beneath T's. */
3606 for (int stratum = t->stratum () - 1; stratum >= 0; --stratum)
3607 if (m_stack[stratum] != NULL)
3608 return m_stack[stratum];
3610 return NULL;
3613 /* See target.h. */
3615 struct target_ops *
3616 find_target_at (enum strata stratum)
3618 return current_inferior ()->target_at (stratum);
3623 /* See target.h */
3625 void
3626 target_announce_detach (int from_tty)
3628 pid_t pid;
3629 const char *exec_file;
3631 if (!from_tty)
3632 return;
3634 pid = inferior_ptid.pid ();
3635 exec_file = get_exec_file (0);
3636 if (exec_file == nullptr)
3637 gdb_printf ("Detaching from pid %s\n",
3638 target_pid_to_str (ptid_t (pid)).c_str ());
3639 else
3640 gdb_printf (_("Detaching from program: %s, %s\n"), exec_file,
3641 target_pid_to_str (ptid_t (pid)).c_str ());
3644 /* See target.h */
3646 void
3647 target_announce_attach (int from_tty, int pid)
3649 if (!from_tty)
3650 return;
3652 const char *exec_file = get_exec_file (0);
3654 if (exec_file != nullptr)
3655 gdb_printf ("Attaching to program: %s, %s\n", exec_file,
3656 target_pid_to_str (ptid_t (pid)).c_str ());
3657 else
3658 gdb_printf ("Attaching to %s\n",
3659 target_pid_to_str (ptid_t (pid)).c_str ());
3662 /* The inferior process has died. Long live the inferior! */
3664 void
3665 generic_mourn_inferior (void)
3667 inferior *inf = current_inferior ();
3669 switch_to_no_thread ();
3671 /* Mark breakpoints uninserted in case something tries to delete a
3672 breakpoint while we delete the inferior's threads (which would
3673 fail, since the inferior is long gone). */
3674 mark_breakpoints_out ();
3676 if (inf->pid != 0)
3677 exit_inferior (inf);
3679 /* Note this wipes step-resume breakpoints, so needs to be done
3680 after exit_inferior, which ends up referencing the step-resume
3681 breakpoints through clear_thread_inferior_resources. */
3682 breakpoint_init_inferior (inf_exited);
3684 registers_changed ();
3686 reopen_exec_file ();
3687 reinit_frame_cache ();
3689 if (deprecated_detach_hook)
3690 deprecated_detach_hook ();
3693 /* Convert a normal process ID to a string. Returns the string in a
3694 static buffer. */
3696 std::string
3697 normal_pid_to_str (ptid_t ptid)
3699 return string_printf ("process %d", ptid.pid ());
3702 static std::string
3703 default_pid_to_str (struct target_ops *ops, ptid_t ptid)
3705 return normal_pid_to_str (ptid);
3708 /* Error-catcher for target_find_memory_regions. */
3709 static int
3710 dummy_find_memory_regions (struct target_ops *self,
3711 find_memory_region_ftype ignore1, void *ignore2)
3713 error (_("Command not implemented for this target."));
3714 return 0;
3717 /* Error-catcher for target_make_corefile_notes. */
3718 static gdb::unique_xmalloc_ptr<char>
3719 dummy_make_corefile_notes (struct target_ops *self,
3720 bfd *ignore1, int *ignore2)
3722 error (_("Command not implemented for this target."));
3723 return NULL;
3726 #include "target-delegates.c"
3728 /* The initial current target, so that there is always a semi-valid
3729 current target. */
3731 static dummy_target the_dummy_target;
3733 /* See target.h. */
3735 target_ops *
3736 get_dummy_target ()
3738 return &the_dummy_target;
3741 static const target_info dummy_target_info = {
3742 "None",
3743 N_("None"),
3747 strata
3748 dummy_target::stratum () const
3750 return dummy_stratum;
3753 strata
3754 debug_target::stratum () const
3756 return debug_stratum;
3759 const target_info &
3760 dummy_target::info () const
3762 return dummy_target_info;
3765 const target_info &
3766 debug_target::info () const
3768 return beneath ()->info ();
3773 void
3774 target_close (struct target_ops *targ)
3776 for (inferior *inf : all_inferiors ())
3777 gdb_assert (!inf->target_is_pushed (targ));
3779 fileio_handles_invalidate_target (targ);
3781 targ->close ();
3783 if (targetdebug)
3784 gdb_printf (gdb_stdlog, "target_close ()\n");
3788 target_thread_alive (ptid_t ptid)
3790 return current_inferior ()->top_target ()->thread_alive (ptid);
3793 void
3794 target_update_thread_list (void)
3796 current_inferior ()->top_target ()->update_thread_list ();
3799 void
3800 target_stop (ptid_t ptid)
3802 process_stratum_target *proc_target = current_inferior ()->process_target ();
3804 gdb_assert (!proc_target->commit_resumed_state);
3806 if (!may_stop)
3808 warning (_("May not interrupt or stop the target, ignoring attempt"));
3809 return;
3812 current_inferior ()->top_target ()->stop (ptid);
3815 void
3816 target_interrupt ()
3818 if (!may_stop)
3820 warning (_("May not interrupt or stop the target, ignoring attempt"));
3821 return;
3824 current_inferior ()->top_target ()->interrupt ();
3827 /* See target.h. */
3829 void
3830 target_pass_ctrlc (void)
3832 /* Pass the Ctrl-C to the first target that has a thread
3833 running. */
3834 for (inferior *inf : all_inferiors ())
3836 target_ops *proc_target = inf->process_target ();
3837 if (proc_target == NULL)
3838 continue;
3840 for (thread_info *thr : inf->non_exited_threads ())
3842 /* A thread can be THREAD_STOPPED and executing, while
3843 running an infcall. */
3844 if (thr->state == THREAD_RUNNING || thr->executing ())
3846 /* We can get here quite deep in target layers. Avoid
3847 switching thread context or anything that would
3848 communicate with the target (e.g., to fetch
3849 registers), or flushing e.g., the frame cache. We
3850 just switch inferior in order to be able to call
3851 through the target_stack. */
3852 scoped_restore_current_inferior restore_inferior;
3853 set_current_inferior (inf);
3854 current_inferior ()->top_target ()->pass_ctrlc ();
3855 return;
3861 /* See target.h. */
3863 void
3864 default_target_pass_ctrlc (struct target_ops *ops)
3866 target_interrupt ();
3869 /* See target/target.h. */
3871 void
3872 target_stop_and_wait (ptid_t ptid)
3874 struct target_waitstatus status;
3875 bool was_non_stop = non_stop;
3877 non_stop = true;
3878 target_stop (ptid);
3880 target_wait (ptid, &status, 0);
3882 non_stop = was_non_stop;
3885 /* See target/target.h. */
3887 void
3888 target_continue_no_signal (ptid_t ptid)
3890 target_resume (ptid, 0, GDB_SIGNAL_0);
3893 /* See target/target.h. */
3895 void
3896 target_continue (ptid_t ptid, enum gdb_signal signal)
3898 target_resume (ptid, 0, signal);
3901 /* Concatenate ELEM to LIST, a comma-separated list. */
3903 static void
3904 str_comma_list_concat_elem (std::string *list, const char *elem)
3906 if (!list->empty ())
3907 list->append (", ");
3909 list->append (elem);
3912 /* Helper for target_options_to_string. If OPT is present in
3913 TARGET_OPTIONS, append the OPT_STR (string version of OPT) in RET.
3914 OPT is removed from TARGET_OPTIONS. */
3916 static void
3917 do_option (target_wait_flags *target_options, std::string *ret,
3918 target_wait_flag opt, const char *opt_str)
3920 if ((*target_options & opt) != 0)
3922 str_comma_list_concat_elem (ret, opt_str);
3923 *target_options &= ~opt;
3927 /* See target.h. */
3929 std::string
3930 target_options_to_string (target_wait_flags target_options)
3932 std::string ret;
3934 #define DO_TARG_OPTION(OPT) \
3935 do_option (&target_options, &ret, OPT, #OPT)
3937 DO_TARG_OPTION (TARGET_WNOHANG);
3939 if (target_options != 0)
3940 str_comma_list_concat_elem (&ret, "unknown???");
3942 return ret;
3945 void
3946 target_fetch_registers (struct regcache *regcache, int regno)
3948 current_inferior ()->top_target ()->fetch_registers (regcache, regno);
3949 if (targetdebug)
3950 regcache->debug_print_register ("target_fetch_registers", regno);
3953 void
3954 target_store_registers (struct regcache *regcache, int regno)
3956 if (!may_write_registers)
3957 error (_("Writing to registers is not allowed (regno %d)"), regno);
3959 current_inferior ()->top_target ()->store_registers (regcache, regno);
3960 if (targetdebug)
3962 regcache->debug_print_register ("target_store_registers", regno);
3967 target_core_of_thread (ptid_t ptid)
3969 return current_inferior ()->top_target ()->core_of_thread (ptid);
3973 simple_verify_memory (struct target_ops *ops,
3974 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
3976 LONGEST total_xfered = 0;
3978 while (total_xfered < size)
3980 ULONGEST xfered_len;
3981 enum target_xfer_status status;
3982 gdb_byte buf[1024];
3983 ULONGEST howmuch = std::min<ULONGEST> (sizeof (buf), size - total_xfered);
3985 status = target_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
3986 buf, NULL, lma + total_xfered, howmuch,
3987 &xfered_len);
3988 if (status == TARGET_XFER_OK
3989 && memcmp (data + total_xfered, buf, xfered_len) == 0)
3991 total_xfered += xfered_len;
3992 QUIT;
3994 else
3995 return 0;
3997 return 1;
4000 /* Default implementation of memory verification. */
4002 static int
4003 default_verify_memory (struct target_ops *self,
4004 const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
4006 /* Start over from the top of the target stack. */
4007 return simple_verify_memory (current_inferior ()->top_target (),
4008 data, memaddr, size);
4012 target_verify_memory (const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
4014 target_ops *target = current_inferior ()->top_target ();
4016 return target->verify_memory (data, memaddr, size);
4019 /* The documentation for this function is in its prototype declaration in
4020 target.h. */
4023 target_insert_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
4024 enum target_hw_bp_type rw)
4026 target_ops *target = current_inferior ()->top_target ();
4028 return target->insert_mask_watchpoint (addr, mask, rw);
4031 /* The documentation for this function is in its prototype declaration in
4032 target.h. */
4035 target_remove_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
4036 enum target_hw_bp_type rw)
4038 target_ops *target = current_inferior ()->top_target ();
4040 return target->remove_mask_watchpoint (addr, mask, rw);
4043 /* The documentation for this function is in its prototype declaration
4044 in target.h. */
4047 target_masked_watch_num_registers (CORE_ADDR addr, CORE_ADDR mask)
4049 target_ops *target = current_inferior ()->top_target ();
4051 return target->masked_watch_num_registers (addr, mask);
4054 /* The documentation for this function is in its prototype declaration
4055 in target.h. */
4058 target_ranged_break_num_registers (void)
4060 return current_inferior ()->top_target ()->ranged_break_num_registers ();
4063 /* See target.h. */
4065 struct btrace_target_info *
4066 target_enable_btrace (thread_info *tp, const struct btrace_config *conf)
4068 return current_inferior ()->top_target ()->enable_btrace (tp, conf);
4071 /* See target.h. */
4073 void
4074 target_disable_btrace (struct btrace_target_info *btinfo)
4076 current_inferior ()->top_target ()->disable_btrace (btinfo);
4079 /* See target.h. */
4081 void
4082 target_teardown_btrace (struct btrace_target_info *btinfo)
4084 current_inferior ()->top_target ()->teardown_btrace (btinfo);
4087 /* See target.h. */
4089 enum btrace_error
4090 target_read_btrace (struct btrace_data *btrace,
4091 struct btrace_target_info *btinfo,
4092 enum btrace_read_type type)
4094 target_ops *target = current_inferior ()->top_target ();
4096 return target->read_btrace (btrace, btinfo, type);
4099 /* See target.h. */
4101 const struct btrace_config *
4102 target_btrace_conf (const struct btrace_target_info *btinfo)
4104 return current_inferior ()->top_target ()->btrace_conf (btinfo);
4107 /* See target.h. */
4109 void
4110 target_stop_recording (void)
4112 current_inferior ()->top_target ()->stop_recording ();
4115 /* See target.h. */
4117 void
4118 target_save_record (const char *filename)
4120 current_inferior ()->top_target ()->save_record (filename);
4123 /* See target.h. */
4126 target_supports_delete_record ()
4128 return current_inferior ()->top_target ()->supports_delete_record ();
4131 /* See target.h. */
4133 void
4134 target_delete_record (void)
4136 current_inferior ()->top_target ()->delete_record ();
4139 /* See target.h. */
4141 enum record_method
4142 target_record_method (ptid_t ptid)
4144 return current_inferior ()->top_target ()->record_method (ptid);
4147 /* See target.h. */
4150 target_record_is_replaying (ptid_t ptid)
4152 return current_inferior ()->top_target ()->record_is_replaying (ptid);
4155 /* See target.h. */
4158 target_record_will_replay (ptid_t ptid, int dir)
4160 return current_inferior ()->top_target ()->record_will_replay (ptid, dir);
4163 /* See target.h. */
4165 void
4166 target_record_stop_replaying (void)
4168 current_inferior ()->top_target ()->record_stop_replaying ();
4171 /* See target.h. */
4173 void
4174 target_goto_record_begin (void)
4176 current_inferior ()->top_target ()->goto_record_begin ();
4179 /* See target.h. */
4181 void
4182 target_goto_record_end (void)
4184 current_inferior ()->top_target ()->goto_record_end ();
4187 /* See target.h. */
4189 void
4190 target_goto_record (ULONGEST insn)
4192 current_inferior ()->top_target ()->goto_record (insn);
4195 /* See target.h. */
4197 void
4198 target_insn_history (int size, gdb_disassembly_flags flags)
4200 current_inferior ()->top_target ()->insn_history (size, flags);
4203 /* See target.h. */
4205 void
4206 target_insn_history_from (ULONGEST from, int size,
4207 gdb_disassembly_flags flags)
4209 current_inferior ()->top_target ()->insn_history_from (from, size, flags);
4212 /* See target.h. */
4214 void
4215 target_insn_history_range (ULONGEST begin, ULONGEST end,
4216 gdb_disassembly_flags flags)
4218 current_inferior ()->top_target ()->insn_history_range (begin, end, flags);
4221 /* See target.h. */
4223 void
4224 target_call_history (int size, record_print_flags flags)
4226 current_inferior ()->top_target ()->call_history (size, flags);
4229 /* See target.h. */
4231 void
4232 target_call_history_from (ULONGEST begin, int size, record_print_flags flags)
4234 current_inferior ()->top_target ()->call_history_from (begin, size, flags);
4237 /* See target.h. */
4239 void
4240 target_call_history_range (ULONGEST begin, ULONGEST end, record_print_flags flags)
4242 current_inferior ()->top_target ()->call_history_range (begin, end, flags);
4245 /* See target.h. */
4247 const struct frame_unwind *
4248 target_get_unwinder (void)
4250 return current_inferior ()->top_target ()->get_unwinder ();
4253 /* See target.h. */
4255 const struct frame_unwind *
4256 target_get_tailcall_unwinder (void)
4258 return current_inferior ()->top_target ()->get_tailcall_unwinder ();
4261 /* See target.h. */
4263 void
4264 target_prepare_to_generate_core (void)
4266 current_inferior ()->top_target ()->prepare_to_generate_core ();
4269 /* See target.h. */
4271 void
4272 target_done_generating_core (void)
4274 current_inferior ()->top_target ()->done_generating_core ();
4279 static char targ_desc[] =
4280 "Names of targets and files being debugged.\nShows the entire \
4281 stack of targets currently in use (including the exec-file,\n\
4282 core-file, and process, if any), as well as the symbol file name.";
4284 static void
4285 default_rcmd (struct target_ops *self, const char *command,
4286 struct ui_file *output)
4288 error (_("\"monitor\" command not supported by this target."));
4291 static void
4292 do_monitor_command (const char *cmd, int from_tty)
4294 target_rcmd (cmd, gdb_stdtarg);
4297 /* Erases all the memory regions marked as flash. CMD and FROM_TTY are
4298 ignored. */
4300 void
4301 flash_erase_command (const char *cmd, int from_tty)
4303 /* Used to communicate termination of flash operations to the target. */
4304 bool found_flash_region = false;
4305 struct gdbarch *gdbarch = target_gdbarch ();
4307 std::vector<mem_region> mem_regions = target_memory_map ();
4309 /* Iterate over all memory regions. */
4310 for (const mem_region &m : mem_regions)
4312 /* Is this a flash memory region? */
4313 if (m.attrib.mode == MEM_FLASH)
4315 found_flash_region = true;
4316 target_flash_erase (m.lo, m.hi - m.lo);
4318 ui_out_emit_tuple tuple_emitter (current_uiout, "erased-regions");
4320 current_uiout->message (_("Erasing flash memory region at address "));
4321 current_uiout->field_core_addr ("address", gdbarch, m.lo);
4322 current_uiout->message (", size = ");
4323 current_uiout->field_string ("size", hex_string (m.hi - m.lo));
4324 current_uiout->message ("\n");
4328 /* Did we do any flash operations? If so, we need to finalize them. */
4329 if (found_flash_region)
4330 target_flash_done ();
4331 else
4332 current_uiout->message (_("No flash memory regions found.\n"));
4335 /* Print the name of each layers of our target stack. */
4337 static void
4338 maintenance_print_target_stack (const char *cmd, int from_tty)
4340 gdb_printf (_("The current target stack is:\n"));
4342 for (target_ops *t = current_inferior ()->top_target ();
4343 t != NULL;
4344 t = t->beneath ())
4346 if (t->stratum () == debug_stratum)
4347 continue;
4348 gdb_printf (" - %s (%s)\n", t->shortname (), t->longname ());
4352 /* See target.h. */
4354 void
4355 target_async (int enable)
4357 /* If we are trying to enable async mode then it must be the case that
4358 async mode is possible for this target. */
4359 gdb_assert (!enable || target_can_async_p ());
4360 infrun_async (enable);
4361 current_inferior ()->top_target ()->async (enable);
4364 /* See target.h. */
4366 void
4367 target_thread_events (int enable)
4369 current_inferior ()->top_target ()->thread_events (enable);
4372 /* Controls if targets can report that they can/are async. This is
4373 just for maintainers to use when debugging gdb. */
4374 bool target_async_permitted = true;
4376 static void
4377 set_maint_target_async (bool permitted)
4379 if (have_live_inferiors ())
4380 error (_("Cannot change this setting while the inferior is running."));
4382 target_async_permitted = permitted;
4385 static bool
4386 get_maint_target_async ()
4388 return target_async_permitted;
4391 static void
4392 show_maint_target_async (ui_file *file, int from_tty,
4393 cmd_list_element *c, const char *value)
4395 gdb_printf (file,
4396 _("Controlling the inferior in "
4397 "asynchronous mode is %s.\n"), value);
4400 /* Return true if the target operates in non-stop mode even with "set
4401 non-stop off". */
4403 static int
4404 target_always_non_stop_p (void)
4406 return current_inferior ()->top_target ()->always_non_stop_p ();
4409 /* See target.h. */
4411 bool
4412 target_is_non_stop_p ()
4414 return ((non_stop
4415 || target_non_stop_enabled == AUTO_BOOLEAN_TRUE
4416 || (target_non_stop_enabled == AUTO_BOOLEAN_AUTO
4417 && target_always_non_stop_p ()))
4418 && target_can_async_p ());
4421 /* See target.h. */
4423 bool
4424 exists_non_stop_target ()
4426 if (target_is_non_stop_p ())
4427 return true;
4429 scoped_restore_current_thread restore_thread;
4431 for (inferior *inf : all_inferiors ())
4433 switch_to_inferior_no_thread (inf);
4434 if (target_is_non_stop_p ())
4435 return true;
4438 return false;
4441 /* Controls if targets can report that they always run in non-stop
4442 mode. This is just for maintainers to use when debugging gdb. */
4443 enum auto_boolean target_non_stop_enabled = AUTO_BOOLEAN_AUTO;
4445 /* Set callback for maint target-non-stop setting. */
4447 static void
4448 set_maint_target_non_stop (auto_boolean enabled)
4450 if (have_live_inferiors ())
4451 error (_("Cannot change this setting while the inferior is running."));
4453 target_non_stop_enabled = enabled;
4456 /* Get callback for maint target-non-stop setting. */
4458 static auto_boolean
4459 get_maint_target_non_stop ()
4461 return target_non_stop_enabled;
4464 static void
4465 show_maint_target_non_stop (ui_file *file, int from_tty,
4466 cmd_list_element *c, const char *value)
4468 if (target_non_stop_enabled == AUTO_BOOLEAN_AUTO)
4469 gdb_printf (file,
4470 _("Whether the target is always in non-stop mode "
4471 "is %s (currently %s).\n"), value,
4472 target_always_non_stop_p () ? "on" : "off");
4473 else
4474 gdb_printf (file,
4475 _("Whether the target is always in non-stop mode "
4476 "is %s.\n"), value);
4479 /* Temporary copies of permission settings. */
4481 static bool may_write_registers_1 = true;
4482 static bool may_write_memory_1 = true;
4483 static bool may_insert_breakpoints_1 = true;
4484 static bool may_insert_tracepoints_1 = true;
4485 static bool may_insert_fast_tracepoints_1 = true;
4486 static bool may_stop_1 = true;
4488 /* Make the user-set values match the real values again. */
4490 void
4491 update_target_permissions (void)
4493 may_write_registers_1 = may_write_registers;
4494 may_write_memory_1 = may_write_memory;
4495 may_insert_breakpoints_1 = may_insert_breakpoints;
4496 may_insert_tracepoints_1 = may_insert_tracepoints;
4497 may_insert_fast_tracepoints_1 = may_insert_fast_tracepoints;
4498 may_stop_1 = may_stop;
4501 /* The one function handles (most of) the permission flags in the same
4502 way. */
4504 static void
4505 set_target_permissions (const char *args, int from_tty,
4506 struct cmd_list_element *c)
4508 if (target_has_execution ())
4510 update_target_permissions ();
4511 error (_("Cannot change this setting while the inferior is running."));
4514 /* Make the real values match the user-changed values. */
4515 may_write_registers = may_write_registers_1;
4516 may_insert_breakpoints = may_insert_breakpoints_1;
4517 may_insert_tracepoints = may_insert_tracepoints_1;
4518 may_insert_fast_tracepoints = may_insert_fast_tracepoints_1;
4519 may_stop = may_stop_1;
4520 update_observer_mode ();
4523 /* Set memory write permission independently of observer mode. */
4525 static void
4526 set_write_memory_permission (const char *args, int from_tty,
4527 struct cmd_list_element *c)
4529 /* Make the real values match the user-changed values. */
4530 may_write_memory = may_write_memory_1;
4531 update_observer_mode ();
4534 void _initialize_target ();
4536 void
4537 _initialize_target ()
4539 the_debug_target = new debug_target ();
4541 add_info ("target", info_target_command, targ_desc);
4542 add_info ("files", info_target_command, targ_desc);
4544 add_setshow_zuinteger_cmd ("target", class_maintenance, &targetdebug, _("\
4545 Set target debugging."), _("\
4546 Show target debugging."), _("\
4547 When non-zero, target debugging is enabled. Higher numbers are more\n\
4548 verbose."),
4549 set_targetdebug,
4550 show_targetdebug,
4551 &setdebuglist, &showdebuglist);
4553 add_setshow_boolean_cmd ("trust-readonly-sections", class_support,
4554 &trust_readonly, _("\
4555 Set mode for reading from readonly sections."), _("\
4556 Show mode for reading from readonly sections."), _("\
4557 When this mode is on, memory reads from readonly sections (such as .text)\n\
4558 will be read from the object file instead of from the target. This will\n\
4559 result in significant performance improvement for remote targets."),
4560 NULL,
4561 show_trust_readonly,
4562 &setlist, &showlist);
4564 add_com ("monitor", class_obscure, do_monitor_command,
4565 _("Send a command to the remote monitor (remote targets only)."));
4567 add_cmd ("target-stack", class_maintenance, maintenance_print_target_stack,
4568 _("Print the name of each layer of the internal target stack."),
4569 &maintenanceprintlist);
4571 add_setshow_boolean_cmd ("target-async", no_class,
4572 _("\
4573 Set whether gdb controls the inferior in asynchronous mode."), _("\
4574 Show whether gdb controls the inferior in asynchronous mode."), _("\
4575 Tells gdb whether to control the inferior in asynchronous mode."),
4576 set_maint_target_async,
4577 get_maint_target_async,
4578 show_maint_target_async,
4579 &maintenance_set_cmdlist,
4580 &maintenance_show_cmdlist);
4582 add_setshow_auto_boolean_cmd ("target-non-stop", no_class,
4583 _("\
4584 Set whether gdb always controls the inferior in non-stop mode."), _("\
4585 Show whether gdb always controls the inferior in non-stop mode."), _("\
4586 Tells gdb whether to control the inferior in non-stop mode."),
4587 set_maint_target_non_stop,
4588 get_maint_target_non_stop,
4589 show_maint_target_non_stop,
4590 &maintenance_set_cmdlist,
4591 &maintenance_show_cmdlist);
4593 add_setshow_boolean_cmd ("may-write-registers", class_support,
4594 &may_write_registers_1, _("\
4595 Set permission to write into registers."), _("\
4596 Show permission to write into registers."), _("\
4597 When this permission is on, GDB may write into the target's registers.\n\
4598 Otherwise, any sort of write attempt will result in an error."),
4599 set_target_permissions, NULL,
4600 &setlist, &showlist);
4602 add_setshow_boolean_cmd ("may-write-memory", class_support,
4603 &may_write_memory_1, _("\
4604 Set permission to write into target memory."), _("\
4605 Show permission to write into target memory."), _("\
4606 When this permission is on, GDB may write into the target's memory.\n\
4607 Otherwise, any sort of write attempt will result in an error."),
4608 set_write_memory_permission, NULL,
4609 &setlist, &showlist);
4611 add_setshow_boolean_cmd ("may-insert-breakpoints", class_support,
4612 &may_insert_breakpoints_1, _("\
4613 Set permission to insert breakpoints in the target."), _("\
4614 Show permission to insert breakpoints in the target."), _("\
4615 When this permission is on, GDB may insert breakpoints in the program.\n\
4616 Otherwise, any sort of insertion attempt will result in an error."),
4617 set_target_permissions, NULL,
4618 &setlist, &showlist);
4620 add_setshow_boolean_cmd ("may-insert-tracepoints", class_support,
4621 &may_insert_tracepoints_1, _("\
4622 Set permission to insert tracepoints in the target."), _("\
4623 Show permission to insert tracepoints in the target."), _("\
4624 When this permission is on, GDB may insert tracepoints in the program.\n\
4625 Otherwise, any sort of insertion attempt will result in an error."),
4626 set_target_permissions, NULL,
4627 &setlist, &showlist);
4629 add_setshow_boolean_cmd ("may-insert-fast-tracepoints", class_support,
4630 &may_insert_fast_tracepoints_1, _("\
4631 Set permission to insert fast tracepoints in the target."), _("\
4632 Show permission to insert fast tracepoints in the target."), _("\
4633 When this permission is on, GDB may insert fast tracepoints.\n\
4634 Otherwise, any sort of insertion attempt will result in an error."),
4635 set_target_permissions, NULL,
4636 &setlist, &showlist);
4638 add_setshow_boolean_cmd ("may-interrupt", class_support,
4639 &may_stop_1, _("\
4640 Set permission to interrupt or signal the target."), _("\
4641 Show permission to interrupt or signal the target."), _("\
4642 When this permission is on, GDB may interrupt/stop the target's execution.\n\
4643 Otherwise, any attempt to interrupt or stop will be ignored."),
4644 set_target_permissions, NULL,
4645 &setlist, &showlist);
4647 add_com ("flash-erase", no_class, flash_erase_command,
4648 _("Erase all flash memory regions."));
4650 add_setshow_boolean_cmd ("auto-connect-native-target", class_support,
4651 &auto_connect_native_target, _("\
4652 Set whether GDB may automatically connect to the native target."), _("\
4653 Show whether GDB may automatically connect to the native target."), _("\
4654 When on, and GDB is not connected to a target yet, GDB\n\
4655 attempts \"run\" and other commands with the native target."),
4656 NULL, show_auto_connect_native_target,
4657 &setlist, &showlist);