LLDB mainline
Process.h
Go to the documentation of this file.
1//===-- Process.h -----------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLDB_TARGET_PROCESS_H
10#define LLDB_TARGET_PROCESS_H
11
12#include "lldb/Host/Config.h"
13
14#include <climits>
15
16#include <chrono>
17#include <list>
18#include <memory>
19#include <mutex>
20#include <optional>
21#include <string>
22#include <unordered_set>
23#include <vector>
24
42#include "lldb/Target/Memory.h"
48#include "lldb/Target/Trace.h"
52#include "lldb/Utility/Args.h"
54#include "lldb/Utility/Event.h"
56#include "lldb/Utility/Locked.h"
58#include "lldb/Utility/Policy.h"
61#include "lldb/Utility/Status.h"
66#include "lldb/lldb-private.h"
67
68#include "llvm/ADT/AddressRanges.h"
69#include "llvm/ADT/ArrayRef.h"
70#include "llvm/Support/Error.h"
71#include "llvm/Support/Threading.h"
72#include "llvm/Support/VersionTuple.h"
73
74namespace lldb_private {
75
76template <typename B, typename S> struct Range;
77
82
84public:
85 // Pass nullptr for "process" if the ProcessProperties are to be the global
86 // copy
88
90
91 bool GetDisableMemoryCache() const;
92#ifndef NDEBUG
93 bool GetVerifyMemoryReads() const;
94#endif
95 uint64_t GetMemoryCacheLineSize() const;
97 void SetExtraStartupCommands(const Args &args);
99 uint32_t GetVirtualAddressableBits() const;
100 void SetVirtualAddressableBits(uint32_t bits);
101 uint32_t GetHighmemVirtualAddressableBits() const;
104 void SetPythonOSPluginPath(const FileSpec &file);
106 void SetIgnoreBreakpointsInExpressions(bool ignore);
108 void SetUnwindOnErrorInExpressions(bool ignore);
109 bool GetStopOnSharedLibraryEvents() const;
110 void SetStopOnSharedLibraryEvents(bool stop);
112 void SetDisableLangRuntimeUnwindPlans(bool disable);
114 bool GetDetachKeepsStopped() const;
115 void SetDetachKeepsStopped(bool keep_stopped);
116 bool GetWarningsOptimization() const;
118 bool GetStopOnExec() const;
119 std::chrono::seconds GetUtilityExpressionTimeout() const;
120 std::chrono::seconds GetInterruptTimeout() const;
121 bool GetOSPluginReportsAllThreads() const;
122 void SetOSPluginReportsAllThreads(bool does_report);
123 bool GetSteppingRunsAllThreads() const;
126 bool TrackMemoryCacheChanges() const;
127 bool GetUseDelayedBreakpoints() const;
128
129protected:
130 Process *m_process; // Can be nullptr for global ProcessProperties
131 std::unique_ptr<ProcessExperimentalProperties> m_experimental_properties_up;
132
133private:
135};
136
137// ProcessAttachInfo
138//
139// Describes any information that is required to attach to a process.
140
142public:
143 ProcessAttachInfo() = default;
144
146 ProcessInfo::operator=(launch_info);
148 SetResumeCount(launch_info.GetResumeCount());
149 m_detach_on_error = launch_info.GetDetachOnError();
150 }
151
152 bool GetWaitForLaunch() const { return m_wait_for_launch; }
153
155
156 bool GetAsync() const { return m_async; }
157
158 void SetAsync(bool b) { m_async = b; }
159
160 bool GetIgnoreExisting() const { return m_ignore_existing; }
161
163
165
167
168 uint32_t GetResumeCount() const { return m_resume_count; }
169
170 void SetResumeCount(uint32_t c) { m_resume_count = c; }
171
172 llvm::StringRef GetProcessPluginName() const {
173 return llvm::StringRef(m_plugin_name);
174 }
175
176 void SetProcessPluginName(llvm::StringRef plugin) {
177 m_plugin_name = std::string(plugin);
178 }
179
180 void Clear() {
182 m_plugin_name.clear();
183 m_resume_count = 0;
184 m_wait_for_launch = false;
185 m_ignore_existing = true;
187 }
188
189 bool ProcessInfoSpecified() const {
190 if (GetExecutableFile())
191 return true;
193 return true;
195 return true;
196 return false;
197 }
198
199 bool GetDetachOnError() const { return m_detach_on_error; }
200
201 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
202
204
205protected:
206 std::string m_plugin_name;
207 uint32_t m_resume_count = 0; // How many times do we resume after launching
208 bool m_wait_for_launch = false;
209 bool m_ignore_existing = true;
210 bool m_continue_once_attached = false; // Supports the use-case scenario of
211 // immediately continuing the process
212 // once attached.
214 true; // If we are debugging remotely, instruct the stub to
215 // detach rather than killing the target on error.
216 bool m_async =
217 false; // Use an async attach where we start the attach and return
218 // immediately (used by GUI programs with --waitfor so they can
219 // call SBProcess::Stop() to cancel attach)
220};
221
222// This class tracks the Modification state of the process. Things that can
223// currently modify the program are running the program (which will up the
224// StopID) and writing memory (which will up the MemoryID.)
225// FIXME: Should we also include modification of register states?
226
228 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
229
230public:
231 ProcessModID() = default;
232
235
237 if (this != &rhs) {
238 m_stop_id = rhs.m_stop_id;
240 }
241 return *this;
242 }
243
244 ~ProcessModID() = default;
245
246 uint32_t BumpStopID() {
247 const uint32_t prev_stop_id = m_stop_id++;
250 return prev_stop_id;
251 }
252
254
260
263 }
264
265 uint32_t GetStopID() const { return m_stop_id; }
266 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
267 uint32_t GetMemoryID() const { return m_memory_id; }
268 uint32_t GetResumeID() const { return m_resume_id; }
272
273 bool MemoryIDEqual(const ProcessModID &compare) const {
274 return m_memory_id == compare.m_memory_id;
275 }
276
277 bool StopIDEqual(const ProcessModID &compare) const {
278 return m_stop_id == compare.m_stop_id;
279 }
280
282
283 bool IsValid() const { return m_stop_id != UINT32_MAX; }
284
286 // If we haven't yet resumed the target, then it can't be for a user
287 // expression...
288 if (m_resume_id == 0)
289 return false;
290
292 }
293
294 bool IsRunningExpression() const {
295 // Don't return true if we are no longer running an expression:
297 return true;
298 return false;
299 }
300
302 if (on)
304 else
306 }
307
309 if (on)
311 else {
312 assert(m_running_utility_function > 0 &&
313 "Called SetRunningUtilityFunction(false) without calling "
314 "SetRunningUtilityFunction(true) before?");
316 }
317 }
318
320 m_last_natural_stop_event = std::move(event_sp);
321 }
322
323 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
324 if (stop_id == m_last_natural_stop_id)
326 return lldb::EventSP();
327 }
328
329 void Dump(Stream &stream) const {
330 stream.Format("ProcessModID:\n"
331 " m_stop_id: {0}\n m_last_natural_stop_id: {1}\n"
332 " m_resume_id: {2}\n m_memory_id: {3}\n"
333 " m_last_user_expression_resume: {4}\n"
334 " m_running_user_expression: {5}\n"
335 " m_running_utility_function: {6}\n",
339 }
340
341private:
342 uint32_t m_stop_id = 0;
344 uint32_t m_resume_id = 0;
345 uint32_t m_memory_id = 0;
350};
351
352inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
353 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
354 return true;
355 else
356 return false;
357}
358
359inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
360 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
361}
362
363/// \class Process Process.h "lldb/Target/Process.h"
364/// A plug-in interface definition class for debugging a process.
365class Process : public std::enable_shared_from_this<Process>,
366 public ProcessProperties,
367 public Broadcaster,
369 public PluginInterface {
370 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
371 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
372 friend class DynamicLoader; // For LoadOperatingSystemPlugin
373 friend class ProcessEventData;
374 friend class StopInfo;
375 friend class Target;
376 friend class ThreadList;
377 friend class MemoryCache;
379
380public:
381 /// Broadcaster event bits definitions.
382 enum {
389 };
390 // This is all the event bits the public process broadcaster broadcasts.
391 // The process shadow listener signs up for all these bits...
392 static constexpr int g_all_event_bits =
396
397 enum {
401 };
402
404 // We use a read/write lock to allow on or more clients to access the process
405 // state while the process is stopped (reader). We lock the write lock to
406 // control access to the process while it is running (readers, or clients
407 // that want the process stopped can block waiting for the process to stop,
408 // or just try to lock it to see if they can immediately access the stopped
409 // process. If the try read lock fails, then the process is running.
411
412 // These two functions fill out the Broadcaster interface:
413
414 static llvm::StringRef GetStaticBroadcasterClass();
415
416 static constexpr llvm::StringRef AttachSynchronousHijackListenerName =
417 "lldb.internal.Process.AttachSynchronous.hijack";
418 static constexpr llvm::StringRef LaunchSynchronousHijackListenerName =
419 "lldb.internal.Process.LaunchSynchronous.hijack";
420 static constexpr llvm::StringRef ResumeSynchronousHijackListenerName =
421 "lldb.internal.Process.ResumeSynchronous.hijack";
422
423 llvm::StringRef GetBroadcasterClass() const override {
425 }
426
427/// A notification structure that can be used by clients to listen
428/// for changes in a process's lifetime.
429///
430/// \see RegisterNotificationCallbacks (const Notifications&) @see
431/// UnregisterNotificationCallbacks (const Notifications&)
432 typedef struct {
433 void *baton;
434 void (*initialize)(void *baton, Process *process);
435 void (*process_state_changed)(void *baton, Process *process,
436 lldb::StateType state);
438
440 friend class Process;
441
442 public:
444 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
445
447
448 static llvm::StringRef GetFlavorString();
449
450 llvm::StringRef GetFlavor() const override;
451
452 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
453
454 lldb::StateType GetState() const { return m_state; }
455 bool GetRestarted() const { return m_restarted; }
456
457 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
458
459 const char *GetRestartedReasonAtIndex(size_t idx) {
460 return ((idx < m_restarted_reasons.size())
461 ? m_restarted_reasons[idx].c_str()
462 : nullptr);
463 }
464
465 bool GetInterrupted() const { return m_interrupted; }
466
467 void Dump(Stream *s) const override;
468
469 virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo);
470
471 void DoOnRemoval(Event *event_ptr) override;
472
473 static const Process::ProcessEventData *
474 GetEventDataFromEvent(const Event *event_ptr);
475
476 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
477
478 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
479
480 static bool GetRestartedFromEvent(const Event *event_ptr);
481
482 static size_t GetNumRestartedReasons(const Event *event_ptr);
483
484 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
485 size_t idx);
486
487 static void AddRestartedReason(Event *event_ptr, const char *reason);
488
489 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
490
491 static bool GetInterruptedFromEvent(const Event *event_ptr);
492
493 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
494
495 static bool SetUpdateStateOnRemoval(Event *event_ptr);
496
497 private:
498 bool ForwardEventToPendingListeners(Event *event_ptr) override;
499
501
502 void SetRestarted(bool new_value) { m_restarted = new_value; }
503
504 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
505
506 void AddRestartedReason(const char *reason) {
507 m_restarted_reasons.push_back(reason);
508 }
509
512 std::vector<std::string> m_restarted_reasons;
513 bool m_restarted = false; // For "eStateStopped" events, this is true if the
514 // target was automatically restarted.
516 bool m_interrupted = false;
517
520 };
521
522 /// Destructor.
523 ///
524 /// The destructor is virtual since this class is designed to be inherited
525 /// from by the plug-in instance.
526 ~Process() override;
527
528 static void SettingsInitialize();
529
530 static void SettingsTerminate();
531
533
534 /// Find a Process plug-in that can debug \a module using the currently
535 /// selected architecture.
536 ///
537 /// Scans all loaded plug-in interfaces that implement versions of the
538 /// Process plug-in interface and returns the first instance that can debug
539 /// the file.
540 ///
541 /// \see Process::CanDebug ()
543 llvm::StringRef plugin_name,
544 lldb::ListenerSP listener_sp,
545 const FileSpec *crash_file_path,
546 bool can_connect);
547
549
550 uint32_t GetAddressByteSize() const;
551
552 /// Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is
553 /// no known pid.
554 lldb::pid_t GetID() const { return m_pid; }
555
556 /// Sets the stored pid.
557 ///
558 /// This does not change the pid of underlying process.
559 void SetID(lldb::pid_t new_pid) { m_pid = new_pid; }
560
561 uint32_t GetUniqueID() const { return m_process_unique_id; }
562
563 /// Check if a plug-in instance can debug the file in \a module.
564 ///
565 /// Each plug-in is given a chance to say whether it can debug the file in
566 /// \a module. If the Process plug-in instance can debug a file on the
567 /// current system, it should return \b true.
568 ///
569 /// \return
570 /// Returns \b true if this Process plug-in instance can
571 /// debug the executable, \b false otherwise.
572 virtual bool CanDebug(lldb::TargetSP target,
573 bool plugin_specified_by_name) = 0;
574
575 /// This object is about to be destroyed, do any necessary cleanup.
576 ///
577 /// Subclasses that override this method should always call this superclass
578 /// method.
579 /// If you are running Finalize in your Process subclass Destructor, pass
580 /// \b true. If we are in the destructor, shared_from_this will no longer
581 /// work, so we have to avoid doing anything that might trigger that.
582 virtual void Finalize(bool destructing);
583
584 /// Return whether this object is valid (i.e. has not been finalized.)
585 ///
586 /// \return
587 /// Returns \b true if this Process has not been finalized
588 /// and \b false otherwise.
589 bool IsValid() const { return !m_finalizing; }
590
591 /// Return a multi-word command object that can be used to expose plug-in
592 /// specific commands.
593 ///
594 /// This object will be used to resolve plug-in commands and can be
595 /// triggered by a call to:
596 ///
597 /// (lldb) process command <args>
598 ///
599 /// \return
600 /// A CommandObject which can be one of the concrete subclasses
601 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
602 /// or CommandObjectMultiword.
603 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
604
605 /// The underlying plugin might store the low-level communication history for
606 /// this session. Dump it into the provided stream.
607 virtual void DumpPluginHistory(Stream &s) {}
608
609 /// Launch a new process.
610 ///
611 /// Launch a new process by spawning a new process using the target object's
612 /// executable module's file as the file to launch.
613 ///
614 /// This function is not meant to be overridden by Process subclasses. It
615 /// will first call Process::WillLaunch (Module *) and if that returns \b
616 /// true, Process::DoLaunch (Module*, char const *[],char const *[],const
617 /// char *,const char *, const char *) will be called to actually do the
618 /// launching. If DoLaunch returns \b true, then Process::DidLaunch() will
619 /// be called.
620 ///
621 /// \param[in] launch_info
622 /// Details regarding the environment, STDIN/STDOUT/STDERR
623 /// redirection, working path, etc. related to the requested launch.
624 ///
625 /// \return
626 /// An error object. Call GetID() to get the process ID if
627 /// the error object is success.
628 virtual Status Launch(ProcessLaunchInfo &launch_info);
629
630 virtual Status LoadCore();
631
632 virtual Status DoLoadCore() {
634 "error: {0} does not support loading core files.", GetPluginName());
635 }
636
637 /// The "ShadowListener" for a process is just an ordinary Listener that
638 /// listens for all the Process event bits. It's convenient because you can
639 /// specify it in the LaunchInfo or AttachInfo, so it will get events from
640 /// the very start of the process.
641 void SetShadowListener(lldb::ListenerSP shadow_listener_sp) {
642 if (shadow_listener_sp)
643 AddListener(shadow_listener_sp, g_all_event_bits);
644 }
645
646 // FUTURE WORK: GetLoadImageUtilityFunction are the first use we've
647 // had of having other plugins cache data in the Process. This is handy for
648 // long-living plugins - like the Platform - which manage interactions whose
649 // lifetime is governed by the Process lifetime. If we find we need to do
650 // this more often, we should construct a general solution to the problem.
651 // The consensus suggestion was that we have a token based registry in the
652 // Process. Some undecided questions are (1) who manages the tokens. It's
653 // probably best that you add the element and get back a token that
654 // represents it. That will avoid collisions. But there may be some utility
655 // in the registerer controlling the token? (2) whether the thing added
656 // should be simply owned by Process, and just go away when it does (3)
657 // whether the registree should be notified of the Process' demise.
658 //
659 // We are postponing designing this till we have at least a second use case.
660 /// Get the cached UtilityFunction that assists in loading binary images
661 /// into the process.
662 ///
663 /// \param[in] platform
664 /// The platform fetching the UtilityFunction.
665 /// \param[in] factory
666 /// A function that will be called only once per-process in a
667 /// thread-safe way to create the UtilityFunction if it has not
668 /// been initialized yet.
669 ///
670 /// \return
671 /// The cached utility function, or an Error if the platform is not
672 /// the same as the target's platform, or if it could not be created.
673 llvm::Expected<UtilityFunction &> GetLoadImageUtilityFunction(
674 Platform *platform,
675 llvm::function_ref<llvm::Expected<std::unique_ptr<UtilityFunction>>()>
676 factory);
677
678 /// Get the dynamic loader plug-in for this process.
679 ///
680 /// The default action is to let the DynamicLoader plug-ins check the main
681 /// executable and the DynamicLoader will select itself automatically.
682 /// Subclasses can override this if inspecting the executable is not
683 /// desired, or if Process subclasses can only use a specific DynamicLoader
684 /// plug-in.
686
688
689 // Returns AUXV structure found in many ELF-based environments.
690 //
691 // The default action is to return an empty data buffer.
692 //
693 // \return
694 // A data extractor containing the contents of the AUXV data.
695 virtual DataExtractor GetAuxvData();
696
697 /// Sometimes processes know how to retrieve and load shared libraries. This
698 /// is normally done by DynamicLoader plug-ins, but sometimes the connection
699 /// to the process allows retrieving this information. The dynamic loader
700 /// plug-ins can use this function if they can't determine the current
701 /// shared library load state.
702 ///
703 /// \return
704 /// A status object indicating if the operation was sucessful or not.
705 virtual llvm::Error LoadModules() {
706 return llvm::createStringError("Not implemented.");
707 }
708
709 /// Query remote GDBServer for a detailed loaded library list
710 /// \return
711 /// The list of modules currently loaded by the process, or an error.
712 virtual llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() {
713 return llvm::createStringError(llvm::inconvertibleErrorCode(),
714 "Not implemented");
715 }
716
717 /// Save core dump into the specified file.
718 ///
719 /// \param[in] outfile
720 /// Path to store core dump in.
721 ///
722 /// \return
723 /// true if saved successfully, false if saving the core dump
724 /// is not supported by the plugin, error otherwise.
725 virtual llvm::Expected<bool> SaveCore(llvm::StringRef outfile);
726
727 /// Helper function for Process::SaveCore(...) that calculates the address
728 /// ranges that should be saved. This allows all core file plug-ins to save
729 /// consistent memory ranges given a \a core_style.
731 CoreFileMemoryRanges &ranges);
732
733 /// Helper function for Process::SaveCore(...) that calculates the thread list
734 /// based upon options set within a given \a core_options object.
735 /// \note If there is no thread list defined, all threads will be saved.
736 std::vector<lldb::ThreadSP>
737 CalculateCoreFileThreadList(const SaveCoreOptions &core_options);
738
739protected:
740 virtual JITLoaderList &GetJITLoaders();
741
742public:
743 /// Get the system architecture for this process.
744 virtual ArchSpec GetSystemArchitecture() { return {}; }
745
746 /// Get the system runtime plug-in for this process.
747 ///
748 /// \return
749 /// Returns a pointer to the SystemRuntime plugin for this Process
750 /// if one is available. Else returns nullptr.
752
753 /// Attach to an existing process using the process attach info.
754 ///
755 /// This function is not meant to be overridden by Process subclasses. It
756 /// will first call WillAttach (lldb::pid_t) or WillAttach (const char *),
757 /// and if that returns \b true, DoAttach (lldb::pid_t) or DoAttach (const
758 /// char *) will be called to actually do the attach. If DoAttach returns \b
759 /// true, then Process::DidAttach() will be called.
760 ///
761 /// \param[in] attach_info
762 /// The process attach info.
763 ///
764 /// \return
765 /// Returns \a pid if attaching was successful, or
766 /// LLDB_INVALID_PROCESS_ID if attaching fails.
767 virtual Status Attach(ProcessAttachInfo &attach_info);
768
769 /// Attach to a remote system via a URL
770 ///
771 /// \param[in] remote_url
772 /// The URL format that we are connecting to.
773 ///
774 /// \return
775 /// Returns an error object.
776 virtual Status ConnectRemote(llvm::StringRef remote_url);
777
778 bool GetShouldDetach() const { return m_should_detach; }
779
780 void SetShouldDetach(bool b) { m_should_detach = b; }
781
782 /// Get the image vector for the current process.
783 ///
784 /// \return
785 /// The constant reference to the member m_image_tokens.
786 const std::vector<lldb::addr_t>& GetImageTokens() { return m_image_tokens; }
787
788 /// Get the image information address for the current process.
789 ///
790 /// Some runtimes have system functions that can help dynamic loaders locate
791 /// the dynamic loader information needed to observe shared libraries being
792 /// loaded or unloaded. This function is in the Process interface (as
793 /// opposed to the DynamicLoader interface) to ensure that remote debugging
794 /// can take advantage of this functionality.
795 ///
796 /// \return
797 /// The address of the dynamic loader information, or
798 /// LLDB_INVALID_ADDRESS if this is not supported by this
799 /// interface.
801
802 /// Called when the process is about to broadcast a public stop.
803 ///
804 /// There are public and private stops. Private stops are when the process
805 /// is doing things like stepping and the client doesn't need to know about
806 /// starts and stop that implement a thread plan. Single stepping over a
807 /// source line in code might end up being implemented by one or more
808 /// process starts and stops. Public stops are when clients will be notified
809 /// that the process is stopped. These events typically trigger UI updates
810 /// (thread stack frames to be displayed, variables to be displayed, and
811 /// more). This function can be overriden and allows process subclasses to
812 /// do something before the eBroadcastBitStateChanged event is sent to
813 /// public clients.
814 virtual void WillPublicStop() {}
815
816/// Register for process and thread notifications.
817///
818/// Clients can register notification callbacks by filling out a
819/// Process::Notifications structure and calling this function.
820///
821/// \param[in] callbacks
822/// A structure that contains the notification baton and
823/// callback functions.
824///
825/// \see Process::Notifications
827
828/// Unregister for process and thread notifications.
829///
830/// Clients can unregister notification callbacks by passing a copy of the
831/// original baton and callbacks in \a callbacks.
832///
833/// \param[in] callbacks
834/// A structure that contains the notification baton and
835/// callback functions.
836///
837/// \return
838/// Returns \b true if the notification callbacks were
839/// successfully removed from the process, \b false otherwise.
840///
841/// \see Process::Notifications
843
844 //==================================================================
845 // Built in Process Control functions
846 //==================================================================
847 /// Resumes all of a process's threads as configured using the Thread run
848 /// control functions.
849 ///
850 /// Threads for a process should be updated with one of the run control
851 /// actions (resume, step, or suspend) that they should take when the
852 /// process is resumed. If no run control action is given to a thread it
853 /// will be resumed by default.
854 ///
855 /// This function is not meant to be overridden by Process subclasses. This
856 /// function will take care of disabling any breakpoints that threads may be
857 /// stopped at, single stepping, and re-enabling breakpoints, and enabling
858 /// the basic flow control that the plug-in instances need not worry about.
859 ///
860 /// N.B. This function also sets the Write side of the Run Lock, which is
861 /// unset when the corresponding stop event is pulled off the Public Event
862 /// Queue. If you need to resume the process without setting the Run Lock,
863 /// use PrivateResume (though you should only do that from inside the
864 /// Process class.
865 ///
866 /// \return
867 /// Returns an error object.
868 ///
869 /// \see Thread:Resume()
870 /// \see Thread:Step()
871 /// \see Thread:Suspend()
872 Status Resume();
873
874 /// Resume a process, and wait for it to stop.
876
877 /// Halts a running process.
878 ///
879 /// This function is not meant to be overridden by Process subclasses. If
880 /// the process is successfully halted, a eStateStopped process event with
881 /// GetInterrupted will be broadcast. If false, we will halt the process
882 /// with no events generated by the halt.
883 ///
884 /// \param[in] clear_thread_plans
885 /// If true, when the process stops, clear all thread plans.
886 ///
887 /// \param[in] use_run_lock
888 /// Whether to release the run lock after the stop.
889 ///
890 /// \return
891 /// Returns an error object. If the error is empty, the process is
892 /// halted.
893 /// otherwise the halt has failed.
894 Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
895
896 /// Detaches from a running or stopped process.
897 ///
898 /// This function is not meant to be overridden by Process subclasses.
899 ///
900 /// \param[in] keep_stopped
901 /// If true, don't resume the process on detach.
902 ///
903 /// \return
904 /// Returns an error object.
905 Status Detach(bool keep_stopped);
906
907 /// Kills the process and shuts down all threads that were spawned to track
908 /// and monitor the process.
909 ///
910 /// This function is not meant to be overridden by Process subclasses.
911 ///
912 /// \param[in] force_kill
913 /// Whether lldb should force a kill (instead of a detach) from
914 /// the inferior process. Normally if lldb launched a binary and
915 /// Destroy is called, lldb kills it. If lldb attached to a
916 /// running process and Destroy is called, lldb detaches. If
917 /// this behavior needs to be over-ridden, this is the bool that
918 /// can be used.
919 ///
920 /// \return
921 /// Returns an error object.
922 Status Destroy(bool force_kill);
923
924 /// Sends a process a UNIX signal \a signal.
925 ///
926 /// This function is not meant to be overridden by Process subclasses.
927 ///
928 /// \return
929 /// Returns an error object.
930 Status Signal(int signal);
931
932 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
933
935
936 //==================================================================
937 // Plug-in Process Control Overrides
938 //==================================================================
939
940 /// Called before attaching to a process.
941 ///
942 /// \return
943 /// Returns an error object.
945
946 /// Called before attaching to a process.
947 ///
948 /// Allow Process plug-ins to execute some code before attaching a process.
949 ///
950 /// \return
951 /// Returns an error object.
953 return Status();
954 }
955
956 /// Called before attaching to a process.
957 ///
958 /// \return
959 /// Returns an error object.
960 Status WillAttachToProcessWithName(const char *process_name,
961 bool wait_for_launch);
962
963 /// Called before attaching to a process.
964 ///
965 /// Allow Process plug-ins to execute some code before attaching a process.
966 ///
967 /// \return
968 /// Returns an error object.
969 virtual Status DoWillAttachToProcessWithName(const char *process_name,
970 bool wait_for_launch) {
971 return Status();
972 }
973
974 /// Attach to a remote system via a URL
975 ///
976 /// \param[in] remote_url
977 /// The URL format that we are connecting to.
978 ///
979 /// \return
980 /// Returns an error object.
981 virtual Status DoConnectRemote(llvm::StringRef remote_url) {
982 return Status::FromErrorString("remote connections are not supported");
983 }
984
985 /// Attach to an existing process using a process ID.
986 ///
987 /// \param[in] pid
988 /// The process ID that we should attempt to attach to.
989 ///
990 /// \param[in] attach_info
991 /// Information on how to do the attach. For example, GetUserID()
992 /// will return the uid to attach as.
993 ///
994 /// \return
995 /// Returns a successful Status attaching was successful, or
996 /// an appropriate (possibly platform-specific) error code if
997 /// attaching fails.
998 /// hanming : need flag
1000 const ProcessAttachInfo &attach_info) {
1002 "error: {0} does not support attaching to a process by pid",
1003 GetPluginName());
1004 }
1005
1006 /// Attach to an existing process using a partial process name.
1007 ///
1008 /// \param[in] process_name
1009 /// The name of the process to attach to.
1010 ///
1011 /// \param[in] attach_info
1012 /// Information on how to do the attach. For example, GetUserID()
1013 /// will return the uid to attach as.
1014 ///
1015 /// \return
1016 /// Returns a successful Status attaching was successful, or
1017 /// an appropriate (possibly platform-specific) error code if
1018 /// attaching fails.
1019 virtual Status
1020 DoAttachToProcessWithName(const char *process_name,
1021 const ProcessAttachInfo &attach_info) {
1022 return Status::FromErrorString("attach by name is not supported");
1023 }
1024
1025 /// Called after attaching a process.
1026 ///
1027 /// \param[in] process_arch
1028 /// If you can figure out the process architecture after attach, fill it
1029 /// in here.
1030 ///
1031 /// Allow Process plug-ins to execute some code after attaching to a
1032 /// process.
1033 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1034
1035 /// Called after a process re-execs itself.
1036 ///
1037 /// Allow Process plug-ins to execute some code after a process has exec'ed
1038 /// itself. Subclasses typically should override DoDidExec() as the
1039 /// lldb_private::Process class needs to remove its dynamic loader, runtime,
1040 /// ABI and other plug-ins, as well as unload all shared libraries.
1041 virtual void DidExec();
1042
1043 /// Subclasses of Process should implement this function if they need to do
1044 /// anything after a process exec's itself.
1045 virtual void DoDidExec() {}
1046
1047 /// Called after a reported fork.
1048 virtual void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid,
1049 bool is_expression_fork = false) {}
1050
1051 /// Called after a reported vfork.
1052 virtual void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid,
1053 bool is_expression_fork = false) {}
1054
1055 /// Called after reported vfork completion.
1056 virtual void DidVForkDone() {}
1057
1058 /// Called before launching to a process.
1059 /// \return
1060 /// Returns an error object.
1061 Status WillLaunch(Module *module);
1062
1063 /// Called before launching to a process.
1064 ///
1065 /// Allow Process plug-ins to execute some code before launching a process.
1066 ///
1067 /// \return
1068 /// Returns an error object.
1069 virtual Status DoWillLaunch(Module *module) { return Status(); }
1070
1071 /// Launch a new process.
1072 ///
1073 /// Launch a new process by spawning a new process using \a exe_module's
1074 /// file as the file to launch. Launch details are provided in \a
1075 /// launch_info.
1076 ///
1077 /// \param[in] exe_module
1078 /// The module from which to extract the file specification and
1079 /// launch.
1080 ///
1081 /// \param[in] launch_info
1082 /// Details (e.g. arguments, stdio redirection, etc.) for the
1083 /// requested launch.
1084 ///
1085 /// \return
1086 /// An Status instance indicating success or failure of the
1087 /// operation.
1088 virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1090 "error: {0} does not support launching processes", GetPluginName());
1091 }
1092
1093 /// Called after launching a process.
1094 ///
1095 /// Allow Process plug-ins to execute some code after launching a process.
1096 virtual void DidLaunch() {}
1097
1098 /// Called before resuming to a process.
1099 ///
1100 /// Allow Process plug-ins to execute some code before resuming a process.
1101 ///
1102 /// \return
1103 /// Returns an error object.
1104 virtual Status WillResume() { return Status(); }
1105
1106 /// Reports whether this process supports reverse execution.
1107 ///
1108 /// \return
1109 /// Returns true if the process supports reverse execution (at least
1110 /// under some circumstances).
1111 virtual bool SupportsReverseDirection() { return false; }
1112
1113 /// Resumes all of a process's threads as configured using the Thread run
1114 /// control functions.
1115 ///
1116 /// Threads for a process should be updated with one of the run control
1117 /// actions (resume, step, or suspend) that they should take when the
1118 /// process is resumed. If no run control action is given to a thread it
1119 /// will be resumed by default.
1120 ///
1121 /// \return
1122 /// Returns \b true if the process successfully resumes using
1123 /// the thread run control actions, \b false otherwise.
1124 ///
1125 /// \see Thread:Resume()
1126 /// \see Thread:Step()
1127 /// \see Thread:Suspend()
1129 if (direction == lldb::RunDirection::eRunForward)
1131 "{0} does not support resuming processes", GetPluginName());
1133 "{0} does not support reverse execution of processes", GetPluginName());
1134 }
1135
1136 /// Called after resuming a process.
1137 ///
1138 /// Allow Process plug-ins to execute some code after resuming a process.
1139 virtual void DidResume() {}
1140
1141 /// Called before halting to a process.
1142 ///
1143 /// Allow Process plug-ins to execute some code before halting a process.
1144 ///
1145 /// \return
1146 /// Returns an error object.
1147 virtual Status WillHalt() { return Status(); }
1148
1149 /// Halts a running process.
1150 ///
1151 /// DoHalt must produce one and only one stop StateChanged event if it
1152 /// actually stops the process. If the stop happens through some natural
1153 /// event (for instance a SIGSTOP), then forwarding that event will do.
1154 /// Otherwise, you must generate the event manually. This function is called
1155 /// from the context of the private state thread.
1156 ///
1157 /// \param[out] caused_stop
1158 /// If true, then this Halt caused the stop, otherwise, the
1159 /// process was already stopped.
1160 ///
1161 /// \return
1162 /// Returns \b true if the process successfully halts, \b false
1163 /// otherwise.
1164 virtual Status DoHalt(bool &caused_stop) {
1166 "error: {0} does not support halting processes", GetPluginName());
1167 }
1168
1169 /// Called after halting a process.
1170 ///
1171 /// Allow Process plug-ins to execute some code after halting a process.
1172 virtual void DidHalt() {}
1173
1174 /// Called before detaching from a process.
1175 ///
1176 /// Allow Process plug-ins to execute some code before detaching from a
1177 /// process.
1178 ///
1179 /// \return
1180 /// Returns an error object.
1181 virtual Status WillDetach() { return Status(); }
1182
1183 /// Detaches from a running or stopped process.
1184 ///
1185 /// \return
1186 /// Returns \b true if the process successfully detaches, \b
1187 /// false otherwise.
1188 virtual Status DoDetach(bool keep_stopped) {
1190 "error: {0} does not support detaching from processes",
1191 GetPluginName());
1192 }
1193
1194 /// Called after detaching from a process.
1195 ///
1196 /// Allow Process plug-ins to execute some code after detaching from a
1197 /// process.
1198 virtual void DidDetach() {}
1199
1200 virtual bool DetachRequiresHalt() { return false; }
1201
1202 /// Called before sending a signal to a process.
1203 ///
1204 /// Allow Process plug-ins to execute some code before sending a signal to a
1205 /// process.
1206 ///
1207 /// \return
1208 /// Returns no error if it is safe to proceed with a call to
1209 /// Process::DoSignal(int), otherwise an error describing what
1210 /// prevents the signal from being sent.
1211 virtual Status WillSignal() { return Status(); }
1212
1213 /// Sends a process a UNIX signal \a signal.
1214 ///
1215 /// \return
1216 /// Returns an error object.
1217 virtual Status DoSignal(int signal) {
1219 "error: {0} does not support sending signals to processes",
1220 GetPluginName());
1221 }
1222
1223 virtual Status WillDestroy() { return Status(); }
1224
1225 virtual Status DoDestroy() = 0;
1226
1227 virtual void DidDestroy() {}
1228
1229 virtual bool DestroyRequiresHalt() { return true; }
1230
1231 /// Called after sending a signal to a process.
1232 ///
1233 /// Allow Process plug-ins to execute some code after sending a signal to a
1234 /// process.
1235 virtual void DidSignal() {}
1236
1237 /// Currently called as part of ShouldStop.
1238 /// FIXME: Should really happen when the target stops before the
1239 /// event is taken from the queue...
1240 ///
1241 /// This callback is called as the event
1242 /// is about to be queued up to allow Process plug-ins to execute some code
1243 /// prior to clients being notified that a process was stopped. Common
1244 /// operations include updating the thread list, invalidating any thread
1245 /// state (registers, stack, etc) prior to letting the notification go out.
1246 ///
1247 virtual void RefreshStateAfterStop() = 0;
1248
1249 /// Sometimes the connection to a process can detect the host OS version
1250 /// that the process is running on. The current platform should be checked
1251 /// first in case the platform is connected, but clients can fall back onto
1252 /// this function if the platform fails to identify the host OS version. The
1253 /// platform should be checked first in case you are running a simulator
1254 /// platform that might itself be running natively, but have different
1255 /// heuristics for figuring out which OS is emulating.
1256 ///
1257 /// \return
1258 /// Returns the version tuple of the host OS. In case of failure an empty
1259 /// VersionTuple is returner.
1260 virtual llvm::VersionTuple GetHostOSVersion() { return llvm::VersionTuple(); }
1261
1262 /// \return the macCatalyst version of the host OS.
1263 virtual llvm::VersionTuple GetHostMacCatalystVersion() { return {}; }
1264
1265 /// Get the target object pointer for this module.
1266 ///
1267 /// \return
1268 /// A Target object pointer to the target that owns this
1269 /// module.
1270 Target &GetTarget() { return *m_target_wp.lock(); }
1271
1272 /// Get the const target object pointer for this module.
1273 ///
1274 /// \return
1275 /// A const Target object pointer to the target that owns this
1276 /// module.
1277 const Target &GetTarget() const { return *m_target_wp.lock(); }
1278
1279 /// Flush all data in the process.
1280 ///
1281 /// Flush the memory caches, all threads, and any other cached data in the
1282 /// process.
1283 ///
1284 /// This function can be called after a world changing event like adding a
1285 /// new symbol file, or after the process makes a large context switch (from
1286 /// boot ROM to booted into an OS).
1287 void Flush();
1288
1289 /// Get accessor for the current process state.
1290 ///
1291 /// \return
1292 /// The current state of the process.
1293 ///
1294 /// \see lldb::StateType
1296
1298 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1299 const EvaluateExpressionOptions &requested_options,
1300 DiagnosticManager &diagnostic_manager);
1301
1302 void GetStatus(Stream &ostrm, bool is_verbose = false);
1303
1304 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1305 uint32_t start_frame, uint32_t num_frames,
1306 uint32_t num_frames_with_source, bool stop_format);
1307
1308 /// Send an async interrupt request.
1309 ///
1310 /// If \a thread is specified the async interrupt stop will be attributed to
1311 /// the specified thread.
1312 ///
1313 /// \param[in] thread
1314 /// The thread the async interrupt will be attributed to.
1315 void SendAsyncInterrupt(Thread *thread = nullptr);
1316
1317 // Notify this process class that modules got loaded.
1318 //
1319 // If subclasses override this method, they must call this version before
1320 // doing anything in the subclass version of the function.
1321 virtual void ModulesDidLoad(ModuleList &module_list);
1322
1323 /// Retrieve the list of shared libraries that are loaded for this process
1324 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10, pre-
1325 /// watchOS 3 systems. The following two methods are for newer versions of
1326 /// those OSes.
1327 ///
1328 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1329 /// read all of the shared libraries out of memory over a slow communication
1330 /// channel may be too long. In that instance, the gdb-remote stub may be
1331 /// able to retrieve the necessary information about the solibs out of
1332 /// memory and return a concise summary sufficient for the DynamicLoader
1333 /// plugin.
1334 ///
1335 /// \param [in] image_list_address
1336 /// The address where the table of shared libraries is stored in memory,
1337 /// if that is appropriate for this platform. Else this may be
1338 /// passed as LLDB_INVALID_ADDRESS.
1339 ///
1340 /// \param [in] image_count
1341 /// The number of shared libraries that are present in this process, if
1342 /// that is appropriate for this platofrm Else this may be passed as
1343 /// LLDB_INVALID_ADDRESS.
1344 ///
1345 /// \return
1346 /// A StructuredDataSP object which, if non-empty, will contain the
1347 /// information the DynamicLoader needs to get the initial scan of
1348 /// solibs resolved.
1351 lldb::addr_t image_count) {
1352 return StructuredData::ObjectSP();
1353 }
1354
1355 /// Retrieve a StructuredData dictionary about all of the binaries
1356 /// loaded in the process at this time.
1357 /// A Darwin target specific behavior, only supported by debugserver,
1358 /// response will include load address, filepath, uuid, and may also
1359 /// include the fully parsed mach header and load commands.
1360 ///
1361 /// \param [in] information_level
1362 /// How much information about each binary should be returned;
1363 /// there may be performance reasons to retrieve a minimal set
1364 /// of information about all binaries, and then retrieve the
1365 /// full information for a subset of the whole group.
1366 ///
1367 /// \return
1368 /// A StructuredData object with the information that could be
1369 /// retrieved.
1374
1375 /// Retrieve a StructuredData dictionary about the binaries at
1376 /// the provided load addresses.
1377 /// A Darwin target specific behavior, only supported by debugserver,
1378 /// response will include load address, filepath, uuid, fully parsed
1379 /// mach header and load commands.
1380 ///
1381 /// \param [in] information_level
1382 /// How much information about each binary should be returned;
1383 /// there may be performance reasons to retrieve a minimal set
1384 /// of information about all binaries, and then retrieve the
1385 /// full information for a subset of the whole group.
1386 ///
1387 /// \param [in] load_addresses
1388 /// The virtual address of the start of binaries to fetch
1389 /// information.
1390 ///
1391 /// \return
1392 /// A StructuredData object with the information that could be
1393 /// retrieved..
1396 const std::vector<lldb::addr_t> &load_addresses) {
1397 return StructuredData::ObjectSP();
1398 }
1399
1400 // Get information about the library shared cache, if that exists
1401 //
1402 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1403 // return information about the library shared cache (a set of standard
1404 // libraries that are loaded at the same location for all processes on a
1405 // system) in use.
1409
1410 // Get information about the launch state of the process, if possible.
1411 //
1412 // On Darwin systems, libdyld can report on process state, most importantly
1413 // the startup stages where the system library is not yet initialized.
1416 return {};
1417 }
1418
1419 /// Print a user-visible warning about a module being built with
1420 /// optimization
1421 ///
1422 /// Prints a async warning message to the user one time per Module where a
1423 /// function is found that was compiled with optimization, per Process.
1424 ///
1425 /// \param [in] sc
1426 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1427 /// pre-computed.
1429
1430 /// Print a user-visible warning about a function written in a
1431 /// language that this version of LLDB doesn't support.
1432 ///
1433 /// \see PrintWarningOptimization
1435
1436 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1437
1438 /// Given a module spec, try to find the UUID information.
1439 ///
1440 /// \param [in,out] spec
1441 /// A module specification with as much detail as possible about the
1442 /// module for which we are trying to find a UUID. The
1443 /// ModuleSpec.m_file should be filled in. If a dynamic loader is
1444 /// calling this, the load address of the module can be filled in as
1445 /// well. Sometimes the file path for a library can be a symlink and
1446 /// the load address can help resolve the module.
1447 ///
1448 /// \return True if the UUID was added, false otherwise.
1449 virtual bool FindModuleUUID(ModuleSpec &spec);
1450
1451 /// Get the exit status for a process.
1452 ///
1453 /// \return
1454 /// The process's return code, or -1 if the current process
1455 /// state is not eStateExited.
1456 int GetExitStatus();
1457
1458 /// Get a textual description of what the process exited.
1459 ///
1460 /// \return
1461 /// The textual description of why the process exited, or nullptr
1462 /// if there is no description available.
1463 const char *GetExitDescription();
1464
1465 virtual void DidExit() {}
1466
1467 /// Get the current address mask in the Process
1468 ///
1469 /// This mask can used to set/clear non-address bits in an addr_t.
1470 ///
1471 /// \return
1472 /// The current address mask.
1473 /// Bits which are set to 1 are not used for addressing.
1474 /// An address mask of 0 means all bits are used for addressing.
1475 /// An address mask of LLDB_INVALID_ADDRESS_MASK (all 1's) means
1476 /// that no mask has been set.
1479
1480 /// The highmem masks are for targets where we may have different masks
1481 /// for low memory versus high memory addresses, and they will be left
1482 /// as LLDB_INVALID_ADDRESS_MASK normally, meaning the base masks
1483 /// should be applied to all addresses.
1486
1487 void SetCodeAddressMask(lldb::addr_t code_address_mask);
1488 void SetDataAddressMask(lldb::addr_t data_address_mask);
1489
1490 void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask);
1491 void SetHighmemDataAddressMask(lldb::addr_t data_address_mask);
1492
1493 /// Some targets might use bits in a code address to indicate a mode switch,
1494 /// ARM uses bit zero to signify a code address is thumb, so any ARM ABI
1495 /// plug-ins would strip those bits.
1496 /// Or use the high bits to authenticate a pointer value.
1499
1500 /// Use this method when you do not know, or do not care what kind of address
1501 /// you are fixing. On platforms where there would be a difference between the
1502 /// two types, it will pick the safest option.
1503 ///
1504 /// Its purpose is to signal that no specific choice was made and provide an
1505 /// alternative to randomly picking FixCode/FixData address. Which could break
1506 /// platforms where there is a difference (only Arm Thumb at this time).
1508
1509 /// Get the Modification ID of the process.
1510 ///
1511 /// \return
1512 /// The modification ID of the process.
1513 ProcessModID GetModID() const { return m_mod_id; }
1514
1515 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1516
1517 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1518
1519 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1520
1522 return m_mod_id.GetLastUserExpressionResumeID();
1523 }
1524
1525 uint32_t GetLastNaturalStopID() const {
1526 return m_mod_id.GetLastNaturalStopID();
1527 }
1528
1529 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1530 return m_mod_id.GetStopEventForStopID(stop_id);
1531 }
1532
1533 /// Set accessor for the process exit status (return code).
1534 ///
1535 /// Sometimes a child exits and the exit can be detected by global functions
1536 /// (signal handler for SIGCHLD for example). This accessor allows the exit
1537 /// status to be set from an external source.
1538 ///
1539 /// Setting this will cause a eStateExited event to be posted to the process
1540 /// event queue.
1541 ///
1542 /// \param[in] exit_status
1543 /// The value for the process's return code.
1544 ///
1545 /// \param[in] exit_string
1546 /// A StringRef containing the reason for exiting. May be empty.
1547 ///
1548 /// \return
1549 /// Returns \b false if the process was already in an exited state, \b
1550 /// true otherwise.
1551 virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string);
1552
1553 /// Check if a process is still alive.
1554 ///
1555 /// \return
1556 /// Returns \b true if the process is still valid, \b false
1557 /// otherwise.
1558 virtual bool IsAlive();
1559
1560 /// Check if a process is a live debug session, or a corefile/post-mortem.
1561 virtual bool IsLiveDebugSession() const { return true; };
1562
1563 /// Provide a way to retrieve the core dump file that is loaded for debugging.
1564 /// Only available if IsLiveDebugSession() returns false.
1565 ///
1566 /// \return
1567 /// File path to the core file.
1568 virtual FileSpec GetCoreFile() const { return {}; }
1569
1570 class CoreArgs {
1571 std::string m_cmd;
1573
1574 public:
1575 CoreArgs() = default;
1576 CoreArgs(const std::string &args, bool might_be_truncated)
1577 : m_cmd(args), m_might_be_truncated(might_be_truncated) {}
1578
1579 void Format(Stream &stream) const {
1580 if (m_cmd.empty())
1581 return;
1582 stream << "Core was generated by '" << m_cmd << "'";
1583 if (this->m_might_be_truncated)
1584 stream << " (command might be truncated)";
1585 stream << ".\n";
1586 }
1587
1588 bool empty() const { return m_cmd.empty(); }
1589
1590 Args as_args() const { return Args(m_cmd); }
1591 };
1592
1593 /// Provide arguments of a command that triggered a core dump.
1594 ///
1595 /// \return
1596 /// The arguments that created the core dump.
1597 /// If this process is a live debug session, or the core dump contained no
1598 /// arguments, returns a std::nullopt.
1599 virtual std::optional<CoreArgs> GetCoreFileArgs() { return std::nullopt; }
1600
1601 /// Before lldb detaches from a process, it warns the user that they are
1602 /// about to lose their debug session. In some cases, this warning doesn't
1603 /// need to be emitted -- for instance, with core file debugging where the
1604 /// user can reconstruct the "state" by simply re-running the debugger on
1605 /// the core file.
1606 ///
1607 /// \return
1608 /// Returns \b true if the user should be warned about detaching from
1609 /// this process.
1610 virtual bool WarnBeforeDetach() const { return true; }
1611
1612 /// Read of memory from a process.
1613 ///
1614 /// This function will read memory from the current process's address space
1615 /// and remove any traps that may have been inserted into the memory.
1616 ///
1617 /// Process subclasses implement Process::DoReadMemory(const ProcessAddress &,
1618 /// void *, size_t, Status &) instead of this function, and override
1619 /// Process::ShouldUseMemoryCache to keep their reads out of the memory cache.
1620 ///
1621 /// \param[in] process_addr
1622 /// A virtual load address that indicates where to start reading
1623 /// memory from. It does not need to be fixed: this function removes any
1624 /// non-address bits (see Process::FixAnyAddress) before the address
1625 /// reaches Process::DoReadMemory.
1626 ///
1627 /// \param[out] buf
1628 /// A byte buffer that is at least \a size bytes long that
1629 /// will receive the memory bytes.
1630 ///
1631 /// \param[in] size
1632 /// The number of bytes to read.
1633 ///
1634 /// \param[out] error
1635 /// An error that indicates the success or failure of this
1636 /// operation. If error indicates success (error.Success()),
1637 /// then the value returned can be trusted, otherwise zero
1638 /// will be returned. Any previous contents of \a error are cleared.
1639 ///
1640 /// \return
1641 /// The number of bytes that were actually read into \a buf. If
1642 /// the returned number is greater than zero, yet less than \a
1643 /// size, then this function will get called again with \a
1644 /// process_addr, \a buf, and \a size updated appropriately. Zero is
1645 /// returned in the case of an error.
1646 size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size,
1647 Status &error);
1648
1649 /// Read from multiple memory ranges and write the results into buffer.
1650 ///
1651 /// \param[in] ranges
1652 /// A collection of ranges (base address + size) to read from.
1653 ///
1654 /// \param[out] buffer
1655 /// A buffer where the read memory will be written to. It must be at least
1656 /// as long as the sum of the sizes of each range.
1657 ///
1658 /// \return
1659 /// A vector of MutableArrayRef, where each MutableArrayRef is a slice of
1660 /// the input buffer into which the memory contents were copied. The size
1661 /// of the slice indicates how many bytes were read successfully. Partial
1662 /// reads are always performed from the start of the requested range,
1663 /// never from the middle or end.
1664 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
1665 ReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
1666 llvm::MutableArrayRef<uint8_t> buffer);
1667
1668 /// Read of memory from a process.
1669 ///
1670 /// This function has the same semantics of ReadMemory except that it
1671 /// bypasses caching.
1672 ///
1673 /// \param[in] vm_addr
1674 /// A virtual load address that indicates where to start reading
1675 /// memory from.
1676 ///
1677 /// \param[out] buf
1678 /// A byte buffer that is at least \a size bytes long that
1679 /// will receive the memory bytes.
1680 ///
1681 /// \param[in] size
1682 /// The number of bytes to read.
1683 ///
1684 /// \param[out] error
1685 /// An error that indicates the success or failure of this
1686 /// operation. If error indicates success (error.Success()),
1687 /// then the value returned can be trusted, otherwise zero
1688 /// will be returned.
1689 ///
1690 /// \return
1691 /// The number of bytes that were actually read into \a buf. If
1692 /// the returned number is greater than zero, yet less than \a
1693 /// size, then this function will get called again with \a
1694 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1695 /// returned in the case of an error.
1696 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1697 Status &error);
1698
1699 /// Read a null-terminated C string from memory
1700 ///
1701 /// This function will read a cache page at a time until the null
1702 /// terminator is found. It will stop reading if the null terminator isn't
1703 /// found before reading \a cstr_max_len bytes, and the results are always
1704 /// guaranteed to be null-terminated (at most cstr_max_len - 1 bytes will be
1705 /// read).
1706 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1707 size_t cstr_max_len, Status &error);
1708
1709 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1710 Status &error);
1711
1712 llvm::SmallVector<std::optional<std::string>>
1713 ReadCStringsFromMemory(llvm::ArrayRef<lldb::addr_t> addresses);
1714
1715 /// Reads an unsigned integer of the specified byte size from process
1716 /// memory.
1717 ///
1718 /// \param[in] load_addr
1719 /// A load address of the integer to read.
1720 ///
1721 /// \param[in] byte_size
1722 /// The size in byte of the integer to read.
1723 ///
1724 /// \param[in] fail_value
1725 /// The value to return if we fail to read an integer.
1726 ///
1727 /// \param[out] error
1728 /// An error that indicates the success or failure of this
1729 /// operation. If error indicates success (error.Success()),
1730 /// then the value returned can be trusted, otherwise zero
1731 /// will be returned.
1732 ///
1733 /// \return
1734 /// The unsigned integer that was read from the process memory
1735 /// space. If the integer was smaller than a uint64_t, any
1736 /// unused upper bytes will be zero filled. If the process
1737 /// byte order differs from the host byte order, the integer
1738 /// value will be appropriately byte swapped into host byte
1739 /// order.
1741 size_t byte_size, uint64_t fail_value,
1742 Status &error);
1743
1744 /// Use Process::ReadMemoryRanges to efficiently read multiple unsigned
1745 /// integers from memory at once.
1746 llvm::SmallVector<std::optional<uint64_t>>
1747 ReadUnsignedIntegersFromMemory(llvm::ArrayRef<lldb::addr_t> addresses,
1748 unsigned byte_size);
1749
1750 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1751 int64_t fail_value, Status &error);
1752
1753 llvm::Expected<lldb::addr_t> ReadPointerFromMemory(lldb::addr_t vm_addr);
1754
1755 /// Use Process::ReadMemoryRanges to efficiently read multiple pointers from
1756 /// memory at once.
1757 llvm::SmallVector<std::optional<lldb::addr_t>>
1758 ReadPointersFromMemory(llvm::ArrayRef<lldb::addr_t> ptr_locs);
1759
1760 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1761 Status &error);
1762
1763 /// Actually do the writing of memory to a process.
1764 ///
1765 /// \param[in] vm_addr
1766 /// A virtual load address that indicates where to start writing
1767 /// memory to.
1768 ///
1769 /// \param[in] buf
1770 /// A byte buffer that is at least \a size bytes long that
1771 /// contains the data to write.
1772 ///
1773 /// \param[in] size
1774 /// The number of bytes to write.
1775 ///
1776 /// \param[out] error
1777 /// An error value in case the memory write fails.
1778 ///
1779 /// \return
1780 /// The number of bytes that were actually written.
1781 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1782 size_t size, Status &error) {
1784 "error: {0} does not support writing to processes", GetPluginName());
1785 return 0;
1786 }
1787
1788 /// Write all or part of a scalar value to memory.
1789 ///
1790 /// The value contained in \a scalar will be swapped to match the byte order
1791 /// of the process that is being debugged. If \a size is less than the size
1792 /// of scalar, the least significant \a size bytes from scalar will be
1793 /// written. If \a size is larger than the byte size of scalar, then the
1794 /// extra space will be padded with zeros and the scalar value will be
1795 /// placed in the least significant bytes in memory.
1796 ///
1797 /// \param[in] vm_addr
1798 /// A virtual load address that indicates where to start writing
1799 /// memory to.
1800 ///
1801 /// \param[in] scalar
1802 /// The scalar to write to the debugged process.
1803 ///
1804 /// \param[in] size
1805 /// This value can be smaller or larger than the scalar value
1806 /// itself. If \a size is smaller than the size of \a scalar,
1807 /// the least significant bytes in \a scalar will be used. If
1808 /// \a size is larger than the byte size of \a scalar, then
1809 /// the extra space will be padded with zeros. If \a size is
1810 /// set to UINT32_MAX, then the size of \a scalar will be used.
1811 ///
1812 /// \param[out] error
1813 /// An error value in case the memory write fails.
1814 ///
1815 /// \return
1816 /// The number of bytes that were actually written.
1817 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1818 size_t size, Status &error);
1819
1820 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1821 bool is_signed, Scalar &scalar,
1822 Status &error);
1823
1824 /// Write memory to a process.
1825 ///
1826 /// This function will write memory to the current process's address space
1827 /// and maintain any traps that might be present due to software
1828 /// breakpoints.
1829 ///
1830 /// This function is not meant to be overridden by Process subclasses, the
1831 /// subclasses should implement Process::DoWriteMemory (lldb::addr_t,
1832 /// size_t, void *).
1833 ///
1834 /// \param[in] vm_addr
1835 /// A virtual load address that indicates where to start writing
1836 /// memory to.
1837 ///
1838 /// \param[in] buf
1839 /// A byte buffer that is at least \a size bytes long that
1840 /// contains the data to write.
1841 ///
1842 /// \param[in] size
1843 /// The number of bytes to write.
1844 ///
1845 /// \return
1846 /// The number of bytes that were actually written.
1847 // TODO: change this to take an ArrayRef<uint8_t>
1848 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1849 Status &error);
1850
1851 /// Actually allocate memory in the process.
1852 ///
1853 /// This function will allocate memory in the process's address space. This
1854 /// can't rely on the generic function calling mechanism, since that
1855 /// requires this function.
1856 ///
1857 /// \param[in] size
1858 /// The size of the allocation requested.
1859 ///
1860 /// \return
1861 /// The address of the allocated buffer in the process, or
1862 /// LLDB_INVALID_ADDRESS if the allocation failed.
1863
1864 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1865 Status &error) {
1867 "error: {0} does not support allocating in the debug process",
1868 GetPluginName());
1869 return LLDB_INVALID_ADDRESS;
1870 }
1871
1872 /// Determines whether DoAllocateMemory is expected to succeed, without
1873 /// running code in the process.
1874 virtual bool DoCanAllocateMemory() { return false; }
1875
1876 virtual Status WriteObjectFile(std::vector<ObjectFile::LoadableData> entries);
1877
1878 /// The public interface to allocating memory in the process.
1879 ///
1880 /// This function will allocate memory in the process's address space. This
1881 /// can't rely on the generic function calling mechanism, since that
1882 /// requires this function.
1883 ///
1884 /// \param[in] size
1885 /// The size of the allocation requested.
1886 ///
1887 /// \param[in] permissions
1888 /// Or together any of the lldb::Permissions bits. The permissions on
1889 /// a given memory allocation can't be changed after allocation. Note
1890 /// that a block that isn't set writable can still be written on from
1891 /// lldb,
1892 /// just not by the process itself.
1893 ///
1894 /// \param[in,out] error
1895 /// An error object to fill in if things go wrong.
1896 /// \return
1897 /// The address of the allocated buffer in the process, or
1898 /// LLDB_INVALID_ADDRESS if the allocation failed.
1899 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1900
1901 /// The public interface to allocating memory in the process, this also
1902 /// clears the allocated memory.
1903 ///
1904 /// This function will allocate memory in the process's address space. This
1905 /// can't rely on the generic function calling mechanism, since that
1906 /// requires this function.
1907 ///
1908 /// \param[in] size
1909 /// The size of the allocation requested.
1910 ///
1911 /// \param[in] permissions
1912 /// Or together any of the lldb::Permissions bits. The permissions on
1913 /// a given memory allocation can't be changed after allocation. Note
1914 /// that a block that isn't set writable can still be written on from
1915 /// lldb,
1916 /// just not by the process itself.
1917 ///
1918 /// \param[in,out] error
1919 /// An error object to fill in if things go wrong.
1920 ///
1921 /// \return
1922 /// The address of the allocated buffer in the process, or
1923 /// LLDB_INVALID_ADDRESS if the allocation failed.
1924
1925 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
1926 Status &error);
1927
1928 /// If this architecture and process supports memory tagging, return a tag
1929 /// manager that can be used to maniupulate those memory tags.
1930 ///
1931 /// \return
1932 /// Either a valid pointer to a tag manager or an error describing why one
1933 /// could not be provided.
1934 llvm::Expected<const MemoryTagManager *> GetMemoryTagManager();
1935
1936 /// Read memory tags for the range addr to addr+len. It is assumed
1937 /// that this range has already been granule aligned.
1938 /// (see MemoryTagManager::MakeTaggedRange)
1939 ///
1940 /// This calls DoReadMemoryTags to do the target specific operations.
1941 ///
1942 /// \param[in] addr
1943 /// Start of memory range to read tags for.
1944 ///
1945 /// \param[in] len
1946 /// Length of memory range to read tags for (in bytes).
1947 ///
1948 /// \return
1949 /// If this architecture or process does not support memory tagging,
1950 /// an error saying so.
1951 /// If it does, either the memory tags or an error describing a
1952 /// failure to read or unpack them.
1953 virtual llvm::Expected<std::vector<lldb::addr_t>>
1954 ReadMemoryTags(lldb::addr_t addr, size_t len);
1955
1956 /// Write memory tags for a range of memory.
1957 /// (calls DoWriteMemoryTags to do the target specific work)
1958 ///
1959 /// \param[in] addr
1960 /// The address to start writing tags from. It is assumed that this
1961 /// address is granule aligned.
1962 ///
1963 /// \param[in] len
1964 /// The size of the range to write tags for. It is assumed that this
1965 /// is some multiple of the granule size. This len can be different
1966 /// from (number of tags * granule size) in the case where you want
1967 /// lldb-server to repeat tags across the range.
1968 ///
1969 /// \param[in] tags
1970 /// Allocation tags to be written. Since lldb-server can repeat tags for a
1971 /// range, the number of tags doesn't have to match the number of granules
1972 /// in the range. (though most of the time it will)
1973 ///
1974 /// \return
1975 /// A Status telling you if the write succeeded or not.
1976 Status WriteMemoryTags(lldb::addr_t addr, size_t len,
1977 const std::vector<lldb::addr_t> &tags);
1978
1979 /// Resolve dynamically loaded indirect functions.
1980 ///
1981 /// \param[in] address
1982 /// The load address of the indirect function to resolve.
1983 ///
1984 /// \param[out] error
1985 /// An error value in case the resolve fails.
1986 ///
1987 /// \return
1988 /// The address of the resolved function.
1989 /// LLDB_INVALID_ADDRESS if the resolution failed.
1990 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
1991 Status &error);
1992
1993 /// Locate the memory region that contains load_addr.
1994 ///
1995 /// If load_addr is within the address space the process has mapped
1996 /// range_info will be filled in with the start and end of that range as
1997 /// well as the permissions for that range and range_info. GetMapped will
1998 /// return true.
1999 ///
2000 /// If load_addr is outside any mapped region then range_info will have its
2001 /// start address set to load_addr and the end of the range will indicate
2002 /// the start of the next mapped range or be set to LLDB_INVALID_ADDRESS if
2003 /// there are no valid mapped ranges between load_addr and the end of the
2004 /// process address space.
2005 ///
2006 /// GetMemoryRegionInfo calls DoGetMemoryRegionInfo. Override that function in
2007 /// process subclasses.
2008 ///
2009 /// \param[in] load_addr
2010 /// The load address to query the range_info for. May include non
2011 /// address bits, these will be removed by the ABI plugin if there is
2012 /// one.
2013 ///
2014 /// \param[out] range_info
2015 /// An range_info value containing the details of the range.
2016 ///
2017 /// \return
2018 /// An error value.
2020 MemoryRegionInfo &range_info);
2021
2022 /// Obtain all the mapped memory regions within this process.
2023 ///
2024 /// \param[out] region_list
2025 /// A vector to contain MemoryRegionInfo objects for all mapped
2026 /// ranges.
2027 ///
2028 /// \return
2029 /// An error value.
2030 virtual Status
2032
2033 llvm::Expected<AddressSpaceInfo>
2034 GetAddressSpaceInfo(llvm::StringRef address_space_name);
2035
2036 llvm::Expected<AddressSpaceInfo>
2037 GetAddressSpaceInfo(lldb::addr_space_t address_space_id);
2038
2039 /// Get the number of watchpoints supported by this target.
2040 ///
2041 /// We may be able to determine the number of watchpoints available
2042 /// on this target; retrieve this value if possible.
2043 ///
2044 /// This number may be less than the number of watchpoints a user
2045 /// can specify. This is because a single user watchpoint may require
2046 /// multiple watchpoint slots to implement. Due to the size
2047 /// and/or alignment of objects.
2048 ///
2049 /// \return
2050 /// Returns the number of watchpoints, if available.
2051 virtual std::optional<uint32_t> GetWatchpointSlotCount() {
2052 return std::nullopt;
2053 }
2054
2055 /// Whether lldb will be notified about watchpoints after
2056 /// the instruction has completed executing, or if the
2057 /// instruction is rolled back and it is notified before it
2058 /// executes.
2059 /// The default behavior is "exceptions received after instruction
2060 /// has executed", except for certain CPU architectures.
2061 /// Process subclasses may override this if they have additional
2062 /// information.
2063 ///
2064 /// \return
2065 /// Returns true for targets where lldb is notified after
2066 /// the instruction has completed executing.
2068
2069 /// Creates and populates a module using an in-memory object file.
2070 ///
2071 /// \param[in] file_spec
2072 /// The name or path to the module file. May be empty.
2073 ///
2074 /// \param[in] header_addr
2075 /// The address pointing to the beginning of the object file's header.
2076 ///
2077 /// \param[in] size_to_read
2078 /// The number of bytes to read from memory. This should be large enough to
2079 /// identify the object file format. Defaults to 512.
2080 llvm::Expected<lldb::ModuleSP>
2081 ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr,
2082 size_t size_to_read = 512);
2083
2084 /// Attempt to get the attributes for a region of memory in the process.
2085 ///
2086 /// It may be possible for the remote debug server to inspect attributes for
2087 /// a region of memory in the process, such as whether there is a valid page
2088 /// of memory at a given address or whether that page is
2089 /// readable/writable/executable by the process.
2090 ///
2091 /// \param[in] load_addr
2092 /// The address of interest in the process.
2093 ///
2094 /// \param[out] permissions
2095 /// If this call returns successfully, this bitmask will have
2096 /// its Permissions bits set to indicate whether the region is
2097 /// readable/writable/executable. If this call fails, the
2098 /// bitmask values are undefined.
2099 ///
2100 /// \return
2101 /// Returns true if it was able to determine the attributes of the
2102 /// memory region. False if not.
2103 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2104 uint32_t &permissions);
2105
2106 /// Determines whether executing JIT-compiled code in this process is
2107 /// possible.
2108 ///
2109 /// \return
2110 /// True if execution of JIT code is possible; false otherwise.
2111 bool CanJIT();
2112
2113 /// Sets whether executing JIT-compiled code in this process is possible.
2114 ///
2115 /// \param[in] can_jit
2116 /// True if execution of JIT code is possible; false otherwise.
2117 void SetCanJIT(bool can_jit);
2118
2119 /// Determines whether executing function calls using the interpreter is
2120 /// possible for this process.
2121 ///
2122 /// \return
2123 /// True if possible; false otherwise.
2125
2126 /// Sets whether executing function calls using the interpreter is possible
2127 /// for this process.
2128 ///
2129 /// \param[in] can_interpret_function_calls
2130 /// True if possible; false otherwise.
2131 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2132 m_can_interpret_function_calls = can_interpret_function_calls;
2133 }
2134
2135 /// Sets whether executing code in this process is possible. This could be
2136 /// either through JIT or interpreting.
2137 ///
2138 /// \param[in] can_run_code
2139 /// True if execution of code is possible; false otherwise.
2140 void SetCanRunCode(bool can_run_code);
2141
2142 /// Actually deallocate memory in the process.
2143 ///
2144 /// This function will deallocate memory in the process's address space that
2145 /// was allocated with AllocateMemory.
2146 ///
2147 /// \param[in] ptr
2148 /// A return value from AllocateMemory, pointing to the memory you
2149 /// want to deallocate.
2150 ///
2151 /// \return
2152 /// \b true if the memory was deallocated, \b false otherwise.
2155 "error: {0} does not support deallocating in the debug process",
2156 GetPluginName());
2157 }
2158
2159 /// The public interface to deallocating memory in the process.
2160 ///
2161 /// This function will deallocate memory in the process's address space that
2162 /// was allocated with AllocateMemory.
2163 ///
2164 /// \param[in] ptr
2165 /// A return value from AllocateMemory, pointing to the memory you
2166 /// want to deallocate.
2167 ///
2168 /// \return
2169 /// \b true if the memory was deallocated, \b false otherwise.
2171
2172 /// Get any available STDOUT.
2173 ///
2174 /// Calling this method is a valid operation only if all of the following
2175 /// conditions are true: 1) The process was launched, and not attached to.
2176 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2177 /// process was launched without supplying a valid file path
2178 /// for STDOUT.
2179 ///
2180 /// Note that the implementation will probably need to start a read thread
2181 /// in the background to make sure that the pipe is drained and the STDOUT
2182 /// buffered appropriately, to prevent the process from deadlocking trying
2183 /// to write to a full buffer.
2184 ///
2185 /// Events will be queued indicating that there is STDOUT available that can
2186 /// be retrieved using this function.
2187 ///
2188 /// \param[out] buf
2189 /// A buffer that will receive any STDOUT bytes that are
2190 /// currently available.
2191 ///
2192 /// \param[in] buf_size
2193 /// The size in bytes for the buffer \a buf.
2194 ///
2195 /// \return
2196 /// The number of bytes written into \a buf. If this value is
2197 /// equal to \a buf_size, another call to this function should
2198 /// be made to retrieve more STDOUT data.
2199 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2200
2201 /// Get any available STDERR.
2202 ///
2203 /// Calling this method is a valid operation only if all of the following
2204 /// conditions are true: 1) The process was launched, and not attached to.
2205 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2206 /// process was launched without supplying a valid file path
2207 /// for STDERR.
2208 ///
2209 /// Note that the implementation will probably need to start a read thread
2210 /// in the background to make sure that the pipe is drained and the STDERR
2211 /// buffered appropriately, to prevent the process from deadlocking trying
2212 /// to write to a full buffer.
2213 ///
2214 /// Events will be queued indicating that there is STDERR available that can
2215 /// be retrieved using this function.
2216 ///
2217 /// \param[in] buf
2218 /// A buffer that will receive any STDERR bytes that are
2219 /// currently available.
2220 ///
2221 /// \param[out] buf_size
2222 /// The size in bytes for the buffer \a buf.
2223 ///
2224 /// \return
2225 /// The number of bytes written into \a buf. If this value is
2226 /// equal to \a buf_size, another call to this function should
2227 /// be made to retrieve more STDERR data.
2228 virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2229
2230 /// Puts data into this process's STDIN.
2231 ///
2232 /// Calling this method is a valid operation only if all of the following
2233 /// conditions are true: 1) The process was launched, and not attached to.
2234 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2235 /// process was launched without supplying a valid file path
2236 /// for STDIN.
2237 ///
2238 /// \param[in] buf
2239 /// A buffer that contains the data to write to the process's STDIN.
2240 ///
2241 /// \param[in] buf_size
2242 /// The size in bytes for the buffer \a buf.
2243 ///
2244 /// \return
2245 /// The number of bytes written into \a buf. If this value is
2246 /// less than \a buf_size, another call to this function should
2247 /// be made to write the rest of the data.
2248 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2249 error = Status::FromErrorString("stdin unsupported");
2250 return 0;
2251 }
2252
2253 /// Get any available profile data.
2254 ///
2255 /// \param[out] buf
2256 /// A buffer that will receive any profile data bytes that are
2257 /// currently available.
2258 ///
2259 /// \param[out] buf_size
2260 /// The size in bytes for the buffer \a buf.
2261 ///
2262 /// \return
2263 /// The number of bytes written into \a buf. If this value is
2264 /// equal to \a buf_size, another call to this function should
2265 /// be made to retrieve more profile data.
2266 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2267
2268 // Process Breakpoints
2270
2272
2273protected:
2276 "error: {0} does not support enabling breakpoints", GetPluginName());
2277 }
2278
2281 "error: {0} does not support disabling breakpoints", GetPluginName());
2282 }
2283
2284 /// Compare BreakpointSiteSPs by ID, so that iteration order is independent
2285 /// of pointer addresses.
2286 struct SiteIDCmp {
2288 const lldb::BreakpointSiteSP &rhs) const {
2289 return lhs->GetID() < rhs->GetID();
2290 }
2291 };
2293 std::map<lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp>;
2294
2295 virtual llvm::Error
2296 UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action);
2297
2298public:
2299 /// Performs `action` on `site`. If `forbid_delay` is true, the action is
2300 /// performed immediately, otherwise the method will delay the breakpoint if
2301 /// it is correct to do so.
2304 bool forbid_delay);
2305
2306 // This is implemented completely using the lldb::Process API. Subclasses
2307 // don't need to implement this function unless the standard flow of read
2308 // existing opcode, write breakpoint opcode, verify breakpoint opcode doesn't
2309 // work for a specific process plug-in.
2311
2312 // This is implemented completely using the lldb::Process API. Subclasses
2313 // don't need to implement this function unless the standard flow of
2314 // restoring original opcode in memory and verifying the restored opcode
2315 // doesn't work for a specific process plug-in.
2317
2319
2321 GetBreakpointSiteList() const;
2322
2324
2326
2328 bool use_hardware);
2329
2331
2333
2334 bool IsBreakpointSiteEnabled(const BreakpointSite &site);
2335
2337
2338 /// Reports whether this process should delay physically enabling/disabling
2339 /// breakpoints until the process is about to resume. The default honors the
2340 /// user-facing `target.process.use-delayed-breakpoints` setting.
2341 virtual bool ShouldUseDelayedBreakpoints() const {
2342 return GetUseDelayedBreakpoints();
2343 }
2344
2345 // BreakpointLocations use RemoveConstituentFromBreakpointSite to remove
2346 // themselves from the constituent's list of this breakpoint sites.
2348 lldb::user_id_t constituent_id,
2349 lldb::BreakpointSiteSP &bp_site_sp);
2350
2351 // Process Watchpoints (optional)
2352 virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify = true);
2353
2355 bool notify = true);
2356
2357 // Thread Queries
2358
2359 /// Update the thread list.
2360 ///
2361 /// This method performs some general clean up before invoking
2362 /// \a DoUpdateThreadList, which should be implemented by each
2363 /// process plugin.
2364 ///
2365 /// \return
2366 /// \b true if the new thread list could be generated, \b false otherwise.
2367 bool UpdateThreadList(ThreadList &old_thread_list,
2368 ThreadList &new_thread_list);
2369
2371
2373
2378
2379 // When ExtendedBacktraces are requested, the HistoryThreads that are created
2380 // need an owner -- they're saved here in the Process. The threads in this
2381 // list are not iterated over - driver programs need to request the extended
2382 // backtrace calls starting from a root concrete thread one by one.
2384
2386
2387 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2388
2390
2391 // Returns true if an index id has been assigned to a thread.
2392 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2393
2394 // Given a thread_id, it will assign a more reasonable index id for display
2395 // to the user. If the thread_id has previously been assigned, the same index
2396 // id will be used.
2397 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2398
2399 // Queue Queries
2400
2401 virtual void UpdateQueueListIfNeeded();
2402
2407
2412
2413 // Event Handling
2415
2416 // Returns the process state when it is stopped. If specified, event_sp_ptr
2417 // is set to the event which triggered the stop. If wait_always = false, and
2418 // the process is already stopped, this function returns immediately. If the
2419 // process is hijacked and use_run_lock is true (the default), then this
2420 // function releases the run lock after the stop. Setting use_run_lock to
2421 // false will avoid this behavior.
2422 // If we are waiting to stop that will return control to the user,
2423 // then we also want to run SelectMostRelevantFrame, which is controlled
2424 // by "select_most_relevant".
2427 lldb::EventSP *event_sp_ptr = nullptr,
2428 bool wait_always = true,
2429 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2430 Stream *stream = nullptr, bool use_run_lock = true,
2431 SelectMostRelevant select_most_relevant =
2433
2434 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2435
2436 /// Waits for the process state to be running within a given msec timeout.
2437 ///
2438 /// The main purpose of this is to implement an interlock waiting for
2439 /// HandlePrivateEvent to push an IOHandler.
2440 ///
2441 /// \param[in] timeout
2442 /// The maximum time length to wait for the process to transition to the
2443 /// eStateRunning state.
2444 void SyncIOHandler(uint32_t iohandler_id, const Timeout<std::micro> &timeout);
2445
2447 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2449 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2450
2451 /// Centralize the code that handles and prints descriptions for process
2452 /// state changes.
2453 ///
2454 /// \param[in] event_sp
2455 /// The process state changed event
2456 ///
2457 /// \param[in] stream
2458 /// The output stream to get the state change description
2459 ///
2460 /// \param[in,out] pop_process_io_handler
2461 /// If this value comes in set to \b true, then pop the Process IOHandler
2462 /// if needed.
2463 /// Else this variable will be set to \b true or \b false to indicate if
2464 /// the process
2465 /// needs to have its process IOHandler popped.
2466 ///
2467 /// \return
2468 /// \b true if the event describes a process state changed event, \b false
2469 /// otherwise.
2470 static bool
2471 HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream,
2472 SelectMostRelevant select_most_relevant,
2473 bool &pop_process_io_handler);
2474
2476
2478 public:
2480 : m_process(process) {
2481 m_process.HijackProcessEvents(std::move(listener_sp));
2482 }
2483
2484 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2485
2486 private:
2488 };
2489
2491 friend class ProcessProperties;
2492 /// If you need to ensure that you and only you will hear about some public
2493 /// event, then make a new listener, set to listen to process events, and
2494 /// then call this with that listener. Then you will have to wait on that
2495 /// listener explicitly for events (rather than using the GetNextEvent &
2496 /// WaitFor* calls above. Be sure to call RestoreProcessEvents when you are
2497 /// done.
2498 ///
2499 /// \param[in] listener_sp
2500 /// This is the new listener to whom all process events will be delivered.
2501 ///
2502 /// \return
2503 /// Returns \b true if the new listener could be installed,
2504 /// \b false otherwise.
2505 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2506
2507 /// Restores the process event broadcasting to its normal state.
2508 ///
2509 void RestoreProcessEvents();
2510
2512
2514
2515 const lldb::ABISP &GetABI();
2516
2518
2519 std::vector<LanguageRuntime *> GetLanguageRuntimes();
2520
2522
2523 bool IsPossibleDynamicValue(ValueObject &in_value);
2524
2525 bool IsRunning() const;
2526
2530
2531 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2532
2533/// Prune ThreadPlanStacks for unreported threads.
2534///
2535/// \param[in] tid
2536/// The tid whose Plan Stack we are seeking to prune.
2537///
2538/// \return
2539/// \b true if the TID is found or \b false if not.
2541
2542/// Prune ThreadPlanStacks for all unreported threads.
2543void PruneThreadPlans();
2544
2545 /// Find the thread plan stack associated with thread with \a tid.
2546 ///
2547 /// \param[in] tid
2548 /// The tid whose Plan Stack we are seeking.
2549 ///
2550 /// \return
2551 /// Returns a ThreadPlan if the TID is found or nullptr if not.
2553
2554 /// Dump the thread plans associated with thread with \a tid.
2555 ///
2556 /// \param[in,out] strm
2557 /// The stream to which to dump the output
2558 ///
2559 /// \param[in] tid
2560 /// The tid whose Plan Stack we are dumping
2561 ///
2562 /// \param[in] desc_level
2563 /// How much detail to dump
2564 ///
2565 /// \param[in] internal
2566 /// If \b true dump all plans, if false only user initiated plans
2567 ///
2568 /// \param[in] condense_trivial
2569 /// If true, only dump a header if the plan stack is just the base plan.
2570 ///
2571 /// \param[in] skip_unreported_plans
2572 /// If true, only dump a plan if it is currently backed by an
2573 /// lldb_private::Thread *.
2574 ///
2575 /// \return
2576 /// Returns \b true if TID was found, \b false otherwise
2578 lldb::DescriptionLevel desc_level, bool internal,
2579 bool condense_trivial, bool skip_unreported_plans);
2580
2581 /// Dump all the thread plans for this process.
2582 ///
2583 /// \param[in,out] strm
2584 /// The stream to which to dump the output
2585 ///
2586 /// \param[in] desc_level
2587 /// How much detail to dump
2588 ///
2589 /// \param[in] internal
2590 /// If \b true dump all plans, if false only user initiated plans
2591 ///
2592 /// \param[in] condense_trivial
2593 /// If true, only dump a header if the plan stack is just the base plan.
2594 ///
2595 /// \param[in] skip_unreported_plans
2596 /// If true, skip printing all thread plan stacks that don't currently
2597 /// have a backing lldb_private::Thread *.
2598 void DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
2599 bool internal, bool condense_trivial,
2600 bool skip_unreported_plans);
2601
2602 /// Call this to set the lldb in the mode where it breaks on new thread
2603 /// creations, and then auto-restarts. This is useful when you are trying
2604 /// to run only one thread, but either that thread or the kernel is creating
2605 /// new threads in the process. If you stop when the thread is created, you
2606 /// can immediately suspend it, and keep executing only the one thread you
2607 /// intend.
2608 ///
2609 /// \return
2610 /// Returns \b true if we were able to start up the notification
2611 /// \b false otherwise.
2612 virtual bool StartNoticingNewThreads() { return true; }
2613
2614 /// Call this to turn off the stop & notice new threads mode.
2615 ///
2616 /// \return
2617 /// Returns \b true if we were able to start up the notification
2618 /// \b false otherwise.
2619 virtual bool StopNoticingNewThreads() { return true; }
2620
2621 void SetRunningUserExpression(bool on);
2622 void SetRunningUtilityFunction(bool on);
2623
2624 // lldb::ExecutionContextScope pure virtual functions
2626
2627 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2628
2630
2634
2635 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2636
2637#ifdef _WIN32
2638 /// Associates a ConPTY read and write HANDLEs with the process' STDIO
2639 /// handling and configures an asynchronous reading of that ConPTY's stdout
2640 /// HANDLE.
2641 ///
2642 /// This method installs a ConnectionGenericFile for the passed ConPTY and
2643 /// starts a dedicated read thread. If the read thread starts successfully,
2644 /// the method also ensures that an IOHandlerProcessSTDIOWindows is created to
2645 /// manage user input to the process.
2646 ///
2647 /// When data is successfully read from the ConPTY, it is stored in
2648 /// m_stdout_data. There is no differentiation between stdout and stderr.
2649 ///
2650 /// \see lldb_private::Process::STDIOReadThreadBytesReceived()
2651 /// \see lldb_private::IOHandlerProcessSTDIOWindows
2652 /// \see lldb_private::PseudoConsole
2653 virtual void SetPseudoConsoleHandle() {};
2654#endif
2655
2656 /// Associates a file descriptor with the process' STDIO handling
2657 /// and configures an asynchronous reading of that descriptor.
2658 ///
2659 /// This method installs a ConnectionFileDescriptor for the passed file
2660 /// descriptor and starts a dedicated read thread. If the read thread starts
2661 /// successfully, the method also ensures that an IOHandlerProcessSTDIO is
2662 /// created to manage user input to the process.
2663 ///
2664 /// The descriptor's ownership is transferred to the underlying
2665 /// ConnectionFileDescriptor.
2666 ///
2667 /// When data is successfully read from the file descriptor, it is stored in
2668 /// m_stdout_data. There is no differentiation between stdout and stderr.
2669 ///
2670 /// \param[in] fd
2671 /// The file descriptor to use for process STDIO communication. It's
2672 /// assumed to be valid and will be managed by the newly created
2673 /// connection.
2674 ///
2675 /// \param[in] secondary_fd A descriptor for the secondary side of that same
2676 /// terminal as file_descriptor. This is used to keep the terminal (and
2677 /// its output buffer alive). The process takes ownership of it and keeps
2678 /// it open until it stops monitoring fd.
2679 ///
2680 /// Pass std::nullopt if fd is not a pseudo terminal or no such
2681 /// descriptor is available.
2682 ///
2683 /// \see lldb_private::Process::STDIOReadThreadBytesReceived()
2684 /// \see lldb_private::IOHandlerProcessSTDIO
2685 /// \see lldb_private::ConnectionFileDescriptor
2686 void SetSTDIOFileDescriptor(int file_descriptor,
2687 std::optional<int> secondary_fd = std::nullopt);
2688
2689#if !defined(_WIN32)
2690 /// Associates the primary side of \a pty with the process' STDIO handling.
2691 /// The process takes ownership of both of \a pty's descriptors.
2692 ///
2693 /// \see SetSTDIOFileDescriptor()
2694 void SetSTDIOPseudoTerminal(PseudoTerminal &pty);
2695#endif
2696
2697 // Add a permanent region of memory that should never be read or written to.
2698 // This can be used to ensure that memory reads or writes to certain areas of
2699 // memory never end up being sent to the DoReadMemory or DoWriteMemory
2700 // functions which can improve performance.
2701 void AddInvalidMemoryRegion(const LoadRange &region);
2702
2703 // Remove a permanent region of memory that should never be read or written
2704 // to that was previously added with AddInvalidMemoryRegion.
2705 bool RemoveInvalidMemoryRange(const LoadRange &region);
2706
2707 // If the setup code of a thread plan needs to do work that might involve
2708 // calling a function in the target, it should not do that work directly in
2709 // one of the thread plan functions (DidPush/WillResume) because such work
2710 // needs to be handled carefully. Instead, put that work in a
2711 // PreResumeAction callback, and register it with the process. It will get
2712 // done before the actual "DoResume" gets called.
2713
2715
2716 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2717
2718 bool RunPreResumeActions();
2719
2720 void ClearPreResumeActions();
2721
2722 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2723
2725
2726 virtual Status SendEventData(const char *data) {
2728 "Sending an event is not supported for this process.");
2729 }
2730
2732
2735
2736 /// Try to fetch the module specification for a module with the given file
2737 /// name and architecture. Process sub-classes have to override this method
2738 /// if they support platforms where the Platform object can't get the module
2739 /// spec for all module.
2740 ///
2741 /// \param[in] module_file_spec
2742 /// The file name of the module to get specification for.
2743 ///
2744 /// \param[in] arch
2745 /// The architecture of the module to get specification for.
2746 ///
2747 /// \param[out] module_spec
2748 /// The fetched module specification if the return value is
2749 /// \b true, unchanged otherwise.
2750 ///
2751 /// \return
2752 /// Returns \b true if the module spec fetched successfully,
2753 /// \b false otherwise.
2754 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2755 const ArchSpec &arch, ModuleSpec &module_spec);
2756
2757 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2758 const llvm::Triple &triple) {}
2759
2760 /// Try to find the load address of a file.
2761 /// The load address is defined as the address of the first memory region
2762 /// what contains data mapped from the specified file.
2763 ///
2764 /// \param[in] file
2765 /// The name of the file whose load address we are looking for
2766 ///
2767 /// \param[out] is_loaded
2768 /// \b True if the file is loaded into the memory and false
2769 /// otherwise.
2770 ///
2771 /// \param[out] load_addr
2772 /// The load address of the file if it is loaded into the
2773 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2774 virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2775 lldb::addr_t &load_addr) {
2776 return Status::FromErrorString("Not supported");
2777 }
2778
2779 /// Fetch process defined metadata.
2780 ///
2781 /// \return
2782 /// A StructuredDataSP object which, if non-empty, will contain the
2783 /// information related to the process.
2784 virtual StructuredData::DictionarySP GetMetadata() { return nullptr; }
2785
2786 /// Fetch extended crash information held by the process. This will never be
2787 /// an empty shared pointer, it will always have a dict, though it may be
2788 /// empty.
2790 assert(m_crash_info_dict_sp && "We always have a valid dictionary");
2791 return m_crash_info_dict_sp;
2792 }
2793
2795 // StructuredData::Dictionary is add only, so we have to make a new one:
2796 m_crash_info_dict_sp = std::make_shared<StructuredData::Dictionary>();
2797 }
2798
2799 size_t AddImageToken(lldb::addr_t image_ptr);
2800
2801 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2802
2803 void ResetImageToken(size_t token);
2804
2805 /// Find the next branch instruction to set a breakpoint on
2806 ///
2807 /// When instruction stepping through a source line, instead of stepping
2808 /// through each instruction, we can put a breakpoint on the next branch
2809 /// instruction (within the range of instructions we are stepping through)
2810 /// and continue the process to there, yielding significant performance
2811 /// benefits over instruction stepping.
2812 ///
2813 /// \param[in] default_stop_addr
2814 /// The address of the instruction where lldb would put a
2815 /// breakpoint normally.
2816 ///
2817 /// \param[in] range_bounds
2818 /// The range which the breakpoint must be contained within.
2819 /// Typically a source line.
2820 ///
2821 /// \return
2822 /// The address of the next branch instruction, or the end of
2823 /// the range provided in range_bounds. If there are any
2824 /// problems with the disassembly or getting the instructions,
2825 /// the original default_stop_addr will be returned.
2827 AddressRange range_bounds);
2828
2829 /// Configure asynchronous structured data feature.
2830 ///
2831 /// Each Process type that supports using an asynchronous StructuredData
2832 /// feature should implement this to enable/disable/configure the feature.
2833 /// The default implementation here will always return an error indiciating
2834 /// the feature is unsupported.
2835 ///
2836 /// StructuredDataPlugin implementations will call this to configure a
2837 /// feature that has been reported as being supported.
2838 ///
2839 /// \param[in] type_name
2840 /// The StructuredData type name as previously discovered by
2841 /// the Process-derived instance.
2842 ///
2843 /// \param[in] config_sp
2844 /// Configuration data for the feature being enabled. This config
2845 /// data, which may be null, will be passed along to the feature
2846 /// to process. The feature will dictate whether this is a dictionary,
2847 /// an array or some other object. If the feature needs to be
2848 /// set up properly before it can be enabled, then the config should
2849 /// also take an enable/disable flag.
2850 ///
2851 /// \return
2852 /// Returns the result of attempting to configure the feature.
2853 virtual Status
2854 ConfigureStructuredData(llvm::StringRef type_name,
2855 const StructuredData::ObjectSP &config_sp);
2856
2857 /// Broadcasts the given structured data object from the given plugin.
2858 ///
2859 /// StructuredDataPlugin instances can use this to optionally broadcast any
2860 /// of their data if they want to make it available for clients. The data
2861 /// will come in on the structured data event bit
2862 /// (eBroadcastBitStructuredData).
2863 ///
2864 /// \param[in] object_sp
2865 /// The structured data object to broadcast.
2866 ///
2867 /// \param[in] plugin_sp
2868 /// The plugin that will be reported in the event's plugin
2869 /// parameter.
2871 const lldb::StructuredDataPluginSP &plugin_sp);
2872
2873 /// Returns the StructuredDataPlugin associated with a given type name, if
2874 /// there is one.
2875 ///
2876 /// There will only be a plugin for a given StructuredDataType if the
2877 /// debugged process monitor claims that the feature is supported. This is
2878 /// one way to tell whether a feature is available.
2879 ///
2880 /// \return
2881 /// The plugin if one is available for the specified feature;
2882 /// otherwise, returns an empty shared pointer.
2884 GetStructuredDataPlugin(llvm::StringRef type_name) const;
2885
2886 virtual void *GetImplementation() { return nullptr; }
2887
2889
2893
2894 /// Find a pattern within a memory region.
2895 ///
2896 /// This function searches for a pattern represented by the provided buffer
2897 /// within the memory range specified by the low and high addresses. It uses
2898 /// a bad character heuristic to optimize the search process.
2899 ///
2900 /// \param[in] low The starting address of the memory region to be searched.
2901 /// (inclusive)
2902 ///
2903 /// \param[in] high The ending address of the memory region to be searched.
2904 /// (exclusive)
2905 ///
2906 /// \param[in] buf A pointer to the buffer containing the pattern to be
2907 /// searched.
2908 ///
2909 /// \param[in] buffer_size The size of the buffer in bytes.
2910 ///
2911 /// \return The address where the pattern was found or LLDB_INVALID_ADDRESS if
2912 /// not found.
2914 const uint8_t *buf, size_t size);
2915
2916 AddressRanges FindRangesInMemory(const uint8_t *buf, uint64_t size,
2917 const AddressRanges &ranges,
2918 size_t alignment, size_t max_matches,
2919 Status &error);
2920
2921 lldb::addr_t FindInMemory(const uint8_t *buf, uint64_t size,
2922 const AddressRange &range, size_t alignment,
2923 Status &error);
2924
2925 /// Get the base run direction for the process.
2926 /// The base direction is the direction the process will execute in
2927 /// (forward or backward) if no thread plan overrides the direction.
2929 /// Set the base run direction for the process.
2930 /// As a side-effect, if this changes the base direction, then we
2931 /// discard all non-base thread plans to ensure that when execution resumes
2932 /// we definitely execute in the requested direction.
2933 /// FIXME: this is overkill. In some situations ensuring the latter
2934 /// would not require discarding all non-base thread plans.
2935 void SetBaseDirection(lldb::RunDirection direction);
2936
2937protected:
2938 friend class Trace;
2939
2940 /// Construct with a shared pointer to a target, and the Process listener.
2941 /// Uses the Host UnixSignalsSP by default.
2942 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
2943
2944 /// Construct with a shared pointer to a target, the Process listener, and
2945 /// the appropriate UnixSignalsSP for the process.
2946 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
2947 const lldb::UnixSignalsSP &unix_signals_sp);
2948
2949 /// Get the processor tracing type supported for this process.
2950 /// Responses might be different depending on the architecture and
2951 /// capabilities of the underlying OS.
2952 ///
2953 /// \return
2954 /// The supported trace type or an \a llvm::Error if tracing is
2955 /// not supported for the inferior.
2956 virtual llvm::Expected<TraceSupportedResponse> TraceSupported();
2957
2958 /// Start tracing a process or its threads.
2959 ///
2960 /// \param[in] request
2961 /// JSON object with the information necessary to start tracing. In the
2962 /// case of gdb-remote processes, this JSON object should conform to the
2963 /// jLLDBTraceStart packet.
2964 ///
2965 /// \return
2966 /// \a llvm::Error::success if the operation was successful, or
2967 /// \a llvm::Error otherwise.
2968 virtual llvm::Error TraceStart(const llvm::json::Value &request) {
2969 return llvm::make_error<UnimplementedError>();
2970 }
2971
2972 /// Stop tracing a live process or its threads.
2973 ///
2974 /// \param[in] request
2975 /// The information determining which threads or process to stop tracing.
2976 ///
2977 /// \return
2978 /// \a llvm::Error::success if the operation was successful, or
2979 /// \a llvm::Error otherwise.
2980 virtual llvm::Error TraceStop(const TraceStopRequest &request) {
2981 return llvm::make_error<UnimplementedError>();
2982 }
2983
2984 /// Get the current tracing state of the process and its threads.
2985 ///
2986 /// \param[in] type
2987 /// Tracing technology type to consider.
2988 ///
2989 /// \return
2990 /// A JSON object string with custom data depending on the trace
2991 /// technology, or an \a llvm::Error in case of errors.
2992 virtual llvm::Expected<std::string> TraceGetState(llvm::StringRef type) {
2993 return llvm::make_error<UnimplementedError>();
2994 }
2995
2996 /// Get binary data given a trace technology and a data identifier.
2997 ///
2998 /// \param[in] request
2999 /// Object with the params of the requested data.
3000 ///
3001 /// \return
3002 /// A vector of bytes with the requested data, or an \a llvm::Error in
3003 /// case of failures.
3004 virtual llvm::Expected<std::vector<uint8_t>>
3006 return llvm::make_error<UnimplementedError>();
3007 }
3008
3009 // This calls a function of the form "void * (*)(void)".
3010 bool CallVoidArgVoidPtrReturn(const Address *address,
3011 lldb::addr_t &returned_func,
3012 bool trap_exceptions = false);
3013
3014 /// Update the thread list following process plug-in's specific logic.
3015 ///
3016 /// This method should only be invoked by \a UpdateThreadList.
3017 ///
3018 /// \return
3019 /// \b true if the new thread list could be generated, \b false otherwise.
3020 virtual bool DoUpdateThreadList(ThreadList &old_thread_list,
3021 ThreadList &new_thread_list) = 0;
3022
3023 /// Whether ReadMemory should serve reads of \a process_addr out of the
3024 /// memory cache.
3025 virtual bool ShouldUseMemoryCache(const ProcessAddress &process_addr) {
3026 return true;
3027 }
3028
3029 /// Actually do the reading of memory from a process.
3030 ///
3031 /// Subclasses must override this function and can return fewer bytes than
3032 /// requested when memory requests are too large. This class will break up
3033 /// the memory requests and keep advancing the arguments along as needed.
3034 ///
3035 /// \param[in] process_addr
3036 /// A fixed virtual load address that indicates where to start reading
3037 /// memory from. Unlike the address passed to ReadMemory, which may
3038 /// carry non-address bits, ReadMemory has already removed them (see
3039 /// Process::FixAnyAddress) before calling this function. The exception
3040 /// is an address in a non-default address space, which is passed
3041 /// through unchanged.
3042 ///
3043 /// \param[in] size
3044 /// The number of bytes to read.
3045 ///
3046 /// \param[out] buf
3047 /// A byte buffer that is at least \a size bytes long that
3048 /// will receive the memory bytes.
3049 ///
3050 /// \param[out] error
3051 /// An error that indicates the success or failure of this
3052 /// operation. If error indicates success (error.Success()),
3053 /// then the value returned can be trusted, otherwise zero
3054 /// will be returned. ReadMemory clears \a error before calling this
3055 /// function.
3056 ///
3057 /// \return
3058 /// The number of bytes that were actually read into \a buf.
3059 /// Zero is returned in the case of an error.
3060 virtual size_t DoReadMemory(const ProcessAddress &process_addr, void *buf,
3061 size_t size, Status &error) = 0;
3062
3063 /// Reads each range individually via ReadMemoryFromInferior, bypassing the
3064 /// memory cache. Subclasses may override it to batch the reads more
3065 /// efficiently.
3066 virtual llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
3067 DoReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
3068 llvm::MutableArrayRef<uint8_t> buffer);
3069
3070 virtual void DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr,
3071 const uint8_t *buf, size_t size,
3072 AddressRanges &matches, size_t alignment,
3073 size_t max_matches);
3074
3075 /// DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has
3076 /// removed non address bits from load_addr. Override this method in
3077 /// subclasses of Process.
3078 ///
3079 /// See GetMemoryRegionInfo for details of the logic.
3080 ///
3081 /// \param[in] load_addr
3082 /// The load address to query the range_info for. (non address bits
3083 /// removed)
3084 ///
3085 /// \param[out] range_info
3086 /// An range_info value containing the details of the range.
3087 ///
3088 /// \return
3089 /// An error value.
3091 MemoryRegionInfo &range_info) {
3093 "Process::DoGetMemoryRegionInfo() not supported");
3094 }
3095
3096 /// Provide an override value in the subclass for lldb's
3097 /// CPU-based logic for whether watchpoint exceptions are
3098 /// received before or after an instruction executes.
3099 ///
3100 /// If a Process subclass needs to override this architecture-based
3101 /// result, it may do so by overriding this method.
3102 ///
3103 /// \return
3104 /// No boolean returned means there is no override of the
3105 /// default architecture-based behavior.
3106 /// true is returned for targets where watchpoints are reported
3107 /// after the instruction has completed.
3108 /// false is returned for targets where watchpoints are reported
3109 /// before the instruction executes.
3110 virtual std::optional<bool> DoGetWatchpointReportedAfter() {
3111 return std::nullopt;
3112 }
3113
3114 /// Handle thread specific async interrupt and return the original thread
3115 /// that requested the async interrupt. It can be null if original thread
3116 /// has exited.
3117 ///
3118 /// \param[in] description
3119 /// Returns the stop reason description of the async interrupt.
3120 virtual lldb::ThreadSP
3121 HandleThreadAsyncInterrupt(uint8_t signo, const std::string &description) {
3122 return lldb::ThreadSP();
3123 }
3124
3125 /// The "private" side of resuming a process. This doesn't alter the state
3126 /// of m_run_lock, but just causes the process to resume.
3127 ///
3128 /// \return
3129 /// An Status object describing the success or failure of the resume.
3131
3132 // Called internally
3133 void CompleteAttach();
3134
3135 // NextEventAction provides a way to register an action on the next event
3136 // that is delivered to this process. There is currently only one next event
3137 // action allowed in the process at one time. If a new "NextEventAction" is
3138 // added while one is already present, the old action will be discarded (with
3139 // HandleBeingUnshipped called after it is discarded.)
3140 //
3141 // If you want to resume the process as a result of a resume action, call
3142 // RequestResume, don't call Resume directly.
3144 public:
3150
3151 NextEventAction(Process *process) : m_process(process) {}
3152
3153 virtual ~NextEventAction() = default;
3154
3156 virtual void HandleBeingUnshipped() {}
3158 virtual const char *GetExitString() = 0;
3159 void RequestResume() { m_process->m_resume_requested = true; }
3160
3161 protected:
3163 };
3164
3167 m_next_event_action_up->HandleBeingUnshipped();
3168
3169 m_next_event_action_up.reset(next_event_action);
3170 }
3171
3172 // This is the completer for Attaching:
3174 public:
3175 AttachCompletionHandler(Process *process, uint32_t exec_count);
3176
3177 ~AttachCompletionHandler() override = default;
3178
3179 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
3181 const char *GetExitString() override;
3182
3183 private:
3185 std::string m_exit_string;
3186 };
3187
3191 return false;
3192
3193 lldb::StateType state =
3194 m_current_private_state_thread_sp->GetPrivateState();
3195 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
3196 state != lldb::eStateExited;
3197 }
3198
3200
3201 /// Loads any plugins associated with asynchronous structured data and maps
3202 /// the relevant supported type name to the plugin.
3203 ///
3204 /// Processes can receive asynchronous structured data from the process
3205 /// monitor. This method will load and map any structured data plugins that
3206 /// support the given set of supported type names. Later, if any of these
3207 /// features are enabled, the process monitor is free to generate
3208 /// asynchronous structured data. The data must come in as a single \b
3209 /// StructuredData::Dictionary. That dictionary must have a string field
3210 /// named 'type', with a value that equals the relevant type name string
3211 /// (one of the values in \b supported_type_names).
3212 ///
3213 /// \param[in] supported_type_names
3214 /// An array of zero or more type names. Each must be unique.
3215 /// For each entry in the list, a StructuredDataPlugin will be
3216 /// searched for that supports the structured data type name.
3218 const StructuredData::Array &supported_type_names);
3219
3220 /// Route the incoming structured data dictionary to the right plugin.
3221 ///
3222 /// The incoming structured data must be a dictionary, and it must have a
3223 /// key named 'type' that stores a string value. The string value must be
3224 /// the name of the structured data feature that knows how to handle it.
3225 ///
3226 /// \param[in] object_sp
3227 /// When non-null and pointing to a dictionary, the 'type'
3228 /// key's string value is used to look up the plugin that
3229 /// was registered for that structured data type. It then
3230 /// calls the following method on the StructuredDataPlugin
3231 /// instance:
3232 ///
3233 /// virtual void
3234 /// HandleArrivalOfStructuredData(Process &process,
3235 /// llvm::StringRef type_name,
3236 /// const StructuredData::ObjectSP
3237 /// &object_sp)
3238 ///
3239 /// \return
3240 /// True if the structured data was routed to a plugin; otherwise,
3241 /// false.
3243
3244 /// Check whether the process supports memory tagging.
3245 ///
3246 /// \return
3247 /// true if the process supports memory tagging,
3248 /// false otherwise.
3249 virtual bool SupportsMemoryTagging() { return false; }
3250
3251 /// Does the final operation to read memory tags. E.g. sending a GDB packet.
3252 /// It assumes that ReadMemoryTags has checked that memory tagging is enabled
3253 /// and has expanded the memory range as needed.
3254 ///
3255 /// \param[in] addr
3256 /// Start of address range to read memory tags for.
3257 ///
3258 /// \param[in] len
3259 /// Length of the memory range to read tags for (in bytes).
3260 ///
3261 /// \param[in] type
3262 /// Type of tags to read (get this from a MemoryTagManager)
3263 ///
3264 /// \return
3265 /// The packed tag data received from the remote or an error
3266 /// if the read failed.
3267 virtual llvm::Expected<std::vector<uint8_t>>
3268 DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) {
3269 return llvm::createStringError(
3270 llvm::inconvertibleErrorCode(),
3271 llvm::formatv("{0} does not support reading memory tags",
3272 GetPluginName()));
3273 }
3274
3275 /// Does the final operation to write memory tags. E.g. sending a GDB packet.
3276 /// It assumes that WriteMemoryTags has checked that memory tagging is enabled
3277 /// and has packed the tag data.
3278 ///
3279 /// \param[in] addr
3280 /// Start of address range to write memory tags for.
3281 ///
3282 /// \param[in] len
3283 /// Length of the memory range to write tags for (in bytes).
3284 ///
3285 /// \param[in] type
3286 /// Type of tags to read (get this from a MemoryTagManager)
3287 ///
3288 /// \param[in] tags
3289 /// Packed tags to be written.
3290 ///
3291 /// \return
3292 /// Status telling you whether the write succeeded.
3293 virtual Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type,
3294 const std::vector<uint8_t> &tags) {
3296 "{0} does not support writing memory tags", GetPluginName());
3297 }
3298
3299 // Type definitions
3300 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
3302
3304 bool (*callback)(void *);
3305 void *baton;
3307 void *in_baton)
3308 : callback(in_callback), baton(in_baton) {}
3310 return callback == rhs.callback && baton == rhs.baton;
3311 }
3312 };
3313
3314 /// The PrivateStateThread struct gathers all the bits of state needed to
3315 /// manage handling Process events, from receiving them on the Private State
3316 /// to signaling when process events are broadcase publicly, to determining
3317 /// when various actors can act on the process. It also holds the current
3318 /// private state thread.
3319 /// These need to be swappable as a group to manage the temporary modal
3320 /// private state thread that we spin up when we need to run an expression on
3321 /// the private state thread.
3323 /// Why this PST exists. RunPrivateStateThread reads this directly to
3324 /// decide which Policy to push, rather than re-deriving it from a
3325 /// generic "is this an override PST" flag. This is the same enum
3326 /// Policy::CreatePrivateState()/PolicyStack::PushPrivateState() take, so
3327 /// there's a single purpose value flowing from PST creation through to
3328 /// the policy it pushes.
3330
3332 lldb::StateType private_state,
3333 llvm::StringRef thread_name,
3334 Purpose purpose = Purpose::Default)
3335 : m_process(process), m_public_state(public_state),
3336 m_private_state(private_state), m_purpose(purpose),
3337 m_thread_name(thread_name) {}
3338 // This returns false if we couldn't start up the thread. If that happens,
3339 // you won't be doing any debugging today.
3340 bool StartupThread();
3341
3342 bool IsOnThread(const HostThread &thread) const;
3343
3344 bool IsJoinable() { return m_private_state_thread.IsJoinable(); }
3345
3347 lldb::thread_result_t result = {};
3348 m_private_state_thread.Join(&result);
3349 m_private_state_thread.Reset();
3350 m_is_running = false;
3351 }
3352
3353 bool IsRunning() { return m_is_running; }
3354
3355 bool IsOverride() const { return m_purpose != Purpose::Default; }
3356
3357 void SetThreadName(llvm::StringRef new_name) { m_thread_name = new_name; }
3358
3360 return m_private_state.GetValue();
3361 }
3362
3363 lldb::StateType GetPublicState() const { return m_public_state.GetValue(); }
3364
3366 m_public_state.SetValue(new_value);
3367 }
3368
3370 m_private_state.SetValue(new_value);
3371 }
3372
3373 std::recursive_mutex &GetPrivateStateMutex() {
3374 return m_private_state.GetMutex();
3375 }
3376
3378 return m_private_state.GetValueNoLock();
3379 }
3380
3382 m_private_state.SetValueNoLock(new_state);
3383 }
3384
3386 m_public_state.SetValueNoLock(new_state);
3387 }
3388
3389 bool SetPublicRunLockToRunning() { return m_public_run_lock.SetRunning(); }
3390
3392 return m_private_run_lock.SetRunning();
3393 }
3394
3395 bool SetPublicRunLockToStopped() { return m_public_run_lock.SetStopped(); }
3396
3398 return m_private_run_lock.SetStopped();
3399 }
3400
3402
3404 ///< The process state that we show to client code. This will often differ
3405 ///< from the actual process state, for instance when we've stopped in the
3406 ///< middle of a ThreadPlan's operations, before we've decided to stop or
3407 ///< continue.
3409 ///< The actual state of our process
3411 ///< HostThread for the thread that watches for internal state events
3413 //< These are the locks that client code acquires both to wait on the
3414 //< process stopping, and then to ensure that it stays in the stopped state
3415 //< while the client code is operating on it. Again, we need a parallel
3416 //set, < one for public client code and one for code working on behalf of
3417 //the < private state management.
3420 bool m_is_running = false;
3422 ///< This will be the thread name given to the Private State HostThread when
3423 ///< it gets spun up.
3424 std::string m_thread_name;
3425 };
3426
3430 return m_current_private_state_thread_sp->SetPrivateRunLockToStopped();
3431 return false;
3432 }
3436 return m_current_private_state_thread_sp->SetPrivateRunLockToRunning();
3437 return false;
3438 }
3442 return m_current_private_state_thread_sp->SetPublicRunLockToStopped();
3443 return false;
3444 }
3448 return m_current_private_state_thread_sp->SetPublicRunLockToRunning();
3449 return false;
3450 }
3451
3452 std::recursive_mutex &GetPrivateStateMutex() {
3454 return m_current_private_state_thread_sp->GetPrivateStateMutex();
3455 }
3456
3462
3468
3471 return lldb::eStateUnloaded;
3472 return m_current_private_state_thread_sp->GetPrivateStateNoLock();
3473 }
3474
3477 m_current_private_state_thread_sp->SetPrivateStateNoLock(new_state);
3478 }
3479
3480 // Member variables
3481 std::weak_ptr<Target> m_target_wp; ///< The target that owns this process.
3483 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3484 // changed events into the private
3485 // state thread's listener.
3487 // broadcaster, used to
3488 // pause, resume & stop the
3489 // private state thread.
3490 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3491 // private state thread.
3492 /// This is filled on construction with the "main" private state which will
3493 /// be exposed to clients of this process. It won't have a running private
3494 /// state thread until you call StartupThread. This needs to be a pointer
3495 /// so I can transparently swap it out for the modal one, but there will
3496 /// always be a private state thread in this slot.
3497 std::shared_ptr<PrivateStateThread> m_current_private_state_thread_sp;
3498
3499 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3500 ///other alterations.
3501 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3502 ///created gets a unique integer ID that
3503 ///increments with each new instance
3504 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
3505 ///that won't get re-used.
3506 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3507 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3508 std::string m_exit_string; ///< A textual description of why a process exited.
3509 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3510 ///be safely accessed from multiple threads
3511 std::recursive_mutex m_thread_mutex;
3512 ThreadList m_thread_list_real; ///< The threads for this process as are known
3513 ///to the protocol we are debugging with
3514 ThreadList m_thread_list; ///< The threads for this process as the user will
3515 ///see them. This is usually the same as
3516 ///< m_thread_list_real, but might be different if there is an OS plug-in
3517 ///creating memory threads
3518 ThreadPlanStackMap m_thread_plans; ///< This is the list of thread plans for
3519 /// threads in m_thread_list, as well as
3520 /// threads we knew existed, but haven't
3521 /// determined that they have died yet.
3523 m_extended_thread_list; ///< Constituent for extended threads that may be
3524 /// generated, cleared on natural stops
3525 /// A list of address spaces for this process. Empty for single address space
3526 /// processes.
3527 std::vector<AddressSpaceInfo> m_address_spaces;
3528 lldb::RunDirection m_base_direction; ///< ThreadPlanBase run direction
3529 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3530 ///extended_thread_list was last updated
3531 QueueList
3532 m_queue_list; ///< The list of libdispatch queues at a given stop point
3533 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3534 ///last fetched
3536 m_watchpoint_resource_list; ///< Watchpoint resources currently in use.
3537 std::vector<Notifications> m_notifications; ///< The list of notifications
3538 ///that this process can deliver.
3539 std::vector<lldb::addr_t> m_image_tokens;
3541 m_breakpoint_site_list; ///< This is the list of breakpoint
3542 /// locations we intend to insert in
3543 /// the target.
3547 /// by the expression
3548 /// parser to validate
3549 /// data that
3550 /// expressions use.
3554 m_unix_signals_sp; /// This is the current signal set for this process.
3559 std::recursive_mutex m_stdio_communication_mutex;
3560 /// The secondary side of the pseudo terminal the inferior uses for stdio.
3561 /// std::nullopt if no pseudo terminal is open.
3563 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3564 /// server
3565 std::string m_stdout_data;
3566 std::string m_stderr_data;
3567 std::recursive_mutex m_profile_data_comm_mutex;
3568 std::vector<std::string> m_profile_data;
3573 bool m_should_detach; /// Should we detach if the process object goes away
3574 /// with an explicit call to Kill or Detach?
3576 std::recursive_mutex m_language_runtimes_mutex;
3578 std::unique_ptr<NextEventAction> m_next_event_action_up;
3579 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3581 bool m_resume_requested; // If m_currently_handling_event or
3582 // m_currently_handling_do_on_removals are true,
3583 // Resume will only request a resume, using this
3584 // flag to check.
3585
3586 lldb::tid_t m_interrupt_tid; /// The tid of the thread that issued the async
3587 /// interrupt, used by thread plan timeout. It
3588 /// can be LLDB_INVALID_THREAD_ID to indicate
3589 /// user level async interrupt.
3590
3591 /// This is set at the beginning of Process::Finalize() to stop functions
3592 /// from looking up or creating things during or after a finalize call.
3593 std::atomic<bool> m_finalizing;
3594 // When we are "Finalizing" we need to do some cleanup. But if the Finalize
3595 // call is coming in the Destructor, we can't do any actual work in the
3596 // process because that is likely to call "shared_from_this" which crashes
3597 // if run while destructing. We use this flag to determine that.
3598 std::atomic<bool> m_destructing;
3599
3600 /// Mask for code an data addresses.
3601 /// The default value LLDB_INVALID_ADDRESS_MASK means no mask has been set,
3602 /// and addresses values should not be modified.
3603 /// In these masks, the bits are set to 1 indicate bits that are not
3604 /// significant for addressing.
3605 /// The highmem masks are for targets where we may have different masks
3606 /// for low memory versus high memory addresses, and they will be left
3607 /// as LLDB_INVALID_ADDRESS_MASK normally, meaning the base masks
3608 /// should be applied to all addresses.
3609 /// @{
3614 /// @}
3615
3618 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3619 /// coalescing in
3620 /// ShouldBroadcastEvent.
3621 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3623 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3624 // don't support the ability to modify
3625 // the stack.
3627 llvm::StringMap<lldb::StructuredDataPluginSP> m_structured_data_plugin_map;
3628
3630
3631 std::unique_ptr<UtilityFunction> m_dlopen_utility_func_up;
3633 /// The error from the one attempt to create m_dlopen_utility_func_up,
3634 /// set only if that attempt failed.
3636
3637 /// Per process source file cache.
3639
3640 /// A repository for extra crash information, consulted in
3641 /// GetExtendedCrashInformation.
3643
3653
3655 std::recursive_mutex m_delayed_breakpoints_mutex;
3656
3657 llvm::Error FlushDelayedBreakpoints();
3658
3659 void RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3660 uint8_t *buf) const;
3661
3662 /// Cache memory, restoring the original bytes under any breakpoint.
3663 void AddCacheData(lldb::addr_t addr,
3664 const lldb::WritableDataBufferSP &data_buffer_sp);
3665
3667
3668 void SetPublicState(lldb::StateType new_state, bool restarted);
3669
3670 void SetPrivateState(lldb::StateType state);
3671
3672 // Starts the private state thread and assigns it to
3673 // m_current_private_state_thread_sp. If backup_ptr is non-null, this is
3674 // a "secondary" thread, and the current thread will be backed up into
3675 // backup_ptr before being replaced by the new thread. Pass a non-null
3676 // backup_ptr in the case where you have to temporarily spin up a secondary
3677 // state thread to handle events from a hand-called function on the primary
3678 // private state thread.
3680 lldb::StateType state, bool run_lock_is_running,
3681 std::shared_ptr<PrivateStateThread> *backup_ptr = nullptr);
3682
3684
3686
3688
3689private:
3690 // Starts up the private state thread that will watch for events from the
3691 // debugee.
3692
3695
3696protected:
3697 void HandlePrivateEvent(lldb::EventSP &event_sp);
3698
3700
3702 const Timeout<std::micro> &timeout);
3703
3704 // This waits for both the state change broadcaster, and the control
3705 // broadcaster. If control_only, it only waits for the control broadcaster.
3706
3707 bool GetEventsPrivate(lldb::EventSP &event_sp,
3708 const Timeout<std::micro> &timeout, bool control_only);
3709
3712 const Timeout<std::micro> &timeout);
3713
3714 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3715 Status &error);
3716
3717 void AppendSTDOUT(const char *s, size_t len);
3718
3719 void AppendSTDERR(const char *s, size_t len);
3720
3721 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3722
3723 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3724 size_t src_len);
3725
3726 /// Stop monitoring the process' stdio.
3727 ///
3728 /// \param drain
3729 /// Whether to read any remaining stdio buffers before.
3730 void StopSTDIOMonitoring(bool drain);
3731
3732 /// Close m_stdio_secondary_fd if it is still open.
3734
3735 bool PushProcessIOHandler();
3736
3737 bool PopProcessIOHandler();
3738
3740
3742 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3743 return static_cast<bool>(m_process_input_reader);
3744 }
3745
3747
3749
3750 void LoadOperatingSystemPlugin(bool flush);
3751
3753
3754 // Updates the state of site.
3755 // This should be used by derived Process classes after they have changed the
3756 // state of a site.
3757 void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled = true) {
3758 site.SetEnabled(is_enabled);
3759 }
3760
3761private:
3762 Status DestroyImpl(bool force_kill);
3763
3764#ifndef NDEBUG
3765 /// Re-read \a size bytes at \a addr and assert they match the cache.
3766 void VerifyMemoryRead(lldb::addr_t addr, const void *cache_buf,
3767 size_t cache_bytes_read, size_t size,
3768 const Status &cache_error);
3769#endif
3770
3771 /// This is the part of the event handling that for a process event. It
3772 /// decides what to do with the event and returns true if the event needs to
3773 /// be propagated to the user, and false otherwise. If the event is not
3774 /// propagated, this call will most likely set the target to executing
3775 /// again. There is only one place where this call should be called,
3776 /// HandlePrivateEvent. Don't call it from anywhere else...
3777 ///
3778 /// \param[in] event_ptr
3779 /// This is the event we are handling.
3780 ///
3781 /// \return
3782 /// Returns \b true if the event should be reported to the
3783 /// user, \b false otherwise.
3784 bool ShouldBroadcastEvent(Event *event_ptr);
3785
3786 void ControlPrivateStateThread(uint32_t signal);
3787
3789 lldb::EventSP &event_sp);
3790
3791 lldb::EventSP CreateEventFromProcessState(uint32_t event_type);
3792
3793 Process(const Process &) = delete;
3794 const Process &operator=(const Process &) = delete;
3795};
3796
3797/// RAII guard that should be acquired when an utility function is called within
3798/// a given process.
3801
3802public:
3804 if (m_process)
3805 m_process->SetRunningUtilityFunction(true);
3806 }
3808 if (m_process)
3809 m_process->SetRunningUtilityFunction(false);
3810 }
3811};
3812
3813} // namespace lldb_private
3814
3815#endif // LLDB_TARGET_PROCESS_H
static llvm::raw_ostream & error(Stream &strm)
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
An architecture specification class.
Definition ArchSpec.h:32
void Clear()
Clears the object state.
Definition ArchSpec.cpp:558
A command line argument class.
Definition Args.h:33
Class that manages the actual breakpoint that will be inserted into the running program.
void SetEnabled(bool enabled)
Sets whether the current breakpoint site is enabled or not.
uint32_t AddListener(const lldb::ListenerSP &listener_sp, uint32_t event_mask)
Listen for any events specified by event_mask.
Broadcaster(lldb::BroadcasterManagerSP manager_sp, std::string name)
Construct with a broadcaster with a name.
An data extractor class.
A class to manage flag bits.
Definition Debugger.h:106
Encapsulates dynamic check functions used by expressions.
A plug-in interface definition class for dynamic loaders.
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:56
Bundles a value of type T with the Mutex that guards it.
Definition Locked.h:178
Class used by the Process to hold a list of its JITLoaders.
A collection class for Module objects.
Definition ModuleList.h:127
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:92
A plug-in interface definition class for halted OS helpers.
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:81
virtual llvm::StringRef GetPluginName()=0
A C++ wrapper class for providing threaded access to a value of type T.
Definition Predicate.h:42
An address in a process, qualified by an address space.
void SetDetachOnError(bool enable)
Definition Process.h:201
bool ProcessInfoSpecified() const
Definition Process.h:189
ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
Definition Process.h:145
void SetContinueOnceAttached(bool b)
Definition Process.h:166
uint32_t GetResumeCount() const
Definition Process.h:168
void SetResumeCount(uint32_t c)
Definition Process.h:170
void SetProcessPluginName(llvm::StringRef plugin)
Definition Process.h:176
bool GetContinueOnceAttached() const
Definition Process.h:164
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3240
llvm::StringRef GetProcessPluginName() const
Definition Process.h:172
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
lldb::pid_t GetParentProcessID() const
llvm::StringRef GetProcessPluginName() const
void SetRunningUserExpression(bool on)
Definition Process.h:301
lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const
Definition Process.h:323
const ProcessModID & operator=(const ProcessModID &rhs)
Definition Process.h:236
uint32_t GetMemoryID() const
Definition Process.h:267
friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs)
Definition Process.h:352
uint32_t m_running_utility_function
Definition Process.h:348
ProcessModID(const ProcessModID &rhs)
Definition Process.h:233
void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp)
Definition Process.h:319
uint32_t m_running_user_expression
Definition Process.h:347
uint32_t GetStopID() const
Definition Process.h:265
bool IsRunningUtilityFunction() const
Definition Process.h:261
uint32_t m_last_natural_stop_id
Definition Process.h:343
bool IsLastResumeForUserExpression() const
Definition Process.h:285
uint32_t GetResumeID() const
Definition Process.h:268
bool IsRunningExpression() const
Definition Process.h:294
uint32_t m_last_user_expression_resume
Definition Process.h:346
uint32_t GetLastNaturalStopID() const
Definition Process.h:266
lldb::EventSP m_last_natural_stop_event
Definition Process.h:349
uint32_t GetLastUserExpressionResumeID() const
Definition Process.h:269
bool MemoryIDEqual(const ProcessModID &compare) const
Definition Process.h:273
void Dump(Stream &stream) const
Definition Process.h:329
bool StopIDEqual(const ProcessModID &compare) const
Definition Process.h:277
void SetRunningUtilityFunction(bool on)
Definition Process.h:308
bool GetSteppingRunsAllThreads() const
Definition Process.cpp:394
void SetStopOnSharedLibraryEvents(bool stop)
Definition Process.cpp:319
std::unique_ptr< ProcessExperimentalProperties > m_experimental_properties_up
Definition Process.h:131
FollowForkMode GetFollowForkMode() const
Definition Process.cpp:430
uint32_t GetVirtualAddressableBits() const
Definition Process.cpp:252
void SetIgnoreBreakpointsInExpressions(bool ignore)
Definition Process.cpp:297
bool GetUnwindOnErrorInExpressions() const
Definition Process.cpp:302
std::chrono::seconds GetInterruptTimeout() const
Definition Process.cpp:387
bool GetDisableLangRuntimeUnwindPlans() const
Definition Process.cpp:324
void SetDetachKeepsStopped(bool keep_stopped)
Definition Process.cpp:351
void SetDisableLangRuntimeUnwindPlans(bool disable)
Definition Process.cpp:330
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:380
void SetVirtualAddressableBits(uint32_t bits)
Definition Process.cpp:258
bool GetStopOnSharedLibraryEvents() const
Definition Process.cpp:313
void SetHighmemVirtualAddressableBits(uint32_t bits)
Definition Process.cpp:269
void SetOSPluginReportsAllThreads(bool does_report)
Definition Process.cpp:424
void SetUnwindOnErrorInExpressions(bool ignore)
Definition Process.cpp:308
bool GetUseDelayedBreakpoints() const
Definition Process.cpp:374
FileSpec GetPythonOSPluginPath() const
Definition Process.cpp:247
void SetPythonOSPluginPath(const FileSpec &file)
Definition Process.cpp:286
void SetExtraStartupCommands(const Args &args)
Definition Process.cpp:242
bool GetOSPluginReportsAllThreads() const
Definition Process.cpp:414
bool GetWarningsUnsupportedLanguage() const
Definition Process.cpp:362
uint32_t GetHighmemVirtualAddressableBits() const
Definition Process.cpp:263
OptionValueProperties * GetExperimentalProperties() const
Definition Process.cpp:407
bool GetIgnoreBreakpointsInExpressions() const
Definition Process.cpp:291
uint64_t GetMemoryCacheLineSize() const
Definition Process.cpp:229
ProcessProperties(lldb_private::Process *process)
Definition Process.cpp:169
RAII helper around the read-lock side of ProcessRunLock.
Read/write lock around the process running/stopped state.
EventActionResult HandleBeingInterrupted() override
Definition Process.cpp:3232
EventActionResult PerformAction(lldb::EventSP &event_sp) override
Definition Process.cpp:3175
AttachCompletionHandler(Process *process, uint32_t exec_count)
Definition Process.cpp:3164
CoreArgs(const std::string &args, bool might_be_truncated)
Definition Process.h:1576
void Format(Stream &stream) const
Definition Process.h:1579
virtual EventActionResult HandleBeingInterrupted()=0
virtual const char * GetExitString()=0
virtual EventActionResult PerformAction(lldb::EventSP &event_sp)=0
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4819
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
Definition Process.cpp:4587
static void AddRestartedReason(Event *event_ptr, const char *reason)
Definition Process.cpp:4856
void SetInterrupted(bool new_value)
Definition Process.h:504
lldb::ProcessSP GetProcessSP() const
Definition Process.h:452
std::vector< std::string > m_restarted_reasons
Definition Process.h:512
void SetRestarted(bool new_value)
Definition Process.h:502
static void SetRestartedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4827
const ProcessEventData & operator=(const ProcessEventData &)=delete
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4803
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4873
bool ForwardEventToPendingListeners(Event *event_ptr) override
This will be queried for a Broadcaster with a primary and some secondary listeners after the primary ...
Definition Process.cpp:4691
ProcessEventData(const ProcessEventData &)=delete
llvm::StringRef GetFlavor() const override
Definition Process.cpp:4583
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition Process.cpp:4864
const char * GetRestartedReasonAtIndex(size_t idx)
Definition Process.h:459
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4811
lldb::StateType GetState() const
Definition Process.h:454
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Process.cpp:4792
static llvm::StringRef GetFlavorString()
Definition Process.cpp:4579
void DoOnRemoval(Event *event_ptr) override
Definition Process.cpp:4705
void AddRestartedReason(const char *reason)
Definition Process.h:506
void Dump(Stream *s) const override
Definition Process.cpp:4779
ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
Definition Process.h:2479
A plug-in interface definition class for debugging a process.
Definition Process.h:369
virtual Status EnableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2274
Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.cpp:3255
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
Definition Process.cpp:6800
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3556
friend class ProcessProperties
Definition Process.h:2491
virtual void DidVForkDone()
Called after reported vfork completion.
Definition Process.h:1056
virtual Status DoSignal(int signal)
Sends a process a UNIX signal signal.
Definition Process.h:1217
virtual Status WillResume()
Called before resuming to a process.
Definition Process.h:1104
std::mutex m_process_input_reader_mutex
Definition Process.h:3557
lldb::addr_t m_code_address_mask
Mask for code an data addresses.
Definition Process.h:3610
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1608
std::vector< lldb::addr_t > m_image_tokens
Definition Process.h:3539
virtual Status DoHalt(bool &caused_stop)
Halts a running process.
Definition Process.h:1164
virtual void DidLaunch()
Called after launching a process.
Definition Process.h:1096
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1986
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:554
lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const
Definition Process.h:1529
lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner, bool use_hardware)
Definition Process.cpp:1805
virtual Status WillSignal()
Called before sending a signal to a process.
Definition Process.h:1211
void ResetImageToken(size_t token)
Definition Process.cpp:6551
lldb::JITLoaderListUP m_jit_loaders_up
Definition Process.h:3545
lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process, this also clears the allocated memory.
Definition Process.cpp:2753
void SetNextEventAction(Process::NextEventAction *next_event_action)
Definition Process.h:3165
Status Destroy(bool force_kill)
Kills the process and shuts down all threads that were spawned to track and monitor the process.
Definition Process.cpp:3864
virtual Status WillDetach()
Called before detaching from a process.
Definition Process.h:1181
virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.h:1088
virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error)
Puts data into this process's STDIN.
Definition Process.h:2248
StopPointSiteList< lldb_private::BreakpointSite > m_breakpoint_site_list
This is the list of breakpoint locations we intend to insert in the target.
Definition Process.h:3541
void ControlPrivateStateThread(uint32_t signal)
Definition Process.cpp:4235
ThreadList & GetThreadList()
Definition Process.h:2372
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7218
virtual DataExtractor GetAuxvData()
Definition Process.cpp:3144
virtual std::optional< uint32_t > GetWatchpointSlotCount()
Get the number of watchpoints supported by this target.
Definition Process.h:2051
void SetShadowListener(lldb::ListenerSP shadow_listener_sp)
The "ShadowListener" for a process is just an ordinary Listener that listens for all the Process even...
Definition Process.h:641
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:486
void PrintWarningUnsupportedLanguage(const SymbolContext &sc)
Print a user-visible warning about a function written in a language that this version of LLDB doesn't...
Definition Process.cpp:6476
Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state, lldb::EventSP &event_sp)
Definition Process.cpp:2943
std::vector< std::string > m_profile_data
Definition Process.h:3568
bool m_can_interpret_function_calls
Definition Process.h:3623
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1378
void PruneThreadPlans()
Prune ThreadPlanStacks for all unreported threads.
Definition Process.cpp:1262
MemoryRegionInfoCache m_memory_region_infos_cache
Definition Process.h:3571
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3959
virtual void DidExit()
Definition Process.h:1465
std::string m_stdout_data
Remember if stdin must be forwarded to remote debug server.
Definition Process.h:3565
bool RemoveInvalidMemoryRange(const LoadRange &region)
Definition Process.cpp:6244
DelayedBreakpointCache m_delayed_breakpoints
Definition Process.h:3654
uint32_t GetNextThreadIndexID(uint64_t thread_id)
Definition Process.cpp:1301
Status PrivateResume()
The "private" side of resuming a process.
Definition Process.cpp:3584
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition Process.cpp:1604
QueueList::QueueIterable Queues()
Definition Process.h:2408
void SetSTDIOFileDescriptor(int file_descriptor, std::optional< int > secondary_fd=std::nullopt)
Associates a file descriptor with the process' STDIO handling and configures an asynchronous reading ...
Definition Process.cpp:5031
void SendAsyncInterrupt(Thread *thread=nullptr)
Send an async interrupt request.
Definition Process.cpp:4283
uint32_t GetResumeID() const
Definition Process.h:1519
void AddInvalidMemoryRegion(const LoadRange &region)
Definition Process.cpp:6240
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6434
virtual bool WarnBeforeDetach() const
Before lldb detaches from a process, it warns the user that they are about to lose their debug sessio...
Definition Process.h:1610
InstrumentationRuntimeCollection m_instrumentation_runtimes
Definition Process.h:3577
llvm::Error ExecuteBreakpointSiteAction(BreakpointSite &site, Process::BreakpointAction action, bool forbid_delay)
Performs action on site.
Definition Process.cpp:1648
std::atomic< bool > m_destructing
Definition Process.h:3598
virtual void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid, bool is_expression_fork=false)
Called after a reported vfork.
Definition Process.h:1052
std::shared_ptr< PrivateStateThread > m_current_private_state_thread_sp
This is filled on construction with the "main" private state which will be exposed to clients of this...
Definition Process.h:3497
virtual llvm::Error UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action)
Definition Process.cpp:1792
virtual Status DoGetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
Definition Process.h:3090
@ eBroadcastInternalStateControlResume
Definition Process.h:400
@ eBroadcastInternalStateControlStop
Definition Process.h:398
@ eBroadcastInternalStateControlPause
Definition Process.h:399
int GetExitStatus()
Get the exit status for a process.
Definition Process.cpp:1068
OperatingSystem * GetOperatingSystem()
Definition Process.h:2517
lldb::ExpressionResults RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp, const EvaluateExpressionOptions &requested_options, DiagnosticManager &diagnostic_manager)
Definition Process.cpp:5269
Status WillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition Process.cpp:3251
virtual Status DoDetach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.h:1188
std::unique_ptr< UtilityFunction > m_dlopen_utility_func_up
Definition Process.h:3631
void SetRunningUtilityFunction(bool on)
Definition Process.cpp:1523
void DisableAllBreakpointSites()
Definition Process.cpp:1617
uint32_t m_process_unique_id
Each lldb_private::Process class that is created gets a unique integer ID that increments with each n...
Definition Process.h:3501
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
Definition Process.cpp:2540
Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr, AddressRange range_bounds)
Find the next branch instruction to set a breakpoint on.
Definition Process.cpp:6557
virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr, uint32_t &permissions)
Attempt to get the attributes for a region of memory in the process.
Definition Process.cpp:2845
static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream, SelectMostRelevant select_most_relevant, bool &pop_process_io_handler)
Centralize the code that handles and prints descriptions for process state changes.
Definition Process.cpp:796
bool SetPublicRunLockToRunning()
Definition Process.h:3445
virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error)
Get any available profile data.
Definition Process.cpp:4962
void CloseSTDIOSecondaryFileDescriptor()
Close m_stdio_secondary_fd if it is still open.
Definition Process.cpp:5090
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6355
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2738
std::unique_ptr< NextEventAction > m_next_event_action_up
Definition Process.h:3578
void SetHighmemDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6342
bool PruneThreadPlansForTID(lldb::tid_t tid)
Prune ThreadPlanStacks for unreported threads.
Definition Process.cpp:1258
virtual void DidDetach()
Called after detaching from a process.
Definition Process.h:1198
virtual llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > DoReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Reads each range individually via ReadMemoryFromInferior, bypassing the memory cache.
Definition Process.cpp:2173
Status EnableBreakpointSiteByID(lldb::user_id_t break_id)
Definition Process.cpp:1685
ProcessModID GetModID() const
Get the Modification ID of the process.
Definition Process.h:1513
lldb::RunDirection GetBaseDirection() const
Get the base run direction for the process.
Definition Process.h:2928
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2461
size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error)
Definition Process.cpp:2695
virtual Status Launch(ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.cpp:2904
DynamicCheckerFunctions * GetDynamicCheckers()
Definition Process.h:2527
std::mutex m_run_thread_plan_lock
Definition Process.h:3626
static void SettingsInitialize()
Definition Process.cpp:5132
virtual StructuredData::DictionarySP GetMetadata()
Fetch process defined metadata.
Definition Process.h:2784
virtual void DumpPluginHistory(Stream &s)
The underlying plugin might store the low-level communication history for this session.
Definition Process.h:607
static constexpr llvm::StringRef AttachSynchronousHijackListenerName
Definition Process.h:416
void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, const lldb::StructuredDataPluginSP &plugin_sp)
Broadcasts the given structured data object from the given plugin.
Definition Process.cpp:4946
void Flush()
Flush all data in the process.
Definition Process.cpp:6282
bool m_clear_thread_plans_on_stop
Definition Process.h:3616
lldb::ProcessSP CalculateProcess() override
Definition Process.h:2627
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a null-terminated C string from memory.
Definition Process.cpp:2415
void ResumePrivateStateThread()
Definition Process.cpp:4217
void MapSupportedStructuredDataPlugins(const StructuredData::Array &supported_type_names)
Loads any plugins associated with asynchronous structured data and maps the relevant supported type n...
Definition Process.cpp:6677
bool GetEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, bool control_only)
Definition Process.cpp:1051
lldb::ABISP m_abi_sp
This is the current signal set for this process.
Definition Process.h:3555
virtual void DidSignal()
Called after sending a signal to a process.
Definition Process.h:1235
size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2114
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2292
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3158
void RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size, uint8_t *buf) const
Definition Process.cpp:1861
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3506
lldb::StateType GetPrivateState() const
Definition Process.h:3463
void SetPrivateStateNoLock(lldb::StateType new_state)
Definition Process.h:3475
bool DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid, lldb::DescriptionLevel desc_level, bool internal, bool condense_trivial, bool skip_unreported_plans)
Dump the thread plans associated with thread with tid.
Definition Process.cpp:1267
lldb::ListenerSP m_private_state_listener_sp
Definition Process.h:3490
uint32_t m_extended_thread_stop_id
The natural stop id when extended_thread_list was last updated.
Definition Process.h:3529
bool PreResumeActionCallback(void *)
Definition Process.h:2714
lldb::RunDirection m_base_direction
ThreadPlanBase run direction.
Definition Process.h:3528
Range< lldb::addr_t, lldb::addr_t > LoadRange
Definition Process.h:403
static constexpr llvm::StringRef ResumeSynchronousHijackListenerName
Definition Process.h:420
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3757
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2572
QueueList m_queue_list
The list of libdispatch queues at a given stop point.
Definition Process.h:3532
void ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6268
virtual Status WillDestroy()
Definition Process.h:1223
lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context)
Definition Process.cpp:1294
std::vector< PreResumeCallbackAndBaton > m_pre_resume_actions
Definition Process.h:3579
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2774
lldb::StateType GetStateChangedEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:1033
void LoadOperatingSystemPlugin(bool flush)
Definition Process.cpp:2895
lldb::StructuredDataPluginSP GetStructuredDataPlugin(llvm::StringRef type_name) const
Returns the StructuredDataPlugin associated with a given type name, if there is one.
Definition Process.cpp:4954
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3544
ThreadList & GetExtendedThreadList()
Definition Process.h:2383
void ResetExtendedCrashInfoDict()
Definition Process.h:2794
AddressRanges FindRangesInMemory(const uint8_t *buf, uint64_t size, const AddressRanges &ranges, size_t alignment, size_t max_matches, Status &error)
Definition Process.cpp:2247
virtual bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec)
Try to fetch the module specification for a module with the given file name and architecture.
Definition Process.cpp:6534
virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Actually do the writing of memory to a process.
Definition Process.h:1781
virtual llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request)
Get binary data given a trace technology and a data identifier.
Definition Process.h:3005
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2727
std::recursive_mutex m_stdio_communication_mutex
Definition Process.h:3559
static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp, llvm::StringRef plugin_name, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
Find a Process plug-in that can debug module using the currently selected architecture.
Definition Process.cpp:443
std::map< lldb::LanguageType, lldb::LanguageRuntimeSP > LanguageRuntimeCollection
Definition Process.h:3301
virtual bool SupportsReverseDirection()
Reports whether this process supports reverse execution.
Definition Process.h:1111
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition Process.h:3536
Status DisableBreakpointSiteByID(lldb::user_id_t break_id)
Definition Process.cpp:1633
llvm::Expected< const MemoryTagManager * > GetMemoryTagManager()
If this architecture and process supports memory tagging, return a tag manager that can be used to ma...
Definition Process.cpp:6865
~Process() override
Destructor.
Definition Process.cpp:578
virtual llvm::Expected< LoadedModuleInfoList > GetLoadedModuleList()
Query remote GDBServer for a detailed loaded library list.
Definition Process.h:712
virtual Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, const std::vector< uint8_t > &tags)
Does the final operation to write memory tags.
Definition Process.h:3293
friend class StopInfo
Definition Process.h:374
std::recursive_mutex m_profile_data_comm_mutex
Definition Process.h:3567
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1713
std::vector< AddressSpaceInfo > m_address_spaces
A list of address spaces for this process.
Definition Process.h:3527
lldb::InstrumentationRuntimeSP GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
Definition Process.cpp:6525
ProcessRunLock::ProcessRunLocker StopLocker
Definition Process.h:410
Status ResumeSynchronous(Stream *stream)
Resume a process, and wait for it to stop.
Definition Process.cpp:1395
virtual Status SendEventData(const char *data)
Definition Process.h:2726
lldb::addr_t FixAnyAddress(lldb::addr_t pc)
Use this method when you do not know, or do not care what kind of address you are fixing.
Definition Process.cpp:6361
virtual Status DoWillLaunch(Module *module)
Called before launching to a process.
Definition Process.h:1069
virtual Status ConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.cpp:3533
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4925
llvm::StringMap< lldb::StructuredDataPluginSP > m_structured_data_plugin_map
Definition Process.h:3627
SourceManager::SourceFileCache m_source_file_cache
Per process source file cache.
Definition Process.h:3638
virtual Status DisableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2279
size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source, bool stop_format)
Definition Process.cpp:6194
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Process.cpp:4893
Event * PeekAtStateChangedEvents()
Definition Process.cpp:1016
std::vector< Notifications > m_notifications
The list of notifications that this process can deliver.
Definition Process.h:3537
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition Process.cpp:1305
llvm::SmallVector< std::optional< uint64_t > > ReadUnsignedIntegersFromMemory(llvm::ArrayRef< lldb::addr_t > addresses, unsigned byte_size)
Use Process::ReadMemoryRanges to efficiently read multiple unsigned integers from memory at once.
Definition Process.cpp:2502
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6540
llvm::Error FlushDelayedBreakpoints()
Definition Process.cpp:1775
lldb::StateType GetPrivateStateNoLock() const
Definition Process.h:3469
virtual void DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr, const uint8_t *buf, size_t size, AddressRanges &matches, size_t alignment, size_t max_matches)
Definition Process.cpp:2216
virtual bool DestroyRequiresHalt()
Definition Process.h:1229
lldb::EventSP CreateEventFromProcessState(uint32_t event_type)
Definition Process.cpp:4919
StructuredData::DictionarySP m_crash_info_dict_sp
A repository for extra crash information, consulted in GetExtendedCrashInformation.
Definition Process.h:3642
Status CalculateCoreFileSaveRanges(const SaveCoreOptions &core_options, CoreFileMemoryRanges &ranges)
Helper function for Process::SaveCore(...) that calculates the address ranges that should be saved.
Definition Process.cpp:7149
lldb::ThreadSP CalculateThread() override
Definition Process.h:2629
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4891
bool SetPublicRunLockToStopped()
Definition Process.h:3439
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6335
virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo()
Definition Process.h:1406
virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address, lldb::addr_t image_count)
Retrieve the list of shared libraries that are loaded for this process This method is used on pre-mac...
Definition Process.h:1350
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3969
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.cpp:3808
void UpdateThreadListIfNeeded()
Definition Process.cpp:1167
static constexpr llvm::StringRef LaunchSynchronousHijackListenerName
Definition Process.h:418
virtual llvm::Expected< std::vector< lldb::addr_t > > ReadMemoryTags(lldb::addr_t addr, size_t len)
Read memory tags for the range addr to addr+len.
Definition Process.cpp:6884
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:589
virtual void DidResume()
Called after resuming a process.
Definition Process.h:1139
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6367
void SetCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6323
AllocatedMemoryCache m_allocated_memory_cache
Definition Process.h:3572
ThreadList::ThreadIterable Threads()
Definition Process.h:2385
virtual Status LoadCore()
Definition Process.cpp:3075
uint32_t GetUniqueID() const
Definition Process.h:561
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2551
std::mutex m_exit_status_mutex
Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads.
Definition Process.h:3509
Status Signal(int signal)
Sends a process a UNIX signal signal.
Definition Process.cpp:3949
void SetDynamicLoader(lldb::DynamicLoaderUP dyld)
Definition Process.cpp:3140
ThreadPlanStackMap m_thread_plans
This is the list of thread plans for threads in m_thread_list, as well as threads we knew existed,...
Definition Process.h:3518
std::recursive_mutex m_thread_mutex
Definition Process.h:3511
virtual Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure asynchronous structured data feature.
Definition Process.cpp:6669
Guarded< std::optional< int >, std::mutex > m_stdio_secondary_fd
The secondary side of the pseudo terminal the inferior uses for stdio.
Definition Process.h:3562
virtual Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.h:969
bool m_currently_handling_do_on_removals
Definition Process.h:3580
void HandlePrivateEvent(lldb::EventSP &event_sp)
Definition Process.cpp:4295
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4939
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1319
virtual Status DoWillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition Process.h:952
ProcessRunLock & GetRunLock()
Definition Process.cpp:6278
friend class MemoryCache
Definition Process.h:377
virtual Status DoLoadCore()
Definition Process.h:632
Predicate< uint32_t > m_iohandler_sync
Definition Process.h:3569
virtual llvm::Error TraceStop(const TraceStopRequest &request)
Stop tracing a live process or its threads.
Definition Process.h:2980
LanguageRuntimeCollection m_language_runtimes
Should we detach if the process object goes away with an explicit call to Kill or Detach?
Definition Process.h:3575
virtual Status GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list)
Obtain all the mapped memory regions within this process.
Definition Process.cpp:6632
size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, Status &error)
Definition Process.cpp:2584
virtual bool StopNoticingNewThreads()
Call this to turn off the stop & notice new threads mode.
Definition Process.h:2619
virtual llvm::VersionTuple GetHostMacCatalystVersion()
Definition Process.h:1263
void SetRunningUserExpression(bool on)
Definition Process.cpp:1519
enum lldb_private::Process::@120260360120067272255351105340035202127223005263 m_can_jit
bool IsPossibleDynamicValue(ValueObject &in_value)
Definition Process.cpp:1583
uint32_t GetIOHandlerID() const
Definition Process.h:2434
std::recursive_mutex m_delayed_breakpoints_mutex
Definition Process.h:3655
llvm::Expected< lldb::ModuleSP > ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Creates and populates a module using an in-memory object file.
Definition Process.cpp:2812
Process(const Process &)=delete
const Target & GetTarget() const
Get the const target object pointer for this module.
Definition Process.h:1277
Status m_dlopen_utility_func_error
The error from the one attempt to create m_dlopen_utility_func_up, set only if that attempt failed.
Definition Process.h:3635
virtual FileSpec GetCoreFile() const
Provide a way to retrieve the core dump file that is loaded for debugging.
Definition Process.h:1568
virtual llvm::Error TraceStart(const llvm::json::Value &request)
Start tracing a process or its threads.
Definition Process.h:2968
void RemoveConstituentFromBreakpointSite(lldb::user_id_t site_id, lldb::user_id_t constituent_id, lldb::BreakpointSiteSP &bp_site_sp)
Definition Process.cpp:1847
void VerifyMemoryRead(lldb::addr_t addr, const void *cache_buf, size_t cache_bytes_read, size_t size, const Status &cache_error)
Re-read size bytes at addr and assert they match the cache.
Definition Process.cpp:2080
lldb::addr_t FindInMemory(lldb::addr_t low, lldb::addr_t high, const uint8_t *buf, size_t size)
Find a pattern within a memory region.
Definition Process.cpp:3700
lldb::OperatingSystemUP m_os_up
Definition Process.h:3551
StructuredData::DictionarySP GetExtendedCrashInfoDict()
Fetch extended crash information held by the process.
Definition Process.h:2789
uint32_t GetLastNaturalStopID() const
Definition Process.h:1525
lldb::StateType WaitForProcessToStop(const Timeout< std::micro > &timeout, lldb::EventSP *event_sp_ptr=nullptr, bool wait_always=true, lldb::ListenerSP hijack_listener=lldb::ListenerSP(), Stream *stream=nullptr, bool use_run_lock=true, SelectMostRelevant select_most_relevant=DoNoSelectMostRelevantFrame)
Definition Process.cpp:728
friend class ThreadPlanSingleThreadTimeout
Definition Process.h:378
virtual void ForceScriptedState(lldb::StateType state)
Definition Process.h:2888
virtual lldb::ThreadSP HandleThreadAsyncInterrupt(uint8_t signo, const std::string &description)
Handle thread specific async interrupt and return the original thread that requested the async interr...
Definition Process.h:3121
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3554
bool StateChangedIsHijackedForSynchronousResume()
Definition Process.cpp:1439
const char * GetExitDescription()
Get a textual description of what the process exited.
Definition Process.cpp:1076
void SetPublicState(lldb::StateType new_state, bool restarted)
Definition Process.cpp:1338
lldb::tid_t m_interrupt_tid
Definition Process.h:3586
void SetDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6329
virtual Status DoConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.h:981
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
Definition Process.cpp:2490
llvm::once_flag m_dlopen_utility_func_flag_once
Definition Process.h:3632
virtual llvm::VersionTuple GetHostOSVersion()
Sometimes the connection to a process can detect the host OS version that the process is running on.
Definition Process.h:1260
void AddCacheData(lldb::addr_t addr, const lldb::WritableDataBufferSP &data_buffer_sp)
Cache memory, restoring the original bytes under any breakpoint.
Definition Process.cpp:1889
virtual void UpdateQueueListIfNeeded()
Definition Process.cpp:1281
virtual Status UpdateAutomaticSignalFiltering()
Definition Process.cpp:6773
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
Definition Process.cpp:1527
std::map< lldb::addr_t, lldb::addr_t > m_resolved_indirect_addresses
This helps with the Public event coalescing in ShouldBroadcastEvent.
Definition Process.h:3621
virtual Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
Attach to an existing process using a process ID.
Definition Process.h:999
llvm::SmallVector< std::optional< std::string > > ReadCStringsFromMemory(llvm::ArrayRef< lldb::addr_t > addresses)
Definition Process.cpp:2340
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition Process.cpp:2778
Status ClearBreakpointSiteByID(lldb::user_id_t break_id)
Definition Process.cpp:1624
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1906
void AppendSTDERR(const char *s, size_t len)
Definition Process.cpp:4932
bool GetShouldDetach() const
Definition Process.h:778
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:481
uint32_t m_thread_index_id
Each thread is created with a 1 based index that won't get re-used.
Definition Process.h:3504
bool ProcessIOHandlerExists() const
Definition Process.h:3741
virtual Status DoResume(lldb::RunDirection direction)
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.h:1128
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6744
virtual void DidDestroy()
Definition Process.h:1227
virtual void WillPublicStop()
Called when the process is about to broadcast a public stop.
Definition Process.h:814
friend class Trace
Definition Process.h:2938
bool IsBreakpointSiteEnabled(const BreakpointSite &site)
Definition Process.cpp:1699
virtual void PrefetchModuleSpecs(llvm::ArrayRef< FileSpec > module_file_specs, const llvm::Triple &triple)
Definition Process.h:2757
Broadcaster m_private_state_control_broadcaster
Definition Process.h:3486
const std::vector< lldb::addr_t > & GetImageTokens()
Get the image vector for the current process.
Definition Process.h:786
lldb::addr_t GetHighmemCodeAddressMask()
The highmem masks are for targets where we may have different masks for low memory versus high memory...
Definition Process.cpp:6305
bool IsRunning() const
Definition Process.cpp:1064
Broadcaster m_private_state_broadcaster
Definition Process.h:3483
const Process & operator=(const Process &)=delete
virtual bool DetachRequiresHalt()
Definition Process.h:1200
virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(lldb::BinaryInformationLevel info_level)
Retrieve a StructuredData dictionary about all of the binaries loaded in the process at this time.
Definition Process.h:1371
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1142
virtual bool ShouldUseMemoryCache(const ProcessAddress &process_addr)
Whether ReadMemory should serve reads of process_addr out of the memory cache.
Definition Process.h:3025
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
Definition Process.h:3512
lldb::addr_t m_data_address_mask
Definition Process.h:3611
virtual ArchSpec GetSystemArchitecture()
Get the system architecture for this process.
Definition Process.h:744
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2783
virtual Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2867
void RegisterNotificationCallbacks(const Process::Notifications &callbacks)
Register for process and thread notifications.
Definition Process.cpp:656
virtual void DidAttach(ArchSpec &process_arch)
Called after attaching a process.
Definition Process.h:1033
virtual lldb::addr_t ResolveIndirectFunction(const Address *address, Status &error)
Resolve dynamically loaded indirect functions.
Definition Process.cpp:6404
lldb::StateType m_last_broadcast_state
Definition Process.h:3618
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition Process.cpp:1555
ProcessModID m_mod_id
Tracks the state of the process over stops and other alterations.
Definition Process.h:3499
virtual CommandObject * GetPluginCommandObject()
Return a multi-word command object that can be used to expose plug-in specific commands.
Definition Process.h:603
virtual bool FindModuleUUID(ModuleSpec &spec)
Given a module spec, try to find the UUID information.
Definition Process.cpp:6504
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:559
friend class Target
Definition Process.h:375
virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, lldb::addr_t &load_addr)
Try to find the load address of a file.
Definition Process.h:2774
virtual JITLoaderList & GetJITLoaders()
Definition Process.cpp:3150
uint32_t AssignIndexIDToThread(uint64_t thread_id)
Definition Process.cpp:1310
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1084
uint32_t m_queue_list_stop_id
The natural stop id when queue list was last fetched.
Definition Process.h:3533
void PrintWarningOptimization(const SymbolContext &sc)
Print a user-visible warning about a module being built with optimization.
Definition Process.cpp:6468
virtual bool DoCanAllocateMemory()
Determines whether DoAllocateMemory is expected to succeed, without running code in the process.
Definition Process.h:1874
friend class FunctionCaller
Definition Process.h:370
virtual bool CanDebug(lldb::TargetSP target, bool plugin_specified_by_name)=0
Check if a plug-in instance can debug the file in module.
virtual std::optional< bool > DoGetWatchpointReportedAfter()
Provide an override value in the subclass for lldb's CPU-based logic for whether watchpoint exception...
Definition Process.h:3110
static ProcessProperties & GetGlobalProperties()
Definition Process.cpp:592
void StopSTDIOMonitoring(bool drain)
Stop monitoring the process' stdio.
Definition Process.cpp:5076
lldb::addr_t m_highmem_code_address_mask
Definition Process.h:3612
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6545
int m_exit_status
The exit status of the process, or -1 if not set.
Definition Process.h:3507
std::vector< LanguageRuntime * > GetLanguageRuntimes()
Definition Process.cpp:1535
void SetShouldDetach(bool b)
Definition Process.h:780
virtual lldb_private::StructuredData::ObjectSP GetDynamicLoaderProcessState()
Definition Process.h:1415
bool StartPrivateStateThread(lldb::StateType state, bool run_lock_is_running, std::shared_ptr< PrivateStateThread > *backup_ptr=nullptr)
Definition Process.cpp:4160
MemoryCache m_memory_cache
Definition Process.h:3570
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:5025
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
Definition Process.cpp:6494
virtual void DidHalt()
Called after halting a process.
Definition Process.h:1172
lldb::addr_t FixCodeAddress(lldb::addr_t pc)
Some targets might use bits in a code address to indicate a mode switch, ARM uses bit zero to signify...
Definition Process.cpp:6349
lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:2874
void RestoreProcessEvents()
Restores the process event broadcasting to its normal state.
Definition Process.cpp:990
virtual bool SupportsMemoryTagging()
Check whether the process supports memory tagging.
Definition Process.h:3249
bool SetPrivateRunLockToRunning()
Definition Process.h:3433
void DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level, bool internal, bool condense_trivial, bool skip_unreported_plans)
Dump all the thread plans for this process.
Definition Process.cpp:1274
uint32_t GetAddressByteSize() const
Definition Process.cpp:3973
uint32_t GetStopID() const
Definition Process.h:1517
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1448
llvm::Expected< AddressSpaceInfo > GetAddressSpaceInfo(llvm::StringRef address_space_name)
Definition Process.cpp:7241
lldb::addr_t m_highmem_data_address_mask
Definition Process.h:3613
virtual Status DoDestroy()=0
Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Definition Process.cpp:3756
virtual llvm::Error LoadModules()
Sometimes processes know how to retrieve and load shared libraries.
Definition Process.h:705
bool GetWatchpointReportedAfter()
Whether lldb will be notified about watchpoints after the instruction has completed executing,...
Definition Process.cpp:2793
SourceManager::SourceFileCache & GetSourceFileCache()
Definition Process.h:2890
lldb::StateType GetNextEvent(lldb::EventSP &event_sp)
Definition Process.cpp:696
virtual bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)=0
Update the thread list following process plug-in's specific logic.
virtual llvm::Expected< std::vector< uint8_t > > DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type)
Does the final operation to read memory tags.
Definition Process.h:3268
bool StateChangedIsExternallyHijacked()
Definition Process.cpp:1430
void SetCanInterpretFunctionCalls(bool can_interpret_function_calls)
Sets whether executing function calls using the interpreter is possible for this process.
Definition Process.h:2131
lldb::StateType GetPublicState() const
Definition Process.h:3457
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:5006
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2600
virtual llvm::Expected< bool > SaveCore(llvm::StringRef outfile)
Save core dump into the specified file.
Definition Process.cpp:3146
bool ProcessIOHandlerIsActive()
Definition Process.cpp:5095
Status DestroyImpl(bool force_kill)
Definition Process.cpp:3872
bool m_force_next_event_delivery
Definition Process.h:3617
void GetStatus(Stream &ostrm, bool is_verbose=false)
Definition Process.cpp:6171
lldb::SystemRuntimeUP m_system_runtime_up
Definition Process.h:3552
virtual Status WillHalt()
Called before halting to a process.
Definition Process.h:1147
bool ShouldBroadcastEvent(Event *event_ptr)
This is the part of the event handling that for a process event.
Definition Process.cpp:3977
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3134
std::string m_exit_string
A textual description of why a process exited.
Definition Process.h:3508
lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up
The functions used by the expression parser to validate data that expressions use.
Definition Process.h:3546
void SyncIOHandler(uint32_t iohandler_id, const Timeout< std::micro > &timeout)
Waits for the process state to be running within a given msec timeout.
Definition Process.cpp:707
void ForceNextEventDelivery()
Definition Process.h:3199
ThreadPlanStack * FindThreadPlans(lldb::tid_t tid)
Find the thread plan stack associated with thread with tid.
Definition Process.cpp:1254
virtual void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid, bool is_expression_fork=false)
Called after a reported fork.
Definition Process.h:1048
virtual Status Attach(ProcessAttachInfo &attach_info)
Attach to an existing process using the process attach info.
Definition Process.cpp:3260
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:600
lldb::addr_t GetDataAddressMask()
Definition Process.cpp:6298
std::recursive_mutex & GetPrivateStateMutex()
Definition Process.h:3452
virtual bool ShouldUseDelayedBreakpoints() const
Reports whether this process should delay physically enabling/disabling breakpoints until the process...
Definition Process.h:2341
void SynchronouslyNotifyStateChanged(lldb::StateType state)
Definition Process.cpp:675
bool SetPrivateRunLockToStopped()
Definition Process.h:3427
void SetSTDIOPseudoTerminal(PseudoTerminal &pty)
Associates the primary side of pty with the process' STDIO handling.
Definition Process.cpp:5061
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2763
StopPointSiteList< lldb_private::WatchpointResource > & GetWatchpointResourceList()
Definition Process.h:2375
llvm::StringRef GetBroadcasterClass() const override
This needs to be filled in if you are going to register the broadcaster with the broadcaster manager ...
Definition Process.h:423
virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info)
Attach to an existing process using a partial process name.
Definition Process.h:1020
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3514
virtual bool StartNoticingNewThreads()
Call this to set the lldb in the mode where it breaks on new thread creations, and then auto-restarts...
Definition Process.h:2612
bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
Update the thread list.
Definition Process.cpp:1161
virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(lldb::BinaryInformationLevel info_level, const std::vector< lldb::addr_t > &load_addresses)
Retrieve a StructuredData dictionary about the binaries at the provided load addresses.
Definition Process.h:1394
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3964
llvm::Expected< UtilityFunction & > GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< llvm::Expected< std::unique_ptr< UtilityFunction > >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
Definition Process.cpp:6779
void SetBaseDirection(lldb::RunDirection direction)
Set the base run direction for the process.
Definition Process.cpp:3577
Status WriteMemoryTags(lldb::addr_t addr, size_t len, const std::vector< lldb::addr_t > &tags)
Write memory tags for a range of memory.
Definition Process.cpp:6900
virtual size_t DoReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)=0
Actually do the reading of memory from a process.
virtual std::optional< CoreArgs > GetCoreFileArgs()
Provide arguments of a command that triggered a core dump.
Definition Process.h:1599
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
Definition Process.h:1561
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3481
virtual void DoDidExec()
Subclasses of Process should implement this function if they need to do anything after a process exec...
Definition Process.h:1045
llvm::SmallVector< std::optional< lldb::addr_t > > ReadPointersFromMemory(llvm::ArrayRef< lldb::addr_t > ptr_locs)
Use Process::ReadMemoryRanges to efficiently read multiple pointers from memory at once.
Definition Process.cpp:2567
virtual void RefreshStateAfterStop()=0
Currently called as part of ShouldStop.
llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > ReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Read from multiple memory ranges and write the results into buffer.
Definition Process.cpp:2146
lldb::addr_t GetCodeAddressMask()
Get the current address mask in the Process.
Definition Process.cpp:6291
bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks)
Unregister for process and thread notifications.
Definition Process.cpp:662
bool HijackProcessEvents(lldb::ListenerSP listener_sp)
If you need to ensure that you and only you will hear about some public event, then make a new listen...
Definition Process.cpp:982
QueueList & GetQueueList()
Definition Process.h:2403
virtual Status DoDeallocateMemory(lldb::addr_t ptr)
Actually deallocate memory in the process.
Definition Process.h:2153
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition Process.cpp:6608
friend class DynamicLoader
Definition Process.h:372
static void SettingsTerminate()
Definition Process.cpp:5134
virtual void * GetImplementation()
Definition Process.h:2886
lldb::addr_t GetHighmemDataAddressMask()
Definition Process.cpp:6314
ThreadList m_extended_thread_list
Constituent for extended threads that may be generated, cleared on natural stops.
Definition Process.h:3523
bool CallVoidArgVoidPtrReturn(const Address *address, lldb::addr_t &returned_func, bool trap_exceptions=false)
Definition Process.cpp:6807
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6249
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition Process.cpp:1899
Status Halt(bool clear_thread_plans=false, bool use_run_lock=true)
Halts a running process.
Definition Process.cpp:3654
lldb::pid_t m_pid
Definition Process.h:3482
const lldb::ABISP & GetABI()
Definition Process.cpp:1529
friend class Debugger
Definition Process.h:371
Status WillLaunch(Module *module)
Called before launching to a process.
Definition Process.cpp:3247
std::vector< lldb::ThreadSP > CalculateCoreFileThreadList(const SaveCoreOptions &core_options)
Helper function for Process::SaveCore(...) that calculates the thread list based upon options set wit...
Definition Process.cpp:7207
size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, size_t size, Status &error)
Write all or part of a scalar value to memory.
Definition Process.cpp:2677
uint32_t GetLastUserExpressionResumeID() const
Definition Process.h:1521
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4987
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
Definition Process.cpp:6508
bool PrivateStateThreadIsRunning() const
Definition Process.h:3188
const ProcessModID & GetModIDRef() const
Definition Process.h:1515
lldb::thread_result_t RunPrivateStateThread(PrivateStateThread::Purpose purpose)
Definition Process.cpp:4426
lldb::StateType GetStateChangedEvents(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout, lldb::ListenerSP hijack_listener)
Definition Process.cpp:992
ThreadedCommunication m_stdio_communication
Definition Process.h:3558
lldb::StackFrameSP CalculateStackFrame() override
Definition Process.h:2631
static constexpr int g_all_event_bits
Definition Process.h:392
virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error)
Actually allocate memory in the process.
Definition Process.h:1864
std::atomic< bool > m_finalizing
The tid of the thread that issued the async interrupt, used by thread plan timeout.
Definition Process.h:3593
virtual llvm::Expected< std::string > TraceGetState(llvm::StringRef type)
Get the current tracing state of the process and its threads.
Definition Process.h:2992
bool CanInterpretFunctionCalls()
Determines whether executing function calls using the interpreter is possible for this process.
Definition Process.h:2124
std::recursive_mutex m_language_runtimes_mutex
Definition Process.h:3576
std::string m_stderr_data
Definition Process.h:3566
friend class ThreadList
Definition Process.h:376
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2861
LockingAdaptedIterable< std::mutex, collection > QueueIterable
Definition QueueList.h:51
The SourceFileCache class separates the source manager from the cache of source files.
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
A plug-in interface definition class for system runtimes.
LockingAdaptedIterable< std::recursive_mutex, collection > ThreadIterable
"lldb/Core/ThreadedCommunication.h" Variation of Communication that supports threaded reads.
#define LLDB_INVALID_ADDRESS_MASK
Address Mask Bits not used for addressing are set to 1 in the mask; all mask bits set is an invalid v...
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
std::map< lldb::InstrumentationRuntimeType, lldb::InstrumentationRuntimeSP > InstrumentationRuntimeCollection
bool operator!=(const Address &lhs, const Address &rhs)
Definition Address.cpp:1011
llvm::APFloat::cmpResult compare(Scalar lhs, Scalar rhs)
Definition Scalar.cpp:876
bool operator==(const Address &lhs, const Address &rhs)
Definition Address.cpp:1005
static uint32_t bits(const uint32_t val, const uint32_t msbit, const uint32_t lsbit)
Definition ARMUtils.h:265
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::unique_ptr< lldb_private::SystemRuntime > SystemRuntimeUP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
RunDirection
Execution directions.
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::unique_ptr< lldb_private::OperatingSystem > OperatingSystemUP
std::shared_ptr< lldb_private::Thread > ThreadSP
void * thread_result_t
Definition lldb-types.h:62
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
std::unique_ptr< lldb_private::DynamicCheckerFunctions > DynamicCheckerFunctionsUP
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateExited
Process has exited and can't be examined.
LanguageType
Programming language type.
ExpressionResults
The results of expression evaluation.
std::shared_ptr< lldb_private::StructuredDataPlugin > StructuredDataPluginSP
int32_t break_id_t
Definition lldb-types.h:88
std::shared_ptr< lldb_private::Process > ProcessSP
InstrumentationRuntimeType
std::shared_ptr< lldb_private::Event > EventSP
std::unique_ptr< lldb_private::DynamicLoader > DynamicLoaderUP
std::unique_ptr< lldb_private::JITLoaderList > JITLoaderListUP
uint64_t pid_t
Definition lldb-types.h:84
ByteOrder
Byte ordering definitions.
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::weak_ptr< lldb_private::Process > ProcessWP
std::shared_ptr< lldb_private::Listener > ListenerSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
BinaryInformationLevel
When the Process plugin can retrieve information about all binaries loaded in the target process,...
uint64_t addr_space_t
Definition lldb-types.h:81
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP
PrivateStatePurpose
Why a private-state policy is being pushed.
Definition Policy.h:61
BreakpointSiteToActionMap m_site_to_action
Definition Process.h:3651
void Enqueue(lldb::BreakpointSiteSP site, BreakpointAction action)
Definition Process.cpp:88
void RemoveSite(lldb::BreakpointSiteSP site)
Definition Process.h:3646
A notification structure that can be used by clients to listen for changes in a process's lifetime.
Definition Process.h:432
void(* process_state_changed)(void *baton, Process *process, lldb::StateType state)
Definition Process.h:435
void(* initialize)(void *baton, Process *process)
Definition Process.h:434
bool operator==(const PreResumeCallbackAndBaton &rhs)
Definition Process.h:3309
PreResumeCallbackAndBaton(PreResumeActionCallback in_callback, void *in_baton)
Definition Process.h:3306
lldb::StateType GetPublicState() const
Definition Process.h:3363
ThreadSafeValue< lldb::StateType > m_private_state
HostThread for the thread that watches for internal state events.
Definition Process.h:3410
void SetThreadName(llvm::StringRef new_name)
Definition Process.h:3357
PrivateStateThread(Process &process, lldb::StateType public_state, lldb::StateType private_state, llvm::StringRef thread_name, Purpose purpose=Purpose::Default)
Definition Process.h:3331
lldb::StateType GetPrivateState() const
Definition Process.h:3359
ThreadSafeValue< lldb::StateType > m_public_state
The actual state of our process.
Definition Process.h:3408
Process & m_process
The process state that we show to client code.
Definition Process.h:3403
Purpose m_purpose
This will be the thread name given to the Private State HostThread when it gets spun up.
Definition Process.h:3421
bool IsOnThread(const HostThread &thread) const
Definition Process.cpp:4149
std::recursive_mutex & GetPrivateStateMutex()
Definition Process.h:3373
Policy::PrivateStatePurpose Purpose
Why this PST exists.
Definition Process.h:3329
void SetPublicState(lldb::StateType new_value)
Definition Process.h:3365
void SetPrivateState(lldb::StateType new_value)
Definition Process.h:3369
void SetPublicStateNoLock(lldb::StateType new_state)
Definition Process.h:3385
void SetPrivateStateNoLock(lldb::StateType new_state)
Definition Process.h:3381
lldb::StateType GetPrivateStateNoLock() const
Definition Process.h:3377
Compare BreakpointSiteSPs by ID, so that iteration order is independent of pointer addresses.
Definition Process.h:2286
bool operator()(const lldb::BreakpointSiteSP &lhs, const lldb::BreakpointSiteSP &rhs) const
Definition Process.h:2287
jLLDBTraceGetBinaryData gdb-remote packet
jLLDBTraceStop gdb-remote packet