8000 Extract a `ReadLibrary` function in DllLoader.cpp · fancycode/MemoryModule@bc38a6b · GitHub
[go: up one dir, main page]

Skip to content

Commit bc38a6b

Browse files
committed
Extract a ReadLibrary function in DllLoader.cpp
1 parent d46b74d commit bc38a6b

File tree

1 file changed

+42
-17
lines changed

1 file changed

+42
-17
lines changed

example/DllLoader/DllLoader.cpp

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -46,36 +46,61 @@ void LoadFromFile(void)
4646
FreeLibrary(handle);
4747
}
4848

49+
void* ReadLibrary(long* pSize) {
50+
long read;
51+
void* result;
52+
FILE* fp;
53+
54+
fp = _tfopen(DLL_FILE, _T("rb"));
55+
if (fp == NULL)
56+
{
57+
_tprintf(_T("Can't open DLL file \"%s\"."), DLL_FILE);
58+
return NULL;
59+
}
60+
61+
fseek(fp, 0, SEEK_END);
62+
*pSize = ftell(fp);
63+
if (*pSize < 0)
64+
{
65+
fclose(fp);
66+
return NULL;
67+
}
68+
69+
result = (unsigned char *)malloc(*pSize);
70+
if (result == NULL)
71+
{
72+
return NULL;
73+
}
74+
75+
fseek(fp, 0, SEEK_SET);
76+
read = fread(result, 1, *pSize, fp);
77+
fclose(fp);
78+
if (read != static_cast<size_t>(*pSize))
79+
{
80+
free(result);
81+
return NULL;
82+
}
83+
84+
return result;
85+
}
86+
4987
void LoadFromMemory(void)
5088
{
51-
FILE *fp;
52-
unsigned char *data=NULL;
89+
void *data;
5390
long size;
54-
size_t read;
5591
HMEMORYMODULE handle;
5692
addNumberProc addNumber;
5793
HMEMORYRSRC resourceInfo;
5894
DWORD resourceSize;
5995
LPVOID resourceData;
6096
TCHAR buffer[100];
6197

62-
fp = _tfopen(DLL_FILE, _T("rb"));
63-
if (fp == NULL)
98+
data = ReadLibrary(&size);
99+
if (data == NULL)
64100
{
65-
_tprintf(_T("Can't open DLL file \"%s\"."), DLL_FILE);
66-
goto exit;
101+
return;
67102
}
68103

69-
fseek(fp, 0, SEEK_END);
70-
size = ftell(fp);
71-
assert(size >= 0);
72-
data = (unsigned char *)malloc(size);
73-
assert(data != NULL);
74-
fseek(fp, 0, SEEK_SET);
75-
read = fread(data, 1, size, fp);
76-
assert(read == static_cast<size_t>(size));
77-
fclose(fp);
78-
79104
handle = MemoryLoadLibrary(data, size);
80105
if (handle == NULL)
81106
{

0 commit comments

Comments
 (0)
0