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