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