-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.d
436 lines (351 loc) · 12.9 KB
/
app.d
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
import tkd.tkdapplication;
import std.stdio, std.file, std.process, std.array, std.conv, std.string, std.regex,
std.algorithm, std.range;
import core.exception;
enum VERSION = "1.0.6";
class Application : TkdApplication {
Text asmBox;
Text codeBox;
Entry addressEntry;
string currentFile = "";
string lastASM = "";
//////////////////////
//GUI setup
//////////////////////
override protected void initInterface() {
mainWindow.setTitle("CodeWrite")
.setMinSize(652, 0)
.setDefaultIcon(new EmbeddedPng!("icon.png"))
.bind("<Control-o>", &open)
.bind("<Control-s>", &save)
.bind("<Control-n>", &newFile)
.bind("<Control-Shift-s>", &saveAs)
.setProtocolCommand(WindowProtocol.deleteWindow, (args) {
if (confirmDiscard(args)) this.exit();
});
////
//Menu bar things
////
auto menuBar = new MenuBar(mainWindow);
auto fileMenu = new Menu(menuBar, "File")
.addEntry("New ASM File", &newFile)
.addEntry("Open ASM File...", &open)
.addEntry("Save ASM", &save)
.addEntry("Save ASM File As...", &saveAs);
auto helpMenu = new Menu(menuBar, "Help")
.addEntry("About", &about);
////
//Left frame (ASM text box)
////
auto leftFrame = new Frame().pack(10, 10, GeometrySide.left, GeometryFill.both, AnchorPosition.west, true);
auto addressFrame = new LabelFrame(leftFrame, "Insertion Address").pack(0, 0, GeometrySide.top, GeometryFill.x);
addressEntry = new Entry(addressFrame).pack(8, 0, GeometrySide.left);
auto asmFrame = new LabelFrame(leftFrame, "ASM").pack(0, 0, GeometrySide.top, GeometryFill.both, AnchorPosition.west, true);
asmBox = new Text(asmFrame).pack(8, 0, GeometrySide.top, GeometryFill.both, AnchorPosition.center, true)
.setWidth(30)
.setUndoLevels(100)
.setWrapMode("none");
auto asmYScroll = new YScrollBar(asmBox).attachWidget(asmBox).pack(0, 0, GeometrySide.right, GeometryFill.y);
auto asmXScroll = new XScrollBar(asmBox).attachWidget(asmBox).pack(0, 0, GeometrySide.bottom, GeometryFill.x);
asmBox.attachXScrollBar(asmXScroll);
asmBox.attachYScrollBar(asmYScroll);
////
//Right frame (Gecko code text box)
////
auto codesFrame = new LabelFrame("Codes").pack(10, 0, GeometrySide.right, GeometryFill.y, AnchorPosition.east);
//new Button(codesFrame, "Send to Code Manager").pack(8, 0, GeometrySide.top, GeometryFill.x);
codeBox = new Text(codesFrame).pack(8, 0, GeometrySide.top, GeometryFill.both, AnchorPosition.center, true)
.setWidth(25)
.setUndoLevels(100);
//auto codesYScroll = new YScrollBar(codeBox).attachWidget(codeBox).pack(0, 0, GeometrySide.right, GeometryFill.y);
//codeBox.attachYScrollBar(codesYScroll).setWidth(25);
////
//In-between buttons
////
new Button("←").pack(10, 0, GeometrySide.top, GeometryFill.none, AnchorPosition.north)
.setCommand(&codeToAsm);
new Button("→").pack(10, 0, GeometrySide.bottom, GeometryFill.none, AnchorPosition.south)
.setCommand(&asmToCode);
}
//////////////////////
//Menu commands
//////////////////////
void newFile(CommandArgs args) {
if (!confirmDiscard(args)) return;
asmBox.clear;
lastASM = "";
currentFile = "";
}
void open(CommandArgs args) {
if (!confirmDiscard(args)) return;
auto dialog = new OpenFileDialog("Open an ASM file...")
.setMultiSelection(false)
.setDefaultExtension(".asm")
.addFileType("{{ASM files} {.asm}}")
.addFileType("{{All files} {*}}")
.show;
if (dialog.getResult != "") {
asmBox.clear;
currentFile = dialog.getResult;
auto openedText = readText(currentFile);
auto firstLine = openedText.until("\n").to!string;
auto re = ctRegex!(`#To be inserted at ([a-f,A-F,0-9]{8})(\r)?$`);
auto result = matchFirst(firstLine, re);
if (!result.empty) {
addressEntry.setValue(result.hit[$-8..$]);
openedText = openedText[firstLine.length+1..$];
}
asmBox.insertText(1, 0, openedText);
lastASM = openedText;
}
}
bool confirmDiscard(CommandArgs args) {
auto asmText = (asmBox.getText)[0..$-1]; //chop of trailing newline from Text widget
if (lastASM != asmText && asmText != "") {
auto result = new MessageDialog("Save file?")
.setIcon(MessageDialogIcon.question)
.setMessage("Save changes to this file?")
.setType(MessageDialogType.yesnocancel)
.show
.getResult;
if (result == "yes") {
save(args);
}
else if (result == "cancel") {
return false;
}
}
return true;
}
void save(CommandArgs args) {
if (currentFile == "") saveAs(args);
else {
writeOutASM();
}
}
void saveAs(CommandArgs args) {
auto result = new SaveFileDialog("Save an ASM file...")
.setConfirmOverwrite(true)
.setDefaultExtension(".asm")
.addFileType("{{ASM files} {.asm}}")
.addFileType("{{All files} {*}}")
.show
.getResult;
if (result != "") {
currentFile = result;
writeOutASM();
}
}
void writeOutASM() {
auto asmText = (asmBox.getText)[0..$-1]; //chop off trailing newline from Text widget
lastASM = asmText;
auto address = addressEntry.getValue;
auto re = ctRegex!("([a-f,A-F,0-9]{8})$");
if (!matchFirst(address, re).empty) {
asmText = "#To be inserted at " ~ address ~ "\n" ~ asmText;
}
std.file.write(currentFile, asmText);
}
void about(CommandArgs args) {
auto dialog = new MessageDialog("About CodeWrite")
.setMessage("CodeWrite v" ~ VERSION ~ "\n" ~
"by TheGag96/codeThaumaturge\n" ~
"written in D using tkd for Tcl/Tk bindings")
.show;
}
//////////////////////
//Internal functions
//////////////////////
void asmToCode(CommandArgs args) {
if (asmBox.getText.strip == "") return;
////
//Preprocess code string to remove ; comments
////
auto re = regex(r";.*$", "gm"); //" fix shitty sublime parsing
string assembly = replaceAll(asmBox.getText, re, "");
////
//Check validity of start address
////
bool codeIsExecute = (addressEntry.getValue.strip == "" || addressEntry.getValue.strip.toUpper == "N/A");
uint startAddress;
if (!codeIsExecute) {
try {
startAddress = addressEntry.getValue.to!uint(16);
if (startAddress < 0x80000000 || startAddress > 0x81FFFFFF) throw new Exception("ayy lmao");
}
catch (Exception e) {
errorNotice("Your address should be a hex number between 80000000 and 81FFFFFF (or use N/A for the C0 codetype).");
return;
}
}
////
//Run compiler and get results
////
std.file.write("temptemptemp.asm", assembly);
scope(exit) std.file.remove("temptemptemp.asm");
auto shell = execute(["powerpc-gekko-as.exe", "-a32", "-mbig", "-mregnames", "-mgekko", "temptemptemp.asm"], null, Config.suppressConsole);
if (!exists("a.out")) {
errorNotice("Looks like the ASM failed to compile. Output:\n\n " ~ shell.output);
return;
}
scope(exit) std.file.remove("a.out");
auto data = cast(ubyte[]) std.file.read("a.out");
data = data[52..data.countUntil([0x00, 0x2E, 0x73, 0x79, 0x6D, 0x74, 0x61, 0x62])];
auto numLines = data.length/8+1;
////
//Output formatted code to text box
////
auto code = appender!string;
if (codeIsExecute) code.put("C0000000");
else code.put(format("%08X", startAddress + 0x42000000));
code.put(" ");
code.put(format("%08X", numLines));
int counter = 0;
foreach (b; data) {
if (counter % 8 == 4) code.put(" ");
else if (counter % 8 == 0) code.put("\n");
code.put(format("%02X", b));
counter++;
}
if (counter % 8 == 4) {
code.put(" 00000000");
}
else {
code.put("\n60000000 00000000");
}
codeBox.clear();
codeBox.insertText(0, 0, code.data);
}
void codeToAsm(CommandArgs args) {
if (codeBox.getText.strip == "") return;
////
//Process code
////
ubyte[] bytes;
auto re = ctRegex!r"\*+|\s+";
auto pureCode = codeBox.getText.replaceAll(re, "").toUpper;
uint offset;
try {
if (pureCode.length % 8 != 0) throw new Exception("invalid");
//needs to be a valid code command
if (pureCode[0..2] == "C2") {
offset = pureCode[2..8].to!uint(16) + 0x80000000;
}
else if (pureCode[0..2] == "C3") {
offset = pureCode[2..8].to!uint(16) + 0x81000000;
}
else if (pureCode[0..2] == "C0") {
offset = 0;
}
else {
throw new Exception("invalid");
}
//get offset for later
//convert every two characters to bytes
pureCode = pureCode[16..$];
foreach (i; iota(0, pureCode.length, 2)) {
bytes ~= pureCode[i..i+2].to!ubyte(16);
}
//trim off trailing 00000000
if (bytes[$-8..$] == [0, 0, 0, 0, 0, 0, 0, 0]) bytes = bytes[0..$-8];
}
catch (Exception e) {
errorNotice("Looks like this isn't a valid ASM code.");
return;
}
//write code to file
std.file.write("code.bin", bytes);
scope(exit) std.file.remove("code.bin");
////
//Run disassembler and get results
////
auto command = execute(["vdappc", "code.bin", "0"], null, Config.suppressConsole);
auto decompiled = command.output.replace("\t", " ").lineSplitter.map!(x => x[20..$]).join("\n");
//remove trailing 0 data
if (decompiled.endsWith(".word 0x00000000")) decompiled = decompiled[0..$-17];
if (decompiled.endsWith("nop ")) decompiled = decompiled[0..$-5];
if (offset == 0) {
addressEntry.setValue("N/A");
}
else {
addressEntry.setValue(offset.to!string(16));
}
////
//Fix and prettify output
////
auto fixed = appender!(string[]);
bool[uint] labelTable = [0 : true];
uint codeSize = 4 * (cast(uint)decompiled.count("\n")+1);
static immutable IMMEDIATES = ["li", "lis", "ori", "addi", "cmpwi", "subi", "andi.", "andis.", "cmpli", "mulli", "oris"];
uint pos = 0;
foreach (line; decompiled.lineSplitter) {
bool madeFix = false;
try {
//branch instructions get a label made for their jump location
if (line.startsWith('b')) {
string opcode = line[0..line.countUntil(' ')];
//some branches look like bne- cr3,somewhere. so, we gotta handle them
auto branchArgs = line[opcode.length+1..$].findSplitAfter(",");
int jumpLocation = cast(int) (branchArgs[1][2..$].to!uint(16));
if (jumpLocation > codeSize || jumpLocation < 0) {
//check for absolute branches
if (opcode.endsWith('a') || opcode.endsWith("a+") || opcode.endsWith("a-")) {
fixed.put(format(" %s %s0x%X\n", opcode, branchArgs[0], cast(uint)jumpLocation));
}
else {
if (jumpLocation >= 0) fixed.put(format(" %s %s0x%X\n", opcode, branchArgs[0], jumpLocation-pos));
else fixed.put(format(" %s %s-0x%X\n", opcode, branchArgs[0], -jumpLocation+pos));
}
}
else {
labelTable[jumpLocation] = true;
fixed.put(format(" %s %sloc_0x%X\n", opcode, branchArgs[0], jumpLocation));
}
madeFix = true;
}
else if (IMMEDIATES.canFind(line[0..line.countUntil(' ')])) {
//convert most immediate values to hex
string unedited = line[0..line.lastIndexOf(',')+1];
int value = line[unedited.length..$].to!int & 0xFFFF;
fixed.put(format(" %s0x%X\n", unedited, value));
madeFix = true;
}
}
catch (ConvException e) { /* Sometimes just starting with "b" doesn't mean it's an immediate branch lel */ }
catch (RangeError e) { }
if (!madeFix) {
fixed.put(format(" %s\n", line));
}
pos += 4;
}
asmBox.clear();
pos = 0;
uint lineNum = 1;
foreach (line; fixed.data) {
if (pos in labelTable) {
if (pos != 0) {
asmBox.insertText(lineNum, 0, "\n");
lineNum++;
}
asmBox.insertText(lineNum, 0, format("loc_0x%X:\n", pos));
lineNum++;
}
asmBox.insertText(lineNum, 0, line.replace(",", ", "));
pos += 4;
lineNum++;
}
//make label after last line if a branch skips past everything
if (pos in labelTable) {
asmBox.insertText(lineNum, 0, format("\nloc_0x%X:\n", pos));
}
}
void errorNotice(string message) {
new MessageDialog("Whoopsie!")
.setMessage(message)
.show();
}
}
void main() {
auto application = new Application;
application.run();
}