Open5

ゼロからのOS自作入門メモ: 第1章

maeharinmaeharin

USBメモリの/EFI/BOOT/BOOTX64.EFI に配置とは仕様で決まってる?

以下のとおり、UEFIの仕様書に記載されている

https://uefi.org/specifications
のUEFI Specification Version 2.9 (March 2021)

maeharinmaeharin

okteta(バイナリエディタ)で入力してる謎の数値列は、PE32+ image formatのファイル

UEFIの仕様書で明記されている

UEFI uses a subset of the PE32+ image format with a modified header signature. The modification to the signature value in the PE32+ image is done to distinguish UEFI images from normal PE32 executables. The “+” addition to PE32 provides the 64-bit relocation fix-up extensions to standard PE32 format.

The PE Executable machine type is contained in the machine field of the COFF file header as
defined in the Microsoft Portable Executable and Common Object File Format Specification, Revision 6.0

PEファイルの仕様はこちら
https://docs.microsoft.com/ja-jp/windows/win32/debug/pe-format

  • イメージ = 実行ファイル
maeharinmaeharin

MS-DOS Stub (Image Only)
The MS-DOS stub is a valid application that runs under MS-DOS. It is placed at the front of the EXE image. The linker places a default stub here, which prints out the message "This program cannot be run in DOS mode" when the image is run in MS-DOS. The user can specify a different stub by using the /STUB linker option.

At location 0x3c, the stub has the file offset to the PE signature. This information enables Windows to properly execute the image file, even though it has an MS-DOS stub. This file offset is placed at location 0x3c during linking.

Signature (Image Only)
After the MS-DOS stub, at the file offset specified at offset 0x3c, is a 4-byte signature that identifies the file as a PE format image file. This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).

0x3c = 60バイト目に、PEシグネチャへのファイルのオフセットを記載するとのこと。PEシグネチャとは、そのファイルがPE形式であることを表す4バイトの識別子で PE\0\0

ここでoktetaで開いたバイナリを見てみると

60バイト目には 80 とある。0x80 = 128バイト。つまりファイルオフセット128バイトにPEシグネチャがあるはず。128バイト目をみると、そこから4バイトは50 45 00 00となっている。これはASCIIコードでPE\0\0。確かに仕様書通りになってる

https://www.k-cube.co.jp/wakaba/server/ascii_code.html

COFF File Header (Object and Image)
At the beginning of an object file, or immediately after the signature of an image file, is a standard COFF file header in the following format. Note that the Windows loader limits the number of sections to 96.

PEシグネチャの直後から、COFFファイルヘッダが始まる。最初の2バイトはMachineフィールドで、その実行ファイルがターゲットとする機器のMachine Typesを表す。

x64なら 0x8664 となるようだ。たしかに 64 86 となっている。0x8664は2バイト(マルチバイト)
なので、リトルエンディアンで64が先に来てる