Java Code Examples for org.objectweb.asm.MethodVisitor#visitMaxs()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitMaxs() . 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: ConstructorAssembler.java    From spring-boot-netty with MIT License 6 votes vote down vote up
public static void assembleConstructor(final Type invokerType, final String parentName, final ClassWriter cw) {
    final MethodVisitor ctor = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    final Label cs = createLabel();
    final Label ce = createLabel();

    ctor.visitCode();
    ctor.visitLabel(cs);
    ctor.visitVarInsn(ALOAD, 0);
    ctor.visitMethodInsn(INVOKESPECIAL, parentName, "<init>", "()V", false);
    ctor.visitInsn(RETURN);
    ctor.visitLabel(ce);
    final String cn = invokerType.getDescriptor();
    ctor.visitLocalVariable("this", cn, null, cs, ce, 0);
    ctor.visitEnd();

    ctor.visitMaxs(0, 0);
}
 
Example 2
Source File: TileEntityRegistry.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] generateClass(Class<? extends TileEntity> baseClass, String className, String contentId)
{
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, className, null, Type.getInternalName(baseClass), null);

    // Constructor
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitLdcInsn(contentId);
    mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(baseClass), "<init>", "(Ljava/lang/String;)V", false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();

    return cw.toByteArray();
}
 
Example 3
Source File: IncludingClassVisitor.java    From OpenModsLib with MIT License 6 votes vote down vote up
public void addMethod(ClassVisitor target, Method method) {
	MethodVisitor mv = target.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC,
			method.getName(),
			method.getDescriptor(),
			null, null);

	mv.visitVarInsn(Opcodes.ALOAD, 0);
	visitInterfaceAccess(mv);
	// should have interface reference on stack
	// checkcast just to be safe
	mv.visitTypeInsn(Opcodes.CHECKCAST, intf.getInternalName());

	Type[] args = method.getArgumentTypes();
	for (int i = 0; i < args.length; i++)
		mv.visitVarInsn(args[i].getOpcode(Opcodes.ILOAD), i + 1);

	mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, intf.getInternalName(), method.getName(), method.getDescriptor(), true);
	Type returnType = method.getReturnType();
	mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
	mv.visitMaxs(args.length + 1, args.length + 1);
	mv.visitEnd();
}
 
Example 4
Source File: StringFogClassVisitor.java    From StringFog with Apache License 2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    if (!mIgnoreClass && !isClInitExists && !mStaticFinalFields.isEmpty()) {
        MethodVisitor mv = super.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();
        // Here init static final fields.
        for (ClassStringField field : mStaticFinalFields) {
            if (!canEncrypted(field.value)) {
                continue;
            }
            String originValue = field.value;
            String encryptValue = mStringFogImpl.encrypt(originValue, mKey);
            mMappingPrinter.output(getJavaClassName(), originValue, encryptValue);
            mv.visitLdcInsn(encryptValue);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, mFogClassName, "decrypt", "(Ljava/lang/String;)Ljava/lang/String;", false);
            mv.visitFieldInsn(Opcodes.PUTSTATIC, mClassName, field.name, ClassStringField.STRING_DESC);
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 0);
        mv.visitEnd();
    }
    super.visitEnd();
}
 
Example 5
Source File: EventSubclassTransformer.java    From patchwork-patcher with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds a public marker method that returns true.
 *
 * <p>It appears like so: <pre>
 * public boolean name() {
 *     return true;
 * }
 * </pre></p>
 *
 * @param name The name of the generated method
 */
private void visitMarkerMethod(String name) {
	MethodVisitor isCancelable = super.visitMethod(Opcodes.ACC_PUBLIC, name, BOOLEAN_DESCRIPTOR, null, null);

	if (isCancelable != null) {
		AnnotationVisitor override = isCancelable.visitAnnotation("Ljava/lang/Override;", true);

		if (override != null) {
			override.visitEnd();
		}

		isCancelable.visitInsn(Opcodes.ICONST_1);
		isCancelable.visitInsn(Opcodes.IRETURN);
		isCancelable.visitMaxs(2, 1);
		isCancelable.visitEnd();
	}
}
 
Example 6
Source File: AClassWithBadMethodDump.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public static byte[] dump(String className) throws Exception {

    ClassWriter cw = new ClassWriter(0);
    FieldVisitor fv;
    MethodVisitor mv;
    AnnotationVisitor av0;

    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER,
        className, null, "java/lang/Object",
        null);
    {
      mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
      mv.visitCode();
      mv.visitVarInsn(ALOAD, 0);
      mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
      mv.visitInsn(RETURN);
      mv.visitMaxs(1, 1);
      mv.visitEnd();
    }
    {
      mv = cw.visitMethod(ACC_PRIVATE, "badMethod", "()V", null, null);
      mv.visitCode();
      mv.visitLdcInsn("Should not return on void");
      mv.visitInsn(ARETURN);
      mv.visitMaxs(1, 1);
      mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();
  }
 
Example 7
Source File: ImplHelper.java    From panama-layout-prototype with Eclipse Public License 1.0 5 votes vote down vote up
static void getLayoutImpl(ClassVisitor cw, MethodVisitor mv, String typeName) {
	{
		mv = cw.visitMethod(ACC_PUBLIC, "copyFrom", "(Lcom/ibm/layout/Layout;)V", null, null);
		mv.visitCode();
		mv.visitFieldInsn(GETSTATIC, typeName, "unsafe", "Lsun/misc/Unsafe;");
		mv.visitVarInsn(ALOAD, 1);
		mv.visitTypeInsn(CHECKCAST, typeName);
		mv.visitFieldInsn(GETFIELD, typeName, "location", "Lcom/ibm/layout/Location;");
		mv.visitMethodInsn(INVOKEVIRTUAL, "com/ibm/layout/Location", "getData", "()[B", false);
		mv.visitVarInsn(ALOAD, 1);
		mv.visitTypeInsn(CHECKCAST, typeName);
		mv.visitFieldInsn(GETFIELD, typeName, "location", "Lcom/ibm/layout/Location;");
		mv.visitMethodInsn(INVOKEVIRTUAL, "com/ibm/layout/Location", "getOffset", "()J", false);
		mv.visitVarInsn(ALOAD, 0);
		mv.visitFieldInsn(GETFIELD, typeName, "location", "Lcom/ibm/layout/Location;");
		mv.visitMethodInsn(INVOKEVIRTUAL, "com/ibm/layout/Location", "getData", "()[B", false);
		mv.visitVarInsn(ALOAD, 0);
		mv.visitFieldInsn(GETFIELD, typeName, "location", "Lcom/ibm/layout/Location;");
		mv.visitMethodInsn(INVOKEVIRTUAL, "com/ibm/layout/Location", "getOffset", "()J", false);
		mv.visitVarInsn(ALOAD, 0);
		mv.visitMethodInsn(INVOKEVIRTUAL, typeName, "sizeof", "()J", false);
		mv.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "copyMemory", "(Ljava/lang/Object;JLjava/lang/Object;JJ)V", false);
		mv.visitInsn(RETURN);
		mv.visitMaxs(9, 2);
		mv.visitEnd();
		}
}
 
Example 8
Source File: InterfaceFieldClassGeneratorTest.java    From AVM with MIT License 5 votes vote down vote up
public static byte[] getNestedInterfaceCalledFIELDSLevelTwo() {

        ClassWriter classWriter = new ClassWriter(0);
        FieldVisitor fieldVisitor;
        MethodVisitor methodVisitor;

        classWriter.visit(V10, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "NestedInterfaces$FIELDS$FIELDS", null, "java/lang/Object", null);

        classWriter.visitSource("NestedInterfaces.java", null);

        classWriter.visitInnerClass("NestedInterfaces$FIELDS", "NestedInterfaces", "FIELDS", ACC_STATIC | ACC_ABSTRACT | ACC_INTERFACE);

        classWriter.visitInnerClass("NestedInterfaces$FIELDS$FIELDS", "NestedInterfaces$FIELDS", "FIELDS", ACC_PUBLIC | ACC_STATIC | ACC_ABSTRACT | ACC_INTERFACE);

        {
            fieldVisitor = classWriter.visitField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC, "b", "I", null, null);
            fieldVisitor.visitEnd();
        }
        {
            methodVisitor = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
            methodVisitor.visitCode();
            Label label0 = new Label();
            methodVisitor.visitLabel(label0);
            methodVisitor.visitLineNumber(7, label0);
            methodVisitor.visitTypeInsn(NEW, "java/lang/Object");
            methodVisitor.visitInsn(DUP);
            methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I", false);
            methodVisitor.visitFieldInsn(PUTSTATIC, "NestedInterfaces$FIELDS$FIELDS", "b", "I");
            methodVisitor.visitInsn(RETURN);
            methodVisitor.visitMaxs(2, 0);
            methodVisitor.visitEnd();
        }
        classWriter.visitEnd();

        return classWriter.toByteArray();
    }
 
Example 9
Source File: RegisterObjectHolders.java    From patchwork-patcher with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void accept(MethodVisitor method) {
	for (Map.Entry<String, ObjectHolder> entry : objectHolderEntries) {
		String shimName = entry.getKey();
		ObjectHolder holder = entry.getValue();

		VanillaRegistry registry = VanillaRegistry.get(holder.getDescriptor());

		String registerDescriptor = "(Lnet/minecraft/class_2378;Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)V";

		method.visitFieldInsn(Opcodes.GETSTATIC, "net/patchworkmc/api/registries/ObjectHolderRegistry", "INSTANCE", "Lnet/patchworkmc/api/registries/ObjectHolderRegistry;");

		if (registry == null) {
			if (holder.getDescriptor().startsWith("Lnet/minecraft/class_")) {
				Patchwork.LOGGER.warn("Don't know what registry the minecraft class " + holder.getDescriptor() + " belongs to, falling back to dynamic!");
			}

			method.visitLdcInsn(Type.getObjectType(holder.getDescriptor().substring(1, holder.getDescriptor().length() - 1)));
			registerDescriptor = "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)V";
		} else {
			method.visitFieldInsn(Opcodes.GETSTATIC, REGISTRY, registry.getField(), registry.getFieldDescriptor());
		}

		method.visitLdcInsn(holder.getNamespace());
		method.visitLdcInsn(holder.getName());
		method.visitTypeInsn(Opcodes.NEW, shimName);
		method.visitInsn(Opcodes.DUP);

		method.visitMethodInsn(Opcodes.INVOKESPECIAL, shimName, "<init>", "()V", false);

		method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/patchworkmc/api/registries/ObjectHolderRegistry", "register", registerDescriptor, false);
	}

	method.visitInsn(Opcodes.RETURN);

	method.visitMaxs(6, 0);
	method.visitEnd();
}
 
Example 10
Source File: ConstructorGenerator.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void generate(ClassVisitor cw) {
    CodeEmitter out = new CodeEmitter(unit, arguments, createMethod(cw));
    MethodVisitor mv = out.getMethodVisitor();
    unit.getSuperInit().generate(out);
    code.generate(out);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 11
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a call to the delegate object.
 */
protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {
    MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
    mv.visitVarInsn(ALOAD, 0); // load this
    mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate
    // using InvokerHelper to allow potential intercepted calls
    int size;
    mv.visitLdcInsn(name); // method name
    Type[] args = Type.getArgumentTypes(desc);
    BytecodeHelper.pushConstant(mv, args.length);
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
    size = 6;
    int idx = 1;
    for (int i = 0; i < args.length; i++) {
        Type arg = args[i];
        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i);
        // primitive types must be boxed
        boxPrimitiveType(mv, idx, arg);
        size = Math.max(size, 5 + registerLen(arg));
        idx += registerLen(arg);
        mv.visitInsn(AASTORE); // store value into array
    }
    mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "invokeMethod", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", false);
    unwrapResult(mv, desc);
    mv.visitMaxs(size, registerLen(args) + 1);

    return mv;
}
 
Example 12
Source File: MethodAccessorEmitter.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Emits a synthetic overloaded constructor which delegates the construction logic to the source
 * constructor. For example,
 *
 * <pre><code>
 *   class Foo {
 *     private Foo(A a) {...}
 *
 *     &#047;&#047; Synthetic overloaded constructor
 *     Foo(A a, NestCC var) {
 *       this(a);
 *     }
 *   }
 * </code></pre>
 */
@Override
public MethodVisitor visitClassConstructor(MethodDeclInfo methodDeclInfo, ClassVisitor cv) {
  ClassName nestCompanion = nestDigest.nestCompanion(methodDeclInfo.owner());
  MethodDeclInfo constructorBridge = methodDeclInfo.bridgeOfConstructor(nestCompanion);
  MethodVisitor mv = constructorBridge.accept(cv);
  mv.visitCode();
  mv.visitVarInsn(Opcodes.ALOAD, 0);

  ImmutableList<Type> constructorBridgeArgTypes = constructorBridge.argumentTypes();
  // Exclude last placeholder element loading.
  for (int i = 0, slotOffset = 1; i < constructorBridgeArgTypes.size() - 1; i++) {
    mv.visitVarInsn(constructorBridgeArgTypes.get(i).getOpcode(Opcodes.ILOAD), slotOffset);
    slotOffset += constructorBridgeArgTypes.get(i).getSize();
  }
  mv.visitMethodInsn(
      Opcodes.INVOKESPECIAL,
      methodDeclInfo.ownerName(),
      methodDeclInfo.name(),
      methodDeclInfo.descriptor(),
      /* isInterface= */ false);
  mv.visitInsn(Opcodes.RETURN);
  int slot = 0;
  for (Type bridgeConstructorArgType : constructorBridgeArgTypes) {
    slot += bridgeConstructorArgType.getSize();
  }
  mv.visitMaxs(slot, slot);
  mv.visitEnd();
  return mv;
}
 
Example 13
Source File: OffHeapAugmentor.java    From Concurnas with MIT License 5 votes vote down vote up
private void createConstuctorWithDefaultInit(){
//add initUncreatable and boolean[]
  	
  	{//toBinary
	MethodVisitor mv = super.visitMethod(ACC_PUBLIC, "<init>", "(Lcom/concurnas/bootstrap/runtime/InitUncreatable;[Z)V", null, null);
	mv.visitCode();
	mv.visitLabel(new Label());
	
	mv.visitVarInsn(ALOAD, 0);
	
	if(superclassname.equals("java/lang/Object")){
		mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
	}else if(superclassname.equals("com/concurnas/bootstrap/runtime/cps/CObject")){
		mv.visitMethodInsn(INVOKESPECIAL, "com/concurnas/bootstrap/runtime/cps/CObject", "<init>", "()V");
	}else{
		mv.visitVarInsn(ALOAD, 1);
		mv.visitVarInsn(ALOAD, 2);
		mv.visitMethodInsn(INVOKESPECIAL, superclassname, "<init>", "(Lcom/concurnas/bootstrap/runtime/InitUncreatable;[Z)V");
	}
	
	mv.visitVarInsn(ALOAD, 0);
	mv.visitVarInsn(ALOAD, 1);
	mv.visitVarInsn(ALOAD, 2);
	mv.visitMethodInsn(INVOKESPECIAL, classname, "defaultFieldInit$", "(Lcom/concurnas/bootstrap/runtime/InitUncreatable;[Z)V");
	mv.visitInsn(RETURN);
	mv.visitMaxs(2, 2);
	mv.visitEnd();
}
  	
  }
 
Example 14
Source File: ModuleFood.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
private boolean tryAddFieldGetter(ClassNode classNode, String methodName, String fieldName, String fieldDescriptor)
{
	String methodDescriptor = ASMHelper.toMethodDescriptor(fieldDescriptor);
	if (ASMHelper.findMethodNodeOfClass(classNode, methodName, methodDescriptor) != null)
		return false;

	MethodVisitor mv = classNode.visitMethod(Opcodes.ACC_PUBLIC, methodName, methodDescriptor, null, null);
	mv.visitVarInsn(Opcodes.ALOAD, 0);
	mv.visitFieldInsn(Opcodes.GETFIELD, ASMHelper.toInternalClassName(classNode.name), fieldName, fieldDescriptor);
	mv.visitInsn(Type.getType(fieldDescriptor).getOpcode(Opcodes.IRETURN));
	mv.visitMaxs(0, 0);
	return true;
}
 
Example 15
Source File: JCasClassConversion.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
void genv3_classInit() {
  MethodVisitor mv = cv.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);    
  genv3_commonStaticFieldInit(mv);
  genv3_registerFeatures(mv);
  mv.visitInsn(RETURN);
  mv.visitMaxs(1, 0);
  mv.visitEnd();
}
 
Example 16
Source File: AsmClassAccess.java    From jadira with Apache License 2.0 4 votes vote down vote up
private static void enhanceForPutValueObject(ClassVisitor cw, String accessClassNm, String clazzNm, Field[] fields) {

		int maxStack = 6;
		MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "putValue", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V", null, null);

		mv.visitCode();

		mv.visitVarInsn(ALOAD, 0);
		mv.visitFieldInsn(GETFIELD, accessClassNm, "fieldNames", "[Ljava/lang/String;");
		mv.visitVarInsn(ALOAD, 2);
		mv.visitMethodInsn(INVOKESTATIC, "java/util/Arrays", "binarySearch", "([Ljava/lang/Object;Ljava/lang/Object;)I");
		mv.visitVarInsn(ISTORE, 4);
		mv.visitVarInsn(ILOAD, 4);

		if (fields.length > 0) {
			maxStack = 5;
			Label[] labels = constructLabels(fields);

			Label defaultLabel = new Label();
			mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

			for (int i = 0, n = labels.length; i < n; i++) {
				Field field = fields[i];

				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, clazzNm);

				mv.visitVarInsn(ALOAD, 3);

				Type fieldType = Type.getType(field.getType());
				switch (fieldType.getSort()) {
				case Type.BOOLEAN:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
					break;
				case Type.BYTE:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Byte");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B");
					break;
				case Type.CHAR:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Character");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C");
					break;
				case Type.SHORT:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Short");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S");
					break;
				case Type.INT:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
					break;
				case Type.FLOAT:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Float");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F");
					break;
				case Type.LONG:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Long");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J");
					break;
				case Type.DOUBLE:
					mv.visitTypeInsn(CHECKCAST, "java/lang/Double");
					mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D");
					break;
				case Type.ARRAY:
					mv.visitTypeInsn(CHECKCAST, fieldType.getDescriptor());
					break;
				case Type.OBJECT:
					mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName());
					break;
				}

				mv.visitFieldInsn(PUTFIELD, clazzNm, field.getName(), fieldType.getDescriptor());
				mv.visitInsn(RETURN);
			}

			mv.visitLabel(defaultLabel);
			mv.visitFrame(F_SAME, 0, null, 0, null);
		} else {
			maxStack = 6;
		}
		enhanceForThrowingException(mv, IllegalArgumentException.class, "Field was not found", "Ljava/lang/Object;", ALOAD, 2);
		mv.visitMaxs(maxStack, 5);
		mv.visitEnd();
	}
 
Example 17
Source File: RetroWeaver.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
public void visitEnd() {
    if (isEnum) {
    	cv.visitField(ACC_PRIVATE + ACC_STATIC + ACC_FINAL + ACC_SYNTHETIC,
    			SERIAL_ID_FIELD,
    			SERIAL_ID_SIGNATURE,
    			null, new Long(0L));
    }
    if (!classLiteralCalls.isEmpty()) {
		// generate synthetic fields and class$ method
		for(String fieldName: classLiteralCalls) {
			FieldVisitor fv = visitField(ACC_STATIC + ACC_SYNTHETIC
					+ (isInterface?ACC_PUBLIC:ACC_PRIVATE),
 					fieldName,
 					CLASS_FIELD_DESC,
 					null, null);
			fv.visitEnd();
		}
            if (!isInterface) {
                 // "class$" method
 		MethodVisitor mv = cv.visitMethod(ACC_STATIC+ACC_SYNTHETIC,
                                                        "class$",
                                                        "(Ljava/lang/String;)Ljava/lang/Class;",
                                                        null, null);
	
 		/*mv.visitCode();

                Label beginTry = new Label();
                Label endTry = new Label();
                Label catchBlock = new Label();
                Label finished = new Label();
                mv.visitTryCatchBlock(beginTry, endTry, catchBlock, "java/lang/Exception");
                mv.visitLabel(beginTry);
                mv.visitVarInsn(ALOAD, 0);
                mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");        
                mv.visitLabel(endTry);
                mv.visitJumpInsn(GOTO, finished);
                mv.visitLabel(catchBlock);
                mv.visitInsn(POP);
                mv.visitLabel(finished);

                mv.visitInsn(ARETURN);
 
         mv.visitMaxs(0, 0);
         mv.visitEnd();*/
                mv.visitCode();
                Label l0 = new Label();
                Label l1 = new Label();
                Label l2 = new Label();
                mv.visitTryCatchBlock(l0, l1, l2, "java/lang/ClassNotFoundException");
                mv.visitLabel(l0);
                mv.visitVarInsn(ALOAD, 0);
                mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
                mv.visitLabel(l1);
                mv.visitInsn(ARETURN);
                mv.visitLabel(l2);
                mv.visitVarInsn(ASTORE, 1);
                mv.visitInsn(ACONST_NULL);
                mv.visitInsn(ARETURN);
                /*mv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError");
                mv.visitInsn(DUP);
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "()V");
                mv.visitVarInsn(ALOAD, 1);
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NoClassDefFoundError", "initCause", "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
                mv.visitInsn(ATHROW);*/
                mv.visitMaxs(2, 2);
                mv.visitEnd();

		}                
	}

    if (!stripAttributes) {
    	RetroWeaverAttribute a = new RetroWeaverAttribute(Weaver.getBuildNumber(), originalClassVersion);        
    	cv.visitAttribute(a);
    }

    cv.visitEnd();
}
 
Example 18
Source File: FieldAccess.java    From reflectasm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static private void insertSetPrimitive (ClassWriter cw, String classNameInternal, ArrayList<Field> fields,
	Type primitiveType) {
	int maxStack = 6;
	int maxLocals = 4; // See correction below for LLOAD and DLOAD
	final String setterMethodName;
	final String typeNameInternal = primitiveType.getDescriptor();
	final int loadValueInstruction;
	switch (primitiveType.getSort()) {
	case Type.BOOLEAN:
		setterMethodName = "setBoolean";
		loadValueInstruction = ILOAD;
		break;
	case Type.BYTE:
		setterMethodName = "setByte";
		loadValueInstruction = ILOAD;
		break;
	case Type.CHAR:
		setterMethodName = "setChar";
		loadValueInstruction = ILOAD;
		break;
	case Type.SHORT:
		setterMethodName = "setShort";
		loadValueInstruction = ILOAD;
		break;
	case Type.INT:
		setterMethodName = "setInt";
		loadValueInstruction = ILOAD;
		break;
	case Type.FLOAT:
		setterMethodName = "setFloat";
		loadValueInstruction = FLOAD;
		break;
	case Type.LONG:
		setterMethodName = "setLong";
		loadValueInstruction = LLOAD;
		maxLocals++; // (LLOAD and DLOAD actually load two slots)
		break;
	case Type.DOUBLE:
		setterMethodName = "setDouble";
		loadValueInstruction = DLOAD;
		maxLocals++; // (LLOAD and DLOAD actually load two slots)
		break;
	default:
		setterMethodName = "set";
		loadValueInstruction = ALOAD;
		break;
	}
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, setterMethodName, "(Ljava/lang/Object;I" + typeNameInternal + ")V", null,
		null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		Label labelForInvalidTypes = new Label();
		boolean hasAnyBadTypeLabel = false;
		for (int i = 0, n = labels.length; i < n; i++) {
			if (Type.getType(fields.get(i).getType()).equals(primitiveType))
				labels[i] = new Label();
			else {
				labels[i] = labelForInvalidTypes;
				hasAnyBadTypeLabel = true;
			}
		}
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			if (!labels[i].equals(labelForInvalidTypes)) {
				Field field = fields.get(i);
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, classNameInternal);
				mv.visitVarInsn(loadValueInstruction, 3);
				mv.visitFieldInsn(PUTFIELD, field.getDeclaringClass().getName().replace('.', '/'), field.getName(),
					typeNameInternal);
				mv.visitInsn(RETURN);
			}
		}
		// Rest of fields: different type
		if (hasAnyBadTypeLabel) {
			mv.visitLabel(labelForInvalidTypes);
			mv.visitFrame(F_SAME, 0, null, 0, null);
			insertThrowExceptionForFieldType(mv, primitiveType.getClassName());
		}
		// Default: field not found
		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	mv = insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, maxLocals);
	mv.visitEnd();
}
 
Example 19
Source File: CommonHelpers.java    From HttpSessionReplacer with MIT License 4 votes vote down vote up
static void addLogError(ClassVisitor cw) {
  MethodVisitor mv;
  mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC + ACC_VARARGS, "$$error", "(Ljava/lang/String;[Ljava/lang/Object;)V",
      null, null);
  mv.visitCode();
  Label l0 = new Label();
  mv.visitLabel(l0);
  mv.visitLineNumber(433, l0);
  mv.visitFieldInsn(GETSTATIC, "java/lang/System", "err", "Ljava/io/PrintStream;");
  mv.visitLdcInsn("SessionAgent: [ERROR] %s");
  mv.visitInsn(ICONST_1);
  mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
  mv.visitInsn(DUP);
  mv.visitInsn(ICONST_0);
  mv.visitVarInsn(ALOAD, 0);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "format",
      "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false);
  mv.visitInsn(AASTORE);
  mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "format",
      "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false);
  mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  Label l1 = new Label();
  mv.visitLabel(l1);
  mv.visitLineNumber(434, l1);
  mv.visitVarInsn(ALOAD, 1);
  Label l2 = new Label();
  mv.visitJumpInsn(IFNULL, l2);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitInsn(ARRAYLENGTH);
  mv.visitInsn(ICONST_1);
  mv.visitJumpInsn(IF_ICMPLE, l2);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitInsn(ARRAYLENGTH);
  mv.visitInsn(ICONST_1);
  mv.visitInsn(ISUB);
  mv.visitInsn(AALOAD);
  mv.visitTypeInsn(INSTANCEOF, "java/lang/Throwable");
  mv.visitJumpInsn(IFEQ, l2);
  Label l3 = new Label();
  mv.visitLabel(l3);
  mv.visitLineNumber(435, l3);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitVarInsn(ALOAD, 1);
  mv.visitInsn(ARRAYLENGTH);
  mv.visitInsn(ICONST_1);
  mv.visitInsn(ISUB);
  mv.visitInsn(AALOAD);
  mv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
  mv.visitFieldInsn(GETSTATIC, "java/lang/System", "err", "Ljava/io/PrintStream;");
  mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Throwable", "printStackTrace", "(Ljava/io/PrintStream;)V", false);
  mv.visitLabel(l2);
  mv.visitLineNumber(437, l2);
  mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
  mv.visitInsn(RETURN);
  Label l4 = new Label();
  mv.visitLabel(l4);
  mv.visitLocalVariable("format", "Ljava/lang/String;", null, l0, l4, 0);
  mv.visitLocalVariable("args", "[Ljava/lang/Object;", null, l0, l4, 1);
  mv.visitMaxs(7, 2);
  mv.visitEnd();
}
 
Example 20
Source File: AsmBackedEmptyScriptGenerator.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private <T extends Script> Class<? extends T> generateEmptyScriptClass(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = type.getName() + "_Decorated";
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);
    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(), new String[0]);

    // Constructor

    String constructorDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]);
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    // super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
            constructorDescriptor);

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // run() method

    String runDesciptor = Type.getMethodDescriptor(Type.getType(Object.class), new Type[0]);
    methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "run", runDesciptor, null, new String[0]);
    methodVisitor.visitCode();

    // return null
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);

    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    JavaMethod<ClassLoader, Class> method = JavaReflectionUtil.method(ClassLoader.class, Class.class, "defineClass", String.class, byte[].class, int.class, int.class);
    @SuppressWarnings("unchecked")
    Class<T> clazz = method.invoke(type.getClassLoader(), typeName, bytecode, 0, bytecode.length);
    return clazz;
}