]> Git Repo - binutils.git/blob - gdb/python/py-prettyprint.c
7aa83bce41a733ec3d6837c2bd3014bd3129d612
[binutils.git] / gdb / python / py-prettyprint.c
1 /* Python pretty-printing
2
3    Copyright (C) 2008, 2009, 2010 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 "exceptions.h"
22 #include "objfiles.h"
23 #include "symtab.h"
24 #include "language.h"
25 #include "valprint.h"
26
27 #include "python.h"
28
29 #ifdef HAVE_PYTHON
30 #include "python-internal.h"
31
32 /* Helper function for find_pretty_printer which iterates over a list,
33    calls each function and inspects output.  This will return a
34    printer object if one recognizes VALUE.  If no printer is found, it
35    will return None.  On error, it will set the Python error and
36    return NULL.  */
37
38 static PyObject *
39 search_pp_list (PyObject *list, PyObject *value)
40 {
41   Py_ssize_t pp_list_size, list_index;
42   PyObject *function, *printer = NULL;
43
44   pp_list_size = PyList_Size (list);
45   for (list_index = 0; list_index < pp_list_size; list_index++)
46     {
47       function = PyList_GetItem (list, list_index);
48       if (! function)
49         return NULL;
50
51       /* Skip if disabled.  */
52       if (PyObject_HasAttr (function, gdbpy_enabled_cst))
53         {
54           PyObject *attr = PyObject_GetAttr (function, gdbpy_enabled_cst);
55           int cmp;
56
57           if (!attr)
58             return NULL;
59           cmp = PyObject_IsTrue (attr);
60           if (cmp == -1)
61             return NULL;
62
63           if (!cmp)
64             continue;
65         }
66
67       printer = PyObject_CallFunctionObjArgs (function, value, NULL);
68       if (! printer)
69         return NULL;
70       else if (printer != Py_None)
71         return printer;
72
73       Py_DECREF (printer);
74     }
75
76   Py_RETURN_NONE;
77 }
78
79 /* Subroutine of find_pretty_printer to simplify it.
80    Look for a pretty-printer to print VALUE in all objfiles.
81    The result is NULL if there's an error and the search should be terminated.
82    The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
83    Otherwise the result is the pretty-printer function, suitably inc-ref'd.  */
84
85 static PyObject *
86 find_pretty_printer_from_objfiles (PyObject *value)
87 {
88   PyObject *pp_list;
89   PyObject *function;
90   struct objfile *obj;
91
92   ALL_OBJFILES (obj)
93   {
94     PyObject *objf = objfile_to_objfile_object (obj);
95     if (!objf)
96       {
97         /* Ignore the error and continue.  */
98         PyErr_Clear ();
99         continue;
100       }
101
102     pp_list = objfpy_get_printers (objf, NULL);
103     function = search_pp_list (pp_list, value);
104     Py_XDECREF (pp_list);
105
106     /* If there is an error in any objfile list, abort the search and exit.  */
107     if (! function)
108       return NULL;
109
110     if (function != Py_None)
111       return function;
112     
113     Py_DECREF (function);
114   }
115
116   Py_RETURN_NONE;
117 }
118
119 /* Subroutine of find_pretty_printer to simplify it.
120    Look for a pretty-printer to print VALUE in the current program space.
121    The result is NULL if there's an error and the search should be terminated.
122    The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
123    Otherwise the result is the pretty-printer function, suitably inc-ref'd.  */
124
125 static PyObject *
126 find_pretty_printer_from_progspace (PyObject *value)
127 {
128   PyObject *pp_list;
129   PyObject *function;
130   PyObject *obj = pspace_to_pspace_object (current_program_space);
131
132   if (!obj)
133     return NULL;
134   pp_list = pspy_get_printers (obj, NULL);
135   function = search_pp_list (pp_list, value);
136   Py_XDECREF (pp_list);
137   return function;
138 }
139
140 /* Subroutine of find_pretty_printer to simplify it.
141    Look for a pretty-printer to print VALUE in the gdb module.
142    The result is NULL if there's an error and the search should be terminated.
143    The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
144    Otherwise the result is the pretty-printer function, suitably inc-ref'd.  */
145
146 static PyObject *
147 find_pretty_printer_from_gdb (PyObject *value)
148 {
149   PyObject *pp_list;
150   PyObject *function;
151
152   /* Fetch the global pretty printer dictionary.  */
153   if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
154     Py_RETURN_NONE;
155   pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
156   if (pp_list == NULL || ! PyList_Check (pp_list))
157     {
158       Py_XDECREF (pp_list);
159       Py_RETURN_NONE;
160     }
161
162   function = search_pp_list (pp_list, value);
163   Py_XDECREF (pp_list);
164   return function;
165 }
166
167 /* Find the pretty-printing constructor function for VALUE.  If no
168    pretty-printer exists, return None.  If one exists, return a new
169    reference.  On error, set the Python error and return NULL.  */
170
171 static PyObject *
172 find_pretty_printer (PyObject *value)
173 {
174   PyObject *function;
175
176   /* Look at the pretty-printer dictionary for each objfile
177      in the current program-space.  */
178   function = find_pretty_printer_from_objfiles (value);
179   if (function == NULL || function != Py_None)
180     return function;
181   Py_DECREF (function);
182
183   /* Look at the pretty-printer dictionary for the current program-space.  */
184   function = find_pretty_printer_from_progspace (value);
185   if (function == NULL || function != Py_None)
186     return function;
187   Py_DECREF (function);
188
189   /* Look at the pretty-printer dictionary in the gdb module.  */
190   function = find_pretty_printer_from_gdb (value);
191   return function;
192 }
193
194 /* Pretty-print a single value, via the printer object PRINTER.
195    If the function returns a string, a PyObject containing the string
196    is returned.  If the function returns Py_NONE that means the pretty
197    printer returned the Python None as a value.  Otherwise, if the
198    function returns a value,  *OUT_VALUE is set to the value, and NULL
199    is returned.  On error, *OUT_VALUE is set to NULL, and NULL is
200    returned.  */
201
202 static PyObject *
203 pretty_print_one_value (PyObject *printer, struct value **out_value)
204 {
205   volatile struct gdb_exception except;
206   PyObject *result = NULL;
207
208   *out_value = NULL;
209   TRY_CATCH (except, RETURN_MASK_ALL)
210     {
211       result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
212       if (result)
213         {
214           if (! gdbpy_is_string (result) && ! gdbpy_is_lazy_string (result)  
215               && result != Py_None)
216             {
217               *out_value = convert_value_from_python (result);
218               if (PyErr_Occurred ())
219                 *out_value = NULL;
220               Py_DECREF (result);
221               result = NULL;
222             }
223         }
224     }
225
226   return result;
227 }
228
229 /* Return the display hint for the object printer, PRINTER.  Return
230    NULL if there is no display_hint method, or if the method did not
231    return a string.  On error, print stack trace and return NULL.  On
232    success, return an xmalloc()d string.  */
233 char *
234 gdbpy_get_display_hint (PyObject *printer)
235 {
236   PyObject *hint;
237   char *result = NULL;
238
239   if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
240     return NULL;
241
242   hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
243   if (hint)
244     {
245       if (gdbpy_is_string (hint))
246         result = python_string_to_host_string (hint);
247       Py_DECREF (hint);
248     }
249   else
250     gdbpy_print_stack ();
251
252   return result;
253 }
254
255 /* Helper for apply_val_pretty_printer which calls to_string and
256    formats the result.  If the value returnd is Py_None, nothing is
257    printed and the function returns a 1; in all other cases data is
258    printed as given by the pretty printer and the function returns 0.
259 */
260 static int
261 print_string_repr (PyObject *printer, const char *hint,
262                    struct ui_file *stream, int recurse,
263                    const struct value_print_options *options,
264                    const struct language_defn *language,
265                    struct gdbarch *gdbarch)
266 {
267   struct value *replacement = NULL;
268   PyObject *py_str = NULL;
269   int is_py_none = 0;
270
271   py_str = pretty_print_one_value (printer, &replacement);
272   if (py_str)
273     {
274       if (py_str == Py_None)
275         is_py_none = 1;
276       else
277         {
278           gdb_byte *output = NULL;
279           long length;
280           struct type *type;
281           char *encoding = NULL;
282           PyObject *string = NULL;
283           int is_lazy;
284
285           is_lazy = gdbpy_is_lazy_string (py_str);
286           if (is_lazy)
287             output = gdbpy_extract_lazy_string (py_str, &type, &length, &encoding);
288           else
289             {
290               string = python_string_to_target_python_string (py_str);
291               if (string)
292                 {
293                   output = PyString_AsString (string);
294                   length = PyString_Size (string);
295                   type = builtin_type (gdbarch)->builtin_char;
296                 }
297               else
298                 gdbpy_print_stack ();
299               
300             }
301         
302           if (output)
303             {
304               if (is_lazy || (hint && !strcmp (hint, "string")))
305                 LA_PRINT_STRING (stream, type, output, length, encoding,
306                                  0, options);
307               else
308                 fputs_filtered (output, stream);
309             }
310           else
311             gdbpy_print_stack ();
312           
313           if (string)
314             Py_DECREF (string);
315           else
316             xfree (output);
317       
318           xfree (encoding);
319           Py_DECREF (py_str);
320         }
321     }
322   else if (replacement)
323     {
324       struct value_print_options opts = *options;
325
326       opts.addressprint = 0;
327       common_val_print (replacement, stream, recurse, &opts, language);
328     }
329   else
330     gdbpy_print_stack ();
331
332   return is_py_none;
333 }
334
335 static void
336 py_restore_tstate (void *p)
337 {
338   PyFrameObject *frame = p;
339   PyThreadState *tstate = PyThreadState_GET ();
340
341   tstate->frame = frame;
342 }
343
344 /* Create a dummy PyFrameObject, needed to work around
345    a Python-2.4 bug with generators.  */
346 static PyObject *
347 push_dummy_python_frame ()
348 {
349   PyObject *empty_string, *null_tuple, *globals;
350   PyCodeObject *code;
351   PyFrameObject *frame;
352   PyThreadState *tstate;
353
354   empty_string = PyString_FromString ("");
355   if (!empty_string)
356     return NULL;
357
358   null_tuple = PyTuple_New (0);
359   if (!null_tuple)
360     {
361       Py_DECREF (empty_string);
362       return NULL;
363     }
364
365   code = PyCode_New (0,                 /* argcount */
366                      0,                 /* nlocals */
367                      0,                 /* stacksize */
368                      0,                 /* flags */
369                      empty_string,      /* code */
370                      null_tuple,        /* consts */
371                      null_tuple,        /* names */
372                      null_tuple,        /* varnames */
373 #if PYTHON_API_VERSION >= 1010
374                      null_tuple,        /* freevars */
375                      null_tuple,        /* cellvars */
376 #endif
377                      empty_string,      /* filename */
378                      empty_string,      /* name */
379                      1,                 /* firstlineno */
380                      empty_string       /* lnotab */
381                     );
382
383   Py_DECREF (empty_string);
384   Py_DECREF (null_tuple);
385
386   if (!code)
387     return NULL;
388
389   globals = PyDict_New ();
390   if (!globals)
391     {
392       Py_DECREF (code);
393       return NULL;
394     }
395
396   tstate = PyThreadState_GET ();
397
398   frame = PyFrame_New (tstate, code, globals, NULL);
399
400   Py_DECREF (globals);
401   Py_DECREF (code);
402
403   if (!frame)
404     return NULL;
405
406   tstate->frame = frame;
407   make_cleanup (py_restore_tstate, frame->f_back);
408   return (PyObject *) frame;
409 }
410
411 /* Helper for apply_val_pretty_printer that formats children of the
412    printer, if any exist.  If is_py_none is true, then nothing has
413    been printed by to_string, and format output accordingly. */
414 static void
415 print_children (PyObject *printer, const char *hint,
416                 struct ui_file *stream, int recurse,
417                 const struct value_print_options *options,
418                 const struct language_defn *language,
419                 int is_py_none)
420 {
421   int is_map, is_array, done_flag, pretty;
422   unsigned int i;
423   PyObject *children, *iter, *frame;
424   struct cleanup *cleanups;
425
426   if (! PyObject_HasAttr (printer, gdbpy_children_cst))
427     return;
428
429   /* If we are printing a map or an array, we want some special
430      formatting.  */
431   is_map = hint && ! strcmp (hint, "map");
432   is_array = hint && ! strcmp (hint, "array");
433
434   children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
435                                          NULL);
436   if (! children)
437     {
438       gdbpy_print_stack ();
439       return;
440     }
441
442   cleanups = make_cleanup_py_decref (children);
443
444   iter = PyObject_GetIter (children);
445   if (!iter)
446     {
447       gdbpy_print_stack ();
448       goto done;
449     }
450   make_cleanup_py_decref (iter);
451
452   /* Use the prettyprint_arrays option if we are printing an array,
453      and the pretty option otherwise.  */
454   pretty = is_array ? options->prettyprint_arrays : options->pretty;
455
456   /* Manufacture a dummy Python frame to work around Python 2.4 bug,
457      where it insists on having a non-NULL tstate->frame when
458      a generator is called.  */
459   frame = push_dummy_python_frame ();
460   if (!frame)
461     {
462       gdbpy_print_stack ();
463       goto done;
464     }
465   make_cleanup_py_decref (frame);
466
467   done_flag = 0;
468   for (i = 0; i < options->print_max; ++i)
469     {
470       PyObject *py_v, *item = PyIter_Next (iter);
471       char *name;
472       struct cleanup *inner_cleanup;
473
474       if (! item)
475         {
476           if (PyErr_Occurred ())
477             gdbpy_print_stack ();
478           /* Set a flag so we can know whether we printed all the
479              available elements.  */
480           else    
481             done_flag = 1;
482           break;
483         }
484
485       if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
486         {
487           gdbpy_print_stack ();
488           Py_DECREF (item);
489           continue;
490         }
491       inner_cleanup = make_cleanup_py_decref (item);
492
493       /* Print initial "{".  For other elements, there are three
494          cases:
495          1. Maps.  Print a "," after each value element.
496          2. Arrays.  Always print a ",".
497          3. Other.  Always print a ",".  */
498       if (i == 0)
499         {
500          if (is_py_none)
501            fputs_filtered ("{", stream);
502          else
503            fputs_filtered (" = {", stream);
504        }
505
506       else if (! is_map || i % 2 == 0)
507         fputs_filtered (pretty ? "," : ", ", stream);
508
509       /* In summary mode, we just want to print "= {...}" if there is
510          a value.  */
511       if (options->summary)
512         {
513           /* This increment tricks the post-loop logic to print what
514              we want.  */
515           ++i;
516           /* Likewise.  */
517           pretty = 0;
518           break;
519         }
520
521       if (! is_map || i % 2 == 0)
522         {
523           if (pretty)
524             {
525               fputs_filtered ("\n", stream);
526               print_spaces_filtered (2 + 2 * recurse, stream);
527             }
528           else
529             wrap_here (n_spaces (2 + 2 *recurse));
530         }
531
532       if (is_map && i % 2 == 0)
533         fputs_filtered ("[", stream);
534       else if (is_array)
535         {
536           /* We print the index, not whatever the child method
537              returned as the name.  */
538           if (options->print_array_indexes)
539             fprintf_filtered (stream, "[%d] = ", i);
540         }
541       else if (! is_map)
542         {
543           fputs_filtered (name, stream);
544           fputs_filtered (" = ", stream);
545         }
546
547       if (gdbpy_is_lazy_string (py_v) || gdbpy_is_string (py_v))
548         {
549           gdb_byte *output = NULL;
550
551           if (gdbpy_is_lazy_string (py_v))
552             {
553               struct type *type;
554               long length;
555               char *encoding = NULL;
556
557               output = gdbpy_extract_lazy_string (py_v, &type,
558                                                   &length, &encoding);
559               if (!output)
560                 gdbpy_print_stack ();
561               LA_PRINT_STRING (stream, type, output, length, encoding,
562                                0, options);
563               xfree (encoding);
564               xfree (output);
565             }
566           else
567             {
568               output = python_string_to_host_string (py_v);
569               fputs_filtered (output, stream);
570               xfree (output);
571             }
572         }
573       else
574         {
575           struct value *value = convert_value_from_python (py_v);
576
577           if (value == NULL)
578             {
579               gdbpy_print_stack ();
580               error (_("Error while executing Python code."));
581             }
582           else
583             common_val_print (value, stream, recurse + 1, options, language);
584         }
585
586       if (is_map && i % 2 == 0)
587         fputs_filtered ("] = ", stream);
588
589       do_cleanups (inner_cleanup);
590     }
591
592   if (i)
593     {
594       if (!done_flag)
595         {
596           if (pretty)
597             {
598               fputs_filtered ("\n", stream);
599               print_spaces_filtered (2 + 2 * recurse, stream);
600             }
601           fputs_filtered ("...", stream);
602         }
603       if (pretty)
604         {
605           fputs_filtered ("\n", stream);
606           print_spaces_filtered (2 * recurse, stream);
607         }
608       fputs_filtered ("}", stream);
609     }
610
611  done:
612   do_cleanups (cleanups);
613 }
614
615 int
616 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
617                           int embedded_offset, CORE_ADDR address,
618                           struct ui_file *stream, int recurse,
619                           const struct value *val,
620                           const struct value_print_options *options,
621                           const struct language_defn *language)
622 {
623   struct gdbarch *gdbarch = get_type_arch (type);
624   PyObject *printer = NULL;
625   PyObject *val_obj = NULL;
626   struct value *value;
627   char *hint = NULL;
628   struct cleanup *cleanups;
629   int result = 0;
630   int is_py_none = 0;
631   cleanups = ensure_python_env (gdbarch, language);
632
633   /* Instantiate the printer.  */
634   if (valaddr)
635     valaddr += embedded_offset;
636   value = value_from_contents_and_address (type, valaddr,
637                                            address + embedded_offset);
638   if (val != NULL)
639     {
640       set_value_component_location (value, val);
641       /* set_value_component_location resets the address, so we may
642          need to set it again.  */
643       if (VALUE_LVAL (value) != lval_internalvar
644           && VALUE_LVAL (value) != lval_internalvar_component
645           && VALUE_LVAL (value) != lval_computed)
646         set_value_address (value, address + embedded_offset);
647     }
648
649   val_obj = value_to_value_object (value);
650   if (! val_obj)
651     goto done;
652   
653   /* Find the constructor.  */
654   printer = find_pretty_printer (val_obj);
655   Py_DECREF (val_obj);
656   make_cleanup_py_decref (printer);
657   if (! printer || printer == Py_None)
658     goto done;
659
660   /* If we are printing a map, we want some special formatting.  */
661   hint = gdbpy_get_display_hint (printer);
662   make_cleanup (free_current_contents, &hint);
663
664   /* Print the section */
665   is_py_none = print_string_repr (printer, hint, stream, recurse,
666                                   options, language, gdbarch);
667   print_children (printer, hint, stream, recurse, options, language,
668                   is_py_none);
669
670   result = 1;
671
672
673  done:
674   if (PyErr_Occurred ())
675     gdbpy_print_stack ();
676   do_cleanups (cleanups);
677   return result;
678 }
679
680
681 /* Apply a pretty-printer for the varobj code.  PRINTER_OBJ is the
682    print object.  It must have a 'to_string' method (but this is
683    checked by varobj, not here) which takes no arguments and
684    returns a string.  The printer will return a value and in the case
685    of a Python string being returned, this function will return a
686    PyObject containing the string.  For any other type, *REPLACEMENT is
687    set to the replacement value and this function returns NULL.  On
688    error, *REPLACEMENT is set to NULL and this function also returns
689    NULL.  */
690 PyObject *
691 apply_varobj_pretty_printer (PyObject *printer_obj,
692                              struct value **replacement)
693 {
694   PyObject *py_str = NULL;
695
696   *replacement = NULL;
697   py_str = pretty_print_one_value (printer_obj, replacement);
698
699   if (*replacement == NULL && py_str == NULL)
700     gdbpy_print_stack ();
701
702   return py_str;
703 }
704
705 /* Find a pretty-printer object for the varobj module.  Returns a new
706    reference to the object if successful; returns NULL if not.  VALUE
707    is the value for which a printer tests to determine if it 
708    can pretty-print the value.  */
709 PyObject *
710 gdbpy_get_varobj_pretty_printer (struct value *value)
711 {
712   PyObject *val_obj;
713   PyObject *pretty_printer = NULL;
714   volatile struct gdb_exception except;
715
716   TRY_CATCH (except, RETURN_MASK_ALL)
717     {
718       value = value_copy (value);
719     }
720   GDB_PY_HANDLE_EXCEPTION (except);
721   
722   val_obj = value_to_value_object (value);
723   if (! val_obj)
724     return NULL;
725
726   pretty_printer = find_pretty_printer (val_obj);
727   Py_DECREF (val_obj);
728   return pretty_printer;
729 }
730
731 /* A Python function which wraps find_pretty_printer and instantiates
732    the resulting class.  This accepts a Value argument and returns a
733    pretty printer instance, or None.  This function is useful as an
734    argument to the MI command -var-set-visualizer.  */
735 PyObject *
736 gdbpy_default_visualizer (PyObject *self, PyObject *args)
737 {
738   PyObject *val_obj;
739   PyObject *cons;
740   struct value *value;
741
742   if (! PyArg_ParseTuple (args, "O", &val_obj))
743     return NULL;
744   value = value_object_to_value (val_obj);
745   if (! value)
746     {
747       PyErr_SetString (PyExc_TypeError, 
748                        _("Argument must be a gdb.Value."));
749       return NULL;
750     }
751
752   cons = find_pretty_printer (val_obj);
753   return cons;
754 }
755
756 #else /* HAVE_PYTHON */
757
758 int
759 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
760                           int embedded_offset, CORE_ADDR address,
761                           struct ui_file *stream, int recurse,
762                           const struct value *val,
763                           const struct value_print_options *options,
764                           const struct language_defn *language)
765 {
766   return 0;
767 }
768
769 #endif /* HAVE_PYTHON */
This page took 0.0616409999999999 seconds and 2 git commands to generate.