pmbootstrap-meow/pmb/chroot/binfmt.py
Caleb Connolly 1d9bbd613e
chroot: require explicit initialisation (MR 2252)
We currently lazily initialize the chroot's on first use, plus a few
bonus calls to init. However, there are some instances where we actually
don't want the chroot to be initialised (mostly to break recursion
loops).

Simplify the codebase by removing all of this, and just calling
pmb.chroot.init() where it's needed.

In addition, print a warning if init() is called multiple times for one
chroot. This should help us catch these instances if they crop up again.

Signed-off-by: Caleb Connolly <caleb@postmarketos.org>
2024-06-23 12:38:37 +02:00

66 lines
2 KiB
Python

# Copyright 2023 Oliver Smith
# SPDX-License-Identifier: GPL-3.0-or-later
import os
from pmb.core.chroot import Chroot
from pmb.helpers import logging
from pmb.core.types import PmbArgs
import pmb.helpers.run
import pmb.helpers.other
import pmb.parse
import pmb.parse.arch
def is_registered(arch_qemu):
return os.path.exists("/proc/sys/fs/binfmt_misc/qemu-" + arch_qemu)
def register(args: PmbArgs, arch):
"""
Get arch, magic, mask.
"""
arch_qemu = pmb.parse.arch.alpine_to_qemu(arch)
# always make sure the qemu-<arch> binary is installed, since registering
# may happen outside of this method (e.g. by OS)
if f"qemu-{arch_qemu}" not in pmb.chroot.apk.installed(args):
pmb.chroot.apk.install(args, ["qemu-" + arch_qemu], Chroot.native())
if is_registered(arch_qemu):
return
pmb.helpers.other.check_binfmt_misc(args)
# Don't continue if the actions from check_binfmt_misc caused the OS to
# automatically register the target arch
if is_registered(arch_qemu):
return
info = pmb.parse.binfmt_info(arch_qemu)
# Build registration string
# https://en.wikipedia.org/wiki/Binfmt_misc
# :name:type:offset:magic:mask:interpreter:flags
name = "qemu-" + arch_qemu
type = "M"
offset = ""
magic = info["magic"]
mask = info["mask"]
interpreter = "/usr/bin/qemu-" + arch_qemu + "-static"
flags = "C"
code = ":".join(["", name, type, offset, magic, mask, interpreter,
flags])
# Register in binfmt_misc
logging.info("Register qemu binfmt (" + arch_qemu + ")")
register = "/proc/sys/fs/binfmt_misc/register"
pmb.helpers.run.root(
args, ["sh", "-c", 'echo "' + code + '" > ' + register])
def unregister(args: PmbArgs, arch):
arch_qemu = pmb.parse.arch.alpine_to_qemu(arch)
binfmt_file = "/proc/sys/fs/binfmt_misc/qemu-" + arch_qemu
if not os.path.exists(binfmt_file):
return
logging.info("Unregister qemu binfmt (" + arch_qemu + ")")
pmb.helpers.run.root(args, ["sh", "-c", "echo -1 > " + binfmt_file])