Target.h 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. //===-- Target.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. #ifndef LLDB_TARGET_TARGET_H
  9. #define LLDB_TARGET_TARGET_H
  10. #include <list>
  11. #include <map>
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. #include "lldb/Breakpoint/BreakpointList.h"
  16. #include "lldb/Breakpoint/BreakpointName.h"
  17. #include "lldb/Breakpoint/WatchpointList.h"
  18. #include "lldb/Core/Architecture.h"
  19. #include "lldb/Core/Disassembler.h"
  20. #include "lldb/Core/ModuleList.h"
  21. #include "lldb/Core/UserSettingsController.h"
  22. #include "lldb/Expression/Expression.h"
  23. #include "lldb/Host/ProcessLaunchInfo.h"
  24. #include "lldb/Symbol/TypeSystem.h"
  25. #include "lldb/Target/ExecutionContextScope.h"
  26. #include "lldb/Target/PathMappingList.h"
  27. #include "lldb/Target/SectionLoadHistory.h"
  28. #include "lldb/Target/ThreadSpec.h"
  29. #include "lldb/Utility/ArchSpec.h"
  30. #include "lldb/Utility/Broadcaster.h"
  31. #include "lldb/Utility/LLDBAssert.h"
  32. #include "lldb/Utility/Timeout.h"
  33. #include "lldb/lldb-public.h"
  34. namespace lldb_private {
  35. OptionEnumValues GetDynamicValueTypes();
  36. enum InlineStrategy {
  37. eInlineBreakpointsNever = 0,
  38. eInlineBreakpointsHeaders,
  39. eInlineBreakpointsAlways
  40. };
  41. enum LoadScriptFromSymFile {
  42. eLoadScriptFromSymFileTrue,
  43. eLoadScriptFromSymFileFalse,
  44. eLoadScriptFromSymFileWarn
  45. };
  46. enum LoadCWDlldbinitFile {
  47. eLoadCWDlldbinitTrue,
  48. eLoadCWDlldbinitFalse,
  49. eLoadCWDlldbinitWarn
  50. };
  51. enum LoadDependentFiles {
  52. eLoadDependentsDefault,
  53. eLoadDependentsYes,
  54. eLoadDependentsNo,
  55. };
  56. enum ImportStdModule {
  57. eImportStdModuleFalse,
  58. eImportStdModuleFallback,
  59. eImportStdModuleTrue,
  60. };
  61. class TargetExperimentalProperties : public Properties {
  62. public:
  63. TargetExperimentalProperties();
  64. };
  65. class TargetProperties : public Properties {
  66. public:
  67. TargetProperties(Target *target);
  68. ~TargetProperties() override;
  69. ArchSpec GetDefaultArchitecture() const;
  70. void SetDefaultArchitecture(const ArchSpec &arch);
  71. bool GetMoveToNearestCode() const;
  72. lldb::DynamicValueType GetPreferDynamicValue() const;
  73. bool SetPreferDynamicValue(lldb::DynamicValueType d);
  74. bool GetPreloadSymbols() const;
  75. void SetPreloadSymbols(bool b);
  76. bool GetDisableASLR() const;
  77. void SetDisableASLR(bool b);
  78. bool GetInheritTCC() const;
  79. void SetInheritTCC(bool b);
  80. bool GetDetachOnError() const;
  81. void SetDetachOnError(bool b);
  82. bool GetDisableSTDIO() const;
  83. void SetDisableSTDIO(bool b);
  84. const char *GetDisassemblyFlavor() const;
  85. InlineStrategy GetInlineStrategy() const;
  86. llvm::StringRef GetArg0() const;
  87. void SetArg0(llvm::StringRef arg);
  88. bool GetRunArguments(Args &args) const;
  89. void SetRunArguments(const Args &args);
  90. Environment GetEnvironment() const;
  91. void SetEnvironment(Environment env);
  92. bool GetSkipPrologue() const;
  93. PathMappingList &GetSourcePathMap() const;
  94. FileSpecList GetExecutableSearchPaths();
  95. void AppendExecutableSearchPaths(const FileSpec &);
  96. FileSpecList GetDebugFileSearchPaths();
  97. FileSpecList GetClangModuleSearchPaths();
  98. bool GetEnableAutoImportClangModules() const;
  99. ImportStdModule GetImportStdModule() const;
  100. bool GetEnableAutoApplyFixIts() const;
  101. uint64_t GetNumberOfRetriesWithFixits() const;
  102. bool GetEnableNotifyAboutFixIts() const;
  103. bool GetEnableSaveObjects() const;
  104. bool GetEnableSyntheticValue() const;
  105. uint32_t GetMaxZeroPaddingInFloatFormat() const;
  106. uint32_t GetMaximumNumberOfChildrenToDisplay() const;
  107. uint32_t GetMaximumSizeOfStringSummary() const;
  108. uint32_t GetMaximumMemReadSize() const;
  109. FileSpec GetStandardInputPath() const;
  110. FileSpec GetStandardErrorPath() const;
  111. FileSpec GetStandardOutputPath() const;
  112. void SetStandardInputPath(llvm::StringRef path);
  113. void SetStandardOutputPath(llvm::StringRef path);
  114. void SetStandardErrorPath(llvm::StringRef path);
  115. void SetStandardInputPath(const char *path) = delete;
  116. void SetStandardOutputPath(const char *path) = delete;
  117. void SetStandardErrorPath(const char *path) = delete;
  118. bool GetBreakpointsConsultPlatformAvoidList();
  119. lldb::LanguageType GetLanguage() const;
  120. llvm::StringRef GetExpressionPrefixContents();
  121. uint64_t GetExprErrorLimit() const;
  122. bool GetUseHexImmediates() const;
  123. bool GetUseFastStepping() const;
  124. bool GetDisplayExpressionsInCrashlogs() const;
  125. LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const;
  126. LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const;
  127. Disassembler::HexImmediateStyle GetHexImmediateStyle() const;
  128. MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const;
  129. bool GetUserSpecifiedTrapHandlerNames(Args &args) const;
  130. void SetUserSpecifiedTrapHandlerNames(const Args &args);
  131. bool GetNonStopModeEnabled() const;
  132. void SetNonStopModeEnabled(bool b);
  133. bool GetDisplayRuntimeSupportValues() const;
  134. void SetDisplayRuntimeSupportValues(bool b);
  135. bool GetDisplayRecognizedArguments() const;
  136. void SetDisplayRecognizedArguments(bool b);
  137. const ProcessLaunchInfo &GetProcessLaunchInfo() const;
  138. void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info);
  139. bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const;
  140. void SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b);
  141. void SetRequireHardwareBreakpoints(bool b);
  142. bool GetRequireHardwareBreakpoints() const;
  143. bool GetAutoInstallMainExecutable() const;
  144. void UpdateLaunchInfoFromProperties();
  145. void SetDebugUtilityExpression(bool debug);
  146. bool GetDebugUtilityExpression() const;
  147. private:
  148. // Callbacks for m_launch_info.
  149. void Arg0ValueChangedCallback();
  150. void RunArgsValueChangedCallback();
  151. void EnvVarsValueChangedCallback();
  152. void InputPathValueChangedCallback();
  153. void OutputPathValueChangedCallback();
  154. void ErrorPathValueChangedCallback();
  155. void DetachOnErrorValueChangedCallback();
  156. void DisableASLRValueChangedCallback();
  157. void InheritTCCValueChangedCallback();
  158. void DisableSTDIOValueChangedCallback();
  159. Environment ComputeEnvironment() const;
  160. // Member variables.
  161. ProcessLaunchInfo m_launch_info;
  162. std::unique_ptr<TargetExperimentalProperties> m_experimental_properties_up;
  163. Target *m_target;
  164. };
  165. class EvaluateExpressionOptions {
  166. public:
  167. // MSVC has a bug here that reports C4268: 'const' static/global data
  168. // initialized with compiler generated default constructor fills the object
  169. // with zeros. Confirmed that MSVC is *not* zero-initializing, it's just a
  170. // bogus warning.
  171. #if defined(_MSC_VER)
  172. #pragma warning(push)
  173. #pragma warning(disable : 4268)
  174. #endif
  175. static constexpr std::chrono::milliseconds default_timeout{500};
  176. #if defined(_MSC_VER)
  177. #pragma warning(pop)
  178. #endif
  179. static constexpr ExecutionPolicy default_execution_policy =
  180. eExecutionPolicyOnlyWhenNeeded;
  181. EvaluateExpressionOptions() = default;
  182. ExecutionPolicy GetExecutionPolicy() const { return m_execution_policy; }
  183. void SetExecutionPolicy(ExecutionPolicy policy = eExecutionPolicyAlways) {
  184. m_execution_policy = policy;
  185. }
  186. lldb::LanguageType GetLanguage() const { return m_language; }
  187. void SetLanguage(lldb::LanguageType language) { m_language = language; }
  188. bool DoesCoerceToId() const { return m_coerce_to_id; }
  189. const char *GetPrefix() const {
  190. return (m_prefix.empty() ? nullptr : m_prefix.c_str());
  191. }
  192. void SetPrefix(const char *prefix) {
  193. if (prefix && prefix[0])
  194. m_prefix = prefix;
  195. else
  196. m_prefix.clear();
  197. }
  198. void SetCoerceToId(bool coerce = true) { m_coerce_to_id = coerce; }
  199. bool DoesUnwindOnError() const { return m_unwind_on_error; }
  200. void SetUnwindOnError(bool unwind = false) { m_unwind_on_error = unwind; }
  201. bool DoesIgnoreBreakpoints() const { return m_ignore_breakpoints; }
  202. void SetIgnoreBreakpoints(bool ignore = false) {
  203. m_ignore_breakpoints = ignore;
  204. }
  205. bool DoesKeepInMemory() const { return m_keep_in_memory; }
  206. void SetKeepInMemory(bool keep = true) { m_keep_in_memory = keep; }
  207. lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
  208. void
  209. SetUseDynamic(lldb::DynamicValueType dynamic = lldb::eDynamicCanRunTarget) {
  210. m_use_dynamic = dynamic;
  211. }
  212. const Timeout<std::micro> &GetTimeout() const { return m_timeout; }
  213. void SetTimeout(const Timeout<std::micro> &timeout) { m_timeout = timeout; }
  214. const Timeout<std::micro> &GetOneThreadTimeout() const {
  215. return m_one_thread_timeout;
  216. }
  217. void SetOneThreadTimeout(const Timeout<std::micro> &timeout) {
  218. m_one_thread_timeout = timeout;
  219. }
  220. bool GetTryAllThreads() const { return m_try_others; }
  221. void SetTryAllThreads(bool try_others = true) { m_try_others = try_others; }
  222. bool GetStopOthers() const { return m_stop_others; }
  223. void SetStopOthers(bool stop_others = true) { m_stop_others = stop_others; }
  224. bool GetDebug() const { return m_debug; }
  225. void SetDebug(bool b) {
  226. m_debug = b;
  227. if (m_debug)
  228. m_generate_debug_info = true;
  229. }
  230. bool GetGenerateDebugInfo() const { return m_generate_debug_info; }
  231. void SetGenerateDebugInfo(bool b) { m_generate_debug_info = b; }
  232. bool GetColorizeErrors() const { return m_ansi_color_errors; }
  233. void SetColorizeErrors(bool b) { m_ansi_color_errors = b; }
  234. bool GetTrapExceptions() const { return m_trap_exceptions; }
  235. void SetTrapExceptions(bool b) { m_trap_exceptions = b; }
  236. bool GetREPLEnabled() const { return m_repl; }
  237. void SetREPLEnabled(bool b) { m_repl = b; }
  238. void SetCancelCallback(lldb::ExpressionCancelCallback callback, void *baton) {
  239. m_cancel_callback_baton = baton;
  240. m_cancel_callback = callback;
  241. }
  242. bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const {
  243. return ((m_cancel_callback != nullptr)
  244. ? m_cancel_callback(phase, m_cancel_callback_baton)
  245. : false);
  246. }
  247. // Allows the expression contents to be remapped to point to the specified
  248. // file and line using #line directives.
  249. void SetPoundLine(const char *path, uint32_t line) const {
  250. if (path && path[0]) {
  251. m_pound_line_file = path;
  252. m_pound_line_line = line;
  253. } else {
  254. m_pound_line_file.clear();
  255. m_pound_line_line = 0;
  256. }
  257. }
  258. const char *GetPoundLineFilePath() const {
  259. return (m_pound_line_file.empty() ? nullptr : m_pound_line_file.c_str());
  260. }
  261. uint32_t GetPoundLineLine() const { return m_pound_line_line; }
  262. void SetResultIsInternal(bool b) { m_result_is_internal = b; }
  263. bool GetResultIsInternal() const { return m_result_is_internal; }
  264. void SetAutoApplyFixIts(bool b) { m_auto_apply_fixits = b; }
  265. bool GetAutoApplyFixIts() const { return m_auto_apply_fixits; }
  266. void SetRetriesWithFixIts(uint64_t number_of_retries) {
  267. m_retries_with_fixits = number_of_retries;
  268. }
  269. uint64_t GetRetriesWithFixIts() const { return m_retries_with_fixits; }
  270. bool IsForUtilityExpr() const { return m_running_utility_expression; }
  271. void SetIsForUtilityExpr(bool b) { m_running_utility_expression = b; }
  272. private:
  273. ExecutionPolicy m_execution_policy = default_execution_policy;
  274. lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
  275. std::string m_prefix;
  276. bool m_coerce_to_id = false;
  277. bool m_unwind_on_error = true;
  278. bool m_ignore_breakpoints = false;
  279. bool m_keep_in_memory = false;
  280. bool m_try_others = true;
  281. bool m_stop_others = true;
  282. bool m_debug = false;
  283. bool m_trap_exceptions = true;
  284. bool m_repl = false;
  285. bool m_generate_debug_info = false;
  286. bool m_ansi_color_errors = false;
  287. bool m_result_is_internal = false;
  288. bool m_auto_apply_fixits = true;
  289. uint64_t m_retries_with_fixits = 1;
  290. /// True if the executed code should be treated as utility code that is only
  291. /// used by LLDB internally.
  292. bool m_running_utility_expression = false;
  293. lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues;
  294. Timeout<std::micro> m_timeout = default_timeout;
  295. Timeout<std::micro> m_one_thread_timeout = llvm::None;
  296. lldb::ExpressionCancelCallback m_cancel_callback = nullptr;
  297. void *m_cancel_callback_baton = nullptr;
  298. // If m_pound_line_file is not empty and m_pound_line_line is non-zero, use
  299. // #line %u "%s" before the expression content to remap where the source
  300. // originates
  301. mutable std::string m_pound_line_file;
  302. mutable uint32_t m_pound_line_line;
  303. };
  304. // Target
  305. class Target : public std::enable_shared_from_this<Target>,
  306. public TargetProperties,
  307. public Broadcaster,
  308. public ExecutionContextScope,
  309. public ModuleList::Notifier {
  310. public:
  311. friend class TargetList;
  312. friend class Debugger;
  313. /// Broadcaster event bits definitions.
  314. enum {
  315. eBroadcastBitBreakpointChanged = (1 << 0),
  316. eBroadcastBitModulesLoaded = (1 << 1),
  317. eBroadcastBitModulesUnloaded = (1 << 2),
  318. eBroadcastBitWatchpointChanged = (1 << 3),
  319. eBroadcastBitSymbolsLoaded = (1 << 4)
  320. };
  321. // These two functions fill out the Broadcaster interface:
  322. static ConstString &GetStaticBroadcasterClass();
  323. ConstString &GetBroadcasterClass() const override {
  324. return GetStaticBroadcasterClass();
  325. }
  326. // This event data class is for use by the TargetList to broadcast new target
  327. // notifications.
  328. class TargetEventData : public EventData {
  329. public:
  330. TargetEventData(const lldb::TargetSP &target_sp);
  331. TargetEventData(const lldb::TargetSP &target_sp,
  332. const ModuleList &module_list);
  333. ~TargetEventData() override;
  334. static ConstString GetFlavorString();
  335. ConstString GetFlavor() const override {
  336. return TargetEventData::GetFlavorString();
  337. }
  338. void Dump(Stream *s) const override;
  339. static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr);
  340. static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
  341. static ModuleList GetModuleListFromEvent(const Event *event_ptr);
  342. const lldb::TargetSP &GetTarget() const { return m_target_sp; }
  343. const ModuleList &GetModuleList() const { return m_module_list; }
  344. private:
  345. lldb::TargetSP m_target_sp;
  346. ModuleList m_module_list;
  347. TargetEventData(const TargetEventData &) = delete;
  348. const TargetEventData &operator=(const TargetEventData &) = delete;
  349. };
  350. ~Target() override;
  351. static void SettingsInitialize();
  352. static void SettingsTerminate();
  353. static FileSpecList GetDefaultExecutableSearchPaths();
  354. static FileSpecList GetDefaultDebugFileSearchPaths();
  355. static ArchSpec GetDefaultArchitecture();
  356. static void SetDefaultArchitecture(const ArchSpec &arch);
  357. bool IsDummyTarget() const { return m_is_dummy_target; }
  358. /// Find a binary on the system and return its Module,
  359. /// or return an existing Module that is already in the Target.
  360. ///
  361. /// Given a ModuleSpec, find a binary satisifying that specification,
  362. /// or identify a matching Module already present in the Target,
  363. /// and return a shared pointer to it.
  364. ///
  365. /// \param[in] module_spec
  366. /// The criteria that must be matched for the binary being loaded.
  367. /// e.g. UUID, architecture, file path.
  368. ///
  369. /// \param[in] notify
  370. /// If notify is true, and the Module is new to this Target,
  371. /// Target::ModulesDidLoad will be called.
  372. /// If notify is false, it is assumed that the caller is adding
  373. /// multiple Modules and will call ModulesDidLoad with the
  374. /// full list at the end.
  375. /// ModulesDidLoad must be called when a Module/Modules have
  376. /// been added to the target, one way or the other.
  377. ///
  378. /// \param[out] error_ptr
  379. /// Optional argument, pointing to a Status object to fill in
  380. /// with any results / messages while attempting to find/load
  381. /// this binary. Many callers will be internal functions that
  382. /// will handle / summarize the failures in a custom way and
  383. /// don't use these messages.
  384. ///
  385. /// \return
  386. /// An empty ModuleSP will be returned if no matching file
  387. /// was found. If error_ptr was non-nullptr, an error message
  388. /// will likely be provided.
  389. lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
  390. Status *error_ptr = nullptr);
  391. // Settings accessors
  392. static const lldb::TargetPropertiesSP &GetGlobalProperties();
  393. std::recursive_mutex &GetAPIMutex();
  394. void DeleteCurrentProcess();
  395. void CleanupProcess();
  396. /// Dump a description of this object to a Stream.
  397. ///
  398. /// Dump a description of the contents of this object to the
  399. /// supplied stream \a s. The dumped content will be only what has
  400. /// been loaded or parsed up to this point at which this function
  401. /// is called, so this is a good way to see what has been parsed
  402. /// in a target.
  403. ///
  404. /// \param[in] s
  405. /// The stream to which to dump the object description.
  406. void Dump(Stream *s, lldb::DescriptionLevel description_level);
  407. // If listener_sp is null, the listener of the owning Debugger object will be
  408. // used.
  409. const lldb::ProcessSP &CreateProcess(lldb::ListenerSP listener_sp,
  410. llvm::StringRef plugin_name,
  411. const FileSpec *crash_file,
  412. bool can_connect);
  413. const lldb::ProcessSP &GetProcessSP() const;
  414. bool IsValid() { return m_valid; }
  415. void Destroy();
  416. Status Launch(ProcessLaunchInfo &launch_info,
  417. Stream *stream); // Optional stream to receive first stop info
  418. Status Attach(ProcessAttachInfo &attach_info,
  419. Stream *stream); // Optional stream to receive first stop info
  420. // This part handles the breakpoints.
  421. BreakpointList &GetBreakpointList(bool internal = false);
  422. const BreakpointList &GetBreakpointList(bool internal = false) const;
  423. lldb::BreakpointSP GetLastCreatedBreakpoint() {
  424. return m_last_created_breakpoint;
  425. }
  426. lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id);
  427. // Use this to create a file and line breakpoint to a given module or all
  428. // module it is nullptr
  429. lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
  430. const FileSpec &file, uint32_t line_no,
  431. uint32_t column, lldb::addr_t offset,
  432. LazyBool check_inlines,
  433. LazyBool skip_prologue, bool internal,
  434. bool request_hardware,
  435. LazyBool move_to_nearest_code);
  436. // Use this to create breakpoint that matches regex against the source lines
  437. // in files given in source_file_list: If function_names is non-empty, also
  438. // filter by function after the matches are made.
  439. lldb::BreakpointSP CreateSourceRegexBreakpoint(
  440. const FileSpecList *containingModules,
  441. const FileSpecList *source_file_list,
  442. const std::unordered_set<std::string> &function_names,
  443. RegularExpression source_regex, bool internal, bool request_hardware,
  444. LazyBool move_to_nearest_code);
  445. // Use this to create a breakpoint from a load address
  446. lldb::BreakpointSP CreateBreakpoint(lldb::addr_t load_addr, bool internal,
  447. bool request_hardware);
  448. // Use this to create a breakpoint from a load address and a module file spec
  449. lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,
  450. bool internal,
  451. const FileSpec *file_spec,
  452. bool request_hardware);
  453. // Use this to create Address breakpoints:
  454. lldb::BreakpointSP CreateBreakpoint(const Address &addr, bool internal,
  455. bool request_hardware);
  456. // Use this to create a function breakpoint by regexp in
  457. // containingModule/containingSourceFiles, or all modules if it is nullptr
  458. // When "skip_prologue is set to eLazyBoolCalculate, we use the current
  459. // target setting, else we use the values passed in
  460. lldb::BreakpointSP CreateFuncRegexBreakpoint(
  461. const FileSpecList *containingModules,
  462. const FileSpecList *containingSourceFiles, RegularExpression func_regexp,
  463. lldb::LanguageType requested_language, LazyBool skip_prologue,
  464. bool internal, bool request_hardware);
  465. // Use this to create a function breakpoint by name in containingModule, or
  466. // all modules if it is nullptr When "skip_prologue is set to
  467. // eLazyBoolCalculate, we use the current target setting, else we use the
  468. // values passed in. func_name_type_mask is or'ed values from the
  469. // FunctionNameType enum.
  470. lldb::BreakpointSP CreateBreakpoint(
  471. const FileSpecList *containingModules,
  472. const FileSpecList *containingSourceFiles, const char *func_name,
  473. lldb::FunctionNameType func_name_type_mask, lldb::LanguageType language,
  474. lldb::addr_t offset, LazyBool skip_prologue, bool internal,
  475. bool request_hardware);
  476. lldb::BreakpointSP
  477. CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp,
  478. bool throw_bp, bool internal,
  479. Args *additional_args = nullptr,
  480. Status *additional_args_error = nullptr);
  481. lldb::BreakpointSP CreateScriptedBreakpoint(
  482. const llvm::StringRef class_name, const FileSpecList *containingModules,
  483. const FileSpecList *containingSourceFiles, bool internal,
  484. bool request_hardware, StructuredData::ObjectSP extra_args_sp,
  485. Status *creation_error = nullptr);
  486. // This is the same as the func_name breakpoint except that you can specify a
  487. // vector of names. This is cheaper than a regular expression breakpoint in
  488. // the case where you just want to set a breakpoint on a set of names you
  489. // already know. func_name_type_mask is or'ed values from the
  490. // FunctionNameType enum.
  491. lldb::BreakpointSP CreateBreakpoint(
  492. const FileSpecList *containingModules,
  493. const FileSpecList *containingSourceFiles, const char *func_names[],
  494. size_t num_names, lldb::FunctionNameType func_name_type_mask,
  495. lldb::LanguageType language, lldb::addr_t offset, LazyBool skip_prologue,
  496. bool internal, bool request_hardware);
  497. lldb::BreakpointSP
  498. CreateBreakpoint(const FileSpecList *containingModules,
  499. const FileSpecList *containingSourceFiles,
  500. const std::vector<std::string> &func_names,
  501. lldb::FunctionNameType func_name_type_mask,
  502. lldb::LanguageType language, lldb::addr_t m_offset,
  503. LazyBool skip_prologue, bool internal,
  504. bool request_hardware);
  505. // Use this to create a general breakpoint:
  506. lldb::BreakpointSP CreateBreakpoint(lldb::SearchFilterSP &filter_sp,
  507. lldb::BreakpointResolverSP &resolver_sp,
  508. bool internal, bool request_hardware,
  509. bool resolve_indirect_symbols);
  510. // Use this to create a watchpoint:
  511. lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size,
  512. const CompilerType *type, uint32_t kind,
  513. Status &error);
  514. lldb::WatchpointSP GetLastCreatedWatchpoint() {
  515. return m_last_created_watchpoint;
  516. }
  517. WatchpointList &GetWatchpointList() { return m_watchpoint_list; }
  518. // Manages breakpoint names:
  519. void AddNameToBreakpoint(BreakpointID &id, const char *name, Status &error);
  520. void AddNameToBreakpoint(lldb::BreakpointSP &bp_sp, const char *name,
  521. Status &error);
  522. void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, ConstString name);
  523. BreakpointName *FindBreakpointName(ConstString name, bool can_create,
  524. Status &error);
  525. void DeleteBreakpointName(ConstString name);
  526. void ConfigureBreakpointName(BreakpointName &bp_name,
  527. const BreakpointOptions &options,
  528. const BreakpointName::Permissions &permissions);
  529. void ApplyNameToBreakpoints(BreakpointName &bp_name);
  530. // This takes ownership of the name obj passed in.
  531. void AddBreakpointName(BreakpointName *bp_name);
  532. void GetBreakpointNames(std::vector<std::string> &names);
  533. // This call removes ALL breakpoints regardless of permission.
  534. void RemoveAllBreakpoints(bool internal_also = false);
  535. // This removes all the breakpoints, but obeys the ePermDelete on them.
  536. void RemoveAllowedBreakpoints();
  537. void DisableAllBreakpoints(bool internal_also = false);
  538. void DisableAllowedBreakpoints();
  539. void EnableAllBreakpoints(bool internal_also = false);
  540. void EnableAllowedBreakpoints();
  541. bool DisableBreakpointByID(lldb::break_id_t break_id);
  542. bool EnableBreakpointByID(lldb::break_id_t break_id);
  543. bool RemoveBreakpointByID(lldb::break_id_t break_id);
  544. // The flag 'end_to_end', default to true, signifies that the operation is
  545. // performed end to end, for both the debugger and the debuggee.
  546. bool RemoveAllWatchpoints(bool end_to_end = true);
  547. bool DisableAllWatchpoints(bool end_to_end = true);
  548. bool EnableAllWatchpoints(bool end_to_end = true);
  549. bool ClearAllWatchpointHitCounts();
  550. bool ClearAllWatchpointHistoricValues();
  551. bool IgnoreAllWatchpoints(uint32_t ignore_count);
  552. bool DisableWatchpointByID(lldb::watch_id_t watch_id);
  553. bool EnableWatchpointByID(lldb::watch_id_t watch_id);
  554. bool RemoveWatchpointByID(lldb::watch_id_t watch_id);
  555. bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count);
  556. Status SerializeBreakpointsToFile(const FileSpec &file,
  557. const BreakpointIDList &bp_ids,
  558. bool append);
  559. Status CreateBreakpointsFromFile(const FileSpec &file,
  560. BreakpointIDList &new_bps);
  561. Status CreateBreakpointsFromFile(const FileSpec &file,
  562. std::vector<std::string> &names,
  563. BreakpointIDList &new_bps);
  564. /// Get \a load_addr as a callable code load address for this target
  565. ///
  566. /// Take \a load_addr and potentially add any address bits that are
  567. /// needed to make the address callable. For ARM this can set bit
  568. /// zero (if it already isn't) if \a load_addr is a thumb function.
  569. /// If \a addr_class is set to AddressClass::eInvalid, then the address
  570. /// adjustment will always happen. If it is set to an address class
  571. /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
  572. /// returned.
  573. lldb::addr_t GetCallableLoadAddress(
  574. lldb::addr_t load_addr,
  575. AddressClass addr_class = AddressClass::eInvalid) const;
  576. /// Get \a load_addr as an opcode for this target.
  577. ///
  578. /// Take \a load_addr and potentially strip any address bits that are
  579. /// needed to make the address point to an opcode. For ARM this can
  580. /// clear bit zero (if it already isn't) if \a load_addr is a
  581. /// thumb function and load_addr is in code.
  582. /// If \a addr_class is set to AddressClass::eInvalid, then the address
  583. /// adjustment will always happen. If it is set to an address class
  584. /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
  585. /// returned.
  586. lldb::addr_t
  587. GetOpcodeLoadAddress(lldb::addr_t load_addr,
  588. AddressClass addr_class = AddressClass::eInvalid) const;
  589. // Get load_addr as breakable load address for this target. Take a addr and
  590. // check if for any reason there is a better address than this to put a
  591. // breakpoint on. If there is then return that address. For MIPS, if
  592. // instruction at addr is a delay slot instruction then this method will find
  593. // the address of its previous instruction and return that address.
  594. lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr);
  595. void ModulesDidLoad(ModuleList &module_list);
  596. void ModulesDidUnload(ModuleList &module_list, bool delete_locations);
  597. void SymbolsDidLoad(ModuleList &module_list);
  598. void ClearModules(bool delete_locations);
  599. /// Called as the last function in Process::DidExec().
  600. ///
  601. /// Process::DidExec() will clear a lot of state in the process,
  602. /// then try to reload a dynamic loader plugin to discover what
  603. /// binaries are currently available and then this function should
  604. /// be called to allow the target to do any cleanup after everything
  605. /// has been figured out. It can remove breakpoints that no longer
  606. /// make sense as the exec might have changed the target
  607. /// architecture, and unloaded some modules that might get deleted.
  608. void DidExec();
  609. /// Gets the module for the main executable.
  610. ///
  611. /// Each process has a notion of a main executable that is the file
  612. /// that will be executed or attached to. Executable files can have
  613. /// dependent modules that are discovered from the object files, or
  614. /// discovered at runtime as things are dynamically loaded.
  615. ///
  616. /// \return
  617. /// The shared pointer to the executable module which can
  618. /// contains a nullptr Module object if no executable has been
  619. /// set.
  620. ///
  621. /// \see DynamicLoader
  622. /// \see ObjectFile::GetDependentModules (FileSpecList&)
  623. /// \see Process::SetExecutableModule(lldb::ModuleSP&)
  624. lldb::ModuleSP GetExecutableModule();
  625. Module *GetExecutableModulePointer();
  626. /// Set the main executable module.
  627. ///
  628. /// Each process has a notion of a main executable that is the file
  629. /// that will be executed or attached to. Executable files can have
  630. /// dependent modules that are discovered from the object files, or
  631. /// discovered at runtime as things are dynamically loaded.
  632. ///
  633. /// Setting the executable causes any of the current dependent
  634. /// image information to be cleared and replaced with the static
  635. /// dependent image information found by calling
  636. /// ObjectFile::GetDependentModules (FileSpecList&) on the main
  637. /// executable and any modules on which it depends. Calling
  638. /// Process::GetImages() will return the newly found images that
  639. /// were obtained from all of the object files.
  640. ///
  641. /// \param[in] module_sp
  642. /// A shared pointer reference to the module that will become
  643. /// the main executable for this process.
  644. ///
  645. /// \param[in] load_dependent_files
  646. /// If \b true then ask the object files to track down any
  647. /// known dependent files.
  648. ///
  649. /// \see ObjectFile::GetDependentModules (FileSpecList&)
  650. /// \see Process::GetImages()
  651. void SetExecutableModule(
  652. lldb::ModuleSP &module_sp,
  653. LoadDependentFiles load_dependent_files = eLoadDependentsDefault);
  654. bool LoadScriptingResources(std::list<Status> &errors,
  655. Stream *feedback_stream = nullptr,
  656. bool continue_on_error = true) {
  657. return m_images.LoadScriptingResourcesInTarget(
  658. this, errors, feedback_stream, continue_on_error);
  659. }
  660. /// Get accessor for the images for this process.
  661. ///
  662. /// Each process has a notion of a main executable that is the file
  663. /// that will be executed or attached to. Executable files can have
  664. /// dependent modules that are discovered from the object files, or
  665. /// discovered at runtime as things are dynamically loaded. After
  666. /// a main executable has been set, the images will contain a list
  667. /// of all the files that the executable depends upon as far as the
  668. /// object files know. These images will usually contain valid file
  669. /// virtual addresses only. When the process is launched or attached
  670. /// to, the DynamicLoader plug-in will discover where these images
  671. /// were loaded in memory and will resolve the load virtual
  672. /// addresses is each image, and also in images that are loaded by
  673. /// code.
  674. ///
  675. /// \return
  676. /// A list of Module objects in a module list.
  677. const ModuleList &GetImages() const { return m_images; }
  678. ModuleList &GetImages() { return m_images; }
  679. /// Return whether this FileSpec corresponds to a module that should be
  680. /// considered for general searches.
  681. ///
  682. /// This API will be consulted by the SearchFilterForUnconstrainedSearches
  683. /// and any module that returns \b true will not be searched. Note the
  684. /// SearchFilterForUnconstrainedSearches is the search filter that
  685. /// gets used in the CreateBreakpoint calls when no modules is provided.
  686. ///
  687. /// The target call at present just consults the Platform's call of the
  688. /// same name.
  689. ///
  690. /// \param[in] module_spec
  691. /// Path to the module.
  692. ///
  693. /// \return \b true if the module should be excluded, \b false otherwise.
  694. bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec);
  695. /// Return whether this module should be considered for general searches.
  696. ///
  697. /// This API will be consulted by the SearchFilterForUnconstrainedSearches
  698. /// and any module that returns \b true will not be searched. Note the
  699. /// SearchFilterForUnconstrainedSearches is the search filter that
  700. /// gets used in the CreateBreakpoint calls when no modules is provided.
  701. ///
  702. /// The target call at present just consults the Platform's call of the
  703. /// same name.
  704. ///
  705. /// FIXME: When we get time we should add a way for the user to set modules
  706. /// that they
  707. /// don't want searched, in addition to or instead of the platform ones.
  708. ///
  709. /// \param[in] module_sp
  710. /// A shared pointer reference to the module that checked.
  711. ///
  712. /// \return \b true if the module should be excluded, \b false otherwise.
  713. bool
  714. ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP &module_sp);
  715. const ArchSpec &GetArchitecture() const { return m_arch.GetSpec(); }
  716. /// Set the architecture for this target.
  717. ///
  718. /// If the current target has no Images read in, then this just sets the
  719. /// architecture, which will be used to select the architecture of the
  720. /// ExecutableModule when that is set. If the current target has an
  721. /// ExecutableModule, then calling SetArchitecture with a different
  722. /// architecture from the currently selected one will reset the
  723. /// ExecutableModule to that slice of the file backing the ExecutableModule.
  724. /// If the file backing the ExecutableModule does not contain a fork of this
  725. /// architecture, then this code will return false, and the architecture
  726. /// won't be changed. If the input arch_spec is the same as the already set
  727. /// architecture, this is a no-op.
  728. ///
  729. /// \param[in] arch_spec
  730. /// The new architecture.
  731. ///
  732. /// \param[in] set_platform
  733. /// If \b true, then the platform will be adjusted if the currently
  734. /// selected platform is not compatible with the architecture being set.
  735. /// If \b false, then just the architecture will be set even if the
  736. /// currently selected platform isn't compatible (in case it might be
  737. /// manually set following this function call).
  738. ///
  739. /// \return
  740. /// \b true if the architecture was successfully set, \bfalse otherwise.
  741. bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform = false);
  742. bool MergeArchitecture(const ArchSpec &arch_spec);
  743. Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }
  744. Debugger &GetDebugger() { return m_debugger; }
  745. size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
  746. Status &error);
  747. // Reading memory through the target allows us to skip going to the process
  748. // for reading memory if possible and it allows us to try and read from any
  749. // constant sections in our object files on disk. If you always want live
  750. // program memory, read straight from the process. If you possibly want to
  751. // read from const sections in object files, read from the target. This
  752. // version of ReadMemory will try and read memory from the process if the
  753. // process is alive. The order is:
  754. // 1 - if (force_live_memory == false) and the address falls in a read-only
  755. // section, then read from the file cache
  756. // 2 - if there is a process, then read from memory
  757. // 3 - if there is no process, then read from the file cache
  758. size_t ReadMemory(const Address &addr, void *dst, size_t dst_len,
  759. Status &error, bool force_live_memory = false,
  760. lldb::addr_t *load_addr_ptr = nullptr);
  761. size_t ReadCStringFromMemory(const Address &addr, std::string &out_str,
  762. Status &error);
  763. size_t ReadCStringFromMemory(const Address &addr, char *dst,
  764. size_t dst_max_len, Status &result_error);
  765. size_t ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
  766. bool is_signed, Scalar &scalar,
  767. Status &error,
  768. bool force_live_memory = false);
  769. uint64_t ReadUnsignedIntegerFromMemory(const Address &addr,
  770. size_t integer_byte_size,
  771. uint64_t fail_value, Status &error,
  772. bool force_live_memory = false);
  773. bool ReadPointerFromMemory(const Address &addr, Status &error,
  774. Address &pointer_addr,
  775. bool force_live_memory = false);
  776. SectionLoadList &GetSectionLoadList() {
  777. return m_section_load_history.GetCurrentSectionLoadList();
  778. }
  779. static Target *GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
  780. const SymbolContext *sc_ptr);
  781. // lldb::ExecutionContextScope pure virtual functions
  782. lldb::TargetSP CalculateTarget() override;
  783. lldb::ProcessSP CalculateProcess() override;
  784. lldb::ThreadSP CalculateThread() override;
  785. lldb::StackFrameSP CalculateStackFrame() override;
  786. void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
  787. PathMappingList &GetImageSearchPathList();
  788. llvm::Expected<TypeSystem &>
  789. GetScratchTypeSystemForLanguage(lldb::LanguageType language,
  790. bool create_on_demand = true);
  791. std::vector<TypeSystem *> GetScratchTypeSystems(bool create_on_demand = true);
  792. PersistentExpressionState *
  793. GetPersistentExpressionStateForLanguage(lldb::LanguageType language);
  794. // Creates a UserExpression for the given language, the rest of the
  795. // parameters have the same meaning as for the UserExpression constructor.
  796. // Returns a new-ed object which the caller owns.
  797. UserExpression *
  798. GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix,
  799. lldb::LanguageType language,
  800. Expression::ResultType desired_type,
  801. const EvaluateExpressionOptions &options,
  802. ValueObject *ctx_obj, Status &error);
  803. // Creates a FunctionCaller for the given language, the rest of the
  804. // parameters have the same meaning as for the FunctionCaller constructor.
  805. // Since a FunctionCaller can't be
  806. // IR Interpreted, it makes no sense to call this with an
  807. // ExecutionContextScope that lacks
  808. // a Process.
  809. // Returns a new-ed object which the caller owns.
  810. FunctionCaller *GetFunctionCallerForLanguage(lldb::LanguageType language,
  811. const CompilerType &return_type,
  812. const Address &function_address,
  813. const ValueList &arg_value_list,
  814. const char *name, Status &error);
  815. /// Creates and installs a UtilityFunction for the given language.
  816. llvm::Expected<std::unique_ptr<UtilityFunction>>
  817. CreateUtilityFunction(std::string expression, std::string name,
  818. lldb::LanguageType language, ExecutionContext &exe_ctx);
  819. // Install any files through the platform that need be to installed prior to
  820. // launching or attaching.
  821. Status Install(ProcessLaunchInfo *launch_info);
  822. bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr);
  823. bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr,
  824. uint32_t stop_id = SectionLoadHistory::eStopIDNow);
  825. bool SetSectionLoadAddress(const lldb::SectionSP &section,
  826. lldb::addr_t load_addr,
  827. bool warn_multiple = false);
  828. size_t UnloadModuleSections(const lldb::ModuleSP &module_sp);
  829. size_t UnloadModuleSections(const ModuleList &module_list);
  830. bool SetSectionUnloaded(const lldb::SectionSP &section_sp);
  831. bool SetSectionUnloaded(const lldb::SectionSP &section_sp,
  832. lldb::addr_t load_addr);
  833. void ClearAllLoadedSections();
  834. /// Set the \a Trace object containing processor trace information of this
  835. /// target.
  836. ///
  837. /// \param[in] trace_sp
  838. /// The trace object.
  839. void SetTrace(const lldb::TraceSP &trace_sp);
  840. /// Get the \a Trace object containing processor trace information of this
  841. /// target.
  842. ///
  843. /// \return
  844. /// The trace object. It might be undefined.
  845. lldb::TraceSP &GetTrace();
  846. /// Similar to \a GetTrace, but this also tries to create a \a Trace object
  847. /// if not available using the default supported tracing technology for
  848. /// this process.
  849. llvm::Expected<lldb::TraceSP &> GetTraceOrCreate();
  850. // Since expressions results can persist beyond the lifetime of a process,
  851. // and the const expression results are available after a process is gone, we
  852. // provide a way for expressions to be evaluated from the Target itself. If
  853. // an expression is going to be run, then it should have a frame filled in in
  854. // the execution context.
  855. lldb::ExpressionResults EvaluateExpression(
  856. llvm::StringRef expression, ExecutionContextScope *exe_scope,
  857. lldb::ValueObjectSP &result_valobj_sp,
  858. const EvaluateExpressionOptions &options = EvaluateExpressionOptions(),
  859. std::string *fixed_expression = nullptr, ValueObject *ctx_obj = nullptr);
  860. lldb::ExpressionVariableSP GetPersistentVariable(ConstString name);
  861. lldb::addr_t GetPersistentSymbol(ConstString name);
  862. /// This method will return the address of the starting function for
  863. /// this binary, e.g. main() or its equivalent. This can be used as
  864. /// an address of a function that is not called once a binary has
  865. /// started running - e.g. as a return address for inferior function
  866. /// calls that are unambiguous completion of the function call, not
  867. /// called during the course of the inferior function code running.
  868. ///
  869. /// If no entry point can be found, an invalid address is returned.
  870. ///
  871. /// \param [out] err
  872. /// This object will be set to failure if no entry address could
  873. /// be found, and may contain a helpful error message.
  874. //
  875. /// \return
  876. /// Returns the entry address for this program, or an error
  877. /// if none can be found.
  878. llvm::Expected<lldb_private::Address> GetEntryPointAddress();
  879. // Target Stop Hooks
  880. class StopHook : public UserID {
  881. public:
  882. StopHook(const StopHook &rhs);
  883. virtual ~StopHook() = default;
  884. enum class StopHookKind : uint32_t { CommandBased = 0, ScriptBased };
  885. enum class StopHookResult : uint32_t {
  886. KeepStopped = 0,
  887. RequestContinue,
  888. AlreadyContinued
  889. };
  890. lldb::TargetSP &GetTarget() { return m_target_sp; }
  891. // Set the specifier. The stop hook will own the specifier, and is
  892. // responsible for deleting it when we're done.
  893. void SetSpecifier(SymbolContextSpecifier *specifier);
  894. SymbolContextSpecifier *GetSpecifier() { return m_specifier_sp.get(); }
  895. bool ExecutionContextPasses(const ExecutionContext &exe_ctx);
  896. // Called on stop, this gets passed the ExecutionContext for each "stop
  897. // with a reason" thread. It should add to the stream whatever text it
  898. // wants to show the user, and return False to indicate it wants the target
  899. // not to stop.
  900. virtual StopHookResult HandleStop(ExecutionContext &exe_ctx,
  901. lldb::StreamSP output) = 0;
  902. // Set the Thread Specifier. The stop hook will own the thread specifier,
  903. // and is responsible for deleting it when we're done.
  904. void SetThreadSpecifier(ThreadSpec *specifier);
  905. ThreadSpec *GetThreadSpecifier() { return m_thread_spec_up.get(); }
  906. bool IsActive() { return m_active; }
  907. void SetIsActive(bool is_active) { m_active = is_active; }
  908. void SetAutoContinue(bool auto_continue) {
  909. m_auto_continue = auto_continue;
  910. }
  911. bool GetAutoContinue() const { return m_auto_continue; }
  912. void GetDescription(Stream *s, lldb::DescriptionLevel level) const;
  913. virtual void GetSubclassDescription(Stream *s,
  914. lldb::DescriptionLevel level) const = 0;
  915. protected:
  916. lldb::TargetSP m_target_sp;
  917. lldb::SymbolContextSpecifierSP m_specifier_sp;
  918. std::unique_ptr<ThreadSpec> m_thread_spec_up;
  919. bool m_active = true;
  920. bool m_auto_continue = false;
  921. StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid);
  922. };
  923. class StopHookCommandLine : public StopHook {
  924. public:
  925. virtual ~StopHookCommandLine() = default;
  926. StringList &GetCommands() { return m_commands; }
  927. void SetActionFromString(const std::string &strings);
  928. void SetActionFromStrings(const std::vector<std::string> &strings);
  929. StopHookResult HandleStop(ExecutionContext &exc_ctx,
  930. lldb::StreamSP output_sp) override;
  931. void GetSubclassDescription(Stream *s,
  932. lldb::DescriptionLevel level) const override;
  933. private:
  934. StringList m_commands;
  935. // Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
  936. // and fill it with commands, and SetSpecifier to set the specifier shared
  937. // pointer (can be null, that will match anything.)
  938. StopHookCommandLine(lldb::TargetSP target_sp, lldb::user_id_t uid)
  939. : StopHook(target_sp, uid) {}
  940. friend class Target;
  941. };
  942. class StopHookScripted : public StopHook {
  943. public:
  944. virtual ~StopHookScripted() = default;
  945. StopHookResult HandleStop(ExecutionContext &exc_ctx,
  946. lldb::StreamSP output) override;
  947. Status SetScriptCallback(std::string class_name,
  948. StructuredData::ObjectSP extra_args_sp);
  949. void GetSubclassDescription(Stream *s,
  950. lldb::DescriptionLevel level) const override;
  951. private:
  952. std::string m_class_name;
  953. /// This holds the dictionary of keys & values that can be used to
  954. /// parametrize any given callback's behavior.
  955. StructuredDataImpl *m_extra_args; // We own this structured data,
  956. // but the SD itself manages the UP.
  957. /// This holds the python callback object.
  958. StructuredData::GenericSP m_implementation_sp;
  959. /// Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
  960. /// and fill it with commands, and SetSpecifier to set the specifier shared
  961. /// pointer (can be null, that will match anything.)
  962. StopHookScripted(lldb::TargetSP target_sp, lldb::user_id_t uid)
  963. : StopHook(target_sp, uid) {}
  964. friend class Target;
  965. };
  966. typedef std::shared_ptr<StopHook> StopHookSP;
  967. /// Add an empty stop hook to the Target's stop hook list, and returns a
  968. /// shared pointer to it in new_hook. Returns the id of the new hook.
  969. StopHookSP CreateStopHook(StopHook::StopHookKind kind);
  970. /// If you tried to create a stop hook, and that failed, call this to
  971. /// remove the stop hook, as it will also reset the stop hook counter.
  972. void UndoCreateStopHook(lldb::user_id_t uid);
  973. // Runs the stop hooks that have been registered for this target.
  974. // Returns true if the stop hooks cause the target to resume.
  975. bool RunStopHooks();
  976. size_t GetStopHookSize();
  977. bool SetSuppresStopHooks(bool suppress) {
  978. bool old_value = m_suppress_stop_hooks;
  979. m_suppress_stop_hooks = suppress;
  980. return old_value;
  981. }
  982. bool GetSuppressStopHooks() { return m_suppress_stop_hooks; }
  983. bool RemoveStopHookByID(lldb::user_id_t uid);
  984. void RemoveAllStopHooks();
  985. StopHookSP GetStopHookByID(lldb::user_id_t uid);
  986. bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state);
  987. void SetAllStopHooksActiveState(bool active_state);
  988. size_t GetNumStopHooks() const { return m_stop_hooks.size(); }
  989. StopHookSP GetStopHookAtIndex(size_t index) {
  990. if (index >= GetNumStopHooks())
  991. return StopHookSP();
  992. StopHookCollection::iterator pos = m_stop_hooks.begin();
  993. while (index > 0) {
  994. pos++;
  995. index--;
  996. }
  997. return (*pos).second;
  998. }
  999. lldb::PlatformSP GetPlatform() { return m_platform_sp; }
  1000. void SetPlatform(const lldb::PlatformSP &platform_sp) {
  1001. m_platform_sp = platform_sp;
  1002. }
  1003. SourceManager &GetSourceManager();
  1004. // Methods.
  1005. lldb::SearchFilterSP
  1006. GetSearchFilterForModule(const FileSpec *containingModule);
  1007. lldb::SearchFilterSP
  1008. GetSearchFilterForModuleList(const FileSpecList *containingModuleList);
  1009. lldb::SearchFilterSP
  1010. GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules,
  1011. const FileSpecList *containingSourceFiles);
  1012. lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language,
  1013. const char *repl_options, bool can_create);
  1014. void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp);
  1015. StackFrameRecognizerManager &GetFrameRecognizerManager() {
  1016. return *m_frame_recognizer_manager_up;
  1017. }
  1018. protected:
  1019. /// Implementing of ModuleList::Notifier.
  1020. void NotifyModuleAdded(const ModuleList &module_list,
  1021. const lldb::ModuleSP &module_sp) override;
  1022. void NotifyModuleRemoved(const ModuleList &module_list,
  1023. const lldb::ModuleSP &module_sp) override;
  1024. void NotifyModuleUpdated(const ModuleList &module_list,
  1025. const lldb::ModuleSP &old_module_sp,
  1026. const lldb::ModuleSP &new_module_sp) override;
  1027. void NotifyWillClearList(const ModuleList &module_list) override;
  1028. void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override;
  1029. class Arch {
  1030. public:
  1031. explicit Arch(const ArchSpec &spec);
  1032. const Arch &operator=(const ArchSpec &spec);
  1033. const ArchSpec &GetSpec() const { return m_spec; }
  1034. Architecture *GetPlugin() const { return m_plugin_up.get(); }
  1035. private:
  1036. ArchSpec m_spec;
  1037. std::unique_ptr<Architecture> m_plugin_up;
  1038. };
  1039. // Member variables.
  1040. Debugger &m_debugger;
  1041. lldb::PlatformSP m_platform_sp; ///< The platform for this target.
  1042. std::recursive_mutex m_mutex; ///< An API mutex that is used by the lldb::SB*
  1043. /// classes make the SB interface thread safe
  1044. /// When the private state thread calls SB API's - usually because it is
  1045. /// running OS plugin or Python ThreadPlan code - it should not block on the
  1046. /// API mutex that is held by the code that kicked off the sequence of events
  1047. /// that led us to run the code. We hand out this mutex instead when we
  1048. /// detect that code is running on the private state thread.
  1049. std::recursive_mutex m_private_mutex;
  1050. Arch m_arch;
  1051. ModuleList m_images; ///< The list of images for this process (shared
  1052. /// libraries and anything dynamically loaded).
  1053. SectionLoadHistory m_section_load_history;
  1054. BreakpointList m_breakpoint_list;
  1055. BreakpointList m_internal_breakpoint_list;
  1056. using BreakpointNameList = std::map<ConstString, BreakpointName *>;
  1057. BreakpointNameList m_breakpoint_names;
  1058. lldb::BreakpointSP m_last_created_breakpoint;
  1059. WatchpointList m_watchpoint_list;
  1060. lldb::WatchpointSP m_last_created_watchpoint;
  1061. // We want to tightly control the process destruction process so we can
  1062. // correctly tear down everything that we need to, so the only class that
  1063. // knows about the process lifespan is this target class.
  1064. lldb::ProcessSP m_process_sp;
  1065. lldb::SearchFilterSP m_search_filter_sp;
  1066. PathMappingList m_image_search_paths;
  1067. TypeSystemMap m_scratch_type_system_map;
  1068. typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
  1069. REPLMap m_repl_map;
  1070. lldb::SourceManagerUP m_source_manager_up;
  1071. typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
  1072. StopHookCollection m_stop_hooks;
  1073. lldb::user_id_t m_stop_hook_next_id;
  1074. bool m_valid;
  1075. bool m_suppress_stop_hooks;
  1076. bool m_is_dummy_target;
  1077. unsigned m_next_persistent_variable_index = 0;
  1078. /// An optional \a lldb_private::Trace object containing processor trace
  1079. /// information of this target.
  1080. lldb::TraceSP m_trace_sp;
  1081. /// Stores the frame recognizers of this target.
  1082. lldb::StackFrameRecognizerManagerUP m_frame_recognizer_manager_up;
  1083. static void ImageSearchPathsChanged(const PathMappingList &path_list,
  1084. void *baton);
  1085. // Utilities for `statistics` command.
  1086. private:
  1087. std::vector<uint32_t> m_stats_storage;
  1088. bool m_collecting_stats = false;
  1089. public:
  1090. void SetCollectingStats(bool v) { m_collecting_stats = v; }
  1091. bool GetCollectingStats() { return m_collecting_stats; }
  1092. void IncrementStats(lldb_private::StatisticKind key) {
  1093. if (!GetCollectingStats())
  1094. return;
  1095. lldbassert(key < lldb_private::StatisticKind::StatisticMax &&
  1096. "invalid statistics!");
  1097. m_stats_storage[key] += 1;
  1098. }
  1099. std::vector<uint32_t> GetStatistics() { return m_stats_storage; }
  1100. private:
  1101. /// Construct with optional file and arch.
  1102. ///
  1103. /// This member is private. Clients must use
  1104. /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
  1105. /// so all targets can be tracked from the central target list.
  1106. ///
  1107. /// \see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
  1108. Target(Debugger &debugger, const ArchSpec &target_arch,
  1109. const lldb::PlatformSP &platform_sp, bool is_dummy_target);
  1110. // Helper function.
  1111. bool ProcessIsValid();
  1112. // Copy breakpoints, stop hooks and so forth from the dummy target:
  1113. void PrimeFromDummyTarget(Target &target);
  1114. void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal);
  1115. void FinalizeFileActions(ProcessLaunchInfo &info);
  1116. Target(const Target &) = delete;
  1117. const Target &operator=(const Target &) = delete;
  1118. };
  1119. } // namespace lldb_private
  1120. #endif // LLDB_TARGET_TARGET_H