aboutsummaryrefslogtreecommitdiff
path: root/sandbox/src/main/java/org/robolectric/internal/bytecode/ClassInstrumentor.java
blob: a9b532a2678d91ddae0dca8f6f7674ebef28730b (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
package org.robolectric.internal.bytecode;

import static java.lang.invoke.MethodType.methodType;

import com.google.common.collect.Iterables;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.ConstantDynamic;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.JSRInlinerAdapter;
import org.objectweb.asm.commons.Method;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.robolectric.util.PerfStatsCollector;

/**
 * Instruments (i.e. modifies the bytecode) of classes to place the scaffolding necessary to use
 * Robolectric's shadows.
 */
public class ClassInstrumentor {
  private static final Handle BOOTSTRAP_INIT;
  private static final Handle BOOTSTRAP;
  private static final Handle BOOTSTRAP_STATIC;
  private static final Handle BOOTSTRAP_INTRINSIC;
  private static final String ROBO_INIT_METHOD_NAME = "$$robo$init";
  protected static final Type OBJECT_TYPE = Type.getType(Object.class);
  private static final ShadowImpl SHADOW_IMPL = new ShadowImpl();
  final Decorator decorator;

  static {
    String className = Type.getInternalName(InvokeDynamicSupport.class);

    MethodType bootstrap =
        methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class);

    /*
     * There is an additional int.class argument to the invokedynamic bootstrap method. This conveys
     * whether or not the method invocation represents a native method. A one means the original
     * method was a native method, and a zero means it was not. It should be boolean.class, but
     * that is nt possible due to https://bugs.java.com/bugdatabase/view_bug?bug_id=JDK-8322510.
     */
    String bootstrapMethod =
        bootstrap
            .appendParameterTypes(MethodHandle.class, /* isNative */ int.class)
            .toMethodDescriptorString();
    String bootstrapIntrinsic =
        bootstrap.appendParameterTypes(String.class).toMethodDescriptorString();

    BOOTSTRAP_INIT =
        new Handle(
            Opcodes.H_INVOKESTATIC,
            className,
            "bootstrapInit",
            bootstrap.toMethodDescriptorString(),
            false);
    BOOTSTRAP = new Handle(Opcodes.H_INVOKESTATIC, className, "bootstrap", bootstrapMethod, false);
    BOOTSTRAP_STATIC =
        new Handle(Opcodes.H_INVOKESTATIC, className, "bootstrapStatic", bootstrapMethod, false);
    BOOTSTRAP_INTRINSIC =
        new Handle(
            Opcodes.H_INVOKESTATIC, className, "bootstrapIntrinsic", bootstrapIntrinsic, false);
  }

  public ClassInstrumentor() {
    this(new ShadowDecorator());
  }

  protected ClassInstrumentor(Decorator decorator) {
    this.decorator = decorator;
  }

  private MutableClass analyzeClass(
      byte[] origClassBytes,
      final InstrumentationConfiguration config,
      ClassNodeProvider classNodeProvider) {
    ClassNode classNode =
        new ClassNode(Opcodes.ASM4) {
          @Override
          public MethodVisitor visitMethod(
              int access, String name, String desc, String signature, String[] exceptions) {
            MethodVisitor methodVisitor =
                super.visitMethod(access, name, config.remapParams(desc), signature, exceptions);
            return new JSRInlinerAdapter(methodVisitor, access, name, desc, signature, exceptions);
          }
        };

    final ClassReader classReader = new ClassReader(origClassBytes);
    classReader.accept(classNode, 0);
    return new MutableClass(classNode, config, classNodeProvider);
  }

  byte[] instrumentToBytes(MutableClass mutableClass) {
    instrument(mutableClass);

    ClassNode classNode = mutableClass.classNode;
    ClassWriter writer = new InstrumentingClassWriter(mutableClass.classNodeProvider, classNode);
    Remapper remapper =
        new Remapper() {
          @Override
          public String map(final String internalName) {
            return mutableClass.config.mappedTypeName(internalName);
          }
        };
    ClassRemapper visitor = new ClassRemapper(writer, remapper);
    classNode.accept(visitor);

    return writer.toByteArray();
  }

  public byte[] instrument(
      ClassDetails classDetails,
      InstrumentationConfiguration config,
      ClassNodeProvider classNodeProvider) {
    PerfStatsCollector perfStats = PerfStatsCollector.getInstance();
    MutableClass mutableClass =
        perfStats.measure(
            "analyze class",
            () -> analyzeClass(classDetails.getClassBytes(), config, classNodeProvider));
    byte[] instrumentedBytes =
        perfStats.measure("instrument class", () -> instrumentToBytes(mutableClass));
    recordPackageStats(perfStats, mutableClass);
    return instrumentedBytes;
  }

  private void recordPackageStats(PerfStatsCollector perfStats, MutableClass mutableClass) {
    String className = mutableClass.getName();
    for (int i = className.indexOf('.'); i != -1; i = className.indexOf('.', i + 1)) {
      perfStats.incrementCount("instrument package " + className.substring(0, i));
    }
  }

  public void instrument(MutableClass mutableClass) {
    try {
      // Need Java version >=7 to allow invokedynamic
      mutableClass.classNode.version = Math.max(mutableClass.classNode.version, Opcodes.V1_7);

      if (mutableClass.getName().equals("android.util.SparseArray")) {
        addSetToSparseArray(mutableClass);
      }

      instrumentMethods(mutableClass);

      if (mutableClass.isInterface()) {
        mutableClass.addInterface(Type.getInternalName(InstrumentedInterface.class));
      } else {
        makeClassPublic(mutableClass.classNode);
        if ((mutableClass.classNode.access & Opcodes.ACC_FINAL) == Opcodes.ACC_FINAL) {
          mutableClass
              .classNode
              .visitAnnotation("Lcom/google/errorprone/annotations/DoNotMock;", true)
              .visit(
                  "value",
                  "This class is final. Consider using the real thing, or "
                      + "adding/enhancing a Robolectric shadow for it.");
        }
        mutableClass.classNode.access = mutableClass.classNode.access & ~Opcodes.ACC_FINAL;

        // If there is no constructor, adds one
        addNoArgsConstructor(mutableClass);

        addRoboInitMethod(mutableClass);

        removeFinalFromFields(mutableClass);

        decorator.decorate(mutableClass);
      }
    } catch (Exception e) {
      throw new RuntimeException("failed to instrument " + mutableClass.getName(), e);
    }
  }

  // See https://github.com/robolectric/robolectric/issues/6840
  // Adds Set(int, object) to android.util.SparseArray.
  private void addSetToSparseArray(MutableClass mutableClass) {
    for (MethodNode method : mutableClass.getMethods()) {
      if ("set".equals(method.name)) {
        return;
      }
    }

    MethodNode setFunction =
        new MethodNode(
            Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC,
            "set",
            "(ILjava/lang/Object;)V",
            "(ITE;)V",
            null);
    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(setFunction);
    generator.loadThis();
    generator.loadArg(0);
    generator.loadArg(1);
    generator.invokeVirtual(mutableClass.classType, new Method("put", "(ILjava/lang/Object;)V"));
    generator.returnValue();
    mutableClass.addMethod(setFunction);
  }

  /**
   * Checks if the first or second instruction is a Jacoco load instruction. Robolectric is not
   * capable at the moment of re-instrumenting Jacoco-instrumented constructors, so these are
   * currently skipped.
   *
   * @param ctor constructor method node
   * @return whether or not the constructor can be instrumented
   */
  private boolean isJacocoInstrumented(MethodNode ctor) {
    AbstractInsnNode[] insns = ctor.instructions.toArray();
    if (insns.length > 1) {
      AbstractInsnNode node = insns[0];
      if (node instanceof LabelNode) {
        node = insns[1];
      }
      if ((node instanceof LdcInsnNode && ((LdcInsnNode) node).cst instanceof ConstantDynamic)) {
        ConstantDynamic cst = (ConstantDynamic) ((LdcInsnNode) node).cst;
        return cst.getName().equals("$jacocoData");
      } else if (node instanceof MethodInsnNode) {
        return Objects.equals(((MethodInsnNode) node).name, "$jacocoInit");
      }
    }
    return false;
  }

  /**
   * Adds a call $$robo$init, which instantiates a shadow object if required. This is to support
   * custom shadows for Jacoco-instrumented classes (except cnstructor shadows).
   */
  protected void addCallToRoboInit(MutableClass mutableClass, MethodNode ctor) {
    AbstractInsnNode returnNode =
        Iterables.find(
            ctor.instructions,
            node -> {
              if (node.getOpcode() == Opcodes.INVOKESPECIAL) {
                MethodInsnNode mNode = (MethodInsnNode) node;
                return (mNode.owner.equals(mutableClass.internalClassName)
                    || mNode.owner.equals(mutableClass.classNode.superName));
              }
              return false;
            },
            null);
    ctor.instructions.insert(
        returnNode,
        new MethodInsnNode(
            Opcodes.INVOKEVIRTUAL,
            mutableClass.classType.getInternalName(),
            ROBO_INIT_METHOD_NAME,
            "()V"));
    ctor.instructions.insert(returnNode, new VarInsnNode(Opcodes.ALOAD, 0));
  }

  private void instrumentMethods(MutableClass mutableClass) {
    if (mutableClass.isInterface()) {
      for (MethodNode method : mutableClass.getMethods()) {
        rewriteMethodBody(mutableClass, method);
      }
    } else {
      for (MethodNode method : mutableClass.getMethods()) {
        rewriteMethodBody(mutableClass, method);

        if (method.name.equals("<clinit>")) {
          method.name = ShadowConstants.STATIC_INITIALIZER_METHOD_NAME;
          mutableClass.addMethod(generateStaticInitializerNotifierMethod(mutableClass));
        } else if (method.name.equals("<init>")) {
          if (isJacocoInstrumented(method)) {
            addCallToRoboInit(mutableClass, method);
          } else {
            instrumentConstructor(mutableClass, method);
          }
        } else if (!isSyntheticAccessorMethod(method) && !Modifier.isAbstract(method.access)) {
          instrumentNormalMethod(mutableClass, method);
        }
      }
    }
  }

  private static void addNoArgsConstructor(MutableClass mutableClass) {
    if (!mutableClass.foundMethods.contains("<init>()V")) {
      MethodNode defaultConstructor =
          new MethodNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, "<init>", "()V", "()V", null);
      RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(defaultConstructor);
      generator.loadThis();
      generator.visitMethodInsn(
          Opcodes.INVOKESPECIAL, mutableClass.classNode.superName, "<init>", "()V", false);
      generator.loadThis();
      generator.invokeVirtual(mutableClass.classType, new Method(ROBO_INIT_METHOD_NAME, "()V"));
      generator.returnValue();
      mutableClass.addMethod(defaultConstructor);
    }
  }

  /**
   * Generates code like this:
   *
   * <pre>
   * protected void $$robo$init() {
   *   if (__robo_data__ == null) {
   *     __robo_data__ = RobolectricInternals.initializing(this);
   *   }
   * }
   * </pre>
   */
  private void addRoboInitMethod(MutableClass mutableClass) {
    MethodNode initMethodNode =
        new MethodNode(
            Opcodes.ACC_PROTECTED | Opcodes.ACC_SYNTHETIC,
            ROBO_INIT_METHOD_NAME,
            "()V",
            null,
            null);
    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(initMethodNode);
    Label alreadyInitialized = new Label();
    generator.loadThis(); // this
    generator.getField(
        mutableClass.classType,
        ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME,
        OBJECT_TYPE); // contents of __robo_data__
    generator.ifNonNull(alreadyInitialized);
    generator.loadThis(); // this
    generator.loadThis(); // this, this
    writeCallToInitializing(mutableClass, generator);
    // this, __robo_data__
    generator.putField(
        mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE);
    generator.mark(alreadyInitialized);
    generator.returnValue();
    mutableClass.addMethod(initMethodNode);
  }

  protected void writeCallToInitializing(
      MutableClass mutableClass, RobolectricGeneratorAdapter generator) {
    generator.invokeDynamic(
        "initializing",
        Type.getMethodDescriptor(OBJECT_TYPE, mutableClass.classType),
        BOOTSTRAP_INIT);
  }

  private static void removeFinalFromFields(MutableClass mutableClass) {
    for (FieldNode fieldNode : mutableClass.getFields()) {
      fieldNode.access &= ~Modifier.FINAL;
    }
  }

  private static boolean isSyntheticAccessorMethod(MethodNode method) {
    return (method.access & Opcodes.ACC_SYNTHETIC) != 0;
  }

  /**
   * Constructors are instrumented as follows:
   *
   * <ul>
   *   <li>The original constructor will be stripped of its instructions leading up to, and
   *       including, the call to super() or this(). It is also renamed to $$robo$$__constructor__
   *   <li>A method called __constructor__ is created and its job is to call
   *       $$robo$$__constructor__. The __constructor__ method is what gets shadowed if a Shadow
   *       wants to shadow a constructor.
   *   <li>A new constructor is created and contains the stripped instructions of the original
   *       constructor leading up to, and including, the call to super() or this(). Then, it has a
   *       call to $$robo$init to initialize the Class' Shadow Object. Then, it uses invokedynamic
   *       to call __constructor__. Finally, it contains any instructions that might occur after the
   *       return statement in the original constructor.
   * </ul>
   *
   * @param method the constructor to instrument
   */
  protected void instrumentConstructor(MutableClass mutableClass, MethodNode method) {
    int methodAccess = method.access;
    makeMethodPrivate(method);

    InsnList callSuper = extractCallToSuperConstructor(mutableClass, method);
    method.name = directMethodName(mutableClass, ShadowConstants.CONSTRUCTOR_METHOD_NAME);
    mutableClass.addMethod(
        redirectorMethod(mutableClass, method, ShadowConstants.CONSTRUCTOR_METHOD_NAME));

    String[] exceptions = exceptionArray(method);
    MethodNode initMethodNode =
        new MethodNode(methodAccess, "<init>", method.desc, method.signature, exceptions);
    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(initMethodNode);
    initMethodNode.instructions.add(callSuper);
    generator.loadThis();
    generator.invokeVirtual(mutableClass.classType, new Method(ROBO_INIT_METHOD_NAME, "()V"));
    generateClassHandlerCall(
        mutableClass, method, ShadowConstants.CONSTRUCTOR_METHOD_NAME, generator, false);

    generator.endMethod();

    InsnList postamble = extractInstructionsAfterReturn(method, initMethodNode);
    if (postamble.size() > 0) {
      initMethodNode.instructions.add(postamble);
    }
    mutableClass.addMethod(initMethodNode);
  }

  /**
   * Checks to see if there are instructions after RETURN. If there are, it will check to see if
   * they belong in the call-to-super, or the shadowable part of the constructor.
   */
  private InsnList extractInstructionsAfterReturn(MethodNode method, MethodNode initMethodNode) {
    InsnList removedInstructions = new InsnList();
    AbstractInsnNode returnNode =
        Iterables.find(
            method.instructions,
            node -> node instanceof InsnNode && node.getOpcode() == Opcodes.RETURN,
            null);
    if (returnNode == null) {
      return removedInstructions;
    }
    if (returnNode.getNext() instanceof LabelNode) {
      // There are instructions after the return, check where they belong. Note this is a very rare
      // edge case and only seems to happen with desugared+proguarded classes such as
      // play-services-basement's ApiException.
      LabelNode labelAfterReturn = (LabelNode) returnNode.getNext();
      boolean inInitMethodNode =
          Iterables.any(
              initMethodNode.instructions,
              input ->
                  input instanceof JumpInsnNode
                      && ((JumpInsnNode) input).label == labelAfterReturn);

      if (inInitMethodNode) {
        while (returnNode.getNext() != null) {
          AbstractInsnNode node = returnNode.getNext();
          method.instructions.remove(node);
          removedInstructions.add(node);
        }
      }
    }
    return removedInstructions;
  }

  private static InsnList extractCallToSuperConstructor(
      MutableClass mutableClass, MethodNode ctor) {
    InsnList removedInstructions = new InsnList();
    // Start removing instructions at the beginning of the method. The first instructions of
    // constructors may vary.
    int startIndex = 0;

    AbstractInsnNode[] insns = ctor.instructions.toArray();
    for (int i = 0; i < insns.length; i++) {
      AbstractInsnNode node = insns[i];

      switch (node.getOpcode()) {
        case Opcodes.INVOKESPECIAL:
          MethodInsnNode mnode = (MethodInsnNode) node;
          if (mnode.owner.equals(mutableClass.internalClassName)
              || mnode.owner.equals(mutableClass.classNode.superName)) {
            if (!"<init>".equals(mnode.name)) {
              throw new AssertionError("Invalid MethodInsnNode name");
            }

            // remove all instructions in the range 0 (the start) to invokespecial
            // <init>
            while (startIndex <= i) {
              ctor.instructions.remove(insns[startIndex]);
              removedInstructions.add(insns[startIndex]);
              startIndex++;
            }
            return removedInstructions;
          }
          break;

        case Opcodes.ATHROW:
          ctor.visitCode();
          ctor.visitInsn(Opcodes.RETURN);
          ctor.visitEnd();
          return removedInstructions;

        default:
          // nothing to do
      }
    }

    throw new RuntimeException("huh? " + ctor.name + ctor.desc);
  }

  /**
   * Instruments a normal method
   *
   * <ul>
   *   <li>Rename the method from {@code methodName} to {@code $$robo$$methodName}.
   *   <li>Make it private so we can invoke it directly without subclass overrides taking
   *       precedence.
   *   <li>Remove {@code final} modifiers, if present.
   *   <li>Create a delegator method named {@code methodName} which delegates to the {@link
   *       ClassHandler}.
   * </ul>
   */
  protected void instrumentNormalMethod(MutableClass mutableClass, MethodNode method) {
    // if not abstract, set a final modifier
    if ((method.access & Opcodes.ACC_ABSTRACT) == 0) {
      method.access = method.access | Opcodes.ACC_FINAL;
    }
    boolean isNativeMethod = (method.access & Opcodes.ACC_NATIVE) != 0;
    if (isNativeMethod) {
      instrumentNativeMethod(mutableClass, method);
    }

    // Create delegator method with same name as original method. The delegator method will use
    // invokedynamic to decide at runtime whether to call original method or shadowed method
    String originalName = method.name;
    method.name = directMethodName(mutableClass, originalName);

    MethodNode delegatorMethodNode =
        new MethodNode(
            method.access, originalName, method.desc, method.signature, exceptionArray(method));
    delegatorMethodNode.visibleAnnotations = method.visibleAnnotations;
    delegatorMethodNode.access &= ~(Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_FINAL);

    makeMethodPrivate(method);

    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(delegatorMethodNode);
    generateClassHandlerCall(mutableClass, method, originalName, generator, isNativeMethod);
    generator.endMethod();
    mutableClass.addMethod(delegatorMethodNode);
  }
  /**
   * Creates native stub which returns the default return value.
   *
   * @param mutableClass Class to be instrumented
   * @param method Method to be instrumented, must be native
   */
  protected void instrumentNativeMethod(MutableClass mutableClass, MethodNode method) {

    String nativeBindingMethodName =
        SHADOW_IMPL.directNativeMethodName(mutableClass.getName(), method.name);

    // Generate native binding method
    MethodNode nativeBindingMethod =
        new MethodNode(
            Opcodes.ASM4,
            nativeBindingMethodName,
            method.desc,
            method.signature,
            exceptionArray(method));
    nativeBindingMethod.access = method.access | Opcodes.ACC_SYNTHETIC;
    makeMethodPrivate(nativeBindingMethod);
    mutableClass.addMethod(nativeBindingMethod);

    method.access = method.access & ~Opcodes.ACC_NATIVE;

    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(method);

    Type returnType = generator.getReturnType();
    generator.pushDefaultReturnValueToStack(returnType);
    generator.returnValue();
  }

  protected static String directMethodName(MutableClass mutableClass, String originalName) {
    return SHADOW_IMPL.directMethodName(mutableClass.getName(), originalName);
  }

  // todo rename
  private MethodNode redirectorMethod(
      MutableClass mutableClass, MethodNode method, String newName) {
    MethodNode redirector =
        new MethodNode(
            Opcodes.ASM4, newName, method.desc, method.signature, exceptionArray(method));
    redirector.access =
        method.access & ~(Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_FINAL);
    makeMethodPrivate(redirector);
    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(redirector);
    generator.invokeMethod(mutableClass.internalClassName, method);
    generator.returnValue();
    return redirector;
  }

  protected String[] exceptionArray(MethodNode method) {
    List<String> exceptions = method.exceptions;
    return exceptions.toArray(new String[exceptions.size()]);
  }

  /** Filters methods that might need special treatment because of various reasons */
  private void rewriteMethodBody(MutableClass mutableClass, MethodNode callingMethod) {
    ListIterator<AbstractInsnNode> instructions = callingMethod.instructions.iterator();
    while (instructions.hasNext()) {
      AbstractInsnNode node = instructions.next();

      switch (node.getOpcode()) {
        case Opcodes.NEW:
          TypeInsnNode newInsnNode = (TypeInsnNode) node;
          newInsnNode.desc = mutableClass.config.mappedTypeName(newInsnNode.desc);
          break;

        case Opcodes.GETFIELD:
          /* falls through */
        case Opcodes.PUTFIELD:
          /* falls through */
        case Opcodes.GETSTATIC:
          /* falls through */
        case Opcodes.PUTSTATIC:
          FieldInsnNode fieldInsnNode = (FieldInsnNode) node;
          fieldInsnNode.desc = mutableClass.config.mappedTypeName(fieldInsnNode.desc); // todo test
          break;

        case Opcodes.INVOKESTATIC:
          /* falls through */
        case Opcodes.INVOKEINTERFACE:
          /* falls through */
        case Opcodes.INVOKESPECIAL:
          /* falls through */
        case Opcodes.INVOKEVIRTUAL:
          MethodInsnNode targetMethod = (MethodInsnNode) node;
          targetMethod.desc = mutableClass.config.remapParams(targetMethod.desc);
          if (isGregorianCalendarBooleanConstructor(targetMethod)) {
            replaceGregorianCalendarBooleanConstructor(instructions, targetMethod);
          } else if (mutableClass.config.shouldIntercept(targetMethod)) {
            interceptInvokeVirtualMethod(mutableClass, instructions, targetMethod);
          }
          break;

        case Opcodes.INVOKEDYNAMIC:
          /* no unusual behavior */
          break;

        default:
          break;
      }
    }
  }

  /**
   * Verifies if the @targetMethod is a {@code <init>(boolean)} constructor for {@link
   * java.util.GregorianCalendar}.
   */
  private static boolean isGregorianCalendarBooleanConstructor(MethodInsnNode targetMethod) {
    return targetMethod.owner.equals("java/util/GregorianCalendar")
        && targetMethod.name.equals("<init>")
        && targetMethod.desc.equals("(Z)V");
  }

  /**
   * Replaces the void {@code <init>(boolean)} constructor for a call to the {@code void <init>(int,
   * int, int)} one.
   */
  private static void replaceGregorianCalendarBooleanConstructor(
      ListIterator<AbstractInsnNode> instructions, MethodInsnNode targetMethod) {
    // Remove the call to GregorianCalendar(boolean)
    instructions.remove();

    // Discard the already-pushed parameter for GregorianCalendar(boolean)
    instructions.add(new InsnNode(Opcodes.POP));

    // Add parameters values for calling GregorianCalendar(int, int, int)
    instructions.add(new InsnNode(Opcodes.ICONST_0));
    instructions.add(new InsnNode(Opcodes.ICONST_0));
    instructions.add(new InsnNode(Opcodes.ICONST_0));

    // Call GregorianCalendar(int, int, int)
    instructions.add(
        new MethodInsnNode(
            Opcodes.INVOKESPECIAL,
            targetMethod.owner,
            targetMethod.name,
            "(III)V",
            targetMethod.itf));
  }

  /**
   * Decides to call through the appropriate method to intercept the method with an INVOKEVIRTUAL
   * Opcode, depending if the invokedynamic bytecode instruction is available (Java 7+).
   */
  protected void interceptInvokeVirtualMethod(
      MutableClass mutableClass,
      ListIterator<AbstractInsnNode> instructions,
      MethodInsnNode targetMethod) {
    instructions.remove(); // remove the method invocation

    Type type = Type.getObjectType(targetMethod.owner);
    String description = targetMethod.desc;
    String owner = type.getClassName();

    if (targetMethod.getOpcode() != Opcodes.INVOKESTATIC) {
      String thisType = type.getDescriptor();
      description = "(" + thisType + description.substring(1);
    }

    instructions.add(
        new InvokeDynamicInsnNode(targetMethod.name, description, BOOTSTRAP_INTRINSIC, owner));
  }

  /** Replaces protected and private class modifiers with public. */
  private static void makeClassPublic(ClassNode clazz) {
    clazz.access =
        (clazz.access | Opcodes.ACC_PUBLIC) & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
  }

  /** Replaces protected and public class modifiers with private. */
  protected void makeMethodPrivate(MethodNode method) {
    method.access =
        (method.access | Opcodes.ACC_PRIVATE) & ~(Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED);
  }

  private static MethodNode generateStaticInitializerNotifierMethod(MutableClass mutableClass) {
    MethodNode methodNode = new MethodNode(Opcodes.ACC_STATIC, "<clinit>", "()V", "()V", null);
    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(methodNode);
    generator.push(mutableClass.classType);
    generator.invokeStatic(
        Type.getType(RobolectricInternals.class),
        new Method("classInitializing", "(Ljava/lang/Class;)V"));
    generator.returnValue();
    generator.endMethod();
    return methodNode;
  }

  // todo javadocs
  protected void generateClassHandlerCall(
      MutableClass mutableClass,
      MethodNode originalMethod,
      String originalMethodName,
      RobolectricGeneratorAdapter generator,
      boolean isNativeMethod) {
    Handle original =
        new Handle(
            getTag(originalMethod),
            mutableClass.classType.getInternalName(),
            originalMethod.name,
            originalMethod.desc,
            getTag(originalMethod) == Opcodes.H_INVOKEINTERFACE);

    if (generator.isStatic()) {
      generator.loadArgs();
      generator.invokeDynamic(
          originalMethodName, originalMethod.desc, BOOTSTRAP_STATIC, original, isNativeMethod);
    } else {
      String desc = "(" + mutableClass.classType.getDescriptor() + originalMethod.desc.substring(1);
      generator.loadThis();
      generator.loadArgs();
      generator.invokeDynamic(originalMethodName, desc, BOOTSTRAP, original, isNativeMethod);
    }

    generator.returnValue();
  }

  int getTag(MethodNode m) {
    return Modifier.isStatic(m.access) ? Opcodes.H_INVOKESTATIC : Opcodes.H_INVOKESPECIAL;
  }

  // implemented in DirectClassInstrumentor
  public void setAndroidJarSDKVersion(int androidJarSDKVersion) {}

  // implemented in DirectClassInstrumentor
  protected int getAndroidJarSDKVersion() {
    return -1;
  }

  public interface Decorator {
    void decorate(MutableClass mutableClass);
  }

  /**
   * Provides try/catch code generation with a {@link org.objectweb.asm.commons.GeneratorAdapter}.
   */
  static class TryCatch {
    private final Label start;
    private final Label end;
    private final Label handler;
    private final GeneratorAdapter generatorAdapter;

    TryCatch(GeneratorAdapter generatorAdapter, Type type) {
      this.generatorAdapter = generatorAdapter;
      this.start = generatorAdapter.mark();
      this.end = new Label();
      this.handler = new Label();
      generatorAdapter.visitTryCatchBlock(start, end, handler, type.getInternalName());
    }

    void end() {
      generatorAdapter.mark(end);
    }

    void handler() {
      generatorAdapter.mark(handler);
    }
  }
}