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