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