run_qemu.sh: Refactor pvmfw_overlay

To make the calling code clearer, decompose the 5-parameters function
into two steps: generating the DTS for PVMFW and injecting a DTS into an
existing DTB. This allows us to get rid of an intermediate file by using
inter-function bash piping.

Move the responsibility of hex-formatting addresses and sizes into the
DTS function that requires it.

Rename ${QEMU_PATCHED_DTB} to the shorter ${DTB}.

Change-Id: I10914391ca022a507e56cce855ec347b00838f9a
diff --git a/aarch64/run_qemu.sh b/aarch64/run_qemu.sh
index 5145075..bade6b4 100755
--- a/aarch64/run_qemu.sh
+++ b/aarch64/run_qemu.sh
@@ -100,17 +100,10 @@
 }
 
 function pvmfw_overlay() {
-	local in="$1"
-	local out="$2"
-	local tmp="$3"
-	local addr="$4"
-	local size="$5"
+	local addr=$(hex "$1")
+	local size=$(hex "$2")
 
-	# Convert input DTB back to source.
-	${DTC} -I dtb -O dts -o "${tmp}" "${in}"
-
-	# Append an overlay describing the pvmfw.
-	cat <<EOF >> "${tmp}"
+	cat <<EOF
 &{/} {
 	pkvm_template@${addr} {
 		compatible = "pkvm,arm64";
@@ -120,9 +113,13 @@
 	};
 };
 EOF
+}
 
-	# Compile back to DTB.
-	${DTC} -I dts -O dtb -o "${out}" "${tmp}"
+function inject_overlay() {
+	local overlay="$1"
+	local dtb="$2"
+
+	${DTC} -I dts -O dtb <(cat <(${DTC} -I dtb -O dts "${dtb}") "${overlay}")
 }
 
 CMD=()
@@ -224,30 +221,28 @@
 
 if [ -n "${PVMFW}" ]; then
 	QEMU_DTB="$(mktemp)"
-	QEMU_PATCHED_DTB="$(mktemp)"
-	TMP_DTS="$(mktemp)"
+	DTB="$(mktemp)"
 
 	# Mark files for deletion on EXIT.
-	TMP_FILES+=("${QEMU_DTB}" "${QEMU_PATCHED_DTB}" "${TMP_DTS}")
+	TMP_FILES+=("${QEMU_DTB}" "${DTB}")
 
 	# Dump the QEMU DTB.
 	"${CMD[@]}" -machine dumpdtb="${QEMU_DTB}" > /dev/null
 
 	# Compile the overlayed DTB with dummy values to determine its size.
-	pvmfw_overlay "${QEMU_DTB}" "${QEMU_PATCHED_DTB}" "${TMP_DTS}" 0x0 0x0
-	TMP_DTB_SIZE=$(file_size "${QEMU_PATCHED_DTB}")
+	inject_overlay <(pvmfw_overlay 0x0 0x0) "${QEMU_DTB}" >"${DTB}"
 
 	# 128MiB (or RAM/2 if RAM<256MiB) is left to the kernel to decompress.
 	# This is followed by the ramdisk and then 2MiB-aligned DTB.
 	# We place the pvmfw at the following page.
-	PVMFW_ADDR=$(( KERNEL_ADDR + 128*MiB + TMP_DTB_SIZE ))
+	PVMFW_ADDR=$(( KERNEL_ADDR + 128*MiB + $(file_size "${DTB}") ))
 	PVMFW_ADDR=$(hex $(align_page_size ${PVMFW_ADDR}))
-	PVMFW_SIZE=$(hex $(file_size "${PVMFW}"))
+	PVMFW_SIZE=$(file_size "${PVMFW}")
 
-	pvmfw_overlay "${QEMU_DTB}" "${QEMU_PATCHED_DTB}" "${TMP_DTS}" \
-			 "${PVMFW_ADDR}" "${PVMFW_SIZE}"
+	inject_overlay <(pvmfw_overlay ${PVMFW_ADDR} ${PVMFW_SIZE}) "${QEMU_DTB}" \
+		>"${DTB}"
 
-	CMD+=(-dtb "${QEMU_PATCHED_DTB}")
+	CMD+=(-dtb "${DTB}")
 	CMD+=(-device loader,file="${PVMFW}",addr=${PVMFW_ADDR},force-raw=true)
 fi