Michael Labbé
Michael Labbé

Reputation: 12286

What's the best way to discover why threads are being created in my C++ app and what they do?

I am doing an audit of a C++ app running on Windows, compiled against multithreaded debug DLL. It has a lot of third party dependencies which can spawn threads. I need to track why each thread is there and how much stack space it is allocating.

What is a good way to trace back to the start of a thread's creation so I can see where it is spawned?

Update: I should point out I have the source code to the entire app outside of Microsoft dependencies. However, a lot of the threads have callstacks that exist exclusively inside of libraries that ship with the OS such as ntdll.dll and kernel32.dll.

Upvotes: 2

Views: 405

Answers (5)

peterchen
peterchen

Reputation: 41106

I haven't encountered yet a way to track back to the CreateThread call, I don't think that information is available for a thread.

What helped me a few times is to name the threads I control, see MSDN. Won't help you for threads spawned and running in 3rd party libs, though.

Upvotes: 0

Michael
Michael

Reputation: 55415

You can use the Windows Performance Toolkit to view ThreadCreate events. On Vista on up, you can get the stacks for each thread create, so you can see which code is creating the thread.

Collect the trace with:

xperf -on base -stackwalk ThreadCreate 

Run your scenario, the write out the trace with:

xperf -stop -d mylog.etl

View the trace file with:

xperf mylog.etl

In the Trace menu option, set your symbol path appropriately and load symbols. You can use the Microsoft Symbol Server to get public symbols for the operating system.

Under "Process Lifetimes", right click and select "Thread Summary Table". You can add columns for creation stack and user stack size. Expand your process, you can see all threads that were created, the stack that created that thread, and the stack size.

Upvotes: 5

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Process Explorer can list threads as well as their call stack. Very useful if you want to inspect a process without attaching a real debugger.

Upvotes: 4

grigy
grigy

Reputation: 6826

Do you have access to source code? If that's the case make a function that shows the thread id and allocated memory and call it for all threads.

Upvotes: 0

Tim
Tim

Reputation: 20360

why not grep the source code and look for it? (that will tell you why)

Upvotes: 0

Related Questions