Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have an executable binary; let's call it a.out. I can see the binary contains strings

$ strings a.out
...
/usr/share/foo
....

I need to change the string /usr/share/foo to /usr/share/bar. Can I just replace the string with sed?:

sed -i 's@/usr/share/foo@/usr/share/bar@' a.out

This looks like a safe thing to do. Will this also work when the strings are not the same length?

share|improve this question

1 Answer 1

up vote 9 down vote accepted

I don't know if your version of sed will be binary-clean or if will choke on what it thinks are really long lines in its input, but barring those issues, editing the string in-place should work. To see whether it does, compare the old and new versions with cmp -l. It should tell you whether or not the only three differences between the two files are those 3 bytes.

Editing strings in a compiled executable will indeed work if the strings are of the same length, but it will almost always also work if you are shortening the string, due to the way that strings work in C. In C strings, everything after the NUL terminator does not count, so if you write a new NUL terminator before the position of the old one, you will effectively shorten the string.

In general, there is no way you can lengthen a string using this hack.

share|improve this answer
    
What about shortening the string with something like sed -i 's@longstring@foo@' a.out? This will make the whole binary smaller by 7 bytes, Will this not corrupt the binary ? –  Martin Vegter 8 hours ago
    
Yes, it will corrupt the binary. That's why you have to translate the string to one of the exact same length, but set a NUL terminator at an earlier position as I explained (although maybe too briefly). The trouble is that you can't have a NUL byte on the command line so you have to put your sed program into a file and refer to it with -f. On the other hand, the safer thing to do would be to use a tool that is designed to work with binary data instead of sed which is designed to work with text data. –  Celada 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.