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