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