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())
103 "unrecognized value for log handler '{0}'", option_arg);
104 break;
105 case 'b':
106 return buffer_size.SetValueFromString(option_arg,
108 case 'v':
110 break;
111 case 's':
113 break;
114 case 'T':
116 break;
117 case 'p':
119 break;
120 case 'n':
122 break;
123 case 'S':
125 break;
126 case 'a':
128 break;
129 case 'F':
131 break;
132 default:
133 llvm_unreachable("Unimplemented option");
134 }
135
136 return error;
137 }
138
139 void OptionParsingStarting(ExecutionContext *execution_context) override {
140 log_file.Clear();
141 buffer_size.Clear();
143 log_options = 0;
144 }
145
146 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
147 return llvm::ArrayRef(g_log_enable_options);
148 }
149
153 uint32_t log_options = 0;
154 };
155
156 void
158 OptionElementVector &opt_element_vector) override {
159 CompleteEnableDisable(request);
160 }
161
162protected:
163 void DoExecute(Args &args, CommandReturnObject &result) override {
164 if (args.GetArgumentCount() < 2) {
166 "%s takes a log channel and one or more log types.\n",
167 m_cmd_name.c_str());
168 return;
169 }
170
171 if (m_options.handler == eLogHandlerCircular &&
172 m_options.buffer_size.GetCurrentValue() == 0) {
173 result.AppendError(
174 "the circular buffer handler requires a non-zero buffer size.\n");
175 return;
176 }
177
178 if ((m_options.handler != eLogHandlerCircular &&
179 m_options.handler != eLogHandlerStream) &&
180 m_options.buffer_size.GetCurrentValue() != 0) {
181 result.AppendError("a buffer size can only be specified for the circular "
182 "and stream buffer handler.\n");
183 return;
184 }
185
186 if (m_options.handler != eLogHandlerStream && m_options.log_file) {
187 result.AppendError(
188 "a file name can only be specified for the stream handler.\n");
189 return;
190 }
191
192 // Store into a std::string since we're about to shift the channel off.
193 const std::string channel = std::string(args[0].ref());
194 args.Shift(); // Shift off the channel
195 char log_file[PATH_MAX];
196 if (m_options.log_file)
197 m_options.log_file.GetPath(log_file, sizeof(log_file));
198 else
199 log_file[0] = '\0';
200
201 std::string error;
202 llvm::raw_string_ostream error_stream(error);
203 bool success = GetDebugger().EnableLog(
204 channel, args.GetArgumentArrayRef(), log_file, m_options.log_options,
205 m_options.buffer_size.GetCurrentValue(), m_options.handler,
206 error_stream);
207 result.GetErrorStream() << error;
208
209 if (success)
211 else
213 }
214
216};
217
219public:
220 // Constructors and Destructors
222 : CommandObjectParsed(interpreter, "log disable",
223 "Disable one or more log channel categories.",
224 nullptr) {
227 CommandArgumentData channel_arg;
228 CommandArgumentData category_arg;
229
230 // Define the first (and only) variant of this arg.
231 channel_arg.arg_type = eArgTypeLogChannel;
232 channel_arg.arg_repetition = eArgRepeatPlain;
233
234 // There is only one variant this argument could be; put it into the
235 // argument entry.
236 arg1.push_back(channel_arg);
237
238 category_arg.arg_type = eArgTypeLogCategory;
239 category_arg.arg_repetition = eArgRepeatPlus;
240
241 arg2.push_back(category_arg);
242
243 // Push the data for the first argument into the m_arguments vector.
244 m_arguments.push_back(arg1);
245 m_arguments.push_back(arg2);
246 }
247
248 ~CommandObjectLogDisable() override = default;
249
250 void
252 OptionElementVector &opt_element_vector) override {
253 CompleteEnableDisable(request);
254 }
255
256protected:
257 void DoExecute(Args &args, CommandReturnObject &result) override {
258 if (args.empty()) {
260 "%s takes a log channel and one or more log types.\n",
261 m_cmd_name.c_str());
262 return;
263 }
264
265 const std::string channel = std::string(args[0].ref());
266 args.Shift(); // Shift off the channel
267 if (channel == "all") {
270 } else {
271 std::string error;
272 llvm::raw_string_ostream error_stream(error);
274 error_stream))
276 result.GetErrorStream() << error;
277 }
278 }
279};
280
282public:
283 // Constructors and Destructors
285 : CommandObjectParsed(interpreter, "log list",
286 "List the log categories for one or more log "
287 "channels. If none specified, lists them all.",
288 nullptr) {
290 }
291
292 ~CommandObjectLogList() override = default;
293
294 void
296 OptionElementVector &opt_element_vector) override {
297 for (llvm::StringRef channel : Log::ListChannels())
298 request.TryCompleteCurrentArg(channel);
299 }
300
301protected:
302 void DoExecute(Args &args, CommandReturnObject &result) override {
303 std::string output;
304 llvm::raw_string_ostream output_stream(output);
305 if (args.empty()) {
306 Log::ListAllLogChannels(output_stream);
308 } else {
309 bool success = true;
310 for (const auto &entry : args.entries())
311 success =
312 success && Log::ListChannelCategories(entry.ref(), output_stream);
313 if (success)
315 }
316 result.GetOutputStream() << output;
317 }
318};
320public:
322 : CommandObjectParsed(interpreter, "log dump",
323 "dump circular buffer logs", nullptr) {
325 }
326
327 ~CommandObjectLogDump() override = default;
328
329 Options *GetOptions() override { return &m_options; }
330
331 class CommandOptions : public Options {
332 public:
333 CommandOptions() = default;
334
335 ~CommandOptions() override = default;
336
337 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
338 ExecutionContext *execution_context) override {
340 const int short_option = m_getopt_table[option_idx].val;
341
342 switch (short_option) {
343 case 'f':
344 log_file.SetFile(option_arg, FileSpec::Style::native);
346 break;
347 default:
348 llvm_unreachable("Unimplemented option");
349 }
350
351 return error;
352 }
353
354 void OptionParsingStarting(ExecutionContext *execution_context) override {
355 log_file.Clear();
356 }
357
358 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
359 return llvm::ArrayRef(g_log_dump_options);
360 }
361
363 };
364
365 void
367 OptionElementVector &opt_element_vector) override {
368 CompleteEnableDisable(request);
369 }
370
371protected:
372 void DoExecute(Args &args, CommandReturnObject &result) override {
373 if (args.empty()) {
375 "%s takes a log channel and one or more log types.\n",
376 m_cmd_name.c_str());
377 return;
378 }
379
380 std::unique_ptr<llvm::raw_ostream> stream_up;
381 if (m_options.log_file) {
385 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
386 m_options.log_file, flags, lldb::eFilePermissionsFileDefault, false);
387 if (!file) {
388 result.AppendErrorWithFormat("Unable to open log file '%s': %s",
389 m_options.log_file.GetPath().c_str(),
390 llvm::toString(file.takeError()).c_str());
391 return;
392 }
393 stream_up = std::make_unique<llvm::raw_fd_ostream>(
394 (*file)->GetDescriptor(), /*shouldClose=*/true);
395 } else {
396 stream_up = std::make_unique<llvm::raw_fd_ostream>(
397 GetDebugger().GetOutputFileSP()->GetDescriptor(),
398 /*shouldClose=*/false);
399 }
400
401 const std::string channel = std::string(args[0].ref());
402 std::string error;
403 llvm::raw_string_ostream error_stream(error);
404 if (Log::DumpLogChannel(channel, *stream_up, error_stream)) {
406 } else {
408 result.GetErrorStream() << error;
409 }
410 }
411
413};
414
416public:
417 // Constructors and Destructors
419 : CommandObjectParsed(interpreter, "log timers enable",
420 "enable LLDB internal performance timers",
421 "log timers enable <depth>") {
423 }
424
425 ~CommandObjectLogTimerEnable() override = default;
426
427protected:
428 void DoExecute(Args &args, CommandReturnObject &result) override {
430
431 if (args.GetArgumentCount() == 0) {
434 } else if (args.GetArgumentCount() == 1) {
435 uint32_t depth;
436 if (args[0].ref().consumeInteger(0, depth)) {
437 result.AppendError(
438 "Could not convert enable depth to an unsigned integer.");
439 } else {
442 }
443 }
444
445 if (!result.Succeeded()) {
446 result.AppendError("Missing subcommand");
447 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
448 }
449 }
450};
451
453public:
454 // Constructors and Destructors
456 : CommandObjectParsed(interpreter, "log timers disable",
457 "disable LLDB internal performance timers",
458 nullptr) {}
459
460 ~CommandObjectLogTimerDisable() override = default;
461
462protected:
463 void DoExecute(Args &args, CommandReturnObject &result) override {
467
468 if (!result.Succeeded()) {
469 result.AppendError("Missing subcommand");
470 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
471 }
472 }
473};
474
476public:
477 // Constructors and Destructors
479 : CommandObjectParsed(interpreter, "log timers dump",
480 "dump LLDB internal performance timers", nullptr) {}
481
482 ~CommandObjectLogTimerDump() override = default;
483
484protected:
485 void DoExecute(Args &args, CommandReturnObject &result) override {
488
489 if (!result.Succeeded()) {
490 result.AppendError("Missing subcommand");
491 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
492 }
493 }
494};
495
497public:
498 // Constructors and Destructors
500 : CommandObjectParsed(interpreter, "log timers reset",
501 "reset LLDB internal performance timers", nullptr) {
502 }
503
504 ~CommandObjectLogTimerReset() override = default;
505
506protected:
507 void DoExecute(Args &args, CommandReturnObject &result) override {
510
511 if (!result.Succeeded()) {
512 result.AppendError("Missing subcommand");
513 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
514 }
515 }
516};
517
519public:
520 // Constructors and Destructors
522 : CommandObjectParsed(interpreter, "log timers increment",
523 "increment LLDB internal performance timers",
524 "log timers increment <bool>") {
526 }
527
529
530 void
532 OptionElementVector &opt_element_vector) override {
533 request.TryCompleteCurrentArg("true");
534 request.TryCompleteCurrentArg("false");
535 }
536
537protected:
538 void DoExecute(Args &args, CommandReturnObject &result) override {
540
541 if (args.GetArgumentCount() == 1) {
542 bool success;
543 bool increment =
544 OptionArgParser::ToBoolean(args[0].ref(), false, &success);
545
546 if (success) {
547 Timer::SetQuiet(!increment);
549 } else
550 result.AppendError("could not convert increment value to boolean");
551 }
552
553 if (!result.Succeeded()) {
554 result.AppendError("Missing subcommand");
555 result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
556 }
557 }
558};
559
561public:
563 : CommandObjectMultiword(interpreter, "log timers",
564 "Enable, disable, dump, and reset LLDB internal "
565 "performance timers.",
566 "log timers < enable <depth> | disable | dump | "
567 "increment <bool> | reset >") {
569 new CommandObjectLogTimerEnable(interpreter)));
571 interpreter)));
572 LoadSubCommand("dump",
575 "reset", CommandObjectSP(new CommandObjectLogTimerReset(interpreter)));
577 "increment",
579 }
580
581 ~CommandObjectLogTimer() override = default;
582};
583
585 : CommandObjectMultiword(interpreter, "log",
586 "Commands controlling LLDB internal logging.",
587 "log <subcommand> [<command-options>]") {
588 LoadSubCommand("enable",
589 CommandObjectSP(new CommandObjectLogEnable(interpreter)));
590 LoadSubCommand("disable",
591 CommandObjectSP(new CommandObjectLogDisable(interpreter)));
592 LoadSubCommand("list",
593 CommandObjectSP(new CommandObjectLogList(interpreter)));
594 LoadSubCommand("dump",
595 CommandObjectSP(new CommandObjectLogDump(interpreter)));
596 LoadSubCommand("timers",
597 CommandObjectSP(new CommandObjectLogTimer(interpreter)));
598}
599
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:173
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition Args.cpp:295
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool empty() const
Definition Args.h:122
CommandObjectLog(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
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"
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)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
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:251
static void ListAllLogChannels(llvm::raw_ostream &stream)
Definition Log.cpp:316
static bool DumpLogChannel(llvm::StringRef channel, llvm::raw_ostream &output_stream, llvm::raw_ostream &error_stream)
Definition Log.cpp:267
static bool ListChannelCategories(llvm::StringRef channel, llvm::raw_ostream &stream)
Definition Log.cpp:283
static void DisableAllLogChannels()
Definition Log.cpp:294
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:299
static std::vector< llvm::StringRef > ListChannels()
Returns the list of log channels.
Definition Log.cpp:309
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:118
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
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
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeLogCategory
Used to build individual command argument lists.
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