Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override readonly variable lldb swift

Tags:

swift

lldb

Is there a way in lldb to overwrite a readonly variable.

For example if you had a struct

struct Object {
    let name: String
}

Doing the following in at a breakpoint in Xcode with lldb

(lldb) expression object.name = "Tom"

Will result in

error: <EXPR>:2:19: error: cannot assign to property: 'name' is a get-only property

I fully understand why this happens, just want to know if there is an easy way to get around this during debugging?

Please note this is in Swift & NOT Objective-C

like image 881
sbarow Avatar asked Sep 01 '16 00:09

sbarow


1 Answers

You can use the memory write {address} lldb command to overwrite the memory and change the string value. I managed to do it one address at a time, but it seems like memory write is capable of doing it one go.

(lldb) help memory write
     Write to the memory of the process being debugged.

Syntax: memory write <cmd-options> <address> <value> [<value> [...]]

Command Options Usage:
  memory write [-f <format>] [-s <byte-size>] <address> <value> [<value> [...]]
  memory write -i <filename> [-s <byte-size>] [-o <offset>] <address> <value> [<value> [...]]

       -f <format> ( --format <format> )
            Specify a format to be used for display.

       -i <filename> ( --infile <filename> )
            Write memory using the contents of a file.

       -o <offset> ( --offset <offset> )
            Start writing bytes from an offset within the input file.

       -s <byte-size> ( --size <byte-size> )
            The size in bytes to use when displaying with the selected format.

     This command takes options and free-form arguments.  If your arguments
     resemble option specifiers (i.e., they start with a - or --), you must use
     ' -- ' between the end of the command options and the beginning of the
     arguments.

Here's an example (hopefully someone with more understanding of the lldb and the internals of Swift can provide a better method):

Example using memory write

This shows overwriting the memory one byte at a time. po "Tom".dataUsingEncoding(NSUTF8StringEncoding)! gets the hex representation, which is used to step through and overwrite the memory of object.name. I'm sure there's an easier way to do it (in one command), but I couldn't figure out the correct parameter values to pull it off.

like image 52
Austin Avatar answered Oct 27 '22 23:10

Austin