]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Commands / CommandObjectLog.cpp
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 OptionDefinition g_log_options[] = {
40     // clang-format off
41   { LLDB_OPT_SET_1, false, "file",       'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Set the destination file to log to." },
42   { LLDB_OPT_SET_1, false, "threadsafe", 't', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,     "Enable thread safe logging to avoid interweaved log lines." },
43   { LLDB_OPT_SET_1, false, "verbose",    'v', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,     "Enable verbose logging." },
44   { LLDB_OPT_SET_1, false, "sequence",   's', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,     "Prepend all log lines with an increasing integer sequence id." },
45   { LLDB_OPT_SET_1, false, "timestamp",  'T', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,     "Prepend all log lines with a timestamp." },
46   { LLDB_OPT_SET_1, false, "pid-tid",    'p', OptionParser::eNoArgument,       nullptr, 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, 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, nullptr, 0, eArgTypeNone,     "Append a stack backtrace to each log line." },
49   { LLDB_OPT_SET_1, false, "append",     'a', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,     "Append to the log file instead of overwriting." },
50   { LLDB_OPT_SET_1, false, "file-function",'F',OptionParser::eNoArgument,      nullptr, 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, true, FileSpec::Style::native);
105         break;
106       case 't':
107         log_options |= LLDB_LOG_OPTION_THREADSAFE;
108         break;
109       case 'v':
110         log_options |= LLDB_LOG_OPTION_VERBOSE;
111         break;
112       case 's':
113         log_options |= LLDB_LOG_OPTION_PREPEND_SEQUENCE;
114         break;
115       case 'T':
116         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP;
117         break;
118       case 'p':
119         log_options |= LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD;
120         break;
121       case 'n':
122         log_options |= LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
123         break;
124       case 'S':
125         log_options |= LLDB_LOG_OPTION_BACKTRACE;
126         break;
127       case 'a':
128         log_options |= LLDB_LOG_OPTION_APPEND;
129         break;
130       case 'F':
131         log_options |= LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION;
132         break;
133       default:
134         error.SetErrorStringWithFormat("unrecognized option '%c'",
135                                        short_option);
136         break;
137       }
138
139       return error;
140     }
141
142     void OptionParsingStarting(ExecutionContext *execution_context) override {
143       log_file.Clear();
144       log_options = 0;
145     }
146
147     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
148       return llvm::makeArrayRef(g_log_options);
149     }
150
151     // Instance variables to hold the values for command options.
152
153     FileSpec log_file;
154     uint32_t log_options;
155   };
156
157 protected:
158   bool DoExecute(Args &args, CommandReturnObject &result) override {
159     if (args.GetArgumentCount() < 2) {
160       result.AppendErrorWithFormat(
161           "%s takes a log channel and one or more log types.\n",
162           m_cmd_name.c_str());
163       return false;
164     }
165
166     // Store into a std::string since we're about to shift the channel off.
167     const std::string channel = args[0].ref;
168     args.Shift(); // Shift off the channel
169     char log_file[PATH_MAX];
170     if (m_options.log_file)
171       m_options.log_file.GetPath(log_file, sizeof(log_file));
172     else
173       log_file[0] = '\0';
174
175     std::string error;
176     llvm::raw_string_ostream error_stream(error);
177     bool success = m_interpreter.GetDebugger().EnableLog(
178         channel, args.GetArgumentArrayRef(), log_file, m_options.log_options,
179         error_stream);
180     result.GetErrorStream() << error_stream.str();
181
182     if (success)
183       result.SetStatus(eReturnStatusSuccessFinishNoResult);
184     else
185       result.SetStatus(eReturnStatusFailed);
186     return result.Succeeded();
187   }
188
189   CommandOptions m_options;
190 };
191
192 class CommandObjectLogDisable : public CommandObjectParsed {
193 public:
194   //------------------------------------------------------------------
195   // Constructors and Destructors
196   //------------------------------------------------------------------
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 protected:
227   bool DoExecute(Args &args, CommandReturnObject &result) override {
228     if (args.empty()) {
229       result.AppendErrorWithFormat(
230           "%s takes a log channel and one or more log types.\n",
231           m_cmd_name.c_str());
232       return false;
233     }
234
235     const std::string channel = args[0].ref;
236     args.Shift(); // Shift off the channel
237     if (channel == "all") {
238       Log::DisableAllLogChannels();
239       result.SetStatus(eReturnStatusSuccessFinishNoResult);
240     } else {
241       std::string error;
242       llvm::raw_string_ostream error_stream(error);
243       if (Log::DisableLogChannel(channel, args.GetArgumentArrayRef(),
244                                  error_stream))
245         result.SetStatus(eReturnStatusSuccessFinishNoResult);
246       result.GetErrorStream() << error_stream.str();
247     }
248     return result.Succeeded();
249   }
250 };
251
252 class CommandObjectLogList : public CommandObjectParsed {
253 public:
254   //------------------------------------------------------------------
255   // Constructors and Destructors
256   //------------------------------------------------------------------
257   CommandObjectLogList(CommandInterpreter &interpreter)
258       : CommandObjectParsed(interpreter, "log list",
259                             "List the log categories for one or more log "
260                             "channels.  If none specified, lists them all.",
261                             nullptr) {
262     CommandArgumentEntry arg;
263     CommandArgumentData channel_arg;
264
265     // Define the first (and only) variant of this arg.
266     channel_arg.arg_type = eArgTypeLogChannel;
267     channel_arg.arg_repetition = eArgRepeatStar;
268
269     // There is only one variant this argument could be; put it into the
270     // argument entry.
271     arg.push_back(channel_arg);
272
273     // Push the data for the first argument into the m_arguments vector.
274     m_arguments.push_back(arg);
275   }
276
277   ~CommandObjectLogList() override = default;
278
279 protected:
280   bool DoExecute(Args &args, CommandReturnObject &result) override {
281     std::string output;
282     llvm::raw_string_ostream output_stream(output);
283     if (args.empty()) {
284       Log::ListAllLogChannels(output_stream);
285       result.SetStatus(eReturnStatusSuccessFinishResult);
286     } else {
287       bool success = true;
288       for (const auto &entry : args.entries())
289         success =
290             success && Log::ListChannelCategories(entry.ref, output_stream);
291       if (success)
292         result.SetStatus(eReturnStatusSuccessFinishResult);
293     }
294     result.GetOutputStream() << output_stream.str();
295     return result.Succeeded();
296   }
297 };
298
299 class CommandObjectLogTimer : public CommandObjectParsed {
300 public:
301   //------------------------------------------------------------------
302   // Constructors and Destructors
303   //------------------------------------------------------------------
304   CommandObjectLogTimer(CommandInterpreter &interpreter)
305       : CommandObjectParsed(interpreter, "log timers",
306                             "Enable, disable, dump, and reset LLDB internal "
307                             "performance timers.",
308                             "log timers < enable <depth> | disable | dump | "
309                             "increment <bool> | reset >") {}
310
311   ~CommandObjectLogTimer() override = default;
312
313 protected:
314   bool DoExecute(Args &args, CommandReturnObject &result) override {
315     result.SetStatus(eReturnStatusFailed);
316
317     if (args.GetArgumentCount() == 1) {
318       auto sub_command = args[0].ref;
319
320       if (sub_command.equals_lower("enable")) {
321         Timer::SetDisplayDepth(UINT32_MAX);
322         result.SetStatus(eReturnStatusSuccessFinishNoResult);
323       } else if (sub_command.equals_lower("disable")) {
324         Timer::DumpCategoryTimes(&result.GetOutputStream());
325         Timer::SetDisplayDepth(0);
326         result.SetStatus(eReturnStatusSuccessFinishResult);
327       } else if (sub_command.equals_lower("dump")) {
328         Timer::DumpCategoryTimes(&result.GetOutputStream());
329         result.SetStatus(eReturnStatusSuccessFinishResult);
330       } else if (sub_command.equals_lower("reset")) {
331         Timer::ResetCategoryTimes();
332         result.SetStatus(eReturnStatusSuccessFinishResult);
333       }
334     } else if (args.GetArgumentCount() == 2) {
335       auto sub_command = args[0].ref;
336       auto param = args[1].ref;
337
338       if (sub_command.equals_lower("enable")) {
339         uint32_t depth;
340         if (param.consumeInteger(0, depth)) {
341           result.AppendError(
342               "Could not convert enable depth to an unsigned integer.");
343         } else {
344           Timer::SetDisplayDepth(depth);
345           result.SetStatus(eReturnStatusSuccessFinishNoResult);
346         }
347       } else if (sub_command.equals_lower("increment")) {
348         bool success;
349         bool increment = OptionArgParser::ToBoolean(param, false, &success);
350         if (success) {
351           Timer::SetQuiet(!increment);
352           result.SetStatus(eReturnStatusSuccessFinishNoResult);
353         } else
354           result.AppendError("Could not convert increment value to boolean.");
355       }
356     }
357
358     if (!result.Succeeded()) {
359       result.AppendError("Missing subcommand");
360       result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
361     }
362     return result.Succeeded();
363   }
364 };
365
366 CommandObjectLog::CommandObjectLog(CommandInterpreter &interpreter)
367     : CommandObjectMultiword(interpreter, "log",
368                              "Commands controlling LLDB internal logging.",
369                              "log <subcommand> [<command-options>]") {
370   LoadSubCommand("enable",
371                  CommandObjectSP(new CommandObjectLogEnable(interpreter)));
372   LoadSubCommand("disable",
373                  CommandObjectSP(new CommandObjectLogDisable(interpreter)));
374   LoadSubCommand("list",
375                  CommandObjectSP(new CommandObjectLogList(interpreter)));
376   LoadSubCommand("timers",
377                  CommandObjectSP(new CommandObjectLogTimer(interpreter)));
378 }
379
380 CommandObjectLog::~CommandObjectLog() = default;