1#!/bin/bash
2
3set -e
4set -u
5
6if [ -v ANDROID_DIR ]; then
7    if [ ! -d "${ANDROID_DIR}" ]; then
8        echo ANDROID_DIR, "${ANDROID_DIR}", must be a directory
9        exit 1
10    fi
11    if [ ! -v ANDROID_PRODUCT ]; then
12        ANDROID_PRODUCT="trusty"
13    fi
14    ANDROID_BUILD_DIR="${ANDROID_DIR}/out/target/product/${ANDROID_PRODUCT}"
15fi
16
17if [ ! -v EXTRA_CMDLINE ]; then
18    EXTRA_CMDLINE=""
19fi
20
21QEMU_MACHINE="-machine virt,secure=on,virtualization=on"
22QEMU_FINAL_ARGS=()
23QEMU_ARGS=(
24    -nographic
25    -cpu cortex-a57
26    -smp 4
27    -m 1024
28    -bios bl1.bin
29    -d unimp
30    -semihosting-config enable,target=native
31    -no-acpi
32    )
33QEMU_SERIAL_ARGS=(
34    -serial mon:stdio
35    )
36for ARG in "$@"; do
37    if [ "${ARG}" = "-S" ]; then
38        QEMU_FINAL_ARGS+=("${ARG}")
39    else
40        QEMU_ARGS+=("${ARG}")
41    fi
42    if [ "${ARG}" = "-serial" ]; then
43        QEMU_SERIAL_ARGS=()
44    fi
45done
46QEMU_ARGS+=(${QEMU_SERIAL_ARGS[@]+${QEMU_SERIAL_ARGS[@]}})
47
48if [ -v KERNEL_DIR ]
49then
50    DTC="${KERNEL_DIR}/scripts/dtc/dtc"
51    QEMU_ARGS+=(
52        -kernel ${KERNEL_DIR}/arch/arm64/boot/Image
53        -append "earlyprintk console=ttyAMA0,38400 keep_bootcon root=/dev/vda ro init=/init androidboot.hardware=qemu_trusty ${EXTRA_CMDLINE}"
54        )
55    if [ -v ANDROID_BUILD_DIR ]; then
56        QEMU_ARGS+=(
57            -drive file=${ANDROID_BUILD_DIR}/userdata.img,index=2,if=none,id=hdc,format=raw
58            -device virtio-blk-device,drive=hdc
59            -drive file=${ANDROID_BUILD_DIR}/vendor.img,index=1,if=none,id=hdb,format=raw
60            -device virtio-blk-device,drive=hdb
61            -drive file=${ANDROID_BUILD_DIR}/system.img,index=0,if=none,id=hda,format=raw
62            -device virtio-blk-device,drive=hda
63            )
64    else
65        echo Set ANDROID_DIR to run a non-secure android build
66    fi
67    ${QEMU} ${QEMU_MACHINE},dumpdtb=qemu-gen.dtb "${QEMU_ARGS[@]}"
68    ${DTC} -q -O dts qemu-gen.dtb >qemu-gen.dts
69    cat qemu-gen.dts firmware.android.dts | ${DTC} -q -O dtb >qemu-comb.dtb
70    QEMU_ARGS+=(
71        -dtb qemu-comb.dtb
72        )
73else
74    echo Set KERNEL_DIR to run a non-secure kernel
75fi
76${QEMU} ${QEMU_MACHINE} "${QEMU_ARGS[@]}" ${QEMU_FINAL_ARGS[@]+"${QEMU_FINAL_ARGS[@]}"}
77