How to set name to a Win32 Thread? - windows

How do I set a name to a Win32 thread. I did'nt find any Win32 API to achieve the same. Basically I want to add the Thread Name in the Log file. Is TLS (Thread Local Storage) the only way to do it?

Does this help ?
How to: Set a Thread Name in Native Code
In managed code, it is as easy as setting the Name property of the corresponding Thread object.

http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.90).aspx
//
// Usage: SetThreadName (-1, "MainThread");
//
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}

According to discussion with the Microsoft debugging team leads (see link below for details) the SetThreadDescription API is the API that will be used going forward by Microsoft to support thread naming officially in native code. By "officially" I mean an MS-supported API for naming threads, as opposed to the current exception-throwing hack that currently only works while a process is running in Visual Studio.
This API became available starting in Windows 10, version 1607.
Currently, however, there is very little tooling support, so the names you set won't be visible in the Visual Studio or WinDbg debuggers. As of April 2017, however, the Microsoft xperf/WPA tools do support it (threads named via this API will have their names show up properly in those tools).
If you would like to see this gain better support, such as in WinDbg, Visual Studio, and crash dump files, please vote for it using this link:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17608120-properly-support-native-thread-naming-via-the-sett

Win32 threads do not have names. There is a Microsoft convention whereby applications raise special SEH exceptions containing a thread name. These exceptions can be intercepted by debuggers and used to indicate the thread name. A couple of the answers cover that.
However, that is all handled by the debugger. Threads themselves are nameless objects. So, if you want to associate names with your threads, you'll have to develop your own mechanism. Whilst you could use thread local storage that will only allow you to obtain the name from code executing in that thread. So a global map between thread ID and the name would seem like the most natural and useful approach.

You can use a thread-local storage object to store the name. For example,
__declspec( thread ) char threadName[32];
Then you can write and read this from a thread. This might be useful in a logger application, where you want to print out the name of the thread for every message. You probably want to write this variable as soon as the thread starts, and also throw the Microsoft exception (https://stackoverflow.com/a/10364541/364818) so that the debugger also knows the thread name.

If your application runs on Windows version 1607+, you can use SetThreadDescription()

If you want to see the name of your thread in the debugger (windbg or visual studio):
http://blogs.msdn.com/stevejs/archive/2005/12/19/505815.aspx
I'm not actually sure if there's a reverse method to get the thread name. But TLS sounds like the way to go.

Another way to do this is to store a pointer to the name in the ArbitraryUserPointer field of the TEB of the thread. This can be written to and read from at runtime.
There's a CodeProject article titled "Debugging With The Thread Information Block" that shows you how to do this.

You can always store this information for yourself in a suitable data structure. Use a hash or a map to map GetThreadId() to this name. Since GetThreadId() is always a unique identifier, this works just fine.
Cheers !
Of course, if he's creating many
threads, that hashmap will slowly fill
up and use more and more memory, so
some cleanup procedure is probably a
good thing as well.
You're absolutely right. When a thread dies, it's corresponding entry in the map should naturally be removed.

Related

How do I know if my MFC Application use COM / OLE?

I come from Win7 to Win10 and recently ran in an "Improper argument error" by opening an file.
The error occurs very rare and randomly.
No further info or call stack info are provided. I had do search deep in MFC code. The DocManager opens the document and then calls CDocument::SetPathName(..,TRUE) to add the current file to the recent file list too.
It seems this function use now an OLE/COM function.
void CRecentFileList::Add(LPCTSTR lpszPathName, LPCTSTR lpszAppID)
{
:
:
Add(lpszPathName);
HRESULT hr = S_OK;
CComPtr<IShellItem> psi = NULL;
hr = _AfxSHCreateItemFromParsingName(lpszPathName, NULL, IID_IShellItem, reinterpret_cast<void**>(&psi));
ENSURE(SUCCEEDED(hr)); // Remark Tom: This throws an AfxInvalidException()
}
hr ErrorCode is -2147221008, which means CoInitialize has not been called.
I am surprised, because I never used COM / OLE Stuff.
Do overcome this error, I must add AfxOleInit() in InitInstance.
My question is, how Do I know in advance if my application needs to use OLE / COM?
Additional question, do I have any drawback if I use COM / OLE in my application. (memory & speed)?
My question is, how Do I know in advance if my application needs to use OLE / COM?
MFC applications are supposed to always initialize OLE/COM, specifically with a concurrency model of STA (single thread apartment). This is done automatically in the wizard-generated templates, otherwise it must be done explicitly in user's code. From the CWinApp documentation:
MFC applications must be initialized as single threaded apartment (STA).
If you call CoInitializeEx in your InitInstance override, specify COINIT_APARTMENTTHREADED (rather than COINIT_MULTITHREADED).
Having OLE/COM always initialized to STA also avoids the curse of the implicit MTA mentioned by #IInspectable in a comment.

Is it safe to use WM_COPYDATA between 64-and 32-bit (WOW64) apps?

There is a good SO Q/A session on the general use of WM_COPYDATA messages here, and a 'discussion' about whether or not this will work between apps of different 32/64-bitness here. However, the latter seems to be focussed on possible misuse of the 'data pointer' being passed. So, I'm raising a new question here.
I am working on getting two Windows apps to communicate/synchronize with each other and, as a first-round approach, I'm using Windows Messaging to implement this. Everything seems OK for now … but I'm using the WM_COPYDATA message to pass info between the apps.
My question: Is this approach guaranteed to be safe when the two apps have different (32/64) bitness? I've done some tests using the code below with all four possible combinations of 32 vs 64 builds between 'client' and 'server', and all work as expected; but is this just because I'm getting 'lucky' results (from possible undefined behaviour), or does the WOW64 system (especially when server is 64-bit and client is 32) take care of all the necessary marshalling?
If anyone can confirm that it is guaranteed to work, I would very much appreciate an 'official' link/reference confirming that.
Shared header file:
static const WPARAM nmIdFilePath = 0x00001100;
struct nmLockInfoType {
char filePathID[1024];
// More elements will be added later!
};
static const nmLockInfoType nmLockInfoDefault = {
"<<<Uninitialised Image Data Path>>>",
//...
};
extern nmLockInfoType nmLockInfo; // MUST be provided by each app!
///nmLockInfoType nmLockInfo = nmLockInfoDefault; // Use this code to instatiate it (once, somewhere)!
Server program code (inside the handler for a RegisterWindowMessage(L"HANDSHAKE"); message):
//...
COPYDATASTRUCT cds;
cds.dwData = nmIdFilePath; // Pre-defined ID
cds.cbData = sizeof(nmLockInfoType);
cds.lpData = &nmLockInfo; // Pre-defined structure (see above)
//...
// Send a copy of the "Welcome Pack" data structure to the client app ...
::SendMessage(clientLock, WM_COPYDATA, WPARAM(m_hWnd), LPARAM(&cds)); // "clientLock is the HWND of the client app's MainWnd
Client Program code:
BOOL MyFrame::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
switch (pCopyDataStruct->dwData)
{
case nmIdFilePath:
memcpy(&nmLockInfo, pCopyDataStruct->lpData, pCopyDataStruct->cbData);
return nmsSucceeded; // This is NON_ZERO so evaluates to TRUE
// Other cases here ...
}
return CMDIFrameWnd::OnCopyData(pWnd, pCopyDataStruct);
}
I'm particularly concerned about the case when the client is 32-bit but the server is 64-bit; in such a case, it would be sending a 64-bit data address to a 32-bit app (albeit, a WOW64 app). Does the in-built 'marshalling' handle this in WOW64 situations?
It's safe only when we follow the rule how to use it. Please refer the remarks of WM_COPYDATA message from below:
The data being passed must not contain pointers or other references to
objects not accessible to the application receiving the data.
While this message is being sent, the referenced data must not be
changed by another thread of the sending process.
The receiving application should consider the data read-only. The
lParam parameter is valid only during the processing of the message.
The receiving application should not free the memory referenced by
lParam. If the receiving application must access the data after
SendMessage returns, it must copy the data into a local buffer.
For example, if we are trying to passing the data type: ULONG_PTR, then the data copy maybe not function well when pass it from 64-bit application to 32-bit application. Because it is 32-bit on 32-bit application and 64-bit on 64-bit application.
You can test it via modify the code below:
struct nmLockInfoType {
char filePathID[1024];
ULONG_PTR point64_32;
// More elements will be added later!
};
The scenario mentioned above, which should be safe as the result you tested. Feel free to let me know if you still have concern about.
In-addition, below is an helpful document about developing 64-bit application for your reference:
Common Visual C++ 64-bit Migration Issues

what is the purpose of the BeingDebugged flag in the PEB structure?

What is the purpose of this flag (from the OS side)?
Which functions use this flag except isDebuggerPresent?
thanks a lot
It's effectively the same, but reading the PEB doesn't require a trip through kernel mode.
More explicitly, the IsDebuggerPresent API is documented and stable; the PEB structure is not, and could, conceivably, change across versions.
Also, the IsDebuggerPresent API (or flag) only checks for user-mode debuggers; kernel debuggers aren't detected via this function.
Why put it in the PEB? It saves some time, which was more important in early versions of NT. (There are a bunch of user-mode functions that check this flag before doing some runtime validation, and will break to the debugger if set.)
If you change the PEB field to 0, then IsDebuggerPresent will also return 0, although I believe that CheckRemoteDebuggerPresent will not.
As you have found the IsDebuggerPresent flag reads this from the PEB. As far as I know the PEB structure is not an official API but IsDebuggerPresent is so you should stick to that layer.
The uses of this method are quite limited if you are after a copy protection to prevent debugging your app. As you have found it is only a flag in your process space. If somebody debugs your application all he needs to do is to zero out the flag in the PEB table and let your app run.
You can raise the level by using the method CheckRemoteDebuggerPresent where you pass in your own process handle to get an answer. This method goes into the kernel and checks for the existence of a special debug structure which is associated with your process if it is beeing debugged. A user mode process cannot fake this one but you know there are always ways around by simply removing your check ....

Identify and intercept function call

I'm developing a launcher for a game.
Want to intercept game's call for a function that prints text.
I don't know whether the code that contains this function is dynamically linked or statically. So I dont even know the function name.
I did intercepted some windows-api calls of this game through microsoft Detours, Ninject and some others.
But this one is not in import table either.
What should I do to catch this function call? What profiler should be used? IDA? How this could be done?
EDIT:
Finally found function address. Thanks, Skino!
Tried to hook it with Detours, injected dll. Injected DllMain:
typedef int (WINAPI *PrintTextType)(char *, int, float , int);
static PrintTextType PrintText_Origin = NULL;
int WINAPI PrintText_Hooked(char * a, int b, float c, int d)
{
return PrintText_Origin(a, b, c , d);
}
HMODULE game_dll_base;
/* game_dll_base initialization goes here */
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if(fdwReason==DLL_PROCESS_ATTACH)
{
DisableThreadLibraryCalls(hinstDLL);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
PrintText_Origin = (PrintTextType)((DWORD)game_dll_base + 0x6049B0);
DetourAttach((PVOID *)&PrintText_Origin , PrintText_Hooked);
DetourTransactionCommit();
}
}
It hooks as expected. Parameter a has text that should be displayed. But when calling original function return PrintText_Origin (a, b, c , d); application crashes(http://i46.tinypic.com/ohabm.png, http://i46.tinypic.com/dfeh4.png)
Original function disassembly:
http://pastebin.com/1Ydg7NED
After Detours:
http://pastebin.com/eM3L8EJh
EDIT2:
After Detours:
http://pastebin.com/GuJXtyad
PrintText_Hooked disassembly http://pastebin.com/FPRMK5qt w3_loader.dll is the injected dll
Im bad at ASM, please tell what can be wrong ?
Want to intercept game's call for a function that prints text.
You can use a debugger for the investigative phase. Either IDA, or even Visual Studio (in combination with e.g. HxD), should do. It should be relatively easy to identify the function using the steps below:
Identify a particular fragment of text whose printing you want to trace (e.g. Hello World!)
Break the game execution at any point before the game normally prints the fragment you identified above
Search for that fragment of text† (look for either Unicode or ANSI) in the game's memory. IDA will allow you to do that IIRC, as will the free HxD (Extras > Open RAM...)
Once the address of the fragment has been identified, set a break-on-access/read data breakpoint so the debugger will give you control the moment the game attempts to read said fragment (while or immediately prior to displaying it)
Resume execution, wait for the data breakpoint to trigger
Inspect the stack trace and look for a suitable candidate for hooking
Step through from the moment the fragment is read from memory until it is printed if you want to explore additional potential hook points
†provided text is not kept compressed (or, for whatever reason, encrypted) until the very last moment
Once you are done with the investigative phase and you have identified where you'd like to inject your hook, you have two options when writing your launcher:
If, based on the above exercise, you were able to identify an export/import after all, then use any API hooking techniques
EDIT Use Microsoft Detours, making sure that you first correctly identify the calling convention (cdecl, fastcall, stdcall) of the function you are trying to detour, and use that calling convention for both the prototype of the original as well as for the implementation of the dummy. See examples.
If not, you will have to
use the Debugging API to programatically load the game
compute the hook address based on your investigative phase (either as a hard-coded offset from the module base, or by looking for the instruction bytes around the hook site‡)
set a breakpoint
resume the process
wait for the breakpoint to trigger, do whatever you have to do
resume execution, wait for the next trigger etc. again, all done programatically by your launcher via the Debugging API.
‡to be able to continue to work with eventual patch releases of the game
At this stage it sounds like you don't have a notion of what library function you're trying to hook, and you've stated it's not (obviously at least) an imported external function in the import table which probably means that the function responsible for generating the text is likely located inside the .text of the application you are disassembling directly or loaded dynamically, the text generation (especially in a game) is likely a part of the application.
In my experience, this simplest way to find code that is difficult to trace such as this is by stopping the application shortly during or before/after text is displayed and using IDA's fabulous call-graph functionality to establish what is responsible for writing it out (use watches and breakpoints liberally!)
Look carefully to calls to CreateRemoteThread or any other commonly used dynamic loading mechanism if you have reason to believe this functionality might be provided by an exported function that isn't showing up in the import table.
I strongly advice against it but for the sake of completeness, you could also hook NtSetInformationThread in the system service dispatch table. here's a good dump of the table for different Windows versions here. If you want to get the index in the table yourself you can just disassemble the NtSetInformationThread export from ntdll.dll.

Some Windows API calls fail unless the string arguments are in the system memory rather than local stack

We have an older massive C++ application and we have been converting it to support Unicode as well as 64-bits. The following strange thing has been happening:
Calls to registry functions and windows creation functions, like the following, have been failing:
hWnd = CreateSysWindowExW( ExStyle, ClassNameW.StringW(), Label2.StringW(), Style,
Posn.X(), Posn.Y(),
Size.X(), Size.Y(),
hParentWnd, (HMENU)Id,
AppInstance(), NULL);
ClassNameW and Label2 are instances of our own Text class which essentially uses malloc to allocate the memory used to store the string.
Anyway, when the functions fail, and I call GetLastError it returns the error code for "invalid memory access" (though I can inspect and see the string arguments fine in the debugger). Yet if I change the code as follows then it works perfectly fine:
BSTR Label2S = SysAllocString(Label2.StringW());
BSTR ClassNameWS = SysAllocString(ClassNameW.StringW());
hWnd = CreateSysWindowExW( ExStyle, ClassNameWS, Label2S, Style,
Posn.X(), Posn.Y(),
Size.X(), Size.Y(),
hParentWnd, (HMENU)Id,
AppInstance(), NULL);
SysFreeString(ClassNameWS); ClassNameWS = 0;
SysFreeString(Label2S); Label2S = 0;
So what gives? Why would the original functions work fine with the arguments in local memory, but when used with Unicode, the registry function require SysAllocString, and when used in 64-bit, the Windows creation functions also require SysAllocString'd string arguments? Our Windows procedure functions have all been converted to be Unicode, always, and yes we use SetWindowLogW call the correct default Unicode DefWindowProcW etc. That all seems to work fine and handles and draws Unicode properly etc.
The documentation at http://msdn.microsoft.com/en-us/library/ms632679%28v=vs.85%29.aspx does not say anything about this. While our application is massive we do use debug heaps and tools like Purify to check for and clean up any memory corruption. Also at the time of this failure, there is still only one main system thread. So it is not a thread issue.
So what is going on? I have read that if string arguments are marshalled anywhere or passed across process boundaries, then you have to use SysAllocString/BSTR, yet we call lots of API functions and there is lots of code out there which calls these functions just using plain local strings?
What am I missing? I have tried Googling this, as someone else must have run into this, but with little luck.
Edit 1: Our StringW function does not create any temporary objects which might go out of scope before the actual API call. The function is as follows:
Class Text {
const wchar_t* StringW () const
{
return TextStartW;
}
wchar_t* TextStartW; // pointer to current start of text in DataArea
I have been running our application with the debug heap and memory checking and other diagnostic tools, and found no source of memory corruption, and looking at the assembly, there is no sign of temporary objects or invalid memory access.
BUT I finally figured it out:
We compile our code /Zp1, which means byte aligned memory allocations. SysAllocString (in 64-bits) always return a pointer that is aligned on a 8 byte boundary. Presumably a 32-bit ANSI C++ application goes through an API layer to the underlying Unicode windows DLLs, which would also align the pointer for you.
But if you use Unicode, you do not get that incidental pointer alignment that the conversion mapping layer gives you, and if you use 64-bits, of course the situation will get even worse.
I added a method to our Text class which shifts the string pointer so that it is aligned on an eight byte boundary, and viola, everything runs fine!!!
Of course the Microsoft people say it must be memory corruption and I am jumping the wrong conclusion, but there is evidence it is not the case.
Also, if you use /Zp1 and include windows.h in a 64-bit application, the debugger will tell you sizeof(BITMAP)==28, but calling GetObject on a bitmap will fail and tell you it needs a 32-byte structure. So I suspect that some of Microsoft's API is inherently dependent on aligned pointers, and I also know that some optimized assembly (I have seen some from Fortran compilers) takes advantage of that and crashes badly if you ever give it unaligned pointers.
So the moral of all of this is, dont use "funky" compiler arguments like /Zp1. In our case we have to for historical reasons, but the number of times this has bitten us...
Someone please give me a "this is useful" tick on my answer please?
Using a bit of psychic debugging, I'm going to guess that the strings in your application are pooled in a read-only section.
It's possible that the CreateSysWindowsEx is attempting to write to the memory passed in for the window class or title. That would explain why the calls work when allocated on the heap (SysAllocString) but not when used as constants.
The easiest way to investigate this is to use a low level debugger like windbg - it should break into the debugger at the point where the access violation occurs which should help figure out the problem. Don't use Visual Studio, it has a nasty habit of being helpful and hiding first chance exceptions.
Another thing to try is to enable appverifier on your application - it's possible that it may show something.
Calling a Windows API function does not cross the process boundary, since the various Windows DLLs are loaded into your process.
It sounds like whatever pointer that StringW() is returning isn't valid when Windows is trying to access it. I would look there - is it possible that the pointer returned it out of scope and deleted shortly after it is called?
If you share some more details about your string class, that could help diagnose the problem here.

Resources