Home | History | Annotate | Line # | Download | only in python
py-disasm.c revision 1.1
      1  1.1  christos /* Python interface to instruction disassembly.
      2  1.1  christos 
      3  1.1  christos    Copyright (C) 2021-2023 Free Software Foundation, Inc.
      4  1.1  christos 
      5  1.1  christos    This file is part of GDB.
      6  1.1  christos 
      7  1.1  christos    This program is free software; you can redistribute it and/or modify
      8  1.1  christos    it under the terms of the GNU General Public License as published by
      9  1.1  christos    the Free Software Foundation; either version 3 of the License, or
     10  1.1  christos    (at your option) any later version.
     11  1.1  christos 
     12  1.1  christos    This program is distributed in the hope that it will be useful,
     13  1.1  christos    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14  1.1  christos    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15  1.1  christos    GNU General Public License for more details.
     16  1.1  christos 
     17  1.1  christos    You should have received a copy of the GNU General Public License
     18  1.1  christos    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19  1.1  christos 
     20  1.1  christos #include "defs.h"
     21  1.1  christos #include "python-internal.h"
     22  1.1  christos #include "dis-asm.h"
     23  1.1  christos #include "arch-utils.h"
     24  1.1  christos #include "charset.h"
     25  1.1  christos #include "disasm.h"
     26  1.1  christos #include "progspace.h"
     27  1.1  christos 
     28  1.1  christos /* Implement gdb.disassembler.DisassembleInfo type.  An object of this type
     29  1.1  christos    represents a single disassembler request from GDB.  */
     30  1.1  christos 
     31  1.1  christos struct disasm_info_object
     32  1.1  christos {
     33  1.1  christos   PyObject_HEAD
     34  1.1  christos 
     35  1.1  christos   /* The architecture in which we are disassembling.  */
     36  1.1  christos   struct gdbarch *gdbarch;
     37  1.1  christos 
     38  1.1  christos   /* The program_space in which we are disassembling.  */
     39  1.1  christos   struct program_space *program_space;
     40  1.1  christos 
     41  1.1  christos   /* Address of the instruction to disassemble.  */
     42  1.1  christos   bfd_vma address;
     43  1.1  christos 
     44  1.1  christos   /* The disassemble_info passed from core GDB, this contains the
     45  1.1  christos      callbacks necessary to read the instruction from core GDB, and to
     46  1.1  christos      print the disassembled instruction.  */
     47  1.1  christos   disassemble_info *gdb_info;
     48  1.1  christos 
     49  1.1  christos   /* If copies of this object are created then they are chained together
     50  1.1  christos      via this NEXT pointer, this allows all the copies to be invalidated at
     51  1.1  christos      the same time as the parent object.  */
     52  1.1  christos   struct disasm_info_object *next;
     53  1.1  christos };
     54  1.1  christos 
     55  1.1  christos extern PyTypeObject disasm_info_object_type
     56  1.1  christos     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_info_object");
     57  1.1  christos 
     58  1.1  christos /* Implement gdb.disassembler.DisassemblerResult type, an object that holds
     59  1.1  christos    the result of calling the disassembler.  This is mostly the length of
     60  1.1  christos    the disassembled instruction (in bytes), and the string representing the
     61  1.1  christos    disassembled instruction.  */
     62  1.1  christos 
     63  1.1  christos struct disasm_result_object
     64  1.1  christos {
     65  1.1  christos   PyObject_HEAD
     66  1.1  christos 
     67  1.1  christos   /* The length of the disassembled instruction in bytes.  */
     68  1.1  christos   int length;
     69  1.1  christos 
     70  1.1  christos   /* A buffer which, when allocated, holds the disassembled content of an
     71  1.1  christos      instruction.  */
     72  1.1  christos   string_file *content;
     73  1.1  christos };
     74  1.1  christos 
     75  1.1  christos extern PyTypeObject disasm_result_object_type
     76  1.1  christos     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_result_object");
     77  1.1  christos 
     78  1.1  christos /* When this is false we fast path out of gdbpy_print_insn, which should
     79  1.1  christos    keep the performance impact of the Python disassembler down.  This is
     80  1.1  christos    set to true from Python by calling gdb.disassembler._set_enabled() when
     81  1.1  christos    the user registers a disassembler.  */
     82  1.1  christos 
     83  1.1  christos static bool python_print_insn_enabled = false;
     84  1.1  christos 
     85  1.1  christos /* A sub-class of gdb_disassembler that holds a pointer to a Python
     86  1.1  christos    DisassembleInfo object.  A pointer to an instance of this class is
     87  1.1  christos    placed in the application_data field of the disassemble_info that is
     88  1.1  christos    used when we call gdbarch_print_insn.  */
     89  1.1  christos 
     90  1.1  christos struct gdbpy_disassembler : public gdb_printing_disassembler
     91  1.1  christos {
     92  1.1  christos   /* Constructor.  */
     93  1.1  christos   gdbpy_disassembler (disasm_info_object *obj, PyObject *memory_source);
     94  1.1  christos 
     95  1.1  christos   /* Get the DisassembleInfo object pointer.  */
     96  1.1  christos   disasm_info_object *
     97  1.1  christos   py_disasm_info () const
     98  1.1  christos   {
     99  1.1  christos     return m_disasm_info_object;
    100  1.1  christos   }
    101  1.1  christos 
    102  1.1  christos   /* Callbacks used by disassemble_info.  */
    103  1.1  christos   static void memory_error_func (int status, bfd_vma memaddr,
    104  1.1  christos 				 struct disassemble_info *info) noexcept;
    105  1.1  christos   static void print_address_func (bfd_vma addr,
    106  1.1  christos 				  struct disassemble_info *info) noexcept;
    107  1.1  christos   static int read_memory_func (bfd_vma memaddr, gdb_byte *buff,
    108  1.1  christos 			       unsigned int len,
    109  1.1  christos 			       struct disassemble_info *info) noexcept;
    110  1.1  christos 
    111  1.1  christos   /* Return a reference to an optional that contains the address at which a
    112  1.1  christos      memory error occurred.  The optional will only have a value if a
    113  1.1  christos      memory error actually occurred.  */
    114  1.1  christos   const gdb::optional<CORE_ADDR> &memory_error_address () const
    115  1.1  christos   { return m_memory_error_address; }
    116  1.1  christos 
    117  1.1  christos   /* Return the content of the disassembler as a string.  The contents are
    118  1.1  christos      moved out of the disassembler, so after this call the disassembler
    119  1.1  christos      contents have been reset back to empty.  */
    120  1.1  christos   std::string release ()
    121  1.1  christos   {
    122  1.1  christos     return m_string_file.release ();
    123  1.1  christos   }
    124  1.1  christos 
    125  1.1  christos   /* If there is a Python exception stored in this disassembler then
    126  1.1  christos      restore it (i.e. set the PyErr_* state), clear the exception within
    127  1.1  christos      this disassembler, and return true.  There must be no current
    128  1.1  christos      exception set (i.e. !PyErr_Occurred()) when this function is called,
    129  1.1  christos      as any such exception might get lost.
    130  1.1  christos 
    131  1.1  christos      Otherwise, there is no exception stored in this disassembler, return
    132  1.1  christos      false.  */
    133  1.1  christos   bool restore_exception ()
    134  1.1  christos   {
    135  1.1  christos     gdb_assert (!PyErr_Occurred ());
    136  1.1  christos     if (m_stored_exception.has_value ())
    137  1.1  christos       {
    138  1.1  christos 	gdbpy_err_fetch ex = std::move (*m_stored_exception);
    139  1.1  christos 	m_stored_exception.reset ();
    140  1.1  christos 	ex.restore ();
    141  1.1  christos 	return true;
    142  1.1  christos       }
    143  1.1  christos 
    144  1.1  christos     return false;
    145  1.1  christos   }
    146  1.1  christos 
    147  1.1  christos private:
    148  1.1  christos 
    149  1.1  christos   /* Where the disassembler result is written.  */
    150  1.1  christos   string_file m_string_file;
    151  1.1  christos 
    152  1.1  christos   /* The DisassembleInfo object we are disassembling for.  */
    153  1.1  christos   disasm_info_object *m_disasm_info_object;
    154  1.1  christos 
    155  1.1  christos   /* When the user indicates that a memory error has occurred then the
    156  1.1  christos      address of the memory error is stored in here.  */
    157  1.1  christos   gdb::optional<CORE_ADDR> m_memory_error_address;
    158  1.1  christos 
    159  1.1  christos   /* When the user calls the builtin_disassemble function, if they pass a
    160  1.1  christos      memory source object then a pointer to the object is placed in here,
    161  1.1  christos      otherwise, this field is nullptr.  */
    162  1.1  christos   PyObject *m_memory_source;
    163  1.1  christos 
    164  1.1  christos   /* Move the exception EX into this disassembler object.  */
    165  1.1  christos   void store_exception (gdbpy_err_fetch &&ex)
    166  1.1  christos   {
    167  1.1  christos     /* The only calls to store_exception are from read_memory_func, which
    168  1.1  christos        will return early if there's already an exception stored.  */
    169  1.1  christos     gdb_assert (!m_stored_exception.has_value ());
    170  1.1  christos     m_stored_exception.emplace (std::move (ex));
    171  1.1  christos   }
    172  1.1  christos 
    173  1.1  christos   /* Return true if there is an exception stored in this disassembler.  */
    174  1.1  christos   bool has_stored_exception () const
    175  1.1  christos   {
    176  1.1  christos     return m_stored_exception.has_value ();
    177  1.1  christos   }
    178  1.1  christos 
    179  1.1  christos   /* Store a single exception.  This is used to pass Python exceptions back
    180  1.1  christos      from ::memory_read to disasmpy_builtin_disassemble.  */
    181  1.1  christos   gdb::optional<gdbpy_err_fetch> m_stored_exception;
    182  1.1  christos };
    183  1.1  christos 
    184  1.1  christos /* Return true if OBJ is still valid, otherwise, return false.  A valid OBJ
    185  1.1  christos    will have a non-nullptr gdb_info field.  */
    186  1.1  christos 
    187  1.1  christos static bool
    188  1.1  christos disasm_info_object_is_valid (disasm_info_object *obj)
    189  1.1  christos {
    190  1.1  christos   return obj->gdb_info != nullptr;
    191  1.1  christos }
    192  1.1  christos 
    193  1.1  christos /* Fill in OBJ with all the other arguments.  */
    194  1.1  christos 
    195  1.1  christos static void
    196  1.1  christos disasm_info_fill (disasm_info_object *obj, struct gdbarch *gdbarch,
    197  1.1  christos 		  program_space *progspace, bfd_vma address,
    198  1.1  christos 		  disassemble_info *di, disasm_info_object *next)
    199  1.1  christos {
    200  1.1  christos   obj->gdbarch = gdbarch;
    201  1.1  christos   obj->program_space = progspace;
    202  1.1  christos   obj->address = address;
    203  1.1  christos   obj->gdb_info = di;
    204  1.1  christos   obj->next = next;
    205  1.1  christos }
    206  1.1  christos 
    207  1.1  christos /* Implement DisassembleInfo.__init__.  Takes a single argument that must
    208  1.1  christos    be another DisassembleInfo object and copies the contents from the
    209  1.1  christos    argument into this new object.  */
    210  1.1  christos 
    211  1.1  christos static int
    212  1.1  christos disasm_info_init (PyObject *self, PyObject *args, PyObject *kwargs)
    213  1.1  christos {
    214  1.1  christos   static const char *keywords[] = { "info", NULL };
    215  1.1  christos   PyObject *info_obj;
    216  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "O!", keywords,
    217  1.1  christos 					&disasm_info_object_type,
    218  1.1  christos 					&info_obj))
    219  1.1  christos     return -1;
    220  1.1  christos 
    221  1.1  christos   disasm_info_object *other = (disasm_info_object *) info_obj;
    222  1.1  christos   disasm_info_object *info = (disasm_info_object *) self;
    223  1.1  christos   disasm_info_fill (info, other->gdbarch, other->program_space,
    224  1.1  christos 		    other->address, other->gdb_info, other->next);
    225  1.1  christos   other->next = info;
    226  1.1  christos 
    227  1.1  christos   /* As the OTHER object now holds a pointer to INFO we inc the ref count
    228  1.1  christos      on INFO.  This stops INFO being deleted until OTHER has gone away.  */
    229  1.1  christos   Py_INCREF ((PyObject *) info);
    230  1.1  christos   return 0;
    231  1.1  christos }
    232  1.1  christos 
    233  1.1  christos /* The tp_dealloc callback for the DisassembleInfo type.  */
    234  1.1  christos 
    235  1.1  christos static void
    236  1.1  christos disasm_info_dealloc (PyObject *self)
    237  1.1  christos {
    238  1.1  christos   disasm_info_object *obj = (disasm_info_object *) self;
    239  1.1  christos 
    240  1.1  christos   /* We no longer care about the object our NEXT pointer points at, so we
    241  1.1  christos      can decrement its reference count.  This macro handles the case when
    242  1.1  christos      NEXT is nullptr.  */
    243  1.1  christos   Py_XDECREF ((PyObject *) obj->next);
    244  1.1  christos 
    245  1.1  christos   /* Now core deallocation behaviour.  */
    246  1.1  christos   Py_TYPE (self)->tp_free (self);
    247  1.1  christos }
    248  1.1  christos 
    249  1.1  christos /* Implement DisassembleInfo.is_valid(), really just a wrapper around the
    250  1.1  christos    disasm_info_object_is_valid function above.  */
    251  1.1  christos 
    252  1.1  christos static PyObject *
    253  1.1  christos disasmpy_info_is_valid (PyObject *self, PyObject *args)
    254  1.1  christos {
    255  1.1  christos   disasm_info_object *disasm_obj = (disasm_info_object *) self;
    256  1.1  christos 
    257  1.1  christos   if (disasm_info_object_is_valid (disasm_obj))
    258  1.1  christos     Py_RETURN_TRUE;
    259  1.1  christos 
    260  1.1  christos   Py_RETURN_FALSE;
    261  1.1  christos }
    262  1.1  christos 
    263  1.1  christos /* Set the Python exception to be a gdb.MemoryError object, with ADDRESS
    264  1.1  christos    as its payload.  */
    265  1.1  christos 
    266  1.1  christos static void
    267  1.1  christos disasmpy_set_memory_error_for_address (CORE_ADDR address)
    268  1.1  christos {
    269  1.1  christos   PyObject *address_obj = gdb_py_object_from_longest (address).release ();
    270  1.1  christos   PyErr_SetObject (gdbpy_gdb_memory_error, address_obj);
    271  1.1  christos }
    272  1.1  christos 
    273  1.1  christos /* Ensure that a gdb.disassembler.DisassembleInfo is valid.  */
    274  1.1  christos 
    275  1.1  christos #define DISASMPY_DISASM_INFO_REQUIRE_VALID(Info)			\
    276  1.1  christos   do {									\
    277  1.1  christos     if (!disasm_info_object_is_valid (Info))				\
    278  1.1  christos       {									\
    279  1.1  christos 	PyErr_SetString (PyExc_RuntimeError,				\
    280  1.1  christos 			 _("DisassembleInfo is no longer valid."));	\
    281  1.1  christos 	return nullptr;							\
    282  1.1  christos       }									\
    283  1.1  christos   } while (0)
    284  1.1  christos 
    285  1.1  christos /* Initialise OBJ, a DisassemblerResult object with LENGTH and CONTENT.
    286  1.1  christos    OBJ might already have been initialised, in which case any existing
    287  1.1  christos    content should be discarded before the new CONTENT is moved in.  */
    288  1.1  christos 
    289  1.1  christos static void
    290  1.1  christos disasmpy_init_disassembler_result (disasm_result_object *obj, int length,
    291  1.1  christos 				   std::string content)
    292  1.1  christos {
    293  1.1  christos   if (obj->content == nullptr)
    294  1.1  christos     obj->content = new string_file;
    295  1.1  christos   else
    296  1.1  christos     obj->content->clear ();
    297  1.1  christos 
    298  1.1  christos   obj->length = length;
    299  1.1  christos   *(obj->content) = std::move (content);
    300  1.1  christos }
    301  1.1  christos 
    302  1.1  christos /* Implement gdb.disassembler.builtin_disassemble().  Calls back into GDB's
    303  1.1  christos    builtin disassembler.  The first argument is a DisassembleInfo object
    304  1.1  christos    describing what to disassemble.  The second argument is optional and
    305  1.1  christos    provides a mechanism to modify the memory contents that the builtin
    306  1.1  christos    disassembler will actually disassemble.
    307  1.1  christos 
    308  1.1  christos    Returns an instance of gdb.disassembler.DisassemblerResult, an object
    309  1.1  christos    that wraps a disassembled instruction, or it raises a
    310  1.1  christos    gdb.MemoryError.  */
    311  1.1  christos 
    312  1.1  christos static PyObject *
    313  1.1  christos disasmpy_builtin_disassemble (PyObject *self, PyObject *args, PyObject *kw)
    314  1.1  christos {
    315  1.1  christos   PyObject *info_obj, *memory_source_obj = nullptr;
    316  1.1  christos   static const char *keywords[] = { "info", "memory_source", nullptr };
    317  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O!|O", keywords,
    318  1.1  christos 					&disasm_info_object_type, &info_obj,
    319  1.1  christos 					&memory_source_obj))
    320  1.1  christos     return nullptr;
    321  1.1  christos 
    322  1.1  christos   disasm_info_object *disasm_info = (disasm_info_object *) info_obj;
    323  1.1  christos   DISASMPY_DISASM_INFO_REQUIRE_VALID (disasm_info);
    324  1.1  christos 
    325  1.1  christos   /* Where the result will be written.  */
    326  1.1  christos   gdbpy_disassembler disassembler (disasm_info, memory_source_obj);
    327  1.1  christos 
    328  1.1  christos   /* Now actually perform the disassembly.  LENGTH is set to the length of
    329  1.1  christos      the disassembled instruction, or -1 if there was a memory-error
    330  1.1  christos      encountered while disassembling.  See below more more details on
    331  1.1  christos      handling of -1 return value.  */
    332  1.1  christos   int length = gdbarch_print_insn (disasm_info->gdbarch, disasm_info->address,
    333  1.1  christos 				   disassembler.disasm_info ());
    334  1.1  christos 
    335  1.1  christos   /* It is possible that, while calling a user overridden memory read
    336  1.1  christos      function, a Python exception was raised that couldn't be
    337  1.1  christos      translated into a standard memory-error.  In this case the first such
    338  1.1  christos      exception is stored in the disassembler and restored here.  */
    339  1.1  christos   if (disassembler.restore_exception ())
    340  1.1  christos     return nullptr;
    341  1.1  christos 
    342  1.1  christos   if (length == -1)
    343  1.1  christos     {
    344  1.1  christos 
    345  1.1  christos       /* In an ideal world, every disassembler should always call the
    346  1.1  christos 	 memory error function before returning a status of -1 as the only
    347  1.1  christos 	 error a disassembler should encounter is a failure to read
    348  1.1  christos 	 memory.  Unfortunately, there are some disassemblers who don't
    349  1.1  christos 	 follow this rule, and will return -1 without calling the memory
    350  1.1  christos 	 error function.
    351  1.1  christos 
    352  1.1  christos 	 To make the Python API simpler, we just classify everything as a
    353  1.1  christos 	 memory error, but the message has to be modified for the case
    354  1.1  christos 	 where the disassembler didn't call the memory error function.  */
    355  1.1  christos       if (disassembler.memory_error_address ().has_value ())
    356  1.1  christos 	{
    357  1.1  christos 	  CORE_ADDR addr = *disassembler.memory_error_address ();
    358  1.1  christos 	  disasmpy_set_memory_error_for_address (addr);
    359  1.1  christos 	}
    360  1.1  christos       else
    361  1.1  christos 	{
    362  1.1  christos 	  std::string content = disassembler.release ();
    363  1.1  christos 	  if (!content.empty ())
    364  1.1  christos 	    PyErr_SetString (gdbpy_gdberror_exc, content.c_str ());
    365  1.1  christos 	  else
    366  1.1  christos 	    PyErr_SetString (gdbpy_gdberror_exc,
    367  1.1  christos 			     _("Unknown disassembly error."));
    368  1.1  christos 	}
    369  1.1  christos       return nullptr;
    370  1.1  christos     }
    371  1.1  christos 
    372  1.1  christos   /* Instructions are either non-zero in length, or we got an error,
    373  1.1  christos      indicated by a length of -1, which we handled above.  */
    374  1.1  christos   gdb_assert (length > 0);
    375  1.1  christos 
    376  1.1  christos   /* We should not have seen a memory error in this case.  */
    377  1.1  christos   gdb_assert (!disassembler.memory_error_address ().has_value ());
    378  1.1  christos 
    379  1.1  christos   /* Create a DisassemblerResult containing the results.  */
    380  1.1  christos   std::string content = disassembler.release ();
    381  1.1  christos   PyTypeObject *type = &disasm_result_object_type;
    382  1.1  christos   gdbpy_ref<disasm_result_object> res
    383  1.1  christos     ((disasm_result_object *) type->tp_alloc (type, 0));
    384  1.1  christos   disasmpy_init_disassembler_result (res.get (), length, std::move (content));
    385  1.1  christos   return reinterpret_cast<PyObject *> (res.release ());
    386  1.1  christos }
    387  1.1  christos 
    388  1.1  christos /* Implement gdb._set_enabled function.  Takes a boolean parameter, and
    389  1.1  christos    sets whether GDB should enter the Python disassembler code or not.
    390  1.1  christos 
    391  1.1  christos    This is called from within the Python code when a new disassembler is
    392  1.1  christos    registered.  When no disassemblers are registered the global C++ flag
    393  1.1  christos    is set to false, and GDB never even enters the Python environment to
    394  1.1  christos    check for a disassembler.
    395  1.1  christos 
    396  1.1  christos    When the user registers a new Python disassembler, the global C++ flag
    397  1.1  christos    is set to true, and now GDB will enter the Python environment to check
    398  1.1  christos    if there's a disassembler registered for the current architecture.  */
    399  1.1  christos 
    400  1.1  christos static PyObject *
    401  1.1  christos disasmpy_set_enabled (PyObject *self, PyObject *args, PyObject *kw)
    402  1.1  christos {
    403  1.1  christos   PyObject *newstate;
    404  1.1  christos   static const char *keywords[] = { "state", nullptr };
    405  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords,
    406  1.1  christos 					&newstate))
    407  1.1  christos     return nullptr;
    408  1.1  christos 
    409  1.1  christos   if (!PyBool_Check (newstate))
    410  1.1  christos     {
    411  1.1  christos       PyErr_SetString (PyExc_TypeError,
    412  1.1  christos 		       _("The value passed to `_set_enabled' must be a boolean."));
    413  1.1  christos       return nullptr;
    414  1.1  christos     }
    415  1.1  christos 
    416  1.1  christos   python_print_insn_enabled = PyObject_IsTrue (newstate);
    417  1.1  christos   Py_RETURN_NONE;
    418  1.1  christos }
    419  1.1  christos 
    420  1.1  christos /* Implement DisassembleInfo.read_memory(LENGTH, OFFSET).  Read LENGTH
    421  1.1  christos    bytes at OFFSET from the start of the instruction currently being
    422  1.1  christos    disassembled, and return a memory buffer containing the bytes.
    423  1.1  christos 
    424  1.1  christos    OFFSET defaults to zero if it is not provided.  LENGTH is required.  If
    425  1.1  christos    the read fails then this will raise a gdb.MemoryError exception.  */
    426  1.1  christos 
    427  1.1  christos static PyObject *
    428  1.1  christos disasmpy_info_read_memory (PyObject *self, PyObject *args, PyObject *kw)
    429  1.1  christos {
    430  1.1  christos   disasm_info_object *obj = (disasm_info_object *) self;
    431  1.1  christos   DISASMPY_DISASM_INFO_REQUIRE_VALID (obj);
    432  1.1  christos 
    433  1.1  christos   LONGEST length, offset = 0;
    434  1.1  christos   gdb::unique_xmalloc_ptr<gdb_byte> buffer;
    435  1.1  christos   static const char *keywords[] = { "length", "offset", nullptr };
    436  1.1  christos 
    437  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "L|L", keywords,
    438  1.1  christos 					&length, &offset))
    439  1.1  christos     return nullptr;
    440  1.1  christos 
    441  1.1  christos   /* The apparent address from which we are reading memory.  Note that in
    442  1.1  christos      some cases GDB actually disassembles instructions from a buffer, so
    443  1.1  christos      we might not actually be reading this information directly from the
    444  1.1  christos      inferior memory.  This is all hidden behind the read_memory_func API
    445  1.1  christos      within the disassemble_info structure.  */
    446  1.1  christos   CORE_ADDR address = obj->address + offset;
    447  1.1  christos 
    448  1.1  christos   /* Setup a buffer to hold the result.  */
    449  1.1  christos   buffer.reset ((gdb_byte *) xmalloc (length));
    450  1.1  christos 
    451  1.1  christos   /* Read content into BUFFER.  If the read fails then raise a memory
    452  1.1  christos      error, otherwise, convert BUFFER to a Python memory buffer, and return
    453  1.1  christos      it to the user.  */
    454  1.1  christos   disassemble_info *info = obj->gdb_info;
    455  1.1  christos   if (info->read_memory_func ((bfd_vma) address, buffer.get (),
    456  1.1  christos 			      (unsigned int) length, info) != 0)
    457  1.1  christos     {
    458  1.1  christos       disasmpy_set_memory_error_for_address (address);
    459  1.1  christos       return nullptr;
    460  1.1  christos     }
    461  1.1  christos   return gdbpy_buffer_to_membuf (std::move (buffer), address, length);
    462  1.1  christos }
    463  1.1  christos 
    464  1.1  christos /* Implement DisassembleInfo.address attribute, return the address at which
    465  1.1  christos    GDB would like an instruction disassembled.  */
    466  1.1  christos 
    467  1.1  christos static PyObject *
    468  1.1  christos disasmpy_info_address (PyObject *self, void *closure)
    469  1.1  christos {
    470  1.1  christos   disasm_info_object *obj = (disasm_info_object *) self;
    471  1.1  christos   DISASMPY_DISASM_INFO_REQUIRE_VALID (obj);
    472  1.1  christos   return gdb_py_object_from_longest (obj->address).release ();
    473  1.1  christos }
    474  1.1  christos 
    475  1.1  christos /* Implement DisassembleInfo.architecture attribute.  Return the
    476  1.1  christos    gdb.Architecture in which we are disassembling.  */
    477  1.1  christos 
    478  1.1  christos static PyObject *
    479  1.1  christos disasmpy_info_architecture (PyObject *self, void *closure)
    480  1.1  christos {
    481  1.1  christos   disasm_info_object *obj = (disasm_info_object *) self;
    482  1.1  christos   DISASMPY_DISASM_INFO_REQUIRE_VALID (obj);
    483  1.1  christos   return gdbarch_to_arch_object (obj->gdbarch);
    484  1.1  christos }
    485  1.1  christos 
    486  1.1  christos /* Implement DisassembleInfo.progspace attribute.  Return the
    487  1.1  christos    gdb.Progspace in which we are disassembling.  */
    488  1.1  christos 
    489  1.1  christos static PyObject *
    490  1.1  christos disasmpy_info_progspace (PyObject *self, void *closure)
    491  1.1  christos {
    492  1.1  christos   disasm_info_object *obj = (disasm_info_object *) self;
    493  1.1  christos   DISASMPY_DISASM_INFO_REQUIRE_VALID (obj);
    494  1.1  christos   return pspace_to_pspace_object (obj->program_space).release ();
    495  1.1  christos }
    496  1.1  christos 
    497  1.1  christos /* This implements the disassemble_info read_memory_func callback and is
    498  1.1  christos    called from the libopcodes disassembler when the disassembler wants to
    499  1.1  christos    read memory.
    500  1.1  christos 
    501  1.1  christos    From the INFO argument we can find the gdbpy_disassembler object for
    502  1.1  christos    which we are disassembling, and from that object we can find the
    503  1.1  christos    DisassembleInfo for the current disassembly call.
    504  1.1  christos 
    505  1.1  christos    This function reads the instruction bytes by calling the read_memory
    506  1.1  christos    method on the DisassembleInfo object.  This method might have been
    507  1.1  christos    overridden by user code.
    508  1.1  christos 
    509  1.1  christos    Read LEN bytes from MEMADDR and place them into BUFF.  Return 0 on
    510  1.1  christos    success (in which case BUFF has been filled), or -1 on error, in which
    511  1.1  christos    case the contents of BUFF are undefined.  */
    512  1.1  christos 
    513  1.1  christos int
    514  1.1  christos gdbpy_disassembler::read_memory_func (bfd_vma memaddr, gdb_byte *buff,
    515  1.1  christos 				      unsigned int len,
    516  1.1  christos 				      struct disassemble_info *info) noexcept
    517  1.1  christos {
    518  1.1  christos   gdbpy_disassembler *dis
    519  1.1  christos     = static_cast<gdbpy_disassembler *> (info->application_data);
    520  1.1  christos   disasm_info_object *obj = dis->py_disasm_info ();
    521  1.1  christos 
    522  1.1  christos   /* If a previous read attempt resulted in an exception, then we don't
    523  1.1  christos      allow any further reads to succeed.  We only do this check for the
    524  1.1  christos      read_memory_func as this is the only one the user can hook into,
    525  1.1  christos      thus, this check prevents us calling back into user code if a
    526  1.1  christos      previous call has already thrown an error.  */
    527  1.1  christos   if (dis->has_stored_exception ())
    528  1.1  christos     return -1;
    529  1.1  christos 
    530  1.1  christos   /* The DisassembleInfo.read_memory method expects an offset from the
    531  1.1  christos      address stored within the DisassembleInfo object; calculate that
    532  1.1  christos      offset here.  */
    533  1.1  christos   LONGEST offset = (LONGEST) memaddr - (LONGEST) obj->address;
    534  1.1  christos 
    535  1.1  christos   /* Now call the DisassembleInfo.read_memory method.  This might have been
    536  1.1  christos      overridden by the user.  */
    537  1.1  christos   gdbpy_ref<> result_obj (PyObject_CallMethod ((PyObject *) obj,
    538  1.1  christos 					       "read_memory",
    539  1.1  christos 					       "KL", len, offset));
    540  1.1  christos 
    541  1.1  christos   /* Handle any exceptions.  */
    542  1.1  christos   if (result_obj == nullptr)
    543  1.1  christos     {
    544  1.1  christos       /* If we got a gdb.MemoryError then we ignore this and just report
    545  1.1  christos 	 that the read failed to the caller.  The caller is then
    546  1.1  christos 	 responsible for calling the memory_error_func if it wants to.
    547  1.1  christos 	 Remember, the disassembler might just be probing to see if these
    548  1.1  christos 	 bytes can be read, if we automatically call the memory error
    549  1.1  christos 	 function, we can end up registering an error prematurely.  */
    550  1.1  christos       if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
    551  1.1  christos 	{
    552  1.1  christos 	  PyErr_Clear ();
    553  1.1  christos 	  return -1;
    554  1.1  christos 	}
    555  1.1  christos 
    556  1.1  christos       /* For any other exception type we capture the value of the Python
    557  1.1  christos 	 exception and throw it, this will then be caught in
    558  1.1  christos 	 disasmpy_builtin_disassemble, at which point the exception will be
    559  1.1  christos 	 restored.  */
    560  1.1  christos       dis->store_exception (gdbpy_err_fetch ());
    561  1.1  christos       return -1;
    562  1.1  christos     }
    563  1.1  christos 
    564  1.1  christos   /* Convert the result to a buffer.  */
    565  1.1  christos   Py_buffer py_buff;
    566  1.1  christos   if (!PyObject_CheckBuffer (result_obj.get ())
    567  1.1  christos       || PyObject_GetBuffer (result_obj.get(), &py_buff, PyBUF_CONTIG_RO) < 0)
    568  1.1  christos     {
    569  1.1  christos       PyErr_Format (PyExc_TypeError,
    570  1.1  christos 		    _("Result from read_memory is not a buffer"));
    571  1.1  christos       dis->store_exception (gdbpy_err_fetch ());
    572  1.1  christos       return -1;
    573  1.1  christos     }
    574  1.1  christos 
    575  1.1  christos   /* Wrap PY_BUFF so that it is cleaned up correctly at the end of this
    576  1.1  christos      scope.  */
    577  1.1  christos   Py_buffer_up buffer_up (&py_buff);
    578  1.1  christos 
    579  1.1  christos   /* Validate that the buffer is the correct length.  */
    580  1.1  christos   if (py_buff.len != len)
    581  1.1  christos     {
    582  1.1  christos       PyErr_Format (PyExc_ValueError,
    583  1.1  christos 		    _("Buffer returned from read_memory is sized %d instead of the expected %d"),
    584  1.1  christos 		    py_buff.len, len);
    585  1.1  christos       dis->store_exception (gdbpy_err_fetch ());
    586  1.1  christos       return -1;
    587  1.1  christos     }
    588  1.1  christos 
    589  1.1  christos   /* Copy the data out of the Python buffer and return success.  */
    590  1.1  christos   const gdb_byte *buffer = (const gdb_byte *) py_buff.buf;
    591  1.1  christos   memcpy (buff, buffer, len);
    592  1.1  christos   return 0;
    593  1.1  christos }
    594  1.1  christos 
    595  1.1  christos /* Implement DisassemblerResult.length attribute, return the length of the
    596  1.1  christos    disassembled instruction.  */
    597  1.1  christos 
    598  1.1  christos static PyObject *
    599  1.1  christos disasmpy_result_length (PyObject *self, void *closure)
    600  1.1  christos {
    601  1.1  christos   disasm_result_object *obj = (disasm_result_object *) self;
    602  1.1  christos   return gdb_py_object_from_longest (obj->length).release ();
    603  1.1  christos }
    604  1.1  christos 
    605  1.1  christos /* Implement DisassemblerResult.string attribute, return the content string
    606  1.1  christos    of the disassembled instruction.  */
    607  1.1  christos 
    608  1.1  christos static PyObject *
    609  1.1  christos disasmpy_result_string (PyObject *self, void *closure)
    610  1.1  christos {
    611  1.1  christos   disasm_result_object *obj = (disasm_result_object *) self;
    612  1.1  christos 
    613  1.1  christos   gdb_assert (obj->content != nullptr);
    614  1.1  christos   gdb_assert (strlen (obj->content->c_str ()) > 0);
    615  1.1  christos   gdb_assert (obj->length > 0);
    616  1.1  christos   return PyUnicode_Decode (obj->content->c_str (),
    617  1.1  christos 			   obj->content->size (),
    618  1.1  christos 			   host_charset (), nullptr);
    619  1.1  christos }
    620  1.1  christos 
    621  1.1  christos /* Implement DisassemblerResult.__init__.  Takes two arguments, an
    622  1.1  christos    integer, the length in bytes of the disassembled instruction, and a
    623  1.1  christos    string, the disassembled content of the instruction.  */
    624  1.1  christos 
    625  1.1  christos static int
    626  1.1  christos disasmpy_result_init (PyObject *self, PyObject *args, PyObject *kwargs)
    627  1.1  christos {
    628  1.1  christos   static const char *keywords[] = { "length", "string", NULL };
    629  1.1  christos   int length;
    630  1.1  christos   const char *string;
    631  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "is", keywords,
    632  1.1  christos 					&length, &string))
    633  1.1  christos     return -1;
    634  1.1  christos 
    635  1.1  christos   if (length <= 0)
    636  1.1  christos     {
    637  1.1  christos       PyErr_SetString (PyExc_ValueError,
    638  1.1  christos 		       _("Length must be greater than 0."));
    639  1.1  christos       return -1;
    640  1.1  christos     }
    641  1.1  christos 
    642  1.1  christos   if (strlen (string) == 0)
    643  1.1  christos     {
    644  1.1  christos       PyErr_SetString (PyExc_ValueError,
    645  1.1  christos 		       _("String must not be empty."));
    646  1.1  christos       return -1;
    647  1.1  christos     }
    648  1.1  christos 
    649  1.1  christos   disasm_result_object *obj = (disasm_result_object *) self;
    650  1.1  christos   disasmpy_init_disassembler_result (obj, length, std::string (string));
    651  1.1  christos 
    652  1.1  christos   return 0;
    653  1.1  christos }
    654  1.1  christos 
    655  1.1  christos /* Implement memory_error_func callback for disassemble_info.  Extract the
    656  1.1  christos    underlying DisassembleInfo Python object, and set a memory error on
    657  1.1  christos    it.  */
    658  1.1  christos 
    659  1.1  christos void
    660  1.1  christos gdbpy_disassembler::memory_error_func (int status, bfd_vma memaddr,
    661  1.1  christos 				       struct disassemble_info *info) noexcept
    662  1.1  christos {
    663  1.1  christos   gdbpy_disassembler *dis
    664  1.1  christos     = static_cast<gdbpy_disassembler *> (info->application_data);
    665  1.1  christos   dis->m_memory_error_address.emplace (memaddr);
    666  1.1  christos }
    667  1.1  christos 
    668  1.1  christos /* Wrapper of print_address.  */
    669  1.1  christos 
    670  1.1  christos void
    671  1.1  christos gdbpy_disassembler::print_address_func (bfd_vma addr,
    672  1.1  christos 					struct disassemble_info *info) noexcept
    673  1.1  christos {
    674  1.1  christos   gdbpy_disassembler *dis
    675  1.1  christos     = static_cast<gdbpy_disassembler *> (info->application_data);
    676  1.1  christos   print_address (dis->arch (), addr, dis->stream ());
    677  1.1  christos }
    678  1.1  christos 
    679  1.1  christos /* constructor.  */
    680  1.1  christos 
    681  1.1  christos gdbpy_disassembler::gdbpy_disassembler (disasm_info_object *obj,
    682  1.1  christos 					PyObject *memory_source)
    683  1.1  christos   : gdb_printing_disassembler (obj->gdbarch, &m_string_file,
    684  1.1  christos 			       read_memory_func, memory_error_func,
    685  1.1  christos 			       print_address_func),
    686  1.1  christos     m_disasm_info_object (obj),
    687  1.1  christos     m_memory_source (memory_source)
    688  1.1  christos { /* Nothing.  */ }
    689  1.1  christos 
    690  1.1  christos /* A wrapper around a reference to a Python DisassembleInfo object, which
    691  1.1  christos    ensures that the object is marked as invalid when we leave the enclosing
    692  1.1  christos    scope.
    693  1.1  christos 
    694  1.1  christos    Each DisassembleInfo is created in gdbpy_print_insn, and is done with by
    695  1.1  christos    the time that function returns.  However, there's nothing to stop a user
    696  1.1  christos    caching a reference to the DisassembleInfo, and thus keeping the object
    697  1.1  christos    around.
    698  1.1  christos 
    699  1.1  christos    We therefore have the notion of a DisassembleInfo becoming invalid, this
    700  1.1  christos    happens when gdbpy_print_insn returns.  This class is responsible for
    701  1.1  christos    marking the DisassembleInfo as invalid in its destructor.  */
    702  1.1  christos 
    703  1.1  christos struct scoped_disasm_info_object
    704  1.1  christos {
    705  1.1  christos   /* Constructor.  */
    706  1.1  christos   scoped_disasm_info_object (struct gdbarch *gdbarch, CORE_ADDR memaddr,
    707  1.1  christos 			     disassemble_info *info)
    708  1.1  christos     : m_disasm_info (allocate_disasm_info_object ())
    709  1.1  christos   {
    710  1.1  christos     disasm_info_fill (m_disasm_info.get (), gdbarch, current_program_space,
    711  1.1  christos 		      memaddr, info, nullptr);
    712  1.1  christos   }
    713  1.1  christos 
    714  1.1  christos   /* Upon destruction mark m_diasm_info as invalid.  */
    715  1.1  christos   ~scoped_disasm_info_object ()
    716  1.1  christos   {
    717  1.1  christos     /* Invalidate the original DisassembleInfo object as well as any copies
    718  1.1  christos        that the user might have made.  */
    719  1.1  christos     for (disasm_info_object *obj = m_disasm_info.get ();
    720  1.1  christos 	 obj != nullptr;
    721  1.1  christos 	 obj = obj->next)
    722  1.1  christos       obj->gdb_info = nullptr;
    723  1.1  christos   }
    724  1.1  christos 
    725  1.1  christos   /* Return a pointer to the underlying disasm_info_object instance.  */
    726  1.1  christos   disasm_info_object *
    727  1.1  christos   get () const
    728  1.1  christos   {
    729  1.1  christos     return m_disasm_info.get ();
    730  1.1  christos   }
    731  1.1  christos 
    732  1.1  christos private:
    733  1.1  christos 
    734  1.1  christos   /* Wrapper around the call to PyObject_New, this wrapper function can be
    735  1.1  christos      called from the constructor initialization list, while PyObject_New, a
    736  1.1  christos      macro, can't.  */
    737  1.1  christos   static disasm_info_object *
    738  1.1  christos   allocate_disasm_info_object ()
    739  1.1  christos   {
    740  1.1  christos     return (disasm_info_object *) PyObject_New (disasm_info_object,
    741  1.1  christos 						&disasm_info_object_type);
    742  1.1  christos   }
    743  1.1  christos 
    744  1.1  christos   /* A reference to a gdb.disassembler.DisassembleInfo object.  When this
    745  1.1  christos      containing instance goes out of scope this reference is released,
    746  1.1  christos      however, the user might be holding other references to the
    747  1.1  christos      DisassembleInfo object in Python code, so the underlying object might
    748  1.1  christos      not be deleted.  */
    749  1.1  christos   gdbpy_ref<disasm_info_object> m_disasm_info;
    750  1.1  christos };
    751  1.1  christos 
    752  1.1  christos /* See python-internal.h.  */
    753  1.1  christos 
    754  1.1  christos gdb::optional<int>
    755  1.1  christos gdbpy_print_insn (struct gdbarch *gdbarch, CORE_ADDR memaddr,
    756  1.1  christos 		  disassemble_info *info)
    757  1.1  christos {
    758  1.1  christos   /* Early exit case.  This must be done as early as possible, and
    759  1.1  christos      definitely before we enter Python environment.  The
    760  1.1  christos      python_print_insn_enabled flag is set (from Python) only when the user
    761  1.1  christos      has installed one (or more) Python disassemblers.  So in the common
    762  1.1  christos      case (no custom disassembler installed) this flag will be false,
    763  1.1  christos      allowing for a quick return.  */
    764  1.1  christos   if (!gdb_python_initialized || !python_print_insn_enabled)
    765  1.1  christos     return {};
    766  1.1  christos 
    767  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
    768  1.1  christos 
    769  1.1  christos   /* Import the gdb.disassembler module.  */
    770  1.1  christos   gdbpy_ref<> gdb_python_disassembler_module
    771  1.1  christos     (PyImport_ImportModule ("gdb.disassembler"));
    772  1.1  christos   if (gdb_python_disassembler_module == nullptr)
    773  1.1  christos     {
    774  1.1  christos       gdbpy_print_stack ();
    775  1.1  christos       return {};
    776  1.1  christos     }
    777  1.1  christos 
    778  1.1  christos   /* Get the _print_insn attribute from the module, this should be the
    779  1.1  christos      function we are going to call to actually perform the disassembly.  */
    780  1.1  christos   gdbpy_ref<> hook
    781  1.1  christos     (PyObject_GetAttrString (gdb_python_disassembler_module.get (),
    782  1.1  christos 			     "_print_insn"));
    783  1.1  christos   if (hook == nullptr)
    784  1.1  christos     {
    785  1.1  christos       gdbpy_print_stack ();
    786  1.1  christos       return {};
    787  1.1  christos     }
    788  1.1  christos 
    789  1.1  christos   /* Create the new DisassembleInfo object we will pass into Python.  This
    790  1.1  christos      object will be marked as invalid when we leave this scope.  */
    791  1.1  christos   scoped_disasm_info_object scoped_disasm_info (gdbarch, memaddr, info);
    792  1.1  christos   disasm_info_object *disasm_info = scoped_disasm_info.get ();
    793  1.1  christos 
    794  1.1  christos   /* Call into the registered disassembler to (possibly) perform the
    795  1.1  christos      disassembly.  */
    796  1.1  christos   PyObject *insn_disas_obj = (PyObject *) disasm_info;
    797  1.1  christos   gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
    798  1.1  christos 						    insn_disas_obj,
    799  1.1  christos 						    nullptr));
    800  1.1  christos 
    801  1.1  christos   if (result == nullptr)
    802  1.1  christos     {
    803  1.1  christos       /* The call into Python code resulted in an exception.  If this was a
    804  1.1  christos 	 gdb.MemoryError, then we can figure out an address and call the
    805  1.1  christos 	 disassemble_info::memory_error_func to report the error back to
    806  1.1  christos 	 core GDB.  Any other exception type we report back to core GDB as
    807  1.1  christos 	 an unknown error (return -1 without first calling the
    808  1.1  christos 	 memory_error_func callback).  */
    809  1.1  christos 
    810  1.1  christos       if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
    811  1.1  christos 	{
    812  1.1  christos 	  /* A gdb.MemoryError might have an address attribute which
    813  1.1  christos 	     contains the address at which the memory error occurred.  If
    814  1.1  christos 	     this is the case then use this address, otherwise, fallback to
    815  1.1  christos 	     just using the address of the instruction we were asked to
    816  1.1  christos 	     disassemble.  */
    817  1.1  christos 	  gdbpy_err_fetch err;
    818  1.1  christos 	  PyErr_Clear ();
    819  1.1  christos 
    820  1.1  christos 	  CORE_ADDR addr;
    821  1.1  christos 	  if (err.value () != nullptr
    822  1.1  christos 	      && PyObject_HasAttrString (err.value ().get (), "address"))
    823  1.1  christos 	    {
    824  1.1  christos 	      PyObject *addr_obj
    825  1.1  christos 		= PyObject_GetAttrString (err.value ().get (), "address");
    826  1.1  christos 	      if (get_addr_from_python (addr_obj, &addr) < 0)
    827  1.1  christos 		addr = disasm_info->address;
    828  1.1  christos 	    }
    829  1.1  christos 	  else
    830  1.1  christos 	    addr = disasm_info->address;
    831  1.1  christos 
    832  1.1  christos 	  info->memory_error_func (-1, addr, info);
    833  1.1  christos 	  return gdb::optional<int> (-1);
    834  1.1  christos 	}
    835  1.1  christos       else if (PyErr_ExceptionMatches (gdbpy_gdberror_exc))
    836  1.1  christos 	{
    837  1.1  christos 	  gdbpy_err_fetch err;
    838  1.1  christos 	  gdb::unique_xmalloc_ptr<char> msg = err.to_string ();
    839  1.1  christos 
    840  1.1  christos 	  info->fprintf_func (info->stream, "%s", msg.get ());
    841  1.1  christos 	  return gdb::optional<int> (-1);
    842  1.1  christos 	}
    843  1.1  christos       else
    844  1.1  christos 	{
    845  1.1  christos 	  gdbpy_print_stack ();
    846  1.1  christos 	  return gdb::optional<int> (-1);
    847  1.1  christos 	}
    848  1.1  christos 
    849  1.1  christos     }
    850  1.1  christos   else if (result == Py_None)
    851  1.1  christos     {
    852  1.1  christos       /* A return value of None indicates that the Python code could not,
    853  1.1  christos 	 or doesn't want to, disassemble this instruction.  Just return an
    854  1.1  christos 	 empty result and core GDB will try to disassemble this for us.  */
    855  1.1  christos       return {};
    856  1.1  christos     }
    857  1.1  christos 
    858  1.1  christos   /* Check the result is a DisassemblerResult (or a sub-class).  */
    859  1.1  christos   if (!PyObject_IsInstance (result.get (),
    860  1.1  christos 			    (PyObject *) &disasm_result_object_type))
    861  1.1  christos     {
    862  1.1  christos       PyErr_SetString (PyExc_TypeError,
    863  1.1  christos 		       _("Result is not a DisassemblerResult."));
    864  1.1  christos       gdbpy_print_stack ();
    865  1.1  christos       return gdb::optional<int> (-1);
    866  1.1  christos     }
    867  1.1  christos 
    868  1.1  christos   /* The call into Python neither raised an exception, or returned None.
    869  1.1  christos      Check to see if the result looks valid.  */
    870  1.1  christos   gdbpy_ref<> length_obj (PyObject_GetAttrString (result.get (), "length"));
    871  1.1  christos   if (length_obj == nullptr)
    872  1.1  christos     {
    873  1.1  christos       gdbpy_print_stack ();
    874  1.1  christos       return gdb::optional<int> (-1);
    875  1.1  christos     }
    876  1.1  christos 
    877  1.1  christos   gdbpy_ref<> string_obj (PyObject_GetAttrString (result.get (), "string"));
    878  1.1  christos   if (string_obj == nullptr)
    879  1.1  christos     {
    880  1.1  christos       gdbpy_print_stack ();
    881  1.1  christos       return gdb::optional<int> (-1);
    882  1.1  christos     }
    883  1.1  christos   if (!gdbpy_is_string (string_obj.get ()))
    884  1.1  christos     {
    885  1.1  christos       PyErr_SetString (PyExc_TypeError, _("String attribute is not a string."));
    886  1.1  christos       gdbpy_print_stack ();
    887  1.1  christos       return gdb::optional<int> (-1);
    888  1.1  christos     }
    889  1.1  christos 
    890  1.1  christos   gdb::unique_xmalloc_ptr<char> string
    891  1.1  christos     = gdbpy_obj_to_string (string_obj.get ());
    892  1.1  christos   if (string == nullptr)
    893  1.1  christos     {
    894  1.1  christos       gdbpy_print_stack ();
    895  1.1  christos       return gdb::optional<int> (-1);
    896  1.1  christos     }
    897  1.1  christos 
    898  1.1  christos   long length;
    899  1.1  christos   if (!gdb_py_int_as_long (length_obj.get (), &length))
    900  1.1  christos     {
    901  1.1  christos       gdbpy_print_stack ();
    902  1.1  christos       return gdb::optional<int> (-1);
    903  1.1  christos     }
    904  1.1  christos 
    905  1.1  christos   long max_insn_length = (gdbarch_max_insn_length_p (gdbarch) ?
    906  1.1  christos 			  gdbarch_max_insn_length (gdbarch) : INT_MAX);
    907  1.1  christos   if (length <= 0)
    908  1.1  christos     {
    909  1.1  christos       PyErr_SetString
    910  1.1  christos 	(PyExc_ValueError,
    911  1.1  christos 	 _("Invalid length attribute: length must be greater than 0."));
    912  1.1  christos       gdbpy_print_stack ();
    913  1.1  christos       return gdb::optional<int> (-1);
    914  1.1  christos     }
    915  1.1  christos   if (length > max_insn_length)
    916  1.1  christos     {
    917  1.1  christos       PyErr_Format
    918  1.1  christos 	(PyExc_ValueError,
    919  1.1  christos 	 _("Invalid length attribute: length %d greater than architecture maximum of %d"),
    920  1.1  christos 	 length, max_insn_length);
    921  1.1  christos       gdbpy_print_stack ();
    922  1.1  christos       return gdb::optional<int> (-1);
    923  1.1  christos     }
    924  1.1  christos 
    925  1.1  christos   if (strlen (string.get ()) == 0)
    926  1.1  christos     {
    927  1.1  christos       PyErr_SetString (PyExc_ValueError,
    928  1.1  christos 		       _("String attribute must not be empty."));
    929  1.1  christos       gdbpy_print_stack ();
    930  1.1  christos       return gdb::optional<int> (-1);
    931  1.1  christos     }
    932  1.1  christos 
    933  1.1  christos   /* Print the disassembled instruction back to core GDB, and return the
    934  1.1  christos      length of the disassembled instruction.  */
    935  1.1  christos   info->fprintf_func (info->stream, "%s", string.get ());
    936  1.1  christos   return gdb::optional<int> (length);
    937  1.1  christos }
    938  1.1  christos 
    939  1.1  christos /* The tp_dealloc callback for the DisassemblerResult type.  Takes care of
    940  1.1  christos    deallocating the content buffer.  */
    941  1.1  christos 
    942  1.1  christos static void
    943  1.1  christos disasmpy_dealloc_result (PyObject *self)
    944  1.1  christos {
    945  1.1  christos   disasm_result_object *obj = (disasm_result_object *) self;
    946  1.1  christos   delete obj->content;
    947  1.1  christos   Py_TYPE (self)->tp_free (self);
    948  1.1  christos }
    949  1.1  christos 
    950  1.1  christos /* The get/set attributes of the gdb.disassembler.DisassembleInfo type.  */
    951  1.1  christos 
    952  1.1  christos static gdb_PyGetSetDef disasm_info_object_getset[] = {
    953  1.1  christos   { "address", disasmpy_info_address, nullptr,
    954  1.1  christos     "Start address of the instruction to disassemble.", nullptr },
    955  1.1  christos   { "architecture", disasmpy_info_architecture, nullptr,
    956  1.1  christos     "Architecture to disassemble in", nullptr },
    957  1.1  christos   { "progspace", disasmpy_info_progspace, nullptr,
    958  1.1  christos     "Program space to disassemble in", nullptr },
    959  1.1  christos   { nullptr }   /* Sentinel */
    960  1.1  christos };
    961  1.1  christos 
    962  1.1  christos /* The methods of the gdb.disassembler.DisassembleInfo type.  */
    963  1.1  christos 
    964  1.1  christos static PyMethodDef disasm_info_object_methods[] = {
    965  1.1  christos   { "read_memory", (PyCFunction) disasmpy_info_read_memory,
    966  1.1  christos     METH_VARARGS | METH_KEYWORDS,
    967  1.1  christos     "read_memory (LEN, OFFSET = 0) -> Octets[]\n\
    968  1.1  christos Read LEN octets for the instruction to disassemble." },
    969  1.1  christos   { "is_valid", disasmpy_info_is_valid, METH_NOARGS,
    970  1.1  christos     "is_valid () -> Boolean.\n\
    971  1.1  christos Return true if this DisassembleInfo is valid, false if not." },
    972  1.1  christos   {nullptr}  /* Sentinel */
    973  1.1  christos };
    974  1.1  christos 
    975  1.1  christos /* The get/set attributes of the gdb.disassembler.DisassemblerResult type.  */
    976  1.1  christos 
    977  1.1  christos static gdb_PyGetSetDef disasm_result_object_getset[] = {
    978  1.1  christos   { "length", disasmpy_result_length, nullptr,
    979  1.1  christos     "Length of the disassembled instruction.", nullptr },
    980  1.1  christos   { "string", disasmpy_result_string, nullptr,
    981  1.1  christos     "String representing the disassembled instruction.", nullptr },
    982  1.1  christos   { nullptr }   /* Sentinel */
    983  1.1  christos };
    984  1.1  christos 
    985  1.1  christos /* These are the methods we add into the _gdb.disassembler module, which
    986  1.1  christos    are then imported into the gdb.disassembler module.  These are global
    987  1.1  christos    functions that support performing disassembly.  */
    988  1.1  christos 
    989  1.1  christos PyMethodDef python_disassembler_methods[] =
    990  1.1  christos {
    991  1.1  christos   { "builtin_disassemble", (PyCFunction) disasmpy_builtin_disassemble,
    992  1.1  christos     METH_VARARGS | METH_KEYWORDS,
    993  1.1  christos     "builtin_disassemble (INFO, MEMORY_SOURCE = None) -> None\n\
    994  1.1  christos Disassemble using GDB's builtin disassembler.  INFO is an instance of\n\
    995  1.1  christos gdb.disassembler.DisassembleInfo.  The MEMORY_SOURCE, if not None, should\n\
    996  1.1  christos be an object with the read_memory method." },
    997  1.1  christos   { "_set_enabled", (PyCFunction) disasmpy_set_enabled,
    998  1.1  christos     METH_VARARGS | METH_KEYWORDS,
    999  1.1  christos     "_set_enabled (STATE) -> None\n\
   1000  1.1  christos Set whether GDB should call into the Python _print_insn code or not." },
   1001  1.1  christos   {nullptr, nullptr, 0, nullptr}
   1002  1.1  christos };
   1003  1.1  christos 
   1004  1.1  christos /* Structure to define the _gdb.disassembler module.  */
   1005  1.1  christos 
   1006  1.1  christos static struct PyModuleDef python_disassembler_module_def =
   1007  1.1  christos {
   1008  1.1  christos   PyModuleDef_HEAD_INIT,
   1009  1.1  christos   "_gdb.disassembler",
   1010  1.1  christos   nullptr,
   1011  1.1  christos   -1,
   1012  1.1  christos   python_disassembler_methods,
   1013  1.1  christos   nullptr,
   1014  1.1  christos   nullptr,
   1015  1.1  christos   nullptr,
   1016  1.1  christos   nullptr
   1017  1.1  christos };
   1018  1.1  christos 
   1019  1.1  christos /* Called to initialize the Python structures in this file.  */
   1020  1.1  christos 
   1021  1.1  christos int
   1022  1.1  christos gdbpy_initialize_disasm ()
   1023  1.1  christos {
   1024  1.1  christos   /* Create the _gdb.disassembler module, and add it to the _gdb module.  */
   1025  1.1  christos 
   1026  1.1  christos   PyObject *gdb_disassembler_module;
   1027  1.1  christos   gdb_disassembler_module = PyModule_Create (&python_disassembler_module_def);
   1028  1.1  christos   if (gdb_disassembler_module == nullptr)
   1029  1.1  christos     return -1;
   1030  1.1  christos   PyModule_AddObject(gdb_module, "disassembler", gdb_disassembler_module);
   1031  1.1  christos 
   1032  1.1  christos   /* This is needed so that 'import _gdb.disassembler' will work.  */
   1033  1.1  christos   PyObject *dict = PyImport_GetModuleDict ();
   1034  1.1  christos   PyDict_SetItemString (dict, "_gdb.disassembler", gdb_disassembler_module);
   1035  1.1  christos 
   1036  1.1  christos   disasm_info_object_type.tp_new = PyType_GenericNew;
   1037  1.1  christos   if (PyType_Ready (&disasm_info_object_type) < 0)
   1038  1.1  christos     return -1;
   1039  1.1  christos 
   1040  1.1  christos   if (gdb_pymodule_addobject (gdb_disassembler_module, "DisassembleInfo",
   1041  1.1  christos 			      (PyObject *) &disasm_info_object_type) < 0)
   1042  1.1  christos     return -1;
   1043  1.1  christos 
   1044  1.1  christos   disasm_result_object_type.tp_new = PyType_GenericNew;
   1045  1.1  christos   if (PyType_Ready (&disasm_result_object_type) < 0)
   1046  1.1  christos     return -1;
   1047  1.1  christos 
   1048  1.1  christos   if (gdb_pymodule_addobject (gdb_disassembler_module, "DisassemblerResult",
   1049  1.1  christos 			      (PyObject *) &disasm_result_object_type) < 0)
   1050  1.1  christos     return -1;
   1051  1.1  christos 
   1052  1.1  christos   return 0;
   1053  1.1  christos }
   1054  1.1  christos 
   1055  1.1  christos /* Describe the gdb.disassembler.DisassembleInfo type.  */
   1056  1.1  christos 
   1057  1.1  christos PyTypeObject disasm_info_object_type = {
   1058  1.1  christos   PyVarObject_HEAD_INIT (nullptr, 0)
   1059  1.1  christos   "gdb.disassembler.DisassembleInfo",		/*tp_name*/
   1060  1.1  christos   sizeof (disasm_info_object),			/*tp_basicsize*/
   1061  1.1  christos   0,						/*tp_itemsize*/
   1062  1.1  christos   disasm_info_dealloc,				/*tp_dealloc*/
   1063  1.1  christos   0,						/*tp_print*/
   1064  1.1  christos   0,						/*tp_getattr*/
   1065  1.1  christos   0,						/*tp_setattr*/
   1066  1.1  christos   0,						/*tp_compare*/
   1067  1.1  christos   0,						/*tp_repr*/
   1068  1.1  christos   0,						/*tp_as_number*/
   1069  1.1  christos   0,						/*tp_as_sequence*/
   1070  1.1  christos   0,						/*tp_as_mapping*/
   1071  1.1  christos   0,						/*tp_hash */
   1072  1.1  christos   0,						/*tp_call*/
   1073  1.1  christos   0,						/*tp_str*/
   1074  1.1  christos   0,						/*tp_getattro*/
   1075  1.1  christos   0,						/*tp_setattro*/
   1076  1.1  christos   0,						/*tp_as_buffer*/
   1077  1.1  christos   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags*/
   1078  1.1  christos   "GDB instruction disassembler object",	/* tp_doc */
   1079  1.1  christos   0,						/* tp_traverse */
   1080  1.1  christos   0,						/* tp_clear */
   1081  1.1  christos   0,						/* tp_richcompare */
   1082  1.1  christos   0,						/* tp_weaklistoffset */
   1083  1.1  christos   0,						/* tp_iter */
   1084  1.1  christos   0,						/* tp_iternext */
   1085  1.1  christos   disasm_info_object_methods,			/* tp_methods */
   1086  1.1  christos   0,						/* tp_members */
   1087  1.1  christos   disasm_info_object_getset,			/* tp_getset */
   1088  1.1  christos   0,						/* tp_base */
   1089  1.1  christos   0,						/* tp_dict */
   1090  1.1  christos   0,						/* tp_descr_get */
   1091  1.1  christos   0,						/* tp_descr_set */
   1092  1.1  christos   0,						/* tp_dictoffset */
   1093  1.1  christos   disasm_info_init,				/* tp_init */
   1094  1.1  christos   0,						/* tp_alloc */
   1095  1.1  christos };
   1096  1.1  christos 
   1097  1.1  christos /* Describe the gdb.disassembler.DisassemblerResult type.  */
   1098  1.1  christos 
   1099  1.1  christos PyTypeObject disasm_result_object_type = {
   1100  1.1  christos   PyVarObject_HEAD_INIT (nullptr, 0)
   1101  1.1  christos   "gdb.disassembler.DisassemblerResult",	/*tp_name*/
   1102  1.1  christos   sizeof (disasm_result_object),		/*tp_basicsize*/
   1103  1.1  christos   0,						/*tp_itemsize*/
   1104  1.1  christos   disasmpy_dealloc_result,			/*tp_dealloc*/
   1105  1.1  christos   0,						/*tp_print*/
   1106  1.1  christos   0,						/*tp_getattr*/
   1107  1.1  christos   0,						/*tp_setattr*/
   1108  1.1  christos   0,						/*tp_compare*/
   1109  1.1  christos   0,						/*tp_repr*/
   1110  1.1  christos   0,						/*tp_as_number*/
   1111  1.1  christos   0,						/*tp_as_sequence*/
   1112  1.1  christos   0,						/*tp_as_mapping*/
   1113  1.1  christos   0,						/*tp_hash */
   1114  1.1  christos   0,						/*tp_call*/
   1115  1.1  christos   0,						/*tp_str*/
   1116  1.1  christos   0,						/*tp_getattro*/
   1117  1.1  christos   0,						/*tp_setattro*/
   1118  1.1  christos   0,						/*tp_as_buffer*/
   1119  1.1  christos   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags*/
   1120  1.1  christos   "GDB object, representing a disassembler result",	/* tp_doc */
   1121  1.1  christos   0,						/* tp_traverse */
   1122  1.1  christos   0,						/* tp_clear */
   1123  1.1  christos   0,						/* tp_richcompare */
   1124  1.1  christos   0,						/* tp_weaklistoffset */
   1125  1.1  christos   0,						/* tp_iter */
   1126  1.1  christos   0,						/* tp_iternext */
   1127  1.1  christos   0,						/* tp_methods */
   1128  1.1  christos   0,						/* tp_members */
   1129  1.1  christos   disasm_result_object_getset,			/* tp_getset */
   1130  1.1  christos   0,						/* tp_base */
   1131  1.1  christos   0,						/* tp_dict */
   1132  1.1  christos   0,						/* tp_descr_get */
   1133  1.1  christos   0,						/* tp_descr_set */
   1134  1.1  christos   0,						/* tp_dictoffset */
   1135  1.1  christos   disasmpy_result_init,				/* tp_init */
   1136  1.1  christos   0,						/* tp_alloc */
   1137  1.1  christos };
   1138