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