openMSX
Interpreter.cc
Go to the documentation of this file.
1 #include "Interpreter.hh"
2 #include "Command.hh"
3 #include "TclObject.hh"
4 #include "CommandException.hh"
6 #include "MSXMotherBoard.hh"
7 #include "Setting.hh"
8 #include "InterpreterOutput.hh"
9 #include "MSXCPUInterface.hh"
10 #include "FileOperations.hh"
11 #include "ranges.hh"
12 #include "span.hh"
13 #include "stl.hh"
14 #include "unreachable.hh"
15 #include <iostream>
16 #include <utility>
17 #include <vector>
18 #include <cstdint>
19 //#include <tk.h>
20 
21 using std::string;
22 using std::vector;
23 
24 namespace openmsx {
25 
26 // See comments in traceProc()
27 static std::vector<std::pair<uintptr_t, BaseSetting*>> traces; // sorted on first
28 static uintptr_t traceCount = 0;
29 
30 
31 static int dummyClose(ClientData /*instanceData*/, Tcl_Interp* /*interp*/)
32 {
33  return 0;
34 }
35 static int dummyInput(ClientData /*instanceData*/, char* /*buf*/,
36  int /*bufSize*/, int* /*errorCodePtr*/)
37 {
38  return 0;
39 }
40 static void dummyWatch(ClientData /*instanceData*/, int /*mask*/)
41 {
42 }
43 static int dummyGetHandle(ClientData /*instanceData*/, int /*direction*/,
44  ClientData* /*handlePtr*/)
45 {
46  return TCL_ERROR;
47 }
48 Tcl_ChannelType Interpreter::channelType = {
49  const_cast<char*>("openMSX console"),// Type name
50  nullptr, // Always non-blocking
51  dummyClose, // Close proc
52  dummyInput, // Input proc
53  Interpreter::outputProc, // Output proc
54  nullptr, // Seek proc
55  nullptr, // Set option proc
56  nullptr, // Get option proc
57  dummyWatch, // Watch for events on console
58  dummyGetHandle, // Get a handle from the device
59  nullptr, // Tcl_DriverClose2Proc
60  nullptr, // Tcl_DriverBlockModeProc
61  nullptr, // Tcl_DriverFlushProc
62  nullptr, // Tcl_DriverHandlerProc
63  nullptr, // Tcl_DriverWideSeekProc
64  nullptr, // Tcl_DriverThreadActionProc
65  nullptr, // Tcl_DriverTruncateProc
66 };
67 
68 void Interpreter::init(const char* programName)
69 {
70  Tcl_FindExecutable(programName);
71 }
72 
74 {
75  interp = Tcl_CreateInterp();
76  Tcl_Preserve(interp);
77 
78  // TODO need to investigate this: doesn't work on windows
79  /*
80  if (Tcl_Init(interp) != TCL_OK) {
81  std::cout << "Tcl_Init: " << interp->result << '\n';
82  }
83  if (Tk_Init(interp) != TCL_OK) {
84  std::cout << "Tk_Init error: " << interp->result << '\n';
85  }
86  if (Tcl_Eval(interp, "wm withdraw .") != TCL_OK) {
87  std::cout << "wm withdraw error: " << interp->result << '\n';
88  }
89  */
90 
91  Tcl_Channel channel = Tcl_CreateChannel(&channelType,
92  "openMSX console", this, TCL_WRITABLE);
93  if (channel) {
94  Tcl_SetChannelOption(interp, channel, "-translation", "binary");
95  Tcl_SetChannelOption(interp, channel, "-buffering", "line");
96  Tcl_SetChannelOption(interp, channel, "-encoding", "utf-8");
97  }
98  Tcl_SetStdChannel(channel, TCL_STDOUT);
99 
100  setVariable(TclObject("env(OPENMSX_USER_DATA)"),
102  setVariable(TclObject("env(OPENMSX_SYSTEM_DATA)"),
104 }
105 
107 {
108  // see comment in MSXCPUInterface::cleanup()
110 
111  if (!Tcl_InterpDeleted(interp)) {
112  Tcl_DeleteInterp(interp);
113  }
114  Tcl_Release(interp);
115 
116  // Tcl_Finalize() should only be called once for the whole application
117  // tcl8.6 checks for this (tcl8.5 did not).
118  // Normally we only create/destroy exactly one Interpreter object for
119  // openMSX, and then simply calling Tcl_Finalize() here is fine. Though
120  // when running unittest we do create/destroy multiple Interpreter's.
121  // Another option is to not call Tcl_Finalize(), but that leaves some
122  // memory allocated, and makes memory-leak checkers report more errors.
123  static bool scheduled = false;
124  if (!scheduled) {
125  scheduled = true;
126  atexit(Tcl_Finalize);
127  }
128 }
129 
130 int Interpreter::outputProc(ClientData clientData, const char* buf,
131  int toWrite, int* /*errorCodePtr*/)
132 {
133  try {
134  auto* output = static_cast<Interpreter*>(clientData)->output;
135  std::string_view text(buf, toWrite);
136  if (!text.empty() && output) {
137  output->output(text);
138  }
139  } catch (...) {
140  UNREACHABLE; // we cannot let exceptions pass through Tcl
141  }
142  return toWrite;
143 }
144 
145 void Interpreter::registerCommand(const string& name, Command& command)
146 {
147  auto token = Tcl_CreateObjCommand(
148  interp, name.c_str(), commandProc,
149  static_cast<ClientData>(&command), nullptr);
150  command.setToken(token);
151 }
152 
154 {
155  Tcl_DeleteCommandFromToken(interp, static_cast<Tcl_Command>(command.getToken()));
156 }
157 
158 int Interpreter::commandProc(ClientData clientData, Tcl_Interp* interp,
159  int objc, Tcl_Obj* const objv[])
160 {
161  try {
162  auto& command = *static_cast<Command*>(clientData);
163  span<const TclObject> tokens(
164  reinterpret_cast<TclObject*>(const_cast<Tcl_Obj**>(objv)),
165  objc);
166  int res = TCL_OK;
167  TclObject result;
168  try {
169  if (!command.isAllowedInEmptyMachine()) {
170  if (auto controller =
171  dynamic_cast<MSXCommandController*>(
172  &command.getCommandController())) {
173  if (!controller->getMSXMotherBoard().getMachineConfig()) {
174  throw CommandException(
175  "Can't execute command in empty machine");
176  }
177  }
178  }
179  command.execute(tokens, result);
180  } catch (MSXException& e) {
181  result = e.getMessage();
182  res = TCL_ERROR;
183  }
184  Tcl_SetObjResult(interp, result.getTclObject());
185  return res;
186  } catch (...) {
187  UNREACHABLE; // we cannot let exceptions pass through Tcl
188  return TCL_ERROR;
189  }
190 }
191 
192 // Returns
193 // - build-in Tcl commands
194 // - openmsx commands
195 // - user-defined procs
197 {
198  return execute("openmsx::all_command_names");
199 }
200 
201 bool Interpreter::isComplete(const string& command) const
202 {
203  return Tcl_CommandComplete(command.c_str()) != 0;
204 }
205 
206 TclObject Interpreter::execute(const string& command)
207 {
208  int success = Tcl_Eval(interp, command.c_str());
209  if (success != TCL_OK) {
210  throw CommandException(Tcl_GetStringResult(interp));
211  }
212  return TclObject(Tcl_GetObjResult(interp));
213 }
214 
216 {
217  int success = Tcl_EvalFile(interp, filename.c_str());
218  if (success != TCL_OK) {
219  throw CommandException(Tcl_GetStringResult(interp));
220  }
221  return TclObject(Tcl_GetObjResult(interp));
222 }
223 
224 static void setVar(Tcl_Interp* interp, const TclObject& name, const TclObject& value)
225 {
226  if (!Tcl_ObjSetVar2(interp, name.getTclObjectNonConst(), nullptr,
227  value.getTclObjectNonConst(),
228  TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG)) {
229  // might contain error message of a trace proc
230  std::cerr << Tcl_GetStringResult(interp) << '\n';
231  }
232 }
233 static Tcl_Obj* getVar(Tcl_Interp* interp, const TclObject& name)
234 {
235  return Tcl_ObjGetVar2(interp, name.getTclObjectNonConst(), nullptr,
236  TCL_GLOBAL_ONLY);
237 }
238 
239 void Interpreter::setVariable(const TclObject& name, const TclObject& value)
240 {
241  if (!Tcl_ObjSetVar2(interp, name.getTclObjectNonConst(), nullptr,
242  value.getTclObjectNonConst(),
243  TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG)) {
244  throw CommandException(Tcl_GetStringResult(interp));
245  }
246 }
247 
248 void Interpreter::unsetVariable(const char* name)
249 {
250  Tcl_UnsetVar(interp, name, TCL_GLOBAL_ONLY);
251 }
252 
253 static TclObject getSafeValue(BaseSetting& setting)
254 {
255  try {
256  return setting.getValue();
257  } catch (MSXException&) {
258  return TclObject(0); // 'safe' value, see comment in registerSetting()
259  }
260 }
262 {
263  const auto& name = variable.getFullNameObj();
264  if (Tcl_Obj* tclVarValue = getVar(interp, name)) {
265  // Tcl var already existed, use this value
266  try {
267  variable.setValueDirect(TclObject(tclVarValue));
268  } catch (MSXException&) {
269  // Ignore: can happen in case of proxy settings when
270  // the current machine doesn't have this setting.
271  // E.g.
272  // (start with cbios machine)
273  // set renshaturbo 0
274  // create_machine
275  // machine2::load_machine Panasonic_FS-A1GT
276  }
277  } else {
278  // define Tcl var
279  setVariable(name, getSafeValue(variable));
280  }
281 
282  // The call setVariable() above can already trigger traces on this
283  // variable (in Tcl it's possible to already set traces on a variable
284  // before that variable is defined). We didn't yet set a trace on it
285  // ourselves. So for example on proxy-settings we don't yet delegate
286  // read/writes to the actual setting. This means that inside the trace
287  // callback we see the value set above instead of the 'actual' value.
288  //
289  // This scenario can be triggered in the load_icons script by
290  // executing the following commands (interactively):
291  // delete_machine machine1
292  // create_machine
293  // machine2::load_machine msx2
294  //
295  // Before changing the 'safe-value' (see getSafeValue()) to '0',
296  // this gave errors because the load_icons script didn't expect to see
297  // 'proxy' (the old 'safe-value') as value.
298  //
299  // The current solution (choosing '0' as safe value) is not ideal, but
300  // good enough for now.
301  //
302  // A possible better solution is to move Tcl_TraceVar() before
303  // setVariable(), I did an initial attempt but there were some
304  // problems. TODO investigate this further.
305 
306  uintptr_t traceID = traceCount++;
307  traces.emplace_back(traceID, &variable); // still in sorted order
308  Tcl_TraceVar(interp, name.getString().data(), // 0-terminated
309  TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS,
310  traceProc, reinterpret_cast<ClientData>(traceID));
311 }
312 
314 {
315  auto it = rfind_if_unguarded(traces, EqualTupleValue<1>(&variable));
316  uintptr_t traceID = it->first;
317  traces.erase(it);
318 
319  const char* name = variable.getFullName().data(); // 0-terminated
320  Tcl_UntraceVar(interp, name,
321  TCL_TRACE_READS | TCL_TRACE_WRITES | TCL_TRACE_UNSETS,
322  traceProc, reinterpret_cast<ClientData>(traceID));
323  unsetVariable(name);
324 }
325 
326 static BaseSetting* getTraceSetting(uintptr_t traceID)
327 {
328  auto it = ranges::lower_bound(traces, traceID, LessTupleElement<0>());
329  return ((it != end(traces)) && (it->first == traceID))
330  ? it->second : nullptr;
331 }
332 
333 #ifndef NDEBUG
334 static std::string_view removeColonColon(std::string_view s)
335 {
336  if (StringOp::startsWith(s, "::")) s.remove_prefix(2);
337  return s;
338 }
339 #endif
340 
341 char* Interpreter::traceProc(ClientData clientData, Tcl_Interp* interp,
342  const char* part1, const char* /*part2*/, int flags)
343 {
344  try {
345  // Lookup Setting object that belongs to this Tcl variable.
346  //
347  // In a previous implementation we passed this object directly
348  // as the clientData. However this went wrong in the following
349  // scenario:
350  //
351  // proc foo {} { carta eject ; carta spmanbow.rom }
352  // bind Q foo
353  // [press Q twice]
354  //
355  // The problem is that when a SCC cartridge is removed, we
356  // delete several settings (e.g. SCC_ch1_mute). While deleting
357  // a setting we unset the corresponsing Tcl variable (see
358  // unregisterSetting() above), this in turn triggers a
359  // TCL_TRACE_UNSET callback (this function). To prevent this
360  // callback from triggering we first remove the trace before
361  // unsetting the variable. However it seems when a setting is
362  // deleted from within an active Tcl proc (like in the example
363  // above), the callback is anyway triggered, but only at the
364  // end of the proc (so in the foo proc above, the settings
365  // are deleted after the first statement, but the callbacks
366  // only happen after the second statement). By that time the
367  // Setting object is already deleted and the callback function
368  // works on a deleted object.
369  //
370  // To prevent this we don't anymore pass a pointer to the
371  // Setting object as clientData, but we lookup the Setting in
372  // a map. If the Setting was deleted, we won't find it anymore
373  // in the map and return.
374 
375  auto traceID = reinterpret_cast<uintptr_t>(clientData);
376  auto* variable = getTraceSetting(traceID);
377  if (!variable) return nullptr;
378 
379  const TclObject& part1Obj = variable->getFullNameObj();
380  assert(removeColonColon(part1) == removeColonColon(part1Obj.getString()));
381 
382  static string static_string;
383  if (flags & TCL_TRACE_READS) {
384  try {
385  setVar(interp, part1Obj, variable->getValue());
386  } catch (MSXException& e) {
387  static_string = std::move(e).getMessage();
388  return const_cast<char*>(static_string.c_str());
389  }
390  }
391  if (flags & TCL_TRACE_WRITES) {
392  try {
393  Tcl_Obj* v = getVar(interp, part1Obj);
394  TclObject newValue(v ? v : Tcl_NewObj());
395  variable->setValueDirect(newValue);
396  const TclObject& newValue2 = variable->getValue();
397  if (newValue != newValue2) {
398  setVar(interp, part1Obj, newValue2);
399  }
400  } catch (MSXException& e) {
401  setVar(interp, part1Obj, getSafeValue(*variable));
402  static_string = std::move(e).getMessage();
403  return const_cast<char*>(static_string.c_str());
404  }
405  }
406  if (flags & TCL_TRACE_UNSETS) {
407  try {
408  // note we cannot use restoreDefault(), because
409  // that goes via Tcl and the Tcl variable
410  // doesn't exist at this point
411  variable->setValueDirect(TclObject(
412  variable->getRestoreValue()));
413  } catch (MSXException&) {
414  // for some reason default value is not valid ATM,
415  // keep current value (happened for videosource
416  // setting before turning on (set power on) the
417  // MSX machine)
418  }
419  setVar(interp, part1Obj, getSafeValue(*variable));
420  Tcl_TraceVar(interp, part1, TCL_TRACE_READS |
421  TCL_TRACE_WRITES | TCL_TRACE_UNSETS,
422  traceProc,
423  reinterpret_cast<ClientData>(traceID));
424  }
425  } catch (...) {
426  UNREACHABLE; // we cannot let exceptions pass through Tcl
427  }
428  return nullptr;
429 }
430 
431 void Interpreter::createNamespace(const std::string& name)
432 {
433  execute(strCat("namespace eval ", name, " {}"));
434 }
435 
436 void Interpreter::deleteNamespace(const std::string& name)
437 {
438  execute("namespace delete " + name);
439 }
440 
442 {
443  //Tcl_ServiceAll();
444  Tcl_DoOneEvent(TCL_DONT_WAIT);
445 }
446 
447 TclParser Interpreter::parse(std::string_view command)
448 {
449  return TclParser(interp, command);
450 }
451 
452 void Interpreter::wrongNumArgs(unsigned argc, span<const TclObject> tokens, const char* message)
453 {
454  assert(argc <= tokens.size());
455  Tcl_WrongNumArgs(interp, argc, reinterpret_cast<Tcl_Obj* const*>(tokens.data()), message);
456  // not efficient, but anyway on an error path
457  throw CommandException(Tcl_GetStringResult(interp));
458 }
459 
460 } // namespace openmsx
const TclObject & getFullNameObj() const
Get the name of this setting.
Definition: Setting.hh:33
const std::string & getMessage() const &
Definition: MSXException.hh:23
void registerCommand(const std::string &name, Command &command)
Definition: Interpreter.cc:145
virtual const TclObject & getValue() const =0
Get current value as a TclObject.
TclObject executeFile(const std::string &filename)
Definition: Interpreter.cc:215
void init(const char *programName)
Definition: Interpreter.cc:68
void deleteNamespace(const std::string &name)
Delete the global namespace with given name.
Definition: Interpreter.cc:436
Definition: span.hh:34
string getSystemDataDir()
Get system directory.
bool startsWith(string_view total, string_view part)
Definition: StringOp.cc:71
Tcl_Obj * getTclObject()
Definition: TclObject.hh:117
Tcl_Obj * getTclObjectNonConst() const
Definition: TclObject.hh:118
void wrongNumArgs(unsigned argc, span< const TclObject > tokens, const char *message)
Definition: Interpreter.cc:452
constexpr const char *const filename
virtual void output(std::string_view text)=0
string getUserDataDir()
Get the openMSX data dir in the user&#39;s home directory.
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
void unsetVariable(const char *name)
Definition: Interpreter.cc:248
std::string_view getString() const
Definition: TclObject.cc:102
TclParser parse(std::string_view command)
Definition: Interpreter.cc:447
void createNamespace(const std::string &name)
Create the global namespace with given name.
Definition: Interpreter.cc:431
auto lower_bound(ForwardRange &&range, const T &value)
Definition: ranges.hh:71
void unregisterCommand(Command &command)
Definition: Interpreter.cc:153
void setVariable(const TclObject &name, const TclObject &value)
Definition: Interpreter.cc:239
friend class TclObject
Definition: Interpreter.hh:68
TclObject getCommandNames()
Definition: Interpreter.cc:196
TclObject execute(const std::string &command)
Definition: Interpreter.cc:206
void setToken(void *token_)
Definition: Command.hh:68
void * getToken() const
Definition: Command.hh:69
std::string_view getFullName() const
Definition: Setting.hh:35
std::string strCat(Ts &&...ts)
Definition: strCat.hh:573
void registerSetting(BaseSetting &variable)
Definition: Interpreter.cc:261
auto rfind_if_unguarded(RANGE &range, PRED pred)
Definition: stl.hh:160
void unregisterSetting(BaseSetting &variable)
Definition: Interpreter.cc:313
bool isComplete(const std::string &command) const
Definition: Interpreter.cc:201
#define UNREACHABLE
Definition: unreachable.hh:38
virtual void setValueDirect(const TclObject &value)=0
Similar to setValue(), but doesn&#39;t trigger Tcl traces.