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