Coverage Report

Created: 2022-01-15 10:30

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