How to build an ATL project properly? - c++

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 !!

Related

What is invoke_main and mainCRTStartup?

I have a CUI based and GUI based application that is written with CPP language. GUI based application has the following code:
#include <Windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
const TCHAR* title = TEXT("پیام");
const TCHAR* text = TEXT("سلام، من یک پنجره هستم.");
MessageBox(NULL, text, title, MB_OKCANCEL | MB_ICONINFORMATION);
return 0;
}
and CUI based program has the following code:
#include <Windows.h>
#include <iostream>
int main(int argc, const char* argv)
{
const char* cMessage = "Native Windows Development.\n";
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), cMessage, strlen(cMessage), NULL, NULL);
return 0;
}
However, when I debug these programs in WinDBG, I have seen before main and WinMain function, a lot of other functions like mainCRTStartup and invoke_main for CUI based app and WinMainCRTStartup and invoke_main for GUI based app have called.
What are these functions and what they did before executing the main? and also how can I get more information about these two function?
With VS tool, we could see the call stack below:
And if you double-click on each call of the stack, you could see what it did in the code(as comments, the source code was located at ..\VC\Tools\MSVC\14.24.28314\crt\src\vcruntime).
First wWinMainCRTStartup is just to call function __scrt_common_main:
extern "C" int wWinMainCRTStartup()
{
return __scrt_common_main();
}
In __scrt_common_main, the comments contains the detals:
// This is the common main implementation to which all of the CRT main functions
// delegate (for executables; DLLs are handled separately).
static __forceinline int __cdecl __scrt_common_main()
{
// The /GS security cookie must be initialized before any exception handling
// targeting the current image is registered. No function using exception
// handling can be called in the current image until after this call:
__security_init_cookie();
return __scrt_common_main_seh();
}
The function is the common main implementation to which all of the CRT
main functions delegate (for executables; DLLs are handled
separately) and __security_init_cookie is to initialize /GS security cookie
before any exception handling for current image.
Then, it was the __scrt_common_main_seh:
initialize crt, acquire startup lock, check the current native startup state, release startup lock, invoke the dynamically initialized __declspec(thread) variables, register the callback function for thread-local destructors.
After complete the Initialization, call invoke_main, as the name, it invoke main/wWinMain.
static int __cdecl invoke_main()
{
return wWinMain(
reinterpret_cast<HINSTANCE>(&__ImageBase),
nullptr,
_get_wide_winmain_command_line(),
__scrt_get_show_window_mode());
}

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.

C++ - How to find source of heap / stack corruption on program exit

I have a project which causes two assertion failures in succession, AFTER the 'main'-function is completed. This is very problematic because it doesn't show me the piece of code causing the problem.
I was able to narrow the problem down somewhat. With an empty main-function:
int main(int argc,char* argv[])
{
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
return main(__argc,__argv);
}
everything is working just fine. However as soon as I use any class or function from a specific dll (which is part of the project), the problem starts occurring:
int main(int argc,char* argv[])
{
Color col(255,0,0,255);
col.r += 1;
int r = HeapValidate(GetProcessHeap(),0,nullptr);
std::cout<<r<<std::endl;
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
return main(__argc,__argv);
}
the 'Color' class is part of that dll, but it's not the cause of the issue. 'HeapValidate' returns 1, which means the heap is valid according to the documentation.
The dll in question contains hundreds of thousands lines of code, which makes debugging even more difficult.
On a similar question, I found the suggestion to use WinDBG, but I'm not sure what to do with the result:
http://pastebin.com/zV27b51Z
It confirms that the issue is some sort of memory corruption, but I still don't know where it originates from.
Is there any way to reliably find the origin, or am I stuck using trial and error?
My OS is Windows 8.1, I'm using Visual Studio 2013.
Run the application under debugger and press Retry button in assertion messagebox. DebugBreak will be called and the debugger will take coltrol.

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

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
);

VC++ project, how to define DLL missing error messages?

So the idea is when the user haven't installed DirectX End-User Runtime the program to show message like "DirectX Runtime missing! Download it from here", instead of the windows loader error (eg.: "d3dx9_43.dll is missing!"). So I find a very funky solution of the problem as I used a delay loaded DLL's and an DLL check before any function defined in the module is invoked using LoadLibrary. If the dll is missing the program shows a user-defined dialog box and exits, otherwise it calls FreeLibrary with the HMODULE returned by LoadLibrary and continues executing. This is implemented as a function like follows:
bool CheckResourcesAvailability() //Mainly check for the existence of delay loaded DLL's
{
HMODULE hMod; //Resourse handle
if((hMod = LoadLibraryEx(_T("d3d9.dll"), NULL, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) == NULL)
{
DialogBox(hProgramInstance, MAKEINTRESOURCE(IDD_DX_RE), 0, (DLGPROC)&DxRedistMissingDlg);
return false;
}
FreeLibrary(hMod);
if((hMod = LoadLibraryEx(_T("D3DX9_43.dll"), NULL, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) == NULL)
{
DialogBox(hProgramInstance, MAKEINTRESOURCE(IDD_DX_RE), 0, (DLGPROC)&DxRedistMissingDlg);
return false;
}
FreeLibrary(hMod);
return true;
}
*As DxRedistMissingDlg and MAKEINTRESOURCE(IDD_DX_RE) creates the user-defined error message dialog.
And In WinMain it's called as follows:
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
hProgramInstance = hInstance;
#ifndef _DEBUG
SetErrorMode(SEM_FAILCRITICALERRORS); //Don't display windows error messages
#endif
//Check for missing delay - loaded dependencies and inform the user
if(!CheckResourcesAvailability())
return -1;
//Some other code.........
}
But I don't think this is the cleanest way to do it. First we aren't sure that d3dx9.lib really inherits from D3DX9_43.dll (I know that because I used IDA PRO) and also the LoadLibrary function is called twice - one time at the CheckResourcesAvailability() function and second when the DLL is delay-loaded. Any ideas for a better implementation?
Use delay load hooks to let the delay loader notify you whenever a given DLL or a specific exported function is missing. Not only does that tell you which DLL/function is missing, but also lets you specify a substitute DLL/function if desired.