A - A - A

Chapter 7. Tools and Techniques

 
Search

Patching

This is the process of modifying a set of files with a 'patch' file containing a list of differences between two sets of files. This is how changes to source code are normally distributed. Patch files are generated by the diff command. You need at least version 2.5 of patch for patching the kernel. Here we use patching the binutils source as an example.

A patch is normally downloaded as a gzipped patch file (denoted by it ending in .gz). If so, gunzip it:

gunzip binutils-patch.gz

You can now patch binutils. Go into your unpacked binutils source directory, and run patch with your downloaded patch file, with argument -p1:

cd /usr/src/binutils-version
patch -p1 < binutils-patch

If you aren't sure exactly how a patch should be applied then the --dry-run option is very useful. Adding this means that patch will do its work, giving all the usual output but no changes are made to the files. To check out the effects of the above patch command, for example, you do:

patch -p1 --dry-run < binutils-patch

You should see a plethora of messages like:

Hunk #1 succeeded at 112

After patching has finished, you can check whether things have worked by searching for files ending in .rej (rejected patches):

% find . -name '*.rej'

In theory, there should be none of these files; all of the patches should have succeeded. However, if there are one or two failed files, it doesn't necessarily mean it won't build especially if the failed files are documentation or have names like README or endings like .info or .texi.

If you have several of these files, however, it could indicate something seriously wrong, and that it won't build. Check that the version of the source the patch is intended to be applied to matches the version of code you have. Also sometimes patches are 'reversed' - i.e. they have the original and modified source version the wrong way round in the diff command that generated the patches. Patch is smart and if it looks like this is the case it will offer to do them all 'backwards' for you.

The -p1 in the above example refers to how many directory '/' separators patch should strip off the filenames before patching. This is to allow for differences in the depth of nesting between the source tree the patch was created on and the one it is being applied to. Normally you will find that -p1 or -p0 is correct. If a patch doesn't seem to work then looking at the depth of filename nesting in it and using a different -p option is the first thing to try.

Once you understand how this works you can save some commands by combining the unzipping and patching commands into one line like this:

zcat binutils-patch.gz | patch -p1 

or, if the patch you have is bzipped instead of gzipped, then do:

bzcat binutils-patch.bz2 | patch -p1