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