Coverage Report

Created: 2023-09-12 09:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/include/lldb/Target/Process.h
Line
Count
Source (jump to first uncovered line)
1
//===-- Process.h -----------------------------------------------*- C++ -*-===//
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
#ifndef LLDB_TARGET_PROCESS_H
10
#define LLDB_TARGET_PROCESS_H
11
12
#include "lldb/Host/Config.h"
13
14
#include <climits>
15
16
#include <chrono>
17
#include <list>
18
#include <memory>
19
#include <mutex>
20
#include <optional>
21
#include <string>
22
#include <unordered_set>
23
#include <vector>
24
25
#include "lldb/Breakpoint/BreakpointSiteList.h"
26
#include "lldb/Core/LoadedModuleInfoList.h"
27
#include "lldb/Core/PluginInterface.h"
28
#include "lldb/Core/SourceManager.h"
29
#include "lldb/Core/ThreadSafeValue.h"
30
#include "lldb/Core/ThreadedCommunication.h"
31
#include "lldb/Core/UserSettingsController.h"
32
#include "lldb/Host/HostThread.h"
33
#include "lldb/Host/ProcessLaunchInfo.h"
34
#include "lldb/Host/ProcessRunLock.h"
35
#include "lldb/Symbol/ObjectFile.h"
36
#include "lldb/Target/ExecutionContextScope.h"
37
#include "lldb/Target/InstrumentationRuntime.h"
38
#include "lldb/Target/Memory.h"
39
#include "lldb/Target/MemoryTagManager.h"
40
#include "lldb/Target/QueueList.h"
41
#include "lldb/Target/ThreadList.h"
42
#include "lldb/Target/ThreadPlanStack.h"
43
#include "lldb/Target/Trace.h"
44
#include "lldb/Utility/ArchSpec.h"
45
#include "lldb/Utility/Broadcaster.h"
46
#include "lldb/Utility/Event.h"
47
#include "lldb/Utility/Listener.h"
48
#include "lldb/Utility/NameMatches.h"
49
#include "lldb/Utility/ProcessInfo.h"
50
#include "lldb/Utility/Status.h"
51
#include "lldb/Utility/StructuredData.h"
52
#include "lldb/Utility/TraceGDBRemotePackets.h"
53
#include "lldb/Utility/UnimplementedError.h"
54
#include "lldb/Utility/UserIDResolver.h"
55
#include "lldb/lldb-private.h"
56
57
#include "llvm/ADT/ArrayRef.h"
58
#include "llvm/Support/Threading.h"
59
#include "llvm/Support/VersionTuple.h"
60
61
namespace lldb_private {
62
63
template <typename B, typename S> struct Range;
64
65
class ProcessExperimentalProperties : public Properties {
66
public:
67
  ProcessExperimentalProperties();
68
};
69
70
class ProcessProperties : public Properties {
71
public:
72
  // Pass nullptr for "process" if the ProcessProperties are to be the global
73
  // copy
74
  ProcessProperties(lldb_private::Process *process);
75
76
  ~ProcessProperties() override;
77
78
  bool GetDisableMemoryCache() const;
79
  uint64_t GetMemoryCacheLineSize() const;
80
  Args GetExtraStartupCommands() const;
81
  void SetExtraStartupCommands(const Args &args);
82
  FileSpec GetPythonOSPluginPath() const;
83
  uint32_t GetVirtualAddressableBits() const;
84
  void SetVirtualAddressableBits(uint32_t bits);
85
  uint32_t GetHighmemVirtualAddressableBits() const;
86
  void SetHighmemVirtualAddressableBits(uint32_t bits);
87
  void SetPythonOSPluginPath(const FileSpec &file);
88
  bool GetIgnoreBreakpointsInExpressions() const;
89
  void SetIgnoreBreakpointsInExpressions(bool ignore);
90
  bool GetUnwindOnErrorInExpressions() const;
91
  void SetUnwindOnErrorInExpressions(bool ignore);
92
  bool GetStopOnSharedLibraryEvents() const;
93
  void SetStopOnSharedLibraryEvents(bool stop);
94
  bool GetDisableLangRuntimeUnwindPlans() const;
95
  void SetDisableLangRuntimeUnwindPlans(bool disable);
96
  bool GetDetachKeepsStopped() const;
97
  void SetDetachKeepsStopped(bool keep_stopped);
98
  bool GetWarningsOptimization() const;
99
  bool GetWarningsUnsupportedLanguage() const;
100
  bool GetStopOnExec() const;
101
  std::chrono::seconds GetUtilityExpressionTimeout() const;
102
  std::chrono::seconds GetInterruptTimeout() const;
103
  bool GetOSPluginReportsAllThreads() const;
104
  void SetOSPluginReportsAllThreads(bool does_report);
105
  bool GetSteppingRunsAllThreads() const;
106
  FollowForkMode GetFollowForkMode() const;
107
108
protected:
109
  Process *m_process; // Can be nullptr for global ProcessProperties
110
  std::unique_ptr<ProcessExperimentalProperties> m_experimental_properties_up;
111
};
112
113
// ProcessAttachInfo
114
//
115
// Describes any information that is required to attach to a process.
116
117
class ProcessAttachInfo : public ProcessInstanceInfo {
118
public:
119
12.1k
  ProcessAttachInfo() = default;
120
121
  ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
122
      : m_resume_count(0), m_wait_for_launch(false), m_ignore_existing(true),
123
        m_continue_once_attached(false), m_detach_on_error(true),
124
2.08k
        m_async(false) {
125
2.08k
    ProcessInfo::operator=(launch_info);
126
2.08k
    SetProcessPluginName(launch_info.GetProcessPluginName());
127
2.08k
    SetResumeCount(launch_info.GetResumeCount());
128
2.08k
    m_detach_on_error = launch_info.GetDetachOnError();
129
2.08k
  }
130
131
3
  bool GetWaitForLaunch() const { return m_wait_for_launch; }
132
133
1
  void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
134
135
26
  bool GetAsync() const { return m_async; }
136
137
0
  void SetAsync(bool b) { m_async = b; }
138
139
0
  bool GetIgnoreExisting() const { return m_ignore_existing; }
140
141
2
  void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
142
143
14
  bool GetContinueOnceAttached() const { return m_continue_once_attached; }
144
145
1
  void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
146
147
2.11k
  uint32_t GetResumeCount() const { return m_resume_count; }
148
149
2.08k
  void SetResumeCount(uint32_t c) { m_resume_count = c; }
150
151
1
  llvm::StringRef GetProcessPluginName() const {
152
1
    return llvm::StringRef(m_plugin_name);
153
1
  }
154
155
2.08k
  void SetProcessPluginName(llvm::StringRef plugin) {
156
2.08k
    m_plugin_name = std::string(plugin);
157
2.08k
  }
158
159
12.1k
  void Clear() {
160
12.1k
    ProcessInstanceInfo::Clear();
161
12.1k
    m_plugin_name.clear();
162
12.1k
    m_resume_count = 0;
163
12.1k
    m_wait_for_launch = false;
164
12.1k
    m_ignore_existing = true;
165
12.1k
    m_continue_once_attached = false;
166
12.1k
  }
167
168
26
  bool ProcessInfoSpecified() const {
169
26
    if (GetExecutableFile())
170
3
      return true;
171
23
    if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
172
23
      return true;
173
0
    if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
174
0
      return true;
175
0
    return false;
176
0
  }
177
178
2.10k
  bool GetDetachOnError() const { return m_detach_on_error; }
179
180
0
  void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
181
182
  lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
183
184
protected:
185
  std::string m_plugin_name;
186
  uint32_t m_resume_count = 0; // How many times do we resume after launching
187
  bool m_wait_for_launch = false;
188
  bool m_ignore_existing = true;
189
  bool m_continue_once_attached = false; // Supports the use-case scenario of
190
                                         // immediately continuing the process
191
                                         // once attached.
192
  bool m_detach_on_error =
193
      true; // If we are debugging remotely, instruct the stub to
194
            // detach rather than killing the target on error.
195
  bool m_async =
196
      false; // Use an async attach where we start the attach and return
197
             // immediately (used by GUI programs with --waitfor so they can
198
             // call SBProcess::Stop() to cancel attach)
199
};
200
201
// This class tracks the Modification state of the process.  Things that can
202
// currently modify the program are running the program (which will up the
203
// StopID) and writing memory (which will up the MemoryID.)
204
// FIXME: Should we also include modification of register states?
205
206
class ProcessModID {
207
  friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
208
209
public:
210
208k
  ProcessModID() = default;
211
212
  ProcessModID(const ProcessModID &rhs)
213
764k
      : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
214
215
190k
  const ProcessModID &operator=(const ProcessModID &rhs) {
216
190k
    if (this != &rhs) {
217
190k
      m_stop_id = rhs.m_stop_id;
218
190k
      m_memory_id = rhs.m_memory_id;
219
190k
    }
220
190k
    return *this;
221
190k
  }
222
223
933k
  ~ProcessModID() = default;
224
225
16.1k
  uint32_t BumpStopID() {
226
16.1k
    const uint32_t prev_stop_id = m_stop_id++;
227
16.1k
    if (!IsLastResumeForUserExpression())
228
12.4k
      m_last_natural_stop_id++;
229
16.1k
    return prev_stop_id;
230
16.1k
  }
231
232
37.1k
  void BumpMemoryID() { m_memory_id++; }
233
234
12.1k
  void BumpResumeID() {
235
12.1k
    m_resume_id++;
236
12.1k
    if (m_running_user_expression > 0)
237
3.02k
      m_last_user_expression_resume = m_resume_id;
238
12.1k
  }
239
240
6.71k
  bool IsRunningUtilityFunction() const {
241
6.71k
    return m_running_utility_function > 0;
242
6.71k
  }
243
244
3.18M
  uint32_t GetStopID() const { return m_stop_id; }
245
35.9k
  uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
246
0
  uint32_t GetMemoryID() const { return m_memory_id; }
247
59.0k
  uint32_t GetResumeID() const { return m_resume_id; }
248
11.1k
  uint32_t GetLastUserExpressionResumeID() const {
249
11.1k
    return m_last_user_expression_resume;
250
11.1k
  }
251
252
569k
  bool MemoryIDEqual(const ProcessModID &compare) const {
253
569k
    return m_memory_id == compare.m_memory_id;
254
569k
  }
255
256
616k
  bool StopIDEqual(const ProcessModID &compare) const {
257
616k
    return m_stop_id == compare.m_stop_id;
258
616k
  }
259
260
28.0k
  void SetInvalid() { m_stop_id = UINT32_MAX; }
261
262
1.53M
  bool IsValid() const { return m_stop_id != UINT32_MAX; }
263
264
32.3k
  bool IsLastResumeForUserExpression() const {
265
    // If we haven't yet resumed the target, then it can't be for a user
266
    // expression...
267
32.3k
    if (m_resume_id == 0)
268
5.06k
      return false;
269
270
27.3k
    return m_resume_id == m_last_user_expression_resume;
271
32.3k
  }
272
273
2.60k
  bool IsRunningExpression() const {
274
    // Don't return true if we are no longer running an expression:
275
2.60k
    if (m_running_user_expression || 
m_running_utility_function2.59k
)
276
11
      return true;
277
2.59k
    return false;
278
2.60k
  }
279
280
5.88k
  void SetRunningUserExpression(bool on) {
281
5.88k
    if (on)
282
2.94k
      m_running_user_expression++;
283
2.94k
    else
284
2.94k
      m_running_user_expression--;
285
5.88k
  }
286
287
3.71k
  void SetRunningUtilityFunction(bool on) {
288
3.71k
    if (on)
289
1.85k
      m_running_utility_function++;
290
1.85k
    else {
291
1.85k
      assert(m_running_utility_function > 0 &&
292
1.85k
             "Called SetRunningUtilityFunction(false) without calling "
293
1.85k
             "SetRunningUtilityFunction(true) before?");
294
1.85k
      m_running_utility_function--;
295
1.85k
    }
296
3.71k
  }
297
298
17.3k
  void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
299
17.3k
    m_last_natural_stop_event = std::move(event_sp);
300
17.3k
  }
301
302
0
  lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
303
0
    if (stop_id == m_last_natural_stop_id)
304
0
      return m_last_natural_stop_event;
305
0
    return lldb::EventSP();
306
0
  }
307
308
private:
309
  uint32_t m_stop_id = 0;
310
  uint32_t m_last_natural_stop_id = 0;
311
  uint32_t m_resume_id = 0;
312
  uint32_t m_memory_id = 0;
313
  uint32_t m_last_user_expression_resume = 0;
314
  uint32_t m_running_user_expression = false;
315
  uint32_t m_running_utility_function = 0;
316
  lldb::EventSP m_last_natural_stop_event;
317
};
318
319
616k
inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
320
616k
  if (lhs.StopIDEqual(rhs) && 
lhs.MemoryIDEqual(rhs)569k
)
321
568k
    return true;
322
47.6k
  else
323
47.6k
    return false;
324
616k
}
325
326
0
inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
327
0
  return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
328
0
}
329
330
/// \class Process Process.h "lldb/Target/Process.h"
331
/// A plug-in interface definition class for debugging a process.
332
class Process : public std::enable_shared_from_this<Process>,
333
                public ProcessProperties,
334
                public Broadcaster,
335
                public ExecutionContextScope,
336
                public PluginInterface {
337
  friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
338
  friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
339
  friend class DynamicLoader; // For LoadOperatingSystemPlugin
340
  friend class ProcessEventData;
341
  friend class StopInfo;
342
  friend class Target;
343
  friend class ThreadList;
344
345
public:
346
  /// Broadcaster event bits definitions.
347
  enum {
348
    eBroadcastBitStateChanged = (1 << 0),
349
    eBroadcastBitInterrupt = (1 << 1),
350
    eBroadcastBitSTDOUT = (1 << 2),
351
    eBroadcastBitSTDERR = (1 << 3),
352
    eBroadcastBitProfileData = (1 << 4),
353
    eBroadcastBitStructuredData = (1 << 5),
354
  };
355
  // This is all the event bits the public process broadcaster broadcasts.
356
  // The process shadow listener signs up for all these bits...
357
  static constexpr int g_all_event_bits = eBroadcastBitStateChanged 
358
                                        | eBroadcastBitInterrupt
359
                                        | eBroadcastBitSTDOUT 
360
                                        | eBroadcastBitSTDERR
361
                                        | eBroadcastBitProfileData 
362
                                        | eBroadcastBitStructuredData;
363
364
  enum {
365
    eBroadcastInternalStateControlStop = (1 << 0),
366
    eBroadcastInternalStateControlPause = (1 << 1),
367
    eBroadcastInternalStateControlResume = (1 << 2)
368
  };
369
370
  typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
371
  // We use a read/write lock to allow on or more clients to access the process
372
  // state while the process is stopped (reader). We lock the write lock to
373
  // control access to the process while it is running (readers, or clients
374
  // that want the process stopped can block waiting for the process to stop,
375
  // or just try to lock it to see if they can immediately access the stopped
376
  // process. If the try read lock fails, then the process is running.
377
  typedef ProcessRunLock::ProcessRunLocker StopLocker;
378
379
  // These two functions fill out the Broadcaster interface:
380
381
  static ConstString &GetStaticBroadcasterClass();
382
383
  static constexpr llvm::StringRef AttachSynchronousHijackListenerName =
384
      "lldb.internal.Process.AttachSynchronous.hijack";
385
  static constexpr llvm::StringRef LaunchSynchronousHijackListenerName =
386
      "lldb.internal.Process.LaunchSynchronous.hijack";
387
  static constexpr llvm::StringRef ResumeSynchronousHijackListenerName =
388
      "lldb.internal.Process.ResumeSynchronous.hijack";
389
390
778
  ConstString &GetBroadcasterClass() const override {
391
778
    return GetStaticBroadcasterClass();
392
778
  }
393
  
394
/// A notification structure that can be used by clients to listen
395
/// for changes in a process's lifetime.
396
///
397
/// \see RegisterNotificationCallbacks (const Notifications&) @see
398
/// UnregisterNotificationCallbacks (const Notifications&)
399
  typedef struct {
400
    void *baton;
401
    void (*initialize)(void *baton, Process *process);
402
    void (*process_state_changed)(void *baton, Process *process,
403
                                  lldb::StateType state);
404
  } Notifications;
405
406
  class ProcessEventData : public EventData {
407
    friend class Process;
408
409
  public:
410
    ProcessEventData();
411
    ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
412
413
    ~ProcessEventData() override;
414
415
    static llvm::StringRef GetFlavorString();
416
417
    llvm::StringRef GetFlavor() const override;
418
419
9.86k
    lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
420
421
113k
    lldb::StateType GetState() const { return m_state; }
422
75.0k
    bool GetRestarted() const { return m_restarted; }
423
424
33
    size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
425
426
3
    const char *GetRestartedReasonAtIndex(size_t idx) {
427
3
      return ((idx < m_restarted_reasons.size())
428
3
                  ? m_restarted_reasons[idx].c_str()
429
3
                  : 
nullptr0
);
430
3
    }
431
432
28.1k
    bool GetInterrupted() const { return m_interrupted; }
433
434
    void Dump(Stream *s) const override;
435
436
    virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo);
437
438
    void DoOnRemoval(Event *event_ptr) override;
439
440
    static const Process::ProcessEventData *
441
    GetEventDataFromEvent(const Event *event_ptr);
442
443
    static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
444
445
    static lldb::StateType GetStateFromEvent(const Event *event_ptr);
446
447
    static bool GetRestartedFromEvent(const Event *event_ptr);
448
449
    static size_t GetNumRestartedReasons(const Event *event_ptr);
450
451
    static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
452
                                                 size_t idx);
453
454
    static void AddRestartedReason(Event *event_ptr, const char *reason);
455
456
    static void SetRestartedInEvent(Event *event_ptr, bool new_value);
457
458
    static bool GetInterruptedFromEvent(const Event *event_ptr);
459
460
    static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
461
462
    static bool SetUpdateStateOnRemoval(Event *event_ptr);
463
464
  private:
465
17.5k
    void SetUpdateStateOnRemoval() { m_update_state++; }
466
467
5.54k
    void SetRestarted(bool new_value) { m_restarted = new_value; }
468
469
34
    void SetInterrupted(bool new_value) { m_interrupted = new_value; }
470
471
6
    void AddRestartedReason(const char *reason) {
472
6
      m_restarted_reasons.push_back(reason);
473
6
    }
474
475
    lldb::ProcessWP m_process_wp;
476
    lldb::StateType m_state = lldb::eStateInvalid;
477
    std::vector<std::string> m_restarted_reasons;
478
    bool m_restarted = false; // For "eStateStopped" events, this is true if the
479
                              // target was automatically restarted.
480
    int m_update_state = 0;
481
    bool m_interrupted = false;
482
483
    ProcessEventData(const ProcessEventData &) = delete;
484
    const ProcessEventData &operator=(const ProcessEventData &) = delete;
485
  };
486
487
  /// Destructor.
488
  ///
489
  /// The destructor is virtual since this class is designed to be inherited
490
  /// from by the plug-in instance.
491
  ~Process() override;
492
493
  static void SettingsInitialize();
494
495
  static void SettingsTerminate();
496
497
  static ProcessProperties &GetGlobalProperties();
498
499
  /// Find a Process plug-in that can debug \a module using the currently
500
  /// selected architecture.
501
  ///
502
  /// Scans all loaded plug-in interfaces that implement versions of the
503
  /// Process plug-in interface and returns the first instance that can debug
504
  /// the file.
505
  ///
506
  /// \see Process::CanDebug ()
507
  static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
508
                                    llvm::StringRef plugin_name,
509
                                    lldb::ListenerSP listener_sp,
510
                                    const FileSpec *crash_file_path,
511
                                    bool can_connect);
512
513
  /// Static function that can be used with the \b host function
514
  /// Host::StartMonitoringChildProcess ().
515
  ///
516
  /// This function can be used by lldb_private::Process subclasses when they
517
  /// want to watch for a local process and have its exit status automatically
518
  /// set when the host child process exits. Subclasses should call
519
  /// Host::StartMonitoringChildProcess () with:
520
  ///     callback = Process::SetHostProcessExitStatus
521
  ///     pid = Process::GetID()
522
  ///     monitor_signals = false
523
  static bool
524
  SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
525
                       bool exited,
526
                       int signo,   // Zero for no signal
527
                       int status); // Exit value of process if signal is zero
528
529
  lldb::ByteOrder GetByteOrder() const;
530
531
  uint32_t GetAddressByteSize() const;
532
533
  /// Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is
534
  /// no known pid.
535
17.5k
  lldb::pid_t GetID() const { return m_pid; }
536
537
  /// Sets the stored pid.
538
  ///
539
  /// This does not change the pid of underlying process.
540
2.39k
  void SetID(lldb::pid_t new_pid) { m_pid = new_pid; }
541
542
0
  uint32_t GetUniqueID() const { return m_process_unique_id; }
543
544
  /// Check if a plug-in instance can debug the file in \a module.
545
  ///
546
  /// Each plug-in is given a chance to say whether it can debug the file in
547
  /// \a module. If the Process plug-in instance can debug a file on the
548
  /// current system, it should return \b true.
549
  ///
550
  /// \return
551
  ///     Returns \b true if this Process plug-in instance can
552
  ///     debug the executable, \b false otherwise.
553
  virtual bool CanDebug(lldb::TargetSP target,
554
                        bool plugin_specified_by_name) = 0;
555
556
  /// This object is about to be destroyed, do any necessary cleanup.
557
  ///
558
  /// Subclasses that override this method should always call this superclass
559
  /// method.
560
  virtual void Finalize();
561
562
  /// Return whether this object is valid (i.e. has not been finalized.)
563
  ///
564
  /// \return
565
  ///     Returns \b true if this Process has not been finalized
566
  ///     and \b false otherwise.
567
1.80M
  bool IsValid() const { return !m_finalizing; }
568
569
  /// Return a multi-word command object that can be used to expose plug-in
570
  /// specific commands.
571
  ///
572
  /// This object will be used to resolve plug-in commands and can be
573
  /// triggered by a call to:
574
  ///
575
  ///     (lldb) process command <args>
576
  ///
577
  /// \return
578
  ///     A CommandObject which can be one of the concrete subclasses
579
  ///     of CommandObject like CommandObjectRaw, CommandObjectParsed,
580
  ///     or CommandObjectMultiword.
581
0
  virtual CommandObject *GetPluginCommandObject() { return nullptr; }
582
  
583
  /// The underlying plugin might store the low-level communication history for
584
  /// this session.  Dump it into the provided stream.
585
0
  virtual void DumpPluginHistory(Stream &s) { return; }
586
587
  /// Launch a new process.
588
  ///
589
  /// Launch a new process by spawning a new process using the target object's
590
  /// executable module's file as the file to launch.
591
  ///
592
  /// This function is not meant to be overridden by Process subclasses. It
593
  /// will first call Process::WillLaunch (Module *) and if that returns \b
594
  /// true, Process::DoLaunch (Module*, char const *[],char const *[],const
595
  /// char *,const char *, const char *) will be called to actually do the
596
  /// launching. If DoLaunch returns \b true, then Process::DidLaunch() will
597
  /// be called.
598
  ///
599
  /// \param[in] launch_info
600
  ///     Details regarding the environment, STDIN/STDOUT/STDERR
601
  ///     redirection, working path, etc. related to the requested launch.
602
  ///
603
  /// \return
604
  ///     An error object. Call GetID() to get the process ID if
605
  ///     the error object is success.
606
  virtual Status Launch(ProcessLaunchInfo &launch_info);
607
608
  virtual Status LoadCore();
609
610
0
  virtual Status DoLoadCore() {
611
0
    Status error;
612
0
    error.SetErrorStringWithFormatv(
613
0
        "error: {0} does not support loading core files.", GetPluginName());
614
0
    return error;
615
0
  }
616
617
  /// The "ShadowListener" for a process is just an ordinary Listener that 
618
  /// listens for all the Process event bits.  It's convenient because you can
619
  /// specify it in the LaunchInfo or AttachInfo, so it will get events from
620
  /// the very start of the process.
621
2.12k
  void SetShadowListener(lldb::ListenerSP shadow_listener_sp) {
622
2.12k
    if (shadow_listener_sp)
623
1
      AddListener(shadow_listener_sp, g_all_event_bits);
624
2.12k
  }
625
626
  // FUTURE WORK: GetLoadImageUtilityFunction are the first use we've
627
  // had of having other plugins cache data in the Process.  This is handy for
628
  // long-living plugins - like the Platform - which manage interactions whose
629
  // lifetime is governed by the Process lifetime.  If we find we need to do
630
  // this more often, we should construct a general solution to the problem.
631
  // The consensus suggestion was that we have a token based registry in the
632
  // Process. Some undecided questions are  (1) who manages the tokens.  It's
633
  // probably best that you add the element  and get back a token that
634
  // represents it.  That will avoid collisions.  But there may be some utility
635
  // in the registerer controlling the token? (2) whether the thing added
636
  // should be simply owned by Process, and just go away when it does (3)
637
  // whether the registree should be notified of the Process' demise.
638
  //
639
  // We are postponing designing this till we have at least a second use case.
640
  /// Get the cached UtilityFunction that assists in loading binary images
641
  /// into the process.
642
  ///
643
  /// \param[in] platform
644
  ///     The platform fetching the UtilityFunction.
645
  /// \param[in] factory
646
  ///     A function that will be called only once per-process in a
647
  ///     thread-safe way to create the UtilityFunction if it has not
648
  ///     been initialized yet.
649
  ///
650
  /// \return
651
  ///     The cached utility function or null if the platform is not the
652
  ///     same as the target's platform.
653
  UtilityFunction *GetLoadImageUtilityFunction(
654
      Platform *platform,
655
      llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory);
656
657
  /// Get the dynamic loader plug-in for this process.
658
  ///
659
  /// The default action is to let the DynamicLoader plug-ins check the main
660
  /// executable and the DynamicLoader will select itself automatically.
661
  /// Subclasses can override this if inspecting the executable is not
662
  /// desired, or if Process subclasses can only use a specific DynamicLoader
663
  /// plug-in.
664
  virtual DynamicLoader *GetDynamicLoader();
665
666
  void SetDynamicLoader(lldb::DynamicLoaderUP dyld);
667
668
  // Returns AUXV structure found in many ELF-based environments.
669
  //
670
  // The default action is to return an empty data buffer.
671
  //
672
  // \return
673
  //    A data extractor containing the contents of the AUXV data.
674
  virtual DataExtractor GetAuxvData();
675
676
  /// Sometimes processes know how to retrieve and load shared libraries. This
677
  /// is normally done by DynamicLoader plug-ins, but sometimes the connection
678
  /// to the process allows retrieving this information. The dynamic loader
679
  /// plug-ins can use this function if they can't determine the current
680
  /// shared library load state.
681
  ///
682
  /// \return
683
  ///    A status object indicating if the operation was sucessful or not.
684
0
  virtual llvm::Error LoadModules() {
685
0
    return llvm::make_error<llvm::StringError>("Not implemented.",
686
0
                                               llvm::inconvertibleErrorCode());
687
0
  }
688
689
  /// Query remote GDBServer for a detailed loaded library list
690
  /// \return
691
  ///    The list of modules currently loaded by the process, or an error.
692
6
  virtual llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() {
693
6
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
694
6
                                   "Not implemented");
695
6
  }
696
697
  /// Save core dump into the specified file.
698
  ///
699
  /// \param[in] outfile
700
  ///     Path to store core dump in.
701
  ///
702
  /// \return
703
  ///     true if saved successfully, false if saving the core dump
704
  ///     is not supported by the plugin, error otherwise.
705
  virtual llvm::Expected<bool> SaveCore(llvm::StringRef outfile);
706
707
protected:
708
  virtual JITLoaderList &GetJITLoaders();
709
710
public:
711
  /// Get the system architecture for this process.
712
323
  virtual ArchSpec GetSystemArchitecture() { return {}; }
713
714
  /// Get the system runtime plug-in for this process.
715
  ///
716
  /// \return
717
  ///   Returns a pointer to the SystemRuntime plugin for this Process
718
  ///   if one is available.  Else returns nullptr.
719
  virtual SystemRuntime *GetSystemRuntime();
720
721
  /// Attach to an existing process using the process attach info.
722
  ///
723
  /// This function is not meant to be overridden by Process subclasses. It
724
  /// will first call WillAttach (lldb::pid_t) or WillAttach (const char *),
725
  /// and if that returns \b true, DoAttach (lldb::pid_t) or DoAttach (const
726
  /// char *) will be called to actually do the attach. If DoAttach returns \b
727
  /// true, then Process::DidAttach() will be called.
728
  ///
729
  /// \param[in] attach_info
730
  ///     The process attach info.
731
  ///
732
  /// \return
733
  ///     Returns \a pid if attaching was successful, or
734
  ///     LLDB_INVALID_PROCESS_ID if attaching fails.
735
  virtual Status Attach(ProcessAttachInfo &attach_info);
736
737
  /// Attach to a remote system via a URL
738
  ///
739
  /// \param[in] remote_url
740
  ///     The URL format that we are connecting to.
741
  ///
742
  /// \return
743
  ///     Returns an error object.
744
  virtual Status ConnectRemote(llvm::StringRef remote_url);
745
746
5.01k
  bool GetShouldDetach() const { return m_should_detach; }
747
748
2.08k
  void SetShouldDetach(bool b) { m_should_detach = b; }
749
750
  /// Get the image vector for the current process.
751
  ///
752
  /// \return
753
  ///     The constant reference to the member m_image_tokens.
754
0
  const std::vector<lldb::addr_t>& GetImageTokens() { return m_image_tokens; }
755
756
  /// Get the image information address for the current process.
757
  ///
758
  /// Some runtimes have system functions that can help dynamic loaders locate
759
  /// the dynamic loader information needed to observe shared libraries being
760
  /// loaded or unloaded. This function is in the Process interface (as
761
  /// opposed to the DynamicLoader interface) to ensure that remote debugging
762
  /// can take advantage of this functionality.
763
  ///
764
  /// \return
765
  ///     The address of the dynamic loader information, or
766
  ///     LLDB_INVALID_ADDRESS if this is not supported by this
767
  ///     interface.
768
  virtual lldb::addr_t GetImageInfoAddress();
769
770
  /// Called when the process is about to broadcast a public stop.
771
  ///
772
  /// There are public and private stops. Private stops are when the process
773
  /// is doing things like stepping and the client doesn't need to know about
774
  /// starts and stop that implement a thread plan. Single stepping over a
775
  /// source line in code might end up being implemented by one or more
776
  /// process starts and stops. Public stops are when clients will be notified
777
  /// that the process is stopped. These events typically trigger UI updates
778
  /// (thread stack frames to be displayed, variables to be displayed, and
779
  /// more). This function can be overriden and allows process subclasses to
780
  /// do something before the eBroadcastBitStateChanged event is sent to
781
  /// public clients.
782
186
  virtual void WillPublicStop() {}
783
784
/// Register for process and thread notifications.
785
///
786
/// Clients can register notification callbacks by filling out a
787
/// Process::Notifications structure and calling this function.
788
///
789
/// \param[in] callbacks
790
///     A structure that contains the notification baton and
791
///     callback functions.
792
///
793
/// \see Process::Notifications
794
  void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
795
796
/// Unregister for process and thread notifications.
797
///
798
/// Clients can unregister notification callbacks by passing a copy of the
799
/// original baton and callbacks in \a callbacks.
800
///
801
/// \param[in] callbacks
802
///     A structure that contains the notification baton and
803
///     callback functions.
804
///
805
/// \return
806
///     Returns \b true if the notification callbacks were
807
///     successfully removed from the process, \b false otherwise.
808
///
809
/// \see Process::Notifications
810
  bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
811
812
  //==================================================================
813
  // Built in Process Control functions
814
  //==================================================================
815
  /// Resumes all of a process's threads as configured using the Thread run
816
  /// control functions.
817
  ///
818
  /// Threads for a process should be updated with one of the run control
819
  /// actions (resume, step, or suspend) that they should take when the
820
  /// process is resumed. If no run control action is given to a thread it
821
  /// will be resumed by default.
822
  ///
823
  /// This function is not meant to be overridden by Process subclasses. This
824
  /// function will take care of disabling any breakpoints that threads may be
825
  /// stopped at, single stepping, and re-enabling breakpoints, and enabling
826
  /// the basic flow control that the plug-in instances need not worry about.
827
  ///
828
  /// N.B. This function also sets the Write side of the Run Lock, which is
829
  /// unset when the corresponding stop event is pulled off the Public Event
830
  /// Queue.  If you need to resume the process without setting the Run Lock,
831
  /// use PrivateResume (though you should only do that from inside the
832
  /// Process class.
833
  ///
834
  /// \return
835
  ///     Returns an error object.
836
  ///
837
  /// \see Thread:Resume()
838
  /// \see Thread:Step()
839
  /// \see Thread:Suspend()
840
  Status Resume();
841
842
  /// Resume a process, and wait for it to stop.
843
  Status ResumeSynchronous(Stream *stream);
844
845
  /// Halts a running process.
846
  ///
847
  /// This function is not meant to be overridden by Process subclasses. If
848
  /// the process is successfully halted, a eStateStopped process event with
849
  /// GetInterrupted will be broadcast.  If false, we will halt the process
850
  /// with no events generated by the halt.
851
  ///
852
  /// \param[in] clear_thread_plans
853
  ///     If true, when the process stops, clear all thread plans.
854
  ///
855
  /// \param[in] use_run_lock
856
  ///     Whether to release the run lock after the stop.
857
  ///
858
  /// \return
859
  ///     Returns an error object.  If the error is empty, the process is
860
  ///     halted.
861
  ///     otherwise the halt has failed.
862
  Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
863
864
  /// Detaches from a running or stopped process.
865
  ///
866
  /// This function is not meant to be overridden by Process subclasses.
867
  ///
868
  /// \param[in] keep_stopped
869
  ///     If true, don't resume the process on detach.
870
  ///
871
  /// \return
872
  ///     Returns an error object.
873
  Status Detach(bool keep_stopped);
874
875
  /// Kills the process and shuts down all threads that were spawned to track
876
  /// and monitor the process.
877
  ///
878
  /// This function is not meant to be overridden by Process subclasses.
879
  ///
880
  /// \param[in] force_kill
881
  ///     Whether lldb should force a kill (instead of a detach) from
882
  ///     the inferior process.  Normally if lldb launched a binary and
883
  ///     Destory is called, lldb kills it.  If lldb attached to a
884
  ///     running process and Destory is called, lldb detaches.  If
885
  ///     this behavior needs to be over-ridden, this is the bool that
886
  ///     can be used.
887
  ///
888
  /// \return
889
  ///     Returns an error object.
890
  Status Destroy(bool force_kill);
891
892
  /// Sends a process a UNIX signal \a signal.
893
  ///
894
  /// This function is not meant to be overridden by Process subclasses.
895
  ///
896
  /// \return
897
  ///     Returns an error object.
898
  Status Signal(int signal);
899
900
  void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
901
902
  const lldb::UnixSignalsSP &GetUnixSignals();
903
904
  //==================================================================
905
  // Plug-in Process Control Overrides
906
  //==================================================================
907
908
  /// Called before attaching to a process.
909
  ///
910
  /// \return
911
  ///     Returns an error object.
912
  Status WillAttachToProcessWithID(lldb::pid_t pid);
913
914
  /// Called before attaching to a process.
915
  ///
916
  /// Allow Process plug-ins to execute some code before attaching a process.
917
  ///
918
  /// \return
919
  ///     Returns an error object.
920
1
  virtual Status DoWillAttachToProcessWithID(lldb::pid_t pid) {
921
1
    return Status();
922
1
  }
923
924
  /// Called before attaching to a process.
925
  ///
926
  /// \return
927
  ///     Returns an error object.
928
  Status WillAttachToProcessWithName(const char *process_name,
929
                                     bool wait_for_launch);
930
931
  /// Called before attaching to a process.
932
  ///
933
  /// Allow Process plug-ins to execute some code before attaching a process.
934
  ///
935
  /// \return
936
  ///     Returns an error object.
937
  virtual Status DoWillAttachToProcessWithName(const char *process_name,
938
0
                                               bool wait_for_launch) {
939
0
    return Status();
940
0
  }
941
942
  /// Attach to a remote system via a URL
943
  ///
944
  /// \param[in] remote_url
945
  ///     The URL format that we are connecting to.
946
  ///
947
  /// \return
948
  ///     Returns an error object.
949
0
  virtual Status DoConnectRemote(llvm::StringRef remote_url) {
950
0
    Status error;
951
0
    error.SetErrorString("remote connections are not supported");
952
0
    return error;
953
0
  }
954
955
  /// Attach to an existing process using a process ID.
956
  ///
957
  /// \param[in] pid
958
  ///     The process ID that we should attempt to attach to.
959
  ///
960
  /// \param[in] attach_info
961
  ///     Information on how to do the attach. For example, GetUserID()
962
  ///     will return the uid to attach as.
963
  ///
964
  /// \return
965
  ///     Returns a successful Status attaching was successful, or
966
  ///     an appropriate (possibly platform-specific) error code if
967
  ///     attaching fails.
968
  /// hanming : need flag
969
  virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
970
0
                                         const ProcessAttachInfo &attach_info) {
971
0
    Status error;
972
0
    error.SetErrorStringWithFormatv(
973
0
        "error: {0} does not support attaching to a process by pid",
974
0
        GetPluginName());
975
0
    return error;
976
0
  }
977
978
  /// Attach to an existing process using a partial process name.
979
  ///
980
  /// \param[in] process_name
981
  ///     The name of the process to attach to.
982
  ///
983
  /// \param[in] attach_info
984
  ///     Information on how to do the attach. For example, GetUserID()
985
  ///     will return the uid to attach as.
986
  ///
987
  /// \return
988
  ///     Returns a successful Status attaching was successful, or
989
  ///     an appropriate (possibly platform-specific) error code if
990
  ///     attaching fails.
991
  virtual Status
992
  DoAttachToProcessWithName(const char *process_name,
993
0
                            const ProcessAttachInfo &attach_info) {
994
0
    Status error;
995
0
    error.SetErrorString("attach by name is not supported");
996
0
    return error;
997
0
  }
998
999
  /// Called after attaching a process.
1000
  ///
1001
  /// \param[in] process_arch
1002
  ///     If you can figure out the process architecture after attach, fill it
1003
  ///     in here.
1004
  ///
1005
  /// Allow Process plug-ins to execute some code after attaching to a
1006
  /// process.
1007
0
  virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1008
1009
  /// Called after a process re-execs itself.
1010
  ///
1011
  /// Allow Process plug-ins to execute some code after a process has exec'ed
1012
  /// itself. Subclasses typically should override DoDidExec() as the
1013
  /// lldb_private::Process class needs to remove its dynamic loader, runtime,
1014
  /// ABI and other plug-ins, as well as unload all shared libraries.
1015
  virtual void DidExec();
1016
1017
  /// Subclasses of Process should implement this function if they need to do
1018
  /// anything after a process exec's itself.
1019
2
  virtual void DoDidExec() {}
1020
1021
  /// Called after a reported fork.
1022
0
  virtual void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {}
1023
1024
  /// Called after a reported vfork.
1025
0
  virtual void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {}
1026
1027
  /// Called after reported vfork completion.
1028
0
  virtual void DidVForkDone() {}
1029
1030
  /// Called before launching to a process.
1031
  /// \return
1032
  ///     Returns an error object.
1033
  Status WillLaunch(Module *module);
1034
1035
  /// Called before launching to a process.
1036
  ///
1037
  /// Allow Process plug-ins to execute some code before launching a process.
1038
  ///
1039
  /// \return
1040
  ///     Returns an error object.
1041
2
  virtual Status DoWillLaunch(Module *module) { return Status(); }
1042
1043
  /// Launch a new process.
1044
  ///
1045
  /// Launch a new process by spawning a new process using \a exe_module's
1046
  /// file as the file to launch. Launch details are provided in \a
1047
  /// launch_info.
1048
  ///
1049
  /// \param[in] exe_module
1050
  ///     The module from which to extract the file specification and
1051
  ///     launch.
1052
  ///
1053
  /// \param[in] launch_info
1054
  ///     Details (e.g. arguments, stdio redirection, etc.) for the
1055
  ///     requested launch.
1056
  ///
1057
  /// \return
1058
  ///     An Status instance indicating success or failure of the
1059
  ///     operation.
1060
0
  virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1061
0
    Status error;
1062
0
    error.SetErrorStringWithFormatv(
1063
0
        "error: {0} does not support launching processes", GetPluginName());
1064
0
    return error;
1065
0
  }
1066
1067
  /// Called after launching a process.
1068
  ///
1069
  /// Allow Process plug-ins to execute some code after launching a process.
1070
0
  virtual void DidLaunch() {}
1071
1072
  /// Called before resuming to a process.
1073
  ///
1074
  /// Allow Process plug-ins to execute some code before resuming a process.
1075
  ///
1076
  /// \return
1077
  ///     Returns an error object.
1078
2
  virtual Status WillResume() { return Status(); }
1079
1080
  /// Resumes all of a process's threads as configured using the Thread run
1081
  /// control functions.
1082
  ///
1083
  /// Threads for a process should be updated with one of the run control
1084
  /// actions (resume, step, or suspend) that they should take when the
1085
  /// process is resumed. If no run control action is given to a thread it
1086
  /// will be resumed by default.
1087
  ///
1088
  /// \return
1089
  ///     Returns \b true if the process successfully resumes using
1090
  ///     the thread run control actions, \b false otherwise.
1091
  ///
1092
  /// \see Thread:Resume()
1093
  /// \see Thread:Step()
1094
  /// \see Thread:Suspend()
1095
0
  virtual Status DoResume() {
1096
0
    Status error;
1097
0
    error.SetErrorStringWithFormatv(
1098
0
        "error: {0} does not support resuming processes", GetPluginName());
1099
0
    return error;
1100
0
  }
1101
1102
  /// Called after resuming a process.
1103
  ///
1104
  /// Allow Process plug-ins to execute some code after resuming a process.
1105
12.1k
  virtual void DidResume() {}
1106
1107
  /// Called before halting to a process.
1108
  ///
1109
  /// Allow Process plug-ins to execute some code before halting a process.
1110
  ///
1111
  /// \return
1112
  ///     Returns an error object.
1113
35
  virtual Status WillHalt() { return Status(); }
1114
1115
  /// Halts a running process.
1116
  ///
1117
  /// DoHalt must produce one and only one stop StateChanged event if it
1118
  /// actually stops the process.  If the stop happens through some natural
1119
  /// event (for instance a SIGSTOP), then forwarding that event will do.
1120
  /// Otherwise, you must generate the event manually. This function is called
1121
  /// from the context of the private state thread.
1122
  ///
1123
  /// \param[out] caused_stop
1124
  ///     If true, then this Halt caused the stop, otherwise, the
1125
  ///     process was already stopped.
1126
  ///
1127
  /// \return
1128
  ///     Returns \b true if the process successfully halts, \b false
1129
  ///     otherwise.
1130
0
  virtual Status DoHalt(bool &caused_stop) {
1131
0
    Status error;
1132
0
    error.SetErrorStringWithFormatv(
1133
0
        "error: {0} does not support halting processes", GetPluginName());
1134
0
    return error;
1135
0
  }
1136
1137
  /// Called after halting a process.
1138
  ///
1139
  /// Allow Process plug-ins to execute some code after halting a process.
1140
35
  virtual void DidHalt() {}
1141
1142
  /// Called before detaching from a process.
1143
  ///
1144
  /// Allow Process plug-ins to execute some code before detaching from a
1145
  /// process.
1146
  ///
1147
  /// \return
1148
  ///     Returns an error object.
1149
19
  virtual Status WillDetach() { return Status(); }
1150
1151
  /// Detaches from a running or stopped process.
1152
  ///
1153
  /// \return
1154
  ///     Returns \b true if the process successfully detaches, \b
1155
  ///     false otherwise.
1156
0
  virtual Status DoDetach(bool keep_stopped) {
1157
0
    Status error;
1158
0
    error.SetErrorStringWithFormatv(
1159
0
        "error: {0} does not support detaching from processes",
1160
0
        GetPluginName());
1161
0
    return error;
1162
0
  }
1163
1164
  /// Called after detaching from a process.
1165
  ///
1166
  /// Allow Process plug-ins to execute some code after detaching from a
1167
  /// process.
1168
15
  virtual void DidDetach() {}
1169
1170
0
  virtual bool DetachRequiresHalt() { return false; }
1171
1172
  /// Called before sending a signal to a process.
1173
  ///
1174
  /// Allow Process plug-ins to execute some code before sending a signal to a
1175
  /// process.
1176
  ///
1177
  /// \return
1178
  ///     Returns no error if it is safe to proceed with a call to
1179
  ///     Process::DoSignal(int), otherwise an error describing what
1180
  ///     prevents the signal from being sent.
1181
2
  virtual Status WillSignal() { return Status(); }
1182
1183
  /// Sends a process a UNIX signal \a signal.
1184
  ///
1185
  /// \return
1186
  ///     Returns an error object.
1187
0
  virtual Status DoSignal(int signal) {
1188
0
    Status error;
1189
0
    error.SetErrorStringWithFormatv(
1190
0
        "error: {0} does not support sending signals to processes",
1191
0
        GetPluginName());
1192
0
    return error;
1193
0
  }
1194
1195
5.00k
  virtual Status WillDestroy() { return Status(); }
1196
1197
  virtual Status DoDestroy() = 0;
1198
1199
5.00k
  virtual void DidDestroy() {}
1200
1201
5.00k
  virtual bool DestroyRequiresHalt() { return true; }
1202
1203
  /// Called after sending a signal to a process.
1204
  ///
1205
  /// Allow Process plug-ins to execute some code after sending a signal to a
1206
  /// process.
1207
2
  virtual void DidSignal() {}
1208
1209
  /// Currently called as part of ShouldStop.
1210
  /// FIXME: Should really happen when the target stops before the
1211
  /// event is taken from the queue...
1212
  ///
1213
  /// This callback is called as the event
1214
  /// is about to be queued up to allow Process plug-ins to execute some code
1215
  /// prior to clients being notified that a process was stopped. Common
1216
  /// operations include updating the thread list, invalidating any thread
1217
  /// state (registers, stack, etc) prior to letting the notification go out.
1218
  ///
1219
  virtual void RefreshStateAfterStop() = 0;
1220
1221
  /// Sometimes the connection to a process can detect the host OS version
1222
  /// that the process is running on. The current platform should be checked
1223
  /// first in case the platform is connected, but clients can fall back onto
1224
  /// this function if the platform fails to identify the host OS version. The
1225
  /// platform should be checked first in case you are running a simulator
1226
  /// platform that might itself be running natively, but have different
1227
  /// heuristics for figuring out which OS is emulating.
1228
  ///
1229
  /// \return
1230
  ///     Returns the version tuple of the host OS. In case of failure an empty
1231
  ///     VersionTuple is returner.
1232
6
  virtual llvm::VersionTuple GetHostOSVersion() { return llvm::VersionTuple(); }
1233
1234
  /// \return the macCatalyst version of the host OS.
1235
0
  virtual llvm::VersionTuple GetHostMacCatalystVersion() { return {}; }
1236
1237
  /// Get the target object pointer for this module.
1238
  ///
1239
  /// \return
1240
  ///     A Target object pointer to the target that owns this
1241
  ///     module.
1242
5.82M
  Target &GetTarget() { return *m_target_wp.lock(); }
1243
1244
  /// Get the const target object pointer for this module.
1245
  ///
1246
  /// \return
1247
  ///     A const Target object pointer to the target that owns this
1248
  ///     module.
1249
1.57M
  const Target &GetTarget() const { return *m_target_wp.lock(); }
1250
1251
  /// Flush all data in the process.
1252
  ///
1253
  /// Flush the memory caches, all threads, and any other cached data in the
1254
  /// process.
1255
  ///
1256
  /// This function can be called after a world changing event like adding a
1257
  /// new symbol file, or after the process makes a large context switch (from
1258
  /// boot ROM to booted into an OS).
1259
  void Flush();
1260
1261
  /// Get accessor for the current process state.
1262
  ///
1263
  /// \return
1264
  ///     The current state of the process.
1265
  ///
1266
  /// \see lldb::StateType
1267
  lldb::StateType GetState();
1268
1269
  lldb::ExpressionResults
1270
  RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1271
                const EvaluateExpressionOptions &options,
1272
                DiagnosticManager &diagnostic_manager);
1273
1274
  static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1275
1276
  void GetStatus(Stream &ostrm);
1277
1278
  size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1279
                         uint32_t start_frame, uint32_t num_frames,
1280
                         uint32_t num_frames_with_source,
1281
                         bool stop_format);
1282
1283
  void SendAsyncInterrupt();
1284
1285
  // Notify this process class that modules got loaded.
1286
  //
1287
  // If subclasses override this method, they must call this version before
1288
  // doing anything in the subclass version of the function.
1289
  virtual void ModulesDidLoad(ModuleList &module_list);
1290
1291
  /// Retrieve the list of shared libraries that are loaded for this process
1292
  /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10, pre-
1293
  /// watchOS 3 systems.  The following two methods are for newer versions of
1294
  /// those OSes.
1295
  ///
1296
  /// For certain platforms, the time it takes for the DynamicLoader plugin to
1297
  /// read all of the shared libraries out of memory over a slow communication
1298
  /// channel may be too long.  In that instance, the gdb-remote stub may be
1299
  /// able to retrieve the necessary information about the solibs out of
1300
  /// memory and return a concise summary sufficient for the DynamicLoader
1301
  /// plugin.
1302
  ///
1303
  /// \param [in] image_list_address
1304
  ///     The address where the table of shared libraries is stored in memory,
1305
  ///     if that is appropriate for this platform.  Else this may be
1306
  ///     passed as LLDB_INVALID_ADDRESS.
1307
  ///
1308
  /// \param [in] image_count
1309
  ///     The number of shared libraries that are present in this process, if
1310
  ///     that is appropriate for this platofrm  Else this may be passed as
1311
  ///     LLDB_INVALID_ADDRESS.
1312
  ///
1313
  /// \return
1314
  ///     A StructuredDataSP object which, if non-empty, will contain the
1315
  ///     information the DynamicLoader needs to get the initial scan of
1316
  ///     solibs resolved.
1317
  virtual lldb_private::StructuredData::ObjectSP
1318
  GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1319
0
                                 lldb::addr_t image_count) {
1320
0
    return StructuredData::ObjectSP();
1321
0
  }
1322
1323
  // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1324
  // return the full list of loaded shared libraries without needing any input.
1325
  virtual lldb_private::StructuredData::ObjectSP
1326
0
  GetLoadedDynamicLibrariesInfos() {
1327
0
    return StructuredData::ObjectSP();
1328
0
  }
1329
1330
  // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1331
  // return information about binaries given their load addresses.
1332
  virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1333
0
      const std::vector<lldb::addr_t> &load_addresses) {
1334
0
    return StructuredData::ObjectSP();
1335
0
  }
1336
1337
  // Get information about the library shared cache, if that exists
1338
  //
1339
  // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1340
  // return information about the library shared cache (a set of standard
1341
  // libraries that are loaded at the same location for all processes on a
1342
  // system) in use.
1343
0
  virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1344
0
    return StructuredData::ObjectSP();
1345
0
  }
1346
1347
  // Get information about the launch state of the process, if possible.
1348
  //
1349
  // On Darwin systems, libdyld can report on process state, most importantly
1350
  // the startup stages where the system library is not yet initialized.
1351
  virtual lldb_private::StructuredData::ObjectSP
1352
0
  GetDynamicLoaderProcessState() {
1353
0
    return {};
1354
0
  }
1355
1356
  /// Print a user-visible warning about a module being built with
1357
  /// optimization
1358
  ///
1359
  /// Prints a async warning message to the user one time per Module where a
1360
  /// function is found that was compiled with optimization, per Process.
1361
  ///
1362
  /// \param [in] sc
1363
  ///     A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1364
  ///     pre-computed.
1365
  void PrintWarningOptimization(const SymbolContext &sc);
1366
1367
  /// Print a user-visible warning about a function written in a
1368
  /// language that this version of LLDB doesn't support.
1369
  ///
1370
  /// \see PrintWarningOptimization
1371
  void PrintWarningUnsupportedLanguage(const SymbolContext &sc);
1372
1373
  virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1374
1375
  /// Get the exit status for a process.
1376
  ///
1377
  /// \return
1378
  ///     The process's return code, or -1 if the current process
1379
  ///     state is not eStateExited.
1380
  int GetExitStatus();
1381
1382
  /// Get a textual description of what the process exited.
1383
  ///
1384
  /// \return
1385
  ///     The textual description of why the process exited, or nullptr
1386
  ///     if there is no description available.
1387
  const char *GetExitDescription();
1388
1389
0
  virtual void DidExit() {}
1390
1391
  lldb::addr_t GetCodeAddressMask();
1392
  lldb::addr_t GetDataAddressMask();
1393
1394
  lldb::addr_t GetHighmemCodeAddressMask();
1395
  lldb::addr_t GetHighmemDataAddressMask();
1396
1397
  void SetCodeAddressMask(lldb::addr_t code_address_mask);
1398
  void SetDataAddressMask(lldb::addr_t data_address_mask);
1399
1400
  void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask);
1401
  void SetHighmemDataAddressMask(lldb::addr_t data_address_mask);
1402
1403
  /// Some targets might use bits in a code address to indicate a mode switch,
1404
  /// ARM uses bit zero to signify a code address is thumb, so any ARM ABI
1405
  /// plug-ins would strip those bits.
1406
  /// Or use the high bits to authenticate a pointer value.
1407
  lldb::addr_t FixCodeAddress(lldb::addr_t pc);
1408
  lldb::addr_t FixDataAddress(lldb::addr_t pc);
1409
1410
  /// Use this method when you do not know, or do not care what kind of address
1411
  /// you are fixing. On platforms where there would be a difference between the
1412
  /// two types, it will pick the safest option.
1413
  ///
1414
  /// Its purpose is to signal that no specific choice was made and provide an
1415
  /// alternative to randomly picking FixCode/FixData address. Which could break
1416
  /// platforms where there is a difference (only Arm Thumb at this time).
1417
  lldb::addr_t FixAnyAddress(lldb::addr_t pc);
1418
1419
  /// Get the Modification ID of the process.
1420
  ///
1421
  /// \return
1422
  ///     The modification ID of the process.
1423
764k
  ProcessModID GetModID() const { return m_mod_id; }
1424
1425
2.64k
  const ProcessModID &GetModIDRef() const { return m_mod_id; }
1426
1427
2.56M
  uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1428
1429
59.0k
  uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1430
1431
11.1k
  uint32_t GetLastUserExpressionResumeID() const {
1432
11.1k
    return m_mod_id.GetLastUserExpressionResumeID();
1433
11.1k
  }
1434
1435
35.9k
  uint32_t GetLastNaturalStopID() const {
1436
35.9k
    return m_mod_id.GetLastNaturalStopID();
1437
35.9k
  }
1438
1439
0
  lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1440
0
    return m_mod_id.GetStopEventForStopID(stop_id);
1441
0
  }
1442
1443
  /// Set accessor for the process exit status (return code).
1444
  ///
1445
  /// Sometimes a child exits and the exit can be detected by global functions
1446
  /// (signal handler for SIGCHLD for example). This accessor allows the exit
1447
  /// status to be set from an external source.
1448
  ///
1449
  /// Setting this will cause a eStateExited event to be posted to the process
1450
  /// event queue.
1451
  ///
1452
  /// \param[in] exit_status
1453
  ///     The value for the process's return code.
1454
  ///
1455
  /// \param[in] exit_string
1456
  ///     A StringRef containing the reason for exiting. May be empty.
1457
  ///
1458
  /// \return
1459
  ///     Returns \b false if the process was already in an exited state, \b
1460
  ///     true otherwise.
1461
  virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string);
1462
1463
  /// Check if a process is still alive.
1464
  ///
1465
  /// \return
1466
  ///     Returns \b true if the process is still valid, \b false
1467
  ///     otherwise.
1468
  virtual bool IsAlive();
1469
1470
14
  virtual bool IsLiveDebugSession() const { return true; };
1471
1472
  /// Before lldb detaches from a process, it warns the user that they are
1473
  /// about to lose their debug session. In some cases, this warning doesn't
1474
  /// need to be emitted -- for instance, with core file debugging where the
1475
  /// user can reconstruct the "state" by simply re-running the debugger on
1476
  /// the core file.
1477
  ///
1478
  /// \return
1479
  ///     Returns \b true if the user should be warned about detaching from
1480
  ///     this process.
1481
12
  virtual bool WarnBeforeDetach() const { return true; }
1482
1483
  /// Read of memory from a process.
1484
  ///
1485
  /// This function will read memory from the current process's address space
1486
  /// and remove any traps that may have been inserted into the memory.
1487
  ///
1488
  /// This function is not meant to be overridden by Process subclasses, the
1489
  /// subclasses should implement Process::DoReadMemory (lldb::addr_t, size_t,
1490
  /// void *).
1491
  ///
1492
  /// \param[in] vm_addr
1493
  ///     A virtual load address that indicates where to start reading
1494
  ///     memory from.
1495
  ///
1496
  /// \param[out] buf
1497
  ///     A byte buffer that is at least \a size bytes long that
1498
  ///     will receive the memory bytes.
1499
  ///
1500
  /// \param[in] size
1501
  ///     The number of bytes to read.
1502
  ///
1503
  /// \param[out] error
1504
  ///     An error that indicates the success or failure of this
1505
  ///     operation. If error indicates success (error.Success()),
1506
  ///     then the value returned can be trusted, otherwise zero
1507
  ///     will be returned.
1508
  ///
1509
  /// \return
1510
  ///     The number of bytes that were actually read into \a buf. If
1511
  ///     the returned number is greater than zero, yet less than \a
1512
  ///     size, then this function will get called again with \a
1513
  ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
1514
  ///     returned in the case of an error.
1515
  virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1516
                            Status &error);
1517
1518
  /// Read of memory from a process.
1519
  ///
1520
  /// This function has the same semantics of ReadMemory except that it
1521
  /// bypasses caching.
1522
  ///
1523
  /// \param[in] vm_addr
1524
  ///     A virtual load address that indicates where to start reading
1525
  ///     memory from.
1526
  ///
1527
  /// \param[out] buf
1528
  ///     A byte buffer that is at least \a size bytes long that
1529
  ///     will receive the memory bytes.
1530
  ///
1531
  /// \param[in] size
1532
  ///     The number of bytes to read.
1533
  ///
1534
  /// \param[out] error
1535
  ///     An error that indicates the success or failure of this
1536
  ///     operation. If error indicates success (error.Success()),
1537
  ///     then the value returned can be trusted, otherwise zero
1538
  ///     will be returned.
1539
  ///
1540
  /// \return
1541
  ///     The number of bytes that were actually read into \a buf. If
1542
  ///     the returned number is greater than zero, yet less than \a
1543
  ///     size, then this function will get called again with \a
1544
  ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
1545
  ///     returned in the case of an error.
1546
  size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1547
                                Status &error);
1548
1549
  /// Read a NULL terminated C string from memory
1550
  ///
1551
  /// This function will read a cache page at a time until the NULL
1552
  /// C string terminator is found. It will stop reading if the NULL
1553
  /// termination byte isn't found before reading \a cstr_max_len bytes, and
1554
  /// the results are always guaranteed to be NULL terminated (at most
1555
  /// cstr_max_len - 1 bytes will be read).
1556
  size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1557
                               size_t cstr_max_len, Status &error);
1558
1559
  size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1560
                               Status &error);
1561
1562
  /// Reads an unsigned integer of the specified byte size from process
1563
  /// memory.
1564
  ///
1565
  /// \param[in] load_addr
1566
  ///     A load address of the integer to read.
1567
  ///
1568
  /// \param[in] byte_size
1569
  ///     The size in byte of the integer to read.
1570
  ///
1571
  /// \param[in] fail_value
1572
  ///     The value to return if we fail to read an integer.
1573
  ///
1574
  /// \param[out] error
1575
  ///     An error that indicates the success or failure of this
1576
  ///     operation. If error indicates success (error.Success()),
1577
  ///     then the value returned can be trusted, otherwise zero
1578
  ///     will be returned.
1579
  ///
1580
  /// \return
1581
  ///     The unsigned integer that was read from the process memory
1582
  ///     space. If the integer was smaller than a uint64_t, any
1583
  ///     unused upper bytes will be zero filled. If the process
1584
  ///     byte order differs from the host byte order, the integer
1585
  ///     value will be appropriately byte swapped into host byte
1586
  ///     order.
1587
  uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1588
                                         size_t byte_size, uint64_t fail_value,
1589
                                         Status &error);
1590
1591
  int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1592
                                      int64_t fail_value, Status &error);
1593
1594
  lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1595
1596
  bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1597
                            Status &error);
1598
1599
  /// Actually do the writing of memory to a process.
1600
  ///
1601
  /// \param[in] vm_addr
1602
  ///     A virtual load address that indicates where to start writing
1603
  ///     memory to.
1604
  ///
1605
  /// \param[in] buf
1606
  ///     A byte buffer that is at least \a size bytes long that
1607
  ///     contains the data to write.
1608
  ///
1609
  /// \param[in] size
1610
  ///     The number of bytes to write.
1611
  ///
1612
  /// \param[out] error
1613
  ///     An error value in case the memory write fails.
1614
  ///
1615
  /// \return
1616
  ///     The number of bytes that were actually written.
1617
  virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1618
0
                               size_t size, Status &error) {
1619
0
    error.SetErrorStringWithFormatv(
1620
0
        "error: {0} does not support writing to processes", GetPluginName());
1621
0
    return 0;
1622
0
  }
1623
1624
  /// Write all or part of a scalar value to memory.
1625
  ///
1626
  /// The value contained in \a scalar will be swapped to match the byte order
1627
  /// of the process that is being debugged. If \a size is less than the size
1628
  /// of scalar, the least significant \a size bytes from scalar will be
1629
  /// written. If \a size is larger than the byte size of scalar, then the
1630
  /// extra space will be padded with zeros and the scalar value will be
1631
  /// placed in the least significant bytes in memory.
1632
  ///
1633
  /// \param[in] vm_addr
1634
  ///     A virtual load address that indicates where to start writing
1635
  ///     memory to.
1636
  ///
1637
  /// \param[in] scalar
1638
  ///     The scalar to write to the debugged process.
1639
  ///
1640
  /// \param[in] size
1641
  ///     This value can be smaller or larger than the scalar value
1642
  ///     itself. If \a size is smaller than the size of \a scalar,
1643
  ///     the least significant bytes in \a scalar will be used. If
1644
  ///     \a size is larger than the byte size of \a scalar, then
1645
  ///     the extra space will be padded with zeros. If \a size is
1646
  ///     set to UINT32_MAX, then the size of \a scalar will be used.
1647
  ///
1648
  /// \param[out] error
1649
  ///     An error value in case the memory write fails.
1650
  ///
1651
  /// \return
1652
  ///     The number of bytes that were actually written.
1653
  size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1654
                             size_t size, Status &error);
1655
1656
  size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1657
                                     bool is_signed, Scalar &scalar,
1658
                                     Status &error);
1659
1660
  /// Write memory to a process.
1661
  ///
1662
  /// This function will write memory to the current process's address space
1663
  /// and maintain any traps that might be present due to software
1664
  /// breakpoints.
1665
  ///
1666
  /// This function is not meant to be overridden by Process subclasses, the
1667
  /// subclasses should implement Process::DoWriteMemory (lldb::addr_t,
1668
  /// size_t, void *).
1669
  ///
1670
  /// \param[in] vm_addr
1671
  ///     A virtual load address that indicates where to start writing
1672
  ///     memory to.
1673
  ///
1674
  /// \param[in] buf
1675
  ///     A byte buffer that is at least \a size bytes long that
1676
  ///     contains the data to write.
1677
  ///
1678
  /// \param[in] size
1679
  ///     The number of bytes to write.
1680
  ///
1681
  /// \return
1682
  ///     The number of bytes that were actually written.
1683
  // TODO: change this to take an ArrayRef<uint8_t>
1684
  size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1685
                     Status &error);
1686
1687
  /// Actually allocate memory in the process.
1688
  ///
1689
  /// This function will allocate memory in the process's address space.  This
1690
  /// can't rely on the generic function calling mechanism, since that
1691
  /// requires this function.
1692
  ///
1693
  /// \param[in] size
1694
  ///     The size of the allocation requested.
1695
  ///
1696
  /// \return
1697
  ///     The address of the allocated buffer in the process, or
1698
  ///     LLDB_INVALID_ADDRESS if the allocation failed.
1699
1700
  virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1701
1
                                        Status &error) {
1702
1
    error.SetErrorStringWithFormatv(
1703
1
        "error: {0} does not support allocating in the debug process",
1704
1
        GetPluginName());
1705
1
    return LLDB_INVALID_ADDRESS;
1706
1
  }
1707
1708
  virtual Status WriteObjectFile(std::vector<ObjectFile::LoadableData> entries);
1709
1710
  /// The public interface to allocating memory in the process.
1711
  ///
1712
  /// This function will allocate memory in the process's address space.  This
1713
  /// can't rely on the generic function calling mechanism, since that
1714
  /// requires this function.
1715
  ///
1716
  /// \param[in] size
1717
  ///     The size of the allocation requested.
1718
  ///
1719
  /// \param[in] permissions
1720
  ///     Or together any of the lldb::Permissions bits.  The permissions on
1721
  ///     a given memory allocation can't be changed after allocation.  Note
1722
  ///     that a block that isn't set writable can still be written on from
1723
  ///     lldb,
1724
  ///     just not by the process itself.
1725
  ///
1726
  /// \param[in,out] error
1727
  ///     An error object to fill in if things go wrong.
1728
  /// \return
1729
  ///     The address of the allocated buffer in the process, or
1730
  ///     LLDB_INVALID_ADDRESS if the allocation failed.
1731
  lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1732
1733
  /// The public interface to allocating memory in the process, this also
1734
  /// clears the allocated memory.
1735
  ///
1736
  /// This function will allocate memory in the process's address space.  This
1737
  /// can't rely on the generic function calling mechanism, since that
1738
  /// requires this function.
1739
  ///
1740
  /// \param[in] size
1741
  ///     The size of the allocation requested.
1742
  ///
1743
  /// \param[in] permissions
1744
  ///     Or together any of the lldb::Permissions bits.  The permissions on
1745
  ///     a given memory allocation can't be changed after allocation.  Note
1746
  ///     that a block that isn't set writable can still be written on from
1747
  ///     lldb,
1748
  ///     just not by the process itself.
1749
  ///
1750
  /// \param[in,out] error
1751
  ///     An error object to fill in if things go wrong.
1752
  ///
1753
  /// \return
1754
  ///     The address of the allocated buffer in the process, or
1755
  ///     LLDB_INVALID_ADDRESS if the allocation failed.
1756
1757
  lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
1758
                               Status &error);
1759
1760
  /// If this architecture and process supports memory tagging, return a tag
1761
  /// manager that can be used to maniupulate those memory tags.
1762
  ///
1763
  /// \return
1764
  ///     Either a valid pointer to a tag manager or an error describing why one
1765
  ///     could not be provided.
1766
  llvm::Expected<const MemoryTagManager *> GetMemoryTagManager();
1767
1768
  /// Read memory tags for the range addr to addr+len. It is assumed
1769
  /// that this range has already been granule aligned.
1770
  /// (see MemoryTagManager::MakeTaggedRange)
1771
  ///
1772
  /// This calls DoReadMemoryTags to do the target specific operations.
1773
  ///
1774
  /// \param[in] addr
1775
  ///     Start of memory range to read tags for.
1776
  ///
1777
  /// \param[in] len
1778
  ///     Length of memory range to read tags for (in bytes).
1779
  ///
1780
  /// \return
1781
  ///     If this architecture or process does not support memory tagging,
1782
  ///     an error saying so.
1783
  ///     If it does, either the memory tags or an error describing a
1784
  ///     failure to read or unpack them.
1785
  virtual llvm::Expected<std::vector<lldb::addr_t>>
1786
  ReadMemoryTags(lldb::addr_t addr, size_t len);
1787
1788
  /// Write memory tags for a range of memory.
1789
  /// (calls DoWriteMemoryTags to do the target specific work)
1790
  ///
1791
  /// \param[in] addr
1792
  ///     The address to start writing tags from. It is assumed that this
1793
  ///     address is granule aligned.
1794
  ///
1795
  /// \param[in] len
1796
  ///     The size of the range to write tags for. It is assumed that this
1797
  ///     is some multiple of the granule size. This len can be different
1798
  ///     from (number of tags * granule size) in the case where you want
1799
  ///     lldb-server to repeat tags across the range.
1800
  ///
1801
  /// \param[in] tags
1802
  ///     Allocation tags to be written. Since lldb-server can repeat tags for a
1803
  ///     range, the number of tags doesn't have to match the number of granules
1804
  ///     in the range. (though most of the time it will)
1805
  ///
1806
  /// \return
1807
  ///     A Status telling you if the write succeeded or not.
1808
  Status WriteMemoryTags(lldb::addr_t addr, size_t len,
1809
                         const std::vector<lldb::addr_t> &tags);
1810
1811
  /// Resolve dynamically loaded indirect functions.
1812
  ///
1813
  /// \param[in] address
1814
  ///     The load address of the indirect function to resolve.
1815
  ///
1816
  /// \param[out] error
1817
  ///     An error value in case the resolve fails.
1818
  ///
1819
  /// \return
1820
  ///     The address of the resolved function.
1821
  ///     LLDB_INVALID_ADDRESS if the resolution failed.
1822
  virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
1823
                                               Status &error);
1824
1825
  /// Locate the memory region that contains load_addr.
1826
  ///
1827
  /// If load_addr is within the address space the process has mapped
1828
  /// range_info will be filled in with the start and end of that range as
1829
  /// well as the permissions for that range and range_info. GetMapped will
1830
  /// return true.
1831
  ///
1832
  /// If load_addr is outside any mapped region then range_info will have its
1833
  /// start address set to load_addr and the end of the range will indicate
1834
  /// the start of the next mapped range or be set to LLDB_INVALID_ADDRESS if
1835
  /// there are no valid mapped ranges between load_addr and the end of the
1836
  /// process address space.
1837
  ///
1838
  /// GetMemoryRegionInfo calls DoGetMemoryRegionInfo. Override that function in
1839
  /// process subclasses.
1840
  ///
1841
  /// \param[in] load_addr
1842
  ///     The load address to query the range_info for. May include non
1843
  ///     address bits, these will be removed by the ABI plugin if there is
1844
  ///     one.
1845
  ///
1846
  /// \param[out] range_info
1847
  ///     An range_info value containing the details of the range.
1848
  ///
1849
  /// \return
1850
  ///     An error value.
1851
  Status GetMemoryRegionInfo(lldb::addr_t load_addr,
1852
                             MemoryRegionInfo &range_info);
1853
1854
  /// Obtain all the mapped memory regions within this process.
1855
  ///
1856
  /// \param[out] region_list
1857
  ///     A vector to contain MemoryRegionInfo objects for all mapped
1858
  ///     ranges.
1859
  ///
1860
  /// \return
1861
  ///     An error value.
1862
  virtual Status
1863
  GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list);
1864
1865
  /// Get the number of watchpoints supported by this target.
1866
  ///
1867
  /// We may be able to determine the number of watchpoints available
1868
  /// on this target; retrieve this value if possible.
1869
  ///
1870
  /// This number may be less than the number of watchpoints a user
1871
  /// can specify. This is because a single user watchpoint may require
1872
  /// multiple watchpoint slots to implement. Due to the size
1873
  /// and/or alignment of objects.
1874
  ///
1875
  /// \return
1876
  ///     Returns the number of watchpoints, if available.
1877
0
  virtual std::optional<uint32_t> GetWatchpointSlotCount() {
1878
0
    return std::nullopt;
1879
0
  }
1880
1881
  /// Whether lldb will be notified about watchpoints after
1882
  /// the instruction has completed executing, or if the
1883
  /// instruction is rolled back and it is notified before it
1884
  /// executes.
1885
  /// The default behavior is "exceptions received after instruction
1886
  /// has executed", except for certain CPU architectures.
1887
  /// Process subclasses may override this if they have additional
1888
  /// information.
1889
  ///
1890
  /// \return
1891
  ///     Returns true for targets where lldb is notified after
1892
  ///     the instruction has completed executing.
1893
  bool GetWatchpointReportedAfter();
1894
1895
  lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
1896
                                      lldb::addr_t header_addr,
1897
                                      size_t size_to_read = 512);
1898
1899
  /// Attempt to get the attributes for a region of memory in the process.
1900
  ///
1901
  /// It may be possible for the remote debug server to inspect attributes for
1902
  /// a region of memory in the process, such as whether there is a valid page
1903
  /// of memory at a given address or whether that page is
1904
  /// readable/writable/executable by the process.
1905
  ///
1906
  /// \param[in] load_addr
1907
  ///     The address of interest in the process.
1908
  ///
1909
  /// \param[out] permissions
1910
  ///     If this call returns successfully, this bitmask will have
1911
  ///     its Permissions bits set to indicate whether the region is
1912
  ///     readable/writable/executable.  If this call fails, the
1913
  ///     bitmask values are undefined.
1914
  ///
1915
  /// \return
1916
  ///     Returns true if it was able to determine the attributes of the
1917
  ///     memory region.  False if not.
1918
  virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
1919
                                         uint32_t &permissions);
1920
1921
  /// Determines whether executing JIT-compiled code in this process is
1922
  /// possible.
1923
  ///
1924
  /// \return
1925
  ///     True if execution of JIT code is possible; false otherwise.
1926
  bool CanJIT();
1927
1928
  /// Sets whether executing JIT-compiled code in this process is possible.
1929
  ///
1930
  /// \param[in] can_jit
1931
  ///     True if execution of JIT code is possible; false otherwise.
1932
  void SetCanJIT(bool can_jit);
1933
1934
  /// Determines whether executing function calls using the interpreter is
1935
  /// possible for this process.
1936
  ///
1937
  /// \return
1938
  ///     True if possible; false otherwise.
1939
6.06k
  bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
1940
1941
  /// Sets whether executing function calls using the interpreter is possible
1942
  /// for this process.
1943
  ///
1944
  /// \param[in] can_interpret_function_calls
1945
  ///     True if possible; false otherwise.
1946
0
  void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
1947
0
    m_can_interpret_function_calls = can_interpret_function_calls;
1948
0
  }
1949
1950
  /// Sets whether executing code in this process is possible. This could be
1951
  /// either through JIT or interpreting.
1952
  ///
1953
  /// \param[in] can_run_code
1954
  ///     True if execution of code is possible; false otherwise.
1955
  void SetCanRunCode(bool can_run_code);
1956
1957
  /// Actually deallocate memory in the process.
1958
  ///
1959
  /// This function will deallocate memory in the process's address space that
1960
  /// was allocated with AllocateMemory.
1961
  ///
1962
  /// \param[in] ptr
1963
  ///     A return value from AllocateMemory, pointing to the memory you
1964
  ///     want to deallocate.
1965
  ///
1966
  /// \return
1967
  ///     \b true if the memory was deallocated, \b false otherwise.
1968
0
  virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
1969
0
    Status error;
1970
0
    error.SetErrorStringWithFormatv(
1971
0
        "error: {0} does not support deallocating in the debug process",
1972
0
        GetPluginName());
1973
0
    return error;
1974
0
  }
1975
1976
  /// The public interface to deallocating memory in the process.
1977
  ///
1978
  /// This function will deallocate memory in the process's address space that
1979
  /// was allocated with AllocateMemory.
1980
  ///
1981
  /// \param[in] ptr
1982
  ///     A return value from AllocateMemory, pointing to the memory you
1983
  ///     want to deallocate.
1984
  ///
1985
  /// \return
1986
  ///     \b true if the memory was deallocated, \b false otherwise.
1987
  Status DeallocateMemory(lldb::addr_t ptr);
1988
1989
  /// Get any available STDOUT.
1990
  ///
1991
  /// Calling this method is a valid operation only if all of the following
1992
  /// conditions are true: 1) The process was launched, and not attached to.
1993
  /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
1994
  /// process was launched without supplying a valid file path
1995
  ///    for STDOUT.
1996
  ///
1997
  /// Note that the implementation will probably need to start a read thread
1998
  /// in the background to make sure that the pipe is drained and the STDOUT
1999
  /// buffered appropriately, to prevent the process from deadlocking trying
2000
  /// to write to a full buffer.
2001
  ///
2002
  /// Events will be queued indicating that there is STDOUT available that can
2003
  /// be retrieved using this function.
2004
  ///
2005
  /// \param[out] buf
2006
  ///     A buffer that will receive any STDOUT bytes that are
2007
  ///     currently available.
2008
  ///
2009
  /// \param[in] buf_size
2010
  ///     The size in bytes for the buffer \a buf.
2011
  ///
2012
  /// \return
2013
  ///     The number of bytes written into \a buf. If this value is
2014
  ///     equal to \a buf_size, another call to this function should
2015
  ///     be made to retrieve more STDOUT data.
2016
  virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2017
2018
  /// Get any available STDERR.
2019
  ///
2020
  /// Calling this method is a valid operation only if all of the following
2021
  /// conditions are true: 1) The process was launched, and not attached to.
2022
  /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2023
  /// process was launched without supplying a valid file path
2024
  ///    for STDERR.
2025
  ///
2026
  /// Note that the implementation will probably need to start a read thread
2027
  /// in the background to make sure that the pipe is drained and the STDERR
2028
  /// buffered appropriately, to prevent the process from deadlocking trying
2029
  /// to write to a full buffer.
2030
  ///
2031
  /// Events will be queued indicating that there is STDERR available that can
2032
  /// be retrieved using this function.
2033
  ///
2034
  /// \param[in] buf
2035
  ///     A buffer that will receive any STDERR bytes that are
2036
  ///     currently available.
2037
  ///
2038
  /// \param[out] buf_size
2039
  ///     The size in bytes for the buffer \a buf.
2040
  ///
2041
  /// \return
2042
  ///     The number of bytes written into \a buf. If this value is
2043
  ///     equal to \a buf_size, another call to this function should
2044
  ///     be made to retrieve more STDERR data.
2045
  virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2046
2047
  /// Puts data into this process's STDIN.
2048
  ///
2049
  /// Calling this method is a valid operation only if all of the following
2050
  /// conditions are true: 1) The process was launched, and not attached to.
2051
  /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2052
  /// process was launched without supplying a valid file path
2053
  ///    for STDIN.
2054
  ///
2055
  /// \param[in] buf
2056
  ///     A buffer that contains the data to write to the process's STDIN.
2057
  ///
2058
  /// \param[in] buf_size
2059
  ///     The size in bytes for the buffer \a buf.
2060
  ///
2061
  /// \return
2062
  ///     The number of bytes written into \a buf. If this value is
2063
  ///     less than \a buf_size, another call to this function should
2064
  ///     be made to write the rest of the data.
2065
0
  virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2066
0
    error.SetErrorString("stdin unsupported");
2067
0
    return 0;
2068
0
  }
2069
2070
  /// Get any available profile data.
2071
  ///
2072
  /// \param[out] buf
2073
  ///     A buffer that will receive any profile data bytes that are
2074
  ///     currently available.
2075
  ///
2076
  /// \param[out] buf_size
2077
  ///     The size in bytes for the buffer \a buf.
2078
  ///
2079
  /// \return
2080
  ///     The number of bytes written into \a buf. If this value is
2081
  ///     equal to \a buf_size, another call to this function should
2082
  ///     be made to retrieve more profile data.
2083
  virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2084
2085
  // Process Breakpoints
2086
  size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2087
2088
18
  virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2089
18
    Status error;
2090
18
    error.SetErrorStringWithFormatv(
2091
18
        "error: {0} does not support enabling breakpoints", GetPluginName());
2092
18
    return error;
2093
18
  }
2094
2095
0
  virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2096
0
    Status error;
2097
0
    error.SetErrorStringWithFormatv(
2098
0
        "error: {0} does not support disabling breakpoints", GetPluginName());
2099
0
    return error;
2100
0
  }
2101
2102
  // This is implemented completely using the lldb::Process API. Subclasses
2103
  // don't need to implement this function unless the standard flow of read
2104
  // existing opcode, write breakpoint opcode, verify breakpoint opcode doesn't
2105
  // work for a specific process plug-in.
2106
  virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2107
2108
  // This is implemented completely using the lldb::Process API. Subclasses
2109
  // don't need to implement this function unless the standard flow of
2110
  // restoring original opcode in memory and verifying the restored opcode
2111
  // doesn't work for a specific process plug-in.
2112
  virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2113
2114
  BreakpointSiteList &GetBreakpointSiteList();
2115
2116
  const BreakpointSiteList &GetBreakpointSiteList() const;
2117
2118
  void DisableAllBreakpointSites();
2119
2120
  Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2121
2122
  lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2123
                                        bool use_hardware);
2124
2125
  Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2126
2127
  Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2128
2129
  // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove themselves
2130
  // from the owner's list of this breakpoint sites.
2131
  void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2132
                                     lldb::user_id_t owner_loc_id,
2133
                                     lldb::BreakpointSiteSP &bp_site_sp);
2134
2135
  // Process Watchpoints (optional)
2136
  virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2137
2138
  virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2139
2140
  // Thread Queries
2141
2142
  /// Update the thread list.
2143
  ///
2144
  /// This method performs some general clean up before invoking
2145
  /// \a DoUpdateThreadList, which should be implemented by each
2146
  /// process plugin.
2147
  ///
2148
  /// \return
2149
  ///     \b true if the new thread list could be generated, \b false otherwise.
2150
  bool UpdateThreadList(ThreadList &old_thread_list,
2151
                        ThreadList &new_thread_list);
2152
2153
  void UpdateThreadListIfNeeded();
2154
2155
174k
  ThreadList &GetThreadList() { return m_thread_list; }
2156
2157
  // When ExtendedBacktraces are requested, the HistoryThreads that are created
2158
  // need an owner -- they're saved here in the Process.  The threads in this
2159
  // list are not iterated over - driver programs need to request the extended
2160
  // backtrace calls starting from a root concrete thread one by one.
2161
0
  ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2162
2163
82
  ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2164
2165
  uint32_t GetNextThreadIndexID(uint64_t thread_id);
2166
2167
  lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2168
2169
  // Returns true if an index id has been assigned to a thread.
2170
  bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2171
2172
  // Given a thread_id, it will assign a more reasonable index id for display
2173
  // to the user. If the thread_id has previously been assigned, the same index
2174
  // id will be used.
2175
  uint32_t AssignIndexIDToThread(uint64_t thread_id);
2176
2177
  // Queue Queries
2178
2179
  virtual void UpdateQueueListIfNeeded();
2180
2181
76
  QueueList &GetQueueList() {
2182
76
    UpdateQueueListIfNeeded();
2183
76
    return m_queue_list;
2184
76
  }
2185
2186
0
  QueueList::QueueIterable Queues() {
2187
0
    UpdateQueueListIfNeeded();
2188
0
    return m_queue_list.Queues();
2189
0
  }
2190
2191
  // Event Handling
2192
  lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2193
2194
  // Returns the process state when it is stopped. If specified, event_sp_ptr
2195
  // is set to the event which triggered the stop. If wait_always = false, and
2196
  // the process is already stopped, this function returns immediately. If the
2197
  // process is hijacked and use_run_lock is true (the default), then this
2198
  // function releases the run lock after the stop. Setting use_run_lock to
2199
  // false will avoid this behavior.
2200
  // If we are waiting to stop that will return control to the user,
2201
  // then we also want to run SelectMostRelevantFrame, which is controlled
2202
  // by "select_most_relevant".
2203
  lldb::StateType
2204
  WaitForProcessToStop(const Timeout<std::micro> &timeout,
2205
                       lldb::EventSP *event_sp_ptr = nullptr,
2206
                       bool wait_always = true,
2207
                       lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2208
                       Stream *stream = nullptr, bool use_run_lock = true,
2209
                       SelectMostRelevant select_most_relevant =
2210
                           DoNoSelectMostRelevantFrame);
2211
2212
728
  uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2213
2214
  /// Waits for the process state to be running within a given msec timeout.
2215
  ///
2216
  /// The main purpose of this is to implement an interlock waiting for
2217
  /// HandlePrivateEvent to push an IOHandler.
2218
  ///
2219
  /// \param[in] timeout
2220
  ///     The maximum time length to wait for the process to transition to the
2221
  ///     eStateRunning state.
2222
  void SyncIOHandler(uint32_t iohandler_id, const Timeout<std::micro> &timeout);
2223
2224
  lldb::StateType GetStateChangedEvents(
2225
      lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2226
      lldb::ListenerSP
2227
          hijack_listener); // Pass an empty ListenerSP to use builtin listener
2228
2229
  /// Centralize the code that handles and prints descriptions for process
2230
  /// state changes.
2231
  ///
2232
  /// \param[in] event_sp
2233
  ///     The process state changed event
2234
  ///
2235
  /// \param[in] stream
2236
  ///     The output stream to get the state change description
2237
  ///
2238
  /// \param[in,out] pop_process_io_handler
2239
  ///     If this value comes in set to \b true, then pop the Process IOHandler
2240
  ///     if needed.
2241
  ///     Else this variable will be set to \b true or \b false to indicate if
2242
  ///     the process
2243
  ///     needs to have its process IOHandler popped.
2244
  ///
2245
  /// \return
2246
  ///     \b true if the event describes a process state changed event, \b false
2247
  ///     otherwise.
2248
  static bool
2249
  HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream,
2250
                                 SelectMostRelevant select_most_relevant,
2251
                                 bool &pop_process_io_handler);
2252
2253
  Event *PeekAtStateChangedEvents();
2254
2255
  class ProcessEventHijacker {
2256
  public:
2257
    ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2258
2.97k
        : m_process(process) {
2259
2.97k
      m_process.HijackProcessEvents(std::move(listener_sp));
2260
2.97k
    }
2261
2262
2.97k
    ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2263
2264
  private:
2265
    Process &m_process;
2266
  };
2267
2268
  friend class ProcessEventHijacker;
2269
  friend class ProcessProperties;
2270
  /// If you need to ensure that you and only you will hear about some public
2271
  /// event, then make a new listener, set to listen to process events, and
2272
  /// then call this with that listener.  Then you will have to wait on that
2273
  /// listener explicitly for events (rather than using the GetNextEvent &
2274
  /// WaitFor* calls above.  Be sure to call RestoreProcessEvents when you are
2275
  /// done.
2276
  ///
2277
  /// \param[in] listener_sp
2278
  ///     This is the new listener to whom all process events will be delivered.
2279
  ///
2280
  /// \return
2281
  ///     Returns \b true if the new listener could be installed,
2282
  ///     \b false otherwise.
2283
  bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2284
2285
  /// Restores the process event broadcasting to its normal state.
2286
  ///
2287
  void RestoreProcessEvents();
2288
2289
  bool StateChangedIsHijackedForSynchronousResume();
2290
2291
  bool StateChangedIsExternallyHijacked();
2292
2293
  const lldb::ABISP &GetABI();
2294
2295
14.0k
  OperatingSystem *GetOperatingSystem() { return m_os_up.get(); }
2296
2297
  std::vector<LanguageRuntime *> GetLanguageRuntimes();
2298
2299
  LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language);
2300
2301
  bool IsPossibleDynamicValue(ValueObject &in_value);
2302
2303
  bool IsRunning() const;
2304
2305
2.24k
  DynamicCheckerFunctions *GetDynamicCheckers() {
2306
2.24k
    return m_dynamic_checkers_up.get();
2307
2.24k
  }
2308
2309
  void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2310
2311
/// Prune ThreadPlanStacks for unreported threads.
2312
///
2313
/// \param[in] tid
2314
///     The tid whose Plan Stack we are seeking to prune.
2315
///
2316
/// \return
2317
///     \b true if the TID is found or \b false if not.
2318
bool PruneThreadPlansForTID(lldb::tid_t tid);
2319
2320
/// Prune ThreadPlanStacks for all unreported threads.
2321
void PruneThreadPlans();
2322
2323
  /// Find the thread plan stack associated with thread with \a tid.
2324
  ///
2325
  /// \param[in] tid
2326
  ///     The tid whose Plan Stack we are seeking.
2327
  ///
2328
  /// \return
2329
  ///     Returns a ThreadPlan if the TID is found or nullptr if not.
2330
  ThreadPlanStack *FindThreadPlans(lldb::tid_t tid);
2331
2332
  /// Dump the thread plans associated with thread with \a tid.
2333
  ///
2334
  /// \param[in,out] strm
2335
  ///     The stream to which to dump the output
2336
  ///
2337
  /// \param[in] tid
2338
  ///     The tid whose Plan Stack we are dumping
2339
  ///
2340
  /// \param[in] desc_level
2341
  ///     How much detail to dump
2342
  ///
2343
  /// \param[in] internal
2344
  ///     If \b true dump all plans, if false only user initiated plans
2345
  ///
2346
  /// \param[in] condense_trivial
2347
  ///     If true, only dump a header if the plan stack is just the base plan.
2348
  ///
2349
  /// \param[in] skip_unreported_plans
2350
  ///     If true, only dump a plan if it is currently backed by an
2351
  ///     lldb_private::Thread *.
2352
  ///
2353
  /// \return
2354
  ///     Returns \b true if TID was found, \b false otherwise
2355
  bool DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
2356
                             lldb::DescriptionLevel desc_level, bool internal,
2357
                             bool condense_trivial, bool skip_unreported_plans);
2358
2359
  /// Dump all the thread plans for this process.
2360
  ///
2361
  /// \param[in,out] strm
2362
  ///     The stream to which to dump the output
2363
  ///
2364
  /// \param[in] desc_level
2365
  ///     How much detail to dump
2366
  ///
2367
  /// \param[in] internal
2368
  ///     If \b true dump all plans, if false only user initiated plans
2369
  ///
2370
  /// \param[in] condense_trivial
2371
  ///     If true, only dump a header if the plan stack is just the base plan.
2372
  ///
2373
  /// \param[in] skip_unreported_plans
2374
  ///     If true, skip printing all thread plan stacks that don't currently
2375
  ///     have a backing lldb_private::Thread *.
2376
  void DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
2377
                       bool internal, bool condense_trivial,
2378
                       bool skip_unreported_plans);
2379
2380
  /// Call this to set the lldb in the mode where it breaks on new thread
2381
  /// creations, and then auto-restarts.  This is useful when you are trying
2382
  /// to run only one thread, but either that thread or the kernel is creating
2383
  /// new threads in the process.  If you stop when the thread is created, you
2384
  /// can immediately suspend it, and keep executing only the one thread you
2385
  /// intend.
2386
  ///
2387
  /// \return
2388
  ///     Returns \b true if we were able to start up the notification
2389
  ///     \b false otherwise.
2390
0
  virtual bool StartNoticingNewThreads() { return true; }
2391
2392
  /// Call this to turn off the stop & notice new threads mode.
2393
  ///
2394
  /// \return
2395
  ///     Returns \b true if we were able to start up the notification
2396
  ///     \b false otherwise.
2397
2
  virtual bool StopNoticingNewThreads() { return true; }
2398
2399
  void SetRunningUserExpression(bool on);
2400
  void SetRunningUtilityFunction(bool on);
2401
2402
  // lldb::ExecutionContextScope pure virtual functions
2403
  lldb::TargetSP CalculateTarget() override;
2404
2405
17.9k
  lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2406
2407
0
  lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2408
2409
8.17k
  lldb::StackFrameSP CalculateStackFrame() override {
2410
8.17k
    return lldb::StackFrameSP();
2411
8.17k
  }
2412
2413
  void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2414
2415
  void SetSTDIOFileDescriptor(int file_descriptor);
2416
2417
  // Add a permanent region of memory that should never be read or written to.
2418
  // This can be used to ensure that memory reads or writes to certain areas of
2419
  // memory never end up being sent to the DoReadMemory or DoWriteMemory
2420
  // functions which can improve performance.
2421
  void AddInvalidMemoryRegion(const LoadRange &region);
2422
2423
  // Remove a permanent region of memory that should never be read or written
2424
  // to that was previously added with AddInvalidMemoryRegion.
2425
  bool RemoveInvalidMemoryRange(const LoadRange &region);
2426
2427
  // If the setup code of a thread plan needs to do work that might involve
2428
  // calling a function in the target, it should not do that work directly in
2429
  // one of the thread plan functions (DidPush/WillResume) because such work
2430
  // needs to be handled carefully.  Instead, put that work in a
2431
  // PreResumeAction callback, and register it with the process.  It will get
2432
  // done before the actual "DoResume" gets called.
2433
2434
  typedef bool(PreResumeActionCallback)(void *);
2435
2436
  void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2437
2438
  bool RunPreResumeActions();
2439
2440
  void ClearPreResumeActions();
2441
2442
  void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2443
2444
  ProcessRunLock &GetRunLock();
2445
2446
  bool CurrentThreadIsPrivateStateThread();
2447
2448
0
  virtual Status SendEventData(const char *data) {
2449
0
    Status return_error("Sending an event is not supported for this process.");
2450
0
    return return_error;
2451
0
  }
2452
2453
  lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2454
2455
  lldb::InstrumentationRuntimeSP
2456
  GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2457
2458
  /// Try to fetch the module specification for a module with the given file
2459
  /// name and architecture. Process sub-classes have to override this method
2460
  /// if they support platforms where the Platform object can't get the module
2461
  /// spec for all module.
2462
  ///
2463
  /// \param[in] module_file_spec
2464
  ///     The file name of the module to get specification for.
2465
  ///
2466
  /// \param[in] arch
2467
  ///     The architecture of the module to get specification for.
2468
  ///
2469
  /// \param[out] module_spec
2470
  ///     The fetched module specification if the return value is
2471
  ///     \b true, unchanged otherwise.
2472
  ///
2473
  /// \return
2474
  ///     Returns \b true if the module spec fetched successfully,
2475
  ///     \b false otherwise.
2476
  virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2477
                             const ArchSpec &arch, ModuleSpec &module_spec);
2478
2479
  virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2480
6
                                   const llvm::Triple &triple) {}
2481
2482
  /// Try to find the load address of a file.
2483
  /// The load address is defined as the address of the first memory region
2484
  /// what contains data mapped from the specified file.
2485
  ///
2486
  /// \param[in] file
2487
  ///     The name of the file whose load address we are looking for
2488
  ///
2489
  /// \param[out] is_loaded
2490
  ///     \b True if the file is loaded into the memory and false
2491
  ///     otherwise.
2492
  ///
2493
  /// \param[out] load_addr
2494
  ///     The load address of the file if it is loaded into the
2495
  ///     processes address space, LLDB_INVALID_ADDRESS otherwise.
2496
  virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2497
0
                                    lldb::addr_t &load_addr) {
2498
0
    return Status("Not supported");
2499
0
  }
2500
2501
  /// Fetch process defined metadata.
2502
  ///
2503
  /// \return
2504
  ///     A StructuredDataSP object which, if non-empty, will contain the
2505
  ///     information related to the process.
2506
5
  virtual StructuredData::DictionarySP GetMetadata() { return nullptr; }
2507
2508
  size_t AddImageToken(lldb::addr_t image_ptr);
2509
2510
  lldb::addr_t GetImagePtrFromToken(size_t token) const;
2511
2512
  void ResetImageToken(size_t token);
2513
2514
  /// Find the next branch instruction to set a breakpoint on
2515
  ///
2516
  /// When instruction stepping through a source line, instead of stepping
2517
  /// through each instruction, we can put a breakpoint on the next branch
2518
  /// instruction (within the range of instructions we are stepping through)
2519
  /// and continue the process to there, yielding significant performance
2520
  /// benefits over instruction stepping.
2521
  ///
2522
  /// \param[in] default_stop_addr
2523
  ///     The address of the instruction where lldb would put a
2524
  ///     breakpoint normally.
2525
  ///
2526
  /// \param[in] range_bounds
2527
  ///     The range which the breakpoint must be contained within.
2528
  ///     Typically a source line.
2529
  ///
2530
  /// \return
2531
  ///     The address of the next branch instruction, or the end of
2532
  ///     the range provided in range_bounds.  If there are any
2533
  ///     problems with the disassembly or getting the instructions,
2534
  ///     the original default_stop_addr will be returned.
2535
  Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2536
                                                AddressRange range_bounds);
2537
2538
  /// Configure asynchronous structured data feature.
2539
  ///
2540
  /// Each Process type that supports using an asynchronous StructuredData
2541
  /// feature should implement this to enable/disable/configure the feature.
2542
  /// The default implementation here will always return an error indiciating
2543
  /// the feature is unsupported.
2544
  ///
2545
  /// StructuredDataPlugin implementations will call this to configure a
2546
  /// feature that has been reported as being supported.
2547
  ///
2548
  /// \param[in] type_name
2549
  ///     The StructuredData type name as previously discovered by
2550
  ///     the Process-derived instance.
2551
  ///
2552
  /// \param[in] config_sp
2553
  ///     Configuration data for the feature being enabled.  This config
2554
  ///     data, which may be null, will be passed along to the feature
2555
  ///     to process.  The feature will dictate whether this is a dictionary,
2556
  ///     an array or some other object.  If the feature needs to be
2557
  ///     set up properly before it can be enabled, then the config should
2558
  ///     also take an enable/disable flag.
2559
  ///
2560
  /// \return
2561
  ///     Returns the result of attempting to configure the feature.
2562
  virtual Status
2563
  ConfigureStructuredData(llvm::StringRef type_name,
2564
                          const StructuredData::ObjectSP &config_sp);
2565
2566
  /// Broadcasts the given structured data object from the given plugin.
2567
  ///
2568
  /// StructuredDataPlugin instances can use this to optionally broadcast any
2569
  /// of their data if they want to make it available for clients.  The data
2570
  /// will come in on the structured data event bit
2571
  /// (eBroadcastBitStructuredData).
2572
  ///
2573
  /// \param[in] object_sp
2574
  ///     The structured data object to broadcast.
2575
  ///
2576
  /// \param[in] plugin_sp
2577
  ///     The plugin that will be reported in the event's plugin
2578
  ///     parameter.
2579
  void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2580
                               const lldb::StructuredDataPluginSP &plugin_sp);
2581
2582
  /// Returns the StructuredDataPlugin associated with a given type name, if
2583
  /// there is one.
2584
  ///
2585
  /// There will only be a plugin for a given StructuredDataType if the
2586
  /// debugged process monitor claims that the feature is supported. This is
2587
  /// one way to tell whether a feature is available.
2588
  ///
2589
  /// \return
2590
  ///     The plugin if one is available for the specified feature;
2591
  ///     otherwise, returns an empty shared pointer.
2592
  lldb::StructuredDataPluginSP
2593
  GetStructuredDataPlugin(llvm::StringRef type_name) const;
2594
2595
2
  virtual void *GetImplementation() { return nullptr; }
2596
2597
0
  virtual void ForceScriptedState(lldb::StateType state) {}
2598
2599
12.3k
  SourceManager::SourceFileCache &GetSourceFileCache() {
2600
12.3k
    return m_source_file_cache;
2601
12.3k
  }
2602
2603
protected:
2604
  friend class Trace;
2605
2606
  /// Construct with a shared pointer to a target, and the Process listener.
2607
  /// Uses the Host UnixSignalsSP by default.
2608
  Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
2609
2610
  /// Construct with a shared pointer to a target, the Process listener, and
2611
  /// the appropriate UnixSignalsSP for the process.
2612
  Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
2613
          const lldb::UnixSignalsSP &unix_signals_sp);
2614
2615
  ///  Get the processor tracing type supported for this process.
2616
  ///  Responses might be different depending on the architecture and
2617
  ///  capabilities of the underlying OS.
2618
  ///
2619
  ///  \return
2620
  ///     The supported trace type or an \a llvm::Error if tracing is
2621
  ///     not supported for the inferior.
2622
  virtual llvm::Expected<TraceSupportedResponse> TraceSupported();
2623
2624
  /// Start tracing a process or its threads.
2625
  ///
2626
  /// \param[in] request
2627
  ///     JSON object with the information necessary to start tracing. In the
2628
  ///     case of gdb-remote processes, this JSON object should conform to the
2629
  ///     jLLDBTraceStart packet.
2630
  ///
2631
  /// \return
2632
  ///     \a llvm::Error::success if the operation was successful, or
2633
  ///     \a llvm::Error otherwise.
2634
0
  virtual llvm::Error TraceStart(const llvm::json::Value &request) {
2635
0
    return llvm::make_error<UnimplementedError>();
2636
0
  }
2637
2638
  /// Stop tracing a live process or its threads.
2639
  ///
2640
  /// \param[in] request
2641
  ///     The information determining which threads or process to stop tracing.
2642
  ///
2643
  /// \return
2644
  ///     \a llvm::Error::success if the operation was successful, or
2645
  ///     \a llvm::Error otherwise.
2646
0
  virtual llvm::Error TraceStop(const TraceStopRequest &request) {
2647
0
    return llvm::make_error<UnimplementedError>();
2648
0
  }
2649
2650
  /// Get the current tracing state of the process and its threads.
2651
  ///
2652
  /// \param[in] type
2653
  ///     Tracing technology type to consider.
2654
  ///
2655
  /// \return
2656
  ///     A JSON object string with custom data depending on the trace
2657
  ///     technology, or an \a llvm::Error in case of errors.
2658
0
  virtual llvm::Expected<std::string> TraceGetState(llvm::StringRef type) {
2659
0
    return llvm::make_error<UnimplementedError>();
2660
0
  }
2661
2662
  /// Get binary data given a trace technology and a data identifier.
2663
  ///
2664
  /// \param[in] request
2665
  ///     Object with the params of the requested data.
2666
  ///
2667
  /// \return
2668
  ///     A vector of bytes with the requested data, or an \a llvm::Error in
2669
  ///     case of failures.
2670
  virtual llvm::Expected<std::vector<uint8_t>>
2671
0
  TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
2672
0
    return llvm::make_error<UnimplementedError>();
2673
0
  }
2674
2675
  // This calls a function of the form "void * (*)(void)".
2676
  bool CallVoidArgVoidPtrReturn(const Address *address,
2677
                                lldb::addr_t &returned_func,
2678
                                bool trap_exceptions = false);
2679
2680
  /// Update the thread list following process plug-in's specific logic.
2681
  ///
2682
  /// This method should only be invoked by \a UpdateThreadList.
2683
  ///
2684
  /// \return
2685
  ///     \b true if the new thread list could be generated, \b false otherwise.
2686
  virtual bool DoUpdateThreadList(ThreadList &old_thread_list,
2687
                                  ThreadList &new_thread_list) = 0;
2688
2689
  /// Actually do the reading of memory from a process.
2690
  ///
2691
  /// Subclasses must override this function and can return fewer bytes than
2692
  /// requested when memory requests are too large. This class will break up
2693
  /// the memory requests and keep advancing the arguments along as needed.
2694
  ///
2695
  /// \param[in] vm_addr
2696
  ///     A virtual load address that indicates where to start reading
2697
  ///     memory from.
2698
  ///
2699
  /// \param[in] size
2700
  ///     The number of bytes to read.
2701
  ///
2702
  /// \param[out] buf
2703
  ///     A byte buffer that is at least \a size bytes long that
2704
  ///     will receive the memory bytes.
2705
  ///
2706
  /// \param[out] error
2707
  ///     An error that indicates the success or failure of this
2708
  ///     operation. If error indicates success (error.Success()),
2709
  ///     then the value returned can be trusted, otherwise zero
2710
  ///     will be returned.
2711
  ///
2712
  /// \return
2713
  ///     The number of bytes that were actually read into \a buf.
2714
  ///     Zero is returned in the case of an error.
2715
  virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2716
                              Status &error) = 0;
2717
2718
  /// DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has
2719
  /// removed non address bits from load_addr. Override this method in
2720
  /// subclasses of Process.
2721
  ///
2722
  /// See GetMemoryRegionInfo for details of the logic.
2723
  ///
2724
  /// \param[in] load_addr
2725
  ///     The load address to query the range_info for. (non address bits
2726
  ///     removed)
2727
  ///
2728
  /// \param[out] range_info
2729
  ///     An range_info value containing the details of the range.
2730
  ///
2731
  /// \return
2732
  ///     An error value.
2733
  virtual Status DoGetMemoryRegionInfo(lldb::addr_t load_addr,
2734
0
                                       MemoryRegionInfo &range_info) {
2735
0
    return Status("Process::DoGetMemoryRegionInfo() not supported");
2736
0
  }
2737
2738
  /// Provide an override value in the subclass for lldb's
2739
  /// CPU-based logic for whether watchpoint exceptions are
2740
  /// received before or after an instruction executes.
2741
  ///
2742
  /// If a Process subclass needs to override this architecture-based
2743
  /// result, it may do so by overriding this method.
2744
  ///
2745
  /// \return
2746
  ///     No boolean returned means there is no override of the
2747
  ///     default architecture-based behavior.
2748
  ///     true is returned for targets where watchpoints are reported
2749
  ///     after the instruction has completed.
2750
  ///     false is returned for targets where watchpoints are reported
2751
  ///     before the instruction executes.
2752
0
  virtual std::optional<bool> DoGetWatchpointReportedAfter() {
2753
0
    return std::nullopt;
2754
0
  }
2755
2756
  lldb::StateType GetPrivateState();
2757
2758
  /// The "private" side of resuming a process.  This doesn't alter the state
2759
  /// of m_run_lock, but just causes the process to resume.
2760
  ///
2761
  /// \return
2762
  ///     An Status object describing the success or failure of the resume.
2763
  Status PrivateResume();
2764
2765
  // Called internally
2766
  void CompleteAttach();
2767
2768
  // NextEventAction provides a way to register an action on the next event
2769
  // that is delivered to this process.  There is currently only one next event
2770
  // action allowed in the process at one time.  If a new "NextEventAction" is
2771
  // added while one is already present, the old action will be discarded (with
2772
  // HandleBeingUnshipped called after it is discarded.)
2773
  //
2774
  // If you want to resume the process as a result of a resume action, call
2775
  // RequestResume, don't call Resume directly.
2776
  class NextEventAction {
2777
  public:
2778
    enum EventActionResult {
2779
      eEventActionSuccess,
2780
      eEventActionRetry,
2781
      eEventActionExit
2782
    };
2783
2784
2.11k
    NextEventAction(Process *process) : m_process(process) {}
2785
2786
2.11k
    virtual ~NextEventAction() = default;
2787
2788
    virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2789
2.11k
    virtual void HandleBeingUnshipped() {}
2790
    virtual EventActionResult HandleBeingInterrupted() = 0;
2791
    virtual const char *GetExitString() = 0;
2792
0
    void RequestResume() { m_process->m_resume_requested = true; }
2793
2794
  protected:
2795
    Process *m_process;
2796
  };
2797
2798
4.22k
  void SetNextEventAction(Process::NextEventAction *next_event_action) {
2799
4.22k
    if (m_next_event_action_up)
2800
2.11k
      m_next_event_action_up->HandleBeingUnshipped();
2801
2802
4.22k
    m_next_event_action_up.reset(next_event_action);
2803
4.22k
  }
2804
2805
  // This is the completer for Attaching:
2806
  class AttachCompletionHandler : public NextEventAction {
2807
  public:
2808
    AttachCompletionHandler(Process *process, uint32_t exec_count);
2809
2810
2.11k
    ~AttachCompletionHandler() override = default;
2811
2812
    EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2813
    EventActionResult HandleBeingInterrupted() override;
2814
    const char *GetExitString() override;
2815
2816
  private:
2817
    uint32_t m_exec_count;
2818
    std::string m_exit_string;
2819
  };
2820
2821
7.64k
  bool PrivateStateThreadIsValid() const {
2822
7.64k
    lldb::StateType state = m_private_state.GetValue();
2823
7.64k
    return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2824
7.64k
           
state != lldb::eStateExited7.61k
&&
m_private_state_thread.IsJoinable()5.45k
;
2825
7.64k
  }
2826
2827
2.97k
  void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2828
2829
  /// Loads any plugins associated with asynchronous structured data and maps
2830
  /// the relevant supported type name to the plugin.
2831
  ///
2832
  /// Processes can receive asynchronous structured data from the process
2833
  /// monitor.  This method will load and map any structured data plugins that
2834
  /// support the given set of supported type names. Later, if any of these
2835
  /// features are enabled, the process monitor is free to generate
2836
  /// asynchronous structured data.  The data must come in as a single \b
2837
  /// StructuredData::Dictionary.  That dictionary must have a string field
2838
  /// named 'type', with a value that equals the relevant type name string
2839
  /// (one of the values in \b supported_type_names).
2840
  ///
2841
  /// \param[in] supported_type_names
2842
  ///     An array of zero or more type names.  Each must be unique.
2843
  ///     For each entry in the list, a StructuredDataPlugin will be
2844
  ///     searched for that supports the structured data type name.
2845
  void MapSupportedStructuredDataPlugins(
2846
      const StructuredData::Array &supported_type_names);
2847
2848
  /// Route the incoming structured data dictionary to the right plugin.
2849
  ///
2850
  /// The incoming structured data must be a dictionary, and it must have a
2851
  /// key named 'type' that stores a string value.  The string value must be
2852
  /// the name of the structured data feature that knows how to handle it.
2853
  ///
2854
  /// \param[in] object_sp
2855
  ///     When non-null and pointing to a dictionary, the 'type'
2856
  ///     key's string value is used to look up the plugin that
2857
  ///     was registered for that structured data type.  It then
2858
  ///     calls the following method on the StructuredDataPlugin
2859
  ///     instance:
2860
  ///
2861
  ///     virtual void
2862
  ///     HandleArrivalOfStructuredData(Process &process,
2863
  ///                                   llvm::StringRef type_name,
2864
  ///                                   const StructuredData::ObjectSP
2865
  ///                                   &object_sp)
2866
  ///
2867
  /// \return
2868
  ///     True if the structured data was routed to a plugin; otherwise,
2869
  ///     false.
2870
  bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
2871
2872
  /// Check whether the process supports memory tagging.
2873
  ///
2874
  /// \return
2875
  ///     true if the process supports memory tagging,
2876
  ///     false otherwise.
2877
0
  virtual bool SupportsMemoryTagging() { return false; }
2878
2879
  /// Does the final operation to read memory tags. E.g. sending a GDB packet.
2880
  /// It assumes that ReadMemoryTags has checked that memory tagging is enabled
2881
  /// and has expanded the memory range as needed.
2882
  ///
2883
  /// \param[in] addr
2884
  ///    Start of address range to read memory tags for.
2885
  ///
2886
  /// \param[in] len
2887
  ///    Length of the memory range to read tags for (in bytes).
2888
  ///
2889
  /// \param[in] type
2890
  ///    Type of tags to read (get this from a MemoryTagManager)
2891
  ///
2892
  /// \return
2893
  ///     The packed tag data received from the remote or an error
2894
  ///     if the read failed.
2895
  virtual llvm::Expected<std::vector<uint8_t>>
2896
0
  DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) {
2897
0
    return llvm::createStringError(
2898
0
        llvm::inconvertibleErrorCode(),
2899
0
        llvm::formatv("{0} does not support reading memory tags",
2900
0
                      GetPluginName()));
2901
0
  }
2902
2903
  /// Does the final operation to write memory tags. E.g. sending a GDB packet.
2904
  /// It assumes that WriteMemoryTags has checked that memory tagging is enabled
2905
  /// and has packed the tag data.
2906
  ///
2907
  /// \param[in] addr
2908
  ///    Start of address range to write memory tags for.
2909
  ///
2910
  /// \param[in] len
2911
  ///    Length of the memory range to write tags for (in bytes).
2912
  ///
2913
  /// \param[in] type
2914
  ///    Type of tags to read (get this from a MemoryTagManager)
2915
  ///
2916
  /// \param[in] tags
2917
  ///    Packed tags to be written.
2918
  ///
2919
  /// \return
2920
  ///     Status telling you whether the write succeeded.
2921
  virtual Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type,
2922
1
                                   const std::vector<uint8_t> &tags) {
2923
1
    Status status;
2924
1
    status.SetErrorStringWithFormatv("{0} does not support writing memory tags",
2925
1
                                     GetPluginName());
2926
1
    return status;
2927
1
  }
2928
2929
  // Type definitions
2930
  typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
2931
      LanguageRuntimeCollection;
2932
2933
  struct PreResumeCallbackAndBaton {
2934
    bool (*callback)(void *);
2935
    void *baton;
2936
    PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
2937
                              void *in_baton)
2938
243
        : callback(in_callback), baton(in_baton) {}
2939
108
    bool operator== (const PreResumeCallbackAndBaton &rhs) {
2940
108
      return callback == rhs.callback && baton == rhs.baton;
2941
108
    }
2942
  };
2943
2944
  // Member variables
2945
  std::weak_ptr<Target> m_target_wp; ///< The target that owns this process.
2946
  lldb::pid_t m_pid = LLDB_INVALID_PROCESS_ID;
2947
  ThreadSafeValue<lldb::StateType> m_public_state;
2948
  ThreadSafeValue<lldb::StateType>
2949
      m_private_state;                     // The actual state of our process
2950
  Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
2951
                                           // changed events into the private
2952
                                           // state thread's listener.
2953
  Broadcaster m_private_state_control_broadcaster; // This is the control
2954
                                                   // broadcaster, used to
2955
                                                   // pause, resume & stop the
2956
                                                   // private state thread.
2957
  lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
2958
                                                // private state thread.
2959
  HostThread m_private_state_thread; ///< Thread ID for the thread that watches
2960
                                     ///internal state events
2961
  ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
2962
                         ///other alterations.
2963
  uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
2964
                                ///created gets a unique integer ID that
2965
                                ///increments with each new instance
2966
  uint32_t m_thread_index_id;   ///< Each thread is created with a 1 based index
2967
                                ///that won't get re-used.
2968
  std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
2969
  int m_exit_status; ///< The exit status of the process, or -1 if not set.
2970
  std::string m_exit_string; ///< A textual description of why a process exited.
2971
  std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
2972
                                  ///be safely accessed from multiple threads
2973
  std::recursive_mutex m_thread_mutex;
2974
  ThreadList m_thread_list_real; ///< The threads for this process as are known
2975
                                 ///to the protocol we are debugging with
2976
  ThreadList m_thread_list; ///< The threads for this process as the user will
2977
                            ///see them. This is usually the same as
2978
  ///< m_thread_list_real, but might be different if there is an OS plug-in
2979
  ///creating memory threads
2980
  ThreadPlanStackMap m_thread_plans; ///< This is the list of thread plans for
2981
                                     /// threads in m_thread_list, as well as
2982
                                     /// threads we knew existed, but haven't
2983
                                     /// determined that they have died yet.
2984
  ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
2985
                                     ///generated, cleared on natural stops
2986
  uint32_t m_extended_thread_stop_id; ///< The natural stop id when
2987
                                      ///extended_thread_list was last updated
2988
  QueueList
2989
      m_queue_list; ///< The list of libdispatch queues at a given stop point
2990
  uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
2991
                                 ///last fetched
2992
  std::vector<Notifications> m_notifications; ///< The list of notifications
2993
                                              ///that this process can deliver.
2994
  std::vector<lldb::addr_t> m_image_tokens;
2995
  BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
2996
                                             ///locations we intend to insert in
2997
                                             ///the target.
2998
  lldb::DynamicLoaderUP m_dyld_up;
2999
  lldb::JITLoaderListUP m_jit_loaders_up;
3000
  lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up; ///< The functions used
3001
                                                         /// by the expression
3002
                                                         /// parser to validate
3003
                                                         /// data that
3004
                                                         /// expressions use.
3005
  lldb::OperatingSystemUP m_os_up;
3006
  lldb::SystemRuntimeUP m_system_runtime_up;
3007
  lldb::UnixSignalsSP
3008
      m_unix_signals_sp; /// This is the current signal set for this process.
3009
  lldb::ABISP m_abi_sp;
3010
  lldb::IOHandlerSP m_process_input_reader;
3011
  mutable std::mutex m_process_input_reader_mutex;
3012
  ThreadedCommunication m_stdio_communication;
3013
  std::recursive_mutex m_stdio_communication_mutex;
3014
  bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3015
                        /// server
3016
  std::string m_stdout_data;
3017
  std::string m_stderr_data;
3018
  std::recursive_mutex m_profile_data_comm_mutex;
3019
  std::vector<std::string> m_profile_data;
3020
  Predicate<uint32_t> m_iohandler_sync;
3021
  MemoryCache m_memory_cache;
3022
  AllocatedMemoryCache m_allocated_memory_cache;
3023
  bool m_should_detach; /// Should we detach if the process object goes away
3024
                        /// with an explicit call to Kill or Detach?
3025
  LanguageRuntimeCollection m_language_runtimes;
3026
  std::recursive_mutex m_language_runtimes_mutex;
3027
  InstrumentationRuntimeCollection m_instrumentation_runtimes;
3028
  std::unique_ptr<NextEventAction> m_next_event_action_up;
3029
  std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3030
  ProcessRunLock m_public_run_lock;
3031
  ProcessRunLock m_private_run_lock;
3032
  bool m_currently_handling_do_on_removals;
3033
  bool m_resume_requested; // If m_currently_handling_event or
3034
                           // m_currently_handling_do_on_removals are true,
3035
                           // Resume will only request a resume, using this
3036
                           // flag to check.
3037
3038
  /// This is set at the beginning of Process::Finalize() to stop functions
3039
  /// from looking up or creating things during or after a finalize call.
3040
  std::atomic<bool> m_finalizing;
3041
3042
  /// Mask for code an data addresses. The default value (0) means no mask is
3043
  /// set.  The bits set to 1 indicate bits that are NOT significant for
3044
  /// addressing.
3045
  /// The highmem versions are for targets where we may have different masks
3046
  /// for low memory versus high memory addresses.
3047
  /// @{
3048
  lldb::addr_t m_code_address_mask = 0;
3049
  lldb::addr_t m_data_address_mask = 0;
3050
  lldb::addr_t m_highmem_code_address_mask = 0;
3051
  lldb::addr_t m_highmem_data_address_mask = 0;
3052
  /// @}
3053
3054
  bool m_clear_thread_plans_on_stop;
3055
  bool m_force_next_event_delivery;
3056
  lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3057
                                          /// coalescing in
3058
                                          /// ShouldBroadcastEvent.
3059
  std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3060
  bool m_destroy_in_process;
3061
  bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3062
                                       // don't support the ability to modify
3063
                                       // the stack.
3064
  std::mutex m_run_thread_plan_lock;
3065
  llvm::StringMap<lldb::StructuredDataPluginSP> m_structured_data_plugin_map;
3066
3067
  enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3068
3069
  std::unique_ptr<UtilityFunction> m_dlopen_utility_func_up;
3070
  llvm::once_flag m_dlopen_utility_func_flag_once;
3071
3072
  /// Per process source file cache.
3073
  SourceManager::SourceFileCache m_source_file_cache;
3074
3075
  size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3076
                                           uint8_t *buf) const;
3077
3078
  void SynchronouslyNotifyStateChanged(lldb::StateType state);
3079
3080
  void SetPublicState(lldb::StateType new_state, bool restarted);
3081
3082
  void SetPrivateState(lldb::StateType state);
3083
3084
  bool StartPrivateStateThread(bool is_secondary_thread = false);
3085
3086
  void StopPrivateStateThread();
3087
3088
  void PausePrivateStateThread();
3089
3090
  void ResumePrivateStateThread();
3091
3092
private:
3093
  // The starts up the private state thread that will watch for events from the
3094
  // debugee. Pass true for is_secondary_thread in the case where you have to
3095
  // temporarily spin up a secondary state thread to handle events from a hand-
3096
  // called function on the primary private state thread.
3097
3098
  lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3099
3100
protected:
3101
  void HandlePrivateEvent(lldb::EventSP &event_sp);
3102
3103
  Status HaltPrivate();
3104
3105
  lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3106
                                            const Timeout<std::micro> &timeout);
3107
3108
  // This waits for both the state change broadcaster, and the control
3109
  // broadcaster. If control_only, it only waits for the control broadcaster.
3110
3111
  bool GetEventsPrivate(lldb::EventSP &event_sp,
3112
                        const Timeout<std::micro> &timeout, bool control_only);
3113
3114
  lldb::StateType
3115
  GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3116
                               const Timeout<std::micro> &timeout);
3117
3118
  size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3119
                            Status &error);
3120
3121
  void AppendSTDOUT(const char *s, size_t len);
3122
3123
  void AppendSTDERR(const char *s, size_t len);
3124
3125
  void BroadcastAsyncProfileData(const std::string &one_profile_data);
3126
3127
  static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3128
                                           size_t src_len);
3129
3130
  bool PushProcessIOHandler();
3131
3132
  bool PopProcessIOHandler();
3133
3134
  bool ProcessIOHandlerIsActive();
3135
3136
1.41k
  bool ProcessIOHandlerExists() const {
3137
1.41k
    std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3138
1.41k
    return static_cast<bool>(m_process_input_reader);
3139
1.41k
  }
3140
3141
  Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3142
3143
  virtual Status UpdateAutomaticSignalFiltering();
3144
3145
  void LoadOperatingSystemPlugin(bool flush);
3146
3147
private:
3148
  Status DestroyImpl(bool force_kill);
3149
3150
  /// This is the part of the event handling that for a process event. It
3151
  /// decides what to do with the event and returns true if the event needs to
3152
  /// be propagated to the user, and false otherwise. If the event is not
3153
  /// propagated, this call will most likely set the target to executing
3154
  /// again. There is only one place where this call should be called,
3155
  /// HandlePrivateEvent. Don't call it from anywhere else...
3156
  ///
3157
  /// \param[in] event_ptr
3158
  ///     This is the event we are handling.
3159
  ///
3160
  /// \return
3161
  ///     Returns \b true if the event should be reported to the
3162
  ///     user, \b false otherwise.
3163
  bool ShouldBroadcastEvent(Event *event_ptr);
3164
3165
  void ControlPrivateStateThread(uint32_t signal);
3166
3167
  Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state,
3168
                       lldb::EventSP &event_sp);
3169
3170
  Process(const Process &) = delete;
3171
  const Process &operator=(const Process &) = delete;
3172
};
3173
3174
/// RAII guard that should be acquired when an utility function is called within
3175
/// a given process.
3176
class UtilityFunctionScope {
3177
  Process *m_process;
3178
3179
public:
3180
2.97k
  UtilityFunctionScope(Process *p) : m_process(p) {
3181
2.97k
    if (m_process)
3182
1.85k
      m_process->SetRunningUtilityFunction(true);
3183
2.97k
  }
3184
2.97k
  ~UtilityFunctionScope() {
3185
2.97k
    if (m_process)
3186
1.85k
      m_process->SetRunningUtilityFunction(false);
3187
2.97k
  }
3188
};
3189
3190
} // namespace lldb_private
3191
3192
#endif // LLDB_TARGET_PROCESS_H