xref: /llvm-project/lldb/source/Commands/CommandObjectLog.cpp (revision e1cfbc79420fee0b71bad62f8d413b68a0eca91e)
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/Interpreter/Args.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Host/FileSpec.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Interpreter/Options.h"
21 #include "lldb/Core/RegularExpression.h"
22 #include "lldb/Core/Stream.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Core/Timer.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Host/StringConvert.h"
27 #include "lldb/Interpreter/CommandInterpreter.h"
28 #include "lldb/Interpreter/CommandReturnObject.h"
29 #include "lldb/Symbol/LineTable.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Symbol/SymbolFile.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/Target.h"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 class CommandObjectLogEnable : public CommandObjectParsed
40 {
41 public:
42     //------------------------------------------------------------------
43     // Constructors and Destructors
44     //------------------------------------------------------------------
45     CommandObjectLogEnable(CommandInterpreter &interpreter) :
46         CommandObjectParsed(interpreter,
47                             "log enable",
48                             "Enable logging for a single log channel.",
49                             nullptr),
50         m_options()
51     {
52         CommandArgumentEntry arg1;
53         CommandArgumentEntry arg2;
54         CommandArgumentData channel_arg;
55         CommandArgumentData category_arg;
56 
57         // Define the first (and only) variant of this arg.
58         channel_arg.arg_type = eArgTypeLogChannel;
59         channel_arg.arg_repetition = eArgRepeatPlain;
60 
61         // There is only one variant this argument could be; put it into the argument entry.
62         arg1.push_back (channel_arg);
63 
64         category_arg.arg_type = eArgTypeLogCategory;
65         category_arg.arg_repetition = eArgRepeatPlus;
66 
67         arg2.push_back (category_arg);
68 
69         // Push the data for the first argument into the m_arguments vector.
70         m_arguments.push_back (arg1);
71         m_arguments.push_back (arg2);
72     }
73 
74     ~CommandObjectLogEnable() override = default;
75 
76     Options *
77     GetOptions () override
78     {
79         return &m_options;
80     }
81 
82 //    int
83 //    HandleArgumentCompletion (Args &input,
84 //                              int &cursor_index,
85 //                              int &cursor_char_position,
86 //                              OptionElementVector &opt_element_vector,
87 //                              int match_start_point,
88 //                              int max_return_elements,
89 //                              bool &word_complete,
90 //                              StringList &matches)
91 //    {
92 //        std::string completion_str (input.GetArgumentAtIndex(cursor_index));
93 //        completion_str.erase (cursor_char_position);
94 //
95 //        if (cursor_index == 1)
96 //        {
97 //            //
98 //            Log::AutoCompleteChannelName (completion_str.c_str(), matches);
99 //        }
100 //        return matches.GetSize();
101 //    }
102 //
103 
104     class CommandOptions : public Options
105     {
106     public:
107         CommandOptions() :
108             Options(),
109             log_file(),
110             log_options(0)
111         {
112         }
113 
114         ~CommandOptions () override = default;
115 
116         Error
117         SetOptionValue (uint32_t option_idx, const char *option_arg,
118                         ExecutionContext *execution_context) override
119         {
120             Error error;
121             const int short_option = m_getopt_table[option_idx].val;
122 
123             switch (short_option)
124             {
125             case 'f':  log_file.SetFile(option_arg, true);                    break;
126             case 't':  log_options |= LLDB_LOG_OPTION_THREADSAFE;             break;
127             case 'v':  log_options |= LLDB_LOG_OPTION_VERBOSE;                break;
128             case 'g':  log_options |= LLDB_LOG_OPTION_DEBUG;                  break;
129             case 's':  log_options |= LLDB_LOG_OPTION_PREPEND_SEQUENCE;       break;
130             case 'T':  log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP;      break;
131             case 'p':  log_options |= LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD;break;
132             case 'n':  log_options |= LLDB_LOG_OPTION_PREPEND_THREAD_NAME;    break;
133             case 'S':  log_options |= LLDB_LOG_OPTION_BACKTRACE;              break;
134             case 'a':  log_options |= LLDB_LOG_OPTION_APPEND;                 break;
135             default:
136                 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
137                 break;
138             }
139 
140             return error;
141         }
142 
143         void
144         OptionParsingStarting(ExecutionContext *execution_context) override
145         {
146             log_file.Clear();
147             log_options = 0;
148         }
149 
150         const OptionDefinition*
151         GetDefinitions () override
152         {
153             return g_option_table;
154         }
155 
156         // Options table: Required for subclasses of Options.
157 
158         static OptionDefinition g_option_table[];
159 
160         // Instance variables to hold the values for command options.
161 
162         FileSpec log_file;
163         uint32_t log_options;
164     };
165 
166 protected:
167     bool
168     DoExecute (Args& args,
169              CommandReturnObject &result) override
170     {
171         if (args.GetArgumentCount() < 2)
172         {
173             result.AppendErrorWithFormat("%s takes a log channel and one or more log types.\n", m_cmd_name.c_str());
174         }
175         else
176         {
177             std::string channel(args.GetArgumentAtIndex(0));
178             args.Shift ();  // Shift off the channel
179             char log_file[PATH_MAX];
180             if (m_options.log_file)
181                 m_options.log_file.GetPath(log_file, sizeof(log_file));
182             else
183                 log_file[0] = '\0';
184             bool success = m_interpreter.GetDebugger().EnableLog (channel.c_str(),
185                                                                   args.GetConstArgumentVector(),
186                                                                   log_file,
187                                                                   m_options.log_options,
188                                                                   result.GetErrorStream());
189             if (success)
190                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
191             else
192                 result.SetStatus (eReturnStatusFailed);
193         }
194         return result.Succeeded();
195     }
196 
197     CommandOptions m_options;
198 };
199 
200 OptionDefinition
201 CommandObjectLogEnable::CommandOptions::g_option_table[] =
202 {
203 { LLDB_OPT_SET_1, false, "file",       'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename,   "Set the destination file to log to."},
204 { LLDB_OPT_SET_1, false, "threadsafe", 't', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,        "Enable thread safe logging to avoid interweaved log lines." },
205 { LLDB_OPT_SET_1, false, "verbose",    'v', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Enable verbose logging." },
206 { LLDB_OPT_SET_1, false, "debug",      'g', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Enable debug logging." },
207 { LLDB_OPT_SET_1, false, "sequence",   's', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Prepend all log lines with an increasing integer sequence id." },
208 { LLDB_OPT_SET_1, false, "timestamp",  'T', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Prepend all log lines with a timestamp." },
209 { 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." },
210 { 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." },
211 { LLDB_OPT_SET_1, false, "stack",      'S', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Append a stack backtrace to each log line." },
212 { LLDB_OPT_SET_1, false, "append",     'a', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeNone,       "Append to the log file instead of overwriting." },
213 { 0, false, nullptr,                       0,  0,                 nullptr, nullptr, 0, eArgTypeNone,       nullptr }
214 };
215 
216 class CommandObjectLogDisable : public CommandObjectParsed
217 {
218 public:
219     //------------------------------------------------------------------
220     // Constructors and Destructors
221     //------------------------------------------------------------------
222     CommandObjectLogDisable(CommandInterpreter &interpreter) :
223         CommandObjectParsed(interpreter,
224                             "log disable",
225                             "Disable one or more log channel categories.",
226                             nullptr)
227     {
228         CommandArgumentEntry arg1;
229         CommandArgumentEntry arg2;
230         CommandArgumentData channel_arg;
231         CommandArgumentData category_arg;
232 
233         // Define the first (and only) variant of this arg.
234         channel_arg.arg_type = eArgTypeLogChannel;
235         channel_arg.arg_repetition = eArgRepeatPlain;
236 
237         // There is only one variant this argument could be; put it into the argument entry.
238         arg1.push_back (channel_arg);
239 
240         category_arg.arg_type = eArgTypeLogCategory;
241         category_arg.arg_repetition = eArgRepeatPlus;
242 
243         arg2.push_back (category_arg);
244 
245         // Push the data for the first argument into the m_arguments vector.
246         m_arguments.push_back (arg1);
247         m_arguments.push_back (arg2);
248     }
249 
250     ~CommandObjectLogDisable() override = default;
251 
252 protected:
253     bool
254     DoExecute (Args& args,
255              CommandReturnObject &result) override
256     {
257         const size_t argc = args.GetArgumentCount();
258         if (argc == 0)
259         {
260             result.AppendErrorWithFormat("%s takes a log channel and one or more log types.\n", m_cmd_name.c_str());
261         }
262         else
263         {
264             Log::Callbacks log_callbacks;
265 
266             std::string channel(args.GetArgumentAtIndex(0));
267             args.Shift ();  // Shift off the channel
268             if (Log::GetLogChannelCallbacks (ConstString(channel.c_str()), log_callbacks))
269             {
270                 log_callbacks.disable (args.GetConstArgumentVector(), &result.GetErrorStream());
271                 result.SetStatus(eReturnStatusSuccessFinishNoResult);
272             }
273             else if (channel == "all")
274             {
275                 Log::DisableAllLogChannels(&result.GetErrorStream());
276             }
277             else
278             {
279                 LogChannelSP log_channel_sp (LogChannel::FindPlugin(channel.c_str()));
280                 if (log_channel_sp)
281                 {
282                     log_channel_sp->Disable(args.GetConstArgumentVector(), &result.GetErrorStream());
283                     result.SetStatus(eReturnStatusSuccessFinishNoResult);
284                 }
285                 else
286                     result.AppendErrorWithFormat("Invalid log channel '%s'.\n", args.GetArgumentAtIndex(0));
287             }
288         }
289         return result.Succeeded();
290     }
291 };
292 
293 class CommandObjectLogList : public CommandObjectParsed
294 {
295 public:
296     //------------------------------------------------------------------
297     // Constructors and Destructors
298     //------------------------------------------------------------------
299     CommandObjectLogList(CommandInterpreter &interpreter) :
300         CommandObjectParsed(interpreter,
301                             "log list",
302                             "List the log categories for one or more log channels.  If none specified, lists them all.",
303                             nullptr)
304     {
305         CommandArgumentEntry arg;
306         CommandArgumentData channel_arg;
307 
308         // Define the first (and only) variant of this arg.
309         channel_arg.arg_type = eArgTypeLogChannel;
310         channel_arg.arg_repetition = eArgRepeatStar;
311 
312         // There is only one variant this argument could be; put it into the argument entry.
313         arg.push_back (channel_arg);
314 
315         // Push the data for the first argument into the m_arguments vector.
316         m_arguments.push_back (arg);
317     }
318 
319     ~CommandObjectLogList() override = default;
320 
321 protected:
322     bool
323     DoExecute (Args& args,
324              CommandReturnObject &result) override
325     {
326         const size_t argc = args.GetArgumentCount();
327         if (argc == 0)
328         {
329             Log::ListAllLogChannels (&result.GetOutputStream());
330             result.SetStatus(eReturnStatusSuccessFinishResult);
331         }
332         else
333         {
334             for (size_t i=0; i<argc; ++i)
335             {
336                 Log::Callbacks log_callbacks;
337 
338                 std::string channel(args.GetArgumentAtIndex(i));
339                 if (Log::GetLogChannelCallbacks (ConstString(channel.c_str()), log_callbacks))
340                 {
341                     log_callbacks.list_categories (&result.GetOutputStream());
342                     result.SetStatus(eReturnStatusSuccessFinishResult);
343                 }
344                 else if (channel == "all")
345                 {
346                     Log::ListAllLogChannels (&result.GetOutputStream());
347                     result.SetStatus(eReturnStatusSuccessFinishResult);
348                 }
349                 else
350                 {
351                     LogChannelSP log_channel_sp (LogChannel::FindPlugin(channel.c_str()));
352                     if (log_channel_sp)
353                     {
354                         log_channel_sp->ListCategories(&result.GetOutputStream());
355                         result.SetStatus(eReturnStatusSuccessFinishNoResult);
356                     }
357                     else
358                         result.AppendErrorWithFormat("Invalid log channel '%s'.\n", args.GetArgumentAtIndex(0));
359                 }
360             }
361         }
362         return result.Succeeded();
363     }
364 };
365 
366 class CommandObjectLogTimer : public CommandObjectParsed
367 {
368 public:
369     //------------------------------------------------------------------
370     // Constructors and Destructors
371     //------------------------------------------------------------------
372     CommandObjectLogTimer(CommandInterpreter &interpreter) :
373         CommandObjectParsed (interpreter,
374                            "log timers",
375                            "Enable, disable, dump, and reset LLDB internal performance timers.",
376                            "log timers < enable <depth> | disable | dump | increment <bool> | reset >")
377     {
378     }
379 
380     ~CommandObjectLogTimer() override = default;
381 
382 protected:
383     bool
384     DoExecute (Args& args,
385              CommandReturnObject &result) override
386     {
387         const size_t argc = args.GetArgumentCount();
388         result.SetStatus(eReturnStatusFailed);
389 
390         if (argc == 1)
391         {
392             const char *sub_command = args.GetArgumentAtIndex(0);
393 
394             if (strcasecmp(sub_command, "enable") == 0)
395             {
396                 Timer::SetDisplayDepth (UINT32_MAX);
397                 result.SetStatus(eReturnStatusSuccessFinishNoResult);
398             }
399             else if (strcasecmp(sub_command, "disable") == 0)
400             {
401                 Timer::DumpCategoryTimes (&result.GetOutputStream());
402                 Timer::SetDisplayDepth (0);
403                 result.SetStatus(eReturnStatusSuccessFinishResult);
404             }
405             else if (strcasecmp(sub_command, "dump") == 0)
406             {
407                 Timer::DumpCategoryTimes (&result.GetOutputStream());
408                 result.SetStatus(eReturnStatusSuccessFinishResult);
409             }
410             else if (strcasecmp(sub_command, "reset") == 0)
411             {
412                 Timer::ResetCategoryTimes ();
413                 result.SetStatus(eReturnStatusSuccessFinishResult);
414             }
415         }
416         else if (argc == 2)
417         {
418             const char *sub_command = args.GetArgumentAtIndex(0);
419 
420             if (strcasecmp(sub_command, "enable") == 0)
421             {
422                 bool success;
423                 uint32_t depth = StringConvert::ToUInt32(args.GetArgumentAtIndex(1), 0, 0, &success);
424                 if (success)
425                 {
426                     Timer::SetDisplayDepth (depth);
427                     result.SetStatus(eReturnStatusSuccessFinishNoResult);
428                 }
429                 else
430                     result.AppendError("Could not convert enable depth to an unsigned integer.");
431             }
432             if (strcasecmp(sub_command, "increment") == 0)
433             {
434                 bool success;
435                 bool increment = Args::StringToBoolean(args.GetArgumentAtIndex(1), false, &success);
436                 if (success)
437                 {
438                     Timer::SetQuiet (!increment);
439                     result.SetStatus(eReturnStatusSuccessFinishNoResult);
440                 }
441                 else
442                     result.AppendError("Could not convert increment value to boolean.");
443             }
444         }
445 
446         if (!result.Succeeded())
447         {
448             result.AppendError("Missing subcommand");
449             result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str());
450         }
451         return result.Succeeded();
452     }
453 };
454 
455 CommandObjectLog::CommandObjectLog(CommandInterpreter &interpreter)
456     : CommandObjectMultiword(interpreter, "log", "Commands controlling LLDB internal logging.",
457                              "log <subcommand> [<command-options>]")
458 {
459     LoadSubCommand ("enable",  CommandObjectSP (new CommandObjectLogEnable (interpreter)));
460     LoadSubCommand ("disable", CommandObjectSP (new CommandObjectLogDisable (interpreter)));
461     LoadSubCommand ("list",    CommandObjectSP (new CommandObjectLogList (interpreter)));
462     LoadSubCommand ("timers",  CommandObjectSP (new CommandObjectLogTimer (interpreter)));
463 }
464 
465 CommandObjectLog::~CommandObjectLog() = default;
466