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