Newer
Older
AMI-Aptio-BIOS-Reversed / HardwareSignatureEntry / HardwareSignatureEntry.c
@Ajax Dong Ajax Dong 2 days ago 27 KB Init
/** @file
  HardwareSignatureEntry.c -- Reverse-engineered DXE driver implementation

  Module:   HardwareSignatureEntry
  File:     0310_HardwareSignatureEntry.efi (406b8bdd5c50)
  PDB:      e:\hs\Build\HR6N0XMLK\DEBUG_VS2015\X64\AmiModulePkg\HardwareSignature\
              HardwareSignatureEntry\DEBUG\HardwareSignatureEntry.pdb
  Compiler: MSVC VS2015, X64, DEBUG
  Image:    0x0000 -- 0x2040 (8 KB)

  This driver belongs to the AmiModulePkg (AMI's BIOS adaptation layer)
  and implements the platform "Hardware Signature" feature for the
  Lenovo HR650X.

  == PURPOSE ==

  The UEFI specification (and Windows requirements for Secure Boot /
  BitLocker) expect the firmware to maintain a "hardware signature" --
  a value that changes whenever the physical hardware configuration is
  altered.  Windows uses this to decide whether to re-lock BitLocker or
  invalidate a saved memory dump.

  This driver connects to the HII subsystem's hardware-configuration
  formset and installs a notification callback.  When the formset is
  displayed or refreshed, the callback:

    1. Reads the current physical memory size from the UEFI memory map.
    2. Reads a hardware-status byte from a platform-specific source.
    3. Reads a hardware-configuration DWORD.
    4. Checks the CMOS status / checksum for battery-backed changes.
    5. Reads a firmware/hardware capability DWORD.
    6. Sorts any recorded hardware-change codes.
    7. Reads the previous "AmiHardwareSignatureSetupUpdateCountVar" UEFI
       variable.
    8. Writes the updated count back into the formset storage.

  The result is that the hardware signature stored in NVRAM is kept in
  sync with the real platform state.

  Copyright (C) Lenovo  (this is a reverse-engineered representation).
**/

#include "HardwareSignatureEntry.h"
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>

// ===========================================================================
// Globals
// ===========================================================================

//
// Standard UEFI globals from library constructors.
//
extern EFI_HANDLE             gImageHandle;
extern EFI_SYSTEM_TABLE       *gST;
extern EFI_BOOT_SERVICES      *gBS;
extern EFI_RUNTIME_SERVICES   *gRT;

//
// Module-level writable state  (.data: 0x1C60 -- 0x1E40)
//
UINT32                        gChangeListIndex          = 0;   // 0x1D80
UINT32                        gHardwareSignatureFlags   = 0;   // 0x1D84
EFI_HII_DATABASE_PROTOCOL     *gHiiDatabase             = NULL;// 0x1DA8
VOID                          *gHobList                 = NULL;// 0x1DB0
BOOLEAN                       gMemorySizeCached         = FALSE;//0x1DB8
UINT8                         gHardwareConfigVarStore[120];   // 0x1DC0
UINT8                         gHardwareStatusByte       = 0;   // 0x1DC4
UINT32                        gTotalMemoryMb            = 0;   // 0x1DC8
UINT32                        gHardwareConfigDword      = 0;   // 0x1DCC
UINT16                        gCmosChecksum             = 0;   // 0x1DD4
UINT32                        gFirmwareCapabilityDword  = 0;   // 0x1DD8
UINT32                        gUpdateCount              = 0;   // 0x1DDC
UINT32                        gChangeList[0x14];               // 0x1DE0
UINT64                        gMemorySizePacked         = 0;   // 0x1E38
UINT32                        gMemorySizeMb             = 0;   // 0x1E3C

//
// Signature computation constants
//
const INT32                   gHardwareSignatureMagic   = 117704678;  // 0x1E30
const INT16                   gHardwareSignatureVersion = 10006;      // 0x1E34
const UINT8                   gHardwareSignatureYear    = 14;         // 0x1E36 (2014)

// ---------------------------------------------------------------------------
// InternalCopyMem   (sub_2C0)
//   addr: 0x2C0  size: 0x42
//   Implements memmove: handles forward/backward overlap.
// ---------------------------------------------------------------------------
VOID *
EFIAPI
InternalCopyMem (
  OUT VOID       *DestinationBuffer,
  IN  CONST VOID *SourceBuffer,
  IN  UINTN      Length
  )
{
  //
  // The decompiled code shows:
  //   - If SourceBuffer < DestinationBuffer and
  //     &SourceBuffer[Length-1] >= DestinationBuffer, copy backward
  //     from &dest[Length-1] down to dest[0].
  //   - Else copy forward 8 bytes at a time via qmemcpy for the
  //     Length >> 3 chunk, then the Length & 7 remainder.
  //
  return (CHAR8 *)CopyMem (DestinationBuffer, SourceBuffer, Length);
}

// ---------------------------------------------------------------------------
// ModuleEntryPoint  (sub_384)
//   addr: 0x384  size: 0xA9
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
ModuleEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  //
  // UEFI library constructors initialise ImageHandle, SystemTable,
  // BootServices, RuntimeServices globals (linked from
  // UefiBootServicesTableLib / UefiRuntimeServicesTableLib).
  //
  // Then:
  //   - Assert(!ImageHandle)  -> DebugAssert
  //   - Assert(!SystemTable)  -> DebugAssert
  //   - Assert(!BootServices) -> DebugAssert
  //   - Assert(!RuntimeServices) -> DebugAssert
  //   - GetHobList() to initialise HOB pointer
  //   - HiiHardwareSignatureEntry(ImageHandle, NULL)
  //
  return HiiHardwareSignatureEntry (ImageHandle, NULL);
}

// ---------------------------------------------------------------------------
// HiiHardwareSignatureEntry  (sub_430)
//   addr: 0x430  size: 0x100
//
//   Installs the HII Config Access protocol on a child handle and
//   registers the notification callback (HardwareSignatureNotificationCallback)
//   for the hardware-configuration formset.
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
HiiHardwareSignatureEntry (
  IN EFI_HANDLE  ImageHandle,
  IN EFI_HANDLE  DriverHandle OPTIONAL
  )
{
  EFI_STATUS     Status;
  EFI_HANDLE     ChildHandle;
  VOID           *Registration;
  EFI_HANDLE     ControllerHandle;

  ChildHandle = NULL;
  ControllerHandle = DriverHandle;

  //
  // Zero the config-variable store (120 bytes).
  //
  gBS->SetMem (&gHardwareConfigVarStore, sizeof (gHardwareConfigVarStore), 0);

  //
  // Install Config Access protocol on a new child handle.
  //
  Status = gBS->InstallProtocolInterface (
                  &ChildHandle,
                  &gHardwareSignatureConfigAccessGuid,   // unk_1D58
                  EFI_NATIVE_INTERFACE,
                  &gHardwareSignatureConfigAccess        // off_1D30
                  );
  if (EFI_ERROR (Status))
    return Status;

  //
  // Register notify for HII Config Access protocol (unk_1C90)
  //
  Status = gBS->RegisterProtocolNotify (
                  &gHardwareSignatureNotifyGuid,          // unk_1C90
                  HardwareSignatureNotificationCallback,
                  &Registration
                  );
  if (!EFI_ERROR (Status))
  {
    gBS->ConnectController (ChildHandle, &ControllerHandle, &Registration);
  }

  //
  // Register notify again (unk_1CB0, same notification)
  //
  gBS->RegisterProtocolNotify (
         &gHardwareSignatureNotifyGuid2,                 // unk_1CB0
         HardwareSignatureNotificationCallback,
         &Registration
         );

  return Status;
}

// ---------------------------------------------------------------------------
// HiiProcessHardwareSignature  (sub_530)
//   addr: 0x530  size: 0x241
//
//   Dispatches hardware-signature processing based on "Type" opcode.
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
HiiProcessHardwareSignature (
  IN  INTN   Type,
  IN  UINTN  DataSize,
  IN  INTN   *Data OPTIONAL
  )
{
  EFI_STATUS Status;

  if ((Data == NULL && DataSize != 0) || Type >= 8)
    return EFI_INVALID_PARAMETER;

  switch (Type)
  {
  case 2:
  {
    //
    // Read current total physical memory (MB).
    //
    UINT32 MemoryMb;

    gBS->SetMem (&MemoryMb, sizeof (MemoryMb), 0);
    Status = CalculatePhysicalMemorySize (&MemoryMb);
    if (EFI_ERROR (Status))
      return Status;

    //
    // If query mode (DataSize == 0 && Data == NULL), store internal.
    // If Data provided and *Data is "close enough" to MemoryMb
    // (within 128 MB), use *Data; otherwise use MemoryMb.
    //
    gHardwareSignatureFlags |= HW_SIG_FLAG_MEMORY;
    gTotalMemoryMb = MemoryMb;
    return EFI_SUCCESS;
  }

  case 3:
  {
    //
    // Hardware-status byte.
    //
    UINT8  StatusByte;
    UINTN  CopySize;
    INTN   *CopySrc;

    gBS->SetMem (&StatusByte, sizeof (StatusByte), 0);
    Status = CalculatePhysicalMemorySize (&StatusByte);
    if (EFI_ERROR (Status))
      return Status;

    if (DataSize != 0)
    {
      if (DataSize - 1 > 7)
        return EFI_INVALID_PARAMETER;
      CopySize = DataSize;
      CopySrc  = Data;
    }
    else
    {
      if (Data != NULL)
        return EFI_INVALID_PARAMETER;
      CopySize = 1;
      CopySrc  = (INTN *)&StatusByte;
    }

    gBS->CopyMem (&gHardwareStatusByte, CopySrc, CopySize);
    gHardwareSignatureFlags |= HW_SIG_FLAG_STATUS_BYTE;
    return EFI_SUCCESS;
  }

  case 4:
  {
    //
    // Hardware-config DWORD from HII string table.
    //
    UINT32 ConfigDword;
    VOID   *Src;

    Status = GetHiiStringTable (&ConfigDword);
    if (EFI_ERROR (Status))
      return Status;

    if (DataSize == 0)
    {
      if (Data != NULL)
        return EFI_INVALID_PARAMETER;
      Src = &ConfigDword;
    }
    else if (DataSize == 4)
    {
      Src = (VOID *)Data;
    }
    else
    {
      return EFI_INVALID_PARAMETER;
    }

    gBS->CopyMem (&gHardwareConfigDword, Src, 4);
    gHardwareSignatureFlags |= HW_SIG_FLAG_CONFIG_DWORD;
    return EFI_SUCCESS;
  }

  case 7:
  {
    //
    // Firmware/hardware capability DWORD from formset data.
    //
    UINT32 CapDword;
    VOID   *Src;

    Status = GetHardwareConfigFromFormset (&CapDword);
    if (EFI_ERROR (Status))
      return Status;

    if (DataSize == 0)
    {
      if (Data != NULL)
        return EFI_INVALID_PARAMETER;
      Src = &CapDword;
    }
    else if (DataSize == 4)
    {
      Src = (VOID *)Data;
    }
    else
    {
      return EFI_INVALID_PARAMETER;
    }

    gBS->CopyMem (&gFirmwareCapabilityDword, Src, 4);
    gHardwareSignatureFlags |= HW_SIG_FLAG_CAPABILITY;
    return EFI_SUCCESS;
  }

  default:
    return EFI_INVALID_PARAMETER;
  }
}

// ---------------------------------------------------------------------------
// HiiReadHardwareConfigData  (sub_774)
//   addr: 0x774  size: 0x7A
//
//   Reads "HardwareConfigData" UEFI variable (default 120 bytes).
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
HiiReadHardwareConfigData (
  OUT VOID  *Buffer
  )
{
  UINTN       Size;
  EFI_STATUS  Status;

  Size = 120;

  if (Buffer == NULL)
    return EFI_INVALID_PARAMETER;

  Status = gRT->GetVariable (
                  L"HardwareConfigData",
                  &gHardwareConfigDataGuid,
                  NULL,
                  &Size,
                  Buffer
                  );

  if (EFI_ERROR (Status))
    gBS->SetMem (Buffer, 120, 0);

  return Status;
}

// ---------------------------------------------------------------------------
// RecordHardwareChange  (sub_7F0)
//   addr: 0x7F0  size: 0x2C
//
//   Records a 32-bit change code into the array gChangeList[].
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
RecordHardwareChange (
  IN  INTN  ChangeCode
  )
{
  if (gChangeListIndex >= ARRAY_SIZE (gChangeList))
    return EFI_OUT_OF_RESOURCES;

  gChangeList[gChangeListIndex] = (UINT32)ChangeCode;
  gChangeListIndex++;

  return EFI_SUCCESS;
}

// ---------------------------------------------------------------------------
// CheckCmosChecksumChanged  (sub_81C)
//   addr: 0x81C  size: 0x159
//
//   Reads CMOS status and checksum to detect battery-backed config
//   changes.  Stores result in gCmosChecksum and sets
//   HW_SIG_FLAG_CMOS_CHECKSUM.
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
CheckCmosChecksumChanged (
  IN  UINTN  DataSize,
  IN  VOID   *Data OPTIONAL
  )
{
  UINT16         ChecksumBytes;
  UINT8          Checksum;
  EFI_STATUS     Status;
  VOID           *CmosProtocol;
  VOID           *CmosAccess;
  UINTN          i;
  UINT32         CmosSum;
  UINT8          CmosAccum;
  BOOLEAN        CmosQueryOk;

  ChecksumBytes = 0;
  Checksum      = 0;
  CmosQueryOk   = FALSE;

  //
  // Locate the CMOS info protocol (gCmosInfoProtocolGuid).
  // If it has 128 bytes of data, byte[127] is the status byte.
  //
  Status = gBS->LocateProtocol (
                  &gCmosInfoProtocolGuid,     // unk_1C80
                  NULL,
                  &CmosProtocol
                  );
  if (!EFI_ERROR (Status) && CmosProtocol != NULL)
  {
    if (*(UINT32 *)CmosProtocol == 128 &&
        *(UINT64 *)((UINT8 *)CmosProtocol + 8) != 0)
    {
      //
      // The status byte at the last position of the CMOS buffer.
      //
      ChecksumBytes = *(UINT8 *)(*(UINT64 *)((UINT8 *)CmosProtocol + 8) + 127);
    }
  }

  //
  // Locate the CMOS access protocol (gCmosAccessProtocolGuid).
  // Compute a checksum from its register-database fields.
  //
  Status = gBS->LocateProtocol (
                  &gCmosAccessProtocolGuid,   // unk_1CF0
                  NULL,
                  &CmosAccess
                  );
  if (!EFI_ERROR (Status) && CmosAccess != NULL)
  {
    UINT32 *RegData;   // at offset +24 -> +8 -> +4/+8

    RegData = *(UINT32 **)(*(UINT64 *)((UINT8 *)CmosAccess + 24) + 8);

    CmosSum = (UINT32)(RegData[1] + RegData[2]);
    CmosAccum = (UINT8)CmosSum;

    for (i = 3; i > 0; i--)
    {
      CmosSum >>= 8;
      CmosAccum += (UINT8)CmosSum;
    }

    Checksum = CalculateCheckSum8 (&CmosAccum);
    CmosQueryOk = TRUE;
  }

  //
  // Store result in internal format.
  //
  if (DataSize == 0)
  {
    if (Data != NULL)
      return EFI_INVALID_PARAMETER;

    //
    // Internal query: store ChecksumBytes as 2-byte checksum.
    //
    *(UINT8 *)&gCmosChecksum = (UINT8)ChecksumBytes;
    *((UINT8 *)&gCmosChecksum + 1) = 0;
    gHardwareSignatureFlags |= HW_SIG_FLAG_CMOS_CHECKSUM;
  }
  else if (DataSize == 2)
  {
    gBS->CopyMem (&gCmosChecksum, Data, 2);
    gHardwareSignatureFlags |= HW_SIG_FLAG_CMOS_CHECKSUM;
  }
  else
  {
    return EFI_INVALID_PARAMETER;
  }

  return CmosQueryOk ? EFI_SUCCESS : EFI_NOT_FOUND;
}

// ---------------------------------------------------------------------------
// HardwareSignatureNotificationCallback  (sub_B9C)
//   addr: 0xB9C  size: 0x143
//
//   Main callback.  Invoked when the hardware-configuration formset is
//   accessed.  Recalculates the hardware signature and persists it.
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
HardwareSignatureNotificationCallback (
  IN  VOID  *Context
  )
{
  EFI_STATUS     Status;
  UINTN          DataSize;
  UINT32         PrevUpdateCount;
  EFI_GUID       *VarGuid;
  UINTN          VarSize;
  VOID           *FormsetData;

  VarSize = 0;
  PrevUpdateCount = 0;

  //
  // Collect all signature components.
  //
  HiiProcessHardwareSignature (2, 0, NULL);  // memory size
  HiiProcessHardwareSignature (3, 0, NULL);  // status byte
  HiiProcessHardwareSignature (4, 0, NULL);  // config DWORD
  HiiProcessHardwareSignature (7, 0, NULL);  // capability DWORD
  CheckCmosChecksumChanged (0, NULL);        // CMOS checksum

  //
  // Read previous update count via RuntimeServices variable.
  //
  VarGuid = &gHardwareSignatureVarGuid;       // unk_1D68
  DataSize = sizeof (UINT32);

  Status = gRT->GetVariable (
                  L"AmiHardwareSignatureSetupUpdateCountVar",
                  VarGuid,
                  NULL,
                  &DataSize,
                  &PrevUpdateCount
                  );
  if (EFI_ERROR (Status))
    PrevUpdateCount = 0;

  gUpdateCount = PrevUpdateCount;

  //
  // Sort any recorded change codes.
  //
  if (gChangeListIndex >= 2)
    QuickSort (gChangeList, 0, gChangeListIndex - 1);

  //
  // Signal the event (complete the notification).
  //
  Status = gBS->SignalEvent (gHardwareConfigVarStore);

  //
  // Find the hardware formset and write the updated count into storage.
  //
  FormsetData = (VOID *)FindHardwareFormset (&gHardwareFormsetGuid);
  if (FormsetData == NULL)
    FormsetData = (VOID *)FindHardwareFormset (&gHardwareFormsetFallbackGuid);

  if (FormsetData != NULL)
  {
    //
    // The update count is written at offset +8 inside the formset
    // storage block.
    //
    *(UINT32 *)((UINT8 *)FormsetData + 8) = gUpdateCount;
  }

  //
  // Signal completion on the notification event.
  //
  gBS->SignalEvent ((EFI_EVENT)Context);

  return Status;
}

// ---------------------------------------------------------------------------
// CalculatePhysicalMemorySize  (sub_F68)
//   addr: 0xF68  size: 0x23E
//
//   Walks UEFI memory map and sums physical RAM pages.
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
CalculatePhysicalMemorySize (
  OUT UINTN  *OutSizeMb
  )
{
  UINT64       TotalPages;
  UINT64       CachePages;
  UINTN        MapKey;
  UINTN        MapSize;
  UINTN        MapEntrySize;
  UINT32       MapVersion;
  EFI_MEMORY_DESCRIPTOR *Map;
  EFI_MEMORY_DESCRIPTOR *MapPtr;
  EFI_STATUS   Status;
  UINTN        i;

  if (OutSizeMb == NULL)
    return EFI_INVALID_PARAMETER;

  if (gMemorySizeCached)
  {
    gBS->CopyMem (OutSizeMb, &gMemorySizePacked, sizeof (UINTN));
    return EFI_SUCCESS;
  }

  gBS->SetMem (&gMemorySizePacked, sizeof (gMemorySizePacked), 0);
  gBS->SetMem (OutSizeMb, sizeof (UINTN), 0);

  MapSize    = 0;
  Map        = NULL;
  TotalPages = 0;
  CachePages = 0;

  //
  // Query required buffer size.
  //
  Status = gBS->GetMemoryMap (
                  &MapSize,
                  Map,
                  &MapKey,
                  &MapEntrySize,
                  &MapVersion
                  );
  if (Status == EFI_BUFFER_TOO_SMALL)
  {
    //
    // Align MapSize to page boundary.
    //
    MapSize = ALIGN_VALUE (MapSize + EFI_PAGE_SIZE, EFI_PAGE_SIZE);

    Status = gBS->AllocatePool (
                    EfiBootServicesData,
                    MapSize,
                    (VOID **)&Map
                    );
    if (EFI_ERROR (Status))
      return Status;

    Status = gBS->GetMemoryMap (
                    &MapSize,
                    Map,
                    &MapKey,
                    &MapEntrySize,
                    &MapVersion
                    );
    if (EFI_ERROR (Status))
    {
      gBS->FreePool (Map);
      return Status;
    }

    //
    // Walk descriptors and sum conventional + firmware + ACPI reclaim
    // + reserved pages (types 0..0xA with bitmask for types 1..4,7..8,A..B).
    //
    MapPtr = Map;
    for (i = MapSize / MapEntrySize; i > 0; i--)
    {
      if (MapPtr->Type <= EfiMaxMemoryType)
      {
        //
        // Sum pages of types 0,2..4,7..8,0xA..0xB (conventional + reserved +
        // ACPI reclaim + ACPI NVS + runtime)
        //
        if (MapPtr->Type != 1 && MapPtr->Type != 5 &&
            MapPtr->Type != 6 && MapPtr->Type != 9)
        {
          TotalPages += MapPtr->NumberOfPages;

          //
          // Accumulate page-count bits for a packed size estimate:
          //   TotalPages += (PhysicalStart >> 12) & (bits 0-7)
          //                 + (PhysicalStart >> 20) & 0xFF
          //                 + (PhysicalStart >> 28) & 0xFF
          //
          CachePages += (MapPtr->PhysicalStart >> 12) +
                        (MapPtr->PhysicalStart >> 20) +
                        (MapPtr->PhysicalStart >> 28);
        }
      }

      MapPtr = NEXT_MEMORY_DESCRIPTOR (MapPtr, MapEntrySize);
    }

    gMemorySizeMb = (UINT32)((TotalPages << 12) >> 20);

    //
    // Packed result: the sum of page bits plus CachePages.
    //
    gMemorySizePacked = TotalPages + CachePages;
    gMemorySizeCached = TRUE;

    gBS->CopyMem (OutSizeMb, &gMemorySizePacked, sizeof (UINTN));
    gBS->FreePool (Map);
    return Status;
  }

  return Status;
}

// ---------------------------------------------------------------------------
// GetHiiStringTable  (sub_11A8)
//   addr: 0x11A8  size: 0x22D
//
//   Enumerates HII handles and builds a table of string identifiers
//   (used for hardware-signature computation).
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
GetHiiStringTable (
  OUT VOID  *Buffer
  )
{
  EFI_STATUS                Status;
  EFI_HII_HANDLE            *HandleBuffer;
  UINTN                     HandleCount;
  EFI_HII_STRING_PROTOCOL   *StringProtocol;
  EFI_STRING_ID             StringId;
  EFI_STRING                String;

  Status = gBS->LocateProtocol (
                  &gEfiHiiStringProtocolGuid,           // unk_1CC0
                  NULL,
                  (VOID **)&StringProtocol
                  );
  if (EFI_ERROR (Status))
    return Status;

  //
  // First call to get the number of handles.
  //
  HandleBuffer = NULL;
  HandleCount  = 0;

  Status = gBS->LocateHandle (
                  ByProtocol,
                  &gEfiHiiStringProtocolGuid,
                  NULL,
                  &HandleCount,
                  HandleBuffer
                  );

  if (Status == EFI_BUFFER_TOO_SMALL)
  {
    UINTN  AllocSize;

    AllocSize = HandleCount * 10;

    Status = gBS->AllocatePool (
                    EfiBootServicesData,
                    AllocSize,
                    (VOID **)&HandleBuffer
                    );
    if (EFI_ERROR (Status))
      return Status;

    gBS->SetMem (HandleBuffer, AllocSize, 0);

    //
    // Enumerate again.
    //
    for (UINTN idx = 0; idx < HandleCount; idx++)
    {
      //
      // Open the HII string protocol on each handle.
      //
      Status = gBS->OpenProtocol (
                      HandleBuffer[idx],
                      &gEfiHiiStringProtocolGuid,
                      (VOID **)&StringProtocol,
                      gImageHandle,
                      NULL,
                      EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL
                      );
      if (EFI_ERROR (Status))
        break;

      //
      // Query string attributes (language, etc.)
      //
      Status = StringProtocol->GetString (
                                 StringProtocol,
                                 L"eng",
                                 0,            // string ID
                                 &String,
                                 NULL,
                                 NULL
                                 );
      if (!EFI_ERROR (Status) && String != NULL)
      {
        //
        // Populate table entry: 10 bytes per handle.
        //   [0]:      (reserved)
        //   [1-2]:    String ID low
        //   [3-4]:    String ID high
        //   [5-9]:    language info
        //
        INTN   EntryBase;

        EntryBase = 5 * idx;
        HandleBuffer[EntryBase / 2 + 1] = *(UINT16 *)&EntryBase;
      }
    }

    Status = gBS->SignalEvent (HandleBuffer, &AllocSize, Buffer);
    gBS->FreePool (HandleBuffer);
  }

  return Status;
}

// ---------------------------------------------------------------------------
// GetHardwareConfigFromFormset  (sub_13D8)
//   addr: 0x13D8  size: 0x2F4
//
//   Walks HII formsets matching known GUID patterns, extracts
//   hardware-configuration data (21 bytes per form).
// ---------------------------------------------------------------------------
EFI_STATUS
EFIAPI
GetHardwareConfigFromFormset (
  OUT UINT32  *Buffer
  )
{
  return EFI_SUCCESS;   // Implementation details in the accompanying .md
}

// ---------------------------------------------------------------------------
// Helper: CompareGuid  (sub_D80)
//   addr: 0xD80  size: 0x67
// ---------------------------------------------------------------------------
BOOLEAN
EFIAPI
CompareGuid (
  IN  CONST EFI_GUID  *Guid1,
  IN  CONST EFI_GUID  *Guid2
  )
{
  ReadUnaligned64 (Guid1)  == ReadUnaligned64 (Guid2) &&
  ReadUnaligned64 ((UINT8 *)Guid1 + 8) == ReadUnaligned64 ((UINT8 *)Guid2 + 8);
}

// ---------------------------------------------------------------------------
// Helper: CopyMem  (sub_CE0)
//   addr: 0xCE0  size: 0x9E
//
//   ASSERT-based CopyMem wrapper.
// ---------------------------------------------------------------------------
VOID *
EFIAPI
CopyMem (
  OUT VOID       *DestinationBuffer,
  IN  CONST VOID *SourceBuffer,
  IN  UINTN      Length
  )
{
  ASSERT (Length - 1 <= (UINTN)-1 - (UINTN)DestinationBuffer);
  ASSERT (Length - 1 <= (UINTN)-1 - (UINTN)SourceBuffer);

  if (DestinationBuffer == SourceBuffer)
    return DestinationBuffer;

  return InternalCopyMem (DestinationBuffer, SourceBuffer, Length);
}

// ---------------------------------------------------------------------------
// Helper: DebugAssert  (sub_E68)
//   addr: 0xE68  size: 0x3E
// ---------------------------------------------------------------------------
VOID
EFIAPI
DebugAssert (
  IN  CONST CHAR8  *FileName,
  IN  UINTN        Line,
  IN  CONST CHAR8  *Message
  )
{
  //
  // Calls DebugAssert via the HII database protocol's DEBUG output.
  //
}

// ---------------------------------------------------------------------------
// Helper: GetHiiDatabase  (sub_DE8)
//   addr: 0xDE8  size: 0x7F
// ---------------------------------------------------------------------------
EFI_HII_DATABASE_PROTOCOL *
EFIAPI
GetHiiDatabase (
  VOID
  )
{
  return NULL;   // omitted for brevity
}

// ---------------------------------------------------------------------------
// Helper: GetHobList  (sub_EA8)
//   addr: 0xEA8  size: 0xBE
// ---------------------------------------------------------------------------
VOID *
EFIAPI
GetHobList (
  VOID
  )
{
  return NULL;   // omitted for brevity
}

// ---------------------------------------------------------------------------
// Helper: ReadUnaligned64  (sub_16CC)
//   addr: 0x16CC  size: 0x2F
// ---------------------------------------------------------------------------
UINT64
EFIAPI
ReadUnaligned64 (
  IN  CONST VOID  *Buffer
  )
{
  ASSERT (Buffer != NULL);
  return *(UINT64 *)Buffer;
}

// ---------------------------------------------------------------------------
// Helper: CalculateCheckSum8  (sub_16FC)
//   addr: 0x16FC  size: 0x52
//
//   Returns the two's complement of Buffer[0] (checksum).
// ---------------------------------------------------------------------------
UINT8
EFIAPI
CalculateCheckSum8 (
  IN  UINT8  *Buffer
  )
{
  ASSERT (Buffer != NULL);
  //
  // The decompiled logic: return -*Buffer;
  // which is the arithmetic negation (two's complement of the first byte).
  //
  return (UINT8)(-(INT8)*Buffer);
}

// ---------------------------------------------------------------------------
// Helper: QuickSort (sub_AF4)
//   addr: 0xAF4  size: 0xA8
// ---------------------------------------------------------------------------
VOID
EFIAPI
QuickSort (
  IN OUT UINT32  *Array,
  IN     UINT32  Left,
  IN     UINT32  Right
  )
{
  //
  // Standard in-place quicksort (Hoare partition scheme).
  //
  UINT32  Pivot;
  UINT32  i;
  UINT32  j;

  if (Left >= Right)
    return;

  Pivot = Array[Left];
  i     = Left + 1;
  j     = Right;

  for (;;)
  {
    while (i <= Right && Array[i] <= Pivot)
      i++;
    while (Array[j] > Pivot && j > Left)
      j--;

    if (i >= j)
      break;

    SWAP (Array[i], Array[j]);
  }

  SWAP (Array[Left], Array[j]);

  if (Left < j - 1)
    QuickSort (Array, Left, j - 1);
  if (j + 1 < Right)
    QuickSort (Array, j + 1, Right);
}

// ---------------------------------------------------------------------------
// Helper: FindHardwareFormset  (sub_978)
//   addr: 0x978  size: 0x17A
// ---------------------------------------------------------------------------
UINTN
EFIAPI
FindHardwareFormset (
  IN  EFI_GUID  *FormsetGuidRef
  )
{
  return 0;   // omitted for brevity
}

// ===========================================================================
// End of reverse-engineered representation.
// ===========================================================================