1 //===-- TraceIntelPT.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 "TraceIntelPT.h"
10 
11 #include "../common/ThreadPostMortemTrace.h"
12 #include "CommandObjectTraceStartIntelPT.h"
13 #include "DecodedThread.h"
14 #include "TraceIntelPTConstants.h"
15 #include "TraceIntelPTSessionFileParser.h"
16 #include "TraceIntelPTSessionSaver.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/Target.h"
20 #include "llvm/ADT/None.h"
21 
22 using namespace lldb;
23 using namespace lldb_private;
24 using namespace lldb_private::trace_intel_pt;
25 using namespace llvm;
26 
27 LLDB_PLUGIN_DEFINE(TraceIntelPT)
28 
29 lldb::CommandObjectSP
30 TraceIntelPT::GetProcessTraceStartCommand(CommandInterpreter &interpreter) {
31   return CommandObjectSP(
32       new CommandObjectProcessTraceStartIntelPT(*this, interpreter));
33 }
34 
35 lldb::CommandObjectSP
36 TraceIntelPT::GetThreadTraceStartCommand(CommandInterpreter &interpreter) {
37   return CommandObjectSP(
38       new CommandObjectThreadTraceStartIntelPT(*this, interpreter));
39 }
40 
41 void TraceIntelPT::Initialize() {
42   PluginManager::RegisterPlugin(GetPluginNameStatic(), "Intel Processor Trace",
43                                 CreateInstanceForSessionFile,
44                                 CreateInstanceForLiveProcess,
45                                 TraceIntelPTSessionFileParser::GetSchema());
46 }
47 
48 void TraceIntelPT::Terminate() {
49   PluginManager::UnregisterPlugin(CreateInstanceForSessionFile);
50 }
51 
52 StringRef TraceIntelPT::GetSchema() {
53   return TraceIntelPTSessionFileParser::GetSchema();
54 }
55 
56 void TraceIntelPT::Dump(Stream *s) const {}
57 
58 llvm::Error TraceIntelPT::SaveLiveTraceToDisk(FileSpec directory) {
59   RefreshLiveProcessState();
60   return TraceIntelPTSessionSaver().SaveToDisk(*this, directory);
61 }
62 
63 Expected<TraceSP> TraceIntelPT::CreateInstanceForSessionFile(
64     const json::Value &trace_session_file, StringRef session_file_dir,
65     Debugger &debugger) {
66   return TraceIntelPTSessionFileParser(debugger, trace_session_file,
67                                        session_file_dir)
68       .Parse();
69 }
70 
71 Expected<TraceSP> TraceIntelPT::CreateInstanceForLiveProcess(Process &process) {
72   TraceSP instance(new TraceIntelPT(process));
73   process.GetTarget().SetTrace(instance);
74   return instance;
75 }
76 
77 TraceIntelPT::TraceIntelPT(
78     const pt_cpu &cpu_info,
79     const std::vector<ThreadPostMortemTraceSP> &traced_threads)
80     : m_cpu_info(cpu_info) {
81   for (const ThreadPostMortemTraceSP &thread : traced_threads) {
82     m_thread_decoders.emplace(thread->GetID(),
83                               std::make_unique<ThreadDecoder>(thread, *this));
84     SetPostMortemThreadDataFile(thread->GetID(), "threadTraceBuffer",
85                                 thread->GetTraceFile());
86   }
87 }
88 
89 DecodedThreadSP TraceIntelPT::Decode(Thread &thread) {
90   RefreshLiveProcessState();
91   if (m_live_refresh_error.hasValue())
92     return std::make_shared<DecodedThread>(
93         thread.shared_from_this(),
94         createStringError(inconvertibleErrorCode(), *m_live_refresh_error));
95 
96   auto it = m_thread_decoders.find(thread.GetID());
97   if (it == m_thread_decoders.end())
98     return std::make_shared<DecodedThread>(
99         thread.shared_from_this(),
100         createStringError(inconvertibleErrorCode(), "thread not traced"));
101   return it->second->Decode();
102 }
103 
104 lldb::TraceCursorUP TraceIntelPT::GetCursor(Thread &thread) {
105   return Decode(thread)->GetCursor();
106 }
107 
108 void TraceIntelPT::DumpTraceInfo(Thread &thread, Stream &s, bool verbose) {
109   Optional<size_t> raw_size = GetRawTraceSize(thread);
110   s.Format("\nthread #{0}: tid = {1}", thread.GetIndexID(), thread.GetID());
111   if (!raw_size) {
112     s << ", not traced\n";
113     return;
114   }
115   s << "\n";
116   DecodedThreadSP decoded_trace_sp = Decode(thread);
117   size_t insn_len = decoded_trace_sp->GetInstructionsCount();
118   size_t mem_used = decoded_trace_sp->CalculateApproximateMemoryUsage();
119 
120   s.Format("  Raw trace size: {0} KiB\n", *raw_size / 1024);
121   s.Format("  Total number of instructions: {0}\n", insn_len);
122   s.Format("  Total approximate memory usage: {0:2} KiB\n",
123            (double)mem_used / 1024);
124   if (insn_len != 0)
125     s.Format("  Average memory usage per instruction: {0:2} bytes\n",
126              (double)mem_used / insn_len);
127 
128   const DecodedThread::LibiptErrors &tsc_errors =
129       decoded_trace_sp->GetTscErrors();
130   s.Format("\n  Number of TSC decoding errors: {0}\n", tsc_errors.total_count);
131   for (const auto &error_message_to_count : tsc_errors.libipt_errors) {
132     s.Format("    {0}: {1}\n", error_message_to_count.first,
133              error_message_to_count.second);
134   }
135 }
136 
137 Optional<size_t> TraceIntelPT::GetRawTraceSize(Thread &thread) {
138   if (IsTraced(thread.GetID()))
139     return Decode(thread)->GetRawTraceSize();
140   else
141     return None;
142 }
143 
144 Expected<pt_cpu> TraceIntelPT::GetCPUInfoForLiveProcess() {
145   Expected<std::vector<uint8_t>> cpu_info = GetLiveProcessBinaryData("cpuInfo");
146   if (!cpu_info)
147     return cpu_info.takeError();
148 
149   int64_t cpu_family = -1;
150   int64_t model = -1;
151   int64_t stepping = -1;
152   std::string vendor_id;
153 
154   StringRef rest(reinterpret_cast<const char *>(cpu_info->data()),
155                  cpu_info->size());
156   while (!rest.empty()) {
157     StringRef line;
158     std::tie(line, rest) = rest.split('\n');
159 
160     SmallVector<StringRef, 2> columns;
161     line.split(columns, StringRef(":"), -1, false);
162 
163     if (columns.size() < 2)
164       continue; // continue searching
165 
166     columns[1] = columns[1].trim(" ");
167     if (columns[0].contains("cpu family") &&
168         columns[1].getAsInteger(10, cpu_family))
169       continue;
170 
171     else if (columns[0].contains("model") && columns[1].getAsInteger(10, model))
172       continue;
173 
174     else if (columns[0].contains("stepping") &&
175              columns[1].getAsInteger(10, stepping))
176       continue;
177 
178     else if (columns[0].contains("vendor_id")) {
179       vendor_id = columns[1].str();
180       if (!vendor_id.empty())
181         continue;
182     }
183 
184     if ((cpu_family != -1) && (model != -1) && (stepping != -1) &&
185         (!vendor_id.empty())) {
186       return pt_cpu{vendor_id == "GenuineIntel" ? pcv_intel : pcv_unknown,
187                     static_cast<uint16_t>(cpu_family),
188                     static_cast<uint8_t>(model),
189                     static_cast<uint8_t>(stepping)};
190     }
191   }
192   return createStringError(inconvertibleErrorCode(),
193                            "Failed parsing the target's /proc/cpuinfo file");
194 }
195 
196 Expected<pt_cpu> TraceIntelPT::GetCPUInfo() {
197   if (!m_cpu_info) {
198     if (llvm::Expected<pt_cpu> cpu_info = GetCPUInfoForLiveProcess())
199       m_cpu_info = *cpu_info;
200     else
201       return cpu_info.takeError();
202   }
203   return *m_cpu_info;
204 }
205 
206 Process *TraceIntelPT::GetLiveProcess() { return m_live_process; }
207 
208 void TraceIntelPT::DoRefreshLiveProcessState(
209     Expected<TraceGetStateResponse> state) {
210   m_thread_decoders.clear();
211 
212   if (!state) {
213     m_live_refresh_error = toString(state.takeError());
214     return;
215   }
216 
217   for (const TraceThreadState &thread_state : state->tracedThreads) {
218     ThreadSP thread_sp =
219         m_live_process->GetThreadList().FindThreadByID(thread_state.tid);
220     m_thread_decoders.emplace(
221         thread_state.tid, std::make_unique<ThreadDecoder>(thread_sp, *this));
222   }
223 }
224 
225 bool TraceIntelPT::IsTraced(lldb::tid_t tid) {
226   RefreshLiveProcessState();
227   return m_thread_decoders.count(tid);
228 }
229 
230 // The information here should match the description of the intel-pt section
231 // of the jLLDBTraceStart packet in the lldb/docs/lldb-gdb-remote.txt
232 // documentation file. Similarly, it should match the CLI help messages of the
233 // TraceIntelPTOptions.td file.
234 const char *TraceIntelPT::GetStartConfigurationHelp() {
235   return R"(Parameters:
236 
237   Note: If a parameter is not specified, a default value will be used.
238 
239   - int threadBufferSize (defaults to 4096 bytes):
240     [process and thread tracing]
241     Trace size in bytes per thread. It must be a power of 2 greater
242     than or equal to 4096 (2^12). The trace is circular keeping the
243     the most recent data.
244 
245   - boolean enableTsc (default to false):
246     [process and thread tracing]
247     Whether to use enable TSC timestamps or not. This is supported on
248     all devices that support intel-pt.
249 
250   - psbPeriod (defaults to null):
251     [process and thread tracing]
252     This value defines the period in which PSB packets will be generated.
253     A PSB packet is a synchronization packet that contains a TSC
254     timestamp and the current absolute instruction pointer.
255 
256     This parameter can only be used if
257 
258         /sys/bus/event_source/devices/intel_pt/caps/psb_cyc
259 
260     is 1. Otherwise, the PSB period will be defined by the processor.
261 
262     If supported, valid values for this period can be found in
263 
264         /sys/bus/event_source/devices/intel_pt/caps/psb_periods
265 
266     which contains a hexadecimal number, whose bits represent
267     valid values e.g. if bit 2 is set, then value 2 is valid.
268 
269     The psb_period value is converted to the approximate number of
270     raw trace bytes between PSB packets as:
271 
272         2 ^ (value + 11)
273 
274     e.g. value 3 means 16KiB between PSB packets. Defaults to 0 if
275     supported.
276 
277   - int processBufferSizeLimit (defaults to 500 MB):
278     [process tracing only]
279     Maximum total trace size per process in bytes. This limit applies
280     to the sum of the sizes of all thread traces of this process,
281     excluding the ones created explicitly with "thread tracing".
282     Whenever a thread is attempted to be traced due to this command
283     and the limit would be reached, the process is stopped with a
284     "processor trace" reason, so that the user can retrace the process
285     if needed.)";
286 }
287 
288 Error TraceIntelPT::Start(size_t thread_buffer_size,
289                           size_t total_buffer_size_limit, bool enable_tsc,
290                           Optional<size_t> psb_period) {
291   TraceIntelPTStartRequest request;
292   request.threadBufferSize = thread_buffer_size;
293   request.processBufferSizeLimit = total_buffer_size_limit;
294   request.enableTsc = enable_tsc;
295   request.psbPeriod = psb_period.map([](size_t val) { return (int64_t)val; });
296   request.type = GetPluginName().str();
297   return Trace::Start(toJSON(request));
298 }
299 
300 Error TraceIntelPT::Start(StructuredData::ObjectSP configuration) {
301   size_t thread_buffer_size = kDefaultThreadBufferSize;
302   size_t process_buffer_size_limit = kDefaultProcessBufferSizeLimit;
303   bool enable_tsc = kDefaultEnableTscValue;
304   Optional<size_t> psb_period = kDefaultPsbPeriod;
305 
306   if (configuration) {
307     if (StructuredData::Dictionary *dict = configuration->GetAsDictionary()) {
308       dict->GetValueForKeyAsInteger("threadBufferSize", thread_buffer_size);
309       dict->GetValueForKeyAsInteger("processBufferSizeLimit",
310                                     process_buffer_size_limit);
311       dict->GetValueForKeyAsBoolean("enableTsc", enable_tsc);
312       dict->GetValueForKeyAsInteger("psbPeriod", psb_period);
313     } else {
314       return createStringError(inconvertibleErrorCode(),
315                                "configuration object is not a dictionary");
316     }
317   }
318 
319   return Start(thread_buffer_size, process_buffer_size_limit, enable_tsc,
320                psb_period);
321 }
322 
323 llvm::Error TraceIntelPT::Start(llvm::ArrayRef<lldb::tid_t> tids,
324                                 size_t thread_buffer_size, bool enable_tsc,
325                                 Optional<size_t> psb_period) {
326   TraceIntelPTStartRequest request;
327   request.threadBufferSize = thread_buffer_size;
328   request.enableTsc = enable_tsc;
329   request.psbPeriod = psb_period.map([](size_t val) { return (int64_t)val; });
330   request.type = GetPluginName().str();
331   request.tids.emplace();
332   for (lldb::tid_t tid : tids)
333     request.tids->push_back(tid);
334   return Trace::Start(toJSON(request));
335 }
336 
337 Error TraceIntelPT::Start(llvm::ArrayRef<lldb::tid_t> tids,
338                           StructuredData::ObjectSP configuration) {
339   size_t thread_buffer_size = kDefaultThreadBufferSize;
340   bool enable_tsc = kDefaultEnableTscValue;
341   Optional<size_t> psb_period = kDefaultPsbPeriod;
342 
343   if (configuration) {
344     if (StructuredData::Dictionary *dict = configuration->GetAsDictionary()) {
345       dict->GetValueForKeyAsInteger("threadBufferSize", thread_buffer_size);
346       dict->GetValueForKeyAsBoolean("enableTsc", enable_tsc);
347       dict->GetValueForKeyAsInteger("psbPeriod", psb_period);
348     } else {
349       return createStringError(inconvertibleErrorCode(),
350                                "configuration object is not a dictionary");
351     }
352   }
353 
354   return Start(tids, thread_buffer_size, enable_tsc, psb_period);
355 }
356 
357 Error TraceIntelPT::OnThreadBufferRead(lldb::tid_t tid,
358                                        OnBinaryDataReadCallback callback) {
359   return OnThreadBinaryDataRead(tid, "threadTraceBuffer", callback);
360 }
361