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