+qemu_is_required() {
+ local target_arch="${1}"
+
+ if [ -z "${target_arch}" ]; then
+ target_arch="${TARGET_ARCH}"
+ fi
+
+ case "${BUILD_ARCH},${target_arch}" in
+ x86_64,arm*|i?86,arm*)
+ return 0
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
+
+qemu_install_helper() {
+ # Do nothing, if qemu is not required
+ if ! qemu_is_required; then
+ return 0
+ fi
+
+ if [ -z "${QEMU_TARGET_HELPER}" ]; then
+ exiterror "QEMU_TARGET_HELPER not set"
+ fi
+
+ # Check if the helper is already installed.
+ if [ -x "${LFS}${QEMU_TARGET_HELPER}" ]; then
+ return 0
+ fi
+
+ # Try to find a suitable binary that we can install
+ # to the build environment.
+ local file
+ for file in "${QEMU_TARGET_HELPER}" "${QEMU_TARGET_HELPER}-static"; do
+ # file must exist and be executable.
+ [ -x "${file}" ] || continue
+
+ # Must be static.
+ file_is_static "${file}" || continue
+
+ local dirname="${LFS}$(dirname "${file}")"
+ mkdir -p "${dirname}"
+
+ install -m 755 "${file}" "${LFS}${QEMU_TARGET_HELPER}"
+ return 0
+ done
+
+ exiterror "Could not find a statically-linked QEMU emulator: ${QEMU_TARGET_HELPER}"
+}
+
+qemu_find_target_helper_name() {
+ local target_arch="${1}"
+
+ local magic
+ case "${target_arch}" in
+ arm*)
+ magic="7f454c4601010100000000000000000002002800"
+ ;;
+ esac
+
+ [ -z "${magic}" ] && return 1
+
+ local file
+ for file in /proc/sys/fs/binfmt_misc/*; do
+ # Search for the file with the correct magic value.
+ grep -qE "^magic ${magic}$" "${file}" || continue
+
+ local interpreter="$(grep "^interpreter" "${file}" | awk '{ print $2 }')"
+
+ [ -n "${interpreter}" ] || continue
+ [ "${interpreter:0:1}" = "/" ] || continue
+ [ -x "${interpreter}" ] || continue
+
+ echo "${interpreter}"
+ return 0
+ done
+
+ return 1
+}
+
+file_is_static() {
+ local file="${1}"
+
+ file ${file} 2>/dev/null | grep -q "statically linked"
+}
+