Saturday, June 13, 2015

Notes on Cross-compiling

A quick post with some useful links and commands:
  • Building binutils, gcc, and gdb: link.
    • See the section "Roll-your-own".
  • Page with a nice table of available targets: link.
  • Comments on examining gcc's IR with the "-fdump-tree-all" and '-fdump-rtl-all" options: link.
  • Useful clang commands.
    • Generate assembly:
      • clang -S ./helloworld.c -target x86
    • Emit LLVM intermediate code:
      • clang -S -emit-llvm ./helloworld.c -o ./helloworld.s
    • Compile LLVM intermediate code into assembly code:
      • llc -march x86 ./helloworld.s
    • Use binutils to generate object file:
      • as ./helloworld.s -o helloworld.o
    • Or gcc to generate executable:
      • gcc ./helloworld.s -o helloworld
  • Command for disassembling object file:
    • objdump -d helloworld.o
  • Command to extract text from object file:
    • objcopy -O binary --only-section=.text /path/firmware.ko /content.bin

Update 9 Aug. 2016.

I realized it could be useful to explain here how to generate a MIPS binary.

The MIPS assembly can be generated using the clang command above:
  • clang -S ./helloworld.c -target mips -o helloworld.s
To generate a MIPS binary, we can build binutils for MIPS.
  • Download latest binutils from here: link.
  • Then (assuming you are on version 2.27 of binutils):
    • tar xzvf binutils-2.27
    • mkdir build-binutils
    • cd build-binutils
    • ../binutils-2.27/configure --TARGET=mips-el-unknown-linux-gnu --prefix=<installpath>
    • make
    • make install
  • helloworld.s can be assembled like this:
    • <installpath>/mipsel-unknown-linux-gnu-as helloworld.s -o helloworld
  • You can examine the contents of the output file using the built objdump, as described above:
    • <installpath>/mipsel-unknown-linux-gnu-objdump -d helloworld
  • And extract the text:
    • <installpath>/mipsel-unknown-linux-gnu-objcopy -O helloworld --only-section=.text ./helloworld helloworld.text
Much of the above was taken from here: link.