org.objectweb.asm.Type Java Examples

The following examples show how to use org.objectweb.asm.Type. 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: MethodAttributeAppenderForInstrumentedMethodTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMethodParameterTypeTypeAnnotationClassFileRetention() throws Exception {
    when(annotationValueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    ParameterDescription parameterDescription = mock(ParameterDescription.class);
    when(parameterDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(parameterDescription.getType()).thenReturn(simpleAnnotatedType);
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Explicit<ParameterDescription>(parameterDescription));
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    when(simpleAnnotatedType.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new QuxBaz.Instance()));
    methodAttributeAppender.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitTypeAnnotation(TypeReference.newFormalParameterReference(0).getValue(),
            null,
            Type.getDescriptor(QuxBaz.class),
            false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #2
Source File: DescParser.java    From Recaf with MIT License 6 votes vote down vote up
private static boolean validate(String token) {
	// Void check
	if(token.equals("V"))
		return true;
	// Ensure type is not an array
	Type type = Type.getType(token);
	while(type.getSort() == Type.ARRAY)
		type = type.getElementType();
	// Check for primitives
	if(type.getSort() < Type.ARRAY)
		return true;
	// Verify L...; pattern
	// - getDescriptor doesn't modify the original element type (vs getInternalName)
	String desc = type.getDescriptor();
	return desc.startsWith("L") && desc.endsWith(";");
}
 
Example #3
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void visitAnnotationArrayElement(final Expression expr, final int arrayElementType, final AnnotationVisitor av) {
    switch (arrayElementType) {
        case 1:
            AnnotationNode atAttr = (AnnotationNode) ((AnnotationConstantExpression) expr).getValue();
            AnnotationVisitor av2 = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(atAttr.getClassNode()));
            visitAnnotationAttributes(atAttr, av2);
            av2.visitEnd();
            break;
        case 2:
            av.visit(null, ((ConstantExpression) expr).getValue());
            break;
        case 3:
            av.visit(null, Type.getType(BytecodeHelper.getTypeDescription(expr.getType())));
            break;
        case 4:
            PropertyExpression propExpr = (PropertyExpression) expr;
            av.visitEnum(null,
                    BytecodeHelper.getTypeDescription(propExpr.getObjectExpression().getType()),
                    String.valueOf(((ConstantExpression) propExpr.getProperty()).getValue()));
            break;
    }
}
 
Example #4
Source File: EntityLlamaPatch.java    From seppuku with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This is where minecraft checks if you can steer llamas
 * @param methodNode
 * @param env
 */
@MethodPatch(
        mcpName = "canBeSteered",
        notchName = "cV",
        mcpDesc = "()Z")
public void canBeSteered(MethodNode methodNode, PatchManager.Environment env) {
    //create a list of instructions and add the needed instructions to call our hook function
    final InsnList insnList = new InsnList();
    //call our hook function
    insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "canBeSteeredHook", "()Z", false));
    //add a label to jump to
    final LabelNode jmp = new LabelNode();
    //add if equals and pass the label
    insnList.add(new JumpInsnNode(IFEQ, jmp));
    //add 1 or true
    insnList.add(new InsnNode(ICONST_1));
    //add return so the rest of the function doesn't get called
    insnList.add(new InsnNode(IRETURN));
    //add our label
    insnList.add(jmp);
    //insert the list of instructions at the top of the function
    methodNode.instructions.insert(insnList);
}
 
Example #5
Source File: DescParser.java    From Recaf with MIT License 6 votes vote down vote up
@Override
public DescAST visit(int lineNo, String line) throws ASTParseException {
	try {
		String trim = line.trim();
		// Verify
		if(trim.contains("(")) {
			Type type = Type.getMethodType(trim);
			if(!validate(type.getReturnType().getDescriptor()))
				throw new ASTParseException(lineNo,
						"Invalid method return type " + type.getReturnType().getDescriptor());
			for(Type arg : type.getArgumentTypes())
				if(!validate(arg.getDescriptor()))
					throw new ASTParseException(lineNo,
							"Invalid method arg type " + arg.getDescriptor());
		} else {
			if(!validate(trim))
				throw new ASTParseException(lineNo, "Invalid field descriptor: " + trim);
		}
		// Create AST
		int start = line.indexOf(trim);
		return new DescAST(lineNo, getOffset() + start, trim);
	} catch(Exception ex) {
		throw new ASTParseException(ex, lineNo, "Bad format for descriptor: " + ex.getMessage());
	}
}
 
Example #6
Source File: RuntimeInstrument.java    From dacapobench with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
protected void onMethodEnter() {
	if (done) return;

	overridden = true;
	Label start  = new Label();
	Label normal = new Label();
	super.visitLabel(start);
	super.visitFieldInsn(Opcodes.GETSTATIC, CONFIGURATION, CONFIGURATION_FIELD_NAME, Type.INT_TYPE.getDescriptor());
	super.visitInsn(Opcodes.DUP);
	super.visitJumpInsn(Opcodes.IFEQ, normal);
	super.visitInsn(Opcodes.IRETURN);
	super.visitLabel(normal);
	super.visitInsn(Opcodes.POP);
	Label end = new Label();
	super.visitJumpInsn(Opcodes.GOTO, end);
	super.visitLabel(end);
	super.visitTryCatchBlock(start, normal, end, Type.getType(Throwable.class).getDescriptor());
}
 
Example #7
Source File: ClassScanner.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) {
  super.visit(version, access, name, signature, superName, interfaces);
  if (FingerprintUtil.isSynthetic(access) || Modifier.isPrivate(access))
    return;

  this.className = Type.getObjectType(name).getClassName();
  if (interfaces != null && interfaces.length != 0) {
    for (int i = 0; i < interfaces.length; ++i)
      interfaces[i] = interfaces[i].replace('/', '.');

    this.interfaces = new ArrayList<>();
    for (int i = 0; i < interfaces.length; ++i)
      this.interfaces.add(interfaces[i]);
  }

  this.superClass = superName == null || "java/lang/Object".equals(superName) ? null : Type.getObjectType(superName).getClassName();
}
 
Example #8
Source File: ContinuableMethodVisitor.java    From tascalate-javaflow with Apache License 2.0 6 votes vote down vote up
private void pushDefault(Type type) {
    switch (type.getSort()) {
        case Type.VOID:
            break;
        case Type.DOUBLE:
            mv.visitInsn(DCONST_0);
            break;
        case Type.LONG:
            mv.visitInsn(LCONST_0);
            break;
        case Type.FLOAT:
            mv.visitInsn(FCONST_0);
            break;
        case Type.OBJECT:
        case Type.ARRAY:
            mv.visitInsn(ACONST_NULL);
            break;
        default:
            mv.visitInsn(ICONST_0);
            break;
    }
}
 
Example #9
Source File: MethodAccessorEmitter.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Emits a bridge method for an instance method in a class. For example,
 *
 * <pre><code>
 *   class Foo {
 *     private X execute(A a) {...}
 *
 *     &#047;&#047; Synthetic bridge method for a static method.
 *     static X execute$bridge(Foo foo, A a) {
 *       return foo.execute(a);
 *     }
 *   }
 * </code></pre>
 */
@Override
public MethodVisitor visitClassInstanceMethod(MethodDeclInfo methodDeclInfo, ClassVisitor cv) {
  MethodDeclInfo bridgeMethod = methodDeclInfo.bridgeOfClassInstanceMethod();
  MethodVisitor mv = bridgeMethod.accept(cv);
  mv.visitCode();
  int slotOffset = 0;
  for (Type argType : bridgeMethod.argumentTypes()) {
    mv.visitVarInsn(argType.getOpcode(Opcodes.ILOAD), slotOffset);
    slotOffset += argType.getSize();
  }

  mv.visitMethodInsn(
      Opcodes.INVOKESPECIAL,
      methodDeclInfo.ownerName(),
      methodDeclInfo.name(),
      methodDeclInfo.descriptor(),
      /* isInterface= */ false);
  mv.visitInsn(bridgeMethod.returnType().getOpcode(Opcodes.IRETURN));
  mv.visitMaxs(slotOffset, slotOffset);
  mv.visitEnd();
  return mv;
}
 
Example #10
Source File: SwitchStmt.java    From maple-ir with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void toCode(MethodVisitor visitor, BytecodeFrontend assembler) {
	if (needsSort()) {
		sort();
	}

	int[] cases = new int[targets.size()];
	Label[] labels = new Label[targets.size()];
	int j = 0;
	for (Entry<Integer, BasicBlock> e : targets.entrySet()) {
		cases[j] = e.getKey();
		labels[j++] = assembler.getLabel(e.getValue());
	}

	expression.toCode(visitor, assembler);
	int[] cast = TypeUtils.getPrimitiveCastOpcodes(expression.getType(), Type.INT_TYPE); // widen
	for (int i = 0; i < cast.length; i++) {
		visitor.visitInsn(cast[i]);
	}
	boolean fitsIntoTable = fitsIntoTableSwitch();
	if (fitsIntoTable) {
		visitor.visitTableSwitchInsn(cases[0], cases[cases.length - 1], assembler.getLabel(defaultTarget), labels);
	} else {
		visitor.visitLookupSwitchInsn(assembler.getLabel(defaultTarget), cases, labels);
	}
}
 
Example #11
Source File: MethodAttributeAppenderForInstrumentedMethodOtherTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReceiverTypeTypeAnnotationsClassFileRetention() throws Exception {
    when(methodDescription.getParameters()).thenReturn((ParameterList) new ParameterList.Empty<ParameterDescription>());
    when(methodDescription.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(methodDescription.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    when(methodDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(methodDescription.getReceiverType()).thenReturn(simpleAnnotatedType);
    when(simpleAnnotatedType.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new QuxBaz.Instance()));
    MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER.apply(methodVisitor, methodDescription, annotationValueFilter);
    verify(methodVisitor).visitTypeAnnotation(TypeReference.newTypeReference(TypeReference.METHOD_RECEIVER).getValue(),
            null,
            Type.getDescriptor(AbstractAttributeAppenderTest.QuxBaz.class),
            false);
    verifyNoMoreInteractions(methodVisitor);
    verify(methodDescription).getDeclaredAnnotations();
    verify(methodDescription).getParameters();
    verify(methodDescription).getReturnType();
    verify(methodDescription).getExceptionTypes();
    verify(methodDescription).getTypeVariables();
    verify(methodDescription).getReceiverType();
    verifyNoMoreInteractions(methodDescription);
}
 
Example #12
Source File: AsmTest.java    From caravan with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
  ClassWriter cw = new ClassWriter(0);
  cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "HelloGen", null, "java/lang/Object", null);

  FieldVisitor fv = cw.visitField(1, "_key", Type.getDescriptor(String.class), null, null);
  fv.visitEnd();

  fv = cw.visitField(1, "_value", Type.getDescriptor(InnerClass.class), null, null);
  fv.visitEnd();

  Class<?> clazz = new DynamicClassLoader().defineClass("HelloGen", cw.toByteArray());
  for(Field f : clazz.getDeclaredFields()) {
    System.out.println(f.getName());
  }
}
 
Example #13
Source File: DefaultClassDependenciesAnalyzer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Set<String> getClassDependencies(ClassRelevancyFilter filter, ClassReader reader) {
    Set<String> out = new HashSet<String>();
    char[] charBuffer = new char[reader.getMaxStringLength()];
    for (int i = 1; i < reader.getItemCount(); i++) {
        int itemOffset = reader.getItem(i);
        if (itemOffset > 0 && reader.readByte(itemOffset - 1) == 7) {
            // A CONSTANT_Class entry, read the class descriptor
            String classDescriptor = reader.readUTF8(itemOffset, charBuffer);
            Type type = Type.getObjectType(classDescriptor);
            while (type.getSort() == Type.ARRAY) {
                type = type.getElementType();
            }
            if (type.getSort() != Type.OBJECT) {
                // A primitive type
                continue;
            }
            String name = type.getClassName();
            if (filter.isRelevant(name)) {
                out.add(name);
            }
        }
    }
    return out;
}
 
Example #14
Source File: SourceInterpreter.java    From JReFrameworker with MIT License 6 votes vote down vote up
@Override
public SourceValue unaryOperation(final AbstractInsnNode insn, final SourceValue value) {
  int size;
  switch (insn.getOpcode()) {
    case LNEG:
    case DNEG:
    case I2L:
    case I2D:
    case L2D:
    case F2L:
    case F2D:
    case D2L:
      size = 2;
      break;
    case GETFIELD:
      size = Type.getType(((FieldInsnNode) insn).desc).getSize();
      break;
    default:
      size = 1;
      break;
  }
  return new SourceValue(size, insn);
}
 
Example #15
Source File: IterateSequence.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
@Override
public void generate(CodeEmitter code) {
    Label done = new Label();
    Label next = new Label();
    MethodVisitor mv = code.getMethodVisitor();
    BytecodeExpression tgt = code.evaluateOnce(target);
    code.exec(tgt);
    code.emitInstanceCheck(tgt.getType(), Iterable.class, done);
    AssignableValue item = this.item == null ? code.allocate(valueType) : this.item;
    AssignableValue iterator = code.allocate(Iterator.class);
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Iterable.class), "iterator", Type.getMethodDescriptor(Type.getType(Iterator.class)), true);
    code.exec(iterator.write(code.adapt(Iterator.class)));
    mv.visitLabel(next);
    code.exec(iterator.read());
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Iterator.class), "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), true);
    mv.visitJumpInsn(Opcodes.IFEQ, done);
    code.exec(iterator.read());
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Iterator.class), "next", Type.getMethodDescriptor(Type.getType(Object.class)), true);
    code.cast(valueType, AnyTypeWidget.getInstance()); // , next);   // don't skip nulls
    code.exec(item.write(item.getType()));
    loop.item(code, item.read(), done, next);
    mv.visitJumpInsn(Opcodes.GOTO, next);
    mv.visitLabel(done);
}
 
Example #16
Source File: ConstructorAdapter.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
@Override
public void invokeSpecial(final Class<?> clazz, final List<BytecodeExpression> arguments) {
    final Type[] args = new Type[arguments.size()];
    for (int i = 0; i < arguments.size(); ++i) {
        args[i] = arguments.get(i).getType().getJVMType();
    }
    unit.setSuperInit(
            new BytecodeSequence() {
                @Override
                public void generate(CodeEmitter code) {
                    code.exec(code.getLocal("this"));
                    for (BytecodeExpression e : arguments) {
                        code.exec(e);
                    }
                    MethodVisitor mv = code.getMethodVisitor();
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(clazz), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, args), false);
                }
            }
    );
}
 
Example #17
Source File: AddInitTransformer.java    From cglib with Apache License 2.0 5 votes vote down vote up
public CodeEmitter begin_method(int access, Signature sig, Type[] exceptions) {
    final CodeEmitter emitter = super.begin_method(access, sig, exceptions);
    if (sig.getName().equals(Constants.CONSTRUCTOR_NAME)) {
        return new CodeEmitter(emitter) {
            public void visitInsn(int opcode) {
                if (opcode == Constants.RETURN) {
                    load_this();
                    invoke(info);
                }
                super.visitInsn(opcode);
            }
        };
    }
    return emitter;
}
 
Example #18
Source File: ManagementFactoryHackClassFileTransformer.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
protected void onMethodExit(int opcode) {
    if (opcode != ATHROW) {
        visitMethodInsn(INVOKESTATIC, Type.getType(BytecodeSafe.class).getInternalName(),
                "exitingGetPlatformMBeanServer", "()V", false);
    }
}
 
Example #19
Source File: CheckClassAdapter.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks a given class.
 * 
 * @param cr
 *          a <code>ClassReader</code> that contains bytecode for the
 *          analysis.
 * @param loader
 *          a <code>ClassLoader</code> which will be used to load referenced
 *          classes. This is useful if you are verifiying multiple
 *          interdependent classes.
 * @param dump
 *          true if bytecode should be printed out not only when errors are
 *          found.
 * @param pw
 *          write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader, final boolean dump, final PrintWriter pw) {
  ClassNode cn = new ClassNode();
  cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

  Type syperType = cn.superName == null ? null : Type.getObjectType(cn.superName);
  List<MethodNode> methods = cn.methods;

  List<Type> interfaces = new ArrayList<Type>();
  for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
    interfaces.add(Type.getObjectType(i.next()));
  }

  for (int i = 0; i < methods.size(); ++i) {
    MethodNode method = methods.get(i);
    SimpleVerifier verifier = new SimpleVerifier(Type.getObjectType(cn.name), syperType, interfaces, (cn.access & Opcodes.ACC_INTERFACE) != 0);
    Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
    if (loader != null) {
      verifier.setClassLoader(loader);
    }
    try {
      a.analyze(cn.name, method);
      if (!dump) {
        continue;
      }
    } catch (Exception e) {
      e.printStackTrace(pw);
    }
    printAnalyzerResult(method, a, pw);
  }
  pw.flush();
}
 
Example #20
Source File: EmitUtils.java    From cglib with Apache License 2.0 5 votes vote down vote up
/**
  * @deprecated use {@link #append_string(CodeEmitter, Type, ArrayDelimiters, CustomizerRegistry)} instead
  */
@Deprecated
public static void append_string(final CodeEmitter e,
                                 Type type,
                                 final ArrayDelimiters delims,
                                 final Customizer customizer) {
    append_string(e, type, delims, CustomizerRegistry.singleton(customizer));
}
 
Example #21
Source File: TypeAttributeAppenderForInstrumentedTypeDifferentiatingTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotationByteCodeRetention() throws Exception {
    when(instrumentedType.getTypeVariables()).thenReturn(new TypeList.Generic.Empty());
    when(instrumentedType.getInterfaces()).thenReturn(new TypeList.Generic.Empty());
    when(instrumentedType.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(new QuxBaz.Instance(), new Baz.Instance()));
    new TypeAttributeAppender.ForInstrumentedType.Differentiating(1, 0, 0).apply(classVisitor, instrumentedType, annotationValueFilter);
    verify(classVisitor).visitAnnotation(Type.getDescriptor(Baz.class), true);
    verifyZeroInteractions(classVisitor);
    verify(instrumentedType).getDeclaredAnnotations();
    verify(instrumentedType).getInterfaces();
    verify(instrumentedType).getTypeVariables();
    verifyNoMoreInteractions(instrumentedType);
}
 
Example #22
Source File: FirstOrderHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
private void addTypeAndSupers(Type type) {
  addType(type);

  FirstOrderTypeInfo info = knownTypes.get(type);
  if (info != null) {
    addTypeAndSupers(info.superType);

    for (Type interfaceType : info.interfaceTypes) {
      addTypeAndSupers(interfaceType);
    }
  }
}
 
Example #23
Source File: ClassAndPackageScanner.java    From thorntail with Apache License 2.0 5 votes vote down vote up
void addConstant(final Object constant) {
    if (constant instanceof Type) {
        addType((Type) constant);
    } else if (constant instanceof Handle) {
        Handle handle = (Handle) constant;
        addInternalType(handle.getOwner());
        addMethodTypes(handle.getDesc());
    }
}
 
Example #24
Source File: AsmBackedClassGenerator.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void overrideSetMethod(MetaBeanProperty property, MetaMethod metaMethod) throws Exception {
    if (metaMethod.getParameterTypes().length != 1) {
        throw new IllegalArgumentException("Can only override set methods that take one argument: " + metaMethod.toString());
    } else if (!extensible) {
        return;
    }
    Type paramType = Type.getType(metaMethod.getParameterTypes()[0].getTheClass());
    Type returnType = Type.getType(metaMethod.getReturnType());
    String methodDescriptor = Type.getMethodDescriptor(returnType, new Type[]{paramType});

    // GENERATE public <returnType> <propName>(<type> v) { val = super.<propName>(v); <prop>Set = true; return val; }
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, metaMethod.getName(), methodDescriptor, null, new String[0]);
    methodVisitor.visitCode();

    // GENERATE super.<propName>(v)

    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(paramType.getOpcode(Opcodes.ILOAD), 1);

    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), metaMethod.getName(), methodDescriptor);

    // GENERATE <prop>Set = true

    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitLdcInsn(true);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), String.format("%sSet",
            property.getName()), Type.BOOLEAN_TYPE.getDescriptor());

    // END

    methodVisitor.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();
}
 
Example #25
Source File: Remapper.java    From JReFrameworker with MIT License 5 votes vote down vote up
/**
 * Returns the given value, remapped with this remapper. Possible values are {@link Boolean},
 * {@link Byte}, {@link Short}, {@link Character}, {@link Integer}, {@link Long}, {@link Double},
 * {@link Float}, {@link String}, {@link Type}, {@link Handle}, {@link ConstantDynamic} or arrays
 * of primitive types .
 *
 * @param value an object. Only {@link Type}, {@link Handle} and {@link ConstantDynamic} values
 *     are remapped.
 * @return the given value, remapped with this remapper.
 */
public Object mapValue(final Object value) {
  if (value instanceof Type) {
    return mapType((Type) value);
  }
  if (value instanceof Handle) {
    Handle handle = (Handle) value;
    return new Handle(
        handle.getTag(),
        mapType(handle.getOwner()),
        mapMethodName(handle.getOwner(), handle.getName(), handle.getDesc()),
        handle.getTag() <= Opcodes.H_PUTSTATIC
            ? mapDesc(handle.getDesc())
            : mapMethodDesc(handle.getDesc()),
        handle.isInterface());
  }
  if (value instanceof ConstantDynamic) {
    ConstantDynamic constantDynamic = (ConstantDynamic) value;
    int bootstrapMethodArgumentCount = constantDynamic.getBootstrapMethodArgumentCount();
    Object[] remappedBootstrapMethodArguments = new Object[bootstrapMethodArgumentCount];
    for (int i = 0; i < bootstrapMethodArgumentCount; ++i) {
      remappedBootstrapMethodArguments[i] =
          mapValue(constantDynamic.getBootstrapMethodArgument(i));
    }
    String descriptor = constantDynamic.getDescriptor();
    return new ConstantDynamic(
        mapInvokeDynamicMethodName(constantDynamic.getName(), descriptor),
        mapDesc(descriptor),
        (Handle) mapValue(constantDynamic.getBootstrapMethod()),
        remappedBootstrapMethodArguments);
  }
  return value;
}
 
Example #26
Source File: ASMMethodNodeAdapter.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public boolean hasAnnotation(final Class<?> annotationClass) {
    if (annotationClass == null) {
        return false;
    }

    final String desc = Type.getDescriptor(annotationClass);
    return hasAnnotation(desc, this.methodNode.invisibleAnnotations) || hasAnnotation(desc, this.methodNode.visibleAnnotations);
}
 
Example #27
Source File: ABICompilerClassVisitor.java    From AVM with MIT License 5 votes vote down vote up
private void visitSwap(MethodVisitor mv, Type topType) {
    if (topType.getSize() == 1) {
        mv.visitInsn(SWAP);
    } else {
        mv.visitInsn(DUP2_X1);
        mv.visitInsn(POP2);
    }
}
 
Example #28
Source File: ByteCodeUtils.java    From Aceso with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Types to LocalVariables, assuming they start from variable 0.
 */
static List<LocalVariable> toLocalVariables( List<Type> types) {
    List<LocalVariable> variables = Lists.newArrayList();
    int stack = 0;
    for (int i = 0; i < types.size(); i++) {
        Type type = types.get(i);
        variables.add(new LocalVariable(type, stack));
        stack += type.getSize();
    }
    return variables;
}
 
Example #29
Source File: BuildStackInfoAdapter.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
private static Type getArrayElementType(Type arrayType) {
    int dim = arrayType.getDimensions();
    if(dim < 1) throw new IllegalArgumentException("Not an array type: " + arrayType);
    if(dim > 1) {
        String descr = arrayType.getDescriptor();
        return Type.getType(descr.substring(1));
    }
    return arrayType.getElementType();
}
 
Example #30
Source File: ConstantVisitor.java    From AVM with MIT License 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
    // If this is a clinit, capture it into the MethodNode, for later use.  Otherwise, pass it on as normal.
    MethodVisitor visitor = null;
    if (kClinitName.equals(name)) {
        this.cachedClinit = new MethodNode(access, name, descriptor, signature, exceptions);
        visitor = this.cachedClinit;
    } else {
        visitor = super.visitMethod(access, name, descriptor, signature, exceptions);
    }

    return new MethodVisitor(Opcodes.ASM6, visitor) {
        @Override
        public void visitLdcInsn(Object value) {
            if (value instanceof Type && ((Type) value).getSort() == Type.OBJECT) {
                // class constants
                // This covers both Type.ARRAY and Type.OBJECT; since both cases were visited in UserClassMappingVisitor and renamed
                super.visitLdcInsn(value);
                super.visitMethodInsn(Opcodes.INVOKESTATIC, Helper.RUNTIME_HELPER_NAME, wrapClassMethodName, wrapClassMethodDescriptor, false);
            } else if (value instanceof String) {
                // Note that we are moving all strings to the constantClassName, so look up the constant which has this value.
                String staticFieldForConstant = ConstantVisitor.this.constantToFieldMap.get(value);
                // (we just created this map in StringConstantCollectionVisitor so nothing can be missing).
                RuntimeAssertionError.assertTrue(null != staticFieldForConstant);
                super.visitFieldInsn(Opcodes.GETSTATIC, ConstantVisitor.this.constantClassName, staticFieldForConstant, postRenameStringDescriptor);
            } else {
                // Type of METHOD and Handle are for classes with version 49 and 51 respectively, and should not happen
                // https://asm.ow2.io/javadoc/org/objectweb/asm/MethodVisitor.html#visitLdcInsn-java.lang.Object-
                RuntimeAssertionError.assertTrue(value instanceof Integer || value instanceof Float || value instanceof Long || value instanceof Double);
                super.visitLdcInsn(value);
            }
        }
    };
}