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