1 //===-- CommandObjectLog.cpp ------------------------------------*- C++ -*-===//
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"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/StreamFile.h"
13 #include "lldb/Host/OptionParser.h"
14 #include "lldb/Interpreter/CommandInterpreter.h"
15 #include "lldb/Interpreter/CommandReturnObject.h"
16 #include "lldb/Interpreter/OptionArgParser.h"
17 #include "lldb/Interpreter/Options.h"
18 #include "lldb/Symbol/LineTable.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolFile.h"
21 #include "lldb/Symbol/SymbolVendor.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Utility/Args.h"
25 #include "lldb/Utility/FileSpec.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/RegularExpression.h"
28 #include "lldb/Utility/Stream.h"
29 #include "lldb/Utility/Timer.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 #define LLDB_OPTIONS_log
35 #include "CommandOptions.inc"
36 
37 /// Common completion logic for log enable/disable.
38 static void CompleteEnableDisable(CompletionRequest &request) {
39   size_t arg_index = request.GetCursorIndex();
40   if (arg_index == 0) { // We got: log enable/disable x[tab]
41     for (llvm::StringRef channel : Log::ListChannels())
42       request.TryCompleteCurrentArg(channel);
43   } else if (arg_index >= 1) { // We got: log enable/disable channel x[tab]
44     llvm::StringRef channel = request.GetParsedLine().GetArgumentAtIndex(0);
45     Log::ForEachChannelCategory(
46         channel, [&request](llvm::StringRef name, llvm::StringRef desc) {
47           request.TryCompleteCurrentArg(name, desc);
48         });
49   }
50 }
51 
52 class CommandObjectLogEnable : public CommandObjectParsed {
53 public:
54   // Constructors and Destructors
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 
85   Options *GetOptions() override { return &m_options; }
86 
87   class CommandOptions : public Options {
88   public:
89     CommandOptions() : Options(), log_file(), log_options(0) {}
90 
91     ~CommandOptions() override = default;
92 
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         llvm_unreachable("Unimplemented option");
132       }
133 
134       return error;
135     }
136 
137     void OptionParsingStarting(ExecutionContext *execution_context) override {
138       log_file.Clear();
139       log_options = 0;
140     }
141 
142     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
143       return llvm::makeArrayRef(g_log_options);
144     }
145 
146     // Instance variables to hold the values for command options.
147 
148     FileSpec log_file;
149     uint32_t log_options;
150   };
151 
152   void
153   HandleArgumentCompletion(CompletionRequest &request,
154                            OptionElementVector &opt_element_vector) override {
155     CompleteEnableDisable(request);
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       result.SetStatus(eReturnStatusFailed);
165       return false;
166     }
167 
168     // Store into a std::string since we're about to shift the channel off.
169     const std::string channel = args[0].ref();
170     args.Shift(); // Shift off the channel
171     char log_file[PATH_MAX];
172     if (m_options.log_file)
173       m_options.log_file.GetPath(log_file, sizeof(log_file));
174     else
175       log_file[0] = '\0';
176 
177     std::string error;
178     llvm::raw_string_ostream error_stream(error);
179     bool success =
180         GetDebugger().EnableLog(channel, args.GetArgumentArrayRef(), log_file,
181                                 m_options.log_options, error_stream);
182     result.GetErrorStream() << error_stream.str();
183 
184     if (success)
185       result.SetStatus(eReturnStatusSuccessFinishNoResult);
186     else
187       result.SetStatus(eReturnStatusFailed);
188     return result.Succeeded();
189   }
190 
191   CommandOptions m_options;
192 };
193 
194 class CommandObjectLogDisable : public CommandObjectParsed {
195 public:
196   // Constructors and Destructors
197   CommandObjectLogDisable(CommandInterpreter &interpreter)
198       : CommandObjectParsed(interpreter, "log disable",
199                             "Disable one or more log channel categories.",
200                             nullptr) {
201     CommandArgumentEntry arg1;
202     CommandArgumentEntry arg2;
203     CommandArgumentData channel_arg;
204     CommandArgumentData category_arg;
205 
206     // Define the first (and only) variant of this arg.
207     channel_arg.arg_type = eArgTypeLogChannel;
208     channel_arg.arg_repetition = eArgRepeatPlain;
209 
210     // There is only one variant this argument could be; put it into the
211     // argument entry.
212     arg1.push_back(channel_arg);
213 
214     category_arg.arg_type = eArgTypeLogCategory;
215     category_arg.arg_repetition = eArgRepeatPlus;
216 
217     arg2.push_back(category_arg);
218 
219     // Push the data for the first argument into the m_arguments vector.
220     m_arguments.push_back(arg1);
221     m_arguments.push_back(arg2);
222   }
223 
224   ~CommandObjectLogDisable() override = default;
225 
226   void
227   HandleArgumentCompletion(CompletionRequest &request,
228                            OptionElementVector &opt_element_vector) override {
229     CompleteEnableDisable(request);
230   }
231 
232 protected:
233   bool DoExecute(Args &args, CommandReturnObject &result) override {
234     if (args.empty()) {
235       result.AppendErrorWithFormat(
236           "%s takes a log channel and one or more log types.\n",
237           m_cmd_name.c_str());
238       result.SetStatus(eReturnStatusFailed);
239       return false;
240     }
241 
242     const std::string channel = args[0].ref();
243     args.Shift(); // Shift off the channel
244     if (channel == "all") {
245       Log::DisableAllLogChannels();
246       result.SetStatus(eReturnStatusSuccessFinishNoResult);
247     } else {
248       std::string error;
249       llvm::raw_string_ostream error_stream(error);
250       if (Log::DisableLogChannel(channel, args.GetArgumentArrayRef(),
251                                  error_stream))
252         result.SetStatus(eReturnStatusSuccessFinishNoResult);
253       result.GetErrorStream() << error_stream.str();
254     }
255     return result.Succeeded();
256   }
257 };
258 
259 class CommandObjectLogList : public CommandObjectParsed {
260 public:
261   // Constructors and Destructors
262   CommandObjectLogList(CommandInterpreter &interpreter)
263       : CommandObjectParsed(interpreter, "log list",
264                             "List the log categories for one or more log "
265                             "channels.  If none specified, lists them all.",
266                             nullptr) {
267     CommandArgumentEntry arg;
268     CommandArgumentData channel_arg;
269 
270     // Define the first (and only) variant of this arg.
271     channel_arg.arg_type = eArgTypeLogChannel;
272     channel_arg.arg_repetition = eArgRepeatStar;
273 
274     // There is only one variant this argument could be; put it into the
275     // argument entry.
276     arg.push_back(channel_arg);
277 
278     // Push the data for the first argument into the m_arguments vector.
279     m_arguments.push_back(arg);
280   }
281 
282   ~CommandObjectLogList() override = default;
283 
284   void
285   HandleArgumentCompletion(CompletionRequest &request,
286                            OptionElementVector &opt_element_vector) override {
287     for (llvm::StringRef channel : Log::ListChannels())
288       request.TryCompleteCurrentArg(channel);
289   }
290 
291 protected:
292   bool DoExecute(Args &args, CommandReturnObject &result) override {
293     std::string output;
294     llvm::raw_string_ostream output_stream(output);
295     if (args.empty()) {
296       Log::ListAllLogChannels(output_stream);
297       result.SetStatus(eReturnStatusSuccessFinishResult);
298     } else {
299       bool success = true;
300       for (const auto &entry : args.entries())
301         success =
302             success && Log::ListChannelCategories(entry.ref(), output_stream);
303       if (success)
304         result.SetStatus(eReturnStatusSuccessFinishResult);
305     }
306     result.GetOutputStream() << output_stream.str();
307     return result.Succeeded();
308   }
309 };
310 
311 class CommandObjectLogTimer : public CommandObjectParsed {
312 public:
313   // Constructors and Destructors
314   CommandObjectLogTimer(CommandInterpreter &interpreter)
315       : CommandObjectParsed(interpreter, "log timers",
316                             "Enable, disable, dump, and reset LLDB internal "
317                             "performance timers.",
318                             "log timers < enable <depth> | disable | dump | "
319                             "increment <bool> | reset >") {}
320 
321   ~CommandObjectLogTimer() override = default;
322 
323 protected:
324   bool DoExecute(Args &args, CommandReturnObject &result) override {
325     result.SetStatus(eReturnStatusFailed);
326 
327     if (args.GetArgumentCount() == 1) {
328       auto sub_command = args[0].ref();
329 
330       if (sub_command.equals_lower("enable")) {
331         Timer::SetDisplayDepth(UINT32_MAX);
332         result.SetStatus(eReturnStatusSuccessFinishNoResult);
333       } else if (sub_command.equals_lower("disable")) {
334         Timer::DumpCategoryTimes(&result.GetOutputStream());
335         Timer::SetDisplayDepth(0);
336         result.SetStatus(eReturnStatusSuccessFinishResult);
337       } else if (sub_command.equals_lower("dump")) {
338         Timer::DumpCategoryTimes(&result.GetOutputStream());
339         result.SetStatus(eReturnStatusSuccessFinishResult);
340       } else if (sub_command.equals_lower("reset")) {
341         Timer::ResetCategoryTimes();
342         result.SetStatus(eReturnStatusSuccessFinishResult);
343       }
344     } else if (args.GetArgumentCount() == 2) {
345       auto sub_command = args[0].ref();
346       auto param = args[1].ref();
347 
348       if (sub_command.equals_lower("enable")) {
349         uint32_t depth;
350         if (param.consumeInteger(0, depth)) {
351           result.AppendError(
352               "Could not convert enable depth to an unsigned integer.");
353         } else {
354           Timer::SetDisplayDepth(depth);
355           result.SetStatus(eReturnStatusSuccessFinishNoResult);
356         }
357       } else if (sub_command.equals_lower("increment")) {
358         bool success;
359         bool increment = OptionArgParser::ToBoolean(param, false, &success);
360         if (success) {
361           Timer::SetQuiet(!increment);
362           result.SetStatus(eReturnStatusSuccessFinishNoResult);
363         } else
364           result.AppendError("Could not convert increment value to boolean.");
365       }
366     }
367 
368     if (!result.Succeeded()) {
369       result.AppendError("Missing subcommand");
370       result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
371     }
372     return result.Succeeded();
373   }
374 };
375 
376 CommandObjectLog::CommandObjectLog(CommandInterpreter &interpreter)
377     : CommandObjectMultiword(interpreter, "log",
378                              "Commands controlling LLDB internal logging.",
379                              "log <subcommand> [<command-options>]") {
380   LoadSubCommand("enable",
381                  CommandObjectSP(new CommandObjectLogEnable(interpreter)));
382   LoadSubCommand("disable",
383                  CommandObjectSP(new CommandObjectLogDisable(interpreter)));
384   LoadSubCommand("list",
385                  CommandObjectSP(new CommandObjectLogList(interpreter)));
386   LoadSubCommand("timers",
387                  CommandObjectSP(new CommandObjectLogTimer(interpreter)));
388 }
389 
390 CommandObjectLog::~CommandObjectLog() = default;
391