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