Repository navigation
Expand file tree
/
Copy pathLayoutCommands.cpp
More file actions
2389 lines (2289 loc) · 77.8 KB
/
Copy pathLayoutCommands.cpp
File metadata and controls
2389 lines (2289 loc) · 77.8 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// LayoutCommands.cpp : the command table modes of the Layout tab.
//
// The command table is compiled script (see PixoScript.h). Mode 3 lists a function as source, mode 4 as
// assembly. Numbers and names in the listing that refer to something else (another function, a menu, a
// string, a bitmap, a layout) can be double-clicked to go there.
#include "stdafx.h"
#include "iPodWizard.h"
#include "LayoutDialog.h"
using namespace PixoScript;
#ifndef EM_SETCUEBANNER
#define EM_SETCUEBANNER 0x1501 // (ECM_FIRST + 1: the grey text of an empty edit box; this is not in the headers of the compiler)
#endif
static const int kFunctionMatch = 100; // kind of a candidate that is a function (the others are MATCH_*)
// The bytes as hex, in the order they are stored: "58 05 6B"
static CString HexBytes(const BYTE *p, int n)
{
CString s, t;
for (int i = 0; i < n; i++)
{
t.Format(_T("%02X"), p[i]);
if (i)
s += _T(" ");
s += t;
}
return s;
}
static bool IsWordChar(TCHAR ch)
{
return _istalnum(ch) || ch == _T('_');
}
// Where a part of a line is: the first place at or after `from` where the token stands on its own (not inside a longer
// word or number)
static int FindToken(const CString &text, const CString &token, int from)
{
int n = text.GetLength(), m = token.GetLength();
if (m == 0)
return -1;
for (int pos = text.Find(token, from); pos >= 0; pos = text.Find(token, pos + 1))
{
bool lead = pos == 0 || !IsWordChar(text[pos - 1]) || !IsWordChar(token[0]);
bool trail = pos + m >= n || !IsWordChar(text[pos + m]) || !IsWordChar(token[m - 1]);
if (lead && trail)
return pos;
}
return -1;
}
void CLayoutDialog::CmdSetupColumns()
{
while (m_ResourceList.DeleteColumn(0) == TRUE);
m_ResourceList.InsertColumn(0, TEXT("Offset"), LVCFMT_LEFT, 80);
m_ResourceList.InsertColumn(1, TEXT("Address"), LVCFMT_LEFT, 74);
if (m_ResourceType == 3)
{
m_ResourceList.InsertColumn(2, TEXT("Source"), LVCFMT_LEFT, 700);
}
else
{
m_ResourceList.InsertColumn(2, TEXT("Bytes"), LVCFMT_LEFT, 120);
m_ResourceList.InsertColumn(3, TEXT("Instruction"), LVCFMT_LEFT, 500);
}
}
void CLayoutDialog::CmdFillTree()
{
m_ResourceTree.DeleteAllItems();
if (!m_Commands.IsValid())
{
m_ResourceTree.InsertItem(_T("This firmware has no command table I can read"), TVI_ROOT, TVI_LAST);
return;
}
for (int i = 0; i < m_Commands.GetNumFunctions(); i++)
{
int id = m_Commands.GetFunctionId(i);
InsertLazy(m_Commands.Label(id), TVI_ROOT, id, !m_Commands.GetCallees(id).empty());
}
}
// The functions a function refers to are added when its item is opened
void CLayoutDialog::OnTvnItemexpandingResourceTree(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
*pResult = 0;
if (pNMTreeView->action != TVE_EXPAND)
return;
if (m_ResourceType == 0)
{
ExpandViewItem(pNMTreeView->itemNew.hItem);
return;
}
if (!IsCommandMode())
return;
HTREEITEM h = pNMTreeView->itemNew.hItem;
if (m_ResourceTree.GetChildItem(h) != NULL)
return;
int id = (int)m_ResourceTree.GetItemData(h);
const std::vector<int> &callees = m_Commands.GetCallees(id);
for (size_t i = 0; i < callees.size(); i++)
{
InsertLazy(m_Commands.Label(callees[i]), h, callees[i], !m_Commands.GetCallees(callees[i]).empty());
}
}
// Raw bytes of a function (header, byte code and padding) inside the firmware image
bool CLayoutDialog::CmdRecord(int functionId, LPBYTE *pBuf, UINT *pLen)
{
const Function *pf = m_Commands.FindFunction(functionId);
if (pf == NULL || m_pFirmware == NULL)
return false;
DWORD len = m_Commands.Script().GetRecordLength(*pf);
DWORD start = m_Commands.GetFunctionOffset(*pf);
if (start + len > m_pFirmware->GetFirmwareSize())
len = m_pFirmware->GetFirmwareSize() - start;
*pBuf = m_pFirmware->GetFirmwareBuffer() + start;
*pLen = len;
return true;
}
// Read a function from a file into the firmware. The file has to be this function: same ID and same code length
// (the length of a function cannot change, everything behind it would have to move).
bool CLayoutDialog::CmdReadRecord(CFile &file, int functionId, LPBYTE dest, UINT len)
{
const Function *pf = m_Commands.FindFunction(functionId);
if (pf == NULL || len < 12)
{
file.Close();
MessageBox(_T("This is not a function of the command table."));
return false;
}
BYTE *tmp = new BYTE[len];
UINT got = file.Read(tmp, len);
file.Close();
bool ok = (got == len);
if (ok)
{
int id = (short)(tmp[0] | (tmp[1] << 8));
int codeLen = tmp[8] | (tmp[9] << 8);
ok = (id == pf->id && codeLen == (int)pf->codeLen);
}
if (!ok)
{
delete[] tmp;
MessageBox(_T("The resource file you chose isn't this function: its ID or the length of its code is different."));
return false;
}
memcpy(dest, tmp, len);
delete[] tmp;
return true;
}
static Line CommentLine(const CString &text)
{
Line l;
l.text = _T("// ") + text;
return l;
}
// A comment line built from parts. Some parts stand for numbers stored in the firmware (see Ref): the list frames
// them, and a click on one shows the bytes in the hex view.
class CLineBuilder
{
public:
void Add(const CString &t) { m_Text += t; }
void Add(const TCHAR *t) { m_Text += t; }
void Token(const CString &t, Ref r)
{
r.token = t;
m_Text += t;
m_Refs.push_back(r);
}
Line Make() const
{
Line l;
l.text = _T("// ") + m_Text;
l.refs = m_Refs;
return l;
}
private:
CString m_Text;
std::vector<Ref> m_Refs;
};
// Absolute place in the firmware image a reference of a line is stored at
DWORD CLayoutDialog::CmdRefAddress(const Ref &r)
{
return r.absolute ? (DWORD)r.off : m_Commands.GetResourceOffset() + (DWORD)r.off;
}
// How a command is used by the function that names it: the statements of that function that hold the call (a key
// handler registered, a timer started, the title and command of a game added to the games list ...), with the IDs of
// strings in them spelled out
CString CLayoutDialog::CmdCallContext(const Function &caller, int calleeId, const std::vector<int> &sites)
{
CScript &script = m_Commands.Script();
std::map<int, std::vector<Line> >::iterator it = m_CmdBodies.find(caller.id);
if (it == m_CmdBodies.end())
{
std::vector<Line> src;
BOOL bClean = FALSE;
if (!script.Decompile(caller, src, &bClean))
src.clear();
it = m_CmdBodies.insert(std::make_pair(caller.id, src)).first;
}
const std::vector<Line> &body = it->second;
if (body.empty())
return CString();
CString token = script.AtomText(calleeId);
std::vector<int> cand; // the lines that name the command
for (size_t k = 0; k < body.size(); k++)
if (FindToken(body[k].text, token, 0) >= 0)
cand.push_back((int)k);
if (cand.empty())
return CString();
CString all;
std::set<int> shown;
for (size_t i = 0; i < sites.size(); i++)
{
int pick = -1;
if (cand.size() == sites.size())
pick = cand[i]; // in code order, one line per place
else
{
int bestDist = INT_MAX; // else the line whose instruction is nearest to the place
for (size_t c = 0; c < cand.size(); c++)
{
int d = abs(body[cand[c]].off - sites[i]);
if (body[cand[c]].off >= 0 && d < bestDist)
{
bestDist = d;
pick = cand[c];
}
}
}
if (pick < 0 || !shown.insert(pick).second)
continue;
const Line &l = body[pick];
CString t = l.text;
t.Trim();
for (size_t r = 0; r < l.refs.size(); r++)
{
const Ref &ref = l.refs[r];
if (ref.type != REF_CONSTANT || !CmdConstantResolves(ref.value))
continue;
std::vector<CLayoutNames::Match> matches;
m_Names.Probe(ref.value, matches);
for (size_t m = 0; m < matches.size(); m++)
if (matches[m].kind == CLayoutNames::MATCH_STRING && !matches[m].text.IsEmpty())
{
t.AppendFormat(_T(" [%d is '%s']"), ref.value, (LPCTSTR)matches[m].text);
break;
}
}
if (!all.IsEmpty())
all += _T(" | ");
all += t;
}
return all;
}
// One place a function is used: a menu entry that runs it, a function that calls it, the list of entry points
Line CLayoutDialog::CmdUseLine(int functionId, const CCommandTable::Use &u, int indent)
{
CLineBuilder b;
b.Add(CString(_T(' '), indent));
CString offText, offTip;
Ref r;
r.off = (int)u.addr;
r.len = (int)u.len;
r.absolute = true;
switch (u.kind)
{
case CCommandTable::USE_ENTRY:
r.type = REF_NONE;
b.Token(_T("Entry point"), r);
b.Add(_T(": Ran at boot time"));
break;
case CCommandTable::USE_SELECT:
case CCommandTable::USE_HILITE:
{
bool bSelect = u.kind == CCommandTable::USE_SELECT;
r.type = REF_MENU;
r.value = u.id;
r.item = u.item;
r.tip.Format(_T("Menu %d entry %d: runs command %d when %s."),
u.id, u.item + 1, functionId, bSelect ? _T("chosen") : _T("highlighted"));
CString where;
where.Format(_T("menu %d, entry %d"), u.id, u.item + 1);
b.Add(bSelect ? _T("Run when chosen: ") : _T("Run when highlighted: "));
b.Token(where, r);
CString text = m_Commands.MenuEntryText(u.id, u.item);
if (!text.IsEmpty())
b.Add(_T(" '") + text + _T("'"));
}
break;
case CCommandTable::USE_CALLER:
{
// "Called by 1387 (name), at offset 12, 40"; the number is where the caller is, the others where it names this
const Function *pc = m_Commands.FindFunction(u.id);
CString id;
id.Format(_T("%d"), u.id);
b.Add(_T("Called by command "));
if (pc)
{
r.off = (int)m_Commands.GetFunctionOffset(*pc);
r.len = 2;
}
r.type = REF_FUNCTION;
r.value = u.id;
r.tip.Format(_T("Start of command %d record."), u.id);
b.Token(id, r);
CString name = m_Commands.Name(u.id);
if (!name.IsEmpty())
b.Add(_T(" (") + name + _T(")"));
const std::vector<int> &sites = m_Commands.GetSites(u.id, functionId);
for (size_t i = 0; i < sites.size() && pc; i++)
{
Ref s;
s.type = REF_NONE;
s.absolute = true;
s.off = (int)(m_Commands.GetCodeOffset(*pc) + sites[i] + 1);
s.len = 2;
s.bigEndian = true;
CString at;
at.Format(_T("%d"), sites[i]);
offText += (offText.IsEmpty() ? _T("") : _T(", ")) + at;
b.Add(i == 0 ? (sites.size() == 1 ? _T(", at offset ") : _T(", at offsets ")) : _T(", "));
b.Token(at, s);
}
if (pc && !sites.empty())
{
CString ctx = CmdCallContext(*pc, functionId, sites);
if (!ctx.IsEmpty())
b.Add(_T(": ") + ctx);
}
}
break;
}
Line l = b.Make();
l.offText = offText;
l.offTip = offTip;
return l;
}
// One command a function refers to, and the places in the function that name it
Line CLayoutDialog::CmdCalleeLine(int functionId, int callee)
{
CLineBuilder b;
CString offText;
b.Add(_T(" "));
const Function *pf = m_Commands.FindFunction(functionId);
const Function *pc = m_Commands.FindFunction(callee);
Ref r;
r.type = REF_FUNCTION;
r.value = callee;
r.absolute = true;
if (pc)
{
r.off = (int)m_Commands.GetFunctionOffset(*pc);
r.len = 2;
}
r.tip.Format(_T("Start of command %d record."), callee);
CString id;
id.Format(_T("%d"), callee);
b.Add(_T("command "));
b.Token(id, r);
CString name = m_Commands.Name(callee);
if (!name.IsEmpty())
b.Add(_T(" (") + name + _T(")"));
const std::vector<int> &sites = m_Commands.GetSites(functionId, callee);
for (size_t i = 0; i < sites.size() && pf; i++)
{
Ref s;
s.type = REF_NONE;
s.absolute = true;
s.off = (int)(m_Commands.GetCodeOffset(*pf) + sites[i] + 1);
s.len = 2;
s.bigEndian = true;
CString at;
at.Format(_T("%d"), sites[i]);
offText += (offText.IsEmpty() ? _T("") : _T(", ")) + at;
b.Add(i == 0 ? (sites.size() == 1 ? _T(", at offset ") : _T(", at offsets ")) : _T(", "));
b.Token(at, s);
}
if (pf && !sites.empty())
{
CString ctx = CmdCallContext(*pf, callee, sites);
if (!ctx.IsEmpty())
b.Add(_T(": ") + ctx);
}
Line l = b.Make();
l.offText = offText;
if (!offText.IsEmpty())
l.offTip = _T("Byte code offsets in this command (counted from the start of its code, after the 10 byte header).");
return l;
}
// The lines of a function's listing: what it is, where it is used and what it refers to, then the code, as source or assembly
void CLayoutDialog::CmdBuildLines(int functionId, bool bSource, std::vector<Line> &lines)
{
lines.clear();
m_CmdBodies.clear();
const Function *pf = m_Commands.FindFunction(functionId);
if (pf == NULL)
return;
CScript &script = m_Commands.Script();
// what the function is: its size (the header of its record is where the line stands)
{
CLineBuilder b;
b.Add(m_Commands.Signature(functionId));
Line l = b.Make();
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)m_Commands.GetFunctionOffset(*pf);
r.len = 10;
r.tip = _T("Command header: ID, parameter count, variable count, stack depth, code length. 2 bytes each, little endian.");
l.refs.push_back(r);
lines.push_back(l);
}
// Do the instructions hang together (stack depth, jumps, arguments, variables)? Every command of the 52 firmwares of the collection does, so a
// command that fails was changed, or this is a firmware that is not known.
{
CString why;
if (!script.Verify(*pf, &why))
lines.push_back(CommentLine(_T("Check failed: ") + why + _T(" The iPod may not run this command correctly.")));
}
// the game this command belongs to: the numbers in the firmware that decide how it plays
if (m_Commands.IsBrickCommand(functionId))
CmdBrickLines(lines);
if (m_Commands.IsStackerCommand(functionId))
CmdStackerLines(lines);
// who runs it: every place, one row each
const std::vector<CCommandTable::Use> &uses = m_Commands.GetUses(functionId);
if (uses.empty())
lines.push_back(CommentLine(_T("Not used by any menu entry or other command")));
else
{
CString head;
head.Format(_T("Used by %d place%s:"), (int)uses.size(), uses.size() == 1 ? _T("") : _T("s"));
lines.push_back(CommentLine(head));
for (size_t i = 0; i < uses.size(); i++)
lines.push_back(CmdUseLine(functionId, uses[i]));
}
// what it runs: every command it refers to, one row each
const std::vector<int> &callees = m_Commands.GetCallees(functionId);
if (!callees.empty())
{
CString head;
head.Format(_T("Refers to %d command%s (and who else uses each):"), (int)callees.size(), callees.size() == 1 ? _T("") : _T("s"));
lines.push_back(CommentLine(head));
for (size_t i = 0; i < callees.size(); i++)
{
lines.push_back(CmdCalleeLine(functionId, callees[i]));
// who else runs that command (the other commands that call it, the menu entries that choose it)
const std::vector<CCommandTable::Use> &others = m_Commands.GetUses(callees[i]);
int nOther = 0;
for (size_t k = 0; k < others.size(); k++)
if (!(others[k].kind == CCommandTable::USE_CALLER && others[k].id == functionId))
nOther++;
if (nOther > 0)
{
CString oh;
oh.Format(_T(" and %d other place%s:"), nOther, nOther == 1 ? _T("") : _T("s"));
lines.push_back(CommentLine(oh.Mid(0)));
for (size_t k = 0; k < others.size(); k++)
if (!(others[k].kind == CCommandTable::USE_CALLER && others[k].id == functionId))
lines.push_back(CmdUseLine(callees[i], others[k], 8));
}
}
}
lines.push_back(Line());
// the code
std::vector<Line> body;
if (bSource)
{
CString head;
CString name = m_Commands.Name(functionId);
if (name.IsEmpty())
name = script.AtomText(functionId);
head.Format(_T("function %s("), (LPCTSTR)name);
for (int i = 0; i < pf->nParams; i++)
{
CString a;
a.Format(i ? _T(", arg%d") : _T("arg%d"), i);
head += a;
}
head += _T(") {");
Line hl;
hl.text = head;
lines.push_back(hl);
BOOL bClean = FALSE;
if (!script.Decompile(*pf, body, &bClean))
lines.push_back(CommentLine(_T("This function's byte code cannot be read")));
else
{
if (!bClean)
lines.push_back(CommentLine(_T("Not everything in this function could be turned back into source")));
for (size_t i = 0; i < body.size(); i++)
lines.push_back(body[i]);
}
Line tl;
tl.text = _T("}");
lines.push_back(tl);
}
else
{
if (!script.Disassemble(*pf, body))
lines.push_back(CommentLine(_T("This function's byte code cannot be read")));
else
for (size_t i = 0; i < body.size(); i++)
lines.push_back(body[i]);
}
}
// Brick (BlockO): the numbers in the firmware that decide how the game plays, each one a link to its bytes. The rules are written down in
// Brick-Game-Logic.txt (research folder). The level table has one row per level: the balls, the rows of bricks (12 bricks per row, so the bricks
// to destroy are 12 x rows) and the width of the paddle.
void CLayoutDialog::CmdBrickLines(std::vector<Line> &lines)
{
const CCommandTable::BrickInfo &bi = m_Commands.Brick();
if (m_pFirmware == NULL || !bi.valid || bi.table == 0xFFFFFFFF)
return;
const BYTE *fw = m_pFirmware->GetFirmwareBuffer();
DWORD size = m_pFirmware->GetFirmwareSize();
if ((ULONGLONG)bi.table + 23 * 12 > size)
return;
lines.push_back(CommentLine(_T("Brick (BlockO) game. This command starts, pauses or asks about the game; the game itself is code of the operating system, not of this script.")));
lines.push_back(CommentLine(_T("What decides how it plays (click a number to see its bytes, Change Value changes it; keep a copy of the firmware). Rules: Brick-Game-Logic.txt.")));
if (bi.lives != 0xFFFFFFFF && bi.lives < size)
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)bi.lives;
r.len = 1;
r.tip = _T("Lives of a new game: the number in the instruction 'mov r0,#3' (1 to 255). Only 3 balls can be in play, more lives are spare.");
CString v;
v.Format(_T("%d"), fw[bi.lives]);
b.Add(_T(" Lives at the start: "));
b.Token(v, r);
lines.push_back(b.Make());
}
if (bi.vx != 0xFFFFFFFF && bi.vx + 8 <= size)
{
DWORD vx = CCommandTable::MovValue(*(const DWORD *)(fw + bi.vx));
DWORD vy = CCommandTable::MovValue(*(const DWORD *)(fw + bi.vy));
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)bi.vx;
r.len = 8;
r.tip = _T("Start speed of a ball: the two instructions that load 0x28000 (across) and 0x21000 (down), 16.16 fixed point. Change Value takes a percent of the original speed (100 = original, 200 = twice as fast).");
CString pct, rest;
pct.Format(_T("%d%%"), (int)((vx * 100.0) / 0x28000 + 0.5));
rest.Format(_T(" of the original (a new ball moves %.2f pixels across and %.2f down every 40 ms; 100%% = 2.50 and 2.06)"), vx / 65536.0, vy / 65536.0);
b.Add(_T(" Ball speed: "));
b.Token(pct, r);
b.Add(rest);
lines.push_back(b.Make());
}
// the other numbers of the game (each found in the code of the game, see Brick-Game-Logic.txt)
if (bi.score != 0xFFFFFFFF && bi.score < size)
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)bi.score;
r.len = 1;
r.tip = _T("Points for every brick destroyed: the number in the instruction 'add r1,r0,#1' (1 to 255).");
CString v;
v.Format(_T("%d"), fw[bi.score]);
b.Add(_T(" Points for each brick: "));
b.Token(v, r);
lines.push_back(b.Make());
}
if (bi.bonus != 0xFFFFFFFF && bi.bonus + 4 <= size)
{
DWORD w = *(const DWORD *)(fw + bi.bonus);
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)bi.bonus;
r.len = 4;
r.tip = _T("Lives given when every brick of a level is gone. Stock: one for every ball still in play (the instruction 'add r0,r0,r1'). Change Value: 1 = that (the original), 0 or 2 to 255 = that many lives whatever the number of balls.");
CString v = (w & 0xFFFFF000) == 0xE2800000 ? CString() : CString(_T("one for each ball still in play"));
if (v.IsEmpty())
v.Format(_T("%d"), (int)(w & 0xFFF));
b.Add(_T(" Lives gained when a level is cleared: "));
b.Token(v, r);
lines.push_back(b.Make());
}
if (bi.ballW != 0xFFFFFFFF && bi.ballH != 0xFFFFFFFF && bi.ballW < size && bi.ballH < size)
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 1;
CString v;
r.off = (int)bi.ballW;
r.tip = _T("Width of a ball in pixels (the instruction that sets the right edge of its rectangle, 1 to 20). The rectangle is also what hits bricks, the paddle and the walls.");
v.Format(_T("%d"), fw[bi.ballW]);
b.Add(_T(" Ball size: "));
b.Token(v, r);
b.Add(_T(" wide, "));
r.off = (int)bi.ballH;
r.tip = _T("Height of a ball in pixels (the number added to its top to get the bottom edge, 1 to 20).");
v.Format(_T("%d"), fw[bi.ballH]);
b.Token(v, r);
b.Add(_T(" high (pixels)"));
lines.push_back(b.Make());
}
if (bi.ballGap != 0xFFFFFFFF && bi.ballGap < size)
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.off = (int)bi.ballGap;
r.len = 1;
r.tip = _T("How far below the last row of bricks a new ball starts, in pixels (0 to 60).");
CString v;
v.Format(_T("%d"), fw[bi.ballGap]);
b.Add(_T(" A new ball starts "));
b.Token(v, r);
b.Add(_T(" pixels below the bricks"));
lines.push_back(b.Make());
}
lines.push_back(CommentLine(_T(" Fixed by the game's code (not a single number): 3 balls at most, 6 rows of 12 bricks, bricks 4 pixels high, a 40 ms step, the paddle moves 4 pixels for every")));
lines.push_back(CommentLine(_T(" click of the wheel (10 for the buttons), and a ball that hits an outer third of the paddle is sped up x1.5 or slowed x0.75 sideways.")));
lines.push_back(CommentLine(_T(" The levels (the game goes on to the next one when every brick is gone, and repeats the last one):")));
for (int lvl = 0; lvl < 22; lvl++)
{
DWORD at = bi.table + 12 * lvl;
const DWORD *w = (const DWORD *)(fw + at);
if (w[0] == 0)
break;
CLineBuilder b;
CString t;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 4;
t.Format(_T(" Level %d: "), lvl + 1);
b.Add(t);
r.off = (int)at;
r.tip = _T("Balls in play at the start of this level (1 to 3).");
t.Format(_T("%u"), w[0]);
b.Token(t, r);
b.Add(w[0] == 1 ? _T(" ball, ") : _T(" balls, "));
r.off = (int)at + 4;
r.tip = _T("Rows of bricks (1 to 6). Each row has 12 bricks, so the bricks to destroy in this level are 12 x this number.");
t.Format(_T("%u"), w[1]);
b.Token(t, r);
t.Format(w[1] == 1 ? _T(" row = %u bricks to destroy, paddle ") : _T(" rows = %u bricks to destroy, paddle "), w[1] * 12);
b.Add(t);
r.off = (int)at + 8;
r.tip = _T("Width of the paddle in pixels in this level (1 to 160; the field is 160 pixels wide on a 4G).");
t.Format(_T("%u"), w[2]);
b.Token(t, r);
b.Add(_T(" pixels"));
lines.push_back(b.Make());
}
lines.push_back(Line());
}
// The 12 bit field of "mov rX,#imm" for a value (8 bits rotated right by an even number of bits), or -1 when the value does not fit
static int MovField(DWORD value)
{
if (value == 0)
return -1;
for (DWORD rot = 0; rot < 16; rot++)
{
DWORD r = 2 * rot;
DWORD imm = r ? ((value << r) | (value >> (32 - r))) : value;
if (imm < 256)
return (int)((rot << 8) | imm);
}
return -1;
}
// Stacker (the falling block game of the 3G prototype): the numbers that decide how it plays, each one a link to its bytes. The rules are written down
// in Stacker-Game-Logic.txt (research folder). A piece falls every 12 ticks, the tick is 40 ms; the shapes are 16 entries (4 kinds x 4 rotations).
void CLayoutDialog::CmdStackerLines(std::vector<Line> &lines)
{
const CCommandTable::StackerInfo &si = m_Commands.Stacker();
if (m_pFirmware == NULL || !si.valid)
return;
const BYTE *fw = m_pFirmware->GetFirmwareBuffer();
DWORD size = m_pFirmware->GetFirmwareSize();
if ((ULONGLONG)si.table + 16 * 32 > size || si.firstPiece >= size || si.tick[2] >= size || si.points >= size || si.column[1] >= size)
return;
lines.push_back(CommentLine(_T("Stacker game (falling blocks, 12 x 16 board). This command starts, pauses or asks about the game; the game itself is code of the operating system, not of this script.")));
lines.push_back(CommentLine(_T("What decides how it plays (click a number to see its bytes, Change Value changes it; keep a copy of the firmware). Rules: Stacker-Game-Logic.txt.")));
CString v;
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 1;
r.off = (int)si.points;
r.tip = _T("Points for every full row: the number in the instruction 'add r1,r0,#12' (1 to 255).");
v.Format(_T("%d"), fw[si.points]);
b.Add(_T(" Points for a full row: "));
b.Token(v, r);
lines.push_back(b.Make());
}
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 1;
r.off = (int)si.tick[0];
r.tip = _T("Length of a tick in milliseconds: the number in 'mov r1,#40', in three places that Change Value changes together (5 to 255). A piece falls every 12 ticks.");
v.Format(_T("%d"), fw[si.tick[0]]);
b.Add(_T(" A tick is "));
b.Token(v, r);
v.Format(_T(" ms: a piece falls one row every %d ms (12 ticks); the fast drop and the wheel are handled on every tick"), 12 * fw[si.tick[0]]);
b.Add(v);
lines.push_back(b.Make());
}
{
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 1;
r.off = (int)si.column[0];
r.tip = _T("The column (0 to 11) a new piece appears in: the number in 'mov r0,#6' (and in the one for the first piece; Change Value changes both).");
v.Format(_T("%d"), fw[si.column[0]]);
b.Add(_T(" A new piece appears in column "));
b.Token(v, r);
r.off = (int)si.firstPiece;
r.tip = _T("The kind of the first piece of a game (0 square, 1 S/Z, 2 T, 3 bar): the shape number in 'mov r1,#4' divided by 4. The later pieces are random.");
v.Format(_T("%d"), fw[si.firstPiece] / 4);
b.Add(_T(", the first piece is kind "));
b.Token(v, r);
b.Add(_T(" (0 to 3)"));
lines.push_back(b.Make());
}
lines.push_back(CommentLine(_T(" The pieces: columns x rows, the origin (the cell that sits on the piece's position) and the 4 x 4 cells (the number is the block picture, . is empty):")));
for (int e = 0; e < 16; e++)
{
DWORD at = si.table + 32 * e;
const DWORD *w = (const DWORD *)(fw + at);
CLineBuilder b;
Ref r;
r.type = REF_NONE;
r.absolute = true;
r.len = 4;
CString t;
t.Format(_T(" Kind %d, turn %d: "), e / 4, e % 4);
b.Add(t);
static const TCHAR *const tip[4] = { _T("Columns the shape is wide (1 to 4)."), _T("Rows the shape is high (1 to 4)."),
_T("Column of the shape that sits on the piece's position (0 to 3)."), _T("Row of the shape that sits on the piece's position (0 to 3).") };
static const TCHAR *const sep[4] = { _T(" x "), _T(", origin "), _T(","), _T(" cells ") };
for (int k = 0; k < 4; k++)
{
r.off = (int)at + 4 * k;
r.len = 4;
r.tip = tip[k];
t.Format(_T("%u"), w[k]);
b.Token(t, r);
b.Add(sep[k]);
}
CString cells;
for (int row = 0; row < 4; row++)
{
if (row)
cells += _T(" ");
for (int col = 0; col < 4; col++)
{
BYTE c = fw[at + 16 + 4 * row + col];
cells += c == 0 ? _T('.') : (c < 10 ? (TCHAR)(_T('0') + c) : _T('#'));
}
}
r.off = (int)at + 16;
r.len = 16;
r.tip = _T("The 4 x 4 cells of the shape, row by row, one byte each: 0 empty, 1 to 4 the block picture. Change Value with Hex: type the 16 bytes.");
b.Token(cells, r);
lines.push_back(b.Make());
}
lines.push_back(CommentLine(_T(" Fixed by the game's code (not a single number): the 12 x 16 board, 6 pixel cells, 4 kinds of piece chosen at random, the wheel moves a piece one cell, Select turns it.")));
lines.push_back(Line());
}
// How many bytes the marked bytes of a number of the games take
static DWORD BrickKindSize(int kind)
{
switch (kind)
{
case 2: return 8;
case 3: case 4: case 5: case 7: case 15: return 4;
case 16: return 16;
}
return 1;
}
// What the marked bytes are, when they are one of the numbers of Brick or Stacker (see CmdBrickLines, CmdStackerLines): 0 none, 1 lives, 2 speed (percent, both
// instructions), 3 balls, 4 rows, 5 paddle width (the level table), 6 points per brick, 7 lives for a cleared level, 8 / 9 width / height of the ball, 10 where a
// ball starts below the bricks; Stacker: 11 points per row, 12 tick length (three places), 13 start column (two places), 14 kind of the first piece, 15 a number of a
// shape, 16 the cells of a shape
int CLayoutDialog::BrickKind(DWORD off, DWORD size) const
{
const CCommandTable::StackerInfo &si = m_Commands.Stacker();
if (si.valid)
{
if (off == si.points && size == 1)
return 11;
if (off == si.tick[0] && size == 1)
return 12;
if (off == si.column[0] && size == 1)
return 13;
if (off == si.firstPiece && size == 1)
return 14;
if (off >= si.table && off < si.table + 16 * 32)
{
DWORD in = (off - si.table) % 32;
if (in < 16 && in % 4 == 0 && size == 4)
return 15;
if (in == 16 && size == 16)
return 16;
}
}
const CCommandTable::BrickInfo &bi = m_Commands.Brick();
if (!bi.valid || bi.table == 0xFFFFFFFF)
return 0;
if (bi.lives != 0xFFFFFFFF && off == bi.lives && size == 1)
return 1;
if (bi.vx != 0xFFFFFFFF && off == bi.vx && size == 8)
return 2;
if (off >= bi.table && off < bi.table + 22 * 12 && size == 4 && (off - bi.table) % 4 == 0)
return 3 + (int)(((off - bi.table) / 4) % 3);
if (bi.score != 0xFFFFFFFF && off == bi.score && size == 1)
return 6;
if (bi.bonus != 0xFFFFFFFF && off == bi.bonus && size == 4)
return 7;
if (bi.ballW != 0xFFFFFFFF && off == bi.ballW && size == 1)
return 8;
if (bi.ballH != 0xFFFFFFFF && off == bi.ballH && size == 1)
return 9;
if (bi.ballGap != 0xFFFFFFFF && off == bi.ballGap && size == 1)
return 10;
return 0;
}
// The current value of one of them as Change Value takes it (decimal)
CString CLayoutDialog::BrickValueText(int kind, DWORD off)
{
CString s;
if (m_pFirmware == NULL || (ULONGLONG)off + BrickKindSize(kind) > m_pFirmware->GetFirmwareSize())
return s;
const BYTE *fw = m_pFirmware->GetFirmwareBuffer();
switch (kind)
{
case 1: case 6: case 8: case 9: case 10: case 11: case 12: case 13:
s.Format(_T("%d"), fw[off]);
break;
case 14:
s.Format(_T("%d"), fw[off] / 4);
break;
case 2:
s.Format(_T("%d"), (int)((CCommandTable::MovValue(*(const DWORD *)(fw + off)) * 100.0) / 0x28000 + 0.5));
break;
case 7:
{
DWORD w = *(const DWORD *)(fw + off);
s.Format(_T("%d"), (w & 0xFFFFF000) == 0xE2800000 ? (int)(w & 0xFFF) : 1); // 1: one for every ball still in play (the original)
}
break;
case 16:
break; // cells: Hex only
default:
s.Format(_T("%u"), *(const DWORD *)(fw + off));
break;
}
return s;
}
// "Change Value" on one of the numbers of Brick or Stacker. Handled here when the marked bytes are one of them. Hex: the bytes themselves; Decimal: the value.
bool CLayoutDialog::BrickChange()
{
if (!m_bLinkClick || m_pFirmware == NULL)
return false;
DWORD off = m_ValOffset;
int kind = BrickKind(off, m_ValSize);
if (kind == 0)
return false;
if (IsDlgButtonChecked(IDC_RADIO_STRINGVAL) == 1)
{
MessageBox(_T("Type the number as Decimal or Hex."));
return true;
}
const CCommandTable::StackerInfo &si = m_Commands.Stacker();
if (IsDlgButtonChecked(IDC_RADIO_HEXVAL) == 1)
{
// Hex: the bytes themselves ("05 00 80 E2"), as many as are typed (not more than are selected); the rest stay as they are
CString hexText = m_ChangeString;
hexText.Remove(' ');
int lenm = hexText.GetLength();
if (lenm == 0 || (lenm % 2) != 0)
{
MessageBox(_T("Type the bytes as pairs of hex digits, for example 05 00 80 E2."));
return true;
}
for (int j = 0; j < lenm; j++)
if (!_istxdigit(hexText[j]))
{
MessageBox(_T("That is not a hex value."));
return true;
}
if ((DWORD)(lenm / 2) > m_ValSize)
{
MessageBox(_T("The value you typed is too long!"));
return true;
}
BYTE raw[16];
for (int k = 0, j = 0; j < lenm; j += 2, k++)
{
unsigned int bv = 0;
swscanf(hexText.Mid(j, 2), _T("%X"), &bv);
raw[k] = (BYTE)bv;
}
m_pFirmware->SetData(off, raw, lenm / 2);
if (kind == 12) // the other places of the same number
{
m_pFirmware->SetData(si.tick[1], raw, 1);
m_pFirmware->SetData(si.tick[2], raw, 1);
}
else if (kind == 13)
m_pFirmware->SetData(si.column[1], raw, 1);
BrickChanged(off);
return true;
}
if (kind == 16)
{
MessageBox(_T("The cells of a shape are 16 bytes: choose Hex and type them (for example 01 01 00 00 01 01 00 00 00 00 00 00 00 00 00 00)."));
return true;
}
long value = 0;
if (_stscanf(m_ChangeString, _T("%ld"), &value) != 1)
{
MessageBox(_T("That is not a number."));
return true;
}
static const long lo[17] = { 0, 1, 10, 1, 1, 1, 1, 0, 1, 1, 0, 1, 5, 0, 0, 0, 0 }, hi[17] = { 0, 255, 400, 3, 6, 160, 255, 255, 20, 20, 60, 255, 255, 11, 3, 4, 0 };
static const TCHAR *const what[17] = { _T(""), _T("The lives have to be between 1 and 255."), _T("The speed has to be between 10 and 400 percent of the original."),
_T("A level has 1 to 3 balls."), _T("A level has 1 to 6 rows of bricks."), _T("The paddle has to be between 1 and 160 pixels wide."),
_T("The points for a brick have to be between 1 and 255."), _T("Type 1 for one life per ball still in play (the original), or 0 or 2 to 255 for that many lives in all."),
_T("The ball has to be between 1 and 20 pixels wide."), _T("The ball has to be between 1 and 20 pixels high."),
_T("A ball starts 0 to 60 pixels below the bricks."), _T("The points for a row have to be between 1 and 255."),
_T("A tick has to be between 5 and 255 milliseconds."), _T("A piece appears in a column from 0 to 11."),
_T("The first piece is a kind from 0 to 3 (square, S/Z, T, bar)."), _T("A shape number has to be between 0 and 4."), _T("") };
if (value < lo[kind] || value > hi[kind])
{
MessageBox(what[kind]);
return true;
}
LPBYTE fw = m_pFirmware->GetFirmwareBuffer();
if (kind == 2)
{
// the speed is stored as an immediate of two instructions: only some values fit
int fx = MovField((DWORD)(0x28000 * (double)value / 100.0)), fy = MovField((DWORD)(0x21000 * (double)value / 100.0));
if (fx < 0 || fy < 0)
{
CString near_;
int n = 0;
for (int pct = 10; pct <= 400 && n < 8; pct++)
if (abs(pct - (int)value) <= 25 && MovField((DWORD)(0x28000 * (double)pct / 100.0)) >= 0 && MovField((DWORD)(0x21000 * (double)pct / 100.0)) >= 0)
{
CString p;
p.Format(n ? _T(", %d") : _T("%d"), pct);
near_ += p;
n++;
}
CString msg;
msg.Format(_T("The speed %ld%% cannot be stored exactly: the game keeps it as an 8 bit number shifted by an even amount, so only some values fit."), value);
if (!near_.IsEmpty())