11#include "../common/ThreadPostMortemTrace.h"
35 auto do_parse = [&]() ->
Error {
45 if (module.
uuid.has_value())
53 return error.ToError();
55 bool load_addr_changed =
false;
58 return Error::success();
60 if (
Error err = do_parse())
61 return createStringError(
62 inconvertibleErrorCode(),
"Error when parsing module %s. %s",
64 return Error::success();
68 const json::Value &value) {
70 raw_string_ostream os(err);
71 root.printErrorContext(value, os);
72 return createStringError(
73 std::errc::invalid_argument,
"%s\n\nContext:\n%s\n\nSchema:\n%s",
77ThreadPostMortemTraceSP
82 std::optional<FileSpec> trace_file;
86 ThreadPostMortemTraceSP thread_sp =
87 std::make_shared<ThreadPostMortemTrace>(process, tid, trace_file);
92Expected<TraceIntelPTBundleLoader::ParsedProcess>
94 llvm::StringRef triple) {
101 return error.ToError();
106 ProcessSP process_sp = target_sp->CreateProcess(
113 return parsed_process;
116Expected<TraceIntelPTBundleLoader::ParsedProcess>
118 Expected<ParsedProcess> parsed_process =
122 return parsed_process.takeError();
124 ProcessSP process_sp = parsed_process->target_sp->GetProcessSP();
127 parsed_process->threads.push_back(
ParseThread(*process_sp, thread));
131 return std::move(err);
134 process_sp->GetThreadList().SetSelectedThreadByIndexID(0);
139 process_sp->DidAttach(process_arch);
141 return parsed_process;
144Expected<TraceIntelPTBundleLoader::ParsedProcess>
147 Expected<ParsedProcess> parsed_process =
151 return parsed_process.takeError();
153 ProcessSP process_sp = parsed_process->target_sp->GetProcessSP();
156 for (
const JSONCpu &cpu : *bundle_description.
cpus) {
157 ThreadPostMortemTraceSP thread_sp = std::make_shared<ThreadPostMortemTrace>(
159 thread_sp->SetName(formatv(
"kernel_cpu_{0}", cpu.
id).str().c_str());
160 process_sp->GetThreadList().AddThread(thread_sp);
161 parsed_process->threads.push_back(thread_sp);
171 parsed_process->target_sp->GetOrCreateModule(module_spec,
false, &
error);
174 return error.ToError();
177 bundle_description.
kernel->load_address
178 ? bundle_description.
kernel->load_address->value
181 bool load_addr_changed =
false;
182 module_sp->SetLoadAddress(*parsed_process->target_sp, load_address,
false,
185 process_sp->GetThreadList().SetSelectedThreadByIndexID(0);
190 process_sp->DidAttach(process_arch);
192 return parsed_process;
195Expected<std::vector<TraceIntelPTBundleLoader::ParsedProcess>>
198 std::vector<ParsedProcess> parsed_processes;
200 auto HandleError = [&](
Error &&err) {
204 return std::move(err);
209 if (Expected<ParsedProcess> parsed_process =
ParseProcess(process))
210 parsed_processes.push_back(std::move(*parsed_process));
212 return HandleError(parsed_process.takeError());
216 if (bundle_description.
kernel) {
217 if (Expected<ParsedProcess> kernel_process =
219 parsed_processes.push_back(std::move(*kernel_process));
221 return HandleError(kernel_process.takeError());
224 return parsed_processes;
228 static std::string schema;
229 if (schema.empty()) {
233 // CPU information gotten from, for example, /proc/cpuinfo.
235 "vendor": "GenuineIntel" | "unknown",
244 // Optional clang/llvm target triple.
245 // This must be provided if the trace will be created not using the
246 // CLI or on a machine other than where the target was traced.
248 // A list of known threads for the given process. When context switch
249 // data is provided, LLDB will automatically create threads for the
250 // this process whenever it finds new threads when traversing the
251 // context switches, so passing values to this list in this case is
256 // Path to the raw Intel PT buffer file for this thread.
261 "systemPath": string,
262 // Original path of the module at runtime.
264 // Path to a copy of the file if not available at "systemPath".
265 "loadAddress": integer | string decimal | hex string,
266 // Lowest address of the sections of the module loaded on memory.
268 // Build UUID for the file for sanity checks.
276 // Id of this CPU core.
278 // Path to the raw Intel PT buffer for this cpu core.
279 "contextSwitchTrace": string,
280 // Path to the raw perf_event_open context switch trace file for this cpu core.
281 // The perf_event must have been configured with PERF_SAMPLE_TID and
282 // PERF_SAMPLE_TIME, as well as sample_id_all = 1.
285 "tscPerfZeroConversion"?: {
286 // Values used to convert between TSCs and nanoseconds. See the time_zero
287 // section in https://man7.org/linux/man-pages/man2/perf_event_open.2.html
288 // for for information.
291 "timeShift": integer,
292 "timeZero": integer | string decimal | hex string,
295 "loadAddress"?: integer | string decimal | hex string,
296 // Kernel's image load address. Defaults to 0xffffffff81000000, which
297 // is a load address of x86 architecture if KASLR is not enabled.
299 // Path to the kernel image.
305- All paths are either absolute or relative to folder containing the bundle
307- "cpus" is provided if and only if processes[].threads[].iptTrace is not provided.
308- "tscPerfZeroConversion" must be provided if "cpus" is provided.
309- If "kernel" is provided, then the "processes" section must be empty or not
310 passed at all, and the "cpus" section must be provided. This configuration
311 indicates that the kernel was traced and user processes weren't. Besides
312 that, the kernel is treated as a single process with one thread per CPU
313 core. This doesn't handle actual kernel threads, but instead treats
314 all the instructions executed by the kernel on each core as an
315 individual thread.})";
322 if (!bundle_description.
cpus || !bundle_description.
processes)
323 return Error::success();
326 return createStringError(inconvertibleErrorCode(),
327 "TSC to nanos conversion values are needed when "
328 "context switch information is provided.");
330 DenseMap<lldb::pid_t, JSONProcess *> indexed_processes;
331 DenseMap<JSONProcess *, DenseSet<tid_t>> indexed_threads;
334 indexed_processes[process.
pid] = &process;
336 indexed_threads[&process].insert(thread.
tid);
340 auto proc = indexed_processes.find(pid);
341 if (proc == indexed_processes.end())
343 if (indexed_threads[proc->second].count(tid))
345 indexed_threads[proc->second].insert(tid);
346 proc->second->
threads.push_back({tid, None});
349 for (
const JSONCpu &cpu : *bundle_description.
cpus) {
352 [&](ArrayRef<uint8_t> data) ->
Error {
353 Expected<std::vector<ThreadContinuousExecution>> executions =
354 DecodePerfContextSwitchTrace(
355 data, cpu.id, *bundle_description.tsc_perf_zero_conversion);
357 return executions.takeError();
358 for (const ThreadContinuousExecution &execution : *executions)
359 on_thread_seen(execution.pid, execution.tid);
360 return Error::success();
365 return Error::success();
370 std::vector<ParsedProcess> &parsed_processes) {
371 std::vector<ThreadPostMortemTraceSP> threads;
372 std::vector<ProcessSP> processes;
373 for (
const ParsedProcess &parsed_process : parsed_processes) {
374 processes.push_back(parsed_process.target_sp->GetProcessSP());
375 threads.insert(threads.end(), parsed_process.threads.begin(),
376 parsed_process.threads.end());
384 bundle_description, processes, threads, trace_mode);
386 parsed_process.target_sp->SetTrace(trace_instance);
388 return trace_instance;
406 if (bundle_description.
cpus) {
413 if (bundle_description.
kernel) {
414 bundle_description.
kernel->file =
420 json::Path::Root root(
"traceBundle");
428 return std::move(err);
430 if (Expected<std::vector<ParsedProcess>> parsed_processes =
434 return parsed_processes.takeError();
static llvm::raw_ostream & error(Stream &strm)
An architecture specification class.
TargetList & GetTargetList()
Get accessor for the target list.
bool IsRelative() const
Returns true if the filespec represents a relative path.
void PrependPathComponent(llvm::StringRef component)
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
FileSpec & GetPlatformFileSpec()
A plug-in interface definition class for debugging a process.
ThreadList & GetThreadList()
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
bool DeleteTarget(lldb::TargetSP &target_sp)
Delete a Target object from the list.
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
void AddThread(const lldb::ThreadSP &thread_sp)
static llvm::Error OnDataFileRead(FileSpec file, OnBinaryDataReadCallback callback)
Helper method for reading a data file and passing its data to the given callback.
bool SetFromStringRef(llvm::StringRef str)
llvm::Error AugmentThreadsFromContextSwitches(JSONTraceBundleDescription &bundle_description)
When applicable, augment the list of threads in the trace bundle by inspecting the context switch tra...
llvm::Expected< lldb::TraceSP > CreateTraceIntelPTInstance(JSONTraceBundleDescription &bundle_description, std::vector< ParsedProcess > &parsed_processes)
Given a bundle description and a list of fully parsed processes, create an actual Trace instance that...
void NormalizeAllPaths(JSONTraceBundleDescription &bundle_description)
Modifiy the bundle description by normalizing all the paths relative to the session file directory.
llvm::Expected< std::vector< ParsedProcess > > LoadBundle(const JSONTraceBundleDescription &bundle_description)
Create the corresponding Process, Thread and Module objects given this bundle description.
lldb::ThreadPostMortemTraceSP ParseThread(Process &process, const JSONThread &thread)
Create a post-mortem thread associated with the given process using the definition from thread.
llvm::Error CreateJSONError(llvm::json::Path::Root &root, const llvm::json::Value &value)
Create a user-friendly error message upon a JSON-parsing failure using the json::ObjectMapper functio...
llvm::Expected< lldb::TraceSP > Load()
Parse the trace bundle description and create the corresponding Target objects.
static llvm::StringRef GetSchema()
FileSpec NormalizePath(const std::string &path)
Resolve non-absolute paths relative to the bundle folder.
const std::string m_bundle_dir
const llvm::json::Value & m_bundle_description
llvm::Expected< ParsedProcess > CreateEmptyProcess(lldb::pid_t pid, llvm::StringRef triple)
Create an empty Process object with given pid and target.
llvm::Expected< ParsedProcess > ParseProcess(const JSONProcess &process)
Create the corresponding Threads and Process objects given the JSON process definition.
llvm::Expected< ParsedProcess > ParseKernel(const JSONTraceBundleDescription &bundle_description)
Create a kernel process and cpu threads given the JSON kernel definition.
llvm::Error ParseModule(Target &target, const JSONModule &module)
Create a module associated with the given target using the definition from module.
static TraceIntelPTSP CreateInstanceForPostmortemTrace(JSONTraceBundleDescription &bundle_description, llvm::ArrayRef< lldb::ProcessSP > traced_processes, llvm::ArrayRef< lldb::ThreadPostMortemTraceSP > traced_threads, TraceMode trace_mode)
Postmortem trace constructor.
const lldb::pid_t kDefaultKernelProcessID
bool fromJSON(const json::Value &value, JSONModule &module, Path path)
const lldb::addr_t kDefaultKernelLoadAddress
A class that represents a running process on the host machine.
const char * toString(AppleArm64ExceptionClass EC)
std::string context_switch_trace
std::optional< std::string > uuid
std::optional< std::string > file
std::optional< std::string > triple
std::vector< JSONModule > modules
std::vector< JSONThread > threads
std::optional< std::string > ipt_trace
std::optional< std::vector< JSONCpu > > cpus
std::optional< LinuxPerfZeroTscConversion > tsc_perf_zero_conversion
std::optional< JSONKernel > kernel
std::optional< std::vector< JSONProcess > > processes
Helper struct holding the objects created when parsing a process.