3

I find myself jumping into the python interpreter a lot to do very basic byte conversions, such as the following:

>>> ords = lambda s: [hex(ord(c)) for c in s]
>>> ords('Help')
['0x48', '0x65', '0x6c', '0x70']

Is there a way to add a python function into gdb so I can type ords('Help') and it will invoke the above? If so, how/where would I define the python function?


Related to: https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html

1
  • Please merge your questions together and begin at the beginning. Show an example of a situation that comes up in your code where you expect this to be helpful, show what you would like to be able to do in the debugger session, and explain why you expect that it would help you find the bug. Commented Sep 20, 2020 at 1:12

1 Answer 1

4

Yes, you can do this with the GDB Python API.

ords.py:

import gdb
class ordinal(gdb.Command):
    def __init__(self):
        super(ordinal, self).__init__("ords", gdb.COMMAND_USER)

    def invoke(self, argument, fromtty):
        argv = gdb.string_to_argv(argument)
        if len(argv) > 0:
            argv[0] = argv[0].strip('()')
            print([hex(ord(c)) for c in argv[0]])
        else:
            print("No arguments supplied")

ordinal()

In GDB (I'm using GDB 8.3.1):

(gdb) source ords.py
(gdb) ords('Help')
['0x48', '0x65', '0x6c', '0x70'] 
Sign up to request clarification or add additional context in comments.

3 Comments

awesome, thanks so much for the help. Do you know if there's a way to automatically import this in ~/.gdbinit ?
actually it worked perfectly putting it directly into the .gdbinit within the python ... end section. One question out of curiosity. Why do you need to do ordinal() at the end for this to work?
"The last line instantiates the class, and is necessary to trigger the registration of the command with GDB." sourceware.org/gdb/onlinedocs/gdb/Commands-In-Python.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.