UnixLocalInferiorProcess.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. //===-- UnixLocalInferiorProcess.cpp - A Local process on a Unixy system --===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides one implementation of the InferiorProcess class, which is
  11. // designed to be used on unixy systems (those that support pipe, fork, exec,
  12. // and signals).
  13. //
  14. // When the process is started, the debugger creates a pair of pipes, forks, and
  15. // makes the child start executing the program. The child executes the process
  16. // with an IntrinsicLowering instance that turns debugger intrinsics into actual
  17. // callbacks.
  18. //
  19. // This target takes advantage of the fact that the Module* addresses in the
  20. // parent and the Module* addresses in the child will be the same, due to the
  21. // use of fork(). As such, global addresses looked up in the child can be sent
  22. // over the pipe to the debugger.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/Debugger/InferiorProcess.h"
  26. #include "llvm/Constant.h"
  27. #include "llvm/Instructions.h"
  28. #include "llvm/Module.h"
  29. #include "llvm/ModuleProvider.h"
  30. #include "llvm/Type.h"
  31. #include "llvm/CodeGen/IntrinsicLowering.h"
  32. #include "llvm/ExecutionEngine/GenericValue.h"
  33. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  34. #include "llvm/Support/FileUtilities.h"
  35. #include "llvm/ADT/StringExtras.h"
  36. #include "FDHandle.h"
  37. #include <cerrno>
  38. #include <csignal>
  39. #include <unistd.h> // Unix-specific debugger support
  40. #include <sys/types.h>
  41. #include <sys/wait.h>
  42. using namespace llvm;
  43. // runChild - Entry point for the child process.
  44. static void runChild(Module *M, const std::vector<std::string> &Arguments,
  45. const char * const *envp,
  46. FDHandle ReadFD, FDHandle WriteFD);
  47. //===----------------------------------------------------------------------===//
  48. // Parent/Child Pipe Protocol
  49. //===----------------------------------------------------------------------===//
  50. //
  51. // The parent/child communication protocol is designed to have the child process
  52. // responding to requests that the debugger makes. Whenever the child process
  53. // has stopped (due to a break point, single stepping, etc), the child process
  54. // enters a message processing loop, where it reads and responds to commands
  55. // until the parent decides that it wants to continue execution in some way.
  56. //
  57. // Whenever the child process stops, it notifies the debugger by sending a
  58. // character over the wire.
  59. //
  60. namespace {
  61. /// LocationToken - Objects of this type are sent across the pipe from the
  62. /// child to the parent to indicate where various stack frames are located.
  63. struct LocationToken {
  64. unsigned Line, Col;
  65. const GlobalVariable *File;
  66. LocationToken(unsigned L = 0, unsigned C = 0, const GlobalVariable *F = 0)
  67. : Line(L), Col(C), File(F) {}
  68. };
  69. }
  70. // Once the debugger process has received the LocationToken, it can make
  71. // requests of the child by sending one of the following enum values followed by
  72. // any data required by that command. The child responds with data appropriate
  73. // to the command.
  74. //
  75. namespace {
  76. /// CommandID - This enum defines all of the commands that the child process
  77. /// can respond to. The actual expected data and responses are defined as the
  78. /// enum values are defined.
  79. ///
  80. enum CommandID {
  81. //===------------------------------------------------------------------===//
  82. // Execution commands - These are sent to the child to from the debugger to
  83. // get it to do certain things.
  84. //
  85. // StepProgram: void->char - This command causes the program to continue
  86. // execution, but stop as soon as it reaches another stoppoint.
  87. StepProgram,
  88. // FinishProgram: FrameDesc*->char - This command causes the program to
  89. // continue execution until the specified function frame returns.
  90. FinishProgram,
  91. // ContProgram: void->char - This command causes the program to continue
  92. // execution, stopping at some point in the future.
  93. ContProgram,
  94. // GetSubprogramDescriptor: FrameDesc*->GlobalValue* - This command returns
  95. // the GlobalValue* descriptor object for the specified stack frame.
  96. GetSubprogramDescriptor,
  97. // GetParentFrame: FrameDesc*->FrameDesc* - This command returns the frame
  98. // descriptor for the parent stack frame to the specified one, or null if
  99. // there is none.
  100. GetParentFrame,
  101. // GetFrameLocation - FrameDesc*->LocationToken - This command returns the
  102. // location that a particular stack frame is stopped at.
  103. GetFrameLocation,
  104. // AddBreakpoint - LocationToken->unsigned - This command instructs the
  105. // target to install a breakpoint at the specified location.
  106. AddBreakpoint,
  107. // RemoveBreakpoint - unsigned->void - This command instructs the target to
  108. // remove a breakpoint.
  109. RemoveBreakpoint,
  110. };
  111. }
  112. //===----------------------------------------------------------------------===//
  113. // Parent Process Code
  114. //===----------------------------------------------------------------------===//
  115. namespace {
  116. class IP : public InferiorProcess {
  117. // ReadFD, WriteFD - The file descriptors to read/write to the inferior
  118. // process.
  119. FDHandle ReadFD, WriteFD;
  120. // ChildPID - The unix PID of the child process we forked.
  121. mutable pid_t ChildPID;
  122. public:
  123. IP(Module *M, const std::vector<std::string> &Arguments,
  124. const char * const *envp);
  125. ~IP();
  126. std::string getStatus() const;
  127. /// Execution method implementations...
  128. virtual void stepProgram();
  129. virtual void finishProgram(void *Frame);
  130. virtual void contProgram();
  131. // Stack frame method implementations...
  132. virtual void *getPreviousFrame(void *Frame) const;
  133. virtual const GlobalVariable *getSubprogramDesc(void *Frame) const;
  134. virtual void getFrameLocation(void *Frame, unsigned &LineNo,
  135. unsigned &ColNo,
  136. const GlobalVariable *&SourceDesc) const;
  137. // Breakpoint implementation methods
  138. virtual unsigned addBreakpoint(unsigned LineNo, unsigned ColNo,
  139. const GlobalVariable *SourceDesc);
  140. virtual void removeBreakpoint(unsigned ID);
  141. private:
  142. /// startChild - This starts up the child process, and initializes the
  143. /// ChildPID member.
  144. ///
  145. void startChild(Module *M, const std::vector<std::string> &Arguments,
  146. const char * const *envp);
  147. /// killChild - Kill or reap the child process. This throws the
  148. /// InferiorProcessDead exception an exit code if the process had already
  149. /// died, otherwise it just kills it and returns.
  150. void killChild() const;
  151. private:
  152. // Methods for communicating with the child process. If the child exits or
  153. // dies while attempting to communicate with it, ChildPID is set to zero and
  154. // an exception is thrown.
  155. /// readFromChild - Low-level primitive to read some data from the child,
  156. /// throwing an exception if it dies.
  157. void readFromChild(void *Buffer, unsigned Size) const;
  158. /// writeToChild - Low-level primitive to send some data to the child
  159. /// process, throwing an exception if the child died.
  160. void writeToChild(void *Buffer, unsigned Size) const;
  161. /// sendCommand - Send a command token and the request data to the child.
  162. ///
  163. void sendCommand(CommandID Command, void *Data, unsigned Size) const;
  164. /// waitForStop - This method waits for the child process to reach a stop
  165. /// point.
  166. void waitForStop();
  167. };
  168. }
  169. // create - This is the factory method for the InferiorProcess class. Since
  170. // there is currently only one subclass of InferiorProcess, we just define it
  171. // here.
  172. InferiorProcess *
  173. InferiorProcess::create(Module *M, const std::vector<std::string> &Arguments,
  174. const char * const *envp) {
  175. return new IP(M, Arguments, envp);
  176. }
  177. /// IP constructor - Create some pipes, them fork a child process. The child
  178. /// process should start execution of the debugged program, but stop at the
  179. /// first available opportunity.
  180. IP::IP(Module *M, const std::vector<std::string> &Arguments,
  181. const char * const *envp)
  182. : InferiorProcess(M) {
  183. // Start the child running...
  184. startChild(M, Arguments, envp);
  185. // Okay, we created the program and it is off and running. Wait for it to
  186. // stop now.
  187. try {
  188. waitForStop();
  189. } catch (InferiorProcessDead &IPD) {
  190. throw "Error waiting for the child process to stop. "
  191. "It exited with status " + itostr(IPD.getExitCode());
  192. }
  193. }
  194. IP::~IP() {
  195. // If the child is still running, kill it.
  196. if (!ChildPID) return;
  197. killChild();
  198. }
  199. /// getStatus - Return information about the unix process being debugged.
  200. ///
  201. std::string IP::getStatus() const {
  202. if (ChildPID == 0)
  203. return "Unix target. ERROR: child process appears to be dead!\n";
  204. return "Unix target: PID #" + utostr((unsigned)ChildPID) + "\n";
  205. }
  206. /// startChild - This starts up the child process, and initializes the
  207. /// ChildPID member.
  208. ///
  209. void IP::startChild(Module *M, const std::vector<std::string> &Arguments,
  210. const char * const *envp) {
  211. // Create the pipes. Make sure to immediately assign the returned file
  212. // descriptors to FDHandle's so they get destroyed if an exception is thrown.
  213. int FDs[2];
  214. if (pipe(FDs)) throw "Error creating a pipe!";
  215. FDHandle ChildReadFD(FDs[0]);
  216. WriteFD = FDs[1];
  217. if (pipe(FDs)) throw "Error creating a pipe!";
  218. ReadFD = FDs[0];
  219. FDHandle ChildWriteFD(FDs[1]);
  220. // Fork off the child process.
  221. switch (ChildPID = fork()) {
  222. case -1: throw "Error forking child process!";
  223. case 0: // child
  224. delete this; // Free parent pipe file descriptors
  225. runChild(M, Arguments, envp, ChildReadFD, ChildWriteFD);
  226. exit(1);
  227. default: break;
  228. }
  229. }
  230. /// sendCommand - Send a command token and the request data to the child.
  231. ///
  232. void IP::sendCommand(CommandID Command, void *Data, unsigned Size) const {
  233. writeToChild(&Command, sizeof(Command));
  234. writeToChild(Data, Size);
  235. }
  236. /// stepProgram - Implement the 'step' command, continuing execution until
  237. /// the next possible stop point.
  238. void IP::stepProgram() {
  239. sendCommand(StepProgram, 0, 0);
  240. waitForStop();
  241. }
  242. /// finishProgram - Implement the 'finish' command, executing the program until
  243. /// the current function returns to its caller.
  244. void IP::finishProgram(void *Frame) {
  245. sendCommand(FinishProgram, &Frame, sizeof(Frame));
  246. waitForStop();
  247. }
  248. /// contProgram - Implement the 'cont' command, continuing execution until
  249. /// a breakpoint is encountered.
  250. void IP::contProgram() {
  251. sendCommand(ContProgram, 0, 0);
  252. waitForStop();
  253. }
  254. //===----------------------------------------------------------------------===//
  255. // Stack manipulation methods
  256. //
  257. /// getPreviousFrame - Given the descriptor for the current stack frame,
  258. /// return the descriptor for the caller frame. This returns null when it
  259. /// runs out of frames.
  260. void *IP::getPreviousFrame(void *Frame) const {
  261. sendCommand(GetParentFrame, &Frame, sizeof(Frame));
  262. readFromChild(&Frame, sizeof(Frame));
  263. return Frame;
  264. }
  265. /// getSubprogramDesc - Return the subprogram descriptor for the current
  266. /// stack frame.
  267. const GlobalVariable *IP::getSubprogramDesc(void *Frame) const {
  268. sendCommand(GetSubprogramDescriptor, &Frame, sizeof(Frame));
  269. const GlobalVariable *Desc;
  270. readFromChild(&Desc, sizeof(Desc));
  271. return Desc;
  272. }
  273. /// getFrameLocation - This method returns the source location where each stack
  274. /// frame is stopped.
  275. void IP::getFrameLocation(void *Frame, unsigned &LineNo, unsigned &ColNo,
  276. const GlobalVariable *&SourceDesc) const {
  277. sendCommand(GetFrameLocation, &Frame, sizeof(Frame));
  278. LocationToken Loc;
  279. readFromChild(&Loc, sizeof(Loc));
  280. LineNo = Loc.Line;
  281. ColNo = Loc.Col;
  282. SourceDesc = Loc.File;
  283. }
  284. //===----------------------------------------------------------------------===//
  285. // Breakpoint manipulation methods
  286. //
  287. unsigned IP::addBreakpoint(unsigned LineNo, unsigned ColNo,
  288. const GlobalVariable *SourceDesc) {
  289. LocationToken Loc;
  290. Loc.Line = LineNo;
  291. Loc.Col = ColNo;
  292. Loc.File = SourceDesc;
  293. sendCommand(AddBreakpoint, &Loc, sizeof(Loc));
  294. unsigned ID;
  295. readFromChild(&ID, sizeof(ID));
  296. return ID;
  297. }
  298. void IP::removeBreakpoint(unsigned ID) {
  299. sendCommand(RemoveBreakpoint, &ID, sizeof(ID));
  300. }
  301. //===----------------------------------------------------------------------===//
  302. // Methods for communication with the child process
  303. //
  304. // Methods for communicating with the child process. If the child exits or dies
  305. // while attempting to communicate with it, ChildPID is set to zero and an
  306. // exception is thrown.
  307. //
  308. /// readFromChild - Low-level primitive to read some data from the child,
  309. /// throwing an exception if it dies.
  310. void IP::readFromChild(void *Buffer, unsigned Size) const {
  311. assert(ChildPID &&
  312. "Child process died and still attempting to communicate with it!");
  313. while (Size) {
  314. ssize_t Amount = read(ReadFD, Buffer, Size);
  315. if (Amount == 0) {
  316. // If we cannot communicate with the process, kill it.
  317. killChild();
  318. // If killChild succeeded, then the process must have closed the pipe FD
  319. // or something, because the child existed, but we cannot communicate with
  320. // it.
  321. throw InferiorProcessDead(-1);
  322. } else if (Amount == -1) {
  323. if (errno != EINTR) {
  324. ChildPID = 0;
  325. killChild();
  326. throw "Error reading from child process!";
  327. }
  328. } else {
  329. // We read a chunk.
  330. Buffer = (char*)Buffer + Amount;
  331. Size -= Amount;
  332. }
  333. }
  334. }
  335. /// writeToChild - Low-level primitive to send some data to the child
  336. /// process, throwing an exception if the child died.
  337. void IP::writeToChild(void *Buffer, unsigned Size) const {
  338. while (Size) {
  339. ssize_t Amount = write(WriteFD, Buffer, Size);
  340. if (Amount < 0 && errno == EINTR) continue;
  341. if (Amount <= 0) {
  342. // If we cannot communicate with the process, kill it.
  343. killChild();
  344. // If killChild succeeded, then the process must have closed the pipe FD
  345. // or something, because the child existed, but we cannot communicate with
  346. // it.
  347. throw InferiorProcessDead(-1);
  348. } else {
  349. // We wrote a chunk.
  350. Buffer = (char*)Buffer + Amount;
  351. Size -= Amount;
  352. }
  353. }
  354. }
  355. /// killChild - Kill or reap the child process. This throws the
  356. /// InferiorProcessDead exception an exit code if the process had already
  357. /// died, otherwise it just returns the exit code if it had to be killed.
  358. void IP::killChild() const {
  359. assert(ChildPID != 0 && "Child has already been reaped!");
  360. // If the process terminated on its own accord, closing the pipe file
  361. // descriptors, we will get here. Check to see if the process has already
  362. // died in this manner, gracefully.
  363. int Status = 0;
  364. int PID;
  365. do {
  366. PID = waitpid(ChildPID, &Status, WNOHANG);
  367. } while (PID < 0 && errno == EINTR);
  368. if (PID < 0) throw "Error waiting for child to exit!";
  369. // Ok, there is a slight race condition here. It's possible that we will find
  370. // out that the file descriptor closed before waitpid will indicate that the
  371. // process gracefully died. If we don't know that the process gracefully
  372. // died, wait a bit and try again. This is pretty nasty.
  373. if (PID == 0) {
  374. usleep(10000); // Wait a bit.
  375. // Try again.
  376. Status = 0;
  377. do {
  378. PID = waitpid(ChildPID, &Status, WNOHANG);
  379. } while (PID < 0 && errno == EINTR);
  380. if (PID < 0) throw "Error waiting for child to exit!";
  381. }
  382. // If the child process was already dead, then indicate that the process
  383. // terminated on its own.
  384. if (PID) {
  385. assert(PID == ChildPID && "Didn't reap child?");
  386. ChildPID = 0; // Child has been reaped
  387. if (WIFEXITED(Status))
  388. throw InferiorProcessDead(WEXITSTATUS(Status));
  389. else if (WIFSIGNALED(Status))
  390. throw InferiorProcessDead(WTERMSIG(Status));
  391. throw InferiorProcessDead(-1);
  392. }
  393. // Otherwise, the child exists and has not yet been killed.
  394. if (kill(ChildPID, SIGKILL) < 0)
  395. throw "Error killing child process!";
  396. do {
  397. PID = waitpid(ChildPID, 0, 0);
  398. } while (PID < 0 && errno == EINTR);
  399. if (PID <= 0) throw "Error waiting for child to exit!";
  400. assert(PID == ChildPID && "Didn't reap child?");
  401. }
  402. /// waitForStop - This method waits for the child process to reach a stop
  403. /// point. When it does, it fills in the CurLocation member and returns.
  404. void IP::waitForStop() {
  405. char Dummy;
  406. readFromChild(&Dummy, sizeof(char));
  407. }
  408. //===----------------------------------------------------------------------===//
  409. // Child Process Code
  410. //===----------------------------------------------------------------------===//
  411. namespace {
  412. class SourceSubprogram;
  413. /// SourceRegion - Instances of this class represent the regions that are
  414. /// active in the program.
  415. class SourceRegion {
  416. /// Parent - A pointer to the region that encloses the current one.
  417. SourceRegion *Parent;
  418. /// CurSubprogram - The subprogram that contains this region. This allows
  419. /// efficient stack traversals.
  420. SourceSubprogram *CurSubprogram;
  421. /// CurLine, CurCol, CurFile - The last location visited by this region.
  422. /// This is used for getting the source location of callers in stack frames.
  423. unsigned CurLine, CurCol;
  424. void *CurFileDesc;
  425. //std::vector<void*> ActiveObjects;
  426. public:
  427. SourceRegion(SourceRegion *p, SourceSubprogram *Subprogram = 0)
  428. : Parent(p), CurSubprogram(Subprogram ? Subprogram : p->getSubprogram()) {
  429. CurLine = 0; CurCol = 0;
  430. CurFileDesc = 0;
  431. }
  432. virtual ~SourceRegion() {}
  433. SourceRegion *getParent() const { return Parent; }
  434. SourceSubprogram *getSubprogram() const { return CurSubprogram; }
  435. void updateLocation(unsigned Line, unsigned Col, void *File) {
  436. CurLine = Line;
  437. CurCol = Col;
  438. CurFileDesc = File;
  439. }
  440. /// Return a LocationToken for the place that this stack frame stopped or
  441. /// called a sub-function.
  442. LocationToken getLocation(ExecutionEngine *EE) {
  443. LocationToken LT;
  444. LT.Line = CurLine;
  445. LT.Col = CurCol;
  446. const GlobalValue *GV = EE->getGlobalValueAtAddress(CurFileDesc);
  447. LT.File = dyn_cast_or_null<GlobalVariable>(GV);
  448. return LT;
  449. }
  450. };
  451. /// SourceSubprogram - This is a stack-frame that represents a source program.
  452. ///
  453. class SourceSubprogram : public SourceRegion {
  454. /// Desc - A pointer to the descriptor for the subprogram that this frame
  455. /// represents.
  456. void *Desc;
  457. public:
  458. SourceSubprogram(SourceRegion *P, void *desc)
  459. : SourceRegion(P, this), Desc(desc) {}
  460. void *getDescriptor() const { return Desc; }
  461. };
  462. /// Child class - This class contains all of the information and methods used
  463. /// by the child side of the debugger. The single instance of this object is
  464. /// pointed to by the "TheChild" global variable.
  465. class Child {
  466. /// M - The module for the program currently being debugged.
  467. ///
  468. Module *M;
  469. /// EE - The execution engine that we are using to run the program.
  470. ///
  471. ExecutionEngine *EE;
  472. /// ReadFD, WriteFD - The file descriptor handles for this side of the
  473. /// debugger pipe.
  474. FDHandle ReadFD, WriteFD;
  475. /// RegionStack - A linked list of all of the regions dynamically active.
  476. ///
  477. SourceRegion *RegionStack;
  478. /// StopAtNextOpportunity - If this flag is set, the child process will stop
  479. /// and report to the debugger at the next possible chance it gets.
  480. volatile bool StopAtNextOpportunity;
  481. /// StopWhenSubprogramReturns - If this is non-null, the debugger requests
  482. /// that the program stops when the specified function frame is destroyed.
  483. SourceSubprogram *StopWhenSubprogramReturns;
  484. /// Breakpoints - This contains a list of active breakpoints and their IDs.
  485. ///
  486. std::vector<std::pair<unsigned, LocationToken> > Breakpoints;
  487. /// CurBreakpoint - The last assigned breakpoint.
  488. ///
  489. unsigned CurBreakpoint;
  490. public:
  491. Child(Module *m, ExecutionEngine *ee, FDHandle &Read, FDHandle &Write)
  492. : M(m), EE(ee), ReadFD(Read), WriteFD(Write),
  493. RegionStack(0), CurBreakpoint(0) {
  494. StopAtNextOpportunity = true;
  495. StopWhenSubprogramReturns = 0;
  496. }
  497. /// writeToParent - Send the specified buffer of data to the debugger
  498. /// process.
  499. ///
  500. void writeToParent(const void *Buffer, unsigned Size);
  501. /// readFromParent - Read the specified number of bytes from the parent.
  502. ///
  503. void readFromParent(void *Buffer, unsigned Size);
  504. /// childStopped - This method is called whenever the child has stopped
  505. /// execution due to a breakpoint, step command, interruption, or whatever.
  506. /// This stops the process, responds to any requests from the debugger, and
  507. /// when commanded to, can continue execution by returning.
  508. ///
  509. void childStopped();
  510. /// startSubprogram - This method creates a new region for the subroutine
  511. /// with the specified descriptor.
  512. ///
  513. void startSubprogram(void *FuncDesc);
  514. /// startRegion - This method initiates the creation of an anonymous region.
  515. ///
  516. void startRegion();
  517. /// endRegion - This method terminates the last active region.
  518. ///
  519. void endRegion();
  520. /// reachedLine - This method is automatically called by the program every
  521. /// time it executes an llvm.dbg.stoppoint intrinsic. If the debugger wants
  522. /// us to stop here, we do so, otherwise we continue execution.
  523. ///
  524. void reachedLine(unsigned Line, unsigned Col, void *SourceDesc);
  525. };
  526. /// TheChild - The single instance of the Child class, which only gets created
  527. /// in the child process.
  528. Child *TheChild = 0;
  529. } // end anonymous namespace
  530. // writeToParent - Send the specified buffer of data to the debugger process.
  531. void Child::writeToParent(const void *Buffer, unsigned Size) {
  532. while (Size) {
  533. ssize_t Amount = write(WriteFD, Buffer, Size);
  534. if (Amount < 0 && errno == EINTR) continue;
  535. if (Amount <= 0) {
  536. write(2, "ERROR: Connection to debugger lost!\n", 36);
  537. abort();
  538. } else {
  539. // We wrote a chunk.
  540. Buffer = (const char*)Buffer + Amount;
  541. Size -= Amount;
  542. }
  543. }
  544. }
  545. // readFromParent - Read the specified number of bytes from the parent.
  546. void Child::readFromParent(void *Buffer, unsigned Size) {
  547. while (Size) {
  548. ssize_t Amount = read(ReadFD, Buffer, Size);
  549. if (Amount < 0 && errno == EINTR) continue;
  550. if (Amount <= 0) {
  551. write(2, "ERROR: Connection to debugger lost!\n", 36);
  552. abort();
  553. } else {
  554. // We read a chunk.
  555. Buffer = (char*)Buffer + Amount;
  556. Size -= Amount;
  557. }
  558. }
  559. }
  560. /// childStopped - This method is called whenever the child has stopped
  561. /// execution due to a breakpoint, step command, interruption, or whatever.
  562. /// This stops the process, responds to any requests from the debugger, and when
  563. /// commanded to, can continue execution by returning.
  564. ///
  565. void Child::childStopped() {
  566. // Since we stopped, notify the parent that we did so.
  567. char Token = 0;
  568. writeToParent(&Token, sizeof(char));
  569. StopAtNextOpportunity = false;
  570. StopWhenSubprogramReturns = 0;
  571. // Now that the debugger knows that we stopped, read commands from it and
  572. // respond to them appropriately.
  573. CommandID Command;
  574. while (1) {
  575. SourceRegion *Frame;
  576. const void *Result;
  577. readFromParent(&Command, sizeof(CommandID));
  578. switch (Command) {
  579. case StepProgram:
  580. // To step the program, just return.
  581. StopAtNextOpportunity = true;
  582. return;
  583. case FinishProgram: // Run until exit from the specified function...
  584. readFromParent(&Frame, sizeof(Frame));
  585. // The user wants us to stop when the specified FUNCTION exits, not when
  586. // the specified REGION exits.
  587. StopWhenSubprogramReturns = Frame->getSubprogram();
  588. return;
  589. case ContProgram:
  590. // To continue, just return back to execution.
  591. return;
  592. case GetSubprogramDescriptor:
  593. readFromParent(&Frame, sizeof(Frame));
  594. Result =
  595. EE->getGlobalValueAtAddress(Frame->getSubprogram()->getDescriptor());
  596. writeToParent(&Result, sizeof(Result));
  597. break;
  598. case GetParentFrame:
  599. readFromParent(&Frame, sizeof(Frame));
  600. Result = Frame ? Frame->getSubprogram()->getParent() : RegionStack;
  601. writeToParent(&Result, sizeof(Result));
  602. break;
  603. case GetFrameLocation: {
  604. readFromParent(&Frame, sizeof(Frame));
  605. LocationToken LT = Frame->getLocation(EE);
  606. writeToParent(&LT, sizeof(LT));
  607. break;
  608. }
  609. case AddBreakpoint: {
  610. LocationToken Loc;
  611. readFromParent(&Loc, sizeof(Loc));
  612. // Convert the GlobalVariable pointer to the address it was emitted to.
  613. Loc.File = (GlobalVariable*)EE->getPointerToGlobal(Loc.File);
  614. unsigned ID = CurBreakpoint++;
  615. Breakpoints.push_back(std::make_pair(ID, Loc));
  616. writeToParent(&ID, sizeof(ID));
  617. break;
  618. }
  619. case RemoveBreakpoint: {
  620. unsigned ID = 0;
  621. readFromParent(&ID, sizeof(ID));
  622. for (unsigned i = 0, e = Breakpoints.size(); i != e; ++i)
  623. if (Breakpoints[i].first == ID) {
  624. Breakpoints.erase(Breakpoints.begin()+i);
  625. break;
  626. }
  627. break;
  628. }
  629. default:
  630. assert(0 && "Unknown command!");
  631. }
  632. }
  633. }
  634. /// startSubprogram - This method creates a new region for the subroutine
  635. /// with the specified descriptor.
  636. void Child::startSubprogram(void *SPDesc) {
  637. RegionStack = new SourceSubprogram(RegionStack, SPDesc);
  638. }
  639. /// startRegion - This method initiates the creation of an anonymous region.
  640. ///
  641. void Child::startRegion() {
  642. RegionStack = new SourceRegion(RegionStack);
  643. }
  644. /// endRegion - This method terminates the last active region.
  645. ///
  646. void Child::endRegion() {
  647. SourceRegion *R = RegionStack->getParent();
  648. // If the debugger wants us to stop when this frame is destroyed, do so.
  649. if (RegionStack == StopWhenSubprogramReturns) {
  650. StopAtNextOpportunity = true;
  651. StopWhenSubprogramReturns = 0;
  652. }
  653. delete RegionStack;
  654. RegionStack = R;
  655. }
  656. /// reachedLine - This method is automatically called by the program every time
  657. /// it executes an llvm.dbg.stoppoint intrinsic. If the debugger wants us to
  658. /// stop here, we do so, otherwise we continue execution. Note that the Data
  659. /// pointer coming in is a pointer to the LLVM global variable that represents
  660. /// the source file we are in. We do not use the contents of the global
  661. /// directly in the child, but we do use its address.
  662. ///
  663. void Child::reachedLine(unsigned Line, unsigned Col, void *SourceDesc) {
  664. if (RegionStack)
  665. RegionStack->updateLocation(Line, Col, SourceDesc);
  666. // If we hit a breakpoint, stop the program.
  667. for (unsigned i = 0, e = Breakpoints.size(); i != e; ++i)
  668. if (Line == Breakpoints[i].second.Line &&
  669. SourceDesc == (void*)Breakpoints[i].second.File &&
  670. Col == Breakpoints[i].second.Col) {
  671. childStopped();
  672. return;
  673. }
  674. // If we are single stepping the program, make sure to stop it.
  675. if (StopAtNextOpportunity)
  676. childStopped();
  677. }
  678. //===----------------------------------------------------------------------===//
  679. // Child class wrapper functions
  680. //
  681. // These functions are invoked directly by the program as it executes, in place
  682. // of the debugging intrinsic functions that it contains.
  683. //
  684. /// llvm_debugger_stop - Every time the program reaches a new source line, it
  685. /// will call back to this function. If the debugger has a breakpoint or
  686. /// otherwise wants us to stop on this line, we do so, and notify the debugger
  687. /// over the pipe.
  688. ///
  689. extern "C"
  690. void *llvm_debugger_stop(void *Dummy, unsigned Line, unsigned Col,
  691. void *SourceDescriptor) {
  692. TheChild->reachedLine(Line, Col, SourceDescriptor);
  693. return Dummy;
  694. }
  695. /// llvm_dbg_region_start - This function is invoked every time an anonymous
  696. /// region of the source program is entered.
  697. ///
  698. extern "C"
  699. void *llvm_dbg_region_start(void *Dummy) {
  700. TheChild->startRegion();
  701. return Dummy;
  702. }
  703. /// llvm_dbg_subprogram - This function is invoked every time a source-language
  704. /// subprogram has been entered.
  705. ///
  706. extern "C"
  707. void *llvm_dbg_subprogram(void *FuncDesc) {
  708. TheChild->startSubprogram(FuncDesc);
  709. return 0;
  710. }
  711. /// llvm_dbg_region_end - This function is invoked every time a source-language
  712. /// region (started with llvm.dbg.region.start or llvm.dbg.func.start) is
  713. /// terminated.
  714. ///
  715. extern "C"
  716. void llvm_dbg_region_end(void *Dummy) {
  717. TheChild->endRegion();
  718. }
  719. namespace {
  720. /// DebuggerIntrinsicLowering - This class implements a simple intrinsic
  721. /// lowering class that revectors debugging intrinsics to call actual
  722. /// functions (defined above), instead of being turned into noops.
  723. struct DebuggerIntrinsicLowering : public DefaultIntrinsicLowering {
  724. virtual void LowerIntrinsicCall(CallInst *CI) {
  725. Module *M = CI->getParent()->getParent()->getParent();
  726. switch (CI->getCalledFunction()->getIntrinsicID()) {
  727. case Intrinsic::dbg_stoppoint:
  728. // Turn call into a call to llvm_debugger_stop
  729. CI->setOperand(0, M->getOrInsertFunction("llvm_debugger_stop",
  730. CI->getCalledFunction()->getFunctionType()));
  731. break;
  732. case Intrinsic::dbg_region_start:
  733. // Turn call into a call to llvm_dbg_region_start
  734. CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_start",
  735. CI->getCalledFunction()->getFunctionType()));
  736. break;
  737. case Intrinsic::dbg_region_end:
  738. // Turn call into a call to llvm_dbg_region_end
  739. CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_end",
  740. CI->getCalledFunction()->getFunctionType()));
  741. break;
  742. case Intrinsic::dbg_func_start:
  743. // Turn call into a call to llvm_dbg_subprogram
  744. CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_subprogram",
  745. CI->getCalledFunction()->getFunctionType()));
  746. break;
  747. default:
  748. DefaultIntrinsicLowering::LowerIntrinsicCall(CI);
  749. break;
  750. }
  751. }
  752. };
  753. } // end anonymous namespace
  754. static void runChild(Module *M, const std::vector<std::string> &Arguments,
  755. const char * const *envp,
  756. FDHandle ReadFD, FDHandle WriteFD) {
  757. // Create an execution engine that uses our custom intrinsic lowering object
  758. // to revector debugging intrinsic functions into actual functions defined
  759. // above.
  760. ExecutionEngine *EE =
  761. ExecutionEngine::create(new ExistingModuleProvider(M), false,
  762. new DebuggerIntrinsicLowering());
  763. assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
  764. // Call the main function from M as if its signature were:
  765. // int main (int argc, char **argv, const char **envp)
  766. // using the contents of Args to determine argc & argv, and the contents of
  767. // EnvVars to determine envp.
  768. //
  769. Function *Fn = M->getMainFunction();
  770. if (!Fn) exit(1);
  771. // Create the child class instance which will be used by the debugger
  772. // callbacks to keep track of the current state of the process.
  773. assert(TheChild == 0 && "A child process has already been created??");
  774. TheChild = new Child(M, EE, ReadFD, WriteFD);
  775. // Run main...
  776. int Result = EE->runFunctionAsMain(Fn, Arguments, envp);
  777. // If the program didn't explicitly call exit, call exit now, for the program.
  778. // This ensures that any atexit handlers get called correctly.
  779. Function *Exit = M->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy,
  780. (Type *)0);
  781. std::vector<GenericValue> Args;
  782. GenericValue ResultGV;
  783. ResultGV.IntVal = Result;
  784. Args.push_back(ResultGV);
  785. EE->runFunction(Exit, Args);
  786. abort();
  787. }