LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

UnixLocalInferiorProcess.cpp

Go to the documentation of this file.
00001 //===-- UnixLocalInferiorProcess.cpp - A Local process on a Unixy system --===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 // 
00010 // This file provides one implementation of the InferiorProcess class, which is
00011 // designed to be used on unixy systems (those that support pipe, fork, exec,
00012 // and signals).
00013 //
00014 // When the process is started, the debugger creates a pair of pipes, forks, and
00015 // makes the child start executing the program.  The child executes the process
00016 // with an IntrinsicLowering instance that turns debugger intrinsics into actual
00017 // callbacks.
00018 //
00019 // This target takes advantage of the fact that the Module* addresses in the
00020 // parent and the Module* addresses in the child will be the same, due to the
00021 // use of fork().  As such, global addresses looked up in the child can be sent
00022 // over the pipe to the debugger.
00023 //
00024 //===----------------------------------------------------------------------===//
00025 
00026 #include "llvm/Debugger/InferiorProcess.h"
00027 #include "llvm/Constant.h"
00028 #include "llvm/Instructions.h"
00029 #include "llvm/Module.h"
00030 #include "llvm/ModuleProvider.h"
00031 #include "llvm/Type.h"
00032 #include "llvm/CodeGen/IntrinsicLowering.h"
00033 #include "llvm/ExecutionEngine/GenericValue.h"
00034 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00035 #include "llvm/Support/FileUtilities.h"
00036 #include "llvm/ADT/StringExtras.h"
00037 #include <cerrno>
00038 #include <csignal>
00039 #include <unistd.h>        // Unix-specific debugger support
00040 #include <sys/types.h>
00041 #include <sys/wait.h>
00042 using namespace llvm;
00043 
00044 // runChild - Entry point for the child process.
00045 static void runChild(Module *M, const std::vector<std::string> &Arguments,
00046                      const char * const *envp,
00047                      FDHandle ReadFD, FDHandle WriteFD);
00048 
00049 //===----------------------------------------------------------------------===//
00050 //                        Parent/Child Pipe Protocol
00051 //===----------------------------------------------------------------------===//
00052 //
00053 // The parent/child communication protocol is designed to have the child process
00054 // responding to requests that the debugger makes.  Whenever the child process
00055 // has stopped (due to a break point, single stepping, etc), the child process
00056 // enters a message processing loop, where it reads and responds to commands
00057 // until the parent decides that it wants to continue execution in some way.
00058 //
00059 // Whenever the child process stops, it notifies the debugger by sending a
00060 // character over the wire.
00061 //
00062 
00063 namespace {
00064   /// LocationToken - Objects of this type are sent across the pipe from the
00065   /// child to the parent to indicate where various stack frames are located.
00066   struct LocationToken {
00067     unsigned Line, Col;
00068     const GlobalVariable *File;
00069     LocationToken(unsigned L = 0, unsigned C = 0, const GlobalVariable *F = 0)
00070       : Line(L), Col(C), File(F) {}
00071   };
00072 }
00073 
00074 // Once the debugger process has received the LocationToken, it can make
00075 // requests of the child by sending one of the following enum values followed by
00076 // any data required by that command.  The child responds with data appropriate
00077 // to the command.
00078 //
00079 namespace {
00080   /// CommandID - This enum defines all of the commands that the child process
00081   /// can respond to.  The actual expected data and responses are defined as the
00082   /// enum values are defined.
00083   ///
00084   enum CommandID {
00085     //===------------------------------------------------------------------===//
00086     // Execution commands - These are sent to the child to from the debugger to
00087     // get it to do certain things.
00088     //
00089 
00090     // StepProgram: void->char - This command causes the program to continue
00091     // execution, but stop as soon as it reaches another stoppoint.
00092     StepProgram,
00093 
00094     // FinishProgram: FrameDesc*->char - This command causes the program to
00095     // continue execution until the specified function frame returns.
00096     FinishProgram, 
00097 
00098     // ContProgram: void->char - This command causes the program to continue
00099     // execution, stopping at some point in the future.
00100     ContProgram,
00101 
00102     // GetSubprogramDescriptor: FrameDesc*->GlobalValue* - This command returns
00103     // the GlobalValue* descriptor object for the specified stack frame.
00104     GetSubprogramDescriptor,
00105 
00106     // GetParentFrame: FrameDesc*->FrameDesc* - This command returns the frame
00107     // descriptor for the parent stack frame to the specified one, or null if
00108     // there is none.
00109     GetParentFrame,
00110 
00111     // GetFrameLocation - FrameDesc*->LocationToken - This command returns the
00112     // location that a particular stack frame is stopped at.
00113     GetFrameLocation,
00114 
00115     // AddBreakpoint - LocationToken->unsigned - This command instructs the
00116     // target to install a breakpoint at the specified location.
00117     AddBreakpoint,
00118 
00119     // RemoveBreakpoint - unsigned->void - This command instructs the target to
00120     // remove a breakpoint.
00121     RemoveBreakpoint,
00122   };
00123 }
00124 
00125 
00126 
00127 
00128 //===----------------------------------------------------------------------===//
00129 //                            Parent Process Code
00130 //===----------------------------------------------------------------------===//
00131 
00132 namespace {
00133   class IP : public InferiorProcess {
00134     // ReadFD, WriteFD - The file descriptors to read/write to the inferior
00135     // process.
00136     FDHandle ReadFD, WriteFD;
00137 
00138     // ChildPID - The unix PID of the child process we forked.
00139     mutable pid_t ChildPID;
00140   public:
00141     IP(Module *M, const std::vector<std::string> &Arguments,
00142        const char * const *envp);
00143     ~IP();
00144 
00145     std::string getStatus() const;
00146 
00147     /// Execution method implementations...
00148     virtual void stepProgram();
00149     virtual void finishProgram(void *Frame);
00150     virtual void contProgram();
00151 
00152 
00153     // Stack frame method implementations...
00154     virtual void *getPreviousFrame(void *Frame) const;
00155     virtual const GlobalVariable *getSubprogramDesc(void *Frame) const;
00156     virtual void getFrameLocation(void *Frame, unsigned &LineNo,
00157                                   unsigned &ColNo,
00158                                   const GlobalVariable *&SourceDesc) const;
00159 
00160     // Breakpoint implementation methods
00161     virtual unsigned addBreakpoint(unsigned LineNo, unsigned ColNo,
00162                                    const GlobalVariable *SourceDesc);
00163     virtual void removeBreakpoint(unsigned ID);
00164 
00165 
00166   private:
00167     /// startChild - This starts up the child process, and initializes the
00168     /// ChildPID member.
00169     ///
00170     void startChild(Module *M, const std::vector<std::string> &Arguments,
00171                     const char * const *envp);
00172 
00173     /// killChild - Kill or reap the child process.  This throws the
00174     /// InferiorProcessDead exception an exit code if the process had already
00175     /// died, otherwise it just kills it and returns.
00176     void killChild() const;
00177 
00178   private:
00179     // Methods for communicating with the child process.  If the child exits or
00180     // dies while attempting to communicate with it, ChildPID is set to zero and
00181     // an exception is thrown.
00182 
00183     /// readFromChild - Low-level primitive to read some data from the child,
00184     /// throwing an exception if it dies.
00185     void readFromChild(void *Buffer, unsigned Size) const;
00186 
00187     /// writeToChild - Low-level primitive to send some data to the child
00188     /// process, throwing an exception if the child died.
00189     void writeToChild(void *Buffer, unsigned Size) const;
00190 
00191     /// sendCommand - Send a command token and the request data to the child.
00192     ///
00193     void sendCommand(CommandID Command, void *Data, unsigned Size) const;
00194 
00195     /// waitForStop - This method waits for the child process to reach a stop
00196     /// point.
00197     void waitForStop();
00198   };
00199 }
00200 
00201 // create - This is the factory method for the InferiorProcess class.  Since
00202 // there is currently only one subclass of InferiorProcess, we just define it
00203 // here.
00204 InferiorProcess *
00205 InferiorProcess::create(Module *M, const std::vector<std::string> &Arguments,
00206                         const char * const *envp) {
00207   return new IP(M, Arguments, envp);
00208 }
00209 
00210 /// IP constructor - Create some pipes, them fork a child process.  The child
00211 /// process should start execution of the debugged program, but stop at the
00212 /// first available opportunity.
00213 IP::IP(Module *M, const std::vector<std::string> &Arguments,
00214        const char * const *envp)
00215   : InferiorProcess(M) {
00216 
00217   // Start the child running...
00218   startChild(M, Arguments, envp);
00219   
00220   // Okay, we created the program and it is off and running.  Wait for it to
00221   // stop now.
00222   try {
00223     waitForStop();
00224   } catch (InferiorProcessDead &IPD) {
00225     throw "Error waiting for the child process to stop.  "
00226           "It exited with status " + itostr(IPD.getExitCode());
00227   }
00228 }
00229 
00230 IP::~IP() {
00231   // If the child is still running, kill it.
00232   if (!ChildPID) return;
00233 
00234   killChild();
00235 }
00236 
00237 /// getStatus - Return information about the unix process being debugged.
00238 ///
00239 std::string IP::getStatus() const {
00240   if (ChildPID == 0)
00241     return "Unix target.  ERROR: child process appears to be dead!\n";
00242 
00243   return "Unix target: PID #" + utostr((unsigned)ChildPID) + "\n";
00244 }
00245 
00246 
00247 /// startChild - This starts up the child process, and initializes the
00248 /// ChildPID member.
00249 ///
00250 void IP::startChild(Module *M, const std::vector<std::string> &Arguments,
00251                     const char * const *envp) {
00252   // Create the pipes.  Make sure to immediately assign the returned file
00253   // descriptors to FDHandle's so they get destroyed if an exception is thrown.
00254   int FDs[2];
00255   if (pipe(FDs)) throw "Error creating a pipe!";
00256   FDHandle ChildReadFD(FDs[0]);
00257   WriteFD = FDs[1];
00258 
00259   if (pipe(FDs)) throw "Error creating a pipe!";
00260   ReadFD = FDs[0];
00261   FDHandle ChildWriteFD(FDs[1]);
00262 
00263   // Fork off the child process.
00264   switch (ChildPID = fork()) {
00265   case -1: throw "Error forking child process!";
00266   case 0:  // child
00267     delete this;       // Free parent pipe file descriptors
00268     runChild(M, Arguments, envp, ChildReadFD, ChildWriteFD);
00269     exit(1);
00270   default: break;
00271   }
00272 }
00273 
00274 /// sendCommand - Send a command token and the request data to the child.
00275 ///
00276 void IP::sendCommand(CommandID Command, void *Data, unsigned Size) const {
00277   writeToChild(&Command, sizeof(Command));
00278   writeToChild(Data, Size);
00279 }
00280 
00281 /// stepProgram - Implement the 'step' command, continuing execution until
00282 /// the next possible stop point.
00283 void IP::stepProgram() {
00284   sendCommand(StepProgram, 0, 0);
00285   waitForStop();
00286 }
00287 
00288 /// finishProgram - Implement the 'finish' command, executing the program until
00289 /// the current function returns to its caller.
00290 void IP::finishProgram(void *Frame) {
00291   sendCommand(FinishProgram, &Frame, sizeof(Frame));
00292   waitForStop();
00293 }
00294 
00295 /// contProgram - Implement the 'cont' command, continuing execution until
00296 /// a breakpoint is encountered.
00297 void IP::contProgram() {
00298   sendCommand(ContProgram, 0, 0);
00299   waitForStop();
00300 }
00301 
00302 
00303 //===----------------------------------------------------------------------===//
00304 // Stack manipulation methods
00305 //
00306 
00307 /// getPreviousFrame - Given the descriptor for the current stack frame,
00308 /// return the descriptor for the caller frame.  This returns null when it
00309 /// runs out of frames.
00310 void *IP::getPreviousFrame(void *Frame) const {
00311   sendCommand(GetParentFrame, &Frame, sizeof(Frame));
00312   readFromChild(&Frame, sizeof(Frame));
00313   return Frame;
00314 }
00315 
00316 /// getSubprogramDesc - Return the subprogram descriptor for the current
00317 /// stack frame.
00318 const GlobalVariable *IP::getSubprogramDesc(void *Frame) const {
00319   sendCommand(GetSubprogramDescriptor, &Frame, sizeof(Frame));
00320   const GlobalVariable *Desc;
00321   readFromChild(&Desc, sizeof(Desc));
00322   return Desc;
00323 }
00324 
00325 /// getFrameLocation - This method returns the source location where each stack
00326 /// frame is stopped.
00327 void IP::getFrameLocation(void *Frame, unsigned &LineNo, unsigned &ColNo, 
00328                           const GlobalVariable *&SourceDesc) const {
00329   sendCommand(GetFrameLocation, &Frame, sizeof(Frame));
00330   LocationToken Loc;
00331   readFromChild(&Loc, sizeof(Loc));
00332   LineNo     = Loc.Line;
00333   ColNo      = Loc.Col;
00334   SourceDesc = Loc.File;
00335 }
00336 
00337 
00338 //===----------------------------------------------------------------------===//
00339 // Breakpoint manipulation methods
00340 //
00341 unsigned IP::addBreakpoint(unsigned LineNo, unsigned ColNo,
00342                            const GlobalVariable *SourceDesc) {
00343   LocationToken Loc;
00344   Loc.Line = LineNo;
00345   Loc.Col = ColNo;
00346   Loc.File = SourceDesc;
00347   sendCommand(AddBreakpoint, &Loc, sizeof(Loc));
00348   unsigned ID;
00349   readFromChild(&ID, sizeof(ID));
00350   return ID;
00351 }
00352 
00353 void IP::removeBreakpoint(unsigned ID) {
00354   sendCommand(RemoveBreakpoint, &ID, sizeof(ID));
00355 }
00356 
00357 
00358 //===----------------------------------------------------------------------===//
00359 //             Methods for communication with the child process
00360 //
00361 // Methods for communicating with the child process.  If the child exits or dies
00362 // while attempting to communicate with it, ChildPID is set to zero and an
00363 // exception is thrown.
00364 //
00365 
00366 /// readFromChild - Low-level primitive to read some data from the child,
00367 /// throwing an exception if it dies.
00368 void IP::readFromChild(void *Buffer, unsigned Size) const {
00369   assert(ChildPID &&
00370          "Child process died and still attempting to communicate with it!");
00371   while (Size) {
00372     ssize_t Amount = read(ReadFD, Buffer, Size);
00373     if (Amount == 0) {
00374       // If we cannot communicate with the process, kill it.
00375       killChild();
00376       // If killChild succeeded, then the process must have closed the pipe FD
00377       // or something, because the child existed, but we cannot communicate with
00378       // it.
00379       throw InferiorProcessDead(-1);
00380     } else if (Amount == -1) {
00381       if (errno != EINTR) {
00382         ChildPID = 0;
00383         killChild();
00384         throw "Error reading from child process!";
00385       }
00386     } else {
00387       // We read a chunk.
00388       Buffer = (char*)Buffer + Amount;
00389       Size -= Amount;
00390     }
00391   }
00392 }
00393 
00394 /// writeToChild - Low-level primitive to send some data to the child
00395 /// process, throwing an exception if the child died.
00396 void IP::writeToChild(void *Buffer, unsigned Size) const {
00397   while (Size) {
00398     ssize_t Amount = write(WriteFD, Buffer, Size);
00399     if (Amount < 0 && errno == EINTR) continue;
00400     if (Amount <= 0) {
00401       // If we cannot communicate with the process, kill it.
00402       killChild();
00403 
00404       // If killChild succeeded, then the process must have closed the pipe FD
00405       // or something, because the child existed, but we cannot communicate with
00406       // it.
00407       throw InferiorProcessDead(-1);
00408     } else {
00409       // We wrote a chunk.
00410       Buffer = (char*)Buffer + Amount;
00411       Size -= Amount;
00412     }
00413   }
00414 }
00415 
00416 /// killChild - Kill or reap the child process.  This throws the
00417 /// InferiorProcessDead exception an exit code if the process had already
00418 /// died, otherwise it just returns the exit code if it had to be killed.
00419 void IP::killChild() const {
00420   assert(ChildPID != 0 && "Child has already been reaped!");
00421   
00422   // If the process terminated on its own accord, closing the pipe file
00423   // descriptors, we will get here.  Check to see if the process has already
00424   // died in this manner, gracefully.
00425   int Status = 0;
00426   int PID;
00427   do {
00428     PID = waitpid(ChildPID, &Status, WNOHANG);
00429   } while (PID < 0 && errno == EINTR);
00430   if (PID < 0) throw "Error waiting for child to exit!";
00431 
00432   // Ok, there is a slight race condition here.  It's possible that we will find
00433   // out that the file descriptor closed before waitpid will indicate that the
00434   // process gracefully died.  If we don't know that the process gracefully
00435   // died, wait a bit and try again.  This is pretty nasty.
00436   if (PID == 0) {
00437     usleep(10000);   // Wait a bit.
00438 
00439     // Try again.
00440     Status = 0;
00441     do {
00442       PID = waitpid(ChildPID, &Status, WNOHANG);
00443     } while (PID < 0 && errno == EINTR);
00444     if (PID < 0) throw "Error waiting for child to exit!";
00445   }
00446 
00447   // If the child process was already dead, then indicate that the process
00448   // terminated on its own.
00449   if (PID) {
00450     assert(PID == ChildPID && "Didn't reap child?");
00451     ChildPID = 0;            // Child has been reaped
00452     if (WIFEXITED(Status))
00453       throw InferiorProcessDead(WEXITSTATUS(Status));
00454     else if (WIFSIGNALED(Status))
00455       throw InferiorProcessDead(WTERMSIG(Status));
00456     throw InferiorProcessDead(-1);
00457   }
00458   
00459   // Otherwise, the child exists and has not yet been killed.
00460   if (kill(ChildPID, SIGKILL) < 0)
00461     throw "Error killing child process!";
00462 
00463   do {
00464     PID = waitpid(ChildPID, 0, 0);
00465   } while (PID < 0 && errno == EINTR);
00466   if (PID <= 0) throw "Error waiting for child to exit!";
00467 
00468   assert(PID == ChildPID && "Didn't reap child?");
00469 }
00470 
00471 
00472 /// waitForStop - This method waits for the child process to reach a stop
00473 /// point.  When it does, it fills in the CurLocation member and returns.
00474 void IP::waitForStop() {
00475   char Dummy;
00476   readFromChild(&Dummy, sizeof(char));
00477 }
00478 
00479 
00480 //===----------------------------------------------------------------------===//
00481 //                             Child Process Code
00482 //===----------------------------------------------------------------------===//
00483 
00484 namespace {
00485   class SourceSubprogram;
00486 
00487   /// SourceRegion - Instances of this class represent the regions that are
00488   /// active in the program.
00489   class SourceRegion {
00490     /// Parent - A pointer to the region that encloses the current one.
00491     SourceRegion *Parent;
00492 
00493     /// CurSubprogram - The subprogram that contains this region.  This allows
00494     /// efficient stack traversals.
00495     SourceSubprogram *CurSubprogram;
00496 
00497     /// CurLine, CurCol, CurFile - The last location visited by this region.
00498     /// This is used for getting the source location of callers in stack frames.
00499     unsigned CurLine, CurCol;
00500     void *CurFileDesc;
00501 
00502     //std::vector<void*> ActiveObjects;
00503   public:
00504     SourceRegion(SourceRegion *p, SourceSubprogram *Subprogram = 0)
00505      : Parent(p), CurSubprogram(Subprogram ? Subprogram : p->getSubprogram()) {
00506       CurLine = 0; CurCol = 0;
00507       CurFileDesc = 0;
00508     }
00509 
00510     virtual ~SourceRegion() {}
00511 
00512     SourceRegion *getParent() const { return Parent; }
00513     SourceSubprogram *getSubprogram() const { return CurSubprogram; }
00514 
00515     void updateLocation(unsigned Line, unsigned Col, void *File) {
00516       CurLine = Line;
00517       CurCol = Col;
00518       CurFileDesc = File;
00519     }
00520 
00521     /// Return a LocationToken for the place that this stack frame stopped or
00522     /// called a sub-function.
00523     LocationToken getLocation(ExecutionEngine *EE) {
00524       LocationToken LT;
00525       LT.Line = CurLine;
00526       LT.Col = CurCol;
00527       const GlobalValue *GV = EE->getGlobalValueAtAddress(CurFileDesc);
00528       LT.File = dyn_cast_or_null<GlobalVariable>(GV);
00529       return LT;
00530     }
00531   };
00532 
00533   /// SourceSubprogram - This is a stack-frame that represents a source program.
00534   ///
00535   class SourceSubprogram : public SourceRegion {
00536     /// Desc - A pointer to the descriptor for the subprogram that this frame
00537     /// represents.
00538     void *Desc;
00539   public:
00540     SourceSubprogram(SourceRegion *P, void *desc)
00541       : SourceRegion(P, this), Desc(desc) {}
00542     void *getDescriptor() const { return Desc; }
00543   };
00544 
00545 
00546   /// Child class - This class contains all of the information and methods used
00547   /// by the child side of the debugger.  The single instance of this object is
00548   /// pointed to by the "TheChild" global variable.
00549   class Child {
00550     /// M - The module for the program currently being debugged.
00551     ///
00552     Module *M;
00553 
00554     /// EE - The execution engine that we are using to run the program.
00555     ///
00556     ExecutionEngine *EE;
00557 
00558     /// ReadFD, WriteFD - The file descriptor handles for this side of the
00559     /// debugger pipe.
00560     FDHandle ReadFD, WriteFD;
00561 
00562     /// RegionStack - A linked list of all of the regions dynamically active.
00563     ///
00564     SourceRegion *RegionStack;
00565 
00566     /// StopAtNextOpportunity - If this flag is set, the child process will stop
00567     /// and report to the debugger at the next possible chance it gets.
00568     volatile bool StopAtNextOpportunity;
00569 
00570     /// StopWhenSubprogramReturns - If this is non-null, the debugger requests
00571     /// that the program stops when the specified function frame is destroyed.
00572     SourceSubprogram *StopWhenSubprogramReturns;
00573 
00574     /// Breakpoints - This contains a list of active breakpoints and their IDs.
00575     ///
00576     std::vector<std::pair<unsigned, LocationToken> > Breakpoints;
00577 
00578     /// CurBreakpoint - The last assigned breakpoint.
00579     ///
00580     unsigned CurBreakpoint;
00581 
00582   public:
00583     Child(Module *m, ExecutionEngine *ee, FDHandle &Read, FDHandle &Write)
00584       : M(m), EE(ee), ReadFD(Read), WriteFD(Write),
00585         RegionStack(0), CurBreakpoint(0) {
00586       StopAtNextOpportunity = true;
00587       StopWhenSubprogramReturns = 0;
00588     }
00589 
00590     /// writeToParent - Send the specified buffer of data to the debugger
00591     /// process.
00592     ///
00593     void writeToParent(const void *Buffer, unsigned Size);
00594 
00595     /// readFromParent - Read the specified number of bytes from the parent.
00596     ///
00597     void readFromParent(void *Buffer, unsigned Size);
00598 
00599     /// childStopped - This method is called whenever the child has stopped
00600     /// execution due to a breakpoint, step command, interruption, or whatever.
00601     /// This stops the process, responds to any requests from the debugger, and
00602     /// when commanded to, can continue execution by returning.
00603     ///
00604     void childStopped();
00605 
00606     /// startSubprogram - This method creates a new region for the subroutine
00607     /// with the specified descriptor.
00608     ///
00609     void startSubprogram(void *FuncDesc);
00610 
00611     /// startRegion - This method initiates the creation of an anonymous region.
00612     ///
00613     void startRegion();
00614 
00615     /// endRegion - This method terminates the last active region.
00616     ///
00617     void endRegion();
00618 
00619     /// reachedLine - This method is automatically called by the program every
00620     /// time it executes an llvm.dbg.stoppoint intrinsic.  If the debugger wants
00621     /// us to stop here, we do so, otherwise we continue execution.
00622     ///
00623     void reachedLine(unsigned Line, unsigned Col, void *SourceDesc);
00624   };
00625 
00626   /// TheChild - The single instance of the Child class, which only gets created
00627   /// in the child process.
00628   Child *TheChild = 0;
00629 } // end anonymous namespace
00630 
00631 
00632 // writeToParent - Send the specified buffer of data to the debugger process.
00633 void Child::writeToParent(const void *Buffer, unsigned Size) {
00634   while (Size) {
00635     ssize_t Amount = write(WriteFD, Buffer, Size);
00636     if (Amount < 0 && errno == EINTR) continue;
00637     if (Amount <= 0) {
00638       write(2, "ERROR: Connection to debugger lost!\n", 36);
00639       abort();
00640     } else {
00641       // We wrote a chunk.
00642       Buffer = (const char*)Buffer + Amount;
00643       Size -= Amount;
00644     }
00645   }
00646 }
00647 
00648 // readFromParent - Read the specified number of bytes from the parent.
00649 void Child::readFromParent(void *Buffer, unsigned Size) {
00650   while (Size) {
00651     ssize_t Amount = read(ReadFD, Buffer, Size);
00652     if (Amount < 0 && errno == EINTR) continue;
00653     if (Amount <= 0) {
00654       write(2, "ERROR: Connection to debugger lost!\n", 36);
00655       abort();
00656     } else {
00657       // We read a chunk.
00658       Buffer = (char*)Buffer + Amount;
00659       Size -= Amount;
00660     }
00661   }
00662 }
00663 
00664 /// childStopped - This method is called whenever the child has stopped
00665 /// execution due to a breakpoint, step command, interruption, or whatever.
00666 /// This stops the process, responds to any requests from the debugger, and when
00667 /// commanded to, can continue execution by returning.
00668 ///
00669 void Child::childStopped() {
00670   // Since we stopped, notify the parent that we did so.
00671   char Token = 0;
00672   writeToParent(&Token, sizeof(char));
00673 
00674   StopAtNextOpportunity = false;
00675   StopWhenSubprogramReturns = 0;
00676 
00677   // Now that the debugger knows that we stopped, read commands from it and
00678   // respond to them appropriately.
00679   CommandID Command;
00680   while (1) {
00681     SourceRegion *Frame;
00682     const void *Result;
00683     readFromParent(&Command, sizeof(CommandID));
00684 
00685     switch (Command) {
00686     case StepProgram:
00687       // To step the program, just return.
00688       StopAtNextOpportunity = true;
00689       return;
00690 
00691     case FinishProgram:         // Run until exit from the specified function...
00692       readFromParent(&Frame, sizeof(Frame));
00693       // The user wants us to stop when the specified FUNCTION exits, not when
00694       // the specified REGION exits.
00695       StopWhenSubprogramReturns = Frame->getSubprogram();
00696       return;
00697 
00698     case ContProgram:
00699       // To continue, just return back to execution.
00700       return;
00701 
00702     case GetSubprogramDescriptor:
00703       readFromParent(&Frame, sizeof(Frame));
00704       Result =
00705         EE->getGlobalValueAtAddress(Frame->getSubprogram()->getDescriptor());
00706       writeToParent(&Result, sizeof(Result));
00707       break;
00708 
00709     case GetParentFrame:
00710       readFromParent(&Frame, sizeof(Frame));
00711       Result = Frame ? Frame->getSubprogram()->getParent() : RegionStack;
00712       writeToParent(&Result, sizeof(Result));
00713       break;
00714 
00715     case GetFrameLocation: {
00716       readFromParent(&Frame, sizeof(Frame));
00717       LocationToken LT = Frame->getLocation(EE);
00718       writeToParent(&LT, sizeof(LT));
00719       break;
00720     }
00721     case AddBreakpoint: {
00722       LocationToken Loc;
00723       readFromParent(&Loc, sizeof(Loc));
00724       // Convert the GlobalVariable pointer to the address it was emitted to.
00725       Loc.File = (GlobalVariable*)EE->getPointerToGlobal(Loc.File);
00726       unsigned ID = CurBreakpoint++;
00727       Breakpoints.push_back(std::make_pair(ID, Loc));
00728       writeToParent(&ID, sizeof(ID));
00729       break;
00730     }
00731     case RemoveBreakpoint: {
00732       unsigned ID = 0;
00733       readFromParent(&ID, sizeof(ID));
00734       for (unsigned i = 0, e = Breakpoints.size(); i != e; ++i)
00735         if (Breakpoints[i].first == ID) {
00736           Breakpoints.erase(Breakpoints.begin()+i);
00737           break;
00738         }
00739       break;
00740     }
00741     default:
00742       assert(0 && "Unknown command!");
00743     }
00744   }
00745 }
00746 
00747 
00748 
00749 /// startSubprogram - This method creates a new region for the subroutine
00750 /// with the specified descriptor.
00751 void Child::startSubprogram(void *SPDesc) {
00752   RegionStack = new SourceSubprogram(RegionStack, SPDesc);
00753 }
00754 
00755 /// startRegion - This method initiates the creation of an anonymous region.
00756 ///
00757 void Child::startRegion() {
00758   RegionStack = new SourceRegion(RegionStack);
00759 }
00760 
00761 /// endRegion - This method terminates the last active region.
00762 ///
00763 void Child::endRegion() {
00764   SourceRegion *R = RegionStack->getParent();
00765 
00766   // If the debugger wants us to stop when this frame is destroyed, do so.
00767   if (RegionStack == StopWhenSubprogramReturns) {
00768     StopAtNextOpportunity = true;
00769     StopWhenSubprogramReturns = 0;
00770   }
00771 
00772   delete RegionStack;
00773   RegionStack = R;
00774 }
00775 
00776 
00777 
00778 
00779 /// reachedLine - This method is automatically called by the program every time
00780 /// it executes an llvm.dbg.stoppoint intrinsic.  If the debugger wants us to
00781 /// stop here, we do so, otherwise we continue execution.  Note that the Data
00782 /// pointer coming in is a pointer to the LLVM global variable that represents
00783 /// the source file we are in.  We do not use the contents of the global
00784 /// directly in the child, but we do use its address.
00785 ///
00786 void Child::reachedLine(unsigned Line, unsigned Col, void *SourceDesc) {
00787   if (RegionStack)
00788     RegionStack->updateLocation(Line, Col, SourceDesc);
00789 
00790   // If we hit a breakpoint, stop the program.
00791   for (unsigned i = 0, e = Breakpoints.size(); i != e; ++i)
00792     if (Line       == Breakpoints[i].second.Line &&
00793         SourceDesc == (void*)Breakpoints[i].second.File &&
00794         Col        == Breakpoints[i].second.Col) {
00795       childStopped();
00796       return;
00797     }
00798 
00799   // If we are single stepping the program, make sure to stop it.
00800   if (StopAtNextOpportunity)
00801     childStopped();
00802 }
00803 
00804 
00805 
00806 
00807 //===----------------------------------------------------------------------===//
00808 //                        Child class wrapper functions
00809 //
00810 // These functions are invoked directly by the program as it executes, in place
00811 // of the debugging intrinsic functions that it contains.
00812 //
00813 
00814 
00815 /// llvm_debugger_stop - Every time the program reaches a new source line, it
00816 /// will call back to this function.  If the debugger has a breakpoint or
00817 /// otherwise wants us to stop on this line, we do so, and notify the debugger
00818 /// over the pipe.
00819 ///
00820 extern "C"
00821 void *llvm_debugger_stop(void *Dummy, unsigned Line, unsigned Col,
00822                          void *SourceDescriptor) {
00823   TheChild->reachedLine(Line, Col, SourceDescriptor);
00824   return Dummy;
00825 }
00826 
00827 
00828 /// llvm_dbg_region_start - This function is invoked every time an anonymous
00829 /// region of the source program is entered.
00830 ///
00831 extern "C"
00832 void *llvm_dbg_region_start(void *Dummy) {
00833   TheChild->startRegion();
00834   return Dummy;
00835 }
00836 
00837 /// llvm_dbg_subprogram - This function is invoked every time a source-language
00838 /// subprogram has been entered.
00839 ///
00840 extern "C"
00841 void *llvm_dbg_subprogram(void *FuncDesc) {
00842   TheChild->startSubprogram(FuncDesc);
00843   return 0;
00844 }
00845 
00846 /// llvm_dbg_region_end - This function is invoked every time a source-language
00847 /// region (started with llvm.dbg.region.start or llvm.dbg.func.start) is
00848 /// terminated.
00849 ///
00850 extern "C"
00851 void llvm_dbg_region_end(void *Dummy) {
00852   TheChild->endRegion();
00853 }
00854 
00855 
00856 
00857 
00858 namespace {
00859   /// DebuggerIntrinsicLowering - This class implements a simple intrinsic
00860   /// lowering class that revectors debugging intrinsics to call actual
00861   /// functions (defined above), instead of being turned into noops.
00862   struct DebuggerIntrinsicLowering : public DefaultIntrinsicLowering {
00863     virtual void LowerIntrinsicCall(CallInst *CI) {
00864       Module *M = CI->getParent()->getParent()->getParent();
00865       switch (CI->getCalledFunction()->getIntrinsicID()) {
00866       case Intrinsic::dbg_stoppoint:
00867         // Turn call into a call to llvm_debugger_stop
00868         CI->setOperand(0, M->getOrInsertFunction("llvm_debugger_stop",
00869                                   CI->getCalledFunction()->getFunctionType()));
00870         break;
00871       case Intrinsic::dbg_region_start:
00872         // Turn call into a call to llvm_dbg_region_start
00873         CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_start",
00874                                   CI->getCalledFunction()->getFunctionType()));
00875         break;
00876 
00877       case Intrinsic::dbg_region_end:
00878         // Turn call into a call to llvm_dbg_region_end
00879         CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_end",
00880                                   CI->getCalledFunction()->getFunctionType()));
00881         break;
00882       case Intrinsic::dbg_func_start:
00883         // Turn call into a call to llvm_dbg_subprogram
00884         CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_subprogram",
00885                                   CI->getCalledFunction()->getFunctionType()));
00886         break;
00887       default:
00888         DefaultIntrinsicLowering::LowerIntrinsicCall(CI);
00889         break;
00890       }
00891     }
00892   };
00893 } // end anonymous namespace
00894 
00895 
00896 static void runChild(Module *M, const std::vector<std::string> &Arguments,
00897                      const char * const *envp,
00898                      FDHandle ReadFD, FDHandle WriteFD) {
00899 
00900   // Create an execution engine that uses our custom intrinsic lowering object
00901   // to revector debugging intrinsic functions into actual functions defined
00902   // above.
00903   ExecutionEngine *EE =
00904     ExecutionEngine::create(new ExistingModuleProvider(M), false,
00905                             new DebuggerIntrinsicLowering());
00906   assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
00907   
00908   // Call the main function from M as if its signature were:
00909   //   int main (int argc, char **argv, const char **envp)
00910   // using the contents of Args to determine argc & argv, and the contents of
00911   // EnvVars to determine envp.
00912   //
00913   Function *Fn = M->getMainFunction();
00914   if (!Fn) exit(1);
00915 
00916   // Create the child class instance which will be used by the debugger
00917   // callbacks to keep track of the current state of the process.
00918   assert(TheChild == 0 && "A child process has already been created??");
00919   TheChild = new Child(M, EE, ReadFD, WriteFD);
00920 
00921   // Run main...
00922   int Result = EE->runFunctionAsMain(Fn, Arguments, envp);
00923 
00924   // If the program didn't explicitly call exit, call exit now, for the program.
00925   // This ensures that any atexit handlers get called correctly.
00926   Function *Exit = M->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, 0);
00927 
00928   std::vector<GenericValue> Args;
00929   GenericValue ResultGV;
00930   ResultGV.IntVal = Result;
00931   Args.push_back(ResultGV);
00932   EE->runFunction(Exit, Args);
00933   abort();
00934 }