aboutsummaryrefslogtreecommitdiff
path: root/dexmaker-mockito-inline-extended/src/main/jni/staticjvmtiagent/agent.cc
blob: 5fcc4b17007958e7392de213f91fe822b08b49a1 (plain)
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
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdlib>
#include <sstream>
#include <cstring>
#include <cassert>
#include <cstdarg>
#include <algorithm>

#include <jni.h>

#include "jvmti.h"

#include <slicer/dex_ir.h>
#include <slicer/code_ir.h>
#include <slicer/dex_ir_builder.h>
#include <slicer/dex_utf8.h>
#include <slicer/writer.h>
#include <slicer/reader.h>
#include <slicer/instrumentation.h>

using namespace dex;
using namespace lir;

namespace com_android_dx_mockito_inline {
    static jvmtiEnv* localJvmtiEnv;

    static jobject sTransformer;

    // Converts a class name to a type descriptor
    // (ex. "java.lang.String" to "Ljava/lang/String;")
    static std::string
    ClassNameToDescriptor(const char* class_name) {
        std::stringstream ss;
        ss << "L";
        for (auto p = class_name; *p != '\0'; ++p) {
            ss << (*p == '.' ? '/' : *p);
        }
        ss << ";";
        return ss.str();
    }

    // Takes the full dex file for class 'classBeingRedefined'
    // - isolates the dex code for the class out of the dex file
    // - calls sTransformer.runTransformers on the isolated dex code
    // - send the transformed code back to the runtime
    static void
    Transform(jvmtiEnv* jvmti_env,
              JNIEnv* env,
              jclass classBeingRedefined,
              jobject loader,
              const char* name,
              jobject protectionDomain,
              jint classDataLen,
              const unsigned char* classData,
              jint* newClassDataLen,
              unsigned char** newClassData) {
        if (sTransformer != nullptr) {
            // Even reading the classData array is expensive as the data is only generated when the
            // memory is touched. Hence call JvmtiAgent#shouldTransform to check if we need to transform
            // the class.
            jclass cls = env->GetObjectClass(sTransformer);
            jmethodID shouldTransformMethod = env->GetMethodID(cls, "shouldTransform",
                                                               "(Ljava/lang/Class;)Z");

            jboolean shouldTransform = env->CallBooleanMethod(sTransformer, shouldTransformMethod,
                                                              classBeingRedefined);
            if (!shouldTransform) {
                return;
            }

            // Isolate byte code of class class. This is needed as Android usually gives us more
            // than the class we need.
            Reader reader(classData, classDataLen);

            u4 index = reader.FindClassIndex(ClassNameToDescriptor(name).c_str());
            reader.CreateClassIr(index);
            std::shared_ptr<ir::DexFile> ir = reader.GetIr();

            struct Allocator : public Writer::Allocator {
                virtual void* Allocate(size_t size) {return ::malloc(size);}
                virtual void Free(void* ptr) {::free(ptr);}
            };

            Allocator allocator;
            Writer writer(ir);
            size_t isolatedClassLen = 0;
            std::shared_ptr<jbyte> isolatedClass((jbyte*)writer.CreateImage(&allocator,
                                                                            &isolatedClassLen));

            // Create jbyteArray with isolated byte code of class
            jbyteArray isolatedClassArr = env->NewByteArray(isolatedClassLen);
            env->SetByteArrayRegion(isolatedClassArr, 0, isolatedClassLen,
                                    isolatedClass.get());

            jstring nameStr = env->NewStringUTF(name);

            // Call JvmtiAgent#runTransformers
            jmethodID runTransformersMethod = env->GetMethodID(cls, "runTransformers",
                                                               "(Ljava/lang/ClassLoader;"
                                                               "Ljava/lang/String;"
                                                               "Ljava/lang/Class;"
                                                               "Ljava/security/ProtectionDomain;"
                                                               "[B)[B");

            jbyteArray transformedArr = (jbyteArray) env->CallObjectMethod(sTransformer,
                                                                           runTransformersMethod,
                                                                           loader, nameStr,
                                                                           classBeingRedefined,
                                                                           protectionDomain,
                                                                           isolatedClassArr);

            // Set transformed byte code
            if (!env->ExceptionOccurred() && transformedArr != nullptr) {
                *newClassDataLen = env->GetArrayLength(transformedArr);

                jbyte* transformed = env->GetByteArrayElements(transformedArr, 0);

                jvmti_env->Allocate(*newClassDataLen, newClassData);
                std::memcpy(*newClassData, transformed, *newClassDataLen);

                env->ReleaseByteArrayElements(transformedArr, transformed, 0);
            }
        }
    }

    // Add a label before instructionAfter
    static void
    addLabel(CodeIr& c,
             lir::Instruction* instructionAfter,
             Label* returnTrueLabel) {
        c.instructions.InsertBefore(instructionAfter, returnTrueLabel);
    }

    // Add a byte code before instructionAfter
    static void
    addInstr(CodeIr& c,
             lir::Instruction* instructionAfter,
             Opcode opcode,
             const std::list<Operand*>& operands) {
        auto instruction = c.Alloc<Bytecode>();

        instruction->opcode = opcode;

        for (auto it = operands.begin(); it != operands.end(); it++) {
            instruction->operands.push_back(*it);
        }

        c.instructions.InsertBefore(instructionAfter, instruction);
    }

    // Add a method call byte code before instructionAfter
    static void
    addCall(ir::Builder& b,
            CodeIr& c,
            lir::Instruction* instructionAfter,
            Opcode opcode,
            ir::Type* type,
            const char* methodName,
            ir::Type* returnType,
            const std::vector<ir::Type*>& types,
            const std::list<int>& regs) {
        auto proto = b.GetProto(returnType, b.GetTypeList(types));
        auto method = b.GetMethodDecl(b.GetAsciiString(methodName), proto, type);

        VRegList* param_regs = c.Alloc<VRegList>();
        for (auto it = regs.begin(); it != regs.end(); it++) {
            param_regs->registers.push_back(*it);
        }

        addInstr(c, instructionAfter, opcode, {param_regs, c.Alloc<Method>(method,
                                                                           method->orig_index)});
    }

    typedef struct {
        ir::Type* boxedType;
        ir::Type* scalarType;
        std::string unboxMethod;
    } BoxingInfo;

    // Get boxing / unboxing info for a type
    static BoxingInfo
    getBoxingInfo(ir::Builder &b,
                  char typeCode) {
        BoxingInfo boxingInfo;

        if (typeCode != 'L' && typeCode !=  '[') {
            std::stringstream tmp;
            tmp << typeCode;
            boxingInfo.scalarType = b.GetType(tmp.str().c_str());
        }

        switch (typeCode) {
            case 'B':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Byte;");
                boxingInfo.unboxMethod = "byteValue";
                break;
            case 'S':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Short;");
                boxingInfo.unboxMethod = "shortValue";
                break;
            case 'I':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Integer;");
                boxingInfo.unboxMethod = "intValue";
                break;
            case 'C':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Character;");
                boxingInfo.unboxMethod = "charValue";
                break;
            case 'F':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Float;");
                boxingInfo.unboxMethod = "floatValue";
                break;
            case 'Z':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Boolean;");
                boxingInfo.unboxMethod = "booleanValue";
                break;
            case 'J':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Long;");
                boxingInfo.unboxMethod = "longValue";
                break;
            case 'D':
                boxingInfo.boxedType = b.GetType("Ljava/lang/Double;");
                boxingInfo.unboxMethod = "doubleValue";
                break;
            default:
                // real object
                break;
        }

        return boxingInfo;
    }

    static size_t
    getNumParams(ir::EncodedMethod *method) {
        if (method->decl->prototype->param_types == nullptr) {
            return 0;
        }

        return method->decl->prototype->param_types->types.size();
    }

    static bool
    canBeTransformed(ir::EncodedMethod *method) {
        std::string type = method->decl->parent->Decl();
        ir::String* methodName = method->decl->name;

        return ((method->access_flags & kAccStatic) != 0)
               && !(((method->access_flags & (kAccPrivate | kAccBridge | kAccNative)) != 0)
                    || (Utf8Cmp(methodName->c_str(), "<clinit>") == 0)
                    || (strncmp(type.c_str(), "java.", 5) == 0
                        && (method->access_flags & (kAccPrivate | kAccPublic | kAccProtected))
                           == 0));
    }

    // Transforms the classes to add the mockito hooks
    // - equals and hashcode are handled in a special way
    extern "C" JNIEXPORT jbyteArray JNICALL
    Java_com_android_dx_mockito_inline_StaticClassTransformer_nativeRedefine(JNIEnv* env,
                                                                           jobject generator,
                                                                           jstring idStr,
                                                                           jbyteArray originalArr) {
        unsigned char* original = (unsigned char*)env->GetByteArrayElements(originalArr, 0);

        Reader reader(original, env->GetArrayLength(originalArr));
        reader.CreateClassIr(0);
        std::shared_ptr<ir::DexFile> dex_ir = reader.GetIr();
        ir::Builder b(dex_ir);

        ir::Type* objectT = b.GetType("Ljava/lang/Object;");
        ir::Type* objectArrayT = b.GetType("[Ljava/lang/Object;");
        ir::Type* stringT = b.GetType("Ljava/lang/String;");
        ir::Type* methodT = b.GetType("Ljava/lang/reflect/Method;");
        ir::Type* callableT = b.GetType("Ljava/util/concurrent/Callable;");
        ir::Type* dispatcherT = b.GetType("Lcom/android/dx/mockito/inline/MockMethodDispatcher;");

        // Add id to dex file
        const char* idNative = env->GetStringUTFChars(idStr, 0);
        ir::String* id = b.GetAsciiString(idNative);
        env->ReleaseStringUTFChars(idStr, idNative);

        for (auto& method : dex_ir->encoded_methods) {
            if (!canBeTransformed(method.get())) {
                continue;
            }
            /*
            static long method_original(int param1, long param2, String param3) {
                foo();
                return bar();
            }

            static long method_transformed(int param1, long param2, String param3) {
                // MockMethodDispatcher dispatcher = MockMethodDispatcher.get(idStr, this);
                const-string v0, "65463hg34t"
                const v1, 0
                invoke-static {v0, v1}, MockMethodDispatcher.get(String, Object):MockMethodDispatcher
                move-result-object v0

                // if (dispatcher == null) {
                //    goto original_method;
                // }
                if-eqz v0, original_method

                // Method origin = dispatcher.getOrigin(this, methodDesc);
                const-string v1 "fully.qualified.ClassName#original_method(int, long, String)"
                const v2, 0
                invoke-virtual {v0, v2, v1}, MockMethodDispatcher.getOrigin(Object, String):Method
                move-result-object v1

                // if (origin == null) {
                //     goto original_method;
                // }
                if-eqz v1, original_method

                // Create an array with Objects of all parameters.

                //     Object[] arguments = new Object[3]
                const v3, 3
                new-array v2, v3, Object[]

                //     Integer param1Integer = Integer.valueOf(param1)
                move-from16 v3, ARG1     # this is necessary as invoke-static cannot deal with high
                                         # registers and ARG1 might be high
                invoke-static {v3}, Integer.valueOf(int):Integer
                move-result-object v3

                //     arguments[0] = param1Integer
                const v4, 0
                aput-object v3, v2, v4

                //     Long param2Long = Long.valueOf(param2)
                move-widefrom16 v3:v4, ARG2.1:ARG2.2 # this is necessary as invoke-static cannot
                                                     # deal with high registers and ARG2 might be
                                                     # high
                invoke-static {v3, v4}, Long.valueOf(long):Long
                move-result-object v3

                //     arguments[1] = param2Long
                const v4, 1
                aput-object v3, v2, v4

                //     arguments[2] = param3
                const v4, 2
                move-objectfrom16 v3, ARG3     # this is necessary as aput-object cannot deal with
                                               # high registers and ARG3 might be high
                aput-object v3, v2, v4

                // Callable<?> mocked = dispatcher.handle(methodDesc --as this parameter--,
                //                                        origin, arguments);
                const-string v3 "fully.qualified.ClassName#original_method(int, long, String)"
                invoke-virtual {v0,v3,v1,v2}, MockMethodDispatcher.handle(Object, Method,
                                                                          Object[]):Callable
                move-result-object v0

                //  if (mocked != null) {
                if-eqz v0, original_method

                //      Object ret = mocked.call();
                invoke-interface {v0}, Callable.call():Object
                move-result-object v0

                //      Long retLong = (Long)ret
                check-cast v0, Long

                //      long retlong = retLong.longValue();
                invoke-virtual {v0}, Long.longValue():long
                move-result-wide v0:v1

                //      return retlong;
                return-wide v0:v1

                //  }

            original_method:
                // Move all method arguments down so that they match what the original code expects.
                // Let's assume three arguments, one int, one long, one String and the and used to
                // use 4 registers
                move16 v5, v6             # ARG1
                move-wide16 v6:v7, v7:v8  # ARG2 (overlapping moves are allowed)
                move-object16 v8, v9      # ARG3

                // foo();
                // return bar();
                unmodified original byte code
            }
            */

            CodeIr c(method.get(), dex_ir);

            // Make sure there are at least 5 local registers to use
            int originalNumRegisters = method->code->registers - method->code->ins_count;
            int numAdditionalRegs = std::max(0, 5 - originalNumRegisters);
            int firstArg = originalNumRegisters + numAdditionalRegs;

            if (numAdditionalRegs > 0) {
                c.ir_method->code->registers += numAdditionalRegs;
            }

            lir::Instruction* fi = *(c.instructions.begin());

            // Add methodDesc to dex file
            std::stringstream ss;
            ss << method->decl->parent->Decl() << "#" << method->decl->name->c_str() << "(" ;
            bool first = true;
            if (method->decl->prototype->param_types != nullptr) {
                for (const auto& type : method->decl->prototype->param_types->types) {
                    if (first) {
                        first = false;
                    } else {
                        ss << ",";
                    }

                    ss << type->Decl().c_str();
                }
            }
            ss << ")";
            std::string methodDescStr = ss.str();
            ir::String* methodDesc = b.GetAsciiString(methodDescStr.c_str());

            size_t numParams = getNumParams(method.get());

            Label* originalMethodLabel = c.Alloc<Label>(0);
            CodeLocation* originalMethod = c.Alloc<CodeLocation>(originalMethodLabel);
            VReg* v0 = c.Alloc<VReg>(0);
            VReg* v1 = c.Alloc<VReg>(1);
            VReg* v2 = c.Alloc<VReg>(2);
            VReg* v3 = c.Alloc<VReg>(3);
            VReg* v4 = c.Alloc<VReg>(4);

            addInstr(c, fi, OP_CONST_STRING, {v0, c.Alloc<String>(id, id->orig_index)});
            addInstr(c, fi, OP_CONST, {v1, c.Alloc<Const32>(0)});
            addCall(b, c, fi, OP_INVOKE_STATIC, dispatcherT, "get", dispatcherT, {stringT, objectT},
                    {0, 1});
            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v0});
            addInstr(c, fi, OP_IF_EQZ, {v0, originalMethod});
            addInstr(c, fi, OP_CONST_STRING,
                     {v1, c.Alloc<String>(methodDesc, methodDesc->orig_index)});
            addInstr(c, fi, OP_CONST, {v2, c.Alloc<Const32>(0)});
            addCall(b, c, fi, OP_INVOKE_VIRTUAL, dispatcherT, "getOrigin", methodT,
                    {objectT, stringT}, {0, 2, 1});
            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v1});
            addInstr(c, fi, OP_IF_EQZ, {v1, originalMethod});
            addInstr(c, fi, OP_CONST, {v3, c.Alloc<Const32>(numParams)});
            addInstr(c, fi, OP_NEW_ARRAY, {v2, v3, c.Alloc<Type>(objectArrayT,
                                                                 objectArrayT->orig_index)});

            if (numParams > 0) {
                int argReg = firstArg;

                for (int argNum = 0; argNum < numParams; argNum++) {
                    const auto& type = method->decl->prototype->param_types->types[argNum];
                    BoxingInfo boxingInfo = getBoxingInfo(b, type->descriptor->c_str()[0]);

                    switch (type->GetCategory()) {
                        case ir::Type::Category::Scalar:
                            addInstr(c, fi, OP_MOVE_FROM16, {v3, c.Alloc<VReg>(argReg)});
                            addCall(b, c, fi, OP_INVOKE_STATIC, boxingInfo.boxedType, "valueOf",
                                    boxingInfo.boxedType, {type}, {3});
                            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v3});

                            argReg++;
                            break;
                        case ir::Type::Category::WideScalar: {
                            VRegPair* v3v4 = c.Alloc<VRegPair>(3);
                            VRegPair* argRegPair = c.Alloc<VRegPair>(argReg);

                            addInstr(c, fi, OP_MOVE_WIDE_FROM16, {v3v4, argRegPair});
                            addCall(b, c, fi, OP_INVOKE_STATIC, boxingInfo.boxedType, "valueOf",
                                    boxingInfo.boxedType, {type}, {3, 4});
                            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v3});

                            argReg += 2;
                            break;
                        }
                        case ir::Type::Category::Reference:
                            addInstr(c, fi, OP_MOVE_OBJECT_FROM16, {v3, c.Alloc<VReg>(argReg)});

                            argReg++;
                            break;
                        case ir::Type::Category::Void:
                            assert(false);
                    }

                    addInstr(c, fi, OP_CONST, {v4, c.Alloc<Const32>(argNum)});
                    addInstr(c, fi, OP_APUT_OBJECT, {v3, v2, v4});
                }
            }

            // NASTY Hack: Push in method name as "mock"
            addInstr(c, fi, OP_CONST_STRING,
                     {v3, c.Alloc<String>(methodDesc, methodDesc->orig_index)});
            addCall(b, c, fi, OP_INVOKE_VIRTUAL, dispatcherT, "handle", callableT,
                    {objectT, methodT, objectArrayT}, {0, 3, 1, 2});
            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v0});
            addInstr(c, fi, OP_IF_EQZ, {v0, originalMethod});
            addCall(b, c, fi, OP_INVOKE_INTERFACE, callableT, "call", objectT, {}, {0});
            addInstr(c, fi, OP_MOVE_RESULT_OBJECT, {v0});

            ir::Type *returnType = method->decl->prototype->return_type;
            BoxingInfo boxingInfo = getBoxingInfo(b, returnType->descriptor->c_str()[0]);

            switch (returnType->GetCategory()) {
                case ir::Type::Category::Scalar:
                    addInstr(c, fi, OP_CHECK_CAST, {v0,
                                                    c.Alloc<Type>(boxingInfo.boxedType, boxingInfo.boxedType->orig_index)});
                    addCall(b, c, fi, OP_INVOKE_VIRTUAL, boxingInfo.boxedType,
                            boxingInfo.unboxMethod.c_str(), returnType, {}, {0});
                    addInstr(c, fi, OP_MOVE_RESULT, {v0});
                    addInstr(c, fi, OP_RETURN, {v0});
                    break;
                case ir::Type::Category::WideScalar: {
                    VRegPair* v0v1 = c.Alloc<VRegPair>(0);

                    addInstr(c, fi, OP_CHECK_CAST, {v0,
                                                    c.Alloc<Type>(boxingInfo.boxedType, boxingInfo.boxedType->orig_index)});
                    addCall(b, c, fi, OP_INVOKE_VIRTUAL, boxingInfo.boxedType,
                            boxingInfo.unboxMethod.c_str(), returnType, {}, {0});
                    addInstr(c, fi, OP_MOVE_RESULT_WIDE, {v0v1});
                    addInstr(c, fi, OP_RETURN_WIDE, {v0v1});
                    break;
                }
                case ir::Type::Category::Reference:
                    addInstr(c, fi, OP_CHECK_CAST, {v0, c.Alloc<Type>(returnType,
                                                                      returnType->orig_index)});
                    addInstr(c, fi, OP_RETURN_OBJECT, {v0});
                    break;
                case ir::Type::Category::Void:
                    addInstr(c, fi, OP_RETURN_VOID, {});
                    break;
            }

            addLabel(c, fi, originalMethodLabel);

            if (numParams > 0) {
                int argReg = firstArg;

                for (int argNum = 0; argNum < numParams; argNum++) {
                    const auto& type = method->decl->prototype->param_types->types[argNum];
                    int origReg = argReg - numAdditionalRegs;
                    switch (type->GetCategory()) {
                        case ir::Type::Category::Scalar:
                            addInstr(c, fi, OP_MOVE_16, {c.Alloc<VReg>(origReg),
                                                         c.Alloc<VReg>(argReg)});
                            argReg++;
                            break;
                        case ir::Type::Category::WideScalar:
                            addInstr(c, fi, OP_MOVE_WIDE_16,{c.Alloc<VRegPair>(origReg),
                                                             c.Alloc<VRegPair>(argReg)});
                            argReg +=2;
                            break;
                        case ir::Type::Category::Reference:
                            addInstr(c, fi, OP_MOVE_OBJECT_16, {c.Alloc<VReg>(origReg),
                                                                c.Alloc<VReg>(argReg)});
                            argReg++;
                            break;
                    }
                }
            }

            c.Assemble();
        }

        struct Allocator : public Writer::Allocator {
            virtual void* Allocate(size_t size) {return ::malloc(size);}
            virtual void Free(void* ptr) {::free(ptr);}
        };

        Allocator allocator;
        Writer writer(dex_ir);
        size_t transformedLen = 0;
        std::shared_ptr<jbyte> transformed((jbyte*)writer.CreateImage(&allocator, &transformedLen));

        jbyteArray transformedArr = env->NewByteArray(transformedLen);
        env->SetByteArrayRegion(transformedArr, 0, transformedLen, transformed.get());

        return transformedArr;
    }

    // Initializes the agent
    extern "C" jint Agent_OnAttach(JavaVM* vm,
                                   char* options,
                                   void* reserved) {
        jint jvmError = vm->GetEnv(reinterpret_cast<void**>(&localJvmtiEnv), JVMTI_VERSION_1_2);
        if (jvmError != JNI_OK) {
            return jvmError;
        }

        jvmtiCapabilities caps;
        memset(&caps, 0, sizeof(caps));
        caps.can_retransform_classes = 1;

        jvmtiError error = localJvmtiEnv->AddCapabilities(&caps);
        if (error != JVMTI_ERROR_NONE) {
            return error;
        }

        jvmtiEventCallbacks cb;
        memset(&cb, 0, sizeof(cb));
        cb.ClassFileLoadHook = Transform;

        error = localJvmtiEnv->SetEventCallbacks(&cb, sizeof(cb));
        if (error != JVMTI_ERROR_NONE) {
            return error;
        }

        error = localJvmtiEnv->SetEventNotificationMode(JVMTI_ENABLE,
                                                        JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, nullptr);
        if (error != JVMTI_ERROR_NONE) {
            return error;
        }

        return JVMTI_ERROR_NONE;
    }

    // Throw runtime exception
    static void throwRuntimeExpection(JNIEnv* env, const char* fmt, ...) {
        char msgBuf[512];

        va_list args;
        va_start (args, fmt);
        vsnprintf(msgBuf, sizeof(msgBuf), fmt, args);
        va_end (args);

        jclass exceptionClass = env->FindClass("java/lang/RuntimeException");
        env->ThrowNew(exceptionClass, msgBuf);
    }

    // Register transformer hook
    extern "C" JNIEXPORT void JNICALL
    Java_com_android_dx_mockito_inline_StaticJvmtiAgent_nativeRegisterTransformerHook(JNIEnv* env,
                                                                                     jobject thiz) {
        sTransformer = env->NewGlobalRef(thiz);
    }

    // Unregister transformer hook
    extern "C" JNIEXPORT void JNICALL
    Java_com_android_dx_mockito_inline_StaticJvmtiAgent_nativeUnregisterTransformerHook(JNIEnv* env,
                                                                                     jobject thiz) {
        env->DeleteGlobalRef(sTransformer);
        sTransformer = nullptr;
    }

    // Triggers retransformation of classes via this file's Transform method
    extern "C" JNIEXPORT void JNICALL
    Java_com_android_dx_mockito_inline_StaticJvmtiAgent_nativeRetransformClasses(JNIEnv* env,
                                                                             jobject thiz,
                                                                             jobjectArray classes) {
        jsize numTransformedClasses = env->GetArrayLength(classes);
        jclass *transformedClasses = (jclass*) malloc(numTransformedClasses * sizeof(jclass));
        for (int i = 0; i < numTransformedClasses; i++) {
            transformedClasses[i] = (jclass) env->NewGlobalRef(env->GetObjectArrayElement(classes, i));
        }

        jvmtiError error = localJvmtiEnv->RetransformClasses(numTransformedClasses,
                                                             transformedClasses);

        for (int i = 0; i < numTransformedClasses; i++) {
            env->DeleteGlobalRef(transformedClasses[i]);
        }
        free(transformedClasses);

        if (error != JVMTI_ERROR_NONE) {
            throwRuntimeExpection(env, "Could not retransform classes: %d", error);
        }
    }

    static jvmtiFrameInfo* frameToInspect;
    static std::string calledClass;

    // Takes the full dex file for class 'classBeingRedefined'
    // - isolates the dex code for the class out of the dex file
    // - calls sTransformer.runTransformers on the isolated dex code
    // - send the transformed code back to the runtime
    static void
    InspectClass(jvmtiEnv* jvmtiEnv,
                 JNIEnv* env,
                 jclass classBeingRedefined,
                 jobject loader,
                 const char* name,
                 jobject protectionDomain,
                 jint classDataLen,
                 const unsigned char* classData,
                 jint* newClassDataLen,
                 unsigned char** newClassData) {
        calledClass = "none";

        Reader reader(classData, classDataLen);

        char *calledMethodName;
        char *calledMethodSignature;
        jvmtiError error = jvmtiEnv->GetMethodName(frameToInspect->method, &calledMethodName,
                                                   &calledMethodSignature, nullptr);
        if (error != JVMTI_ERROR_NONE) {
            return;
        }

        u4 index = reader.FindClassIndex(ClassNameToDescriptor(name).c_str());
        reader.CreateClassIr(index);
        std::shared_ptr<ir::DexFile> class_ir = reader.GetIr();

        for (auto& method : class_ir->encoded_methods) {
            if (Utf8Cmp(method->decl->name->c_str(), calledMethodName) == 0
                && Utf8Cmp(method->decl->prototype->Signature().c_str(), calledMethodSignature) == 0) {
                CodeIr method_ir(method.get(), class_ir);

                for (auto instruction : method_ir.instructions) {
                    Bytecode* bytecode = dynamic_cast<Bytecode*>(instruction);
                    if (bytecode != nullptr && bytecode->offset == frameToInspect->location) {
                        Method *method = bytecode->CastOperand<Method>(1);
                        calledClass = method->ir_method->parent->Decl().c_str();

                        goto exit;
                    }
                }
            }
        }

        exit:
        free(calledMethodName);
        free(calledMethodSignature);
    }

#define GOTO_ON_ERROR(label) \
    if (error != JVMTI_ERROR_NONE) { \
        goto label; \
    }

// stack frame of the caller if method was called directly
#define DIRECT_CALL_STACK_FRAME (6)

// stack frame of the caller if method was called as 'real method'
#define REALMETHOD_CALL_STACK_FRAME (23)

    extern "C" JNIEXPORT jstring JNICALL
    Java_com_android_dx_mockito_inline_StaticMockMethodAdvice_nativeGetCalledClassName(JNIEnv* env,
                                                                            jclass klass,
                                                                            jthread currentThread) {

        JavaVM *vm;
        jint jvmError = env->GetJavaVM(&vm);
        if (jvmError != JNI_OK) {
            return nullptr;
        }

        jvmtiEnv *jvmtiEnv;
        jvmError = vm->GetEnv(reinterpret_cast<void**>(&jvmtiEnv), JVMTI_VERSION_1_2);
        if (jvmError != JNI_OK) {
            return nullptr;
        }

        jvmtiCapabilities caps;
        memset(&caps, 0, sizeof(caps));
        caps.can_retransform_classes = 1;

        jvmtiError error = jvmtiEnv->AddCapabilities(&caps);
        GOTO_ON_ERROR(unregister_env_and_exit);

        jvmtiEventCallbacks cb;
        memset(&cb, 0, sizeof(cb));
        cb.ClassFileLoadHook = InspectClass;

        jvmtiFrameInfo frameInfo[REALMETHOD_CALL_STACK_FRAME + 1];
        jint numFrames;
        error = jvmtiEnv->GetStackTrace(nullptr, 0, REALMETHOD_CALL_STACK_FRAME + 1, frameInfo,
                                        &numFrames);
        GOTO_ON_ERROR(unregister_env_and_exit);

        // Method might be called directly or as 'real method' (see
        // StaticMockMethodAdvice.SuperMethodCall#invoke). Hence the real caller might be in stack
        // frame DIRECT_CALL_STACK_FRAME for a direct call or REALMETHOD_CALL_STACK_FRAME for a
        // call through the 'real method' mechanism.
        int callingFrameNum;
        if (numFrames < REALMETHOD_CALL_STACK_FRAME) {
            callingFrameNum = DIRECT_CALL_STACK_FRAME;
        } else {
            char *directCallMethodName;

            jvmtiEnv->GetMethodName(frameInfo[DIRECT_CALL_STACK_FRAME].method,
                                    &directCallMethodName, nullptr, nullptr);
            if (strcmp(directCallMethodName, "invoke") == 0) {
                callingFrameNum = REALMETHOD_CALL_STACK_FRAME;
            } else {
                callingFrameNum = DIRECT_CALL_STACK_FRAME;
            }
        }

        jclass callingClass;
        error = jvmtiEnv->GetMethodDeclaringClass(frameInfo[callingFrameNum].method, &callingClass);
        GOTO_ON_ERROR(unregister_env_and_exit);

        error = jvmtiEnv->SetEventCallbacks(&cb, sizeof(cb));
        GOTO_ON_ERROR(unregister_env_and_exit);

        error = jvmtiEnv->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
                                                   currentThread);
        GOTO_ON_ERROR(unset_cb_and_exit);

        frameToInspect = &frameInfo[callingFrameNum];
        error = jvmtiEnv->RetransformClasses(1, &callingClass);
        GOTO_ON_ERROR(disable_hook_and_exit);

        disable_hook_and_exit:
        jvmtiEnv->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
                                           currentThread);

        unset_cb_and_exit:
        memset(&cb, 0, sizeof(cb));
        jvmtiEnv->SetEventCallbacks(&cb, sizeof(cb));

        unregister_env_and_exit:
        jvmtiEnv->DisposeEnvironment();

        if (error != JVMTI_ERROR_NONE) {
            return nullptr;
        }

        return env->NewStringUTF(calledClass.c_str());
    }

}  // namespace com_android_dx_mockito_inline