Skip to content

Instantly share code, notes, and snippets.

@th0rex
Last active April 29, 2024 07:39
Show Gist options
  • Save th0rex/946c12e04c7ded43d12abbc92c9b5363 to your computer and use it in GitHub Desktop.
Save th0rex/946c12e04c7ded43d12abbc92c9b5363 to your computer and use it in GitHub Desktop.
Build qemu as a library
#!/bin/sh
set -e
[ -z "$1" ] && echo "Usage: $0 <target>" && exit 1
case "$(uname)" in
Linux)
ncpu="$(nproc)"
;;
Darwin)
ncpu="$(sysctl -n hw.physicalcpu)"
;;
esac
flags="$(./configure --help | perl -ne 'print if s/^ ([a-z][\w-]*) .*/\1/' | tail -n +2 | awk '{print "--disable-"$1}' ORS=' ')"
${2:-.}/configure --extra-cflags=-fPIC --target-list=$1 --disable-slirp $flags
make clean >/dev/null
file=$(mktemp)
make -n 2>/dev/null >$file
cmdline="$(cat $file | perl -ne "print if s/.*LINK.*$1.*&& //" | perl -ne 's/ -o qemu-system-[a-z]+/ -shared -o libqemu.so/; print')"
vl="$(cat $file | perl -ne 'print if s/.*CC.*vl.o.*&& //' | head -n 1)"
# Build everything as usual
make "-j$ncpu" >/dev/null
# Build vl.c but better
$vl -D"main=__definetly_not_main_lmao__"
# Build a shared library, without vl.o and otherwise *exactly* the same
# flags.
cd $1
$cmdline
echo "$(echo "$vl" | grep -E -o '(-I|-f|-W|-m|-p)[^ ]+' | tr '\n' ' ')" \
"$(echo "$cmdline" | grep -E -o '(-Wl|-l|-L)[a-z0-9-]+ ' | sed '/-labels/d' | sed '/-limits/d' | tr '\n' ' ')"

Place file into qemu root directory Do cd path/to/qemu && ./name_of_file name_of_target (i.e. x86_64-softmmu) Library is at /path/to/qemu/x86_64-softmmu/libqemu.so You might need to compile vl.c and link with it in your final binary, just do something like this:

#define main __definetly_not_main
#include "/path/to/qemu/vl.c"
#undef main

int main() {
  // Whatver you want to do with qemu
}
@theoparis
Copy link

I'm still getting ERROR: Unknown target name 'x86_64-softmmu'

@ThomazPom
Copy link

Please note that the cmdline on Line 26 of the script is outdated and incompatible with recent versions of the QEMU source. It currently defines to an empty string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment