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