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 = default;
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() = default;
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     }
813     StructuredDataDarwinLog &plugin =
814         *static_cast<StructuredDataDarwinLog *>(plugin_sp.get());
815 
816     if (m_enable) {
817       // Hook up the breakpoint for the process that detects when libtrace has
818       // been sufficiently initialized to really start the os_log stream.  This
819       // is insurance to assure us that logging is really enabled.  Requesting
820       // that logging be enabled for a process before libtrace is initialized
821       // results in a scenario where no errors occur, but no logging is
822       // captured, either.  This step is to eliminate that possibility.
823       plugin.AddInitCompletionHook(*process_sp);
824     }
825 
826     // Send configuration to the feature by way of the process. Construct the
827     // options we will use.
828     auto config_sp = m_options_sp->BuildConfigurationData(m_enable);
829     const Status error =
830         process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
831 
832     // Report results.
833     if (!error.Success()) {
834       result.AppendError(error.AsCString());
835       // Our configuration failed, so we're definitely disabled.
836       plugin.SetEnabled(false);
837     } else {
838       result.SetStatus(eReturnStatusSuccessFinishNoResult);
839       // Our configuration succeeded, so we're enabled/disabled per whichever
840       // one this command is setup to do.
841       plugin.SetEnabled(m_enable);
842     }
843     return result.Succeeded();
844   }
845 
846   Options *GetOptions() override {
847     // We don't have options when this represents disable.
848     return m_enable ? m_options_sp.get() : nullptr;
849   }
850 
851 private:
852   const bool m_enable;
853   EnableOptionsSP m_options_sp;
854 };
855 
856 /// Provides the status command.
857 class StatusCommand : public CommandObjectParsed {
858 public:
859   StatusCommand(CommandInterpreter &interpreter)
860       : CommandObjectParsed(interpreter, "status",
861                             "Show whether Darwin log supported is available"
862                             " and enabled.",
863                             "plugin structured-data darwin-log status") {}
864 
865 protected:
866   bool DoExecute(Args &command, CommandReturnObject &result) override {
867     auto &stream = result.GetOutputStream();
868 
869     // Figure out if we've got a process.  If so, we can tell if DarwinLog is
870     // available for that process.
871     Target &target = GetSelectedOrDummyTarget();
872     auto process_sp = target.GetProcessSP();
873     if (!process_sp) {
874       stream.PutCString("Availability: unknown (requires process)\n");
875       stream.PutCString("Enabled: not applicable "
876                         "(requires process)\n");
877     } else {
878       auto plugin_sp =
879           process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
880       stream.Printf("Availability: %s\n",
881                     plugin_sp ? "available" : "unavailable");
882       ConstString plugin_name = StructuredDataDarwinLog::GetStaticPluginName();
883       const bool enabled =
884           plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false;
885       stream.Printf("Enabled: %s\n", enabled ? "true" : "false");
886     }
887 
888     // Display filter settings.
889     DebuggerSP debugger_sp =
890         GetCommandInterpreter().GetDebugger().shared_from_this();
891     auto options_sp = GetGlobalEnableOptions(debugger_sp);
892     if (!options_sp) {
893       // Nothing more to do.
894       result.SetStatus(eReturnStatusSuccessFinishResult);
895       return true;
896     }
897 
898     // Print filter rules
899     stream.PutCString("DarwinLog filter rules:\n");
900 
901     stream.IndentMore();
902 
903     if (options_sp->GetFilterRules().empty()) {
904       stream.Indent();
905       stream.PutCString("none\n");
906     } else {
907       // Print each of the filter rules.
908       int rule_number = 0;
909       for (auto rule_sp : options_sp->GetFilterRules()) {
910         ++rule_number;
911         if (!rule_sp)
912           continue;
913 
914         stream.Indent();
915         stream.Printf("%02d: ", rule_number);
916         rule_sp->Dump(stream);
917         stream.PutChar('\n');
918       }
919     }
920     stream.IndentLess();
921 
922     // Print no-match handling.
923     stream.Indent();
924     stream.Printf("no-match behavior: %s\n",
925                   options_sp->GetFallthroughAccepts() ? "accept" : "reject");
926 
927     result.SetStatus(eReturnStatusSuccessFinishResult);
928     return true;
929   }
930 };
931 
932 /// Provides the darwin-log base command
933 class BaseCommand : public CommandObjectMultiword {
934 public:
935   BaseCommand(CommandInterpreter &interpreter)
936       : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log",
937                                "Commands for configuring Darwin os_log "
938                                "support.",
939                                "") {
940     // enable
941     auto enable_help = "Enable Darwin log collection, or re-enable "
942                        "with modified configuration.";
943     auto enable_syntax = "plugin structured-data darwin-log enable";
944     auto enable_cmd_sp = CommandObjectSP(
945         new EnableCommand(interpreter,
946                           true, // enable
947                           "enable", enable_help, enable_syntax));
948     LoadSubCommand("enable", enable_cmd_sp);
949 
950     // disable
951     auto disable_help = "Disable Darwin log collection.";
952     auto disable_syntax = "plugin structured-data darwin-log disable";
953     auto disable_cmd_sp = CommandObjectSP(
954         new EnableCommand(interpreter,
955                           false, // disable
956                           "disable", disable_help, disable_syntax));
957     LoadSubCommand("disable", disable_cmd_sp);
958 
959     // status
960     auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter));
961     LoadSubCommand("status", status_cmd_sp);
962   }
963 };
964 
965 EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger) {
966   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
967   // We are abusing the options data model here so that we can parse options
968   // without requiring the Debugger instance.
969 
970   // We have an empty execution context at this point.  We only want to parse
971   // options, and we don't need any context to do this here. In fact, we want
972   // to be able to parse the enable options before having any context.
973   ExecutionContext exe_ctx;
974 
975   EnableOptionsSP options_sp(new EnableOptions());
976   options_sp->NotifyOptionParsingStarting(&exe_ctx);
977 
978   CommandReturnObject result(debugger.GetUseColor());
979 
980   // Parse the arguments.
981   auto options_property_sp =
982       debugger.GetPropertyValue(nullptr, "plugin.structured-data.darwin-log."
983                                          "auto-enable-options",
984                                 false, error);
985   if (!error.Success())
986     return EnableOptionsSP();
987   if (!options_property_sp) {
988     error.SetErrorString("failed to find option setting for "
989                          "plugin.structured-data.darwin-log.");
990     return EnableOptionsSP();
991   }
992 
993   const char *enable_options =
994       options_property_sp->GetAsString()->GetCurrentValue();
995   Args args(enable_options);
996   if (args.GetArgumentCount() > 0) {
997     // Eliminate the initial '--' that would be required to set the settings
998     // that themselves include '-' and/or '--'.
999     const char *first_arg = args.GetArgumentAtIndex(0);
1000     if (first_arg && (strcmp(first_arg, "--") == 0))
1001       args.Shift();
1002   }
1003 
1004   bool require_validation = false;
1005   llvm::Expected<Args> args_or =
1006       options_sp->Parse(args, &exe_ctx, PlatformSP(), require_validation);
1007   if (!args_or) {
1008     LLDB_LOG_ERROR(
1009         log, args_or.takeError(),
1010         "Parsing plugin.structured-data.darwin-log.auto-enable-options value "
1011         "failed: {0}");
1012     return EnableOptionsSP();
1013   }
1014 
1015   if (!options_sp->VerifyOptions(result))
1016     return EnableOptionsSP();
1017 
1018   // We successfully parsed and validated the options.
1019   return options_sp;
1020 }
1021 
1022 bool RunEnableCommand(CommandInterpreter &interpreter) {
1023   StreamString command_stream;
1024 
1025   command_stream << "plugin structured-data darwin-log enable";
1026   auto enable_options = GetGlobalProperties()->GetAutoEnableOptions();
1027   if (!enable_options.empty()) {
1028     command_stream << ' ';
1029     command_stream << enable_options;
1030   }
1031 
1032   // Run the command.
1033   CommandReturnObject return_object(interpreter.GetDebugger().GetUseColor());
1034   interpreter.HandleCommand(command_stream.GetData(), eLazyBoolNo,
1035                             return_object);
1036   return return_object.Succeeded();
1037 }
1038 }
1039 using namespace sddarwinlog_private;
1040 
1041 #pragma mark -
1042 #pragma mark Public static API
1043 
1044 // Public static API
1045 
1046 void StructuredDataDarwinLog::Initialize() {
1047   RegisterFilterOperations();
1048   PluginManager::RegisterPlugin(
1049       GetStaticPluginName(), "Darwin os_log() and os_activity() support",
1050       &CreateInstance, &DebuggerInitialize, &FilterLaunchInfo);
1051 }
1052 
1053 void StructuredDataDarwinLog::Terminate() {
1054   PluginManager::UnregisterPlugin(&CreateInstance);
1055 }
1056 
1057 ConstString StructuredDataDarwinLog::GetStaticPluginName() {
1058   static ConstString s_plugin_name("darwin-log");
1059   return s_plugin_name;
1060 }
1061 
1062 #pragma mark -
1063 #pragma mark PluginInterface API
1064 
1065 // PluginInterface API
1066 
1067 ConstString StructuredDataDarwinLog::GetPluginName() {
1068   return GetStaticPluginName();
1069 }
1070 
1071 #pragma mark -
1072 #pragma mark StructuredDataPlugin API
1073 
1074 // StructuredDataPlugin API
1075 
1076 bool StructuredDataDarwinLog::SupportsStructuredDataType(
1077     ConstString type_name) {
1078   return type_name == GetDarwinLogTypeName();
1079 }
1080 
1081 void StructuredDataDarwinLog::HandleArrivalOfStructuredData(
1082     Process &process, ConstString type_name,
1083     const StructuredData::ObjectSP &object_sp) {
1084   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1085   if (log) {
1086     StreamString json_stream;
1087     if (object_sp)
1088       object_sp->Dump(json_stream);
1089     else
1090       json_stream.PutCString("<null>");
1091     LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called with json: %s",
1092               __FUNCTION__, json_stream.GetData());
1093   }
1094 
1095   // Ignore empty structured data.
1096   if (!object_sp) {
1097     LLDB_LOGF(log,
1098               "StructuredDataDarwinLog::%s() StructuredData object "
1099               "is null",
1100               __FUNCTION__);
1101     return;
1102   }
1103 
1104   // Ignore any data that isn't for us.
1105   if (type_name != GetDarwinLogTypeName()) {
1106     LLDB_LOGF(log,
1107               "StructuredDataDarwinLog::%s() StructuredData type "
1108               "expected to be %s but was %s, ignoring",
1109               __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1110               type_name.AsCString());
1111     return;
1112   }
1113 
1114   // Broadcast the structured data event if we have that enabled. This is the
1115   // way that the outside world (all clients) get access to this data.  This
1116   // plugin sets policy as to whether we do that.
1117   DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this();
1118   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1119   if (options_sp && options_sp->GetBroadcastEvents()) {
1120     LLDB_LOGF(log, "StructuredDataDarwinLog::%s() broadcasting event",
1121               __FUNCTION__);
1122     process.BroadcastStructuredData(object_sp, shared_from_this());
1123   }
1124 
1125   // Later, hang on to a configurable amount of these and allow commands to
1126   // inspect, including showing backtraces.
1127 }
1128 
1129 static void SetErrorWithJSON(Status &error, const char *message,
1130                              StructuredData::Object &object) {
1131   if (!message) {
1132     error.SetErrorString("Internal error: message not set.");
1133     return;
1134   }
1135 
1136   StreamString object_stream;
1137   object.Dump(object_stream);
1138   object_stream.Flush();
1139 
1140   error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData());
1141 }
1142 
1143 Status StructuredDataDarwinLog::GetDescription(
1144     const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) {
1145   Status error;
1146 
1147   if (!object_sp) {
1148     error.SetErrorString("No structured data.");
1149     return error;
1150   }
1151 
1152   // Log message payload objects will be dictionaries.
1153   const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
1154   if (!dictionary) {
1155     SetErrorWithJSON(error, "Structured data should have been a dictionary "
1156                             "but wasn't",
1157                      *object_sp);
1158     return error;
1159   }
1160 
1161   // Validate this is really a message for our plugin.
1162   ConstString type_name;
1163   if (!dictionary->GetValueForKeyAsString("type", type_name)) {
1164     SetErrorWithJSON(error, "Structured data doesn't contain mandatory "
1165                             "type field",
1166                      *object_sp);
1167     return error;
1168   }
1169 
1170   if (type_name != GetDarwinLogTypeName()) {
1171     // This is okay - it simply means the data we received is not a log
1172     // message.  We'll just format it as is.
1173     object_sp->Dump(stream);
1174     return error;
1175   }
1176 
1177   // DarwinLog dictionaries store their data
1178   // in an array with key name "events".
1179   StructuredData::Array *events = nullptr;
1180   if (!dictionary->GetValueForKeyAsArray("events", events) || !events) {
1181     SetErrorWithJSON(error, "Log structured data is missing mandatory "
1182                             "'events' field, expected to be an array",
1183                      *object_sp);
1184     return error;
1185   }
1186 
1187   events->ForEach(
1188       [&stream, &error, &object_sp, this](StructuredData::Object *object) {
1189         if (!object) {
1190           // Invalid.  Stop iterating.
1191           SetErrorWithJSON(error, "Log event entry is null", *object_sp);
1192           return false;
1193         }
1194 
1195         auto event = object->GetAsDictionary();
1196         if (!event) {
1197           // Invalid, stop iterating.
1198           SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp);
1199           return false;
1200         }
1201 
1202         // If we haven't already grabbed the first timestamp value, do that
1203         // now.
1204         if (!m_recorded_first_timestamp) {
1205           uint64_t timestamp = 0;
1206           if (event->GetValueForKeyAsInteger("timestamp", timestamp)) {
1207             m_first_timestamp_seen = timestamp;
1208             m_recorded_first_timestamp = true;
1209           }
1210         }
1211 
1212         HandleDisplayOfEvent(*event, stream);
1213         return true;
1214       });
1215 
1216   stream.Flush();
1217   return error;
1218 }
1219 
1220 bool StructuredDataDarwinLog::GetEnabled(ConstString type_name) const {
1221   if (type_name == GetStaticPluginName())
1222     return m_is_enabled;
1223   else
1224     return false;
1225 }
1226 
1227 void StructuredDataDarwinLog::SetEnabled(bool enabled) {
1228   m_is_enabled = enabled;
1229 }
1230 
1231 void StructuredDataDarwinLog::ModulesDidLoad(Process &process,
1232                                              ModuleList &module_list) {
1233   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1234   LLDB_LOGF(log, "StructuredDataDarwinLog::%s called (process uid %u)",
1235             __FUNCTION__, process.GetUniqueID());
1236 
1237   // Check if we should enable the darwin log support on startup/attach.
1238   if (!GetGlobalProperties()->GetEnableOnStartup() &&
1239       !s_is_explicitly_enabled) {
1240     // We're neither auto-enabled or explicitly enabled, so we shouldn't try to
1241     // enable here.
1242     LLDB_LOGF(log,
1243               "StructuredDataDarwinLog::%s not applicable, we're not "
1244               "enabled (process uid %u)",
1245               __FUNCTION__, process.GetUniqueID());
1246     return;
1247   }
1248 
1249   // If we already added the breakpoint, we've got nothing left to do.
1250   {
1251     std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1252     if (m_added_breakpoint) {
1253       LLDB_LOGF(log,
1254                 "StructuredDataDarwinLog::%s process uid %u's "
1255                 "post-libtrace-init breakpoint is already set",
1256                 __FUNCTION__, process.GetUniqueID());
1257       return;
1258     }
1259   }
1260 
1261   // The logging support module name, specifies the name of the image name that
1262   // must be loaded into the debugged process before we can try to enable
1263   // logging.
1264   const char *logging_module_cstr =
1265       GetGlobalProperties()->GetLoggingModuleName();
1266   if (!logging_module_cstr || (logging_module_cstr[0] == 0)) {
1267     // We need this.  Bail.
1268     LLDB_LOGF(log,
1269               "StructuredDataDarwinLog::%s no logging module name "
1270               "specified, we don't know where to set a breakpoint "
1271               "(process uid %u)",
1272               __FUNCTION__, process.GetUniqueID());
1273     return;
1274   }
1275 
1276   const ConstString logging_module_name = ConstString(logging_module_cstr);
1277 
1278   // We need to see libtrace in the list of modules before we can enable
1279   // tracing for the target process.
1280   bool found_logging_support_module = false;
1281   for (size_t i = 0; i < module_list.GetSize(); ++i) {
1282     auto module_sp = module_list.GetModuleAtIndex(i);
1283     if (!module_sp)
1284       continue;
1285 
1286     auto &file_spec = module_sp->GetFileSpec();
1287     found_logging_support_module =
1288         (file_spec.GetLastPathComponent() == logging_module_name);
1289     if (found_logging_support_module)
1290       break;
1291   }
1292 
1293   if (!found_logging_support_module) {
1294     LLDB_LOGF(log,
1295               "StructuredDataDarwinLog::%s logging module %s "
1296               "has not yet been loaded, can't set a breakpoint "
1297               "yet (process uid %u)",
1298               __FUNCTION__, logging_module_name.AsCString(),
1299               process.GetUniqueID());
1300     return;
1301   }
1302 
1303   // Time to enqueue the breakpoint so we can wait for logging support to be
1304   // initialized before we try to tap the libtrace stream.
1305   AddInitCompletionHook(process);
1306   LLDB_LOGF(log,
1307             "StructuredDataDarwinLog::%s post-init hook breakpoint "
1308             "set for logging module %s (process uid %u)",
1309             __FUNCTION__, logging_module_name.AsCString(),
1310             process.GetUniqueID());
1311 
1312   // We need to try the enable here as well, which will succeed in the event
1313   // that we're attaching to (rather than launching) the process and the
1314   // process is already past initialization time.  In that case, the completion
1315   // breakpoint will never get hit and therefore won't start that way.  It
1316   // doesn't hurt much beyond a bit of bandwidth if we end up doing this twice.
1317   // It hurts much more if we don't get the logging enabled when the user
1318   // expects it.
1319   EnableNow();
1320 }
1321 
1322 // public destructor
1323 
1324 StructuredDataDarwinLog::~StructuredDataDarwinLog() {
1325   if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) {
1326     ProcessSP process_sp(GetProcess());
1327     if (process_sp) {
1328       process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
1329       m_breakpoint_id = LLDB_INVALID_BREAK_ID;
1330     }
1331   }
1332 }
1333 
1334 #pragma mark -
1335 #pragma mark Private instance methods
1336 
1337 // Private constructors
1338 
1339 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp)
1340     : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false),
1341       m_first_timestamp_seen(0), m_is_enabled(false),
1342       m_added_breakpoint_mutex(), m_added_breakpoint(),
1343       m_breakpoint_id(LLDB_INVALID_BREAK_ID) {}
1344 
1345 // Private static methods
1346 
1347 StructuredDataPluginSP
1348 StructuredDataDarwinLog::CreateInstance(Process &process) {
1349   // Currently only Apple targets support the os_log/os_activity protocol.
1350   if (process.GetTarget().GetArchitecture().GetTriple().getVendor() ==
1351       llvm::Triple::VendorType::Apple) {
1352     auto process_wp = ProcessWP(process.shared_from_this());
1353     return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp));
1354   } else {
1355     return StructuredDataPluginSP();
1356   }
1357 }
1358 
1359 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) {
1360   // Setup parent class first.
1361   StructuredDataPlugin::InitializeBasePluginForDebugger(debugger);
1362 
1363   // Get parent command.
1364   auto &interpreter = debugger.GetCommandInterpreter();
1365   llvm::StringRef parent_command_text = "plugin structured-data";
1366   auto parent_command =
1367       interpreter.GetCommandObjectForCommand(parent_command_text);
1368   if (!parent_command) {
1369     // Ut oh, parent failed to create parent command.
1370     // TODO log
1371     return;
1372   }
1373 
1374   auto command_name = "darwin-log";
1375   auto command_sp = CommandObjectSP(new BaseCommand(interpreter));
1376   bool result = parent_command->LoadSubCommand(command_name, command_sp);
1377   if (!result) {
1378     // TODO log it once we setup structured data logging
1379   }
1380 
1381   if (!PluginManager::GetSettingForPlatformPlugin(
1382           debugger, StructuredDataDarwinLogProperties::GetSettingName())) {
1383     const bool is_global_setting = true;
1384     PluginManager::CreateSettingForStructuredDataPlugin(
1385         debugger, GetGlobalProperties()->GetValueProperties(),
1386         ConstString("Properties for the darwin-log"
1387                     " plug-in."),
1388         is_global_setting);
1389   }
1390 }
1391 
1392 Status StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info,
1393                                                  Target *target) {
1394   Status error;
1395 
1396   // If we're not debugging this launched process, there's nothing for us to do
1397   // here.
1398   if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug))
1399     return error;
1400 
1401   // Darwin os_log() support automatically adds debug-level and info-level
1402   // messages when a debugger is attached to a process.  However, with
1403   // integrated support for debugging built into the command-line LLDB, the
1404   // user may specifically set to *not* include debug-level and info-level
1405   // content.  When the user is using the integrated log support, we want to
1406   // put the kabosh on that automatic adding of info and debug level. This is
1407   // done by adding an environment variable to the process on launch. (This
1408   // also means it is not possible to suppress this behavior if attaching to an
1409   // already-running app).
1410   // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1411 
1412   // If the target architecture is not one that supports DarwinLog, we have
1413   // nothing to do here.
1414   auto &triple = target ? target->GetArchitecture().GetTriple()
1415                         : launch_info.GetArchitecture().GetTriple();
1416   if (triple.getVendor() != llvm::Triple::Apple) {
1417     return error;
1418   }
1419 
1420   // If DarwinLog is not enabled (either by explicit user command or via the
1421   // auto-enable option), then we have nothing to do.
1422   if (!GetGlobalProperties()->GetEnableOnStartup() &&
1423       !s_is_explicitly_enabled) {
1424     // Nothing to do, DarwinLog is not enabled.
1425     return error;
1426   }
1427 
1428   // If we don't have parsed configuration info, that implies we have enable-
1429   // on-startup set up, but we haven't yet attempted to run the enable command.
1430   if (!target) {
1431     // We really can't do this without a target.  We need to be able to get to
1432     // the debugger to get the proper options to do this right.
1433     // TODO log.
1434     error.SetErrorString("requires a target to auto-enable DarwinLog.");
1435     return error;
1436   }
1437 
1438   DebuggerSP debugger_sp = target->GetDebugger().shared_from_this();
1439   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1440   if (!options_sp && debugger_sp) {
1441     options_sp = ParseAutoEnableOptions(error, *debugger_sp.get());
1442     if (!options_sp || !error.Success())
1443       return error;
1444 
1445     // We already parsed the options, save them now so we don't generate them
1446     // again until the user runs the command manually.
1447     SetGlobalEnableOptions(debugger_sp, options_sp);
1448   }
1449 
1450   if (!options_sp->GetEchoToStdErr()) {
1451     // The user doesn't want to see os_log/NSLog messages echo to stderr. That
1452     // mechanism is entirely separate from the DarwinLog support. By default we
1453     // don't want to get it via stderr, because that would be in duplicate of
1454     // the explicit log support here.
1455 
1456     // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent
1457     // echoing of os_log()/NSLog() to stderr in the target program.
1458     launch_info.GetEnvironment().erase("OS_ACTIVITY_DT_MODE");
1459 
1460     // We will also set the env var that tells any downstream launcher from
1461     // adding OS_ACTIVITY_DT_MODE.
1462     launch_info.GetEnvironment()["IDE_DISABLED_OS_ACTIVITY_DT_MODE"] = "1";
1463   }
1464 
1465   // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable debug and
1466   // info level messages.
1467   const char *env_var_value;
1468   if (options_sp->GetIncludeDebugLevel())
1469     env_var_value = "debug";
1470   else if (options_sp->GetIncludeInfoLevel())
1471     env_var_value = "info";
1472   else
1473     env_var_value = "default";
1474 
1475   launch_info.GetEnvironment()["OS_ACTIVITY_MODE"] = env_var_value;
1476 
1477   return error;
1478 }
1479 
1480 bool StructuredDataDarwinLog::InitCompletionHookCallback(
1481     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
1482     lldb::user_id_t break_loc_id) {
1483   // We hit the init function.  We now want to enqueue our new thread plan,
1484   // which will in turn enqueue a StepOut thread plan. When the StepOut
1485   // finishes and control returns to our new thread plan, that is the time when
1486   // we can execute our logic to enable the logging support.
1487 
1488   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1489   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1490 
1491   // Get the current thread.
1492   if (!context) {
1493     LLDB_LOGF(log,
1494               "StructuredDataDarwinLog::%s() warning: no context, "
1495               "ignoring",
1496               __FUNCTION__);
1497     return false;
1498   }
1499 
1500   // Get the plugin from the process.
1501   auto process_sp = context->exe_ctx_ref.GetProcessSP();
1502   if (!process_sp) {
1503     LLDB_LOGF(log,
1504               "StructuredDataDarwinLog::%s() warning: invalid "
1505               "process in context, ignoring",
1506               __FUNCTION__);
1507     return false;
1508   }
1509   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %d",
1510             __FUNCTION__, process_sp->GetUniqueID());
1511 
1512   auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
1513   if (!plugin_sp) {
1514     LLDB_LOGF(log,
1515               "StructuredDataDarwinLog::%s() warning: no plugin for "
1516               "feature %s in process uid %u",
1517               __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1518               process_sp->GetUniqueID());
1519     return false;
1520   }
1521 
1522   // Create the callback for when the thread plan completes.
1523   bool called_enable_method = false;
1524   const auto process_uid = process_sp->GetUniqueID();
1525 
1526   std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp);
1527   ThreadPlanCallOnFunctionExit::Callback callback =
1528       [plugin_wp, &called_enable_method, log, process_uid]() {
1529         LLDB_LOGF(log,
1530                   "StructuredDataDarwinLog::post-init callback: "
1531                   "called (process uid %u)",
1532                   process_uid);
1533 
1534         auto strong_plugin_sp = plugin_wp.lock();
1535         if (!strong_plugin_sp) {
1536           LLDB_LOGF(log,
1537                     "StructuredDataDarwinLog::post-init callback: "
1538                     "plugin no longer exists, ignoring (process "
1539                     "uid %u)",
1540                     process_uid);
1541           return;
1542         }
1543         // Make sure we only call it once, just in case the thread plan hits
1544         // the breakpoint twice.
1545         if (!called_enable_method) {
1546           LLDB_LOGF(log,
1547                     "StructuredDataDarwinLog::post-init callback: "
1548                     "calling EnableNow() (process uid %u)",
1549                     process_uid);
1550           static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get())
1551               ->EnableNow();
1552           called_enable_method = true;
1553         } else {
1554           // Our breakpoint was hit more than once.  Unexpected but no harm
1555           // done.  Log it.
1556           LLDB_LOGF(log,
1557                     "StructuredDataDarwinLog::post-init callback: "
1558                     "skipping EnableNow(), already called by "
1559                     "callback [we hit this more than once] "
1560                     "(process uid %u)",
1561                     process_uid);
1562         }
1563       };
1564 
1565   // Grab the current thread.
1566   auto thread_sp = context->exe_ctx_ref.GetThreadSP();
1567   if (!thread_sp) {
1568     LLDB_LOGF(log,
1569               "StructuredDataDarwinLog::%s() warning: failed to "
1570               "retrieve the current thread from the execution "
1571               "context, nowhere to run the thread plan (process uid "
1572               "%u)",
1573               __FUNCTION__, process_sp->GetUniqueID());
1574     return false;
1575   }
1576 
1577   // Queue the thread plan.
1578   auto thread_plan_sp =
1579       ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp, callback));
1580   const bool abort_other_plans = false;
1581   thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans);
1582   LLDB_LOGF(log,
1583             "StructuredDataDarwinLog::%s() queuing thread plan on "
1584             "trace library init method entry (process uid %u)",
1585             __FUNCTION__, process_sp->GetUniqueID());
1586 
1587   // We return false here to indicate that it isn't a public stop.
1588   return false;
1589 }
1590 
1591 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) {
1592   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1593   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called (process uid %u)",
1594             __FUNCTION__, process.GetUniqueID());
1595 
1596   // Make sure we haven't already done this.
1597   {
1598     std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1599     if (m_added_breakpoint) {
1600       LLDB_LOGF(log,
1601                 "StructuredDataDarwinLog::%s() ignoring request, "
1602                 "breakpoint already set (process uid %u)",
1603                 __FUNCTION__, process.GetUniqueID());
1604       return;
1605     }
1606 
1607     // We're about to do this, don't let anybody else try to do it.
1608     m_added_breakpoint = true;
1609   }
1610 
1611   // Set a breakpoint for the process that will kick in when libtrace has
1612   // finished its initialization.
1613   Target &target = process.GetTarget();
1614 
1615   // Build up the module list.
1616   FileSpecList module_spec_list;
1617   auto module_file_spec =
1618       FileSpec(GetGlobalProperties()->GetLoggingModuleName());
1619   module_spec_list.Append(module_file_spec);
1620 
1621   // We aren't specifying a source file set.
1622   FileSpecList *source_spec_list = nullptr;
1623 
1624   const char *func_name = "_libtrace_init";
1625   const lldb::addr_t offset = 0;
1626   const LazyBool skip_prologue = eLazyBoolCalculate;
1627   // This is an internal breakpoint - the user shouldn't see it.
1628   const bool internal = true;
1629   const bool hardware = false;
1630 
1631   auto breakpoint_sp = target.CreateBreakpoint(
1632       &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull,
1633       eLanguageTypeC, offset, skip_prologue, internal, hardware);
1634   if (!breakpoint_sp) {
1635     // Huh?  Bail here.
1636     LLDB_LOGF(log,
1637               "StructuredDataDarwinLog::%s() failed to set "
1638               "breakpoint in module %s, function %s (process uid %u)",
1639               __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1640               func_name, process.GetUniqueID());
1641     return;
1642   }
1643 
1644   // Set our callback.
1645   breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr);
1646   m_breakpoint_id = breakpoint_sp->GetID();
1647   LLDB_LOGF(log,
1648             "StructuredDataDarwinLog::%s() breakpoint set in module %s,"
1649             "function %s (process uid %u)",
1650             __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1651             func_name, process.GetUniqueID());
1652 }
1653 
1654 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream,
1655                                             uint64_t timestamp) {
1656   const uint64_t delta_nanos = timestamp - m_first_timestamp_seen;
1657 
1658   const uint64_t hours = delta_nanos / NANOS_PER_HOUR;
1659   uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR;
1660 
1661   const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE;
1662   nanos_remaining = nanos_remaining % NANOS_PER_MINUTE;
1663 
1664   const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND;
1665   nanos_remaining = nanos_remaining % NANOS_PER_SECOND;
1666 
1667   stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours,
1668                 minutes, seconds, nanos_remaining);
1669 }
1670 
1671 size_t
1672 StructuredDataDarwinLog::DumpHeader(Stream &output_stream,
1673                                     const StructuredData::Dictionary &event) {
1674   StreamString stream;
1675 
1676   ProcessSP process_sp = GetProcess();
1677   if (!process_sp) {
1678     // TODO log
1679     return 0;
1680   }
1681 
1682   DebuggerSP debugger_sp =
1683       process_sp->GetTarget().GetDebugger().shared_from_this();
1684   if (!debugger_sp) {
1685     // TODO log
1686     return 0;
1687   }
1688 
1689   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1690   if (!options_sp) {
1691     // TODO log
1692     return 0;
1693   }
1694 
1695   // Check if we should even display a header.
1696   if (!options_sp->GetDisplayAnyHeaderFields())
1697     return 0;
1698 
1699   stream.PutChar('[');
1700 
1701   int header_count = 0;
1702   if (options_sp->GetDisplayTimestampRelative()) {
1703     uint64_t timestamp = 0;
1704     if (event.GetValueForKeyAsInteger("timestamp", timestamp)) {
1705       DumpTimestamp(stream, timestamp);
1706       ++header_count;
1707     }
1708   }
1709 
1710   if (options_sp->GetDisplayActivityChain()) {
1711     llvm::StringRef activity_chain;
1712     if (event.GetValueForKeyAsString("activity-chain", activity_chain) &&
1713         !activity_chain.empty()) {
1714       if (header_count > 0)
1715         stream.PutChar(',');
1716 
1717       // Display the activity chain, from parent-most to child-most activity,
1718       // separated by a colon (:).
1719       stream.PutCString("activity-chain=");
1720       stream.PutCString(activity_chain);
1721       ++header_count;
1722     }
1723   }
1724 
1725   if (options_sp->GetDisplaySubsystem()) {
1726     llvm::StringRef subsystem;
1727     if (event.GetValueForKeyAsString("subsystem", subsystem) &&
1728         !subsystem.empty()) {
1729       if (header_count > 0)
1730         stream.PutChar(',');
1731       stream.PutCString("subsystem=");
1732       stream.PutCString(subsystem);
1733       ++header_count;
1734     }
1735   }
1736 
1737   if (options_sp->GetDisplayCategory()) {
1738     llvm::StringRef category;
1739     if (event.GetValueForKeyAsString("category", category) &&
1740         !category.empty()) {
1741       if (header_count > 0)
1742         stream.PutChar(',');
1743       stream.PutCString("category=");
1744       stream.PutCString(category);
1745       ++header_count;
1746     }
1747   }
1748   stream.PutCString("] ");
1749 
1750   output_stream.PutCString(stream.GetString());
1751 
1752   return stream.GetSize();
1753 }
1754 
1755 size_t StructuredDataDarwinLog::HandleDisplayOfEvent(
1756     const StructuredData::Dictionary &event, Stream &stream) {
1757   // Check the type of the event.
1758   ConstString event_type;
1759   if (!event.GetValueForKeyAsString("type", event_type)) {
1760     // Hmm, we expected to get events that describe what they are.  Continue
1761     // anyway.
1762     return 0;
1763   }
1764 
1765   if (event_type != GetLogEventType())
1766     return 0;
1767 
1768   size_t total_bytes = 0;
1769 
1770   // Grab the message content.
1771   llvm::StringRef message;
1772   if (!event.GetValueForKeyAsString("message", message))
1773     return true;
1774 
1775   // Display the log entry.
1776   const auto len = message.size();
1777 
1778   total_bytes += DumpHeader(stream, event);
1779 
1780   stream.Write(message.data(), len);
1781   total_bytes += len;
1782 
1783   // Add an end of line.
1784   stream.PutChar('\n');
1785   total_bytes += sizeof(char);
1786 
1787   return total_bytes;
1788 }
1789 
1790 void StructuredDataDarwinLog::EnableNow() {
1791   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1792   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1793 
1794   // Run the enable command.
1795   auto process_sp = GetProcess();
1796   if (!process_sp) {
1797     // Nothing to do.
1798     LLDB_LOGF(log,
1799               "StructuredDataDarwinLog::%s() warning: failed to get "
1800               "valid process, skipping",
1801               __FUNCTION__);
1802     return;
1803   }
1804   LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %u",
1805             __FUNCTION__, process_sp->GetUniqueID());
1806 
1807   // If we have configuration data, we can directly enable it now. Otherwise,
1808   // we need to run through the command interpreter to parse the auto-run
1809   // options (which is the only way we get here without having already-parsed
1810   // configuration data).
1811   DebuggerSP debugger_sp =
1812       process_sp->GetTarget().GetDebugger().shared_from_this();
1813   if (!debugger_sp) {
1814     LLDB_LOGF(log,
1815               "StructuredDataDarwinLog::%s() warning: failed to get "
1816               "debugger shared pointer, skipping (process uid %u)",
1817               __FUNCTION__, process_sp->GetUniqueID());
1818     return;
1819   }
1820 
1821   auto options_sp = GetGlobalEnableOptions(debugger_sp);
1822   if (!options_sp) {
1823     // We haven't run the enable command yet.  Just do that now, it'll take
1824     // care of the rest.
1825     auto &interpreter = debugger_sp->GetCommandInterpreter();
1826     const bool success = RunEnableCommand(interpreter);
1827     if (log) {
1828       if (success)
1829         LLDB_LOGF(log,
1830                   "StructuredDataDarwinLog::%s() ran enable command "
1831                   "successfully for (process uid %u)",
1832                   __FUNCTION__, process_sp->GetUniqueID());
1833       else
1834         LLDB_LOGF(log,
1835                   "StructuredDataDarwinLog::%s() error: running "
1836                   "enable command failed (process uid %u)",
1837                   __FUNCTION__, process_sp->GetUniqueID());
1838     }
1839     // Report failures to the debugger error stream.
1840     auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1841     if (error_stream_sp) {
1842       error_stream_sp->Printf("failed to configure DarwinLog "
1843                               "support\n");
1844       error_stream_sp->Flush();
1845     }
1846     return;
1847   }
1848 
1849   // We've previously been enabled. We will re-enable now with the previously
1850   // specified options.
1851   auto config_sp = options_sp->BuildConfigurationData(true);
1852   if (!config_sp) {
1853     LLDB_LOGF(log,
1854               "StructuredDataDarwinLog::%s() warning: failed to "
1855               "build configuration data for enable options, skipping "
1856               "(process uid %u)",
1857               __FUNCTION__, process_sp->GetUniqueID());
1858     return;
1859   }
1860 
1861   // We can run it directly.
1862   // Send configuration to the feature by way of the process.
1863   const Status error =
1864       process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
1865 
1866   // Report results.
1867   if (!error.Success()) {
1868     LLDB_LOGF(log,
1869               "StructuredDataDarwinLog::%s() "
1870               "ConfigureStructuredData() call failed "
1871               "(process uid %u): %s",
1872               __FUNCTION__, process_sp->GetUniqueID(), error.AsCString());
1873     auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1874     if (error_stream_sp) {
1875       error_stream_sp->Printf("failed to configure DarwinLog "
1876                               "support: %s\n",
1877                               error.AsCString());
1878       error_stream_sp->Flush();
1879     }
1880     m_is_enabled = false;
1881   } else {
1882     m_is_enabled = true;
1883     LLDB_LOGF(log,
1884               "StructuredDataDarwinLog::%s() success via direct "
1885               "configuration (process uid %u)",
1886               __FUNCTION__, process_sp->GetUniqueID());
1887   }
1888 }
1889