alien_fx_fiend

Added Claude lmarena.ai Fixes Still Crashes

Dec 29th, 2024
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 112.51 KB | Source Code | 0 0
  1. ===+++ main.cpp +++===
  2. #define STRICT
  3. #define WIN32_LEAN_AND_MEAN
  4. #define DEBUG_OUTPUT(format, ...) \
  5.     do { \
  6.         OUTPUT("[DEBUG] %s:%d - " format "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  7.     } while(0)
  8. #ifndef OUTPUT
  9. #define OUTPUT(format, ...) wprintf(L##format, ##__VA_ARGS__)
  10. #endif
  11. #include <Windows.h>
  12. #include <winternl.h>
  13. #include <CommCtrl.h>
  14. #include <commdlg.h>
  15. #include <string>
  16. #include <strsafe.h>
  17. #include <sstream>
  18. #include <iomanip>
  19. #include <stdio.h>
  20. #include <vector>
  21. #include <shellapi.h>
  22. //#include "helpers.h"
  23. #include "PEHeaders.h"
  24. #include "resource.h"
  25. #pragma comment(lib, "comctl32.lib")
  26.  
  27. //namespace was here
  28.  
  29. // Window defines
  30. #define WINDOW_CLASS_NAME L"PEAnalyzerWindow"
  31. #define OUTPUT(format, ...) AppendToOutput(L##format, ##__VA_ARGS__)
  32. #define WINDOW_WIDTH    1024
  33. #define WINDOW_HEIGHT   768
  34. #define EDIT_MARGIN    10
  35.  
  36. // Global variables
  37. HWND g_hMainWindow = NULL;
  38. HWND g_hEditControl = NULL;
  39. HWND g_hStatusBar = NULL;
  40. HWND g_hProgressBar = NULL;
  41. HFONT g_hFont = NULL;
  42. std::wstringstream g_OutputText;
  43. std::vector<wchar_t> g_OutputBuffer;
  44. std::wstring tempBuffer;
  45. WCHAR filePathW[MAX_PATH];
  46.  
  47. // Resource parsing constants
  48. static const wchar_t* RESOURCE_TYPES[] = {
  49.     L"Unknown",     L"Cursor",      L"Bitmap",      L"Icon",
  50.     L"Menu",        L"Dialog",      L"String",      L"FontDir",
  51.     L"Font",        L"Accelerator", L"RCData",      L"MessageTable",
  52.     L"GroupCursor", L"GroupIcon",   L"Version",     L"DlgInclude"
  53. };
  54.  
  55. //adding structs here now
  56.  
  57. enum class FileValidationResult {
  58.     Valid,
  59.     InvalidPath,
  60.     FileNotFound,
  61.     AccessDenied,
  62.     UnsupportedType
  63. };
  64.  
  65. // Forward declarations for global functions
  66. void UpdateEditControl();
  67. void AppendToOutput(const wchar_t* format, ...);
  68. void SetStatusText(const wchar_t* text);
  69. void ShowProgress(int percentage);
  70. void OpenFileDialog(HWND hwnd);
  71. void AnalyzePEFile(const wchar_t* filePathW);
  72. //analyzepefile 4wd func
  73. HANDLE GetFileContent(const wchar_t* lpFilePath);
  74. void OpenFileDialog(HWND hwnd); // Add these in the global scope, before any namespace declarations
  75.  
  76. // GUI-related forward declarations
  77. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
  78. LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam,
  79.     LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
  80. void CreateMainWindow(HINSTANCE hInstance);
  81. void InitializeControls(HWND hwnd);
  82. void AddMenus(HWND hwnd);
  83. //void SetStatusText(const wchar_t* text);
  84. //void ShowProgress(int percentage);
  85. //void UpdateEditControl();    
  86. DWORD GetFileSizeCustom(const wchar_t* filePath);
  87.  
  88. //bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders);
  89.  
  90.  
  91. //using namespace std;
  92. //using namespace PEParser;
  93. //using namespace PEHelpers;
  94.  
  95. //namespace PEParser {
  96.  
  97. //struct PEAnalyzer;  // Forward declaration
  98. class FileMapper;
  99. FileValidationResult ValidatePEFile(const wchar_t* filePath);
  100. bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath);
  101. //class FileValidationResult ValidatePEFile(const wchar_t* filePath);
  102. void ParseSections(const PEAnalyzer& analyzer); //forwarddeclare parse+ bring namespace up
  103. void ParseImportDirectory(const PEAnalyzer& analyzer);
  104. void ParseExportDirectory(const PEAnalyzer& analyzer);
  105. void ParseResourceDirectory(const PEAnalyzer& analyzer);
  106. void ParseDebugDirectory(const PEAnalyzer& analyzer);
  107. void AnalyzeHeaders(const PEAnalyzer& analyzer);
  108. void AnalyzeDataDirectories(const PEAnalyzer& analyzer);
  109. //bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath);
  110.  
  111. //newglobals
  112. void ParseNTHeader64(const PEAnalyzer& analyzer);
  113. void ParseNTHeader32(const PEAnalyzer& analyzer);
  114. void ParseImportFunctions32(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc);
  115. void ParseImportFunctions64(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc);
  116. void ParseExportedFunctions(const PEAnalyzer& analyzer, PIMAGE_EXPORT_DIRECTORY pExportDir,
  117.     PDWORD pFunctions, PDWORD pNames, PWORD pOrdinals);
  118. void ProcessResourceDirectory(
  119.     PIMAGE_RESOURCE_DIRECTORY resDir,
  120.     int level,
  121.     const wchar_t* type,
  122.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  123.     const PEAnalyzer& analyzer);
  124. void ProcessNamedResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  125.     int level, PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  126.     const PEAnalyzer& analyzer);
  127. void ProcessIdResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  128.     int level, const wchar_t* type,
  129.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  130.     const PEAnalyzer& analyzer);
  131. void ProcessResourceSubdirectory(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  132.     int level, const wchar_t* type,
  133.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  134.     const PEAnalyzer& analyzer);
  135. void ProcessResourceData(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  136.     int level, const wchar_t* type,
  137.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  138.     const PEAnalyzer& analyzer);
  139. void ProcessDebugEntry(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer);
  140. void ProcessRSDSDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  141.     const PEAnalyzer& analyzer);
  142. void ProcessCodeViewDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer);
  143. void ProcessNB10DebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  144.     const PEAnalyzer& analyzer);
  145. //void ParseImportDirectory(const PEAnalyzer& analyzer);
  146. //void ParseExportDirectory(const PEAnalyzer& analyzer);
  147. //DWORD GetFileSizeCustom(const wchar_t* filePath);
  148. //endnewglobals
  149.  
  150. //using namespace std;
  151. //using namespace PEHelpers;
  152. //struct was here
  153.  
  154.  
  155. // File mapping helper class
  156. class FileMapper {
  157. private:
  158.     HANDLE hFile;
  159.     HANDLE hMapping;
  160.     LPVOID lpView;
  161.  
  162. public:
  163.     FileMapper() : hFile(INVALID_HANDLE_VALUE), hMapping(nullptr), lpView(nullptr) {}
  164.     ~FileMapper() { Cleanup(); }
  165.  
  166.     void Cleanup() {
  167.         if (lpView) {
  168.             UnmapViewOfFile(lpView);
  169.             lpView = nullptr;
  170.         }
  171.         if (hMapping) {
  172.             CloseHandle(hMapping);
  173.             hMapping = nullptr;
  174.         }
  175.         if (hFile != INVALID_HANDLE_VALUE) {
  176.             CloseHandle(hFile);
  177.             hFile = INVALID_HANDLE_VALUE;
  178.         }
  179.     }
  180.  
  181.         bool Initialize(const wchar_t* path) {
  182.         Cleanup();
  183.        
  184.         hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ,
  185.             nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  186.         if (hFile == INVALID_HANDLE_VALUE) {
  187.             OUTPUT("[-] Failed to open file\n");
  188.             return false;
  189.         }
  190.  
  191.         LARGE_INTEGER fileSize;
  192.         if (!GetFileSizeEx(hFile, &fileSize)) {
  193.             OUTPUT("[-] Failed to get file size\n");
  194.             Cleanup();
  195.             return false;
  196.         }
  197.  
  198.         // Create mapping without SEC_IMAGE first
  199.         hMapping = CreateFileMappingW(hFile, nullptr, PAGE_READONLY,
  200.             fileSize.HighPart, fileSize.LowPart, nullptr);
  201.         if (!hMapping) {
  202.             OUTPUT("[-] Failed to create file mapping\n");
  203.             Cleanup();
  204.             return false;
  205.         }
  206.  
  207.         lpView = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  208.         if (!lpView) {
  209.             OUTPUT("[-] Failed to map view of file\n");
  210.             Cleanup();
  211.             return false;
  212.         }
  213.  
  214.         return true;
  215.         }
  216.  
  217.         LPVOID GetView() const { return lpView; }
  218. };
  219.  
  220. FileValidationResult ValidatePEFile(const wchar_t* filePath) {
  221.     if (!filePath || wcslen(filePath) == 0) {
  222.         OUTPUT("[-] Null or empty file path\n");
  223.         return FileValidationResult::InvalidPath;
  224.     }
  225.  
  226.     // Check file extension
  227.     const wchar_t* ext = wcsrchr(filePath, L'.');
  228.     if (!ext || (wcscmp(ext, L".exe") != 0 && wcscmp(ext, L".dll") != 0)) {
  229.         OUTPUT("[-] Unsupported file type. Only .exe and .dll are supported\n");
  230.         return FileValidationResult::UnsupportedType;
  231.     }
  232.  
  233.     // Detailed file access check
  234.     HANDLE hFile = CreateFileW(
  235.         filePath,
  236.         GENERIC_READ,
  237.         FILE_SHARE_READ | FILE_SHARE_WRITE,
  238.         NULL,
  239.         OPEN_EXISTING,
  240.         FILE_ATTRIBUTE_NORMAL,
  241.         NULL
  242.     );
  243.  
  244.     if (hFile == INVALID_HANDLE_VALUE) {
  245.         DWORD error = GetLastError();
  246.         switch (error) {
  247.         case ERROR_FILE_NOT_FOUND:
  248.             OUTPUT("[-] File not found: %s\n", filePath);
  249.             return FileValidationResult::FileNotFound;
  250.         case ERROR_ACCESS_DENIED:
  251.             OUTPUT("[-] Access denied. Check file permissions: %s\n", filePath);
  252.             return FileValidationResult::AccessDenied;
  253.         default:
  254.             OUTPUT("[-] File open error %d: %s\n", error, filePath);
  255.             return FileValidationResult::InvalidPath;
  256.         }
  257.     }
  258.  
  259.     // Additional checks
  260.     LARGE_INTEGER fileSize;
  261.     if (!GetFileSizeEx(hFile, &fileSize)) {
  262.         CloseHandle(hFile);
  263.         OUTPUT("[-] Cannot determine file size\n");
  264.         return FileValidationResult::InvalidPath;
  265.     }
  266.  
  267.     CloseHandle(hFile);
  268.     return FileValidationResult::Valid;
  269. }
  270.  
  271. // Initialization function
  272. bool InitializePEAnalyzer(PEAnalyzer& analyzer, const wchar_t* filePath) {
  273.     try {
  274.         FileValidationResult validationResult = ValidatePEFile(filePath);
  275.         if (validationResult != FileValidationResult::Valid) {
  276.             OUTPUT("[-] File validation failed with code: %d\n",
  277.                 static_cast<int>(validationResult));
  278.             return false;
  279.         }
  280.  
  281.         if (!analyzer.lpFileContent) {
  282.             OUTPUT("[-] No file content available\n");
  283.             return false;
  284.         }
  285.  
  286.     FileMapper mapper;
  287.     if (!mapper.Initialize(filePath)) {
  288.         OUTPUT("[-] Failed to map file. Detailed error in FileMapper\n");
  289.         return false;
  290.     }
  291.  
  292.     analyzer.pDosHeader = static_cast<PIMAGE_DOS_HEADER>(analyzer.lpFileContent);
  293.     if (analyzer.pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  294.         OUTPUT("[-] Invalid DOS signature: 0x%X\n", analyzer.pDosHeader->e_magic);
  295.         return false;
  296.     }
  297.  
  298.     analyzer.lpFileContent = mapper.GetView();
  299.     analyzer.fileSize = GetFileSizeCustom(filePath);
  300.  
  301.     // Comprehensive PE signature validation
  302.         if (!analyzer.lpFileContent || analyzer.fileSize == 0) {
  303.         OUTPUT("[-] Memory mapping failed or file size is zero\n");
  304.         return false;
  305.     }
  306.  
  307.         // Add bounds checking
  308.         if (analyzer.fileSize < sizeof(IMAGE_DOS_HEADER)) {
  309.             OUTPUT("[-] File too small to contain DOS header\n");
  310.             return false;
  311.         }
  312.  
  313.     // DOS Header validation with extensive checks
  314.         analyzer.pDosHeader = static_cast<PIMAGE_DOS_HEADER>(analyzer.lpFileContent);
  315.  
  316.         // Validate DOS header
  317.         if (!IsSafeToRead(analyzer, analyzer.pDosHeader, sizeof(IMAGE_DOS_HEADER))) {
  318.             OUTPUT("[-] Invalid DOS header access\n");
  319.             return false;
  320.         }
  321.  
  322.     // More robust DOS signature check
  323.         if (analyzer.pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  324.             OUTPUT("[-] Invalid DOS signature: 0x%X (Expected 0x%X)\n",
  325.                 analyzer.pDosHeader->e_magic, IMAGE_DOS_SIGNATURE);
  326.             return false;
  327.         }
  328.  
  329.     // Validate e_lfanew with more checks
  330.     if (analyzer.pDosHeader->e_lfanew >= analyzer.fileSize ||
  331.         analyzer.pDosHeader->e_lfanew < sizeof(IMAGE_DOS_HEADER)) {
  332.         OUTPUT("[-] Invalid e_lfanew value: 0x%X\n", analyzer.pDosHeader->e_lfanew);
  333.         return false;
  334.     }
  335.  
  336.     /*analyzer.lpFileContent = mapper.GetView();
  337.     if (!analyzer.lpFileContent) {
  338.         OUTPUT("[-] Failed to get file view. Memory mapping issue.\n");
  339.         return false;
  340.     }
  341.  
  342.     analyzer.fileSize = GetFileSizeCustom(filePath);
  343.     if (!analyzer.fileSize) {
  344.         OUTPUT("[-] Unable to determine file size. File might be empty.\n");
  345.         return false;
  346.     }*/
  347.  
  348.     // Validate file content
  349.     /*if (analyzer.fileSize < sizeof(IMAGE_DOS_HEADER)) {
  350.         OUTPUT("[-] File too small to be a valid PE\n");
  351.         return false;
  352.     }
  353.  
  354.     analyzer.pDosHeader = static_cast<PIMAGE_DOS_HEADER>(analyzer.lpFileContent);
  355.     if (!analyzer.pDosHeader || analyzer.pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
  356.         OUTPUT("[-] Invalid DOS signature\n");
  357.         return false;
  358.     }
  359.  
  360.     // Validate e_lfanew
  361.     if (analyzer.pDosHeader->e_lfanew >= analyzer.fileSize ||
  362.         analyzer.pDosHeader->e_lfanew < sizeof(IMAGE_DOS_HEADER)) {
  363.         OUTPUT("[-] Invalid e_lfanew value\n");
  364.         return false;
  365.     }*/
  366.  
  367.     // Validate NT Headers location
  368.     LONG ntHeaderOffset = analyzer.pDosHeader->e_lfanew;
  369.     if (ntHeaderOffset <= 0 ||
  370.         ntHeaderOffset >= analyzer.fileSize ||
  371.         ntHeaderOffset < sizeof(IMAGE_DOS_HEADER)) {
  372.         OUTPUT("[-] Invalid NT Headers offset: 0x%X\n", ntHeaderOffset);
  373.         return false;
  374.     }
  375.  
  376.     // NT Headers signature validation
  377.     auto pNtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(
  378.         static_cast<BYTE*>(analyzer.lpFileContent) + ntHeaderOffset);
  379.  
  380.     if (pNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
  381.         OUTPUT("[-] Invalid NT signature: 0x%X (Expected 0x%X)\n",
  382.             pNtHeaders->Signature,
  383.             IMAGE_NT_SIGNATURE);
  384.         return false;
  385.     }
  386.  
  387.     /*if (IsBadReadPtr(pNtHeaders, sizeof(IMAGE_NT_HEADERS)) ||
  388.         pNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
  389.         OUTPUT("[-] Invalid NT signature\n");
  390.         return false;
  391.     }*/
  392.  
  393.     // Determine architecture with additional safety checks
  394.     WORD magicNumber = pNtHeaders->OptionalHeader.Magic;
  395.     analyzer.is64Bit = (magicNumber == IMAGE_NT_OPTIONAL_HDR64_MAGIC);
  396.  
  397.     try {
  398.         if (analyzer.is64Bit) {
  399.             analyzer.pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  400.             analyzer.pNtHeaders32 = nullptr;
  401.  
  402.             // Validate 64-bit optional header
  403.             if (pNtHeaders->FileHeader.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64)) {
  404.                 OUTPUT("[-] Invalid 64-bit optional header size\n");
  405.                 return false;
  406.             }
  407.         }
  408.         else {
  409.             analyzer.pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  410.             analyzer.pNtHeaders64 = nullptr;
  411.  
  412.             // Validate 32-bit optional header
  413.             if (pNtHeaders->FileHeader.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)) {
  414.                 OUTPUT("[-] Invalid 32-bit optional header size\n");
  415.                 return false;
  416.             }
  417.         }
  418.     }
  419.     catch (...) {
  420.         OUTPUT("[-] Exception during architecture determination\n");
  421.         return false;
  422.     }
  423.  
  424.     return true;
  425. }
  426. catch (const std::exception& ex) {
  427.     OUTPUT("[-] Initialization error: %s\n", ex.what());
  428.     return false;
  429. }
  430. catch (...) {
  431.     OUTPUT("[-] Unknown initialization error\n");
  432.     return false;
  433. }
  434. }
  435.  
  436. // Helper function for file size
  437. DWORD GetFileSizeCustom(const wchar_t* filePath) {
  438.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  439.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  440.     if (hFile == INVALID_HANDLE_VALUE) return 0;
  441.  
  442.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  443.     CloseHandle(hFile);
  444.     return fileSize;
  445. } //removing other not this duplicate
  446.  
  447. // Main analysis function
  448. void AnalyzePEFile(const wchar_t* filePathW) {
  449.     try {
  450.         if (!filePathW || wcslen(filePathW) == 0) {
  451.             OUTPUT("[-] Invalid file path\n");
  452.             SetStatusText(L"Invalid file path!");
  453.             ShowProgress(0);
  454.             return;
  455.         }
  456.  
  457.  
  458.     /* // Check file extension
  459.     const wchar_t* ext = wcsrchr(filePathW, L'.');
  460.     if (!ext || (wcscmp(ext, L".exe") != 0 && wcscmp(ext, L".dll") != 0)) {
  461.         OUTPUT("[-] Unsupported file type. Use .exe or .dll\n");
  462.         SetStatusText(L"Unsupported file type!");
  463.         ShowProgress(0);
  464.         return;
  465.     } */
  466.  
  467.     /* // Check if file exists
  468.     HANDLE hFile = CreateFileW(filePathW, GENERIC_READ, FILE_SHARE_READ,
  469.         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  470.     if (hFile == INVALID_HANDLE_VALUE) {
  471.         DWORD error = GetLastError();
  472.         OUTPUT("[-] Cannot open file. Error code: %d\n", error);
  473.         SetStatusText(L"Failed to open file!");
  474.         ShowProgress(0);
  475.         return;
  476.     }
  477.     CloseHandle(hFile); */
  478.  
  479.     // Reset and prepare for analysis
  480.         g_OutputText.str(L"");
  481.         g_OutputText.clear();
  482.         UpdateEditControl();
  483.  
  484.         OUTPUT("[+] Starting PE Analysis for: %s\n\n", filePathW);
  485.         SetStatusText(L"Analyzing PE File...");
  486.         ShowProgress(10);
  487.     //ShowProgress(10);
  488.  
  489.         PEAnalyzer analyzer;
  490.         FileMapper mapper;
  491.  
  492.         if (!mapper.Initialize(filePathW)) {
  493.             OUTPUT("[-] Failed to map file\n");
  494.             SetStatusText(L"Analysis Failed - Mapping Error");
  495.             ShowProgress(0);
  496.             return;
  497.         }
  498.  
  499.         // Add safety check
  500.         /*if (!analyzer.lpFileContent || !analyzer.pDosHeader) {
  501.             OUTPUT("[-] Invalid PE file structure\n");
  502.             SetStatusText(L"Invalid PE File");
  503.             ShowProgress(0);
  504.             UpdateEditControl();
  505.             return;
  506.         }*/
  507.  
  508.  
  509.         analyzer.lpFileContent = mapper.GetView();
  510.         analyzer.fileSize = GetFileSizeCustom(filePathW);
  511.  
  512.         if (!InitializePEAnalyzer(analyzer, filePathW)) {
  513.             OUTPUT("[-] PE Initialization Failed\n");
  514.             SetStatusText(L"Analysis Failed - Invalid PE");
  515.             ShowProgress(0);
  516.             return;
  517.         }
  518.  
  519.         // Detailed logging for architecture
  520.         OUTPUT("[+] File Architecture: %s\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  521.  
  522.         // Show initial progress
  523.         //ShowProgress(10);
  524.  
  525.         /* // Add null checks before processing
  526.         if (!analyzer.lpFileContent) {
  527.             OUTPUT("[-] No file content available\n");
  528.             SetStatusText(L"Failed to read file content!");
  529.             ShowProgress(0);
  530.             return;
  531.         }
  532.  
  533.         // Inside AnalyzePEFile, before parsing headers
  534.         if (analyzer.is64Bit) {
  535.             if (!PEHelpers::ValidateFileSize(analyzer.pNtHeaders64->OptionalHeader.SizeOfImage, analyzer.fileSize)) {
  536.                 OUTPUT("[-] PE file size mismatch with 64-bit image size!\n");
  537.                 throw std::runtime_error("Invalid file size or PE image");
  538.             }
  539.         }
  540.         else {
  541.             if (!PEHelpers::ValidateFileSize(analyzer.pNtHeaders32->OptionalHeader.SizeOfImage, analyzer.fileSize)) {
  542.                 OUTPUT("[-] PE file size mismatch with 32-bit image size!\n");
  543.                 throw std::runtime_error("Invalid file size or PE image");
  544.             }
  545.         }*/
  546.  
  547.         // Wrap each analysis step in its own try-catch
  548.         // Basic headers analysis
  549.         try {
  550.             ShowProgress(20);
  551.             AnalyzeHeaders(analyzer);
  552.         }
  553.         catch (const std::exception& ex) {
  554.             OUTPUT("[-] Header Analysis Error: %s\n", ex.what());
  555.         }
  556.         //AnalyzeHeaders(analyzer);
  557.  
  558.         // Data directories
  559.         try {
  560.             ShowProgress(30);
  561.             AnalyzeDataDirectories(analyzer);
  562.         }
  563.         catch (const std::exception& ex) {
  564.             OUTPUT("[-] Data Directories Analysis Error: %s\n", ex.what());
  565.         }
  566.         //AnalyzeDataDirectories(analyzer);
  567.  
  568.         // Parse sections
  569.         try {
  570.             ShowProgress(40);
  571.             ParseSections(analyzer);
  572.         }
  573.         catch (const std::exception& ex) {
  574.             OUTPUT("[-] Sections Parsing Error: %s\n", ex.what());
  575.         }
  576.  
  577.         //ParseSections(analyzer);
  578.  
  579.         // Parse imports
  580.         try {
  581.             ShowProgress(50);
  582.             ParseImportDirectory(analyzer);
  583.         }
  584.         catch (const std::exception& ex) {
  585.             OUTPUT("[-] Import Directory Parsing Error: %s\n", ex.what());
  586.         }
  587.         //ParseImportDirectory(analyzer);
  588.  
  589.         // Parse exports
  590.         try {
  591.             ShowProgress(60);
  592.             ParseExportDirectory(analyzer);
  593.         }
  594.         catch (const std::exception& ex) {
  595.             OUTPUT("[-] Export Directory Parsing Error: %s\n", ex.what());
  596.         }
  597.         //ParseExportDirectory(analyzer);
  598.  
  599.         // Parse resources
  600.         try {
  601.             ShowProgress(70);
  602.             ParseResourceDirectory(analyzer);
  603.         }
  604.         catch (const std::exception& ex) {
  605.             OUTPUT("[-] Resource Directory Parsing Error: %s\n", ex.what());
  606.         }
  607.         //ParseResourceDirectory(analyzer);
  608.  
  609.         // Parse debug info
  610.         try {
  611.             ShowProgress(80);
  612.             ParseDebugDirectory(analyzer);
  613.         }
  614.         catch (const std::exception& ex) {
  615.             OUTPUT("[-] Debug Directory Parsing Error: %s\n", ex.what());
  616.         }
  617.         //ParseDebugDirectory(analyzer);
  618.  
  619.         ShowProgress(100);
  620.         SetStatusText(L"Analysis Complete");
  621.     }
  622.     //}
  623.     catch (const std::exception& ex) {
  624.         OUTPUT("[-] Analysis failed: %s\n", ex.what());
  625.         SetStatusText(L"Analysis Failed - Exception");
  626.         ShowProgress(0);
  627.     }
  628.     catch (...) {
  629.         OUTPUT("[-] Unknown error during analysis\n");
  630.         SetStatusText(L"Analysis Failed - Unknown Error");
  631.         ShowProgress(0);
  632.     }
  633.     /*catch (const std::exception& ex) {
  634.         OUTPUT("[-] Exception during analysis: %s\n", ex.what());
  635.         SetStatusText(L"Analysis failed due to error.");
  636.         ShowProgress(0);
  637.         return;
  638.     }*/ //newly commented out
  639.     /*catch (const std::exception& e) {
  640.         OUTPUT("[-] Error during analysis: %s\n", e.what());
  641.         SetStatusText(L"Analysis failed!");
  642.     }*/
  643.  
  644.     //ShowWindow(g_hProgressBar, SW_HIDE);
  645.     // Ensure edit control is updated
  646.     UpdateEditControl();
  647.     //analyzer.~PEAnalyzer(); // Explicit call to the destructor if not already invoked
  648. }
  649.  
  650. //amalgamating parsing funcs here experimental
  651.  
  652.     // Header analysis function
  653. void AnalyzeHeaders(const PEAnalyzer& analyzer) {
  654.     if (!analyzer.lpFileContent || !analyzer.pDosHeader) {
  655.         throw std::runtime_error("Invalid PE headers");
  656.     }
  657.  
  658.     OUTPUT("[+] PE IMAGE INFORMATION\n\n");
  659.     OUTPUT("[+] Architecture: %s\n\n", analyzer.is64Bit ? "x64" : "x86");
  660.  
  661.     // DOS Header
  662.     OUTPUT("[+] DOS HEADER\n");
  663.     OUTPUT("\te_magic    : 0x%X\n", analyzer.pDosHeader->e_magic);
  664.     OUTPUT("\te_cblp     : 0x%X\n", analyzer.pDosHeader->e_cblp);
  665.     OUTPUT("\te_cp       : 0x%X\n", analyzer.pDosHeader->e_cp);
  666.     OUTPUT("\te_crlc     : 0x%X\n", analyzer.pDosHeader->e_crlc);
  667.     OUTPUT("\te_cparhdr  : 0x%X\n", analyzer.pDosHeader->e_cparhdr);
  668.     OUTPUT("\te_minalloc : 0x%X\n", analyzer.pDosHeader->e_minalloc);
  669.     OUTPUT("\te_maxalloc : 0x%X\n", analyzer.pDosHeader->e_maxalloc);
  670.     OUTPUT("\te_ss       : 0x%X\n", analyzer.pDosHeader->e_ss);
  671.     OUTPUT("\te_sp       : 0x%X\n", analyzer.pDosHeader->e_sp);
  672.     OUTPUT("\te_csum     : 0x%X\n", analyzer.pDosHeader->e_csum);
  673.     OUTPUT("\te_ip       : 0x%X\n", analyzer.pDosHeader->e_ip);
  674.     OUTPUT("\te_cs       : 0x%X\n", analyzer.pDosHeader->e_cs);
  675.     OUTPUT("\te_lfarlc   : 0x%X\n", analyzer.pDosHeader->e_lfarlc);
  676.     OUTPUT("\te_ovno     : 0x%X\n", analyzer.pDosHeader->e_ovno);
  677.     OUTPUT("\te_oemid    : 0x%X\n", analyzer.pDosHeader->e_oemid);
  678.     OUTPUT("\te_oeminfo  : 0x%X\n", analyzer.pDosHeader->e_oeminfo);
  679.     OUTPUT("\te_lfanew   : 0x%X\n\n", analyzer.pDosHeader->e_lfanew);
  680.  
  681.     // NT Headers
  682.     if (analyzer.is64Bit && analyzer.pNtHeaders64) {
  683.         ParseNTHeader64(analyzer);
  684.         //AnalyzeNTHeaders64(analyzer);
  685.     }
  686.     else if (analyzer.pNtHeaders32) {
  687.         ParseNTHeader32(analyzer);
  688.         //AnalyzeNTHeaders32(analyzer);
  689.     }
  690.     else {
  691.         throw std::runtime_error("Invalid NT headers");
  692.     }
  693. }
  694.  
  695. void ParseNTHeader32(const PEAnalyzer& analyzer) {
  696.     if (!analyzer.pNtHeaders32) {
  697.         throw std::runtime_error("Invalid NT headers");
  698.     }
  699.  
  700.     OUTPUT("[+] NT HEADER (32-bit)\n");
  701.     OUTPUT("\tSignature: 0x%X\n\n", analyzer.pNtHeaders32->Signature);
  702.  
  703.     // File Header
  704.     OUTPUT("[+] FILE HEADER\n");
  705.     OUTPUT("\tMachine: 0x%X\n", analyzer.pNtHeaders32->FileHeader.Machine);
  706.     OUTPUT("\tNumberOfSections: 0x%X\n", analyzer.pNtHeaders32->FileHeader.NumberOfSections);
  707.     OUTPUT("\tTimeDateStamp: 0x%X\n", analyzer.pNtHeaders32->FileHeader.TimeDateStamp);
  708.     OUTPUT("\tPointerToSymbolTable: 0x%X\n", analyzer.pNtHeaders32->FileHeader.PointerToSymbolTable);
  709.     OUTPUT("\tNumberOfSymbols: 0x%X\n", analyzer.pNtHeaders32->FileHeader.NumberOfSymbols);
  710.     OUTPUT("\tSizeOfOptionalHeader: 0x%X\n", analyzer.pNtHeaders32->FileHeader.SizeOfOptionalHeader);
  711.     OUTPUT("\tCharacteristics: 0x%X\n\n", analyzer.pNtHeaders32->FileHeader.Characteristics);
  712.  
  713.     // Optional Header
  714.     OUTPUT("[+] OPTIONAL HEADER\n");
  715.     OUTPUT("\tMagic: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.Magic);
  716.     OUTPUT("\tAddressOfEntryPoint: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.AddressOfEntryPoint);
  717.     OUTPUT("\tImageBase: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.ImageBase);
  718.     OUTPUT("\tSectionAlignment: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SectionAlignment);
  719.     OUTPUT("\tFileAlignment: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.FileAlignment);
  720.     OUTPUT("\tSizeOfImage: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SizeOfImage);
  721.     OUTPUT("\tSizeOfHeaders: 0x%X\n", analyzer.pNtHeaders32->OptionalHeader.SizeOfHeaders);
  722.     OUTPUT("\tSubsystem: 0x%X\n\n", analyzer.pNtHeaders32->OptionalHeader.Subsystem);
  723. }
  724.  
  725. void ParseNTHeader64(const PEAnalyzer& analyzer) {
  726.     if (!analyzer.pNtHeaders64) {
  727.         throw std::runtime_error("Invalid NT headers");
  728.     }
  729.  
  730.     OUTPUT("[+] NT HEADER (64-bit)\n");
  731.     OUTPUT("\tSignature: 0x%X\n\n", analyzer.pNtHeaders64->Signature);
  732.  
  733.     // File Header
  734.     OUTPUT("[+] FILE HEADER\n");
  735.     OUTPUT("\tMachine: 0x%X\n", analyzer.pNtHeaders64->FileHeader.Machine);
  736.     OUTPUT("\tNumberOfSections: 0x%X\n", analyzer.pNtHeaders64->FileHeader.NumberOfSections);
  737.     OUTPUT("\tTimeDateStamp: 0x%X\n", analyzer.pNtHeaders64->FileHeader.TimeDateStamp);
  738.     OUTPUT("\tPointerToSymbolTable: 0x%X\n", analyzer.pNtHeaders64->FileHeader.PointerToSymbolTable);
  739.     OUTPUT("\tNumberOfSymbols: 0x%X\n", analyzer.pNtHeaders64->FileHeader.NumberOfSymbols);
  740.     OUTPUT("\tSizeOfOptionalHeader: 0x%X\n", analyzer.pNtHeaders64->FileHeader.SizeOfOptionalHeader);
  741.     OUTPUT("\tCharacteristics: 0x%X\n\n", analyzer.pNtHeaders64->FileHeader.Characteristics);
  742.  
  743.     // Optional Header
  744.     OUTPUT("[+] OPTIONAL HEADER\n");
  745.     OUTPUT("\tMagic: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.Magic);
  746.     OUTPUT("\tAddressOfEntryPoint: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.AddressOfEntryPoint);
  747.     OUTPUT("\tImageBase: 0x%llX\n", analyzer.pNtHeaders64->OptionalHeader.ImageBase);
  748.     OUTPUT("\tSectionAlignment: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SectionAlignment);
  749.     OUTPUT("\tFileAlignment: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.FileAlignment);
  750.     OUTPUT("\tSizeOfImage: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SizeOfImage);
  751.     OUTPUT("\tSizeOfHeaders: 0x%X\n", analyzer.pNtHeaders64->OptionalHeader.SizeOfHeaders);
  752.     OUTPUT("\tSubsystem: 0x%X\n\n", analyzer.pNtHeaders64->OptionalHeader.Subsystem);
  753. }
  754. //}
  755.  
  756.         //russianheat (clipped peanalyzefile() code here)
  757.  
  758.  
  759.         // Data Directories analysis
  760. void AnalyzeDataDirectories(const PEAnalyzer& analyzer) {
  761.     OUTPUT("[+] DATA DIRECTORIES\n");
  762.     const IMAGE_DATA_DIRECTORY* dataDirectories = analyzer.is64Bit ?
  763.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory :
  764.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory;
  765.  
  766.     for (int i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++) {
  767.         if (dataDirectories[i].VirtualAddress != 0) {
  768.             OUTPUT("\t%s:\n", PEHelpers::GetDataDirectoryName(i).c_str());
  769.             OUTPUT("\t\tVirtualAddress: 0x%X\n", dataDirectories[i].VirtualAddress);
  770.             OUTPUT("\t\tSize: 0x%X\n", dataDirectories[i].Size);
  771.         }
  772.     }
  773.     OUTPUT("\n");
  774. }
  775.  
  776. // Safe memory check helper
  777. template<typename T>
  778. bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size) {
  779.     if (!ptr) return false;
  780.     DWORD_PTR start = reinterpret_cast<DWORD_PTR>(analyzer.lpFileContent);
  781.     DWORD_PTR end = start + analyzer.fileSize;
  782.     DWORD_PTR ptrAddr = reinterpret_cast<DWORD_PTR>(ptr);
  783.     return (ptrAddr >= start && (ptrAddr + size) <= end);
  784. }
  785.  
  786. // Section parsing with safety checks
  787. void ParseSections(const PEAnalyzer& analyzer) {
  788.     OUTPUT("[+] SECTION HEADERS\n");
  789.  
  790.     PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(
  791.         analyzer.is64Bit ?
  792.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  793.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32));
  794.  
  795.     WORD numberOfSections = analyzer.is64Bit ?
  796.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  797.         analyzer.pNtHeaders32->FileHeader.NumberOfSections;
  798.  
  799.     if (!IsSafeToRead(analyzer, pSection,
  800.         sizeof(IMAGE_SECTION_HEADER) * numberOfSections)) {
  801.         throw std::runtime_error("Invalid section headers");
  802.     }
  803.  
  804.     for (WORD i = 0; i < numberOfSections; i++, pSection++) {
  805.         char sectionName[IMAGE_SIZEOF_SHORT_NAME + 1] = {};
  806.         memcpy(sectionName, pSection->Name, IMAGE_SIZEOF_SHORT_NAME);
  807.  
  808.         // Sanitize section name
  809.         for (int j = 0; j < IMAGE_SIZEOF_SHORT_NAME; j++) {
  810.             if (!isprint(static_cast<unsigned char>(sectionName[j]))) {
  811.                 sectionName[j] = '\0';
  812.                 break;
  813.             }
  814.         }
  815.  
  816.         // Output section information
  817.         OUTPUT("\tSECTION: %s\n", sectionName);
  818.         OUTPUT("\t\tVirtualSize: 0x%X\n", pSection->Misc.VirtualSize);
  819.         OUTPUT("\t\tVirtualAddress: 0x%X\n", pSection->VirtualAddress);
  820.         OUTPUT("\t\tSizeOfRawData: 0x%X\n", pSection->SizeOfRawData);
  821.         OUTPUT("\t\tPointerToRawData: 0x%X\n", pSection->PointerToRawData);
  822.         OUTPUT("\t\tPointerToRelocations: 0x%X\n", pSection->PointerToRelocations);
  823.         OUTPUT("\t\tPointerToLinenumbers: 0x%X\n", pSection->PointerToLinenumbers);
  824.         OUTPUT("\t\tNumberOfRelocations: 0x%X\n", pSection->NumberOfRelocations);
  825.         OUTPUT("\t\tNumberOfLinenumbers: 0x%X\n", pSection->NumberOfLinenumbers);
  826.         OUTPUT("\t\tCharacteristics: 0x%X %s\n\n",
  827.             pSection->Characteristics,
  828.             PEHelpers::GetSectionProtection(pSection->Characteristics).c_str());
  829.     }
  830. } //end of parsesection here
  831.  
  832.     // Import Directory parsing with safety checks
  833. void ParseImportDirectory(const PEAnalyzer& analyzer) {
  834.     const auto& importDir = analyzer.is64Bit ?
  835.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] :
  836.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  837.  
  838.     if (!importDir.VirtualAddress || !importDir.Size) {
  839.         OUTPUT("\n[-] No import directory found.\n");
  840.         return;
  841.     }
  842.  
  843.     OUTPUT("\n[+] IMPORT DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  844.  
  845.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  846.         importDir.VirtualAddress,
  847.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  848.             (PIMAGE_NT_HEADERS)analyzer.pNtHeaders64 :
  849.             (PIMAGE_NT_HEADERS)analyzer.pNtHeaders32),
  850.         analyzer.is64Bit ?
  851.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  852.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  853.         analyzer.lpFileContent,
  854.         analyzer.fileSize);
  855.  
  856.     if (!IsSafeToRead(analyzer, pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  857.         throw std::runtime_error("Invalid import descriptor");
  858.     }
  859.  
  860.     while (pImportDesc->Name != 0) {
  861.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  862.             pImportDesc->Name,
  863.             IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  864.                 reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  865.                 reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  866.             analyzer.is64Bit ?
  867.             analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  868.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  869.             analyzer.lpFileContent,
  870.             analyzer.fileSize);
  871.  
  872.         if (!IsSafeToRead(analyzer, dllName, 1)) {
  873.             break;
  874.         }
  875.  
  876.         OUTPUT("\n\tDLL NAME: %s\n", dllName);
  877.         OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  878.         OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  879.         OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  880.         OUTPUT("\tFirstThunk: 0x%X\n\n", pImportDesc->FirstThunk);
  881.         OUTPUT("\tImported Functions:\n");
  882.  
  883.         // Parse functions based on architecture
  884.         if (analyzer.is64Bit) {
  885.             ParseImportFunctions64(analyzer, pImportDesc);
  886.         }
  887.         else {
  888.             ParseImportFunctions32(analyzer, pImportDesc);
  889.         }
  890.  
  891.         pImportDesc++;
  892.         if (!IsSafeToRead(analyzer, pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  893.             break;
  894.         }
  895.     }
  896. }
  897.  
  898. void ParseImportFunctions32(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc) {
  899.     auto pThunk = (PIMAGE_THUNK_DATA32)PEHelpers::GetRvaPtr(
  900.         pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  901.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  902.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  903.         analyzer.lpFileContent,
  904.         analyzer.fileSize);
  905.  
  906.     while (pThunk && pThunk->u1.AddressOfData) {
  907.         if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)) {
  908.             auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  909.                 pThunk->u1.AddressOfData,
  910.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  911.                 analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  912.                 analyzer.lpFileContent,
  913.                 analyzer.fileSize);
  914.  
  915.             if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  916.                 OUTPUT("\t\t%s\n", pImportByName->Name);
  917.             }
  918.         }
  919.         else {
  920.             OUTPUT("\t\tOrdinal: %d\n", pThunk->u1.Ordinal & 0xFFFF);
  921.         }
  922.         pThunk++;
  923.     }
  924. }
  925.  
  926. void ParseImportFunctions64(const PEAnalyzer& analyzer, PIMAGE_IMPORT_DESCRIPTOR pImportDesc) {
  927.     auto pThunk = (PIMAGE_THUNK_DATA64)PEHelpers::GetRvaPtr(
  928.         pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  929.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  930.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  931.         analyzer.lpFileContent,
  932.         analyzer.fileSize);
  933.  
  934.     while (pThunk && pThunk->u1.AddressOfData) {
  935.         if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)) {
  936.             auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  937.                 (DWORD)pThunk->u1.AddressOfData,
  938.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  939.                 analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  940.                 analyzer.lpFileContent,
  941.                 analyzer.fileSize);
  942.  
  943.             if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  944.                 OUTPUT("\t\t%s\n", pImportByName->Name);
  945.             }
  946.         }
  947.         else {
  948.             OUTPUT("\t\tOrdinal: %lld\n", pThunk->u1.Ordinal & 0xFFFF);
  949.         }
  950.         pThunk++;
  951.     }
  952. }
  953.  
  954. // Export Directory parsing with safety checks
  955. void ParseExportDirectory(const PEAnalyzer& analyzer) {
  956.     const auto& exportDir = analyzer.is64Bit ?
  957.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] :
  958.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  959.  
  960.     if (!exportDir.VirtualAddress || !exportDir.Size) {
  961.         OUTPUT("\n[-] No export directory found.\n");
  962.         return;
  963.     }
  964.  
  965.     OUTPUT("\n[+] EXPORT DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  966.  
  967.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  968.         exportDir.VirtualAddress,
  969.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  970.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  971.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  972.         analyzer.is64Bit ?
  973.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  974.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  975.         analyzer.lpFileContent,
  976.         analyzer.fileSize);
  977.  
  978.     if (!IsSafeToRead(analyzer, pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  979.         throw std::runtime_error("Invalid export directory");
  980.     }
  981.  
  982.     // Output export directory information
  983.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  984.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  985.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  986.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  987.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  988.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  989.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  990.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  991.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  992.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  993.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  994.  
  995.     // Get export tables with safety checks
  996.  
  997.     // Add IMAGE_FIRST_SECTION and section count parameters
  998.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfFunctions,
  999.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1000.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1001.         analyzer.lpFileContent,
  1002.         analyzer.fileSize);
  1003.  
  1004.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNames,
  1005.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1006.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1007.         analyzer.lpFileContent,
  1008.         analyzer.fileSize);
  1009.  
  1010.     auto pOrdinals = (PWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNameOrdinals,
  1011.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1012.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1013.         analyzer.lpFileContent,
  1014.         analyzer.fileSize);
  1015.  
  1016.     //auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfFunctions, /*...*/);
  1017.     //auto pNames = (PDWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNames, /*...*/);
  1018.     //auto pOrdinals = (PWORD)PEHelpers::GetRvaPtr(pExportDir->AddressOfNameOrdinals, /*...*/);
  1019.  
  1020.     if (!IsSafeToRead(analyzer, pFunctions, sizeof(DWORD) * pExportDir->NumberOfFunctions) ||
  1021.         !IsSafeToRead(analyzer, pNames, sizeof(DWORD) * pExportDir->NumberOfNames) ||
  1022.         !IsSafeToRead(analyzer, pOrdinals, sizeof(WORD) * pExportDir->NumberOfNames)) {
  1023.         throw std::runtime_error("Invalid export tables");
  1024.     }
  1025.  
  1026.     // Parse and output exported functions
  1027.     ParseExportedFunctions(analyzer, pExportDir, pFunctions, pNames, pOrdinals);
  1028. }
  1029.  
  1030. void ParseExportedFunctions(const PEAnalyzer& analyzer, PIMAGE_EXPORT_DIRECTORY pExportDir,
  1031.     PDWORD pFunctions, PDWORD pNames, PWORD pOrdinals) {
  1032.  
  1033.     OUTPUT("\tExported Functions:\n\n");
  1034.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1035.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1036.             IsBadReadPtr(pOrdinals + i, sizeof(WORD))) {
  1037.             break;
  1038.         }
  1039.  
  1040.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1041.             pNames[i],
  1042.             analyzer.is64Bit ? IMAGE_FIRST_SECTION((PIMAGE_NT_HEADERS64)analyzer.pNtHeaders64) : IMAGE_FIRST_SECTION((PIMAGE_NT_HEADERS32)analyzer.pNtHeaders32),
  1043.             analyzer.is64Bit ? analyzer.pNtHeaders64->FileHeader.NumberOfSections : analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1044.             analyzer.lpFileContent,
  1045.             analyzer.fileSize);
  1046.  
  1047.         /*const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1048.             pNames[i],
  1049.             IMAGE_FIRST_SECTION(analyzer.is64Bit ? analyzer.pNtHeaders64 : analyzer.pNtHeaders32),
  1050.             analyzer.is64Bit ? analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1051.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1052.             analyzer.lpFileContent);*/
  1053.  
  1054.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1055.             WORD ordinal = pOrdinals[i];
  1056.             if (ordinal < pExportDir->NumberOfFunctions) {
  1057.                 DWORD functionRva = pFunctions[ordinal];
  1058.                 OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1059.                     functionName,
  1060.                     ordinal + pExportDir->Base,
  1061.                     functionRva);
  1062.             }
  1063.         }
  1064.     }
  1065. }
  1066.  
  1067. void ParseResourceDirectory(const PEAnalyzer& analyzer) {
  1068.     const auto& resourceDir = analyzer.is64Bit ?
  1069.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] :
  1070.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
  1071.  
  1072.     if (!resourceDir.VirtualAddress || !resourceDir.Size) {
  1073.         OUTPUT("\n[-] No resource directory found.\n");
  1074.         return;
  1075.     }
  1076.  
  1077.     OUTPUT("\n[+] RESOURCE DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  1078.  
  1079.     auto pResourceDir = (PIMAGE_RESOURCE_DIRECTORY)PEHelpers::GetRvaPtr(
  1080.         resourceDir.VirtualAddress,
  1081.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  1082.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  1083.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  1084.         analyzer.is64Bit ?
  1085.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1086.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1087.         analyzer.lpFileContent,
  1088.         analyzer.fileSize);
  1089.  
  1090.     if (!IsSafeToRead(analyzer, pResourceDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1091.         throw std::runtime_error("Invalid resource directory");
  1092.     }
  1093.  
  1094.     ProcessResourceDirectory(pResourceDir, 0, nullptr, pResourceDir, analyzer);
  1095. }
  1096.  
  1097. void ProcessResourceDirectory(
  1098.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1099.     int level,
  1100.     const wchar_t* type,
  1101.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1102.     const PEAnalyzer& analyzer)
  1103. {
  1104.     if (!IsSafeToRead(analyzer, resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1105.         return;
  1106.     }
  1107.  
  1108.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1109.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1110.  
  1111.     for (WORD i = 0; i < totalEntries; i++) {
  1112.         if (!IsSafeToRead(analyzer, entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1113.             break;
  1114.         }
  1115.  
  1116.         // Indent based on level
  1117.         for (int indent = 0; indent < level; indent++) {
  1118.             OUTPUT("\t");
  1119.         }
  1120.  
  1121.         // Process named entries
  1122.         if (entry[i].NameIsString) {
  1123.             ProcessNamedResourceEntry(entry[i], level, baseResourceDir, analyzer);
  1124.         }
  1125.         // Process ID entries
  1126.         else {
  1127.             ProcessIdResourceEntry(entry[i], level, type, baseResourceDir, analyzer);
  1128.         }
  1129.  
  1130.         // Process subdirectories or data
  1131.         if (entry[i].DataIsDirectory) {
  1132.             ProcessResourceSubdirectory(entry[i], level, type, baseResourceDir, analyzer);
  1133.         }
  1134.         else {
  1135.             ProcessResourceData(entry[i], level, type, baseResourceDir, analyzer);
  1136.         }
  1137.     }
  1138. }
  1139.  
  1140. //newlyfrom You,com Claude
  1141. void ProcessNamedResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1142.     int level, PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1143.     const PEAnalyzer& analyzer) {
  1144.  
  1145.     auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry.NameOffset);
  1146.     if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1147.         std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1148.         wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1149.             nameEntry->NameString, nameEntry->Length);
  1150.         resourceName[nameEntry->Length] = L'\0';
  1151.  
  1152.         if (level == 0) {
  1153.             OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1154.         }
  1155.         else {
  1156.             OUTPUT("Name: %s\n", resourceName.data());
  1157.         }
  1158.     }
  1159. }
  1160.  
  1161. void ProcessIdResourceEntry(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1162.     int level, const wchar_t* type,
  1163.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1164.     const PEAnalyzer& analyzer) {
  1165.  
  1166.     if (level == 0) {
  1167.         DWORD resourceType = entry.Id;
  1168.         if (resourceType < 16) {
  1169.             OUTPUT("Resource Type: %s (ID: %d)\n", RESOURCE_TYPES[resourceType], resourceType);
  1170.         }
  1171.         else {
  1172.             OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1173.         }
  1174.     }
  1175.     else {
  1176.         OUTPUT("ID: %d\n", entry.Id);
  1177.     }
  1178. }
  1179.  
  1180. void ProcessResourceSubdirectory(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1181.     int level, const wchar_t* type,
  1182.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1183.     const PEAnalyzer& analyzer) {
  1184.  
  1185.     auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry.OffsetToDirectory);
  1186.     if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1187.         ProcessResourceDirectory(nextDir, level + 1,
  1188.             level == 0 ? RESOURCE_TYPES[min(entry.Id, 15)] : type,
  1189.             baseResourceDir, analyzer);
  1190.     }
  1191. }
  1192.  
  1193. void ProcessResourceData(const IMAGE_RESOURCE_DIRECTORY_ENTRY& entry,
  1194.     int level, const wchar_t* type,
  1195.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1196.     const PEAnalyzer& analyzer) {
  1197.  
  1198.     auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry.OffsetToData);
  1199.     if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1200.         for (int indent = 0; indent < level + 1; indent++) {
  1201.             OUTPUT("\t");
  1202.         }
  1203.         OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1204.     }
  1205. }
  1206.  
  1207. void ParseDebugDirectory(const PEAnalyzer& analyzer) {
  1208.     const auto& debugDir = analyzer.is64Bit ?
  1209.         analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG] :
  1210.         analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  1211.  
  1212.     if (!debugDir.VirtualAddress || !debugDir.Size) {
  1213.         OUTPUT("\n[-] No debug directory found.\n");
  1214.         return;
  1215.     }
  1216.  
  1217.     OUTPUT("\n[+] DEBUG DIRECTORY (%s)\n", analyzer.is64Bit ? "64-bit" : "32-bit");
  1218.  
  1219.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  1220.         debugDir.VirtualAddress,
  1221.         IMAGE_FIRST_SECTION(analyzer.is64Bit ?
  1222.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64) :
  1223.             reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32)),
  1224.         analyzer.is64Bit ?
  1225.         analyzer.pNtHeaders64->FileHeader.NumberOfSections :
  1226.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1227.         analyzer.lpFileContent,
  1228.         analyzer.fileSize);
  1229.  
  1230.     if (!IsSafeToRead(analyzer, pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  1231.         throw std::runtime_error("Invalid debug directory");
  1232.     }
  1233.  
  1234.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  1235.     for (DWORD i = 0; i < numEntries; i++) {
  1236.         ProcessDebugEntry(pDebugDir[i], analyzer);
  1237.     }
  1238. }
  1239.  
  1240. void ProcessDebugEntry(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer) {
  1241.     OUTPUT("\tDebug Entry:\n");
  1242.     OUTPUT("\tCharacteristics: 0x%X\n", debugEntry.Characteristics);
  1243.     OUTPUT("\tTimeDateStamp: 0x%X\n", debugEntry.TimeDateStamp);
  1244.     OUTPUT("\tVersion: %d.%d\n", debugEntry.MajorVersion, debugEntry.MinorVersion);
  1245.     OUTPUT("\tType: 0x%X", debugEntry.Type);
  1246.  
  1247.     // Output debug type
  1248.     switch (debugEntry.Type) {
  1249.     case IMAGE_DEBUG_TYPE_COFF:
  1250.         OUTPUT(" (COFF)\n"); break;
  1251.     case IMAGE_DEBUG_TYPE_CODEVIEW:
  1252.         OUTPUT(" (CodeView)\n");
  1253.         ProcessCodeViewDebugInfo(debugEntry, analyzer);
  1254.         break;
  1255.         // ... other debug types ...
  1256.     default:
  1257.         OUTPUT(" (Unknown)\n"); break;
  1258.     }
  1259.  
  1260.     OUTPUT("\tSizeOfData: 0x%X\n", debugEntry.SizeOfData);
  1261.     OUTPUT("\tAddressOfRawData: 0x%X\n", debugEntry.AddressOfRawData);
  1262.     OUTPUT("\tPointerToRawData: 0x%X\n\n", debugEntry.PointerToRawData);
  1263. }
  1264.  
  1265. // Helper functions for processing specific debug info types
  1266. void ProcessCodeViewDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, const PEAnalyzer& analyzer) {
  1267.     if (debugEntry.Type != IMAGE_DEBUG_TYPE_CODEVIEW ||
  1268.         !debugEntry.PointerToRawData ||
  1269.         debugEntry.SizeOfData < sizeof(DWORD)) {
  1270.         return;
  1271.     }
  1272.  
  1273.     auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + debugEntry.PointerToRawData);
  1274.     if (!IsSafeToRead(analyzer, pCVHeader, sizeof(DWORD))) {
  1275.         return;
  1276.     }
  1277.  
  1278.     // Process different CodeView formats
  1279.     switch (*pCVHeader) {
  1280.     case 0x53445352: // 'RSDS'
  1281.         ProcessRSDSDebugInfo(debugEntry, pCVHeader, analyzer);
  1282.         break;
  1283.     case 0x3031424E: // 'NB10'
  1284.         ProcessNB10DebugInfo(debugEntry, pCVHeader, analyzer);
  1285.         break;
  1286.     }
  1287. }
  1288.  
  1289. void ProcessRSDSDebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  1290.     const PEAnalyzer& analyzer) {
  1291.  
  1292.     if (debugEntry.SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  1293.         auto pCVData = (char*)(pCVHeader + 1);
  1294.         if (!IsBadReadPtr(pCVData + 16, 1)) {
  1295.             auto guid = (GUID*)pCVData;
  1296.             DWORD age = *(DWORD*)(pCVData + 16);
  1297.             const char* pdbPath = pCVData + 20;
  1298.  
  1299.             OUTPUT("\tPDB Information:\n");
  1300.             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  1301.                 guid->Data1, guid->Data2, guid->Data3,
  1302.                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  1303.                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  1304.             OUTPUT("\tAge: %d\n", age);
  1305.             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  1306.         }
  1307.     }
  1308. }
  1309.  
  1310. void ProcessNB10DebugInfo(const IMAGE_DEBUG_DIRECTORY& debugEntry, DWORD* pCVHeader,
  1311.     const PEAnalyzer& analyzer) {
  1312.  
  1313.     if (debugEntry.SizeOfData >= 16) {
  1314.         auto pNB10Data = (char*)(pCVHeader + 1);
  1315.         DWORD offset = *(DWORD*)pNB10Data;
  1316.         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  1317.         DWORD age = *(DWORD*)(pNB10Data + 8);
  1318.         const char* pdbPath = pNB10Data + 12;
  1319.  
  1320.         OUTPUT("\tPDB Information (NB10):\n");
  1321.         OUTPUT("\tOffset: 0x%X\n", offset);
  1322.         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  1323.         OUTPUT("\tAge: %d\n", age);
  1324.         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  1325.     }
  1326. }
  1327.  
  1328. //colonelburton
  1329.  
  1330. void ParseImportDirectory32(const PEAnalyzer& analyzer) {
  1331.     const auto& importDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  1332.     if (!importDir.VirtualAddress || !importDir.Size) return;
  1333.  
  1334.     if (!PEHelpers::IsRvaValid(importDir.VirtualAddress, analyzer.fileSize,
  1335.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1336.         OUTPUT("[-] Invalid import directory RVA!\n");
  1337.         throw std::runtime_error("RVA out of bounds");
  1338.         return;
  1339.     }
  1340.  
  1341.     OUTPUT("\n[+] IMPORT DIRECTORY (32-bit)\n");
  1342.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  1343.         importDir.VirtualAddress,
  1344.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1345.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1346.         analyzer.lpFileContent,
  1347.         analyzer.fileSize);
  1348.  
  1349.     if (!pImportDesc) return;
  1350.  
  1351.     while (pImportDesc->Name != 0) {
  1352.         if (IsBadReadPtr(pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  1353.             OUTPUT("[-] Invalid import descriptor detected!\n");
  1354.             break;
  1355.         }
  1356.  
  1357.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  1358.             pImportDesc->Name,
  1359.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1360.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1361.             analyzer.lpFileContent,
  1362.             analyzer.fileSize);
  1363.  
  1364.         if (dllName && !IsBadReadPtr(dllName, 1)) {
  1365.             std::vector<wchar_t> wideDllName(MAX_PATH);
  1366.             MultiByteToWideChar(CP_ACP, 0, dllName, -1, wideDllName.data(), MAX_PATH);
  1367.  
  1368.             OUTPUT("\n\tDLL NAME: %s\n", wideDllName.data());
  1369.             OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  1370.             OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  1371.             OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  1372.             OUTPUT("\tFirstThunk: 0x%X\n", pImportDesc->FirstThunk);
  1373.             OUTPUT("\n\tImported Functions:\n");
  1374.  
  1375.             auto pThunk = (PIMAGE_THUNK_DATA32)PEHelpers::GetRvaPtr(
  1376.                 pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  1377.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1378.                 analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1379.                 analyzer.lpFileContent,
  1380.                 analyzer.fileSize);
  1381.  
  1382.             while (pThunk && pThunk->u1.AddressOfData) {
  1383.                 if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)) {
  1384.                     auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  1385.                         pThunk->u1.AddressOfData,
  1386.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1387.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1388.                         analyzer.lpFileContent,
  1389.                         analyzer.fileSize);
  1390.  
  1391.                     if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  1392.                         std::vector<wchar_t> wideFuncName(MAX_PATH);
  1393.                         MultiByteToWideChar(CP_ACP, 0, (char*)pImportByName->Name, -1,
  1394.                             wideFuncName.data(), MAX_PATH);
  1395.                         OUTPUT("\t\t%s\n", wideFuncName.data());
  1396.                     }
  1397.                 }
  1398.                 else {
  1399.                     OUTPUT("\t\tOrdinal: %d\n", pThunk->u1.Ordinal & 0xFFFF);
  1400.                 }
  1401.                 pThunk++;
  1402.             }
  1403.         }
  1404.         pImportDesc++;
  1405.     }
  1406. }
  1407.  
  1408. void ParseImportDirectory64(const PEAnalyzer& analyzer) {
  1409.     const auto& importDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  1410.     if (!importDir.VirtualAddress || !importDir.Size) return;
  1411.  
  1412.     if (!PEHelpers::IsRvaValid(importDir.VirtualAddress, analyzer.fileSize,
  1413.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  1414.         OUTPUT("[-] Invalid import directory RVA!\n");
  1415.         throw std::runtime_error("RVA out of bounds");
  1416.         return;
  1417.     }
  1418.  
  1419.     OUTPUT("\n[+] IMPORT DIRECTORY (64-bit)\n");
  1420.     auto pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)PEHelpers::GetRvaPtr(
  1421.         importDir.VirtualAddress,
  1422.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1423.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1424.         analyzer.lpFileContent,
  1425.         analyzer.fileSize);
  1426.  
  1427.     if (!pImportDesc) return;
  1428.  
  1429.     while (pImportDesc->Name != 0) {
  1430.         if (IsBadReadPtr(pImportDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
  1431.             OUTPUT("[-] Invalid import descriptor detected!\n");
  1432.             break;
  1433.         }
  1434.  
  1435.         const char* dllName = (const char*)PEHelpers::GetRvaPtr(
  1436.             pImportDesc->Name,
  1437.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1438.             analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1439.             analyzer.lpFileContent,
  1440.             analyzer.fileSize);
  1441.  
  1442.         if (dllName && !IsBadReadPtr(dllName, 1)) {
  1443.             std::vector<wchar_t> wideDllName(MAX_PATH);
  1444.             MultiByteToWideChar(CP_ACP, 0, dllName, -1, wideDllName.data(), MAX_PATH);
  1445.  
  1446.             OUTPUT("\n\tDLL NAME: %s\n", wideDllName.data());
  1447.             OUTPUT("\tCharacteristics: 0x%X\n", pImportDesc->Characteristics);
  1448.             OUTPUT("\tTimeDateStamp: 0x%X\n", pImportDesc->TimeDateStamp);
  1449.             OUTPUT("\tForwarderChain: 0x%X\n", pImportDesc->ForwarderChain);
  1450.             OUTPUT("\tFirstThunk: 0x%X\n", pImportDesc->FirstThunk);
  1451.             OUTPUT("\n\tImported Functions:\n");
  1452.  
  1453.             auto pThunk = (PIMAGE_THUNK_DATA64)PEHelpers::GetRvaPtr(
  1454.                 pImportDesc->OriginalFirstThunk ? pImportDesc->OriginalFirstThunk : pImportDesc->FirstThunk,
  1455.                 IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1456.                 analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1457.                 analyzer.lpFileContent,
  1458.                 analyzer.fileSize);
  1459.  
  1460.             while (pThunk && pThunk->u1.AddressOfData) {
  1461.                 if (!(pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)) {
  1462.                     auto pImportByName = (PIMAGE_IMPORT_BY_NAME)PEHelpers::GetRvaPtr(
  1463.                         (DWORD)pThunk->u1.AddressOfData,
  1464.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1465.                         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1466.                         analyzer.lpFileContent,
  1467.                         analyzer.fileSize);
  1468.  
  1469.                     if (pImportByName && !IsBadReadPtr(pImportByName, sizeof(IMAGE_IMPORT_BY_NAME))) {
  1470.                         std::vector<wchar_t> wideFuncName(MAX_PATH);
  1471.                         MultiByteToWideChar(CP_ACP, 0, (char*)pImportByName->Name, -1,
  1472.                             wideFuncName.data(), MAX_PATH);
  1473.                         OUTPUT("\t\t%s\n", wideFuncName.data());
  1474.                     }
  1475.                 }
  1476.                 else {
  1477.                     OUTPUT("\t\tOrdinal: %lld\n", pThunk->u1.Ordinal & 0xFFFF);
  1478.                 }
  1479.                 pThunk++;
  1480.             }
  1481.         }
  1482.         pImportDesc++;
  1483.     }
  1484. }
  1485.  
  1486. /*void ParseImportDirectory(const PEAnalyzer& analyzer) {
  1487.     if (analyzer.is64Bit) {
  1488.         ParseImportDirectory64(analyzer);
  1489.     }
  1490.     else {
  1491.         ParseImportDirectory32(analyzer);
  1492.     }
  1493. }*/ //removing the empty content duplicates
  1494. //}
  1495.  
  1496. void ParseExportDirectory32(const PEAnalyzer& analyzer) {
  1497.     const auto& exportDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  1498.     if (!exportDir.VirtualAddress || !exportDir.Size) return;
  1499.  
  1500.     if (!PEHelpers::IsRvaValid(exportDir.VirtualAddress, analyzer.fileSize,
  1501.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1502.         OUTPUT("[-] Invalid export directory RVA!\n");
  1503.         throw std::runtime_error("RVA out of bounds");
  1504.         return;
  1505.     }
  1506.  
  1507.     OUTPUT("\n[+] EXPORT DIRECTORY (32-bit)\n");
  1508.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  1509.         exportDir.VirtualAddress,
  1510.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1511.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1512.         analyzer.lpFileContent,
  1513.         analyzer.fileSize);
  1514.  
  1515.     if (!pExportDir || IsBadReadPtr(pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  1516.         OUTPUT("[-] Invalid export directory structure!\n");
  1517.         return;
  1518.     }
  1519.  
  1520.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  1521.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  1522.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  1523.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  1524.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  1525.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  1526.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  1527.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  1528.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  1529.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  1530.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  1531.  
  1532.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(
  1533.         pExportDir->AddressOfFunctions,
  1534.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1535.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1536.         analyzer.lpFileContent,
  1537.         analyzer.fileSize);
  1538.  
  1539.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(
  1540.         pExportDir->AddressOfNames,
  1541.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1542.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1543.         analyzer.lpFileContent,
  1544.         analyzer.fileSize);
  1545.  
  1546.     auto pNameOrdinals = (PWORD)PEHelpers::GetRvaPtr(
  1547.         pExportDir->AddressOfNameOrdinals,
  1548.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1549.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1550.         analyzer.lpFileContent,
  1551.         analyzer.fileSize);
  1552.  
  1553.     if (!pNames || !pNameOrdinals || !pFunctions) {
  1554.         OUTPUT("[-] Invalid export address tables!\n");
  1555.         return;
  1556.     }
  1557.  
  1558.     OUTPUT("\tExported Functions:\n\n");
  1559.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1560.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1561.             IsBadReadPtr(pNameOrdinals + i, sizeof(WORD))) {
  1562.             break;
  1563.         }
  1564.  
  1565.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1566.             pNames[i],
  1567.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1568.             analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1569.             analyzer.lpFileContent,
  1570.             analyzer.fileSize);
  1571.  
  1572.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1573.             WORD ordinal = pNameOrdinals[i];
  1574.             if (ordinal < pExportDir->NumberOfFunctions) {
  1575.                 DWORD functionRva = pFunctions[ordinal];
  1576.  
  1577.                 // Check for forwarded export
  1578.                 if (functionRva >= exportDir.VirtualAddress &&
  1579.                     functionRva < (exportDir.VirtualAddress + exportDir.Size)) {
  1580.  
  1581.                     const char* forwardName = (const char*)PEHelpers::GetRvaPtr(
  1582.                         functionRva,
  1583.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1584.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1585.                         analyzer.lpFileContent,
  1586.                         analyzer.fileSize);
  1587.  
  1588.                     if (forwardName && !IsBadReadPtr(forwardName, 1)) {
  1589.                         std::vector<wchar_t> wideForwardName(MAX_PATH);
  1590.                         MultiByteToWideChar(CP_ACP, 0, forwardName, -1,
  1591.                             wideForwardName.data(), MAX_PATH);
  1592.                         OUTPUT("\t\t%s (Ordinal: %d) -> Forward to: %s\n",
  1593.                             functionName,
  1594.                             ordinal + pExportDir->Base,
  1595.                             wideForwardName.data());
  1596.                     }
  1597.                 }
  1598.                 else {
  1599.                     OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1600.                         functionName,
  1601.                         ordinal + pExportDir->Base,
  1602.                         functionRva);
  1603.                 }
  1604.             }
  1605.         }
  1606.     }
  1607. }
  1608.  
  1609. void ParseExportDirectory64(const PEAnalyzer& analyzer) {
  1610.     const auto& exportDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  1611.     if (!exportDir.VirtualAddress || !exportDir.Size) return;
  1612.  
  1613.     if (!PEHelpers::IsRvaValid(exportDir.VirtualAddress, analyzer.fileSize,
  1614.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  1615.         OUTPUT("[-] Invalid export directory RVA!\n");
  1616.         throw std::runtime_error("RVA out of bounds");
  1617.         return;
  1618.     }
  1619.  
  1620.     OUTPUT("\n[+] EXPORT DIRECTORY (64-bit)\n");
  1621.     // Rest of the implementation is identical to 32-bit version
  1622.     // Just using pNtHeaders64 instead of pNtHeaders64
  1623.     auto pExportDir = (PIMAGE_EXPORT_DIRECTORY)PEHelpers::GetRvaPtr(
  1624.         exportDir.VirtualAddress,
  1625.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1626.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1627.         analyzer.lpFileContent,
  1628.         analyzer.fileSize);
  1629.  
  1630.     if (!pExportDir || IsBadReadPtr(pExportDir, sizeof(IMAGE_EXPORT_DIRECTORY))) {
  1631.         OUTPUT("[-] Invalid export directory structure!\n");
  1632.         return;
  1633.     }
  1634.  
  1635.     OUTPUT("\tCharacteristics: 0x%X\n", pExportDir->Characteristics);
  1636.     OUTPUT("\tTimeDateStamp: 0x%X\n", pExportDir->TimeDateStamp);
  1637.     OUTPUT("\tMajorVersion: %d\n", pExportDir->MajorVersion);
  1638.     OUTPUT("\tMinorVersion: %d\n", pExportDir->MinorVersion);
  1639.     OUTPUT("\tName: 0x%X\n", pExportDir->Name);
  1640.     OUTPUT("\tBase: %d\n", pExportDir->Base);
  1641.     OUTPUT("\tNumberOfFunctions: %d\n", pExportDir->NumberOfFunctions);
  1642.     OUTPUT("\tNumberOfNames: %d\n", pExportDir->NumberOfNames);
  1643.     OUTPUT("\tAddressOfFunctions: 0x%X\n", pExportDir->AddressOfFunctions);
  1644.     OUTPUT("\tAddressOfNames: 0x%X\n", pExportDir->AddressOfNames);
  1645.     OUTPUT("\tAddressOfNameOrdinals: 0x%X\n\n", pExportDir->AddressOfNameOrdinals);
  1646.  
  1647.     auto pFunctions = (PDWORD)PEHelpers::GetRvaPtr(
  1648.         pExportDir->AddressOfFunctions,
  1649.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1650.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1651.         analyzer.lpFileContent,
  1652.         analyzer.fileSize);
  1653.  
  1654.     auto pNames = (PDWORD)PEHelpers::GetRvaPtr(
  1655.         pExportDir->AddressOfNames,
  1656.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1657.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1658.         analyzer.lpFileContent,
  1659.         analyzer.fileSize);
  1660.  
  1661.     auto pNameOrdinals = (PWORD)PEHelpers::GetRvaPtr(
  1662.         pExportDir->AddressOfNameOrdinals,
  1663.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1664.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1665.         analyzer.lpFileContent,
  1666.         analyzer.fileSize);
  1667.  
  1668.     if (!pNames || !pNameOrdinals || !pFunctions) {
  1669.         OUTPUT("[-] Invalid export address tables!\n");
  1670.         return;
  1671.     }
  1672.  
  1673.     OUTPUT("\tExported Functions:\n\n");
  1674.     for (DWORD i = 0; i < pExportDir->NumberOfNames; i++) {
  1675.         if (IsBadReadPtr(pNames + i, sizeof(DWORD)) ||
  1676.             IsBadReadPtr(pNameOrdinals + i, sizeof(WORD))) {
  1677.             break;
  1678.         }
  1679.  
  1680.         const char* functionName = (const char*)PEHelpers::GetRvaPtr(
  1681.             pNames[i],
  1682.             IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1683.             analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1684.             analyzer.lpFileContent,
  1685.             analyzer.fileSize);
  1686.  
  1687.         if (functionName && !IsBadReadPtr(functionName, 1)) {
  1688.             WORD ordinal = pNameOrdinals[i];
  1689.             if (ordinal < pExportDir->NumberOfFunctions) {
  1690.                 DWORD functionRva = pFunctions[ordinal];
  1691.  
  1692.                 // Check for forwarded export
  1693.                 if (functionRva >= exportDir.VirtualAddress &&
  1694.                     functionRva < (exportDir.VirtualAddress + exportDir.Size)) {
  1695.  
  1696.                     const char* forwardName = (const char*)PEHelpers::GetRvaPtr(
  1697.                         functionRva,
  1698.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  1699.                         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  1700.                         analyzer.lpFileContent,
  1701.                         analyzer.fileSize);
  1702.  
  1703.                     if (forwardName && !IsBadReadPtr(forwardName, 1)) {
  1704.                         std::vector<wchar_t> wideForwardName(MAX_PATH);
  1705.                         MultiByteToWideChar(CP_ACP, 0, forwardName, -1,
  1706.                             wideForwardName.data(), MAX_PATH);
  1707.                         OUTPUT("\t\t%s (Ordinal: %d) -> Forward to: %s\n",
  1708.                             functionName,
  1709.                             ordinal + pExportDir->Base,
  1710.                             wideForwardName.data());
  1711.                     }
  1712.                 }
  1713.                 else {
  1714.                     OUTPUT("\t\t%s (Ordinal: %d, RVA: 0x%08X)\n",
  1715.                         functionName,
  1716.                         ordinal + pExportDir->Base,
  1717.                         functionRva);
  1718.                 }
  1719.             }
  1720.         }
  1721.     }
  1722. }
  1723. // Copying the same logic as ParseExportDirectory32 but with 64-bit headers
  1724. // ... [Same implementation as above, just using pNtHeaders64]
  1725.  
  1726. /*void ParseExportDirectory(const PEAnalyzer& analyzer) {
  1727.     if (analyzer.is64Bit) {
  1728.         ParseExportDirectory64(analyzer);
  1729.     }
  1730.     else {
  1731.         ParseExportDirectory32(analyzer);
  1732.     }
  1733. }*/ //removing this duplicate
  1734.  
  1735. void ProcessResourceDirectory32(
  1736.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1737.     int level,
  1738.     const wchar_t* type,
  1739.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1740.     const wchar_t* resourceTypes[],
  1741.     const PEAnalyzer& analyzer)
  1742. {
  1743.     if (IsBadReadPtr(resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1744.         return;
  1745.     }
  1746.  
  1747.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1748.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1749.  
  1750.     for (WORD i = 0; i < totalEntries; i++) {
  1751.         if (IsBadReadPtr(entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1752.             break;
  1753.         }
  1754.  
  1755.         for (int indent = 0; indent < level; indent++) {
  1756.             OUTPUT("\t");
  1757.         }
  1758.  
  1759.         if (entry[i].NameIsString) {
  1760.             auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry[i].NameOffset);
  1761.             if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1762.                 std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1763.                 wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1764.                     nameEntry->NameString, nameEntry->Length);
  1765.                 resourceName[nameEntry->Length] = L'\0';
  1766.  
  1767.                 if (level == 0) {
  1768.                     OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1769.                 }
  1770.                 else {
  1771.                     OUTPUT("Name: %s\n", resourceName.data());
  1772.                 }
  1773.             }
  1774.         }
  1775.         else {
  1776.             if (level == 0) {
  1777.                 DWORD resourceType = entry[i].Id;
  1778.                 if (resourceType < 16) {
  1779.                     OUTPUT("Resource Type: %s (ID: %d)\n", resourceTypes[resourceType], resourceType);
  1780.                 }
  1781.                 else {
  1782.                     OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1783.                 }
  1784.             }
  1785.             else {
  1786.                 OUTPUT("ID: %d\n", entry[i].Id);
  1787.             }
  1788.         }
  1789.  
  1790.         if (entry[i].DataIsDirectory) {
  1791.             auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry[i].OffsetToDirectory);
  1792.             if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1793.                 ProcessResourceDirectory32(nextDir, level + 1,
  1794.                     level == 0 ? resourceTypes[min(entry[i].Id, 15)] : type,
  1795.                     baseResourceDir, resourceTypes, analyzer);
  1796.             }
  1797.         }
  1798.         else {
  1799.             auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry[i].OffsetToData);
  1800.             if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1801.                 for (int indent = 0; indent < level + 1; indent++) {
  1802.                     OUTPUT("\t");
  1803.                 }
  1804.                 OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1805.  
  1806.                 // Special handling for Version resources
  1807.                 if (type && wcscmp(type, L"Version") == 0) {
  1808.                     auto versionData = (BYTE*)PEHelpers::GetRvaPtr(
  1809.                         dataEntry->OffsetToData,
  1810.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1811.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1812.                         analyzer.lpFileContent,
  1813.                         analyzer.fileSize);
  1814.  
  1815.                     if (versionData && !IsBadReadPtr(versionData, sizeof(VS_FIXEDFILEINFO))) {
  1816.                         auto versionInfo = (VS_FIXEDFILEINFO*)(versionData + 40);
  1817.                         if (versionInfo->dwSignature == 0xFEEF04BD) {
  1818.                             for (int indent = 0; indent < level + 2; indent++) {
  1819.                                 OUTPUT("\t");
  1820.                             }
  1821.                             OUTPUT("File Version: %d.%d.%d.%d\n",
  1822.                                 HIWORD(versionInfo->dwFileVersionMS),
  1823.                                 LOWORD(versionInfo->dwFileVersionMS),
  1824.                                 HIWORD(versionInfo->dwFileVersionLS),
  1825.                                 LOWORD(versionInfo->dwFileVersionLS));
  1826.                         }
  1827.                     }
  1828.                 }
  1829.             }
  1830.         }
  1831.     }
  1832. }
  1833.  
  1834. void ProcessResourceDirectory64(
  1835.     PIMAGE_RESOURCE_DIRECTORY resDir,
  1836.     int level,
  1837.     const wchar_t* type,
  1838.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  1839.     const wchar_t* resourceTypes[],
  1840.     const PEAnalyzer& analyzer)
  1841. {
  1842.     // Similar to ProcessResourceDirectory32 but using 64-bit structures
  1843.     // Main difference is using analyzer.pNtHeaders64 instead of analyzer.pNtHeaders32
  1844.     if (IsBadReadPtr(resDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1845.         return;
  1846.         // Rest of the implementation follows the same pattern
  1847.     }
  1848.  
  1849.     auto entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resDir + 1);
  1850.     WORD totalEntries = resDir->NumberOfNamedEntries + resDir->NumberOfIdEntries;
  1851.  
  1852.     for (WORD i = 0; i < totalEntries; i++) {
  1853.         if (IsBadReadPtr(entry + i, sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))) {
  1854.             break;
  1855.         }
  1856.  
  1857.         for (int indent = 0; indent < level; indent++) {
  1858.             OUTPUT("\t");
  1859.         }
  1860.  
  1861.         if (entry[i].NameIsString) {
  1862.             auto nameEntry = (PIMAGE_RESOURCE_DIR_STRING_U)((BYTE*)baseResourceDir + entry[i].NameOffset);
  1863.             if (!IsBadReadPtr(nameEntry, sizeof(IMAGE_RESOURCE_DIR_STRING_U))) {
  1864.                 std::vector<wchar_t> resourceName(nameEntry->Length + 1);
  1865.                 wcsncpy_s(resourceName.data(), nameEntry->Length + 1,
  1866.                     nameEntry->NameString, nameEntry->Length);
  1867.                 resourceName[nameEntry->Length] = L'\0';
  1868.  
  1869.                 if (level == 0) {
  1870.                     OUTPUT("Resource Type: Custom (%s)\n", resourceName.data());
  1871.                 }
  1872.                 else {
  1873.                     OUTPUT("Name: %s\n", resourceName.data());
  1874.                 }
  1875.             }
  1876.         }
  1877.         else {
  1878.             if (level == 0) {
  1879.                 DWORD resourceType = entry[i].Id;
  1880.                 if (resourceType < 16) {
  1881.                     OUTPUT("Resource Type: %s (ID: %d)\n", resourceTypes[resourceType], resourceType);
  1882.                 }
  1883.                 else {
  1884.                     OUTPUT("Resource Type: Custom (ID: %d)\n", resourceType);
  1885.                 }
  1886.             }
  1887.             else {
  1888.                 OUTPUT("ID: %d\n", entry[i].Id);
  1889.             }
  1890.         }
  1891.  
  1892.         if (entry[i].DataIsDirectory) {
  1893.             auto nextDir = (PIMAGE_RESOURCE_DIRECTORY)((BYTE*)baseResourceDir + entry[i].OffsetToDirectory);
  1894.             if (!IsBadReadPtr(nextDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1895.                 ProcessResourceDirectory32(nextDir, level + 1,
  1896.                     level == 0 ? resourceTypes[min(entry[i].Id, 15)] : type,
  1897.                     baseResourceDir, resourceTypes, analyzer);
  1898.             }
  1899.         }
  1900.         else {
  1901.             auto dataEntry = (PIMAGE_RESOURCE_DATA_ENTRY)((BYTE*)baseResourceDir + entry[i].OffsetToData);
  1902.             if (!IsBadReadPtr(dataEntry, sizeof(IMAGE_RESOURCE_DATA_ENTRY))) {
  1903.                 for (int indent = 0; indent < level + 1; indent++) {
  1904.                     OUTPUT("\t");
  1905.                 }
  1906.                 OUTPUT("Size: %d bytes, RVA: 0x%X\n", dataEntry->Size, dataEntry->OffsetToData);
  1907.  
  1908.                 // Special handling for Version resources
  1909.                 if (type && wcscmp(type, L"Version") == 0) {
  1910.                     auto versionData = (BYTE*)PEHelpers::GetRvaPtr(
  1911.                         dataEntry->OffsetToData,
  1912.                         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1913.                         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1914.                         analyzer.lpFileContent,
  1915.                         analyzer.fileSize);
  1916.  
  1917.                     if (versionData && !IsBadReadPtr(versionData, sizeof(VS_FIXEDFILEINFO))) {
  1918.                         auto versionInfo = (VS_FIXEDFILEINFO*)(versionData + 40);
  1919.                         if (versionInfo->dwSignature == 0xFEEF04BD) {
  1920.                             for (int indent = 0; indent < level + 2; indent++) {
  1921.                                 OUTPUT("\t");
  1922.                             }
  1923.                             OUTPUT("File Version: %d.%d.%d.%d\n",
  1924.                                 HIWORD(versionInfo->dwFileVersionMS),
  1925.                                 LOWORD(versionInfo->dwFileVersionMS),
  1926.                                 HIWORD(versionInfo->dwFileVersionLS),
  1927.                                 LOWORD(versionInfo->dwFileVersionLS));
  1928.                         }
  1929.                     }
  1930.                 }
  1931.             }
  1932.         }
  1933.     }
  1934. }
  1935.  
  1936. void ParseResourceDirectory32(const PEAnalyzer& analyzer) {
  1937.     const auto& resourceDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
  1938.     if (!resourceDir.VirtualAddress || !resourceDir.Size) return;
  1939.  
  1940.     if (!PEHelpers::IsRvaValid(resourceDir.VirtualAddress, analyzer.fileSize,
  1941.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1942.         OUTPUT("[-] Invalid resource directory RVA!\n");
  1943.         throw std::runtime_error("RVA out of bounds");
  1944.         return;
  1945.     }
  1946.  
  1947.     OUTPUT("\n[+] RESOURCE DIRECTORY (32-bit)\n");
  1948.     auto pResourceDir = (PIMAGE_RESOURCE_DIRECTORY)PEHelpers::GetRvaPtr(
  1949.         resourceDir.VirtualAddress,
  1950.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1951.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1952.         analyzer.lpFileContent,
  1953.         analyzer.fileSize);
  1954.  
  1955.     if (!pResourceDir || IsBadReadPtr(pResourceDir, sizeof(IMAGE_RESOURCE_DIRECTORY))) {
  1956.         OUTPUT("[-] Invalid or corrupted resource directory\n");
  1957.         return;
  1958.     }
  1959.  
  1960.     const wchar_t* resourceTypes[] = {
  1961.         L"Unknown",     L"Cursor",      L"Bitmap",      L"Icon",
  1962.         L"Menu",        L"Dialog",      L"String",      L"FontDir",
  1963.         L"Font",        L"Accelerator", L"RCData",      L"MessageTable",
  1964.         L"GroupCursor", L"GroupIcon",   L"Version",     L"DlgInclude"
  1965.     };
  1966.  
  1967.     ProcessResourceDirectory32(pResourceDir, 0, nullptr, pResourceDir, resourceTypes, analyzer);
  1968. }
  1969.  
  1970. void ParseDebugDirectory32(const PEAnalyzer& analyzer) {
  1971.     const auto& debugDir = analyzer.pNtHeaders32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  1972.     if (!debugDir.VirtualAddress || !debugDir.Size) return;
  1973.  
  1974.     if (!PEHelpers::IsRvaValid(debugDir.VirtualAddress, analyzer.fileSize,
  1975.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders32))) {
  1976.         OUTPUT("[-] Invalid debug directory RVA!\n");
  1977.         throw std::runtime_error("RVA out of bounds");
  1978.         return;
  1979.     }
  1980.  
  1981.     OUTPUT("\n[+] DEBUG DIRECTORY (32-bit)\n");
  1982.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  1983.         debugDir.VirtualAddress,
  1984.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders32),
  1985.         analyzer.pNtHeaders32->FileHeader.NumberOfSections,
  1986.         analyzer.lpFileContent,
  1987.         analyzer.fileSize);
  1988.  
  1989.     if (!pDebugDir || IsBadReadPtr(pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  1990.         OUTPUT("[-] Invalid debug directory structure!\n");
  1991.         return;
  1992.     }
  1993.  
  1994.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  1995.     for (DWORD i = 0; i < numEntries; i++) {
  1996.         OUTPUT("\tDebug Entry %d:\n", i + 1);
  1997.         OUTPUT("\tCharacteristics: 0x%X\n", pDebugDir[i].Characteristics);
  1998.         OUTPUT("\tTimeDateStamp: 0x%X\n", pDebugDir[i].TimeDateStamp);
  1999.         OUTPUT("\tMajorVersion: %d\n", pDebugDir[i].MajorVersion);
  2000.         OUTPUT("\tMinorVersion: %d\n", pDebugDir[i].MinorVersion);
  2001.         OUTPUT("\tType: 0x%X", pDebugDir[i].Type);
  2002.  
  2003.         switch (pDebugDir[i].Type) {
  2004.         case IMAGE_DEBUG_TYPE_COFF:
  2005.             OUTPUT(" (COFF)\n"); break;
  2006.         case IMAGE_DEBUG_TYPE_CODEVIEW:
  2007.             OUTPUT(" (CodeView)\n"); break;
  2008.         case IMAGE_DEBUG_TYPE_FPO:
  2009.             OUTPUT(" (FPO)\n"); break;
  2010.         case IMAGE_DEBUG_TYPE_MISC:
  2011.             OUTPUT(" (Misc)\n"); break;
  2012.         case IMAGE_DEBUG_TYPE_EXCEPTION:
  2013.             OUTPUT(" (Exception)\n"); break;
  2014.         case IMAGE_DEBUG_TYPE_FIXUP:
  2015.             OUTPUT(" (Fixup)\n"); break;
  2016.         case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
  2017.             OUTPUT(" (OMAP to Src)\n"); break;
  2018.         case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
  2019.             OUTPUT(" (OMAP from Src)\n"); break;
  2020.         case IMAGE_DEBUG_TYPE_BORLAND:
  2021.             OUTPUT(" (Borland)\n"); break;
  2022.         default:
  2023.             OUTPUT(" (Unknown)\n"); break;
  2024.         }
  2025.  
  2026.         OUTPUT("\tSizeOfData: 0x%X\n", pDebugDir[i].SizeOfData);
  2027.         OUTPUT("\tAddressOfRawData: 0x%X\n", pDebugDir[i].AddressOfRawData);
  2028.         OUTPUT("\tPointerToRawData: 0x%X\n\n", pDebugDir[i].PointerToRawData);
  2029.  
  2030.         // Special handling for CodeView debug information
  2031.         if (pDebugDir[i].Type == IMAGE_DEBUG_TYPE_CODEVIEW &&
  2032.             pDebugDir[i].PointerToRawData != 0 &&
  2033.             pDebugDir[i].SizeOfData >= sizeof(DWORD)) {
  2034.  
  2035.             auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + pDebugDir[i].PointerToRawData);
  2036.             if (!IsBadReadPtr(pCVHeader, sizeof(DWORD))) {
  2037.                 switch (*pCVHeader) {
  2038.                 case 0x53445352: // 'RSDS'
  2039.                     if (pDebugDir[i].SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  2040.                         auto pCVData = (char*)(pCVHeader + 1);
  2041.                         if (!IsBadReadPtr(pCVData + 16, 1)) {
  2042.                             auto guid = (GUID*)pCVData;
  2043.                             DWORD age = *(DWORD*)(pCVData + 16);
  2044.                             const char* pdbPath = pCVData + 20;
  2045.  
  2046.                             OUTPUT("\tPDB Information:\n");
  2047.                             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  2048.                                 guid->Data1, guid->Data2, guid->Data3,
  2049.                                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  2050.                                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  2051.                             OUTPUT("\tAge: %d\n", age);
  2052.                             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2053.                         }
  2054.                     }
  2055.                     break;
  2056.  
  2057.                 case 0x3031424E: // 'NB10'
  2058.                     if (pDebugDir[i].SizeOfData >= 16) {
  2059.                         auto pNB10Data = (char*)(pCVHeader + 1);
  2060.                         DWORD offset = *(DWORD*)pNB10Data;
  2061.                         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  2062.                         DWORD age = *(DWORD*)(pNB10Data + 8);
  2063.                         const char* pdbPath = pNB10Data + 12;
  2064.  
  2065.                         OUTPUT("\tPDB Information (NB10):\n");
  2066.                         OUTPUT("\tOffset: 0x%X\n", offset);
  2067.                         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  2068.                         OUTPUT("\tAge: %d\n", age);
  2069.                         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2070.                     }
  2071.                     break;
  2072.                 }
  2073.             }
  2074.         }
  2075.     }
  2076. }
  2077.  
  2078. void ParseDebugDirectory64(const PEAnalyzer& analyzer) {
  2079.     const auto& debugDir = analyzer.pNtHeaders64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
  2080.     if (!debugDir.VirtualAddress || !debugDir.Size) return;
  2081.  
  2082.     if (!PEHelpers::IsRvaValid(debugDir.VirtualAddress, analyzer.fileSize,
  2083.         reinterpret_cast<PIMAGE_NT_HEADERS>(analyzer.pNtHeaders64))) {
  2084.         OUTPUT("[-] Invalid debug directory RVA!\n");
  2085.         throw std::runtime_error("RVA out of bounds");
  2086.         return;
  2087.     }
  2088.  
  2089.     OUTPUT("\n[+] DEBUG DIRECTORY (64-bit)\n");
  2090.     // Rest of implementation follows same pattern as 32-bit version
  2091.     // Just using pNtHeaders64 instead of pNtHeaders32
  2092.     auto pDebugDir = (PIMAGE_DEBUG_DIRECTORY)PEHelpers::GetRvaPtr(
  2093.         debugDir.VirtualAddress,
  2094.         IMAGE_FIRST_SECTION(analyzer.pNtHeaders64),
  2095.         analyzer.pNtHeaders64->FileHeader.NumberOfSections,
  2096.         analyzer.lpFileContent,
  2097.         analyzer.fileSize);
  2098.  
  2099.     if (!pDebugDir || IsBadReadPtr(pDebugDir, sizeof(IMAGE_DEBUG_DIRECTORY))) {
  2100.         OUTPUT("[-] Invalid debug directory structure!\n");
  2101.         return;
  2102.     }
  2103.  
  2104.     DWORD numEntries = min(debugDir.Size / sizeof(IMAGE_DEBUG_DIRECTORY), 16);
  2105.     for (DWORD i = 0; i < numEntries; i++) {
  2106.         OUTPUT("\tDebug Entry %d:\n", i + 1);
  2107.         OUTPUT("\tCharacteristics: 0x%X\n", pDebugDir[i].Characteristics);
  2108.         OUTPUT("\tTimeDateStamp: 0x%X\n", pDebugDir[i].TimeDateStamp);
  2109.         OUTPUT("\tMajorVersion: %d\n", pDebugDir[i].MajorVersion);
  2110.         OUTPUT("\tMinorVersion: %d\n", pDebugDir[i].MinorVersion);
  2111.         OUTPUT("\tType: 0x%X", pDebugDir[i].Type);
  2112.  
  2113.         switch (pDebugDir[i].Type) {
  2114.         case IMAGE_DEBUG_TYPE_COFF:
  2115.             OUTPUT(" (COFF)\n"); break;
  2116.         case IMAGE_DEBUG_TYPE_CODEVIEW:
  2117.             OUTPUT(" (CodeView)\n"); break;
  2118.         case IMAGE_DEBUG_TYPE_FPO:
  2119.             OUTPUT(" (FPO)\n"); break;
  2120.         case IMAGE_DEBUG_TYPE_MISC:
  2121.             OUTPUT(" (Misc)\n"); break;
  2122.         case IMAGE_DEBUG_TYPE_EXCEPTION:
  2123.             OUTPUT(" (Exception)\n"); break;
  2124.         case IMAGE_DEBUG_TYPE_FIXUP:
  2125.             OUTPUT(" (Fixup)\n"); break;
  2126.         case IMAGE_DEBUG_TYPE_OMAP_TO_SRC:
  2127.             OUTPUT(" (OMAP to Src)\n"); break;
  2128.         case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC:
  2129.             OUTPUT(" (OMAP from Src)\n"); break;
  2130.         case IMAGE_DEBUG_TYPE_BORLAND:
  2131.             OUTPUT(" (Borland)\n"); break;
  2132.         default:
  2133.             OUTPUT(" (Unknown)\n"); break;
  2134.         }
  2135.  
  2136.         OUTPUT("\tSizeOfData: 0x%X\n", pDebugDir[i].SizeOfData);
  2137.         OUTPUT("\tAddressOfRawData: 0x%X\n", pDebugDir[i].AddressOfRawData);
  2138.         OUTPUT("\tPointerToRawData: 0x%X\n\n", pDebugDir[i].PointerToRawData);
  2139.  
  2140.         // Special handling for CodeView debug information
  2141.         if (pDebugDir[i].Type == IMAGE_DEBUG_TYPE_CODEVIEW &&
  2142.             pDebugDir[i].PointerToRawData != 0 &&
  2143.             pDebugDir[i].SizeOfData >= sizeof(DWORD)) {
  2144.  
  2145.             auto pCVHeader = (DWORD*)((BYTE*)analyzer.lpFileContent + pDebugDir[i].PointerToRawData);
  2146.             if (!IsBadReadPtr(pCVHeader, sizeof(DWORD))) {
  2147.                 switch (*pCVHeader) {
  2148.                 case 0x53445352: // 'RSDS'
  2149.                     if (pDebugDir[i].SizeOfData >= (sizeof(DWORD) + sizeof(GUID) + sizeof(DWORD) + 1)) {
  2150.                         auto pCVData = (char*)(pCVHeader + 1);
  2151.                         if (!IsBadReadPtr(pCVData + 16, 1)) {
  2152.                             auto guid = (GUID*)pCVData;
  2153.                             DWORD age = *(DWORD*)(pCVData + 16);
  2154.                             const char* pdbPath = pCVData + 20;
  2155.  
  2156.                             OUTPUT("\tPDB Information:\n");
  2157.                             OUTPUT("\tGUID: {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
  2158.                                 guid->Data1, guid->Data2, guid->Data3,
  2159.                                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  2160.                                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  2161.                             OUTPUT("\tAge: %d\n", age);
  2162.                             OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2163.                         }
  2164.                     }
  2165.                     break;
  2166.  
  2167.                 case 0x3031424E: // 'NB10'
  2168.                     if (pDebugDir[i].SizeOfData >= 16) {
  2169.                         auto pNB10Data = (char*)(pCVHeader + 1);
  2170.                         DWORD offset = *(DWORD*)pNB10Data;
  2171.                         DWORD timestamp = *(DWORD*)(pNB10Data + 4);
  2172.                         DWORD age = *(DWORD*)(pNB10Data + 8);
  2173.                         const char* pdbPath = pNB10Data + 12;
  2174.  
  2175.                         OUTPUT("\tPDB Information (NB10):\n");
  2176.                         OUTPUT("\tOffset: 0x%X\n", offset);
  2177.                         OUTPUT("\tTimestamp: 0x%X\n", timestamp);
  2178.                         OUTPUT("\tAge: %d\n", age);
  2179.                         OUTPUT("\tPDB Path: %s\n\n", pdbPath);
  2180.                     }
  2181.                     break;
  2182.                 }
  2183.             }
  2184.         }
  2185.     }
  2186. }
  2187. // ... [Same implementation as ParseDebugDirectory32]
  2188.  
  2189. //newfunctionshere (lateest fixes)
  2190.  
  2191.  
  2192. void ProcessResourceDirectory32(
  2193.     PIMAGE_RESOURCE_DIRECTORY resDir,
  2194.     int level,
  2195.     const wchar_t* type,
  2196.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  2197.     const wchar_t* resourceTypes[],
  2198.     const PEAnalyzer& analyzer);
  2199.  
  2200. void ProcessResourceDirectory64(
  2201.     PIMAGE_RESOURCE_DIRECTORY resDir,
  2202.     int level,
  2203.     const wchar_t* type,
  2204.     PIMAGE_RESOURCE_DIRECTORY baseResourceDir,
  2205.     const wchar_t* resourceTypes[],
  2206.     const PEAnalyzer& analyzer);
  2207.  
  2208. // Main window class name
  2209. //const char* const WINDOW_CLASS_NAME = "PEAnalyzerWindow";
  2210.  
  2211. //new inserted here >>
  2212.  
  2213. // Page Break
  2214.  
  2215. //here
  2216.  
  2217. // Page Break
  2218.  
  2219. void AddMenus(HWND hwnd) {
  2220.     HMENU hMenuBar = CreateMenu();
  2221.     HMENU hFileMenu = CreateMenu();
  2222.     AppendMenu(hMenuBar, MF_POPUP, (UINT_PTR)hFileMenu, L"&File");
  2223.     AppendMenu(hFileMenu, MF_STRING, 1, L"&Open\tCtrl+O");  // Updated to show shortcut
  2224.     AppendMenu(hFileMenu, MF_STRING, 2, L"E&xit");
  2225.     SetMenu(hwnd, hMenuBar);
  2226. }
  2227.  
  2228. // First, add this helper function to determine if the PE file is 64-bit
  2229. bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2230.     return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2231. } //removing this duplicate
  2232.  
  2233. // Helper function to safely get file size
  2234. /*DWORD GetFileSizeCustom(const wchar_t* filePath) {
  2235.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  2236.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  2237.  
  2238.     if (hFile == INVALID_HANDLE_VALUE) {
  2239.         return 0;
  2240.     }
  2241.  
  2242.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2243.     CloseHandle(hFile);
  2244.     return fileSize;
  2245. }*/ //removing this duplicate instead
  2246.  
  2247. // Add this helper function
  2248. void SafeOutput(const std::wstring& text) {
  2249.     try {
  2250.         g_OutputText << text;
  2251.         UpdateEditControl();
  2252.     }
  2253.     catch (...) {
  2254.         SetStatusText(L"Error writing output");
  2255.     }
  2256. }
  2257.  
  2258. void UpdateStatusBar(const wchar_t* text, int progress = -1) {
  2259.     if (text) {
  2260.         SetStatusText(text);
  2261.     }
  2262.     if (progress >= 0) {
  2263.         ShowProgress(progress);
  2264.     }
  2265. }
  2266.  
  2267. void ClearProgress() {
  2268.     ShowWindow(g_hProgressBar, SW_HIDE);
  2269.     SetStatusText(L"Ready");
  2270. }
  2271.  
  2272.  
  2273.  
  2274. void SetStatusText(const wchar_t* text) {
  2275.     SendMessage(g_hStatusBar, SB_SETTEXT, 0, (LPARAM)text);
  2276. }
  2277.  
  2278. void ShowProgress(int percentage) {
  2279.     // Update progress bar
  2280.     SendMessage(g_hProgressBar, PBM_SETPOS, (WPARAM)percentage, 0);
  2281.  
  2282.     // Update status text in first part
  2283.     wchar_t status[256];
  2284.     swprintf_s(status, L"Analyzing... %d%%", percentage);
  2285.     //swprintf_s(status, L"Analyzing...");
  2286.     SetStatusText(status); //commented-out
  2287.     SendMessage(g_hStatusBar, SB_SETTEXT, 0, (LPARAM)status);
  2288. }
  2289.  
  2290. void OpenFileDialog(HWND hwnd) {
  2291.     WCHAR fileName[MAX_PATH] = L"";
  2292.     OPENFILENAMEW ofn = { sizeof(OPENFILENAMEW), hwnd, NULL, L"Executable Files (*.exe;*.dll)\0*.exe;*.dll\0All Files (*.*)\0*.*\0", NULL, 0, 1, fileName, MAX_PATH, NULL, 0, NULL, NULL, OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, 0, 0, L"exe", NULL, NULL, NULL };
  2293.     if (GetOpenFileNameW(&ofn)) {
  2294.         SetWindowTextW(g_hEditControl, L"");
  2295.         g_OutputText.str(L"");
  2296.         g_OutputText.clear();
  2297.         AnalyzePEFile(ofn.lpstrFile);
  2298.         UpdateEditControl();
  2299.     }
  2300. }
  2301.  
  2302.  
  2303. // Modified AppendToOutput to handle newlines properly:
  2304. void AppendToOutput(const wchar_t* format, ...) {
  2305.     std::vector<wchar_t> buffer(1024);
  2306.     va_list args;
  2307.     va_start(args, format);
  2308.  
  2309.     while (true) {
  2310.         int result = _vsnwprintf(buffer.data(), buffer.size(), format, args);
  2311.         if (result >= 0) break;
  2312.         buffer.resize(buffer.size() * 2);
  2313.     }
  2314.     va_end(args);
  2315.  
  2316.     // Convert \n to \r\n
  2317.     std::wstring output = buffer.data();
  2318.     size_t pos = 0;
  2319.     while ((pos = output.find(L'\n', pos)) != std::wstring::npos) {
  2320.         if (pos == 0 || output[pos - 1] != L'\r') {
  2321.             output.insert(pos, L"\r");
  2322.             pos += 2;
  2323.         }
  2324.         else {
  2325.             pos++;
  2326.         }
  2327.     }
  2328.  
  2329.     g_OutputText << output;
  2330.     UpdateEditControl();
  2331. }
  2332.  
  2333.  
  2334. //use vectors for unlimited size growth of buffer, use an alternative to editbox, check for fast loops overloading, in its primitive form it works properly! try w/o getimports3264 datadirectories getsections    
  2335.  
  2336. //adding here
  2337. // Line Break
  2338. // new code below starting here vv
  2339.  
  2340.  
  2341.  
  2342. DWORD GetFileSize(const wchar_t* filePath) {
  2343.     HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ,
  2344.         nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  2345.     if (hFile == INVALID_HANDLE_VALUE) return 0;
  2346.  
  2347.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2348.     CloseHandle(hFile);
  2349.     return fileSize;
  2350. }
  2351. //}
  2352. // Page Break
  2353.  
  2354. //}
  2355.  
  2356. //UpdateEditControl();
  2357. //}
  2358.  
  2359. // new code upto here ending here ^^
  2360. // Line Break
  2361. //  //end adding here
  2362.  
  2363.  
  2364.  
  2365. //filePathW
  2366. //lpFilePath
  2367. HANDLE GetFileContent(const wchar_t* lpFilePath) {
  2368.     HANDLE hFile = CreateFileW(lpFilePath, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
  2369.     if (hFile == INVALID_HANDLE_VALUE) return nullptr;
  2370.     DWORD fileSize = ::GetFileSize(hFile, nullptr);
  2371.     auto lpFileContent = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, fileSize);
  2372.     DWORD bytesRead;
  2373.     ReadFile(hFile, lpFileContent, fileSize, &bytesRead, nullptr);
  2374.     CloseHandle(hFile);
  2375.     return lpFileContent;
  2376. }
  2377.  
  2378. void UpdateEditControl() {
  2379.     SetWindowTextW(g_hEditControl, g_OutputText.str().c_str());
  2380.     SendMessage(g_hEditControl, EM_SETSEL, -1, -1);
  2381.     SendMessage(g_hEditControl, EM_SCROLLCARET, 0, 0);
  2382. }
  2383. //}
  2384.  
  2385. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  2386.     INITCOMMONCONTROLSEX icc = { sizeof(INITCOMMONCONTROLSEX), ICC_WIN95_CLASSES };
  2387.     InitCommonControlsEx(&icc);
  2388.  
  2389.     // Get command line parameters in Unicode
  2390.     int argc;
  2391.     LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  2392.  
  2393.     CreateMainWindow(hInstance);
  2394.     if (!g_hMainWindow) {
  2395.         LocalFree(argv);
  2396.         return -1;
  2397.     }
  2398.  
  2399.     ShowWindow(g_hMainWindow, nCmdShow);
  2400.     UpdateWindow(g_hMainWindow);
  2401.  
  2402.     // If there's a command line parameter, process it
  2403.     if (argc > 1) {
  2404.         // Process the first parameter as file path
  2405.         SetWindowTextW(g_hEditControl, L"");
  2406.         g_OutputText.str(L"");
  2407.         g_OutputText.clear();
  2408.         AnalyzePEFile(argv[1]);
  2409.         UpdateEditControl();
  2410.     }
  2411.  
  2412.     LocalFree(argv);
  2413.  
  2414.     MSG msg = {};
  2415.     while (GetMessage(&msg, NULL, 0, 0)) {
  2416.         TranslateMessage(&msg);
  2417.         DispatchMessage(&msg);
  2418.     }
  2419.  
  2420.     if (g_hFont) DeleteObject(g_hFont);
  2421.     return (int)msg.wParam;
  2422. }
  2423.  
  2424. void CreateMainWindow(HINSTANCE hInstance) {
  2425.     WNDCLASSEXW wc = { sizeof(WNDCLASSEXW), 0, WindowProc, 0, 0, hInstance,
  2426.         LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)),
  2427.         LoadCursor(NULL, IDC_ARROW),
  2428.         (HBRUSH)(COLOR_WINDOW + 1),
  2429.         NULL, WINDOW_CLASS_NAME,
  2430.         LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)) };
  2431.     RegisterClassExW(&wc);
  2432.  
  2433.     // Get screen dimensions
  2434.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  2435.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  2436.  
  2437.     // Calculate center position
  2438.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  2439.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  2440.  
  2441.     // Remove WS_MAXIMIZEBOX and WS_THICKFRAME from the window style
  2442.     DWORD style = (WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX) & ~WS_THICKFRAME;
  2443.     //WS_OVERLAPPEDWINDOW ~~> style
  2444.     g_hMainWindow = CreateWindowExW(0, WINDOW_CLASS_NAME, L"PE File Analyzer",
  2445.         style, windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  2446.         nullptr, nullptr, hInstance, nullptr);
  2447. }
  2448.  
  2449. void InitializeControls(HWND hwnd) {
  2450.     // Create status bar
  2451.     g_hStatusBar = CreateWindowEx(0, STATUSCLASSNAME, NULL,
  2452.         WS_CHILD | WS_VISIBLE,
  2453.         0, 0, 0, 0, hwnd, NULL,
  2454.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
  2455.  
  2456.     // Set up status bar parts
  2457.     RECT rcClient;
  2458.     GetClientRect(hwnd, &rcClient);
  2459.     int statusParts[2] = { 150, rcClient.right };
  2460.     SendMessage(g_hStatusBar, SB_SETPARTS, 2, (LPARAM)statusParts);
  2461.  
  2462.     // Create progress bar in the second part of status bar
  2463.     RECT rcPart;
  2464.     SendMessage(g_hStatusBar, SB_GETRECT, 1, (LPARAM)&rcPart);
  2465.  
  2466.     g_hProgressBar = CreateWindowEx(0, PROGRESS_CLASS, NULL,
  2467.         WS_CHILD | WS_VISIBLE | PBS_SMOOTH,
  2468.         rcPart.left + 5, rcPart.top + 2,
  2469.         rcPart.right - rcPart.left - 10, rcPart.bottom - rcPart.top - 4,
  2470.         g_hStatusBar, NULL,
  2471.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
  2472.  
  2473.     // Set blue color and range
  2474.     SendMessage(g_hProgressBar, PBM_SETBARCOLOR, 0, (LPARAM)RGB(0, 120, 215));  // Windows 10 blue
  2475.     SendMessage(g_hProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
  2476.     SendMessage(g_hProgressBar, PBM_SETSTEP, 1, 0);
  2477.  
  2478.     // Get status bar height for edit control positioning
  2479.     RECT rcStatus;
  2480.     GetWindowRect(g_hStatusBar, &rcStatus);
  2481.     int statusHeight = rcStatus.bottom - rcStatus.top;
  2482.  
  2483.     // Create edit control
  2484.     g_hEditControl = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
  2485.         WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL |
  2486.         ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,
  2487.         EDIT_MARGIN, EDIT_MARGIN,
  2488.         rcClient.right - (2 * EDIT_MARGIN),
  2489.         rcClient.bottom - statusHeight - (2 * EDIT_MARGIN),
  2490.         hwnd, nullptr,
  2491.         (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE), nullptr);
  2492.  
  2493.     // Create and set font
  2494.     g_hFont = CreateFont(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0,
  2495.         ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
  2496.         DEFAULT_QUALITY, DEFAULT_PITCH | FF_MODERN, L"Consolas");
  2497.  
  2498.     if (g_hFont)
  2499.         SendMessage(g_hEditControl, WM_SETFONT, (WPARAM)g_hFont, TRUE);
  2500.  
  2501.     SetWindowSubclass(g_hEditControl, EditSubclassProc, 0, 0);
  2502. }
  2503.  
  2504. LRESULT CALLBACK EditSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) {
  2505.     if (uMsg == WM_KEYDOWN) {
  2506.         if ((GetKeyState(VK_CONTROL) & 0x8000) && wParam == 'O') {
  2507.             SendMessage(GetParent(hwnd), WM_COMMAND, 1, 0);
  2508.             return 0;
  2509.         }
  2510.         switch (wParam) {
  2511.         case VK_F1:
  2512.             SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_F1, 0);
  2513.             return 0;
  2514.         case VK_ESCAPE:
  2515.             SendMessage(GetParent(hwnd), WM_KEYDOWN, VK_ESCAPE, 0);
  2516.             return 0;
  2517.         case VK_PRIOR:
  2518.             // Scroll up
  2519.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2520.             return 0;
  2521.         case VK_NEXT:
  2522.             // Scroll down
  2523.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2524.             return 0;
  2525.         case VK_UP:
  2526.             // Scroll one line up
  2527.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_LINEUP, 0), 0);
  2528.             return 0;
  2529.         case VK_DOWN:
  2530.             // Scroll one line down
  2531.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_LINEDOWN, 0), 0);
  2532.             return 0;
  2533.         }
  2534.     }
  2535.     if (uMsg == WM_MOUSEWHEEL) {
  2536.         int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  2537.         if (delta > 0) {
  2538.             // Scroll up
  2539.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2540.         }
  2541.         else {
  2542.             // Scroll down
  2543.             SendMessage(hwnd, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2544.         }
  2545.         return 0;
  2546.     }
  2547.     return DefSubclassProc(hwnd, uMsg, wParam, lParam);
  2548. }
  2549.  
  2550. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  2551.     switch (uMsg) {
  2552.     case WM_CREATE: InitializeControls(hwnd); AddMenus(hwnd); return 0;
  2553.     case WM_SIZE:
  2554.     {
  2555.         RECT rcClient;
  2556.         GetClientRect(hwnd, &rcClient);
  2557.  
  2558.         // Resize status bar
  2559.         SendMessage(g_hStatusBar, WM_SIZE, 0, 0);
  2560.  
  2561.         // Recalculate status bar parts
  2562.         int statusParts[2] = { 150, rcClient.right };
  2563.         SendMessage(g_hStatusBar, SB_SETPARTS, 2, (LPARAM)statusParts);
  2564.  
  2565.         // Reposition progress bar
  2566.         RECT rcPart;
  2567.         SendMessage(g_hStatusBar, SB_GETRECT, 1, (LPARAM)&rcPart);
  2568.         SetWindowPos(g_hProgressBar, NULL,
  2569.             rcPart.left + 5, rcPart.top + 2,
  2570.             rcPart.right - rcPart.left - 10, rcPart.bottom - rcPart.top - 4,
  2571.             SWP_NOZORDER);
  2572.  
  2573.         // Get status bar height
  2574.         RECT rcStatus;
  2575.         GetWindowRect(g_hStatusBar, &rcStatus);
  2576.         int statusHeight = rcStatus.bottom - rcStatus.top;
  2577.  
  2578.         // Resize edit control
  2579.         SetWindowPos(g_hEditControl, NULL,
  2580.             EDIT_MARGIN,
  2581.             EDIT_MARGIN,
  2582.             rcClient.right - (2 * EDIT_MARGIN),
  2583.             rcClient.bottom - statusHeight - (2 * EDIT_MARGIN),
  2584.             SWP_NOZORDER);
  2585.         return 0;
  2586.     }
  2587.  
  2588.     case WM_KEYDOWN:
  2589.     {
  2590.         if (GetKeyState(VK_CONTROL) & 0x8000) {
  2591.             switch (wParam) {
  2592.             case 'O':
  2593.                 OpenFileDialog(hwnd);
  2594.                 return 0;
  2595.             }
  2596.         }
  2597.         switch (wParam) {
  2598.         case VK_F1:
  2599.             MessageBoxW(hwnd,
  2600.                 L"PE Header Parser 4.3 GUI-based Programmed in C++ Win32 API (1546 lines of code) by Entisoft Software(c) Evans Thorpemorton",
  2601.                 L"About",
  2602.                 MB_OK | MB_ICONINFORMATION);
  2603.             return 0;
  2604.         case VK_ESCAPE:
  2605.             PostQuitMessage(0);
  2606.             return 0;
  2607.         case VK_PRIOR:
  2608.             // Scroll up
  2609.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2610.             return 0;
  2611.         case VK_NEXT:
  2612.             // Scroll down
  2613.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2614.             return 0;
  2615.         case VK_UP:
  2616.             // Scroll one line up
  2617.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_LINEUP, 0), 0);
  2618.             return 0;
  2619.         case VK_DOWN:
  2620.             // Scroll one line down
  2621.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_LINEDOWN, 0), 0);
  2622.             return 0;
  2623.         }
  2624.         break;
  2625.     }
  2626.     case WM_MOUSEWHEEL:
  2627.     {
  2628.         int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  2629.         if (delta > 0) {
  2630.             // Scroll up
  2631.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEUP, 0), 0);
  2632.         }
  2633.         else {
  2634.             // Scroll down
  2635.             SendMessage(g_hEditControl, WM_VSCROLL, MAKELONG(SB_PAGEDOWN, 0), 0);
  2636.         }
  2637.         return 0;
  2638.     }
  2639.     case WM_COMMAND: if (LOWORD(wParam) == 1) OpenFileDialog(hwnd); if (LOWORD(wParam) == 2) PostQuitMessage(0); return 0;
  2640.     case WM_DESTROY:
  2641.         if (g_hStatusBar) DestroyWindow(g_hStatusBar);
  2642.         PostQuitMessage(0);
  2643.         return 0;
  2644.     }
  2645.     return DefWindowProc(hwnd, uMsg, wParam, lParam);
  2646. }
  2647.  
  2648. ===+++ PEHeaders.h +++===
  2649. #pragma once
  2650. #ifndef PE_ANALYZER_STRUCT_H
  2651. #define PE_ANALYZER_STRUCT_H
  2652. #include <Windows.h>
  2653. #include <winternl.h>
  2654.  
  2655. // Core PE analysis structure
  2656. struct PEAnalyzer {
  2657.     LPVOID lpFileContent;
  2658.     DWORD fileSize;
  2659.     bool is64Bit;
  2660.     PIMAGE_NT_HEADERS32 pNtHeaders32;
  2661.     PIMAGE_NT_HEADERS64 pNtHeaders64;
  2662.     PIMAGE_DOS_HEADER pDosHeader;
  2663.  
  2664.     PEAnalyzer() : lpFileContent(nullptr), fileSize(0), is64Bit(false),
  2665.         pNtHeaders32(nullptr), pNtHeaders64(nullptr), pDosHeader(nullptr) {}
  2666.  
  2667.     // Remove destructor as FileMapper will handle cleanup
  2668. };
  2669. //struct PEAnalyzer;  // Add this before the namespace
  2670. // Declare functions that use PEAnalyzer
  2671.     template<typename T>
  2672.     bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size);
  2673. #endif // PE_ANALYZER_STRUCT_H
  2674. namespace PEHelpers {
  2675. //ifndef OUTPUT was here
  2676.  
  2677.     // Inline function to prevent multiple definition
  2678.     inline bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2679.         return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2680.     }
  2681.     //bool ValidateFileSize(const PEAnalyzer& analyzer, DWORD expectedSize, DWORD fileSize);
  2682.     bool ValidateFileSize(DWORD expectedSize, DWORD fileSize);
  2683.     // Add the template function declaration here
  2684.     //template<typename T>
  2685.     //bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size);
  2686.     bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders);
  2687.     DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders);
  2688.     DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders);
  2689.     DWORD_PTR GetRvaPtr(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2690.         WORD numberOfSections, LPVOID baseAddress);
  2691.     DWORD RvaToOffset(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2692.         WORD numberOfSections);
  2693.     std::wstring GetImageCharacteristics(DWORD characteristics);
  2694.     std::wstring GetSubsystem(WORD subsystem);
  2695.     std::wstring GetDataDirectoryName(int DirectoryNumber);
  2696.     std::wstring GetSectionProtection(DWORD characteristics);
  2697.  
  2698.     //    using namespace std;
  2699.     //    using namespace PEAnalyzer;
  2700.         // Core PE validation functions
  2701.     // Ensure this function is defined exactly once
  2702.     /*inline bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2703.         return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2704.     }*/
  2705.  
  2706. /*bool Is64BitPE(PIMAGE_NT_HEADERS pNtHeaders) {
  2707.     return pNtHeaders->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  2708. }*/
  2709.  
  2710. bool ValidateFileSize(DWORD expectedSize, DWORD fileSize) {
  2711.     return expectedSize > 0 && expectedSize <= fileSize;
  2712. }
  2713.  
  2714. template<typename T>
  2715. bool IsSafeToRead(const PEAnalyzer& analyzer, const T* ptr, size_t size = sizeof(T)) {
  2716.     // Check if pointer is null
  2717.     if (!ptr) {
  2718.         OUTPUT("[-] Null pointer detected\n");
  2719.         return false;
  2720.     }
  2721.  
  2722.     // Calculate pointer ranges
  2723.     DWORD_PTR startAddress = reinterpret_cast<DWORD_PTR>(analyzer.lpFileContent);
  2724.     DWORD_PTR endAddress = startAddress + analyzer.fileSize;
  2725.     DWORD_PTR ptrAddress = reinterpret_cast<DWORD_PTR>(ptr);
  2726.     DWORD_PTR ptrEndAddress = ptrAddress + size;
  2727.  
  2728.     // Comprehensive pointer validation
  2729.     bool isValidPointer = (
  2730.         ptr != nullptr &&                  // Not null
  2731.         ptrAddress >= startAddress &&       // Above file start
  2732.         ptrEndAddress <= endAddress &&      // Below file end
  2733.         ptrAddress < ptrEndAddress          // Prevent integer overflow
  2734.         );
  2735.  
  2736.     if (!isValidPointer) {
  2737.         OUTPUT("[-] Pointer validation failed\n");
  2738.         OUTPUT("    Pointer: 0x%p\n", ptr);
  2739.         OUTPUT("    File Start: 0x%p\n", reinterpret_cast<void*>(startAddress));
  2740.         OUTPUT("    File End: 0x%p\n", reinterpret_cast<void*>(endAddress));
  2741.         OUTPUT("    Pointer Start: 0x%p\n", reinterpret_cast<void*>(ptrAddress));
  2742.         OUTPUT("    Pointer End: 0x%p\n", reinterpret_cast<void*>(ptrEndAddress));
  2743.         return false;
  2744.     }
  2745.  
  2746.     return true;
  2747. }
  2748.  
  2749. bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders) {
  2750.     if (!pNtHeaders) {
  2751.         OUTPUT("[-] Invalid NT Headers for RVA validation\n");
  2752.         return false;
  2753.     }
  2754.  
  2755.     DWORD sizeOfImage = PEHelpers::Is64BitPE(pNtHeaders) ?
  2756.         reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders)->OptionalHeader.SizeOfImage :
  2757.         reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders)->OptionalHeader.SizeOfImage;
  2758.  
  2759.     bool isValid = (
  2760.         rva > 0 &&                  // RVA is non-zero
  2761.         rva < sizeOfImage&&         // RVA is within image size
  2762.         rva < fileSize               // RVA is within file size
  2763.         );
  2764.  
  2765.     if (!isValid) {
  2766.         OUTPUT("[-] Invalid RVA: 0x%X\n", rva);
  2767.         OUTPUT("    Size of Image: 0x%X\n", sizeOfImage);
  2768.         OUTPUT("    File Size: 0x%X\n", fileSize);
  2769.     }
  2770.  
  2771.     return isValid;
  2772. }
  2773.  
  2774. /*bool IsRvaValid(DWORD rva, DWORD fileSize, PIMAGE_NT_HEADERS pNtHeaders) {
  2775.     return rva < pNtHeaders->OptionalHeader.SizeOfImage&& rva < fileSize;
  2776. }*/
  2777.  
  2778. DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders) {
  2779.     if (PEHelpers::Is64BitPE(pNtHeaders)) {  // Add PEHelpers:: namespace qualifier
  2780.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2781.         return static_cast<DWORD_PTR>(pNtHeaders64->OptionalHeader.ImageBase);
  2782.     }
  2783.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2784.     return static_cast<DWORD_PTR>(pNtHeaders32->OptionalHeader.ImageBase);
  2785. }
  2786.  
  2787. DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders) {
  2788.     if (PEHelpers::Is64BitPE(pNtHeaders)) {  // Add PEHelpers:: namespace qualifier
  2789.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2790.         return pNtHeaders64->OptionalHeader.SizeOfImage;
  2791.     }
  2792.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2793.     return pNtHeaders32->OptionalHeader.SizeOfImage;
  2794. }
  2795.  
  2796. /* // RVA and address conversion helpers
  2797. DWORD_PTR GetImageBase(PIMAGE_NT_HEADERS pNtHeaders) {
  2798.     if (Is64BitPE(pNtHeaders)) {
  2799.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2800.         return static_cast<DWORD_PTR>(pNtHeaders64->OptionalHeader.ImageBase);
  2801.     }
  2802.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2803.     return static_cast<DWORD_PTR>(pNtHeaders32->OptionalHeader.ImageBase);
  2804. }
  2805.  
  2806. DWORD GetSizeOfImage(PIMAGE_NT_HEADERS pNtHeaders) {
  2807.     if (Is64BitPE(pNtHeaders)) {
  2808.         auto pNtHeaders64 = reinterpret_cast<PIMAGE_NT_HEADERS64>(pNtHeaders);
  2809.         return pNtHeaders64->OptionalHeader.SizeOfImage;
  2810.     }
  2811.     auto pNtHeaders32 = reinterpret_cast<PIMAGE_NT_HEADERS32>(pNtHeaders);
  2812.     return pNtHeaders32->OptionalHeader.SizeOfImage;
  2813. }*/
  2814.  
  2815. DWORD_PTR GetRvaPtr(
  2816.     DWORD rva,
  2817.     PIMAGE_SECTION_HEADER pSectionHeader,
  2818.     WORD numberOfSections,
  2819.     LPVOID baseAddress,
  2820.     DWORD fileSize  // Add file size as a parameter
  2821. ) {
  2822.     if (!rva || !pSectionHeader || !baseAddress) {
  2823.         OUTPUT("[-] Invalid parameters in GetRvaPtr\n");
  2824.         return 0;
  2825.     }
  2826.  
  2827.     for (WORD i = 0; i < numberOfSections; i++) {
  2828.         // Check if RVA falls within this section
  2829.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2830.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2831.  
  2832.             // Calculate pointer
  2833.             DWORD_PTR delta = reinterpret_cast<DWORD_PTR>(baseAddress) +
  2834.                 pSectionHeader[i].PointerToRawData;
  2835.  
  2836.             DWORD_PTR result = delta + (rva - pSectionHeader[i].VirtualAddress);
  2837.  
  2838.             // Additional validation
  2839.             if (result < reinterpret_cast<DWORD_PTR>(baseAddress) ||
  2840.                 result >= (reinterpret_cast<DWORD_PTR>(baseAddress) + fileSize)) {
  2841.                 OUTPUT("[-] RVA pointer out of bounds\n");
  2842.                 return 0;
  2843.             }
  2844.  
  2845.             return result;
  2846.         }
  2847.     }
  2848.  
  2849.     OUTPUT("[-] RVA not found in any section: 0x%X\n", rva);
  2850.     return 0;
  2851. }
  2852. //}
  2853. //}
  2854.  
  2855. /* DWORD_PTR GetRvaPtr(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader,
  2856.     WORD numberOfSections, LPVOID baseAddress) {
  2857.     if (!rva || !pSectionHeader || !baseAddress) return 0;
  2858.  
  2859.     for (WORD i = 0; i < numberOfSections; i++) {
  2860.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2861.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2862.             DWORD_PTR delta = (DWORD_PTR)baseAddress + pSectionHeader[i].PointerToRawData;
  2863.             return delta + (rva - pSectionHeader[i].VirtualAddress);
  2864.         }
  2865.     }
  2866.     OUTPUT("[-] Failed to map RVA: 0x%X\n", rva);
  2867.     return 0;
  2868. } */
  2869.  
  2870. DWORD RvaToOffset(DWORD rva, PIMAGE_SECTION_HEADER pSectionHeader, WORD numberOfSections) {
  2871.     if (!rva || !pSectionHeader) return 0;
  2872.  
  2873.     for (WORD i = 0; i < numberOfSections; i++) {
  2874.         if (rva >= pSectionHeader[i].VirtualAddress &&
  2875.             rva < (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData)) {
  2876.             return (rva - pSectionHeader[i].VirtualAddress) + pSectionHeader[i].PointerToRawData;
  2877.         }
  2878.     }
  2879.     OUTPUT("[-] Failed to map RVA: 0x%X\n", rva);
  2880.     return 0;
  2881. }
  2882.  
  2883. // PE information helper functions
  2884. std::wstring GetImageCharacteristics(DWORD characteristics) {
  2885.     if (characteristics & IMAGE_FILE_DLL) return L"(DLL)";
  2886.     if (characteristics & IMAGE_FILE_SYSTEM) return L"(DRIVER)";
  2887.     if (characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) return L"(EXE)";
  2888.     return L"(UNKNOWN)";
  2889. }
  2890.  
  2891. std::wstring GetSubsystem(WORD subsystem) {
  2892.     switch (subsystem) {
  2893.     case IMAGE_SUBSYSTEM_NATIVE: return L"(NATIVE/DRIVER)";
  2894.     case IMAGE_SUBSYSTEM_WINDOWS_GUI: return L"(GUI)";
  2895.     case IMAGE_SUBSYSTEM_WINDOWS_CUI: return L"(CONSOLE)";
  2896.     default: return L"(UNKNOWN)";
  2897.     }
  2898. }
  2899.  
  2900. std::wstring GetDataDirectoryName(int DirectoryNumber) {
  2901.     static const wchar_t* names[] = {
  2902.         L"Export Table", L"Import Table", L"Resource Table",
  2903.         L"Exception Entry", L"Security Entry", L"Relocation Table",
  2904.         L"Debug Entry", L"Copyright Entry", L"Global PTR Entry",
  2905.         L"TLS Entry", L"Configuration Entry", L"Bound Import Entry",
  2906.         L"IAT", L"Delay Import Descriptor", L"COM Descriptor"
  2907.     };
  2908.     return (DirectoryNumber < 15) ? names[DirectoryNumber] : L"Unknown";
  2909. }
  2910.  
  2911. std::wstring GetSectionProtection(DWORD characteristics) {
  2912.     std::wstring protection = L"(";
  2913.     bool needsSeparator = false;
  2914.  
  2915.     if (characteristics & IMAGE_SCN_MEM_EXECUTE) {
  2916.         protection += L"EXECUTE";
  2917.         needsSeparator = true;
  2918.     }
  2919.     if (characteristics & IMAGE_SCN_MEM_READ) {
  2920.         if (needsSeparator) protection += L" | ";
  2921.         protection += L"READ";
  2922.         needsSeparator = true;
  2923.     }
  2924.     if (characteristics & IMAGE_SCN_MEM_WRITE) {
  2925.         if (needsSeparator) protection += L" | ";
  2926.         protection += L"WRITE";
  2927.     }
  2928.     protection += L")";
  2929.     return protection;
  2930. }
  2931. }
Add Comment
Please, Sign In to add comment