1 //===-- StructuredDataDarwinLog.cpp ---------------------------------------===//
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 "StructuredDataDarwinLog.h"
10 
11 #include <cstring>
12 
13 #include <memory>
14 #include <sstream>
15 
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Host/OptionParser.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandObjectMultiword.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/OptionArgParser.h"
25 #include "lldb/Interpreter/OptionValueProperties.h"
26 #include "lldb/Interpreter/OptionValueString.h"
27 #include "lldb/Interpreter/Property.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/ThreadPlanCallOnFunctionExit.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/RegularExpression.h"
33 
34 #define DARWIN_LOG_TYPE_VALUE "DarwinLog"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 LLDB_PLUGIN_DEFINE(StructuredDataDarwinLog)
40 
41 #pragma mark -
42 #pragma mark Anonymous Namespace
43 
44 // Anonymous namespace
45 
46 namespace sddarwinlog_private {
47 const uint64_t NANOS_PER_MICRO = 1000;
48 const uint64_t NANOS_PER_MILLI = NANOS_PER_MICRO * 1000;
49 const uint64_t NANOS_PER_SECOND = NANOS_PER_MILLI * 1000;
50 const uint64_t NANOS_PER_MINUTE = NANOS_PER_SECOND * 60;
51 const uint64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * 60;
52 
53 static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS = true;
54 
55 /// Global, sticky enable switch.  If true, the user has explicitly
56 /// run the enable command.  When a process launches or is attached to,
57 /// we will enable DarwinLog if either the settings for auto-enable is
58 /// on, or if the user had explicitly run enable at some point prior
59 /// to the launch/attach.
60 static bool s_is_explicitly_enabled;
61 
62 class EnableOptions;
63 using EnableOptionsSP = std::shared_ptr<EnableOptions>;
64 
65 using OptionsMap =
66     std::map<DebuggerWP, EnableOptionsSP, std::owner_less<DebuggerWP>>;
67 
68 static OptionsMap &GetGlobalOptionsMap() {
69   static OptionsMap s_options_map;
70   return s_options_map;
71 }
72 
73 static std::mutex &GetGlobalOptionsMapLock() {
74   static std::mutex s_options_map_lock;
75   return s_options_map_lock;
76 }
77 
78 EnableOptionsSP GetGlobalEnableOptions(const DebuggerSP &debugger_sp) {
79   if (!debugger_sp)
80     return EnableOptionsSP();
81 
82   std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
83   OptionsMap &options_map = GetGlobalOptionsMap();
84   DebuggerWP debugger_wp(debugger_sp);
85   auto find_it = options_map.find(debugger_wp);
86   if (find_it != options_map.end())
87     return find_it->second;
88   else
89     return EnableOptionsSP();
90 }
91 
92 void SetGlobalEnableOptions(const DebuggerSP &debugger_sp,
93                             const EnableOptionsSP &options_sp) {
94   std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
95   OptionsMap &options_map = GetGlobalOptionsMap();
96   DebuggerWP debugger_wp(debugger_sp);
97   auto find_it = options_map.find(debugger_wp);
98   if (find_it != options_map.end())
99     find_it->second = options_sp;
100   else
101     options_map.insert(std::make_pair(debugger_wp, options_sp));
102 }
103 
104 #pragma mark -
105 #pragma mark Settings Handling
106 
107 /// Code to handle the StructuredDataDarwinLog settings
108 
109 #define LLDB_PROPERTIES_darwinlog
110 #include "StructuredDataDarwinLogProperties.inc"
111 
112 enum {
113 #define LLDB_PROPERTIES_darwinlog
114 #include "StructuredDataDarwinLogPropertiesEnum.inc"
115 };
116 
117 class StructuredDataDarwinLogProperties : public Properties {
118 public:
119   static ConstString &GetSettingName() {
120     static ConstString g_setting_name("darwin-log");
121     return g_setting_name;
122   }
123 
124   StructuredDataDarwinLogProperties() : Properties() {
125     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
126     m_collection_sp->Initialize(g_darwinlog_properties);
127   }
128 
129   ~StructuredDataDarwinLogProperties() override {}
130 
131   bool GetEnableOnStartup() const {
132     const uint32_t idx = ePropertyEnableOnStartup;
133     return m_collection_sp->GetPropertyAtIndexAsBoolean(
134         nullptr, idx, g_darwinlog_properties[idx].default_uint_value != 0);
135   }
136 
137   llvm::StringRef GetAutoEnableOptions() const {
138     const uint32_t idx = ePropertyAutoEnableOptions;
139     return m_collection_sp->GetPropertyAtIndexAsString(
140         nullptr, idx, g_darwinlog_properties[idx].default_cstr_value);
141   }
142 
143   const char *GetLoggingModuleName() const { return "libsystem_trace.dylib"; }
144 };
145 
146 using StructuredDataDarwinLogPropertiesSP =
147     std::shared_ptr<StructuredDataDarwinLogProperties>;
148 
149 static const StructuredDataDarwinLogPropertiesSP &GetGlobalProperties() {
150   static StructuredDataDarwinLogPropertiesSP g_settings_sp;
151   if (!g_settings_sp)
152     g_settings_sp = std::make_shared<StructuredDataDarwinLogProperties>();
153   return g_settings_sp;
154 }
155 
156 const char *const s_filter_attributes[] = {
157     "activity",       // current activity
158     "activity-chain", // entire activity chain, each level separated by ':'
159     "category",       // category of the log message
160     "message",        // message contents, fully expanded
161     "subsystem"       // subsystem of the log message
162 
163     // Consider implementing this action as it would be cheaper to filter.
164     // "message" requires always formatting the message, which is a waste of
165     // cycles if it ends up being rejected. "format",      // format string
166     // used to format message text
167 };
168 
169 static ConstString GetDarwinLogTypeName() {
170   static const ConstString s_key_name("DarwinLog");
171   return s_key_name;
172 }
173 
174 static ConstString GetLogEventType() {
175   static const ConstString s_event_type("log");
176   return s_event_type;
177 }
178 
179 class FilterRule;
180 using FilterRuleSP = std::shared_ptr<FilterRule>;
181 
182 class FilterRule {
183 public:
184   virtual ~FilterRule() {}
185 
186   using OperationCreationFunc =
187       std::function<FilterRuleSP(bool accept, size_t attribute_index,
188                                  const std::string &op_arg, Status &error)>;
189 
190   static void RegisterOperation(ConstString operation,
191                                 const OperationCreationFunc &creation_func) {
192     GetCreationFuncMap().insert(std::make_pair(operation, creation_func));
193   }
194 
195   static FilterRuleSP CreateRule(bool match_accepts, size_t attribute,
196                                  ConstString operation,
197                                  const std::string &op_arg, Status &error) {
198     // Find the creation func for this type of filter rule.
199     auto map = GetCreationFuncMap();
200     auto find_it = map.find(operation);
201     if (find_it == map.end()) {
202       error.SetErrorStringWithFormat("unknown filter operation \""
203                                      "%s\"",
204                                      operation.GetCString());
205       return FilterRuleSP();
206     }
207 
208     return find_it->second(match_accepts, attribute, op_arg, error);
209   }
210 
211   StructuredData::ObjectSP Serialize() const {
212     StructuredData::Dictionary *dict_p = new StructuredData::Dictionary();
213 
214     // Indicate whether this is an accept or reject rule.
215     dict_p->AddBooleanItem("accept", m_accept);
216 
217     // Indicate which attribute of the message this filter references. This can
218     // drop into the rule-specific DoSerialization if we get to the point where
219     // not all FilterRule derived classes work on an attribute.  (e.g. logical
220     // and/or and other compound operations).
221     dict_p->AddStringItem("attribute", s_filter_attributes[m_attribute_index]);
222 
223     // Indicate the type of the rule.
224     dict_p->AddStringItem("type", GetOperationType().GetCString());
225 
226     // Let the rule add its own specific details here.
227     DoSerialization(*dict_p);
228 
229     return StructuredData::ObjectSP(dict_p);
230   }
231 
232   virtual void Dump(Stream &stream) const = 0;
233 
234   ConstString GetOperationType() const { return m_operation; }
235 
236 protected:
237   FilterRule(bool accept, size_t attribute_index, ConstString operation)
238       : m_accept(accept), m_attribute_index(attribute_index),
239         m_operation(operation) {}
240 
241   virtual void DoSerialization(StructuredData::Dictionary &dict) const = 0;
242 
243   bool GetMatchAccepts() const { return m_accept; }
244 
245   const char *GetFilterAttribute() const {
246     return s_filter_attributes[m_attribute_index];
247   }
248 
249 private:
250   using CreationFuncMap = std::map<ConstString, OperationCreationFunc>;
251 
252   static CreationFuncMap &GetCreationFuncMap() {
253     static CreationFuncMap s_map;
254     return s_map;
255   }
256 
257   const bool m_accept;
258   const size_t m_attribute_index;
259   const ConstString m_operation;
260 };
261 
262 using FilterRules = std::vector<FilterRuleSP>;
263 
264 class RegexFilterRule : public FilterRule {
265 public:
266   static void RegisterOperation() {
267     FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
268   }
269 
270   void Dump(Stream &stream) const override {
271     stream.Printf("%s %s regex %s", GetMatchAccepts() ? "accept" : "reject",
272                   GetFilterAttribute(), m_regex_text.c_str());
273   }
274 
275 protected:
276   void DoSerialization(StructuredData::Dictionary &dict) const override {
277     dict.AddStringItem("regex", m_regex_text);
278   }
279 
280 private:
281   static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
282                                       const std::string &op_arg,
283                                       Status &error) {
284     // We treat the op_arg as a regex.  Validate it.
285     if (op_arg.empty()) {
286       error.SetErrorString("regex filter type requires a regex "
287                            "argument");
288       return FilterRuleSP();
289     }
290 
291     // Instantiate the regex so we can report any errors.
292     auto regex = RegularExpression(op_arg);
293     if (llvm::Error err = regex.GetError()) {
294       error.SetErrorString(llvm::toString(std::move(err)));
295       return FilterRuleSP();
296     }
297 
298     // We passed all our checks, this appears fine.
299     error.Clear();
300     return FilterRuleSP(new RegexFilterRule(accept, attribute_index, op_arg));
301   }
302 
303   static ConstString StaticGetOperation() {
304     static ConstString s_operation("regex");
305     return s_operation;
306   }
307 
308   RegexFilterRule(bool accept, size_t attribute_index,
309                   const std::string &regex_text)
310       : FilterRule(accept, attribute_index, StaticGetOperation()),
311         m_regex_text(regex_text) {}
312 
313   const std::string m_regex_text;
314 };
315 
316 class ExactMatchFilterRule : public FilterRule {
317 public:
318   static void RegisterOperation() {
319     FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
320   }
321 
322   void Dump(Stream &stream) const override {
323     stream.Printf("%s %s match %s", GetMatchAccepts() ? "accept" : "reject",
324                   GetFilterAttribute(), m_match_text.c_str());
325   }
326 
327 protected:
328   void DoSerialization(StructuredData::Dictionary &dict) const override {
329     dict.AddStringItem("exact_text", m_match_text);
330   }
331 
332 private:
333   static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
334                                       const std::string &op_arg,
335                                       Status &error) {
336     if (op_arg.empty()) {
337       error.SetErrorString("exact match filter type requires an "
338                            "argument containing the text that must "
339                            "match the specified message attribute.");
340       return FilterRuleSP();
341     }
342 
343     error.Clear();
344     return FilterRuleSP(
345         new ExactMatchFilterRule(accept, attribute_index, op_arg));
346   }
347 
348   static ConstString StaticGetOperation() {
349     static ConstString s_operation("match");
350     return s_operation;
351   }
352 
353   ExactMatchFilterRule(bool accept, size_t attribute_index,
354                        const std::string &match_text)
355       : FilterRule(accept, attribute_index, StaticGetOperation()),
356         m_match_text(match_text) {}
357 
358   const std::string m_match_text;
359 };
360 
361 static void RegisterFilterOperations() {
362   ExactMatchFilterRule::RegisterOperation();
363   RegexFilterRule::RegisterOperation();
364 }
365 
366 // =========================================================================
367 // Commands
368 // =========================================================================
369 
370 /// Provides the main on-off switch for enabling darwin logging.
371 ///
372 /// It is valid to run the enable command when logging is already enabled.
373 /// This resets the logging with whatever settings are currently set.
374 
375 static constexpr OptionDefinition g_enable_option_table[] = {
376     // Source stream include/exclude options (the first-level filter). This one
377     // should be made as small as possible as everything that goes through here
378     // must be processed by the process monitor.
379     {LLDB_OPT_SET_ALL, false, "any-process", 'a', OptionParser::eNoArgument,
380      nullptr, {}, 0, eArgTypeNone,
381      "Specifies log messages from other related processes should be "
382      "included."},
383     {LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, nullptr,
384      {}, 0, eArgTypeNone,
385      "Specifies debug-level log messages should be included.  Specifying"
386      " --debug implies --info."},
387     {LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, nullptr,
388      {}, 0, eArgTypeNone,
389      "Specifies info-level log messages should be included."},
390     {LLDB_OPT_SET_ALL, false, "filter", 'f', OptionParser::eRequiredArgument,
391      nullptr, {}, 0, eArgRawInput,
392      // There doesn't appear to be a great way for me to have these multi-line,
393      // formatted tables in help.  This looks mostly right but there are extra
394      // linefeeds added at seemingly random spots, and indentation isn't
395      // handled properly on those lines.
396      "Appends a filter rule to the log message filter chain.  Multiple "
397      "rules may be added by specifying this option multiple times, "
398      "once per filter rule.  Filter rules are processed in the order "
399      "they are specified, with the --no-match-accepts setting used "
400      "for any message that doesn't match one of the rules.\n"
401      "\n"
402      "    Filter spec format:\n"
403      "\n"
404      "    --filter \"{action} {attribute} {op}\"\n"
405      "\n"
406      "    {action} :=\n"
407      "      accept |\n"
408      "      reject\n"
409      "\n"
410      "    {attribute} :=\n"
411      "       activity       |  // message's most-derived activity\n"
412      "       activity-chain |  // message's {parent}:{child} activity\n"
413      "       category       |  // message's category\n"
414      "       message        |  // message's expanded contents\n"
415      "       subsystem      |  // message's subsystem\n"
416      "\n"
417      "    {op} :=\n"
418      "      match {exact-match-text} |\n"
419      "      regex {search-regex}\n"
420      "\n"
421      "The regex flavor used is the C++ std::regex ECMAScript format.  "
422      "Prefer character classes like [[:digit:]] to \\d and the like, as "
423      "getting the backslashes escaped through properly is error-prone."},
424     {LLDB_OPT_SET_ALL, false, "live-stream", 'l',
425      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
426      "Specify whether logging events are live-streamed or buffered.  "
427      "True indicates live streaming, false indicates buffered.  The "
428      "default is true (live streaming).  Live streaming will deliver "
429      "log messages with less delay, but buffered capture mode has less "
430      "of an observer effect."},
431     {LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n',
432      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
433      "Specify whether a log message that doesn't match any filter rule "
434      "is accepted or rejected, where true indicates accept.  The "
435      "default is true."},
436     {LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e',
437      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
438      "Specify whether os_log()/NSLog() messages are echoed to the "
439      "target program's stderr.  When DarwinLog is enabled, we shut off "
440      "the mirroring of os_log()/NSLog() to the program's stderr.  "
441      "Setting this flag to true will restore the stderr mirroring."
442      "The default is false."},
443     {LLDB_OPT_SET_ALL, false, "broadcast-events", 'b',
444      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
445      "Specify if the plugin should broadcast events.  Broadcasting "
446      "log events is a requirement for displaying the log entries in "
447      "LLDB command-line.  It is also required if LLDB clients want to "
448      "process log events.  The default is true."},
449     // Message formatting options
450     {LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r',
451      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
452      "Include timestamp in the message header when printing a log "
453      "message.  The timestamp is relative to the first displayed "
454      "message."},
455     {LLDB_OPT_SET_ALL, false, "subsystem", 's', OptionParser::eNoArgument,
456      nullptr, {}, 0, eArgTypeNone,
457      "Include the subsystem in the message header when displaying "
458      "a log message."},
459     {LLDB_OPT_SET_ALL, false, "category", 'c', OptionParser::eNoArgument,
460      nullptr, {}, 0, eArgTypeNone,
461      "Include the category in the message header when displaying "
462      "a log message."},
463     {LLDB_OPT_SET_ALL, false, "activity-chain", 'C', OptionParser::eNoArgument,
464      nullptr, {}, 0, eArgTypeNone,
465      "Include the activity parent-child chain in the message header "
466      "when displaying a log message.  The activity hierarchy is "
467      "displayed as {grandparent-activity}:"
468      "{parent-activity}:{activity}[:...]."},
469     {LLDB_OPT_SET_ALL, false, "all-fields", 'A', OptionParser::eNoArgument,
470      nullptr, {}, 0, eArgTypeNone,
471      "Shortcut to specify that all header fields should be displayed."}};
472 
473 class EnableOptions : public Options {
474 public:
475   EnableOptions()
476       : Options(),
477         m_filter_fall_through_accepts(DEFAULT_FILTER_FALLTHROUGH_ACCEPTS),
478         m_filter_rules() {}
479 
480   void OptionParsingStarting(ExecutionContext *execution_context) override {
481     m_include_debug_level = false;
482     m_include_info_level = false;
483     m_include_any_process = false;
484     m_filter_fall_through_accepts = DEFAULT_FILTER_FALLTHROUGH_ACCEPTS;
485     m_echo_to_stderr = false;
486     m_display_timestamp_relative = false;
487     m_display_subsystem = false;
488     m_display_category = false;
489     m_display_activity_chain = false;
490     m_broadcast_events = true;
491     m_live_stream = true;
492     m_filter_rules.clear();
493   }
494 
495   Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
496                         ExecutionContext *execution_context) override {
497     Status error;
498 
499     const int short_option = m_getopt_table[option_idx].val;
500     switch (short_option) {
501     case 'a':
502       m_include_any_process = true;
503       break;
504 
505     case 'A':
506       m_display_timestamp_relative = true;
507       m_display_category = true;
508       m_display_subsystem = true;
509       m_display_activity_chain = true;
510       break;
511 
512     case 'b':
513       m_broadcast_events =
514           OptionArgParser::ToBoolean(option_arg, true, nullptr);
515       break;
516 
517     case 'c':
518       m_display_category = true;
519       break;
520 
521     case 'C':
522       m_display_activity_chain = true;
523       break;
524 
525     case 'd':
526       m_include_debug_level = true;
527       break;
528 
529     case 'e':
530       m_echo_to_stderr = OptionArgParser::ToBoolean(option_arg, false, nullptr);
531       break;
532 
533     case 'f':
534       return ParseFilterRule(option_arg);
535 
536     case 'i':
537       m_include_info_level = true;
538       break;
539 
540     case 'l':
541       m_live_stream = OptionArgParser::ToBoolean(option_arg, false, nullptr);
542       break;
543 
544     case 'n':
545       m_filter_fall_through_accepts =
546           OptionArgParser::ToBoolean(option_arg, true, nullptr);
547       break;
548 
549     case 'r':
550       m_display_timestamp_relative = true;
551       break;
552 
553     case 's':
554       m_display_subsystem = true;
555       break;
556 
557     default:
558       error.SetErrorStringWithFormat("unsupported option '%c'", short_option);
559     }
560     return error;
561   }
562 
563   llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
564     return llvm::makeArrayRef(g_enable_option_table);
565   }
566 
567   StructuredData::DictionarySP BuildConfigurationData(bool enabled) {
568     StructuredData::DictionarySP config_sp(new StructuredData::Dictionary());
569 
570     // Set the basic enabled state.
571     config_sp->AddBooleanItem("enabled", enabled);
572 
573     // If we're disabled, there's nothing more to add.
574     if (!enabled)
575       return config_sp;
576 
577     // Handle source stream flags.
578     auto source_flags_sp =
579         StructuredData::DictionarySP(new StructuredData::Dictionary());
580     config_sp->AddItem("source-flags", source_flags_sp);
581 
582     source_flags_sp->AddBooleanItem("any-process", m_include_any_process);
583     source_flags_sp->AddBooleanItem("debug-level", m_include_debug_level);
584     // The debug-level flag, if set, implies info-level.
585     source_flags_sp->AddBooleanItem("info-level", m_include_info_level ||
586                                                       m_include_debug_level);
587     source_flags_sp->AddBooleanItem("live-stream", m_live_stream);
588 
589     // Specify default filter rule (the fall-through)
590     config_sp->AddBooleanItem("filter-fall-through-accepts",
591                               m_filter_fall_through_accepts);
592 
593     // Handle filter rules
594     if (!m_filter_rules.empty()) {
595       auto json_filter_rules_sp =
596           StructuredData::ArraySP(new StructuredData::Array);
597       config_sp->AddItem("filter-rules", json_filter_rules_sp);
598       for (auto &rule_sp : m_filter_rules) {
599         if (!rule_sp)
600           continue;
601         json_filter_rules_sp->AddItem(rule_sp->Serialize());
602       }
603     }
604     return config_sp;
605   }
606 
607   bool GetIncludeDebugLevel() const { return m_include_debug_level; }
608 
609   bool GetIncludeInfoLevel() const {
610     // Specifying debug level implies info level.
611     return m_include_info_level || m_include_debug_level;
612   }
613 
614   const FilterRules &GetFilterRules() const { return m_filter_rules; }
615 
616   bool GetFallthroughAccepts() const { return m_filter_fall_through_accepts; }
617 
618   bool GetEchoToStdErr() const { return m_echo_to_stderr; }
619 
620   bool GetDisplayTimestampRelative() const {
621     return m_display_timestamp_relative;
622   }
623 
624   bool GetDisplaySubsystem() const { return m_display_subsystem; }
625   bool GetDisplayCategory() const { return m_display_category; }
626   bool GetDisplayActivityChain() const { return m_display_activity_chain; }
627 
628   bool GetDisplayAnyHeaderFields() const {
629     return m_display_timestamp_relative || m_display_activity_chain ||
630            m_display_subsystem || m_display_category;
631   }
632 
633   bool GetBroadcastEvents() const { return m_broadcast_events; }
634 
635 private:
636   Status ParseFilterRule(llvm::StringRef rule_text) {
637     Status error;
638 
639     if (rule_text.empty()) {
640       error.SetErrorString("invalid rule_text");
641       return error;
642     }
643 
644     // filter spec format:
645     //
646     // {action} {attribute} {op}
647     //
648     // {action} :=
649     //   accept |
650     //   reject
651     //
652     // {attribute} :=
653     //   category       |
654     //   subsystem      |
655     //   activity       |
656     //   activity-chain |
657     //   message        |
658     //   format
659     //
660     // {op} :=
661     //   match {exact-match-text} |
662     //   regex {search-regex}
663 
664     // Parse action.
665     auto action_end_pos = rule_text.find(' ');
666     if (action_end_pos == std::string::npos) {
667       error.SetErrorStringWithFormat("could not parse filter rule "
668                                      "action from \"%s\"",
669                                      rule_text.str().c_str());
670       return error;
671     }
672     auto action = rule_text.substr(0, action_end_pos);
673     bool accept;
674     if (action == "accept")
675       accept = true;
676     else if (action == "reject")
677       accept = false;
678     else {
679       error.SetErrorString("filter action must be \"accept\" or \"deny\"");
680       return error;
681     }
682 
683     // parse attribute
684     auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1);
685     if (attribute_end_pos == std::string::npos) {
686       error.SetErrorStringWithFormat("could not parse filter rule "
687                                      "attribute from \"%s\"",
688                                      rule_text.str().c_str());
689       return error;
690     }
691     auto attribute = rule_text.substr(action_end_pos + 1,
692                                       attribute_end_pos - (action_end_pos + 1));
693     auto attribute_index = MatchAttributeIndex(attribute);
694     if (attribute_index < 0) {
695       error.SetErrorStringWithFormat("filter rule attribute unknown: "
696                                      "%s",
697                                      attribute.str().c_str());
698       return error;
699     }
700 
701     // parse operation
702     auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1);
703     auto operation = rule_text.substr(
704         attribute_end_pos + 1, operation_end_pos - (attribute_end_pos + 1));
705 
706     // add filter spec
707     auto rule_sp = FilterRule::CreateRule(
708         accept, attribute_index, ConstString(operation),
709         std::string(rule_text.substr(operation_end_pos + 1)), error);
710 
711     if (rule_sp && error.Success())
712       m_filter_rules.push_back(rule_sp);
713 
714     return error;
715   }
716 
717   int MatchAttributeIndex(llvm::StringRef attribute_name) const {
718     for (const auto &Item : llvm::enumerate(s_filter_attributes)) {
719       if (attribute_name == Item.value())
720         return Item.index();
721     }
722 
723     // We didn't match anything.
724     return -1;
725   }
726 
727   bool m_include_debug_level = false;
728   bool m_include_info_level = false;
729   bool m_include_any_process = false;
730   bool m_filter_fall_through_accepts;
731   bool m_echo_to_stderr = false;
732   bool m_display_timestamp_relative = false;
733   bool m_display_subsystem = false;
734   bool m_display_category = false;
735   bool m_display_activity_chain = false;
736   bool m_broadcast_events = true;
737   bool m_live_stream = true;
738   FilterRules m_filter_rules;
739 };
740 
741 class EnableCommand : public CommandObjectParsed {
742 public:
743   EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name,
744                 const char *help, const char *syntax)
745       : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable),
746         m_options_sp(enable ? new EnableOptions() : nullptr) {}
747 
748 protected:
749   void AppendStrictSourcesWarning(CommandReturnObject &result,
750                                   const char *source_name) {
751     if (!source_name)
752       return;
753 
754     // Check if we're *not* using strict sources.  If not, then the user is
755     // going to get debug-level info anyways, probably not what they're
756     // expecting. Unfortunately we can only fix this by adding an env var,
757     // which would have had to have happened already.  Thus, a warning is the
758     // best we can do here.
759     StreamString stream;
760     stream.Printf("darwin-log source settings specify to exclude "
761                   "%s messages, but setting "
762                   "'plugin.structured-data.darwin-log."
763                   "strict-sources' is disabled.  This process will "
764                   "automatically have %s messages included.  Enable"
765                   " the property and relaunch the target binary to have"
766                   " these messages excluded.",
767                   source_name, source_name);
768     result.AppendWarning(stream.GetString());
769   }
770 
771   bool DoExecute(Args &command, CommandReturnObject &result) override {
772     // First off, set the global sticky state of enable/disable based on this
773     // command execution.
774     s_is_explicitly_enabled = m_enable;
775 
776     // Next, if this is an enable, save off the option data. We will need it
777     // later if a process hasn't been launched or attached yet.
778     if (m_enable) {
779       // Save off enabled configuration so we can apply these parsed options
780       // the next time an attach or launch occurs.
781       DebuggerSP debugger_sp =
782           GetCommandInterpreter().GetDebugger().shared_from_this();
783       SetGlobalEnableOptions(debugger_sp, m_options_sp);
784     }
785 
786     // Now check if we have a running process.  If so, we should instruct the
787     // process monitor to enable/disable DarwinLog support now.
788     Target &target = GetSelectedOrDummyTarget();
789 
790     // Grab the active process.
791     auto process_sp = target.GetProcessSP();
792     if (!process_sp) {
793       // No active process, so there is nothing more to do right now.
794       result.SetStatus(eReturnStatusSuccessFinishNoResult);
795       return true;
796     }
797 
798     // If the process is no longer alive, we can't do this now. We'll catch it
799     // the next time the process is started up.
800     if (!process_sp->IsAlive()) {
801       result.SetStatus(eReturnStatusSuccessFinishNoResult);
802       return true;
803     }
804 
805     // Get the plugin for the process.
806     auto plugin_sp =
807         process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
808     if (!plugin_sp || (plugin_sp->GetPluginName() !=
809                        StructuredDataDarwinLog::GetStaticPluginName())) {
810       result.AppendError("failed to get StructuredDataPlugin for "
811                          "the process");
812       result.SetStatus(eReturnStatusFailed);
813     }
814     StructuredDataDarwinLog &plugin =
815         *static_cast<StructuredDataDarwinLog *>(plugin_sp.get());
816 
817     if (m_enable) {
818       // Hook up the breakpoint for the process that detects when libtrace has
819       // been sufficiently initialized to really start the os_log stream.  This
820       // is insurance to assure us that logging is really enabled.  Requesting
821       // that logging be enabled for a process before libtrace is initialized
822       // results in a scenario where no errors occur, but no logging is
823       // captured, either.  This step is to eliminate that possibility.
824       plugin.AddInitCompletionHook(*process_sp);
825     }
826 
827     // Send configuration to the feature by way of the process. Construct the
828     // options we will use.
829     auto config_sp = m_options_sp->BuildConfigurationData(m_enable);
830     const Status error =
831         process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
832 
833     // Report results.
834     if (!error.Success()) {
835       result.AppendError(error.AsCString());
836       result.SetStatus(eReturnStatusFailed);
837       // Our configuration failed, so we're definitely disabled.
838       plugin.SetEnabled(false);
839     } else {
840       result.SetStatus(eReturnStatusSuccessFinishNoResult);
841       // Our configuration succeeded, so we're enabled/disabled per whichever
842       // one this command is setup to do.
843       plugin.SetEnabled(m_enable);
844     }
845     return result.Succeeded();
846   }
847 
848   Options *GetOptions() override {
849     // We don't have options when this represents disable.
850     return m_enable ? m_options_sp.get() : nullptr;
851   }
852 
853 private:
854   const bool m_enable;
855   EnableOptionsSP m_options_sp;
856 };
857 
858 /// Provides the status command.
859 class StatusCommand : public CommandObjectParsed {
860 public:
861   StatusCommand(CommandInterpreter &interpreter)
862       : CommandObjectParsed(interpreter, "status",
863                             "Show whether Darwin log supported is available"
864                             " and enabled.",
865                             "plugin structured-data darwin-log status") {}
866 
867 protected:
868   bool DoExecute(Args &command, CommandReturnObject &result) override {
869     auto &stream = result.GetOutputStream();
870 
871     // Figure out if we've got a process.  If so, we can tell if DarwinLog is
872     // available for that process.
873     Target &target = GetSelectedOrDummyTarget();
874     auto process_sp = target.GetProcessSP();
875     if (!process_sp) {
876       stream.PutCString("Availability: unknown (requires process)\n");
877       stream.PutCString("Enabled: not applicable "
878                         "(requires process)\n");
879     } else {
880       auto plugin_sp =
881           process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
882       stream.Printf("Availability: %s\n",
883                     plugin_sp ? "available" : "unavailable");
884       ConstString plugin_name = StructuredDataDarwinLog::GetStaticPluginName();
885       const bool enabled =
886           plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false;
887       stream.Printf("Enabled: %s\n", enabled ? "true" : "false");
888     }
889 
890     // Display filter settings.
891     DebuggerSP debugger_sp =
892         GetCommandInterpreter().GetDebugger().shared_from_this();
893     auto options_sp = GetGlobalEnableOptions(debugger_sp);
894     if (!options_sp) {
895       // Nothing more to do.
896       result.SetStatus(eReturnStatusSuccessFinishResult);
897       return true;
898     }
899 
900     // Print filter rules
901     stream.PutCString("DarwinLog filter rules:\n");
902 
903     stream.IndentMore();
904 
905     if (options_sp->GetFilterRules().empty()) {
906       stream.Indent();
907       stream.PutCString("none\n");
908     } else {
909       // Print each of the filter rules.
910       int rule_number = 0;
911       for (auto rule_sp : options_sp->GetFilterRules()) {
912         ++rule_number;
913         if (!rule_sp)
914           continue;
915 
916         stream.Indent();
917         stream.Printf("%02d: ", rule_number);
918         rule_sp->Dump(stream);
919         stream.PutChar('\n');
920       }
921     }
922     stream.IndentLess();
923 
924     // Print no-match handling.
925     stream.Indent();
926     stream.Printf("no-match behavior: %s\n",
927                   options_sp->GetFallthroughAccepts() ? "accept" : "reject");
928 
929     result.SetStatus(eReturnStatusSuccessFinishResult);
930     return true;
931   }
932 };
933 
934 /// Provides the darwin-log base command
935 class BaseCommand : public CommandObjectMultiword {
936 public:
937   BaseCommand(CommandInterpreter &interpreter)
938       : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log",
939                                "Commands for configuring Darwin os_log "
940                                "support.",
941                                "") {
942     // enable
943     auto enable_help = "Enable Darwin log collection, or re-enable "
944                        "with modified configuration.";
945     auto enable_syntax = "plugin structured-data darwin-log enable";
946     auto enable_cmd_sp = CommandObjectSP(
947         new EnableCommand(interpreter,
948                           true, // enable
949                           "enable", enable_help, enable_syntax));
950     LoadSubCommand("enable", enable_cmd_sp);
951 
952     // disable
953     auto disable_help = "Disable Darwin log collection.";
954     auto disable_syntax = "plugin structured-data darwin-log disable";
955     auto disable_cmd_sp = CommandObjectSP(
956         new EnableCommand(interpreter,
957                           false, // disable
958                           "disable", disable_help, disable_syntax));
959     LoadSubCommand("disable", disable_cmd_sp);
960 
961     // status
962     auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter));
963     LoadSubCommand("status", status_cmd_sp);
964   }
965 };
966 
967 EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger) {
968   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
969   // We are abusing the options data model here so that we can parse options
970   // without requiring the Debugger instance.
971 
972   // We have an empty execution context at this point.  We only want to parse
973   // options, and we don't need any context to do this here. In fact, we want
974   // to be able to parse the enable options before having any context.
975   ExecutionContext exe_ctx;
976 
977   EnableOptionsSP options_sp(new EnableOptions());
978   options_sp->NotifyOptionParsingStarting(&exe_ctx);
979 
980   CommandReturnObject result(debugger.GetUseColor());
981 
982   // Parse the arguments.
983   auto options_property_sp =
984       debugger.GetPropertyValue(nullptr, "plugin.structured-data.darwin-log."
985                                          "auto-enable-options",
986                                 false, error);
987   if (!error.Success())
988     return EnableOptionsSP();
989   if (!options_property_sp) {
990     error.SetErrorString("failed to find option setting for "
991                          "plugin.structured-data.darwin-log.");
992     return EnableOptionsSP();
993   }
994 
995   const char *enable_options =
996       options_property_sp->GetAsString()->GetCurrentValue();
997   Args args(enable_options);
998   if (args.GetArgumentCount() > 0) {
999     // Eliminate the initial '--' that would be required to set the settings
1000     // that themselves include '-' and/or '--'.
1001     const char *first_arg = args.GetArgumentAtIndex(0);
1002     if (first_arg && (strcmp(first_arg, "--") == 0))
1003       args.Shift();
1004   }
1005 
1006   bool require_validation = false;
1007   llvm::Expected<Args> args_or =
1008       options_sp->Parse(args, &exe_ctx, PlatformSP(), require_validation);
1009   if (!args_or) {
1010     LLDB_LOG_ERROR(
1011         log, args_or.takeError(),
1012         "Parsing plugin.structured-data.darwin-log.auto-enable-options value "
1013         "failed: {0}");
1014     return EnableOptionsSP();
1015   }
1016 
1017   if (!options_sp->VerifyOptions(result))
1018     return EnableOptionsSP();
1019 
1020   // We successfully parsed and validated the options.
1021   return options_sp;
1022 }
1023 
1024 bool RunEnableCommand(CommandInterpreter &interpreter) {
1025   StreamString command_stream;
1026 
1027   command_stream << "plugin structured-data darwin-log enable";
1028   auto enable_options = GetGlobalProperties()->GetAutoEnableOptions();
1029   if (!enable_options.empty()) {
1030     command_stream << ' ';
1031     command_stream << enable_options;
1032   }
1033 
1034   // Run the command.
1035   CommandReturnObject return_object(interpreter.GetDebugger().GetUseColor());
1036   interpreter.HandleCommand(command_stream.GetData(), eLazyBoolNo,
1037                             return_object);
1038   return return_object.Succeeded();
1039 }
1040 }
1041 using namespace sddarwinlog_private;
1042 
1043 #pragma mark -
1044 #pragma mark Public static API
1045 
1046 // Public static API
1047 
1048 void StructuredDataDarwinLog::Initialize() {
1049   RegisterFilterOperations();
1050   PluginManager::RegisterPlugin(
1051       GetStaticPluginName(), "Darwin os_log() and os_activity() support",
1052       &CreateInstance, &DebuggerInitialize, &FilterLaunchInfo);
1053 }
1054 
1055 void StructuredDataDarwinLog::Terminate() {
1056   PluginManager::UnregisterPlugin(&CreateInstance);
1057 }
1058 
1059 ConstString StructuredDataDarwinLog::GetStaticPluginName() {
1060   static ConstString s_plugin_name("darwin-log");
1061   return s_plugin_name;
1062 }
1063 
1064 #pragma mark -
1065 #pragma mark PluginInterface API
1066 
1067 // PluginInterface API
1068 
1069 ConstString StructuredDataDarwinLog::GetPluginName() {
1070   return GetStaticPluginName();
1071 }
1072 
1073 uint32_t StructuredDataDarwinLog::GetPluginVersion() { return 1; }
1074 
1075 #pragma mark -
1076 #pragma mark StructuredDataPlugin API
1077 
1078 // StructuredDataPlugin API
1079 
1080 bool StructuredDataDarwinLog::SupportsStructuredDataType(
1081     ConstString type_name) {
1082   return type_name == GetDarwinLogTypeName();
1083 }
1084 
1085 void StructuredDataDarwinLog::HandleArrivalOfStructuredData(
1086     Process &process, ConstString type_name,
1087     const StructuredData::ObjectSP &object_sp) {
1088   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1089   if (log) {
1090     StreamString json_stream;
1091     if (object_sp)
1092       object_sp->Dump(json_stream);
1093     else
1094       json_stream.PutCString("<null>");
1095     LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called with json: %s",
1096               __FUNCTION__, json_stream.GetData());
1097   }
1098 
1099   // Ignore empty structured data.
1100   if (!object_sp) {
1101     LLDB_LOGF(log,
1102               "StructuredDataDarwinLog::%s() StructuredData object "
1103               "is null",
1104               __FUNCTION__);
1105     return;
1106   }
1107 
1108   // Ignore any data that isn't for us.
1109   if (type_name != GetDarwinLogTypeName()) {
1110     LLDB_LOGF(log,
1111               "StructuredDataDarwinLog::%s() StructuredData type "
1112               "expected to be %s but was %s, ignoring",
1113               __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1114               type_name.AsCString());
1115     return;
1116   }
1117 
1118   // Broadcast the structured data event if we have that enabled. This is the
1119   // way that the outside world (all clients) get access to this data.  This
1120   // plugin sets policy as to whether we do that.
1121   DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this();
1122   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1123   if (options_sp && options_sp->GetBroadcastEvents()) {
1124     LLDB_LOGF(log, "StructuredDataDarwinLog::%s() broadcasting event",
1125               __FUNCTION__);
1126     process.BroadcastStructuredData(object_sp, shared_from_this());
1127   }
1128 
1129   // Later, hang on to a configurable amount of these and allow commands to
1130   // inspect, including showing backtraces.
1131 }
1132 
1133 static void SetErrorWithJSON(Status &error, const char *message,
1134                              StructuredData::Object &object) {
1135   if (!message) {
1136     error.SetErrorString("Internal error: message not set.");
1137     return;
1138   }
1139 
1140   StreamString object_stream;
1141   object.Dump(object_stream);
1142   object_stream.Flush();
1143 
1144   error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData());
1145 }
1146 
1147 Status StructuredDataDarwinLog::GetDescription(
1148     const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) {
1149   Status error;
1150 
1151   if (!object_sp) {
1152     error.SetErrorString("No structured data.");
1153     return error;
1154   }
1155 
1156   // Log message payload objects will be dictionaries.
1157   const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
1158   if (!dictionary) {
1159     SetErrorWithJSON(error, "Structured data should have been a dictionary "
1160                             "but wasn't",
1161                      *object_sp);
1162     return error;
1163   }
1164 
1165   // Validate this is really a message for our plugin.
1166   ConstString type_name;
1167   if (!dictionary->GetValueForKeyAsString("type", type_name)) {
1168     SetErrorWithJSON(error, "Structured data doesn't contain mandatory "
1169                             "type field",
1170                      *object_sp);
1171     return error;
1172   }
1173 
1174   if (type_name != GetDarwinLogTypeName()) {
1175     // This is okay - it simply means the data we received is not a log
1176     // message.  We'll just format it as is.
1177     object_sp->Dump(stream);
1178     return error;
1179   }
1180 
1181   // DarwinLog dictionaries store their data
1182   // in an array with key name "events".
1183   StructuredData::Array *events = nullptr;
1184   if (!dictionary->GetValueForKeyAsArray("events", events) || !events) {
1185     SetErrorWithJSON(error, "Log structured data is missing mandatory "
1186                             "'events' field, expected to be an array",
1187                      *object_sp);
1188     return error;
1189   }
1190 
1191   events->ForEach(
1192       [&stream, &error, &object_sp, this](StructuredData::Object *object) {
1193         if (!object) {
1194           // Invalid.  Stop iterating.
1195           SetErrorWithJSON(error, "Log event entry is null", *object_sp);
1196           return false;
1197         }
1198 
1199         auto event = object->GetAsDictionary();
1200         if (!event) {
1201           // Invalid, stop iterating.
1202           SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp);
1203           return false;
1204         }
1205 
1206         // If we haven't already grabbed the first timestamp value, do that
1207         // now.
1208         if (!m_recorded_first_timestamp) {
1209           uint64_t timestamp = 0;
1210           if (event->GetValueForKeyAsInteger("timestamp", timestamp)) {
1211             m_first_timestamp_seen = timestamp;
1212             m_recorded_first_timestamp = true;
1213           }
1214         }
1215 
1216         HandleDisplayOfEvent(*event, stream);
1217         return true;
1218       });
1219 
1220   stream.Flush();
1221   return error;
1222 }
1223 
1224 bool StructuredDataDarwinLog::GetEnabled(ConstString type_name) const {
1225   if (type_name == GetStaticPluginName())
1226     return m_is_enabled;
1227   else
1228     return false;
1229 }
1230 
1231 void StructuredDataDarwinLog::SetEnabled(bool enabled) {
1232   m_is_enabled = enabled;
1233 }
1234 
1235 void StructuredDataDarwinLog::ModulesDidLoad(Process &process,
1236                                              ModuleList &module_list) {
1237   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1238   LLDB_LOGF(log, "StructuredDataDarwinLog::%s called (process uid %u)",
1239             __FUNCTION__, process.GetUniqueID());
1240 
1241   // Check if we should enable the darwin log support on startup/attach.
1242   if (!GetGlobalProperties()->GetEnableOnStartup() &&
1243       !s_is_explicitly_enabled) {
1244     // We're neither auto-enabled or explicitly enabled, so we shouldn't try to
1245     // enable here.
1246     LLDB_LOGF(log,
1247               "StructuredDataDarwinLog::%s not applicable, we're not "
1248               "enabled (process uid %u)",
1249               __FUNCTION__, process.GetUniqueID());
1250     return;
1251   }
1252 
1253   // If we already added the breakpoint, we've got nothing left to do.
1254   {
1255     std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1256     if (m_added_breakpoint) {
1257       LLDB_LOGF(log,
1258                 "StructuredDataDarwinLog::%s process uid %u's "
1259                 "post-libtrace-init breakpoint is already set",
1260                 __FUNCTION__, process.GetUniqueID());
1261       return;
1262     }
1263   }
1264 
1265   // The logging support module name, specifies the name of the image name that
1266   // must be loaded into the debugged process before we can try to enable
1267   // logging.
1268   const char *logging_module_cstr =
1269       GetGlobalProperties()->GetLoggingModuleName();
1270   if (!logging_module_cstr || (logging_module_cstr[0] == 0)) {
1271     // We need this.  Bail.
1272     LLDB_LOGF(log,
1273               "StructuredDataDarwinLog::%s no logging module name "
1274               "specified, we don't know where to set a breakpoint "
1275               "(process uid %u)",
1276               __FUNCTION__, process.GetUniqueID());
1277     return;
1278   }
1279 
1280   const ConstString logging_module_name = ConstString(logging_module_cstr);
1281 
1282   // We need to see libtrace in the list of modules before we can enable
1283   // tracing for the target process.
1284   bool found_logging_support_module = false;
1285   for (size_t i = 0; i < module_list.GetSize(); ++i) {
1286     auto module_sp = module_list.GetModuleAtIndex(i);
1287     if (!module_sp)
1288       continue;
1289 
1290     auto &file_spec = module_sp->GetFileSpec();
1291     found_logging_support_module =
1292         (file_spec.GetLastPathComponent() == logging_module_name);
1293     if (found_logging_support_module)
1294       break;
1295   }
1296 
1297   if (!found_logging_support_module) {
1298     LLDB_LOGF(log,
1299               "StructuredDataDarwinLog::%s logging module %s "
1300               "has not yet been loaded, can't set a breakpoint "
1301               "yet (process uid %u)",
1302               __FUNCTION__, logging_module_name.AsCString(),
1303               process.GetUniqueID());
1304     return;
1305   }
1306 
1307   // Time to enqueue the breakpoint so we can wait for logging support to be
1308   // initialized before we try to tap the libtrace stream.
1309   AddInitCompletionHook(process);
1310   LLDB_LOGF(log,
1311             "StructuredDataDarwinLog::%s post-init hook breakpoint "
1312             "set for logging module %s (process uid %u)",
1313             __FUNCTION__, logging_module_name.AsCString(),
1314             process.GetUniqueID());
1315 
1316   // We need to try the enable here as well, which will succeed in the event
1317   // that we're attaching to (rather than launching) the process and the
1318   // process is already past initialization time.  In that case, the completion
1319   // breakpoint will never get hit and therefore won't start that way.  It
1320   // doesn't hurt much beyond a bit of bandwidth if we end up doing this twice.
1321   // It hurts much more if we don't get the logging enabled when the user
1322   // expects it.
1323   EnableNow();
1324 }
1325 
1326 // public destructor
1327 
1328 StructuredDataDarwinLog::~StructuredDataDarwinLog() {
1329   if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) {
1330     ProcessSP process_sp(GetProcess());
1331     if (process_sp) {
1332       process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
1333       m_breakpoint_id = LLDB_INVALID_BREAK_ID;
1334     }
1335   }
1336 }
1337 
1338 #pragma mark -
1339 #pragma mark Private instance methods
1340 
1341 // Private constructors
1342 
1343 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp)
1344     : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false),
1345       m_first_timestamp_seen(0), m_is_enabled(false),
1346       m_added_breakpoint_mutex(), m_added_breakpoint(),
1347       m_breakpoint_id(LLDB_INVALID_BREAK_ID) {}
1348 
1349 // Private static methods
1350 
1351 StructuredDataPluginSP
1352 StructuredDataDarwinLog::CreateInstance(Process &process) {
1353   // Currently only Apple targets support the os_log/os_activity protocol.
1354   if (process.GetTarget().GetArchitecture().GetTriple().getVendor() ==
1355       llvm::Triple::VendorType::Apple) {
1356     auto process_wp = ProcessWP(process.shared_from_this());
1357     return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp));
1358   } else {
1359     return StructuredDataPluginSP();
1360   }
1361 }
1362 
1363 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) {
1364   // Setup parent class first.
1365   StructuredDataPlugin::InitializeBasePluginForDebugger(debugger);
1366 
1367   // Get parent command.
1368   auto &interpreter = debugger.GetCommandInterpreter();
1369   llvm::StringRef parent_command_text = "plugin structured-data";
1370   auto parent_command =
1371       interpreter.GetCommandObjectForCommand(parent_command_text);
1372   if (!parent_command) {
1373     // Ut oh, parent failed to create parent command.
1374     // TODO log
1375     return;
1376   }
1377 
1378   auto command_name = "darwin-log";
1379   auto command_sp = CommandObjectSP(new BaseCommand(interpreter));
1380   bool result = parent_command->LoadSubCommand(command_name, command_sp);
1381   if (!result) {
1382     // TODO log it once we setup structured data logging
1383   }
1384 
1385   if (!PluginManager::GetSettingForPlatformPlugin(
1386           debugger, StructuredDataDarwinLogProperties::GetSettingName())) {
1387     const bool is_global_setting = true;
1388     PluginManager::CreateSettingForStructuredDataPlugin(
1389         debugger, GetGlobalProperties()->GetValueProperties(),
1390         ConstString("Properties for the darwin-log"
1391                     " plug-in."),
1392         is_global_setting);
1393   }
1394 }
1395 
1396 Status StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info,
1397                                                  Target *target) {
1398   Status error;
1399 
1400   // If we're not debugging this launched process, there's nothing for us to do
1401   // here.
1402   if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug))
1403     return error;
1404 
1405   // Darwin os_log() support automatically adds debug-level and info-level
1406   // messages when a debugger is attached to a process.  However, with
1407   // integrated support for debugging built into the command-line LLDB, the
1408   // user may specifically set to *not* include debug-level and info-level
1409   // content.  When the user is using the integrated log support, we want to
1410   // put the kabosh on that automatic adding of info and debug level. This is
1411   // done by adding an environment variable to the process on launch. (This
1412   // also means it is not possible to suppress this behavior if attaching to an
1413   // already-running app).
1414   // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1415 
1416   // If the target architecture is not one that supports DarwinLog, we have
1417   // nothing to do here.
1418   auto &triple = target ? target->GetArchitecture().GetTriple()
1419                         : launch_info.GetArchitecture().GetTriple();
1420   if (triple.getVendor() != llvm::Triple::Apple) {
1421     return error;
1422   }
1423 
1424   // If DarwinLog is not enabled (either by explicit user command or via the
1425   // auto-enable option), then we have nothing to do.
1426   if (!GetGlobalProperties()->GetEnableOnStartup() &&
1427       !s_is_explicitly_enabled) {
1428     // Nothing to do, DarwinLog is not enabled.
1429     return error;
1430   }
1431 
1432   // If we don't have parsed configuration info, that implies we have enable-
1433   // on-startup set up, but we haven't yet attempted to run the enable command.
1434   if (!target) {
1435     // We really can't do this without a target.  We need to be able to get to
1436     // the debugger to get the proper options to do this right.
1437     // TODO log.
1438     error.SetErrorString("requires a target to auto-enable DarwinLog.");
1439     return error;
1440   }
1441 
1442   DebuggerSP debugger_sp = target->GetDebugger().shared_from_this();
1443   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1444   if (!options_sp && debugger_sp) {
1445     options_sp = ParseAutoEnableOptions(error, *debugger_sp.get());
1446     if (!options_sp || !error.Success())
1447       return error;
1448 
1449     // We already parsed the options, save them now so we don't generate them
1450     // again until the user runs the command manually.
1451     SetGlobalEnableOptions(debugger_sp, options_sp);
1452   }
1453 
1454   if (!options_sp->GetEchoToStdErr()) {
1455     // The user doesn't want to see os_log/NSLog messages echo to stderr. That
1456     // mechanism is entirely separate from the DarwinLog support. By default we
1457     // don't want to get it via stderr, because that would be in duplicate of
1458     // the explicit log support here.
1459 
1460     // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent
1461     // echoing of os_log()/NSLog() to stderr in the target program.
1462     launch_info.GetEnvironment().erase("OS_ACTIVITY_DT_MODE");
1463 
1464     // We will also set the env var that tells any downstream launcher from
1465     // adding OS_ACTIVITY_DT_MODE.
1466     launch_info.GetEnvironment()["IDE_DISABLED_OS_ACTIVITY_DT_MODE"] = "1";
1467   }
1468 
1469   // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable debug and
1470   // info level messages.
1471   const char *env_var_value;
1472   if (options_sp->GetIncludeDebugLevel())
1473     env_var_value = "debug";
1474   else if (options_sp->GetIncludeInfoLevel())
1475     env_var_value = "info";
1476   else
1477     env_var_value = "default";
1478 
1479   launch_info.GetEnvironment()["OS_ACTIVITY_MODE"] = env_var_value;
1480 
1481   return error;
1482 }
1483 
1484 bool StructuredDataDarwinLog::InitCompletionHookCallback(
1485     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
1486     lldb::user_id_t break_loc_id) {
1487   // We hit the init function.  We now want to enqueue our new thread plan,
1488   // which will in turn enqueue a StepOut thread plan. When the StepOut
1489   // finishes and control returns to our new thread plan, that is the time when
1490   // we can execute our logic to enable the logging support.
1491 
1492   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1493   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1494 
1495   // Get the current thread.
1496   if (!context) {
1497     LLDB_LOGF(log,
1498               "StructuredDataDarwinLog::%s() warning: no context, "
1499               "ignoring",
1500               __FUNCTION__);
1501     return false;
1502   }
1503 
1504   // Get the plugin from the process.
1505   auto process_sp = context->exe_ctx_ref.GetProcessSP();
1506   if (!process_sp) {
1507     LLDB_LOGF(log,
1508               "StructuredDataDarwinLog::%s() warning: invalid "
1509               "process in context, ignoring",
1510               __FUNCTION__);
1511     return false;
1512   }
1513   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %d",
1514             __FUNCTION__, process_sp->GetUniqueID());
1515 
1516   auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
1517   if (!plugin_sp) {
1518     LLDB_LOGF(log,
1519               "StructuredDataDarwinLog::%s() warning: no plugin for "
1520               "feature %s in process uid %u",
1521               __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1522               process_sp->GetUniqueID());
1523     return false;
1524   }
1525 
1526   // Create the callback for when the thread plan completes.
1527   bool called_enable_method = false;
1528   const auto process_uid = process_sp->GetUniqueID();
1529 
1530   std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp);
1531   ThreadPlanCallOnFunctionExit::Callback callback =
1532       [plugin_wp, &called_enable_method, log, process_uid]() {
1533         LLDB_LOGF(log,
1534                   "StructuredDataDarwinLog::post-init callback: "
1535                   "called (process uid %u)",
1536                   process_uid);
1537 
1538         auto strong_plugin_sp = plugin_wp.lock();
1539         if (!strong_plugin_sp) {
1540           LLDB_LOGF(log,
1541                     "StructuredDataDarwinLog::post-init callback: "
1542                     "plugin no longer exists, ignoring (process "
1543                     "uid %u)",
1544                     process_uid);
1545           return;
1546         }
1547         // Make sure we only call it once, just in case the thread plan hits
1548         // the breakpoint twice.
1549         if (!called_enable_method) {
1550           LLDB_LOGF(log,
1551                     "StructuredDataDarwinLog::post-init callback: "
1552                     "calling EnableNow() (process uid %u)",
1553                     process_uid);
1554           static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get())
1555               ->EnableNow();
1556           called_enable_method = true;
1557         } else {
1558           // Our breakpoint was hit more than once.  Unexpected but no harm
1559           // done.  Log it.
1560           LLDB_LOGF(log,
1561                     "StructuredDataDarwinLog::post-init callback: "
1562                     "skipping EnableNow(), already called by "
1563                     "callback [we hit this more than once] "
1564                     "(process uid %u)",
1565                     process_uid);
1566         }
1567       };
1568 
1569   // Grab the current thread.
1570   auto thread_sp = context->exe_ctx_ref.GetThreadSP();
1571   if (!thread_sp) {
1572     LLDB_LOGF(log,
1573               "StructuredDataDarwinLog::%s() warning: failed to "
1574               "retrieve the current thread from the execution "
1575               "context, nowhere to run the thread plan (process uid "
1576               "%u)",
1577               __FUNCTION__, process_sp->GetUniqueID());
1578     return false;
1579   }
1580 
1581   // Queue the thread plan.
1582   auto thread_plan_sp =
1583       ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp, callback));
1584   const bool abort_other_plans = false;
1585   thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans);
1586   LLDB_LOGF(log,
1587             "StructuredDataDarwinLog::%s() queuing thread plan on "
1588             "trace library init method entry (process uid %u)",
1589             __FUNCTION__, process_sp->GetUniqueID());
1590 
1591   // We return false here to indicate that it isn't a public stop.
1592   return false;
1593 }
1594 
1595 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) {
1596   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1597   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called (process uid %u)",
1598             __FUNCTION__, process.GetUniqueID());
1599 
1600   // Make sure we haven't already done this.
1601   {
1602     std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1603     if (m_added_breakpoint) {
1604       LLDB_LOGF(log,
1605                 "StructuredDataDarwinLog::%s() ignoring request, "
1606                 "breakpoint already set (process uid %u)",
1607                 __FUNCTION__, process.GetUniqueID());
1608       return;
1609     }
1610 
1611     // We're about to do this, don't let anybody else try to do it.
1612     m_added_breakpoint = true;
1613   }
1614 
1615   // Set a breakpoint for the process that will kick in when libtrace has
1616   // finished its initialization.
1617   Target &target = process.GetTarget();
1618 
1619   // Build up the module list.
1620   FileSpecList module_spec_list;
1621   auto module_file_spec =
1622       FileSpec(GetGlobalProperties()->GetLoggingModuleName());
1623   module_spec_list.Append(module_file_spec);
1624 
1625   // We aren't specifying a source file set.
1626   FileSpecList *source_spec_list = nullptr;
1627 
1628   const char *func_name = "_libtrace_init";
1629   const lldb::addr_t offset = 0;
1630   const LazyBool skip_prologue = eLazyBoolCalculate;
1631   // This is an internal breakpoint - the user shouldn't see it.
1632   const bool internal = true;
1633   const bool hardware = false;
1634 
1635   auto breakpoint_sp = target.CreateBreakpoint(
1636       &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull,
1637       eLanguageTypeC, offset, skip_prologue, internal, hardware);
1638   if (!breakpoint_sp) {
1639     // Huh?  Bail here.
1640     LLDB_LOGF(log,
1641               "StructuredDataDarwinLog::%s() failed to set "
1642               "breakpoint in module %s, function %s (process uid %u)",
1643               __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1644               func_name, process.GetUniqueID());
1645     return;
1646   }
1647 
1648   // Set our callback.
1649   breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr);
1650   m_breakpoint_id = breakpoint_sp->GetID();
1651   LLDB_LOGF(log,
1652             "StructuredDataDarwinLog::%s() breakpoint set in module %s,"
1653             "function %s (process uid %u)",
1654             __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1655             func_name, process.GetUniqueID());
1656 }
1657 
1658 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream,
1659                                             uint64_t timestamp) {
1660   const uint64_t delta_nanos = timestamp - m_first_timestamp_seen;
1661 
1662   const uint64_t hours = delta_nanos / NANOS_PER_HOUR;
1663   uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR;
1664 
1665   const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE;
1666   nanos_remaining = nanos_remaining % NANOS_PER_MINUTE;
1667 
1668   const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND;
1669   nanos_remaining = nanos_remaining % NANOS_PER_SECOND;
1670 
1671   stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours,
1672                 minutes, seconds, nanos_remaining);
1673 }
1674 
1675 size_t
1676 StructuredDataDarwinLog::DumpHeader(Stream &output_stream,
1677                                     const StructuredData::Dictionary &event) {
1678   StreamString stream;
1679 
1680   ProcessSP process_sp = GetProcess();
1681   if (!process_sp) {
1682     // TODO log
1683     return 0;
1684   }
1685 
1686   DebuggerSP debugger_sp =
1687       process_sp->GetTarget().GetDebugger().shared_from_this();
1688   if (!debugger_sp) {
1689     // TODO log
1690     return 0;
1691   }
1692 
1693   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1694   if (!options_sp) {
1695     // TODO log
1696     return 0;
1697   }
1698 
1699   // Check if we should even display a header.
1700   if (!options_sp->GetDisplayAnyHeaderFields())
1701     return 0;
1702 
1703   stream.PutChar('[');
1704 
1705   int header_count = 0;
1706   if (options_sp->GetDisplayTimestampRelative()) {
1707     uint64_t timestamp = 0;
1708     if (event.GetValueForKeyAsInteger("timestamp", timestamp)) {
1709       DumpTimestamp(stream, timestamp);
1710       ++header_count;
1711     }
1712   }
1713 
1714   if (options_sp->GetDisplayActivityChain()) {
1715     llvm::StringRef activity_chain;
1716     if (event.GetValueForKeyAsString("activity-chain", activity_chain) &&
1717         !activity_chain.empty()) {
1718       if (header_count > 0)
1719         stream.PutChar(',');
1720 
1721       // Display the activity chain, from parent-most to child-most activity,
1722       // separated by a colon (:).
1723       stream.PutCString("activity-chain=");
1724       stream.PutCString(activity_chain);
1725       ++header_count;
1726     }
1727   }
1728 
1729   if (options_sp->GetDisplaySubsystem()) {
1730     llvm::StringRef subsystem;
1731     if (event.GetValueForKeyAsString("subsystem", subsystem) &&
1732         !subsystem.empty()) {
1733       if (header_count > 0)
1734         stream.PutChar(',');
1735       stream.PutCString("subsystem=");
1736       stream.PutCString(subsystem);
1737       ++header_count;
1738     }
1739   }
1740 
1741   if (options_sp->GetDisplayCategory()) {
1742     llvm::StringRef category;
1743     if (event.GetValueForKeyAsString("category", category) &&
1744         !category.empty()) {
1745       if (header_count > 0)
1746         stream.PutChar(',');
1747       stream.PutCString("category=");
1748       stream.PutCString(category);
1749       ++header_count;
1750     }
1751   }
1752   stream.PutCString("] ");
1753 
1754   output_stream.PutCString(stream.GetString());
1755 
1756   return stream.GetSize();
1757 }
1758 
1759 size_t StructuredDataDarwinLog::HandleDisplayOfEvent(
1760     const StructuredData::Dictionary &event, Stream &stream) {
1761   // Check the type of the event.
1762   ConstString event_type;
1763   if (!event.GetValueForKeyAsString("type", event_type)) {
1764     // Hmm, we expected to get events that describe what they are.  Continue
1765     // anyway.
1766     return 0;
1767   }
1768 
1769   if (event_type != GetLogEventType())
1770     return 0;
1771 
1772   size_t total_bytes = 0;
1773 
1774   // Grab the message content.
1775   llvm::StringRef message;
1776   if (!event.GetValueForKeyAsString("message", message))
1777     return true;
1778 
1779   // Display the log entry.
1780   const auto len = message.size();
1781 
1782   total_bytes += DumpHeader(stream, event);
1783 
1784   stream.Write(message.data(), len);
1785   total_bytes += len;
1786 
1787   // Add an end of line.
1788   stream.PutChar('\n');
1789   total_bytes += sizeof(char);
1790 
1791   return total_bytes;
1792 }
1793 
1794 void StructuredDataDarwinLog::EnableNow() {
1795   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1796   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1797 
1798   // Run the enable command.
1799   auto process_sp = GetProcess();
1800   if (!process_sp) {
1801     // Nothing to do.
1802     LLDB_LOGF(log,
1803               "StructuredDataDarwinLog::%s() warning: failed to get "
1804               "valid process, skipping",
1805               __FUNCTION__);
1806     return;
1807   }
1808   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %u",
1809             __FUNCTION__, process_sp->GetUniqueID());
1810 
1811   // If we have configuration data, we can directly enable it now. Otherwise,
1812   // we need to run through the command interpreter to parse the auto-run
1813   // options (which is the only way we get here without having already-parsed
1814   // configuration data).
1815   DebuggerSP debugger_sp =
1816       process_sp->GetTarget().GetDebugger().shared_from_this();
1817   if (!debugger_sp) {
1818     LLDB_LOGF(log,
1819               "StructuredDataDarwinLog::%s() warning: failed to get "
1820               "debugger shared pointer, skipping (process uid %u)",
1821               __FUNCTION__, process_sp->GetUniqueID());
1822     return;
1823   }
1824 
1825   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1826   if (!options_sp) {
1827     // We haven't run the enable command yet.  Just do that now, it'll take
1828     // care of the rest.
1829     auto &interpreter = debugger_sp->GetCommandInterpreter();
1830     const bool success = RunEnableCommand(interpreter);
1831     if (log) {
1832       if (success)
1833         LLDB_LOGF(log,
1834                   "StructuredDataDarwinLog::%s() ran enable command "
1835                   "successfully for (process uid %u)",
1836                   __FUNCTION__, process_sp->GetUniqueID());
1837       else
1838         LLDB_LOGF(log,
1839                   "StructuredDataDarwinLog::%s() error: running "
1840                   "enable command failed (process uid %u)",
1841                   __FUNCTION__, process_sp->GetUniqueID());
1842     }
1843     // Report failures to the debugger error stream.
1844     auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1845     if (error_stream_sp) {
1846       error_stream_sp->Printf("failed to configure DarwinLog "
1847                               "support\n");
1848       error_stream_sp->Flush();
1849     }
1850     return;
1851   }
1852 
1853   // We've previously been enabled. We will re-enable now with the previously
1854   // specified options.
1855   auto config_sp = options_sp->BuildConfigurationData(true);
1856   if (!config_sp) {
1857     LLDB_LOGF(log,
1858               "StructuredDataDarwinLog::%s() warning: failed to "
1859               "build configuration data for enable options, skipping "
1860               "(process uid %u)",
1861               __FUNCTION__, process_sp->GetUniqueID());
1862     return;
1863   }
1864 
1865   // We can run it directly.
1866   // Send configuration to the feature by way of the process.
1867   const Status error =
1868       process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
1869 
1870   // Report results.
1871   if (!error.Success()) {
1872     LLDB_LOGF(log,
1873               "StructuredDataDarwinLog::%s() "
1874               "ConfigureStructuredData() call failed "
1875               "(process uid %u): %s",
1876               __FUNCTION__, process_sp->GetUniqueID(), error.AsCString());
1877     auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1878     if (error_stream_sp) {
1879       error_stream_sp->Printf("failed to configure DarwinLog "
1880                               "support: %s\n",
1881                               error.AsCString());
1882       error_stream_sp->Flush();
1883     }
1884     m_is_enabled = false;
1885   } else {
1886     m_is_enabled = true;
1887     LLDB_LOGF(log,
1888               "StructuredDataDarwinLog::%s() success via direct "
1889               "configuration (process uid %u)",
1890               __FUNCTION__, process_sp->GetUniqueID());
1891   }
1892 }
1893