]> Git Repo - binutils.git/blob - gdb/python/py-framefilter.c
Unify gdb printf functions
[binutils.git] / gdb / python / py-framefilter.c
1 /* Python frame filters
2
3    Copyright (C) 2013-2022 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 "objfiles.h"
22 #include "symtab.h"
23 #include "language.h"
24 #include "arch-utils.h"
25 #include "python.h"
26 #include "ui-out.h"
27 #include "valprint.h"
28 #include "stack.h"
29 #include "source.h"
30 #include "annotate.h"
31 #include "hashtab.h"
32 #include "demangle.h"
33 #include "mi/mi-cmds.h"
34 #include "python-internal.h"
35 #include "gdbsupport/gdb_optional.h"
36 #include "cli/cli-style.h"
37
38 enum mi_print_types
39 {
40   MI_PRINT_ARGS,
41   MI_PRINT_LOCALS
42 };
43
44 /* Helper  function  to  extract  a  symbol, a  name  and  a  language
45    definition from a Python object that conforms to the "Symbol Value"
46    interface.  OBJ  is the Python  object to extract the  values from.
47    NAME is a  pass-through argument where the name of  the symbol will
48    be written.  NAME is allocated in  this function, but the caller is
49    responsible for clean up.  SYM is a pass-through argument where the
50    symbol will be written and  SYM_BLOCK is a pass-through argument to
51    write  the block where the symbol lies in.  In the case of the  API
52    returning a  string,  this will be set to NULL.  LANGUAGE is also a
53    pass-through  argument  denoting  the  language  attributed  to the
54    Symbol.  In the case of SYM being  NULL, this  will be  set to  the
55    current  language.  Returns  EXT_LANG_BT_ERROR  on  error  with the
56    appropriate Python exception set, and EXT_LANG_BT_OK on success.  */
57
58 static enum ext_lang_bt_status
59 extract_sym (PyObject *obj, gdb::unique_xmalloc_ptr<char> *name,
60              struct symbol **sym, const struct block **sym_block,
61              const struct language_defn **language)
62 {
63   gdbpy_ref<> result (PyObject_CallMethod (obj, "symbol", NULL));
64
65   if (result == NULL)
66     return EXT_LANG_BT_ERROR;
67
68   /* For 'symbol' callback, the function can return a symbol or a
69      string.  */
70   if (gdbpy_is_string (result.get ()))
71     {
72       *name = python_string_to_host_string (result.get ());
73
74       if (*name == NULL)
75         return EXT_LANG_BT_ERROR;
76       /* If the API returns a string (and not a symbol), then there is
77          no symbol derived language available and the frame filter has
78          either overridden the symbol with a string, or supplied a
79          entirely synthetic symbol/value pairing.  In that case, use
80          the current language.  */
81       *language = current_language;
82       *sym = NULL;
83       *sym_block = NULL;
84     }
85   else
86     {
87       /* This type checks 'result' during the conversion so we
88          just call it unconditionally and check the return.  */
89       *sym = symbol_object_to_symbol (result.get ());
90       /* TODO: currently, we have no way to recover the block in which SYMBOL
91          was found, so we have no block to return.  Trying to evaluate SYMBOL
92          will yield an incorrect value when it's located in a FRAME and
93          evaluated from another frame (as permitted in nested functions).  */
94       *sym_block = NULL;
95
96       if (*sym == NULL)
97         {
98           PyErr_SetString (PyExc_RuntimeError,
99                            _("Unexpected value.  Expecting a "
100                              "gdb.Symbol or a Python string."));
101           return EXT_LANG_BT_ERROR;
102         }
103
104       /* Duplicate the symbol name, so the caller has consistency
105          in garbage collection.  */
106       name->reset (xstrdup ((*sym)->print_name ()));
107
108       /* If a symbol is specified attempt to determine the language
109          from the symbol.  If mode is not "auto", then the language
110          has been explicitly set, use that.  */
111       if (language_mode == language_mode_auto)
112         *language = language_def ((*sym)->language ());
113       else
114         *language = current_language;
115     }
116
117   return EXT_LANG_BT_OK;
118 }
119
120 /* Helper function to extract a value from an object that conforms to
121    the "Symbol Value" interface.  OBJ is the Python object to extract
122    the value from.  VALUE is a pass-through argument where the value
123    will be written.  If the object does not have the value attribute,
124    or provides the Python None for a value, VALUE will be set to NULL
125    and this function will return as successful.  Returns EXT_LANG_BT_ERROR
126    on error with the appropriate Python exception set, and EXT_LANG_BT_OK on
127    success.  */
128
129 static enum ext_lang_bt_status
130 extract_value (PyObject *obj, struct value **value)
131 {
132   if (PyObject_HasAttrString (obj, "value"))
133     {
134       gdbpy_ref<> vresult (PyObject_CallMethod (obj, "value", NULL));
135
136       if (vresult == NULL)
137         return EXT_LANG_BT_ERROR;
138
139       /* The Python code has returned 'None' for a value, so we set
140          value to NULL.  This flags that GDB should read the
141          value.  */
142       if (vresult == Py_None)
143         {
144           *value = NULL;
145           return EXT_LANG_BT_OK;
146         }
147       else
148         {
149           *value = convert_value_from_python (vresult.get ());
150
151           if (*value == NULL)
152             return EXT_LANG_BT_ERROR;
153
154           return EXT_LANG_BT_OK;
155         }
156     }
157   else
158     *value = NULL;
159
160   return EXT_LANG_BT_OK;
161 }
162
163 /* MI prints only certain values according to the type of symbol and
164    also what the user has specified.  SYM is the symbol to check, and
165    MI_PRINT_TYPES is an enum specifying what the user wants emitted
166    for the MI command in question.  */
167 static int
168 mi_should_print (struct symbol *sym, enum mi_print_types type)
169 {
170   int print_me = 0;
171
172   switch (sym->aclass ())
173     {
174     default:
175     case LOC_UNDEF:     /* catches errors        */
176     case LOC_CONST:     /* constant              */
177     case LOC_TYPEDEF:   /* local typedef         */
178     case LOC_LABEL:     /* local label           */
179     case LOC_BLOCK:     /* local function        */
180     case LOC_CONST_BYTES:       /* loc. byte seq.        */
181     case LOC_UNRESOLVED:        /* unresolved static     */
182     case LOC_OPTIMIZED_OUT:     /* optimized out         */
183       print_me = 0;
184       break;
185
186     case LOC_ARG:       /* argument              */
187     case LOC_REF_ARG:   /* reference arg         */
188     case LOC_REGPARM_ADDR:      /* indirect register arg */
189     case LOC_LOCAL:     /* stack local           */
190     case LOC_STATIC:    /* static                */
191     case LOC_REGISTER:  /* register              */
192     case LOC_COMPUTED:  /* computed location     */
193       if (type == MI_PRINT_LOCALS)
194         print_me = ! sym->is_argument ();
195       else
196         print_me = sym->is_argument ();
197     }
198   return print_me;
199 }
200
201 /* Helper function which outputs a type name extracted from VAL to a
202    "type" field in the output stream OUT.  OUT is the ui-out structure
203    the type name will be output too, and VAL is the value that the
204    type will be extracted from.  */
205
206 static void
207 py_print_type (struct ui_out *out, struct value *val)
208 {
209   check_typedef (value_type (val));
210
211   string_file stb;
212   type_print (value_type (val), "", &stb, -1);
213   out->field_stream ("type", stb);
214 }
215
216 /* Helper function which outputs a value to an output field in a
217    stream.  OUT is the ui-out structure the value will be output to,
218    VAL is the value that will be printed, OPTS contains the value
219    printing options, ARGS_TYPE is an enumerator describing the
220    argument format, and LANGUAGE is the language_defn that the value
221    will be printed with.  */
222
223 static void
224 py_print_value (struct ui_out *out, struct value *val,
225                 const struct value_print_options *opts,
226                 int indent,
227                 enum ext_lang_frame_args args_type,
228                 const struct language_defn *language)
229 {
230   int should_print = 0;
231
232   /* MI does not print certain values, differentiated by type,
233      depending on what ARGS_TYPE indicates.  Test type against option.
234      For CLI print all values.  */
235   if (args_type == MI_PRINT_SIMPLE_VALUES
236       || args_type == MI_PRINT_ALL_VALUES)
237     {
238       struct type *type = check_typedef (value_type (val));
239
240       if (args_type == MI_PRINT_ALL_VALUES)
241         should_print = 1;
242       else if (args_type == MI_PRINT_SIMPLE_VALUES
243                && type->code () != TYPE_CODE_ARRAY
244                && type->code () != TYPE_CODE_STRUCT
245                && type->code () != TYPE_CODE_UNION)
246         should_print = 1;
247     }
248   else if (args_type != NO_VALUES)
249     should_print = 1;
250
251   if (should_print)
252     {
253       string_file stb;
254
255       common_val_print (val, &stb, indent, opts, language);
256       out->field_stream ("value", stb);
257     }
258 }
259
260 /* Helper function to call a Python method and extract an iterator
261    from the result.  If the function returns anything but an iterator
262    the exception is preserved and NULL is returned.  FILTER is the
263    Python object to call, and FUNC is the name of the method.  Returns
264    a PyObject, or NULL on error with the appropriate exception set.
265    This function can return an iterator, or NULL.  */
266
267 static PyObject *
268 get_py_iter_from_func (PyObject *filter, const char *func)
269 {
270   if (PyObject_HasAttrString (filter, func))
271     {
272       gdbpy_ref<> result (PyObject_CallMethod (filter, func, NULL));
273
274       if (result != NULL)
275         {
276           if (result == Py_None)
277             {
278               return result.release ();
279             }
280           else
281             {
282               return PyObject_GetIter (result.get ());
283             }
284         }
285     }
286   else
287     Py_RETURN_NONE;
288
289   return NULL;
290 }
291
292 /*  Helper function to output a single frame argument and value to an
293     output stream.  This function will account for entry values if the
294     FV parameter is populated, the frame argument has entry values
295     associated with them, and the appropriate "set entry-value"
296     options are set.  Will output in CLI or MI like format depending
297     on the type of output stream detected.  OUT is the output stream,
298     SYM_NAME is the name of the symbol.  If SYM_NAME is populated then
299     it must have an accompanying value in the parameter FV.  FA is a
300     frame argument structure.  If FA is populated, both SYM_NAME and
301     FV are ignored.  OPTS contains the value printing options,
302     ARGS_TYPE is an enumerator describing the argument format,
303     PRINT_ARGS_FIELD is a flag which indicates if we output "ARGS=1"
304     in MI output in commands where both arguments and locals are
305     printed.  */
306
307 static void
308 py_print_single_arg (struct ui_out *out,
309                      const char *sym_name,
310                      struct frame_arg *fa,
311                      struct value *fv,
312                      const struct value_print_options *opts,
313                      enum ext_lang_frame_args args_type,
314                      int print_args_field,
315                      const struct language_defn *language)
316 {
317   struct value *val;
318
319   if (fa != NULL)
320     {
321       if (fa->val == NULL && fa->error == NULL)
322         return;
323       language = language_def (fa->sym->language ());
324       val = fa->val;
325     }
326   else
327     val = fv;
328
329   gdb::optional<ui_out_emit_tuple> maybe_tuple;
330
331   /*  MI has varying rules for tuples, but generally if there is only
332       one element in each item in the list, do not start a tuple.  The
333       exception is -stack-list-variables which emits an ARGS="1" field
334       if the value is a frame argument.  This is denoted in this
335       function with PRINT_ARGS_FIELD which is flag from the caller to
336       emit the ARGS field.  */
337   if (out->is_mi_like_p ())
338     {
339       if (print_args_field || args_type != NO_VALUES)
340         maybe_tuple.emplace (out, nullptr);
341     }
342
343   annotate_arg_begin ();
344
345   /* If frame argument is populated, check for entry-values and the
346      entry value options.  */
347   if (fa != NULL)
348     {
349       string_file stb;
350
351       gdb_puts (fa->sym->print_name (), &stb);
352       if (fa->entry_kind == print_entry_values_compact)
353         {
354           stb.puts ("=");
355
356           gdb_puts (fa->sym->print_name (), &stb);
357         }
358       if (fa->entry_kind == print_entry_values_only
359           || fa->entry_kind == print_entry_values_compact)
360         stb.puts ("@entry");
361       out->field_stream ("name", stb);
362     }
363   else
364     /* Otherwise, just output the name.  */
365     out->field_string ("name", sym_name);
366
367   annotate_arg_name_end ();
368
369   out->text ("=");
370
371   if (print_args_field)
372     out->field_signed ("arg", 1);
373
374   /* For MI print the type, but only for simple values.  This seems
375      weird, but this is how MI choose to format the various output
376      types.  */
377   if (args_type == MI_PRINT_SIMPLE_VALUES && val != NULL)
378     py_print_type (out, val);
379
380   if (val != NULL)
381     annotate_arg_value (value_type (val));
382
383   /* If the output is to the CLI, and the user option "set print
384      frame-arguments" is set to none, just output "...".  */
385   if (! out->is_mi_like_p () && args_type == NO_VALUES)
386     out->field_string ("value", "...");
387   else
388     {
389       /* Otherwise, print the value for both MI and the CLI, except
390          for the case of MI_PRINT_NO_VALUES.  */
391       if (args_type != NO_VALUES)
392         {
393           if (val == NULL)
394             {
395               gdb_assert (fa != NULL && fa->error != NULL);
396               out->field_fmt ("value", metadata_style.style (),
397                               _("<error reading variable: %s>"),
398                               fa->error.get ());
399             }
400           else
401             py_print_value (out, val, opts, 0, args_type, language);
402         }
403     }
404 }
405
406 /* Helper function to loop over frame arguments provided by the
407    "frame_arguments" Python API.  Elements in the iterator must
408    conform to the "Symbol Value" interface.  ITER is the Python
409    iterable object, OUT is the output stream, ARGS_TYPE is an
410    enumerator describing the argument format, PRINT_ARGS_FIELD is a
411    flag which indicates if we output "ARGS=1" in MI output in commands
412    where both arguments and locals are printed, and FRAME is the
413    backing frame.  Returns EXT_LANG_BT_ERROR on error, with any GDB
414    exceptions converted to a Python exception, or EXT_LANG_BT_OK on
415    success.  */
416
417 static enum ext_lang_bt_status
418 enumerate_args (PyObject *iter,
419                 struct ui_out *out,
420                 enum ext_lang_frame_args args_type,
421                 int print_args_field,
422                 struct frame_info *frame)
423 {
424   struct value_print_options opts;
425
426   get_user_print_options (&opts);
427
428   if (args_type == CLI_SCALAR_VALUES)
429     {
430       /* True in "summary" mode, false otherwise.  */
431       opts.summary = 1;
432     }
433
434   opts.deref_ref = 1;
435
436   annotate_frame_args ();
437
438   /*  Collect the first argument outside of the loop, so output of
439       commas in the argument output is correct.  At the end of the
440       loop block collect another item from the iterator, and, if it is
441       not null emit a comma.  */
442   gdbpy_ref<> item (PyIter_Next (iter));
443   if (item == NULL && PyErr_Occurred ())
444     return EXT_LANG_BT_ERROR;
445
446   while (item != NULL)
447     {
448       const struct language_defn *language;
449       gdb::unique_xmalloc_ptr<char> sym_name;
450       struct symbol *sym;
451       const struct block *sym_block;
452       struct value *val;
453       enum ext_lang_bt_status success = EXT_LANG_BT_ERROR;
454
455       success = extract_sym (item.get (), &sym_name, &sym, &sym_block,
456                              &language);
457       if (success == EXT_LANG_BT_ERROR)
458         return EXT_LANG_BT_ERROR;
459
460       success = extract_value (item.get (), &val);
461       if (success == EXT_LANG_BT_ERROR)
462         return EXT_LANG_BT_ERROR;
463
464       if (sym && out->is_mi_like_p ()
465           && ! mi_should_print (sym, MI_PRINT_ARGS))
466         continue;
467
468       /* If the object did not provide a value, read it using
469          read_frame_args and account for entry values, if any.  */
470       if (val == NULL)
471         {
472           struct frame_arg arg, entryarg;
473
474           /* If there is no value, and also no symbol, set error and
475              exit.  */
476           if (sym == NULL)
477             {
478               PyErr_SetString (PyExc_RuntimeError,
479                                _("No symbol or value provided."));
480               return EXT_LANG_BT_ERROR;
481             }
482
483           read_frame_arg (user_frame_print_options,
484                           sym, frame, &arg, &entryarg);
485
486           /* The object has not provided a value, so this is a frame
487              argument to be read by GDB.  In this case we have to
488              account for entry-values.  */
489
490           if (arg.entry_kind != print_entry_values_only)
491             {
492               py_print_single_arg (out, NULL, &arg,
493                                    NULL, &opts,
494                                    args_type,
495                                    print_args_field,
496                                    NULL);
497             }
498
499           if (entryarg.entry_kind != print_entry_values_no)
500             {
501               if (arg.entry_kind != print_entry_values_only)
502                 {
503                   out->text (", ");
504                   out->wrap_hint (4);
505                 }
506
507               py_print_single_arg (out, NULL, &entryarg, NULL, &opts,
508                                    args_type, print_args_field, NULL);
509             }
510         }
511       else
512         {
513           /* If the object has provided a value, we just print that.  */
514           if (val != NULL)
515             py_print_single_arg (out, sym_name.get (), NULL, val, &opts,
516                                  args_type, print_args_field,
517                                  language);
518         }
519
520       /* Collect the next item from the iterator.  If
521          this is the last item, do not print the
522          comma.  */
523       item.reset (PyIter_Next (iter));
524       if (item != NULL)
525         out->text (", ");
526       else if (PyErr_Occurred ())
527         return EXT_LANG_BT_ERROR;
528
529       annotate_arg_end ();
530     }
531
532   return EXT_LANG_BT_OK;
533 }
534
535
536 /* Helper function to loop over variables provided by the
537    "frame_locals" Python API.  Elements in the iterable must conform
538    to the "Symbol Value" interface.  ITER is the Python iterable
539    object, OUT is the output stream, INDENT is whether we should
540    indent the output (for CLI), ARGS_TYPE is an enumerator describing
541    the argument format, PRINT_ARGS_FIELD is flag which indicates
542    whether to output the ARGS field in the case of
543    -stack-list-variables and FRAME is the backing frame.  Returns
544    EXT_LANG_BT_ERROR on error, with any GDB exceptions converted to a Python
545    exception, or EXT_LANG_BT_OK on success.  */
546
547 static enum ext_lang_bt_status
548 enumerate_locals (PyObject *iter,
549                   struct ui_out *out,
550                   int indent,
551                   enum ext_lang_frame_args args_type,
552                   int print_args_field,
553                   struct frame_info *frame)
554 {
555   struct value_print_options opts;
556
557   get_user_print_options (&opts);
558   opts.deref_ref = 1;
559
560   while (true)
561     {
562       const struct language_defn *language;
563       gdb::unique_xmalloc_ptr<char> sym_name;
564       struct value *val;
565       enum ext_lang_bt_status success = EXT_LANG_BT_ERROR;
566       struct symbol *sym;
567       const struct block *sym_block;
568       int local_indent = 8 + (8 * indent);
569       gdb::optional<ui_out_emit_tuple> tuple;
570
571       gdbpy_ref<> item (PyIter_Next (iter));
572       if (item == NULL)
573         break;
574
575       success = extract_sym (item.get (), &sym_name, &sym, &sym_block,
576                              &language);
577       if (success == EXT_LANG_BT_ERROR)
578         return EXT_LANG_BT_ERROR;
579
580       success = extract_value (item.get (), &val);
581       if (success == EXT_LANG_BT_ERROR)
582         return EXT_LANG_BT_ERROR;
583
584       if (sym != NULL && out->is_mi_like_p ()
585           && ! mi_should_print (sym, MI_PRINT_LOCALS))
586         continue;
587
588       /* If the object did not provide a value, read it.  */
589       if (val == NULL)
590         val = read_var_value (sym, sym_block, frame);
591
592       /* With PRINT_NO_VALUES, MI does not emit a tuple normally as
593          each output contains only one field.  The exception is
594          -stack-list-variables, which always provides a tuple.  */
595       if (out->is_mi_like_p ())
596         {
597           if (print_args_field || args_type != NO_VALUES)
598             tuple.emplace (out, nullptr);
599         }
600
601       /* If the output is not MI we indent locals.  */
602       out->spaces (local_indent);
603       out->field_string ("name", sym_name.get ());
604       out->text (" = ");
605
606       if (args_type == MI_PRINT_SIMPLE_VALUES)
607         py_print_type (out, val);
608
609       /* CLI always prints values for locals.  MI uses the
610          simple/no/all system.  */
611       if (! out->is_mi_like_p ())
612         {
613           int val_indent = (indent + 1) * 4;
614
615           py_print_value (out, val, &opts, val_indent, args_type,
616                           language);
617         }
618       else
619         {
620           if (args_type != NO_VALUES)
621             py_print_value (out, val, &opts, 0, args_type,
622                             language);
623         }
624
625       out->text ("\n");
626     }
627
628   if (!PyErr_Occurred ())
629     return EXT_LANG_BT_OK;
630
631   return EXT_LANG_BT_ERROR;
632 }
633
634 /*  Helper function for -stack-list-variables.  Returns EXT_LANG_BT_ERROR on
635     error, or EXT_LANG_BT_OK on success.  */
636
637 static enum ext_lang_bt_status
638 py_mi_print_variables (PyObject *filter, struct ui_out *out,
639                        struct value_print_options *opts,
640                        enum ext_lang_frame_args args_type,
641                        struct frame_info *frame)
642 {
643   gdbpy_ref<> args_iter (get_py_iter_from_func (filter, "frame_args"));
644   if (args_iter == NULL)
645     return EXT_LANG_BT_ERROR;
646
647   gdbpy_ref<> locals_iter (get_py_iter_from_func (filter, "frame_locals"));
648   if (locals_iter == NULL)
649     return EXT_LANG_BT_ERROR;
650
651   ui_out_emit_list list_emitter (out, "variables");
652
653   if (args_iter != Py_None
654       && (enumerate_args (args_iter.get (), out, args_type, 1, frame)
655           == EXT_LANG_BT_ERROR))
656     return EXT_LANG_BT_ERROR;
657
658   if (locals_iter != Py_None
659       && (enumerate_locals (locals_iter.get (), out, 1, args_type, 1, frame)
660           == EXT_LANG_BT_ERROR))
661     return EXT_LANG_BT_ERROR;
662
663   return EXT_LANG_BT_OK;
664 }
665
666 /* Helper function for printing locals.  This function largely just
667    creates the wrapping tuple, and calls enumerate_locals.  Returns
668    EXT_LANG_BT_ERROR on error, or EXT_LANG_BT_OK on success.  */
669
670 static enum ext_lang_bt_status
671 py_print_locals (PyObject *filter,
672                  struct ui_out *out,
673                  enum ext_lang_frame_args args_type,
674                  int indent,
675                  struct frame_info *frame)
676 {
677   gdbpy_ref<> locals_iter (get_py_iter_from_func (filter, "frame_locals"));
678   if (locals_iter == NULL)
679     return EXT_LANG_BT_ERROR;
680
681   ui_out_emit_list list_emitter (out, "locals");
682
683   if (locals_iter != Py_None
684       && (enumerate_locals (locals_iter.get (), out, indent, args_type,
685                             0, frame) == EXT_LANG_BT_ERROR))
686     return EXT_LANG_BT_ERROR;
687
688   return EXT_LANG_BT_OK;
689 }
690
691 /* Helper function for printing frame arguments.  This function
692    largely just creates the wrapping tuple, and calls enumerate_args.
693    Returns EXT_LANG_BT_ERROR on error, with any GDB exceptions converted to
694    a Python exception, or EXT_LANG_BT_OK on success.  */
695
696 static enum ext_lang_bt_status
697 py_print_args (PyObject *filter,
698                struct ui_out *out,
699                enum ext_lang_frame_args args_type,
700                struct frame_info *frame)
701 {
702   gdbpy_ref<> args_iter (get_py_iter_from_func (filter, "frame_args"));
703   if (args_iter == NULL)
704     return EXT_LANG_BT_ERROR;
705
706   ui_out_emit_list list_emitter (out, "args");
707
708   out->wrap_hint (3);
709   annotate_frame_args ();
710   out->text (" (");
711
712   if (args_type == CLI_PRESENCE)
713     {
714       if (args_iter != Py_None)
715         {
716           gdbpy_ref<> item (PyIter_Next (args_iter.get ()));
717
718           if (item != NULL)
719             out->text ("...");
720           else if (PyErr_Occurred ())
721             return EXT_LANG_BT_ERROR;
722         }
723     }
724   else if (args_iter != Py_None
725            && (enumerate_args (args_iter.get (), out, args_type, 0, frame)
726                == EXT_LANG_BT_ERROR))
727     return EXT_LANG_BT_ERROR;
728
729   out->text (")");
730
731   return EXT_LANG_BT_OK;
732 }
733
734 /*  Print a single frame to the designated output stream, detecting
735     whether the output is MI or console, and formatting the output
736     according to the conventions of that protocol.  FILTER is the
737     frame-filter associated with this frame.  FLAGS is an integer
738     describing the various print options.  The FLAGS variables is
739     described in "apply_frame_filter" function.  ARGS_TYPE is an
740     enumerator describing the argument format.  OUT is the output
741     stream to print, INDENT is the level of indention for this frame
742     (in the case of elided frames), and LEVELS_PRINTED is a hash-table
743     containing all the frames level that have already been printed.
744     If a frame level has been printed, do not print it again (in the
745     case of elided frames).  Returns EXT_LANG_BT_ERROR on error, with any
746     GDB exceptions converted to a Python exception, or EXT_LANG_BT_OK
747     on success.  It can also throw an exception RETURN_QUIT.  */
748
749 static enum ext_lang_bt_status
750 py_print_frame (PyObject *filter, frame_filter_flags flags,
751                 enum ext_lang_frame_args args_type,
752                 struct ui_out *out, int indent, htab_t levels_printed)
753 {
754   int has_addr = 0;
755   CORE_ADDR address = 0;
756   struct gdbarch *gdbarch = NULL;
757   struct frame_info *frame = NULL;
758   struct value_print_options opts;
759
760   int print_level, print_frame_info, print_args, print_locals;
761   /* Note that the below default in non-mi mode is the same as the
762      default value for the backtrace command (see the call to print_frame_info
763      in backtrace_command_1).
764      Having the same default ensures that 'bt' and 'bt no-filters'
765      have the same behaviour when some filters exist but do not apply
766      to a frame.  */
767   enum print_what print_what
768     = out->is_mi_like_p () ? LOC_AND_ADDRESS : LOCATION;
769   gdb::unique_xmalloc_ptr<char> function_to_free;
770
771   /* Extract print settings from FLAGS.  */
772   print_level = (flags & PRINT_LEVEL) ? 1 : 0;
773   print_frame_info = (flags & PRINT_FRAME_INFO) ? 1 : 0;
774   print_args = (flags & PRINT_ARGS) ? 1 : 0;
775   print_locals = (flags & PRINT_LOCALS) ? 1 : 0;
776
777   get_user_print_options (&opts);
778   if (print_frame_info)
779     {
780       gdb::optional<enum print_what> user_frame_info_print_what;
781
782       get_user_print_what_frame_info (&user_frame_info_print_what);
783       if (!out->is_mi_like_p () && user_frame_info_print_what.has_value ())
784         {
785           /* Use the specific frame information desired by the user.  */
786           print_what = *user_frame_info_print_what;
787         }
788     }
789
790   /* Get the underlying frame.  This is needed to determine GDB
791   architecture, and also, in the cases of frame variables/arguments to
792   read them if they returned filter object requires us to do so.  */
793   gdbpy_ref<> py_inf_frame (PyObject_CallMethod (filter, "inferior_frame",
794                                                  NULL));
795   if (py_inf_frame == NULL)
796     return EXT_LANG_BT_ERROR;
797
798   frame = frame_object_to_frame_info (py_inf_frame.get ());
799   if (frame == NULL)
800     return EXT_LANG_BT_ERROR;
801
802   symtab_and_line sal = find_frame_sal (frame);
803
804   gdbarch = get_frame_arch (frame);
805
806   /* stack-list-variables.  */
807   if (print_locals && print_args && ! print_frame_info)
808     {
809       if (py_mi_print_variables (filter, out, &opts,
810                                  args_type, frame) == EXT_LANG_BT_ERROR)
811         return EXT_LANG_BT_ERROR;
812       return EXT_LANG_BT_OK;
813     }
814
815   gdb::optional<ui_out_emit_tuple> tuple;
816
817   /* -stack-list-locals does not require a
818      wrapping frame attribute.  */
819   if (print_frame_info || (print_args && ! print_locals))
820     tuple.emplace (out, "frame");
821
822   if (print_frame_info)
823     {
824       /* Elided frames are also printed with this function (recursively)
825          and are printed with indention.  */
826       if (indent > 0)
827         out->spaces (indent * 4);
828
829       /* The address is required for frame annotations, and also for
830          address printing.  */
831       if (PyObject_HasAttrString (filter, "address"))
832         {
833           gdbpy_ref<> paddr (PyObject_CallMethod (filter, "address", NULL));
834
835           if (paddr == NULL)
836             return EXT_LANG_BT_ERROR;
837
838           if (paddr != Py_None)
839             {
840               if (get_addr_from_python (paddr.get (), &address) < 0)
841                 return EXT_LANG_BT_ERROR;
842
843               has_addr = 1;
844             }
845         }
846     }
847
848   /* For MI, each piece is controlled individually.  */
849   bool location_print = (print_frame_info
850                          && !out->is_mi_like_p ()
851                          && (print_what == LOCATION
852                              || print_what == SRC_AND_LOC
853                              || print_what == LOC_AND_ADDRESS
854                              || print_what == SHORT_LOCATION));
855
856   /* Print frame level.  MI does not require the level if
857      locals/variables only are being printed.  */
858   if (print_level
859       && (location_print
860           || (out->is_mi_like_p () && (print_frame_info || print_args))))
861     {
862       struct frame_info **slot;
863       int level;
864
865       slot = (struct frame_info **) htab_find_slot (levels_printed,
866                                                     frame, INSERT);
867
868       level = frame_relative_level (frame);
869
870       /* Check if this frame has already been printed (there are cases
871          where elided synthetic dummy-frames have to 'borrow' the frame
872          architecture from the eliding frame.  If that is the case, do
873          not print 'level', but print spaces.  */
874       if (*slot == frame)
875         out->field_skip ("level");
876       else
877         {
878           *slot = frame;
879           annotate_frame_begin (print_level ? level : 0,
880                                 gdbarch, address);
881           out->text ("#");
882           out->field_fmt_signed (2, ui_left, "level", level);
883         }
884     }
885
886   if (location_print || (out->is_mi_like_p () && print_frame_info))
887     {
888       /* Print address to the address field.  If an address is not provided,
889          print nothing.  */
890       if (opts.addressprint && has_addr)
891         {
892           if (!sal.symtab
893               || frame_show_address (frame, sal)
894               || print_what == LOC_AND_ADDRESS)
895             {
896               annotate_frame_address ();
897               out->field_core_addr ("addr", gdbarch, address);
898               if (get_frame_pc_masked (frame))
899                 out->field_string ("pac", " [PAC]");
900               annotate_frame_address_end ();
901               out->text (" in ");
902             }
903         }
904
905       /* Print frame function name.  */
906       if (PyObject_HasAttrString (filter, "function"))
907         {
908           gdbpy_ref<> py_func (PyObject_CallMethod (filter, "function", NULL));
909           const char *function = NULL;
910
911           if (py_func == NULL)
912             return EXT_LANG_BT_ERROR;
913
914           if (gdbpy_is_string (py_func.get ()))
915             {
916               function_to_free = python_string_to_host_string (py_func.get ());
917
918               if (function_to_free == NULL)
919                 return EXT_LANG_BT_ERROR;
920
921               function = function_to_free.get ();
922             }
923           else if (PyLong_Check (py_func.get ()))
924             {
925               CORE_ADDR addr;
926               struct bound_minimal_symbol msymbol;
927
928               if (get_addr_from_python (py_func.get (), &addr) < 0)
929                 return EXT_LANG_BT_ERROR;
930
931               msymbol = lookup_minimal_symbol_by_pc (addr);
932               if (msymbol.minsym != NULL)
933                 function = msymbol.minsym->print_name ();
934             }
935           else if (py_func != Py_None)
936             {
937               PyErr_SetString (PyExc_RuntimeError,
938                                _("FrameDecorator.function: expecting a " \
939                                  "String, integer or None."));
940               return EXT_LANG_BT_ERROR;
941             }
942
943           annotate_frame_function_name ();
944           if (function == NULL)
945             out->field_skip ("func");
946           else
947             out->field_string ("func", function, function_name_style.style ());
948         }
949     }
950
951
952   /* Frame arguments.  Check the result, and error if something went
953      wrong.  */
954   if (print_args && (location_print || out->is_mi_like_p ()))
955     {
956       if (py_print_args (filter, out, args_type, frame) == EXT_LANG_BT_ERROR)
957         return EXT_LANG_BT_ERROR;
958     }
959
960   /* File name/source/line number information.  */
961   bool print_location_source
962     = ((location_print && print_what != SHORT_LOCATION)
963        || (out->is_mi_like_p () && print_frame_info));
964   if (print_location_source)
965     {
966       annotate_frame_source_begin ();
967
968       if (PyObject_HasAttrString (filter, "filename"))
969         {
970           gdbpy_ref<> py_fn (PyObject_CallMethod (filter, "filename", NULL));
971
972           if (py_fn == NULL)
973             return EXT_LANG_BT_ERROR;
974
975           if (py_fn != Py_None)
976             {
977               gdb::unique_xmalloc_ptr<char>
978                 filename (python_string_to_host_string (py_fn.get ()));
979
980               if (filename == NULL)
981                 return EXT_LANG_BT_ERROR;
982
983               out->wrap_hint (3);
984               out->text (" at ");
985               annotate_frame_source_file ();
986               out->field_string ("file", filename.get (),
987                                  file_name_style.style ());
988               annotate_frame_source_file_end ();
989             }
990         }
991
992       if (PyObject_HasAttrString (filter, "line"))
993         {
994           gdbpy_ref<> py_line (PyObject_CallMethod (filter, "line", NULL));
995           int line;
996
997           if (py_line == NULL)
998             return EXT_LANG_BT_ERROR;
999
1000           if (py_line != Py_None)
1001             {
1002               line = PyLong_AsLong (py_line.get ());
1003               if (PyErr_Occurred ())
1004                 return EXT_LANG_BT_ERROR;
1005
1006               out->text (":");
1007               annotate_frame_source_line ();
1008               out->field_signed ("line", line);
1009             }
1010         }
1011       if (out->is_mi_like_p ())
1012         out->field_string ("arch",
1013                            (gdbarch_bfd_arch_info (gdbarch))->printable_name);
1014     }
1015
1016   bool source_print
1017     = (! out->is_mi_like_p ()
1018        && (print_what == SRC_LINE || print_what == SRC_AND_LOC));
1019   if (source_print)
1020     {
1021       if (print_location_source)
1022         out->text ("\n"); /* Newline after the location source.  */
1023       print_source_lines (sal.symtab, sal.line, sal.line + 1, 0);
1024     }
1025
1026   /* For MI we need to deal with the "children" list population of
1027      elided frames, so if MI output detected do not send newline.  */
1028   if (! out->is_mi_like_p ())
1029     {
1030       annotate_frame_end ();
1031       /* print_source_lines has already printed a newline.  */
1032       if (!source_print)
1033         out->text ("\n");
1034     }
1035
1036   if (print_locals)
1037     {
1038       if (py_print_locals (filter, out, args_type, indent,
1039                            frame) == EXT_LANG_BT_ERROR)
1040         return EXT_LANG_BT_ERROR;
1041     }
1042
1043   if ((flags & PRINT_HIDE) == 0)
1044     {
1045       /* Finally recursively print elided frames, if any.  */
1046       gdbpy_ref<> elided (get_py_iter_from_func (filter, "elided"));
1047       if (elided == NULL)
1048         return EXT_LANG_BT_ERROR;
1049
1050       if (elided != Py_None)
1051         {
1052           PyObject *item;
1053
1054           ui_out_emit_list inner_list_emiter (out, "children");
1055
1056           indent++;
1057
1058           while ((item = PyIter_Next (elided.get ())))
1059             {
1060               gdbpy_ref<> item_ref (item);
1061
1062               enum ext_lang_bt_status success
1063                 = py_print_frame (item, flags, args_type, out, indent,
1064                                   levels_printed);
1065
1066               if (success == EXT_LANG_BT_ERROR)
1067                 return EXT_LANG_BT_ERROR;
1068             }
1069           if (item == NULL && PyErr_Occurred ())
1070             return EXT_LANG_BT_ERROR;
1071         }
1072     }
1073
1074   return EXT_LANG_BT_OK;
1075 }
1076
1077 /* Helper function to initiate frame filter invocation at starting
1078    frame FRAME.  */
1079
1080 static PyObject *
1081 bootstrap_python_frame_filters (struct frame_info *frame,
1082                                 int frame_low, int frame_high)
1083 {
1084   gdbpy_ref<> frame_obj (frame_info_to_frame_object (frame));
1085   if (frame_obj == NULL)
1086     return NULL;
1087
1088   gdbpy_ref<> module (PyImport_ImportModule ("gdb.frames"));
1089   if (module == NULL)
1090     return NULL;
1091
1092   gdbpy_ref<> sort_func (PyObject_GetAttrString (module.get (),
1093                                                  "execute_frame_filters"));
1094   if (sort_func == NULL)
1095     return NULL;
1096
1097   gdbpy_ref<> py_frame_low = gdb_py_object_from_longest (frame_low);
1098   if (py_frame_low == NULL)
1099     return NULL;
1100
1101   gdbpy_ref<> py_frame_high = gdb_py_object_from_longest (frame_high);
1102   if (py_frame_high == NULL)
1103     return NULL;
1104
1105   gdbpy_ref<> iterable (PyObject_CallFunctionObjArgs (sort_func.get (),
1106                                                       frame_obj.get (),
1107                                                       py_frame_low.get (),
1108                                                       py_frame_high.get (),
1109                                                       NULL));
1110   if (iterable == NULL)
1111     return NULL;
1112
1113   if (iterable != Py_None)
1114     return PyObject_GetIter (iterable.get ());
1115   else
1116     return iterable.release ();
1117 }
1118
1119 /*  This is the only publicly exported function in this file.  FRAME
1120     is the source frame to start frame-filter invocation.  FLAGS is an
1121     integer holding the flags for printing.  The following elements of
1122     the FRAME_FILTER_FLAGS enum denotes the make-up of FLAGS:
1123     PRINT_LEVEL is a flag indicating whether to print the frame's
1124     relative level in the output.  PRINT_FRAME_INFO is a flag that
1125     indicates whether this function should print the frame
1126     information, PRINT_ARGS is a flag that indicates whether to print
1127     frame arguments, and PRINT_LOCALS, likewise, with frame local
1128     variables.  ARGS_TYPE is an enumerator describing the argument
1129     format, OUT is the output stream to print.  FRAME_LOW is the
1130     beginning of the slice of frames to print, and FRAME_HIGH is the
1131     upper limit of the frames to count.  Returns EXT_LANG_BT_ERROR on error,
1132     or EXT_LANG_BT_OK on success.  */
1133
1134 enum ext_lang_bt_status
1135 gdbpy_apply_frame_filter (const struct extension_language_defn *extlang,
1136                           struct frame_info *frame, frame_filter_flags flags,
1137                           enum ext_lang_frame_args args_type,
1138                           struct ui_out *out, int frame_low, int frame_high)
1139 {
1140   struct gdbarch *gdbarch = NULL;
1141   enum ext_lang_bt_status success = EXT_LANG_BT_ERROR;
1142
1143   if (!gdb_python_initialized)
1144     return EXT_LANG_BT_NO_FILTERS;
1145
1146   try
1147     {
1148       gdbarch = get_frame_arch (frame);
1149     }
1150   catch (const gdb_exception_error &except)
1151     {
1152       /* Let gdb try to print the stack trace.  */
1153       return EXT_LANG_BT_NO_FILTERS;
1154     }
1155
1156   gdbpy_enter enter_py (gdbarch);
1157
1158   /* When we're limiting the number of frames, be careful to request
1159      one extra frame, so that we can print a message if there are more
1160      frames.  */
1161   int frame_countdown = -1;
1162   if ((flags & PRINT_MORE_FRAMES) != 0 && frame_low >= 0 && frame_high >= 0)
1163     {
1164       ++frame_high;
1165       /* This has an extra +1 because it is checked before a frame is
1166          printed.  */
1167       frame_countdown = frame_high - frame_low + 1;
1168     }
1169
1170   gdbpy_ref<> iterable (bootstrap_python_frame_filters (frame, frame_low,
1171                                                         frame_high));
1172
1173   if (iterable == NULL)
1174     {
1175       /* Normally if there is an error GDB prints the exception,
1176          abandons the backtrace and exits.  The user can then call "bt
1177          no-filters", and get a default backtrace (it would be
1178          confusing to automatically start a standard backtrace halfway
1179          through a Python filtered backtrace).  However in the case
1180          where GDB cannot initialize the frame filters (most likely
1181          due to incorrect auto-load paths), GDB has printed nothing.
1182          In this case it is OK to print the default backtrace after
1183          printing the error message.  GDB returns EXT_LANG_BT_NO_FILTERS
1184          here to signify there are no filters after printing the
1185          initialization error.  This return code will trigger a
1186          default backtrace.  */
1187
1188       gdbpy_print_stack_or_quit ();
1189       return EXT_LANG_BT_NO_FILTERS;
1190     }
1191
1192   /* If iterable is None, then there are no frame filters registered.
1193      If this is the case, defer to default GDB printing routines in MI
1194      and CLI.  */
1195   if (iterable == Py_None)
1196     return EXT_LANG_BT_NO_FILTERS;
1197
1198   htab_up levels_printed (htab_create (20,
1199                                        htab_hash_pointer,
1200                                        htab_eq_pointer,
1201                                        NULL));
1202
1203   while (true)
1204     {
1205       gdbpy_ref<> item (PyIter_Next (iterable.get ()));
1206
1207       if (item == NULL)
1208         {
1209           if (PyErr_Occurred ())
1210             {
1211               gdbpy_print_stack_or_quit ();
1212               return EXT_LANG_BT_ERROR;
1213             }
1214           break;
1215         }
1216
1217       if (frame_countdown != -1)
1218         {
1219           gdb_assert ((flags & PRINT_MORE_FRAMES) != 0);
1220           --frame_countdown;
1221           if (frame_countdown == 0)
1222             {
1223               /* We've printed all the frames we were asked to
1224                  print, but more frames existed.  */
1225               gdb_printf (_("(More stack frames follow...)\n"));
1226               break;
1227             }
1228         }
1229
1230       try
1231         {
1232           success = py_print_frame (item.get (), flags, args_type, out, 0,
1233                                     levels_printed.get ());
1234         }
1235       catch (const gdb_exception_error &except)
1236         {
1237           gdbpy_convert_exception (except);
1238           success = EXT_LANG_BT_ERROR;
1239         }
1240
1241       /* Do not exit on error printing a single frame.  Print the
1242          error and continue with other frames.  */
1243       if (success == EXT_LANG_BT_ERROR)
1244         gdbpy_print_stack_or_quit ();
1245     }
1246
1247   return success;
1248 }
This page took 0.098562 seconds and 4 git commands to generate.