Simple threads example for Dev C++ using windows.h - c++

I have been trying to learn multithreading for the first time but most of the examples I saw had a thread.h header file. Its not there in Dev C++.
I found this article, which says you can do it using windows.h.Sadly it doesn't provide any example programs. Can somebody please provide an example program which uses thread functions in windows.h or any other header file which is widely used and is present in Dev C++?
Thank You

Best option is to do threading in c or c++ use pthread.h header file
example work on gcc or dev c++
#include <stdio.h>
#include <stdlib.h>
#include<pthread.h>
int i=0;
void* fun()
{
for(i=0;i<100;i++)
printf("\nThe thread 1 is running");
}
void* van()
{
for(i=0;i<100;i++)
printf("\nthread 2 is running ");
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
pthread_join(t2,NULL);
return 0;
}

Well windows.h has a function called CreateThread().
It's signature and other info can been seen here.
You need a callback function, that will start executing when you start the thread.
NULL can be passed to the first lpThreadAttributes argument.
HANDLE WINAPI CreateThread(
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
);

Related

Winapi hook via mhook causes program crash or hang

I am trying to hook StartDocW to intercept printing via mhook. I use AppInit_DLLs to load my library.
DLL code is simple:
#include <windows.h>
#include "mhook/mhook-lib/mhook.h"
using StartDocPtr = int(*)(HDC, const DOCINFO*);
StartDocPtr orig;
int HookedStartDocW(HDC hdc, const DOCINFO* lpdi) {
return orig(hdc, lpdi);
}
BOOL WINAPI DllMain(__in HINSTANCE, __in DWORD Reason, __in LPVOID) {
orig = (StartDocPtr)GetProcAddress(GetModuleHandle("gdi32"), "StartDocW");
switch (Reason)
{
case DLL_PROCESS_ATTACH:
Mhook_SetHook((PVOID*)&orig, &HookedStartDocW);
break;
case DLL_PROCESS_DETACH:
Mhook_Unhook((PVOID*)&orig);
break;
}
}
Hook is working and printing is done OK. But If I change HookStartDocW to following:
int HookedStartDocW(HDC hdc, const DOCINFO* lpdi) {
char buf[40];
GetModuleFileName(NULL, buf, 40);
return orig(hdc, lpdi);
}
Programs on printing will crash immediately. Even if I just leave char buf[40] and comment GetModuleHandle - program will hang. Why is this happening?
Moreover, if program crashes\hangs on printing (if I add anything besides return orig(hdc, lpdi)) - PC starts to behave very weirdly, refusing to run programs, etc. If I reboot it - Windows just endlessly spins on boot screen, the only way to bring it back to live - is to boot via liveCD and rename\delete my hook DLL.
Printing programs: Excel 2016, notepad.
Compiler - MSVC 2015, x64 release DLL compilation, using MBCS instead of unicode.
Your hook is declared wrong.
Look at the actual declaration of StartDocW() in Wingdi.h:
__gdi_entry WINGDIAPI int WINAPI StartDocW(__in HDC hdc, __in CONST DOCINFOW *lpdi);
You can ignore __gdi_entry. WINGDIAPI simply resolves to __declspec(dllimport). What is important in this declaration is the WINAPI.
Like almost all Win32 API functions, StartDocW() uses the __stdcall calling convention. The WINAPI macro resolves to __stdcall.
Your code does not specify any calling convention at all, so it uses your compiler's default, which is usually __cdecl instead. So you are mismanaging the call stack. That is why your code crashes.
You are also using DOCINFO when you should be using DOCINFOW instead. It is clear in your code that you are compiling for MBCS and not for UNICODE, so DOCINFO maps to DOCINFOA. You can't pass a DOCINFOA to StartDocW(), it expects a DOCINFOW instead.
You need to fix your declarations, eg:
#include <windows.h>
#include "mhook/mhook-lib/mhook.h"
using StartDocPtr = int (WINAPI *)(HDC, const DOCINFOW*);
StartDocPtr orig = nullptr;
int WINAPI HookedStartDocW(HDC hdc, const DOCINFOW* lpdi) {
//...
return orig(hdc, lpdi);
}
BOOL WINAPI DllMain(__in HINSTANCE, __in DWORD Reason, __in LPVOID) {
orig = (StartDocPtr) GetProcAddress(GetModuleHandle(TEXT("gdi32")), "StartDocW");
switch (Reason)
{
case DLL_PROCESS_ATTACH:
Mhook_SetHook((PVOID*)&orig, &HookedStartDocW);
break;
case DLL_PROCESS_DETACH:
Mhook_Unhook((PVOID*)&orig);
break;
}
}

Compiler Error C2664 or C2731 C++ 2015

I have been able to fine the WinMain function. Now I'm trying to make a win32 app:
#include <Windows.h>
int WINAPI WinMain() {
MessageBox(NULL,"Test", "Hello World", NULL);
return 0;
}
and then I get error C2731.
You haven't provided any parameters to the WinMain() method, and the error C2731 is saying that this method cannot be overloaded.
From MSDN:
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow);
Error C2664 is most likely your call to MessageBox, so try changing to something like:
MessageBox(NULL, L"Test", L"Hello World", NULL);
I figured it out I wasn't useint main.cpp as my main source code file and my WinMain needed to be switched to wWinMain

Getting function by name in c++

Code:
#include <tchar.h>
#include <windows.h>
typedef INT (WINAPI * lolMessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nCmdShow)
{
lolMessageBoxA UchwytMessageBoxA;
UchwytMessageBoxA = lolMessageBoxA(GetProcAddress(GetModuleHandle("User32.dll"),"MessageBoxA"));
UchwytMessageBoxA(NULL,"TEST WINDOWS","TEXT 2", MB_OKCANCEL | MB_ICONWARNING);
return 0;
}
When i called MessageBoxA normally before making hook the hooking part worked good. But when i erased that part and leaved only the 'hooking' part it fails...
Solved:
#include <tchar.h>
#include <windows.h>
typedef INT (WINAPI * lolMessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nCmdShow)
{
lolMessageBoxA UchwytMessageBoxA;
LoadLibraryA("User32.dll");
UchwytMessageBoxA = lolMessageBoxA(GetProcAddress(GetModuleHandle("User32.dll"),"MessageBoxA"));
UchwytMessageBoxA(NULL,"TEST WINDOWS","TEXT 2", MB_OKCANCEL | MB_ICONWARNING);
return 0;
}
As presented here, there's no reason for the process to have loaded user32.dll. So the call to GetModuleHandle will return NULL. Then the call to GetProcAddress will also fail and return NULL. And well, you can see what happens next.
When you called MessageBoxA directly, the linker would have produced an import table that forced the loader to load user32.dll. But when you removed the call to MessageBoxA, there was no need for it to do so.
You should replace the call to GetModuleHandle with a call to LoadLibrary, and so force the library to be loaded.
Finally, the real reason for you having asked this question is that your code neglects error checking. Don't do that. Check the values returned by the Win32 function calls. Had you done so you would have been able to work this out for yourself.

How to build an ATL project properly?

For the lack of the documentation on the Internet about this technologie, can someone please just explain the architecture of an ATL project (Service EXE) ?
And, give a full example of the main methods defined by Microsoft able to be written xxx.cpp item ?
An example of response to the second question:
extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/,
LPTSTR /*lpCmdLine*/, int nShowCmd)
{
return _AtlModule.WinMain(nShowCmd);
}
void CATLProject6Module::ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
// I can do this this and this
CAtlServiceModuleT<CATLProject6Module, 100>::ServiceMain(dwArgc, lpszArgv);
}
//Run method()...
//Handler method()...
//...
This topic may help anyone interested in developing his first Active Template Library application (Service EXE) !
Thanks a lot !!

Can Windows API functions be over-written and called after it?

I want to modify the native functions available in Windows API, such as CreateWindowEx or ShowWindow in a way that when an application is compiled with those functions included, it will instead call my functions, perform the tasks there, and then call the original native function.
In other words, I want to in a way proxy the functions, while still using the same names (so if a program was written to be compiled with the native API, simply adding these functions would modify the way those native functions are handled)
HWND WINAPI CreateWindowEx(
__in DWORD dwExStyle,
__in_opt LPCTSTR lpClassName,
__in_opt LPCTSTR lpWindowName,
__in DWORD dwStyle,
__in int x,
__in int y,
__in int nWidth,
__in int nHeight,
__in_opt HWND hWndParent,
__in_opt HMENU hMenu,
__in_opt HINSTANCE hInstance,
__in_opt LPVOID lpParam
) {
//my custom code here....
// done with my custom code... so now I want to run the native function
return CreateWindowEx(dwExStyle, lpClassName, lpWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam);
}
This (for obvious reasons) gives a stack overflow, as it keeps on calling itself over and over. What I would want it to do is, when it is called, it runs through the custom function I've created, and thereafter runs the native functions available in Windows API.
I am quite new to c++, but for example in many other languages, I could store a reference to the native function under another name, which I could then call inside my custom function. Is there anything similar available in c++?
As I've written in the comment, the parent of many hooking libraries was probably the microsoft Detours
Now that it isn't free anymore there are various alternatives. Here there is a comparison of some of them (link removed. I'm not sure it was safe. Try googling for "Microsoft Detours is a library utilized in the particular interception" and select a source or more simply for Detours Alternatives.
Mmmh it seems the only free alternative at this time are http://easyhook.codeplex.com/ and http://www.codeproject.com/KB/system/mini_hook_engine.aspx
There is a SO question: Detours alternative for Registry interception if you are interested.
One interpretation of your question is that you have a project, with source code, and you want to change that project so it uses your own versions of certain winapi functions.
Here is a solution which you can implement for each imported API function. Example here is for ShowWindow:
#define ShowWindow Deleted_Winapi_ShowWindow // prevent windows.h from defining ShowWindow
#include <windows.h>
#undef ShowWindow
namespace HiddenWinapi
{
extern "C"
{
// Do what windows.h does, but hide it inside a namespace.
WINUSERAPI BOOL WINAPI ShowWindow( __in HWND hWnd, __in int nCmdShow);
}
}
// make your own function to be called instead of the API, and delegate to the actual API in the namespace.
BOOL WINAPI ShowWindow(HWND hwnd, int nCmdShow)
{
// ... do stuff ...
// call the original API
return HiddenWinapi::ShowWindow(hwnd, nCmdShow);
}
To use this solution for CreateWindowEx, you need to stub the actual imported function name (e.g. CreateWindowExW), because CreateWindowEx is just a macro which expands to CreateWindowExW or CreateWindowExA.
Here is a solution which replaces the macro with your own, but I think in all cases it would be better to use the above solution.
#include <windows.h>
#undef CreateWindowEx
// Note that this is a unicode-only version. If your app mixes A and W versions, see
// the solution below for non-macro APIs.
HWND WINAPI CreateWindowEx(DWORD dwExStyle, LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam)
{
// ... do stuff ...
// call the REAL function.
return CreateWindowExW(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam);
}
If you want to do this yourself the easiest way is to modify the import address table in the PE (portable executable) header. This is not trivial, though.
However, I believe there's a standard library for what you want called Detours. I've never used that one myself, though, because it wasn't around when I started doing this, so I have a - not for public consumption - library for doing it via the import table when I need it.