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