I am trying to understand how self-extracting PE files work. Can somebody explain why my code isn't working, or fix the main() part.
#include <iostream>
#include <Windows.h>
using namespace std;
void ExtractResource(const HINSTANCE hInstance, WORD resourceID, const char* outputFilename);
int main()
{
HINSTANCE hInst = GetModuleHandle (0);
ExtractResource(hInst, 101, "101.dll");
ExtractResource(hInst, 102, "102.dll");
ExtractResource(hInst, 103, "103.dll");
ExtractResource(hInst, 104, "104.dll");
cout << "Files are now extracted!";
Sleep(INFINITE);
}
void ExtractResource(const HINSTANCE hInstance, WORD resourceID, const char* outputFilename){
// First find and load the required resource
HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceID), "BINARY");
if(hResource==NULL)
return;
HGLOBAL hFileResource = LoadResource(hInstance, hResource);
// Now open and map this to a disk file
LPVOID lpFile = LockResource(hFileResource);
DWORD dwSize = SizeofResource(hInstance, hResource);
// Open the file and filemap
HANDLE hFile = CreateFileA(outputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW,
FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_READONLY, NULL);
HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);
LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);
// Write the file
CopyMemory(lpBaseAddress, lpFile, dwSize);
// Unmap the file and close the handles
UnmapViewOfFile(lpBaseAddress);
CloseHandle(hFilemap);
CloseHandle(hFile);
}
I have 4 dll-files in resources, but I can't extract them using this. The resource ID´s should be correct, I checked it from resource header.
Is the problem in hInst
or what else there could be wrong? I hope somebody could help me :) I have just a ~month ago started learning C & C++ so forgive me.