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