Determine whether caller is called from EXE or DLL - c++

I need to determine the caller code whether is coming from EXE or DLL.
DLL
#ifdef DLL_EXPORTS
__declspec(dllexport) void say_hello();
__declspec(dllexport) void getCurrentModuleName();
#else
__declspec(dllimport) void say_hello();
__declspec(dllexport) void getCurrentModuleName();
#endif
#include <cstdio>
#include <windows.h>
#include <Dbghelp.h>
#include <iostream>
#include <tchar.h>
#include "dll.h"
#include "Psapi.h"
__declspec(naked) void *GetStackPointer()
{
__asm
{
mov eax, esp
ret
}
}
void getCurrentModuleName()
{
BOOL result = SymInitialize(GetCurrentProcess(), NULL , TRUE);
DWORD64 dwBaseAddress = SymGetModuleBase64(GetCurrentProcess(), (DWORD64)GetStackPointer());
TCHAR szBuffer[50];
GetModuleBaseName(GetCurrentProcess(), (HMODULE) dwBaseAddress, szBuffer, sizeof(szBuffer));
std::wcout << _T("--->") << szBuffer << std::endl;
}
void say_hello() {
getCurrentModuleName();
}
EXE
#include <windows.h>
#include <cstdio>
#include "dll.h"
int main() {
printf ("ENTERING EXE CODE...\n");
getCurrentModuleName();
printf ("ENTERING DLL CODE...\n");
say_hello();
getchar();
}
Here is the output.
ENTERING EXE CODE...
--->exe.exe
ENTERING DLL CODE...
--->exe.exe
I wish I can get
ENTERING EXE CODE...
--->exe.exe
ENTERING DLL CODE...
--->dll.dll
As the last caller code are from DLL itself (say_hello in DLL)
Is there any way I can achieve this?

GetStackAddress is returning the value of ESP, which is a reference to the stack. The stack is allocated per thread, independently of any modules loaded in the process.
What you need to do is extract from the stack, the value of the return address - which will be an address in the calling module.
Given that the usual prefix code in a function is:
push ebp
mov ebp,esp
sub esp, bytes_of_local_variables
esp is going to be somewhat random, but [ebp] should be pointing at the previous ebp, and [ebp+4] should be pointing at the current frames return address.
So, you could try this:
__declspec(naked) void *GetReturnAddressAssumingStandardFramePointers()
{
__asm
{
mov eax, [ebp+4]
ret
}
}
Just make sure that functions that call that arn't compiled with /Oy

In that case use the return address of the function, which you can figure out by looking directly at the stack. The rest of the answer still applies.

You get stack pointer inside getCurrentModuleName() which is in DLL, but you need to get returning address from stack at the beginning of getCurrentModuleName() which shows you where getCurrentModuleName() was called from.

Use EnumProcessModules(). For each one call GetModuleInformation(). Compare the address of the function that you're executing (using a function pointer) to the lpBaseOfDll and SizeOfImage members of the MODULEINFO struct. If it falls within the range, you know that's the current module. If so, use GetModuleBaseName to retrieve the name of the module.

Here is the solution. The limitation is that, it is only able to trace up to 62 frames.
// Must have in order for us to turned address into module name.
SymInitialize(GetCurrentProcess(), NULL , TRUE);
// Limitation of RtlCaptureStackBackTrace.
const int kMaxCallers = 62;
void* callers[kMaxCallers];
int count = RtlCaptureStackBackTrace(0, kMaxCallers, callers, NULL);
for (int i = 0; i < count; i++) {
TCHAR szBuffer[50];
DWORD64 dwBaseAddress = SymGetModuleBase64(GetCurrentProcess(), (DWORD64)callers[i]);
GetModuleBaseName(GetCurrentProcess(), (HMODULE) dwBaseAddress, szBuffer, sizeof(szBuffer));
std::wcout << _T("--->") << szBuffer << std::endl;
}

Related

How do I call a external c function and import it using af function with a c-style calling convention?

I'm importing a function in a console application from an external .dll the function copies a struct out of shared memory (if you want to test it then any global memory should work)
Here is the function in the dll
struct DataMemBuff {
double High[5] = { 0,0,0,0,0 };
};
#ifdef __cplusplus // If used by C++ code,
extern "C" { // we need to export the C interface
#endif
__declspec(dllexport) DataMemBuff __cdecl GetDatainBuf();
#ifdef __cplusplus
}
#endif
DataMemBuff __cdecl GetDatainBuf()
{
DataMemBuff tempbuf;
memcpy(&tempbuf, lpvMem, sizeof(tempbuf));
return tempbuf;
}
And here is an example of how I import that function into the console application
#include "stdafx.h"
#include <Windows.h>
#include <memory.h>
#include <iostream>
#include <tchar.h>
using namespace std;
typedef DataMemBuff(CALLBACK* _cdecl GetData)(void);
GetData _GetData;
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hDll = NULL;
int x = 1;
struct DataMemBuff tempIndcData;
hDll = LoadLibrary(_T("Data.dll"));
if (hDll == NULL)
{
cout << "The dll did not load" << endl;
printf("Here is the error %lu", GetLastError());
}
else
{
cout << "The dll loaded fine" << endl;
}
_GetData = (GetData)GetProcAddress(hDll, "GetDatainBuf");
if (!_GetData)
{
// handle the error
cout << "The dll did not load the function" << endl;
}
else
{
// call the function
tempIndcData = _GetData();
printf("The memory was copied\n");
}
}
the function imports fine, however it has a problem returning the data on the stack back to the function because of the c style calling convention _cdecl, and it throws an exception on this line when it calls the imported funciton:
tempIndcData = _GetData();
Exception thrown:
This is usually a result of calling a function declared with one
calling convention with a function pointer declared with a different
calling convention.
I have tried throwing in a _cdecl in the declaration going from this:
typedef DataMemBuff(CALLBACK* GetData)(void);
GetData _GetData;
to this:
typedef DataMemBuff(CALLBACK* _cdecl GetData)(void);
GetData _cdecl _GetData;
and that did not help, probably because I don't understand calling enough, but there must be some way to tell GetProcAddress that it is getting a function call with c-style calling conventions.
My question is: what syntax do I use to import a function that uses c-style calling conventions using GetProcAddress?

Create a proxy DLL with GCC/MinGW

With the Visual C++ compiler, it is possible to create a DLL file, that can imitate another DLL file and redirect all function calls to the original DLL. Here is an article with a tool that can generate Visual C++ code automatically.
The generated function-stubs work (tested) and look like this:
extern "C" __declspec(naked) void __stdcall __E__0__()
{
__asm
{
jmp p[0]; // p[0] = GetProcAddress(hL,"AcceptEx");
}
}
Now I want to do the same thing with MinGW/GCC instead of MSVC.
__declspec(naked) isn't supported by GCC on i386, so we need another way.
As suggested here, I could override functions by writing assembly code in the global scope. Here's my code that should do the trick:
__asm__
(
"jmp *%0"
: /* empty output list */
: "r" (pointer_to_original_function) /* p[0] in the example above */
);
My snippet uses GCC's extended ASM. But unfortunatelly this is only allowed inside of functions, not in the global scope!
So... how do I do that? My next approach would be to try it without extended ASM, but how do I get the pointer address in assembly then?
Here i'm trying to get it from a global variable, but it segfaults at repace_this_stub():
#include <stdio.h>
void try_to_jump_to_me()
{
printf("you made the jump\n");
}
void* target_pointer = try_to_jump_to_me;
__asm__ (
"replace_this_stub:"
"jmp target_pointer"
);
void replace_this_stub();
int main(int argc, char** argv)
{
printf("starting in main. \n");
replace_this_stub();
printf("back in main?\n");
}
If the pointer is in a global variable, you can just use its name. Be sure to apply any name mangling. Also put your code in the applicable code section and give it a name. Sample code:
#include <stdio.h>
void* p = printf;
asm(
".section .text\n\t"
"proxy: jmp *p\n\t"
".previous\n\t");
extern void proxy();
int main()
{
proxy("Hello world!\n");
return 0;
}
If you want to use an array, just add the appropriate displacement. Extended sample:
#include <stdio.h>
#include <string.h>
void* p[] = { printf, strcpy };
#define str(x) #x
#define PROXY(name, index) asm( \
".section .text\n\t" \
str(proxy_##name) ": jmp *p + " str(index) " * 4\n\t" \
".previous\n\t"); \
extern void proxy_##name()
PROXY(printf, 0);
PROXY(strcpy, 1);
int main()
{
char buf[128];
proxy_strcpy(buf, "Hello world!\n");
proxy_printf(buf);
return 0;
}

How to access a function inside a dll file in C++

I am currently trying to communicate with a device using CAN. To do so I am using PCAN Basic using C++.
Unfortunately, I know nothing about accessing a function inside a dll file (which is what is provided). I found this link:
Calling a dll function from C++
and am trying to use LoadLibrary via code I found here:
http://www.goffconcepts.com/techarticles/development/cpp/calldll.html
My Code:
// dll_get_func.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h> /* For sqrt() */
#include <windows.h>
#define DELCLDIR __declspec("Pcan_usb.dll")
#define PCAN_USBBUS1 0x51
#define CAN_BAUD_1M 0x0014 // 1 MBit/s
#define MSGTYPE_STANDARD 0x00
typedef struct {
DWORD ID; // 11/29 bit identifier
BYTE MSGTYPE; // Bits from MSGTYPE_*
BYTE LEN; // Data Length Code of the Msg (0..8)
BYTE DATA[8]; // Data 0 .. 7
} TPCANMsg;
int hardCodeInit(void)
{
/* get handle to dll */
HINSTANCE hGetProcIDDLL = LoadLibrary(_T("Pcan_usb.dll"));
/* get pointer to the function in the dll*/
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"CAN_Init");
/*
Define the Function in the DLL for reuse. This is just prototyping the dll's function.
A mock of it. Use "stdcall" for maximum compatibility.
*/
typedef int (__stdcall * pICFUNC)(WORD wBTR0BTR1, int CANMsgType);
pICFUNC CAN_Init;
CAN_Init = pICFUNC(lpfnGetProcessID);
//DWORD __stdcall CAN_Init(WORD wBTR0BTR1, int CANMsgType);
/* The actual call to the function contained in the dll */
int intMyReturnVal = CAN_Init(PCAN_USBBUS1,CAN_BAUD_1M);
/* Release the Dll */
FreeLibrary(hGetProcIDDLL);
/* The return val from the dll */
return intMyReturnVal;
}
int hardCodeWrite(void)
{
HINSTANCE hGetProcIDDLL = LoadLibrary(_T("Pcan_usb.dll"));
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"CAN_Write");
typedef int (__stdcall * pICFUNC)(WORD wBTR0BTR1, TPCANMsg CANMsgType);
pICFUNC CAN_Write;
CAN_Write = pICFUNC(lpfnGetProcessID);
TPCANMsg msgOut;
msgOut.MSGTYPE = MSGTYPE_STANDARD;
msgOut.LEN = 1;
msgOut.DATA[0] = 0x03; // 0x03 = Get ID
int toReturn;
toReturn = CAN_Write(PCAN_USBBUS1,msgOut);
FreeLibrary(hGetProcIDDLL);
return toReturn;
}
int _tmain(int argc, _TCHAR* argv[])
{
int derp=hardCodeInit();
int herp=hardCodeWrite();
std::cout<<derp;
std::cout<<herp;
_getch();
return 0;
}
However, Visual Studio says that there is a:
Unhandled exception at 0x10001D95 (Pcan_usb.dll) in dll_get_func.exe: 0xC0000005:
Access violation reading location 0x00000051.
I have Pcan_usb.dll and Pcan_usb.lib in the same folder and I am using visual studio 2012.
There are several points here. Signature of the LoadLibrary:
HMODULE WINAPI LoadLibrary(_In_ LPCTSTR lpFileName);
Remove unneeded casts. This will simplify reading and understanding your code.
FARPROC lpfnGetProcessID - the name of the variable is confusing. This might be a source of confusion or misunderstanding.
Regarding the AV - the signature of the CAN_Init function as you are trying to use it is wrong. From your post it is hard to tell for sure what is should be. Look into manual (if possible), header file, etc.
Main point - you should not release the library. There are rare cases when this is needed. Most likely your case does not need this. It is very difficult to believe that you need to reload the library (and this what happens when you call FreeLibrary/LoadLibrary!) between initing it and writing.
Access violation reading location 0x00000051.
This tells me the function is treating PCAN_USBBUS1 as a pointer. Perhaps:
#define PCAN_USBBUS1 0x51
should be changed to
WORD pcan_usbbus1 = 0x51;
And the call to CAN_Init should be changed to:
int intMyReturnVal = CAN_Init(&pcan_usbbus1, CAN_BAUD_1M);
The function signature should probably be something like:
typedef int (__stdcall * pICFUNC)(WORD* wBTR0BTR1, int CANMsgType);
^ pointer here
I imagine CAN_BAUD_1M might also need to be changed in the same way but maybe not.

call dll in a c++ file

I created a DLL file (helloWorld.dll):
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define DLL_FUNC extern "C" __declspec(dllexport)
DLL_FUNC int __stdcall Hello() {
MessageBox(HWND_DESKTOP, "Hello, world", "MEssage", MB_OK);
return 0;
}
After that I created a cpp where I would like to call (useDLL.cpp)
#include <windows.h>
#include <stdio.h>
int main () {
typedef void (*pfunc)();
HINSTANCE hdll = LoadLibrary("HelloWorld.dll");
pfunc Hello;
Hello = (pfunc)GetProcAddress(hdll, "hello");
Hello();
return 0;
}
How can I call the Hello() function?
The code in the question contains a number of errors:
LoadLibrary returns HMODULE and not HINSTANCE
The function pointer has the wrong return value and an incorrect calling convention.
Function names are case sensitive and you must account for name decoration.
You did no error checking at all. Your code probably fails on the call to GetProcAddress, returns NULL and then bombs when you try to call the function at NULL.
So you need something like this:
typedef int (__stdcall *HelloProc)();
....
HMODULE hdll = LoadLibrary("HelloWorld.dll");
if (hdll == NULL)
// handle error
HelloProc Hello = (HelloProc)GetProcAddress(hdll, "_Hello#0");
if (Hello == NULL)
// handle error
int retval = Hello();
The function name is decorated because you used __stdcall. If you had used __cdecl, or a .def file, then there would have been no decoration. I'm assuming MSVC decoration. It seems that decoration differs with your compiler, mingw, and the function is named "Hello#0".
Frankly it's much easier to do it with a .lib file instead of calling LoadLibrary and GetProcAddress. If you can, I'd switch to that way now.
You need to specifically search and find specific functions you are lookins for, check out this link:
Calling functions in a DLL from C++

Porting VC++ inline assembler to x64 (of a __stdcall hook)

I need to port the inline assembler to be able to compile on x64.
I'm trying to get familiar with the x64 Intrinsics etc but I guess someone being into it could easily help me out.
void __stdcall Hook(P1, P2)
{
__asm pushad
static void* OriginalFunctionPointer =
GetProcAddress(GetModuleHandleA("Some.dll"), "[...]");
// [...]
__asm popad
__asm push (P2)
__asm push (P1)
__asm call (OriginalFunctionPointer)
}
seems you need a hooking library like this one(or this if you want a C++ API) along with a function proto, then no inline assembly is needed, in 32 or 64-bit mode. also, those pushad/popad's aren't needed when you are doing inline assembly.
typedef void (__stdcall*myfp)(int,int);
void __stdcall MyHook(int arg1, int arg2)
{
static myfp TheFP = (myfp)GetProcAddress(GetModuleHandleA("Some.dll"), "[...]");
//your extra code
TheFP(arg1,arg2);
}
of course the injection of this hook needs to take place somewhere else.
for hooking classes you need to account for the hidden this pointer (pDevice in this case):
#define D3D8FUNC(name,...) typedef HRESULT (__stdcall * name)(__VA_ARGS__)
D3D8FUNC(D3D8SetTexture,void* pDevice, DWORD dwStage, void* pTexture);
HRESULT __stdcall D3DSetTexture(void* pDevice, DWORD dwStage, void* pTexture)
{
LOG("[D3DSetTexture][0x%p] Device: 0x%p Stage: %u Texture: 0x%p\n",_ReturnAddress(),pDevice,dwStage,pTexture);
return Direct3D::gpfD3D8SetTexture(pDevice,dwStage,pTexture);
}
//in the init
Direct3D::gpfD3D8SetTexture = System::VirtualFunctionHook<Direct3D::D3D8SetTexture>(Direct3D::gpDevice,61,D3DSetTexture);