xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/infcall.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Perform an inferior function call, for GDB, the GNU debugger.
2 
3    Copyright (C) 1986-2023 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "defs.h"
21 #include "infcall.h"
22 #include "breakpoint.h"
23 #include "tracepoint.h"
24 #include "target.h"
25 #include "regcache.h"
26 #include "inferior.h"
27 #include "infrun.h"
28 #include "block.h"
29 #include "gdbcore.h"
30 #include "language.h"
31 #include "objfiles.h"
32 #include "gdbcmd.h"
33 #include "command.h"
34 #include "dummy-frame.h"
35 #include "ada-lang.h"
36 #include "f-lang.h"
37 #include "gdbthread.h"
38 #include "event-top.h"
39 #include "observable.h"
40 #include "top.h"
41 #include "interps.h"
42 #include "thread-fsm.h"
43 #include <algorithm>
44 #include "gdbsupport/scope-exit.h"
45 #include <list>
46 
47 /* True if we are debugging inferior calls.  */
48 
49 static bool debug_infcall = false;
50 
51 /* Print an "infcall" debug statement.  */
52 
53 #define infcall_debug_printf(fmt, ...) \
54   debug_prefixed_printf_cond (debug_infcall, "infcall", fmt, ##__VA_ARGS__)
55 
56 /* Print "infcall" enter/exit debug statements.  */
57 
58 #define INFCALL_SCOPED_DEBUG_ENTER_EXIT \
59   scoped_debug_enter_exit (debug_infcall, "infcall")
60 
61 /* Print "infcall" start/end debug statements.  */
62 
63 #define INFCALL_SCOPED_DEBUG_START_END(fmt, ...) \
64   scoped_debug_start_end (debug_infrun, "infcall", fmt, ##__VA_ARGS__)
65 
66 /* Implement 'show debug infcall'.  */
67 
68 static void
69 show_debug_infcall (struct ui_file *file, int from_tty,
70 		   struct cmd_list_element *c, const char *value)
71 {
72   gdb_printf (file, _("Inferior call debugging is %s.\n"), value);
73 }
74 
75 /* If we can't find a function's name from its address,
76    we print this instead.  */
77 #define RAW_FUNCTION_ADDRESS_FORMAT "at 0x%s"
78 #define RAW_FUNCTION_ADDRESS_SIZE (sizeof (RAW_FUNCTION_ADDRESS_FORMAT) \
79 				   + 2 * sizeof (CORE_ADDR))
80 
81 /* NOTE: cagney/2003-04-16: What's the future of this code?
82 
83    GDB needs an asynchronous expression evaluator, that means an
84    asynchronous inferior function call implementation, and that in
85    turn means restructuring the code so that it is event driven.  */
86 
87 static bool may_call_functions_p = true;
88 static void
89 show_may_call_functions_p (struct ui_file *file, int from_tty,
90 			   struct cmd_list_element *c,
91 			   const char *value)
92 {
93   gdb_printf (file,
94 	      _("Permission to call functions in the program is %s.\n"),
95 	      value);
96 }
97 
98 /* How you should pass arguments to a function depends on whether it
99    was defined in K&R style or prototype style.  If you define a
100    function using the K&R syntax that takes a `float' argument, then
101    callers must pass that argument as a `double'.  If you define the
102    function using the prototype syntax, then you must pass the
103    argument as a `float', with no promotion.
104 
105    Unfortunately, on certain older platforms, the debug info doesn't
106    indicate reliably how each function was defined.  A function type's
107    TYPE_PROTOTYPED flag may be clear, even if the function was defined
108    in prototype style.  When calling a function whose TYPE_PROTOTYPED
109    flag is clear, GDB consults this flag to decide what to do.
110 
111    For modern targets, it is proper to assume that, if the prototype
112    flag is clear, that can be trusted: `float' arguments should be
113    promoted to `double'.  For some older targets, if the prototype
114    flag is clear, that doesn't tell us anything.  The default is to
115    trust the debug information; the user can override this behavior
116    with "set coerce-float-to-double 0".  */
117 
118 static bool coerce_float_to_double_p = true;
119 static void
120 show_coerce_float_to_double_p (struct ui_file *file, int from_tty,
121 			       struct cmd_list_element *c, const char *value)
122 {
123   gdb_printf (file,
124 	      _("Coercion of floats to doubles "
125 		"when calling functions is %s.\n"),
126 	      value);
127 }
128 
129 /* This boolean tells what gdb should do if a signal is received while
130    in a function called from gdb (call dummy).  If set, gdb unwinds
131    the stack and restore the context to what as it was before the
132    call.
133 
134    The default is to stop in the frame where the signal was received.  */
135 
136 static bool unwind_on_signal_p = false;
137 static void
138 show_unwind_on_signal_p (struct ui_file *file, int from_tty,
139 			 struct cmd_list_element *c, const char *value)
140 {
141   gdb_printf (file,
142 	      _("Unwinding of stack if a signal is "
143 		"received while in a call dummy is %s.\n"),
144 	      value);
145 }
146 
147 /* This boolean tells what gdb should do if a std::terminate call is
148    made while in a function called from gdb (call dummy).
149    As the confines of a single dummy stack prohibit out-of-frame
150    handlers from handling a raised exception, and as out-of-frame
151    handlers are common in C++, this can lead to no handler being found
152    by the unwinder, and a std::terminate call.  This is a false positive.
153    If set, gdb unwinds the stack and restores the context to what it
154    was before the call.
155 
156    The default is to unwind the frame if a std::terminate call is
157    made.  */
158 
159 static bool unwind_on_terminating_exception_p = true;
160 
161 static void
162 show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
163 					struct cmd_list_element *c,
164 					const char *value)
165 
166 {
167   gdb_printf (file,
168 	      _("Unwind stack if a C++ exception is "
169 		"unhandled while in a call dummy is %s.\n"),
170 	      value);
171 }
172 
173 /* Perform the standard coercions that are specified
174    for arguments to be passed to C, Ada or Fortran functions.
175 
176    If PARAM_TYPE is non-NULL, it is the expected parameter type.
177    IS_PROTOTYPED is non-zero if the function declaration is prototyped.  */
178 
179 static struct value *
180 value_arg_coerce (struct gdbarch *gdbarch, struct value *arg,
181 		  struct type *param_type, int is_prototyped)
182 {
183   const struct builtin_type *builtin = builtin_type (gdbarch);
184   struct type *arg_type = check_typedef (value_type (arg));
185   struct type *type
186     = param_type ? check_typedef (param_type) : arg_type;
187 
188   /* Perform any Ada- and Fortran-specific coercion first.  */
189   if (current_language->la_language == language_ada)
190     arg = ada_convert_actual (arg, type);
191   else if (current_language->la_language == language_fortran)
192     type = fortran_preserve_arg_pointer (arg, type);
193 
194   /* Force the value to the target if we will need its address.  At
195      this point, we could allocate arguments on the stack instead of
196      calling malloc if we knew that their addresses would not be
197      saved by the called function.  */
198   arg = value_coerce_to_target (arg);
199 
200   switch (type->code ())
201     {
202     case TYPE_CODE_REF:
203     case TYPE_CODE_RVALUE_REF:
204       {
205 	struct value *new_value;
206 
207 	if (TYPE_IS_REFERENCE (arg_type))
208 	  return value_cast_pointers (type, arg, 0);
209 
210 	/* Cast the value to the reference's target type, and then
211 	   convert it back to a reference.  This will issue an error
212 	   if the value was not previously in memory - in some cases
213 	   we should clearly be allowing this, but how?  */
214 	new_value = value_cast (type->target_type (), arg);
215 	new_value = value_ref (new_value, type->code ());
216 	return new_value;
217       }
218     case TYPE_CODE_INT:
219     case TYPE_CODE_CHAR:
220     case TYPE_CODE_BOOL:
221     case TYPE_CODE_ENUM:
222       /* If we don't have a prototype, coerce to integer type if necessary.  */
223       if (!is_prototyped)
224 	{
225 	  if (type->length () < builtin->builtin_int->length ())
226 	    type = builtin->builtin_int;
227 	}
228       /* Currently all target ABIs require at least the width of an integer
229 	 type for an argument.  We may have to conditionalize the following
230 	 type coercion for future targets.  */
231       if (type->length () < builtin->builtin_int->length ())
232 	type = builtin->builtin_int;
233       break;
234     case TYPE_CODE_FLT:
235       if (!is_prototyped && coerce_float_to_double_p)
236 	{
237 	  if (type->length () < builtin->builtin_double->length ())
238 	    type = builtin->builtin_double;
239 	  else if (type->length () > builtin->builtin_double->length ())
240 	    type = builtin->builtin_long_double;
241 	}
242       break;
243     case TYPE_CODE_FUNC:
244       type = lookup_pointer_type (type);
245       break;
246     case TYPE_CODE_ARRAY:
247       /* Arrays are coerced to pointers to their first element, unless
248 	 they are vectors, in which case we want to leave them alone,
249 	 because they are passed by value.  */
250       if (current_language->c_style_arrays_p ())
251 	if (!type->is_vector ())
252 	  type = lookup_pointer_type (type->target_type ());
253       break;
254     case TYPE_CODE_UNDEF:
255     case TYPE_CODE_PTR:
256     case TYPE_CODE_STRUCT:
257     case TYPE_CODE_UNION:
258     case TYPE_CODE_VOID:
259     case TYPE_CODE_SET:
260     case TYPE_CODE_RANGE:
261     case TYPE_CODE_STRING:
262     case TYPE_CODE_ERROR:
263     case TYPE_CODE_MEMBERPTR:
264     case TYPE_CODE_METHODPTR:
265     case TYPE_CODE_METHOD:
266     case TYPE_CODE_COMPLEX:
267     default:
268       break;
269     }
270 
271   return value_cast (type, arg);
272 }
273 
274 /* See infcall.h.  */
275 
276 CORE_ADDR
277 find_function_addr (struct value *function,
278 		    struct type **retval_type,
279 		    struct type **function_type)
280 {
281   struct type *ftype = check_typedef (value_type (function));
282   struct gdbarch *gdbarch = ftype->arch ();
283   struct type *value_type = NULL;
284   /* Initialize it just to avoid a GCC false warning.  */
285   CORE_ADDR funaddr = 0;
286 
287   /* If it's a member function, just look at the function
288      part of it.  */
289 
290   /* Determine address to call.  */
291   if (ftype->code () == TYPE_CODE_FUNC
292       || ftype->code () == TYPE_CODE_METHOD)
293     funaddr = value_address (function);
294   else if (ftype->code () == TYPE_CODE_PTR)
295     {
296       funaddr = value_as_address (function);
297       ftype = check_typedef (ftype->target_type ());
298       if (ftype->code () == TYPE_CODE_FUNC
299 	  || ftype->code () == TYPE_CODE_METHOD)
300 	funaddr = gdbarch_convert_from_func_ptr_addr
301 	  (gdbarch, funaddr, current_inferior ()->top_target());
302     }
303   if (ftype->code () == TYPE_CODE_FUNC
304       || ftype->code () == TYPE_CODE_METHOD)
305     {
306       if (ftype->is_gnu_ifunc ())
307 	{
308 	  CORE_ADDR resolver_addr = funaddr;
309 
310 	  /* Resolve the ifunc.  Note this may call the resolver
311 	     function in the inferior.  */
312 	  funaddr = gnu_ifunc_resolve_addr (gdbarch, resolver_addr);
313 
314 	  /* Skip querying the function symbol if no RETVAL_TYPE or
315 	     FUNCTION_TYPE have been asked for.  */
316 	  if (retval_type != NULL || function_type != NULL)
317 	    {
318 	      type *target_ftype = find_function_type (funaddr);
319 	      /* If we don't have debug info for the target function,
320 		 see if we can instead extract the target function's
321 		 type from the type that the resolver returns.  */
322 	      if (target_ftype == NULL)
323 		target_ftype = find_gnu_ifunc_target_type (resolver_addr);
324 	      if (target_ftype != NULL)
325 		{
326 		  value_type = check_typedef (target_ftype)->target_type ();
327 		  ftype = target_ftype;
328 		}
329 	    }
330 	}
331       else
332 	value_type = ftype->target_type ();
333     }
334   else if (ftype->code () == TYPE_CODE_INT)
335     {
336       /* Handle the case of functions lacking debugging info.
337 	 Their values are characters since their addresses are char.  */
338       if (ftype->length () == 1)
339 	funaddr = value_as_address (value_addr (function));
340       else
341 	{
342 	  /* Handle function descriptors lacking debug info.  */
343 	  int found_descriptor = 0;
344 
345 	  funaddr = 0;	/* pacify "gcc -Werror" */
346 	  if (VALUE_LVAL (function) == lval_memory)
347 	    {
348 	      CORE_ADDR nfunaddr;
349 
350 	      funaddr = value_as_address (value_addr (function));
351 	      nfunaddr = funaddr;
352 	      funaddr = gdbarch_convert_from_func_ptr_addr
353 		(gdbarch, funaddr, current_inferior ()->top_target ());
354 	      if (funaddr != nfunaddr)
355 		found_descriptor = 1;
356 	    }
357 	  if (!found_descriptor)
358 	    /* Handle integer used as address of a function.  */
359 	    funaddr = (CORE_ADDR) value_as_long (function);
360 	}
361     }
362   else
363     error (_("Invalid data type for function to be called."));
364 
365   if (retval_type != NULL)
366     *retval_type = value_type;
367   if (function_type != NULL)
368     *function_type = ftype;
369   return funaddr + gdbarch_deprecated_function_start_offset (gdbarch);
370 }
371 
372 /* For CALL_DUMMY_ON_STACK, push a breakpoint sequence that the called
373    function returns to.  */
374 
375 static CORE_ADDR
376 push_dummy_code (struct gdbarch *gdbarch,
377 		 CORE_ADDR sp, CORE_ADDR funaddr,
378 		 gdb::array_view<value *> args,
379 		 struct type *value_type,
380 		 CORE_ADDR *real_pc, CORE_ADDR *bp_addr,
381 		 struct regcache *regcache)
382 {
383   gdb_assert (gdbarch_push_dummy_code_p (gdbarch));
384 
385   return gdbarch_push_dummy_code (gdbarch, sp, funaddr,
386 				  args.data (), args.size (),
387 				  value_type, real_pc, bp_addr,
388 				  regcache);
389 }
390 
391 /* See infcall.h.  */
392 
393 void
394 error_call_unknown_return_type (const char *func_name)
395 {
396   if (func_name != NULL)
397     error (_("'%s' has unknown return type; "
398 	     "cast the call to its declared return type"),
399 	   func_name);
400   else
401     error (_("function has unknown return type; "
402 	     "cast the call to its declared return type"));
403 }
404 
405 /* Fetch the name of the function at FUNADDR.
406    This is used in printing an error message for call_function_by_hand.
407    BUF is used to print FUNADDR in hex if the function name cannot be
408    determined.  It must be large enough to hold formatted result of
409    RAW_FUNCTION_ADDRESS_FORMAT.  */
410 
411 static const char *
412 get_function_name (CORE_ADDR funaddr, char *buf, int buf_size)
413 {
414   {
415     struct symbol *symbol = find_pc_function (funaddr);
416 
417     if (symbol)
418       return symbol->print_name ();
419   }
420 
421   {
422     /* Try the minimal symbols.  */
423     struct bound_minimal_symbol msymbol = lookup_minimal_symbol_by_pc (funaddr);
424 
425     if (msymbol.minsym)
426       return msymbol.minsym->print_name ();
427   }
428 
429   {
430     std::string tmp = string_printf (_(RAW_FUNCTION_ADDRESS_FORMAT),
431 				     hex_string (funaddr));
432 
433     gdb_assert (tmp.length () + 1 <= buf_size);
434     return strcpy (buf, tmp.c_str ());
435   }
436 }
437 
438 /* All the meta data necessary to extract the call's return value.  */
439 
440 struct call_return_meta_info
441 {
442   /* The caller frame's architecture.  */
443   struct gdbarch *gdbarch;
444 
445   /* The called function.  */
446   struct value *function;
447 
448   /* The return value's type.  */
449   struct type *value_type;
450 
451   /* Are we returning a value using a structure return or a normal
452      value return?  */
453   int struct_return_p;
454 
455   /* If using a structure return, this is the structure's address.  */
456   CORE_ADDR struct_addr;
457 };
458 
459 /* Extract the called function's return value.  */
460 
461 static struct value *
462 get_call_return_value (struct call_return_meta_info *ri)
463 {
464   struct value *retval = NULL;
465   thread_info *thr = inferior_thread ();
466   bool stack_temporaries = thread_stack_temporaries_enabled_p (thr);
467 
468   if (ri->value_type->code () == TYPE_CODE_VOID)
469     retval = allocate_value (ri->value_type);
470   else if (ri->struct_return_p)
471     {
472       if (stack_temporaries)
473 	{
474 	  retval = value_from_contents_and_address (ri->value_type, NULL,
475 						    ri->struct_addr);
476 	  push_thread_stack_temporary (thr, retval);
477 	}
478       else
479 	{
480 	  retval = allocate_value (ri->value_type);
481 	  read_value_memory (retval, 0, 1, ri->struct_addr,
482 			     value_contents_raw (retval).data (),
483 			     ri->value_type->length ());
484 	}
485     }
486   else
487     {
488       retval = allocate_value (ri->value_type);
489       gdbarch_return_value (ri->gdbarch, ri->function, ri->value_type,
490 			    get_current_regcache (),
491 			    value_contents_raw (retval).data (), NULL);
492       if (stack_temporaries && class_or_union_p (ri->value_type))
493 	{
494 	  /* Values of class type returned in registers are copied onto
495 	     the stack and their lval_type set to lval_memory.  This is
496 	     required because further evaluation of the expression
497 	     could potentially invoke methods on the return value
498 	     requiring GDB to evaluate the "this" pointer.  To evaluate
499 	     the this pointer, GDB needs the memory address of the
500 	     value.  */
501 	  value_force_lval (retval, ri->struct_addr);
502 	  push_thread_stack_temporary (thr, retval);
503 	}
504     }
505 
506   gdb_assert (retval != NULL);
507   return retval;
508 }
509 
510 /* Data for the FSM that manages an infcall.  It's main job is to
511    record the called function's return value.  */
512 
513 struct call_thread_fsm : public thread_fsm
514 {
515   /* All the info necessary to be able to extract the return
516      value.  */
517   struct call_return_meta_info return_meta_info;
518 
519   /* The called function's return value.  This is extracted from the
520      target before the dummy frame is popped.  */
521   struct value *return_value = nullptr;
522 
523   /* The top level that started the infcall (and is synchronously
524      waiting for it to end).  */
525   struct ui *waiting_ui;
526 
527   call_thread_fsm (struct ui *waiting_ui, struct interp *cmd_interp,
528 		   struct gdbarch *gdbarch, struct value *function,
529 		   struct type *value_type,
530 		   int struct_return_p, CORE_ADDR struct_addr);
531 
532   bool should_stop (struct thread_info *thread) override;
533 
534   bool should_notify_stop () override;
535 };
536 
537 /* Allocate a new call_thread_fsm object.  */
538 
539 call_thread_fsm::call_thread_fsm (struct ui *waiting_ui,
540 				  struct interp *cmd_interp,
541 				  struct gdbarch *gdbarch,
542 				  struct value *function,
543 				  struct type *value_type,
544 				  int struct_return_p, CORE_ADDR struct_addr)
545   : thread_fsm (cmd_interp),
546     waiting_ui (waiting_ui)
547 {
548   return_meta_info.gdbarch = gdbarch;
549   return_meta_info.function = function;
550   return_meta_info.value_type = value_type;
551   return_meta_info.struct_return_p = struct_return_p;
552   return_meta_info.struct_addr = struct_addr;
553 }
554 
555 /* Implementation of should_stop method for infcalls.  */
556 
557 bool
558 call_thread_fsm::should_stop (struct thread_info *thread)
559 {
560   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
561 
562   if (stop_stack_dummy == STOP_STACK_DUMMY)
563     {
564       /* Done.  */
565       set_finished ();
566 
567       /* Stash the return value before the dummy frame is popped and
568 	 registers are restored to what they were before the
569 	 call..  */
570       return_value = get_call_return_value (&return_meta_info);
571 
572       /* Break out of wait_sync_command_done.  */
573       scoped_restore save_ui = make_scoped_restore (&current_ui, waiting_ui);
574       target_terminal::ours ();
575       waiting_ui->prompt_state = PROMPT_NEEDED;
576     }
577 
578   return true;
579 }
580 
581 /* Implementation of should_notify_stop method for infcalls.  */
582 
583 bool
584 call_thread_fsm::should_notify_stop ()
585 {
586   if (finished_p ())
587     {
588       /* Infcall succeeded.  Be silent and proceed with evaluating the
589 	 expression.  */
590       return false;
591     }
592 
593   /* Something wrong happened.  E.g., an unexpected breakpoint
594      triggered, or a signal was intercepted.  Notify the stop.  */
595   return true;
596 }
597 
598 /* Subroutine of call_function_by_hand to simplify it.
599    Start up the inferior and wait for it to stop.
600    Return the exception if there's an error, or an exception with
601    reason >= 0 if there's no error.
602 
603    This is done inside a TRY_CATCH so the caller needn't worry about
604    thrown errors.  The caller should rethrow if there's an error.  */
605 
606 static struct gdb_exception
607 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
608 		   struct thread_info *call_thread, CORE_ADDR real_pc)
609 {
610   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
611 
612   struct gdb_exception caught_error;
613   ptid_t call_thread_ptid = call_thread->ptid;
614   int was_running = call_thread->state == THREAD_RUNNING;
615 
616   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
617 			core_addr_to_string (real_pc),
618 			call_thread_ptid.to_string ().c_str (),
619 			was_running);
620 
621   current_ui->unregister_file_handler ();
622 
623   scoped_restore restore_in_infcall
624     = make_scoped_restore (&call_thread->control.in_infcall, 1);
625 
626   clear_proceed_status (0);
627 
628   /* Associate the FSM with the thread after clear_proceed_status
629      (otherwise it'd clear this FSM).  */
630   call_thread->set_thread_fsm (std::move (sm));
631 
632   disable_watchpoints_before_interactive_call_start ();
633 
634   /* We want to print return value, please...  */
635   call_thread->control.proceed_to_finish = 1;
636 
637   try
638     {
639       /* Infcalls run synchronously, in the foreground.  */
640       scoped_restore restore_prompt_state
641 	= make_scoped_restore (&current_ui->prompt_state, PROMPT_BLOCKED);
642 
643       /* So that we don't print the prompt prematurely in
644 	 fetch_inferior_event.  */
645       scoped_restore restore_ui_async
646 	= make_scoped_restore (&current_ui->async, 0);
647 
648       proceed (real_pc, GDB_SIGNAL_0);
649 
650       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
651 				 all_non_exited_threads ());
652 
653       /* Inferior function calls are always synchronous, even if the
654 	 target supports asynchronous execution.  */
655       wait_sync_command_done ();
656 
657       infcall_debug_printf ("inferior call completed successfully");
658     }
659   catch (gdb_exception &e)
660     {
661       infcall_debug_printf ("exception while making inferior call (%d): %s",
662 			    e.reason, e.what ());
663       caught_error = std::move (e);
664     }
665 
666   infcall_debug_printf ("thread is now: %s",
667 			inferior_ptid.to_string ().c_str ());
668 
669   /* If GDB has the prompt blocked before, then ensure that it remains
670      so.  normal_stop calls async_enable_stdin, so reset the prompt
671      state again here.  In other cases, stdin will be re-enabled by
672      inferior_event_handler, when an exception is thrown.  */
673   if (current_ui->prompt_state == PROMPT_BLOCKED)
674     current_ui->unregister_file_handler ();
675   else
676     current_ui->register_file_handler ();
677 
678   /* If the infcall does NOT succeed, normal_stop will have already
679      finished the thread states.  However, on success, normal_stop
680      defers here, so that we can set back the thread states to what
681      they were before the call.  Note that we must also finish the
682      state of new threads that might have spawned while the call was
683      running.  The main cases to handle are:
684 
685      - "(gdb) print foo ()", or any other command that evaluates an
686      expression at the prompt.  (The thread was marked stopped before.)
687 
688      - "(gdb) break foo if return_false()" or similar cases where we
689      do an infcall while handling an event (while the thread is still
690      marked running).  In this example, whether the condition
691      evaluates true and thus we'll present a user-visible stop is
692      decided elsewhere.  */
693   if (!was_running
694       && call_thread_ptid == inferior_ptid
695       && stop_stack_dummy == STOP_STACK_DUMMY)
696     finish_thread_state (call_thread->inf->process_target (),
697 			 user_visible_resume_ptid (0));
698 
699   enable_watchpoints_after_interactive_call_stop ();
700 
701   /* Call breakpoint_auto_delete on the current contents of the bpstat
702      of inferior call thread.
703      If all error()s out of proceed ended up calling normal_stop
704      (and perhaps they should; it already does in the special case
705      of error out of resume()), then we wouldn't need this.  */
706   if (caught_error.reason < 0)
707     {
708       if (call_thread->state != THREAD_EXITED)
709 	breakpoint_auto_delete (call_thread->control.stop_bpstat);
710     }
711 
712   return caught_error;
713 }
714 
715 /* Reserve space on the stack for a value of the given type.
716    Return the address of the allocated space.
717    Make certain that the value is correctly aligned.
718    The SP argument is modified.  */
719 
720 static CORE_ADDR
721 reserve_stack_space (const type *values_type, CORE_ADDR &sp)
722 {
723   frame_info_ptr frame = get_current_frame ();
724   struct gdbarch *gdbarch = get_frame_arch (frame);
725   CORE_ADDR addr = 0;
726 
727   if (gdbarch_inner_than (gdbarch, 1, 2))
728     {
729       /* Stack grows downward.  Align STRUCT_ADDR and SP after
730 	 making space.  */
731       sp -= values_type->length ();
732       if (gdbarch_frame_align_p (gdbarch))
733 	sp = gdbarch_frame_align (gdbarch, sp);
734       addr = sp;
735     }
736   else
737     {
738       /* Stack grows upward.  Align the frame, allocate space, and
739 	 then again, re-align the frame???  */
740       if (gdbarch_frame_align_p (gdbarch))
741 	sp = gdbarch_frame_align (gdbarch, sp);
742       addr = sp;
743       sp += values_type->length ();
744       if (gdbarch_frame_align_p (gdbarch))
745 	sp = gdbarch_frame_align (gdbarch, sp);
746     }
747 
748   return addr;
749 }
750 
751 /* The data structure which keeps a destructor function and
752    its implicit 'this' parameter.  */
753 
754 struct destructor_info
755 {
756   destructor_info (struct value *function, struct value *self)
757     : function (function), self (self) { }
758 
759   struct value *function;
760   struct value *self;
761 };
762 
763 
764 /* Auxiliary function that takes a list of destructor functions
765    with their 'this' parameters, and invokes the functions.  */
766 
767 static void
768 call_destructors (const std::list<destructor_info> &dtors_to_invoke,
769 		  struct type *default_return_type)
770 {
771   for (auto vals : dtors_to_invoke)
772     {
773       call_function_by_hand (vals.function, default_return_type,
774 			     gdb::make_array_view (&(vals.self), 1));
775     }
776 }
777 
778 /* See infcall.h.  */
779 
780 struct value *
781 call_function_by_hand (struct value *function,
782 		       type *default_return_type,
783 		       gdb::array_view<value *> args)
784 {
785   return call_function_by_hand_dummy (function, default_return_type,
786 				      args, NULL, NULL);
787 }
788 
789 /* All this stuff with a dummy frame may seem unnecessarily complicated
790    (why not just save registers in GDB?).  The purpose of pushing a dummy
791    frame which looks just like a real frame is so that if you call a
792    function and then hit a breakpoint (get a signal, etc), "backtrace"
793    will look right.  Whether the backtrace needs to actually show the
794    stack at the time the inferior function was called is debatable, but
795    it certainly needs to not display garbage.  So if you are contemplating
796    making dummy frames be different from normal frames, consider that.  */
797 
798 /* Perform a function call in the inferior.
799    ARGS is a vector of values of arguments.
800    FUNCTION is a value, the function to be called.
801    Returns a value representing what the function returned.
802    May fail to return, if a breakpoint or signal is hit
803    during the execution of the function.
804 
805    ARGS is modified to contain coerced values.  */
806 
807 struct value *
808 call_function_by_hand_dummy (struct value *function,
809 			     type *default_return_type,
810 			     gdb::array_view<value *> args,
811 			     dummy_frame_dtor_ftype *dummy_dtor,
812 			     void *dummy_dtor_data)
813 {
814   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
815 
816   CORE_ADDR sp;
817   struct type *target_values_type;
818   function_call_return_method return_method = return_method_normal;
819   CORE_ADDR struct_addr = 0;
820   CORE_ADDR real_pc;
821   CORE_ADDR bp_addr;
822   struct frame_id dummy_id;
823   frame_info_ptr frame;
824   struct gdbarch *gdbarch;
825   ptid_t call_thread_ptid;
826   struct gdb_exception e;
827   char name_buf[RAW_FUNCTION_ADDRESS_SIZE];
828 
829   if (!may_call_functions_p)
830     error (_("Cannot call functions in the program: "
831 	     "may-call-functions is off."));
832 
833   if (!target_has_execution ())
834     noprocess ();
835 
836   if (get_traceframe_number () >= 0)
837     error (_("May not call functions while looking at trace frames."));
838 
839   if (execution_direction == EXEC_REVERSE)
840     error (_("Cannot call functions in reverse mode."));
841 
842   /* We're going to run the target, and inspect the thread's state
843      afterwards.  Hold a strong reference so that the pointer remains
844      valid even if the thread exits.  */
845   thread_info_ref call_thread
846     = thread_info_ref::new_reference (inferior_thread ());
847 
848   bool stack_temporaries = thread_stack_temporaries_enabled_p (call_thread.get ());
849 
850   frame = get_current_frame ();
851   frame.prepare_reinflate ();
852   gdbarch = get_frame_arch (frame);
853 
854   if (!gdbarch_push_dummy_call_p (gdbarch))
855     error (_("This target does not support function calls."));
856 
857   /* Find the function type and do a sanity check.  */
858   type *ftype;
859   type *values_type;
860   CORE_ADDR funaddr = find_function_addr (function, &values_type, &ftype);
861 
862   if (is_nocall_function (ftype))
863     error (_("Cannot call the function '%s' which does not follow the "
864 	     "target calling convention."),
865 	   get_function_name (funaddr, name_buf, sizeof (name_buf)));
866 
867   frame.reinflate ();
868 
869   if (values_type == NULL || values_type->is_stub ())
870     values_type = default_return_type;
871   if (values_type == NULL)
872     {
873       const char *name = get_function_name (funaddr,
874 					    name_buf, sizeof (name_buf));
875       error (_("'%s' has unknown return type; "
876 	       "cast the call to its declared return type"),
877 	     name);
878     }
879 
880   values_type = check_typedef (values_type);
881 
882   if (args.size () < ftype->num_fields ())
883     error (_("Too few arguments in function call."));
884 
885   infcall_debug_printf ("calling %s", get_function_name (funaddr, name_buf,
886 							 sizeof (name_buf)));
887 
888   /* A holder for the inferior status.
889      This is only needed while we're preparing the inferior function call.  */
890   infcall_control_state_up inf_status (save_infcall_control_state ());
891 
892   /* Save the caller's registers and other state associated with the
893      inferior itself so that they can be restored once the
894      callee returns.  To allow nested calls the registers are (further
895      down) pushed onto a dummy frame stack.  This unique pointer
896      is released once the regcache has been pushed).  */
897   infcall_suspend_state_up caller_state (save_infcall_suspend_state ());
898 
899   /* Ensure that the initial SP is correctly aligned.  */
900   {
901     CORE_ADDR old_sp = get_frame_sp (frame);
902 
903     if (gdbarch_frame_align_p (gdbarch))
904       {
905 	sp = gdbarch_frame_align (gdbarch, old_sp);
906 	/* NOTE: cagney/2003-08-13: Skip the "red zone".  For some
907 	   ABIs, a function can use memory beyond the inner most stack
908 	   address.  AMD64 called that region the "red zone".  Skip at
909 	   least the "red zone" size before allocating any space on
910 	   the stack.  */
911 	if (gdbarch_inner_than (gdbarch, 1, 2))
912 	  sp -= gdbarch_frame_red_zone_size (gdbarch);
913 	else
914 	  sp += gdbarch_frame_red_zone_size (gdbarch);
915 	/* Still aligned?  */
916 	gdb_assert (sp == gdbarch_frame_align (gdbarch, sp));
917 	/* NOTE: cagney/2002-09-18:
918 
919 	   On a RISC architecture, a void parameterless generic dummy
920 	   frame (i.e., no parameters, no result) typically does not
921 	   need to push anything the stack and hence can leave SP and
922 	   FP.  Similarly, a frameless (possibly leaf) function does
923 	   not push anything on the stack and, hence, that too can
924 	   leave FP and SP unchanged.  As a consequence, a sequence of
925 	   void parameterless generic dummy frame calls to frameless
926 	   functions will create a sequence of effectively identical
927 	   frames (SP, FP and TOS and PC the same).  This, not
928 	   surprisingly, results in what appears to be a stack in an
929 	   infinite loop --- when GDB tries to find a generic dummy
930 	   frame on the internal dummy frame stack, it will always
931 	   find the first one.
932 
933 	   To avoid this problem, the code below always grows the
934 	   stack.  That way, two dummy frames can never be identical.
935 	   It does burn a few bytes of stack but that is a small price
936 	   to pay :-).  */
937 	if (sp == old_sp)
938 	  {
939 	    if (gdbarch_inner_than (gdbarch, 1, 2))
940 	      /* Stack grows down.  */
941 	      sp = gdbarch_frame_align (gdbarch, old_sp - 1);
942 	    else
943 	      /* Stack grows up.  */
944 	      sp = gdbarch_frame_align (gdbarch, old_sp + 1);
945 	  }
946 	/* SP may have underflown address zero here from OLD_SP.  Memory access
947 	   functions will probably fail in such case but that is a target's
948 	   problem.  */
949       }
950     else
951       /* FIXME: cagney/2002-09-18: Hey, you loose!
952 
953 	 Who knows how badly aligned the SP is!
954 
955 	 If the generic dummy frame ends up empty (because nothing is
956 	 pushed) GDB won't be able to correctly perform back traces.
957 	 If a target is having trouble with backtraces, first thing to
958 	 do is add FRAME_ALIGN() to the architecture vector.  If that
959 	 fails, try dummy_id().
960 
961 	 If the ABI specifies a "Red Zone" (see the doco) the code
962 	 below will quietly trash it.  */
963       sp = old_sp;
964 
965     /* Skip over the stack temporaries that might have been generated during
966        the evaluation of an expression.  */
967     if (stack_temporaries)
968       {
969 	struct value *lastval;
970 
971 	lastval = get_last_thread_stack_temporary (call_thread.get ());
972 	if (lastval != NULL)
973 	  {
974 	    CORE_ADDR lastval_addr = value_address (lastval);
975 
976 	    if (gdbarch_inner_than (gdbarch, 1, 2))
977 	      {
978 		gdb_assert (sp >= lastval_addr);
979 		sp = lastval_addr;
980 	      }
981 	    else
982 	      {
983 		gdb_assert (sp <= lastval_addr);
984 		sp = lastval_addr + value_type (lastval)->length ();
985 	      }
986 
987 	    if (gdbarch_frame_align_p (gdbarch))
988 	      sp = gdbarch_frame_align (gdbarch, sp);
989 	  }
990       }
991   }
992 
993   /* Are we returning a value using a structure return?  */
994 
995   if (gdbarch_return_in_first_hidden_param_p (gdbarch, values_type))
996     {
997       return_method = return_method_hidden_param;
998 
999       /* Tell the target specific argument pushing routine not to
1000 	 expect a value.  */
1001       target_values_type = builtin_type (gdbarch)->builtin_void;
1002     }
1003   else
1004     {
1005       if (using_struct_return (gdbarch, function, values_type))
1006 	return_method = return_method_struct;
1007       target_values_type = values_type;
1008     }
1009 
1010   gdb::observers::inferior_call_pre.notify (inferior_ptid, funaddr);
1011 
1012   /* Determine the location of the breakpoint (and possibly other
1013      stuff) that the called function will return to.  The SPARC, for a
1014      function returning a structure or union, needs to make space for
1015      not just the breakpoint but also an extra word containing the
1016      size (?) of the structure being passed.  */
1017 
1018   switch (gdbarch_call_dummy_location (gdbarch))
1019     {
1020     case ON_STACK:
1021       {
1022 	const gdb_byte *bp_bytes;
1023 	CORE_ADDR bp_addr_as_address;
1024 	int bp_size;
1025 
1026 	/* Be careful BP_ADDR is in inferior PC encoding while
1027 	   BP_ADDR_AS_ADDRESS is a plain memory address.  */
1028 
1029 	sp = push_dummy_code (gdbarch, sp, funaddr, args,
1030 			      target_values_type, &real_pc, &bp_addr,
1031 			      get_current_regcache ());
1032 
1033 	/* Write a legitimate instruction at the point where the infcall
1034 	   breakpoint is going to be inserted.  While this instruction
1035 	   is never going to be executed, a user investigating the
1036 	   memory from GDB would see this instruction instead of random
1037 	   uninitialized bytes.  We chose the breakpoint instruction
1038 	   as it may look as the most logical one to the user and also
1039 	   valgrind 3.7.0 needs it for proper vgdb inferior calls.
1040 
1041 	   If software breakpoints are unsupported for this target we
1042 	   leave the user visible memory content uninitialized.  */
1043 
1044 	bp_addr_as_address = bp_addr;
1045 	bp_bytes = gdbarch_breakpoint_from_pc (gdbarch, &bp_addr_as_address,
1046 					       &bp_size);
1047 	if (bp_bytes != NULL)
1048 	  write_memory (bp_addr_as_address, bp_bytes, bp_size);
1049       }
1050       break;
1051     case AT_ENTRY_POINT:
1052       {
1053 	CORE_ADDR dummy_addr;
1054 
1055 	real_pc = funaddr;
1056 	dummy_addr = entry_point_address ();
1057 
1058 	/* A call dummy always consists of just a single breakpoint, so
1059 	   its address is the same as the address of the dummy.
1060 
1061 	   The actual breakpoint is inserted separatly so there is no need to
1062 	   write that out.  */
1063 	bp_addr = dummy_addr;
1064 	break;
1065       }
1066     default:
1067       internal_error (_("bad switch"));
1068     }
1069 
1070   /* Coerce the arguments and handle pass-by-reference.
1071      We want to remember the destruction required for pass-by-ref values.
1072      For these, store the dtor function and the 'this' argument
1073      in DTORS_TO_INVOKE.  */
1074   std::list<destructor_info> dtors_to_invoke;
1075 
1076   for (int i = args.size () - 1; i >= 0; i--)
1077     {
1078       int prototyped;
1079       struct type *param_type;
1080 
1081       /* FIXME drow/2002-05-31: Should just always mark methods as
1082 	 prototyped.  Can we respect TYPE_VARARGS?  Probably not.  */
1083       if (ftype->code () == TYPE_CODE_METHOD)
1084 	prototyped = 1;
1085       else if (ftype->target_type () == NULL && ftype->num_fields () == 0
1086 	       && default_return_type != NULL)
1087 	{
1088 	  /* Calling a no-debug function with the return type
1089 	     explicitly cast.  Assume the function is prototyped,
1090 	     with a prototype matching the types of the arguments.
1091 	     E.g., with:
1092 	     float mult (float v1, float v2) { return v1 * v2; }
1093 	     This:
1094 	     (gdb) p (float) mult (2.0f, 3.0f)
1095 	     Is a simpler alternative to:
1096 	     (gdb) p ((float (*) (float, float)) mult) (2.0f, 3.0f)
1097 	  */
1098 	  prototyped = 1;
1099 	}
1100       else if (i < ftype->num_fields ())
1101 	prototyped = ftype->is_prototyped ();
1102       else
1103 	prototyped = 0;
1104 
1105       if (i < ftype->num_fields ())
1106 	param_type = ftype->field (i).type ();
1107       else
1108 	param_type = NULL;
1109 
1110       value *original_arg = args[i];
1111       args[i] = value_arg_coerce (gdbarch, args[i],
1112 				  param_type, prototyped);
1113 
1114       if (param_type == NULL)
1115 	continue;
1116 
1117       auto info = language_pass_by_reference (param_type);
1118       if (!info.copy_constructible)
1119 	error (_("expression cannot be evaluated because the type '%s' "
1120 		 "is not copy constructible"), param_type->name ());
1121 
1122       if (!info.destructible)
1123 	error (_("expression cannot be evaluated because the type '%s' "
1124 		 "is not destructible"), param_type->name ());
1125 
1126       if (info.trivially_copyable)
1127 	continue;
1128 
1129       /* Make a copy of the argument on the stack.  If the argument is
1130 	 trivially copy ctor'able, copy bit by bit.  Otherwise, call
1131 	 the copy ctor to initialize the clone.  */
1132       CORE_ADDR addr = reserve_stack_space (param_type, sp);
1133       value *clone
1134 	= value_from_contents_and_address (param_type, nullptr, addr);
1135       push_thread_stack_temporary (call_thread.get (), clone);
1136       value *clone_ptr
1137 	= value_from_pointer (lookup_pointer_type (param_type), addr);
1138 
1139       if (info.trivially_copy_constructible)
1140 	{
1141 	  int length = param_type->length ();
1142 	  write_memory (addr, value_contents (args[i]).data (), length);
1143 	}
1144       else
1145 	{
1146 	  value *copy_ctor;
1147 	  value *cctor_args[2] = { clone_ptr, original_arg };
1148 	  find_overload_match (gdb::make_array_view (cctor_args, 2),
1149 			       param_type->name (), METHOD,
1150 			       &clone_ptr, nullptr, &copy_ctor, nullptr,
1151 			       nullptr, 0, EVAL_NORMAL);
1152 
1153 	  if (copy_ctor == nullptr)
1154 	    error (_("expression cannot be evaluated because a copy "
1155 		     "constructor for the type '%s' could not be found "
1156 		     "(maybe inlined?)"), param_type->name ());
1157 
1158 	  call_function_by_hand (copy_ctor, default_return_type,
1159 				 gdb::make_array_view (cctor_args, 2));
1160 	}
1161 
1162       /* If the argument has a destructor, remember it so that we
1163 	 invoke it after the infcall is complete.  */
1164       if (!info.trivially_destructible)
1165 	{
1166 	  /* Looking up the function via overload resolution does not
1167 	     work because the compiler (in particular, gcc) adds an
1168 	     artificial int parameter in some cases.  So we look up
1169 	     the function by using the "~" name.  This should be OK
1170 	     because there can be only one dtor definition.  */
1171 	  const char *dtor_name = nullptr;
1172 	  for (int fieldnum = 0;
1173 	       fieldnum < TYPE_NFN_FIELDS (param_type);
1174 	       fieldnum++)
1175 	    {
1176 	      fn_field *fn
1177 		= TYPE_FN_FIELDLIST1 (param_type, fieldnum);
1178 	      const char *field_name
1179 		= TYPE_FN_FIELDLIST_NAME (param_type, fieldnum);
1180 
1181 	      if (field_name[0] == '~')
1182 		dtor_name = TYPE_FN_FIELD_PHYSNAME (fn, 0);
1183 	    }
1184 
1185 	  if (dtor_name == nullptr)
1186 	    error (_("expression cannot be evaluated because a destructor "
1187 		     "for the type '%s' could not be found "
1188 		     "(maybe inlined?)"), param_type->name ());
1189 
1190 	  value *dtor
1191 	    = find_function_in_inferior (dtor_name, 0);
1192 
1193 	  /* Insert the dtor to the front of the list to call them
1194 	     in reverse order later.  */
1195 	  dtors_to_invoke.emplace_front (dtor, clone_ptr);
1196 	}
1197 
1198       args[i] = clone_ptr;
1199     }
1200 
1201   /* Reserve space for the return structure to be written on the
1202      stack, if necessary.
1203 
1204      While evaluating expressions, we reserve space on the stack for
1205      return values of class type even if the language ABI and the target
1206      ABI do not require that the return value be passed as a hidden first
1207      argument.  This is because we want to store the return value as an
1208      on-stack temporary while the expression is being evaluated.  This
1209      enables us to have chained function calls in expressions.
1210 
1211      Keeping the return values as on-stack temporaries while the expression
1212      is being evaluated is OK because the thread is stopped until the
1213      expression is completely evaluated.  */
1214 
1215   if (return_method != return_method_normal
1216       || (stack_temporaries && class_or_union_p (values_type)))
1217     struct_addr = reserve_stack_space (values_type, sp);
1218 
1219   std::vector<struct value *> new_args;
1220   if (return_method == return_method_hidden_param)
1221     {
1222       /* Add the new argument to the front of the argument list.  */
1223       new_args.reserve (args.size ());
1224       new_args.push_back
1225 	(value_from_pointer (lookup_pointer_type (values_type), struct_addr));
1226       new_args.insert (new_args.end (), args.begin (), args.end ());
1227       args = new_args;
1228     }
1229 
1230   /* Create the dummy stack frame.  Pass in the call dummy address as,
1231      presumably, the ABI code knows where, in the call dummy, the
1232      return address should be pointed.  */
1233   sp = gdbarch_push_dummy_call (gdbarch, function, get_current_regcache (),
1234 				bp_addr, args.size (), args.data (),
1235 				sp, return_method, struct_addr);
1236 
1237   /* Set up a frame ID for the dummy frame so we can pass it to
1238      set_momentary_breakpoint.  We need to give the breakpoint a frame
1239      ID so that the breakpoint code can correctly re-identify the
1240      dummy breakpoint.  */
1241   /* Sanity.  The exact same SP value is returned by PUSH_DUMMY_CALL,
1242      saved as the dummy-frame TOS, and used by dummy_id to form
1243      the frame ID's stack address.  */
1244   dummy_id = frame_id_build (sp, bp_addr);
1245 
1246   /* Create a momentary breakpoint at the return address of the
1247      inferior.  That way it breaks when it returns.  */
1248 
1249   {
1250     symtab_and_line sal;
1251     sal.pspace = current_program_space;
1252     sal.pc = bp_addr;
1253     sal.section = find_pc_overlay (sal.pc);
1254 
1255     /* Sanity.  The exact same SP value is returned by
1256        PUSH_DUMMY_CALL, saved as the dummy-frame TOS, and used by
1257        dummy_id to form the frame ID's stack address.  */
1258     breakpoint *bpt
1259       = set_momentary_breakpoint (gdbarch, sal,
1260 				  dummy_id, bp_call_dummy).release ();
1261 
1262     /* set_momentary_breakpoint invalidates FRAME.  */
1263     frame = NULL;
1264 
1265     bpt->disposition = disp_del;
1266     gdb_assert (bpt->related_breakpoint == bpt);
1267 
1268     breakpoint *longjmp_b = set_longjmp_breakpoint_for_call_dummy ();
1269     if (longjmp_b)
1270       {
1271 	/* Link BPT into the chain of LONGJMP_B.  */
1272 	bpt->related_breakpoint = longjmp_b;
1273 	while (longjmp_b->related_breakpoint != bpt->related_breakpoint)
1274 	  longjmp_b = longjmp_b->related_breakpoint;
1275 	longjmp_b->related_breakpoint = bpt;
1276       }
1277   }
1278 
1279   /* Create a breakpoint in std::terminate.
1280      If a C++ exception is raised in the dummy-frame, and the
1281      exception handler is (normally, and expected to be) out-of-frame,
1282      the default C++ handler will (wrongly) be called in an inferior
1283      function call.  This is wrong, as an exception can be  normally
1284      and legally handled out-of-frame.  The confines of the dummy frame
1285      prevent the unwinder from finding the correct handler (or any
1286      handler, unless it is in-frame).  The default handler calls
1287      std::terminate.  This will kill the inferior.  Assert that
1288      terminate should never be called in an inferior function
1289      call.  Place a momentary breakpoint in the std::terminate function
1290      and if triggered in the call, rewind.  */
1291   if (unwind_on_terminating_exception_p)
1292     set_std_terminate_breakpoint ();
1293 
1294   /* Everything's ready, push all the info needed to restore the
1295      caller (and identify the dummy-frame) onto the dummy-frame
1296      stack.  */
1297   dummy_frame_push (caller_state.release (), &dummy_id, call_thread.get ());
1298   if (dummy_dtor != NULL)
1299     register_dummy_frame_dtor (dummy_id, call_thread.get (),
1300 			       dummy_dtor, dummy_dtor_data);
1301 
1302   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
1303   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
1304 
1305   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
1306      If you're looking to implement asynchronous dummy-frames, then
1307      just below is the place to chop this function in two..  */
1308 
1309   {
1310     /* Save the current FSM.  We'll override it.  */
1311     std::unique_ptr<thread_fsm> saved_sm = call_thread->release_thread_fsm ();
1312     struct call_thread_fsm *sm;
1313 
1314     /* Save this thread's ptid, we need it later but the thread
1315        may have exited.  */
1316     call_thread_ptid = call_thread->ptid;
1317 
1318     /* Run the inferior until it stops.  */
1319 
1320     /* Create the FSM used to manage the infcall.  It tells infrun to
1321        not report the stop to the user, and captures the return value
1322        before the dummy frame is popped.  run_inferior_call registers
1323        it with the thread ASAP.  */
1324     sm = new call_thread_fsm (current_ui, command_interp (),
1325 			      gdbarch, function,
1326 			      values_type,
1327 			      return_method != return_method_normal,
1328 			      struct_addr);
1329     {
1330       std::unique_ptr<call_thread_fsm> sm_up (sm);
1331       e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
1332     }
1333 
1334     if (e.reason < 0)
1335       infcall_debug_printf ("after inferior call, exception (%d): %s",
1336 			    e.reason, e.what ());
1337     infcall_debug_printf ("after inferior call, thread state is: %s",
1338 			  thread_state_string (call_thread->state));
1339 
1340     gdb::observers::inferior_call_post.notify (call_thread_ptid, funaddr);
1341 
1342     if (call_thread->state != THREAD_EXITED)
1343       {
1344 	/* The FSM should still be the same.  */
1345 	gdb_assert (call_thread->thread_fsm () == sm);
1346 
1347 	if (call_thread->thread_fsm ()->finished_p ())
1348 	  {
1349 	    struct value *retval;
1350 
1351 	    infcall_debug_printf ("call completed");
1352 
1353 	    /* The inferior call is successful.  Pop the dummy frame,
1354 	       which runs its destructors and restores the inferior's
1355 	       suspend state, and restore the inferior control
1356 	       state.  */
1357 	    dummy_frame_pop (dummy_id, call_thread.get ());
1358 	    restore_infcall_control_state (inf_status.release ());
1359 
1360 	    /* Get the return value.  */
1361 	    retval = sm->return_value;
1362 
1363 	    /* Restore the original FSM and clean up / destroh the call FSM.
1364 	       Doing it in this order ensures that if the call to clean_up
1365 	       throws, the original FSM is properly restored.  */
1366 	    {
1367 	      std::unique_ptr<thread_fsm> finalizing
1368 		= call_thread->release_thread_fsm ();
1369 	      call_thread->set_thread_fsm (std::move (saved_sm));
1370 
1371 	      finalizing->clean_up (call_thread.get ());
1372 	    }
1373 
1374 	    maybe_remove_breakpoints ();
1375 
1376 	    gdb_assert (retval != NULL);
1377 
1378 	    /* Destruct the pass-by-ref argument clones.  */
1379 	    call_destructors (dtors_to_invoke, default_return_type);
1380 
1381 	    return retval;
1382 	  }
1383 	else
1384 	  infcall_debug_printf ("call did not complete");
1385 
1386 	/* Didn't complete.  Clean up / destroy the call FSM, and restore the
1387 	   previous state machine, and handle the error.  */
1388 	{
1389 	  std::unique_ptr<thread_fsm> finalizing
1390 	    = call_thread->release_thread_fsm ();
1391 	  call_thread->set_thread_fsm (std::move (saved_sm));
1392 
1393 	  finalizing->clean_up (call_thread.get ());
1394 	}
1395       }
1396   }
1397 
1398   /* Rethrow an error if we got one trying to run the inferior.  */
1399 
1400   if (e.reason < 0)
1401     {
1402       const char *name = get_function_name (funaddr,
1403 					    name_buf, sizeof (name_buf));
1404 
1405       discard_infcall_control_state (inf_status.release ());
1406 
1407       /* We could discard the dummy frame here if the program exited,
1408 	 but it will get garbage collected the next time the program is
1409 	 run anyway.  */
1410 
1411       switch (e.reason)
1412 	{
1413 	case RETURN_ERROR:
1414 	  throw_error (e.error, _("%s\n\
1415 An error occurred while in a function called from GDB.\n\
1416 Evaluation of the expression containing the function\n\
1417 (%s) will be abandoned.\n\
1418 When the function is done executing, GDB will silently stop."),
1419 		       e.what (), name);
1420 	case RETURN_QUIT:
1421 	default:
1422 	  throw_exception (std::move (e));
1423 	}
1424     }
1425 
1426   /* If the program has exited, or we stopped at a different thread,
1427      exit and inform the user.  */
1428 
1429   if (! target_has_execution ())
1430     {
1431       const char *name = get_function_name (funaddr,
1432 					    name_buf, sizeof (name_buf));
1433 
1434       /* If we try to restore the inferior status,
1435 	 we'll crash as the inferior is no longer running.  */
1436       discard_infcall_control_state (inf_status.release ());
1437 
1438       /* We could discard the dummy frame here given that the program exited,
1439 	 but it will get garbage collected the next time the program is
1440 	 run anyway.  */
1441 
1442       error (_("The program being debugged exited while in a function "
1443 	       "called from GDB.\n"
1444 	       "Evaluation of the expression containing the function\n"
1445 	       "(%s) will be abandoned."),
1446 	     name);
1447     }
1448 
1449   if (call_thread_ptid != inferior_ptid)
1450     {
1451       const char *name = get_function_name (funaddr,
1452 					    name_buf, sizeof (name_buf));
1453 
1454       /* We've switched threads.  This can happen if another thread gets a
1455 	 signal or breakpoint while our thread was running.
1456 	 There's no point in restoring the inferior status,
1457 	 we're in a different thread.  */
1458       discard_infcall_control_state (inf_status.release ());
1459       /* Keep the dummy frame record, if the user switches back to the
1460 	 thread with the hand-call, we'll need it.  */
1461       if (stopped_by_random_signal)
1462 	error (_("\
1463 The program received a signal in another thread while\n\
1464 making a function call from GDB.\n\
1465 Evaluation of the expression containing the function\n\
1466 (%s) will be abandoned.\n\
1467 When the function is done executing, GDB will silently stop."),
1468 	       name);
1469       else
1470 	error (_("\
1471 The program stopped in another thread while making a function call from GDB.\n\
1472 Evaluation of the expression containing the function\n\
1473 (%s) will be abandoned.\n\
1474 When the function is done executing, GDB will silently stop."),
1475 	       name);
1476     }
1477 
1478     {
1479       /* Make a copy as NAME may be in an objfile freed by dummy_frame_pop.  */
1480       std::string name = get_function_name (funaddr, name_buf,
1481 					    sizeof (name_buf));
1482 
1483       if (stopped_by_random_signal)
1484 	{
1485 	  /* We stopped inside the FUNCTION because of a random
1486 	     signal.  Further execution of the FUNCTION is not
1487 	     allowed.  */
1488 
1489 	  if (unwind_on_signal_p)
1490 	    {
1491 	      /* The user wants the context restored.  */
1492 
1493 	      /* We must get back to the frame we were before the
1494 		 dummy call.  */
1495 	      dummy_frame_pop (dummy_id, call_thread.get ());
1496 
1497 	      /* We also need to restore inferior status to that before the
1498 		 dummy call.  */
1499 	      restore_infcall_control_state (inf_status.release ());
1500 
1501 	      /* FIXME: Insert a bunch of wrap_here; name can be very
1502 		 long if it's a C++ name with arguments and stuff.  */
1503 	      error (_("\
1504 The program being debugged was signaled while in a function called from GDB.\n\
1505 GDB has restored the context to what it was before the call.\n\
1506 To change this behavior use \"set unwindonsignal off\".\n\
1507 Evaluation of the expression containing the function\n\
1508 (%s) will be abandoned."),
1509 		     name.c_str ());
1510 	    }
1511 	  else
1512 	    {
1513 	      /* The user wants to stay in the frame where we stopped
1514 		 (default).
1515 		 Discard inferior status, we're not at the same point
1516 		 we started at.  */
1517 	      discard_infcall_control_state (inf_status.release ());
1518 
1519 	      /* FIXME: Insert a bunch of wrap_here; name can be very
1520 		 long if it's a C++ name with arguments and stuff.  */
1521 	      error (_("\
1522 The program being debugged was signaled while in a function called from GDB.\n\
1523 GDB remains in the frame where the signal was received.\n\
1524 To change this behavior use \"set unwindonsignal on\".\n\
1525 Evaluation of the expression containing the function\n\
1526 (%s) will be abandoned.\n\
1527 When the function is done executing, GDB will silently stop."),
1528 		     name.c_str ());
1529 	    }
1530 	}
1531 
1532       if (stop_stack_dummy == STOP_STD_TERMINATE)
1533 	{
1534 	  /* We must get back to the frame we were before the dummy
1535 	     call.  */
1536 	  dummy_frame_pop (dummy_id, call_thread.get ());
1537 
1538 	  /* We also need to restore inferior status to that before
1539 	     the dummy call.  */
1540 	  restore_infcall_control_state (inf_status.release ());
1541 
1542 	  error (_("\
1543 The program being debugged entered a std::terminate call, most likely\n\
1544 caused by an unhandled C++ exception.  GDB blocked this call in order\n\
1545 to prevent the program from being terminated, and has restored the\n\
1546 context to its original state before the call.\n\
1547 To change this behaviour use \"set unwind-on-terminating-exception off\".\n\
1548 Evaluation of the expression containing the function (%s)\n\
1549 will be abandoned."),
1550 		 name.c_str ());
1551 	}
1552       else if (stop_stack_dummy == STOP_NONE)
1553 	{
1554 
1555 	  /* We hit a breakpoint inside the FUNCTION.
1556 	     Keep the dummy frame, the user may want to examine its state.
1557 	     Discard inferior status, we're not at the same point
1558 	     we started at.  */
1559 	  discard_infcall_control_state (inf_status.release ());
1560 
1561 	  /* The following error message used to say "The expression
1562 	     which contained the function call has been discarded."
1563 	     It is a hard concept to explain in a few words.  Ideally,
1564 	     GDB would be able to resume evaluation of the expression
1565 	     when the function finally is done executing.  Perhaps
1566 	     someday this will be implemented (it would not be easy).  */
1567 	  /* FIXME: Insert a bunch of wrap_here; name can be very long if it's
1568 	     a C++ name with arguments and stuff.  */
1569 	  error (_("\
1570 The program being debugged stopped while in a function called from GDB.\n\
1571 Evaluation of the expression containing the function\n\
1572 (%s) will be abandoned.\n\
1573 When the function is done executing, GDB will silently stop."),
1574 		 name.c_str ());
1575 	}
1576 
1577     }
1578 
1579   /* The above code errors out, so ...  */
1580   gdb_assert_not_reached ("... should not be here");
1581 }
1582 
1583 void _initialize_infcall ();
1584 void
1585 _initialize_infcall ()
1586 {
1587   add_setshow_boolean_cmd ("may-call-functions", no_class,
1588 			   &may_call_functions_p, _("\
1589 Set permission to call functions in the program."), _("\
1590 Show permission to call functions in the program."), _("\
1591 When this permission is on, GDB may call functions in the program.\n\
1592 Otherwise, any sort of attempt to call a function in the program\n\
1593 will result in an error."),
1594 			   NULL,
1595 			   show_may_call_functions_p,
1596 			   &setlist, &showlist);
1597 
1598   add_setshow_boolean_cmd ("coerce-float-to-double", class_obscure,
1599 			   &coerce_float_to_double_p, _("\
1600 Set coercion of floats to doubles when calling functions."), _("\
1601 Show coercion of floats to doubles when calling functions."), _("\
1602 Variables of type float should generally be converted to doubles before\n\
1603 calling an unprototyped function, and left alone when calling a prototyped\n\
1604 function.  However, some older debug info formats do not provide enough\n\
1605 information to determine that a function is prototyped.  If this flag is\n\
1606 set, GDB will perform the conversion for a function it considers\n\
1607 unprototyped.\n\
1608 The default is to perform the conversion."),
1609 			   NULL,
1610 			   show_coerce_float_to_double_p,
1611 			   &setlist, &showlist);
1612 
1613   add_setshow_boolean_cmd ("unwindonsignal", no_class,
1614 			   &unwind_on_signal_p, _("\
1615 Set unwinding of stack if a signal is received while in a call dummy."), _("\
1616 Show unwinding of stack if a signal is received while in a call dummy."), _("\
1617 The unwindonsignal lets the user determine what gdb should do if a signal\n\
1618 is received while in a function called from gdb (call dummy).  If set, gdb\n\
1619 unwinds the stack and restore the context to what as it was before the call.\n\
1620 The default is to stop in the frame where the signal was received."),
1621 			   NULL,
1622 			   show_unwind_on_signal_p,
1623 			   &setlist, &showlist);
1624 
1625   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
1626 			   &unwind_on_terminating_exception_p, _("\
1627 Set unwinding of stack if std::terminate is called while in call dummy."), _("\
1628 Show unwinding of stack if std::terminate() is called while in a call dummy."),
1629 			   _("\
1630 The unwind on terminating exception flag lets the user determine\n\
1631 what gdb should do if a std::terminate() call is made from the\n\
1632 default exception handler.  If set, gdb unwinds the stack and restores\n\
1633 the context to what it was before the call.  If unset, gdb allows the\n\
1634 std::terminate call to proceed.\n\
1635 The default is to unwind the frame."),
1636 			   NULL,
1637 			   show_unwind_on_terminating_exception_p,
1638 			   &setlist, &showlist);
1639 
1640   add_setshow_boolean_cmd
1641     ("infcall", class_maintenance, &debug_infcall,
1642      _("Set inferior call debugging."),
1643      _("Show inferior call debugging."),
1644      _("When on, inferior function call specific debugging is enabled."),
1645      NULL, show_debug_infcall, &setdebuglist, &showdebuglist);
1646 }
1647