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