-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
MethodAnalyzer.java
2032 lines (1743 loc) · 91.8 KB
/
MethodAnalyzer.java
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
/*
* Copyright 2013, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.analysis;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.jf.dexlib2.AccessFlags;
import org.jf.dexlib2.Opcode;
import org.jf.dexlib2.base.reference.BaseMethodReference;
import org.jf.dexlib2.iface.*;
import org.jf.dexlib2.iface.instruction.*;
import org.jf.dexlib2.iface.instruction.formats.*;
import org.jf.dexlib2.iface.reference.FieldReference;
import org.jf.dexlib2.iface.reference.MethodReference;
import org.jf.dexlib2.iface.reference.Reference;
import org.jf.dexlib2.iface.reference.TypeReference;
import org.jf.dexlib2.immutable.instruction.*;
import org.jf.dexlib2.immutable.reference.ImmutableFieldReference;
import org.jf.dexlib2.immutable.reference.ImmutableMethodReference;
import org.jf.dexlib2.util.MethodUtil;
import org.jf.dexlib2.util.TypeUtils;
import org.jf.dexlib2.writer.util.TryListBuilder;
import org.jf.util.BitSetUtils;
import org.jf.util.ExceptionWithContext;
import org.jf.util.SparseArray;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.BitSet;
import java.util.List;
/**
* The MethodAnalyzer performs several functions. It "analyzes" the instructions and infers the register types
* for each register, it can deodex odexed instructions, and it can verify the bytecode. The analysis and verification
* are done in two separate passes, because the analysis has to process instructions multiple times in some cases, and
* there's no need to perform the verification multiple times, so we wait until the method is fully analyzed and then
* verify it.
*
* Before calling the analyze() method, you must have initialized the ClassPath by calling
* ClassPath.InitializeClassPath
*/
public class MethodAnalyzer {
@Nonnull private final Method method;
@Nonnull private final MethodImplementation methodImpl;
private final boolean normalizeVirtualMethods;
private final int paramRegisterCount;
@Nonnull private final ClassPath classPath;
@Nullable private final InlineMethodResolver inlineResolver;
// This contains all the AnalyzedInstruction instances, keyed by the code unit address of the instruction
@Nonnull private final SparseArray<AnalyzedInstruction> analyzedInstructions =
new SparseArray<AnalyzedInstruction>(0);
// Which instructions have been analyzed, keyed by instruction index
@Nonnull private final BitSet analyzedState;
@Nullable private AnalysisException analysisException = null;
// This is a dummy instruction that occurs immediately before the first real instruction. We can initialize the
// register types for this instruction to the parameter types, in order to have them propagate to all of its
// successors, e.g. the first real instruction, the first instructions in any exception handlers covering the first
// instruction, etc.
private final AnalyzedInstruction startOfMethod;
public MethodAnalyzer(@Nonnull ClassPath classPath, @Nonnull Method method,
@Nullable InlineMethodResolver inlineResolver, boolean normalizeVirtualMethods) {
this.classPath = classPath;
this.inlineResolver = inlineResolver;
this.normalizeVirtualMethods = normalizeVirtualMethods;
this.method = method;
MethodImplementation methodImpl = method.getImplementation();
if (methodImpl == null) {
throw new IllegalArgumentException("The method has no implementation");
}
this.methodImpl = methodImpl;
// Override AnalyzedInstruction and provide custom implementations of some of the methods, so that we don't
// have to handle the case this special case of instruction being null, in the main class
startOfMethod = new AnalyzedInstruction(this, new ImmutableInstruction10x(Opcode.NOP), -1, methodImpl.getRegisterCount()) {
@Override protected boolean addPredecessor(AnalyzedInstruction predecessor) {
throw new UnsupportedOperationException();
}
@Override @Nonnull
public RegisterType getPredecessorRegisterType(@Nonnull AnalyzedInstruction predecessor, int registerNumber) {
throw new UnsupportedOperationException();
}
};
buildInstructionList();
analyzedState = new BitSet(analyzedInstructions.size());
paramRegisterCount = MethodUtil.getParameterRegisterCount(method);
analyze();
}
@Nonnull
public ClassPath getClassPath() {
return classPath;
}
private void analyze() {
Method method = this.method;
MethodImplementation methodImpl = this.methodImpl;
int totalRegisters = methodImpl.getRegisterCount();
int parameterRegisters = paramRegisterCount;
int nonParameterRegisters = totalRegisters - parameterRegisters;
//if this isn't a static method, determine which register is the "this" register and set the type to the
//current class
if (!MethodUtil.isStatic(method)) {
int thisRegister = totalRegisters - parameterRegisters;
//if this is a constructor, then set the "this" register to an uninitialized reference of the current class
if (MethodUtil.isConstructor(method)) {
setPostRegisterTypeAndPropagateChanges(startOfMethod, thisRegister,
RegisterType.getRegisterType(RegisterType.UNINIT_THIS,
classPath.getClass(method.getDefiningClass())));
} else {
setPostRegisterTypeAndPropagateChanges(startOfMethod, thisRegister,
RegisterType.getRegisterType(RegisterType.REFERENCE,
classPath.getClass(method.getDefiningClass())));
}
propagateParameterTypes(totalRegisters-parameterRegisters+1);
} else {
propagateParameterTypes(totalRegisters-parameterRegisters);
}
RegisterType uninit = RegisterType.getRegisterType(RegisterType.UNINIT, null);
for (int i=0; i<nonParameterRegisters; i++) {
setPostRegisterTypeAndPropagateChanges(startOfMethod, i, uninit);
}
BitSet instructionsToAnalyze = new BitSet(analyzedInstructions.size());
//make sure all of the "first instructions" are marked for processing
for (AnalyzedInstruction successor: startOfMethod.successors) {
instructionsToAnalyze.set(successor.instructionIndex);
}
BitSet undeodexedInstructions = new BitSet(analyzedInstructions.size());
do {
boolean didSomething = false;
while (!instructionsToAnalyze.isEmpty()) {
for(int i=instructionsToAnalyze.nextSetBit(0); i>=0; i=instructionsToAnalyze.nextSetBit(i+1)) {
instructionsToAnalyze.clear(i);
if (analyzedState.get(i)) {
continue;
}
AnalyzedInstruction instructionToAnalyze = analyzedInstructions.valueAt(i);
try {
if (instructionToAnalyze.originalInstruction.getOpcode().odexOnly()) {
//if we had deodexed an odex instruction in a previous pass, we might have more specific
//register information now, so let's restore the original odexed instruction and
//re-deodex it
instructionToAnalyze.restoreOdexedInstruction();
}
if (!analyzeInstruction(instructionToAnalyze)) {
undeodexedInstructions.set(i);
continue;
} else {
didSomething = true;
undeodexedInstructions.clear(i);
}
} catch (AnalysisException ex) {
this.analysisException = ex;
int codeAddress = getInstructionAddress(instructionToAnalyze);
ex.codeAddress = codeAddress;
ex.addContext(String.format("opcode: %s", instructionToAnalyze.instruction.getOpcode().name));
ex.addContext(String.format("code address: %d", codeAddress));
ex.addContext(String.format("method: %s", method));
break;
}
analyzedState.set(instructionToAnalyze.getInstructionIndex());
for (AnalyzedInstruction successor: instructionToAnalyze.successors) {
instructionsToAnalyze.set(successor.getInstructionIndex());
}
}
if (analysisException != null) {
break;
}
}
if (!didSomething) {
break;
}
if (!undeodexedInstructions.isEmpty()) {
for (int i=undeodexedInstructions.nextSetBit(0); i>=0; i=undeodexedInstructions.nextSetBit(i+1)) {
instructionsToAnalyze.set(i);
}
}
} while (true);
//Now, go through and fix up any unresolvable odex instructions. These are usually odex instructions
//that operate on a null register, and thus always throw an NPE. They can also be any sort of odex instruction
//that occurs after an unresolvable odex instruction. We deodex if possible, or replace with an
//UnresolvableOdexInstruction
for (int i=0; i< analyzedInstructions.size(); i++) {
AnalyzedInstruction analyzedInstruction = analyzedInstructions.valueAt(i);
Instruction instruction = analyzedInstruction.getInstruction();
if (instruction.getOpcode().odexOnly()) {
int objectRegisterNumber;
switch (instruction.getOpcode().format) {
case Format10x:
analyzeOdexReturnVoid(analyzedInstruction, false);
continue;
case Format21c:
case Format22c:
analyzePutGetVolatile(analyzedInstruction, false);
continue;
case Format35c:
analyzeInvokeDirectEmpty(analyzedInstruction, false);
continue;
case Format3rc:
analyzeInvokeObjectInitRange(analyzedInstruction, false);
continue;
case Format22cs:
objectRegisterNumber = ((Instruction22cs)instruction).getRegisterB();
break;
case Format35mi:
case Format35ms:
objectRegisterNumber = ((FiveRegisterInstruction)instruction).getRegisterC();
break;
case Format3rmi:
case Format3rms:
objectRegisterNumber = ((RegisterRangeInstruction)instruction).getStartRegister();
break;
default:
continue;
}
analyzedInstruction.setDeodexedInstruction(
new UnresolvedOdexInstruction(instruction, objectRegisterNumber));
}
}
}
private void propagateParameterTypes(int parameterStartRegister) {
int i=0;
for (MethodParameter parameter: method.getParameters()) {
if (TypeUtils.isWideType(parameter)) {
setPostRegisterTypeAndPropagateChanges(startOfMethod, parameterStartRegister + i++,
RegisterType.getWideRegisterType(parameter, true));
setPostRegisterTypeAndPropagateChanges(startOfMethod, parameterStartRegister + i++,
RegisterType.getWideRegisterType(parameter, false));
} else {
setPostRegisterTypeAndPropagateChanges(startOfMethod, parameterStartRegister + i++,
RegisterType.getRegisterType(classPath, parameter));
}
}
}
public List<AnalyzedInstruction> getAnalyzedInstructions() {
return analyzedInstructions.getValues();
}
public List<Instruction> getInstructions() {
return Lists.transform(analyzedInstructions.getValues(), new Function<AnalyzedInstruction, Instruction>() {
@Nullable @Override public Instruction apply(@Nullable AnalyzedInstruction input) {
if (input == null) {
return null;
}
return input.instruction;
}
});
}
@Nullable
public AnalysisException getAnalysisException() {
return analysisException;
}
public int getParamRegisterCount() {
return paramRegisterCount;
}
public int getInstructionAddress(@Nonnull AnalyzedInstruction instruction) {
return analyzedInstructions.keyAt(instruction.instructionIndex);
}
private void setDestinationRegisterTypeAndPropagateChanges(@Nonnull AnalyzedInstruction analyzedInstruction,
@Nonnull RegisterType registerType) {
setPostRegisterTypeAndPropagateChanges(analyzedInstruction, analyzedInstruction.getDestinationRegister(),
registerType);
}
private void propagateChanges(@Nonnull BitSet changedInstructions, int registerNumber, boolean override) {
//Using a for loop inside the while loop optimizes for the common case of the successors of an instruction
//occurring after the instruction. Any successors that occur prior to the instruction will be picked up on
//the next iteration of the while loop.
//This could also be done recursively, but in large methods it would likely cause very deep recursion.
while (!changedInstructions.isEmpty()) {
for (int instructionIndex=changedInstructions.nextSetBit(0);
instructionIndex>=0;
instructionIndex=changedInstructions.nextSetBit(instructionIndex+1)) {
changedInstructions.clear(instructionIndex);
propagateRegisterToSuccessors(analyzedInstructions.valueAt(instructionIndex), registerNumber,
changedInstructions, override);
}
}
}
private void overridePredecessorRegisterTypeAndPropagateChanges(
@Nonnull AnalyzedInstruction analyzedInstruction, @Nonnull AnalyzedInstruction predecessor,
int registerNumber, @Nonnull RegisterType registerType) {
BitSet changedInstructions = new BitSet(analyzedInstructions.size());
if (!analyzedInstruction.overridePredecessorRegisterType(
predecessor, registerNumber, registerType, analyzedState)) {
return;
}
changedInstructions.set(analyzedInstruction.instructionIndex);
propagateChanges(changedInstructions, registerNumber, true);
if (registerType.category == RegisterType.LONG_LO) {
checkWidePair(registerNumber, analyzedInstruction);
overridePredecessorRegisterTypeAndPropagateChanges(analyzedInstruction, predecessor, registerNumber + 1,
RegisterType.LONG_HI_TYPE);
} else if (registerType.category == RegisterType.DOUBLE_LO) {
checkWidePair(registerNumber, analyzedInstruction);
overridePredecessorRegisterTypeAndPropagateChanges(analyzedInstruction, predecessor, registerNumber + 1,
RegisterType.DOUBLE_HI_TYPE);
}
}
private void initializeRefAndPropagateChanges(@Nonnull AnalyzedInstruction analyzedInstruction,
int registerNumber, @Nonnull RegisterType registerType) {
BitSet changedInstructions = new BitSet(analyzedInstructions.size());
if (!analyzedInstruction.setPostRegisterType(registerNumber, registerType)) {
return;
}
propagateRegisterToSuccessors(analyzedInstruction, registerNumber, changedInstructions, false);
propagateChanges(changedInstructions, registerNumber, false);
if (registerType.category == RegisterType.LONG_LO) {
checkWidePair(registerNumber, analyzedInstruction);
setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.LONG_HI_TYPE);
} else if (registerType.category == RegisterType.DOUBLE_LO) {
checkWidePair(registerNumber, analyzedInstruction);
setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.DOUBLE_HI_TYPE);
}
}
private void setPostRegisterTypeAndPropagateChanges(@Nonnull AnalyzedInstruction analyzedInstruction,
int registerNumber, @Nonnull RegisterType registerType) {
BitSet changedInstructions = new BitSet(analyzedInstructions.size());
if (!analyzedInstruction.setPostRegisterType(registerNumber, registerType)) {
return;
}
propagateRegisterToSuccessors(analyzedInstruction, registerNumber, changedInstructions, false);
propagateChanges(changedInstructions, registerNumber, false);
if (registerType.category == RegisterType.LONG_LO) {
checkWidePair(registerNumber, analyzedInstruction);
setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.LONG_HI_TYPE);
} else if (registerType.category == RegisterType.DOUBLE_LO) {
checkWidePair(registerNumber, analyzedInstruction);
setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.DOUBLE_HI_TYPE);
}
}
private void propagateRegisterToSuccessors(@Nonnull AnalyzedInstruction instruction, int registerNumber,
@Nonnull BitSet changedInstructions, boolean override) {
RegisterType postRegisterType = instruction.getPostInstructionRegisterType(registerNumber);
for (AnalyzedInstruction successor: instruction.successors) {
if (successor.mergeRegister(registerNumber, postRegisterType, analyzedState, override)) {
changedInstructions.set(successor.instructionIndex);
}
}
}
private void buildInstructionList() {
int registerCount = methodImpl.getRegisterCount();
ImmutableList<Instruction> instructions = ImmutableList.copyOf(methodImpl.getInstructions());
analyzedInstructions.ensureCapacity(instructions.size());
//first, create all the instructions and populate the instructionAddresses array
int currentCodeAddress = 0;
for (int i=0; i<instructions.size(); i++) {
Instruction instruction = instructions.get(i);
analyzedInstructions.append(currentCodeAddress,
new AnalyzedInstruction(this, instruction, i, registerCount));
assert analyzedInstructions.indexOfKey(currentCodeAddress) == i;
currentCodeAddress += instruction.getCodeUnits();
}
//next, populate the exceptionHandlers array. The array item for each instruction that can throw an exception
//and is covered by a try block should be set to a list of the first instructions of each exception handler
//for the try block covering the instruction
List<? extends TryBlock<? extends ExceptionHandler>> tries = methodImpl.getTryBlocks();
tries = TryListBuilder.massageTryBlocks(tries);
int triesIndex = 0;
TryBlock currentTry = null;
AnalyzedInstruction[] currentExceptionHandlers = null;
AnalyzedInstruction[][] exceptionHandlers = new AnalyzedInstruction[instructions.size()][];
if (tries != null) {
for (int i=0; i< analyzedInstructions.size(); i++) {
AnalyzedInstruction instruction = analyzedInstructions.valueAt(i);
Opcode instructionOpcode = instruction.instruction.getOpcode();
currentCodeAddress = getInstructionAddress(instruction);
//check if we have gone past the end of the current try
if (currentTry != null) {
if (currentTry.getStartCodeAddress() + currentTry.getCodeUnitCount() <= currentCodeAddress) {
currentTry = null;
triesIndex++;
}
}
//check if the next try is applicable yet
if (currentTry == null && triesIndex < tries.size()) {
TryBlock<? extends ExceptionHandler> tryBlock = tries.get(triesIndex);
if (tryBlock.getStartCodeAddress() <= currentCodeAddress) {
assert(tryBlock.getStartCodeAddress() + tryBlock.getCodeUnitCount() > currentCodeAddress);
currentTry = tryBlock;
currentExceptionHandlers = buildExceptionHandlerArray(tryBlock);
}
}
//if we're inside a try block, and the instruction can throw an exception, then add the exception handlers
//for the current instruction
if (currentTry != null && instructionOpcode.canThrow()) {
exceptionHandlers[i] = currentExceptionHandlers;
}
}
}
//finally, populate the successors and predecessors for each instruction. We start at the fake "StartOfMethod"
//instruction and follow the execution path. Any unreachable code won't have any predecessors or successors,
//and no reachable code will have an unreachable predessor or successor
assert analyzedInstructions.size() > 0;
BitSet instructionsToProcess = new BitSet(instructions.size());
addPredecessorSuccessor(startOfMethod, analyzedInstructions.valueAt(0), exceptionHandlers, instructionsToProcess);
while (!instructionsToProcess.isEmpty()) {
int currentInstructionIndex = instructionsToProcess.nextSetBit(0);
instructionsToProcess.clear(currentInstructionIndex);
AnalyzedInstruction instruction = analyzedInstructions.valueAt(currentInstructionIndex);
Opcode instructionOpcode = instruction.instruction.getOpcode();
int instructionCodeAddress = getInstructionAddress(instruction);
if (instruction.instruction.getOpcode().canContinue()) {
if (currentInstructionIndex == analyzedInstructions.size() - 1) {
throw new AnalysisException("Execution can continue past the last instruction");
}
AnalyzedInstruction nextInstruction = analyzedInstructions.valueAt(currentInstructionIndex+1);
addPredecessorSuccessor(instruction, nextInstruction, exceptionHandlers, instructionsToProcess);
}
if (instruction.instruction instanceof OffsetInstruction) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction.instruction;
if (instructionOpcode == Opcode.PACKED_SWITCH || instructionOpcode == Opcode.SPARSE_SWITCH) {
AnalyzedInstruction analyzedSwitchPayload = analyzedInstructions.get(
instructionCodeAddress + offsetInstruction.getCodeOffset());
if (analyzedSwitchPayload == null) {
throw new AnalysisException("Invalid switch payload offset");
}
SwitchPayload switchPayload = (SwitchPayload)analyzedSwitchPayload.instruction;
for (SwitchElement switchElement: switchPayload.getSwitchElements()) {
AnalyzedInstruction targetInstruction = analyzedInstructions.get(instructionCodeAddress +
switchElement.getOffset());
if (targetInstruction == null) {
throw new AnalysisException("Invalid switch target offset");
}
addPredecessorSuccessor(instruction, targetInstruction, exceptionHandlers,
instructionsToProcess);
}
} else if (instructionOpcode != Opcode.FILL_ARRAY_DATA) {
int targetAddressOffset = offsetInstruction.getCodeOffset();
AnalyzedInstruction targetInstruction = analyzedInstructions.get(instructionCodeAddress +
targetAddressOffset);
addPredecessorSuccessor(instruction, targetInstruction, exceptionHandlers, instructionsToProcess);
}
}
}
}
private void addPredecessorSuccessor(@Nonnull AnalyzedInstruction predecessor,
@Nonnull AnalyzedInstruction successor,
@Nonnull AnalyzedInstruction[][] exceptionHandlers,
@Nonnull BitSet instructionsToProcess) {
addPredecessorSuccessor(predecessor, successor, exceptionHandlers, instructionsToProcess, false);
}
private void addPredecessorSuccessor(@Nonnull AnalyzedInstruction predecessor,
@Nonnull AnalyzedInstruction successor,
@Nonnull AnalyzedInstruction[][] exceptionHandlers,
@Nonnull BitSet instructionsToProcess, boolean allowMoveException) {
if (!allowMoveException && successor.instruction.getOpcode() == Opcode.MOVE_EXCEPTION) {
throw new AnalysisException("Execution can pass from the " + predecessor.instruction.getOpcode().name +
" instruction at code address 0x" + Integer.toHexString(getInstructionAddress(predecessor)) +
" to the move-exception instruction at address 0x" +
Integer.toHexString(getInstructionAddress(successor)));
}
if (!successor.addPredecessor(predecessor)) {
return;
}
predecessor.addSuccessor(successor);
instructionsToProcess.set(successor.getInstructionIndex());
//if the successor can throw an instruction, then we need to add the exception handlers as additional
//successors to the predecessor (and then apply this same logic recursively if needed)
//Technically, we should handle the monitor-exit instruction as a special case. The exception is actually
//thrown *after* the instruction executes, instead of "before" the instruction executes, lke for any other
//instruction. But since it doesn't modify any registers, we can treat it like any other instruction.
AnalyzedInstruction[] exceptionHandlersForSuccessor = exceptionHandlers[successor.instructionIndex];
if (exceptionHandlersForSuccessor != null) {
//the item for this instruction in exceptionHandlersForSuccessor should only be set if this instruction
//can throw an exception
assert successor.instruction.getOpcode().canThrow();
for (AnalyzedInstruction exceptionHandler: exceptionHandlersForSuccessor) {
addPredecessorSuccessor(predecessor, exceptionHandler, exceptionHandlers, instructionsToProcess, true);
}
}
}
@Nonnull
private AnalyzedInstruction[] buildExceptionHandlerArray(@Nonnull TryBlock<? extends ExceptionHandler> tryBlock) {
List<? extends ExceptionHandler> exceptionHandlers = tryBlock.getExceptionHandlers();
AnalyzedInstruction[] handlerInstructions = new AnalyzedInstruction[exceptionHandlers.size()];
for (int i=0; i<exceptionHandlers.size(); i++) {
handlerInstructions[i] = analyzedInstructions.get(exceptionHandlers.get(i).getHandlerCodeAddress());
}
return handlerInstructions;
}
/**
* @return false if analyzedInstruction is an odex instruction that couldn't be deodexed, due to its
* object register being null
*/
private boolean analyzeInstruction(@Nonnull AnalyzedInstruction analyzedInstruction) {
Instruction instruction = analyzedInstruction.instruction;
switch (instruction.getOpcode()) {
case NOP:
return true;
case MOVE:
case MOVE_FROM16:
case MOVE_16:
case MOVE_WIDE:
case MOVE_WIDE_FROM16:
case MOVE_WIDE_16:
case MOVE_OBJECT:
case MOVE_OBJECT_FROM16:
case MOVE_OBJECT_16:
analyzeMove(analyzedInstruction);
return true;
case MOVE_RESULT:
case MOVE_RESULT_WIDE:
case MOVE_RESULT_OBJECT:
analyzeMoveResult(analyzedInstruction);
return true;
case MOVE_EXCEPTION:
analyzeMoveException(analyzedInstruction);
return true;
case RETURN_VOID:
case RETURN:
case RETURN_WIDE:
case RETURN_OBJECT:
return true;
case RETURN_VOID_BARRIER:
case RETURN_VOID_NO_BARRIER:
analyzeOdexReturnVoid(analyzedInstruction);
return true;
case CONST_4:
case CONST_16:
case CONST:
case CONST_HIGH16:
analyzeConst(analyzedInstruction);
return true;
case CONST_WIDE_16:
case CONST_WIDE_32:
case CONST_WIDE:
case CONST_WIDE_HIGH16:
analyzeWideConst(analyzedInstruction);
return true;
case CONST_STRING:
case CONST_STRING_JUMBO:
analyzeConstString(analyzedInstruction);
return true;
case CONST_CLASS:
analyzeConstClass(analyzedInstruction);
return true;
case MONITOR_ENTER:
case MONITOR_EXIT:
return true;
case CHECK_CAST:
analyzeCheckCast(analyzedInstruction);
return true;
case INSTANCE_OF:
analyzeInstanceOf(analyzedInstruction);
return true;
case ARRAY_LENGTH:
analyzeArrayLength(analyzedInstruction);
return true;
case NEW_INSTANCE:
analyzeNewInstance(analyzedInstruction);
return true;
case NEW_ARRAY:
analyzeNewArray(analyzedInstruction);
return true;
case FILLED_NEW_ARRAY:
case FILLED_NEW_ARRAY_RANGE:
return true;
case FILL_ARRAY_DATA:
return true;
case THROW:
case GOTO:
case GOTO_16:
case GOTO_32:
return true;
case PACKED_SWITCH:
case SPARSE_SWITCH:
return true;
case CMPL_FLOAT:
case CMPG_FLOAT:
case CMPL_DOUBLE:
case CMPG_DOUBLE:
case CMP_LONG:
analyzeFloatWideCmp(analyzedInstruction);
return true;
case IF_EQ:
case IF_NE:
case IF_LT:
case IF_GE:
case IF_GT:
case IF_LE:
case IF_LTZ:
case IF_GEZ:
case IF_GTZ:
case IF_LEZ:
return true;
case IF_EQZ:
case IF_NEZ:
analyzeIfEqzNez(analyzedInstruction);
return true;
case AGET:
analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case AGET_BOOLEAN:
analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.BOOLEAN_TYPE);
return true;
case AGET_BYTE:
analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.BYTE_TYPE);
return true;
case AGET_CHAR:
analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.CHAR_TYPE);
return true;
case AGET_SHORT:
analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.SHORT_TYPE);
return true;
case AGET_WIDE:
analyzeAgetWide(analyzedInstruction);
return true;
case AGET_OBJECT:
analyzeAgetObject(analyzedInstruction);
return true;
case APUT:
case APUT_BOOLEAN:
case APUT_BYTE:
case APUT_CHAR:
case APUT_SHORT:
case APUT_WIDE:
case APUT_OBJECT:
return true;
case IGET:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case IGET_BOOLEAN:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.BOOLEAN_TYPE);
return true;
case IGET_BYTE:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.BYTE_TYPE);
return true;
case IGET_CHAR:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.CHAR_TYPE);
return true;
case IGET_SHORT:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.SHORT_TYPE);
return true;
case IGET_WIDE:
case IGET_OBJECT:
analyzeIgetSgetWideObject(analyzedInstruction);
return true;
case IPUT:
case IPUT_BOOLEAN:
case IPUT_BYTE:
case IPUT_CHAR:
case IPUT_SHORT:
case IPUT_WIDE:
case IPUT_OBJECT:
return true;
case SGET:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case SGET_BOOLEAN:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.BOOLEAN_TYPE);
return true;
case SGET_BYTE:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.BYTE_TYPE);
return true;
case SGET_CHAR:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.CHAR_TYPE);
return true;
case SGET_SHORT:
analyze32BitPrimitiveIgetSget(analyzedInstruction, RegisterType.SHORT_TYPE);
return true;
case SGET_WIDE:
case SGET_OBJECT:
analyzeIgetSgetWideObject(analyzedInstruction);
return true;
case SPUT:
case SPUT_BOOLEAN:
case SPUT_BYTE:
case SPUT_CHAR:
case SPUT_SHORT:
case SPUT_WIDE:
case SPUT_OBJECT:
return true;
case INVOKE_VIRTUAL:
analyzeInvokeVirtual(analyzedInstruction, false);
return true;
case INVOKE_SUPER:
analyzeInvokeVirtual(analyzedInstruction, false);
return true;
case INVOKE_DIRECT:
analyzeInvokeDirect(analyzedInstruction);
return true;
case INVOKE_STATIC:
return true;
case INVOKE_INTERFACE:
// TODO: normalize interfaces
return true;
case INVOKE_VIRTUAL_RANGE:
analyzeInvokeVirtual(analyzedInstruction, true);
return true;
case INVOKE_SUPER_RANGE:
analyzeInvokeVirtual(analyzedInstruction, true);
return true;
case INVOKE_DIRECT_RANGE:
analyzeInvokeDirectRange(analyzedInstruction);
return true;
case INVOKE_STATIC_RANGE:
return true;
case INVOKE_INTERFACE_RANGE:
// TODO: normalize interfaces
return true;
case NEG_INT:
case NOT_INT:
analyzeUnaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case NEG_LONG:
case NOT_LONG:
analyzeUnaryOp(analyzedInstruction, RegisterType.LONG_LO_TYPE);
return true;
case NEG_FLOAT:
analyzeUnaryOp(analyzedInstruction, RegisterType.FLOAT_TYPE);
return true;
case NEG_DOUBLE:
analyzeUnaryOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE);
return true;
case INT_TO_LONG:
analyzeUnaryOp(analyzedInstruction, RegisterType.LONG_LO_TYPE);
return true;
case INT_TO_FLOAT:
analyzeUnaryOp(analyzedInstruction, RegisterType.FLOAT_TYPE);
return true;
case INT_TO_DOUBLE:
analyzeUnaryOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE);
return true;
case LONG_TO_INT:
case DOUBLE_TO_INT:
analyzeUnaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case LONG_TO_FLOAT:
case DOUBLE_TO_FLOAT:
analyzeUnaryOp(analyzedInstruction, RegisterType.FLOAT_TYPE);
return true;
case LONG_TO_DOUBLE:
analyzeUnaryOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE);
return true;
case FLOAT_TO_INT:
analyzeUnaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE);
return true;
case FLOAT_TO_LONG:
analyzeUnaryOp(analyzedInstruction, RegisterType.LONG_LO_TYPE);
return true;
case FLOAT_TO_DOUBLE:
analyzeUnaryOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE);
return true;
case DOUBLE_TO_LONG:
analyzeUnaryOp(analyzedInstruction, RegisterType.LONG_LO_TYPE);
return true;
case INT_TO_BYTE:
analyzeUnaryOp(analyzedInstruction, RegisterType.BYTE_TYPE);
return true;
case INT_TO_CHAR:
analyzeUnaryOp(analyzedInstruction, RegisterType.CHAR_TYPE);
return true;
case INT_TO_SHORT:
analyzeUnaryOp(analyzedInstruction, RegisterType.SHORT_TYPE);
return true;
case ADD_INT:
case SUB_INT:
case MUL_INT:
case DIV_INT:
case REM_INT:
case SHL_INT:
case SHR_INT:
case USHR_INT:
analyzeBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, false);
return true;
case AND_INT:
case OR_INT:
case XOR_INT:
analyzeBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, true);
return true;
case ADD_LONG:
case SUB_LONG:
case MUL_LONG:
case DIV_LONG:
case REM_LONG:
case AND_LONG:
case OR_LONG:
case XOR_LONG:
case SHL_LONG:
case SHR_LONG:
case USHR_LONG:
analyzeBinaryOp(analyzedInstruction, RegisterType.LONG_LO_TYPE, false);
return true;
case ADD_FLOAT:
case SUB_FLOAT:
case MUL_FLOAT:
case DIV_FLOAT:
case REM_FLOAT:
analyzeBinaryOp(analyzedInstruction, RegisterType.FLOAT_TYPE, false);
return true;
case ADD_DOUBLE:
case SUB_DOUBLE:
case MUL_DOUBLE:
case DIV_DOUBLE:
case REM_DOUBLE:
analyzeBinaryOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE, false);
return true;
case ADD_INT_2ADDR:
case SUB_INT_2ADDR:
case MUL_INT_2ADDR:
case DIV_INT_2ADDR:
case REM_INT_2ADDR:
case SHL_INT_2ADDR:
case SHR_INT_2ADDR:
case USHR_INT_2ADDR:
analyzeBinary2AddrOp(analyzedInstruction, RegisterType.INTEGER_TYPE, false);
return true;
case AND_INT_2ADDR:
case OR_INT_2ADDR:
case XOR_INT_2ADDR:
analyzeBinary2AddrOp(analyzedInstruction, RegisterType.INTEGER_TYPE, true);
return true;
case ADD_LONG_2ADDR:
case SUB_LONG_2ADDR:
case MUL_LONG_2ADDR:
case DIV_LONG_2ADDR:
case REM_LONG_2ADDR:
case AND_LONG_2ADDR:
case OR_LONG_2ADDR:
case XOR_LONG_2ADDR:
case SHL_LONG_2ADDR:
case SHR_LONG_2ADDR:
case USHR_LONG_2ADDR:
analyzeBinary2AddrOp(analyzedInstruction, RegisterType.LONG_LO_TYPE, false);
return true;
case ADD_FLOAT_2ADDR:
case SUB_FLOAT_2ADDR:
case MUL_FLOAT_2ADDR:
case DIV_FLOAT_2ADDR:
case REM_FLOAT_2ADDR:
analyzeBinary2AddrOp(analyzedInstruction, RegisterType.FLOAT_TYPE, false);
return true;
case ADD_DOUBLE_2ADDR:
case SUB_DOUBLE_2ADDR:
case MUL_DOUBLE_2ADDR:
case DIV_DOUBLE_2ADDR:
case REM_DOUBLE_2ADDR:
analyzeBinary2AddrOp(analyzedInstruction, RegisterType.DOUBLE_LO_TYPE, false);
return true;
case ADD_INT_LIT16:
case RSUB_INT:
case MUL_INT_LIT16:
case DIV_INT_LIT16:
case REM_INT_LIT16:
analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, false);
return true;
case AND_INT_LIT16:
case OR_INT_LIT16:
case XOR_INT_LIT16:
analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, true);
return true;
case ADD_INT_LIT8:
case RSUB_INT_LIT8:
case MUL_INT_LIT8:
case DIV_INT_LIT8:
case REM_INT_LIT8:
case SHL_INT_LIT8:
analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, false);
return true;
case AND_INT_LIT8:
case OR_INT_LIT8:
case XOR_INT_LIT8:
analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.INTEGER_TYPE, true);
return true;
case SHR_INT_LIT8:
analyzeLiteralBinaryOp(analyzedInstruction, getDestTypeForLiteralShiftRight(analyzedInstruction, true),
false);
return true;
case USHR_INT_LIT8:
analyzeLiteralBinaryOp(analyzedInstruction, getDestTypeForLiteralShiftRight(analyzedInstruction, false),
false);
return true;
/*odexed instructions*/
case IGET_VOLATILE:
case IPUT_VOLATILE:
case SGET_VOLATILE: