calling functions inside DLLMAIN() - c++

im trying to create DLL file and im having problem running functions inside DLLMAIN().
i want to do somthing like this :
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
INT APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
foo1();
break;
case DLL_PROCESS_DETACH:
foo2()();
break;
}
return true;
}
void foo1(){
//code
}
void foo2(){
// code
}
but it does not work.
when I'm trying to build the file im getting
'foo1' identifier not found
'foo2' identifier not found
what I'm doing wrong here?
thanks!

Probably because you have not declared the functions. Put a
void foo1();
void foo2();
before yout DllMain and it will compile.
But be warned. You should not do anything substantial in DllMain. Especially anything involving loading libraries directly or indirectly might result in deadlocks.

Related

cant find prxdll.h and prx_attach/detach not working

Alright so i was trying to modify a Visual Studio project (DLL Project). And i needed to
add prxdll.h and i needed to use prx_attach/detach.
#include "dllmain.h"
#include "windows.h"
#include "prxdll.h"
BOOL APIENTRY DllMain(
const HINSTANCE instance,
const DWORD reason,
const PVOID reserved)
{
switch (reason) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(instance);
return prx_attach(instance);
case DLL_PROCESS_DETACH:
prx_detach(reserved);
break;
}
return TRUE;
}
Im gettin an error that has a code with C1083 and it writes this:
"Cannot Open include file: 'prxdll.h': No such file or directory"
And also it says "identifier prx_attach() is undefined" (it says this for prx_detach() too).
Because of these errors i cant compile/build this.

CreateThread in DLL Terminating Prematurely

I am trying to load a DLL from Console Application. The simple console application is shown below:
#include <iostream>
#include <windows.h>
int main(){
HMODULE handleDll = LoadLibraryA("C:\\Tools\\TestDLL.dll");
if (handleDll)
{
std::cout << "DLL Loaded at Address: " << handleDll << std::endl;
}
FreeLibrary(handleDll);
}
The DLL is supposed to a POP a MessageBox which it does but just flashes on the screen instead of waiting for user input. The DLL code is below:
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <Windows.h>
DWORD WINAPI ThreadProc( __in LPVOID lpParameter )
{
MessageBox(NULL, L"Hi From The Thread!", L"Pop a Box!", MB_OK);
return 0;
}
extern "C" __declspec(dllexport)
VOID PopMessageBox()
{
DWORD ThreadID;
HANDLE handleThread;
handleThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &ThreadID);
CloseHandle(handleThread);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
PopMessageBox();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
My question is..how do I make the code in the thread function fully execute without prematurely terminating or causing painful deadlocks? Apologies for my imperfect English and inexperience.
The reason is that you are doing something unsafe in your DllMain: you are calling CreateThread.
You are very limited in what you can do from within DllMain in response to a process attach, a fact that the documentation calls out:
There are significant limits on what you can safely do in a DLL entry point. See General Best Practices for specific Windows APIs that are unsafe to call in DllMain. If you need anything but the simplest initialization then do that in an initialization function for the DLL. You can require applications to call the initialization function after DllMain has run and before they call any other functions in the DLL.
The warning links you to "General Best Pratices" which, among other things, says to "[c]all CreateThread. Creating a thread can work if you do not synchronize with other threads, but it is risky."
Even without the risks associated with synchronizing with other threads, this code is flakey in other ways: for example, your main simply calls FreeLibrary and exits. The thread you had spawned in the DLL, which may literally be mid-execution, will have the code it's supposed to run unmapped. You're literally pulling the rug out from under it!

Why rundll gives missing entry? [duplicate]

This question already has answers here:
How does RunDll32 work?
(2 answers)
Closed 8 years ago.
I have created a dead-simple DLL in Visual Studio 2010, a win32 project of type DLL.
Then I changed the DllMain to this:
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(0,L"Hey there!",0,0);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
and I used rundll32 vahid-win32.dll,dllmain to run it. Message box shows, but after that it gives
Error in vahid-win32.dll
Missing entry: dllmain
What is wrong with my DLL? or with me? :-)
Thanks in advance
Your messagebox doesn't come from you passing DllMain function name. Rather it is automatically called. But Rundll32 looking for a export function with name DllMain with dllexport declaration as given below.
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(0,L"Hey there!",0,0);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" __declspec(dllexport) void mydllmain()
{
MessageBox(0,L"Hey there again!",0,0);
}
when you call RunDll32 with parameter mydllmain, it does me give both the message box with out error.
There's no reason to call DllMain via RunDLL, it's called automatically when the DLL is loaded.
Rather try running a custom function.
Aside from that, the problem is probably the exported name. You need to write a .def file for the DLL.
DllMain it is caused automatically, always. it to cause through rundll32, it will be caused, for this purpose it and is "entry point", you repeatedly try to cause it.

How to hook functions that aren't in the Win32 API?

I made a very simple program that create a windows and display "Random number is: [random number from 0 to 9]" in the top left corner. The function that display the number looks like this:
void DisplayThings(HDC hdc, HWND hWnd, int randomNum)
{
std::stringstream text;
text << "Random number is: " << randomNum;
TextOut(hdc, 0, 0, text.str().c_str(), text.str().length());
}
In OllyDBG, I found it at the address 0x11211A0:
Next, I made a dll that tries to detour the DisplayThings function with the help of Microsoft Detour, here is what the dll looks like:
#pragma comment(lib, "detours.lib")
#include <Windows.h>
#include <detours.h>
#include <tchar.h>
#include <sstream>
typedef void (*pDisplayThingsFunc)(HDC hdc, HWND hWnd, int randomNum);
void DisplayThingsFunc(HDC hdc, HWND hWnd, int randomNum)
{
printf("function is being detoured\n");
TextOut(hdc, 0, 20, L"detoured", 8);
}
pDisplayThingsFunc DisplayThingsFuncToDetour = (pDisplayThingsFunc)(0x11211A0);
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
//DWORD *hiddenValueAdress = (DWORD*)(*(DWORD*)0x020FAB8);
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
AllocConsole();
freopen("CONOUT$", "w", stdout);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)DisplayThingsFuncToDetour, DisplayThingsFunc);
DetourTransactionCommit();
break;
case DLL_PROCESS_DETACH:
FreeConsole();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)DisplayThingsFuncToDetour, DisplayThingsFunc);
DetourTransactionCommit();
break;
}
return TRUE;
}
Once I inject the dll, the address get correctly replaced with a JMP to my new functions, but then something weird happens... The console keep printing "function is being detoured" but the TextOut function fails to display anything...
Any help would be appreciated!
The compiler is optimizing the code, because it deduced that it could safely do so for this function.
It is not exported.
It is not used with function pointers.
It is not used outside the scope that is analyzed. (Depends on compiler settings)
There is most likely only one caller (if there are more different callers with different settings it's less likely that arguments get optimized away).
You could change one of those things (for example by exporting the symbol, by assigning it to a function pointer etc..).
Or you could try to hook it as-is now.
First you need to deduce where the argument you are interested in is getting passed trough, which is most likely a register.
The easiest way to do this is to analyze the call to TextOut and trace the hdc argument back.
If you are lucky and it got optimized simply by making it fastcall, change the type of both your function and your function pointer to fastcall, and be done.
If you are not that lucky, you might have to grab it from an extra register with inline assembly.

How can i set an entrypoint for a dll

First i thought entry point in dlls DLLMain but then when i try to import it in C# i get an error that entrypoint wasn't found Here is my code:
#include <Windows.h>
int Test(int x,int y)
{
return x+y;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(0,L"Test",L"From unmanaged dll",0);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
How can i set an entry point for my dll? And if you dont mind can you give me little explanation about entry point?
Like do i have to set import the same dll again and changing the entry point so i can use other functions in same dll? thanks in advance.
In your example, it seems you intend Test() to be an entry point however you aren't exporting it. Even if you begin exporting it, it might not work properly with C++ name "decoration" (mangling). I'd suggest redefining your function as:
extern "C" __declspec(dllexport) int Test(int x,int y)
The extern "C" component will remove C++ name mangling. The __declspec(dllexport) component exports the symbol.
See http://zone.ni.com/devzone/cda/tut/p/id/3056 for more detail.
Edit: You can add as many entry points as you like in this manner. Calling code merely must know the name of the symbol to retrieve (and if you're creating a static .lib, that takes care of it for you).