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