forked from moonsharp-devs/moonsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
454 lines (355 loc) · 10.7 KB
/
MainForm.cs
File metadata and controls
454 lines (355 loc) · 10.7 KB
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.CoreLib;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Execution;
using MoonSharp.Interpreter.Execution.VM;
using MoonSharp.Interpreter.Loaders;
namespace MoonSharp.Debugger
{
public partial class MainForm : Form, IDebugger
{
List<DynamicExpression> m_Watches = new List<DynamicExpression>();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
m_Ctx = SynchronizationContext.Current;
Script.WarmUp();
//Script.DefaultOptions.TailCallOptimizationThreshold = 1;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Load script";
ofd.DefaultExt = "lua";
ofd.Filter = "Lua files (*.lua)|*.lua|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
DebugScript(ofd.FileName);
openToolStripMenuItem.Enabled = false;
}
}
Script m_Script;
SynchronizationContext m_Ctx;
private void Console_WriteLine(string fmt, params object[] args)
{
fmt = string.Format(fmt, args);
m_Ctx.Post(str =>
{
txtOutput.Text = txtOutput.Text + fmt.ToString().Replace("\n", "\r\n") + "\r\n";
txtOutput.SelectionStart = txtOutput.Text.Length - 1;
txtOutput.SelectionLength = 0;
txtOutput.ScrollToCaret();
}, fmt);
}
private void DebugScript(string filename)
{
m_Script = new Script(CoreModules.Basic | CoreModules.Table | CoreModules.TableIterators | CoreModules.Metatables);
// m_Script.Options.UseLuaErrorLocations = true;
m_Script.Options.DebugPrint = s => { Console_WriteLine("{0}", s); };
// ((ScriptLoaderBase)m_Script.Options.ScriptLoader).ModulePaths = ScriptLoaderBase.UnpackStringPaths("Modules/?;Modules/?.lua");
DynValue fn;
try
{
fn = m_Script.LoadFile(filename, null, filename.Replace(':', '|'));
}
catch (Exception ex)
{
txtOutput.Text = "";
Console_WriteLine("{0}", ex.Message);
return;
}
m_Script.AttachDebugger(this);
Thread m_Debugger = new Thread(() => DebugMain(fn));
m_Debugger.Name = "MoonSharp Execution Thread";
m_Debugger.IsBackground = true;
m_Debugger.Start();
}
public void SetSourceCode(SourceCode sourceCode)
{
}
void IDebugger.SetByteCode(string[] byteCode)
{
string[] source = byteCode.Select((s, i) => string.Format("{0:X8} {1}", i, s)).ToArray();
m_Ctx.Send(o =>
{
codeView.SourceCode = source;
}, null);
}
DebuggerAction m_NextAction;
AutoResetEvent m_WaitLock = new AutoResetEvent(false);
AutoResetEvent m_WaitBack = new AutoResetEvent(false);
DebuggerAction IDebugger.GetAction(int ip, SourceRef sourceCodeRef)
{
m_Ctx.Post(o =>
{
codeView.ActiveLine = ip;
RefreshCodeView(sourceCodeRef);
}, null);
m_WaitLock.WaitOne();
DebuggerAction action = m_NextAction;
m_NextAction = null;
m_WaitBack.Set();
return action;
}
SourceRef m_PrevRef = null;
private void RefreshCodeView(SourceRef sourceCodeRef)
{
if (sourceCodeRef == m_PrevRef)
return;
m_PrevRef = sourceCodeRef;
if (sourceCodeRef == null)
{
txtCodeView.Text = "!! NULL !!";
}
else
{
SourceCode sc = m_Script.GetSourceCode(sourceCodeRef.SourceIdx);
//txtCodeView.Text = sc.Lines[sourceCodeRef.FromLine + 1] + "\n" +
// sourceCodeRef.ToString();
txtCodeView.Text = sc.GetCodeSnippet(sourceCodeRef) + "\r\n\r\n" + sourceCodeRef.ToString();
}
}
void DebugAction(DebuggerAction action)
{
bool savedState = timerFollow.Enabled;
timerFollow.Enabled = false;
m_NextAction = action;
m_WaitLock.Set();
if (!m_WaitBack.WaitOne(1000))
{
MessageBox.Show(this, "Operation timed out", "Timeout");
}
else
{
timerFollow.Enabled = savedState;
}
}
void DebugMain(DynValue fn)
{
try
{
fn.Function.Call();
}
catch (ScriptRuntimeException ex)
{
timerFollow.Enabled = false;
Console_WriteLine("Guest raised unhandled CLR exception: {0} -@{3:X8} {2}\n{1}\n", ex.GetType(), ex.ToString(), ex.DecoratedMessage, ex.InstructionPtr);
}
catch (Exception ex)
{
timerFollow.Enabled = false;
Console_WriteLine("Guest raised unhandled CLR exception: {0} \n{1}\n", ex.GetType(), ex.ToString());
}
}
private void StepIN()
{
DebugAction(new DebuggerAction() { Action = DebuggerAction.ActionType.ByteCodeStepIn });
}
private void StepOVER()
{
DebugAction(new DebuggerAction() { Action = DebuggerAction.ActionType.ByteCodeStepOver });
}
private void GO()
{
DebugAction(new DebuggerAction() { Action = DebuggerAction.ActionType.Run });
}
void IDebugger.Update(WatchType watchType, IEnumerable<WatchItem> items)
{
if (watchType == WatchType.CallStack)
m_Ctx.Post(UpdateCallStack, items);
if (watchType == WatchType.Watches)
m_Ctx.Post(UpdateWatches, items);
if (watchType == WatchType.VStack)
m_Ctx.Post(UpdateVStack, items);
}
void UpdateVStack(object o)
{
IEnumerable<WatchItem> items = (IEnumerable<WatchItem>)o;
lvVStack.BeginUpdate();
lvVStack.Items.Clear();
foreach (var item in items)
{
lvVStack.Add(
item.Address.ToString("X4"),
(item.Value != null) ? item.Value.Type.ToString() : "(undefined)",
(item.Value != null) ? item.Value.ToString() : "(undefined)"
).Tag = item.Value;
}
lvVStack.EndUpdate();
}
void UpdateWatches(object o)
{
IEnumerable<WatchItem> items = (IEnumerable<WatchItem>)o;
lvWatches.BeginUpdate();
lvWatches.Items.Clear();
foreach (var item in items)
{
lvWatches.Add(
item.Name ?? "(???)",
(item.Value != null) ? item.Value.Type.ToLuaTypeString() : "(undefined)",
(item.Value != null) ? item.Value.ToString() : "(undefined)",
(item.LValue != null) ? item.LValue.ToString() : "(undefined)"
).Tag = item.Value;
}
lvWatches.EndUpdate();
}
void UpdateCallStack(object o)
{
IEnumerable<WatchItem> items = (IEnumerable<WatchItem>)o;
lvCallStack.BeginUpdate();
lvCallStack.Items.Clear();
foreach (var item in items)
{
lvCallStack.Add(
item.Address.ToString("X8"),
item.Name ?? ((item.RetAddress < 0) ? "<chunk-root>" : "<??unknown??>"),
item.RetAddress.ToString("X8"),
item.BasePtr.ToString("X8")
).Tag = item.Address;
}
lvCallStack.Add("---", "<CLR>", "---", "---");
lvCallStack.EndUpdate();
}
List<DynamicExpression> IDebugger.GetWatchItems()
{
return m_Watches;
}
private void btnAddWatch_Click(object sender, EventArgs e)
{
string text = WatchInputDialog.GetNewWatchName();
if (!string.IsNullOrEmpty(text))
{
string[] codeToAdd = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
m_Watches.AddRange(codeToAdd.Select(code => m_Script.CreateDynamicExpression(code)));
DebugAction(new DebuggerAction() { Action = DebuggerAction.ActionType.Refresh });
}
}
private void btnRemoveWatch_Click(object sender, EventArgs e)
{
HashSet<string> itemsToRemove = new HashSet<string>(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Text));
int i = m_Watches.RemoveAll(w => itemsToRemove.Contains(w.ExpressionCode));
if (i != 0)
DebugAction(new DebuggerAction() { Action = DebuggerAction.ActionType.Refresh });
}
private void stepInToolStripMenuItem_Click(object sender, EventArgs e)
{
StepIN();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
openToolStripMenuItem.PerformClick();
}
private void stepOverToolStripMenuItem_Click(object sender, EventArgs e)
{
StepOVER();
}
private void toolGO_Click(object sender, EventArgs e)
{
GO();
}
private void gOToolStripMenuItem_Click(object sender, EventArgs e)
{
GO();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
StepIN();
}
private void toolStepOver_Click(object sender, EventArgs e)
{
StepOVER();
}
private void btnViewVStk_Click(object sender, EventArgs e)
{
ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
}
private void lvVStack_MouseDoubleClick(object sender, MouseEventArgs e)
{
ValueBrowser.StartBrowse(lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
}
private void btnViewWatch_Click(object sender, EventArgs e)
{
ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
}
private void lvWatches_MouseDoubleClick(object sender, MouseEventArgs e)
{
ValueBrowser.StartBrowse(lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault());
}
private void toolGoToCodeVStack_Click(object sender, EventArgs e)
{
var v = lvVStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault();
if (v != null && v.Type == DataType.Function)
GotoBytecode(v.Function.EntryPointByteCodeLocation);
}
private void toolGoToCodeWatches_Click(object sender, EventArgs e)
{
var v = lvWatches.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).Cast<DynValue>().FirstOrDefault();
if (v != null && v.Type == DataType.Function)
GotoBytecode(v.Function.EntryPointByteCodeLocation);
}
private void toolGoToCodeXStack_Click(object sender, EventArgs e)
{
var v = lvCallStack.SelectedItems.OfType<ListViewItem>().Select(lvi => lvi.Tag).OfType<int>().FirstOrDefault();
if (v != 0)
GotoBytecode(v);
}
private void GotoBytecode(int code)
{
codeView.CursorLine = code;
}
private void timerFollow_Tick(object sender, EventArgs e)
{
toolStepIN.PerformClick();
}
private void btnFollow_Click(object sender, EventArgs e)
{
timerFollow.Start();
}
private void btnFastHack_Click(object sender, EventArgs e)
{
DebugScript(@"C:\temp\test.lua");
}
void IDebugger.SetSourceCode(SourceCode sourceCode)
{
}
bool IDebugger.IsPauseRequested()
{
return false;
}
public void SignalExecutionEnded()
{
}
public void RefreshBreakpoints(IEnumerable<SourceRef> refs)
{
}
public bool SignalRuntimeException(ScriptRuntimeException ex)
{
Console_WriteLine("Error: {0}", ex.DecoratedMessage);
return true;
}
private void btnOpenTest_Click(object sender, EventArgs e)
{
}
public void SetDebugService(DebugService debugService)
{
}
public DebuggerCaps GetDebuggerCaps()
{
return DebuggerCaps.CanDebugByteCode;
}
}
}