Add hint to nop
[llvm/msp430.git] / tools / llvm-db / Commands.cpp
blobffebdd5d58f4bedfb0d2d304ed7625c9b6694d8f
1 //===-- Commands.cpp - Implement various commands for the CLI -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements many builtin user commands.
12 //===----------------------------------------------------------------------===//
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"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include <iostream>
24 #include <cstdlib>
25 using namespace llvm;
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.
31 const 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();
47 /// startProgramRunning - If the program has been updated, reload it, then
48 /// start executing the program.
49 void CLIDebugger::startProgramRunning() {
50 eliminateRunInfo();
52 // If the program has been modified, reload it!
53 sys::PathWithStatus Program(Dbg.getProgramPath());
54 std::string Err;
55 const sys::FileStatus *Status = Program.getFileStatus(false, &Err);
56 if (!Status)
57 throw Err;
58 if (TheProgramInfo->getProgramTimeStamp() != Status->getTimestamp()) {
59 std::cout << "'" << Program << "' has changed; re-reading program.\n";
61 // Unload an existing program. This kills the program if necessary.
62 Dbg.unloadProgram();
63 delete TheProgramInfo;
64 TheProgramInfo = 0;
65 CurrentFile = 0;
67 Dbg.loadProgram(Program.toString());
68 TheProgramInfo = new ProgramInfo(Dbg.getProgram());
71 std::cout << "Starting program: " << Dbg.getProgramPath() << "\n";
72 Dbg.createProgram();
74 // There was no current frame.
75 LastCurrentFrame = 0;
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.
81 bool 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;
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);
95 if (CurLineNo == LineNo && CurrentFile == &CurSFI->getSourceText())
96 std::cout << " ->";
99 std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
100 return false;
103 /// printProgramLocation - Print a line of the place where the current stack
104 /// frame has stopped and the source line it is on.
106 void CLIDebugger::printProgramLocation(bool PrintLocation) {
107 assert(Dbg.isProgramLoaded() && Dbg.isProgramRunning() &&
108 "Error program is not loaded and running!");
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);
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>";
124 CurrentFile = &FileDesc->getSourceText();
126 std::cout << " at " << CurrentFile->getFilename() << ":" << LineNo;
127 if (ColNo) std::cout << ":" << ColNo;
128 std::cout << "\n";
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;
140 /// eliminateRunInfo - We are about to run the program. Forget any state
141 /// about how the program used to be stopped.
142 void CLIDebugger::eliminateRunInfo() {
143 delete TheRuntimeInfo;
144 TheRuntimeInfo = 0;
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.
150 void CLIDebugger::programStoppedSuccessfully() {
151 assert(TheRuntimeInfo==0 && "Someone forgot to release the old RuntimeInfo!");
153 TheRuntimeInfo = new RuntimeInfo(TheProgramInfo, Dbg.getRunningProcess());
155 // FIXME: if there are any breakpoints at the current location, print them as
156 // well.
158 // Since the program as successfully stopped, print its location.
159 void *CurrentFrame = getRuntimeInfo().getCurrentFrame().getFrameID();
160 printProgramLocation(CurrentFrame != LastCurrentFrame);
161 LastCurrentFrame = CurrentFrame;
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.
170 static 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.";
176 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.";
181 return Result;
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.
187 static unsigned
188 getOptionalUnsignedIntegerOption(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;
194 // If it was specified, add it back to the value we are parsing...
195 Val = TokVal+Val;
197 // And parse normally.
198 return getUnsignedIntegerOption(Msg, Val, isOnlyOption);
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'.
205 void 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.
210 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());
217 //===----------------------------------------------------------------------===//
218 // Program startup and shutdown options
219 //===----------------------------------------------------------------------===//
222 /// file command - If the user specifies an option, search the PATH for the
223 /// specified program/bitcode file and load it. If the user does not specify
224 /// an option, unload the current program.
225 void 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.";
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;
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;
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());
251 std::cout << "successfully loaded '" << Dbg.getProgramPath() << "'!\n";
256 void 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;
264 // Start the program running.
265 startProgramRunning();
267 // The program stopped!
268 programStoppedSuccessfully();
271 void 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.";
277 if (askYesNo("Kill the program being debugged?"))
278 Dbg.killProgram();
279 eliminateRunInfo();
282 void CLIDebugger::quitCommand(std::string &Options) {
283 if (!getToken(Options).empty())
284 throw "quit command does not take any arguments.";
286 if (Dbg.isProgramRunning() &&
287 !askYesNo("The program is running. Exit anyway?"))
288 return;
290 // Throw exception to get out of the user-input loop.
291 throw 0;
295 //===----------------------------------------------------------------------===//
296 // Program execution commands
297 //===----------------------------------------------------------------------===//
299 void CLIDebugger::runCommand(std::string &Options) {
300 if (!Dbg.isProgramLoaded()) throw "No program loaded.";
301 if (Dbg.isProgramRunning() &&
302 !askYesNo("The program is already running. Restart from the beginning?"))
303 return;
305 // Parse all of the options to the run command, which specify program
306 // arguments to run with.
307 parseProgramOptions(Options);
309 eliminateRunInfo();
311 // Start the program running.
312 startProgramRunning();
314 // Start the program running...
315 Options = "";
316 contCommand(Options);
319 void 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.";
323 eliminateRunInfo();
325 Dbg.contProgram();
327 // The program stopped!
328 programStoppedSuccessfully();
331 void CLIDebugger::stepCommand(std::string &Options) {
332 if (!Dbg.isProgramRunning()) throw "Program is not running.";
334 // Figure out how many times to step.
335 unsigned Amount =
336 getOptionalUnsignedIntegerOption("'step' command", 1, Options);
338 eliminateRunInfo();
340 // Step the specified number of times.
341 for (; Amount; --Amount)
342 Dbg.stepProgram();
344 // The program stopped!
345 programStoppedSuccessfully();
348 void CLIDebugger::nextCommand(std::string &Options) {
349 if (!Dbg.isProgramRunning()) throw "Program is not running.";
350 unsigned Amount =
351 getOptionalUnsignedIntegerOption("'next' command", 1, Options);
353 eliminateRunInfo();
355 for (; Amount; --Amount)
356 Dbg.nextProgram();
358 // The program stopped!
359 programStoppedSuccessfully();
362 void 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.";
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();
371 eliminateRunInfo();
373 Dbg.finishProgram(CurrentFrame);
375 // The program stopped!
376 programStoppedSuccessfully();
379 //===----------------------------------------------------------------------===//
380 // Stack frame commands
381 //===----------------------------------------------------------------------===//
383 void CLIDebugger::backtraceCommand(std::string &Options) {
384 // Accepts "full", n, -n
385 if (!getToken(Options).empty())
386 throw "FIXME: bt command argument not implemented yet!";
388 RuntimeInfo &RI = getRuntimeInfo();
389 ProgramInfo &PI = getProgramInfo();
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();
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;
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.
416 std::cout << "\n";
418 } catch (...) {
419 // Stop automatically when we run off the bottom of the stack.
423 void CLIDebugger::upCommand(std::string &Options) {
424 unsigned Num =
425 getOptionalUnsignedIntegerOption("'up' command", 1, Options);
427 RuntimeInfo &RI = getRuntimeInfo();
428 unsigned CurFrame = RI.getCurrentFrameIdx();
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!";
440 RI.setCurrentFrameIdx(CurFrame+Num);
441 printProgramLocation();
444 void CLIDebugger::downCommand(std::string &Options) {
445 unsigned Num =
446 getOptionalUnsignedIntegerOption("'down' command", 1, Options);
448 RuntimeInfo &RI = getRuntimeInfo();
449 unsigned CurFrame = RI.getCurrentFrameIdx();
451 // Check to see if we can go up the specified number of frames.
452 if (CurFrame < Num) {
453 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!";
459 RI.setCurrentFrameIdx(CurFrame-Num);
460 printProgramLocation();
463 void CLIDebugger::frameCommand(std::string &Options) {
464 RuntimeInfo &RI = getRuntimeInfo();
465 unsigned CurFrame = RI.getCurrentFrameIdx();
467 unsigned Num =
468 getOptionalUnsignedIntegerOption("'frame' command", CurFrame, Options);
470 // Check to see if we go to the specified frame.
471 RI.getStackFrame(Num);
473 RI.setCurrentFrameIdx(Num);
474 printProgramLocation();
478 //===----------------------------------------------------------------------===//
479 // Breakpoint related commands
480 //===----------------------------------------------------------------------===//
482 void CLIDebugger::breakCommand(std::string &Options) {
483 // Figure out where the user wants a breakpoint.
484 const SourceFile *File;
485 unsigned LineNo;
487 // 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
492 // Parse the line specifier.
493 parseLineSpec(Options, File, LineNo);
494 } else {
495 // Build a line specifier for the current stack frame.
496 throw "FIXME: breaking at the current location is not implemented yet!";
499 if (!File) File = CurrentFile;
500 if (File == 0)
501 throw "Unknown file to place breakpoint!";
503 std::cerr << "Break: " << File->getFilename() << ":" << LineNo << "\n";
505 throw "breakpoints not implemented yet!";
508 //===----------------------------------------------------------------------===//
509 // Miscellaneous commands
510 //===----------------------------------------------------------------------===//
512 void CLIDebugger::infoCommand(std::string &Options) {
513 std::string What = getToken(Options);
515 if (What.empty() || !getToken(Options).empty()){
516 std::string infoStr("info");
517 helpCommand(infoStr);
518 return;
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";
532 } else if (What == "source") {
533 if (CurrentFile == 0)
534 throw "No current source file.";
536 // Get the SourceFile information for the current file.
537 const SourceFileInfo &SF =
538 getProgramInfo().getSourceFile(CurrentFile->getDescriptor());
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";
550 } else if (What == "sources") {
551 const std::map<const GlobalVariable*, SourceFileInfo*> &SourceFiles =
552 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 << ", ";
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;
569 throw "Unknown info command '" + What + "'. Try 'help info'.";
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.
576 void CLIDebugger::parseLineSpec(std::string &LineSpec,
577 const SourceFile *&SourceFile,
578 unsigned &LineNo) {
579 SourceFile = 0;
580 LineNo = 0;
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!";
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);
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 + "'.";
616 SourceFunctionInfo *SFI =
617 getCurrentLanguage().lookupFunction(Name, getProgramInfo(),
618 TheRuntimeInfo);
619 if (SFI == 0)
620 throw "Unknown identifier '" + Name + "'.";
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;
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!";
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!";
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();
654 void CLIDebugger::listCommand(std::string &Options) {
655 if (!Dbg.isProgramLoaded())
656 throw "No program is loaded. Use the 'file' command.";
658 // Handle "list foo," correctly, by returning " " as the second token
659 Options += " ";
661 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!";
666 // StartLine, EndLine - The starting and ending line numbers to print.
667 unsigned StartLine = 0, EndLine = 0;
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;
681 if ((int)StartLine <= 0) StartLine = 1;
683 } else {
684 // Must be a normal line specifier.
685 const SourceFile *File;
686 unsigned LineNo;
687 parseLineSpec(FirstLineSpec, File, LineNo);
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;
693 if ((int)StartLine <= 0) StartLine = 1;
694 EndLine = StartLine + ListSize;
697 } else {
698 // Parse two line specifiers...
699 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;
711 // Inherit file specified by the first line spec if there was one.
712 if (EndFile == 0) EndFile = StartFile;
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;
721 assert((int)StartLine > 0 && (int)EndLine > 0 && StartLine <= EndLine &&
722 "Error reading line specifiers!");
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.";
729 // Remember for next time.
730 LineListedStart = StartLine;
731 LineListedEnd = StartLine;
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;
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";
753 void CLIDebugger::setCommand(std::string &Options) {
754 std::string What = getToken(Options);
756 if (What.empty())
757 throw "set command expects at least two arguments.";
758 if (What == "args") {
759 parseProgramOptions(Options);
760 } else if (What == "language") {
761 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 + "'.";
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 + "'!";
795 void CLIDebugger::showCommand(std::string &Options) {
796 std::string What = getToken(Options);
798 if (What.empty() || !getToken(Options).empty())
799 throw "show command expects one argument.";
801 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";
811 } else if (What == "language") {
812 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'.";
829 void 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.";
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();
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";
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();
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";