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