aboutsummaryrefslogtreecommitdiff
path: root/lib/ExecutionEngine/Interpreter/UserInput.cpp
blob: a24b31175063d149ca1b0694e2035c585db7cd70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//===-- UserInput.cpp - Interpreter Input Loop support --------------------===//
// 
//  This file implements the interpreter Input I/O loop.
//
//===----------------------------------------------------------------------===//

#include "Interpreter.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Transforms/Linker.h"
#include <algorithm>

enum CommandID {
  Quit, Help,                                 // Basics
  Print, Info, List, StackTrace, Up, Down,    // Inspection
  Next, Step, Run, Finish, Call,              // Control flow changes
  Break, Watch,                               // Debugging
  Load, Flush
};

// CommandTable - Build a lookup table for the commands available to the user...
static struct CommandTableElement {
  const char *Name;
  enum CommandID CID;

  inline bool operator<(const CommandTableElement &E) const {
    return string(Name) < string(E.Name);
  }
  inline bool operator==(const string &S) const { 
    return string(Name) == S;
  }
} CommandTable[] = {
  { "quit"     , Quit       }, { "q", Quit }, { "", Quit }, // Empty str = eof
  { "help"     , Help       }, { "h", Help },

  { "print"    , Print      }, { "p", Print },
  { "list"     , List       },
  { "info"     , Info       },
  { "backtrace", StackTrace }, { "bt", StackTrace }, { "where", StackTrace },
  { "up"       , Up         },
  { "down"     , Down       },

  { "next"     , Next       }, { "n", Next },
  { "step"     , Step       }, { "s", Step },
  { "run"      , Run        },
  { "finish"   , Finish     },
  { "call"     , Call       },

  { "break"    , Break      }, { "b", Break },
  { "watch"    , Watch      },

  { "load"     , Load       },
  { "flush"    , Flush      },
};
static CommandTableElement *CommandTableEnd = 
   CommandTable+sizeof(CommandTable)/sizeof(CommandTable[0]);


//===----------------------------------------------------------------------===//
// handleUserInput - Enter the input loop for the interpreter.  This function
// returns when the user quits the interpreter.
//
void Interpreter::handleUserInput() {
  bool UserQuit = false;

  // Sort the table...
  sort(CommandTable, CommandTableEnd);

  // Print the instruction that we are stopped at...
  printCurrentInstruction();

  do {
    string Command;
    cout << "lli> " << flush;
    cin >> Command;

    CommandTableElement *E = find(CommandTable, CommandTableEnd, Command);

    if (E == CommandTableEnd) {
      cout << "Error: '" << Command << "' not recognized!\n";
      continue;
    }

    switch (E->CID) {
    case Quit:       UserQuit = true;   break;
    case Load:
      cin >> Command;
      loadModule(Command);
      break;
    case Flush: flushModule(); break;
    case Print:
      cin >> Command;
      print(Command);
      break;
    case Info:
      cin >> Command;
      infoValue(Command);
      break;
     
    case List:       list();            break;
    case StackTrace: printStackTrace(); break;
    case Up: 
      if (CurFrame > 0) --CurFrame;
      else cout << "Error: Already at root of stack!\n";
      break;
    case Down:
      if ((unsigned)CurFrame < ECStack.size()-1) ++CurFrame;
      else cout << "Error: Already at bottom of stack!\n";
      break;
    case Next:       nextInstruction(); break;
    case Step:       stepInstruction(); break;
    case Run:        run();             break;
    case Finish:     finish();          break;
    case Call:
      cin >> Command;
      callMethod(Command);    // Enter the specified method
      finish();               // Run until it's complete
      break;

    default:
      cout << "Command '" << Command << "' unimplemented!\n";
      break;
    }

  } while (!UserQuit);
}

//===----------------------------------------------------------------------===//
// loadModule - Load a new module to execute...
//
void Interpreter::loadModule(const string &Filename) {
  string ErrorMsg;
  if (CurMod && !flushModule()) return;  // Kill current execution

  CurMod = ParseBytecodeFile(Filename, &ErrorMsg);
  if (CurMod == 0) {
    cout << "Error parsing '" << Filename << "': No module loaded: "
         << ErrorMsg << "\n";
    return;
  }

  string RuntimeLib = getCurrentExecutablePath() + "/RuntimeLib.bc";
  if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {
    if (LinkModules(CurMod, SupportLib, &ErrorMsg))
      cerr << "Error Linking runtime library into current module: "
           << ErrorMsg << endl;
  } else {
    cerr << "Error loading runtime library '"+RuntimeLib+"': "
         << ErrorMsg << "\n";
  }
}


//===----------------------------------------------------------------------===//
// flushModule - Return true if the current program has been unloaded.
//
bool Interpreter::flushModule() {
  if (CurMod == 0) {
    cout << "Error flushing: No module loaded!\n";
    return false;
  }

  if (!ECStack.empty()) {
    // TODO: if use is not sure, return false
    cout << "Killing current execution!\n";
    ECStack.clear();
    CurFrame = -1;
  }

  delete CurMod;
  CurMod = 0;
  ExitCode = 0;
  return true;
}

//===----------------------------------------------------------------------===//
// setBreakpoint - Enable a breakpoint at the specified location
//
void Interpreter::setBreakpoint(const string &Name) {
  Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
  // TODO: Set a breakpoint on PickedVal
}

//===----------------------------------------------------------------------===//
// callMethod - Enter the specified method...
//
bool Interpreter::callMethod(const string &Name) {
  vector<Value*> Options = LookupMatchingNames(Name);

  for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
    if (!isa<Method>(Options[i])) {
      Options.erase(Options.begin()+i);
      --i;
    }
  }

  Value *PickedMeth = ChooseOneOption(Name, Options);
  if (PickedMeth == 0)
    return true;

  Method *M = cast<Method>(PickedMeth);

  vector<GenericValue> Args;
  // TODO, get args from user...

  callMethod(M, Args);  // Start executing it...

  // Reset the current frame location to the top of stack
  CurFrame = ECStack.size()-1;

  return false;
}

static void *CreateArgv(const vector<string> &InputArgv) {
  // Pointers are 64 bits...
  uint64_t *Result = new uint64_t[InputArgv.size()+1];

  for (unsigned i = 0; i < InputArgv.size(); ++i) {
    unsigned Size = InputArgv[i].size()+1;
    char *Dest = new char[Size];
    copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
    Dest[Size-1] = 0;
    Result[i] = (uint64_t)Dest;
  }

  Result[InputArgv.size()] = 0;
  return Result;
}


// callMainMethod - This is a nasty gross hack that will dissapear when
// callMethod can parse command line options and stuff for us.
//
bool Interpreter::callMainMethod(const string &Name,
                                 const vector<string> &InputArgv) {
  vector<Value*> Options = LookupMatchingNames(Name);

  for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
    if (!isa<Method>(Options[i])) {
      Options.erase(Options.begin()+i);
      --i;
    }
  }

  Value *PickedMeth = ChooseOneOption(Name, Options);
  if (PickedMeth == 0)
    return true;

  Method *M = cast<Method>(PickedMeth);
  const MethodType *MT = M->getMethodType();

  vector<GenericValue> Args;
  switch (MT->getParamTypes().size()) {
  default:
    cout << "Unknown number of arguments to synthesize for '" << Name << "'!\n";
    return true;
  case 2: {
    PointerType *SPP = PointerType::get(PointerType::get(Type::SByteTy));
    if (MT->getParamTypes()[1] != SPP) {
      cout << "Second argument of '" << Name << "' should have type: '"
           << SPP->getDescription() << "'!\n";
      return true;
    }

    GenericValue GV; GV.PointerVal = (uint64_t)CreateArgv(InputArgv);
    Args.push_back(GV);
  }
    // fallthrough
  case 1:
    if (!MT->getParamTypes()[0]->isIntegral()) {
      cout << "First argument of '" << Name << "' should be integral!\n";
      return true;
    } else {
      GenericValue GV; GV.UIntVal = InputArgv.size();
      Args.insert(Args.begin(), GV);
    }
    // fallthrough
  case 0:
    break;
  }

  callMethod(M, Args);  // Start executing it...

  // Reset the current frame location to the top of stack
  CurFrame = ECStack.size()-1;

  return false;
}