windows下获取所有线程堆栈

完成目标主要分成两个步骤:1)获取当前进程的所有线程;2)获取每个线程的上下文,根据堆栈回溯。
完成步骤1,需要用到以下几个接口:

  1. CreateToolhelp32Snapshot(), 获取当前进程的线程列表快照;
  2. Thread32First(),获取首个线程;
  3. Thread32Next(),获取下一个线程,直到遍历完成;

完成步骤2,需要用到几个接口:

  1. OpenThread(),获取线程句柄;
  2. SuspendThread(),挂起线程,保证获取上下文安全;
  3. ResumeThread(),恢复线程;
  4. GetThreadContext(),获取线程上下文,主要是寄存器RIP、RBP、RSP的值;
  5. SymInitialize(),初始化本进程的符号表;
  6. StackWalk(),回溯线程调用栈;
  7. SymGetSymFromAddr(), 根据地址获取符号;
  8. SymGetLineFromAddr(),根据地址获取源文件和行号;
  9. SymCleanup(),清除符号表资源;

以下是一个获取本进程所有线程调用栈的示例。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include
struct TestThreadContext {
    static void workert() {
        for (int j = 0; j < 100000; ++j) {
            if (j % 100 == 0)
                cout << "thread " << GetCurrentThreadId() << " run" << endl;
            Sleep(100);
        }
    }
    // 获取其它线程堆栈
    // stacks {线程id, 调用栈,错误说明}
    static void get_threads_stack(std::list < std::tuple> & stacks) {
        auto pid = GetCurrentProcessId();
        auto tid = GetCurrentThreadId();
        HANDLE proc = GetCurrentProcess();
        SymInitialize(proc, NULL, TRUE);
        HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, pid);
        if (snap == INVALID_HANDLE_VALUE) {
            return;
        }
        THREADENTRY32 e = { sizeof(e) };
        BOOL ok = Thread32First(snap, &e);
        for (; ok; ok = Thread32Next(snap, &e)) {
            if (e.th32OwnerProcessID != pid || e.th32ThreadID == tid)
                continue;
            DWORD thread_id = e.th32ThreadID;
            //cout << "open thread " << e.th32ThreadID << endl;
            HANDLE th = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, FALSE, thread_id);
            if (th == INVALID_HANDLE_VALUE) {
                //cout << "open thread " << tid << " failed" << endl;
                stacks.emplace_back(thread_id, "", "error: open failed");
                continue;
            }
            DWORD ret = SuspendThread(th);
            if (ret == (DWORD)-1) {
                CloseHandle(th);
                stacks.emplace_back(thread_id, "", "error: SuspendThread failed");
                continue;
            }
            CONTEXT ctx;
            ZeroMemory(&ctx, sizeof(ctx));
            ctx.ContextFlags = CONTEXT_ALL;
            ret = GetThreadContext(th, &ctx);
            if (!ret) {
                ResumeThread(th);
                CloseHandle(th);
                stacks.emplace_back(thread_id, "", "error: GetThreadContext failed");
                continue;
            }
            //
            STACKFRAME sf = { 0 };
            sf.AddrPC.Offset = ctx.Rip;
            sf.AddrPC.Mode = AddrModeFlat;
            sf.AddrFrame.Offset = ctx.Rbp;
            sf.AddrFrame.Mode = AddrModeFlat;
            sf.AddrStack.Offset = ctx.Rsp;
            sf.AddrStack.Mode = AddrModeFlat;
            //
            typedef struct tag_SYMBOL_INFO
            {
                IMAGEHLP_SYMBOL symInfo;
                TCHAR szBuffer[MAX_PATH];
            } SYMBOL_INFO, * LPSYMBOL_INFO;
            // 32位系统下变量类型是DWORD ,64位系统下则是DWORD64
            decltype(sf.AddrPC.Offset) dwDisplament = 0;
            DWORD dwDis32 = 0;
            SYMBOL_INFO stack_info = { 0 };
            PIMAGEHLP_SYMBOL pSym = (PIMAGEHLP_SYMBOL)&stack_info;
            pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
            pSym->MaxNameLength = sizeof(SYMBOL_INFO) - offsetof(SYMBOL_INFO, symInfo.Name);
            IMAGEHLP_LINE ImageLine = { 0 };
            ImageLine.SizeOfStruct = sizeof(IMAGEHLP_LINE);
            std::string stack = "";
            while (StackWalk(IMAGE_FILE_MACHINE_AMD64, proc, th, &sf, &ctx, 
                NULL, SymFunctionTableAccess, SymGetModuleBase, NULL))
            {
                char buf[512];
                if (SymGetSymFromAddr(proc, sf.AddrPC.Offset, &dwDisplament, pSym)) {
                    if (SymGetLineFromAddr(proc, sf.AddrPC.Offset, &dwDis32, &ImageLine)) {
                        char* fullpath = ImageLine.FileName;
                        // find file name in full path
                        char* f = fullpath + strlen(fullpath);
                        while (*f != '\\' && f > fullpath) --f;
                        if (f > fullpath)
                            ++f;
                      snprintf(buf, sizeof(buf), "%#llx+%s [%s: %d]\n", 
                            pSym->Address, pSym->Name, f, ImageLine.LineNumber);
                    }
                    else {
                        snprintf(buf, sizeof(buf), "%#llx+%s\n", pSym->Address, pSym->Name);
                    }
                }
                else {
                    snprintf(buf, sizeof(buf), "%#llx\n", sf.AddrPC.Offset);
                }
                stack.append(buf);
            }
            stacks.emplace_back(thread_id, stack, "");
            ResumeThread(th);
            CloseHandle(th);
        }
        CloseHandle(snap);
        SymCleanup(proc);
    }

    // 测试获取其它线程堆栈并打印
    static void master() {
        const int num = 4;
        std::thread ws[num];
        for (int j = 0; j < num; ++j)
            ws[j] = std::thread(workert);
        Sleep(5000);
        std::list < std::tuple> stacks;
        get_threads_stack(stacks);
        for (auto& t : stacks) {
            unsigned tid;
            std::string stack, error;
            std::tie(tid, stack, error) = t;
            if (error.empty()) {
                cout << "thread " << tid << "\n" << stack << std::endl;
            }
            else {
                cout << "thread " << tid << " " << error << std::endl;
            }
        }
        for (int j = 0; j < num; ++j)
            ws[j].join();
    }
};

int main(int argc, char*argv[])
{
    TestThreadContext::master();
    return 0;
}

以上代码在win10上用vs2019编译,c++17标准。测试输出如下所示。

thread thread 1705621204 run runthread
21480 run

thread 3868 run
thread 21328
0x7ffa6c6130c0+NtWaitForWorkViaWorkerFactory
0x7ffa6c5bff40+RtlReleaseSRWLockExclusive
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

thread 20196
0x7ffa6c6130c0+NtWaitForWorkViaWorkerFactory
0x7ffa6c5bff40+RtlReleaseSRWLockExclusive
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

thread 17056
0x7ffa6c60fdd0+ZwDelayExecution
0x7ffa68ed9c00+SleepEx
0x7ff771b12180+TestThreadContext::workert [cross-process.cpp: 340]
0x7ff771b16aa0+std::thread::_Invoke,0> [thread: 44]
0x7ff771b22f1c+thread_start [thread.cpp: 97]
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

thread 21204
0x7ffa6c60fdd0+ZwDelayExecution
0x7ffa68ed9c00+SleepEx
0x7ff771b12180+TestThreadContext::workert [cross-process.cpp: 340]
0x7ff771b16aa0+std::thread::_Invoke,0> [thread: 44]
0x7ff771b22f1c+thread_start [thread.cpp: 97]
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

thread 3868
0x7ffa6c60fdd0+ZwDelayExecution
0x7ffa68ed9c00+SleepEx
0x7ff771b12180+TestThreadContext::workert [cross-process.cpp: 340]
0x7ff771b16aa0+std::thread::_Invoke,0> [thread: 44]
0x7ff771b22f1c+thread_start [thread.cpp: 97]
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

thread 21480
0x7ffa6c60fdd0+ZwDelayExecution
0x7ffa68ed9c00+SleepEx
0x7ff771b12180+TestThreadContext::workert [cross-process.cpp: 340]
0x7ff771b16aa0+std::thread::_Invoke,0> [thread: 44]
0x7ff771b22f1c+thread_start [thread.cpp: 97]
0x7ffa6a0f7960+BaseThreadInitThunk
0x7ffa6c5da250+RtlUserThreadStart

你可能感兴趣的:(windows下获取所有线程堆栈)