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 llvm::StringRef 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()); 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.empty()) { 1104 command_stream << ' '; 1105 command_stream << enable_options; 1106 } 1107 1108 // Run the command. 1109 CommandReturnObject return_object; 1110 interpreter.HandleCommand(command_stream.GetData(), 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.GetData()); 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, object_stream.GetData()); 1226 } 1227 1228 Error StructuredDataDarwinLog::GetDescription( 1229 const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) { 1230 Error error; 1231 1232 if (!object_sp) { 1233 error.SetErrorString("No structured data."); 1234 return error; 1235 } 1236 1237 // Log message payload objects will be dictionaries. 1238 const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); 1239 if (!dictionary) { 1240 SetErrorWithJSON(error, "Structured data should have been a dictionary " 1241 "but wasn't", 1242 *object_sp); 1243 return error; 1244 } 1245 1246 // Validate this is really a message for our plugin. 1247 ConstString type_name; 1248 if (!dictionary->GetValueForKeyAsString("type", type_name)) { 1249 SetErrorWithJSON(error, "Structured data doesn't contain mandatory " 1250 "type field", 1251 *object_sp); 1252 return error; 1253 } 1254 1255 if (type_name != GetDarwinLogTypeName()) { 1256 // This is okay - it simply means the data we received is not a log 1257 // message. We'll just format it as is. 1258 object_sp->Dump(stream); 1259 return error; 1260 } 1261 1262 // DarwinLog dictionaries store their data 1263 // in an array with key name "events". 1264 StructuredData::Array *events = nullptr; 1265 if (!dictionary->GetValueForKeyAsArray("events", events) || !events) { 1266 SetErrorWithJSON(error, "Log structured data is missing mandatory " 1267 "'events' field, expected to be an array", 1268 *object_sp); 1269 return error; 1270 } 1271 1272 events->ForEach( 1273 [&stream, &error, &object_sp, this](StructuredData::Object *object) { 1274 if (!object) { 1275 // Invalid. Stop iterating. 1276 SetErrorWithJSON(error, "Log event entry is null", *object_sp); 1277 return false; 1278 } 1279 1280 auto event = object->GetAsDictionary(); 1281 if (!event) { 1282 // Invalid, stop iterating. 1283 SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp); 1284 return false; 1285 } 1286 1287 // If we haven't already grabbed the first timestamp 1288 // value, do that now. 1289 if (!m_recorded_first_timestamp) { 1290 uint64_t timestamp = 0; 1291 if (event->GetValueForKeyAsInteger("timestamp", timestamp)) { 1292 m_first_timestamp_seen = timestamp; 1293 m_recorded_first_timestamp = true; 1294 } 1295 } 1296 1297 HandleDisplayOfEvent(*event, stream); 1298 return true; 1299 }); 1300 1301 stream.Flush(); 1302 return error; 1303 } 1304 1305 bool StructuredDataDarwinLog::GetEnabled(const ConstString &type_name) const { 1306 if (type_name == GetStaticPluginName()) 1307 return m_is_enabled; 1308 else 1309 return false; 1310 } 1311 1312 void StructuredDataDarwinLog::SetEnabled(bool enabled) { 1313 m_is_enabled = enabled; 1314 } 1315 1316 void StructuredDataDarwinLog::ModulesDidLoad(Process &process, 1317 ModuleList &module_list) { 1318 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1319 if (log) 1320 log->Printf("StructuredDataDarwinLog::%s called (process uid %u)", 1321 __FUNCTION__, process.GetUniqueID()); 1322 1323 // Check if we should enable the darwin log support on startup/attach. 1324 if (!GetGlobalProperties()->GetEnableOnStartup() && 1325 !s_is_explicitly_enabled) { 1326 // We're neither auto-enabled or explicitly enabled, so we shouldn't 1327 // try to enable here. 1328 if (log) 1329 log->Printf("StructuredDataDarwinLog::%s not applicable, we're not " 1330 "enabled (process uid %u)", 1331 __FUNCTION__, process.GetUniqueID()); 1332 return; 1333 } 1334 1335 // If we already added the breakpoint, we've got nothing left to do. 1336 { 1337 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex); 1338 if (m_added_breakpoint) { 1339 if (log) 1340 log->Printf("StructuredDataDarwinLog::%s process uid %u's " 1341 "post-libtrace-init breakpoint is already set", 1342 __FUNCTION__, process.GetUniqueID()); 1343 return; 1344 } 1345 } 1346 1347 // The logging support module name, specifies the name of 1348 // the image name that must be loaded into the debugged process before 1349 // we can try to enable logging. 1350 const char *logging_module_cstr = 1351 GetGlobalProperties()->GetLoggingModuleName(); 1352 if (!logging_module_cstr || (logging_module_cstr[0] == 0)) { 1353 // We need this. Bail. 1354 if (log) 1355 log->Printf("StructuredDataDarwinLog::%s no logging module name " 1356 "specified, we don't know where to set a breakpoint " 1357 "(process uid %u)", 1358 __FUNCTION__, process.GetUniqueID()); 1359 return; 1360 } 1361 1362 const ConstString logging_module_name = ConstString(logging_module_cstr); 1363 1364 // We need to see libtrace in the list of modules before we can enable 1365 // tracing for the target process. 1366 bool found_logging_support_module = false; 1367 for (size_t i = 0; i < module_list.GetSize(); ++i) { 1368 auto module_sp = module_list.GetModuleAtIndex(i); 1369 if (!module_sp) 1370 continue; 1371 1372 auto &file_spec = module_sp->GetFileSpec(); 1373 found_logging_support_module = 1374 (file_spec.GetLastPathComponent() == logging_module_name); 1375 if (found_logging_support_module) 1376 break; 1377 } 1378 1379 if (!found_logging_support_module) { 1380 if (log) 1381 log->Printf("StructuredDataDarwinLog::%s logging module %s " 1382 "has not yet been loaded, can't set a breakpoint " 1383 "yet (process uid %u)", 1384 __FUNCTION__, logging_module_name.AsCString(), 1385 process.GetUniqueID()); 1386 return; 1387 } 1388 1389 // Time to enqueue the breakpoint so we can wait for logging support 1390 // to be initialized before we try to tap the libtrace stream. 1391 AddInitCompletionHook(process); 1392 if (log) 1393 log->Printf("StructuredDataDarwinLog::%s post-init hook breakpoint " 1394 "set for logging module %s (process uid %u)", 1395 __FUNCTION__, logging_module_name.AsCString(), 1396 process.GetUniqueID()); 1397 1398 // We need to try the enable here as well, which will succeed 1399 // in the event that we're attaching to (rather than launching) the 1400 // process and the process is already past initialization time. In that 1401 // case, the completion breakpoint will never get hit and therefore won't 1402 // start that way. It doesn't hurt much beyond a bit of bandwidth 1403 // if we end up doing this twice. It hurts much more if we don't get 1404 // the logging enabled when the user expects it. 1405 EnableNow(); 1406 } 1407 1408 #pragma mark - 1409 #pragma mark Private instance methods 1410 1411 // ----------------------------------------------------------------------------- 1412 // Private constructors 1413 // ----------------------------------------------------------------------------- 1414 1415 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp) 1416 : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false), 1417 m_first_timestamp_seen(0), m_is_enabled(false), 1418 m_added_breakpoint_mutex(), m_added_breakpoint() {} 1419 1420 // ----------------------------------------------------------------------------- 1421 // Private static methods 1422 // ----------------------------------------------------------------------------- 1423 1424 StructuredDataPluginSP 1425 StructuredDataDarwinLog::CreateInstance(Process &process) { 1426 // Currently only Apple targets support the os_log/os_activity 1427 // protocol. 1428 if (process.GetTarget().GetArchitecture().GetTriple().getVendor() == 1429 llvm::Triple::VendorType::Apple) { 1430 auto process_wp = ProcessWP(process.shared_from_this()); 1431 return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp)); 1432 } else { 1433 return StructuredDataPluginSP(); 1434 } 1435 } 1436 1437 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) { 1438 // Setup parent class first. 1439 StructuredDataPlugin::InitializeBasePluginForDebugger(debugger); 1440 1441 // Get parent command. 1442 auto &interpreter = debugger.GetCommandInterpreter(); 1443 llvm::StringRef parent_command_text = "plugin structured-data"; 1444 auto parent_command = 1445 interpreter.GetCommandObjectForCommand(parent_command_text); 1446 if (!parent_command) { 1447 // Ut oh, parent failed to create parent command. 1448 // TODO log 1449 return; 1450 } 1451 1452 auto command_name = "darwin-log"; 1453 auto command_sp = CommandObjectSP(new BaseCommand(interpreter)); 1454 bool result = parent_command->LoadSubCommand(command_name, command_sp); 1455 if (!result) { 1456 // TODO log it once we setup structured data logging 1457 } 1458 1459 if (!PluginManager::GetSettingForPlatformPlugin( 1460 debugger, StructuredDataDarwinLogProperties::GetSettingName())) { 1461 const bool is_global_setting = true; 1462 PluginManager::CreateSettingForStructuredDataPlugin( 1463 debugger, GetGlobalProperties()->GetValueProperties(), 1464 ConstString("Properties for the darwin-log" 1465 " plug-in."), 1466 is_global_setting); 1467 } 1468 } 1469 1470 Error StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info, 1471 Target *target) { 1472 Error error; 1473 1474 // If we're not debugging this launched process, there's nothing for us 1475 // to do here. 1476 if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug)) 1477 return error; 1478 1479 // Darwin os_log() support automatically adds debug-level and info-level 1480 // messages when a debugger is attached to a process. However, with 1481 // integrated suppport for debugging built into the command-line LLDB, 1482 // the user may specifically set to *not* include debug-level and info-level 1483 // content. When the user is using the integrated log support, we want 1484 // to put the kabosh on that automatic adding of info and debug level. 1485 // This is done by adding an environment variable to the process on launch. 1486 // (This also means it is not possible to suppress this behavior if 1487 // attaching to an already-running app). 1488 // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1489 1490 // If the target architecture is not one that supports DarwinLog, we have 1491 // nothing to do here. 1492 auto &triple = target ? target->GetArchitecture().GetTriple() 1493 : launch_info.GetArchitecture().GetTriple(); 1494 if (triple.getVendor() != llvm::Triple::Apple) { 1495 return error; 1496 } 1497 1498 // If DarwinLog is not enabled (either by explicit user command or via 1499 // the auto-enable option), then we have nothing to do. 1500 if (!GetGlobalProperties()->GetEnableOnStartup() && 1501 !s_is_explicitly_enabled) { 1502 // Nothing to do, DarwinLog is not enabled. 1503 return error; 1504 } 1505 1506 // If we don't have parsed configuration info, that implies we have 1507 // enable-on-startup set up, but we haven't yet attempted to run the 1508 // enable command. 1509 if (!target) { 1510 // We really can't do this without a target. We need to be able 1511 // to get to the debugger to get the proper options to do this right. 1512 // TODO log. 1513 error.SetErrorString("requires a target to auto-enable DarwinLog."); 1514 return error; 1515 } 1516 1517 DebuggerSP debugger_sp = target->GetDebugger().shared_from_this(); 1518 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1519 if (!options_sp && debugger_sp) { 1520 options_sp = ParseAutoEnableOptions(error, *debugger_sp.get()); 1521 if (!options_sp || !error.Success()) 1522 return error; 1523 1524 // We already parsed the options, save them now so we don't generate 1525 // them again until the user runs the command manually. 1526 SetGlobalEnableOptions(debugger_sp, options_sp); 1527 } 1528 1529 auto &env_vars = launch_info.GetEnvironmentEntries(); 1530 if (!options_sp->GetEchoToStdErr()) { 1531 // The user doesn't want to see os_log/NSLog messages echo to stderr. 1532 // That mechanism is entirely separate from the DarwinLog support. 1533 // By default we don't want to get it via stderr, because that would 1534 // be in duplicate of the explicit log support here. 1535 1536 // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent 1537 // echoing of os_log()/NSLog() to stderr in the target program. 1538 size_t argument_index; 1539 if (env_vars.ContainsEnvironmentVariable( 1540 llvm::StringRef("OS_ACTIVITY_DT_MODE"), &argument_index)) 1541 env_vars.DeleteArgumentAtIndex(argument_index); 1542 1543 // We will also set the env var that tells any downstream launcher 1544 // from adding OS_ACTIVITY_DT_MODE. 1545 env_vars.AddOrReplaceEnvironmentVariable( 1546 llvm::StringRef("IDE_DISABLED_OS_ACTIVITY_DT_MODE"), 1547 llvm::StringRef("1")); 1548 } 1549 1550 // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable 1551 // debug and info level messages. 1552 const char *env_var_value; 1553 if (options_sp->GetIncludeDebugLevel()) 1554 env_var_value = "debug"; 1555 else if (options_sp->GetIncludeInfoLevel()) 1556 env_var_value = "info"; 1557 else 1558 env_var_value = "default"; 1559 1560 if (env_var_value) { 1561 launch_info.GetEnvironmentEntries().AddOrReplaceEnvironmentVariable( 1562 llvm::StringRef("OS_ACTIVITY_MODE"), llvm::StringRef(env_var_value)); 1563 } 1564 1565 return error; 1566 } 1567 1568 bool StructuredDataDarwinLog::InitCompletionHookCallback( 1569 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 1570 lldb::user_id_t break_loc_id) { 1571 // We hit the init function. We now want to enqueue our new thread plan, 1572 // which will in turn enqueue a StepOut thread plan. When the StepOut 1573 // finishes and control returns to our new thread plan, that is the time 1574 // when we can execute our logic to enable the logging support. 1575 1576 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1577 if (log) 1578 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); 1579 1580 // Get the current thread. 1581 if (!context) { 1582 if (log) 1583 log->Printf("StructuredDataDarwinLog::%s() warning: no context, " 1584 "ignoring", 1585 __FUNCTION__); 1586 return false; 1587 } 1588 1589 // Get the plugin from the process. 1590 auto process_sp = context->exe_ctx_ref.GetProcessSP(); 1591 if (!process_sp) { 1592 if (log) 1593 log->Printf("StructuredDataDarwinLog::%s() warning: invalid " 1594 "process in context, ignoring", 1595 __FUNCTION__); 1596 return false; 1597 } 1598 if (log) 1599 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %d", 1600 __FUNCTION__, process_sp->GetUniqueID()); 1601 1602 auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); 1603 if (!plugin_sp) { 1604 if (log) 1605 log->Printf("StructuredDataDarwinLog::%s() warning: no plugin for " 1606 "feature %s in process uid %u", 1607 __FUNCTION__, GetDarwinLogTypeName().AsCString(), 1608 process_sp->GetUniqueID()); 1609 return false; 1610 } 1611 1612 // Create the callback for when the thread plan completes. 1613 bool called_enable_method = false; 1614 const auto process_uid = process_sp->GetUniqueID(); 1615 1616 std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp); 1617 ThreadPlanCallOnFunctionExit::Callback callback = 1618 [plugin_wp, &called_enable_method, log, process_uid]() { 1619 if (log) 1620 log->Printf("StructuredDataDarwinLog::post-init callback: " 1621 "called (process uid %u)", 1622 process_uid); 1623 1624 auto strong_plugin_sp = plugin_wp.lock(); 1625 if (!strong_plugin_sp) { 1626 if (log) 1627 log->Printf("StructuredDataDarwinLog::post-init callback: " 1628 "plugin no longer exists, ignoring (process " 1629 "uid %u)", 1630 process_uid); 1631 return; 1632 } 1633 // Make sure we only call it once, just in case the 1634 // thread plan hits the breakpoint twice. 1635 if (!called_enable_method) { 1636 if (log) 1637 log->Printf("StructuredDataDarwinLog::post-init callback: " 1638 "calling EnableNow() (process uid %u)", 1639 process_uid); 1640 static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get()) 1641 ->EnableNow(); 1642 called_enable_method = true; 1643 } else { 1644 // Our breakpoint was hit more than once. Unexpected but 1645 // no harm done. Log it. 1646 if (log) 1647 log->Printf("StructuredDataDarwinLog::post-init callback: " 1648 "skipping EnableNow(), already called by " 1649 "callback [we hit this more than once] " 1650 "(process uid %u)", 1651 process_uid); 1652 } 1653 }; 1654 1655 // Grab the current thread. 1656 auto thread_sp = context->exe_ctx_ref.GetThreadSP(); 1657 if (!thread_sp) { 1658 if (log) 1659 log->Printf("StructuredDataDarwinLog::%s() warning: failed to " 1660 "retrieve the current thread from the execution " 1661 "context, nowhere to run the thread plan (process uid " 1662 "%u)", 1663 __FUNCTION__, process_sp->GetUniqueID()); 1664 return false; 1665 } 1666 1667 // Queue the thread plan. 1668 auto thread_plan_sp = ThreadPlanSP( 1669 new ThreadPlanCallOnFunctionExit(*thread_sp.get(), callback)); 1670 const bool abort_other_plans = false; 1671 thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans); 1672 if (log) 1673 log->Printf("StructuredDataDarwinLog::%s() queuing thread plan on " 1674 "trace library init method entry (process uid %u)", 1675 __FUNCTION__, process_sp->GetUniqueID()); 1676 1677 // We return false here to indicate that it isn't a public stop. 1678 return false; 1679 } 1680 1681 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) { 1682 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1683 if (log) 1684 log->Printf("StructuredDataDarwinLog::%s() called (process uid %u)", 1685 __FUNCTION__, process.GetUniqueID()); 1686 1687 // Make sure we haven't already done this. 1688 { 1689 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex); 1690 if (m_added_breakpoint) { 1691 if (log) 1692 log->Printf("StructuredDataDarwinLog::%s() ignoring request, " 1693 "breakpoint already set (process uid %u)", 1694 __FUNCTION__, process.GetUniqueID()); 1695 return; 1696 } 1697 1698 // We're about to do this, don't let anybody else try to do it. 1699 m_added_breakpoint = true; 1700 } 1701 1702 // Set a breakpoint for the process that will kick in when libtrace 1703 // has finished its initialization. 1704 Target &target = process.GetTarget(); 1705 1706 // Build up the module list. 1707 FileSpecList module_spec_list; 1708 auto module_file_spec = 1709 FileSpec(GetGlobalProperties()->GetLoggingModuleName(), false); 1710 module_spec_list.Append(module_file_spec); 1711 1712 // We aren't specifying a source file set. 1713 FileSpecList *source_spec_list = nullptr; 1714 1715 const char *func_name = "_libtrace_init"; 1716 const lldb::addr_t offset = 0; 1717 const LazyBool skip_prologue = eLazyBoolCalculate; 1718 // This is an internal breakpoint - the user shouldn't see it. 1719 const bool internal = true; 1720 const bool hardware = false; 1721 1722 auto breakpoint_sp = target.CreateBreakpoint( 1723 &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull, 1724 eLanguageTypeC, offset, skip_prologue, internal, hardware); 1725 if (!breakpoint_sp) { 1726 // Huh? Bail here. 1727 if (log) 1728 log->Printf("StructuredDataDarwinLog::%s() failed to set " 1729 "breakpoint in module %s, function %s (process uid %u)", 1730 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(), 1731 func_name, process.GetUniqueID()); 1732 return; 1733 } 1734 1735 // Set our callback. 1736 breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr); 1737 if (log) 1738 log->Printf("StructuredDataDarwinLog::%s() breakpoint set in module %s," 1739 "function %s (process uid %u)", 1740 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(), 1741 func_name, process.GetUniqueID()); 1742 } 1743 1744 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream, 1745 uint64_t timestamp) { 1746 const uint64_t delta_nanos = timestamp - m_first_timestamp_seen; 1747 1748 const uint64_t hours = delta_nanos / NANOS_PER_HOUR; 1749 uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR; 1750 1751 const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE; 1752 nanos_remaining = nanos_remaining % NANOS_PER_MINUTE; 1753 1754 const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND; 1755 nanos_remaining = nanos_remaining % NANOS_PER_SECOND; 1756 1757 stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours, 1758 minutes, seconds, nanos_remaining); 1759 } 1760 1761 size_t 1762 StructuredDataDarwinLog::DumpHeader(Stream &output_stream, 1763 const StructuredData::Dictionary &event) { 1764 StreamString stream; 1765 1766 ProcessSP process_sp = GetProcess(); 1767 if (!process_sp) { 1768 // TODO log 1769 return 0; 1770 } 1771 1772 DebuggerSP debugger_sp = 1773 process_sp->GetTarget().GetDebugger().shared_from_this(); 1774 if (!debugger_sp) { 1775 // TODO log 1776 return 0; 1777 } 1778 1779 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1780 if (!options_sp) { 1781 // TODO log 1782 return 0; 1783 } 1784 1785 // Check if we should even display a header. 1786 if (!options_sp->GetDisplayAnyHeaderFields()) 1787 return 0; 1788 1789 stream.PutChar('['); 1790 1791 int header_count = 0; 1792 if (options_sp->GetDisplayTimestampRelative()) { 1793 uint64_t timestamp = 0; 1794 if (event.GetValueForKeyAsInteger("timestamp", timestamp)) { 1795 DumpTimestamp(stream, timestamp); 1796 ++header_count; 1797 } 1798 } 1799 1800 if (options_sp->GetDisplayActivityChain()) { 1801 std::string activity_chain; 1802 if (event.GetValueForKeyAsString("activity-chain", activity_chain) && 1803 !activity_chain.empty()) { 1804 if (header_count > 0) 1805 stream.PutChar(','); 1806 1807 // Switch over to the #if 0 branch once we figure out 1808 // how we want to present settings for the tri-state of 1809 // no-activity, activity (most derived only), or activity-chain. 1810 #if 1 1811 // Display the activity chain, from parent-most to child-most 1812 // activity, separated by a colon (:). 1813 stream.PutCString("activity-chain="); 1814 stream.PutCString(activity_chain); 1815 #else 1816 if (GetGlobalProperties()->GetDisplayActivityChain()) { 1817 // Display the activity chain, from parent-most to child-most 1818 // activity, separated by a colon (:). 1819 stream.PutCString("activity-chain="); 1820 stream.PutCString(activity_chain.c_str()); 1821 } else { 1822 // We're only displaying the child-most activity. 1823 stream.PutCString("activity="); 1824 auto pos = activity_chain.find_last_of(':'); 1825 if (pos == std::string::npos) { 1826 // The activity chain only has one level, use the whole 1827 // thing. 1828 stream.PutCString(activity_chain.c_str()); 1829 } else { 1830 // Display everything after the final ':'. 1831 stream.PutCString(activity_chain.substr(pos + 1).c_str()); 1832 } 1833 } 1834 #endif 1835 ++header_count; 1836 } 1837 } 1838 1839 if (options_sp->GetDisplaySubsystem()) { 1840 std::string subsystem; 1841 if (event.GetValueForKeyAsString("subsystem", subsystem) && 1842 !subsystem.empty()) { 1843 if (header_count > 0) 1844 stream.PutChar(','); 1845 stream.PutCString("subsystem="); 1846 stream.PutCString(subsystem); 1847 ++header_count; 1848 } 1849 } 1850 1851 if (options_sp->GetDisplayCategory()) { 1852 std::string category; 1853 if (event.GetValueForKeyAsString("category", category) && 1854 !category.empty()) { 1855 if (header_count > 0) 1856 stream.PutChar(','); 1857 stream.PutCString("category="); 1858 stream.PutCString(category); 1859 ++header_count; 1860 } 1861 } 1862 stream.PutCString("] "); 1863 1864 output_stream.PutCString(stream.GetString()); 1865 1866 return stream.GetSize(); 1867 } 1868 1869 size_t StructuredDataDarwinLog::HandleDisplayOfEvent( 1870 const StructuredData::Dictionary &event, Stream &stream) { 1871 // Check the type of the event. 1872 ConstString event_type; 1873 if (!event.GetValueForKeyAsString("type", event_type)) { 1874 // Hmm, we expected to get events that describe 1875 // what they are. Continue anyway. 1876 return 0; 1877 } 1878 1879 if (event_type != GetLogEventType()) 1880 return 0; 1881 1882 size_t total_bytes = 0; 1883 1884 // Grab the message content. 1885 std::string message; 1886 if (!event.GetValueForKeyAsString("message", message)) 1887 return true; 1888 1889 // Display the log entry. 1890 const auto len = message.length(); 1891 1892 total_bytes += DumpHeader(stream, event); 1893 1894 stream.Write(message.c_str(), len); 1895 total_bytes += len; 1896 1897 // Add an end of line. 1898 stream.PutChar('\n'); 1899 total_bytes += sizeof(char); 1900 1901 return total_bytes; 1902 } 1903 1904 void StructuredDataDarwinLog::EnableNow() { 1905 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1906 if (log) 1907 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); 1908 1909 // Run the enable command. 1910 auto process_sp = GetProcess(); 1911 if (!process_sp) { 1912 // Nothing to do. 1913 if (log) 1914 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " 1915 "valid process, skipping", 1916 __FUNCTION__); 1917 return; 1918 } 1919 if (log) 1920 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %u", 1921 __FUNCTION__, process_sp->GetUniqueID()); 1922 1923 // If we have configuration data, we can directly enable it now. 1924 // Otherwise, we need to run through the command interpreter to parse 1925 // the auto-run options (which is the only way we get here without having 1926 // already-parsed configuration data). 1927 DebuggerSP debugger_sp = 1928 process_sp->GetTarget().GetDebugger().shared_from_this(); 1929 if (!debugger_sp) { 1930 if (log) 1931 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " 1932 "debugger shared pointer, skipping (process uid %u)", 1933 __FUNCTION__, process_sp->GetUniqueID()); 1934 return; 1935 } 1936 1937 auto options_sp = GetGlobalEnableOptions(debugger_sp); 1938 if (!options_sp) { 1939 // We haven't run the enable command yet. Just do that now, it'll 1940 // take care of the rest. 1941 auto &interpreter = debugger_sp->GetCommandInterpreter(); 1942 const bool success = RunEnableCommand(interpreter); 1943 if (log) { 1944 if (success) 1945 log->Printf("StructuredDataDarwinLog::%s() ran enable command " 1946 "successfully for (process uid %u)", 1947 __FUNCTION__, process_sp->GetUniqueID()); 1948 else 1949 log->Printf("StructuredDataDarwinLog::%s() error: running " 1950 "enable command failed (process uid %u)", 1951 __FUNCTION__, process_sp->GetUniqueID()); 1952 } 1953 // Report failures to the debugger error stream. 1954 auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); 1955 if (error_stream_sp) { 1956 error_stream_sp->Printf("failed to configure DarwinLog " 1957 "support\n"); 1958 error_stream_sp->Flush(); 1959 } 1960 return; 1961 } 1962 1963 // We've previously been enabled. We will re-enable now with the 1964 // previously specified options. 1965 auto config_sp = options_sp->BuildConfigurationData(true); 1966 if (!config_sp) { 1967 if (log) 1968 log->Printf("StructuredDataDarwinLog::%s() warning: failed to " 1969 "build configuration data for enable options, skipping " 1970 "(process uid %u)", 1971 __FUNCTION__, process_sp->GetUniqueID()); 1972 return; 1973 } 1974 1975 // We can run it directly. 1976 // Send configuration to the feature by way of the process. 1977 const Error error = 1978 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp); 1979 1980 // Report results. 1981 if (!error.Success()) { 1982 if (log) 1983 log->Printf("StructuredDataDarwinLog::%s() " 1984 "ConfigureStructuredData() call failed " 1985 "(process uid %u): %s", 1986 __FUNCTION__, process_sp->GetUniqueID(), error.AsCString()); 1987 auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); 1988 if (error_stream_sp) { 1989 error_stream_sp->Printf("failed to configure DarwinLog " 1990 "support: %s\n", 1991 error.AsCString()); 1992 error_stream_sp->Flush(); 1993 } 1994 m_is_enabled = false; 1995 } else { 1996 m_is_enabled = true; 1997 if (log) 1998 log->Printf("StructuredDataDarwinLog::%s() success via direct " 1999 "configuration (process uid %u)", 2000 __FUNCTION__, process_sp->GetUniqueID()); 2001 } 2002 } 2003