// C# firmware application: only firmware-owned pool allocations and unmanaged
// pointers are used. No CLR, OS services, native application shim or GC is needed.
using System.Runtime.InteropServices;
namespace XFESystem.Boot
{
public static unsafe class EfiEntry
{
const ulong Error = 0x8000000000000000;
static nuint ErrorStatus(uint code) => unchecked((nuint)(Error | code));
[StructLayout(LayoutKind.Sequential)] struct Guid { public ulong Low, High; public Guid(ulong low, ulong high) { Low = low; High = high; } }
[StructLayout(LayoutKind.Sequential)] struct TableHeader { public ulong Signature; public uint Revision, HeaderSize, Crc32, Reserved; }
[StructLayout(LayoutKind.Sequential)] struct SystemTable
{
public TableHeader Header; public char* Vendor; public uint Revision;
public void* InputHandle; public Input* Input; public void* OutputHandle; public Output* Output;
public void* ErrorHandle; public Output* ErrorOutput; public void* Runtime; public BootServices* Boot;
public nuint TableCount; public void* Tables;
}
[StructLayout(LayoutKind.Sequential)] struct BootServices { public TableHeader Header; public fixed ulong Functions[44]; }
[StructLayout(LayoutKind.Sequential)] struct Output { public void* Reset; public delegate* unmanaged<Output*, char*, nuint> Write; public void* Test; public void* Query; public void* Set; public void* Attribute; public delegate* unmanaged<Output*, nuint> Clear; }
[StructLayout(LayoutKind.Sequential)] struct Key { public ushort Scan, Unicode; }
[StructLayout(LayoutKind.Sequential)] struct Input { public void* Reset; public delegate* unmanaged<Input*, Key*, nuint> Read; public void* Event; }
[StructLayout(LayoutKind.Sequential)] struct ModeInfo { public uint Version, Width, Height, Format, Red, Green, Blue, Reserved, Stride; }
[StructLayout(LayoutKind.Sequential)] struct GopMode { public uint Maximum, Current; public ModeInfo* Info; public nuint InfoBytes; public ulong Base; public nuint Bytes; }
[StructLayout(LayoutKind.Sequential)] struct Graphics { public delegate* unmanaged<Graphics*, uint, nuint*, ModeInfo**, nuint> Query; public delegate* unmanaged<Graphics*, uint, nuint> Set; public void* Blt; public GopMode* Mode; }
[StructLayout(LayoutKind.Sequential)] struct LoadedImage { public uint Revision; public void* Parent; public SystemTable* Table; public void* Device; public byte* Path; }
[StructLayout(LayoutKind.Sequential)] struct Edid { public uint Bytes; public byte* Data; }
[StructLayout(LayoutKind.Sequential)] struct ExitContext { public DisplayHandoff* Report; public fixed ulong Graphics[8]; }
static Guid GopGuid() => new Guid(0x4A3823DC9042A9DE, 0x6A5180D0DE7AFB96);
static Guid PciGuid() => new Guid(0x4CA568B84CF5B200, 0x9A02503F3EB2EC9E);
static Guid DevicePathGuid() => new Guid(0x11D26D3F09576E91, 0x3B7269C9A000398E);
static Guid LoadedImageGuid() => new Guid(0x11D295625B1B31A1, 0x3B7269C9A0003F8E);
static Guid ActiveEdidGuid() => new Guid(0x44EC9F36BD8C1056, 0x8679817F33A6A892);
static Guid DiscoveredEdidGuid() => new Guid(0x41FAD3801C0C34F6, 0xAA661A6CD08A49A0);
static Guid HandoffGuid() => new Guid(0x3150534958454644, 0x535953454658469C);
static void Zero(byte* data, nuint bytes) { for (nuint i = 0; i < bytes; i++) data[i] = 0; }
static void Copy(byte* source, byte* target, nuint bytes) { for (nuint i = 0; i < bytes; i++) target[i] = source[i]; }
static bool Equal(byte* first, byte* second, nuint bytes) { for (nuint i = 0; i < bytes; i++) if (first[i] != second[i]) return false; return true; }
static byte* Allocate(BootServices* boot, nuint bytes, uint kind)
{
byte* result = null;
return ((delegate* unmanaged<uint, nuint, byte**, nuint>)boot->Functions[5])(kind, bytes, &result) == 0 ? result : null;
}
static void Free(BootServices* boot, void* memory) { if (memory != null) ((delegate* unmanaged<void*, nuint>)boot->Functions[6])(memory); }
static void* Protocol(BootServices* boot, void* handle, Guid guid)
{
void* result = null;
return ((delegate* unmanaged<void*, Guid*, void**, nuint>)boot->Functions[16])(handle, &guid, &result) == 0 ? result : null;
}
static void** Handles(BootServices* boot, Guid guid, nuint* count)
{
void** list = null;
*count = 0;
if (((delegate* unmanaged<uint, Guid*, void*, nuint*, void***, nuint>)boot->Functions[36])(2, &guid, null, count, &list) != 0 || *count > 4096) return null;
return list;
}
static void Write(Output* output, string value) { if (output != null) { fixed (char* text = value) output->Write(output, text); } }
static void Number(Output* output, ulong value)
{
if (output == null) return;
char* text = stackalloc char[22];
int cursor = 21; text[cursor] = '\0';
do { text[--cursor] = (char)('0' + value % 10); value /= 10; } while (value != 0);
output->Write(output, text + cursor);
}
static void Stall(BootServices* boot, nuint microseconds) => ((delegate* unmanaged<nuint, nuint>)boot->Functions[28])(microseconds);
static bool ReadKey(SystemTable* table, Key* key) => table->Input != null && table->Input->Read(table->Input, key) == 0;
static DisplayRecord* Record(DisplayHandoff* report, uint index) => (DisplayRecord*)(report->Displays + index * 7520);
static DisplayMode* Modes(DisplayRecord* record) => (DisplayMode*)record->Modes;
static bool PciHeader(void* pci, byte* header) => ((delegate* unmanaged<void*, uint, uint, nuint, byte*, nuint>)((ulong*)pci)[6])(pci, 0, 0, 64, header) == 0;
static void CopyPath(BootServices* boot, void* handle, DisplayRecord* record)
{
byte* path = (byte*)Protocol(boot, handle, DevicePathGuid());
if (path == null) return;
uint cursor = 0;
while (cursor + 4 <= 256)
{
uint length = (uint)(path[cursor + 2] | path[cursor + 3] << 8);
if (length < 4 || cursor + length > 256) break;
Copy(path + cursor, record->Path + cursor, length);
bool end = path[cursor] == 0x7F;
cursor += length;
if (end) break;
}
record->PathBytes = cursor;
}
static void CopyEdid(BootServices* boot, void* handle, DisplayRecord* record)
{
for (uint source = 1; source <= 2; source++)
{
Edid* edid = (Edid*)Protocol(boot, handle, source == 1 ? ActiveEdidGuid() : DiscoveredEdidGuid());
if (edid == null || edid->Data == null || edid->Bytes < 128 || edid->Bytes > 4096) continue;
Copy(edid->Data, record->Edid, edid->Bytes); record->EdidBytes = edid->Bytes; record->EdidSource = source;
return;
}
}
static void ConnectDisplays(BootServices* boot, DisplayHandoff* report)
{
nuint count; void** list = Handles(boot, PciGuid(), &count);
if (list == null) return;
byte* header = stackalloc byte[64];
for (nuint i = 0; i < count; i++)
{
void* pci = Protocol(boot, list[i], PciGuid());
if (pci == null || !PciHeader(pci, header) || header[11] != 3) continue;
report->DisplayControllers++;
nuint result = ((delegate* unmanaged<void*, void**, byte*, byte, nuint>)boot->Functions[30])(list[i], null, null, 1);
if (result != 0 && result != ErrorStatus(14)) report->ConnectFailures++;
}
Free(boot, list);
}
static void QemuEdid(BootServices* boot, DisplayRecord* record)
{
if (record->PathBytes < 4) return;
nuint count; void** list = Handles(boot, PciGuid(), &count);
if (list == null) return;
byte* header = stackalloc byte[64];
DisplayRecord* path = (DisplayRecord*)Allocate(boot, (nuint)sizeof(DisplayRecord), 2);
if (path == null) { Free(boot, list); return; }
for (nuint i = 0; i < count; i++)
{
void* pci = Protocol(boot, list[i], PciGuid());
// The documented BAR2 read is restricted to QEMU standard VGA.
if (pci == null || !PciHeader(pci, header) || header[0] != 0x34 || header[1] != 0x12 || header[2] != 0x11 || header[3] != 0x11) continue;
Zero((byte*)path, (nuint)sizeof(DisplayRecord)); CopyPath(boot, list[i], path);
if (path->PathBytes < 4 || record->PathBytes < path->PathBytes - 4 || !Equal(path->Path, record->Path, path->PathBytes - 4)) continue;
var read = (delegate* unmanaged<void*, uint, byte, ulong, nuint, byte*, nuint>)((ulong*)pci)[2];
if (read(pci, 0, 2, 0, 128, record->Edid) != 0 || !DisplayPolicy.IsEdidValid(record->Edid, 128)) continue;
uint bytes = ((uint)record->Edid[126] + 1) * 128;
if (bytes > 1024) bytes = 1024;
if (bytes > 128 && read(pci, 0, 2, 0, bytes, record->Edid) != 0) continue;
record->EdidBytes = bytes; record->EdidSource = 3; break;
}
Free(boot, path); Free(boot, list);
}
static DisplayMode ModeRecord(uint id, ModeInfo* info)
{
uint bits = 0;
if (info->Format <= 1) bits = 32;
else if (info->Format == 2)
{
uint masks = info->Red | info->Green | info->Blue | info->Reserved;
while (masks != 0) { bits++; masks >>= 1; }
bits = (bits + 7) / 8 * 8;
}
DisplayMode result = new DisplayMode { Id = id, Width = info->Width, Height = info->Height, StridePixels = info->Stride, BitsPerPixel = bits, Flags = 1 };
if (!result.IsValid) result.Flags = 0;
return result;
}
static void Discover(BootServices* boot, DisplayHandoff* report, Graphics** graphics)
{
nuint count; void** list = Handles(boot, GopGuid(), &count);
if (list == null) return;
for (nuint i = 0; i < count; i++)
{
if (report->DisplayCount >= 8) { report->Flags |= 1; break; }
Graphics* gop = (Graphics*)Protocol(boot, list[i], GopGuid());
if (gop == null || gop->Mode == null) continue;
uint index = report->DisplayCount;
DisplayRecord* record = Record(report, index);
record->Handle = (ulong)list[i];
CopyPath(boot, list[i], record); CopyEdid(boot, list[i], record); QemuEdid(boot, record);
GopMode* state = gop->Mode;
record->OriginalMode = state->Current; record->FirmwareModeCount = state->Maximum;
uint maximum = state->Maximum < 4096 ? state->Maximum : 4096;
for (uint id = 0; id < maximum; id++)
{
nuint bytes = 0; ModeInfo* info = null;
if (gop->Query(gop, id, &bytes, &info) != 0 || info == null || bytes < (nuint)sizeof(ModeInfo)) continue;
DisplayMode mode = ModeRecord(id, info);
if (DisplayPolicy.EdidAdvertises(record->Edid, record->EdidBytes, mode.Width, mode.Height)) mode.Flags |= 4;
if (info != state->Info) Free(boot, info);
if (!mode.IsValid) continue;
if (record->ModeCount >= 128) { report->Flags |= 2; break; }
Modes(record)[record->ModeCount++] = mode;
}
record->SelectedMode = DisplayPolicy.ChooseMode(Modes(record), record->ModeCount, record->Edid, record->EdidBytes, record->OriginalMode);
if (record->ModeCount == 0 || state->Base == 0 || state->Bytes == 0) { Zero((byte*)record, (nuint)sizeof(DisplayRecord)); continue; }
record->FramebufferBase = state->Base; record->FramebufferBytes = (ulong)state->Bytes;
bool duplicate = false;
for (uint previous = 0; previous < index; previous++)
{
DisplayRecord* existing = Record(report, previous);
if (graphics[previous] != gop && existing->FramebufferBase != state->Base) continue;
if (record->EdidBytes > existing->EdidBytes || record->EdidBytes == existing->EdidBytes && record->PathBytes > existing->PathBytes)
{ Copy((byte*)record, (byte*)existing, (nuint)sizeof(DisplayRecord)); graphics[previous] = gop; }
Zero((byte*)record, (nuint)sizeof(DisplayRecord)); duplicate = true; break;
}
if (duplicate) continue;
graphics[index] = gop; report->DisplayCount++;
}
Free(boot, list);
}
static void Picker(SystemTable* table, DisplayHandoff* report)
{
Write(table->Output, "XFESystem: highest firmware resolution per display. Press F2 for display modes.\r\n");
bool open = false;
for (int i = 0; i < 100; i++)
{
Key key;
if (ReadKey(table, &key) && key.Scan == 12) { open = true; break; }
Stall(table->Boot, 10000);
}
if (!open || report->DisplayCount == 0) return;
uint index = 0;
while (true)
{
Output* output = table->Output;
if (output != null) output->Clear(output);
DisplayRecord* record = Record(report, index);
uint selected = 0;
for (uint i = 0; i < record->ModeCount; i++) if (Modes(record)[i].Id == record->SelectedMode) selected = i;
Write(output, "XFESystem display modes | Display "); Number(output, index + 1); Write(output, " of "); Number(output, report->DisplayCount);
Write(output, "\r\nLeft/Right: display Up/Down: resolution Enter: boot Esc: default maximum\r\n");
uint start = selected > 5 ? selected - 5 : 0;
for (uint i = start; i < record->ModeCount && i < start + 11; i++)
{
DisplayMode mode = Modes(record)[i]; Write(output, i == selected ? "> " : " ");
Number(output, mode.Id); Write(output, ": "); Number(output, mode.Width); Write(output, "x"); Number(output, mode.Height);
Write(output, " "); Number(output, mode.BitsPerPixel); Write(output, " bpp\r\n");
}
Key key;
while (!ReadKey(table, &key)) Stall(table->Boot, 10000);
if (key.Scan == 1 || key.Scan == 2)
{
uint next = key.Scan == 1 ? (selected > 0 ? selected - 1 : 0) : (selected + 1 < record->ModeCount ? selected + 1 : selected);
record->SelectedMode = Modes(record)[next].Id; record->Choice = 1;
}
else if (key.Scan == 3) index = (index + 1) % report->DisplayCount;
else if (key.Scan == 4) index = (index + report->DisplayCount - 1) % report->DisplayCount;
else if (key.Scan == 23)
{
for (uint i = 0; i < report->DisplayCount; i++)
{ DisplayRecord* current = Record(report, i); current->SelectedMode = DisplayPolicy.ChooseMode(Modes(current), current->ModeCount, current->Edid, current->EdidBytes, current->OriginalMode); current->Choice = 0; }
return;
}
else if (key.Unicode == 13) return;
}
}
static void Snapshot(DisplayRecord* record, Graphics* gop)
{
if (gop == null || gop->Mode == null) return;
GopMode* state = gop->Mode;
record->SelectedMode = state->Current; record->FramebufferBase = state->Base; record->FramebufferBytes = (ulong)state->Bytes;
if (state->Info == null || state->InfoBytes < (nuint)sizeof(ModeInfo)) return;
ModeInfo* info = state->Info;
record->Width = info->Width; record->Height = info->Height; record->StridePixels = info->Stride;
record->PixelFormat = info->Format; record->RedMask = info->Red; record->GreenMask = info->Green; record->BlueMask = info->Blue;
for (uint i = 0; i < record->ModeCount; i++)
{ DisplayMode* mode = Modes(record) + i; mode->Flags &= ~2u; if (mode->Id == state->Current) mode->Flags |= 2; }
}
static void Apply(DisplayHandoff* report, Graphics** graphics)
{
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i); Graphics* gop = graphics[i];
record->RequestedMode = record->SelectedMode;
nuint status = gop->Set(gop, record->SelectedMode); record->SetStatus = (uint)status;
if (status != 0) record->Flags |= 8;
Snapshot(record, gop);
}
}
static void SelectedModeHints(BootServices* boot, DisplayHandoff* report)
{
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i);
if (record->Width < 320 || record->Width > 4095 || record->Height < 200 || record->Height > 4095) continue;
byte* memory = Allocate(boot, (nuint)sizeof(Edid) + 128, 6);
if (memory == null) continue;
Zero(memory, (nuint)sizeof(Edid) + 128); byte* bytes = memory + sizeof(Edid);
if (record->EdidBytes >= 128) Copy(record->Edid, bytes, 128);
for (int j = 1; j < 7; j++) bytes[j] = 255;
bytes[0] = bytes[7] = 0; bytes[18] = 1; bytes[19] = 4; bytes[24] |= 2; bytes[126] = 0;
byte* detailed = bytes + 54; Zero(detailed, 18);
ulong clock = ((ulong)record->Width + 160) * ((ulong)record->Height + 45) * 60 / 10000;
if (clock < 1) clock = 1; if (clock > 65535) clock = 65535;
detailed[0] = (byte)clock; detailed[1] = (byte)(clock >> 8); detailed[2] = (byte)record->Width; detailed[3] = 160;
detailed[4] = (byte)((record->Width >> 8) << 4); detailed[5] = (byte)record->Height; detailed[6] = 45; detailed[7] = (byte)((record->Height >> 8) << 4);
byte sum = 0; for (int j = 0; j < 127; j++) sum = (byte)(sum + bytes[j]); bytes[127] = (byte)(0 - sum);
Edid* edid = (Edid*)memory; edid->Bytes = 128; edid->Data = bytes;
Guid guid = ActiveEdidGuid(); void* handle = (void*)record->Handle; void* old = Protocol(boot, handle, guid);
nuint status = old != null
? ((delegate* unmanaged<void*, Guid*, void*, void*, nuint>)boot->Functions[14])(handle, &guid, old, edid)
: ((delegate* unmanaged<void**, Guid*, uint, void*, nuint>)boot->Functions[13])(&handle, &guid, 0, edid);
// This synthetic bootloader preference is never a refresh measurement.
if (status == 0) record->Flags |= DisplayHandoff.SelectedModeHint; else Free(boot, memory);
}
}
[UnmanagedCallersOnly(EntryPoint = "XfeExitBootServices")]
static void Exited(void* eventHandle, void* pointer)
{
if (pointer == null) return;
ExitContext* context = (ExitContext*)pointer; DisplayHandoff* report = context->Report;
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i); Graphics* gop = (Graphics*)context->Graphics[i];
if (gop == null || gop->Mode == null || gop->Mode->Info == null || gop->Mode->InfoBytes < (nuint)sizeof(ModeInfo)) continue;
Snapshot(record, gop); record->Flags |= DisplayHandoff.FinalGeometry;
if (record->SelectedMode != record->RequestedMode) record->Flags |= DisplayHandoff.BootloaderChangedMode;
}
report->Flags |= DisplayHandoff.FinalGeometry;
}
static void FinalSnapshot(BootServices* boot, DisplayHandoff* report, Graphics** graphics)
{
ExitContext* context = (ExitContext*)Allocate(boot, (nuint)sizeof(ExitContext), 6);
if (context == null) return;
context->Report = report; for (int i = 0; i < 8; i++) context->Graphics[i] = (ulong)graphics[i];
void* eventHandle = null;
if (((delegate* unmanaged<uint, nuint, delegate* unmanaged<void*, void*, void>, void*, void**, nuint>)boot->Functions[7])(0x201, 16, &Exited, context, &eventHandle) != 0) Free(boot, context);
}
static nuint Chainload(BootServices* boot, void* image)
{
LoadedImage* loaded = (LoadedImage*)Protocol(boot, image, LoadedImageGuid());
if (loaded == null) return ErrorStatus(14);
byte* basePath = (byte*)Protocol(boot, loaded->Device, DevicePathGuid());
if (basePath == null) return ErrorStatus(14);
uint length = 0;
while (length + 4 <= 4096)
{
uint bytes = (uint)(basePath[length + 2] | basePath[length + 3] << 8);
if (bytes < 4 || length + bytes > 4096) return ErrorStatus(2);
if (basePath[length] == 0x7F) break;
length += bytes;
}
if (length + 4 > 4096) return ErrorStatus(2);
const string Filename = "\\EFI\\XFE\\LIMINE.EFI";
uint fileBytes = 4 + (uint)(Filename.Length + 1) * 2, total = length + fileBytes + 4;
byte* path = Allocate(boot, total, 2);
if (path == null) return ErrorStatus(9);
Zero(path, total); Copy(basePath, path, length);
path[length] = 4; path[length + 1] = 4; path[length + 2] = (byte)fileBytes; path[length + 3] = (byte)(fileBytes >> 8);
fixed (char* filename = Filename) Copy((byte*)filename, path + length + 4, fileBytes - 4);
path[total - 4] = 0x7F; path[total - 3] = 0xFF; path[total - 2] = 4;
void* child = null;
nuint status = ((delegate* unmanaged<byte, void*, byte*, byte*, nuint, void**, nuint>)boot->Functions[22])(0, image, path, null, 0, &child);
Free(boot, path);
return status == 0 ? ((delegate* unmanaged<void*, nuint*, char**, nuint>)boot->Functions[23])(child, null, null) : status;
}
[UnmanagedCallersOnly(EntryPoint = "XfeEfiMain")]
public static nuint Enter(void* image, void* pointer)
{
SystemTable* table = (SystemTable*)pointer;
if (table == null || table->Boot == null) return ErrorStatus(2);
BootServices* boot = table->Boot;
((delegate* unmanaged<nuint, ulong, nuint, char*, nuint>)boot->Functions[29])(0, 0, 0, null);
DisplayHandoff* report = (DisplayHandoff*)Allocate(boot, (nuint)sizeof(DisplayHandoff), 6);
if (report == null) return ErrorStatus(9);
Zero((byte*)report, (nuint)sizeof(DisplayHandoff)); report->Magic = 0x3150534944454658; report->Version = 1; report->Bytes = (uint)sizeof(DisplayHandoff);
// Constant byte allocation avoids the zero-library compiler's
// unnecessary checked pointer-element multiplication helper.
byte* graphicsStorage = stackalloc byte[64]; Graphics** graphics = (Graphics**)graphicsStorage;
for (int i = 0; i < 8; i++) graphics[i] = null;
ConnectDisplays(boot, report); Discover(boot, report, graphics); Picker(table, report); Apply(report, graphics); SelectedModeHints(boot, report);
Guid handoff = HandoffGuid();
nuint status = ((delegate* unmanaged<Guid*, void*, nuint>)boot->Functions[21])(&handoff, report);
if (status != 0) return status;
FinalSnapshot(boot, report, graphics);
status = Chainload(boot, image);
Write(table->Output, "XFESystem could not start EFI/XFE/LIMINE.EFI: "); Number(table->Output, (ulong)status); Write(table->Output, "\r\n");
return status;
}
// bflat requires a managed entry point to produce an executable. Firmware
// enters XfeEfiMain directly; no zero-library startup state is used.
public static int Main() => 0;
}
}
// C# firmware application: only firmware-owned pool allocations and unmanaged
// pointers are used. No CLR, OS services, native application shim or GC is needed.
using System.Runtime.InteropServices;
namespace XFESystem.Boot
{
public static unsafe class EfiEntry
{
const ulong Error = 0x8000000000000000;
static nuint ErrorStatus(uint code) => unchecked((nuint)(Error | code));
[StructLayout(LayoutKind.Sequential)] struct Guid { public ulong Low, High; public Guid(ulong low, ulong high) { Low = low; High = high; } }
[StructLayout(LayoutKind.Sequential)] struct TableHeader { public ulong Signature; public uint Revision, HeaderSize, Crc32, Reserved; }
[StructLayout(LayoutKind.Sequential)] struct SystemTable
{
public TableHeader Header; public char* Vendor; public uint Revision;
public void* InputHandle; public Input* Input; public void* OutputHandle; public Output* Output;
public void* ErrorHandle; public Output* ErrorOutput; public void* Runtime; public BootServices* Boot;
public nuint TableCount; public void* Tables;
}
[StructLayout(LayoutKind.Sequential)] struct BootServices { public TableHeader Header; public fixed ulong Functions[44]; }
[StructLayout(LayoutKind.Sequential)] struct Output { public void* Reset; public delegate* unmanaged<Output*, char*, nuint> Write; public void* Test; public void* Query; public void* Set; public void* Attribute; public delegate* unmanaged<Output*, nuint> Clear; }
[StructLayout(LayoutKind.Sequential)] struct Key { public ushort Scan, Unicode; }
[StructLayout(LayoutKind.Sequential)] struct Input { public void* Reset; public delegate* unmanaged<Input*, Key*, nuint> Read; public void* Event; }
[StructLayout(LayoutKind.Sequential)] struct ModeInfo { public uint Version, Width, Height, Format, Red, Green, Blue, Reserved, Stride; }
[StructLayout(LayoutKind.Sequential)] struct GopMode { public uint Maximum, Current; public ModeInfo* Info; public nuint InfoBytes; public ulong Base; public nuint Bytes; }
[StructLayout(LayoutKind.Sequential)] struct Graphics { public delegate* unmanaged<Graphics*, uint, nuint*, ModeInfo**, nuint> Query; public delegate* unmanaged<Graphics*, uint, nuint> Set; public void* Blt; public GopMode* Mode; }
[StructLayout(LayoutKind.Sequential)] struct LoadedImage { public uint Revision; public void* Parent; public SystemTable* Table; public void* Device; public byte* Path; }
[StructLayout(LayoutKind.Sequential)] struct Edid { public uint Bytes; public byte* Data; }
[StructLayout(LayoutKind.Sequential)] struct ExitContext { public DisplayHandoff* Report; public fixed ulong Graphics[8]; }
static Guid GopGuid() => new Guid(0x4A3823DC9042A9DE, 0x6A5180D0DE7AFB96);
static Guid PciGuid() => new Guid(0x4CA568B84CF5B200, 0x9A02503F3EB2EC9E);
static Guid DevicePathGuid() => new Guid(0x11D26D3F09576E91, 0x3B7269C9A000398E);
static Guid LoadedImageGuid() => new Guid(0x11D295625B1B31A1, 0x3B7269C9A0003F8E);
static Guid ActiveEdidGuid() => new Guid(0x44EC9F36BD8C1056, 0x8679817F33A6A892);
static Guid DiscoveredEdidGuid() => new Guid(0x41FAD3801C0C34F6, 0xAA661A6CD08A49A0);
static Guid HandoffGuid() => new Guid(0x3150534958454644, 0x535953454658469C);
static void Zero(byte* data, nuint bytes) { for (nuint i = 0; i < bytes; i++) data[i] = 0; }
static void Copy(byte* source, byte* target, nuint bytes) { for (nuint i = 0; i < bytes; i++) target[i] = source[i]; }
static bool Equal(byte* first, byte* second, nuint bytes) { for (nuint i = 0; i < bytes; i++) if (first[i] != second[i]) return false; return true; }
static byte* Allocate(BootServices* boot, nuint bytes, uint kind)
{
byte* result = null;
return ((delegate* unmanaged<uint, nuint, byte**, nuint>)boot->Functions[5])(kind, bytes, &result) == 0 ? result : null;
}
static void Free(BootServices* boot, void* memory) { if (memory != null) ((delegate* unmanaged<void*, nuint>)boot->Functions[6])(memory); }
static void* Protocol(BootServices* boot, void* handle, Guid guid)
{
void* result = null;
return ((delegate* unmanaged<void*, Guid*, void**, nuint>)boot->Functions[16])(handle, &guid, &result) == 0 ? result : null;
}
static void** Handles(BootServices* boot, Guid guid, nuint* count)
{
void** list = null;
*count = 0;
if (((delegate* unmanaged<uint, Guid*, void*, nuint*, void***, nuint>)boot->Functions[36])(2, &guid, null, count, &list) != 0 || *count > 4096) return null;
return list;
}
static void Write(Output* output, string value) { if (output != null) { fixed (char* text = value) output->Write(output, text); } }
static void Number(Output* output, ulong value)
{
if (output == null) return;
char* text = stackalloc char[22];
int cursor = 21; text[cursor] = '\0';
do { text[--cursor] = (char)('0' + value % 10); value /= 10; } while (value != 0);
output->Write(output, text + cursor);
}
static void Stall(BootServices* boot, nuint microseconds) => ((delegate* unmanaged<nuint, nuint>)boot->Functions[28])(microseconds);
static bool ReadKey(SystemTable* table, Key* key) => table->Input != null && table->Input->Read(table->Input, key) == 0;
static DisplayRecord* Record(DisplayHandoff* report, uint index) => (DisplayRecord*)(report->Displays + index * 7520);
static DisplayMode* Modes(DisplayRecord* record) => (DisplayMode*)record->Modes;
static bool PciHeader(void* pci, byte* header) => ((delegate* unmanaged<void*, uint, uint, nuint, byte*, nuint>)((ulong*)pci)[6])(pci, 0, 0, 64, header) == 0;
static void CopyPath(BootServices* boot, void* handle, DisplayRecord* record)
{
byte* path = (byte*)Protocol(boot, handle, DevicePathGuid());
if (path == null) return;
uint cursor = 0;
while (cursor + 4 <= 256)
{
uint length = (uint)(path[cursor + 2] | path[cursor + 3] << 8);
if (length < 4 || cursor + length > 256) break;
Copy(path + cursor, record->Path + cursor, length);
bool end = path[cursor] == 0x7F;
cursor += length;
if (end) break;
}
record->PathBytes = cursor;
}
static void CopyEdid(BootServices* boot, void* handle, DisplayRecord* record)
{
for (uint source = 1; source <= 2; source++)
{
Edid* edid = (Edid*)Protocol(boot, handle, source == 1 ? ActiveEdidGuid() : DiscoveredEdidGuid());
if (edid == null || edid->Data == null || edid->Bytes < 128 || edid->Bytes > 4096) continue;
Copy(edid->Data, record->Edid, edid->Bytes); record->EdidBytes = edid->Bytes; record->EdidSource = source;
return;
}
}
static void ConnectDisplays(BootServices* boot, DisplayHandoff* report)
{
nuint count; void** list = Handles(boot, PciGuid(), &count);
if (list == null) return;
byte* header = stackalloc byte[64];
for (nuint i = 0; i < count; i++)
{
void* pci = Protocol(boot, list[i], PciGuid());
if (pci == null || !PciHeader(pci, header) || header[11] != 3) continue;
report->DisplayControllers++;
nuint result = ((delegate* unmanaged<void*, void**, byte*, byte, nuint>)boot->Functions[30])(list[i], null, null, 1);
if (result != 0 && result != ErrorStatus(14)) report->ConnectFailures++;
}
Free(boot, list);
}
static void QemuEdid(BootServices* boot, DisplayRecord* record)
{
if (record->PathBytes < 4) return;
nuint count; void** list = Handles(boot, PciGuid(), &count);
if (list == null) return;
byte* header = stackalloc byte[64];
DisplayRecord* path = (DisplayRecord*)Allocate(boot, (nuint)sizeof(DisplayRecord), 2);
if (path == null) { Free(boot, list); return; }
for (nuint i = 0; i < count; i++)
{
void* pci = Protocol(boot, list[i], PciGuid());
// The documented BAR2 read is restricted to QEMU standard VGA.
if (pci == null || !PciHeader(pci, header) || header[0] != 0x34 || header[1] != 0x12 || header[2] != 0x11 || header[3] != 0x11) continue;
Zero((byte*)path, (nuint)sizeof(DisplayRecord)); CopyPath(boot, list[i], path);
if (path->PathBytes < 4 || record->PathBytes < path->PathBytes - 4 || !Equal(path->Path, record->Path, path->PathBytes - 4)) continue;
var read = (delegate* unmanaged<void*, uint, byte, ulong, nuint, byte*, nuint>)((ulong*)pci)[2];
if (read(pci, 0, 2, 0, 128, record->Edid) != 0 || !DisplayPolicy.IsEdidValid(record->Edid, 128)) continue;
uint bytes = ((uint)record->Edid[126] + 1) * 128;
if (bytes > 1024) bytes = 1024;
if (bytes > 128 && read(pci, 0, 2, 0, bytes, record->Edid) != 0) continue;
record->EdidBytes = bytes; record->EdidSource = 3; break;
}
Free(boot, path); Free(boot, list);
}
static DisplayMode ModeRecord(uint id, ModeInfo* info)
{
uint bits = 0;
if (info->Format <= 1) bits = 32;
else if (info->Format == 2)
{
uint masks = info->Red | info->Green | info->Blue | info->Reserved;
while (masks != 0) { bits++; masks >>= 1; }
bits = (bits + 7) / 8 * 8;
}
DisplayMode result = new DisplayMode { Id = id, Width = info->Width, Height = info->Height, StridePixels = info->Stride, BitsPerPixel = bits, Flags = 1 };
if (!result.IsValid) result.Flags = 0;
return result;
}
static void Discover(BootServices* boot, DisplayHandoff* report, Graphics** graphics)
{
nuint count; void** list = Handles(boot, GopGuid(), &count);
if (list == null) return;
for (nuint i = 0; i < count; i++)
{
if (report->DisplayCount >= 8) { report->Flags |= 1; break; }
Graphics* gop = (Graphics*)Protocol(boot, list[i], GopGuid());
if (gop == null || gop->Mode == null) continue;
uint index = report->DisplayCount;
DisplayRecord* record = Record(report, index);
record->Handle = (ulong)list[i];
CopyPath(boot, list[i], record); CopyEdid(boot, list[i], record); QemuEdid(boot, record);
GopMode* state = gop->Mode;
record->OriginalMode = state->Current; record->FirmwareModeCount = state->Maximum;
uint maximum = state->Maximum < 4096 ? state->Maximum : 4096;
for (uint id = 0; id < maximum; id++)
{
nuint bytes = 0; ModeInfo* info = null;
if (gop->Query(gop, id, &bytes, &info) != 0 || info == null || bytes < (nuint)sizeof(ModeInfo)) continue;
DisplayMode mode = ModeRecord(id, info);
if (DisplayPolicy.EdidAdvertises(record->Edid, record->EdidBytes, mode.Width, mode.Height)) mode.Flags |= 4;
if (info != state->Info) Free(boot, info);
if (!mode.IsValid) continue;
if (record->ModeCount >= 128) { report->Flags |= 2; break; }
Modes(record)[record->ModeCount++] = mode;
}
record->SelectedMode = DisplayPolicy.ChooseMode(Modes(record), record->ModeCount, record->Edid, record->EdidBytes, record->OriginalMode);
if (record->ModeCount == 0 || state->Base == 0 || state->Bytes == 0) { Zero((byte*)record, (nuint)sizeof(DisplayRecord)); continue; }
record->FramebufferBase = state->Base; record->FramebufferBytes = (ulong)state->Bytes;
bool duplicate = false;
for (uint previous = 0; previous < index; previous++)
{
DisplayRecord* existing = Record(report, previous);
if (graphics[previous] != gop && existing->FramebufferBase != state->Base) continue;
if (record->EdidBytes > existing->EdidBytes || record->EdidBytes == existing->EdidBytes && record->PathBytes > existing->PathBytes)
{ Copy((byte*)record, (byte*)existing, (nuint)sizeof(DisplayRecord)); graphics[previous] = gop; }
Zero((byte*)record, (nuint)sizeof(DisplayRecord)); duplicate = true; break;
}
if (duplicate) continue;
graphics[index] = gop; report->DisplayCount++;
}
Free(boot, list);
}
static void Picker(SystemTable* table, DisplayHandoff* report)
{
Write(table->Output, "XFESystem: highest firmware resolution per display. Press F2 for display modes.\r\n");
bool open = false;
for (int i = 0; i < 100; i++)
{
Key key;
if (ReadKey(table, &key) && key.Scan == 12) { open = true; break; }
Stall(table->Boot, 10000);
}
if (!open || report->DisplayCount == 0) return;
uint index = 0;
while (true)
{
Output* output = table->Output;
if (output != null) output->Clear(output);
DisplayRecord* record = Record(report, index);
uint selected = 0;
for (uint i = 0; i < record->ModeCount; i++) if (Modes(record)[i].Id == record->SelectedMode) selected = i;
Write(output, "XFESystem display modes | Display "); Number(output, index + 1); Write(output, " of "); Number(output, report->DisplayCount);
Write(output, "\r\nLeft/Right: display Up/Down: resolution Enter: boot Esc: default maximum\r\n");
uint start = selected > 5 ? selected - 5 : 0;
for (uint i = start; i < record->ModeCount && i < start + 11; i++)
{
DisplayMode mode = Modes(record)[i]; Write(output, i == selected ? "> " : " ");
Number(output, mode.Id); Write(output, ": "); Number(output, mode.Width); Write(output, "x"); Number(output, mode.Height);
Write(output, " "); Number(output, mode.BitsPerPixel); Write(output, " bpp\r\n");
}
Key key;
while (!ReadKey(table, &key)) Stall(table->Boot, 10000);
if (key.Scan == 1 || key.Scan == 2)
{
uint next = key.Scan == 1 ? (selected > 0 ? selected - 1 : 0) : (selected + 1 < record->ModeCount ? selected + 1 : selected);
record->SelectedMode = Modes(record)[next].Id; record->Choice = 1;
}
else if (key.Scan == 3) index = (index + 1) % report->DisplayCount;
else if (key.Scan == 4) index = (index + report->DisplayCount - 1) % report->DisplayCount;
else if (key.Scan == 23)
{
for (uint i = 0; i < report->DisplayCount; i++)
{ DisplayRecord* current = Record(report, i); current->SelectedMode = DisplayPolicy.ChooseMode(Modes(current), current->ModeCount, current->Edid, current->EdidBytes, current->OriginalMode); current->Choice = 0; }
return;
}
else if (key.Unicode == 13) return;
}
}
static void Snapshot(DisplayRecord* record, Graphics* gop)
{
if (gop == null || gop->Mode == null) return;
GopMode* state = gop->Mode;
record->SelectedMode = state->Current; record->FramebufferBase = state->Base; record->FramebufferBytes = (ulong)state->Bytes;
if (state->Info == null || state->InfoBytes < (nuint)sizeof(ModeInfo)) return;
ModeInfo* info = state->Info;
record->Width = info->Width; record->Height = info->Height; record->StridePixels = info->Stride;
record->PixelFormat = info->Format; record->RedMask = info->Red; record->GreenMask = info->Green; record->BlueMask = info->Blue;
for (uint i = 0; i < record->ModeCount; i++)
{ DisplayMode* mode = Modes(record) + i; mode->Flags &= ~2u; if (mode->Id == state->Current) mode->Flags |= 2; }
}
static void Apply(DisplayHandoff* report, Graphics** graphics)
{
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i); Graphics* gop = graphics[i];
record->RequestedMode = record->SelectedMode;
nuint status = gop->Set(gop, record->SelectedMode); record->SetStatus = (uint)status;
if (status != 0) record->Flags |= 8;
Snapshot(record, gop);
}
}
static void SelectedModeHints(BootServices* boot, DisplayHandoff* report)
{
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i);
if (record->Width < 320 || record->Width > 4095 || record->Height < 200 || record->Height > 4095) continue;
byte* memory = Allocate(boot, (nuint)sizeof(Edid) + 128, 6);
if (memory == null) continue;
Zero(memory, (nuint)sizeof(Edid) + 128); byte* bytes = memory + sizeof(Edid);
if (record->EdidBytes >= 128) Copy(record->Edid, bytes, 128);
for (int j = 1; j < 7; j++) bytes[j] = 255;
bytes[0] = bytes[7] = 0; bytes[18] = 1; bytes[19] = 4; bytes[24] |= 2; bytes[126] = 0;
byte* detailed = bytes + 54; Zero(detailed, 18);
ulong clock = ((ulong)record->Width + 160) * ((ulong)record->Height + 45) * 60 / 10000;
if (clock < 1) clock = 1; if (clock > 65535) clock = 65535;
detailed[0] = (byte)clock; detailed[1] = (byte)(clock >> 8); detailed[2] = (byte)record->Width; detailed[3] = 160;
detailed[4] = (byte)((record->Width >> 8) << 4); detailed[5] = (byte)record->Height; detailed[6] = 45; detailed[7] = (byte)((record->Height >> 8) << 4);
byte sum = 0; for (int j = 0; j < 127; j++) sum = (byte)(sum + bytes[j]); bytes[127] = (byte)(0 - sum);
Edid* edid = (Edid*)memory; edid->Bytes = 128; edid->Data = bytes;
Guid guid = ActiveEdidGuid(); void* handle = (void*)record->Handle; void* old = Protocol(boot, handle, guid);
nuint status = old != null
? ((delegate* unmanaged<void*, Guid*, void*, void*, nuint>)boot->Functions[14])(handle, &guid, old, edid)
: ((delegate* unmanaged<void**, Guid*, uint, void*, nuint>)boot->Functions[13])(&handle, &guid, 0, edid);
// This synthetic bootloader preference is never a refresh measurement.
if (status == 0) record->Flags |= DisplayHandoff.SelectedModeHint; else Free(boot, memory);
}
}
[UnmanagedCallersOnly(EntryPoint = "XfeExitBootServices")]
static void Exited(void* eventHandle, void* pointer)
{
if (pointer == null) return;
ExitContext* context = (ExitContext*)pointer; DisplayHandoff* report = context->Report;
for (uint i = 0; i < report->DisplayCount; i++)
{
DisplayRecord* record = Record(report, i); Graphics* gop = (Graphics*)context->Graphics[i];
if (gop == null || gop->Mode == null || gop->Mode->Info == null || gop->Mode->InfoBytes < (nuint)sizeof(ModeInfo)) continue;
Snapshot(record, gop); record->Flags |= DisplayHandoff.FinalGeometry;
if (record->SelectedMode != record->RequestedMode) record->Flags |= DisplayHandoff.BootloaderChangedMode;
}
report->Flags |= DisplayHandoff.FinalGeometry;
}
static void FinalSnapshot(BootServices* boot, DisplayHandoff* report, Graphics** graphics)
{
ExitContext* context = (ExitContext*)Allocate(boot, (nuint)sizeof(ExitContext), 6);
if (context == null) return;
context->Report = report; for (int i = 0; i < 8; i++) context->Graphics[i] = (ulong)graphics[i];
void* eventHandle = null;
if (((delegate* unmanaged<uint, nuint, delegate* unmanaged<void*, void*, void>, void*, void**, nuint>)boot->Functions[7])(0x201, 16, &Exited, context, &eventHandle) != 0) Free(boot, context);
}
static nuint Chainload(BootServices* boot, void* image)
{
LoadedImage* loaded = (LoadedImage*)Protocol(boot, image, LoadedImageGuid());
if (loaded == null) return ErrorStatus(14);
byte* basePath = (byte*)Protocol(boot, loaded->Device, DevicePathGuid());
if (basePath == null) return ErrorStatus(14);
uint length = 0;
while (length + 4 <= 4096)
{
uint bytes = (uint)(basePath[length + 2] | basePath[length + 3] << 8);
if (bytes < 4 || length + bytes > 4096) return ErrorStatus(2);
if (basePath[length] == 0x7F) break;
length += bytes;
}
if (length + 4 > 4096) return ErrorStatus(2);
const string Filename = "\\EFI\\XFE\\LIMINE.EFI";
uint fileBytes = 4 + (uint)(Filename.Length + 1) * 2, total = length + fileBytes + 4;
byte* path = Allocate(boot, total, 2);
if (path == null) return ErrorStatus(9);
Zero(path, total); Copy(basePath, path, length);
path[length] = 4; path[length + 1] = 4; path[length + 2] = (byte)fileBytes; path[length + 3] = (byte)(fileBytes >> 8);
fixed (char* filename = Filename) Copy((byte*)filename, path + length + 4, fileBytes - 4);
path[total - 4] = 0x7F; path[total - 3] = 0xFF; path[total - 2] = 4;
void* child = null;
nuint status = ((delegate* unmanaged<byte, void*, byte*, byte*, nuint, void**, nuint>)boot->Functions[22])(0, image, path, null, 0, &child);
Free(boot, path);
return status == 0 ? ((delegate* unmanaged<void*, nuint*, char**, nuint>)boot->Functions[23])(child, null, null) : status;
}
[UnmanagedCallersOnly(EntryPoint = "XfeEfiMain")]
public static nuint Enter(void* image, void* pointer)
{
SystemTable* table = (SystemTable*)pointer;
if (table == null || table->Boot == null) return ErrorStatus(2);
BootServices* boot = table->Boot;
((delegate* unmanaged<nuint, ulong, nuint, char*, nuint>)boot->Functions[29])(0, 0, 0, null);
DisplayHandoff* report = (DisplayHandoff*)Allocate(boot, (nuint)sizeof(DisplayHandoff), 6);
if (report == null) return ErrorStatus(9);
Zero((byte*)report, (nuint)sizeof(DisplayHandoff)); report->Magic = 0x3150534944454658; report->Version = 1; report->Bytes = (uint)sizeof(DisplayHandoff);
// Constant byte allocation avoids the zero-library compiler's
// unnecessary checked pointer-element multiplication helper.
byte* graphicsStorage = stackalloc byte[64]; Graphics** graphics = (Graphics**)graphicsStorage;
for (int i = 0; i < 8; i++) graphics[i] = null;
ConnectDisplays(boot, report); Discover(boot, report, graphics); Picker(table, report); Apply(report, graphics); SelectedModeHints(boot, report);
Guid handoff = HandoffGuid();
nuint status = ((delegate* unmanaged<Guid*, void*, nuint>)boot->Functions[21])(&handoff, report);
if (status != 0) return status;
FinalSnapshot(boot, report, graphics);
status = Chainload(boot, image);
Write(table->Output, "XFESystem could not start EFI/XFE/LIMINE.EFI: "); Number(table->Output, (ulong)status); Write(table->Output, "\r\n");
return status;
}
// bflat requires a managed entry point to produce an executable. Firmware
// enters XfeEfiMain directly; no zero-library startup state is used.
public static int Main() => 0;
}
}