forked from fileoffset/JDO
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Objects.cs
1955 lines (1709 loc) · 73.9 KB
/
Objects.cs
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
using System;
using System.Collections;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Text;
using System.Collections.Generic;
namespace JavaDeObfuscator
{
// ******************************************************************************** //
// ************************** ACTUAL DEOBFUSCATOR ******************************** //
// ******************************************************************************** //
// These class does the actual deobfuscation
class TDeObfuscator
{
// event delegates
public delegate void ProgressHandler(int max, int Progress);
public static event ProgressHandler Progress;
// private variables
private ArrayList FFiles;
private ArrayList FClassFiles;
private ArrayList FInterfaces;
private ArrayList FChangeList;
private Dictionary<string, string> FPackages;
private bool FThoroughMode;
private bool FRenameClasses;
public bool UseUniqueNums { get; set; }
public string OutputDir { get; set; }
/// <summary>
/// The DeObfuscating engine
/// </summary>
/// <param name="Files">All of the files in the project. Must be full path + filename</param>
public TDeObfuscator(ArrayList Files)
{
if (Files == null)
return;
FFiles = Files;
foreach (string f in FFiles)
{
if (!File.Exists(f))
return;
}
FThoroughMode = true;
FRenameClasses = true;
FPackages = new Dictionary<string, string>();
}
public readonly string[] bad_names = { "import", "package", "class", "interface", "enum", "implements", "extends",
"private", "protected", "public", "final", "abstract", "static", "strictfp", "native", "transient",
"synchronized", "volatile", "void", "for", "do", "while", "break", "continue", "if", "else",
"switch", "case", "default", "try", "catch", "finally", "throw", "throws", "instanceof", "assert",
"return", "boolean", "byte", "char", "double", "float", "int", "long", "short", "true", "false",
"null", "super", "this", "new", "const", "goto" };
public bool DoRename(string Name)
{
Name = Common.GetClassName(Name);
if (Name[0] == '<')
return false;
if (Name.Length > 0 && Name.Length <= 2)
return true;
if (Name.Length > 0 && Name.Length <= 3 && Name.Contains("$"))
return true;
foreach (string s in bad_names)
{
if (s == Name)
return true;
}
return false;
}
private bool ClassNameExists(String Name)
{
foreach (Object ClassFile in FClassFiles.ToArray())
{
if (((TClassFile)ClassFile).ThisClassName == Name)
return true;
}
return false;
}
private ArrayList DeObfuscateSingleFile(int index, RenameDatabase RenameStore)
{
TClassFile ClassFile = (TClassFile)FClassFiles[index];
if (ClassFile == null)
return null;
// add the class name to the head of the changelist
FChangeList = new ArrayList();
FChangeList.Add(ClassFile.ThisClassName);
string OriginalClassName = ClassFile.ThisClassName;
string OriginalClassAndType = ClassFile.ThisClassName + " : " + ClassFile.SuperClassName;
// rename the class and add the new class name to the changelist at [1]
if (FRenameClasses && RenameStore.GetNewClassNameOnly(OriginalClassAndType) != null)
{
// check if we need to use a user-supplied class name first
string NewClassName = RenameStore.GetNewClassNameOnly(OriginalClassAndType);
while (ClassNameExists(NewClassName))
{
NewClassName += "_";
}
FChangeList.Add(ClassFile.ChangeClassName(NewClassName));
}
else if (FRenameClasses)
{
bool classReName = DoRename(OriginalClassName);
string NewClassName = OriginalClassName;
if (classReName)
{
if (UseUniqueNums)
{
string format = "{0:D" + (FClassFiles.Count.ToString().Length + 2) + "}";
string uniqueNum = string.Format(format, Convert.ToInt64(ClassFile.ThisClassCode.ToString() + index.ToString()));
NewClassName = String.Format("Class_{0}_{1}", Common.GetClassName(OriginalClassName), uniqueNum);
}
else
NewClassName = String.Format("Class_{0}", Common.GetClassName(OriginalClassName));
// test if the filename we are changing to hasnt already been used!
while (ClassNameExists(NewClassName))
{
NewClassName += "_";
}
}
string[] fragments = OriginalClassName.Split('/');
int idx = fragments.Length - 1;
bool packageReName = false;
string PackageName = string.Empty;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < idx; i++)
{
string fragment = fragments[i];
sb.Append(fragment);
string OriginalPackageName = sb.ToString();
if (!FPackages.TryGetValue(OriginalPackageName, out PackageName))
{
if (DoRename(fragment))
{
packageReName = true;
PackageName = sb.Append(FPackages.Count.ToString().PadLeft(2, '0')).ToString();
FPackages.Add(OriginalPackageName, PackageName);
}
}
else
{
packageReName = true;
sb.Remove(0, sb.Length);
sb.Append(PackageName);
}
sb.Append('/');
}
string ClassName = classReName ? NewClassName : fragments[idx];
NewClassName = sb.Append(ClassName).ToString();
if (classReName || packageReName)
{
FChangeList.Add(ClassFile.ChangeClassName(NewClassName));
}
else
{
FChangeList.Add(OriginalClassName);
}
}
else
FChangeList.Add(OriginalClassName);
// process the Methods
for (int i = 0; i < ClassFile.Methods.Items.Count; i++)
{
MethodInfo mi = (MethodInfo)ClassFile.Methods.Items[i];
RenameData rd = RenameStore.GetNewMethodInfo(OriginalClassAndType, mi.Descriptor, mi.Name.Value);
// this is the rule for renaming
if (DoRename(mi.Name.Value) || rd != null)
{
// clone the original method
TMethodChangeRecord mcr = new TMethodChangeRecord(mi);
// rename all of the functions something meaningful
string NewName;
// if the offset is zero, it probably means its an abstract method
if (ClassFile.AccessFlags == AccessFlags.ACC_INTERFACE)
NewName = String.Format("sub_iface_{0:x}", i);
else if (mi.Offset != 0)
NewName = String.Format("sub_{0:x}", mi.Offset);
else
NewName = String.Format("sub_null_{0:x}", i);
/*if (FThoroughMode)
{
int j = 0;
while (ClassFile.Methods.MethodNameExists(NewName))
{
// rename the method
NewName = NewName + "_" + j;
j++;
}
}*/
// user supplied names take precedence
if (rd != null)
{
NewName = rd.FieldName;
}
// change the method name
ClassFile.ChangeMethodName(i, NewName);
// set the
mcr.ChangedTo(mi);
FChangeList.Add(mcr);
}
// fix the descriptor regardless
ClassFile.ChangeMethodParam(i, OriginalClassName, ClassFile.ThisClassName);
}
// process the Fields
for (int i = 0; i < ClassFile.Fields.Items.Count; i++)
{
FieldInfo fi = (FieldInfo)ClassFile.Fields.Items[i];
RenameData rd = RenameStore.GetNewFieldInfo(OriginalClassAndType, fi.Descriptor, fi.Name.Value);
if (DoRename(fi.Name.Value) || rd != null)
{
// clone the original method
TFieldChangeRecord fcr = new TFieldChangeRecord(fi);
// rename all of the fields something meaningful
string NewName;
// if the offset is zero, it probably means its a null/abstract method
if (fi.Offset != 0)
NewName = String.Format("var_{0:x}", fi.Offset);
else
NewName = String.Format("var_null_{0:x}", fi.Offset);
/*if (FThoroughMode)
{
int j = 0;
while (ClassFile.Methods.FieldNameExists(NewName))
{
// rename the field
NewName = NewName + "_" + j;
j++;
}
}*/
if (rd != null)
{
NewName = rd.FieldName;
}
ClassFile.ChangeFieldName(i, NewName);
fcr.ChangedTo(fi);
FChangeList.Add(fcr);
}
// fix the descriptor regardless
ClassFile.ChangeFieldType(i, OriginalClassName, ClassFile.ThisClassName);
}
return FChangeList;
}
/// <summary>
/// This function runs over a class, fixing up any references from a deobfuscated file.
/// </summary>
/// <param name="Index">This is the index of the ClassFile to have its references updated</param>
/// <param name="ChangeList">This is a list of before/after values from a previously deobfuscated file</param>
private void FixReferencePass1(int Index, ArrayList ChangeList, ArrayList OwnerChangeList)
{
/* the first pass does the following:
* - replaces the Super Class name (if it needs replacing)
* - replaces any constant method/field names (if they need replacing)
* - replaces the class field names (if needed)
* it does NOT change the original class name */
TClassFile ClassFile = (TClassFile)FClassFiles[Index];
if (ClassFile == null)
return;
// - ChangeList[0] is always a string, which is the parent name of the deobfuscated class
// - ChangeList[1] is always the deobfuscated (new) class name... yes i know this is lame :P
string OldParentName = (string)ChangeList[0];
string NewParentName = (string)ChangeList[1];
// check the Super class name if it needs renaming
if (ClassFile.SuperClassName == OldParentName)
{
ClassFile.ChangeSuperClassName(NewParentName);
}
// loop through the constant pool for field/method references
// check the parent of each, and if the parent is the class we have
// just modified, try and match it to one of the changes
// in the changearray
for (int i = 0; i < ClassFile.ConstantPool.MaxItems(); i++)
{
if (ClassFile.ConstantPool.Item(i) is ConstantPoolMethodInfo)
{
ConstantPoolMethodInfo ci = (ConstantPoolMethodInfo)ClassFile.ConstantPool.Item(i);
// check its parent
if (ci.ParentClass.Name == OldParentName || ci.ParentClass.Name == NewParentName)
{
// check the descriptor
// - for fields this is the field type
// - for methods this is the parameter list
// if parents are the same, check the name and descriptor
// against the list of originals
for (int j = 2; j < ChangeList.Count; j++)
{
if ((ChangeList[j] is TMethodChangeRecord) && (ci is ConstantMethodrefInfo || ci is ConstantInterfaceMethodrefInfo))
{
if (ci is ConstantInterfaceMethodrefInfo)
{
// handle interface references differently
TMethodChangeRecord mcr = (TMethodChangeRecord)ChangeList[j];
// if found update it to the overridden version
if (mcr.OriginalMethod.Name.Value == ci.NameAndType.Name &&
mcr.OriginalMethod.Descriptor == ci.NameAndType.Descriptor)
{
// find the overridden version
for (int k = 2; k < OwnerChangeList.Count; k++)
{
if (OwnerChangeList[k] is TMethodChangeRecord)
{
TMethodChangeRecord mcr2 = (TMethodChangeRecord)OwnerChangeList[k];
if (mcr2.OriginalMethod.Name.Value == mcr.OriginalMethod.Name.Value &&
mcr2.OriginalMethod.Descriptor == mcr.OriginalMethod.Descriptor)
{
ClassFile.ChangeConstantFieldName(i, mcr2.NewMethod.Name.Value);
break;
}
}
}
}
}
else
{
TMethodChangeRecord mcr = (TMethodChangeRecord)ChangeList[j];
// if found update it to the new version...
if (mcr.OriginalMethod.Name.Value == ci.NameAndType.Name &&
mcr.OriginalMethod.Descriptor == ci.NameAndType.Descriptor)
{
ClassFile.ChangeConstantFieldName(i, mcr.NewMethod.Name.Value);
break;
}
}
}
else if ((ChangeList[j] is TFieldChangeRecord) && (ci is ConstantFieldrefInfo))
{
TFieldChangeRecord fcr = (TFieldChangeRecord)ChangeList[j];
// if found update it to the new version...
if (fcr.OriginalField.Name.Value == ci.NameAndType.Name &&
fcr.OriginalField.Descriptor == ci.NameAndType.Descriptor)
{
ClassFile.ChangeConstantFieldName(i, fcr.NewField.Name.Value);
break;
}
}
}
}
}
}
// also loop through the Fields array to change all the Types
for (int i = 0; i < ClassFile.Fields.MaxItems(); i++)
{
ClassFile.ChangeFieldType(i, OldParentName, NewParentName);
}
// do the same for methods (fix the parameter list)
for (int i = 0; i < ClassFile.Methods.MaxItems(); i++)
{
ClassFile.ChangeMethodParam(i, OldParentName, NewParentName);
}
// and the same for all the interfaces
for (int i = 0; i < ClassFile.Interfaces.Items.Count; i++)
{
if (ClassFile.Interfaces.Item(i).Name == OldParentName)
ClassFile.ChangeInterfaceName(i, NewParentName);
}
}
/// <summary>
/// Stage 2 simply goes through the constant pool searching for a ClassInfo structure that matches
/// the obfuscated class name, and replaces it with the de-obfuscated class name.
///
/// This is to ensure that any field/variable that references that class will be updated, simply by
/// changing the class info structure at the source.
/// </summary>
/// <param name="Index">Index of the class file we want to update</param>
/// <param name="ChangeList">The array of changes we made deobfuscating a file</param>
private void FixReferencePass2(int Index, ArrayList ChangeList)
{
TClassFile ClassFile = (TClassFile)FClassFiles[Index];
if (ClassFile == null)
return;
string OldParentName = (string)ChangeList[0];
string NewParentName = (string)ChangeList[1];
// iterate through the constant pool looking for class references
// that match the old class name
for (int i = 0; i < ClassFile.ConstantPool.MaxItems(); i++)
{
if (ClassFile.ConstantPool.Item(i) is ConstantClassInfo)
{
ConstantClassInfo ci = (ConstantClassInfo)ClassFile.ConstantPool.Item(i);
// if we found a ClassInfo constant with the same name as the old name
if (ci.Name == OldParentName)
{
// create a new UTF string constant
ConstantUtf8Info ui = new ConstantUtf8Info();
// set it to the new parent name
ui.SetName(NewParentName);
// add it to the constant pool
ushort index = ClassFile.ConstantPool.Add(ui);
// set our original ClassInfo constant's name to the newly added UTF string constant
ci.SetName(index, ClassFile.ConstantPool);
}
// special condition for array type references
else if (ci.Name.IndexOf("L" + OldParentName + ";") >= 0)
{
// create a new UTF string constant
ConstantUtf8Info ui = new ConstantUtf8Info();
// set it to the new parent name
ui.SetName(ci.Name.Replace("L" + OldParentName + ";", "L" + NewParentName + ";"));
// add it to the constant pool
ushort index = ClassFile.ConstantPool.Add(ui);
// set our original ClassInfo constant's name to the newly added UTF string constant
ci.SetName(index, ClassFile.ConstantPool);
}
}
else if (ClassFile.ConstantPool.Item(i) is ConstantPoolMethodInfo)
{
// check the descriptor
// - for fields this is the field type
// - for methods this is the parameter list
ClassFile.ChangeConstantFieldType(i, OldParentName, NewParentName);
}
}
}
private void FixReferences(ArrayList MasterChangeList)
{
// loop through the change record's and apply them to each file
// (except itself)
for (int i = 0; i < FClassFiles.Count; i++)
{
for (int j = 0; j < MasterChangeList.Count; j++)
{
FixReferencePass1(i, (ArrayList)MasterChangeList[j], (ArrayList)MasterChangeList[i]);
}
}
for (int i = 0; i < FClassFiles.Count; i++)
{
for (int j = 0; j < MasterChangeList.Count; j++)
{
FixReferencePass2(i, (ArrayList)MasterChangeList[j]);
}
}
}
/// <summary>
/// Find the index of the parent of the classfile, if it exists in the project.
/// Returns: positive integer index if found, else -1 if not found
/// </summary>
/// <param name="Index">Index of class file to find parent of</param>
/// <returns></returns>
int FindParent(int Index)
{
string ParentName = ((TClassFile)FClassFiles[Index]).SuperClassName;
for (int i = 0; i < FClassFiles.Count; i++)
{
if (i != Index && ((TClassFile)FClassFiles[i]).ThisClassName == ParentName)
{
return i;
}
}
return -1;
}
/*int FindClass(string ClassName)
{
for (int i = 0; i < FClassFiles.Count; i++)
{
if (((TClassFile)FClassFiles[i]).ThisClassName == ClassName)
{
return i;
}
}
return -1;
}*/
int FindInterface(string ClassName)
{
for (int i = 0; i < FClassFiles.Count; i++)
{
if (((TClassFile)FClassFiles[i]).AccessFlags == AccessFlags.ACC_INTERFACE &&
((TClassFile)FClassFiles[i]).ThisClassName == ClassName)
{
return i;
}
}
return -1;
}
ArrayList AddInheritance(int Index, ArrayList MasterChangeList)
{
int Parent = FindParent(Index);
if (Parent >= 0)
{
ArrayList OriginalChangeList = (ArrayList)MasterChangeList[Index];
ArrayList ParentChangeList = (ArrayList)MasterChangeList[Parent];
for (int i = 2; i < ParentChangeList.Count; i++)
{
// add the rest of the parent entries to the original
OriginalChangeList.Add(ParentChangeList[i]);
}
// last of all, if the parent has another parent, recurse and do it all again
if (FindParent(Parent) >= 0)
{
MasterChangeList = AddInheritance(Parent, MasterChangeList);
}
}
return MasterChangeList;
}
ArrayList AddInterfaces(int Index, ArrayList MasterChangeList)
{
// this needs to work differently to inheritance
// it does the following:
// 1. loop through each interface
// 2. check the MasterChangeList for a matching interface
// 3. if found, for all methods in the deobfuscated interface, find corresponding entry in
// current classes change list, and update it
//
TClassFile ClassFile = (TClassFile)FClassFiles[Index];
// for each class file, check each of its interfaces
for (int i = 0; i < ClassFile.Interfaces.Items.Count; i++)
{
// check each interface if it matches any deobfuscated classfile/interface in the project
for (int j = 0; j < FClassFiles.Count; j++)
{
string OldName = (string)((ArrayList)MasterChangeList[j])[0];
if (OldName == ClassFile.Interfaces.Item(i).Name)
{
ArrayList OriginalChangeList = (ArrayList)MasterChangeList[Index];
ArrayList InterfaceChangeList = (ArrayList)MasterChangeList[j];
for (int k = 2; k < InterfaceChangeList.Count; k++)
{
// add the rest of the parent entries to the original
// NOTE: this might work best if added to the START of the list!
OriginalChangeList.Insert(2, InterfaceChangeList[k]);
}
break;
}
}
}
return MasterChangeList;
}
ArrayList FixInheritance(ArrayList MasterChangeList)
{
for (int i = 0; i < FClassFiles.Count; i++)
{
MasterChangeList = AddInheritance(i, MasterChangeList);
//MasterChangeList = AddInterfaces(i, MasterChangeList);
}
return MasterChangeList;
}
public ArrayList DeObfuscateAll()
{
return DeObfuscateAll(null);
}
private int curr_progress;
public ArrayList DeObfuscateAll(RenameDatabase RenameStore)
{
FClassFiles = new ArrayList();
FInterfaces = new ArrayList();
ArrayList MasterChangeList = new ArrayList();
ArrayList NewFileNameList = new ArrayList();
curr_progress = 0;
Progress(FFiles.Count, 0);
// open each class file and add to array
foreach (string fn in FFiles)
{
if (fn.EndsWith(".class"))
{
TClassFile cf = new TClassFile(fn);
AddClassFiles(cf);
}
else
{
Common.Unzip(fn, AddClassFiles);
}
}
// do all the work in memory
for (int i = 0; i < FClassFiles.Count; i++)
{
// this deobfuscates a single class, and keeps a record of all the changes
// in an arraylist of ChangeRecords
//
// we need more here!
//
// first, if the file we deobfuscated had a parent, we have to add the entire change list
// from the parent to the end of the current (recursively), minus the old/new name
// note: this duplications of data fixes problems with inheritance
//
MasterChangeList.Add(DeObfuscateSingleFile(i, RenameStore));
Progress(FClassFiles.Count, i + 1);
}
Progress(FClassFiles.Count, 0);
curr_progress = 0;
// iterate through all the class files using the change records saved
// after the deobfuscation was done
MasterChangeList = FixInheritance(MasterChangeList);
// iterate through all the class files using the change records saved
// after the deobfuscation was done
FixReferences(MasterChangeList);
foreach (string fn in FFiles)
{
// extract the actual filename from the path and replace it with the new ClassName
string file_name = null;//= Path.GetDirectoryName(cf.FileName) + Path.DirectorySeparatorChar + Common.GetClassName(cf.ThisClassName) + ".class";
if (fn.EndsWith(".class"))
{
for (int i = 0; i < FClassFiles.Count; i++)
{
TClassFile cf = (TClassFile)FClassFiles[i];
if (cf.FileName == fn)
{
file_name = Path.Combine(this.OutputDir, cf.ThisClassName + ".class");
if (File.Exists(file_name))
{
file_name = Path.Combine(this.OutputDir, cf.ThisClassName + cf.ThisClassCode + ".class");
}
if (File.Exists(file_name))
{
file_name = Path.Combine(this.OutputDir, cf.ThisClassName + ((i * cf.ThisClassCode) + i) + ".class");
}
//file_name = file_name.Replace('/', '\\');
//if ((file_name != cf.FileName) && FCleanup)
//{
// File.Delete(cf.FileName);
//}
// if for some reason the directory doesn't exist, create it
if (!Directory.Exists(Path.GetDirectoryName(file_name)))
Directory.CreateDirectory(Path.GetDirectoryName(file_name));
using (FileStream fs = new FileStream(file_name, FileMode.Create, FileAccess.Write))
{
cf.Save(fs);
fs.Close();
}
Progress(FClassFiles.Count, ++curr_progress);
//optimize
break;
}
}
}
else
{
file_name = Path.Combine(this.OutputDir, Path.GetFileName(fn));
for (int i = 1; File.Exists(file_name) && i < 100; i++)
{
file_name = Path.GetFileNameWithoutExtension(fn) + i + Path.GetExtension(fn);
file_name = Path.Combine(this.OutputDir, file_name);
}
using (ZipOutputStream zip = new ZipOutputStream(File.Create(file_name)))
{
zip.SetLevel(9); // zip Level 0-9
//s.Password = "123"; //Zip Password
// save all the class files
for (int i = 0; i < FClassFiles.Count; i++)
{
TClassFile cf = (TClassFile)FClassFiles[i];
if (cf.FileName == fn)
{
ZipEntry entry = new ZipEntry(cf.ThisClassName + ".class");
entry.DateTime = DateTime.Now;
zip.PutNextEntry(entry);
cf.Save(zip);
Progress(FClassFiles.Count, ++curr_progress);
}
}
zip.Finish();
zip.Close();
}
}
// return the new filename so the main gui knows what to reload
if (file_name != null)
NewFileNameList.Add(file_name);
}
return NewFileNameList;
}
private void AddClassFiles(TClassFile cf)
{
if (cf != null)
{
if (cf.Open())
{
FClassFiles.Add(cf);
Progress(FClassFiles.Count, ++curr_progress);
}
}
}
public bool ThoroughMode
{
get
{
return FThoroughMode;
}
set
{
FThoroughMode = value;
}
}
public bool RenameClasses
{
get
{
return FRenameClasses;
}
set
{
FRenameClasses = value;
}
}
}
// ******************************************************************************** //
// *************************** JAVA CLASS WRAPPER ******************************** //
// ******************************************************************************** //
// These class encapsulates the java .class file
// With a few special methods jammed in to help rename methods and fields (and refs)
class TClassFile
{
// my internal variables
string FThisClassName;
string FSuperClassName;
// internal class file members as designated by Sun
private uint FMagic;
private ushort FMinorVersion;
private ushort FMajorVersion;
//private ushort FConstantPoolCount;
private TConstantPool FConstantPool;
private AccessFlags FAccessFlags;
private ushort FThisClass;
private ushort FSuperClass;
//private ushort FInterfacesCount;
private TInterfaces FInterfaces;
//private ushort FFieldsCount;
private TFields FFields;
//private ushort FMethodsCount;
private TMethods FMethods;
//private ushort FAttributesCount;
private TAttributes FAttributes;
// internal variables
private string FClassFileName = "";
private BinaryReader FReader = null;
public ushort ThisClassCode
{
get { return FThisClass; }
}
public TClassFile(String ClassFileName)
{
FClassFileName = ClassFileName;
//FHasBeenOpened = false;
FThisClassName = "";
FSuperClassName = "";
}
public TClassFile(String ClassFileName, BinaryReader Reader)
{
FClassFileName = ClassFileName;
FReader = Reader;
//FHasBeenOpened = false;
FThisClassName = "";
FSuperClassName = "";
}
public bool Open()
{
if (FReader == null && File.Exists(FClassFileName))
{
// read the .class file systematically
using (FileStream fs = new FileStream(FClassFileName, FileMode.Open, FileAccess.Read))
{
FReader = new BinaryReader(fs);
return Read();
}
}
else
{
return Read();
}
}
public bool Read()
{
try
{
// read header
FMagic = Common.ReadDWord(FReader);
if (FMagic != 0x0CAFEBABE)
return false;
FMinorVersion = Common.ReadWord(FReader);
FMajorVersion = Common.ReadWord(FReader);
// read constant pool
// this also reads the "FConstantPoolCount"
// so instead use FConstantPool.MaxItems or somesuch
FConstantPool = new TConstantPool(FReader);
// more constants
FAccessFlags = (AccessFlags)Common.ReadWord(FReader);
FThisClass = Common.ReadWord(FReader);
FThisClass--;
FSuperClass = Common.ReadWord(FReader);
FSuperClass--;
FThisClassName = ((ConstantClassInfo)FConstantPool.Item(FThisClass)).Name;
(FConstantPool.Item(FThisClass)).References++;
FSuperClassName = ((ConstantClassInfo)FConstantPool.Item(FSuperClass)).Name;
(FConstantPool.Item(FSuperClass)).References++;
FInterfaces = new TInterfaces(FReader, FConstantPool);
FFields = new TFields(FReader, FConstantPool);
FMethods = new TMethods(FReader, FConstantPool);
FAttributes = new TAttributes(FReader, FConstantPool);
//FHasBeenOpened = true;
return true;
}
catch (Exception e)
{
// catch any unhandled exceptions here
// and exit gracefully.
// garbage collection does the rest ;D
return false;
}
}
public bool Save(Stream fs)
{
if (true)//FHasBeenOpened)
{
try
{
BinaryWriter FWriter = new BinaryWriter(fs);
// write header
Common.WriteDWord(FWriter, FMagic);
Common.WriteWord(FWriter, FMinorVersion);
Common.WriteWord(FWriter, FMajorVersion);
// write constant pool
// this also writes the "FConstantPoolCount"
FConstantPool.Write(FWriter);
// more constants
Common.WriteWord(FWriter, (int)FAccessFlags);
Common.WriteWord(FWriter, FThisClass + 1);
Common.WriteWord(FWriter, FSuperClass + 1);
FInterfaces.Write(FWriter);
FFields.Write(FWriter);
FMethods.Write(FWriter);
FAttributes.Write(FWriter);
//FWriter.Close();
return true;
}
catch (Exception e)
{
// catch any unhandled exceptions here
// and exit gracefully.
// garbage collection does the rest ;D
return false;
}
}
}
public uint Magic
{
get
{
return FMagic;
}
set
{
FMagic = value;
}
}
public string Version()
{
return FMajorVersion.ToString() + "." + FMinorVersion.ToString();
}
public string FileName
{
get
{
return FClassFileName;
}
}
public AccessFlags AccessFlags
{
get
{
return FAccessFlags;
}
}
public TConstantPool ConstantPool
{
get
{
return FConstantPool;
}
}
public TInterfaces Interfaces
{
get
{
return FInterfaces;
}
}
public TFields Fields
{
get
{
return FFields;
}
}
public TMethods Methods
{
get
{
return FMethods;
}
}
public TAttributes Attributes
{
get
{
return FAttributes;
}
}
public TChangeRecord ChangeMethodName(int MethodNumber, string NewName)
{
MethodInfo Method = (MethodInfo)FMethods.Items[MethodNumber];
//MethodInfo OriginalMethod = Method.Clone();
//MethodInfo NewMethod = null;
TChangeRecord Result = null;
ConstantMethodrefInfo MethodRef = null;
ushort NewNameIndex;
// first we need to loop through the constant pool for method
// references that match our new method name
for (int i = 0; i < FConstantPool.MaxItems(); i++)
{
if (FConstantPool.Item(i).Tag == (byte)ConstantPoolInfoTag.ConstantMethodref)
{
MethodRef = (ConstantMethodrefInfo)FConstantPool.Item(i);
if (MethodRef.ParentClass.Name == FThisClassName &&
MethodRef.NameAndType.Name == Method.Name.Value &&
MethodRef.NameAndType.Descriptor == Method.Descriptor)
{
// jackpot, we found the reference!
// there should be only one, so we will break and fix it up after we generate the new name
break;
}
}