1 //===-- UnixLocalInferiorProcess.cpp - A Local process on a Unixy system --===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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,
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
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.
24 //===----------------------------------------------------------------------===//
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"
40 #include <unistd.h> // Unix-specific debugger support
41 #include <sys/types.h>
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);
50 //===----------------------------------------------------------------------===//
51 // Parent/Child Pipe Protocol
52 //===----------------------------------------------------------------------===//
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.
60 // Whenever the child process stops, it notifies the debugger by sending a
61 // character over the wire.
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 {
69 const GlobalVariable *File;
70 LocationToken(unsigned L = 0, unsigned C = 0, const GlobalVariable *F = 0)
71 : Line(L), Col(C), File(F) {}
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
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.
86 //===------------------------------------------------------------------===//
87 // Execution commands - These are sent to the child to from the debugger to
88 // get it to do certain things.
91 // StepProgram: void->char - This command causes the program to continue
92 // execution, but stop as soon as it reaches another stoppoint.
95 // FinishProgram: FrameDesc*->char - This command causes the program to
96 // continue execution until the specified function frame returns.
99 // ContProgram: void->char - This command causes the program to continue
100 // execution, stopping at some point in the future.
103 // GetSubprogramDescriptor: FrameDesc*->GlobalValue* - This command returns
104 // the GlobalValue* descriptor object for the specified stack frame.
105 GetSubprogramDescriptor,
107 // GetParentFrame: FrameDesc*->FrameDesc* - This command returns the frame
108 // descriptor for the parent stack frame to the specified one, or null if
112 // GetFrameLocation - FrameDesc*->LocationToken - This command returns the
113 // location that a particular stack frame is stopped at.
116 // AddBreakpoint - LocationToken->unsigned - This command instructs the
117 // target to install a breakpoint at the specified location.
120 // RemoveBreakpoint - unsigned->void - This command instructs the target to
121 // remove a breakpoint.
129 //===----------------------------------------------------------------------===//
130 // Parent Process Code
131 //===----------------------------------------------------------------------===//
134 class IP : public InferiorProcess {
135 // ReadFD, WriteFD - The file descriptors to read/write to the inferior
137 FDHandle ReadFD, WriteFD;
139 // ChildPID - The unix PID of the child process we forked.
140 mutable pid_t ChildPID;
142 IP(Module *M, const std::vector<std::string> &Arguments,
143 const char * const *envp);
146 std::string getStatus() const;
148 /// Execution method implementations...
149 virtual void stepProgram();
150 virtual void finishProgram(void *Frame);
151 virtual void contProgram();
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,
159 const GlobalVariable *&SourceDesc) const;
161 // Breakpoint implementation methods
162 virtual unsigned addBreakpoint(unsigned LineNo, unsigned ColNo,
163 const GlobalVariable *SourceDesc);
164 virtual void removeBreakpoint(unsigned ID);
168 /// startChild - This starts up the child process, and initializes the
171 void startChild(Module *M, const std::vector<std::string> &Arguments,
172 const char * const *envp);
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;
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.
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;
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;
192 /// sendCommand - Send a command token and the request data to the child.
194 void sendCommand(CommandID Command, void *Data, unsigned Size) const;
196 /// waitForStop - This method waits for the child process to reach a stop
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
206 InferiorProcess::create(Module *M, const std::vector<std::string> &Arguments,
207 const char * const *envp) {
208 return new IP(M, Arguments, envp);
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) {
218 // Start the child running...
219 startChild(M, Arguments, envp);
221 // Okay, we created the program and it is off and running. Wait for it to
225 } catch (InferiorProcessDead &IPD) {
226 throw "Error waiting for the child process to stop. "
227 "It exited with status " + itostr(IPD.getExitCode());
232 // If the child is still running, kill it.
233 if (!ChildPID) return;
238 /// getStatus - Return information about the unix process being debugged.
240 std::string IP::getStatus() const {
242 return "Unix target. ERROR: child process appears to be dead!\n";
244 return "Unix target: PID #" + utostr((unsigned)ChildPID) + "\n";
248 /// startChild - This starts up the child process, and initializes the
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.
256 if (pipe(FDs)) throw "Error creating a pipe!";
257 FDHandle ChildReadFD(FDs[0]);
260 if (pipe(FDs)) throw "Error creating a pipe!";
262 FDHandle ChildWriteFD(FDs[1]);
264 // Fork off the child process.
265 switch (ChildPID = fork()) {
266 case -1: throw "Error forking child process!";
268 delete this; // Free parent pipe file descriptors
269 runChild(M, Arguments, envp, ChildReadFD, ChildWriteFD);
275 /// sendCommand - Send a command token and the request data to the child.
277 void IP::sendCommand(CommandID Command, void *Data, unsigned Size) const {
278 writeToChild(&Command, sizeof(Command));
279 writeToChild(Data, Size);
282 /// stepProgram - Implement the 'step' command, continuing execution until
283 /// the next possible stop point.
284 void IP::stepProgram() {
285 sendCommand(StepProgram, 0, 0);
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));
296 /// contProgram - Implement the 'cont' command, continuing execution until
297 /// a breakpoint is encountered.
298 void IP::contProgram() {
299 sendCommand(ContProgram, 0, 0);
304 //===----------------------------------------------------------------------===//
305 // Stack manipulation methods
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));
317 /// getSubprogramDesc - Return the subprogram descriptor for the current
319 const GlobalVariable *IP::getSubprogramDesc(void *Frame) const {
320 sendCommand(GetSubprogramDescriptor, &Frame, sizeof(Frame));
321 const GlobalVariable *Desc;
322 readFromChild(&Desc, sizeof(Desc));
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));
332 readFromChild(&Loc, sizeof(Loc));
335 SourceDesc = Loc.File;
339 //===----------------------------------------------------------------------===//
340 // Breakpoint manipulation methods
342 unsigned IP::addBreakpoint(unsigned LineNo, unsigned ColNo,
343 const GlobalVariable *SourceDesc) {
347 Loc.File = SourceDesc;
348 sendCommand(AddBreakpoint, &Loc, sizeof(Loc));
350 readFromChild(&ID, sizeof(ID));
354 void IP::removeBreakpoint(unsigned ID) {
355 sendCommand(RemoveBreakpoint, &ID, sizeof(ID));
359 //===----------------------------------------------------------------------===//
360 // Methods for communication with the child process
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.
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 {
371 "Child process died and still attempting to communicate with it!");
373 ssize_t Amount = read(ReadFD, Buffer, Size);
375 // If we cannot communicate with the process, kill it.
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
380 throw InferiorProcessDead(-1);
381 } else if (Amount == -1) {
382 if (errno != EINTR) {
385 throw "Error reading from child process!";
389 Buffer = (char*)Buffer + Amount;
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 {
399 ssize_t Amount = write(WriteFD, Buffer, Size);
400 if (Amount < 0 && errno == EINTR) continue;
402 // If we cannot communicate with the process, kill it.
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
408 throw InferiorProcessDead(-1);
411 Buffer = (char*)Buffer + Amount;
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!");
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.
429 PID = waitpid(ChildPID, &Status, WNOHANG);
430 } while (PID < 0 && errno == EINTR);
431 if (PID < 0) throw "Error waiting for child to exit!";
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.
438 usleep(10000); // Wait a bit.
443 PID = waitpid(ChildPID, &Status, WNOHANG);
444 } while (PID < 0 && errno == EINTR);
445 if (PID < 0) throw "Error waiting for child to exit!";
448 // If the child process was already dead, then indicate that the process
449 // terminated on its own.
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);
460 // Otherwise, the child exists and has not yet been killed.
461 if (kill(ChildPID, SIGKILL) < 0)
462 throw "Error killing child process!";
465 PID = waitpid(ChildPID, 0, 0);
466 } while (PID < 0 && errno == EINTR);
467 if (PID <= 0) throw "Error waiting for child to exit!";
469 assert(PID == ChildPID && "Didn't reap child?");
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() {
477 readFromChild(&Dummy, sizeof(char));
481 //===----------------------------------------------------------------------===//
482 // Child Process Code
483 //===----------------------------------------------------------------------===//
486 class SourceSubprogram;
488 /// SourceRegion - Instances of this class represent the regions that are
489 /// active in the program.
491 /// Parent - A pointer to the region that encloses the current one.
492 SourceRegion *Parent;
494 /// CurSubprogram - The subprogram that contains this region. This allows
495 /// efficient stack traversals.
496 SourceSubprogram *CurSubprogram;
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;
503 //std::vector<void*> ActiveObjects;
505 SourceRegion(SourceRegion *p, SourceSubprogram *Subprogram = 0)
506 : Parent(p), CurSubprogram(Subprogram ? Subprogram : p->getSubprogram()) {
507 CurLine = 0; CurCol = 0;
511 virtual ~SourceRegion() {}
513 SourceRegion *getParent() const { return Parent; }
514 SourceSubprogram *getSubprogram() const { return CurSubprogram; }
516 void updateLocation(unsigned Line, unsigned Col, void *File) {
522 /// Return a LocationToken for the place that this stack frame stopped or
523 /// called a sub-function.
524 LocationToken getLocation(ExecutionEngine *EE) {
528 const GlobalValue *GV = EE->getGlobalValueAtAddress(CurFileDesc);
529 LT.File = dyn_cast_or_null<GlobalVariable>(GV);
534 /// SourceSubprogram - This is a stack-frame that represents a source program.
536 class SourceSubprogram : public SourceRegion {
537 /// Desc - A pointer to the descriptor for the subprogram that this frame
541 SourceSubprogram(SourceRegion *P, void *desc)
542 : SourceRegion(P, this), Desc(desc) {}
543 void *getDescriptor() const { return Desc; }
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.
551 /// M - The module for the program currently being debugged.
555 /// EE - The execution engine that we are using to run the program.
559 /// ReadFD, WriteFD - The file descriptor handles for this side of the
561 FDHandle ReadFD, WriteFD;
563 /// RegionStack - A linked list of all of the regions dynamically active.
565 SourceRegion *RegionStack;
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;
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;
575 /// Breakpoints - This contains a list of active breakpoints and their IDs.
577 std::vector<std::pair<unsigned, LocationToken> > Breakpoints;
579 /// CurBreakpoint - The last assigned breakpoint.
581 unsigned CurBreakpoint;
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;
591 /// writeToParent - Send the specified buffer of data to the debugger
594 void writeToParent(const void *Buffer, unsigned Size);
596 /// readFromParent - Read the specified number of bytes from the parent.
598 void readFromParent(void *Buffer, unsigned Size);
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.
607 /// startSubprogram - This method creates a new region for the subroutine
608 /// with the specified descriptor.
610 void startSubprogram(void *FuncDesc);
612 /// startRegion - This method initiates the creation of an anonymous region.
616 /// endRegion - This method terminates the last active region.
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.
624 void reachedLine(unsigned Line, unsigned Col, void *SourceDesc);
627 /// TheChild - The single instance of the Child class, which only gets created
628 /// in the child process.
630 } // end anonymous namespace
633 // writeToParent - Send the specified buffer of data to the debugger process.
634 void Child::writeToParent(const void *Buffer, unsigned Size) {
636 ssize_t Amount = write(WriteFD, Buffer, Size);
637 if (Amount < 0 && errno == EINTR) continue;
639 write(2, "ERROR: Connection to debugger lost!\n", 36);
643 Buffer = (const char*)Buffer + Amount;
649 // readFromParent - Read the specified number of bytes from the parent.
650 void Child::readFromParent(void *Buffer, unsigned Size) {
652 ssize_t Amount = read(ReadFD, Buffer, Size);
653 if (Amount < 0 && errno == EINTR) continue;
655 write(2, "ERROR: Connection to debugger lost!\n", 36);
659 Buffer = (char*)Buffer + Amount;
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.
670 void Child::childStopped() {
671 // Since we stopped, notify the parent that we did so.
673 writeToParent(&Token, sizeof(char));
675 StopAtNextOpportunity = false;
676 StopWhenSubprogramReturns = 0;
678 // Now that the debugger knows that we stopped, read commands from it and
679 // respond to them appropriately.
684 readFromParent(&Command, sizeof(CommandID));
688 // To step the program, just return.
689 StopAtNextOpportunity = true;
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();
700 // To continue, just return back to execution.
703 case GetSubprogramDescriptor:
704 readFromParent(&Frame, sizeof(Frame));
706 EE->getGlobalValueAtAddress(Frame->getSubprogram()->getDescriptor());
707 writeToParent(&Result, sizeof(Result));
711 readFromParent(&Frame, sizeof(Frame));
712 Result = Frame ? Frame->getSubprogram()->getParent() : RegionStack;
713 writeToParent(&Result, sizeof(Result));
716 case GetFrameLocation: {
717 readFromParent(&Frame, sizeof(Frame));
718 LocationToken LT = Frame->getLocation(EE);
719 writeToParent(<, sizeof(LT));
722 case AddBreakpoint: {
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));
732 case RemoveBreakpoint: {
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);
743 assert(0 && "Unknown command!");
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);
756 /// startRegion - This method initiates the creation of an anonymous region.
758 void Child::startRegion() {
759 RegionStack = new SourceRegion(RegionStack);
762 /// endRegion - This method terminates the last active region.
764 void Child::endRegion() {
765 SourceRegion *R = RegionStack->getParent();
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;
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.
787 void Child::reachedLine(unsigned Line, unsigned Col, void *SourceDesc) {
789 RegionStack->updateLocation(Line, Col, SourceDesc);
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) {
800 // If we are single stepping the program, make sure to stop it.
801 if (StopAtNextOpportunity)
808 //===----------------------------------------------------------------------===//
809 // Child class wrapper functions
811 // These functions are invoked directly by the program as it executes, in place
812 // of the debugging intrinsic functions that it contains.
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
822 void *llvm_debugger_stop(void *Dummy, unsigned Line, unsigned Col,
823 void *SourceDescriptor) {
824 TheChild->reachedLine(Line, Col, SourceDescriptor);
829 /// llvm_dbg_region_start - This function is invoked every time an anonymous
830 /// region of the source program is entered.
833 void *llvm_dbg_region_start(void *Dummy) {
834 TheChild->startRegion();
838 /// llvm_dbg_subprogram - This function is invoked every time a source-language
839 /// subprogram has been entered.
842 void *llvm_dbg_subprogram(void *FuncDesc) {
843 TheChild->startSubprogram(FuncDesc);
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
852 void llvm_dbg_region_end(void *Dummy) {
853 TheChild->endRegion();
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 DebuggerIntrinsicLowering() { ShouldEmitDebugFunctions = true; }
865 virtual void LowerIntrinsicCall(CallInst *CI) {
866 Module *M = CI->getParent()->getParent()->getParent();
867 switch (CI->getCalledFunction()->getIntrinsicID()) {
868 case Intrinsic::dbg_stoppoint:
869 // Turn call into a call to llvm_debugger_stop
870 CI->setOperand(0, M->getOrInsertFunction("llvm_debugger_stop",
871 CI->getCalledFunction()->getFunctionType()));
873 case Intrinsic::dbg_region_start:
874 // Turn call into a call to llvm_dbg_region_start
875 CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_start",
876 CI->getCalledFunction()->getFunctionType()));
879 case Intrinsic::dbg_region_end:
880 // Turn call into a call to llvm_dbg_region_end
881 CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_region_end",
882 CI->getCalledFunction()->getFunctionType()));
884 case Intrinsic::dbg_func_start:
885 // Turn call into a call to llvm_dbg_subprogram
886 CI->setOperand(0, M->getOrInsertFunction("llvm_dbg_subprogram",
887 CI->getCalledFunction()->getFunctionType()));
890 DefaultIntrinsicLowering::LowerIntrinsicCall(CI);
895 } // end anonymous namespace
898 static void runChild(Module *M, const std::vector<std::string> &Arguments,
899 const char * const *envp,
900 FDHandle ReadFD, FDHandle WriteFD) {
902 // Create an execution engine that uses our custom intrinsic lowering object
903 // to revector debugging intrinsic functions into actual functions defined
905 ExecutionEngine *EE =
906 ExecutionEngine::create(new ExistingModuleProvider(M), false,
907 new DebuggerIntrinsicLowering());
908 assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
910 // Call the main function from M as if its signature were:
911 // int main (int argc, char **argv, const char **envp)
912 // using the contents of Args to determine argc & argv, and the contents of
913 // EnvVars to determine envp.
915 Function *Fn = M->getMainFunction();
918 // Create the child class instance which will be used by the debugger
919 // callbacks to keep track of the current state of the process.
920 assert(TheChild == 0 && "A child process has already been created??");
921 TheChild = new Child(M, EE, ReadFD, WriteFD);
924 int Result = EE->runFunctionAsMain(Fn, Arguments, envp);
926 // If the program didn't explicitly call exit, call exit now, for the program.
927 // This ensures that any atexit handlers get called correctly.
928 Function *Exit = M->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy,
931 std::vector<GenericValue> Args;
932 GenericValue ResultGV;
933 ResultGV.IntVal = Result;
934 Args.push_back(ResultGV);
935 EE->runFunction(Exit, Args);