Coverage Report

Created: 2022-01-18 06:27

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