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