1 //===-- IntelPTThreadTraceCollection.cpp ----------------------------------===//
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 "IntelPTThreadTraceCollection.h"
10 
11 using namespace lldb;
12 using namespace lldb_private;
13 using namespace process_linux;
14 using namespace llvm;
15 
16 bool IntelPTThreadTraceCollection::TracesThread(lldb::tid_t tid) const {
17   return m_thread_traces.count(tid);
18 }
19 
20 Error IntelPTThreadTraceCollection::TraceStop(lldb::tid_t tid) {
21   auto it = m_thread_traces.find(tid);
22   if (it == m_thread_traces.end())
23     return createStringError(inconvertibleErrorCode(),
24                              "Thread %" PRIu64 " not currently traced", tid);
25   m_total_buffer_size -= it->second->GetTraceBufferSize();
26   m_thread_traces.erase(tid);
27   return Error::success();
28 }
29 
30 Error IntelPTThreadTraceCollection::TraceStart(
31     lldb::tid_t tid, const TraceIntelPTStartRequest &request) {
32   if (TracesThread(tid))
33     return createStringError(inconvertibleErrorCode(),
34                              "Thread %" PRIu64 " already traced", tid);
35 
36   Expected<IntelPTSingleBufferTraceUP> trace_up =
37       IntelPTSingleBufferTrace::Start(request, tid, /*core_id=*/None,
38                                       TraceCollectionState::Running);
39   if (!trace_up)
40     return trace_up.takeError();
41 
42   m_total_buffer_size += (*trace_up)->GetTraceBufferSize();
43   m_thread_traces.try_emplace(tid, std::move(*trace_up));
44   return Error::success();
45 }
46 
47 size_t IntelPTThreadTraceCollection::GetTotalBufferSize() const {
48   return m_total_buffer_size;
49 }
50 
51 void IntelPTThreadTraceCollection::ForEachThread(
52     std::function<void(lldb::tid_t tid, IntelPTSingleBufferTrace &thread_trace)>
53         callback) {
54   for (auto &it : m_thread_traces)
55     callback(it.first, *it.second);
56 }
57 
58 Expected<IntelPTSingleBufferTrace &>
59 IntelPTThreadTraceCollection::GetTracedThread(lldb::tid_t tid) {
60   auto it = m_thread_traces.find(tid);
61   if (it == m_thread_traces.end())
62     return createStringError(inconvertibleErrorCode(),
63                              "Thread %" PRIu64 " not currently traced", tid);
64   return *it->second.get();
65 }
66 
67 void IntelPTThreadTraceCollection::Clear() {
68   m_thread_traces.clear();
69   m_total_buffer_size = 0;
70 }
71 
72 size_t IntelPTThreadTraceCollection::GetTracedThreadsCount() const {
73   return m_thread_traces.size();
74 }
75