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