blob: ffebdd5d58f4bedfb0d2d304ed7625c9b6694d8f [file] [log] [blame]
Chris Lattner7af5c122004-01-05 05:27:31 +00001//===-- Commands.cpp - Implement various commands for the CLI -------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Chris Lattner7af5c122004-01-05 05:27:31 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Chris Lattner7af5c122004-01-05 05:27:31 +00008//===----------------------------------------------------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00009//
Chris Lattner7af5c122004-01-05 05:27:31 +000010// This file implements many builtin user commands.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CLIDebugger.h"
15#include "CLICommand.h"
16#include "llvm/Debugger/ProgramInfo.h"
17#include "llvm/Debugger/RuntimeInfo.h"
18#include "llvm/Debugger/SourceLanguage.h"
19#include "llvm/Debugger/SourceFile.h"
20#include "llvm/Debugger/InferiorProcess.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/FileUtilities.h"
22#include "llvm/ADT/StringExtras.h"
Chris Lattner7af5c122004-01-05 05:27:31 +000023#include <iostream>
Anton Korobeynikova27694d2008-02-20 11:27:04 +000024#include <cstdlib>
Chris Lattner7af5c122004-01-05 05:27:31 +000025using namespace llvm;
26
27/// getCurrentLanguage - Return the current source language that the user is
28/// playing around with. This is aquired from the current stack frame of a
29/// running program if one exists, but this value can be explicitly set by the
30/// user as well.
31const SourceLanguage &CLIDebugger::getCurrentLanguage() const {
32 // If the user explicitly switched languages with 'set language', use what
33 // they asked for.
34 if (CurrentLanguage) {
35 return *CurrentLanguage;
36 } else if (Dbg.isProgramRunning()) {
37 // Otherwise, if the program is running, infer the current language from it.
38 const GlobalVariable *FuncDesc =
39 getRuntimeInfo().getCurrentFrame().getFunctionDesc();
40 return getProgramInfo().getFunction(FuncDesc).getSourceFile().getLanguage();
41 } else {
42 // Otherwise, default to C like GDB apparently does.
43 return SourceLanguage::getCFamilyInstance();
44 }
45}
46
47/// startProgramRunning - If the program has been updated, reload it, then
48/// start executing the program.
49void CLIDebugger::startProgramRunning() {
50 eliminateRunInfo();
51
52 // If the program has been modified, reload it!
Reid Spencer7b57fe32007-04-08 20:06:05 +000053 sys::PathWithStatus Program(Dbg.getProgramPath());
Chris Lattner252ad032006-07-28 22:03:44 +000054 std::string Err;
Reid Spencer7b57fe32007-04-08 20:06:05 +000055 const sys::FileStatus *Status = Program.getFileStatus(false, &Err);
Reid Spencer8475ec02007-03-29 19:05:44 +000056 if (!Status)
Chris Lattner252ad032006-07-28 22:03:44 +000057 throw Err;
Reid Spencer8475ec02007-03-29 19:05:44 +000058 if (TheProgramInfo->getProgramTimeStamp() != Status->getTimestamp()) {
Chris Lattner7af5c122004-01-05 05:27:31 +000059 std::cout << "'" << Program << "' has changed; re-reading program.\n";
60
61 // Unload an existing program. This kills the program if necessary.
62 Dbg.unloadProgram();
63 delete TheProgramInfo;
64 TheProgramInfo = 0;
65 CurrentFile = 0;
66
Reid Spencer9d88d1a2004-12-13 17:01:53 +000067 Dbg.loadProgram(Program.toString());
Chris Lattner7af5c122004-01-05 05:27:31 +000068 TheProgramInfo = new ProgramInfo(Dbg.getProgram());
69 }
70
71 std::cout << "Starting program: " << Dbg.getProgramPath() << "\n";
72 Dbg.createProgram();
73
74 // There was no current frame.
75 LastCurrentFrame = 0;
76}
77
78/// printSourceLine - Print the specified line of the current source file.
79/// If the specified line is invalid (the source file could not be loaded or
80/// the line number is out of range), don't print anything, but return true.
81bool CLIDebugger::printSourceLine(unsigned LineNo) {
82 assert(CurrentFile && "There is no current source file to print!");
83 const char *LineStart, *LineEnd;
84 CurrentFile->getSourceLine(LineNo-1, LineStart, LineEnd);
85 if (LineStart == 0) return true;
86 std::cout << LineNo;
87
88 // If this is the line the program is currently stopped at, print a marker.
89 if (Dbg.isProgramRunning()) {
90 unsigned CurLineNo, CurColNo;
91 const SourceFileInfo *CurSFI;
92 getRuntimeInfo().getCurrentFrame().getSourceLocation(CurLineNo, CurColNo,
93 CurSFI);
94
95 if (CurLineNo == LineNo && CurrentFile == &CurSFI->getSourceText())
96 std::cout << " ->";
97 }
98
Misha Brukman3da94ae2005-04-22 00:00:37 +000099 std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
Chris Lattner7af5c122004-01-05 05:27:31 +0000100 return false;
101}
102
103/// printProgramLocation - Print a line of the place where the current stack
104/// frame has stopped and the source line it is on.
105///
106void CLIDebugger::printProgramLocation(bool PrintLocation) {
107 assert(Dbg.isProgramLoaded() && Dbg.isProgramRunning() &&
108 "Error program is not loaded and running!");
109
110 // Figure out where the program stopped...
111 StackFrame &SF = getRuntimeInfo().getCurrentFrame();
112 unsigned LineNo, ColNo;
113 const SourceFileInfo *FileDesc;
114 SF.getSourceLocation(LineNo, ColNo, FileDesc);
115
116 // If requested, print out some program information about WHERE we are.
117 if (PrintLocation) {
118 // FIXME: print the current function arguments
119 if (const GlobalVariable *FuncDesc = SF.getFunctionDesc())
120 std::cout << getProgramInfo().getFunction(FuncDesc).getSymbolicName();
121 else
122 std::cout << "<unknown function>";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000123
Chris Lattner7af5c122004-01-05 05:27:31 +0000124 CurrentFile = &FileDesc->getSourceText();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000125
Chris Lattner7af5c122004-01-05 05:27:31 +0000126 std::cout << " at " << CurrentFile->getFilename() << ":" << LineNo;
Chris Lattnerfd80b5c2004-11-19 19:45:44 +0000127 if (ColNo) std::cout << ":" << ColNo;
128 std::cout << "\n";
Chris Lattner7af5c122004-01-05 05:27:31 +0000129 }
130
131 if (printSourceLine(LineNo))
132 std::cout << "<could not load source file>\n";
133 else {
134 LineListedStart = LineNo-ListSize/2+1;
135 if ((int)LineListedStart < 1) LineListedStart = 1;
136 LineListedEnd = LineListedStart+1;
137 }
138}
139
140/// eliminateRunInfo - We are about to run the program. Forget any state
141/// about how the program used to be stopped.
142void CLIDebugger::eliminateRunInfo() {
143 delete TheRuntimeInfo;
144 TheRuntimeInfo = 0;
145}
146
147/// programStoppedSuccessfully - This method updates internal data
148/// structures to reflect the fact that the program just executed a while,
149/// and has successfully stopped.
150void CLIDebugger::programStoppedSuccessfully() {
151 assert(TheRuntimeInfo==0 && "Someone forgot to release the old RuntimeInfo!");
152
153 TheRuntimeInfo = new RuntimeInfo(TheProgramInfo, Dbg.getRunningProcess());
154
155 // FIXME: if there are any breakpoints at the current location, print them as
156 // well.
157
158 // Since the program as successfully stopped, print its location.
159 void *CurrentFrame = getRuntimeInfo().getCurrentFrame().getFrameID();
160 printProgramLocation(CurrentFrame != LastCurrentFrame);
161 LastCurrentFrame = CurrentFrame;
162}
163
164
165
166/// getUnsignedIntegerOption - Get an unsigned integer number from the Val
167/// string. Check to make sure that the string contains an unsigned integer
168/// token, and if not, throw an exception. If isOnlyOption is set, also throw
169/// an exception if there is extra junk at the end of the string.
170static unsigned getUnsignedIntegerOption(const char *Msg, std::string &Val,
171 bool isOnlyOption = true) {
172 std::string Tok = getToken(Val);
173 if (Tok.empty() || (isOnlyOption && !getToken(Val).empty()))
174 throw std::string(Msg) + " expects an unsigned integer argument.";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000175
Chris Lattner7af5c122004-01-05 05:27:31 +0000176 char *EndPtr;
177 unsigned Result = strtoul(Tok.c_str(), &EndPtr, 0);
178 if (EndPtr != Tok.c_str()+Tok.size())
179 throw std::string(Msg) + " expects an unsigned integer argument.";
180
181 return Result;
182}
183
184/// getOptionalUnsignedIntegerOption - This method is just like
185/// getUnsignedIntegerOption, but if the argument value is not specified, a
186/// default is returned instead of causing an error.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000187static unsigned
Chris Lattner7af5c122004-01-05 05:27:31 +0000188getOptionalUnsignedIntegerOption(const char *Msg, unsigned Default,
189 std::string &Val, bool isOnlyOption = true) {
190 // Check to see if the value was specified...
191 std::string TokVal = getToken(Val);
192 if (TokVal.empty()) return Default;
193
194 // If it was specified, add it back to the value we are parsing...
195 Val = TokVal+Val;
196
197 // And parse normally.
198 return getUnsignedIntegerOption(Msg, Val, isOnlyOption);
199}
Chris Lattnere1567ae2004-01-06 05:37:16 +0000200
201
202/// parseProgramOptions - This method parses the Options string and loads it
203/// as options to be passed to the program. This is used by the run command
204/// and by 'set args'.
205void CLIDebugger::parseProgramOptions(std::string &Options) {
206 // FIXME: tokenizing by whitespace is clearly incorrect. Instead we should
207 // honor quotes and other things that a shell would. Also in the future we
208 // should support redirection of standard IO.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000209
Chris Lattnere1567ae2004-01-06 05:37:16 +0000210 std::vector<std::string> Arguments;
211 for (std::string A = getToken(Options); !A.empty(); A = getToken(Options))
212 Arguments.push_back(A);
213 Dbg.setProgramArguments(Arguments.begin(), Arguments.end());
214}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000215
Chris Lattner7af5c122004-01-05 05:27:31 +0000216
217//===----------------------------------------------------------------------===//
218// Program startup and shutdown options
219//===----------------------------------------------------------------------===//
220
221
222/// file command - If the user specifies an option, search the PATH for the
Gabor Greifa99be512007-07-05 17:07:56 +0000223/// specified program/bitcode file and load it. If the user does not specify
Chris Lattner7af5c122004-01-05 05:27:31 +0000224/// an option, unload the current program.
225void CLIDebugger::fileCommand(std::string &Options) {
226 std::string Prog = getToken(Options);
227 if (!getToken(Options).empty())
228 throw "file command takes at most one argument.";
229
230 // Check to make sure the user knows what they are doing
231 if (Dbg.isProgramRunning() &&
232 !askYesNo("A program is already loaded. Kill it?"))
233 return;
234
235 // Unload an existing program. This kills the program if necessary.
236 eliminateRunInfo();
237 delete TheProgramInfo;
238 TheProgramInfo = 0;
239 Dbg.unloadProgram();
240 CurrentFile = 0;
241
242 // If requested, start the new program.
243 if (Prog.empty()) {
244 std::cout << "Unloaded program.\n";
245 } else {
246 std::cout << "Loading program... " << std::flush;
247 Dbg.loadProgram(Prog);
248 assert(Dbg.isProgramLoaded() &&
249 "loadProgram succeeded, but not program loaded!");
250 TheProgramInfo = new ProgramInfo(Dbg.getProgram());
Chris Lattnere1567ae2004-01-06 05:37:16 +0000251 std::cout << "successfully loaded '" << Dbg.getProgramPath() << "'!\n";
Chris Lattner7af5c122004-01-05 05:27:31 +0000252 }
253}
254
255
256void CLIDebugger::createCommand(std::string &Options) {
257 if (!getToken(Options).empty())
258 throw "create command does not take any arguments.";
259 if (!Dbg.isProgramLoaded()) throw "No program loaded.";
260 if (Dbg.isProgramRunning() &&
261 !askYesNo("The program is already running. Restart from the beginning?"))
262 return;
263
264 // Start the program running.
265 startProgramRunning();
266
267 // The program stopped!
268 programStoppedSuccessfully();
269}
270
271void CLIDebugger::killCommand(std::string &Options) {
272 if (!getToken(Options).empty())
273 throw "kill command does not take any arguments.";
274 if (!Dbg.isProgramRunning())
275 throw "No program is currently being run.";
276
277 if (askYesNo("Kill the program being debugged?"))
278 Dbg.killProgram();
279 eliminateRunInfo();
280}
281
282void CLIDebugger::quitCommand(std::string &Options) {
283 if (!getToken(Options).empty())
284 throw "quit command does not take any arguments.";
285
286 if (Dbg.isProgramRunning() &&
287 !askYesNo("The program is running. Exit anyway?"))
288 return;
289
290 // Throw exception to get out of the user-input loop.
291 throw 0;
292}
293
294
295//===----------------------------------------------------------------------===//
296// Program execution commands
297//===----------------------------------------------------------------------===//
298
299void CLIDebugger::runCommand(std::string &Options) {
Chris Lattner7af5c122004-01-05 05:27:31 +0000300 if (!Dbg.isProgramLoaded()) throw "No program loaded.";
301 if (Dbg.isProgramRunning() &&
302 !askYesNo("The program is already running. Restart from the beginning?"))
303 return;
304
Chris Lattnere1567ae2004-01-06 05:37:16 +0000305 // Parse all of the options to the run command, which specify program
306 // arguments to run with.
307 parseProgramOptions(Options);
308
Chris Lattner7af5c122004-01-05 05:27:31 +0000309 eliminateRunInfo();
310
311 // Start the program running.
312 startProgramRunning();
313
314 // Start the program running...
315 Options = "";
316 contCommand(Options);
317}
318
319void CLIDebugger::contCommand(std::string &Options) {
320 if (!getToken(Options).empty()) throw "cont argument not supported yet.";
321 if (!Dbg.isProgramRunning()) throw "Program is not running.";
322
323 eliminateRunInfo();
324
325 Dbg.contProgram();
326
327 // The program stopped!
328 programStoppedSuccessfully();
329}
330
331void CLIDebugger::stepCommand(std::string &Options) {
332 if (!Dbg.isProgramRunning()) throw "Program is not running.";
333
334 // Figure out how many times to step.
335 unsigned Amount =
336 getOptionalUnsignedIntegerOption("'step' command", 1, Options);
337
338 eliminateRunInfo();
339
340 // Step the specified number of times.
341 for (; Amount; --Amount)
342 Dbg.stepProgram();
343
344 // The program stopped!
345 programStoppedSuccessfully();
346}
347
348void CLIDebugger::nextCommand(std::string &Options) {
349 if (!Dbg.isProgramRunning()) throw "Program is not running.";
350 unsigned Amount =
351 getOptionalUnsignedIntegerOption("'next' command", 1, Options);
352
353 eliminateRunInfo();
354
355 for (; Amount; --Amount)
356 Dbg.nextProgram();
357
358 // The program stopped!
359 programStoppedSuccessfully();
360}
361
362void CLIDebugger::finishCommand(std::string &Options) {
363 if (!getToken(Options).empty())
364 throw "finish command does not take any arguments.";
365 if (!Dbg.isProgramRunning()) throw "Program is not running.";
366
367 // Figure out where we are exactly. If the user requests that we return from
368 // a frame that is not the top frame, make sure we get it.
369 void *CurrentFrame = getRuntimeInfo().getCurrentFrame().getFrameID();
370
371 eliminateRunInfo();
372
373 Dbg.finishProgram(CurrentFrame);
374
375 // The program stopped!
376 programStoppedSuccessfully();
377}
378
379//===----------------------------------------------------------------------===//
380// Stack frame commands
381//===----------------------------------------------------------------------===//
382
383void CLIDebugger::backtraceCommand(std::string &Options) {
384 // Accepts "full", n, -n
385 if (!getToken(Options).empty())
386 throw "FIXME: bt command argument not implemented yet!";
387
388 RuntimeInfo &RI = getRuntimeInfo();
389 ProgramInfo &PI = getProgramInfo();
390
391 try {
392 for (unsigned i = 0; ; ++i) {
393 StackFrame &SF = RI.getStackFrame(i);
394 std::cout << "#" << i;
395 if (i == RI.getCurrentFrameIdx())
396 std::cout << " ->";
397 std::cout << "\t" << SF.getFrameID() << " in ";
398 if (const GlobalVariable *G = SF.getFunctionDesc())
399 std::cout << PI.getFunction(G).getSymbolicName();
400
401 unsigned LineNo, ColNo;
402 const SourceFileInfo *SFI;
403 SF.getSourceLocation(LineNo, ColNo, SFI);
404 if (!SFI->getBaseName().empty()) {
405 std::cout << " at " << SFI->getBaseName();
406 if (LineNo) {
407 std::cout << ":" << LineNo;
408 if (ColNo)
409 std::cout << ":" << ColNo;
410 }
411 }
412
413 // FIXME: when we support shared libraries, we should print ' from foo.so'
414 // if the stack frame is from a different object than the current one.
415
416 std::cout << "\n";
417 }
418 } catch (...) {
419 // Stop automatically when we run off the bottom of the stack.
420 }
421}
422
423void CLIDebugger::upCommand(std::string &Options) {
424 unsigned Num =
425 getOptionalUnsignedIntegerOption("'up' command", 1, Options);
426
427 RuntimeInfo &RI = getRuntimeInfo();
428 unsigned CurFrame = RI.getCurrentFrameIdx();
429
430 // Check to see if we go can up the specified number of frames.
431 try {
432 RI.getStackFrame(CurFrame+Num);
433 } catch (...) {
434 if (Num == 1)
435 throw "Initial frame selected; you cannot go up.";
436 else
437 throw "Cannot go up " + utostr(Num) + " frames!";
438 }
439
440 RI.setCurrentFrameIdx(CurFrame+Num);
441 printProgramLocation();
442}
443
444void CLIDebugger::downCommand(std::string &Options) {
445 unsigned Num =
446 getOptionalUnsignedIntegerOption("'down' command", 1, Options);
447
448 RuntimeInfo &RI = getRuntimeInfo();
449 unsigned CurFrame = RI.getCurrentFrameIdx();
450
451 // Check to see if we can go up the specified number of frames.
Anton Korobeynikova27694d2008-02-20 11:27:04 +0000452 if (CurFrame < Num) {
Chris Lattner7af5c122004-01-05 05:27:31 +0000453 if (Num == 1)
454 throw "Bottom (i.e., innermost) frame selected; you cannot go down.";
455 else
456 throw "Cannot go down " + utostr(Num) + " frames!";
Anton Korobeynikova27694d2008-02-20 11:27:04 +0000457 }
Chris Lattner7af5c122004-01-05 05:27:31 +0000458
459 RI.setCurrentFrameIdx(CurFrame-Num);
460 printProgramLocation();
461}
462
463void CLIDebugger::frameCommand(std::string &Options) {
464 RuntimeInfo &RI = getRuntimeInfo();
465 unsigned CurFrame = RI.getCurrentFrameIdx();
466
467 unsigned Num =
468 getOptionalUnsignedIntegerOption("'frame' command", CurFrame, Options);
469
470 // Check to see if we go to the specified frame.
471 RI.getStackFrame(Num);
472
473 RI.setCurrentFrameIdx(Num);
474 printProgramLocation();
475}
476
477
478//===----------------------------------------------------------------------===//
479// Breakpoint related commands
480//===----------------------------------------------------------------------===//
481
482void CLIDebugger::breakCommand(std::string &Options) {
Chris Lattnere1567ae2004-01-06 05:37:16 +0000483 // Figure out where the user wants a breakpoint.
484 const SourceFile *File;
485 unsigned LineNo;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000486
Chris Lattnere1567ae2004-01-06 05:37:16 +0000487 // Check to see if the user specified a line specifier.
488 std::string Option = getToken(Options); // strip whitespace
489 if (!Option.empty()) {
490 Options = Option + Options; // reconstruct string
491
492 // Parse the line specifier.
Chris Lattnerf6608dd2004-01-06 23:46:17 +0000493 parseLineSpec(Options, File, LineNo);
Chris Lattnere1567ae2004-01-06 05:37:16 +0000494 } else {
495 // Build a line specifier for the current stack frame.
496 throw "FIXME: breaking at the current location is not implemented yet!";
497 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000498
Chris Lattnerf2592ce2004-02-08 00:06:20 +0000499 if (!File) File = CurrentFile;
500 if (File == 0)
501 throw "Unknown file to place breakpoint!";
502
503 std::cerr << "Break: " << File->getFilename() << ":" << LineNo << "\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000504
Chris Lattner7af5c122004-01-05 05:27:31 +0000505 throw "breakpoints not implemented yet!";
506}
507
508//===----------------------------------------------------------------------===//
509// Miscellaneous commands
510//===----------------------------------------------------------------------===//
511
512void CLIDebugger::infoCommand(std::string &Options) {
513 std::string What = getToken(Options);
514
Chris Lattner395236f2004-10-26 05:46:17 +0000515 if (What.empty() || !getToken(Options).empty()){
516 std::string infoStr("info");
517 helpCommand(infoStr);
518 return;
519 }
Chris Lattner7af5c122004-01-05 05:27:31 +0000520
521 if (What == "frame") {
522 } else if (What == "functions") {
523 const std::map<const GlobalVariable*, SourceFunctionInfo*> &Functions
524 = getProgramInfo().getSourceFunctions();
525 std::cout << "All defined functions:\n";
526 // FIXME: GDB groups these by source file. We could do that I guess.
527 for (std::map<const GlobalVariable*, SourceFunctionInfo*>::const_iterator
528 I = Functions.begin(), E = Functions.end(); I != E; ++I) {
529 std::cout << I->second->getSymbolicName() << "\n";
530 }
531
532 } else if (What == "source") {
533 if (CurrentFile == 0)
534 throw "No current source file.";
535
536 // Get the SourceFile information for the current file.
537 const SourceFileInfo &SF =
538 getProgramInfo().getSourceFile(CurrentFile->getDescriptor());
539
540 std::cout << "Current source file is: " << SF.getBaseName() << "\n"
541 << "Compilation directory is: " << SF.getDirectory() << "\n";
542 if (unsigned NL = CurrentFile->getNumLines())
543 std::cout << "Located in: " << CurrentFile->getFilename() << "\n"
544 << "Contains " << NL << " lines\n";
545 else
546 std::cout << "Could not find source file.\n";
547 std::cout << "Source language is "
548 << SF.getLanguage().getSourceLanguageName() << "\n";
549
550 } else if (What == "sources") {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000551 const std::map<const GlobalVariable*, SourceFileInfo*> &SourceFiles =
Chris Lattner7af5c122004-01-05 05:27:31 +0000552 getProgramInfo().getSourceFiles();
553 std::cout << "Source files for the program:\n";
554 for (std::map<const GlobalVariable*, SourceFileInfo*>::const_iterator I =
555 SourceFiles.begin(), E = SourceFiles.end(); I != E;) {
556 std::cout << I->second->getDirectory() << "/"
557 << I->second->getBaseName();
558 ++I;
559 if (I != E) std::cout << ", ";
560 }
561 std::cout << "\n";
562 } else if (What == "target") {
563 std::cout << Dbg.getRunningProcess().getStatus();
564 } else {
565 // See if this is something handled by the current language.
566 if (getCurrentLanguage().printInfo(What))
567 return;
568
569 throw "Unknown info command '" + What + "'. Try 'help info'.";
570 }
571}
572
573/// parseLineSpec - Parses a line specifier, for use by the 'list' command.
574/// If SourceFile is returned as a void pointer, then it was not specified.
575/// If the line specifier is invalid, an exception is thrown.
576void CLIDebugger::parseLineSpec(std::string &LineSpec,
577 const SourceFile *&SourceFile,
578 unsigned &LineNo) {
579 SourceFile = 0;
580 LineNo = 0;
581
582 // First, check to see if we have a : separator.
583 std::string FirstPart = getToken(LineSpec, ":");
584 std::string SecondPart = getToken(LineSpec, ":");
585 if (!getToken(LineSpec).empty()) throw "Malformed line specification!";
586
587 // If there is no second part, we must have either "function", "number",
588 // "+offset", or "-offset".
589 if (SecondPart.empty()) {
590 if (FirstPart.empty()) throw "Malformed line specification!";
591 if (FirstPart[0] == '+') {
592 FirstPart.erase(FirstPart.begin(), FirstPart.begin()+1);
593 // For +n, return LineListedEnd+n
594 LineNo = LineListedEnd +
595 getUnsignedIntegerOption("Line specifier '+'", FirstPart);
596
597 } else if (FirstPart[0] == '-') {
598 FirstPart.erase(FirstPart.begin(), FirstPart.begin()+1);
599 // For -n, return LineListedEnd-n
600 LineNo = LineListedEnd -
601 getUnsignedIntegerOption("Line specifier '-'", FirstPart);
602 if ((int)LineNo < 1) LineNo = 1;
603 } else if (FirstPart[0] == '*') {
604 throw "Address expressions not supported as source locations!";
605 } else {
606 // Ok, check to see if this is just a line number.
607 std::string Saved = FirstPart;
608 try {
609 LineNo = getUnsignedIntegerOption("", Saved);
610 } catch (...) {
611 // Ok, it's not a valid line number. It must be a source-language
612 // entity name.
613 std::string Name = getToken(FirstPart);
614 if (!getToken(FirstPart).empty())
615 throw "Extra junk in line specifier after '" + Name + "'.";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000616 SourceFunctionInfo *SFI =
Chris Lattner7af5c122004-01-05 05:27:31 +0000617 getCurrentLanguage().lookupFunction(Name, getProgramInfo(),
618 TheRuntimeInfo);
619 if (SFI == 0)
620 throw "Unknown identifier '" + Name + "'.";
621
622 unsigned L, C;
623 SFI->getSourceLocation(L, C);
624 if (L == 0) throw "Could not locate '" + Name + "'!";
625 LineNo = L;
626 SourceFile = &SFI->getSourceFile().getSourceText();
627 return;
628 }
629 }
630
631 } else {
632 // Ok, this must be a filename qualified line number or function name.
633 // First, figure out the source filename.
634 std::string SourceFilename = getToken(FirstPart);
635 if (!getToken(FirstPart).empty())
636 throw "Invalid filename qualified source location!";
637
638 // Next, check to see if this is just a line number.
639 std::string Saved = SecondPart;
640 try {
641 LineNo = getUnsignedIntegerOption("", Saved);
642 } catch (...) {
643 // Ok, it's not a valid line number. It must be a function name.
644 throw "FIXME: Filename qualified function names are not support "
645 "as line specifiers yet!";
646 }
647
648 // Ok, we got the line number. Now check out the source file name to make
649 // sure it's all good. If it is, return it. If not, throw exception.
650 SourceFile =&getProgramInfo().getSourceFile(SourceFilename).getSourceText();
651 }
652}
653
654void CLIDebugger::listCommand(std::string &Options) {
655 if (!Dbg.isProgramLoaded())
656 throw "No program is loaded. Use the 'file' command.";
657
658 // Handle "list foo," correctly, by returning " " as the second token
659 Options += " ";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000660
Chris Lattner7af5c122004-01-05 05:27:31 +0000661 std::string FirstLineSpec = getToken(Options, ",");
662 std::string SecondLineSpec = getToken(Options, ",");
663 if (!getToken(Options, ",").empty())
664 throw "list command only expects two source location specifiers!";
665
666 // StartLine, EndLine - The starting and ending line numbers to print.
667 unsigned StartLine = 0, EndLine = 0;
668
669 if (SecondLineSpec.empty()) { // No second line specifier provided?
670 // Handle special forms like "", "+", "-", etc.
671 std::string TmpSpec = FirstLineSpec;
672 std::string Tok = getToken(TmpSpec);
673 if (getToken(TmpSpec).empty() && (Tok == "" || Tok == "+" || Tok == "-")) {
674 if (Tok == "+" || Tok == "") {
675 StartLine = LineListedEnd;
676 EndLine = StartLine + ListSize;
677 } else {
678 assert(Tok == "-");
679 StartLine = LineListedStart-ListSize;
680 EndLine = LineListedStart;
Chris Lattnere1567ae2004-01-06 05:37:16 +0000681 if ((int)StartLine <= 0) StartLine = 1;
Chris Lattner7af5c122004-01-05 05:27:31 +0000682 }
683 } else {
684 // Must be a normal line specifier.
685 const SourceFile *File;
686 unsigned LineNo;
687 parseLineSpec(FirstLineSpec, File, LineNo);
688
689 // If the user only specified one file specifier, we should display
690 // ListSize lines centered at the specified line.
691 if (File != 0) CurrentFile = File;
692 StartLine = LineNo - (ListSize+1)/2;
Chris Lattnere1567ae2004-01-06 05:37:16 +0000693 if ((int)StartLine <= 0) StartLine = 1;
Chris Lattner7af5c122004-01-05 05:27:31 +0000694 EndLine = StartLine + ListSize;
695 }
696
697 } else {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000698 // Parse two line specifiers...
Chris Lattner7af5c122004-01-05 05:27:31 +0000699 const SourceFile *StartFile, *EndFile;
700 unsigned StartLineNo, EndLineNo;
701 parseLineSpec(FirstLineSpec, StartFile, StartLineNo);
702 unsigned SavedLLE = LineListedEnd;
703 LineListedEnd = StartLineNo;
704 try {
705 parseLineSpec(SecondLineSpec, EndFile, EndLineNo);
706 } catch (...) {
707 LineListedEnd = SavedLLE;
708 throw;
709 }
710
711 // Inherit file specified by the first line spec if there was one.
712 if (EndFile == 0) EndFile = StartFile;
713
714 if (StartFile != EndFile)
715 throw "Start and end line specifiers are in different files!";
716 CurrentFile = StartFile;
717 StartLine = StartLineNo;
718 EndLine = EndLineNo+1;
719 }
720
721 assert((int)StartLine > 0 && (int)EndLine > 0 && StartLine <= EndLine &&
722 "Error reading line specifiers!");
723
724 // If there was no current file, and the user didn't specify one to list, we
725 // have an error.
726 if (CurrentFile == 0)
727 throw "There is no current file to list.";
728
729 // Remember for next time.
730 LineListedStart = StartLine;
731 LineListedEnd = StartLine;
732
733 for (unsigned LineNo = StartLine; LineNo != EndLine; ++LineNo) {
734 // Print the source line, unless it is invalid.
735 if (printSourceLine(LineNo))
736 break;
737 LineListedEnd = LineNo+1;
738 }
739
740 // If we didn't print any lines, find out why.
741 if (LineListedEnd == StartLine) {
742 // See if we can read line #0 from the file, if not, we couldn't load the
743 // file.
744 const char *LineStart, *LineEnd;
745 CurrentFile->getSourceLine(0, LineStart, LineEnd);
746 if (LineStart == 0)
747 throw "Could not load source file '" + CurrentFile->getFilename() + "'!";
748 else
749 std::cout << "<end of file>\n";
750 }
751}
752
753void CLIDebugger::setCommand(std::string &Options) {
754 std::string What = getToken(Options);
755
756 if (What.empty())
757 throw "set command expects at least two arguments.";
Chris Lattnere1567ae2004-01-06 05:37:16 +0000758 if (What == "args") {
759 parseProgramOptions(Options);
760 } else if (What == "language") {
Chris Lattner7af5c122004-01-05 05:27:31 +0000761 std::string Lang = getToken(Options);
762 if (!getToken(Options).empty())
763 throw "set language expects one argument at most.";
764 if (Lang == "") {
765 std::cout << "The currently understood settings are:\n\n"
766 << "local or auto Automatic setting based on source file\n"
767 << "c Use the C language\n"
768 << "c++ Use the C++ language\n"
769 << "unknown Use when source language is not supported\n";
770 } else if (Lang == "local" || Lang == "auto") {
771 CurrentLanguage = 0;
772 } else if (Lang == "c") {
773 CurrentLanguage = &SourceLanguage::getCFamilyInstance();
774 } else if (Lang == "c++") {
775 CurrentLanguage = &SourceLanguage::getCPlusPlusInstance();
776 } else if (Lang == "unknown") {
777 CurrentLanguage = &SourceLanguage::getUnknownLanguageInstance();
778 } else {
779 throw "Unknown language '" + Lang + "'.";
780 }
781
782 } else if (What == "listsize") {
783 ListSize = getUnsignedIntegerOption("'set prompt' command", Options);
784 } else if (What == "prompt") {
785 // Include any trailing whitespace or other tokens, but not leading
786 // whitespace.
787 Prompt = getToken(Options); // Strip leading whitespace
788 Prompt += Options; // Keep trailing whitespace or other stuff
789 } else {
790 // FIXME: Try to parse this as a source-language program expression.
791 throw "Don't know how to set '" + What + "'!";
792 }
793}
794
795void CLIDebugger::showCommand(std::string &Options) {
796 std::string What = getToken(Options);
797
798 if (What.empty() || !getToken(Options).empty())
799 throw "show command expects one argument.";
800
Chris Lattnere1567ae2004-01-06 05:37:16 +0000801 if (What == "args") {
802 std::cout << "Argument list to give program when started is \"";
803 // FIXME: This doesn't print stuff correctly if the arguments have spaces in
804 // them, but currently the only way to get that is to use the --args command
805 // line argument. This should really handle escaping all hard characters as
806 // needed.
807 for (unsigned i = 0, e = Dbg.getNumProgramArguments(); i != e; ++i)
808 std::cout << (i ? " " : "") << Dbg.getProgramArgument(i);
809 std::cout << "\"\n";
810
811 } else if (What == "language") {
Chris Lattner7af5c122004-01-05 05:27:31 +0000812 std::cout << "The current source language is '";
813 if (CurrentLanguage)
814 std::cout << CurrentLanguage->getSourceLanguageName();
815 else
816 std::cout << "auto; currently "
817 << getCurrentLanguage().getSourceLanguageName();
818 std::cout << "'.\n";
819 } else if (What == "listsize") {
820 std::cout << "Number of source lines llvm-db will list by default is "
821 << ListSize << ".\n";
822 } else if (What == "prompt") {
823 std::cout << "llvm-db's prompt is \"" << Prompt << "\".\n";
824 } else {
825 throw "Unknown show command '" + What + "'. Try 'help show'.";
826 }
827}
828
829void CLIDebugger::helpCommand(std::string &Options) {
830 // Print out all of the commands in the CommandTable
831 std::string Command = getToken(Options);
832 if (!getToken(Options).empty())
833 throw "help command takes at most one argument.";
834
835 // Getting detailed help on a particular command?
836 if (!Command.empty()) {
837 CLICommand *C = getCommand(Command);
838 std::cout << C->getShortHelp() << ".\n" << C->getLongHelp();
839
840 // If there are aliases for this option, print them out.
841 const std::vector<std::string> &Names = C->getOptionNames();
842 if (Names.size() > 1) {
843 std::cout << "The '" << Command << "' command is known as: '"
844 << Names[0] << "'";
845 for (unsigned i = 1, e = Names.size(); i != e; ++i)
846 std::cout << ", '" << Names[i] << "'";
847 std::cout << "\n";
848 }
849
850 } else {
851 unsigned MaxSize = 0;
852 for (std::map<std::string, CLICommand*>::iterator I = CommandTable.begin(),
853 E = CommandTable.end(); I != E; ++I)
854 if (I->first.size() > MaxSize &&
855 I->first == I->second->getPrimaryOptionName())
856 MaxSize = I->first.size();
857
858 // Loop over all of the commands, printing the short help version
859 for (std::map<std::string, CLICommand*>::iterator I = CommandTable.begin(),
860 E = CommandTable.end(); I != E; ++I)
861 if (I->first == I->second->getPrimaryOptionName())
862 std::cout << I->first << std::string(MaxSize - I->first.size(), ' ')
863 << " - " << I->second->getShortHelp() << "\n";
864 }
865}