1 /* Python interface to instruction disassembly.
3 Copyright (C) 2021-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "python-internal.h"
23 #include "arch-utils.h"
26 #include "progspace.h"
28 /* Implement gdb.disassembler.DisassembleInfo type. An object of this type
29 represents a single disassembler request from GDB. */
31 struct disasm_info_object
35 /* The architecture in which we are disassembling. */
36 struct gdbarch
*gdbarch
;
38 /* The program_space in which we are disassembling. */
39 struct program_space
*program_space
;
41 /* Address of the instruction to disassemble. */
44 /* The disassemble_info passed from core GDB, this contains the
45 callbacks necessary to read the instruction from core GDB, and to
46 print the disassembled instruction. */
47 disassemble_info
*gdb_info
;
49 /* If copies of this object are created then they are chained together
50 via this NEXT pointer, this allows all the copies to be invalidated at
51 the same time as the parent object. */
52 struct disasm_info_object
*next
;
55 extern PyTypeObject disasm_info_object_type
56 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_info_object");
58 /* Implement gdb.disassembler.DisassembleAddressPart type. An object of
59 this type represents a small part of a disassembled instruction; a part
60 that is an address that should be printed using a call to GDB's
61 internal print_address function. */
63 struct disasm_addr_part_object
67 /* The address to be formatted. */
70 /* A gdbarch. This is only needed in the case where the user asks for
71 the DisassemblerAddressPart to be converted to a string. When we
72 return this part to GDB within a DisassemblerResult then GDB will use
73 the gdbarch from the initial disassembly request. */
74 struct gdbarch
*gdbarch
;
77 extern PyTypeObject disasm_addr_part_object_type
78 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_addr_part_object");
80 /* Implement gdb.disassembler.DisassembleTextPart type. An object of
81 this type represents a small part of a disassembled instruction; a part
82 that is a piece of test along with an associated style. */
84 struct disasm_text_part_object
88 /* The string that is this part. */
91 /* The style to use when displaying this part. */
92 enum disassembler_style style
;
95 extern PyTypeObject disasm_text_part_object_type
96 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_text_part_object");
98 extern PyTypeObject disasm_part_object_type
99 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("PyObject");
101 /* Implement gdb.disassembler.DisassemblerResult type, an object that holds
102 the result of calling the disassembler. This is mostly the length of
103 the disassembled instruction (in bytes), and the string representing the
104 disassembled instruction. */
106 struct disasm_result_object
110 /* The length of the disassembled instruction in bytes. */
113 /* A vector containing all the parts of the disassembled instruction.
114 Each part will be a DisassemblerPart sub-class. */
115 std::vector
<gdbpy_ref
<>> *parts
;
118 extern PyTypeObject disasm_result_object_type
119 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("disasm_result_object");
121 /* When this is false we fast path out of gdbpy_print_insn, which should
122 keep the performance impact of the Python disassembler down. This is
123 set to true from Python by calling gdb.disassembler._set_enabled() when
124 the user registers a disassembler. */
126 static bool python_print_insn_enabled
= false;
128 /* A sub-class of gdb_disassembler that holds a pointer to a Python
129 DisassembleInfo object. A pointer to an instance of this class is
130 placed in the application_data field of the disassemble_info that is
131 used when we call gdbarch_print_insn. */
133 struct gdbpy_disassembler
: public gdb_disassemble_info
136 gdbpy_disassembler (disasm_info_object
*obj
, PyObject
*memory_source
);
138 /* Get the DisassembleInfo object pointer. */
140 py_disasm_info () const
142 return m_disasm_info_object
;
145 /* Callbacks used by disassemble_info. */
146 static void memory_error_func (int status
, bfd_vma memaddr
,
147 struct disassemble_info
*info
) noexcept
;
148 static void print_address_func (bfd_vma addr
,
149 struct disassemble_info
*info
) noexcept
;
150 static int read_memory_func (bfd_vma memaddr
, gdb_byte
*buff
,
152 struct disassemble_info
*info
) noexcept
;
154 /* Callback used as the disassemble_info's fprintf_func callback. The
155 DIS_INFO pointer is a pointer to a gdbpy_disassembler object. */
156 static int fprintf_func (void *dis_info
, const char *format
, ...) noexcept
157 ATTRIBUTE_PRINTF(2,3);
159 /* Callback used as the disassemble_info's fprintf_styled_func callback.
160 The DIS_INFO pointer is a pointer to a gdbpy_disassembler. */
161 static int fprintf_styled_func (void *dis_info
,
162 enum disassembler_style style
,
163 const char *format
, ...) noexcept
164 ATTRIBUTE_PRINTF(3,4);
166 /* Helper used by fprintf_func and fprintf_styled_func. This function
167 creates a new DisassemblerTextPart and adds it to the disassembler's
168 parts list. The actual disassembler is accessed through DIS_INFO,
169 which is a pointer to the gdbpy_disassembler object. */
170 static int vfprintf_styled_func (void *dis_info
,
171 enum disassembler_style style
,
172 const char *format
, va_list args
) noexcept
173 ATTRIBUTE_PRINTF(3,0);
175 /* Return a reference to an optional that contains the address at which a
176 memory error occurred. The optional will only have a value if a
177 memory error actually occurred. */
178 const std::optional
<CORE_ADDR
> &memory_error_address () const
179 { return m_memory_error_address
; }
181 /* Return the content of the disassembler as a string. The contents are
182 moved out of the disassembler, so after this call the disassembler
183 contents have been reset back to empty. */
184 std::vector
<gdbpy_ref
<>> release ()
186 return std::move (m_parts
);
189 /* If there is a Python exception stored in this disassembler then
190 restore it (i.e. set the PyErr_* state), clear the exception within
191 this disassembler, and return true. There must be no current
192 exception set (i.e. !PyErr_Occurred()) when this function is called,
193 as any such exception might get lost.
195 Otherwise, there is no exception stored in this disassembler, return
197 bool restore_exception ()
199 gdb_assert (!PyErr_Occurred ());
200 if (m_stored_exception
.has_value ())
202 gdbpy_err_fetch ex
= std::move (*m_stored_exception
);
203 m_stored_exception
.reset ();
213 /* The list of all the parts that make up this disassembled instruction.
214 This is populated as a result of the callbacks from libopcodes as the
215 instruction is disassembled. */
216 std::vector
<gdbpy_ref
<>> m_parts
;
218 /* The DisassembleInfo object we are disassembling for. */
219 disasm_info_object
*m_disasm_info_object
;
221 /* When the user indicates that a memory error has occurred then the
222 address of the memory error is stored in here. */
223 std::optional
<CORE_ADDR
> m_memory_error_address
;
225 /* When the user calls the builtin_disassemble function, if they pass a
226 memory source object then a pointer to the object is placed in here,
227 otherwise, this field is nullptr. */
228 PyObject
*m_memory_source
;
230 /* Move the exception EX into this disassembler object. */
231 void store_exception (gdbpy_err_fetch
&&ex
)
233 /* The only calls to store_exception are from read_memory_func, which
234 will return early if there's already an exception stored. */
235 gdb_assert (!m_stored_exception
.has_value ());
236 m_stored_exception
.emplace (std::move (ex
));
239 /* Return true if there is an exception stored in this disassembler. */
240 bool has_stored_exception () const
242 return m_stored_exception
.has_value ();
245 /* Store a single exception. This is used to pass Python exceptions back
246 from ::memory_read to disasmpy_builtin_disassemble. */
247 std::optional
<gdbpy_err_fetch
> m_stored_exception
;
250 /* Return true if OBJ is still valid, otherwise, return false. A valid OBJ
251 will have a non-nullptr gdb_info field. */
254 disasm_info_object_is_valid (disasm_info_object
*obj
)
256 return obj
->gdb_info
!= nullptr;
259 /* Fill in OBJ with all the other arguments. */
262 disasm_info_fill (disasm_info_object
*obj
, struct gdbarch
*gdbarch
,
263 program_space
*progspace
, bfd_vma address
,
264 disassemble_info
*di
, disasm_info_object
*next
)
266 obj
->gdbarch
= gdbarch
;
267 obj
->program_space
= progspace
;
268 obj
->address
= address
;
273 /* Implement DisassembleInfo.__init__. Takes a single argument that must
274 be another DisassembleInfo object and copies the contents from the
275 argument into this new object. */
278 disasm_info_init (PyObject
*self
, PyObject
*args
, PyObject
*kwargs
)
280 static const char *keywords
[] = { "info", NULL
};
282 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwargs
, "O!", keywords
,
283 &disasm_info_object_type
,
287 disasm_info_object
*other
= (disasm_info_object
*) info_obj
;
288 disasm_info_object
*info
= (disasm_info_object
*) self
;
289 disasm_info_fill (info
, other
->gdbarch
, other
->program_space
,
290 other
->address
, other
->gdb_info
, other
->next
);
293 /* As the OTHER object now holds a pointer to INFO we inc the ref count
294 on INFO. This stops INFO being deleted until OTHER has gone away. */
295 Py_INCREF ((PyObject
*) info
);
299 /* The tp_dealloc callback for the DisassembleInfo type. */
302 disasm_info_dealloc (PyObject
*self
)
304 disasm_info_object
*obj
= (disasm_info_object
*) self
;
306 /* We no longer care about the object our NEXT pointer points at, so we
307 can decrement its reference count. This macro handles the case when
309 Py_XDECREF ((PyObject
*) obj
->next
);
311 /* Now core deallocation behaviour. */
312 Py_TYPE (self
)->tp_free (self
);
315 /* Implement __repr__ for the DisassembleInfo type. */
318 disasmpy_info_repr (PyObject
*self
)
320 disasm_info_object
*obj
= (disasm_info_object
*) self
;
322 const char *arch_name
323 = (gdbarch_bfd_arch_info (obj
->gdbarch
))->printable_name
;
324 return PyUnicode_FromFormat ("<%s address=%s architecture=%s>",
325 Py_TYPE (obj
)->tp_name
,
326 core_addr_to_string_nz (obj
->address
),
330 /* Implement DisassembleInfo.is_valid(), really just a wrapper around the
331 disasm_info_object_is_valid function above. */
334 disasmpy_info_is_valid (PyObject
*self
, PyObject
*args
)
336 disasm_info_object
*disasm_obj
= (disasm_info_object
*) self
;
338 if (disasm_info_object_is_valid (disasm_obj
))
344 /* Set the Python exception to be a gdb.MemoryError object, with ADDRESS
348 disasmpy_set_memory_error_for_address (CORE_ADDR address
)
350 PyObject
*address_obj
= gdb_py_object_from_longest (address
).release ();
351 PyErr_SetObject (gdbpy_gdb_memory_error
, address_obj
);
354 /* Create a new DisassemblerTextPart and return a gdbpy_ref wrapper for
355 the new object. STR is the string content of the part and STYLE is the
356 style to be used when GDB displays this part. */
359 make_disasm_text_part (std::string
&&str
, enum disassembler_style style
)
361 PyTypeObject
*type
= &disasm_text_part_object_type
;
362 disasm_text_part_object
*text_part
363 = (disasm_text_part_object
*) type
->tp_alloc (type
, 0);
364 text_part
->string
= new std::string (str
);
365 text_part
->style
= style
;
367 return gdbpy_ref
<> ((PyObject
*) text_part
);
370 /* Create a new DisassemblerAddressPart and return a gdbpy_ref wrapper for
371 the new object. GDBARCH is the architecture used when formatting the
372 address, and ADDRESS is the numerical address to be displayed. */
375 make_disasm_addr_part (struct gdbarch
*gdbarch
, CORE_ADDR address
)
377 PyTypeObject
*type
= &disasm_addr_part_object_type
;
378 disasm_addr_part_object
*addr_part
379 = (disasm_addr_part_object
*) type
->tp_alloc (type
, 0);
380 addr_part
->address
= address
;
381 addr_part
->gdbarch
= gdbarch
;
383 return gdbpy_ref
<> ((PyObject
*) addr_part
);
386 /* Ensure that a gdb.disassembler.DisassembleInfo is valid. */
388 #define DISASMPY_DISASM_INFO_REQUIRE_VALID(Info) \
390 if (!disasm_info_object_is_valid (Info)) \
392 PyErr_SetString (PyExc_RuntimeError, \
393 _("DisassembleInfo is no longer valid.")); \
398 /* Implement DisassembleInfo.text_part method. Creates and returns a new
399 DisassemblerTextPart object. */
402 disasmpy_info_make_text_part (PyObject
*self
, PyObject
*args
,
405 disasm_info_object
*obj
= (disasm_info_object
*) self
;
406 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
408 static const char *keywords
[] = { "style", "string", NULL
};
411 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwargs
, "is", keywords
,
412 &style_num
, &string
))
415 if (style_num
< 0 || style_num
> ((int) dis_style_comment_start
))
417 PyErr_SetString (PyExc_ValueError
,
418 _("Invalid disassembler style."));
422 if (strlen (string
) == 0)
424 PyErr_SetString (PyExc_ValueError
,
425 _("String must not be empty."));
429 gdbpy_ref
<> text_part
430 = make_disasm_text_part (std::string (string
),
431 (enum disassembler_style
) style_num
);
432 return text_part
.release ();
435 /* Implement DisassembleInfo.address_part method. Creates and returns a
436 new DisassemblerAddressPart object. */
439 disasmpy_info_make_address_part (PyObject
*self
, PyObject
*args
,
442 disasm_info_object
*obj
= (disasm_info_object
*) self
;
443 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
445 static const char *keywords
[] = { "address", NULL
};
447 PyObject
*address_object
;
448 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwargs
, "O", keywords
,
452 if (get_addr_from_python (address_object
, &address
) < 0)
455 return make_disasm_addr_part (obj
->gdbarch
, address
).release ();
458 /* Return a string representation of TEXT_PART. The returned string does
459 not include any styling. */
462 disasmpy_part_to_string (const disasm_text_part_object
*text_part
)
464 gdb_assert (text_part
->string
!= nullptr);
465 return *(text_part
->string
);
468 /* Return a string representation of ADDR_PART. The returned string does
469 not include any styling. */
472 disasmpy_part_to_string (const disasm_addr_part_object
*addr_part
)
475 print_address (addr_part
->gdbarch
, addr_part
->address
, &buf
);
476 return buf
.release ();
479 /* PARTS is a vector of Python objects, each is a sub-class of
480 DisassemblerPart. Create a string by concatenating the string
481 representation of each part, and return this new string.
483 Converting an address part requires that we call back into GDB core,
484 which could throw an exception. As such, calls to this function should
485 be wrapped with a try/catch. */
488 disasmpy_parts_list_to_string (const std::vector
<gdbpy_ref
<>> &parts
)
493 if (Py_TYPE (p
.get ()) == &disasm_text_part_object_type
)
495 disasm_text_part_object
*text_part
496 = (disasm_text_part_object
*) p
.get ();
497 str
+= disasmpy_part_to_string (text_part
);
501 gdb_assert (Py_TYPE (p
.get ()) == &disasm_addr_part_object_type
);
503 disasm_addr_part_object
*addr_part
504 = (disasm_addr_part_object
*) p
.get ();
505 str
+= disasmpy_part_to_string (addr_part
);
512 /* Initialise OBJ, a DisassemblerResult object with LENGTH and PARTS.
513 OBJ might already have been initialised, in which case any existing
514 content should be discarded before the new PARTS are moved in. */
517 disasmpy_init_disassembler_result (disasm_result_object
*obj
, int length
,
518 std::vector
<gdbpy_ref
<>> &&parts
)
520 if (obj
->parts
== nullptr)
521 obj
->parts
= new std::vector
<gdbpy_ref
<>>;
523 obj
->parts
->clear ();
525 obj
->length
= length
;
526 *(obj
->parts
) = std::move (parts
);
529 /* Implement gdb.disassembler.builtin_disassemble(). Calls back into GDB's
530 builtin disassembler. The first argument is a DisassembleInfo object
531 describing what to disassemble. The second argument is optional and
532 provides a mechanism to modify the memory contents that the builtin
533 disassembler will actually disassemble.
535 Returns an instance of gdb.disassembler.DisassemblerResult, an object
536 that wraps a disassembled instruction, or it raises a
540 disasmpy_builtin_disassemble (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
542 PyObject
*info_obj
, *memory_source_obj
= nullptr;
543 static const char *keywords
[] = { "info", "memory_source", nullptr };
544 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "O!|O", keywords
,
545 &disasm_info_object_type
, &info_obj
,
549 disasm_info_object
*disasm_info
= (disasm_info_object
*) info_obj
;
550 DISASMPY_DISASM_INFO_REQUIRE_VALID (disasm_info
);
552 /* Where the result will be written. */
553 gdbpy_disassembler
disassembler (disasm_info
, memory_source_obj
);
555 /* Now actually perform the disassembly. LENGTH is set to the length of
556 the disassembled instruction, or -1 if there was a memory-error
557 encountered while disassembling. See below more more details on
558 handling of -1 return value. */
559 int length
= gdbarch_print_insn (disasm_info
->gdbarch
, disasm_info
->address
,
560 disassembler
.disasm_info ());
562 /* It is possible that, while calling a user overridden memory read
563 function, a Python exception was raised that couldn't be
564 translated into a standard memory-error. In this case the first such
565 exception is stored in the disassembler and restored here. */
566 if (disassembler
.restore_exception ())
572 /* In an ideal world, every disassembler should always call the
573 memory error function before returning a status of -1 as the only
574 error a disassembler should encounter is a failure to read
575 memory. Unfortunately, there are some disassemblers who don't
576 follow this rule, and will return -1 without calling the memory
579 To make the Python API simpler, we just classify everything as a
580 memory error, but the message has to be modified for the case
581 where the disassembler didn't call the memory error function. */
582 if (disassembler
.memory_error_address ().has_value ())
584 CORE_ADDR addr
= *disassembler
.memory_error_address ();
585 disasmpy_set_memory_error_for_address (addr
);
589 auto content
= disassembler
.release ();
594 str
= disasmpy_parts_list_to_string (content
);
596 catch (const gdb_exception
&except
)
598 return gdbpy_handle_gdb_exception (nullptr, except
);
601 PyErr_SetString (gdbpy_gdberror_exc
, str
.c_str ());
603 PyErr_SetString (gdbpy_gdberror_exc
,
604 _("Unknown disassembly error."));
609 /* Instructions are either non-zero in length, or we got an error,
610 indicated by a length of -1, which we handled above. */
611 gdb_assert (length
> 0);
613 /* We should not have seen a memory error in this case. */
614 gdb_assert (!disassembler
.memory_error_address ().has_value ());
616 /* Create a DisassemblerResult containing the results. */
617 PyTypeObject
*type
= &disasm_result_object_type
;
618 gdbpy_ref
<disasm_result_object
> res
619 ((disasm_result_object
*) type
->tp_alloc (type
, 0));
620 auto content
= disassembler
.release ();
621 disasmpy_init_disassembler_result (res
.get (), length
, std::move (content
));
622 return reinterpret_cast<PyObject
*> (res
.release ());
625 /* Implement gdb._set_enabled function. Takes a boolean parameter, and
626 sets whether GDB should enter the Python disassembler code or not.
628 This is called from within the Python code when a new disassembler is
629 registered. When no disassemblers are registered the global C++ flag
630 is set to false, and GDB never even enters the Python environment to
631 check for a disassembler.
633 When the user registers a new Python disassembler, the global C++ flag
634 is set to true, and now GDB will enter the Python environment to check
635 if there's a disassembler registered for the current architecture. */
638 disasmpy_set_enabled (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
641 static const char *keywords
[] = { "state", nullptr };
642 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "O", keywords
,
646 if (!PyBool_Check (newstate
))
648 PyErr_SetString (PyExc_TypeError
,
649 _("The value passed to `_set_enabled' must be a boolean."));
653 python_print_insn_enabled
= PyObject_IsTrue (newstate
);
657 /* Implement DisassembleInfo.read_memory(LENGTH, OFFSET). Read LENGTH
658 bytes at OFFSET from the start of the instruction currently being
659 disassembled, and return a memory buffer containing the bytes.
661 OFFSET defaults to zero if it is not provided. LENGTH is required. If
662 the read fails then this will raise a gdb.MemoryError exception. */
665 disasmpy_info_read_memory (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
667 disasm_info_object
*obj
= (disasm_info_object
*) self
;
668 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
670 gdb_py_longest length
, offset
= 0;
671 gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
;
672 static const char *keywords
[] = { "length", "offset", nullptr };
674 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
,
675 GDB_PY_LL_ARG
"|" GDB_PY_LL_ARG
,
676 keywords
, &length
, &offset
))
679 /* The apparent address from which we are reading memory. Note that in
680 some cases GDB actually disassembles instructions from a buffer, so
681 we might not actually be reading this information directly from the
682 inferior memory. This is all hidden behind the read_memory_func API
683 within the disassemble_info structure. */
684 CORE_ADDR address
= obj
->address
+ offset
;
686 /* Setup a buffer to hold the result. */
687 buffer
.reset ((gdb_byte
*) xmalloc (length
));
689 /* Read content into BUFFER. If the read fails then raise a memory
690 error, otherwise, convert BUFFER to a Python memory buffer, and return
692 disassemble_info
*info
= obj
->gdb_info
;
693 if (info
->read_memory_func ((bfd_vma
) address
, buffer
.get (),
694 (unsigned int) length
, info
) != 0)
696 disasmpy_set_memory_error_for_address (address
);
699 return gdbpy_buffer_to_membuf (std::move (buffer
), address
, length
);
702 /* Implement DisassembleInfo.address attribute, return the address at which
703 GDB would like an instruction disassembled. */
706 disasmpy_info_address (PyObject
*self
, void *closure
)
708 disasm_info_object
*obj
= (disasm_info_object
*) self
;
709 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
710 return gdb_py_object_from_longest (obj
->address
).release ();
713 /* Implement DisassembleInfo.architecture attribute. Return the
714 gdb.Architecture in which we are disassembling. */
717 disasmpy_info_architecture (PyObject
*self
, void *closure
)
719 disasm_info_object
*obj
= (disasm_info_object
*) self
;
720 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
721 return gdbarch_to_arch_object (obj
->gdbarch
);
724 /* Implement DisassembleInfo.progspace attribute. Return the
725 gdb.Progspace in which we are disassembling. */
728 disasmpy_info_progspace (PyObject
*self
, void *closure
)
730 disasm_info_object
*obj
= (disasm_info_object
*) self
;
731 DISASMPY_DISASM_INFO_REQUIRE_VALID (obj
);
732 return pspace_to_pspace_object (obj
->program_space
).release ();
735 /* Helper function called when the libopcodes disassembler produces some
736 output. FORMAT and ARGS are used to create a string which GDB will
737 display using STYLE. The string is either added as a new
738 DisassemblerTextPart to the list of parts being built in the current
739 gdbpy_disassembler object (accessed through DIS_INFO). Or, if the last
740 part in the gdbpy_disassembler is a text part in the same STYLE, then
741 the new string is appended to the previous part.
743 The merging behaviour make the Python API a little more user friendly,
744 some disassemblers produce their output character at a time, there's no
745 particular reason for this, it's just how they are implemented. By
746 merging parts with the same style we make it easier for the user to
747 analyse the disassembler output. */
750 gdbpy_disassembler::vfprintf_styled_func (void *dis_info
,
751 enum disassembler_style style
,
753 va_list args
) noexcept
755 gdb_disassemble_info
*di
= (gdb_disassemble_info
*) dis_info
;
756 gdbpy_disassembler
*dis
757 = gdb::checked_static_cast
<gdbpy_disassembler
*> (di
);
759 if (!dis
->m_parts
.empty ()
760 && Py_TYPE (dis
->m_parts
.back ().get ()) == &disasm_text_part_object_type
761 && (((disasm_text_part_object
*) dis
->m_parts
.back ().get ())->style
765 = ((disasm_text_part_object
*) dis
->m_parts
.back ().get ())->string
;
766 string_vappendf (*string
, format
, args
);
770 std::string str
= string_vprintf (format
, args
);
773 gdbpy_ref
<> text_part
774 = make_disasm_text_part (std::move (str
), style
);
775 dis
->m_parts
.emplace_back (std::move (text_part
));
779 /* Something non -ve. */
783 /* Disassembler callback for architectures where libopcodes doesn't
784 created styled output. In these cases we format all the output using
785 the (default) text style. */
788 gdbpy_disassembler::fprintf_func (void *dis_info
,
789 const char *format
, ...) noexcept
792 va_start (args
, format
);
793 vfprintf_styled_func (dis_info
, dis_style_text
, format
, args
);
796 /* Something non -ve. */
800 /* Disassembler callback for architectures where libopcodes does create
801 styled output. Just creates a new text part with the given STYLE. */
804 gdbpy_disassembler::fprintf_styled_func (void *dis_info
,
805 enum disassembler_style style
,
806 const char *format
, ...) noexcept
809 va_start (args
, format
);
810 vfprintf_styled_func (dis_info
, style
, format
, args
);
813 /* Something non -ve. */
817 /* This implements the disassemble_info read_memory_func callback and is
818 called from the libopcodes disassembler when the disassembler wants to
821 From the INFO argument we can find the gdbpy_disassembler object for
822 which we are disassembling, and from that object we can find the
823 DisassembleInfo for the current disassembly call.
825 This function reads the instruction bytes by calling the read_memory
826 method on the DisassembleInfo object. This method might have been
827 overridden by user code.
829 Read LEN bytes from MEMADDR and place them into BUFF. Return 0 on
830 success (in which case BUFF has been filled), or -1 on error, in which
831 case the contents of BUFF are undefined. */
834 gdbpy_disassembler::read_memory_func (bfd_vma memaddr
, gdb_byte
*buff
,
836 struct disassemble_info
*info
) noexcept
838 gdbpy_disassembler
*dis
839 = static_cast<gdbpy_disassembler
*> (info
->application_data
);
840 disasm_info_object
*obj
= dis
->py_disasm_info ();
842 /* If a previous read attempt resulted in an exception, then we don't
843 allow any further reads to succeed. We only do this check for the
844 read_memory_func as this is the only one the user can hook into,
845 thus, this check prevents us calling back into user code if a
846 previous call has already thrown an error. */
847 if (dis
->has_stored_exception ())
850 /* The DisassembleInfo.read_memory method expects an offset from the
851 address stored within the DisassembleInfo object; calculate that
853 gdb_py_longest offset
854 = (gdb_py_longest
) memaddr
- (gdb_py_longest
) obj
->address
;
856 /* Now call the DisassembleInfo.read_memory method. This might have been
857 overridden by the user. */
858 gdbpy_ref
<> result_obj
= gdbpy_call_method ((PyObject
*) obj
, "read_memory",
861 /* Handle any exceptions. */
862 if (result_obj
== nullptr)
864 /* If we got a gdb.MemoryError then we ignore this and just report
865 that the read failed to the caller. The caller is then
866 responsible for calling the memory_error_func if it wants to.
867 Remember, the disassembler might just be probing to see if these
868 bytes can be read, if we automatically call the memory error
869 function, we can end up registering an error prematurely. */
870 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
876 /* For any other exception type we capture the value of the Python
877 exception and throw it, this will then be caught in
878 disasmpy_builtin_disassemble, at which point the exception will be
880 dis
->store_exception (gdbpy_err_fetch ());
884 /* Convert the result to a buffer. */
886 if (!PyObject_CheckBuffer (result_obj
.get ())
887 || PyObject_GetBuffer (result_obj
.get(), &py_buff
, PyBUF_CONTIG_RO
) < 0)
889 PyErr_Format (PyExc_TypeError
,
890 _("Result from read_memory is not a buffer"));
891 dis
->store_exception (gdbpy_err_fetch ());
895 /* Wrap PY_BUFF so that it is cleaned up correctly at the end of this
897 Py_buffer_up
buffer_up (&py_buff
);
899 /* Validate that the buffer is the correct length. */
900 if (py_buff
.len
!= len
)
902 PyErr_Format (PyExc_ValueError
,
903 _("Buffer returned from read_memory is sized %d instead of the expected %d"),
905 dis
->store_exception (gdbpy_err_fetch ());
909 /* Copy the data out of the Python buffer and return success. */
910 const gdb_byte
*buffer
= (const gdb_byte
*) py_buff
.buf
;
911 memcpy (buff
, buffer
, len
);
915 /* Implement __str__ for the DisassemblerResult type. */
918 disasmpy_result_str (PyObject
*self
)
920 disasm_result_object
*obj
= (disasm_result_object
*) self
;
922 /* These conditions are all enforced when the DisassemblerResult object
924 gdb_assert (obj
->parts
!= nullptr);
925 gdb_assert (obj
->parts
->size () > 0);
926 gdb_assert (obj
->length
> 0);
932 str
= disasmpy_parts_list_to_string (*obj
->parts
);
934 catch (const gdb_exception
&except
)
936 return gdbpy_handle_gdb_exception (nullptr, except
);
939 return PyUnicode_Decode (str
.c_str (), str
.size (),
940 host_charset (), nullptr);
943 /* Implement DisassemblerResult.length attribute, return the length of the
944 disassembled instruction. */
947 disasmpy_result_length (PyObject
*self
, void *closure
)
949 disasm_result_object
*obj
= (disasm_result_object
*) self
;
950 return gdb_py_object_from_longest (obj
->length
).release ();
953 /* Implement DisassemblerResult.string attribute, return the content string
954 of the disassembled instruction. */
957 disasmpy_result_string (PyObject
*self
, void *closure
)
959 return disasmpy_result_str (self
);
962 /* Implement DisassemblerResult.parts method. Returns a list of all the
963 parts that make up this result. There should always be at least one
964 part, so the returned list should never be empty. */
967 disasmpy_result_parts (PyObject
*self
, void *closure
)
969 disasm_result_object
*obj
= (disasm_result_object
*) self
;
971 /* These conditions are all enforced when the DisassemblerResult object
973 gdb_assert (obj
->parts
!= nullptr);
974 gdb_assert (obj
->parts
->size () > 0);
975 gdb_assert (obj
->length
> 0);
977 gdbpy_ref
<> result_list (PyList_New (obj
->parts
->size ()));
978 if (result_list
== nullptr)
981 for (auto p
: *obj
->parts
)
983 gdbpy_ref
<> item
= gdbpy_ref
<>::new_reference (p
.get ());
984 PyList_SET_ITEM (result_list
.get (), idx
, item
.release ());
988 /* This should follow naturally from the obj->parts list being
990 gdb_assert (PyList_Size (result_list
.get()) > 0);
992 return result_list
.release ();
995 /* Implement DisassemblerResult.__init__. Takes two arguments, an
996 integer, the length in bytes of the disassembled instruction, and a
997 string, the disassembled content of the instruction. */
1000 disasmpy_result_init (PyObject
*self
, PyObject
*args
, PyObject
*kwargs
)
1002 static const char *keywords
[] = { "length", "string", "parts", NULL
};
1004 const char *string
= nullptr;
1005 PyObject
*parts_list
= nullptr;
1006 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwargs
, "i|zO", keywords
,
1007 &length
, &string
, &parts_list
))
1012 PyErr_SetString (PyExc_ValueError
,
1013 _("Length must be greater than 0."));
1017 if (parts_list
== Py_None
)
1018 parts_list
= nullptr;
1020 if (string
!= nullptr && parts_list
!= nullptr)
1022 PyErr_Format (PyExc_ValueError
,
1023 _("Cannot use 'string' and 'parts' when creating %s."),
1024 Py_TYPE (self
)->tp_name
);
1028 if (string
!= nullptr)
1030 if (strlen (string
) == 0)
1032 PyErr_SetString (PyExc_ValueError
,
1033 _("String must not be empty."));
1037 disasm_result_object
*obj
= (disasm_result_object
*) self
;
1038 std::vector
<gdbpy_ref
<>> content
;
1039 gdbpy_ref
<> text_part
1040 = make_disasm_text_part (std::string (string
), dis_style_text
);
1041 content
.emplace_back (text_part
.release ());
1042 disasmpy_init_disassembler_result (obj
, length
, std::move (content
));
1046 if (!PySequence_Check (parts_list
))
1048 PyErr_SetString (PyExc_TypeError
,
1049 _("'parts' argument is not a sequence"));
1053 Py_ssize_t parts_count
= PySequence_Size (parts_list
);
1054 if (parts_count
<= 0)
1056 PyErr_SetString (PyExc_ValueError
,
1057 _("'parts' list must not be empty."));
1061 disasm_result_object
*obj
= (disasm_result_object
*) self
;
1062 std::vector
<gdbpy_ref
<>> content (parts_count
);
1064 struct gdbarch
*gdbarch
= nullptr;
1065 for (Py_ssize_t i
= 0; i
< parts_count
; ++i
)
1067 gdbpy_ref
<> part (PySequence_GetItem (parts_list
, i
));
1069 if (part
== nullptr)
1072 if (Py_TYPE (part
.get ()) == &disasm_addr_part_object_type
)
1074 disasm_addr_part_object
*addr_part
1075 = (disasm_addr_part_object
*) part
.get ();
1076 gdb_assert (addr_part
->gdbarch
!= nullptr);
1077 if (gdbarch
== nullptr)
1078 gdbarch
= addr_part
->gdbarch
;
1079 else if (addr_part
->gdbarch
!= gdbarch
)
1081 PyErr_SetString (PyExc_ValueError
,
1082 _("Inconsistent gdb.Architectures used "
1083 "in 'parts' sequence."));
1088 content
[i
] = std::move (part
);
1091 disasmpy_init_disassembler_result (obj
, length
, std::move (content
));
1098 /* Implement __repr__ for the DisassemblerResult type. */
1101 disasmpy_result_repr (PyObject
*self
)
1103 disasm_result_object
*obj
= (disasm_result_object
*) self
;
1105 gdb_assert (obj
->parts
!= nullptr);
1107 return PyUnicode_FromFormat ("<%s length=%d string=\"%U\">",
1108 Py_TYPE (obj
)->tp_name
,
1110 disasmpy_result_str (self
));
1113 /* Implement memory_error_func callback for disassemble_info. Extract the
1114 underlying DisassembleInfo Python object, and set a memory error on
1118 gdbpy_disassembler::memory_error_func (int status
, bfd_vma memaddr
,
1119 struct disassemble_info
*info
) noexcept
1121 gdbpy_disassembler
*dis
1122 = static_cast<gdbpy_disassembler
*> (info
->application_data
);
1123 dis
->m_memory_error_address
.emplace (memaddr
);
1126 /* Wrapper of print_address. */
1129 gdbpy_disassembler::print_address_func (bfd_vma addr
,
1130 struct disassemble_info
*info
) noexcept
1132 gdbpy_disassembler
*dis
1133 = static_cast<gdbpy_disassembler
*> (info
->application_data
);
1135 gdbpy_ref
<> addr_part
1136 = make_disasm_addr_part (dis
->arch (), addr
);
1137 dis
->m_parts
.emplace_back (std::move (addr_part
));
1142 gdbpy_disassembler::gdbpy_disassembler (disasm_info_object
*obj
,
1143 PyObject
*memory_source
)
1144 : gdb_disassemble_info (obj
->gdbarch
,
1149 fprintf_styled_func
),
1150 m_disasm_info_object (obj
),
1151 m_memory_source (memory_source
)
1154 /* A wrapper around a reference to a Python DisassembleInfo object, which
1155 ensures that the object is marked as invalid when we leave the enclosing
1158 Each DisassembleInfo is created in gdbpy_print_insn, and is done with by
1159 the time that function returns. However, there's nothing to stop a user
1160 caching a reference to the DisassembleInfo, and thus keeping the object
1163 We therefore have the notion of a DisassembleInfo becoming invalid, this
1164 happens when gdbpy_print_insn returns. This class is responsible for
1165 marking the DisassembleInfo as invalid in its destructor. */
1167 struct scoped_disasm_info_object
1170 scoped_disasm_info_object (struct gdbarch
*gdbarch
, CORE_ADDR memaddr
,
1171 disassemble_info
*info
)
1172 : m_disasm_info (allocate_disasm_info_object ())
1174 disasm_info_fill (m_disasm_info
.get (), gdbarch
, current_program_space
,
1175 memaddr
, info
, nullptr);
1178 /* Upon destruction mark m_disasm_info as invalid. */
1179 ~scoped_disasm_info_object ()
1181 /* Invalidate the original DisassembleInfo object as well as any copies
1182 that the user might have made. */
1183 for (disasm_info_object
*obj
= m_disasm_info
.get ();
1186 obj
->gdb_info
= nullptr;
1189 /* Return a pointer to the underlying disasm_info_object instance. */
1190 disasm_info_object
*
1193 return m_disasm_info
.get ();
1198 /* Wrapper around the call to PyObject_New, this wrapper function can be
1199 called from the constructor initialization list, while PyObject_New, a
1201 static disasm_info_object
*
1202 allocate_disasm_info_object ()
1204 return (disasm_info_object
*) PyObject_New (disasm_info_object
,
1205 &disasm_info_object_type
);
1208 /* A reference to a gdb.disassembler.DisassembleInfo object. When this
1209 containing instance goes out of scope this reference is released,
1210 however, the user might be holding other references to the
1211 DisassembleInfo object in Python code, so the underlying object might
1213 gdbpy_ref
<disasm_info_object
> m_disasm_info
;
1216 /* See python-internal.h. */
1219 gdbpy_print_insn (struct gdbarch
*gdbarch
, CORE_ADDR memaddr
,
1220 disassemble_info
*info
)
1222 /* Early exit case. This must be done as early as possible, and
1223 definitely before we enter Python environment. The
1224 python_print_insn_enabled flag is set (from Python) only when the user
1225 has installed one (or more) Python disassemblers. So in the common
1226 case (no custom disassembler installed) this flag will be false,
1227 allowing for a quick return. */
1228 if (!gdb_python_initialized
|| !python_print_insn_enabled
)
1231 gdbpy_enter
enter_py (get_current_arch (), current_language
);
1233 /* Import the gdb.disassembler module. */
1234 gdbpy_ref
<> gdb_python_disassembler_module
1235 (PyImport_ImportModule ("gdb.disassembler"));
1236 if (gdb_python_disassembler_module
== nullptr)
1238 gdbpy_print_stack ();
1242 /* Get the _print_insn attribute from the module, this should be the
1243 function we are going to call to actually perform the disassembly. */
1245 (PyObject_GetAttrString (gdb_python_disassembler_module
.get (),
1247 if (hook
== nullptr)
1249 gdbpy_print_stack ();
1253 /* Create the new DisassembleInfo object we will pass into Python. This
1254 object will be marked as invalid when we leave this scope. */
1255 scoped_disasm_info_object
scoped_disasm_info (gdbarch
, memaddr
, info
);
1256 disasm_info_object
*disasm_info
= scoped_disasm_info
.get ();
1258 /* Call into the registered disassembler to (possibly) perform the
1260 PyObject
*insn_disas_obj
= (PyObject
*) disasm_info
;
1261 gdbpy_ref
<> result (PyObject_CallFunctionObjArgs (hook
.get (),
1265 if (result
== nullptr)
1267 /* The call into Python code resulted in an exception. If this was a
1268 gdb.MemoryError, then we can figure out an address and call the
1269 disassemble_info::memory_error_func to report the error back to
1270 core GDB. Any other exception type we report back to core GDB as
1271 an unknown error (return -1 without first calling the
1272 memory_error_func callback). */
1274 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
1276 /* A gdb.MemoryError might have an address attribute which
1277 contains the address at which the memory error occurred. If
1278 this is the case then use this address, otherwise, fallback to
1279 just using the address of the instruction we were asked to
1281 gdbpy_err_fetch err
;
1285 if (err
.value () != nullptr
1286 && PyObject_HasAttrString (err
.value ().get (), "address"))
1289 = PyObject_GetAttrString (err
.value ().get (), "address");
1290 if (get_addr_from_python (addr_obj
, &addr
) < 0)
1291 addr
= disasm_info
->address
;
1294 addr
= disasm_info
->address
;
1296 info
->memory_error_func (-1, addr
, info
);
1297 return std::optional
<int> (-1);
1299 else if (PyErr_ExceptionMatches (gdbpy_gdberror_exc
))
1301 gdbpy_err_fetch err
;
1302 gdb::unique_xmalloc_ptr
<char> msg
= err
.to_string ();
1304 info
->fprintf_func (info
->stream
, "%s", msg
.get ());
1305 return std::optional
<int> (-1);
1309 gdbpy_print_stack_or_quit ();
1310 return std::optional
<int> (-1);
1314 else if (result
== Py_None
)
1316 /* A return value of None indicates that the Python code could not,
1317 or doesn't want to, disassemble this instruction. Just return an
1318 empty result and core GDB will try to disassemble this for us. */
1322 /* Check the result is a DisassemblerResult (or a sub-class). */
1323 if (!PyObject_IsInstance (result
.get (),
1324 (PyObject
*) &disasm_result_object_type
))
1326 PyErr_SetString (PyExc_TypeError
,
1327 _("Result is not a DisassemblerResult."));
1328 gdbpy_print_stack ();
1329 return std::optional
<int> (-1);
1332 /* The result from the Python disassembler has the correct type. Convert
1333 this back to the underlying C++ object and read the state directly
1334 from this object. */
1335 struct disasm_result_object
*result_obj
1336 = (struct disasm_result_object
*) result
.get ();
1338 /* Validate the length of the disassembled instruction. */
1339 long length
= result_obj
->length
;
1340 long max_insn_length
= (gdbarch_max_insn_length_p (gdbarch
) ?
1341 gdbarch_max_insn_length (gdbarch
) : INT_MAX
);
1346 _("Invalid length attribute: length must be greater than 0."));
1347 gdbpy_print_stack ();
1348 return std::optional
<int> (-1);
1350 if (length
> max_insn_length
)
1354 _("Invalid length attribute: length %d greater than architecture maximum of %d"),
1355 length
, max_insn_length
);
1356 gdbpy_print_stack ();
1357 return std::optional
<int> (-1);
1360 /* It is impossible to create a DisassemblerResult object with an empty
1361 parts list. We know that each part results in a non-empty string, so
1362 we know that the instruction disassembly will not be the empty
1364 gdb_assert (result_obj
->parts
->size () > 0);
1366 /* Now print out the parts that make up this instruction. */
1367 for (auto &p
: *result_obj
->parts
)
1369 if (Py_TYPE (p
.get ()) == &disasm_text_part_object_type
)
1371 disasm_text_part_object
*text_part
1372 = (disasm_text_part_object
*) p
.get ();
1373 gdb_assert (text_part
->string
!= nullptr);
1374 info
->fprintf_styled_func (info
->stream
, text_part
->style
,
1375 "%s", text_part
->string
->c_str ());
1379 gdb_assert (Py_TYPE (p
.get ()) == &disasm_addr_part_object_type
);
1380 disasm_addr_part_object
*addr_part
1381 = (disasm_addr_part_object
*) p
.get ();
1382 /* A DisassemblerAddressPart can only be created by calling a
1383 method on DisassembleInfo, and the gdbarch is copied from the
1384 DisassembleInfo into the DisassemblerAddressPart. As the
1385 DisassembleInfo has its gdbarch initialised from GDBARCH in
1386 this scope, and this architecture can't be changed, then the
1387 following assert should hold. */
1388 gdb_assert (addr_part
->gdbarch
== gdbarch
);
1389 info
->print_address_func (addr_part
->address
, info
);
1393 return std::optional
<int> (length
);
1396 /* The tp_dealloc callback for the DisassemblerResult type. Takes care of
1397 deallocating the content buffer. */
1400 disasmpy_dealloc_result (PyObject
*self
)
1402 disasm_result_object
*obj
= (disasm_result_object
*) self
;
1404 Py_TYPE (self
)->tp_free (self
);
1407 /* The tp_init callback for the DisassemblerPart type. This just raises an
1408 exception, which prevents the user from creating objects of this type.
1409 Instead the user should create instances of a sub-class. */
1412 disasmpy_part_init (PyObject
*self
, PyObject
*args
, PyObject
*kwargs
)
1414 PyErr_SetString (PyExc_RuntimeError
,
1415 _("Cannot create instances of DisassemblerPart."));
1419 /* Return a string representing STYLE. The returned string is used as a
1420 constant defined in the gdb.disassembler module. */
1423 get_style_name (enum disassembler_style style
)
1427 case dis_style_text
: return "STYLE_TEXT";
1428 case dis_style_mnemonic
: return "STYLE_MNEMONIC";
1429 case dis_style_sub_mnemonic
: return "STYLE_SUB_MNEMONIC";
1430 case dis_style_assembler_directive
: return "STYLE_ASSEMBLER_DIRECTIVE";
1431 case dis_style_register
: return "STYLE_REGISTER";
1432 case dis_style_immediate
: return "STYLE_IMMEDIATE";
1433 case dis_style_address
: return "STYLE_ADDRESS";
1434 case dis_style_address_offset
: return "STYLE_ADDRESS_OFFSET";
1435 case dis_style_symbol
: return "STYLE_SYMBOL";
1436 case dis_style_comment_start
: return "STYLE_COMMENT_START";
1439 gdb_assert_not_reached ("unknown disassembler style");
1442 /* Implement DisassemblerTextPart.__repr__ method. */
1445 disasmpy_text_part_repr (PyObject
*self
)
1447 disasm_text_part_object
*obj
= (disasm_text_part_object
*) self
;
1449 gdb_assert (obj
->string
!= nullptr);
1451 return PyUnicode_FromFormat ("<%s string='%s', style='%s'>",
1452 Py_TYPE (obj
)->tp_name
,
1453 obj
->string
->c_str (),
1454 get_style_name (obj
->style
));
1457 /* Implement DisassemblerTextPart.__str__ attribute. */
1460 disasmpy_text_part_str (PyObject
*self
)
1462 disasm_text_part_object
*obj
= (disasm_text_part_object
*) self
;
1464 return PyUnicode_Decode (obj
->string
->c_str (), obj
->string
->size (),
1465 host_charset (), nullptr);
1468 /* Implement DisassemblerTextPart.string attribute. */
1471 disasmpy_text_part_string (PyObject
*self
, void *closure
)
1473 return disasmpy_text_part_str (self
);
1476 /* Implement DisassemblerTextPart.style attribute. */
1479 disasmpy_text_part_style (PyObject
*self
, void *closure
)
1481 disasm_text_part_object
*obj
= (disasm_text_part_object
*) self
;
1483 LONGEST style_val
= (LONGEST
) obj
->style
;
1484 return gdb_py_object_from_longest (style_val
).release ();
1487 /* Implement DisassemblerAddressPart.__repr__ method. */
1490 disasmpy_addr_part_repr (PyObject
*self
)
1492 disasm_addr_part_object
*obj
= (disasm_addr_part_object
*) self
;
1494 return PyUnicode_FromFormat ("<%s address='%s'>",
1495 Py_TYPE (obj
)->tp_name
,
1496 core_addr_to_string_nz (obj
->address
));
1499 /* Implement DisassemblerAddressPart.__str__ attribute. */
1502 disasmpy_addr_part_str (PyObject
*self
)
1504 disasm_addr_part_object
*obj
= (disasm_addr_part_object
*) self
;
1510 print_address (obj
->gdbarch
, obj
->address
, &buf
);
1511 str
= buf
.release ();
1513 catch (const gdb_exception
&except
)
1515 return gdbpy_handle_gdb_exception (nullptr, except
);
1518 return PyUnicode_Decode (str
.c_str (), str
.size (),
1519 host_charset (), nullptr);
1522 /* Implement DisassemblerAddressPart.string attribute. */
1525 disasmpy_addr_part_string (PyObject
*self
, void *closure
)
1527 return disasmpy_addr_part_str (self
);
1530 /* Implement DisassemblerAddressPart.address attribute. */
1533 disasmpy_addr_part_address (PyObject
*self
, void *closure
)
1535 disasm_addr_part_object
*obj
= (disasm_addr_part_object
*) self
;
1537 return gdb_py_object_from_longest (obj
->address
).release ();
1540 /* The get/set attributes of the gdb.disassembler.DisassembleInfo type. */
1542 static gdb_PyGetSetDef disasm_info_object_getset
[] = {
1543 { "address", disasmpy_info_address
, nullptr,
1544 "Start address of the instruction to disassemble.", nullptr },
1545 { "architecture", disasmpy_info_architecture
, nullptr,
1546 "Architecture to disassemble in", nullptr },
1547 { "progspace", disasmpy_info_progspace
, nullptr,
1548 "Program space to disassemble in", nullptr },
1549 { nullptr } /* Sentinel */
1552 /* The methods of the gdb.disassembler.DisassembleInfo type. */
1554 static PyMethodDef disasm_info_object_methods
[] = {
1555 { "read_memory", (PyCFunction
) disasmpy_info_read_memory
,
1556 METH_VARARGS
| METH_KEYWORDS
,
1557 "read_memory (LEN, OFFSET = 0) -> Octets[]\n\
1558 Read LEN octets for the instruction to disassemble." },
1559 { "is_valid", disasmpy_info_is_valid
, METH_NOARGS
,
1560 "is_valid () -> Boolean.\n\
1561 Return true if this DisassembleInfo is valid, false if not." },
1562 { "text_part", (PyCFunction
) disasmpy_info_make_text_part
,
1563 METH_VARARGS
| METH_KEYWORDS
,
1564 "text_part (STRING, STYLE) -> DisassemblerTextPart\n\
1565 Create a new text part, with contents STRING styled with STYLE." },
1566 { "address_part", (PyCFunction
) disasmpy_info_make_address_part
,
1567 METH_VARARGS
| METH_KEYWORDS
,
1568 "address_part (ADDRESS) -> DisassemblerAddressPart\n\
1569 Create a new address part representing ADDRESS." },
1570 {nullptr} /* Sentinel */
1573 /* The get/set attributes of the gdb.disassembler.DisassemblerResult type. */
1575 static gdb_PyGetSetDef disasm_result_object_getset
[] = {
1576 { "length", disasmpy_result_length
, nullptr,
1577 "Length of the disassembled instruction.", nullptr },
1578 { "string", disasmpy_result_string
, nullptr,
1579 "String representing the disassembled instruction.", nullptr },
1580 { "parts", disasmpy_result_parts
, nullptr,
1581 "List of all the separate disassembly parts", nullptr },
1582 { nullptr } /* Sentinel */
1585 /* The get/set attributes of the gdb.disassembler.DisassemblerTextPart type. */
1587 static gdb_PyGetSetDef disasmpy_text_part_getset
[] = {
1588 { "string", disasmpy_text_part_string
, nullptr,
1589 "String representing a text part.", nullptr },
1590 { "style", disasmpy_text_part_style
, nullptr,
1591 "The style of this text part.", nullptr },
1592 { nullptr } /* Sentinel */
1595 /* The get/set attributes of the gdb.disassembler.DisassemblerAddressPart type. */
1597 static gdb_PyGetSetDef disasmpy_addr_part_getset
[] = {
1598 { "string", disasmpy_addr_part_string
, nullptr,
1599 "String representing an address part.", nullptr },
1600 { "address", disasmpy_addr_part_address
, nullptr,
1601 "The address of this address part.", nullptr },
1602 { nullptr } /* Sentinel */
1605 /* These are the methods we add into the _gdb.disassembler module, which
1606 are then imported into the gdb.disassembler module. These are global
1607 functions that support performing disassembly. */
1609 PyMethodDef python_disassembler_methods
[] =
1611 { "builtin_disassemble", (PyCFunction
) disasmpy_builtin_disassemble
,
1612 METH_VARARGS
| METH_KEYWORDS
,
1613 "builtin_disassemble (INFO, MEMORY_SOURCE = None) -> None\n\
1614 Disassemble using GDB's builtin disassembler. INFO is an instance of\n\
1615 gdb.disassembler.DisassembleInfo. The MEMORY_SOURCE, if not None, should\n\
1616 be an object with the read_memory method." },
1617 { "_set_enabled", (PyCFunction
) disasmpy_set_enabled
,
1618 METH_VARARGS
| METH_KEYWORDS
,
1619 "_set_enabled (STATE) -> None\n\
1620 Set whether GDB should call into the Python _print_insn code or not." },
1621 {nullptr, nullptr, 0, nullptr}
1624 /* Structure to define the _gdb.disassembler module. */
1626 static struct PyModuleDef python_disassembler_module_def
=
1628 PyModuleDef_HEAD_INIT
,
1629 "_gdb.disassembler",
1632 python_disassembler_methods
,
1639 /* Called to initialize the Python structures in this file. */
1641 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
1642 gdbpy_initialize_disasm ()
1644 /* Create the _gdb.disassembler module, and add it to the _gdb module. */
1646 PyObject
*gdb_disassembler_module
;
1647 gdb_disassembler_module
= PyModule_Create (&python_disassembler_module_def
);
1648 if (gdb_disassembler_module
== nullptr)
1650 if (gdb_pymodule_addobject (gdb_module
, "disassembler",
1651 gdb_disassembler_module
) < 0)
1654 /* This is needed so that 'import _gdb.disassembler' will work. */
1655 PyObject
*dict
= PyImport_GetModuleDict ();
1656 if (PyDict_SetItemString (dict
, "_gdb.disassembler",
1657 gdb_disassembler_module
) < 0)
1660 for (int i
= 0; i
<= (int) dis_style_comment_start
; ++i
)
1662 const char *style_name
= get_style_name ((enum disassembler_style
) i
);
1663 if (PyModule_AddIntConstant (gdb_disassembler_module
, style_name
, i
) < 0)
1667 disasm_info_object_type
.tp_new
= PyType_GenericNew
;
1668 if (gdbpy_type_ready (&disasm_info_object_type
, gdb_disassembler_module
) < 0)
1671 disasm_result_object_type
.tp_new
= PyType_GenericNew
;
1672 if (gdbpy_type_ready (&disasm_result_object_type
, gdb_disassembler_module
) < 0)
1675 disasm_part_object_type
.tp_new
= PyType_GenericNew
;
1676 if (gdbpy_type_ready (&disasm_part_object_type
, gdb_disassembler_module
) < 0)
1679 disasm_addr_part_object_type
.tp_new
= PyType_GenericNew
;
1680 if (gdbpy_type_ready (&disasm_addr_part_object_type
, gdb_disassembler_module
) < 0)
1683 disasm_text_part_object_type
.tp_new
= PyType_GenericNew
;
1684 if (gdbpy_type_ready (&disasm_text_part_object_type
, gdb_disassembler_module
) < 0)
1690 GDBPY_INITIALIZE_FILE (gdbpy_initialize_disasm
);
1694 /* Describe the gdb.disassembler.DisassembleInfo type. */
1696 PyTypeObject disasm_info_object_type
= {
1697 PyVarObject_HEAD_INIT (nullptr, 0)
1698 "gdb.disassembler.DisassembleInfo", /*tp_name*/
1699 sizeof (disasm_info_object
), /*tp_basicsize*/
1701 disasm_info_dealloc
, /*tp_dealloc*/
1706 disasmpy_info_repr
, /*tp_repr*/
1708 0, /*tp_as_sequence*/
1709 0, /*tp_as_mapping*/
1716 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
1717 "GDB instruction disassembler object", /* tp_doc */
1718 0, /* tp_traverse */
1720 0, /* tp_richcompare */
1721 0, /* tp_weaklistoffset */
1723 0, /* tp_iternext */
1724 disasm_info_object_methods
, /* tp_methods */
1726 disasm_info_object_getset
, /* tp_getset */
1729 0, /* tp_descr_get */
1730 0, /* tp_descr_set */
1731 0, /* tp_dictoffset */
1732 disasm_info_init
, /* tp_init */
1736 /* Describe the gdb.disassembler.DisassemblerResult type. */
1738 PyTypeObject disasm_result_object_type
= {
1739 PyVarObject_HEAD_INIT (nullptr, 0)
1740 "gdb.disassembler.DisassemblerResult", /*tp_name*/
1741 sizeof (disasm_result_object
), /*tp_basicsize*/
1743 disasmpy_dealloc_result
, /*tp_dealloc*/
1748 disasmpy_result_repr
, /*tp_repr*/
1750 0, /*tp_as_sequence*/
1751 0, /*tp_as_mapping*/
1754 disasmpy_result_str
, /*tp_str*/
1758 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1759 "GDB object, representing a disassembler result", /* tp_doc */
1760 0, /* tp_traverse */
1762 0, /* tp_richcompare */
1763 0, /* tp_weaklistoffset */
1765 0, /* tp_iternext */
1768 disasm_result_object_getset
, /* tp_getset */
1771 0, /* tp_descr_get */
1772 0, /* tp_descr_set */
1773 0, /* tp_dictoffset */
1774 disasmpy_result_init
, /* tp_init */
1778 /* Describe the gdb.disassembler.DisassemblerPart type. This type exists
1779 only as an abstract base-class for the various part sub-types. The
1780 init method for this type throws an error. As such we don't both to
1781 provide a tp_repr method for this parent class. */
1783 PyTypeObject disasm_part_object_type
= {
1784 PyVarObject_HEAD_INIT (nullptr, 0)
1785 "gdb.disassembler.DisassemblerPart", /*tp_name*/
1786 sizeof (PyObject
), /*tp_basicsize*/
1795 0, /*tp_as_sequence*/
1796 0, /*tp_as_mapping*/
1803 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1804 "GDB object, representing part of a disassembled instruction", /* tp_doc */
1805 0, /* tp_traverse */
1807 0, /* tp_richcompare */
1808 0, /* tp_weaklistoffset */
1810 0, /* tp_iternext */
1816 0, /* tp_descr_get */
1817 0, /* tp_descr_set */
1818 0, /* tp_dictoffset */
1819 disasmpy_part_init
, /* tp_init */
1823 /* Describe the gdb.disassembler.DisassemblerTextPart type. */
1825 PyTypeObject disasm_text_part_object_type
= {
1826 PyVarObject_HEAD_INIT (nullptr, 0)
1827 "gdb.disassembler.DisassemblerTextPart", /*tp_name*/
1828 sizeof (disasm_text_part_object_type
), /*tp_basicsize*/
1835 disasmpy_text_part_repr
, /*tp_repr*/
1837 0, /*tp_as_sequence*/
1838 0, /*tp_as_mapping*/
1841 disasmpy_text_part_str
, /*tp_str*/
1845 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1846 "GDB object, representing a text part of an instruction", /* tp_doc */
1847 0, /* tp_traverse */
1849 0, /* tp_richcompare */
1850 0, /* tp_weaklistoffset */
1852 0, /* tp_iternext */
1855 disasmpy_text_part_getset
, /* tp_getset */
1856 &disasm_part_object_type
, /* tp_base */
1858 0, /* tp_descr_get */
1859 0, /* tp_descr_set */
1860 0, /* tp_dictoffset */
1865 /* Describe the gdb.disassembler.DisassemblerAddressPart type. */
1867 PyTypeObject disasm_addr_part_object_type
= {
1868 PyVarObject_HEAD_INIT (nullptr, 0)
1869 "gdb.disassembler.DisassemblerAddressPart", /*tp_name*/
1870 sizeof (disasm_addr_part_object
), /*tp_basicsize*/
1877 disasmpy_addr_part_repr
, /*tp_repr*/
1879 0, /*tp_as_sequence*/
1880 0, /*tp_as_mapping*/
1883 disasmpy_addr_part_str
, /*tp_str*/
1887 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1888 "GDB object, representing an address part of an instruction", /* tp_doc */
1889 0, /* tp_traverse */
1891 0, /* tp_richcompare */
1892 0, /* tp_weaklistoffset */
1894 0, /* tp_iternext */
1897 disasmpy_addr_part_getset
, /* tp_getset */
1898 &disasm_part_object_type
, /* tp_base */
1900 0, /* tp_descr_get */
1901 0, /* tp_descr_set */
1902 0, /* tp_dictoffset */