Advanced Issues: Creating custom LLDB object summaries
Update: It’s recommended to read this post before diving in.
Today we’re going to talk about an advanced XCode debugging feature that might improve your bug-extermination practices and efficiency. It’s well known that XCode has great debugging features, some of which were even discussed here in a previous post. These features are sometimes very straightforward and easy to use, but some of them require a bit of digging.
This is the digging kind.
What I’m going to show you is how to create a python script that will “teach” XCode and the LLDB about your object structures – this way, you will be able to immediately get a custom summary of the object you’re reviewing in the debugger and see what’s important to you while debugging.
For the sake of this tutorial, We’ll use a wonderful and widely-popular class called “Beer”. Let’s say that a “Beer” has a name, a price and a rating:
The problem is that when we use the XCode debugger to inspect a beer object instance, we will automatically be able to see only the pointer address of the instance. This is unlike an NSArray object or an NSString object for instance – in these cases we’ll see the amount of objects in the array or the string itself, respectively. So who the hell cares about the beer’s pointer?? Let’s make this right.
So, let’s get started with the Python script that will eventually enable us to see a better summary:
Step 1: Create the Python script.
Create a new “CustomSummaries.py” file and base it on the following code:
Here’s what you need to know:
Line 1 – imports the lldb library. Must be in your script in order to work.
Lines 7-8 – This function gets called by default and attaches your custom object summary function to the “Beer” object. Make sure you don’t misspell anything here and that you include all the flags as written above. Replace any “Beer” instance with your own class name.
Line 3-5: This is the definition of the object summary – we extract only the beer’s name and return a string that includes a “name: ” prefix followed by the beer name itself. Note that on line 4 we extract the _name property as defined in the “Beer” class.
You can now see the beer name, inline like it were a string object. There’s no need to open the object hierarchy to inspect the beer, it’s right there in front of you.
Step 2: Automate the import
In order for XCode to recognise and run your new script, you’ll have to create a new file in your home folder called “.lldbinit” so that the full path to this file is: ~/.lldbinit
Within this file, add the following line:
command script import PATH_TO_PY_FILE
Make sure you supply the correct, full path to CustomSummaries.py and that’s it, XCode will now include this custom summary every time you run it. If XCode is already running, be sure to restart it in order to see the changes taking place. Enjoy!