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