The University of Queensland Homepage
School of ITEE ITEE Main Website

 Editing Binary Files
Most of the time, it's not appropriate to edit a binary file, but now and then (especially in my line of work), you really wish that you could, even if just to test an idea before actually implementing a better way to modify the binary file.

The VIM text editor is a very powerful editor, and is quite capable of performing simple edits on binary files. It's not pretty, so it's not for the faint hearted. Use the "-b" switch to edit the file, i.e.

vim -b mybinary
It will be a complete mess, with control characters all over the place. There are two fundamental things you need to do: search for a binary string, and replace a binary string with another. Let's suppose you want to change the address of __iob in your binary file, from 0006e4d0 to 00040fa8. We'll take a chance and assume that we won't find occurrences of this string that are actually other binary sequences overlapping to produce a "fake match". We use the standard search command (slash), but of course, we need to use control sequences to encode the binary. Vim works in decimal, so first, we break up the three non zero parts of each address into decimal:
06 is just 6
e4 is 228
d0 is 208
04 is just 4
0f is 015
a8 is 168
So to find 0006e4d0, I use this command (ignore the spaces, they are for readability only):
/ ^V 0 0 6 ^V 2 2 8 ^V 2 0 8
"^V" represents "control-V"; if you don't know about control characters, you should not be editing binary files. In vi and vim, ^V takes three decimal digits, and replaces them with one character with that encoding. After a while, you get to know that ^F is 6, and ^D is 4, so you can shorten the above to
/ ^F ^V 2 2 8 ^V 2 0 8
Note that I didn't bother looking for the zero at the start of the number, so I just visually confirm that there is a null (which displays as ^@) before the cursor.

The only safe command for changing a binary file is r (replace). So I use these commands to make the change I want (-> represents the right arrow)

r ^D -> r ^V 0 1 5 -> r ^V 1 6 8
If you know that there are more sequences to change, you can just use the n command to find the next occurrence of the search string, and repeat the r commands to change those as well.

To write the changes (you did this on a copy, right?) just write the file with the usual ":w" command. Ignore complaints about the end of the last line not being complete.

It is possible that you may have to fiddle with wrap mode; see the help by typing ":help wrap". See also ":help binary".

Pretty simple. I have used this technique to modify the values of symbols in ELF binary files as part of my Binary Translation work. Thanks to the people that wrote and maintain VIM; it's a really great editor. I recommend taking the time to set up syntax highlighting; it is very helpful.