Skip to content

cmd/enter, cmd/run: Add --arch flag for cross-arch containers support#1789

Open
DaliborKr wants to merge 15 commits into
containers:mainfrom
DaliborKr:pr09-enter-run
Open

cmd/enter, cmd/run: Add --arch flag for cross-arch containers support#1789
DaliborKr wants to merge 15 commits into
containers:mainfrom
DaliborKr:pr09-enter-run

Conversation

@DaliborKr
Copy link
Copy Markdown
Collaborator

This is PR 9/10 in a series adding cross-architecture container support using QEMU and binfmt_misc.

Depends on: #1788
Please review #1788 first. The new commits in this PR are:

  • cmd/enter: Add --arch flag for container architecture selection
  • cmd/run: Add --arch flag for container architecture selection

Summary

  • Add the --arch / -a flag to the enter and run commands, completing the CLI surface for cross-architecture support. Users can now create, enter, and run commands in non-native architecture containers using a consistent --arch flag across all three commands.

The existing RunContextWithExitCode() wraps all errors from
exec.Command in generic "failed to invoke" messages, which prevents
callers from distinguishing between actual error types.

Add RunContextWithExitCode2() and RunWithExitCode2() that return
errors with their original types intact, including for ExitError.
This allows callers to use errors.Is() and errors.As() to handle
specific failure modes. For example, detecting a missing skopeo binary
(exec.ErrNotFound) or an ENOEXEC error from inside non native
containers, when an emulator is not set correctly.

These new functions are meant to replace its original versions in the
future.

containers#1780

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
@DaliborKr DaliborKr requested a review from debarshiray as a code owner April 24, 2026 22:17
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for non-native architecture Toolbx containers by leveraging QEMU user-mode emulation and binfmt_misc. It adds an --arch flag to the create, enter, and run commands, and implements the necessary logic to pull non-native images via skopeo and initialize the emulation environment within the container. Feedback highlights a logical flaw in the container initialization sequence where architecture registration might be skipped or fail due to existing registrations, and suggests improving the binfmt_misc mounting logic to handle cases where the filesystem is already mounted.

Comment thread src/cmd/initContainer.go Outdated
Comment on lines +286 to +295
err := architecture.IsArchSupportedOnInitialization(initContainerFlags.archID, interpreterPath)
if err != nil {
errNotSupported := fmt.Errorf("Cannot run container for architecture %s:\n%s", archName, err)
return errNotSupported
}

logrus.Debugf("Registering QEMU emulator for architecture %s in binfmt_mist", archName)
if err := architecture.RegisterBinfmtMisc(initContainerFlags.archID, interpreterPath); err != nil {
return err
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The logic for architecture emulator registration is problematic. IsArchSupportedOnInitialization returns an error if the architecture is not already registered, which causes the function to exit at line 289, preventing RegisterBinfmtMisc from ever running. If the architecture is already registered, IsArchSupportedOnInitialization succeeds, but then RegisterBinfmtMisc is called and will likely fail with an 'already exists' error when trying to write to the binfmt_misc register. The code should check if registration is needed and only attempt it if the architecture is not yet supported.

Comment on lines +130 to +132
if err := shell.Run("mount", nil, &stdout, nil, args...); err != nil {
return fmt.Errorf("failed to mount binfmt_misc: %w", err)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The mount command will fail if binfmt_misc is already mounted at /proc/sys/fs/binfmt_misc. In many container environments, this filesystem might already be available. It is recommended to check if the path is already a mount point or to handle the 'already mounted' exit code from the mount command to avoid unnecessary failures during container initialization.

@softwarefactory-project-zuul
Copy link
Copy Markdown

DaliborKr added 14 commits May 10, 2026 22:12
In /src/cmd/create.go, the same pattern of spinner creation and
nil-safe stopping is repeated.

Extract this into startSpinner() and stopSpinner() helper functions so
that future callers can use spinners without duplicating the code.
Replace the existing inline spinner code in createContainer() and
pullImage() with calls to these new helpers.

containers#1781

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
…atching

Add IsSupportedDistroImage(), which iterates over all supported distros
and checks if the image basename matches any of them. This will be used
by the architecture resolution code to decide whether to parse
architecture suffixes from image tags, as this should be done only for
natively supported images [1].

[1] Toolbx supported distributions: https://containertoolbx.org/distros/

containers#1781

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Introduce the architecture package that represents the core of the
Toolbx cross-architecture support, which is based on user-mode emulation
using QEMU and binfmt_misc.

The Architecture struct collects all per-architecture data (ELF
magic/mask, OCI and binfmt naming, aliases, binfmt registration
parameters) into a single map. Architectures present in the
supportedArchitectures map represent the set of supported
architectures within Toolbx.

Define architecture ID constants NotSpecified, Aarch64, Ppc64le, and
X86_64, along with their supportedArchitectures entries.

Add core query functions:
- ParseArgArchValue() for resolving user-supplied architecture strings

- GetArchNameBinfmt() and GetArchNameOCI() for name
  lookups (one architecture can have multiple valid names [1])

- HasContainerNativeArch() for comparing against the host

- ImageReferenceGetArchFromTag() for extracting architecture
  from image tag suffixes like "42-aarch64" for architecture detection

Expose the HostArchID package variable, which is set in the init()
function, so the variable can be accessed in the early init() state
from every inheritor that utilizes the architecture package (HostArchID
serves as a default value for initContainer --arch flag), and the Config
struct for preserving the architecture ID and the QEMU emulator path,
through the call chain.

[1] https://itsfoss.com/arm-aarch64-x86_64/

containers#1782

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Cross-architecture containers need QEMU binfmt_misc handlers registered
within the container so that non-native architecture binaries can be
executed via the host's kernel.

Add the Registration struct that models a binfmt_misc registration
entry, including name, magic type, offset, ELF magic/mask bytes,
interpreter path, and flags.

Add functions:
- MountBinfmtMisc() to mount the sanboxed binfmt_misc filesystem inside
  a container, which enables setting the C flag in binfmt_misc
  registration without affecting the host system. The C flag presents a
  threat of privilege escalation when registered on the host, that why
  we want to have it isolated [1]

- getDefaultRegistration() to fill a Registration struct containing all
  necessary binfmt_misc information taken from the
  architecture.supportedArchitectures data

- RegisterBinfmtMisc() to write the registration string to
  /proc/sys/fs/binfmt_misc/register, which makes the non-native binary
  perception active

- bytesToEscapedString() helper that formats byte slices into the
  \xHH-escaped string format required by the binfmt_misc register
  interface

[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=21ca59b365c0

containers#1782

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Before creating or initializing a cross-architecture container, the
system must be checked for the required QEMU emulator and binfmt_misc
registration. This prevents users from creating or running non-native
containers when their host system doesn't meet the requirements, and
provides users with an informative error message referring to the
problem.

Add IsArchSupportedOnCreation(), which searches for a statically linked
QEMU binary on the host using exec.LookPath() and verifies that a
matching binfmt_misc registration exists. It returns the path to the
QEMU binary for use during container creation, which is meant to be
passed to the init-container and registered through sandboxed
binfmt_misc within the container.

Add IsArchSupportedOnInitialization() which performs similar checks
from inside the container, looking at the interpreter path passed from
the host and falling back to standard host-mounted locations under
/run/host/usr/bin/.

Add isStaticallyLinkedELF() helper that uses debug/elf to verify a
binary is statically linked. Only a statically linked QEMU interpreter
can be used, because a dynamically linked one would cause the kernel
to attempt to resolve its host-native shared libraries (such as libc.so)
within the container, resulting in an immediate crash.

Add validateBinfmtRegistration(), which checks for the presence of
qemu-<arch> entries in binfmt_misc (or qemu-<arch>-static, since it can
differ based on the system).

containers#1783

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Add Architecture and NameFull fields to the Skopeo Image struct so that
callers can inspect the architecture of a remote image. Move the image
size computation from the /cmd layer into GetSize() and GetSizeHuman()
methods on Image, since the skopeo package owns the layer data.

Add VerifyArchitectureMatch() method to Image that validates the image's
architecture field against an expected architecture ID. The purpose of
this function is to check whether the image architecture matches the
demanded architecture before it is pulled. Specifically, this
verification applies to the images that support only a single
architecture (they are not part of a multi-platform manifest list),
because the skopeo inspect proceeds successfully even when the value
of a flag --override-arch does not match the actual image architecture
(for a multi-architecture image the skopeo inspect with not-matching
--override-arch would fail). Like this, the user can be prevented from
incompatible images.

containers#1784

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Change Inspect() to accept archID and authfile parameters. When the
requested architecture differs from the host's, --override-arch is
passed to skopeo, which then inspects the correct manifest in a
multi-arch image (if it exists for the given architecture, otherwise
the inspection fails). It also uses RunContextWithExitCode2() so callers
can detect a missing skopeo binary via errors.Is(err, exec.ErrNotFound),
which is only a soft dependency of the Toolbx package, as it is not
required for running native containers.

Add CopyOverrideArch(), which uses 'skopeo copy --override-arch' to pull
a specific architecture variant of a multi-arch image into Podman's
local container storage. This is used instead of 'podman pull' because
Podman does not support pulling a foreign architecture image into a
locally addressable name. The way in which the cross-arch extension
chooses the name for non-native images (and also containers) is
described in the discussion at [1]

[1] containers/podman#27780 (comment)

containers#1784

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
…and names

Add resolveArchitectureID(), which combines the --arch command-line
flag with architecture detection from image tag suffixes
(e.g., "fedora-toolbox:42-aarch64"). This detection applies only
to images from distributions that Toolbx explicitly supports (see [1]),
to avoid a false architecture approach on custom images where a
dash-separated component might not represent an architecture, since
there is no standard set regarding preserving architecture in the tag
(see detailed explanation at [2]). When both sources specify an
architecture, it validates that they do not conflict.

Add resolveImageNameWithArchitectureSuffix(), which appends the OCI
architecture name to supported distro image references when the target
architecture differs from the host, to ensure the local Toolbx images
naming convention [2]. Again, this applies only to supported distros.

[1] https://containertoolbx.org/distros/
[2] containers/podman#27780 (comment)

containers#1786

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Change resolveContainerAndImageNames() to accept an archID parameter.
When the target architecture is non-native, and the container name was
auto-generated (was not set by a user), append the architecture suffix
to the container name (e.g., "fedora-toolbox-arm64") to distinguish it
from native containers.

Temporarily update the callers of resolveContainerAndImageNames() to
pass in architecture.HostArchID to the updated signature, to maintain
a default native behavior. Once implemented, the --arch argument in
the callers will pass the actual architecture information.

containers#1786

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Add the --arch flag to the 'create' command, allowing users to create
Toolbx containers for architectures different from the host
(e.g., 'toolbox create --arch arm64').

Utilize the architecture resolution pipeline in create() by using
resolveArchitectureID() (added in [1]) to determine the target
architecture from the --arch flag and image tags.

Validate host support via IsArchSupportedOnCreation() (added in [2]),
which checks for the required QEMU emulator and binfmt_misc
registration.

Pass architecture ID to resolveContainerAndImageNames() (updated in [1])
so that non-native containers get architecture-suffixed names.

Update pullImage() to handle cross-architecture image pulling: when the
target architecture is non-native, use skopeo.CopyOverrideArch()
(added in [3]) instead of podman.Pull(), since Podman does not support
pulling foreign architecture images into locally addressable names.
The need for this is explained in a discussion in [4].

Add a 'toolbox-arch' label to created containers to record the target
architecture in OCI format.

Extract the image pull error formatting into createErrorImagePull() in
utils.go to avoid duplication between the native and cross-arch pull
paths.

Update the createContainer() call in run.go to pass the default
architecture config via GetArchConfigDefault(), maintaining the
existing native-architecture behavior.

[1] containers#1786
[2] containers#1783
[3] containers#1784
[4] containers/podman#27780

containers#1787

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Rework the image download prompt flow to support architecture
verification before pulling non-native images. The new implementation
ensures that the image inspection completes for the non-native creation
path before it is pulled, so the image's architecture can be verified.

The previous implementation used promptForDownloadError as a control
flow mechanism between the first and second download prompts. Replace
this with the pullImageDecision enum (pullNo, pullYes, pullUnknown)
for clearer three-state signaling.

Replaced getImageSizeFromRegistryAsync() with
getImageFromRegistryAsync(), which now returns the full skopeo.Image
struct instead of just the image size string. It calls skopeo.Inspect()
(updated in [1]), making image metadata available throughout the
download prompt flow for both size display and architecture verification
in a single inspect call.

Use Image.GetSizeHuman() (added in [1]) for image size display in the
second download prompt, replacing the local size computation.

Update showPromptForDownloadFirst() to return
(pullImageDecision, *skopeo.Image, error). For non-native architectures,
when the user confirms the download, the function now waits for the
skopeo inspect to complete (with a spinner) before returning, ensuring
that architecture verification can happen before the pull begins.

Update pullImage() to verify the image architecture before pulling
non-native images by calling VerifyArchitectureMatch() (added in [1])
to catch incompatible single-architecture images. Handle the case where
the inspect returns nil (multi-arch manifest has no matching variant)
with an explicit error.

Detect a missing skopeo binary via exec.ErrNotFound, which is only a
soft dependency of the Toolbx package, as it is not required for
running non-native containers, and report it through
createErrorSkopeoNotFound() added in utils.go.

[1] containers#1784

containers#1787

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Add the --arch and --arch-emulator-path flags to the init-container
command, passed from the create command when creating a
cross-architecture container. The --arch flag defaults to the host
architecture ID so that existing native containers continue to work
without changes.

When the container's architecture differs from the host, the
init-container entry point configures QEMU emulation inside the
container before any foreign-architecture binaries can run:

1. Validate QEMU emulation by running the 'true' command, which fails
with ENOEXEC if the host's binfmt_misc registration is not working
(detected via RunWithExitCode2() added in [1]), because it is necessary
to have host emulation working to emulate the binfmt_misc registration
in the following step.

2. Mount a fresh binfmt_misc filesystem inside the container via
MountBinfmtMisc() (added in [2]) to create a sandboxed binfmt_misc
registration with the C flag.

3. Validate architecture support via IsArchSupportedOnInitialization()
(added in [3]), which verifies the QEMU interpreter at the host-mounted
path under /run/host.

4. Register the QEMU interpreter with the C flag via
RegisterBinfmtMisc() (added and explained in [2])

The binfmt_misc registration is performed inside the container rather
than relying on the host's registration, as explained in [2].

Update showEntryPointLog() in run.go to propagate lines prefixed with
'Warning:' to stderr on the host, instead of treating them as errors.
This is needed because the cross-architecture initialization may emit
warnings that should be visible to the user but are not fatal.

[1] containers#1780
[2] containers#1782
[3] containers#1783

containers#1788

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Add the --arch / -a flag to the enter command, allowing users to enter
cross-architecture containers by specifying the target architecture
(e.g., toolbox enter --arch arm64). Can be used with flags --distro
and --release, just as for container creation.

The flag value is resolved through resolveArchitectureID()
(added in [1]) and passed to resolveContainerAndImageNames()
(updated for cross-arch in [1])  so that it resolves to the
architecture-suffixed container name.

[1] containers#1786

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
Add the --arch / -a flag to the run command, allowing users to run
commands inside cross-architecture containers by specifying the target
architecture (e.g., toolbox run --arch arm64 uname -m). Can be used
with flags --distro and --release, just as for container creation.

The flag value is resolved through resolveArchitectureID()
(added in [1]) and passed to resolveContainerAndImageNames()
(updated for cross-arch in [1])  so that it resolves to the
architecture-suffixed container name.

[1] containers#1786

Signed-off-by: Dalibor Kricka <dalidalk@seznam.cz>
@centosinfra-prod-github-app
Copy link
Copy Markdown

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant