OSDN Git Service

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