1 //===-- CommandObjectLog.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "CommandObjectLog.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/StreamFile.h"
14 #include "lldb/Host/OptionParser.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/CommandReturnObject.h"
17 #include "lldb/Interpreter/OptionArgParser.h"
18 #include "lldb/Interpreter/Options.h"
19 #include "lldb/Symbol/LineTable.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/SymbolFile.h"
22 #include "lldb/Symbol/SymbolVendor.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/Args.h"
26 #include "lldb/Utility/FileSpec.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/RegularExpression.h"
29 #include "lldb/Utility/Stream.h"
30 #include "lldb/Utility/Timer.h"
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 static constexpr OptionDefinition g_log_options[] = {
36     // clang-format off
37   { LLDB_OPT_SET_1, false, "file",       'f', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFilename, "Set the destination file to log to." },
38   { LLDB_OPT_SET_1, false, "threadsafe", 't', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Enable thread safe logging to avoid interweaved log lines." },
39   { LLDB_OPT_SET_1, false, "verbose",    'v', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Enable verbose logging." },
40   { LLDB_OPT_SET_1, false, "sequence",   's', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Prepend all log lines with an increasing integer sequence id." },
41   { LLDB_OPT_SET_1, false, "timestamp",  'T', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Prepend all log lines with a timestamp." },
42   { LLDB_OPT_SET_1, false, "pid-tid",    'p', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Prepend all log lines with the process and thread ID that generates the log line." },
43   { LLDB_OPT_SET_1, false, "thread-name",'n', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Prepend all log lines with the thread name for the thread that generates the log line." },
44   { LLDB_OPT_SET_1, false, "stack",      'S', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Append a stack backtrace to each log line." },
45   { LLDB_OPT_SET_1, false, "append",     'a', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeNone,     "Append to the log file instead of overwriting." },
46   { LLDB_OPT_SET_1, false, "file-function",'F',OptionParser::eNoArgument,      nullptr, {}, 0, eArgTypeNone,     "Prepend the names of files and function that generate the logs." },
47     // clang-format on
48 };
49 
50 class CommandObjectLogEnable : public CommandObjectParsed {
51 public:
52   //------------------------------------------------------------------
53   // Constructors and Destructors
54   //------------------------------------------------------------------
CommandObjectLogEnable(CommandInterpreter & interpreter)55   CommandObjectLogEnable(CommandInterpreter &interpreter)
56       : CommandObjectParsed(interpreter, "log enable",
57                             "Enable logging for a single log channel.",
58                             nullptr),
59         m_options() {
60     CommandArgumentEntry arg1;
61     CommandArgumentEntry arg2;
62     CommandArgumentData channel_arg;
63     CommandArgumentData category_arg;
64 
65     // Define the first (and only) variant of this arg.
66     channel_arg.arg_type = eArgTypeLogChannel;
67     channel_arg.arg_repetition = eArgRepeatPlain;
68 
69     // There is only one variant this argument could be; put it into the
70     // argument entry.
71     arg1.push_back(channel_arg);
72 
73     category_arg.arg_type = eArgTypeLogCategory;
74     category_arg.arg_repetition = eArgRepeatPlus;
75 
76     arg2.push_back(category_arg);
77 
78     // Push the data for the first argument into the m_arguments vector.
79     m_arguments.push_back(arg1);
80     m_arguments.push_back(arg2);
81   }
82 
83   ~CommandObjectLogEnable() override = default;
84 
GetOptions()85   Options *GetOptions() override { return &m_options; }
86 
87   class CommandOptions : public Options {
88   public:
CommandOptions()89     CommandOptions() : Options(), log_file(), log_options(0) {}
90 
91     ~CommandOptions() override = default;
92 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)93     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
94                           ExecutionContext *execution_context) override {
95       Status error;
96       const int short_option = m_getopt_table[option_idx].val;
97 
98       switch (short_option) {
99       case 'f':
100         log_file.SetFile(option_arg, FileSpec::Style::native);
101         FileSystem::Instance().Resolve(log_file);
102         break;
103       case 't':
104         log_options |= LLDB_LOG_OPTION_THREADSAFE;
105         break;
106       case 'v':
107         log_options |= LLDB_LOG_OPTION_VERBOSE;
108         break;
109       case 's':
110         log_options |= LLDB_LOG_OPTION_PREPEND_SEQUENCE;
111         break;
112       case 'T':
113         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP;
114         break;
115       case 'p':
116         log_options |= LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD;
117         break;
118       case 'n':
119         log_options |= LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
120         break;
121       case 'S':
122         log_options |= LLDB_LOG_OPTION_BACKTRACE;
123         break;
124       case 'a':
125         log_options |= LLDB_LOG_OPTION_APPEND;
126         break;
127       case 'F':
128         log_options |= LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION;
129         break;
130       default:
131         error.SetErrorStringWithFormat("unrecognized option '%c'",
132                                        short_option);
133         break;
134       }
135 
136       return error;
137     }
138 
OptionParsingStarting(ExecutionContext * execution_context)139     void OptionParsingStarting(ExecutionContext *execution_context) override {
140       log_file.Clear();
141       log_options = 0;
142     }
143 
GetDefinitions()144     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
145       return llvm::makeArrayRef(g_log_options);
146     }
147 
148     // Instance variables to hold the values for command options.
149 
150     FileSpec log_file;
151     uint32_t log_options;
152   };
153 
154 protected:
DoExecute(Args & args,CommandReturnObject & result)155   bool DoExecute(Args &args, CommandReturnObject &result) override {
156     if (args.GetArgumentCount() < 2) {
157       result.AppendErrorWithFormat(
158           "%s takes a log channel and one or more log types.\n",
159           m_cmd_name.c_str());
160       return false;
161     }
162 
163     // Store into a std::string since we're about to shift the channel off.
164     const std::string channel = args[0].ref;
165     args.Shift(); // Shift off the channel
166     char log_file[PATH_MAX];
167     if (m_options.log_file)
168       m_options.log_file.GetPath(log_file, sizeof(log_file));
169     else
170       log_file[0] = '\0';
171 
172     std::string error;
173     llvm::raw_string_ostream error_stream(error);
174     bool success = m_interpreter.GetDebugger().EnableLog(
175         channel, args.GetArgumentArrayRef(), log_file, m_options.log_options,
176         error_stream);
177     result.GetErrorStream() << error_stream.str();
178 
179     if (success)
180       result.SetStatus(eReturnStatusSuccessFinishNoResult);
181     else
182       result.SetStatus(eReturnStatusFailed);
183     return result.Succeeded();
184   }
185 
186   CommandOptions m_options;
187 };
188 
189 class CommandObjectLogDisable : public CommandObjectParsed {
190 public:
191   //------------------------------------------------------------------
192   // Constructors and Destructors
193   //------------------------------------------------------------------
CommandObjectLogDisable(CommandInterpreter & interpreter)194   CommandObjectLogDisable(CommandInterpreter &interpreter)
195       : CommandObjectParsed(interpreter, "log disable",
196                             "Disable one or more log channel categories.",
197                             nullptr) {
198     CommandArgumentEntry arg1;
199     CommandArgumentEntry arg2;
200     CommandArgumentData channel_arg;
201     CommandArgumentData category_arg;
202 
203     // Define the first (and only) variant of this arg.
204     channel_arg.arg_type = eArgTypeLogChannel;
205     channel_arg.arg_repetition = eArgRepeatPlain;
206 
207     // There is only one variant this argument could be; put it into the
208     // argument entry.
209     arg1.push_back(channel_arg);
210 
211     category_arg.arg_type = eArgTypeLogCategory;
212     category_arg.arg_repetition = eArgRepeatPlus;
213 
214     arg2.push_back(category_arg);
215 
216     // Push the data for the first argument into the m_arguments vector.
217     m_arguments.push_back(arg1);
218     m_arguments.push_back(arg2);
219   }
220 
221   ~CommandObjectLogDisable() override = default;
222 
223 protected:
DoExecute(Args & args,CommandReturnObject & result)224   bool DoExecute(Args &args, CommandReturnObject &result) override {
225     if (args.empty()) {
226       result.AppendErrorWithFormat(
227           "%s takes a log channel and one or more log types.\n",
228           m_cmd_name.c_str());
229       return false;
230     }
231 
232     const std::string channel = args[0].ref;
233     args.Shift(); // Shift off the channel
234     if (channel == "all") {
235       Log::DisableAllLogChannels();
236       result.SetStatus(eReturnStatusSuccessFinishNoResult);
237     } else {
238       std::string error;
239       llvm::raw_string_ostream error_stream(error);
240       if (Log::DisableLogChannel(channel, args.GetArgumentArrayRef(),
241                                  error_stream))
242         result.SetStatus(eReturnStatusSuccessFinishNoResult);
243       result.GetErrorStream() << error_stream.str();
244     }
245     return result.Succeeded();
246   }
247 };
248 
249 class CommandObjectLogList : public CommandObjectParsed {
250 public:
251   //------------------------------------------------------------------
252   // Constructors and Destructors
253   //------------------------------------------------------------------
CommandObjectLogList(CommandInterpreter & interpreter)254   CommandObjectLogList(CommandInterpreter &interpreter)
255       : CommandObjectParsed(interpreter, "log list",
256                             "List the log categories for one or more log "
257                             "channels.  If none specified, lists them all.",
258                             nullptr) {
259     CommandArgumentEntry arg;
260     CommandArgumentData channel_arg;
261 
262     // Define the first (and only) variant of this arg.
263     channel_arg.arg_type = eArgTypeLogChannel;
264     channel_arg.arg_repetition = eArgRepeatStar;
265 
266     // There is only one variant this argument could be; put it into the
267     // argument entry.
268     arg.push_back(channel_arg);
269 
270     // Push the data for the first argument into the m_arguments vector.
271     m_arguments.push_back(arg);
272   }
273 
274   ~CommandObjectLogList() override = default;
275 
276 protected:
DoExecute(Args & args,CommandReturnObject & result)277   bool DoExecute(Args &args, CommandReturnObject &result) override {
278     std::string output;
279     llvm::raw_string_ostream output_stream(output);
280     if (args.empty()) {
281       Log::ListAllLogChannels(output_stream);
282       result.SetStatus(eReturnStatusSuccessFinishResult);
283     } else {
284       bool success = true;
285       for (const auto &entry : args.entries())
286         success =
287             success && Log::ListChannelCategories(entry.ref, output_stream);
288       if (success)
289         result.SetStatus(eReturnStatusSuccessFinishResult);
290     }
291     result.GetOutputStream() << output_stream.str();
292     return result.Succeeded();
293   }
294 };
295 
296 class CommandObjectLogTimer : public CommandObjectParsed {
297 public:
298   //------------------------------------------------------------------
299   // Constructors and Destructors
300   //------------------------------------------------------------------
CommandObjectLogTimer(CommandInterpreter & interpreter)301   CommandObjectLogTimer(CommandInterpreter &interpreter)
302       : CommandObjectParsed(interpreter, "log timers",
303                             "Enable, disable, dump, and reset LLDB internal "
304                             "performance timers.",
305                             "log timers < enable <depth> | disable | dump | "
306                             "increment <bool> | reset >") {}
307 
308   ~CommandObjectLogTimer() override = default;
309 
310 protected:
DoExecute(Args & args,CommandReturnObject & result)311   bool DoExecute(Args &args, CommandReturnObject &result) override {
312     result.SetStatus(eReturnStatusFailed);
313 
314     if (args.GetArgumentCount() == 1) {
315       auto sub_command = args[0].ref;
316 
317       if (sub_command.equals_lower("enable")) {
318         Timer::SetDisplayDepth(UINT32_MAX);
319         result.SetStatus(eReturnStatusSuccessFinishNoResult);
320       } else if (sub_command.equals_lower("disable")) {
321         Timer::DumpCategoryTimes(&result.GetOutputStream());
322         Timer::SetDisplayDepth(0);
323         result.SetStatus(eReturnStatusSuccessFinishResult);
324       } else if (sub_command.equals_lower("dump")) {
325         Timer::DumpCategoryTimes(&result.GetOutputStream());
326         result.SetStatus(eReturnStatusSuccessFinishResult);
327       } else if (sub_command.equals_lower("reset")) {
328         Timer::ResetCategoryTimes();
329         result.SetStatus(eReturnStatusSuccessFinishResult);
330       }
331     } else if (args.GetArgumentCount() == 2) {
332       auto sub_command = args[0].ref;
333       auto param = args[1].ref;
334 
335       if (sub_command.equals_lower("enable")) {
336         uint32_t depth;
337         if (param.consumeInteger(0, depth)) {
338           result.AppendError(
339               "Could not convert enable depth to an unsigned integer.");
340         } else {
341           Timer::SetDisplayDepth(depth);
342           result.SetStatus(eReturnStatusSuccessFinishNoResult);
343         }
344       } else if (sub_command.equals_lower("increment")) {
345         bool success;
346         bool increment = OptionArgParser::ToBoolean(param, false, &success);
347         if (success) {
348           Timer::SetQuiet(!increment);
349           result.SetStatus(eReturnStatusSuccessFinishNoResult);
350         } else
351           result.AppendError("Could not convert increment value to boolean.");
352       }
353     }
354 
355     if (!result.Succeeded()) {
356       result.AppendError("Missing subcommand");
357       result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
358     }
359     return result.Succeeded();
360   }
361 };
362 
CommandObjectLog(CommandInterpreter & interpreter)363 CommandObjectLog::CommandObjectLog(CommandInterpreter &interpreter)
364     : CommandObjectMultiword(interpreter, "log",
365                              "Commands controlling LLDB internal logging.",
366                              "log <subcommand> [<command-options>]") {
367   LoadSubCommand("enable",
368                  CommandObjectSP(new CommandObjectLogEnable(interpreter)));
369   LoadSubCommand("disable",
370                  CommandObjectSP(new CommandObjectLogDisable(interpreter)));
371   LoadSubCommand("list",
372                  CommandObjectSP(new CommandObjectLogList(interpreter)));
373   LoadSubCommand("timers",
374                  CommandObjectSP(new CommandObjectLogTimer(interpreter)));
375 }
376 
377 CommandObjectLog::~CommandObjectLog() = default;
378