Exemplo n.º 1
0
static void
python_new_objfile (struct objfile *objfile)
{
  struct cleanup *cleanup;

  if (!gdb_python_initialized)
    return;

  cleanup = ensure_python_env (objfile != NULL
			       ? get_objfile_arch (objfile)
			       : target_gdbarch (),
			       current_language);

  if (objfile == NULL)
    {
      if (emit_clear_objfiles_event () < 0)
	gdbpy_print_stack ();
    }
  else
    {
      if (emit_new_objfile_event (objfile) < 0)
	gdbpy_print_stack ();
    }

  do_cleanups (cleanup);
}
Exemplo n.º 2
0
/* Return the display hint for the object printer, PRINTER.  Return
   NULL if there is no display_hint method, or if the method did not
   return a string.  On error, print stack trace and return NULL.  On
   success, return an xmalloc()d string.  */
char *
gdbpy_get_display_hint (PyObject *printer)
{
    PyObject *hint;
    char *result = NULL;

    if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
        return NULL;

    hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
    if (hint)
    {
        if (gdbpy_is_string (hint))
        {
            result = python_string_to_host_string (hint);
            if (result == NULL)
                gdbpy_print_stack ();
        }
        Py_DECREF (hint);
    }
    else
        gdbpy_print_stack ();

    return result;
}
Exemplo n.º 3
0
static void
print_stack_unless_memory_error (struct ui_file *stream)
{
    if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
    {
        struct cleanup *cleanup;
        PyObject *type, *value, *trace;
        char *msg;

        PyErr_Fetch (&type, &value, &trace);
        cleanup = make_cleanup_py_decref (type);
        make_cleanup_py_decref (value);
        make_cleanup_py_decref (trace);

        msg = gdbpy_exception_to_string (type, value);
        make_cleanup (xfree, msg);

        if (msg == NULL || *msg == '\0')
            fprintf_filtered (stream, _("<error reading variable>"));
        else
            fprintf_filtered (stream, _("<error reading variable: %s>"), msg);

        do_cleanups (cleanup);
    }
    else
        gdbpy_print_stack ();
}
Exemplo n.º 4
0
void
gdbpy_initialize_py_events (void)
{
//  gdb_py_events.module = Py_InitModule ("events", NULL);
    gdb_py_events.module = PyModule_Create (&moduledef); //"events", NULL);

  if (!gdb_py_events.module)
    goto fail;

  if (add_new_registry (&gdb_py_events.stop, "stop") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.cont, "cont") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.exited, "exited") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0)
    goto fail;

  Py_INCREF (gdb_py_events.module);
  if (PyModule_AddObject (gdb_module,
                          "events",
                          (PyObject *) gdb_py_events.module) < 0)
    goto fail;

  return;

  fail:
   gdbpy_print_stack ();
}
Exemplo n.º 5
0
Arquivo: python.c Projeto: ILyoan/gdb
static void
python_run_simple_file (FILE *file, const char *filename)
{
#ifndef _WIN32

  PyRun_SimpleFile (file, filename);

#else /* _WIN32 */

  char *full_path;
  PyObject *python_file;
  struct cleanup *cleanup;

  /* Because we have a string for a filename, and are using Python to
     open the file, we need to expand any tilde in the path first.  */
  full_path = tilde_expand (filename);
  cleanup = make_cleanup (xfree, full_path);
  python_file = PyFile_FromString (full_path, "r");
  if (! python_file)
    {
      do_cleanups (cleanup);
      gdbpy_print_stack ();
      error (_("Error while opening file: %s"), full_path);
    }
 
  make_cleanup_py_decref (python_file);
  PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
  do_cleanups (cleanup);

#endif /* _WIN32 */
}
Exemplo n.º 6
0
static void
add_thread_object (struct thread_info *tp)
{
  struct cleanup *cleanup;
  thread_object *thread_obj;
  inferior_object *inf_obj;
  struct threadlist_entry *entry;

  if (!gdb_python_initialized)
    return;

  cleanup = ensure_python_env (python_gdbarch, python_language);

  thread_obj = create_thread_object (tp);
  if (!thread_obj)
    {
      gdbpy_print_stack ();
      do_cleanups (cleanup);
      return;
    }

  inf_obj = (inferior_object *) thread_obj->inf_obj;

  entry = xmalloc (sizeof (struct threadlist_entry));
  entry->thread_obj = thread_obj;
  entry->next = inf_obj->threads;

  inf_obj->threads = entry;
  inf_obj->nthreads++;

  do_cleanups (cleanup);
}
Exemplo n.º 7
0
static void
python_command (char *arg, int from_tty)
{
    struct cleanup *cleanup;

    cleanup = ensure_python_env (get_current_arch (), current_language);
    while (arg && *arg && isspace (*arg))
        ++arg;
    if (arg && *arg)
    {
        if (PyRun_SimpleString (arg))
        {
            gdbpy_print_stack ();
            error (_("Error while executing Python code."));
        }
    }
    else
    {
        struct command_line *l = get_command_line (python_control, "");

        make_cleanup_free_command_lines (&l);
        execute_control_command_untraced (l);
    }

    do_cleanups (cleanup);
}
Exemplo n.º 8
0
static void
print_stack_unless_memory_error (struct ui_file *stream)
{
  if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
    {
      PyObject *type, *value, *trace;

      PyErr_Fetch (&type, &value, &trace);

      gdbpy_ref<> type_ref (type);
      gdbpy_ref<> value_ref (value);
      gdbpy_ref<> trace_ref (trace);

      gdb::unique_xmalloc_ptr<char>
	msg (gdbpy_exception_to_string (type, value));

      if (msg == NULL || *msg == '\0')
	fprintf_filtered (stream, _("<error reading variable>"));
      else
	fprintf_filtered (stream, _("<error reading variable: %s>"),
			  msg.get ());
    }
  else
    gdbpy_print_stack ();
}
Exemplo n.º 9
0
int
evpy_emit_event (PyObject *event,
                 eventregistry_object *registry)
{
  PyObject *callback_list_copy = NULL;
  Py_ssize_t i;

  /* Create a copy of call back list and use that for
     notifying listeners to avoid skipping callbacks
     in the case of a callback being disconnected during
     a notification.  */
  callback_list_copy = PySequence_List (registry->callbacks);
  if (!callback_list_copy)
    goto fail;

  for (i = 0; i < PyList_Size (callback_list_copy); i++)
    {
      PyObject *func = PyList_GetItem (callback_list_copy, i);
      PyObject *func_result;

      if (func == NULL)
	goto fail;

      func_result = PyObject_CallFunctionObjArgs (func, event, NULL);

      if (func_result == NULL)
	{
	  /* Print the trace here, but keep going -- we want to try to
	     call all of the callbacks even if one is broken.  */
	  gdbpy_print_stack ();
	}
      else
	{
	  Py_DECREF (func_result);
	}
    }

  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return 0;

 fail:
  gdbpy_print_stack ();
  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return -1;
}
static struct value *
fnpy_call (struct gdbarch *gdbarch, const struct language_defn *language,
	   void *cookie, int argc, struct value **argv)
{
  struct value *value = NULL;
  PyObject *result, *callable, *args;
  struct cleanup *cleanup;

  cleanup = ensure_python_env (gdbarch, language);

  args = convert_values_to_python (argc, argv);

  callable = PyObject_GetAttrString ((PyObject *) cookie, "invoke");
  if (! callable)
    {
      Py_DECREF (args);
      error (_("No method named 'invoke' in object."));
    }

  result = PyObject_Call (callable, args, NULL);
  Py_DECREF (callable);
  Py_DECREF (args);

  if (!result)
    {
      gdbpy_print_stack ();
      error (_("Error while executing Python code."));
    }

  value = convert_value_from_python (result);
  if (value == NULL)
    {
      Py_DECREF (result);
      gdbpy_print_stack ();
      error (_("Error while executing Python code."));
    }

  Py_DECREF (result);
  do_cleanups (cleanup);

  return value;
}
Exemplo n.º 11
0
static void
python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
{
  struct cleanup *cleanup;

  cleanup = ensure_python_env (target_gdbarch (), current_language);

  if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 12
0
static void
python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
{
  struct cleanup *cleanup;

  cleanup = ensure_python_env (target_gdbarch (), current_language);

  if (emit_memory_changed_event (addr, len) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 13
0
static void
python_on_register_change (struct frame_info *frame, int regnum)
{
  struct cleanup *cleanup;

  cleanup = ensure_python_env (target_gdbarch (), current_language);

  if (emit_register_changed_event (frame, regnum) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
void
bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object *bp_obj)
{
  struct finish_breakpoint_object *self_finishbp =
        (struct finish_breakpoint_object *) bp_obj;

  /* Can compute return_value only once.  */
  gdb_assert (!self_finishbp->return_value);

  if (!self_finishbp->return_type)
    return;

  TRY
    {
      struct value *function =
        value_object_to_value (self_finishbp->function_value);
      struct type *value_type =
        type_object_to_type (self_finishbp->return_type);

      /* bpfinishpy_init cannot finish into DUMMY_FRAME (throws an error
         in such case) so it is OK to always pass CTX_SAVER as NULL.  */
      struct value *ret = get_return_value (function, value_type, NULL);

      if (ret)
        {
          self_finishbp->return_value = value_to_value_object (ret);
          if (!self_finishbp->return_value)
              gdbpy_print_stack ();
        }
      else
        {
          Py_INCREF (Py_None);
          self_finishbp->return_value = Py_None;
        }
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      gdbpy_convert_exception (except);
      gdbpy_print_stack ();
    }
Exemplo n.º 15
0
void
bpfinishpy_pre_stop_hook (struct breakpoint_object *bp_obj)
{
  struct finish_breakpoint_object *self_finishbp =
        (struct finish_breakpoint_object *) bp_obj;
  volatile struct gdb_exception except;

  /* Can compute return_value only once.  */
  gdb_assert (!self_finishbp->return_value);

  if (!self_finishbp->return_type)
    return;

  TRY_CATCH (except, RETURN_MASK_ALL)
    {
      struct value *function =
        value_object_to_value (self_finishbp->function_value);
      struct type *value_type =
        type_object_to_type (self_finishbp->return_type);
      struct value *ret = get_return_value (function, value_type);

      if (ret)
        {
          self_finishbp->return_value = value_to_value_object (ret);
          if (!self_finishbp->return_value)
              gdbpy_print_stack ();
        }
      else
        {
          Py_INCREF (Py_None);
          self_finishbp->return_value = Py_None;
        }
    }
  if (except.reason < 0)
    {
      gdbpy_convert_exception (except);
      gdbpy_print_stack ();
    }
}
Exemplo n.º 16
0
struct varobj_iter *
py_varobj_get_iterator (struct varobj *var, PyObject *printer)
{
  PyObject *children;
  int i;
  PyObject *iter;
  struct py_varobj_iter *py_iter;
  struct cleanup *back_to = varobj_ensure_python_env (var);

  if (!PyObject_HasAttr (printer, gdbpy_children_cst))
    {
      do_cleanups (back_to);
      return NULL;
    }

  children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
					 NULL);
  if (children == NULL)
    {
      gdbpy_print_stack ();
      error (_("Null value returned for children"));
    }

  make_cleanup_py_decref (children);

  iter = PyObject_GetIter (children);
  if (iter == NULL)
    {
      gdbpy_print_stack ();
      error (_("Could not get children iterator"));
    }

  py_iter = py_varobj_iter_new (var, iter);

  do_cleanups (back_to);

  return &py_iter->base;
}
Exemplo n.º 17
0
static void
python_on_resume (ptid_t ptid)
{
  struct cleanup *cleanup;

  if (!gdb_python_initialized)
    return;

  cleanup = ensure_python_env (target_gdbarch (), current_language);

  if (emit_continue_event (ptid) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 18
0
/* Return the display hint for the object printer, PRINTER.  Return
   NULL if there is no display_hint method, or if the method did not
   return a string.  On error, print stack trace and return NULL.  On
   success, return an xmalloc()d string.  */
gdb::unique_xmalloc_ptr<char>
gdbpy_get_display_hint (PyObject *printer)
{
  gdb::unique_xmalloc_ptr<char> result;

  if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
    return NULL;

  gdbpy_ref<> hint (PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst,
						NULL));
  if (hint != NULL)
    {
      if (gdbpy_is_string (hint.get ()))
	{
	  result = python_string_to_host_string (hint.get ());
	  if (result == NULL)
	    gdbpy_print_stack ();
	}
    }
  else
    gdbpy_print_stack ();

  return result;
}
Exemplo n.º 19
0
static void
python_new_objfile (struct objfile *objfile)
{
  struct cleanup *cleanup;

  if (objfile == NULL)
    return;

  if (!gdb_python_initialized)
    return;

  cleanup = ensure_python_env (get_objfile_arch (objfile), current_language);

  if (emit_new_objfile_event (objfile) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 20
0
static void
python_inferior_exit (struct inferior *inf)
{
  struct cleanup *cleanup;
  const LONGEST *exit_code = NULL;

  if (!gdb_python_initialized)
    return;

  cleanup = ensure_python_env (target_gdbarch (), current_language);

  if (inf->has_exit_code)
    exit_code = &inf->exit_code;

  if (emit_exited_event (exit_code, inf) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 21
0
Arquivo: python.c Projeto: ILyoan/gdb
static void
restore_python_env (void *p)
{
  struct python_env *env = (struct python_env *)p;

  /* Leftover Python error is forbidden by Python Exception Handling.  */
  if (PyErr_Occurred ())
    {
      /* This order is similar to the one calling error afterwards. */
      gdbpy_print_stack ();
      warning (_("internal error: Unhandled Python exception"));
    }

  PyErr_Restore (env->error_type, env->error_value, env->error_traceback);

  PyGILState_Release (env->state);
  python_gdbarch = env->gdbarch;
  python_language = env->language;
  xfree (env);
}
Exemplo n.º 22
0
static void
python_on_normal_stop (struct bpstats *bs, int print_frame)
{
  struct cleanup *cleanup;
  enum gdb_signal stop_signal;

  if (!gdb_python_initialized)
    return;

  if (!find_thread_ptid (inferior_ptid))
      return;

  stop_signal = inferior_thread ()->suspend.stop_signal;

  cleanup = ensure_python_env (get_current_arch (), current_language);

  if (emit_stop_event (bs, stop_signal) < 0)
    gdbpy_print_stack ();

  do_cleanups (cleanup);
}
Exemplo n.º 23
0
static void
python_interactive_command (char *arg, int from_tty)
{
  struct cleanup *cleanup;
  int err;

  cleanup = make_cleanup_restore_integer (&interpreter_async);
  interpreter_async = 0;

  arg = skip_spaces (arg);

  ensure_python_env (get_current_arch (), current_language);

  if (arg && *arg)
    {
      int len = strlen (arg);
      char *script = xmalloc (len + 2);

      strcpy (script, arg);
      script[len] = '\n';
      script[len + 1] = '\0';
      err = eval_python_command (script);
      xfree (script);
    }
  else
    {
      err = PyRun_InteractiveLoop (instream, "<stdin>");
      dont_repeat ();
    }

  if (err)
    {
      gdbpy_print_stack ();
      error (_("Error while executing Python code."));
    }

  do_cleanups (cleanup);
}
Exemplo n.º 24
0
void
eval_python_from_control_command (struct command_line *cmd)
{
    int ret;
    char *script;
    struct cleanup *cleanup;

    if (cmd->body_count != 1)
        error (_("Invalid \"python\" block structure."));

    cleanup = ensure_python_env (get_current_arch (), current_language);

    script = compute_python_string (cmd->body_list[0]);
    ret = PyRun_SimpleString (script);
    xfree (script);
    if (ret)
    {
        gdbpy_print_stack ();
        error (_("Error while executing Python code."));
    }

    do_cleanups (cleanup);
}
Exemplo n.º 25
0
void
gdbpy_initialize_py_events (void)
{
#ifdef IS_PY3K
  gdb_py_events.module = PyModule_Create (&EventModuleDef);
#else
  gdb_py_events.module = Py_InitModule ("events", NULL);
#endif

  if (!gdb_py_events.module)
    goto fail;

  if (add_new_registry (&gdb_py_events.stop, "stop") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.cont, "cont") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.exited, "exited") < 0)
    goto fail;

  if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0)
    goto fail;

#ifndef IS_PY3K
  Py_INCREF (gdb_py_events.module);
#endif
  if (PyModule_AddObject (gdb_module,
                          "events",
                          (PyObject *) gdb_py_events.module) < 0)
    goto fail;

  return;

  fail:
   gdbpy_print_stack ();
}
Exemplo n.º 26
0
static struct value *
fnpy_call (struct gdbarch *gdbarch, const struct language_defn *language,
	   void *cookie, int argc, struct value **argv)
{
  struct value *value = NULL;
  /* 'result' must be set to NULL, this initially indicates whether
     the function was called, or not.  */
  PyObject *result = NULL;
  PyObject *callable, *args;
  struct cleanup *cleanup;

  cleanup = ensure_python_env (gdbarch, language);

  args = convert_values_to_python (argc, argv);
  /* convert_values_to_python can return NULL on error.  If we
     encounter this, do not call the function, but allow the Python ->
     error code conversion below to deal with the Python exception.
     Note, that this is different if the function simply does not
     have arguments.  */

  if (args)
    {
      callable = PyObject_GetAttrString ((PyObject *) cookie, "invoke");
      if (! callable)
	{
	  Py_DECREF (args);
	  error (_("No method named 'invoke' in object."));
	}

      result = PyObject_Call (callable, args, NULL);
      Py_DECREF (callable);
      Py_DECREF (args);
    }

  if (!result)
    {
      PyObject *ptype, *pvalue, *ptraceback;
      char *msg;

      PyErr_Fetch (&ptype, &pvalue, &ptraceback);

      /* Try to fetch an error message contained within ptype, pvalue.
	 When fetching the error message we need to make our own copy,
	 we no longer own ptype, pvalue after the call to PyErr_Restore.  */

      msg = gdbpy_exception_to_string (ptype, pvalue);
      make_cleanup (xfree, msg);

      if (msg == NULL)
	{
	  /* An error occurred computing the string representation of the
	     error message.  This is rare, but we should inform the user.  */

	  printf_filtered (_("An error occurred in a Python "
			     "convenience function\n"
			     "and then another occurred computing the "
			     "error message.\n"));
	  gdbpy_print_stack ();
	}

      /* Don't print the stack for gdb.GdbError exceptions.
	 It is generally used to flag user errors.

	 We also don't want to print "Error occurred in Python command"
	 for user errors.  However, a missing message for gdb.GdbError
	 exceptions is arguably a bug, so we flag it as such.  */

      if (!PyErr_GivenExceptionMatches (ptype, gdbpy_gdberror_exc)
	  || msg == NULL || *msg == '\0')
	{
	  PyErr_Restore (ptype, pvalue, ptraceback);
	  gdbpy_print_stack ();
	  if (msg != NULL && *msg != '\0')
	    error (_("Error occurred in Python convenience function: %s"),
		   msg);
	  else
	    error (_("Error occurred in Python convenience function."));
	}
      else
	{
	  Py_XDECREF (ptype);
	  Py_XDECREF (pvalue);
	  Py_XDECREF (ptraceback);
	  error ("%s", msg);
	}
    }

  value = convert_value_from_python (result);
  if (value == NULL)
    {
      Py_DECREF (result);
      gdbpy_print_stack ();
      error (_("Error while executing Python code."));
    }

  Py_DECREF (result);
  do_cleanups (cleanup);

  return value;
}
Exemplo n.º 27
0
static varobj_item *
py_varobj_iter_next (struct varobj_iter *self)
{
  struct py_varobj_iter *t = (struct py_varobj_iter *) self;
  struct cleanup *back_to;
  PyObject *item;
  PyObject *py_v;
  varobj_item *vitem;
  const char *name = NULL;

  if (!gdb_python_initialized)
    return NULL;

  back_to = varobj_ensure_python_env (self->var);

  item = PyIter_Next (t->iter);

  if (item == NULL)
    {
      /* Normal end of iteration.  */
      if (!PyErr_Occurred ())
	return NULL;

      /* If we got a memory error, just use the text as the item.  */
      if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
	{
	  PyObject *type, *value, *trace;
	  char *name_str, *value_str;

	  PyErr_Fetch (&type, &value, &trace);
	  value_str = gdbpy_exception_to_string (type, value);
	  Py_XDECREF (type);
	  Py_XDECREF (value);
	  Py_XDECREF (trace);
	  if (value_str == NULL)
	    {
	      gdbpy_print_stack ();
	      return NULL;
	    }

	  name_str = xstrprintf ("<error at %d>",
				 self->next_raw_index++);
	  item = Py_BuildValue ("(ss)", name_str, value_str);
	  xfree (name_str);
	  xfree (value_str);
	  if (item == NULL)
	    {
	      gdbpy_print_stack ();
	      return NULL;
	    }
	}
      else
	{
	  /* Any other kind of error.  */
	  gdbpy_print_stack ();
	  return NULL;
	}
    }

  if (!PyArg_ParseTuple (item, "sO", &name, &py_v))
    {
      gdbpy_print_stack ();
      error (_("Invalid item from the child list"));
    }

  vitem = XNEW (struct varobj_item);
  vitem->value = convert_value_from_python (py_v);
  if (vitem->value == NULL)
    gdbpy_print_stack ();
  vitem->name = xstrdup (name);

  self->next_raw_index++;
  do_cleanups (back_to);
  return vitem;
}
Exemplo n.º 28
0
 CATCH (except, RETURN_MASK_ALL)
   {
     gdbpy_convert_exception (except);
     gdbpy_print_stack ();
   }
Exemplo n.º 29
0
/* Helper for gdbpy_apply_val_pretty_printer that formats children of the
   printer, if any exist.  If is_py_none is true, then nothing has
   been printed by to_string, and format output accordingly. */
static void
print_children (PyObject *printer, const char *hint,
		struct ui_file *stream, int recurse,
		const struct value_print_options *options,
		const struct language_defn *language,
		int is_py_none)
{
  int is_map, is_array, done_flag, pretty;
  unsigned int i;

  if (! PyObject_HasAttr (printer, gdbpy_children_cst))
    return;

  /* If we are printing a map or an array, we want some special
     formatting.  */
  is_map = hint && ! strcmp (hint, "map");
  is_array = hint && ! strcmp (hint, "array");

  gdbpy_ref<> children (PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
						    NULL));
  if (children == NULL)
    {
      print_stack_unless_memory_error (stream);
      return;
    }

  gdbpy_ref<> iter (PyObject_GetIter (children.get ()));
  if (iter == NULL)
    {
      print_stack_unless_memory_error (stream);
      return;
    }

  /* Use the prettyformat_arrays option if we are printing an array,
     and the pretty option otherwise.  */
  if (is_array)
    pretty = options->prettyformat_arrays;
  else
    {
      if (options->prettyformat == Val_prettyformat)
	pretty = 1;
      else
	pretty = options->prettyformat_structs;
    }

  /* Manufacture a dummy Python frame to work around Python 2.4 bug,
     where it insists on having a non-NULL tstate->frame when
     a generator is called.  */
#ifndef IS_PY3K
  dummy_python_frame frame;
  if (frame.failed ())
    {
      gdbpy_print_stack ();
      return;
    }
#endif

  done_flag = 0;
  for (i = 0; i < options->print_max; ++i)
    {
      PyObject *py_v;
      const char *name;

      gdbpy_ref<> item (PyIter_Next (iter.get ()));
      if (item == NULL)
	{
	  if (PyErr_Occurred ())
	    print_stack_unless_memory_error (stream);
	  /* Set a flag so we can know whether we printed all the
	     available elements.  */
	  else	
	    done_flag = 1;
	  break;
	}

      if (! PyTuple_Check (item.get ()) || PyTuple_Size (item.get ()) != 2)
	{
	  PyErr_SetString (PyExc_TypeError,
			   _("Result of children iterator not a tuple"
			     " of two elements."));
	  gdbpy_print_stack ();
	  continue;
	}
      if (! PyArg_ParseTuple (item.get (), "sO", &name, &py_v))
	{
	  /* The user won't necessarily get a stack trace here, so provide
	     more context.  */
	  if (gdbpy_print_python_errors_p ())
	    fprintf_unfiltered (gdb_stderr,
				_("Bad result from children iterator.\n"));
	  gdbpy_print_stack ();
	  continue;
	}

      /* Print initial "{".  For other elements, there are three
	 cases:
	 1. Maps.  Print a "," after each value element.
	 2. Arrays.  Always print a ",".
	 3. Other.  Always print a ",".  */
      if (i == 0)
	{
         if (is_py_none)
           fputs_filtered ("{", stream);
         else
           fputs_filtered (" = {", stream);
       }

      else if (! is_map || i % 2 == 0)
	fputs_filtered (pretty ? "," : ", ", stream);

      /* In summary mode, we just want to print "= {...}" if there is
	 a value.  */
      if (options->summary)
	{
	  /* This increment tricks the post-loop logic to print what
	     we want.  */
	  ++i;
	  /* Likewise.  */
	  pretty = 0;
	  break;
	}

      if (! is_map || i % 2 == 0)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  else
	    wrap_here (n_spaces (2 + 2 *recurse));
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("[", stream);
      else if (is_array)
	{
	  /* We print the index, not whatever the child method
	     returned as the name.  */
	  if (options->print_array_indexes)
	    fprintf_filtered (stream, "[%d] = ", i);
	}
      else if (! is_map)
	{
	  fputs_filtered (name, stream);
	  fputs_filtered (" = ", stream);
	}

      if (gdbpy_is_lazy_string (py_v))
	{
	  CORE_ADDR addr;
	  struct type *type;
	  long length;
	  gdb::unique_xmalloc_ptr<char> encoding;
	  struct value_print_options local_opts = *options;

	  gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);

	  local_opts.addressprint = 0;
	  val_print_string (type, encoding.get (), addr, (int) length, stream,
			    &local_opts);
	}
      else if (gdbpy_is_string (py_v))
	{
	  gdb::unique_xmalloc_ptr<char> output;

	  output = python_string_to_host_string (py_v);
	  if (!output)
	    gdbpy_print_stack ();
	  else
	    fputs_filtered (output.get (), stream);
	}
      else
	{
	  struct value *value = convert_value_from_python (py_v);

	  if (value == NULL)
	    {
	      gdbpy_print_stack ();
	      error (_("Error while executing Python code."));
	    }
	  else
	    common_val_print (value, stream, recurse + 1, options, language);
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("] = ", stream);
    }

  if (i)
    {
      if (!done_flag)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  fputs_filtered ("...", stream);
	}
      if (pretty)
	{
	  fputs_filtered ("\n", stream);
	  print_spaces_filtered (2 * recurse, stream);
	}
      fputs_filtered ("}", stream);
    }
}
Exemplo n.º 30
0
static struct value *
fnpy_call (struct gdbarch *gdbarch, const struct language_defn *language,
	   void *cookie, int argc, struct value **argv)
{
  /* The gdbpy_enter object needs to be placed first, so that it's the last to
     be destroyed.  */
  gdbpy_enter enter_py (gdbarch, language);
  struct value *value;
  gdbpy_ref<> result;
  gdbpy_ref<> args (convert_values_to_python (argc, argv));

  /* convert_values_to_python can return NULL on error.  If we
     encounter this, do not call the function, but allow the Python ->
     error code conversion below to deal with the Python exception.
     Note, that this is different if the function simply does not
     have arguments.  */

  if (args != NULL)
    {
      gdbpy_ref<> callable (PyObject_GetAttrString ((PyObject *) cookie,
						    "invoke"));
      if (callable == NULL)
	error (_("No method named 'invoke' in object."));

      result.reset (PyObject_Call (callable.get (), args.get (), NULL));
    }

  if (result == NULL)
    {
      PyObject *ptype, *pvalue, *ptraceback;

      PyErr_Fetch (&ptype, &pvalue, &ptraceback);

      /* Try to fetch an error message contained within ptype, pvalue.
	 When fetching the error message we need to make our own copy,
	 we no longer own ptype, pvalue after the call to PyErr_Restore.  */

      gdb::unique_xmalloc_ptr<char>
	msg (gdbpy_exception_to_string (ptype, pvalue));

      if (msg == NULL)
	{
	  /* An error occurred computing the string representation of the
	     error message.  This is rare, but we should inform the user.  */

	  printf_filtered (_("An error occurred in a Python "
			     "convenience function\n"
			     "and then another occurred computing the "
			     "error message.\n"));
	  gdbpy_print_stack ();
	}

      /* Don't print the stack for gdb.GdbError exceptions.
	 It is generally used to flag user errors.

	 We also don't want to print "Error occurred in Python command"
	 for user errors.  However, a missing message for gdb.GdbError
	 exceptions is arguably a bug, so we flag it as such.  */

      if (!PyErr_GivenExceptionMatches (ptype, gdbpy_gdberror_exc)
	  || msg == NULL || *msg == '\0')
	{
	  PyErr_Restore (ptype, pvalue, ptraceback);
	  gdbpy_print_stack ();
	  if (msg != NULL && *msg != '\0')
	    error (_("Error occurred in Python convenience function: %s"),
		   msg.get ());
	  else
	    error (_("Error occurred in Python convenience function."));
	}
      else
	{
	  Py_XDECREF (ptype);
	  Py_XDECREF (pvalue);
	  Py_XDECREF (ptraceback);
	  error ("%s", msg.get ());
	}
    }

  value = convert_value_from_python (result.get ());
  if (value == NULL)
    {
      gdbpy_print_stack ();
      error (_("Error while executing Python code."));
    }

  return value;
}