LLDB mainline
CommandObjectTrace.cpp
Go to the documentation of this file.
1//===-- CommandObjectTrace.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
10
11#include "llvm/Support/JSON.h"
12#include "llvm/Support/MemoryBuffer.h"
13
14#include "lldb/Core/Debugger.h"
27#include "lldb/Target/Process.h"
28#include "lldb/Target/Trace.h"
29
30using namespace lldb;
31using namespace lldb_private;
32using namespace llvm;
33
34// CommandObjectTraceSave
35#define LLDB_OPTIONS_trace_save
36#include "CommandOptions.inc"
37
38#pragma mark CommandObjectTraceSave
39
41public:
42 class CommandOptions : public Options {
43 public:
45
46 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
47 ExecutionContext *execution_context) override {
49 const int short_option = m_getopt_table[option_idx].val;
50
51 switch (short_option) {
52 case 'c': {
53 m_compact = true;
54 break;
55 }
56 default:
57 llvm_unreachable("Unimplemented option");
58 }
59 return error;
60 }
61
62 void OptionParsingStarting(ExecutionContext *execution_context) override {
63 m_compact = false;
64 };
65
66 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
67 return llvm::ArrayRef(g_trace_save_options);
68 };
69
71 };
72
73 Options *GetOptions() override { return &m_options; }
74
77 interpreter, "trace save",
78 "Save the trace of the current target in the specified directory, "
79 "which will be created if needed. "
80 "This directory will contain a trace bundle, with all the "
81 "necessary files the reconstruct the trace session even on a "
82 "different computer. "
83 "Part of this bundle is the bundle description file with the name "
84 "trace.json. This file can be used by the \"trace load\" command "
85 "to load this trace in LLDB."
86 "Note: if the current target contains information of multiple "
87 "processes or targets, they all will be included in the bundle.",
88 "trace save [<cmd-options>] <bundle_directory>",
89 eCommandRequiresProcess | eCommandTryTargetAPILock |
90 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
91 eCommandProcessMustBeTraced) {
93 m_arguments.push_back({bundle_dir});
94 }
95
96 void
98 OptionElementVector &opt_element_vector) override {
101 request, nullptr);
102 }
103
104 ~CommandObjectTraceSave() override = default;
105
106protected:
107 bool DoExecute(Args &command, CommandReturnObject &result) override {
108 if (command.size() != 1) {
109 result.AppendError("a single path to a directory where the trace bundle "
110 "will be created is required");
111 return false;
112 }
113
114 FileSpec bundle_dir(command[0].ref());
115 FileSystem::Instance().Resolve(bundle_dir);
116
117 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
118
119 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
120
121 if (llvm::Expected<FileSpec> desc_file =
122 trace_sp->SaveToDisk(bundle_dir, m_options.m_compact)) {
124 "Trace bundle description file written to: {0}", *desc_file);
126 } else {
127 result.AppendError(toString(desc_file.takeError()));
128 }
129
130 return result.Succeeded();
131 }
132
134};
135
136// CommandObjectTraceLoad
137#define LLDB_OPTIONS_trace_load
138#include "CommandOptions.inc"
139
140#pragma mark CommandObjectTraceLoad
141
143public:
144 class CommandOptions : public Options {
145 public:
147
148 ~CommandOptions() override = default;
149
150 Status SetOptionValue(uint32_t option_idx, StringRef option_arg,
151 ExecutionContext *execution_context) override {
153 const int short_option = m_getopt_table[option_idx].val;
154
155 switch (short_option) {
156 case 'v': {
157 m_verbose = true;
158 break;
159 }
160 default:
161 llvm_unreachable("Unimplemented option");
162 }
163 return error;
164 }
165
166 void OptionParsingStarting(ExecutionContext *execution_context) override {
167 m_verbose = false;
168 }
169
170 ArrayRef<OptionDefinition> GetDefinitions() override {
171 return ArrayRef(g_trace_load_options);
172 }
173
174 bool m_verbose; // Enable verbose logging for debugging purposes.
175 };
176
179 interpreter, "trace load",
180 "Load a post-mortem processor trace session from a trace bundle.",
181 "trace load <trace_description_file>") {
183 m_arguments.push_back({session_file_arg});
184 }
185
186 void
188 OptionElementVector &opt_element_vector) override {
191 request, nullptr);
192 }
193
194 ~CommandObjectTraceLoad() override = default;
195
196 Options *GetOptions() override { return &m_options; }
197
198protected:
199 bool DoExecute(Args &command, CommandReturnObject &result) override {
200 if (command.size() != 1) {
201 result.AppendError("a single path to a JSON file containing a the "
202 "description of the trace bundle is required");
203 return false;
204 }
205
206 const FileSpec trace_description_file(command[0].ref());
207
208 llvm::Expected<lldb::TraceSP> trace_or_err =
210 trace_description_file);
211
212 if (!trace_or_err) {
214 "%s\n", llvm::toString(trace_or_err.takeError()).c_str());
215 return false;
216 }
217
218 if (m_options.m_verbose) {
219 result.AppendMessageWithFormatv("loading trace with plugin {0}\n",
220 trace_or_err.get()->GetPluginName());
221 }
222
224 return true;
225 }
226
228};
229
230// CommandObjectTraceDump
231#define LLDB_OPTIONS_trace_dump
232#include "CommandOptions.inc"
233
234#pragma mark CommandObjectTraceDump
235
237public:
238 class CommandOptions : public Options {
239 public:
241
242 ~CommandOptions() override = default;
243
244 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
245 ExecutionContext *execution_context) override {
247 const int short_option = m_getopt_table[option_idx].val;
248
249 switch (short_option) {
250 case 'v': {
251 m_verbose = true;
252 break;
253 }
254 default:
255 llvm_unreachable("Unimplemented option");
256 }
257 return error;
258 }
259
260 void OptionParsingStarting(ExecutionContext *execution_context) override {
261 m_verbose = false;
262 }
263
264 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
265 return llvm::ArrayRef(g_trace_dump_options);
266 }
267
268 bool m_verbose; // Enable verbose logging for debugging purposes.
269 };
270
272 : CommandObjectParsed(interpreter, "trace dump",
273 "Dump the loaded processor trace data.",
274 "trace dump") {}
275
276 ~CommandObjectTraceDump() override = default;
277
278 Options *GetOptions() override { return &m_options; }
279
280protected:
281 bool DoExecute(Args &command, CommandReturnObject &result) override {
283 // TODO: fill in the dumping code here!
284 if (error.Success()) {
286 } else {
287 result.AppendErrorWithFormat("%s\n", error.AsCString());
288 }
289 return result.Succeeded();
290 }
291
293};
294
295// CommandObjectTraceSchema
296#define LLDB_OPTIONS_trace_schema
297#include "CommandOptions.inc"
298
299#pragma mark CommandObjectTraceSchema
300
302public:
303 class CommandOptions : public Options {
304 public:
306
307 ~CommandOptions() override = default;
308
309 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
310 ExecutionContext *execution_context) override {
312 const int short_option = m_getopt_table[option_idx].val;
313
314 switch (short_option) {
315 case 'v': {
316 m_verbose = true;
317 break;
318 }
319 default:
320 llvm_unreachable("Unimplemented option");
321 }
322 return error;
323 }
324
325 void OptionParsingStarting(ExecutionContext *execution_context) override {
326 m_verbose = false;
327 }
328
329 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
330 return llvm::ArrayRef(g_trace_schema_options);
331 }
332
333 bool m_verbose; // Enable verbose logging for debugging purposes.
334 };
335
337 : CommandObjectParsed(interpreter, "trace schema",
338 "Show the schema of the given trace plugin.",
339 "trace schema <plug-in>. Use the plug-in name "
340 "\"all\" to see all schemas.\n") {
342 m_arguments.push_back({plugin_arg});
343 }
344
345 ~CommandObjectTraceSchema() override = default;
346
347 Options *GetOptions() override { return &m_options; }
348
349protected:
350 bool DoExecute(Args &command, CommandReturnObject &result) override {
352 if (command.empty()) {
353 result.AppendError(
354 "trace schema cannot be invoked without a plug-in as argument");
355 return false;
356 }
357
358 StringRef plugin_name(command[0].c_str());
359 if (plugin_name == "all") {
360 size_t index = 0;
361 while (true) {
362 StringRef schema = PluginManager::GetTraceSchema(index++);
363 if (schema.empty())
364 break;
365
366 result.AppendMessage(schema);
367 }
368 } else {
369 if (Expected<StringRef> schemaOrErr =
370 Trace::FindPluginSchema(plugin_name))
371 result.AppendMessage(*schemaOrErr);
372 else
373 error = schemaOrErr.takeError();
374 }
375
376 if (error.Success()) {
378 } else {
379 result.AppendErrorWithFormat("%s\n", error.AsCString());
380 }
381 return result.Succeeded();
382 }
383
385};
386
387// CommandObjectTrace
388
390 : CommandObjectMultiword(interpreter, "trace",
391 "Commands for loading and using processor "
392 "trace information.",
393 "trace [<sub-command-options>]") {
394 LoadSubCommand("load",
395 CommandObjectSP(new CommandObjectTraceLoad(interpreter)));
396 LoadSubCommand("dump",
397 CommandObjectSP(new CommandObjectTraceDump(interpreter)));
398 LoadSubCommand("save",
399 CommandObjectSP(new CommandObjectTraceSave(interpreter)));
400 LoadSubCommand("schema",
401 CommandObjectSP(new CommandObjectTraceSchema(interpreter)));
402}
403
405
407 ProcessSP process_sp = m_interpreter.GetExecutionContext().GetProcessSP();
408
409 if (!process_sp)
410 return createStringError(inconvertibleErrorCode(),
411 "Process not available.");
412 if (m_live_debug_session_only && !process_sp->IsLiveDebugSession())
413 return createStringError(inconvertibleErrorCode(),
414 "Process must be alive.");
415
416 if (Expected<TraceSP> trace_sp = process_sp->GetTarget().GetTraceOrCreate())
417 return GetDelegateCommand(**trace_sp);
418 else
419 return createStringError(inconvertibleErrorCode(),
420 "Tracing is not supported. %s",
421 toString(trace_sp.takeError()).c_str());
422}
423
425 if (Expected<CommandObjectSP> delegate = DoGetProxyCommandObject()) {
426 m_delegate_sp = *delegate;
427 m_delegate_error.clear();
428 return m_delegate_sp.get();
429 } else {
430 m_delegate_sp.reset();
431 m_delegate_error = toString(delegate.takeError());
432 return nullptr;
433 }
434}
static llvm::raw_ostream & error(Stream &strm)
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
CommandObjectTraceDump(CommandInterpreter &interpreter)
Options * GetOptions() override
~CommandObjectTraceDump() override=default
bool DoExecute(Args &command, CommandReturnObject &result) override
Status SetOptionValue(uint32_t option_idx, StringRef option_arg, ExecutionContext *execution_context) override
ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
bool DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTraceLoad() override=default
CommandObjectTraceLoad(CommandInterpreter &interpreter)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
Options * GetOptions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
~CommandObjectTraceSave() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
Options * GetOptions() override
CommandObjectTraceSave(CommandInterpreter &interpreter)
bool DoExecute(Args &command, CommandReturnObject &result) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
Options * GetOptions() override
bool DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectTraceSchema() override=default
CommandObjectTraceSchema(CommandInterpreter &interpreter)
A command line argument class.
Definition: Args.h:33
size_t size() const
Definition: Args.h:135
bool empty() const
Definition: Args.h:118
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
ExecutionContext GetExecutionContext() const
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
llvm::Expected< lldb::CommandObjectSP > DoGetProxyCommandObject()
CommandObject * GetProxyCommandObject() override
virtual lldb::CommandObjectSP GetDelegateCommand(Trace &trace)=0
CommandObjectTrace(CommandInterpreter &interpreter)
ExecutionContext m_exe_ctx
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
void AppendMessage(llvm::StringRef in_string)
void void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void void AppendMessageWithFormatv(const char *format, Args &&... args)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
"lldb/Utility/ArgCompletionRequest.h"
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
A file utility class.
Definition: FileSpec.h:56
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
static FileSystem & Instance()
A command line option parsing protocol class.
Definition: Options.h:58
std::vector< Option > m_getopt_table
Definition: Options.h:198
static llvm::StringRef GetTraceSchema(llvm::StringRef plugin_name)
Get the JSON schema for a trace bundle description file corresponding to the given plugin.
An error handling class.
Definition: Status.h:44
static llvm::Expected< lldb::TraceSP > LoadPostMortemTraceFromFile(Debugger &debugger, const FileSpec &trace_description_file)
Load a trace from a trace description file and create Targets, Processes and Threads based on the con...
Definition: Trace.cpp:96
static llvm::Expected< llvm::StringRef > FindPluginSchema(llvm::StringRef plugin_name)
Get the schema of a Trace plug-in given its name.
Definition: Trace.cpp:147
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
const char * toString(AppleArm64ExceptionClass EC)
Definition: SBAddress.h:15
@ eReturnStatusSuccessFinishResult
@ eArgTypeFilename
@ eArgTypeDirectoryName
Definition: Debugger.h:52
Used to build individual command argument lists.
Definition: CommandObject.h:93