Cross Compiling 32 bit kernel on a 64 bit machine

As simple as it sounds, you are probably here because you too just want to get it done at this point, so keep in mind that this is not an elegant solution in terms of the disk space it takes up, but it works.

First set up the target architecture and preferred location to install the toolchain.

export TARGET=i386-pc-linux-gnu
export PREFIX="$HOME/opt/cross/i386"
export PATH="$PREFIX/bin:$PATH"

We will need the source of binutils and gcc to build the toolchain. Depending on the kernel version you are building you might need different versions.

First we will build binutils.

export BINUTILS_VERSION=2.29.1 
wget ftp://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS_VERSION.tar.xz
cd $BINUTILS_BUILD

$BINUTILS_SOURCE/configure \
  --target=$TARGET \
  --prefix=$PREFIX \
  --with-sysroot \
  --disable-nls \
  --disable-werror

make
make install

If you are building for multiple target architectures, then it is recommended that you do so in separate directories.

Now moving on to building gcc,

GCC_VERSION=7.2.0
wget ftp://ftp.gnu.org/gnu/gcc/gcc-$GCC_VERSION/gcc-$GCC_VERSION.tar.xz

cd $GCC_BUILD
$GCC_SOURCE/configure \
  --target=$TARGET \
  --prefix=$PREFIX \
  --enable-languages=c,c++ \
  --without-headers \
  --disable-nls \
  --disable-shared \
  --disable-decimal-float \
  --disable-threads \
  --disable-libmudflap \
  --disable-libssp \
  --disable-libgomp \
  --disable-libquadmath \
  --disable-libatomic \
  --disable-libmpx \
  --disable-libcc1

make all-gcc
make install-gcc 

The packages not required for building the kernel are disabled here.

Now to build the kernel,

export KERNEL_ARCH=x86
export KERNEL_CONF=i386_defconfig

cd $KERNEL_SOURCE
make ARCH=$KERNEL_ARCH O=$KERNEL_BUILD $KERNEL_CONF

cd $KERNEL_BUILD
make ARCH=$KERNEL_ARCH CROSS_COMPILE=$TARGET- V=1 vmlinux modules

For a more general guide to cross compiling multiple kernels refer : https://gts3.org/2017/cross-kernel.html

Also check out https://github.com/R3x/How2Kernel for a beginner’s guide to Kernel Exploitation, a prebuilt x86_64 kernel image and a guide to building a root filesystem. Its a project we are still working on so star the repo and keep an eye out!