How to change the name of a thread - c++

I have a server application that uses "a lot" of threads. Without wanting to get into an argument about how many threads it really should be using, it would be nice to be able to see some descriptive text in the debugger "threads" window describing what each one is, without having to click through to it and determine from the context what it is.
They all have the same start address so generally the threads window says something like "thread_base::start" or something similar. I'd like to know if there is an API call or something that allows me to customise that text.

Here is the code I use.
This goes in a header file.
#pragma once
#define MS_VC_EXCEPTION 0x406d1388
#pragma warning(disable: 6312)
#pragma warning(disable: 6322)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in same addr space)
DWORD dwThreadID; // thread ID (-1 caller thread)
DWORD dwFlags; // reserved for future use, most be zero
} THREADNAME_INFO;
inline
void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)
{
#ifdef _DEBUG
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = szThreadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (DWORD *)&info);
}
__except (EXCEPTION_CONTINUE_EXECUTION)
{
}
#else
dwThreadID;
szThreadName;
#endif
}
Then I call it like this inside the threads proc.
SetThreadName(GetCurrentThreadId(), "VideoSource Thread");
It is worth noting that this is the exact code that David posted a link to (Thanks! I had forgotten where I got it). I didn't delete this post because I'd like the code to still be available if MSDN decides to reorganize its links (again).

Use SetThreadName

Windows 10 added SetThreadDescription(), on that platform this will be the best method.

Related

AccessException: Attempted To Read Or Write Protected/Corrupted Memory -- Known Exception, Unknown Reason?

Yes, I know there's a million threads on this exception, I've probably looked at 20-25 of them, but none of the causes seem to correlate to this, sadly (hence the title, known exception, unknown reason).
I've recently been gaining interest in InfoSec. As my first learners-project, I'd create a basic DLL Injector. Seems to be going well so far, however, this exception is grinding me up, and after some relatively extensive research I'm quite puzzled. Oddly enough, the exception also rises after the function completely finishes.
I couldn't really figure this out myself since external debuggers wouldn't work with my target application, and that was a whole new unrelated issue.
Solutions suggested & attempted so far:
Fix/Remove thread status checking (it was wrong)
Ensure the value behind DllPath ptr is being allocated, not the ptr
Marshaling the C# interop parameters
Anyway, here is my hunk of code:
#pragma once
#include "pch.h"
#include "injection.h" // only specifies UserInject as an exportable proto.
DWORD __stdcall UserInject(DWORD ProcessId, PCSTR DllPath, BOOL UseExtended) {
DWORD length;
CHAR* buffer;
LPVOID memry;
SIZE_T write;
HANDLE hProc;
HMODULE kr32;
HANDLE thread;
length = GetFullPathName(
DllPath,
NULL,
NULL,
NULL
);
AssertNonNull(length, INVALID_PATH);
kr32 = GetModuleHandle("kernel32.dll");
AssertNonNull(kr32, YOUREALLYMESSEDUP);
buffer = new CHAR[length];
GetFullPathName(
DllPath,
length,
buffer,
NULL
);
AssertNonNull(buffer, ERR_DEAD_BUFFER);
hProc = OpenProcess(
ADMIN,
FALSE,
ProcessId
);
AssertNonNull(hProc, INVALID_PROCID);
memry = VirtualAllocEx(
hProc,
nullptr,
sizeof buffer,
SHELLCODE_ALLOCATION,
PAGE_EXECUTE_READWRITE
);
AssertNonNull(memry, INVALID_BUFSIZE);
WriteProcessMemory(
hProc,
memry,
DllPath,
sizeof DllPath,
&write
);
AssertNonNull(write, ERR_SOLID_BUFFER);
auto decidePrototype = [](BOOL UseExtended, HMODULE kr32) -> decltype(auto) {
LPVOID procAddress;
if (!UseExtended) {
procAddress = (LPVOID)GetProcAddress(kr32, LOADLIB_ORD);
}
else {
procAddress = (LPVOID)GetProcAddress(kr32, LOADLIBX_ORD);
};
return (LPTHREAD_START_ROUTINE)procAddress;
};
auto loadLibraryAddress = decidePrototype(UseExtended, kr32);
thread = CreateRemoteThread(
hProc,
NULL,
NULL,
loadLibraryAddress,
memry,
NULL,
NULL
);
AssertNonNull(thread, INVALID_ROUTINE);
WaitForSingleObject(thread, INFINITE);
// The status stuff is quite weird; it was an attempt at debugging. The error occurs with or without this code.
// I left it because 50% of the comments below wouldn't make sense. Just be assured this code is positively *not* the problem (sadly).
// LPDWORD status = (LPDWORD)1;
// GetExitCodeThread(thread, status);
return TRUE // *status;
}
One obscure macro would be "ADMIN" which expands to "PROCESS_ALL_ACCESS", shortened to fit in better. Another is "AssertNonNull":
#define AssertNonNull(o, p) if (o == NULL) return p;
I've given a shot at debugging this code, but it doesn't halt at any specific point. I've thrown MessageBox tests past each operation (e.g allocation, writing) in addition to the integrity checks and didn't get any interesting responses.
I'm sorry I can't really add much extensive detail, but I'm really stone-walled here, not sure what to do, what information to get, or if there's anything to get. In short, I'm just not sure what to look for.
This is also being called from C#, 1% pseudocode.
[DllImport(path, CallingConvention = CallingConvention.StdCall)]
static extern int UserInject(uint ProcId, string DllPath, bool UseExtended);
uint validProcId; // integrity tested
string validDllPath; // integrity tested
UserInject(validProcId, validDllPath, true);
If you're interested in my testing application (for reproduction)
#include <iostream>
#include <Windows.h>
static const std::string toPrint = "Hello, World!\n";
int main()
{
while (true)
{
Sleep(1000);
std::cout << toPrint;
}
}
To my surprise, this wasn't as much an issue with the code as much as it was with the testing application.
The basic injection technique I used is prevented by various exploit protections & security mitigations that Visual Studio 2010+ applies to any applications built in release mode.
If I build my testing application in debug mode, there is no exception. If I use a non-VS built application, there is no exception.
I still need to fix how I create my threads, because no thread is created, but I've figured this out, that should be easy enough.

std::thread - naming your thread

The new C++ has this std::thread type. Works like a charm.
Now I would like to give each thread a name for more easy debugging (like java allows you to).
With pthreads I would do:
pthread_setname_np(pthread_self(), "thread_name");
but how can I do this with c++0x?
I know it uses pthreads underneath on Linux systems, but I would like to make my application portable. Is it possible at all?
A portable way to do this is to maintain a map of names, keyed by the thread's ID, obtained from thread::get_id(). Alternatively, as suggested in the comments, you could use a thread_local variable, if you only need to access the name from within the thread.
If you didn't need portability, then you could get the underlying pthread_t from thread::native_handle() and do whatever platform-specific shenanigans you like with that. Be aware that the _np on the thread naming functions means "not posix", so they aren't guaranteed to be available on all pthreads implementations.
An attempt at making a wrapper to deal with many Linuxes as well as Windows. Please edit as needed.
#ifdef _WIN32
#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(uint32_t dwThreadID, const char* threadName)
{
// DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( t.native_handle() ) );
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)
{
}
}
void SetThreadName( const char* threadName)
{
SetThreadName(GetCurrentThreadId(),threadName);
}
void SetThreadName( std::thread* thread, const char* threadName)
{
DWORD threadId = ::GetThreadId( static_cast<HANDLE>( thread->native_handle() ) );
SetThreadName(threadId,threadName);
}
#elif defined(__linux__)
#include <sys/prctl.h>
void SetThreadName( const char* threadName)
{
prctl(PR_SET_NAME,threadName,0,0,0);
}
#else
void SetThreadName(std::thread* thread, const char* threadName)
{
auto handle = thread->native_handle();
pthread_setname_np(handle,threadName);
}
#endif
You can use std::thread::native_handle to get the underlaying implementation defined thread. There is no standard function for that natively.
You can find an example here.
For windows [debugger], you can easily use the "normal" method;
http://msdn.microsoft.com/en-gb/library/xcb2z8hs.aspx
Just need the thread id which you can obtain via
#include <windows.h>
DWORD ThreadId = ::GetThreadId( static_cast<HANDLE>( mThread.native_handle() ) );
I've both seen this done in a system predating c++11 (where we basically invented our own Thread class that was very similar to std::thread) and in one I wrote fairly recently.
Basically, the pool really puts std::thread 2 layers down- you have a PoolThread class that contains a std::thread plus metadata like its name, ID, etc. and the the control structure that links it to its controlling pool, and the ThreadPool itself. You want to use thread pools in most threaded code for several reasons:
1) You can hide all the explicit "detach", "join", start thread on std::thread construction, etc. from users. That produces MUCH safer & cleaner code.
2) Better resource management: Too many threads will cripple performance even more than having too few. A well-built pool can do advanced things like automatic load balancing and cleaning-up hung or deadlocked threads.
3) Thread reuse: std::thread by itself is easiest to use by running every parallel task on its own thread. But thread creation & destruction are expensive, and can easily swamp the speed boost from parallel processing if you're not careful. So, it usually makes more sense to have pool threads that pull work tasks from a queue and only exit after receiving some signal.
4) Error handling: std::thread is just an execution context. If the task you're running on it throws an un-handled exception or std::thread ITSELF fails, the process will just crash right there. To do fault-tolerant multithreading, you need a Pool or something similar that can quickly catch such things and at least emit meaningful error messages before the process dies.
In header file do:
const std::string & ThreadName(const std::string name="");
In src file do:
const std::string & ThreadName(const std::string name)
{
static std::atomic_int threadCount{0};
const thread_local std::string _name = name + std::to_string(threadCount.fetch_add(1));
return _name;
}
Usage:
void myThread()
{
ThreadName("myThread"); // Call once at very beginning of your thread creation
...
std::cout << ThreadName() << std::endl; // Anyplace in your code
}

C++: _beginthreadex, thread function name not showing in Visual Studio Threads window

I recently learnt that ::_beginthreadex() is always preferable to ::CreateThread(), so I changed all my calls that used ::CreateThread().
The only downside is that I no longer see the thread function's name in Visual Studio's Threads window making it hard to quickly identify threads. I assume this was somehow done automatically by the debugger when I used ::CreateThread(), since the parameters are exactly the same, I just changed the name of the function used.
Is there any way to keep using ::_beginthreadex() and to see the thread's name in the Threads window of Visual Studio?
This happens because _beginthreadex() calls CreateThread() with its own thread function that calls the one you specify (so the debugger uses the _threadstartex function name - the one that _beginthreadex() invokes).
You can manually set the thread name yourself using the SetThreadName() example from MSDN. What you might want to do is create your own wrapper for _beginthreadex() that maybe looks something like:
uintptr_t startthreadex(
void* security,
unsigned stacksize,
unsigned (__stdcall * threadproc) (void *),
void* args,
unsigned flags,
unsigned * pThread_id,
char* thread_name)
{
unsigned alt_thread_id;
if (!pThread_id) {
pThread_id = & alt_thread_id;
}
uintptr_t result = _beginthreadex(security, stacksize, threadproc, args, flgas, pThread_id);
if (result == 0) return result;
SetThreadName( *pThread_id, thread_name);
}
Now you can call startthreadex() instead of _beginthreadex() and pass it a thread name. A small advantage to this is that if you use the same function to run several threads, you can easily give them each unique names that reflect the parameters passed ot the thread or whatever.
If you want the thread name to automatically take be the thread proc function name as the debugger's thread name, you could make a wrapper macro that stringizes the function name parameter (all it takes is another level of indirection or to to solve any problem...).
Here's SetThreadName() (it's from http://msdn.microsoft.com/en-us/library/xcb2z8hs.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)
{
}
}
There is no particular advantage with using _beginthreadex over CreateThread. The CRT functions would eventually call CreateThread only.
You should read:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
http://www.codeguru.com/forum/showthread.php?t=371305
http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/c727ae29-5a7a-42b6-ad0b-f6b21c1180b2

OpenProcess handle invalid for ReadProcessMemory

I've made this simple class to open a process and read memory from it:
The problem is when I call ReadDWORD with any memory address ReadProcessMemory fails with error code 6: ERROR_INVALID_HANDLE, The handle is invalid. And I can't figure out what I'm doing wrong.
If I put the OpenProcess part in the ReadDWORD function it works fine. Is there something wrong with how I store the handle? Why does it become invalid before I use it?
Memory.h
#ifndef MEMORY_H
#define MEMORY_H
#include <windows.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
#include <iostream>
class Memory
{
public:
Memory();
Memory(DWORD offset);
~Memory();
DWORD ReadDWORD(DWORD addr);
private:
HANDLE m_hProc;
DWORD m_Offset;
};
#endif
Memory.cpp
#include "Memory.h"
Memory::Memory()
{
Memory(0);
}
Memory::Memory(DWORD offset)
{
m_hProc = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, 5444); // 5444 is the PID of a process I'm testing this with
m_Offset = offset;
}
Memory::~Memory()
{
CloseHandle(m_hProc);
}
DWORD Memory::ReadDWORD(DWORD addr)
{
// Optional memory offset
addr += m_Offset;
DWORD value = -1;
int result = ReadProcessMemory(m_hProc, (LPVOID)addr, &value, sizeof(DWORD), NULL);
if (result == 0)
std::cout << "ReadProcessMemory error: " << GetLastError() << std::endl;
return value;
}
Memory::Memory()
{
Memory(0);
}
This isn't doing what you think its doing: it's not actually calling the other constructor, instead it's creating a temporary that gets discarded. So you are opening the process, but in a separate temporary object, while this object remains uninitialized.
Safer approach is to have a separate Initialize(offset) method that you call from both ctors.
(The advice in the other answers is also good; check your return values, and where you get a E_INVALID_HANDLE, check that the handle is something that looks like a handle. Or set a breakpoint at the OpenHandle and ReadProcessMemory and check that the same value is being used in both places. C++ is often full of surprises, and there's often no substitute for just stepping through the code to make sure it's doing what you think it's doing.)
To access other processes, you often need to enable certain privileges. SeDebugPrivilege comes to mind. See here. Otherwise see the suggestion from Hans Passant (i.e. GetLastError).
You can use RtlAdjustPrivilege function to get SeDebugPrivilege.
NTSTATUS NTAPI RtlAdjustPrivilege(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN); /*This is the
protoype of RtlAdjustPrivilege function.*/

Can I get a "__try"-clause to compile with /EHsc?

The Microsoft-approved way of setting a thread name doesn't compile with /EHsc enabled. The compiler tells me
C2712: Cannot use __try in functions that require object unwinding
http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
//
// Usage: SetThreadName (-1, "MainThread");
//
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;
void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = szThreadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
}
__except(EXCEPTION_CONTINUE_EXECUTION)
{
}
}
Any idea on how to fix this without changing the compiler settings?
Using Visual Studio 2008 on WinXP
The usual solution is to separate it into two functions, one calling the other. One sets up the SEH __try/__except block and the other has all the stuff related to C++ exceptions and destructor calls for local variables.
But I don't see any types that need a destructor call.
Maybe it's just a typo (except) vs (__except)?