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