pcitree: Look up PCI IDs using pciutils PCI ID database

This commit is contained in:
Björn Ruytenberg 2024-12-10 16:04:06 +01:00
parent 453dff9ac4
commit 3a56de4a14
9 changed files with 516 additions and 10 deletions

3
.gitmodules vendored
View file

@ -10,3 +10,6 @@
[submodule "hyperdbg/tests/script-engine-test"]
path = hyperdbg/tests/script-engine-test
url = https://github.com/HyperDbg/script-engine-test.git
[submodule "hyperdbg/miscellaneous/constants/pciid"]
path = hyperdbg/miscellaneous/constants/pciid
url = https://github.com/HyperDbg/pciids

View file

@ -96,22 +96,41 @@ CommandPcitree(vector<CommandToken> CommandTokens, string Command)
//
// Print PCI device tree
//
ShowMessages("%-12s | %-9s | %s\n%s\n", "DBDF", "VID:DID", "Class Code", "---------------------------------------");
ShowMessages("%-12s | %-9s | %-17s | %s \n%s\n", "DBDF", "VID:DID", "Vendor Name", "Device Name", "----------------------------------------------------------------------");
for (UINT8 i = 0; i < (PcitreePacket.EndpointsTotalNum < EP_MAX_NUM ? PcitreePacket.EndpointsTotalNum : EP_MAX_NUM); i++)
{
ShowMessages("%04x:%02x:%02x:%x | %04x:%04x | %04x%04x%04x\n",
Vendor * CurrentVendor = GetVendorById(PcitreePacket.Endpoints[i].ConfigSpace.VendorId);
char * CurrentVendorName = (char *)"N/A";
char * CurrentDeviceName = (char *)"N/A";
if (CurrentVendor != NULL)
{
CurrentVendorName = CurrentVendor->VendorName;
Device * CurrentDevice = GetDeviceFromVendor(CurrentVendor, PcitreePacket.Endpoints[i].ConfigSpace.DeviceId);
if (CurrentDevice != NULL)
{
CurrentDeviceName = CurrentDevice->DeviceName;
}
}
ShowMessages("%04x:%02x:%02x:%x | %04x:%04x | %-17.*s | %.*s\n",
0, // TODO: Add support for domains beyond 0000
PcitreePacket.Endpoints[i].Bus,
PcitreePacket.Endpoints[i].Device,
PcitreePacket.Endpoints[i].Function,
PcitreePacket.Endpoints[i].ConfigSpace.VendorId,
PcitreePacket.Endpoints[i].ConfigSpace.DeviceId,
PcitreePacket.Endpoints[i].ConfigSpace.ClassCode[0],
PcitreePacket.Endpoints[i].ConfigSpace.ClassCode[1],
PcitreePacket.Endpoints[i].ConfigSpace.ClassCode[2]
strnlen_s(CurrentVendorName, PCI_NAME_STR_LENGTH),
CurrentVendorName,
strnlen_s(CurrentDeviceName, PCI_NAME_STR_LENGTH),
CurrentDeviceName
);
FreeVendor(CurrentVendor);
}
FreePciIdDatabase();
}
else
{

View file

@ -1054,22 +1054,41 @@ StartAgain:
//
// Print PCI device tree
//
ShowMessages("%-12s | %-9s | %s\n%s\n", "DBDF", "VID:DID", "Class Code", "---------------------------------------");
ShowMessages("%-12s | %-9s | %-17s | %s \n%s\n", "DBDF", "VID:DID", "Vendor Name", "Device Name", "----------------------------------------------------------------------");
for (UINT8 i = 0; i < (PcitreePacket->EndpointsTotalNum < EP_MAX_NUM ? PcitreePacket->EndpointsTotalNum : EP_MAX_NUM); i++)
{
ShowMessages("%04x:%02x:%02x:%x | %04x:%04x | %04x%04x%04x\n",
Vendor * CurrentVendor = GetVendorById(PcitreePacket->Endpoints[i].ConfigSpace.VendorId);
char * CurrentVendorName = (char *)"N/A";
char * CurrentDeviceName = (char *)"N/A";
if (CurrentVendor != NULL)
{
CurrentVendorName = CurrentVendor->VendorName;
Device * CurrentDevice = GetDeviceFromVendor(CurrentVendor, PcitreePacket->Endpoints[i].ConfigSpace.DeviceId);
if (CurrentDevice != NULL)
{
CurrentDeviceName = CurrentDevice->DeviceName;
}
}
ShowMessages("%04x:%02x:%02x:%x | %04x:%04x | %-17.*s | %.*s\n",
0, // TODO: Add support for domains beyond 0000
PcitreePacket->Endpoints[i].Bus,
PcitreePacket->Endpoints[i].Device,
PcitreePacket->Endpoints[i].Function,
PcitreePacket->Endpoints[i].ConfigSpace.VendorId,
PcitreePacket->Endpoints[i].ConfigSpace.DeviceId,
PcitreePacket->Endpoints[i].ConfigSpace.ClassCode[0],
PcitreePacket->Endpoints[i].ConfigSpace.ClassCode[1],
PcitreePacket->Endpoints[i].ConfigSpace.ClassCode[2]
strnlen_s(CurrentVendorName, PCI_NAME_STR_LENGTH),
CurrentVendorName,
strnlen_s(CurrentDeviceName, PCI_NAME_STR_LENGTH),
CurrentDeviceName
);
FreeVendor(CurrentVendor);
}
FreePciIdDatabase();
}
else
{

View file

@ -153,6 +153,7 @@
<ClInclude Include="header\transparency.h" />
<ClInclude Include="header\ud.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="pci-id.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\script-eval\code\Functions.c" />
@ -292,8 +293,16 @@
<ClCompile Include="code\debugger\tests\tests.cpp" />
<ClCompile Include="code\debugger\transparency\gaussian-rng.cpp" />
<ClCompile Include="code\debugger\transparency\transparency.cpp" />
<ClCompile Include="pci-id.cpp" />
<MASM Include="code\assembly\asm-vmx-checks.asm" />
</ItemGroup>
<ItemGroup>
<CopyFileToFolders Include="..\miscellaneous\constants\pciid\pci.ids">
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='release|x64'">true</DeploymentContent>
<FileType>Document</FileType>
<DeploymentContent Condition="'$(Configuration)|$(Platform)'=='debug|x64'">true</DeploymentContent>
</CopyFileToFolders>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />

View file

@ -84,6 +84,9 @@
<Filter Include="code\export">
<UniqueIdentifier>{cfacdcfe-8503-4a00-b7e2-75b0e906f75e}</UniqueIdentifier>
</Filter>
<Filter Include="resources">
<UniqueIdentifier>{b0ac8778-17e9-4be4-9f0f-0113a71120a9}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h">
@ -173,6 +176,9 @@
<ClInclude Include="header\hwdbg-scripts.h">
<Filter>header</Filter>
</ClInclude>
<ClInclude Include="pci-id.h">
<Filter>header</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="pch.cpp">
@ -577,10 +583,18 @@
<ClCompile Include="code\debugger\commands\debugging-commands\gg.cpp">
<Filter>code\debugger\commands\debugging-commands</Filter>
</ClCompile>
<ClCompile Include="pci-id.cpp">
<Filter>code\debugger\misc</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<MASM Include="code\assembly\asm-vmx-checks.asm">
<Filter>code\assembly</Filter>
</MASM>
</ItemGroup>
<ItemGroup>
<CopyFileToFolders Include="..\miscellaneous\constants\pciid\pci.ids">
<Filter>resources</Filter>
</CopyFileToFolders>
</ItemGroup>
</Project>

View file

@ -141,6 +141,11 @@ typedef const wchar_t *LPCWCHAR, *PCWCHAR;
#include "SDK/imports/user/HyperDbgScriptImports.h"
#include "SDK/imports/user/HyperDbgLibImports.h"
//
// PCI IDs
//
#include "pci-id.h"
//
// General
//

View file

@ -0,0 +1,378 @@
/**
* @file pci-id.cpp
* @author Björn Ruytenberg (bjorn@bjornweb.nl)
* @brief Provides runtime access to PCI ID database
* @details
* @version 0.12
* @date 2024-12-04
*
* @copyright This project is released under the GNU Public License v3.
*
*/
#include "pch.h"
static char * PciIdDatabaseBuffer = NULL;
/**
* @brief Trims whitespaces in passed string
*
* @param Str
* @param MaxLen
* @return char *
*/
char *
TrimWhitespace(char * Str, UINT8 MaxLen)
{
char * End;
while (*Str == ' ')
Str++; // Trim leading space
if (*Str == '\0')
return Str;
End = Str + strnlen_s(Str, MaxLen) - 1;
while (End > Str && (*End == ' ' || *End == '\n' || *End == '\r'))
End--;
*(End + 1) = '\0';
return Str;
}
/**
* @brief Converts passed string to lowercase
*
* @param Str
* @return char *
*/
char *
ToLower(char * Str)
{
UINT8 StrLength = (UINT8)strnlen_s(Str, PCI_ID_AS_STR_LENGTH);
char * CurrentChar = Str;
while (CurrentChar < Str + StrLength)
{
*CurrentChar = tolower(*CurrentChar);
CurrentChar++;
}
return Str;
}
/**
* @brief Read line from string. Treats SrcBuffer as a stream (similar to fgets and friends), i.e. updates SrcBuffer by number of characters read.
*
* @param DestBuffer
* @param CharLimit
* @param SrcBuffer
* @return char *
*/
char *
ReadLine(char * DestBuffer, UINT64 CharLimit, char ** SrcBuffer)
{
char * Line = strchr(*SrcBuffer, '\n');
if (!Line)
{
return NULL;
}
else
{
strncpy_s(DestBuffer, CharLimit, *SrcBuffer, (Line - *SrcBuffer));
*SrcBuffer += (Line - *SrcBuffer + 1);
return *SrcBuffer;
}
}
/**
* @brief Get Vendor by PCI ID, encoded in ASCII. Do not call directly - use GetVendorById() instead.
*
* @param Filename
* @param VendorId
* @return Vendor *
*/
Vendor *
GetVendorByIdStr(const char * Filename, const char * VendorId)
{
Vendor * MatchedVendor = NULL;
BOOLEAN FoundVendorId = FALSE;
Device * LastDevice = NULL;
SubDevice * LastSubDevice = NULL;
char * PciIdDbBufPtr = NULL;
char Line[1024] = {'\0'};
if (!PciIdDatabaseBuffer)
{
FILE * f = fopen(Filename, "rb");
size_t Length = 0;
if (f == NULL)
{
ShowMessages("Error: Cannot open file '%s': error %d\n", Filename, errno);
return NULL;
}
fseek(f, 0, SEEK_END);
Length = ftell(f);
PciIdDatabaseBuffer = (char *)malloc(Length);
if (!PciIdDatabaseBuffer)
{
return NULL;
}
fseek(f, 0, SEEK_SET);
fread(PciIdDatabaseBuffer, 1, Length, f);
fclose(f);
}
PciIdDbBufPtr = PciIdDatabaseBuffer;
while (ReadLine(Line, sizeof(Line), &PciIdDbBufPtr) != NULL)
{
// Skip comments and empty lines
if (Line[0] == '#' || Line[0] == '\0')
{
continue;
}
// Find vendor
// We assume PCI ID database comprises unique entries only, i.e. we return the first matching entry
if (Line[0] != '\t' && FoundVendorId == FALSE)
{
char VendorBuf[PCI_ID_AS_STR_LENGTH + 1], VendorNameBuf[PCI_NAME_STR_LENGTH];
if (sscanf(Line, "%4s %[^\n]", VendorBuf, VendorNameBuf) == 2)
{
if (strncmp(VendorBuf, VendorId, sizeof(VendorId)) == 0)
{
MatchedVendor = (Vendor *)malloc(sizeof(Vendor));
if (!MatchedVendor)
{
return NULL;
}
int result = sscanf(VendorBuf, "%hx", &(MatchedVendor->VendorId));
if (result != 1)
{
return NULL;
}
strncpy_s(MatchedVendor->VendorName, sizeof(MatchedVendor->VendorName), TrimWhitespace(VendorNameBuf, PCI_NAME_STR_LENGTH), _TRUNCATE);
FoundVendorId = TRUE;
}
}
}
// Get all devices for vendor
else if (Line[0] == '\t' && Line[1] != '\t' && FoundVendorId == TRUE)
{
char DeviceBuf[PCI_ID_AS_STR_LENGTH + 1], DeviceNameBuf[PCI_NAME_STR_LENGTH];
if (sscanf(Line + 1, "%4s %[^\n]", DeviceBuf, DeviceNameBuf) == 2)
{
Device * NewDevice = (Device *)malloc(sizeof(Device));
if (!NewDevice)
{
FreeVendor(MatchedVendor);
return NULL;
}
int Result = sscanf(DeviceBuf, "%hx", &(NewDevice->DeviceId));
if (Result != 1)
{
FreeVendor(MatchedVendor);
return NULL;
}
strncpy_s(NewDevice->DeviceName, sizeof(NewDevice->DeviceName), TrimWhitespace(DeviceNameBuf, PCI_NAME_STR_LENGTH), _TRUNCATE);
NewDevice->SubDevices = NULL;
NewDevice->Next = NULL;
if (LastDevice)
{
LastDevice->Next = NewDevice;
}
else
{
MatchedVendor->Devices = NewDevice; // First device
}
LastDevice = NewDevice;
LastSubDevice = NULL;
}
}
// Get all subdevices for device
else if (Line[0] == '\t' && Line[1] == '\t' && FoundVendorId == TRUE && LastDevice)
{
char SubVendorBuf[PCI_ID_AS_STR_LENGTH + 1], SubDeviceBuf[PCI_ID_AS_STR_LENGTH + 1], SubsystemNameBuf[PCI_NAME_STR_LENGTH];
if (sscanf(Line + 2, "%4s %4s %[^\n]", SubVendorBuf, SubDeviceBuf, SubsystemNameBuf) == 3)
{
SubDevice * NewSubDevice = (SubDevice *)malloc(sizeof(SubDevice));
if (!NewSubDevice)
{
FreeVendor(MatchedVendor);
return NULL;
}
int Result = sscanf(SubVendorBuf, "%hx", &NewSubDevice->SubVendorId);
if (Result != 1)
{
FreeVendor(MatchedVendor);
return NULL;
}
Result = sscanf(SubDeviceBuf, "%hx", &NewSubDevice->SubDeviceId);
if (Result != 1)
{
FreeVendor(MatchedVendor);
return NULL;
}
strncpy_s(NewSubDevice->SubSystemName, sizeof(NewSubDevice->SubSystemName), TrimWhitespace(SubsystemNameBuf, PCI_NAME_STR_LENGTH), _TRUNCATE);
NewSubDevice->Next = NULL;
if (LastSubDevice)
{
LastSubDevice->Next = NewSubDevice;
}
else
{
LastDevice->SubDevices = NewSubDevice; // First subdevice
}
LastSubDevice = NewSubDevice;
}
}
else if (Line[0] != '\t' && FoundVendorId == TRUE) // We hit the next vendor entry, so we're done parsing
{
break;
}
}
return MatchedVendor;
}
/**
* @brief Frees Vendor and all of its members
*
* @param VendorToFree
* @return void
*/
void
FreeVendor(Vendor * VendorToFree)
{
if (VendorToFree == NULL)
return;
Device * CurrentDevice = VendorToFree->Devices;
while (CurrentDevice)
{
SubDevice * CurrentSubDevice = CurrentDevice->SubDevices;
while (CurrentSubDevice)
{
SubDevice * nextSubDevice = CurrentSubDevice->Next;
free(CurrentSubDevice);
CurrentSubDevice = nextSubDevice;
}
Device * NextDevice = CurrentDevice->Next;
free(CurrentDevice);
CurrentDevice = NextDevice;
}
}
/**
* @brief Frees PciIdDatabaseBuffer
* @return void
*/
void
FreePciIdDatabase()
{
if (PciIdDatabaseBuffer != NULL)
{
free(PciIdDatabaseBuffer);
PciIdDatabaseBuffer = NULL;
}
}
/**
* @brief Returns Vendor entry, including corresponding devices and subdevices
* @details Use FreeVendor() on returned Vendor pointer after usage. First call will initialize database - call FreeDatabase() once done querying.
*
* @param VendorId
* @return Vendor
*/
Vendor *
GetVendorById(UINT16 VendorId)
{
char VendorIdAsStr[5];
char ExecutablePath[MAX_PATH];
HMODULE hModule = GetModuleHandle(NULL);
snprintf(VendorIdAsStr, sizeof(VendorIdAsStr), "%04X", VendorId);
GetModuleFileName(hModule, ExecutablePath, sizeof(ExecutablePath));
// Extract executable name
char * ExecutableName = strrchr(ExecutablePath, '\\');
if (ExecutableName != NULL)
{
ExecutableName++;
}
else
{
ExecutableName = ExecutablePath;
}
// Swap executable name for PCI_ID_DATABASE_PATH
strncpy(ExecutableName, PCI_ID_DATABASE_PATH, sizeof(PCI_ID_DATABASE_PATH));
return GetVendorByIdStr(ExecutablePath, ToLower(VendorIdAsStr));
}
/**
* @brief Returns Device entry corresponding to DeviceId
*
* @param VendorToUse
* @param DeviceId
* @return Device
*/
Device *
GetDeviceFromVendor(Vendor * VendorToUse, UINT16 DeviceId)
{
Device * CurrentDevice = NULL;
if (!VendorToUse)
{
return NULL;
}
CurrentDevice = VendorToUse->Devices;
while (CurrentDevice != NULL)
{
if (CurrentDevice->DeviceId == DeviceId)
{
return CurrentDevice;
}
CurrentDevice = CurrentDevice->Next;
}
return NULL;
}
/**
* @brief Returns SubDevice entry corresponding to SubVendorId and DeviceId
*
* @param DeviceToUse
* @param SubVendorId
* @param SubDeviceId
* @return SubDevice
*/
SubDevice *
GetSubDeviceFromDevice(Device * DeviceToUse, UINT16 SubVendorId, UINT16 SubDeviceId)
{
SubDevice * CurrentSubDevice = NULL;
if (!DeviceToUse)
{
return NULL;
}
CurrentSubDevice = DeviceToUse->SubDevices;
while (CurrentSubDevice != NULL)
{
if (CurrentSubDevice->SubVendorId == SubVendorId && CurrentSubDevice->SubDeviceId == SubDeviceId)
{
return CurrentSubDevice;
}
CurrentSubDevice = CurrentSubDevice->Next;
}
return NULL;
}

View file

@ -0,0 +1,58 @@
/**
* @file pci-id.h
* @author Björn Ruytenberg (bjorn@bjornweb.nl)
* @brief PCI ID-related data structures
* @details
* @version 0.12
* @date 2024-12-04
*
* @copyright This project is released under the GNU Public License v3.
*
*/
#pragma once
#define PCI_ID_AS_STR_LENGTH (sizeof(UINT16) * 2)
#define PCI_NAME_STR_LENGTH 255
typedef struct SubDevice
{
UINT16 SubVendorId;
UINT16 SubDeviceId;
char SubSystemName[PCI_NAME_STR_LENGTH];
struct SubDevice * Next;
} SubDevice;
typedef struct Device
{
UINT16 DeviceId;
char DeviceName[PCI_NAME_STR_LENGTH];
SubDevice * SubDevices;
struct Device * Next;
} Device;
typedef struct Vendor
{
UINT16 VendorId;
char VendorName[PCI_NAME_STR_LENGTH];
Device * Devices;
} Vendor;
//
// PCI ID database courtesy of PCI ID Database (pciutils) project at
// https://pci-ids.ucw.cz/
//
#define PCI_ID_DATABASE_PATH "pci.ids"
//////////////////////////////////////////////////
// Functions //
//////////////////////////////////////////////////
Vendor *
GetVendorById(UINT16 VendorId);
void
FreeVendor(Vendor * VendorToFree);
void
FreePciIdDatabase();
Device *
GetDeviceFromVendor(Vendor * VendorToUse, UINT16 DeviceId);
SubDevice *
GetSubDeviceFromDevice(Device * DeviceToUse, UINT16 SubVendorId, UINT16 SubDeviceId);

@ -0,0 +1 @@
Subproject commit 7c8139ba5032bf40daad23628c3ed8abe7cbb4ef