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