org.objectweb.asm.Handle Java Examples

The following examples show how to use org.objectweb.asm.Handle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FramePaddingMethodVisitorTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Parameterized.Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][]{
            {"visitIntInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {"visitVarInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {"visitTypeInsn", new Class<?>[]{int.class, String.class}, new Object[]{0, ""}},
            {"visitFieldInsn", new Class<?>[]{int.class, String.class, String.class, String.class}, new Object[]{0, "", "", ""}},
            {"visitMethodInsn", new Class<?>[]{int.class, String.class, String.class, String.class, boolean.class}, new Object[]{0, "", "", "", false}},
            {"visitInvokeDynamicInsn", new Class<?>[]{String.class, String.class, Handle.class, Object[].class}, new Object[]{"", "", new Handle(0, "", "", "", false), new Object[0]}},
            {"visitJumpInsn", new Class<?>[]{int.class, Label.class}, new Object[]{0, new Label()}},
            {"visitLdcInsn", new Class<?>[]{Object.class}, new Object[]{new Object()}},
            {"visitIincInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {"visitTableSwitchInsn", new Class<?>[]{int.class, int.class, Label.class, Label[].class}, new Object[]{0, 0, new Label(), new Label[0]}},
            {"visitLookupSwitchInsn", new Class<?>[]{Label.class, int[].class, Label[].class}, new Object[]{new Label(), new int[0], new Label[0]}},
            {"visitMultiANewArrayInsn", new Class<?>[]{String.class, int.class}, new Object[]{"", 0}},
            {"visitInsn", new Class<?>[]{int.class}, new Object[]{1}},
    });
}
 
Example #2
Source File: AbstractFunctionalInterfaceWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
default Object[] createBootstrapMethodArguments(String abstractMethodDesc, int insn, ClassNode methodOwnerClassNode, MethodNode methodNode, boolean serializable) {
    Parameter[] parameters = methodNode.getNodeMetaData(ORIGINAL_PARAMETERS_WITH_EXACT_TYPE);
    List<Object> argumentList = new LinkedList<>();

    argumentList.add(Type.getType(abstractMethodDesc));
    argumentList.add(
            new Handle(
                    insn,
                    BytecodeHelper.getClassInternalName(methodOwnerClassNode.getName()),
                    methodNode.getName(),
                    BytecodeHelper.getMethodDescriptor(methodNode),
                    methodOwnerClassNode.isInterface()
            )
    );
    argumentList.add(Type.getType(BytecodeHelper.getMethodDescriptor(methodNode.getReturnType(), parameters)));

    if (serializable) {
        argumentList.add(5);
        argumentList.add(0);
    }

    return argumentList.toArray();
}
 
Example #3
Source File: AbstractFunctionalInterfaceWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
default Handle createBootstrapMethod(boolean isInterface, boolean serializable) {
    if (serializable) {
        return new Handle(
                Opcodes.H_INVOKESTATIC,
                "java/lang/invoke/LambdaMetafactory",
                "altMetafactory",
                "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;",
                isInterface
        );
    }

    return new Handle(
            Opcodes.H_INVOKESTATIC,
            "java/lang/invoke/LambdaMetafactory",
            "metafactory",
            "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
            isInterface
    );
}
 
Example #4
Source File: AbstractAsyncMethodTransformer.java    From tascalate-async-await with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected Object[] findOwnerInvokeDynamic(AbstractInsnNode instruction, List<MethodNode> ownerMethods) {
    if (instruction instanceof InvokeDynamicInsnNode) {
        InvokeDynamicInsnNode n = (InvokeDynamicInsnNode) instruction;
        Handle bsm = n.bsm;
        if ("java/lang/invoke/LambdaMetafactory".equals(bsm.getOwner()) && "metafactory".equals(bsm.getName())) {
            Handle method = Arrays
                .stream(n.bsmArgs)
                .filter(Handle.class::isInstance)
                .map(Handle.class::cast)
                .filter(h -> h.getOwner().equals(classNode.name) /*&& h.getName().startsWith("lambda$")*/)
                .findFirst()
                .orElse(null);
            
            if (null != method) {
                MethodNode targetMethodNode = getMethod(method.getName(), method.getDesc(), ownerMethods);
                if (null != targetMethodNode && (targetMethodNode.access & (/*ACC_STATIC + ACC_PRIVATE +*/ ACC_SYNTHETIC)) == /*ACC_STATIC + ACC_PRIVATE + */ACC_SYNTHETIC) {
                    return new Object[] {method, targetMethodNode};
                }
            }
        }
    }
    return null;
}
 
Example #5
Source File: StateTrackingMethodVisitor.java    From scott with MIT License 6 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
	/*
	 * Track where lambda expressions are defined.
	 */
	if (instrumentationActions.anyLambdaMarkedForTracking()) {
		if ("java/lang/invoke/LambdaMetafactory".equals(bsm.getOwner()) && bsmArgs[1] instanceof Handle) {
			Handle handle = (Handle)bsmArgs[1];
			if (handle.getName().startsWith("lambda$")) {
				instrumentToTrackLambdaDefinition(handle.getName(), lineNumber);
			}
		}
	}
	
	super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
}
 
Example #6
Source File: MethodWeaver.java    From Concurnas with MIT License 6 votes vote down vote up
private void invokeDynamicOnLambda(MethodVisitor mv, AbstractInsnNode ain) {
    InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode)ain;
    Object[]bsmArgs = indy.bsmArgs;
    // Is it a lambda conversion
    if (indy.bsm.getOwner().equals("java/lang/invoke/LambdaMetafactory")) {
        Handle lambdaBody = (Handle)bsmArgs[1];
        Detector detector = this.methodFlow.detector();
        String desc = lambdaBody.getDesc();
        //if (detector.isPausable(lambdaBody.getOwner(), lambdaBody.getName(), desc)) {
        //if(!lambdaBody.getName().equals("<init>")) {
        	bsmArgs[0] = addFiberType((org.objectweb.asm.Type)bsmArgs[0]);
            bsmArgs[1] = new Handle(lambdaBody.getTag(), 
                                    lambdaBody.getOwner(), 
                                    lambdaBody.getName(), 
                                    desc.replace(")", D_FIBER + ")"));
            bsmArgs[2] = addFiberType((org.objectweb.asm.Type)bsmArgs[2]);
        //}
            
        //}
    }
    ain.accept(mv);
}
 
Example #7
Source File: LambdaDesugaring.java    From bazel with Apache License 2.0 6 votes vote down vote up
private Executable findTargetMethod(Handle invokedMethod) throws ClassNotFoundException {
  Type descriptor = Type.getMethodType(invokedMethod.getDesc());
  Class<?> owner = loadFromInternal(invokedMethod.getOwner());
  if (invokedMethod.getTag() == Opcodes.H_NEWINVOKESPECIAL) {
    for (Constructor<?> c : owner.getDeclaredConstructors()) {
      if (Type.getType(c).equals(descriptor)) {
        return c;
      }
    }
  } else {
    for (Method m : owner.getDeclaredMethods()) {
      if (m.getName().equals(invokedMethod.getName()) && Type.getType(m).equals(descriptor)) {
        return m;
      }
    }
  }
  throw new IllegalArgumentException("Referenced method not found: " + invokedMethod);
}
 
Example #8
Source File: BigIntegerMutator.java    From pitest with Apache License 2.0 6 votes vote down vote up
/**
 * Mutates a handle within an invoke virtual.
 */
private Handle mutateHandle(Handle handle) {
  int opcode = handle.getTag();
  String owner = handle.getOwner();
  String name = handle.getName();
  String descriptor = handle.getDesc();

  if (owner.equals(expectedOwner) && opcode == Opcodes.H_INVOKEVIRTUAL) {
    if (REPLACEMENTS.containsKey(name)) {
      Replacement replacement = REPLACEMENTS.get(name);
      if (replacement.descriptor.equals(descriptor)) {
        MutationIdentifier id = context.registerMutation(factory, replacement.toString());
        if (context.shouldMutate(id)) {
          return new Handle(
              opcode,
              owner,
              replacement.destinationName,
              descriptor,
              handle.isInterface());
        }
      }
    }
  }
  return handle;
}
 
Example #9
Source File: ASMContentHandler.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
Handle decodeHandle(final String val) throws SAXException {
  try {
    int dotIndex = val.indexOf('.');
    int descIndex = val.indexOf('(', dotIndex + 1);
    int tagIndex = val.lastIndexOf('(');
    int itfIndex = val.indexOf(' ', tagIndex + 1);

    boolean itf = itfIndex != -1;
    int tag = Integer.parseInt(val.substring(tagIndex + 1, itf ? val.length() - 1 : itfIndex));
    String owner = val.substring(0, dotIndex);
    String name = val.substring(dotIndex + 1, descIndex);
    String desc = val.substring(descIndex, tagIndex - 1);
    return new Handle(tag, owner, name, desc, itf);

  } catch (RuntimeException e) {
    throw new SAXException("Malformed handle " + val, e);
  }
}
 
Example #10
Source File: ExceptionTableSensitiveMethodVisitorTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Parameterized.Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][]{
            {Opcodes.ASM6, "visitLabel", new Class<?>[]{Label.class}, new Object[]{new Label()}},
            {Opcodes.ASM6, "visitFrame", new Class<?>[]{int.class, int.class, Object[].class, int.class, Object[].class}, new Object[]{0, 0, new Object[0], 0, new Object[0]}},
            {Opcodes.ASM6, "visitIntInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {Opcodes.ASM6, "visitVarInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {Opcodes.ASM6, "visitTypeInsn", new Class<?>[]{int.class, String.class}, new Object[]{0, ""}},
            {Opcodes.ASM6, "visitFieldInsn", new Class<?>[]{int.class, String.class, String.class, String.class}, new Object[]{0, "", "", ""}},
            {Opcodes.ASM4, "visitMethodInsn", new Class<?>[]{int.class, String.class, String.class, String.class}, new Object[]{0, "", "", ""}},
            {Opcodes.ASM6, "visitMethodInsn", new Class<?>[]{int.class, String.class, String.class, String.class, boolean.class}, new Object[]{0, "", "", "", false}},
            {Opcodes.ASM6, "visitInvokeDynamicInsn", new Class<?>[]{String.class, String.class, Handle.class, Object[].class}, new Object[]{"", "", new Handle(0, "", "", "", false), new Object[0]}},
            {Opcodes.ASM6, "visitJumpInsn", new Class<?>[]{int.class, Label.class}, new Object[]{0, new Label()}},
            {Opcodes.ASM6, "visitLdcInsn", new Class<?>[]{Object.class}, new Object[]{new Object()}},
            {Opcodes.ASM6, "visitIincInsn", new Class<?>[]{int.class, int.class}, new Object[]{0, 0}},
            {Opcodes.ASM6, "visitTableSwitchInsn", new Class<?>[]{int.class, int.class, Label.class, Label[].class}, new Object[]{0, 0, new Label(), new Label[0]}},
            {Opcodes.ASM6, "visitLookupSwitchInsn", new Class<?>[]{Label.class, int[].class, Label[].class}, new Object[]{new Label(), new int[0], new Label[0]}},
            {Opcodes.ASM6, "visitMultiANewArrayInsn", new Class<?>[]{String.class, int.class}, new Object[]{"", 0}},
            {Opcodes.ASM6, "visitInsn", new Class<?>[]{int.class}, new Object[]{0}},
    });
}
 
Example #11
Source File: MethodRemapper.java    From JReFrameworker with MIT License 6 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  Object[] remappedBootstrapMethodArguments = new Object[bootstrapMethodArguments.length];
  for (int i = 0; i < bootstrapMethodArguments.length; ++i) {
    remappedBootstrapMethodArguments[i] = remapper.mapValue(bootstrapMethodArguments[i]);
  }
  super.visitInvokeDynamicInsn(
      remapper.mapInvokeDynamicMethodName(name, descriptor),
      remapper.mapMethodDesc(descriptor),
      (Handle) remapper.mapValue(bootstrapMethodHandle),
      remappedBootstrapMethodArguments);
}
 
Example #12
Source File: CheckMethodAdapter.java    From JReFrameworker with MIT License 6 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  checkVisitCodeCalled();
  checkVisitMaxsNotCalled();
  checkMethodIdentifier(version, name, "name");
  checkMethodDescriptor(version, descriptor);
  if (bootstrapMethodHandle.getTag() != Opcodes.H_INVOKESTATIC
      && bootstrapMethodHandle.getTag() != Opcodes.H_NEWINVOKESPECIAL) {
    throw new IllegalArgumentException("invalid handle tag " + bootstrapMethodHandle.getTag());
  }
  for (Object bootstrapMethodArgument : bootstrapMethodArguments) {
    checkLdcConstant(bootstrapMethodArgument);
  }
  super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
  ++insnCount;
}
 
Example #13
Source File: BytecodeTypeInference.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public void visitLdcInsn(Object cst) {
  if (cst instanceof Integer) {
    push(InferredType.INT);
  } else if (cst instanceof Float) {
    push(InferredType.FLOAT);
  } else if (cst instanceof Long) {
    push(InferredType.LONG);
    push(InferredType.TOP);
  } else if (cst instanceof Double) {
    push(InferredType.DOUBLE);
    push(InferredType.TOP);
  } else if (cst instanceof String) {
    pushDescriptor("Ljava/lang/String;");
  } else if (cst instanceof Type) {
    pushDescriptor(((Type) cst).getDescriptor());
  } else if (cst instanceof Handle) {
    pushDescriptor("Ljava/lang/invoke/MethodHandle;");
  } else {
    throw new RuntimeException("Cannot handle constant " + cst + " for LDC instruction");
  }
  super.visitLdcInsn(cst);
}
 
Example #14
Source File: TraceMethodVisitor.java    From Concurnas with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  p.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
  super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
}
 
Example #15
Source File: LambdaTest.java    From Despector with MIT License 5 votes vote down vote up
@Test
public void testLambda() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    if (TestHelper.IS_ECLIPSE) {
        mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;",
                new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
                        "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                new Object[] {Type.getType("()V"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$0", "()V"),
                        Type.getType("()V")});
    } else {
        // javac adds an extra decoration to the lambda method name with the
        // name of the calling method
        mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;",
                new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
                        "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                new Object[] {Type.getType("()V"),
                        new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$test_lambda$0", "()V"),
                        Type.getType("()V")});
    }
    mv.visitVarInsn(ASTORE, 1);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true);
    mv.visitInsn(RETURN);
    Label end = new Label();
    mv.visitLabel(end);
    mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0);
    mv.visitLocalVariable("r", "Ljava/lang/Runnable;", null, l1, end, 1);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "Runnable r = () -> System.out.println(\"Hello World\");\n"
            + "r.run();";
    Assert.assertEquals(good, insn);
}
 
Example #16
Source File: CodeSizeEvaluator.java    From JReFrameworker with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  minSize += 5;
  maxSize += 5;
  super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
}
 
Example #17
Source File: LambdaInfo.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static LambdaInfo create(
    String desiredInternalName,
    String factoryMethodDesc,
    boolean needFactory,
    Handle methodReference,
    Handle bridgeMethod) {
  checkArgument(
      !needFactory || !factoryMethodDesc.startsWith("()"),
      "Shouldn't need a factory method for %s : %s",
      desiredInternalName,
      factoryMethodDesc);
  return new AutoValue_LambdaInfo(
      desiredInternalName, factoryMethodDesc, needFactory, methodReference, bridgeMethod);
}
 
Example #18
Source File: JavaConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a var handle constant for an array.
 *
 * @param typeDescription The array type for which the var handle is resolved.
 * @return A dynamic constant that represents the created var handle constant.
 */
public static JavaConstant ofArrayVarHandle(TypeDescription typeDescription) {
    if (!typeDescription.isArray()) {
        throw new IllegalArgumentException("Not an array type: " + typeDescription);
    }
    return new Dynamic(new ConstantDynamic("arrayVarHandle",
            JavaType.VAR_HANDLE.getTypeStub().getDescriptor(),
            new Handle(Opcodes.H_INVOKESTATIC,
                    CONSTANT_BOOTSTRAPS,
                    "arrayVarHandle",
                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/invoke/VarHandle;",
                    false),
            Type.getType(typeDescription.getDescriptor())), JavaType.VAR_HANDLE.getTypeStub());
}
 
Example #19
Source File: PatchVisitor.java    From Stark with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites a method handle owner to this $starkoverride class and optionally change the method
 * lookup in case the lambda function was an instance method.
 *
 * @param handle the method handle to rewrite
 * @return the new method handle to use.
 */
private Handle rewriteHandleOwner(Handle handle) {

    if (handle.getOwner().equals(visitedClassName)) {
        // if the target lambda captured "this", it is not a static method,
        // therefore, we need to change the method signature.
        MethodNode lambdaMethod =
                getMethodByNameInClass(
                        handle.getName(), handle.getDesc(), classAndInterfaceNode);
        if (lambdaMethod == null) {
            throw new RuntimeException(
                    String.format(
                            "Internal stark error while locating lambda %s"
                                    + "in class %s, please file a bug",
                            handle.getName(), visitedClassName));
        }
        // if the original method was not static, it has now been transformed into a
        // a static method during instrumentation, we should therefore adapt the
        // lambda signature to include the receiver as the first parameter.
        String desc =
                (lambdaMethod.access & Opcodes.ACC_STATIC) == 0
                        ? "(L" + visitedClassName + ";" + handle.getDesc().substring(1)
                        : handle.getDesc();

        return new Handle(
                // no matter what the original invoke was, we now always invoke a static
                // method.
                Opcodes.H_INVOKESTATIC,
                visitedClassName + OVERRIDE_SUFFIX,
                handle.getName(),
                desc,
                false);
    }
    return handle;
}
 
Example #20
Source File: JavaConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a constant {@code null} value of type {@link Object}.
 *
 * @return A dynamically resolved null constant.
 */
public static Dynamic ofNullConstant() {
    return new Dynamic(new ConstantDynamic("nullConstant",
            TypeDescription.OBJECT.getDescriptor(),
            new Handle(Opcodes.H_INVOKESTATIC,
                    CONSTANT_BOOTSTRAPS,
                    "nullConstant",
                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;",
                    false)), TypeDescription.OBJECT);
}
 
Example #21
Source File: AnalyzerAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
  if (this.locals == null) {
    labels = null;
    return;
  }
  pop(descriptor);
  pushDescriptor(descriptor);
  labels = null;
}
 
Example #22
Source File: DalvikStatsTool.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
/**
 * Lambdas/Method Refs for D8 desugaring
 *
 * <p>Stateless (no arguments) - Adds 1 class, 1 field (for instance var) and 2 methods (1
 * constructor + 1 accessor) Stateful (has arguments) - Adds 1 class, 1 field per argument and
 * 3 methods (1 constructor + 1 accessor + 1 bridge) + (Optional) 1 forwarding method for
 * static interface method desugaring
 *
 * <p>we always assume the worst case and for every invoke dynamic in the bytecode, augment
 * the dex references by the max possible fields/methods. At worst, we will end up over
 * estimating slightly, but real world test has shown that the difference is very small to
 * notice.
 */
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
  super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
  registerMethodHandleType(bsm);

  String uid =
      String.valueOf(DalvikMemberReference.of(bsm.getOwner(), name, desc).hashCode());
  createAdditionalFieldsForDesugar(uid + String.valueOf(bsm.hashCode()));
  for (Object arg : bsmArgs) {
    if (arg instanceof Handle) {
      registerMethodHandleType((Handle) arg);
    }
    createAdditionalFieldsForDesugar(uid + String.valueOf(arg.hashCode()));
  }
}
 
Example #23
Source File: LambdaTest.java    From Despector with MIT License 5 votes vote down vote up
@Test
public void testProducer() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    if (TestHelper.IS_ECLIPSE) {
        mv.visitInvokeDynamicInsn("call", "()Ljava/util/concurrent/Callable;",
                new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
                        "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                new Object[] {Type.getType("()Ljava/lang/Object;"),
                        new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$2", "()Ljava/lang/Object;"),
                        Type.getType("()Ljava/lang/Object;")});
    } else {
        // javac adds an extra decoration to the lambda method name with the
        // name of the calling method
        mv.visitInvokeDynamicInsn("call", "()Ljava/util/concurrent/Callable;",
                new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
                        "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                new Object[] {Type.getType("()Ljava/lang/Object;"),
                        new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$test_producer$2", "()Ljava/lang/Object;"),
                        Type.getType("()Ljava/lang/Object;")});
    }
    mv.visitVarInsn(ASTORE, 1);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/concurrent/Callable", "call", "()Ljava/lang/Object;", true);
    mv.visitInsn(POP);
    mv.visitInsn(RETURN);
    Label end = new Label();
    mv.visitLabel(end);
    mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0);
    mv.visitLocalVariable("r", "Ljava/util/concurrent/Callable;", "Ljava/util/concurrent/Callable<Ljava/lang/Object;>;", l1, end, 1);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "java.util.concurrent.Callable<Object> r = () -> null;\n"
            + "r.call();";
    Assert.assertEquals(good, insn);
}
 
Example #24
Source File: MethodNode.java    From JReFrameworker with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  instructions.add(
      new InvokeDynamicInsnNode(
          name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments));
}
 
Example #25
Source File: AnalyzerAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
@Override
public void visitLdcInsn(final Object value) {
  super.visitLdcInsn(value);
  if (this.locals == null) {
    labels = null;
    return;
  }
  if (value instanceof Integer) {
    push(Opcodes.INTEGER);
  } else if (value instanceof Long) {
    push(Opcodes.LONG);
    push(Opcodes.TOP);
  } else if (value instanceof Float) {
    push(Opcodes.FLOAT);
  } else if (value instanceof Double) {
    push(Opcodes.DOUBLE);
    push(Opcodes.TOP);
  } else if (value instanceof String) {
    push("java/lang/String");
  } else if (value instanceof Type) {
    int sort = ((Type) value).getSort();
    if (sort == Type.OBJECT || sort == Type.ARRAY) {
      push("java/lang/Class");
    } else if (sort == Type.METHOD) {
      push("java/lang/invoke/MethodType");
    } else {
      throw new IllegalArgumentException();
    }
  } else if (value instanceof Handle) {
    push("java/lang/invoke/MethodHandle");
  } else if (value instanceof ConstantDynamic) {
    pushDescriptor(((ConstantDynamic) value).getDescriptor());
  } else {
    throw new IllegalArgumentException();
  }
  labels = null;
}
 
Example #26
Source File: MethodDependencyVisitor.java    From AVM with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
    if (name.equals("apply") || name.equals("run")) {
        //TODO: Add tests to confirm assumptions like length >= 2, [1] is the Handle, etc.
        Handle ownerHandle = (Handle) bsmArgs[1];
        methodsCalled.add(new MethodInvocation(ownerHandle.getOwner(),
            ownerHandle.getName() + ownerHandle.getDesc(), Opcodes.INVOKEDYNAMIC));
    } else if (!name.equals("makeConcatWithConstants")) {
        throw new RuntimeException("Unsure how to handle this Invoke Dynamic instruction");
    }
}
 
Example #27
Source File: AnalyzerAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
@Override
public void visitInvokeDynamicInsn(
    final String name,
    final String descriptor,
    final Handle bootstrapMethodHandle,
    final Object... bootstrapMethodArguments) {
  super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
  if (this.locals == null) {
    labels = null;
    return;
  }
  pop(descriptor);
  pushDescriptor(descriptor);
  labels = null;
}
 
Example #28
Source File: Constant.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set this item to an InvokeDynamic item.
 * 
 * @param name
 *          invokedynamic's name.
 * @param desc
 *          invokedynamic's descriptor.
 * @param bsm
 *          bootstrap method.
 * @param bsmArgs
 *          bootstrap method constant arguments.
 */
void set(final String name, final String desc, final Handle bsm, final Object[] bsmArgs) {
  this.type = 'y';
  this.strVal1 = name;
  this.strVal2 = desc;
  this.objVal3 = bsm;
  this.objVals = bsmArgs;

  int hashCode = 'y' + name.hashCode() * desc.hashCode() * bsm.hashCode();
  for (int i = 0; i < bsmArgs.length; i++) {
    hashCode *= bsmArgs[i].hashCode();
  }
  this.hashCode = 0x7FFFFFFF & hashCode;
}
 
Example #29
Source File: NamespaceMapper.java    From AVM with MIT License 5 votes vote down vote up
/**
 * @param methodHandle The pre-transform method handle.
 * @param mapMethodDescriptor True if the underlying descriptor should be mapped or false to leave it unchanged.
 * @return The post-transform method handle.
 */
public Handle mapHandle(Handle methodHandle, boolean mapMethodDescriptor, boolean preserveDebuggability) {
    String methodOwner = methodHandle.getOwner();
    String methodName = methodHandle.getName();
    String methodDescriptor = methodHandle.getDesc();

    String newMethodOwner = mapType(methodOwner, preserveDebuggability);
    String newMethodName = mapMethodName(methodName);
    String newMethodDescriptor = mapMethodDescriptor ? mapDescriptor(methodDescriptor,  preserveDebuggability) : methodDescriptor;
    return new Handle(methodHandle.getTag(), newMethodOwner, newMethodName, newMethodDescriptor, methodHandle.isInterface());
}
 
Example #30
Source File: IndyCompile.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static Handle getHandle(final String name, final String optArgs) {
    return new Handle(
            H_INVOKESTATIC,
            "RT",
            name,
            "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;"
                    + optArgs
                    + ")Ljava/lang/invoke/CallSite;");
}