1 //===-- CommandObjectThreadUtil.cpp -----------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectThreadUtil.h"
10 
11 #include "lldb/Interpreter/CommandReturnObject.h"
12 #include "lldb/Target/Process.h"
13 #include "lldb/Target/Thread.h"
14 
15 using namespace lldb;
16 using namespace lldb_private;
17 using namespace llvm;
18 
19 CommandObjectIterateOverThreads::CommandObjectIterateOverThreads(
20     CommandInterpreter &interpreter, const char *name, const char *help,
21     const char *syntax, uint32_t flags)
22     : CommandObjectParsed(interpreter, name, help, syntax, flags) {}
23 
24 bool CommandObjectIterateOverThreads::DoExecute(Args &command,
25                                                 CommandReturnObject &result) {
26   result.SetStatus(m_success_return);
27 
28   bool all_threads = false;
29   if (command.GetArgumentCount() == 0) {
30     Thread *thread = m_exe_ctx.GetThreadPtr();
31     if (!thread || !HandleOneThread(thread->GetID(), result))
32       return false;
33     return result.Succeeded();
34   } else if (command.GetArgumentCount() == 1) {
35     all_threads = ::strcmp(command.GetArgumentAtIndex(0), "all") == 0;
36     m_unique_stacks = ::strcmp(command.GetArgumentAtIndex(0), "unique") == 0;
37   }
38 
39   // Use tids instead of ThreadSPs to prevent deadlocking problems which
40   // result from JIT-ing code while iterating over the (locked) ThreadSP
41   // list.
42   std::vector<lldb::tid_t> tids;
43 
44   if (all_threads || m_unique_stacks) {
45     Process *process = m_exe_ctx.GetProcessPtr();
46 
47     for (ThreadSP thread_sp : process->Threads())
48       tids.push_back(thread_sp->GetID());
49   } else {
50     const size_t num_args = command.GetArgumentCount();
51     Process *process = m_exe_ctx.GetProcessPtr();
52 
53     std::lock_guard<std::recursive_mutex> guard(
54         process->GetThreadList().GetMutex());
55 
56     for (size_t i = 0; i < num_args; i++) {
57       uint32_t thread_idx;
58       if (!llvm::to_integer(command.GetArgumentAtIndex(i), thread_idx)) {
59         result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n",
60                                      command.GetArgumentAtIndex(i));
61         result.SetStatus(eReturnStatusFailed);
62         return false;
63       }
64 
65       ThreadSP thread =
66           process->GetThreadList().FindThreadByIndexID(thread_idx);
67 
68       if (!thread) {
69         result.AppendErrorWithFormat("no thread with index: \"%s\"\n",
70                                      command.GetArgumentAtIndex(i));
71         result.SetStatus(eReturnStatusFailed);
72         return false;
73       }
74 
75       tids.push_back(thread->GetID());
76     }
77   }
78 
79   if (m_unique_stacks) {
80     // Iterate over threads, finding unique stack buckets.
81     std::set<UniqueStack> unique_stacks;
82     for (const lldb::tid_t &tid : tids) {
83       if (!BucketThread(tid, unique_stacks, result)) {
84         return false;
85       }
86     }
87 
88     // Write the thread id's and unique call stacks to the output stream
89     Stream &strm = result.GetOutputStream();
90     Process *process = m_exe_ctx.GetProcessPtr();
91     for (const UniqueStack &stack : unique_stacks) {
92       // List the common thread ID's
93       const std::vector<uint32_t> &thread_index_ids =
94           stack.GetUniqueThreadIndexIDs();
95       strm.Format("{0} thread(s) ", thread_index_ids.size());
96       for (const uint32_t &thread_index_id : thread_index_ids) {
97         strm.Format("#{0} ", thread_index_id);
98       }
99       strm.EOL();
100 
101       // List the shared call stack for this set of threads
102       uint32_t representative_thread_id = stack.GetRepresentativeThread();
103       ThreadSP thread = process->GetThreadList().FindThreadByIndexID(
104           representative_thread_id);
105       if (!HandleOneThread(thread->GetID(), result)) {
106         return false;
107       }
108     }
109   } else {
110     uint32_t idx = 0;
111     for (const lldb::tid_t &tid : tids) {
112       if (idx != 0 && m_add_return)
113         result.AppendMessage("");
114 
115       if (!HandleOneThread(tid, result))
116         return false;
117 
118       ++idx;
119     }
120   }
121   return result.Succeeded();
122 }
123 
124 bool CommandObjectIterateOverThreads::BucketThread(
125     lldb::tid_t tid, std::set<UniqueStack> &unique_stacks,
126     CommandReturnObject &result) {
127   // Grab the corresponding thread for the given thread id.
128   Process *process = m_exe_ctx.GetProcessPtr();
129   Thread *thread = process->GetThreadList().FindThreadByID(tid).get();
130   if (thread == nullptr) {
131     result.AppendErrorWithFormatv("Failed to process thread #{0}.\n", tid);
132     result.SetStatus(eReturnStatusFailed);
133     return false;
134   }
135 
136   // Collect the each frame's address for this call-stack
137   std::stack<lldb::addr_t> stack_frames;
138   const uint32_t frame_count = thread->GetStackFrameCount();
139   for (uint32_t frame_index = 0; frame_index < frame_count; frame_index++) {
140     const lldb::StackFrameSP frame_sp =
141         thread->GetStackFrameAtIndex(frame_index);
142     const lldb::addr_t pc = frame_sp->GetStackID().GetPC();
143     stack_frames.push(pc);
144   }
145 
146   uint32_t thread_index_id = thread->GetIndexID();
147   UniqueStack new_unique_stack(stack_frames, thread_index_id);
148 
149   // Try to match the threads stack to and existing entry.
150   std::set<UniqueStack>::iterator matching_stack =
151       unique_stacks.find(new_unique_stack);
152   if (matching_stack != unique_stacks.end()) {
153     matching_stack->AddThread(thread_index_id);
154   } else {
155     unique_stacks.insert(new_unique_stack);
156   }
157   return true;
158 }
159