Skip to content

Improve Microsoft/scripts/gen_modules_vhdx.sh to run without root or sudo #13989

@julianxhokaxhiu

Description

@julianxhokaxhiu

Is your feature request related to a problem? Please describe.
This issue is about improving the script to generate the modules.vhdx file without requiring root. This is my own personal version but happy for everyone to contribute and improve it to every possible best practice. The script is already being used on the Arch Linux AUR package I've built ( see https://aur.archlinux.org/packages/linux-wsl2-waydroid ).

Describe the solution you'd like
See microsoft/WSL2-Linux-Kernel@0b55427 or the following code

#!/bin/bash
set -ueo pipefail

modules_dir="$1"        # e.g. "path/to/modules"
kernelver="$2"          # e.g. "6.6.114.1"
output="$3"             # e.g. "modules.vhdx"

if [ $# -ne 3 ] || [ ! -d "$modules_dir" ]; then
	printf '%s' "Usage ./$0 <modules dir> <kernelversion> <output file>" 1>&2
	exit 1
fi

if [ -e "$output" ]; then
	printf '%s' "Refusing to overwrite existing file $output" 1>&2
	exit 2
fi

# Calculate modules size (+256 MiB slack)
modules_size=$(du -bs "$modules_dir" | awk '{print $1}')
modules_size=$((modules_size + 256 * 1024 * 1024))

# ext4 block size (4 KiB)
block_size=4096
blocks=$(( (modules_size + block_size - 1) / block_size ))

# Temporary workspace
tmp_dir=$(mktemp -d)
trap 'rm -rf "$tmp_dir"' EXIT

img="$tmp_dir/modules.img"

# Create ext4 image populated from directory
mke2fs \
    -t ext4 \
    -b $block_size \
    -d "$modules_dir" \
    "$img" \
    "$blocks"

# Convert to VHDX
qemu-img convert -O vhdx "$img" "$output"

# Fix ownership since we're probably running under sudo
if [ -n "$SUDO_USER" ]; then
	chown "$SUDO_USER:$SUDO_USER" "$output"
fi

Describe alternatives you've considered
N/A

Additional context
The main idea is to improve the script to be able to run it without the need to use sudo or a root account.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions