Binary editing

Sometimes it can be very useful to edit a binary file. A very popular use is the changing of default (path)names in compilers that aren't versatile enough to pick new (path)names up from the environment. This can cause a compiler to look for some of its files in a `more sensible' place.

A file can be read in as a binary file when the buffer is first placed in the `raw' mode. This is done with the Alt-R command. In the raw mode a file is read without interpretation of the linefeeds and carriage returns in it. It is read with 64 characters per line and the display will look rather messy. Many of the bytes in a binary file correspond to non-ASCII characters. On the micro's and the workstations they can still be shown on the screen. It takes however a very experienced hacker to read the code segment of an executable file. On the other hand a study of the text strings in a program may be very revealing.

When searching for a string in a binary file there can be a problem when the screen representation of the searched for string has part of the string at the end of one line and the rest at the beginning of the next line. Stedi has put the file in the buffer, using its normal lines mechanism and it chopped it up into pieces of 64 characters. The following macro can restore such strings so that the characters that are in the next line will be moved.

    set n = strlen $1 - 1
    while $n
      set a = $1 << $n
      set b = $1 =^ $a
      //"$a"\n"$b"/=/$1\n/
      set n = $n - 1
    endwhile
This way we search for the string `head' end-of-line `tail'. We take a to be n characters from the left of the argument and b is the rest of the argument. When n becomes zero we finish. The macro needs one argument, so it is called with the command
    x reorder string
assuming that the macro got the name `reorder'. The effect could be that
    abcdstr
    ing0123
is changed into
    abcdstring
    0123
It is absolutely no problem that the length of the lines has been changed now. After this macro has been executed one can either search for the string in the normal way, or try to replace it. It is actually rather easy to change the above macro, so that it uses two arguments and makes the replacement immediately. If you don't understand the above macro's you should consult the chapter on macro's p. [*].

One reminder: when changing a binary file, make sure not to add characters between code segments. This can upset all kinds of offsets, causing the program to crash (if you are lucky, because worse things can happen).