Просмотр исходного кода

Make the USB image bootable and add a flash target

Johannes Zellner 1 месяц назад
Родитель
Сommit
ff94515139
4 измененных файлов с 197 добавлено и 39 удалено
  1. 24 4
      Makefile
  2. 108 0
      flash.sh
  3. 61 29
      mbr.S
  4. 4 6
      mbr.ld

+ 24 - 4
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-floppy run-usb run-serial floppy usb space prog bootstrap dev monitor
+.PHONY: all clean run run-floppy run-usb run-serial floppy usb flash space prog bootstrap dev monitor
 
 all: floppy.img usb.img final.bin root.img
 
@@ -253,8 +253,18 @@ boot.bin: boot.elf
 kernel.bin: kernel.elf
 	$(OBJCOPY) -O binary $< $@
 
+# Byte offsets inside boot.bin (see boot.S). Keep decimal: dd's seek= does not
+# parse 0x… literals (it silently treats them as 0) and the error is hidden by
+# the 2>/dev/null below.
+# 62 = kernel_sectors field (0x3E)
+# 87 = low byte of the "movw $1, %si" kernel start LBA (0x57)
+# 26/28/32 = BPB: heads (0x1A, word), hidden sectors (0x1C, dword),
+#            total sectors 32-bit (0x20, dword)
 KERNEL_SECTORS_OFFSET = 62
-BOOT_SECTOR_START_OFFSET = 0x57
+BOOT_SECTOR_START_OFFSET = 87
+BPB_HEADS_OFFSET = 26
+BPB_HIDDEN_OFFSET = 28
+BPB_TOTAL_OFFSET = 32
 
 floppy.img: boot.bin kernel.bin
 	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
@@ -268,8 +278,13 @@ usb.img: mbr.bin boot.bin kernel.bin
 	SECTORS=$$(( ($$(stat -c%s kernel.bin) + 511) / 512 )); \
 	cp boot.bin boot.bin.patched; \
 	printf "$$(printf '\\x%02x\\x%02x' $$((SECTORS & 0xFF)) $$((SECTORS >> 8)))" | dd of=boot.bin.patched bs=1 seek=$(KERNEL_SECTORS_OFFSET) conv=notrunc 2>/dev/null; \
-	printf '\x02' | dd of=boot.bin.patched bs=1 seek=$(BOOT_SECTOR_START_OFFSET) conv=notrunc 2>/dev/null; \
-	cat mbr.bin boot.bin.patched kernel.bin > $@; \
+	printf '\x40' | dd of=boot.bin.patched bs=1 seek=$(BOOT_SECTOR_START_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\xff\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_HEADS_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\x3f\x00\x00\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_HIDDEN_OFFSET) conv=notrunc 2>/dev/null; \
+	printf '\x08\xb7\x01\x00' | dd of=boot.bin.patched bs=1 seek=$(BPB_TOTAL_OFFSET) conv=notrunc 2>/dev/null; \
+	cat mbr.bin > $@; \
+	dd if=/dev/zero bs=512 count=62 2>/dev/null >> $@; \
+	cat boot.bin.patched kernel.bin >> $@; \
 	truncate -s 64M $@; \
 	rm -f boot.bin.patched
 
@@ -336,6 +351,11 @@ floppy: floppy.img
 
 usb: usb.img
 
+# Write usb.img to a USB stick; prompts before destroying anything.
+#   make flash USB=/dev/sdX          FORCE=1 skips the removable-device check.
+flash: usb.img
+	@./flash.sh "$(USB)" "$(FORCE)"
+
 run-floppy: floppy.img root.img
 	qemu-system-i386 -M pc -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
 	qemu-system-x86_64 -M pc -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy

+ 108 - 0
flash.sh

@@ -0,0 +1,108 @@
+#!/bin/sh
+# Flash usb.img onto a USB stick.
+#
+#   make flash USB=/dev/sdX          (re-runs itself through sudo if needed)
+#   make flash USB=/dev/sdX FORCE=1  (skip the USB/removable device check)
+#
+# Refuses to touch partitioned devices or devices with mounted filesystems,
+# prints a summary and needs "yes" before writing anything.
+set -eu
+
+IMG=usb.img
+dev=${1:-}
+force=${2:-}
+
+if [ -z "$dev" ]; then
+	echo "usage: make flash USB=/dev/sdX [FORCE=1]" >&2
+	exit 1
+fi
+
+if [ ! -f "$IMG" ]; then
+	echo "flash: $IMG not found (run 'make usb.img' first)" >&2
+	exit 1
+fi
+
+if [ ! -b "$dev" ]; then
+	echo "flash: $dev: not a block device" >&2
+	exit 1
+fi
+
+command -v lsblk >/dev/null 2>&1 || { echo "flash: lsblk not found" >&2; exit 1; }
+
+dev_type=$(lsblk -ndo TYPE "$dev" | tr -d ' ')
+rm_flag=$(lsblk -ndo RM "$dev" | tr -d ' ')
+tran=$(lsblk -ndo TRAN "$dev" | tr -d ' ')
+model=$(lsblk -ndo MODEL "$dev" | tr -s ' ' | sed 's/^ *//;s/ *$//')
+dev_size=$(lsblk -bndo SIZE "$dev" | tr -d ' ')
+img_size=$(stat -c%s "$IMG")
+
+case "$dev_type" in
+part)
+	echo "flash: $dev is a partition; pass the whole disk (e.g. /dev/sdb)" >&2
+	exit 1
+	;;
+esac
+
+if [ "$force" != "1" ] && [ "$tran" != "usb" ] && [ "$rm_flag" != "1" ]; then
+	echo "flash: $dev does not look like a USB/removable device (TRAN=$tran RM=$rm_flag)" >&2
+	echo "flash: pass FORCE=1 if you really mean it" >&2
+	exit 1
+fi
+
+mounted=$(lsblk -nro MOUNTPOINT "$dev" | sed '/^$/d')
+if [ -n "$mounted" ]; then
+	echo "flash: $dev has mounted filesystems:" >&2
+	echo "$mounted" | sed 's/^/  /' >&2
+	echo "flash: unmount them first (e.g. sudo umount $dev?*)" >&2
+	exit 1
+fi
+
+if [ "$dev_size" -eq 0 ]; then
+	echo "flash: $dev reports 0 bytes - the kernel sees no medium" >&2
+	echo "flash: the stick probably dropped off the bus; replug it into a direct" >&2
+	echo "flash: port (not a hub) and watch 'lsblk' / 'journalctl -k -f'" >&2
+	exit 1
+fi
+
+if [ "$dev_size" -lt "$img_size" ]; then
+	echo "flash: $dev ($dev_size bytes) is smaller than $IMG ($img_size bytes)" >&2
+	exit 1
+fi
+
+# dd needs root; re-exec through sudo if we are not root yet.
+if [ "$(id -u)" -ne 0 ]; then
+	if command -v sudo >/dev/null 2>&1; then
+		echo "flash: re-running with sudo..."
+		exec sudo "$0" "$@"
+	fi
+	echo "flash: must run as root (no sudo found)" >&2
+	exit 1
+fi
+
+echo "About to write $IMG ($img_size bytes) to:"
+echo "  device: $dev"
+echo "  size:   $dev_size bytes"
+echo "  model:  ${model:-unknown}"
+echo "  bus:    ${tran:-unknown} (removable=$rm_flag)"
+printf 'ALL DATA ON %s WILL BE DESTROYED. Type "yes" to continue: ' "$dev"
+read -r answer
+if [ "$answer" != "yes" ]; then
+	echo "flash: aborted"
+	exit 1
+fi
+
+echo "flash: writing..."
+dd if="$IMG" of="$dev" bs=4M conv=fsync status=progress
+
+echo "flash: syncing..."
+sync
+
+printf 'flash: verifying... '
+if head -c "$img_size" "$dev" | cmp -s - "$IMG"; then
+	echo "OK"
+else
+	echo "MISMATCH" >&2
+	exit 1
+fi
+
+echo "flash: done. Safe to remove $dev."

+ 61 - 29
mbr.S

@@ -1,15 +1,23 @@
 /*
  * MBR boot code: finds active partition, loads its boot sector, jumps to it.
- * Placed at sector 0 of usb.img. Partition table points to boot sector at sector 1.
+ * Placed at sector 0 of usb.img. Partition table points to boot sector at sector 63.
+ *
+ * The boot sector is loaded to 0x7C00, i.e. over this code, so the MBR first
+ * relocates its whole sector to 0x0600 and continues from there. Data
+ * references (scratch, partition table, messages) are relative to the
+ * relocated copy via reloc_shift.
  */
 
 .code16
 .section .text
 
+	.equ reloc_base,  0x0600
+	.set reloc_shift, reloc_base - 0x7C00
+
 .globl _start
 _start:
-	/* Standard MBR jump */
-	.byte 0xEB, 0x44, 0x90
+	/* Standard MBR jump to mbr_start at offset 0x44 */
+	.byte 0xEB, 0x42, 0x90
 	.space 0x44 - 3, 0
 
 	.org 0x44
@@ -17,15 +25,25 @@ mbr_start:
 	cli
 	xorw  %ax, %ax
 	movw  %ax, %ds
+	movw  %ax, %es
 	movw  %ax, %ss
 	movw  $0x7c00, %sp
 	sti
 
+	/* Relocate this sector to 0x0600 and continue there. */
+	movw  $0x7c00, %si
+	movw  $reloc_base, %di
+	movw  $256, %cx
+	cld
+	rep movsw
+	ljmp  $0x0000, $relocated+reloc_shift
+
+relocated:
 	/* Save boot drive */
-	movb  %dl, boot_drive
+	movb  %dl, boot_drive+reloc_shift
 
 	/* Find active partition */
-	movw  $0x1BE, %si
+	movw  $part_table+reloc_shift, %si
 	movb  $4, %cl
 
 find_active:
@@ -36,14 +54,14 @@ find_active:
 	jnz   find_active
 
 	/* No active partition found */
-	movw  $no_boot_msg, %si
+	movw  $no_boot_msg+reloc_shift, %si
 	call  print_string
 	jmp   halt
 
 found_active:
 	/* Load boot sector from partition start LBA */
 	movl  8(%si), %eax        /* LBA start of partition */
-	movl  %eax, part_lba
+	movl  %eax, part_lba+reloc_shift
 
 	/* Read boot sector to 0x7C00 */
 	pushw %ds
@@ -51,7 +69,7 @@ found_active:
 	movw  $0x7C00, %bx
 
 read_boot_sector:
-	movl  part_lba, %eax
+	movl  part_lba+reloc_shift, %eax
 	call  read_sector_lba
 	jc    read_error
 
@@ -61,31 +79,29 @@ read_boot_sector:
 	jne   read_error
 
 	/* Jump to boot sector */
-	movb  boot_drive, %dl
+	movb  boot_drive+reloc_shift, %dl
 	ljmp  $0x0000, $0x7C00
 
 read_error:
-	movw  $read_err_msg, %si
+	movw  $read_err_msg+reloc_shift, %si
 	call  print_string
 	jmp   halt
 
-/* Read one sector from LBA using INT 0x13 AH=0x42 */
+/* Read one sector from LBA using INT 0x13 AH=0x42 (DS = 0) */
 read_sector_lba:
 	/* %eax = LBA, %es:%bx = buffer */
-	pushw %ds
-	movw  $0x500, %si
-	movw  %si, %ds
-	xorw  %di, %di
+	movw  $0x500, %di
 	movb  $0x10, (%di)        /* packet size */
-	movb  $1, 1(%di)          /* count = 1 */
+	movb  $0, 1(%di)          /* reserved */
+	movw  $1, 2(%di)          /* count = 1 */
 	movw  %bx, 4(%di)         /* buffer offset */
 	movw  %es, 6(%di)         /* buffer segment */
 	movl  %eax, 8(%di)        /* LBA */
-	xorl  12(%di), %eax       /* LBA high = 0 */
-	popw  %ds
+	movl  $0, 12(%di)         /* LBA high = 0 */
 
+	movw  $0x500, %si         /* DS:SI -> disk address packet */
 	movb  $0x42, %ah
-	movb  boot_drive, %dl
+	movb  boot_drive+reloc_shift, %dl
 	int   $0x13
 	ret
 
@@ -122,15 +138,31 @@ read_err_msg:
 	/* Pad to partition table at offset 0x1BE (446) */
 	.space 0x1BE - (. - _start), 0
 
-/* Partition table: one active partition at LBA 1 */
+part_table:
+	/* Partition 1: active, starts at LBA 63 (CHS 0/1/1, the classic DOS
+	 * start) and holds the boot sector (LBA 63) and kernel (LBA 64+).
+	 * The CHS values match the LBA values for the usual 255 heads /
+	 * 63 sectors geometry; BIOSes are known to validate that. */
 	.byte 0x80              /* bootable */
-	.byte 0x00, 0x01, 0x00  /* CHS start */
-	.byte 0x06              /* type: FAT16 LBA */
-	.byte 0xFF, 0xFF, 0xFF  /* CHS end */
-	.long 1                 /* LBA start (boot sector) */
-	.long 131071            /* sector count */
-	.space 48, 0            /* 3 empty entries */
-
-	/* Boot signature */
-.section .bootsig
+	.byte 0x01, 0x01, 0x00  /* CHS start: C=0 H=1 S=1 (LBA 63) */
+	.byte 0x06              /* type: FAT16 */
+	.byte 0xFE, 0x3F, 0x06  /* CHS end: C=6 H=254 S=63 (LBA 112454) */
+	.long 63                /* LBA start (boot sector) */
+	.long 112392            /* sector count */
+
+	/* Partition 2: dummy. Old AMI BIOSes (e.g. the ASUS AT3IONT-I)
+	 * classify a single-partition MBR as a USB-ZIP disk, which is never
+	 * offered as a hard-disk boot option; a second valid entry makes the
+	 * stick look like a USB hard disk (same trick RMPrepUSB/Easy2Boot
+	 * use). It is never booted: only partition 1 is active. */
+	.byte 0x00              /* not bootable */
+	.byte 0x00, 0x01, 0x07  /* CHS start: C=7 H=0 S=1 (LBA 112455) */
+	.byte 0x21              /* type: dummy */
+	.byte 0x28, 0x20, 0x08  /* CHS end: C=8 H=40 S=32 (LBA 131071) */
+	.long 112455
+	.long 18617
+	.space 32, 0            /* 2 empty entries */
+
+	/* Boot signature at offset 510 */
+	.space 510 - (. - _start), 0
 	.word 0xAA55

+ 4 - 6
mbr.ld

@@ -1,15 +1,13 @@
-/* MBR linker script: places code at offset 0 for raw binary output. */
+/* MBR: one 512-byte section at 0x7C00. mbr.S pads to offset 510 and emits
+ * the 0xAA55 signature inline, so objcopy -O binary yields exactly 512 bytes. */
 ENTRY(_start)
 
 SECTIONS
 {
-	. = 0x0;
-	.boot : AT(0x0) {
+	. = 0x7C00;
+	.boot : {
 		*(.text)
 		*(.rodata .rodata.*)
-		. = 0x1FE;
-		*(.bootsig)
-		. = 0x200;
 	}
 	/DISCARD/ : { *(.eh_frame) *(.note*) *(.comment) }
 }