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",
82 std::optional<FileSpec> trace_file;
87 std::make_shared<ThreadPostMortemTrace>(process, tid, trace_file);
92Expected<TraceIntelPTBundleLoader::ParsedProcess>
94 llvm::StringRef triple) {
101 return error.ToError();
114 return parsed_process;
117Expected<TraceIntelPTBundleLoader::ParsedProcess>
119 Expected<ParsedProcess> parsed_process =
123 return parsed_process.takeError();
125 ProcessSP process_sp = parsed_process->target_sp->GetProcessSP();
128 parsed_process->threads.push_back(
ParseThread(*process_sp, thread));
132 return std::move(err);
135 process_sp->GetThreadList().SetSelectedThreadByIndexID(0);
140 process_sp->DidAttach(process_arch);
142 return parsed_process;
145Expected<TraceIntelPTBundleLoader::ParsedProcess>
148 Expected<ParsedProcess> parsed_process =
152 return parsed_process.takeError();
154 ProcessSP process_sp = parsed_process->target_sp->GetProcessSP();
157 for (
const JSONCpu &cpu : *bundle_description.
cpus) {
160 thread_sp->SetName(formatv(
"kernel_cpu_{0}", cpu.
id).str().c_str());
161 process_sp->GetThreadList().AddThread(thread_sp);
162 parsed_process->threads.push_back(thread_sp);
172 parsed_process->target_sp->GetOrCreateModule(module_spec,
false, &
error);
175 return error.ToError();
178 bundle_description.
kernel->load_address
179 ? bundle_description.
kernel->load_address->value
182 bool load_addr_changed =
false;
183 module_sp->SetLoadAddress(*parsed_process->target_sp, load_address,
false,
186 process_sp->GetThreadList().SetSelectedThreadByIndexID(0);
191 process_sp->DidAttach(process_arch);
193 return parsed_process;
196Expected<std::vector<TraceIntelPTBundleLoader::ParsedProcess>>
199 std::vector<ParsedProcess> parsed_processes;
201 auto HandleError = [&](
Error &&err) {
205 return std::move(err);
210 if (Expected<ParsedProcess> parsed_process =
ParseProcess(process))
211 parsed_processes.push_back(std::move(*parsed_process));
213 return HandleError(parsed_process.takeError());
217 if (bundle_description.
kernel) {
218 if (Expected<ParsedProcess> kernel_process =
220 parsed_processes.push_back(std::move(*kernel_process));
222 return HandleError(kernel_process.takeError());
225 return parsed_processes;
229 static std::string schema;
230 if (schema.empty()) {
234 // CPU information gotten from, for example, /proc/cpuinfo.
236 "vendor": "GenuineIntel" | "unknown",
245 // Optional clang/llvm target triple.
246 // This must be provided if the trace will be created not using the
247 // CLI or on a machine other than where the target was traced.
249 // A list of known threads for the given process. When context switch
250 // data is provided, LLDB will automatically create threads for the
251 // this process whenever it finds new threads when traversing the
252 // context switches, so passing values to this list in this case is
257 // Path to the raw Intel PT buffer file for this thread.
262 "systemPath": string,
263 // Original path of the module at runtime.
265 // Path to a copy of the file if not available at "systemPath".
266 "loadAddress": integer | string decimal | hex string,
267 // Lowest address of the sections of the module loaded on memory.
269 // Build UUID for the file for sanity checks.
277 // Id of this CPU core.
279 // Path to the raw Intel PT buffer for this cpu core.
280 "contextSwitchTrace": string,
281 // Path to the raw perf_event_open context switch trace file for this cpu core.
282 // The perf_event must have been configured with PERF_SAMPLE_TID and
283 // PERF_SAMPLE_TIME, as well as sample_id_all = 1.
286 "tscPerfZeroConversion"?: {
287 // Values used to convert between TSCs and nanoseconds. See the time_zero
288 // section in https://man7.org/linux/man-pages/man2/perf_event_open.2.html
292 "timeShift": integer,
293 "timeZero": integer | string decimal | hex string,
296 "loadAddress"?: integer | string decimal | hex string,
297 // Kernel's image load address. Defaults to 0xffffffff81000000, which
298 // is a load address of x86 architecture if KASLR is not enabled.
300 // Path to the kernel image.
306- All paths are either absolute or relative to folder containing the bundle
308- "cpus" is provided if and only if processes[].threads[].iptTrace is not provided.
309- "tscPerfZeroConversion" must be provided if "cpus" is provided.
310- If "kernel" is provided, then the "processes" section must be empty or not
311 passed at all, and the "cpus" section must be provided. This configuration
312 indicates that the kernel was traced and user processes weren't. Besides
313 that, the kernel is treated as a single process with one thread per CPU
314 core. This doesn't handle actual kernel threads, but instead treats
315 all the instructions executed by the kernel on each core as an
316 individual thread.})";
323 if (!bundle_description.
cpus || !bundle_description.
processes)
324 return Error::success();
327 return createStringError(inconvertibleErrorCode(),
328 "TSC to nanos conversion values are needed when "
329 "context switch information is provided.");
331 DenseMap<lldb::pid_t, JSONProcess *> indexed_processes;
332 DenseMap<JSONProcess *, DenseSet<tid_t>> indexed_threads;
335 indexed_processes[process.
pid] = &process;
337 indexed_threads[&process].insert(thread.
tid);
341 auto proc = indexed_processes.find(pid);
342 if (proc == indexed_processes.end())
344 if (indexed_threads[proc->second].count(tid))
346 indexed_threads[proc->second].insert(tid);
347 proc->second->
threads.push_back({tid, None});
350 for (
const JSONCpu &cpu : *bundle_description.
cpus) {
353 [&](ArrayRef<uint8_t> data) ->
Error {
354 Expected<std::vector<ThreadContinuousExecution>> executions =
355 DecodePerfContextSwitchTrace(
356 data, cpu.id, *bundle_description.tsc_perf_zero_conversion);
358 return executions.takeError();
359 for (const ThreadContinuousExecution &execution : *executions)
360 on_thread_seen(execution.pid, execution.tid);
361 return Error::success();
366 return Error::success();
371 std::vector<ParsedProcess> &parsed_processes) {
372 std::vector<ThreadPostMortemTraceSP> threads;
373 std::vector<ProcessSP> processes;
374 for (
const ParsedProcess &parsed_process : parsed_processes) {
375 processes.push_back(parsed_process.target_sp->GetProcessSP());
376 threads.insert(threads.end(), parsed_process.threads.begin(),
377 parsed_process.threads.end());
385 bundle_description, processes, threads, trace_mode);
387 parsed_process.target_sp->SetTrace(trace_instance);
389 return trace_instance;
407 if (bundle_description.
cpus) {
414 if (bundle_description.
kernel) {
415 bundle_description.
kernel->file =
421 json::Path::Root root(
"traceBundle");
429 return std::move(err);
431 if (Expected<std::vector<ParsedProcess>> parsed_processes =
435 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()
bool DeleteTarget(lldb::TargetSP &target_sp)
Delete a Target object from the list.
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.
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::shared_ptr< lldb_private::Trace > TraceSP
std::shared_ptr< lldb_private::ThreadPostMortemTrace > ThreadPostMortemTraceSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP
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.