-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMod.cs
More file actions
1693 lines (1448 loc) · 62.1 KB
/
Mod.cs
File metadata and controls
1693 lines (1448 loc) · 62.1 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
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SharpTune;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;
using SharpTune.Properties;
using SharpTuneCore;
namespace SharpTune.RomMod
{
public sealed class ModDirection
{
private readonly String name;
private readonly int value;
public static readonly ModDirection Apply = new ModDirection(1, "Apply");
public static readonly ModDirection Remove = new ModDirection(2, "Remove");
public static readonly ModDirection Upgrade = new ModDirection(3, "Ugrade");
private ModDirection(int value, String name)
{
this.name = name;
this.value = value;
}
public override String ToString()
{
return name;
}
}
/// <summary>
/// Defines and Applies a Mod (series of patches) to a ROM.
/// </summary>
public class Mod
{
public string TestBuildWarning = @"WARNING: This is an EXPERIMENTAL TESTING build. "
+@"There is a RISK that this may BRICK YOUR ECU AND RENDER YOUR CAR UNDRIVEABLE! "
+ @"Please take the proper precautions (arrange alternate transportation, park car in a safe place, and have a SH boot mode cable prepared). " + Environment.NewLine + Environment.NewLine
+@"UNAUTHORIZED DISTRIBUTION OR SHARING STRICTLY PROHIBITED. OFFROAD USE ONLY. NO WARRANTY. THIS SOFTWARE IS LICENSED TO YOU “AS IS,” "
+@"AND WITHOUT ANY WARRANTY OF ANY KIND, WHETHER ORAL, WRITTEN, EXPRESS, IMPLIED OR STATUTORY, "
+ @"INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT." + Environment.NewLine + Environment.NewLine
+@"BY CLICKING OK, YOU AGREE TO THE ABOVE TERMS.";
public string ReleaseBuildWarning = @"UNAUTHORIZED DISTRIBUTION OR SHARING STRICTLY PROHIBITED. OFFROAD USE ONLY. NO WARRANTY. THIS SOFTWARE IS LICENSED TO YOU “AS IS,” "
+@"AND WITHOUT ANY WARRANTY OF ANY KIND, WHETHER ORAL, WRITTEN, EXPRESS, IMPLIED OR STATUTORY, "
+ @"INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. " + Environment.NewLine + Environment.NewLine
+@"BY CLICKING OK, YOU AGREE TO THE ABOVE TERMS.";
public const uint BaselineOffset = 0xFF000000;
private const uint metadataAddress = 0x80001000;
private const uint requiredVersionPrefix = 0x12340000;
private const uint calibrationIdPrefix = 0x12340001;
private const uint patchPrefix = 0x12340002;
private const uint copyPatchPrefix = 0x12340012;
private const uint newPatchPrefix = 0x12340004;
private const uint copyNewPatchPrefix = 0x12340014;
private const uint replace4BytesPrefix = 0x12340003;
private const uint replaceLast2Of4BytesPrefix = 0x12340013;
private const uint modNamePrefix = 0x12340007;
private const uint modBuildPrefix = 0x12340009;
private const uint modAuthorPrefix = 0x12340008;
public const uint endoffile = 0x00090009;
private const uint jsrhookPrefix = 0x1234000A;
private const uint ecuIdPrefix = 0x1234000B;
private const uint newEcuIdPrefix = 0x1234000C;
private const uint modInfoPrefix = 0x1234000D;
private const uint modIdPrefix = 0x1234000F;
private const string delim = "\0\0\0\0\0";
public long FileSize { get; private set; }
public string FileName { get; private set; }
public string FilePath { get; private set; }
public uint CalIdAddress { get; private set; }
public uint CalIdLength { get; private set; }
public bool isApplied { get; set; }
public bool isResource { get; private set; }
public bool isCompat { get; private set; }
public bool isAuthd { get; private set; }
public string info { get; private set; }
public Stream modStream { get; private set; }
public string direction
{
get
{
if (isApplied)
return "Remove";
else
return "Apply";
}
private set { }
}
public string ModBuild { get; private set; }
public string ModAuthor { get; private set; }
public string ModInfo { get; private set; }
public uint ModIdentAddress { get; private set; }
public string ModIdent { get; private set; }
public BlobList blobList { get; set; }
public string InitialCalibrationId { get; private set; }
public string FinalCalibrationId { get; private set; }
private readonly SRecordReader reader;
public uint EcuIdAddress { get; private set; }
public uint EcuIdLength { get; private set; }
private string _InitialEcuId;
public string InitialEcuId
{
get
{
return _InitialEcuId;
}
private set
{
_InitialEcuId = value.ToUpper();
}
}
private string _FinalEcuId;
public string FinalEcuId
{
get
{
return _FinalEcuId;
}
private set
{
_FinalEcuId = value.ToUpper();
}
}
public List<Patch> patchList;
public List<Patch> unPatchList;
public ModDefinition modDef { get; private set; }
/// <summary>
/// Constructor for external mods
/// </summary>
/// <param name="modPath"></param>
public Mod(string modPath)
{
isAuthd = false;
this.patchList = new List<Patch>();
this.ModAuthor = "Unknown Author";
this.ModBuild = "Unknown Build";
FileInfo f = new FileInfo(modPath);
FileSize = f.Length;
FileName = f.Name;
FilePath = modPath;
isResource = false;
reader = new SRecordReader(modPath);
TryReadPatches();
TryReversePatches();
}
/// <summary>
/// Constructor for embedded mods
/// </summary>
/// <param name="s"></param>
/// <param name="modPath"></param>
public Mod(Stream s, string modPath)
{
isAuthd = false;
this.patchList = new List<Patch>();
this.ModAuthor = "Unknown Author";
this.ModBuild = "Unknown Build";
reader = new SRecordReader(s, modPath);
FileName = modPath;
FilePath = modPath;
isResource = true;
modStream = s;
TryReadPatches();
TryReversePatches();
}
/// <summary>
/// Constructor for partial-patches
/// </summary>
/// <param name="modPath"></param>
/// <param name="build"></param>
public Mod(string modPath, string build)
{
isAuthd = false;
this.patchList = new List<Patch>();
this.ModAuthor = "Unknown Author";
this.ModBuild = build;
FileInfo f = new FileInfo(modPath);
FileSize = f.Length;
FileName = f.Name;
FilePath = modPath;
isResource = false;
reader = new SRecordReader(modPath);
//TryReadPatches();
//TryReversePatches();
}
public bool TryDefinition(AvailableDevices ad, string defPath)
{
//Read metadata
try
{
Trace.WriteLine("Attempting to read definition metadata");
this.modDef = new ModDefinition(ad, this);
if (!modDef.TryReadDefs(defPath)) return false;
Trace.WriteLine("Success reading definition meatdata");
}
catch (Exception e)
{
Trace.WriteLine("Error reading definition metadata");
Trace.WriteLine(e.Message);
return false;
}
//Create RR logger def
try
{
Trace.WriteLine("Attempting to create RR logger definition");
//TODO: move RR stuff into definition?
//prompt to select logger type
modDef.NewRRLogDefInheritWithTemplate(this.modDef.RamTableList, Settings.Default.RomRaiderLoggerDefPath + @"\MerpMod\" + this.ModBuild + @"\" + this.ModIdent + ".xml", Settings.Default.RomRaiderLoggerDefPath + @"\MerpMod\base.xml", this.InitialEcuId.ToString(), this.FinalEcuId.ToString());
Trace.WriteLine("Success creating RR logger definition");
}
catch (Exception e)
{
Trace.WriteLine("Error creating RR logger definition");
Trace.WriteLine(e.Message);
return false;
}
//Create RR ecu def
try
{
Trace.WriteLine("Attempting to create RR ecu definition");
//TODO: move RR stuff into definition?
//prompt to select logger type
string path = Settings.Default.RomRaiderEcuDefPath + @"\MerpMod\" + this.ModBuild + @"\"; //TODO: use settings???
Directory.CreateDirectory(path);
path += this.ModIdent + ".xml";
modDef.PopulateRREcuDefStub(path);
Trace.WriteLine("Success creating RR ecu definition");
}
catch (Exception e)
{
Trace.WriteLine("Error creating RR ecu definition");
Trace.WriteLine(e.Message);
return false;
}
//Create ECUFlash definition
try {
if (ModBuild != null)
defPath = defPath + "/MerpMod/" + ModBuild + "/";
Directory.CreateDirectory(defPath);
defPath += ModIdent.ToString() + ".xml";
Trace.WriteLine("Attempting to export ECUFlash definition to: " + defPath);
modDef.definition.ExportEcuFlashXML(defPath);
Trace.WriteLine("Success exporting ECUFlash definition");
return true;
}
catch (Exception e)
{
Trace.WriteLine("Error exporting ECUFlash definition");
Trace.WriteLine(e.Message);
return false;
}
}
public bool TryCheckApplyMod(string romPath, string outPath, bool apply, bool commit)
{
if (patchList == null || patchList.Count == 0)
return false;
///string workingPath = outPath + ".temp";
//File.Copy(romPath, outPath, true);
//File.Copy(romPath, workingPath, true);//File.Open(workingPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
MemoryStream outStream = new MemoryStream();
using (FileStream fileStream = File.OpenRead(romPath))
{
outStream.SetLength(fileStream.Length);
fileStream.Read(outStream.GetBuffer(), 0, (int)fileStream.Length);
}
Trace.WriteLine(String.Format("This patch file was intended for: {0}.", this.InitialCalibrationId));
Trace.WriteLine(String.Format("This patch file converts ROM to: {0}.", this.ModIdent));
Trace.WriteLine(String.Format("Build: " + this.ModBuild));
Trace.WriteLine(String.Format("This mod was created by: {0}.", this.ModAuthor));
Trace.WriteLine(String.Format("Mod Info: " + this.ModInfo));
if (apply && TryValidatePatches(outStream))
{
isApplied = false;
isCompat = true;
Trace.WriteLine("This patch file was NOT previously applied to this ROM file.");
}
else if (!apply && TryValidateUnPatches(outStream))
{
isApplied = true;
isCompat = true;
Trace.WriteLine("This patch file was previously applied to this ROM file.");
}
else
isCompat = false;
if (!isCompat)
{
Trace.WriteLine(this.FileName + " is mod is NOT compatible with this ROM file.");
return false;
}
if (!commit)
{
Trace.WriteLine(this.FileName + " is compatible with this ROM file.");
return true;
}
if(isAuthd)
Console.WriteLine("VIN Auth detected in patch: " + this.FileName);
if (isApplied)
{
Trace.WriteLine("Removing patch.");
if (this.TryRemoveMod(outStream))
{
Trace.WriteLine("Verifying patch removal.");
using (Verifier verifier = new Verifier(outStream, reader, !isApplied))
{
if (!verifier.TryVerify(this.patchList))
{
Trace.WriteLine("Verification failed, ROM file not modified.");
return false;
}
}
//File.Copy(workingPath, outPath, true);
//File.Delete(workingPath);
try
{
using (FileStream fileStream = File.OpenWrite(outPath))
{
outStream.Seek(0, SeekOrigin.Begin);
outStream.CopyTo(fileStream);
}
Trace.WriteLine(String.Format("ROM file modified successfully, Mod has been removed. Successfully saved image to {0}", outPath));
}
catch (System.Exception excpt)
{
MessageBox.Show("Error accessing file! It is locked!", "SharpTune", MessageBoxButtons.OK, MessageBoxIcon.Error);
Trace.WriteLine("Error accessing file! It is locked!");
Trace.WriteLine(excpt.Message);
return false;
}
return true;
}
else
{
Trace.WriteLine("The ROM file has not been modified.");
return false;
}
}
else
{
DialogResult res;
if (ModBuild.ContainsCI("debug") || ModBuild.ContainsCI("testing"))
res = MessageBox.Show(TestBuildWarning, "WARNING",MessageBoxButtons.OKCancel,MessageBoxIcon.Hand);
else
res = MessageBox.Show(ReleaseBuildWarning, "WARNING",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
if (res != DialogResult.OK)
return false;
if (!ModBuild.ContainsCI("debug"))// && !isAuthd)//todo field 'isdebug'
{
Process.Start(Settings.Default.DonateUrl);
MessageBox.Show("Please consider donating, this work has been provided to you for free after years of hard work. Professional Tuners: distributing this work, including flashing a customer's car, is a violation of the license terms. Professional Tuners must obtain authorization to distribute this work by donation on a per-vehicle basis.", "Please Donate");
}
Trace.WriteLine("Applying mod.");
if (this.TryApplyMod(outStream))
{
Trace.WriteLine("Verifying mod.");
using (Verifier verifier = new Verifier(outStream, reader, !isApplied))
{
if (!verifier.TryVerify(this.patchList))
{
Trace.WriteLine("Verification failed, ROM file not modified.");
return false;
}
}
if (isAuthd)
{
//if (!SharpTuner.AuthenticateMod(outStream))
//{
outStream.Dispose();
Console.WriteLine("Authentication Failed!! Please Contact Support");
MessageBox.Show("Authentication Failed!! Please Contact Support");
return false;
//}
//Console.WriteLine("Auth Success");
}
try
{
using (FileStream fileStream = File.OpenWrite(outPath))
{
outStream.Seek(0, SeekOrigin.Begin);
outStream.CopyTo(fileStream);
}
Trace.WriteLine(String.Format("ROM file modified successfully, Mod has been applied. Successfully saved image to {0}", outPath));
outStream.Dispose();
//File.Copy(workingPath, outPath, true);
//File.Delete(workingPath);
//TODO CHECK outstream disposal!!!
Console.WriteLine("ROM file modified successfully, mod has been applied.");
return true;
}
catch (System.Exception excpt)
{
MessageBox.Show("Error accessing file! It is locked!", "SharpTune", MessageBoxButtons.OK, MessageBoxIcon.Error);
Trace.WriteLine("Error accessing file! It is locked!");
Trace.WriteLine(excpt.Message);
return false;
}
}
else
{
Trace.WriteLine("The ROM file has not been modified.");
return false;
}
}
}
/// <summary>
/// Create the patch start/end metadata from the patch file.
/// </summary>
public bool TryReadPatches()
{
List<Blob> blobs = new List<Blob>();
BlobList bloblist;
if (!this.TryReadBlobs(out bloblist))
{
return false;
}
blobs = bloblist.Blobs;
this.blobList = bloblist;
Blob metadataBlob;
if (!this.TryGetMetaBlob(metadataAddress, 10, out metadataBlob, blobs))
{
Trace.WriteLine("This patch file does not contain metadata.");
return false;
}
if (!this.TryReadMetadata(metadataBlob, blobs))
{
return false;
}
return true;
}
/// <summary>
/// Print patch descriptions to the console.
/// </summary>
public void PrintPatches()
{
foreach (Patch patch in this.patchList)
{
if (patch.StartAddress > BaselineOffset)
{
continue;
}
Trace.WriteLine(patch.ToString());
}
}
/// <summary>
/// Reverses the "direction" of the patch by start address manipulation
/// </summary>
/// <returns></returns>
///
public bool TryReversePatches()
{
using (var stream = new System.IO.MemoryStream())
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, patchList); //serialize to stream
stream.Position = 0;
//deserialize from stream.
unPatchList = binaryFormatter.Deserialize(stream) as List<Patch>;
}
//Console.ReadKey();
foreach (Patch patch in this.unPatchList)
{
//Swap contents
Blob tempblob;
if (patch.IsNewPatch)
{
//set all bytes in baseline blob to 0xFF
for (int i = 0; i < patch.Payload.Content.Count; i++)
{
patch.Payload.Content[i] = 0xFF;
}
}
else
{
tempblob = patch.Baseline.CloneWithNewStartAddress(patch.Baseline.StartAddress - BaselineOffset);
patch.Baseline = patch.Payload.CloneWithNewStartAddress(patch.Payload.StartAddress + BaselineOffset);
patch.Payload.Content.Clear();
patch.Payload = tempblob;
}
//OLD CODE
//new payload
//baselineBlob = baselineBlob.CloneWithNewStartAddress(baselineBlob.StartAddress - BaselineOffset);
//new baseline
//modifiedBlob = modifiedBlob.CloneWithNewStartAddress(modifiedBlob.StartAddress + BaselineOffset);
//first blob in list is the patch payload, second is baseline
//newBlobs.Add(baselineBlob);
//newBlobs.Add(modifiedBlob);
}
return true;
}
/// <summary>
/// Determine whether the data that the patch was designed to overwrite match what's actually in the ROM.
/// </summary>
public bool TryValidatePatches(Stream romStream)
{
Trace.WriteLine("Attempting to validate patches...");
bool allPatchesValid = true;
foreach (Patch patch in this.patchList)
{
Console.Write(patch.ToString() + " - ");
if (patch.GetType() == typeof(PullJSRHookPatch))
{
if (!this.ValidateJSRHookBytes((PullJSRHookPatch)patch, romStream))
{
// Pass/fail message is printed by ValidateBytes().
allPatchesValid = false;
}
}
else
{
if (!this.ValidateBytes(patch, romStream))
{
// Pass/fail message is printed by ValidateBytes().
allPatchesValid = false;
}
}
}
if (!allPatchesValid)
{
Trace.WriteLine("Invalid patches found!!");
return false;
}
Trace.WriteLine("All patches validated!!");
return true;
}
/// <summary>
/// Determine whether the data that the patch was designed to overwrite match what's actually in the ROM.
/// </summary>
public bool TryValidateUnPatches(Stream romStream)
{
Trace.WriteLine("Attempting to validate patch removal...");
bool allPatchesValid = true;
foreach (Patch patch in this.unPatchList)
{
Console.Write(patch.ToString() + " - ");
if (patch.IsNewPatch)
{
Trace.WriteLine("DATA SECTION WILL BE OVERWRITTEN");
continue;
}
if (!this.ValidateBytes(patch, romStream))
{
// Pass/fail message is printed by ValidateBytes().
allPatchesValid = false;
}
}
if (!allPatchesValid)
{
return false;
}
return true;
}
/// <summary>
/// Try to apply the patches to the ROM.
/// </summary>
public bool TryApplyMod(Stream romStream)
{
foreach (Patch patch in this.patchList)
{
if (!TryApplyPatch(patch, romStream))
{
return false;
}
}
return true;
}
/// <summary>
/// Try to remove patches from a ROM
/// </summary>
/// <returns></returns>
public bool TryRemoveMod(Stream romStream)
{
foreach (Patch patch in this.unPatchList)
{
if (!this.TryApplyPatch(patch,romStream))
{
return false;
}
}
return true;
}
/// <summary>
/// Extract actual ROM data, for appending to a patch file.
/// </summary>
public bool TryPrintBaselines(string patchPath, Stream romStream)
{
string p = this.ModIdent.ToString() + ".patch";
Trace.WriteLine("Copying Patch to " + p);
File.Copy(patchPath, p , true);
this.FilePath = p;
this.FileName = p;
bool result = true;
foreach (Patch patch in this.patchList)
{
if (!this.TryCheckPrintBaseline(patch,romStream))
{
result = false;
Trace.WriteLine("ERROR OCCURRED DURING BASELINE PRINT, POSSIBLE MISMATCH BETWEEN METADATA AND ROM!");
break;
}
}
if (result)
Trace.WriteLine("BASELINE SUCCESSFUL");
return result;
}
/// <summary>
/// Try to read blobs from the patch file.
/// </summary>
private bool TryReadBlobs(out BlobList blist)
{
BlobList list = new BlobList();
this.reader.Open();
SRecord record;
while (this.reader.TryReadNextRecord(out record))
{
if (!record.IsValid)
{
Trace.WriteLine("The patch file contains garbage - was it corrupted somehow?");
Trace.WriteLine(String.Format("Line {0}: {1}", record.LineNumber, record.RawData));
blist = null;
return false;
}
list.ProcessRecord(record);
}
blist = list;
return true;
}
/// <summary>
/// Try to read the patch file metadata (start and end addresses of each patch, etc).
/// </summary>
private bool TryReadMetadata(Blob blob, List<Blob> blobs)
{
int offset = 0;
if (!TryConfirmPatchVersion(blob, ref offset))
{
return false;
}
if (!TryReadMetaHeader8(blob, ref offset))
{
return false;
}
offset = 0;
if (!this.TryReadPatches(blob, ref offset, blobs))
{
return false;
}
if (this.patchList.Count < 3)
{
Trace.WriteLine("This patch file contains no patches.");
return false;
}
return true;
}
/// <summary>
/// Try to read the 'required version' metadata.
/// </summary>
private bool TryConfirmPatchVersion(Blob blob, ref int offset)
{
uint tempUInt32 = 0;
if (!blob.TryGetUInt32(ref tempUInt32, ref offset))
{
Trace.WriteLine(String.Format("This patch file's metadata is way too short (no version metadata)."));
return false;
}
if (tempUInt32 != requiredVersionPrefix)
{
Trace.WriteLine(String.Format("This patch file's metadata starts with {0}, it should start with {1}", tempUInt32, requiredVersionPrefix));
return false;
}
if (!blob.TryGetUInt32(ref tempUInt32, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no version).");
return false;
}
if (tempUInt32 == RomMod.AuthVersion)
{
isAuthd = true;
return true;
}
if (tempUInt32 != RomMod.Version)
{
Trace.WriteLine(String.Format("This is RomPatch.exe version {0}.", RomMod.Version));
Trace.WriteLine(String.Format("This patch file requires version {0}.", tempUInt32));
return false;
}
return true;
}
/// <summary>
/// Try to read the initial and final calibration IDs
/// </summary>
private bool TryReadCalibrationChange(Blob blob, ref int offset)
{
uint tempUInt32 = 0;
if (!blob.TryGetUInt32(ref tempUInt32, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no calibration metadata).");
return false;
}
if (tempUInt32 != calibrationIdPrefix)
{
Trace.WriteLine(String.Format("Expected calibration id prefix {0:X8}, found {1:X8}", calibrationIdPrefix, tempUInt32));
return false;
}
if (!blob.TryGetUInt32(ref tempUInt32, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no calibration address).");
return false;
}
uint calibrationAddress = tempUInt32;
if (!blob.TryGetUInt32(ref tempUInt32, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no calibration length).");
return false;
}
uint calibrationLength = tempUInt32;
string initialCalibrationId;
if (!this.TryReadCalibrationId(blob, ref offset, out initialCalibrationId))
{
return false;
}
this.InitialCalibrationId = initialCalibrationId;
string finalCalibrationId;
if (!this.TryReadCalibrationId(blob, ref offset, out finalCalibrationId))
{
return false;
}
this.FinalCalibrationId = finalCalibrationId;
// Synthesize calibration-change patch and blobs.
Patch patch = new Patch( "Calibration ID Patch",
calibrationAddress,
calibrationAddress + (calibrationLength - 1));
patch.IsMetaChecked = true;
patch.Baseline = new Blob(
calibrationAddress + Mod.BaselineOffset,
Encoding.ASCII.GetBytes(initialCalibrationId));
patch.Payload = new Blob(
calibrationAddress,
Encoding.ASCII.GetBytes(finalCalibrationId));
this.patchList.AddPatch(patch);
return true;
}
/// <summary>
/// Try to read the calibration ID from the patch metadata.
/// </summary>
private bool TryReadCalibrationId(Blob blob, ref int offset, out string calibrationId)
{
calibrationId = string.Empty;
List<byte> calibrationIdBytes = new List<byte>();
byte tempByte = 0;
for (int index = 0; index < 16; index++)
{
if (!blob.TryGetByte(ref tempByte, ref offset))
{
Trace.WriteLine("This patch file's metadata ran out before the complete calibration ID could be found.");
return false;
}
if (calibrationId == string.Empty)
{
if (tempByte != 0)
{
calibrationIdBytes.Add(tempByte);
}
else
{
calibrationId = System.Text.Encoding.ASCII.GetString(calibrationIdBytes.ToArray());
}
}
else
{
if (tempByte != 0)
{
Trace.WriteLine("This patch file's metadata contains garbage after the calibration ID.");
return false;
}
}
}
return true;
}
private bool TryReadMetaHeader8(Blob metadata, ref int offset)
{
UInt32 cookie = 0;
uint tempInt = 0;
Patch patch = null;
while ((metadata.Content.Count > offset + 8) &&
metadata.TryGetUInt32(ref cookie, ref offset))
{
if (cookie == Mod.calibrationIdPrefix)
{
if (!metadata.TryGetUInt32(ref tempInt, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no calibration address).");
return false;
}
this.CalIdAddress = tempInt;
if (!metadata.TryGetUInt32(ref tempInt, ref offset))
{
Trace.WriteLine("This patch file's metadata is way too short (no calibration length).");
return false;
}
this.CalIdLength = tempInt;
string initialCalibrationId;
if (!this.TryReadCalibrationId(metadata, ref offset, out initialCalibrationId))
{
return false;
}
this.InitialCalibrationId = initialCalibrationId;
string finalCalibrationId;
if (!this.TryReadCalibrationId(metadata, ref offset, out finalCalibrationId))
{
return false;
}
if (finalCalibrationId.ContainsCI("ffffffff"))
{
StringBuilder s = new StringBuilder(initialCalibrationId, 0, initialCalibrationId.Length, initialCalibrationId.Length);
s.Remove(initialCalibrationId.Length - 3, 2);
s.Insert(initialCalibrationId.Length - 3, "MM");
FinalCalibrationId = s.ToString();
}
else
{
this.FinalCalibrationId = finalCalibrationId;
}
// Synthesize calibration-change patch and blobs.
patch = new Patch( "Calibration ID Patch",
CalIdAddress,
CalIdAddress + (CalIdLength - 1));
patch.IsMetaChecked = true;
patch.Baseline = new Blob(
CalIdAddress + Mod.BaselineOffset,
Encoding.ASCII.GetBytes(initialCalibrationId));
patch.Payload = new Blob(
CalIdAddress,
Encoding.ASCII.GetBytes(FinalCalibrationId));
this.patchList.AddPatch(patch);
}
else if (cookie == modIdPrefix)
{
if (metadata.TryGetUInt32(ref tempInt, ref offset))
{
this.ModIdentAddress = tempInt;
}
string metaString = null;
if (this.TryReadMetaString(metadata, out metaString, ref offset))
{
// found modName, output to string!
this.ModIdent = metaString;
}
}
else if (cookie == ecuIdPrefix)
{
if (metadata.TryGetUInt32(ref tempInt, ref offset))
{
this.EcuIdAddress = tempInt;
}
if (metadata.TryGetUInt32(ref tempInt, ref offset))
{
this.EcuIdLength = tempInt;
}
string metaString = null;
if (this.TryReadMetaString(metadata, out metaString, ref offset))
{
// found modName, output to string!
this.InitialEcuId = metaString;
}
metadata.TryGetUInt32(ref tempInt, ref offset);
if (this.TryReadMetaString(metadata, out metaString, ref offset))
{
// found modName, output to string!
this.FinalEcuId = metaString;
}
}
else if (cookie == modAuthorPrefix)
{
string metaString = null;
if (this.TryReadMetaString(metadata, out metaString, ref offset))