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