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