Process.h 113 KB

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