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 402 static OptionDefinition g_enable_option_table[] = { 403 // Source stream include/exclude options (the first-level filter). 404 // This one should be made as small as possible as everything that 405 // goes through here must be processed by the process monitor. 406 {LLDB_OPT_SET_ALL, false, "any-process", 'a', OptionParser::eNoArgument, 407 nullptr, nullptr, 0, eArgTypeNone, 408 "Specifies log messages from other related processes should be " 409 "included."}, 410 {LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, nullptr, 411 nullptr, 0, eArgTypeNone, 412 "Specifies debug-level log messages should be included. Specifying" 413 " --debug implies --info."}, 414 {LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, nullptr, 415 nullptr, 0, eArgTypeNone, 416 "Specifies info-level log messages should be included."}, 417 {LLDB_OPT_SET_ALL, false, "filter", 'f', OptionParser::eRequiredArgument, 418 nullptr, nullptr, 0, eArgRawInput, 419 // There doesn't appear to be a great way for me to have these 420 // multi-line, formatted tables in help. This looks mostly right 421 // but there are extra linefeeds added at seemingly random spots, 422 // and indentation isn't handled properly on those lines. 423 "Appends a filter rule to the log message filter chain. Multiple " 424 "rules may be added by specifying this option multiple times, " 425 "once per filter rule. Filter rules are processed in the order " 426 "they are specified, with the --no-match-accepts setting used " 427 "for any message that doesn't match one of the rules.\n" 428 "\n" 429 " Filter spec format:\n" 430 "\n" 431 " --filter \"{action} {attribute} {op}\"\n" 432 "\n" 433 " {action} :=\n" 434 " accept |\n" 435 " reject\n" 436 "\n" 437 " {attribute} :=\n" 438 " activity | // message's most-derived activity\n" 439 " activity-chain | // message's {parent}:{child} activity\n" 440 " category | // message's category\n" 441 " message | // message's expanded contents\n" 442 " subsystem | // message's subsystem\n" 443 "\n" 444 " {op} :=\n" 445 " match {exact-match-text} |\n" 446 " regex {search-regex}\n" 447 "\n" 448 "The regex flavor used is the C++ std::regex ECMAScript format. " 449 "Prefer character classes like [[:digit:]] to \\d and the like, as " 450 "getting the backslashes escaped through properly is error-prone."}, 451 {LLDB_OPT_SET_ALL, false, "live-stream", 'l', 452 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, 453 "Specify whether logging events are live-streamed or buffered. " 454 "True indicates live streaming, false indicates buffered. The " 455 "default is true (live streaming). Live streaming will deliver " 456 "log messages with less delay, but buffered capture mode has less " 457 "of an observer effect."}, 458 {LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n', 459 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, 460 "Specify whether a log message that doesn't match any filter rule " 461 "is accepted or rejected, where true indicates accept. The " 462 "default is true."}, 463 {LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e', 464 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, 465 "Specify whether os_log()/NSLog() messages are echoed to the " 466 "target program's stderr. When DarwinLog is enabled, we shut off " 467 "the mirroring of os_log()/NSLog() to the program's stderr. " 468 "Setting this flag to true will restore the stderr mirroring." 469 "The default is false."}, 470 {LLDB_OPT_SET_ALL, false, "broadcast-events", 'b', 471 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, 472 "Specify if the plugin should broadcast events. Broadcasting " 473 "log events is a requirement for displaying the log entries in " 474 "LLDB command-line. It is also required if LLDB clients want to " 475 "process log events. The default is true."}, 476 // Message formatting options 477 {LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r', 478 OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, 479 "Include timestamp in the message header when printing a log " 480 "message. The timestamp is relative to the first displayed " 481 "message."}, 482 {LLDB_OPT_SET_ALL, false, "subsystem", 's', OptionParser::eNoArgument, 483 nullptr, nullptr, 0, eArgTypeNone, 484 "Include the subsystem in the the message header when displaying " 485 "a log message."}, 486 {LLDB_OPT_SET_ALL, false, "category", 'c', OptionParser::eNoArgument, 487 nullptr, nullptr, 0, eArgTypeNone, 488 "Include the category in the the message header when displaying " 489 "a log message."}, 490 {LLDB_OPT_SET_ALL, false, "activity-chain", 'C', OptionParser::eNoArgument, 491 nullptr, nullptr, 0, eArgTypeNone, 492 "Include the activity parent-child chain in the the message header " 493 "when displaying a log message. The activity hierarchy is " 494 "displayed as {grandparent-activity}:" 495 "{parent-activity}:{activity}[:...]."}, 496 {LLDB_OPT_SET_ALL, false, "all-fields", 'A', OptionParser::eNoArgument, 497 nullptr, nullptr, 0, eArgTypeNone, 498 "Shortcut to specify that all header fields should be displayed."}}; 499 500 class EnableOptions : public Options { 501 public: 502 EnableOptions() 503 : Options(), m_include_debug_level(false), m_include_info_level(false), 504 m_include_any_process(false), 505 m_filter_fall_through_accepts(DEFAULT_FILTER_FALLTHROUGH_ACCEPTS), 506 m_echo_to_stderr(false), m_display_timestamp_relative(false), 507 m_display_subsystem(false), m_display_category(false), 508 m_display_activity_chain(false), m_broadcast_events(true), 509 m_live_stream(true), m_filter_rules() {} 510 511 void OptionParsingStarting(ExecutionContext *execution_context) override { 512 m_include_debug_level = false; 513 m_include_info_level = false; 514 m_include_any_process = false; 515 m_filter_fall_through_accepts = DEFAULT_FILTER_FALLTHROUGH_ACCEPTS; 516 m_echo_to_stderr = false; 517 m_display_timestamp_relative = false; 518 m_display_subsystem = false; 519 m_display_category = false; 520 m_display_activity_chain = false; 521 m_broadcast_events = true; 522 m_live_stream = true; 523 m_filter_rules.clear(); 524 } 525 526 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 527 ExecutionContext *execution_context) override { 528 Error error; 529 530 const int short_option = m_getopt_table[option_idx].val; 531 switch (short_option) { 532 case 'a': 533 m_include_any_process = true; 534 break; 535 536 case 'A': 537 m_display_timestamp_relative = true; 538 m_display_category = true; 539 m_display_subsystem = true; 540 m_display_activity_chain = true; 541 break; 542 543 case 'b': 544 m_broadcast_events = Args::StringToBoolean(option_arg, true, nullptr); 545 break; 546 547 case 'c': 548 m_display_category = true; 549 break; 550 551 case 'C': 552 m_display_activity_chain = true; 553 break; 554 555 case 'd': 556 m_include_debug_level = true; 557 break; 558 559 case 'e': 560 m_echo_to_stderr = Args::StringToBoolean(option_arg, false, nullptr); 561 break; 562 563 case 'f': 564 return ParseFilterRule(option_arg); 565 566 case 'i': 567 m_include_info_level = true; 568 break; 569 570 case 'l': 571 m_live_stream = Args::StringToBoolean(option_arg, false, nullptr); 572 break; 573 574 case 'n': 575 m_filter_fall_through_accepts = 576 Args::StringToBoolean(option_arg, true, nullptr); 577 break; 578 579 case 'r': 580 m_display_timestamp_relative = true; 581 break; 582 583 case 's': 584 m_display_subsystem = true; 585 break; 586 587 default: 588 error.SetErrorStringWithFormat("unsupported option '%c'", short_option); 589 } 590 return error; 591 } 592 593 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 594 return llvm::makeArrayRef(g_enable_option_table); 595 } 596 597 StructuredData::DictionarySP BuildConfigurationData(bool enabled) { 598 StructuredData::DictionarySP config_sp(new StructuredData::Dictionary()); 599 600 // Set the basic enabled state. 601 config_sp->AddBooleanItem("enabled", enabled); 602 603 // If we're disabled, there's nothing more to add. 604 if (!enabled) 605 return config_sp; 606 607 // Handle source stream flags. 608 auto source_flags_sp = 609 StructuredData::DictionarySP(new StructuredData::Dictionary()); 610 config_sp->AddItem("source-flags", source_flags_sp); 611 612 source_flags_sp->AddBooleanItem("any-process", m_include_any_process); 613 source_flags_sp->AddBooleanItem("debug-level", m_include_debug_level); 614 // The debug-level flag, if set, implies info-level. 615 source_flags_sp->AddBooleanItem("info-level", m_include_info_level || 616 m_include_debug_level); 617 source_flags_sp->AddBooleanItem("live-stream", m_live_stream); 618 619 // Specify default filter rule (the fall-through) 620 config_sp->AddBooleanItem("filter-fall-through-accepts", 621 m_filter_fall_through_accepts); 622 623 // Handle filter rules 624 if (!m_filter_rules.empty()) { 625 auto json_filter_rules_sp = 626 StructuredData::ArraySP(new StructuredData::Array); 627 config_sp->AddItem("filter-rules", json_filter_rules_sp); 628 for (auto &rule_sp : m_filter_rules) { 629 if (!rule_sp) 630 continue; 631 json_filter_rules_sp->AddItem(rule_sp->Serialize()); 632 } 633 } 634 return config_sp; 635 } 636 637 bool GetIncludeDebugLevel() const { return m_include_debug_level; } 638 639 bool GetIncludeInfoLevel() const { 640 // Specifying debug level implies info level. 641 return m_include_info_level || m_include_debug_level; 642 } 643 644 const FilterRules &GetFilterRules() const { return m_filter_rules; } 645 646 bool GetFallthroughAccepts() const { return m_filter_fall_through_accepts; } 647 648 bool GetEchoToStdErr() const { return m_echo_to_stderr; } 649 650 bool GetDisplayTimestampRelative() const { 651 return m_display_timestamp_relative; 652 } 653 654 bool GetDisplaySubsystem() const { return m_display_subsystem; } 655 bool GetDisplayCategory() const { return m_display_category; } 656 bool GetDisplayActivityChain() const { return m_display_activity_chain; } 657 658 bool GetDisplayAnyHeaderFields() const { 659 return m_display_timestamp_relative || m_display_activity_chain || 660 m_display_subsystem || m_display_category; 661 } 662 663 bool GetBroadcastEvents() const { return m_broadcast_events; } 664 665 private: 666 Error ParseFilterRule(llvm::StringRef rule_text) { 667 Error error; 668 669 if (rule_text.empty()) { 670 error.SetErrorString("invalid rule_text"); 671 return error; 672 } 673 674 // filter spec format: 675 // 676 // {action} {attribute} {op} 677 // 678 // {action} := 679 // accept | 680 // reject 681 // 682 // {attribute} := 683 // category | 684 // subsystem | 685 // activity | 686 // activity-chain | 687 // message | 688 // format 689 // 690 // {op} := 691 // match {exact-match-text} | 692 // regex {search-regex} 693 694 // Parse action. 695 auto action_end_pos = rule_text.find(" "); 696 if (action_end_pos == std::string::npos) { 697 error.SetErrorStringWithFormat("could not parse filter rule " 698 "action from \"%s\"", 699 rule_text.str().c_str()); 700 return error; 701 } 702 auto action = rule_text.substr(0, action_end_pos); 703 bool accept; 704 if (action == "accept") 705 accept = true; 706 else if (action == "reject") 707 accept = false; 708 else { 709 error.SetErrorString("filter action must be \"accept\" or \"deny\""); 710 return error; 711 } 712 713 // parse attribute 714 auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1); 715 if (attribute_end_pos == std::string::npos) { 716 error.SetErrorStringWithFormat("could not parse filter rule " 717 "attribute from \"%s\"", 718 rule_text.str().c_str()); 719 return error; 720 } 721 auto attribute = rule_text.substr(action_end_pos + 1, 722 attribute_end_pos - (action_end_pos + 1)); 723 auto attribute_index = MatchAttributeIndex(attribute); 724 if (attribute_index < 0) { 725 error.SetErrorStringWithFormat("filter rule attribute unknown: " 726 "%s", 727 attribute.str().c_str()); 728 return error; 729 } 730 731 // parse operation 732 auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1); 733 auto operation = rule_text.substr( 734 attribute_end_pos + 1, operation_end_pos - (attribute_end_pos + 1)); 735 736 // add filter spec 737 auto rule_sp = 738 FilterRule::CreateRule(accept, attribute_index, ConstString(operation), 739 rule_text.substr(operation_end_pos + 1), error); 740 741 if (rule_sp && error.Success()) 742 m_filter_rules.push_back(rule_sp); 743 744 return error; 745 } 746 747 int MatchAttributeIndex(llvm::StringRef attribute_name) const { 748 for (const auto &Item : llvm::enumerate(s_filter_attributes)) { 749 if (attribute_name == Item.Value) 750 return Item.Index; 751 } 752 753 // We didn't match anything. 754 return -1; 755 } 756 757 bool m_include_debug_level; 758 bool m_include_info_level; 759 bool m_include_any_process; 760 bool m_filter_fall_through_accepts; 761 bool m_echo_to_stderr; 762 bool m_display_timestamp_relative; 763 bool m_display_subsystem; 764 bool m_display_category; 765 bool m_display_activity_chain; 766 bool m_broadcast_events; 767 bool m_live_stream; 768 FilterRules m_filter_rules; 769 }; 770 771 class EnableCommand : public CommandObjectParsed { 772 public: 773 EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name, 774 const char *help, const char *syntax) 775 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable), 776 m_options_sp(enable ? new EnableOptions() : nullptr) {} 777 778 protected: 779 void AppendStrictSourcesWarning(CommandReturnObject &result, 780 const char *source_name) { 781 if (!source_name) 782 return; 783 784 // Check if we're *not* using strict sources. If not, 785 // then the user is going to get debug-level info 786 // anyways, probably not what they're expecting. 787 // Unfortunately we can only fix this by adding an 788 // env var, which would have had to have happened 789 // already. Thus, a warning is the best we can do here. 790 StreamString stream; 791 stream.Printf("darwin-log source settings specify to exclude " 792 "%s messages, but setting " 793 "'plugin.structured-data.darwin-log." 794 "strict-sources' is disabled. This process will " 795 "automatically have %s messages included. Enable" 796 " the property and relaunch the target binary to have" 797 " these messages excluded.", 798 source_name, source_name); 799 result.AppendWarning(stream.GetString().c_str()); 800 } 801 802 bool DoExecute(Args &command, CommandReturnObject &result) override { 803 // First off, set the global sticky state of enable/disable 804 // based on this command execution. 805 s_is_explicitly_enabled = m_enable; 806 807 // Next, if this is an enable, save off the option data. 808 // We will need it later if a process hasn't been launched or 809 // attached yet. 810 if (m_enable) { 811 // Save off enabled configuration so we can apply these parsed 812 // options the next time an attach or launch occurs. 813 DebuggerSP debugger_sp = 814 GetCommandInterpreter().GetDebugger().shared_from_this(); 815 SetGlobalEnableOptions(debugger_sp, m_options_sp); 816 } 817 818 // Now check if we have a running process. If so, we should 819 // instruct the process monitor to enable/disable DarwinLog support 820 // now. 821 Target *target = GetSelectedOrDummyTarget(); 822 if (!target) { 823 // No target, so there is nothing more to do right now. 824 result.SetStatus(eReturnStatusSuccessFinishNoResult); 825 return true; 826 } 827 828 // Grab the active process. 829 auto process_sp = target->GetProcessSP(); 830 if (!process_sp) { 831 // No active process, so there is nothing more to do right 832 // now. 833 result.SetStatus(eReturnStatusSuccessFinishNoResult); 834 return true; 835 } 836 837 // If the process is no longer alive, we can't do this now. 838 // We'll catch it the next time the process is started up. 839 if (!process_sp->IsAlive()) { 840 result.SetStatus(eReturnStatusSuccessFinishNoResult); 841 return true; 842 } 843 844 // Get the plugin for the process. 845 auto plugin_sp = 846 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); 847 if (!plugin_sp || (plugin_sp->GetPluginName() != 848 StructuredDataDarwinLog::GetStaticPluginName())) { 849 result.AppendError("failed to get StructuredDataPlugin for " 850 "the process"); 851 result.SetStatus(eReturnStatusFailed); 852 } 853 StructuredDataDarwinLog &plugin = 854 *static_cast<StructuredDataDarwinLog *>(plugin_sp.get()); 855 856 if (m_enable) { 857 // To do this next part right, we need to track whether we 858 // added the proper environment variable at launch time. 859 // It is incorrect to assume that we're enabling after launch, 860 // and that therefore if we needed the env var set to properly 861 // handle the options, that it is set incorrectly. The env var 862 // could have been added if this is a re-enable using different 863 // arguments. This is a bit tricky as the point where we 864 // have to set the env var, we don't yet have a process or the 865 // associated darwin-log plugin instance, and thus don't have a 866 // great place to stick this knowledge. 867 #if 0 868 // Check if we're attempting to disable debug-level or 869 // info-level content but we haven't launched with the magic 870 // env var that suppresses the "always add" of those. In 871 // that scenario, the user is asking *not* to see debug or 872 // info level messages, but will see them anyway. Warn and 873 // show how to correct it. 874 if (!m_options_sp->GetIncludeDebugLevel() && 875 !GetGlobalProperties()->GetUseStrictSources()) 876 { 877 AppendStrictSourcesWarning(result, "debug-level"); 878 } 879 880 if (!m_options_sp->GetIncludeInfoLevel() && 881 !GetGlobalProperties()->GetUseStrictSources()) 882 { 883 AppendStrictSourcesWarning(result, "info-level"); 884 } 885 #endif 886 887 // Hook up the breakpoint for the process that detects when 888 // libtrace has been sufficiently initialized to really start 889 // the os_log stream. This is insurance to assure us that 890 // logging is really enabled. Requesting that logging be 891 // enabled for a process before libtrace is initialized 892 // results in a scenario where no errors occur, but no logging 893 // is captured, either. This step is to eliminate that 894 // possibility. 895 plugin.AddInitCompletionHook(*process_sp.get()); 896 } 897 898 // Send configuration to the feature by way of the process. 899 // Construct the options we will use. 900 auto config_sp = m_options_sp->BuildConfigurationData(m_enable); 901 const Error error = 902 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp); 903 904 // Report results. 905 if (!error.Success()) { 906 result.AppendError(error.AsCString()); 907 result.SetStatus(eReturnStatusFailed); 908 // Our configuration failed, so we're definitely disabled. 909 plugin.SetEnabled(false); 910 } else { 911 result.SetStatus(eReturnStatusSuccessFinishNoResult); 912 // Our configuration succeeeded, so we're enabled/disabled 913 // per whichever one this command is setup to do. 914 plugin.SetEnabled(m_enable); 915 } 916 return result.Succeeded(); 917 } 918 919 Options *GetOptions() override { 920 // We don't have options when this represents disable. 921 return m_enable ? m_options_sp.get() : nullptr; 922 } 923 924 private: 925 const bool m_enable; 926 EnableOptionsSP m_options_sp; 927 }; 928 929 // ------------------------------------------------------------------------- 930 /// Provides the status command. 931 // ------------------------------------------------------------------------- 932 class StatusCommand : public CommandObjectParsed { 933 public: 934 StatusCommand(CommandInterpreter &interpreter) 935 : CommandObjectParsed(interpreter, "status", 936 "Show whether Darwin log supported is available" 937 " and enabled.", 938 "plugin structured-data darwin-log status") {} 939 940 protected: 941 bool DoExecute(Args &command, CommandReturnObject &result) override { 942 auto &stream = result.GetOutputStream(); 943 944 // Figure out if we've got a process. If so, we can tell if 945 // DarwinLog is available for that process. 946 Target *target = GetSelectedOrDummyTarget(); 947 auto process_sp = target ? target->GetProcessSP() : ProcessSP(); 948 if (!target || !process_sp) { 949 stream.PutCString("Availability: unknown (requires process)\n"); 950 stream.PutCString("Enabled: not applicable " 951 "(requires process)\n"); 952 } else { 953 auto plugin_sp = 954 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); 955 stream.Printf("Availability: %s\n", 956 plugin_sp ? "available" : "unavailable"); 957 auto &plugin_name = StructuredDataDarwinLog::GetStaticPluginName(); 958 const bool enabled = 959 plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false; 960 stream.Printf("Enabled: %s\n", enabled ? "true" : "false"); 961 } 962 963 // Display filter settings. 964 DebuggerSP debugger_sp = 965 GetCommandInterpreter().GetDebugger().shared_from_this(); 966 auto options_sp = GetGlobalEnableOptions(debugger_sp); 967 if (!options_sp) { 968 // Nothing more to do. 969 result.SetStatus(eReturnStatusSuccessFinishResult); 970 return true; 971 } 972 973 // Print filter rules 974 stream.PutCString("DarwinLog filter rules:\n"); 975 976 stream.IndentMore(); 977 978 if (options_sp->GetFilterRules().empty()) { 979 stream.Indent(); 980 stream.PutCString("none\n"); 981 } else { 982 // Print each of the filter rules. 983 int rule_number = 0; 984 for (auto rule_sp : options_sp->GetFilterRules()) { 985 ++rule_number; 986 if (!rule_sp) 987 continue; 988 989 stream.Indent(); 990 stream.Printf("%02d: ", rule_number); 991 rule_sp->Dump(stream); 992 stream.PutChar('\n'); 993 } 994 } 995 stream.IndentLess(); 996 997 // Print no-match handling. 998 stream.Indent(); 999 stream.Printf("no-match behavior: %s\n", 1000 options_sp->GetFallthroughAccepts() ? "accept" : "reject"); 1001 1002 result.SetStatus(eReturnStatusSuccessFinishResult); 1003 return true; 1004 } 1005 }; 1006 1007 // ------------------------------------------------------------------------- 1008 /// Provides the darwin-log base command 1009 // ------------------------------------------------------------------------- 1010 class BaseCommand : public CommandObjectMultiword { 1011 public: 1012 BaseCommand(CommandInterpreter &interpreter) 1013 : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log", 1014 "Commands for configuring Darwin os_log " 1015 "support.", 1016 "") { 1017 // enable 1018 auto enable_help = "Enable Darwin log collection, or re-enable " 1019 "with modified configuration."; 1020 auto enable_syntax = "plugin structured-data darwin-log enable"; 1021 auto enable_cmd_sp = CommandObjectSP( 1022 new EnableCommand(interpreter, 1023 true, // enable 1024 "enable", enable_help, enable_syntax)); 1025 LoadSubCommand("enable", enable_cmd_sp); 1026 1027 // disable 1028 auto disable_help = "Disable Darwin log collection."; 1029 auto disable_syntax = "plugin structured-data darwin-log disable"; 1030 auto disable_cmd_sp = CommandObjectSP( 1031 new EnableCommand(interpreter, 1032 false, // disable 1033 "disable", disable_help, disable_syntax)); 1034 LoadSubCommand("disable", disable_cmd_sp); 1035 1036 // status 1037 auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter)); 1038 LoadSubCommand("status", status_cmd_sp); 1039 } 1040 }; 1041 1042 EnableOptionsSP ParseAutoEnableOptions(Error &error, Debugger &debugger) { 1043 // We are abusing the options data model here so that we can parse 1044 // options without requiring the Debugger instance. 1045 1046 // We have an empty execution context at this point. We only want 1047 // to parse options, and we don't need any context to do this here. 1048 // In fact, we want to be able to parse the enable options before having 1049 // any context. 1050 ExecutionContext exe_ctx; 1051 1052 EnableOptionsSP options_sp(new EnableOptions()); 1053 options_sp->NotifyOptionParsingStarting(&exe_ctx); 1054 1055 CommandReturnObject result; 1056 1057 // Parse the arguments. 1058 auto options_property_sp = 1059 debugger.GetPropertyValue(nullptr, "plugin.structured-data.darwin-log." 1060 "auto-enable-options", 1061 false, error); 1062 if (!error.Success()) 1063 return EnableOptionsSP(); 1064 if (!options_property_sp) { 1065 error.SetErrorString("failed to find option setting for " 1066 "plugin.structured-data.darwin-log."); 1067 return EnableOptionsSP(); 1068 } 1069 1070 const char *enable_options = 1071 options_property_sp->GetAsString()->GetCurrentValue(); 1072 Args args(enable_options); 1073 if (args.GetArgumentCount() > 0) { 1074 // Eliminate the initial '--' that would be required to set the 1075 // settings that themselves include '-' and/or '--'. 1076 const char *first_arg = args.GetArgumentAtIndex(0); 1077 if (first_arg && (strcmp(first_arg, "--") == 0)) 1078 args.Shift(); 1079 } 1080 1081 // ParseOptions calls getopt_long_only, which always skips the zero'th item in 1082 // the array and starts at position 1, 1083 // so we need to push a dummy value into position zero. 1084 args.Unshift(llvm::StringRef("dummy_string")); 1085 bool require_validation = false; 1086 error = args.ParseOptions(*options_sp.get(), &exe_ctx, PlatformSP(), 1087 require_validation); 1088 if (!error.Success()) 1089 return EnableOptionsSP(); 1090 1091 if (!options_sp->VerifyOptions(result)) 1092 return EnableOptionsSP(); 1093 1094 // We successfully parsed and validated the options. 1095 return options_sp; 1096 } 1097 1098 bool RunEnableCommand(CommandInterpreter &interpreter) { 1099 StreamString command_stream; 1100 1101 command_stream << "plugin structured-data darwin-log enable"; 1102 auto enable_options = GetGlobalProperties()->GetAutoEnableOptions(); 1103 if (enable_options && (strlen(enable_options) > 0)) { 1104 command_stream << ' '; 1105 command_stream << enable_options; 1106 } 1107 1108 // Run the command. 1109 CommandReturnObject return_object; 1110 interpreter.HandleCommand(command_stream.GetString().c_str(), eLazyBoolNo, 1111 return_object); 1112 return return_object.Succeeded(); 1113 } 1114 } 1115 using namespace sddarwinlog_private; 1116 1117 #pragma mark - 1118 #pragma mark Public static API 1119 1120 // ----------------------------------------------------------------------------- 1121 // Public static API 1122 // ----------------------------------------------------------------------------- 1123 1124 void StructuredDataDarwinLog::Initialize() { 1125 RegisterFilterOperations(); 1126 PluginManager::RegisterPlugin( 1127 GetStaticPluginName(), "Darwin os_log() and os_activity() support", 1128 &CreateInstance, &DebuggerInitialize, &FilterLaunchInfo); 1129 } 1130 1131 void StructuredDataDarwinLog::Terminate() { 1132 PluginManager::UnregisterPlugin(&CreateInstance); 1133 } 1134 1135 const ConstString &StructuredDataDarwinLog::GetStaticPluginName() { 1136 static ConstString s_plugin_name("darwin-log"); 1137 return s_plugin_name; 1138 } 1139 1140 #pragma mark - 1141 #pragma mark PluginInterface API 1142 1143 // ----------------------------------------------------------------------------- 1144 // PluginInterface API 1145 // ----------------------------------------------------------------------------- 1146 1147 ConstString StructuredDataDarwinLog::GetPluginName() { 1148 return GetStaticPluginName(); 1149 } 1150 1151 uint32_t StructuredDataDarwinLog::GetPluginVersion() { return 1; } 1152 1153 #pragma mark - 1154 #pragma mark StructuredDataPlugin API 1155 1156 // ----------------------------------------------------------------------------- 1157 // StructuredDataPlugin API 1158 // ----------------------------------------------------------------------------- 1159 1160 bool StructuredDataDarwinLog::SupportsStructuredDataType( 1161 const ConstString &type_name) { 1162 return type_name == GetDarwinLogTypeName(); 1163 } 1164 1165 void StructuredDataDarwinLog::HandleArrivalOfStructuredData( 1166 Process &process, const ConstString &type_name, 1167 const StructuredData::ObjectSP &object_sp) { 1168 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1169 if (log) { 1170 StreamString json_stream; 1171 if (object_sp) 1172 object_sp->Dump(json_stream); 1173 else 1174 json_stream.PutCString("<null>"); 1175 log->Printf("StructuredDataDarwinLog::%s() called with json: %s", 1176 __FUNCTION__, json_stream.GetString().c_str()); 1177 } 1178 1179 // Ignore empty structured data. 1180 if (!object_sp) { 1181 if (log) 1182 log->Printf("StructuredDataDarwinLog::%s() StructuredData object " 1183 "is null", 1184 __FUNCTION__); 1185 return; 1186 } 1187 1188 // Ignore any data that isn't for us. 1189 if (type_name != GetDarwinLogTypeName()) { 1190 if (log) 1191 log->Printf("StructuredDataDarwinLog::%s() StructuredData type " 1192 "expected to be %s but was %s, ignoring", 1193 __FUNCTION__, GetDarwinLogTypeName().AsCString(), 1194 type_name.AsCString()); 1195 return; 1196 } 1197 1198 // Broadcast the structured data event if we have that enabled. 1199 // This is the way that the outside world (all clients) get access 1200 // to this data. This plugin sets policy as to whether we do that. 1201 DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this(); 1202 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1203 if (options_sp && options_sp->GetBroadcastEvents()) { 1204 if (log) 1205 log->Printf("StructuredDataDarwinLog::%s() broadcasting event", 1206 __FUNCTION__); 1207 process.BroadcastStructuredData(object_sp, shared_from_this()); 1208 } 1209 1210 // Later, hang on to a configurable amount of these and allow commands 1211 // to inspect, including showing backtraces. 1212 } 1213 1214 static void SetErrorWithJSON(Error &error, const char *message, 1215 StructuredData::Object &object) { 1216 if (!message) { 1217 error.SetErrorString("Internal error: message not set."); 1218 return; 1219 } 1220 1221 StreamString object_stream; 1222 object.Dump(object_stream); 1223 object_stream.Flush(); 1224 1225 error.SetErrorStringWithFormat("%s: %s", message, 1226 object_stream.GetString().c_str()); 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 #pragma mark - 1410 #pragma mark Private instance methods 1411 1412 // ----------------------------------------------------------------------------- 1413 // Private constructors 1414 // ----------------------------------------------------------------------------- 1415 1416 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp) 1417 : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false), 1418 m_first_timestamp_seen(0), m_is_enabled(false), 1419 m_added_breakpoint_mutex(), m_added_breakpoint() {} 1420 1421 // ----------------------------------------------------------------------------- 1422 // Private static methods 1423 // ----------------------------------------------------------------------------- 1424 1425 StructuredDataPluginSP 1426 StructuredDataDarwinLog::CreateInstance(Process &process) { 1427 // Currently only Apple targets support the os_log/os_activity 1428 // protocol. 1429 if (process.GetTarget().GetArchitecture().GetTriple().getVendor() == 1430 llvm::Triple::VendorType::Apple) { 1431 auto process_wp = ProcessWP(process.shared_from_this()); 1432 return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp)); 1433 } else { 1434 return StructuredDataPluginSP(); 1435 } 1436 } 1437 1438 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) { 1439 // Setup parent class first. 1440 StructuredDataPlugin::InitializeBasePluginForDebugger(debugger); 1441 1442 // Get parent command. 1443 auto &interpreter = debugger.GetCommandInterpreter(); 1444 llvm::StringRef parent_command_text = "plugin structured-data"; 1445 auto parent_command = 1446 interpreter.GetCommandObjectForCommand(parent_command_text); 1447 if (!parent_command) { 1448 // Ut oh, parent failed to create parent command. 1449 // TODO log 1450 return; 1451 } 1452 1453 auto command_name = "darwin-log"; 1454 auto command_sp = CommandObjectSP(new BaseCommand(interpreter)); 1455 bool result = parent_command->LoadSubCommand(command_name, command_sp); 1456 if (!result) { 1457 // TODO log it once we setup structured data logging 1458 } 1459 1460 if (!PluginManager::GetSettingForPlatformPlugin( 1461 debugger, StructuredDataDarwinLogProperties::GetSettingName())) { 1462 const bool is_global_setting = true; 1463 PluginManager::CreateSettingForStructuredDataPlugin( 1464 debugger, GetGlobalProperties()->GetValueProperties(), 1465 ConstString("Properties for the darwin-log" 1466 " plug-in."), 1467 is_global_setting); 1468 } 1469 } 1470 1471 Error StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info, 1472 Target *target) { 1473 Error error; 1474 1475 // If we're not debugging this launched process, there's nothing for us 1476 // to do here. 1477 if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug)) 1478 return error; 1479 1480 // Darwin os_log() support automatically adds debug-level and info-level 1481 // messages when a debugger is attached to a process. However, with 1482 // integrated suppport for debugging built into the command-line LLDB, 1483 // the user may specifically set to *not* include debug-level and info-level 1484 // content. When the user is using the integrated log support, we want 1485 // to put the kabosh on that automatic adding of info and debug level. 1486 // This is done by adding an environment variable to the process on launch. 1487 // (This also means it is not possible to suppress this behavior if 1488 // attaching to an already-running app). 1489 // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1490 1491 // If the target architecture is not one that supports DarwinLog, we have 1492 // nothing to do here. 1493 auto &triple = target ? target->GetArchitecture().GetTriple() 1494 : launch_info.GetArchitecture().GetTriple(); 1495 if (triple.getVendor() != llvm::Triple::Apple) { 1496 return error; 1497 } 1498 1499 // If DarwinLog is not enabled (either by explicit user command or via 1500 // the auto-enable option), then we have nothing to do. 1501 if (!GetGlobalProperties()->GetEnableOnStartup() && 1502 !s_is_explicitly_enabled) { 1503 // Nothing to do, DarwinLog is not enabled. 1504 return error; 1505 } 1506 1507 // If we don't have parsed configuration info, that implies we have 1508 // enable-on-startup set up, but we haven't yet attempted to run the 1509 // enable command. 1510 if (!target) { 1511 // We really can't do this without a target. We need to be able 1512 // to get to the debugger to get the proper options to do this right. 1513 // TODO log. 1514 error.SetErrorString("requires a target to auto-enable DarwinLog."); 1515 return error; 1516 } 1517 1518 DebuggerSP debugger_sp = target->GetDebugger().shared_from_this(); 1519 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1520 if (!options_sp && debugger_sp) { 1521 options_sp = ParseAutoEnableOptions(error, *debugger_sp.get()); 1522 if (!options_sp || !error.Success()) 1523 return error; 1524 1525 // We already parsed the options, save them now so we don't generate 1526 // them again until the user runs the command manually. 1527 SetGlobalEnableOptions(debugger_sp, options_sp); 1528 } 1529 1530 auto &env_vars = launch_info.GetEnvironmentEntries(); 1531 if (!options_sp->GetEchoToStdErr()) { 1532 // The user doesn't want to see os_log/NSLog messages echo to stderr. 1533 // That mechanism is entirely separate from the DarwinLog support. 1534 // By default we don't want to get it via stderr, because that would 1535 // be in duplicate of the explicit log support here. 1536 1537 // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent 1538 // echoing of os_log()/NSLog() to stderr in the target program. 1539 size_t argument_index; 1540 if (env_vars.ContainsEnvironmentVariable( 1541 llvm::StringRef("OS_ACTIVITY_DT_MODE"), &argument_index)) 1542 env_vars.DeleteArgumentAtIndex(argument_index); 1543 1544 // We will also set the env var that tells any downstream launcher 1545 // from adding OS_ACTIVITY_DT_MODE. 1546 env_vars.AddOrReplaceEnvironmentVariable( 1547 llvm::StringRef("IDE_DISABLED_OS_ACTIVITY_DT_MODE"), 1548 llvm::StringRef("1")); 1549 } 1550 1551 // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable 1552 // debug and info level messages. 1553 const char *env_var_value; 1554 if (options_sp->GetIncludeDebugLevel()) 1555 env_var_value = "debug"; 1556 else if (options_sp->GetIncludeInfoLevel()) 1557 env_var_value = "info"; 1558 else 1559 env_var_value = "default"; 1560 1561 if (env_var_value) { 1562 launch_info.GetEnvironmentEntries().AddOrReplaceEnvironmentVariable( 1563 llvm::StringRef("OS_ACTIVITY_MODE"), llvm::StringRef(env_var_value)); 1564 } 1565 1566 return error; 1567 } 1568 1569 bool StructuredDataDarwinLog::InitCompletionHookCallback( 1570 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 1571 lldb::user_id_t break_loc_id) { 1572 // We hit the init function. We now want to enqueue our new thread plan, 1573 // which will in turn enqueue a StepOut thread plan. When the StepOut 1574 // finishes and control returns to our new thread plan, that is the time 1575 // when we can execute our logic to enable the logging support. 1576 1577 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1578 if (log) 1579 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); 1580 1581 // Get the current thread. 1582 if (!context) { 1583 if (log) 1584 log->Printf("StructuredDataDarwinLog::%s() warning: no context, " 1585 "ignoring", 1586 __FUNCTION__); 1587 return false; 1588 } 1589 1590 // Get the plugin from the process. 1591 auto process_sp = context->exe_ctx_ref.GetProcessSP(); 1592 if (!process_sp) { 1593 if (log) 1594 log->Printf("StructuredDataDarwinLog::%s() warning: invalid " 1595 "process in context, ignoring", 1596 __FUNCTION__); 1597 return false; 1598 } 1599 if (log) 1600 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %d", 1601 __FUNCTION__, process_sp->GetUniqueID()); 1602 1603 auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); 1604 if (!plugin_sp) { 1605 if (log) 1606 log->Printf("StructuredDataDarwinLog::%s() warning: no plugin for " 1607 "feature %s in process uid %u", 1608 __FUNCTION__, GetDarwinLogTypeName().AsCString(), 1609 process_sp->GetUniqueID()); 1610 return false; 1611 } 1612 1613 // Create the callback for when the thread plan completes. 1614 bool called_enable_method = false; 1615 const auto process_uid = process_sp->GetUniqueID(); 1616 1617 std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp); 1618 ThreadPlanCallOnFunctionExit::Callback callback = 1619 [plugin_wp, &called_enable_method, log, process_uid]() { 1620 if (log) 1621 log->Printf("StructuredDataDarwinLog::post-init callback: " 1622 "called (process uid %u)", 1623 process_uid); 1624 1625 auto strong_plugin_sp = plugin_wp.lock(); 1626 if (!strong_plugin_sp) { 1627 if (log) 1628 log->Printf("StructuredDataDarwinLog::post-init callback: " 1629 "plugin no longer exists, ignoring (process " 1630 "uid %u)", 1631 process_uid); 1632 return; 1633 } 1634 // Make sure we only call it once, just in case the 1635 // thread plan hits the breakpoint twice. 1636 if (!called_enable_method) { 1637 if (log) 1638 log->Printf("StructuredDataDarwinLog::post-init callback: " 1639 "calling EnableNow() (process uid %u)", 1640 process_uid); 1641 static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get()) 1642 ->EnableNow(); 1643 called_enable_method = true; 1644 } else { 1645 // Our breakpoint was hit more than once. Unexpected but 1646 // no harm done. Log it. 1647 if (log) 1648 log->Printf("StructuredDataDarwinLog::post-init callback: " 1649 "skipping EnableNow(), already called by " 1650 "callback [we hit this more than once] " 1651 "(process uid %u)", 1652 process_uid); 1653 } 1654 }; 1655 1656 // Grab the current thread. 1657 auto thread_sp = context->exe_ctx_ref.GetThreadSP(); 1658 if (!thread_sp) { 1659 if (log) 1660 log->Printf("StructuredDataDarwinLog::%s() warning: failed to " 1661 "retrieve the current thread from the execution " 1662 "context, nowhere to run the thread plan (process uid " 1663 "%u)", 1664 __FUNCTION__, process_sp->GetUniqueID()); 1665 return false; 1666 } 1667 1668 // Queue the thread plan. 1669 auto thread_plan_sp = ThreadPlanSP( 1670 new ThreadPlanCallOnFunctionExit(*thread_sp.get(), callback)); 1671 const bool abort_other_plans = false; 1672 thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans); 1673 if (log) 1674 log->Printf("StructuredDataDarwinLog::%s() queuing thread plan on " 1675 "trace library init method entry (process uid %u)", 1676 __FUNCTION__, process_sp->GetUniqueID()); 1677 1678 // We return false here to indicate that it isn't a public stop. 1679 return false; 1680 } 1681 1682 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) { 1683 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1684 if (log) 1685 log->Printf("StructuredDataDarwinLog::%s() called (process uid %u)", 1686 __FUNCTION__, process.GetUniqueID()); 1687 1688 // Make sure we haven't already done this. 1689 { 1690 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex); 1691 if (m_added_breakpoint) { 1692 if (log) 1693 log->Printf("StructuredDataDarwinLog::%s() ignoring request, " 1694 "breakpoint already set (process uid %u)", 1695 __FUNCTION__, process.GetUniqueID()); 1696 return; 1697 } 1698 1699 // We're about to do this, don't let anybody else try to do it. 1700 m_added_breakpoint = true; 1701 } 1702 1703 // Set a breakpoint for the process that will kick in when libtrace 1704 // has finished its initialization. 1705 Target &target = process.GetTarget(); 1706 1707 // Build up the module list. 1708 FileSpecList module_spec_list; 1709 auto module_file_spec = 1710 FileSpec(GetGlobalProperties()->GetLoggingModuleName(), false); 1711 module_spec_list.Append(module_file_spec); 1712 1713 // We aren't specifying a source file set. 1714 FileSpecList *source_spec_list = nullptr; 1715 1716 const char *func_name = "_libtrace_init"; 1717 const lldb::addr_t offset = 0; 1718 const LazyBool skip_prologue = eLazyBoolCalculate; 1719 // This is an internal breakpoint - the user shouldn't see it. 1720 const bool internal = true; 1721 const bool hardware = false; 1722 1723 auto breakpoint_sp = target.CreateBreakpoint( 1724 &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull, 1725 eLanguageTypeC, offset, skip_prologue, internal, hardware); 1726 if (!breakpoint_sp) { 1727 // Huh? Bail here. 1728 if (log) 1729 log->Printf("StructuredDataDarwinLog::%s() failed to set " 1730 "breakpoint in module %s, function %s (process uid %u)", 1731 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(), 1732 func_name, process.GetUniqueID()); 1733 return; 1734 } 1735 1736 // Set our callback. 1737 breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr); 1738 if (log) 1739 log->Printf("StructuredDataDarwinLog::%s() breakpoint set in module %s," 1740 "function %s (process uid %u)", 1741 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(), 1742 func_name, process.GetUniqueID()); 1743 } 1744 1745 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream, 1746 uint64_t timestamp) { 1747 const uint64_t delta_nanos = timestamp - m_first_timestamp_seen; 1748 1749 const uint64_t hours = delta_nanos / NANOS_PER_HOUR; 1750 uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR; 1751 1752 const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE; 1753 nanos_remaining = nanos_remaining % NANOS_PER_MINUTE; 1754 1755 const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND; 1756 nanos_remaining = nanos_remaining % NANOS_PER_SECOND; 1757 1758 stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours, 1759 minutes, seconds, nanos_remaining); 1760 } 1761 1762 size_t 1763 StructuredDataDarwinLog::DumpHeader(Stream &output_stream, 1764 const StructuredData::Dictionary &event) { 1765 StreamString stream; 1766 1767 ProcessSP process_sp = GetProcess(); 1768 if (!process_sp) { 1769 // TODO log 1770 return 0; 1771 } 1772 1773 DebuggerSP debugger_sp = 1774 process_sp->GetTarget().GetDebugger().shared_from_this(); 1775 if (!debugger_sp) { 1776 // TODO log 1777 return 0; 1778 } 1779 1780 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1781 if (!options_sp) { 1782 // TODO log 1783 return 0; 1784 } 1785 1786 // Check if we should even display a header. 1787 if (!options_sp->GetDisplayAnyHeaderFields()) 1788 return 0; 1789 1790 stream.PutChar('['); 1791 1792 int header_count = 0; 1793 if (options_sp->GetDisplayTimestampRelative()) { 1794 uint64_t timestamp = 0; 1795 if (event.GetValueForKeyAsInteger("timestamp", timestamp)) { 1796 DumpTimestamp(stream, timestamp); 1797 ++header_count; 1798 } 1799 } 1800 1801 if (options_sp->GetDisplayActivityChain()) { 1802 std::string activity_chain; 1803 if (event.GetValueForKeyAsString("activity-chain", activity_chain) && 1804 !activity_chain.empty()) { 1805 if (header_count > 0) 1806 stream.PutChar(','); 1807 1808 // Switch over to the #if 0 branch once we figure out 1809 // how we want to present settings for the tri-state of 1810 // no-activity, activity (most derived only), or activity-chain. 1811 #if 1 1812 // Display the activity chain, from parent-most to child-most 1813 // activity, separated by a colon (:). 1814 stream.PutCString("activity-chain="); 1815 stream.PutCString(activity_chain); 1816 #else 1817 if (GetGlobalProperties()->GetDisplayActivityChain()) { 1818 // Display the activity chain, from parent-most to child-most 1819 // activity, separated by a colon (:). 1820 stream.PutCString("activity-chain="); 1821 stream.PutCString(activity_chain.c_str()); 1822 } else { 1823 // We're only displaying the child-most activity. 1824 stream.PutCString("activity="); 1825 auto pos = activity_chain.find_last_of(':'); 1826 if (pos == std::string::npos) { 1827 // The activity chain only has one level, use the whole 1828 // thing. 1829 stream.PutCString(activity_chain.c_str()); 1830 } else { 1831 // Display everything after the final ':'. 1832 stream.PutCString(activity_chain.substr(pos + 1).c_str()); 1833 } 1834 } 1835 #endif 1836 ++header_count; 1837 } 1838 } 1839 1840 if (options_sp->GetDisplaySubsystem()) { 1841 std::string subsystem; 1842 if (event.GetValueForKeyAsString("subsystem", subsystem) && 1843 !subsystem.empty()) { 1844 if (header_count > 0) 1845 stream.PutChar(','); 1846 stream.PutCString("subsystem="); 1847 stream.PutCString(subsystem); 1848 ++header_count; 1849 } 1850 } 1851 1852 if (options_sp->GetDisplayCategory()) { 1853 std::string category; 1854 if (event.GetValueForKeyAsString("category", category) && 1855 !category.empty()) { 1856 if (header_count > 0) 1857 stream.PutChar(','); 1858 stream.PutCString("category="); 1859 stream.PutCString(category); 1860 ++header_count; 1861 } 1862 } 1863 stream.PutCString("] "); 1864 1865 auto &result = stream.GetString(); 1866 output_stream.PutCString(result); 1867 1868 return result.size(); 1869 } 1870 1871 size_t StructuredDataDarwinLog::HandleDisplayOfEvent( 1872 const StructuredData::Dictionary &event, Stream &stream) { 1873 // Check the type of the event. 1874 ConstString event_type; 1875 if (!event.GetValueForKeyAsString("type", event_type)) { 1876 // Hmm, we expected to get events that describe 1877 // what they are. Continue anyway. 1878 return 0; 1879 } 1880 1881 if (event_type != GetLogEventType()) 1882 return 0; 1883 1884 size_t total_bytes = 0; 1885 1886 // Grab the message content. 1887 std::string message; 1888 if (!event.GetValueForKeyAsString("message", message)) 1889 return true; 1890 1891 // Display the log entry. 1892 const auto len = message.length(); 1893 1894 total_bytes += DumpHeader(stream, event); 1895 1896 stream.Write(message.c_str(), len); 1897 total_bytes += len; 1898 1899 // Add an end of line. 1900 stream.PutChar('\n'); 1901 total_bytes += sizeof(char); 1902 1903 return total_bytes; 1904 } 1905 1906 void StructuredDataDarwinLog::EnableNow() { 1907 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1908 if (log) 1909 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); 1910 1911 // Run the enable command. 1912 auto process_sp = GetProcess(); 1913 if (!process_sp) { 1914 // Nothing to do. 1915 if (log) 1916 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " 1917 "valid process, skipping", 1918 __FUNCTION__); 1919 return; 1920 } 1921 if (log) 1922 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %u", 1923 __FUNCTION__, process_sp->GetUniqueID()); 1924 1925 // If we have configuration data, we can directly enable it now. 1926 // Otherwise, we need to run through the command interpreter to parse 1927 // the auto-run options (which is the only way we get here without having 1928 // already-parsed configuration data). 1929 DebuggerSP debugger_sp = 1930 process_sp->GetTarget().GetDebugger().shared_from_this(); 1931 if (!debugger_sp) { 1932 if (log) 1933 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " 1934 "debugger shared pointer, skipping (process uid %u)", 1935 __FUNCTION__, process_sp->GetUniqueID()); 1936 return; 1937 } 1938 1939 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1940 if (!options_sp) { 1941 // We haven't run the enable command yet. Just do that now, it'll 1942 // take care of the rest. 1943 auto &interpreter = debugger_sp->GetCommandInterpreter(); 1944 const bool success = RunEnableCommand(interpreter); 1945 if (log) { 1946 if (success) 1947 log->Printf("StructuredDataDarwinLog::%s() ran enable command " 1948 "successfully for (process uid %u)", 1949 __FUNCTION__, process_sp->GetUniqueID()); 1950 else 1951 log->Printf("StructuredDataDarwinLog::%s() error: running " 1952 "enable command failed (process uid %u)", 1953 __FUNCTION__, process_sp->GetUniqueID()); 1954 } 1955 // Report failures to the debugger error stream. 1956 auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); 1957 if (error_stream_sp) { 1958 error_stream_sp->Printf("failed to configure DarwinLog " 1959 "support\n"); 1960 error_stream_sp->Flush(); 1961 } 1962 return; 1963 } 1964 1965 // We've previously been enabled. We will re-enable now with the 1966 // previously specified options. 1967 auto config_sp = options_sp->BuildConfigurationData(true); 1968 if (!config_sp) { 1969 if (log) 1970 log->Printf("StructuredDataDarwinLog::%s() warning: failed to " 1971 "build configuration data for enable options, skipping " 1972 "(process uid %u)", 1973 __FUNCTION__, process_sp->GetUniqueID()); 1974 return; 1975 } 1976 1977 // We can run it directly. 1978 // Send configuration to the feature by way of the process. 1979 const Error error = 1980 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp); 1981 1982 // Report results. 1983 if (!error.Success()) { 1984 if (log) 1985 log->Printf("StructuredDataDarwinLog::%s() " 1986 "ConfigureStructuredData() call failed " 1987 "(process uid %u): %s", 1988 __FUNCTION__, process_sp->GetUniqueID(), error.AsCString()); 1989 auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); 1990 if (error_stream_sp) { 1991 error_stream_sp->Printf("failed to configure DarwinLog " 1992 "support: %s\n", 1993 error.AsCString()); 1994 error_stream_sp->Flush(); 1995 } 1996 m_is_enabled = false; 1997 } else { 1998 m_is_enabled = true; 1999 if (log) 2000 log->Printf("StructuredDataDarwinLog::%s() success via direct " 2001 "configuration (process uid %u)", 2002 __FUNCTION__, process_sp->GetUniqueID()); 2003 } 2004 } 2005