LLDB mainline
CommandObjectLog.cpp
Go to the documentation of this file.
1//===-- CommandObjectLog.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 "CommandObjectLog.h"
10#include "lldb/Core/Debugger.h"
18#include "lldb/Utility/Args.h"
20#include "lldb/Utility/Log.h"
21#include "lldb/Utility/Stream.h"
22#include "lldb/Utility/Timer.h"
23
24using namespace lldb;
25using namespace lldb_private;
26
27#define LLDB_OPTIONS_log_enable
28#include "CommandOptions.inc"
29
30#define LLDB_OPTIONS_log_dump
31#include "CommandOptions.inc"
32
33/// Common completion logic for log enable/disable.
35 size_t arg_index = request.GetCursorIndex();
36 if (arg_index == 0) { // We got: log enable/disable x[tab]
37 for (llvm::StringRef channel : Log::ListChannels())
38 request.TryCompleteCurrentArg(channel);
39 } else if (arg_index >= 1) { // We got: log enable/disable channel x[tab]
40 llvm::StringRef channel = request.GetParsedLine().GetArgumentAtIndex(0);
42 channel, [&request](llvm::StringRef name, llvm::StringRef desc) {
43 request.TryCompleteCurrentArg(name, desc);
44 });
45 }
46}
47
49public:
50 // Constructors and Destructors
52 : CommandObjectParsed(interpreter, "log enable",
53 "Enable logging for a single log channel.",
54 nullptr) {
57 CommandArgumentData channel_arg;
58 CommandArgumentData category_arg;
59
60 // Define the first (and only) variant of this arg.
61 channel_arg.arg_type = eArgTypeLogChannel;
62 channel_arg.arg_repetition = eArgRepeatPlain;
63
64 // There is only one variant this argument could be; put it into the
65 // argument entry.
66 arg1.push_back(channel_arg);
67
68 category_arg.arg_type = eArgTypeLogCategory;
69 category_arg.arg_repetition = eArgRepeatPlus;
70
71 arg2.push_back(category_arg);
72
73 // Push the data for the first argument into the m_arguments vector.
74 m_arguments.push_back(arg1);
75 m_arguments.push_back(arg2);
76 }
77
78 ~CommandObjectLogEnable() override = default;
79
80 Options *GetOptions() override { return &m_options; }
81
82 class CommandOptions : public Options {
83 public:
84 CommandOptions() = default;
85
86 ~CommandOptions() override = default;
87
88 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
89 ExecutionContext *execution_context) override {
91 const int short_option = m_getopt_table[option_idx].val;
92
93 switch (short_option) {
94 case 'f':
95 log_file.SetFile(option_arg, FileSpec::Style::native);
97 break;
98 case 'h':
100 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
101 if (!error.Success())
102 error.SetErrorStringWithFormat(
103 "unrecognized value for log handler '%s'",
104 option_arg.str().c_str());
105 break;
106 case 'b':
107 error =
109 break;
110 case 'v':
112 break;
113 case 's':
115 break;
116 case 'T':
118 break;
119 case 'p':
121 break;
122 case 'n':
124 break;
125 case 'S':
127 break;
128 case 'a':
130 break;
131 case 'F':
133 break;
134 default:
135 llvm_unreachable("Unimplemented option");
136 }
137
138 return error;
139 }
140
141 void OptionParsingStarting(ExecutionContext *execution_context) override {
142 log_file.Clear();
145 log_options = 0;
146 }
147
148 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
149 return llvm::ArrayRef(g_log_enable_options);
150 }
151
155 uint32_t log_options = 0;
156 };
157
158 void
160 OptionElementVector &opt_element_vector) override {
161 CompleteEnableDisable(request);
162 }
163
164protected:
165 void DoExecute(Args &args, CommandReturnObject &result) override {
166 if (args.GetArgumentCount() < 2) {
168 "%s takes a log channel and one or more log types.\n",
169 m_cmd_name.c_str());
170 return;
171 }
172
175 result.AppendError(
176 "the circular buffer handler requires a non-zero buffer size.\n");
177 return;
178 }
179
183 result.AppendError("a buffer size can only be specified for the circular "
184 "and stream buffer handler.\n");
185 return;
186 }
187
189 result.AppendError(
190 "a file name can only be specified for the stream handler.\n");
191 return;
192 }
193
194 // Store into a std::string since we're about to shift the channel off.
195 const std::string channel = std::string(args[0].ref());
196 args.Shift(); // Shift off the channel
197 char log_file[PATH_MAX];
199 m_options.log_file.GetPath(log_file, sizeof(log_file));
200 else
201 log_file[0] = '\0';
202
203 std::string error;
204 llvm::raw_string_ostream error_stream(error);
205 bool success = GetDebugger().EnableLog(
206 channel, args.GetArgumentArrayRef(), log_file, m_options.log_options,
208 error_stream);
209 result.GetErrorStream() << error_stream.str();
210
211 if (success)
213 else
215 }
216
218};
219
221public:
222 // Constructors and Destructors
224 : CommandObjectParsed(interpreter, "log disable",
225 "Disable one or more log channel categories.",
226 nullptr) {
229 CommandArgumentData channel_arg;
230 CommandArgumentData category_arg;
231
232 // Define the first (and only) variant of this arg.
233 channel_arg.arg_type = eArgTypeLogChannel;
234 channel_arg.arg_repetition = eArgRepeatPlain;
235
236 // There is only one variant this argument could be; put it into the
237 // argument entry.
238 arg1.push_back(channel_arg);
239
240 category_arg.arg_type = eArgTypeLogCategory;
241 category_arg.arg_repetition = eArgRepeatPlus;
242
243 arg2.push_back(category_arg);
244
245 // Push the data for the first argument into the m_arguments vector.
246 m_arguments.push_back(arg1);
247 m_arguments.push_back(arg2);
248 }
249
250 ~CommandObjectLogDisable() override = default;
251
252 void
254 OptionElementVector &opt_element_vector) override {
255 CompleteEnableDisable(request);
256 }
257
258protected:
259 void DoExecute(Args &args, CommandReturnObject &result) override {
260 if (args.empty()) {
262 "%s takes a log channel and one or more log types.\n",
263 m_cmd_name.c_str());
264 return;
265 }
266
267 const std::string channel = std::string(args[0].ref());
268 args.Shift(); // Shift off the channel
269 if (channel == "all") {
272 } else {
273 std::string error;
274 llvm::raw_string_ostream error_stream(error);
276 error_stream))
278 result.GetErrorStream() << error_stream.str();
279 }
280 }
281};
282
284public:
285 // Constructors and Destructors
287 : CommandObjectParsed(interpreter, "log list",
288 "List the log categories for one or more log "
289 "channels. If none specified, lists them all.",
290 nullptr) {
292 }
293
294 ~CommandObjectLogList() override = default;
295
296 void
298 OptionElementVector &opt_element_vector) override {
299 for (llvm::StringRef channel : Log::ListChannels())
300 request.TryCompleteCurrentArg(channel);
301 }
302
303protected:
304 void DoExecute(Args &args, CommandReturnObject &result) override {
305 std::string output;
306 llvm::raw_string_ostream output_stream(output);
307 if (args.empty()) {
308 Log::ListAllLogChannels(output_stream);
310 } else {
311 bool success = true;
312 for (const auto &entry : args.entries())
313 success =
314 success && Log::ListChannelCategories(entry.ref(), output_stream);
315 if (success)
317 }
318 result.GetOutputStream() << output_stream.str();
319 }
320};
322public:
324 : CommandObjectParsed(interpreter, "log dump",
325 "dump circular buffer logs", nullptr) {
327 }
328
329 ~CommandObjectLogDump() override = default;
330
331 Options *GetOptions() override { return &m_options; }
332
333 class CommandOptions : public Options {
334 public:
335 CommandOptions() = default;
336
337 ~CommandOptions() override = default;
338
339 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
340 ExecutionContext *execution_context) override {
342 const int short_option = m_getopt_table[option_idx].val;
343
344 switch (short_option) {
345 case 'f':
346 log_file.SetFile(option_arg, FileSpec::Style::native);
348 break;
349 default:
350 llvm_unreachable("Unimplemented option");
351 }
352
353 return error;
354 }
355
356 void OptionParsingStarting(ExecutionContext *execution_context) override {
357 log_file.Clear();
358 }
359
360 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
361 return llvm::ArrayRef(g_log_dump_options);
362 }
363
365 };
366
367 void
369 OptionElementVector &opt_element_vector) override {
370 CompleteEnableDisable(request);
371 }
372
373protected:
374 void DoExecute(Args &args, CommandReturnObject &result) override {
375 if (args.empty()) {
377 "%s takes a log channel and one or more log types.\n",
378 m_cmd_name.c_str());
379 return;
380 }
381
382 std::unique_ptr<llvm::raw_ostream> stream_up;
383 if (m_options.log_file) {
387 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
388 m_options.log_file, flags, lldb::eFilePermissionsFileDefault, false);
389 if (!file) {
390 result.AppendErrorWithFormat("Unable to open log file '%s': %s",
391 m_options.log_file.GetPath().c_str(),
392 llvm::toString(file.takeError()).c_str());
393 return;
394 }
395 stream_up = std::make_unique<llvm::raw_fd_ostream>(
396 (*file)->GetDescriptor(), /*shouldClose=*/true);
397 } else {
398 stream_up = std::make_unique<llvm::raw_fd_ostream>(
399 GetDebugger().GetOutputFile().GetDescriptor(), /*shouldClose=*/false);
400 }
401
402 const std::string channel = std::string(args[0].ref());
403 std::string error;
404 llvm::raw_string_ostream error_stream(error);
405 if (Log::DumpLogChannel(channel, *stream_up, error_stream)) {
407 } else {
409 result.GetErrorStream() << error_stream.str();
410 }
411 }
412
414};
415
417public:
418 // Constructors and Destructors
420 : CommandObjectParsed(interpreter, "log timers enable",
421 "enable LLDB internal performance timers",
422 "log timers enable <depth>") {
424 }
425
426 ~CommandObjectLogTimerEnable() override = default;
427
428protected:
429 void DoExecute(Args &args, CommandReturnObject &result) override {
431
432 if (args.GetArgumentCount() == 0) {
435 } else if (args.GetArgumentCount() == 1) {
436 uint32_t depth;
437 if (args[0].ref().consumeInteger(0, depth)) {
438 result.AppendError(
439 "Could not convert enable depth to an unsigned integer.");
440 } else {
443 }
444 }
445
446 if (!result.Succeeded()) {
447 result.AppendError("Missing subcommand");
448 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
449 }
450 }
451};
452
454public:
455 // Constructors and Destructors
457 : CommandObjectParsed(interpreter, "log timers disable",
458 "disable LLDB internal performance timers",
459 nullptr) {}
460
461 ~CommandObjectLogTimerDisable() override = default;
462
463protected:
464 void DoExecute(Args &args, CommandReturnObject &result) override {
468
469 if (!result.Succeeded()) {
470 result.AppendError("Missing subcommand");
471 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
472 }
473 }
474};
475
477public:
478 // Constructors and Destructors
480 : CommandObjectParsed(interpreter, "log timers dump",
481 "dump LLDB internal performance timers", nullptr) {}
482
483 ~CommandObjectLogTimerDump() override = default;
484
485protected:
486 void DoExecute(Args &args, CommandReturnObject &result) override {
489
490 if (!result.Succeeded()) {
491 result.AppendError("Missing subcommand");
492 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
493 }
494 }
495};
496
498public:
499 // Constructors and Destructors
501 : CommandObjectParsed(interpreter, "log timers reset",
502 "reset LLDB internal performance timers", nullptr) {
503 }
504
505 ~CommandObjectLogTimerReset() override = default;
506
507protected:
508 void DoExecute(Args &args, CommandReturnObject &result) override {
511
512 if (!result.Succeeded()) {
513 result.AppendError("Missing subcommand");
514 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
515 }
516 }
517};
518
520public:
521 // Constructors and Destructors
523 : CommandObjectParsed(interpreter, "log timers increment",
524 "increment LLDB internal performance timers",
525 "log timers increment <bool>") {
527 }
528
530
531 void
533 OptionElementVector &opt_element_vector) override {
534 request.TryCompleteCurrentArg("true");
535 request.TryCompleteCurrentArg("false");
536 }
537
538protected:
539 void DoExecute(Args &args, CommandReturnObject &result) override {
541
542 if (args.GetArgumentCount() == 1) {
543 bool success;
544 bool increment =
545 OptionArgParser::ToBoolean(args[0].ref(), false, &success);
546
547 if (success) {
548 Timer::SetQuiet(!increment);
550 } else
551 result.AppendError("Could not convert increment value to boolean.");
552 }
553
554 if (!result.Succeeded()) {
555 result.AppendError("Missing subcommand");
556 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
557 }
558 }
559};
560
562public:
564 : CommandObjectMultiword(interpreter, "log timers",
565 "Enable, disable, dump, and reset LLDB internal "
566 "performance timers.",
567 "log timers < enable <depth> | disable | dump | "
568 "increment <bool> | reset >") {
570 new CommandObjectLogTimerEnable(interpreter)));
572 interpreter)));
573 LoadSubCommand("dump",
576 "reset", CommandObjectSP(new CommandObjectLogTimerReset(interpreter)));
578 "increment",
580 }
581
582 ~CommandObjectLogTimer() override = default;
583};
584
586 : CommandObjectMultiword(interpreter, "log",
587 "Commands controlling LLDB internal logging.",
588 "log <subcommand> [<command-options>]") {
589 LoadSubCommand("enable",
590 CommandObjectSP(new CommandObjectLogEnable(interpreter)));
591 LoadSubCommand("disable",
592 CommandObjectSP(new CommandObjectLogDisable(interpreter)));
593 LoadSubCommand("list",
594 CommandObjectSP(new CommandObjectLogList(interpreter)));
595 LoadSubCommand("dump",
596 CommandObjectSP(new CommandObjectLogDump(interpreter)));
597 LoadSubCommand("timers",
598 CommandObjectSP(new CommandObjectLogTimer(interpreter)));
599}
600
static void CompleteEnableDisable(CompletionRequest &request)
Common completion logic for log enable/disable.
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION
Definition: Log.h:43
#define LLDB_LOG_OPTION_APPEND
Definition: Log.h:42
#define LLDB_LOG_OPTION_BACKTRACE
Definition: Log.h:41
#define LLDB_LOG_OPTION_PREPEND_TIMESTAMP
Definition: Log.h:38
#define LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD
Definition: Log.h:39
#define LLDB_LOG_OPTION_PREPEND_SEQUENCE
Definition: Log.h:37
#define LLDB_LOG_OPTION_VERBOSE
Definition: Log.h:36
#define LLDB_LOG_OPTION_PREPEND_THREAD_NAME
Definition: Log.h:40
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectLogDisable(CommandInterpreter &interpreter)
~CommandObjectLogDisable() override=default
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
CommandObjectLogDump(CommandInterpreter &interpreter)
Options * GetOptions() override
~CommandObjectLogDump() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
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.
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
Options * GetOptions() override
CommandObjectLogEnable(CommandInterpreter &interpreter)
~CommandObjectLogEnable() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectLogList(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectLogList() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectLogTimerDisable(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectLogTimerDisable() override=default
~CommandObjectLogTimerDump() override=default
CommandObjectLogTimerDump(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectLogTimerEnable() override=default
CommandObjectLogTimerEnable(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectLogTimerIncrement(CommandInterpreter &interpreter)
void DoExecute(Args &args, CommandReturnObject &result) override
~CommandObjectLogTimerIncrement() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectLogTimerReset(CommandInterpreter &interpreter)
~CommandObjectLogTimerReset() override=default
void DoExecute(Args &args, CommandReturnObject &result) override
CommandObjectLogTimer(CommandInterpreter &interpreter)
~CommandObjectLogTimer() override=default
A command line argument class.
Definition: Args.h:33
llvm::ArrayRef< const char * > GetArgumentArrayRef() const
Gets the argument as an ArrayRef.
Definition: Args.h:169
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition: Args.cpp:285
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:116
llvm::ArrayRef< ArgEntry > entries() const
Definition: Args.h:128
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition: Args.cpp:263
bool empty() const
Definition: Args.h:118
CommandObjectLog(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
std::vector< CommandArgumentData > CommandArgumentEntry
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
std::vector< CommandArgumentEntry > m_arguments
void void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
"lldb/Utility/ArgCompletionRequest.h"
const Args & GetParsedLine() const
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
bool EnableLog(llvm::StringRef channel, llvm::ArrayRef< const char * > categories, llvm::StringRef log_file, uint32_t log_options, size_t buffer_size, LogHandlerKind log_handler_kind, llvm::raw_ostream &error_stream)
Definition: Debugger.cpp:1601
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition: FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
void Clear()
Clears the object state.
Definition: FileSpec.cpp:259
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
int Open(const char *path, int flags, int mode=0600)
Wraps ::open in a platform-independent way.
static FileSystem & Instance()
@ eOpenOptionWriteOnly
Definition: File.h:52
@ eOpenOptionCanCreate
Definition: File.h:56
@ eOpenOptionTruncate
Definition: File.h:57
static bool DisableLogChannel(llvm::StringRef channel, llvm::ArrayRef< const char * > categories, llvm::raw_ostream &error_stream)
Definition: Log.cpp:239
static void ListAllLogChannels(llvm::raw_ostream &stream)
Definition: Log.cpp:303
static bool DumpLogChannel(llvm::StringRef channel, llvm::raw_ostream &output_stream, llvm::raw_ostream &error_stream)
Definition: Log.cpp:254
static bool ListChannelCategories(llvm::StringRef channel, llvm::raw_ostream &stream)
Definition: Log.cpp:270
static void DisableAllLogChannels()
Definition: Log.cpp:281
static void ForEachChannelCategory(llvm::StringRef channel, llvm::function_ref< void(llvm::StringRef, llvm::StringRef)> lambda)
Calls the given lambda for every category in the given channel.
Definition: Log.cpp:286
static std::vector< llvm::StringRef > ListChannels()
Returns the list of log channels.
Definition: Log.cpp:296
Status SetValueFromString(llvm::StringRef value, VarSetOperationType op=eVarSetOperationAssign) override
A command line option parsing protocol class.
Definition: Options.h:58
std::vector< Option > m_getopt_table
Definition: Options.h:198
An error handling class.
Definition: Status.h:44
static void ResetCategoryTimes()
Definition: Timer.cpp:130
static void SetQuiet(bool value)
Definition: Timer.cpp:58
static void SetDisplayDepth(uint32_t depth)
Definition: Timer.cpp:111
static void DumpCategoryTimes(Stream &s)
Definition: Timer.cpp:138
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
Definition: lldb-forward.h:325
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeLogCategory
@ eArgTypeLogChannel
Used to build individual command argument lists.
Definition: CommandObject.h:93
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)
#define PATH_MAX