#include "CLIDebugger.h"
#include "CLICommand.h"
#include "llvm/Debugger/ProgramInfo.h"
#include "llvm/Debugger/RuntimeInfo.h"
#include "llvm/Debugger/SourceLanguage.h"
#include "llvm/Debugger/SourceFile.h"
#include "llvm/Debugger/InferiorProcess.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/ADT/StringExtras.h"
#include <iostream>
#include <cstdlib>
using namespace llvm;
const SourceLanguage &CLIDebugger::getCurrentLanguage() const {
if (CurrentLanguage) {
return *CurrentLanguage;
} else if (Dbg.isProgramRunning()) {
const GlobalVariable *FuncDesc =
getRuntimeInfo().getCurrentFrame().getFunctionDesc();
return getProgramInfo().getFunction(FuncDesc).getSourceFile().getLanguage();
} else {
return SourceLanguage::getCFamilyInstance();
}
}
void CLIDebugger::startProgramRunning() {
eliminateRunInfo();
sys::PathWithStatus Program(Dbg.getProgramPath());
std::string Err;
const sys::FileStatus *Status = Program.getFileStatus(false, &Err);
if (!Status)
throw Err;
if (TheProgramInfo->getProgramTimeStamp() != Status->getTimestamp()) {
std::cout << "'" << Program << "' has changed; re-reading program.\n";
Dbg.unloadProgram();
delete TheProgramInfo;
TheProgramInfo = 0;
CurrentFile = 0;
Dbg.loadProgram(Program.toString());
TheProgramInfo = new ProgramInfo(Dbg.getProgram());
}
std::cout << "Starting program: " << Dbg.getProgramPath() << "\n";
Dbg.createProgram();
LastCurrentFrame = 0;
}
bool CLIDebugger::printSourceLine(unsigned LineNo) {
assert(CurrentFile && "There is no current source file to print!");
const char *LineStart, *LineEnd;
CurrentFile->getSourceLine(LineNo-1, LineStart, LineEnd);
if (LineStart == 0) return true;
std::cout << LineNo;
if (Dbg.isProgramRunning()) {
unsigned CurLineNo, CurColNo;
const SourceFileInfo *CurSFI;
getRuntimeInfo().getCurrentFrame().getSourceLocation(CurLineNo, CurColNo,
CurSFI);
if (CurLineNo == LineNo && CurrentFile == &CurSFI->getSourceText())
std::cout << " ->";
}
std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
return false;
}
void CLIDebugger::printProgramLocation(bool PrintLocation) {
assert(Dbg.isProgramLoaded() && Dbg.isProgramRunning() &&
"Error program is not loaded and running!");
StackFrame &SF = getRuntimeInfo().getCurrentFrame();
unsigned LineNo, ColNo;
const SourceFileInfo *FileDesc;
SF.getSourceLocation(LineNo, ColNo, FileDesc);
if (PrintLocation) {
if (const GlobalVariable *FuncDesc = SF.getFunctionDesc())
std::cout << getProgramInfo().getFunction(FuncDesc).getSymbolicName();
else
std::cout << "<unknown function>";
CurrentFile = &FileDesc->getSourceText();
std::cout << " at " << CurrentFile->getFilename() << ":" << LineNo;
if (ColNo) std::cout << ":" << ColNo;
std::cout << "\n";
}
if (printSourceLine(LineNo))
std::cout << "<could not load source file>\n";
else {
LineListedStart = LineNo-ListSize/2+1;
if ((int)LineListedStart < 1) LineListedStart = 1;
LineListedEnd = LineListedStart+1;
}
}
void CLIDebugger::eliminateRunInfo() {
delete TheRuntimeInfo;
TheRuntimeInfo = 0;
}
void CLIDebugger::programStoppedSuccessfully() {
assert(TheRuntimeInfo==0 && "Someone forgot to release the old RuntimeInfo!");
TheRuntimeInfo = new RuntimeInfo(TheProgramInfo, Dbg.getRunningProcess());
void *CurrentFrame = getRuntimeInfo().getCurrentFrame().getFrameID();
printProgramLocation(CurrentFrame != LastCurrentFrame);
LastCurrentFrame = CurrentFrame;
}
static unsigned getUnsignedIntegerOption(const char *Msg, std::string &Val,
bool isOnlyOption = true) {
std::string Tok = getToken(Val);
if (Tok.empty() || (isOnlyOption && !getToken(Val).empty()))
throw std::string(Msg) + " expects an unsigned integer argument.";
char *EndPtr;
unsigned Result = strtoul(Tok.c_str(), &EndPtr, 0);
if (EndPtr != Tok.c_str()+Tok.size())
throw std::string(Msg) + " expects an unsigned integer argument.";
return Result;
}
static unsigned
getOptionalUnsignedIntegerOption(const char *Msg, unsigned Default,
std::string &Val, bool isOnlyOption = true) {
std::string TokVal = getToken(Val);
if (TokVal.empty()) return Default;
Val = TokVal+Val;
return getUnsignedIntegerOption(Msg, Val, isOnlyOption);
}
void CLIDebugger::parseProgramOptions(std::string &Options) {
std::vector<std::string> Arguments;
for (std::string A = getToken(Options); !A.empty(); A = getToken(Options))
Arguments.push_back(A);
Dbg.setProgramArguments(Arguments.begin(), Arguments.end());
}
void CLIDebugger::fileCommand(std::string &Options) {
std::string Prog = getToken(Options);
if (!getToken(Options).empty())
throw "file command takes at most one argument.";
if (Dbg.isProgramRunning() &&
!askYesNo("A program is already loaded. Kill it?"))
return;
eliminateRunInfo();
delete TheProgramInfo;
TheProgramInfo = 0;
Dbg.unloadProgram();
CurrentFile = 0;
if (Prog.empty()) {
std::cout << "Unloaded program.\n";
} else {
std::cout << "Loading program... " << std::flush;
Dbg.loadProgram(Prog);
assert(Dbg.isProgramLoaded() &&
"loadProgram succeeded, but not program loaded!");
TheProgramInfo = new ProgramInfo(Dbg.getProgram());
std::cout << "successfully loaded '" << Dbg.getProgramPath() << "'!\n";
}
}
void CLIDebugger::createCommand(std::string &Options) {
if (!getToken(Options).empty())
throw "create command does not take any arguments.";
if (!Dbg.isProgramLoaded()) throw "No program loaded.";
if (Dbg.isProgramRunning() &&
!askYesNo("The program is already running. Restart from the beginning?"))
return;
startProgramRunning();
programStoppedSuccessfully();
}
void CLIDebugger::killCommand(std::string &Options) {
if (!getToken(Options).empty())
throw "kill command does not take any arguments.";
if (!Dbg.isProgramRunning())
throw "No program is currently being run.";
if (askYesNo("Kill the program being debugged?"))
Dbg.killProgram();
eliminateRunInfo();
}
void CLIDebugger::quitCommand(std::string &Options) {
if (!getToken(Options).empty())
throw "quit command does not take any arguments.";
if (Dbg.isProgramRunning() &&
!askYesNo("The program is running. Exit anyway?"))
return;
throw 0;
}
void CLIDebugger::runCommand(std::string &Options) {
if (!Dbg.isProgramLoaded()) throw "No program loaded.";
if (Dbg.isProgramRunning() &&
!askYesNo("The program is already running. Restart from the beginning?"))
return;
parseProgramOptions(Options);
eliminateRunInfo();
startProgramRunning();
Options = "";
contCommand(Options);
}
void CLIDebugger::contCommand(std::string &Options) {
if (!getToken(Options).empty()) throw "cont argument not supported yet.";
if (!Dbg.isProgramRunning()) throw "Program is not running.";
eliminateRunInfo();
Dbg.contProgram();
programStoppedSuccessfully();
}
void CLIDebugger::stepCommand(std::string &Options) {
if (!Dbg.isProgramRunning()) throw "Program is not running.";
unsigned Amount =
getOptionalUnsignedIntegerOption("'step' command", 1, Options);
eliminateRunInfo();
for (; Amount; --Amount)
Dbg.stepProgram();
programStoppedSuccessfully();
}
void CLIDebugger::nextCommand(std::string &Options) {
if (!Dbg.isProgramRunning()) throw "Program is not running.";
unsigned Amount =
getOptionalUnsignedIntegerOption("'next' command", 1, Options);
eliminateRunInfo();
for (; Amount; --Amount)
Dbg.nextProgram();
programStoppedSuccessfully();
}
void CLIDebugger::finishCommand(std::string &Options) {
if (!getToken(Options).empty())
throw "finish command does not take any arguments.";
if (!Dbg.isProgramRunning()) throw "Program is not running.";
void *CurrentFrame = getRuntimeInfo().getCurrentFrame().getFrameID();
eliminateRunInfo();
Dbg.finishProgram(CurrentFrame);
programStoppedSuccessfully();
}
void CLIDebugger::backtraceCommand(std::string &Options) {
if (!getToken(Options).empty())
throw "FIXME: bt command argument not implemented yet!";
RuntimeInfo &RI = getRuntimeInfo();
ProgramInfo &PI = getProgramInfo();
try {
for (unsigned i = 0; ; ++i) {
StackFrame &SF = RI.getStackFrame(i);
std::cout << "#" << i;
if (i == RI.getCurrentFrameIdx())
std::cout << " ->";
std::cout << "\t" << SF.getFrameID() << " in ";
if (const GlobalVariable *G = SF.getFunctionDesc())
std::cout << PI.getFunction(G).getSymbolicName();
unsigned LineNo, ColNo;
const SourceFileInfo *SFI;
SF.getSourceLocation(LineNo, ColNo, SFI);
if (!SFI->getBaseName().empty()) {
std::cout << " at " << SFI->getBaseName();
if (LineNo) {
std::cout << ":" << LineNo;
if (ColNo)
std::cout << ":" << ColNo;
}
}
std::cout << "\n";
}
} catch (...) {
}
}
void CLIDebugger::upCommand(std::string &Options) {
unsigned Num =
getOptionalUnsignedIntegerOption("'up' command", 1, Options);
RuntimeInfo &RI = getRuntimeInfo();
unsigned CurFrame = RI.getCurrentFrameIdx();
try {
RI.getStackFrame(CurFrame+Num);
} catch (...) {
if (Num == 1)
throw "Initial frame selected; you cannot go up.";
else
throw "Cannot go up " + utostr(Num) + " frames!";
}
RI.setCurrentFrameIdx(CurFrame+Num);
printProgramLocation();
}
void CLIDebugger::downCommand(std::string &Options) {
unsigned Num =
getOptionalUnsignedIntegerOption("'down' command", 1, Options);
RuntimeInfo &RI = getRuntimeInfo();
unsigned CurFrame = RI.getCurrentFrameIdx();
if (CurFrame < Num) {
if (Num == 1)
throw "Bottom (i.e., innermost) frame selected; you cannot go down.";
else
throw "Cannot go down " + utostr(Num) + " frames!";
}
RI.setCurrentFrameIdx(CurFrame-Num);
printProgramLocation();
}
void CLIDebugger::frameCommand(std::string &Options) {
RuntimeInfo &RI = getRuntimeInfo();
unsigned CurFrame = RI.getCurrentFrameIdx();
unsigned Num =
getOptionalUnsignedIntegerOption("'frame' command", CurFrame, Options);
RI.getStackFrame(Num);
RI.setCurrentFrameIdx(Num);
printProgramLocation();
}
void CLIDebugger::breakCommand(std::string &Options) {
const SourceFile *File;
unsigned LineNo;
std::string Option = getToken(Options); if (!Option.empty()) {
Options = Option + Options;
parseLineSpec(Options, File, LineNo);
} else {
throw "FIXME: breaking at the current location is not implemented yet!";
}
if (!File) File = CurrentFile;
if (File == 0)
throw "Unknown file to place breakpoint!";
std::cerr << "Break: " << File->getFilename() << ":" << LineNo << "\n";
throw "breakpoints not implemented yet!";
}
void CLIDebugger::infoCommand(std::string &Options) {
std::string What = getToken(Options);
if (What.empty() || !getToken(Options).empty()){
std::string infoStr("info");
helpCommand(infoStr);
return;
}
if (What == "frame") {
} else if (What == "functions") {
const std::map<const GlobalVariable*, SourceFunctionInfo*> &Functions
= getProgramInfo().getSourceFunctions();
std::cout << "All defined functions:\n";
for (std::map<const GlobalVariable*, SourceFunctionInfo*>::const_iterator
I = Functions.begin(), E = Functions.end(); I != E; ++I) {
std::cout << I->second->getSymbolicName() << "\n";
}
} else if (What == "source") {
if (CurrentFile == 0)
throw "No current source file.";
const SourceFileInfo &SF =
getProgramInfo().getSourceFile(CurrentFile->getDescriptor());
std::cout << "Current source file is: " << SF.getBaseName() << "\n"
<< "Compilation directory is: " << SF.getDirectory() << "\n";
if (unsigned NL = CurrentFile->getNumLines())
std::cout << "Located in: " << CurrentFile->getFilename() << "\n"
<< "Contains " << NL << " lines\n";
else
std::cout << "Could not find source file.\n";
std::cout << "Source language is "
<< SF.getLanguage().getSourceLanguageName() << "\n";
} else if (What == "sources") {
const std::map<const GlobalVariable*, SourceFileInfo*> &SourceFiles =
getProgramInfo().getSourceFiles();
std::cout << "Source files for the program:\n";
for (std::map<const GlobalVariable*, SourceFileInfo*>::const_iterator I =
SourceFiles.begin(), E = SourceFiles.end(); I != E;) {
std::cout << I->second->getDirectory() << "/"
<< I->second->getBaseName();
++I;
if (I != E) std::cout << ", ";
}
std::cout << "\n";
} else if (What == "target") {
std::cout << Dbg.getRunningProcess().getStatus();
} else {
if (getCurrentLanguage().printInfo(What))
return;
throw "Unknown info command '" + What + "'. Try 'help info'.";
}
}
void CLIDebugger::parseLineSpec(std::string &LineSpec,
const SourceFile *&SourceFile,
unsigned &LineNo) {
SourceFile = 0;
LineNo = 0;
std::string FirstPart = getToken(LineSpec, ":");
std::string SecondPart = getToken(LineSpec, ":");
if (!getToken(LineSpec).empty()) throw "Malformed line specification!";
if (SecondPart.empty()) {
if (FirstPart.empty()) throw "Malformed line specification!";
if (FirstPart[0] == '+') {
FirstPart.erase(FirstPart.begin(), FirstPart.begin()+1);
LineNo = LineListedEnd +
getUnsignedIntegerOption("Line specifier '+'", FirstPart);
} else if (FirstPart[0] == '-') {
FirstPart.erase(FirstPart.begin(), FirstPart.begin()+1);
LineNo = LineListedEnd -
getUnsignedIntegerOption("Line specifier '-'", FirstPart);
if ((int)LineNo < 1) LineNo = 1;
} else if (FirstPart[0] == '*') {
throw "Address expressions not supported as source locations!";
} else {
std::string Saved = FirstPart;
try {
LineNo = getUnsignedIntegerOption("", Saved);
} catch (...) {
std::string Name = getToken(FirstPart);
if (!getToken(FirstPart).empty())
throw "Extra junk in line specifier after '" + Name + "'.";
SourceFunctionInfo *SFI =
getCurrentLanguage().lookupFunction(Name, getProgramInfo(),
TheRuntimeInfo);
if (SFI == 0)
throw "Unknown identifier '" + Name + "'.";
unsigned L, C;
SFI->getSourceLocation(L, C);
if (L == 0) throw "Could not locate '" + Name + "'!";
LineNo = L;
SourceFile = &SFI->getSourceFile().getSourceText();
return;
}
}
} else {
std::string SourceFilename = getToken(FirstPart);
if (!getToken(FirstPart).empty())
throw "Invalid filename qualified source location!";
std::string Saved = SecondPart;
try {
LineNo = getUnsignedIntegerOption("", Saved);
} catch (...) {
throw "FIXME: Filename qualified function names are not support "
"as line specifiers yet!";
}
SourceFile =&getProgramInfo().getSourceFile(SourceFilename).getSourceText();
}
}
void CLIDebugger::listCommand(std::string &Options) {
if (!Dbg.isProgramLoaded())
throw "No program is loaded. Use the 'file' command.";
Options += " ";
std::string FirstLineSpec = getToken(Options, ",");
std::string SecondLineSpec = getToken(Options, ",");
if (!getToken(Options, ",").empty())
throw "list command only expects two source location specifiers!";
unsigned StartLine = 0, EndLine = 0;
if (SecondLineSpec.empty()) { std::string TmpSpec = FirstLineSpec;
std::string Tok = getToken(TmpSpec);
if (getToken(TmpSpec).empty() && (Tok == "" || Tok == "+" || Tok == "-")) {
if (Tok == "+" || Tok == "") {
StartLine = LineListedEnd;
EndLine = StartLine + ListSize;
} else {
assert(Tok == "-");
StartLine = LineListedStart-ListSize;
EndLine = LineListedStart;
if ((int)StartLine <= 0) StartLine = 1;
}
} else {
const SourceFile *File;
unsigned LineNo;
parseLineSpec(FirstLineSpec, File, LineNo);
if (File != 0) CurrentFile = File;
StartLine = LineNo - (ListSize+1)/2;
if ((int)StartLine <= 0) StartLine = 1;
EndLine = StartLine + ListSize;
}
} else {
const SourceFile *StartFile, *EndFile;
unsigned StartLineNo, EndLineNo;
parseLineSpec(FirstLineSpec, StartFile, StartLineNo);
unsigned SavedLLE = LineListedEnd;
LineListedEnd = StartLineNo;
try {
parseLineSpec(SecondLineSpec, EndFile, EndLineNo);
} catch (...) {
LineListedEnd = SavedLLE;
throw;
}
if (EndFile == 0) EndFile = StartFile;
if (StartFile != EndFile)
throw "Start and end line specifiers are in different files!";
CurrentFile = StartFile;
StartLine = StartLineNo;
EndLine = EndLineNo+1;
}
assert((int)StartLine > 0 && (int)EndLine > 0 && StartLine <= EndLine &&
"Error reading line specifiers!");
if (CurrentFile == 0)
throw "There is no current file to list.";
LineListedStart = StartLine;
LineListedEnd = StartLine;
for (unsigned LineNo = StartLine; LineNo != EndLine; ++LineNo) {
if (printSourceLine(LineNo))
break;
LineListedEnd = LineNo+1;
}
if (LineListedEnd == StartLine) {
const char *LineStart, *LineEnd;
CurrentFile->getSourceLine(0, LineStart, LineEnd);
if (LineStart == 0)
throw "Could not load source file '" + CurrentFile->getFilename() + "'!";
else
std::cout << "<end of file>\n";
}
}
void CLIDebugger::setCommand(std::string &Options) {
std::string What = getToken(Options);
if (What.empty())
throw "set command expects at least two arguments.";
if (What == "args") {
parseProgramOptions(Options);
} else if (What == "language") {
std::string Lang = getToken(Options);
if (!getToken(Options).empty())
throw "set language expects one argument at most.";
if (Lang == "") {
std::cout << "The currently understood settings are:\n\n"
<< "local or auto Automatic setting based on source file\n"
<< "c Use the C language\n"
<< "c++ Use the C++ language\n"
<< "unknown Use when source language is not supported\n";
} else if (Lang == "local" || Lang == "auto") {
CurrentLanguage = 0;
} else if (Lang == "c") {
CurrentLanguage = &SourceLanguage::getCFamilyInstance();
} else if (Lang == "c++") {
CurrentLanguage = &SourceLanguage::getCPlusPlusInstance();
} else if (Lang == "unknown") {
CurrentLanguage = &SourceLanguage::getUnknownLanguageInstance();
} else {
throw "Unknown language '" + Lang + "'.";
}
} else if (What == "listsize") {
ListSize = getUnsignedIntegerOption("'set prompt' command", Options);
} else if (What == "prompt") {
Prompt = getToken(Options); Prompt += Options; } else {
throw "Don't know how to set '" + What + "'!";
}
}
void CLIDebugger::showCommand(std::string &Options) {
std::string What = getToken(Options);
if (What.empty() || !getToken(Options).empty())
throw "show command expects one argument.";
if (What == "args") {
std::cout << "Argument list to give program when started is \"";
for (unsigned i = 0, e = Dbg.getNumProgramArguments(); i != e; ++i)
std::cout << (i ? " " : "") << Dbg.getProgramArgument(i);
std::cout << "\"\n";
} else if (What == "language") {
std::cout << "The current source language is '";
if (CurrentLanguage)
std::cout << CurrentLanguage->getSourceLanguageName();
else
std::cout << "auto; currently "
<< getCurrentLanguage().getSourceLanguageName();
std::cout << "'.\n";
} else if (What == "listsize") {
std::cout << "Number of source lines llvm-db will list by default is "
<< ListSize << ".\n";
} else if (What == "prompt") {
std::cout << "llvm-db's prompt is \"" << Prompt << "\".\n";
} else {
throw "Unknown show command '" + What + "'. Try 'help show'.";
}
}
void CLIDebugger::helpCommand(std::string &Options) {
std::string Command = getToken(Options);
if (!getToken(Options).empty())
throw "help command takes at most one argument.";
if (!Command.empty()) {
CLICommand *C = getCommand(Command);
std::cout << C->getShortHelp() << ".\n" << C->getLongHelp();
const std::vector<std::string> &Names = C->getOptionNames();
if (Names.size() > 1) {
std::cout << "The '" << Command << "' command is known as: '"
<< Names[0] << "'";
for (unsigned i = 1, e = Names.size(); i != e; ++i)
std::cout << ", '" << Names[i] << "'";
std::cout << "\n";
}
} else {
unsigned MaxSize = 0;
for (std::map<std::string, CLICommand*>::iterator I = CommandTable.begin(),
E = CommandTable.end(); I != E; ++I)
if (I->first.size() > MaxSize &&
I->first == I->second->getPrimaryOptionName())
MaxSize = I->first.size();
for (std::map<std::string, CLICommand*>::iterator I = CommandTable.begin(),
E = CommandTable.end(); I != E; ++I)
if (I->first == I->second->getPrimaryOptionName())
std::cout << I->first << std::string(MaxSize - I->first.size(), ' ')
<< " - " << I->second->getShortHelp() << "\n";
}
}