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