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

The following examples show how to use org.objectweb.asm.MethodVisitor#visitEnd() . These examples are extracted from open source projects. 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 Project: AVM   File: UserlibCollisionTest.java    License: MIT License 6 votes vote down vote up
private static byte[] getJavaLangPackageClassBytes() {

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

        classWriter.visit(V10, ACC_PUBLIC | ACC_SUPER, "java/lang/MyClass", null, "java/lang/Object", null);

        classWriter.visitSource("MyClass.java", null);
        {
            methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            methodVisitor.visitCode();
            Label label0 = new Label();
            methodVisitor.visitLabel(label0);
            methodVisitor.visitLineNumber(3, label0);
            methodVisitor.visitVarInsn(ALOAD, 0);
            methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            methodVisitor.visitInsn(RETURN);
            methodVisitor.visitMaxs(1, 1);
            methodVisitor.visitEnd();
        }
        classWriter.visitEnd();

        return classWriter.toByteArray();
    }
 
Example 2
static void insertNewInstanceInner (ClassWriter cw, String classNameInternal, String enclosingClassNameInternal) {
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "(Ljava/lang/Object;)Ljava/lang/Object;", null, null);
	mv.visitCode();
	if (enclosingClassNameInternal != null) {
		mv.visitTypeInsn(NEW, classNameInternal);
		mv.visitInsn(DUP);
		mv.visitVarInsn(ALOAD, 1);
		mv.visitTypeInsn(CHECKCAST, enclosingClassNameInternal);
		mv.visitInsn(DUP);
		mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;");
		mv.visitInsn(POP);
		mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "<init>", "(L" + enclosingClassNameInternal + ";)V");
		mv.visitInsn(ARETURN);
		mv.visitMaxs(4, 2);
	} else {
		mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
		mv.visitInsn(DUP);
		mv.visitLdcInsn("Not an inner class.");
		mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V");
		mv.visitInsn(ATHROW);
		mv.visitMaxs(3, 2);
	}
	mv.visitEnd();
}
 
Example 3
Source Project: bazel   File: FieldAccessBridgeEmitter.java    License: Apache License 2.0 6 votes vote down vote up
/** Emits a bridge method for a field with a {@link Opcodes.GETSTATIC} access. */
@Override
public MethodVisitor visitGetStatic(FieldKey fieldKey, ClassVisitor cv) {
  MethodKey bridgeMethodKey = fieldKey.bridgeOfStaticRead();

  MethodVisitor mv =
      cv.visitMethod(
          ACC_SYNTHETIC | ACC_STATIC,
          bridgeMethodKey.name(),
          bridgeMethodKey.descriptor(),
          /* signature= */ null,
          /* exceptions= */ null);

  mv.visitFieldInsn(GETSTATIC, fieldKey.ownerName(), fieldKey.name(), fieldKey.descriptor());
  Type fieldType = fieldKey.getFieldType();
  mv.visitInsn(fieldType.getOpcode(Opcodes.IRETURN));
  int fieldTypeSize = fieldType.getSize();
  mv.visitMaxs(fieldTypeSize, fieldTypeSize);
  mv.visitEnd();
  return mv;
}
 
Example 4
Source Project: StringFog   File: StringFogClassVisitor.java    License: 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
public void generateMethod(MethodVisitor methodVisitor,
                           String abstractClassName,
                           String generatedClassName,
                           int access,
                           String name,
                           String desc,
                           String signature,
                           String[] exceptions) {
  Type returnType = Type.getReturnType(desc);

  methodVisitor.visitLdcInsn(returnType);

  methodVisitor.visitMethodInsn(INVOKESTATIC,
      "com/openpojo/random/RandomFactory",
      "getRandomValue",
      "(Ljava/lang/Class;)Ljava/lang/Object;",
      false);

  String replace = returnType.getInternalName();
  methodVisitor.visitTypeInsn(CHECKCAST, replace);
  methodVisitor.visitInsn(ARETURN);
  methodVisitor.visitMaxs(0, 0);
  methodVisitor.visitEnd();
}
 
Example 6
Source Project: JCTools   File: ProxyChannelFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static void implementProxyInstance(ClassVisitor classVisitor, Class<?> iFace, String generatedName) {
    MethodVisitor methodVisitor = classVisitor.visitMethod(Opcodes.ACC_PUBLIC,
            "proxyInstance",
            methodDescriptor(iFace, iFace),
            null,
            null);
    methodVisitor.visitCode();

    methodVisitor.visitVarInsn(Opcodes.ALOAD, LOCALS_INDEX_THIS);
    methodVisitor.visitInsn(Opcodes.ARETURN);

    methodVisitor.visitMaxs(-1, -1);
    methodVisitor.visitEnd();
    
    implementBridgeMethod(classVisitor, generatedName, "proxyInstance", iFace, iFace);
}
 
Example 7
Source Project: AVM   File: ClassShapeRuleTest.java    License: MIT License 5 votes vote down vote up
private static byte[] createDeepPushClass(String className, int pushCount, boolean isLong) {
    // Note that the setup for the method requires at least 2 stack depth.
    Assert.assertTrue(pushCount >= 2);
    
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V10, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null, "java/lang/Object", new String[0]);
    MethodVisitor method = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", "()[B", null, null);
    Object oneLong = Long.valueOf(1L);
    Object oneInt = Integer.valueOf(1);
    Object value = isLong
            ? oneLong
            : oneInt;
    // visitLdcInsn uses a type check so make sure that we got the type we were expecting (some compilers try to get clever here).
    if (isLong) {
        Assert.assertTrue(value instanceof Long);
    } else {
        Assert.assertTrue(value instanceof Integer);
    }
    method.visitLdcInsn(value);
    int storeOpcode = isLong ? Opcodes.LSTORE : Opcodes.ISTORE;
    method.visitVarInsn(storeOpcode, 0);
    int loadOpcode = isLong ? Opcodes.LLOAD : Opcodes.ILOAD;
    // Reduce the push count by 1 since we have at least one more slot for the return value.
    for (int i = 0; i < (pushCount - 1); ++i) {
        method.visitVarInsn(loadOpcode, 0);
    }
    method.visitInsn(Opcodes.ACONST_NULL);
    method.visitInsn(Opcodes.ARETURN);
    method.visitMaxs(0, 0);
    method.visitEnd();
    writer.visitEnd();
    return writer.toByteArray();
}
 
Example 8
Source Project: pitest   File: CoverageClassVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private void addCoverageProbeField() {

    super.visitField(Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC
            | Opcodes.ACC_SYNTHETIC, CodeCoverageStore.PROBE_FIELD_NAME, "[Z", null,
        null);

    super.visitField(Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC
            | Opcodes.ACC_SYNTHETIC, CodeCoverageStore.PROBE_LENGTH_FIELD_NAME, "I",
        null, this.probeCount + 1);

    //If there is no <clinit>, then generate one that sets the probe field directly
    if (!foundClinit) {
      MethodVisitor clinitMv = this.cv
          .visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
      clinitMv.visitCode();


      pushConstant(clinitMv, this.classId);
      pushConstant(clinitMv, this.probeCount);
      clinitMv
          .visitMethodInsn(Opcodes.INVOKESTATIC, CodeCoverageStore.CLASS_NAME,
              "getOrRegisterClassProbes", "(II)[Z", false);

      clinitMv.visitFieldInsn(Opcodes.PUTSTATIC, className,
          CodeCoverageStore.PROBE_FIELD_NAME, "[Z");
      clinitMv.visitInsn(Opcodes.RETURN);
      clinitMv.visitMaxs(0, 0);
      clinitMv.visitEnd();
    }
  }
 
Example 9
@Test
public void testLoopingFinally() throws Exception {
    String testClassName = "TestClass";
    ClassWriter writer = new ClassWriter(0);
    TryCatchCountingVisitor counter = new TryCatchCountingVisitor(writer);
    LoopingExceptionStrippingVisitor visitor = new LoopingExceptionStrippingVisitor();
    visitor.setDelegate(counter);
    visitor.visit(Opcodes.V10, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, testClassName, null, "java/lang/Object", null);
    
    // Create our labels.
    Label start = new Label();
    Label end = new Label();
    Label handler = new Label();
    String type = null;
    
    // Write a target method.
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_STATIC, "targetMethod", "()V", null, null);
    methodVisitor.visitCode();
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.POP);
    methodVisitor.visitLabel(start);
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitLabel(handler);
    methodVisitor.visitInsn(Opcodes.POP);
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitLabel(end);
    methodVisitor.visitTryCatchBlock(start, end, handler, type);
    methodVisitor.visitMaxs(1, 0);
    methodVisitor.visitEnd();
    
    // Finish.
    visitor.visitEnd();
    
    Assert.assertEquals(0, counter.counter);
}
 
Example 10
Source Project: groovy   File: DgmConverter.java    License: Apache License 2.0 5 votes vote down vote up
private static void createIsValidMethodMethod(CachedMethod method, ClassWriter cw, String className) {
    MethodVisitor mv;
    if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) {
        // 1 param meta method
        mv = cw.visitMethod(ACC_PUBLIC, "isValidMethod", "([Ljava/lang/Class;)Z", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 1);
        Label l0 = new Label();
        mv.visitJumpInsn(IFNULL, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;", false);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(AALOAD);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(AALOAD);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "isAssignableFrom", "(Ljava/lang/Class;)Z", false);
        Label l1 = new Label();
        mv.visitJumpInsn(IFEQ, l1);
        mv.visitLabel(l0);
        mv.visitInsn(ICONST_1);
        Label l2 = new Label();
        mv.visitJumpInsn(GOTO, l2);
        mv.visitLabel(l1);
        mv.visitInsn(ICONST_0);
        mv.visitLabel(l2);
        mv.visitInsn(IRETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}
 
Example 11
@Test
public void testNormalTryCatch() throws Exception {
    String testClassName = "TestClass";
    ClassWriter writer = new ClassWriter(0);
    TryCatchCountingVisitor counter = new TryCatchCountingVisitor(writer);
    LoopingExceptionStrippingVisitor visitor = new LoopingExceptionStrippingVisitor();
    visitor.setDelegate(counter);
    visitor.visit(Opcodes.V10, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, testClassName, null, "java/lang/Object", null);
    
    // Create our labels.
    Label start = new Label();
    Label end = new Label();
    Label handler = new Label();
    String type = null;
    
    // Write a target method.
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_STATIC, "targetMethod", "()V", null, null);
    methodVisitor.visitCode();
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.POP);
    methodVisitor.visitLabel(start);
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.POP);
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitLabel(end);
    methodVisitor.visitLabel(handler);
    methodVisitor.visitInsn(Opcodes.POP);
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitTryCatchBlock(start, end, handler, type);
    methodVisitor.visitMaxs(1, 0);
    methodVisitor.visitEnd();
    
    // Finish.
    visitor.visitEnd();
    
    Assert.assertEquals(1, counter.counter);
}
 
Example 12
Source Project: Concurnas   File: REPLCodeRepointStateHolder.java    License: MIT License 5 votes vote down vote up
public void visitEnd() {
	MethodVisitor mv = this.visitMethod(ACC_PUBLIC + ACC_STATIC, "triggerClinit$", "()V", null, null);
	mv.visitCode();
	Label l0 = new Label();
	mv.visitLabel(l0);
	mv.visitInsn(RETURN);
	mv.visitMaxs(0, 0);
	mv.visitEnd();
	
	super.visitEnd();
}
 
Example 13
Source Project: jadira   File: AsmClassAccess.java    License: Apache License 2.0 4 votes vote down vote up
private static void enhanceForGetValueObject(ClassVisitor cw, String accessClassNm, String clazzNm, Field[] fields) {

		MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getValue", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;", 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, 3);
		mv.visitVarInsn(ILOAD, 3);

		final int maxStack;

		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.visitFieldInsn(GETFIELD, clazzNm, field.getName(), Type.getDescriptor(field.getType()));

				Type fieldType = Type.getType(field.getType());
				switch (fieldType.getSort()) {
				case Type.BOOLEAN:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
					break;
				case Type.BYTE:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
					break;
				case Type.CHAR:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;");
					break;
				case Type.SHORT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
					break;
				case Type.INT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
					break;
				case Type.FLOAT:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
					break;
				case Type.LONG:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
					break;
				case Type.DOUBLE:
					mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
					break;
				}

				mv.visitInsn(ARETURN);
			}

			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, 4);
		mv.visitEnd();
	}
 
Example 14
Source Project: JAADAS   File: ReturnsTest.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void generate(TraceClassVisitor visitor) {
	MethodVisitor mv;

	visitor.visit(V1_1, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/Returns", null,
			"java/lang/Object", null);
	
	visitor.visitSource("Returns.java", null);

	{
		mv = visitor.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(0, 0);
		mv.visitEnd();
	}
	{
		mv = visitor.visitMethod(ACC_PUBLIC, "getIntArray", "()[I", null,
				null);
		mv.visitCode();
		mv.visitInsn(ICONST_4);
		mv.visitIntInsn(NEWARRAY, T_INT);
		mv.visitInsn(ARETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
	}
	{
		mv = visitor.visitMethod(ACC_PUBLIC, "getNull",
				"()Ljava/lang/Object;", null, null);
		mv.visitCode();
		mv.visitInsn(ACONST_NULL);
		mv.visitInsn(ARETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
	}
	{
		mv = visitor.visitMethod(ACC_PUBLIC, "getObjectArray",
				"()[Ljava/lang/Object;", null, null);
		mv.visitCode();
		mv.visitInsn(ICONST_4);
		mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
		mv.visitInsn(ARETURN);
		mv.visitMaxs(0, 0);
		mv.visitEnd();
	}
	visitor.visitEnd();

}
 
Example 15
public static byte[] create(String name, String context) {

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

        cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER,
                name.replace('.', '/'),
                null,
                "javax/ws/rs/core/Application", null);

        int lastDot = name.lastIndexOf('.');
        String simpleName = name.substring(lastDot + 1);
        cw.visitSource(simpleName + ".java", null);

        {
            av0 = cw.visitAnnotation("Ljavax/ws/rs/ApplicationPath;", true);
            av0.visit("value", "/");
            av0.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            Label l0 = new Label();
            mv.visitLabel(l0);
            mv.visitLineNumber(10, l0);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/core/Application", "<init>", "()V", false);
            mv.visitInsn(RETURN);
            Label l1 = new Label();
            mv.visitLabel(l1);
            mv.visitLocalVariable("this",
                    "L" + name.replace('.', '/') + ";",
                    null,
                    l0,
                    l1,
                    0);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        cw.visitEnd();

        return cw.toByteArray();
    }
 
Example 16
static private void insertGetPrimitive (ClassWriter cw, String classNameInternal, ArrayList<Field> fields,
	Type primitiveType) {
	int maxStack = 6;
	final String getterMethodName;
	final String typeNameInternal = primitiveType.getDescriptor();
	final int returnValueInstruction;
	switch (primitiveType.getSort()) {
	case Type.BOOLEAN:
		getterMethodName = "getBoolean";
		returnValueInstruction = IRETURN;
		break;
	case Type.BYTE:
		getterMethodName = "getByte";
		returnValueInstruction = IRETURN;
		break;
	case Type.CHAR:
		getterMethodName = "getChar";
		returnValueInstruction = IRETURN;
		break;
	case Type.SHORT:
		getterMethodName = "getShort";
		returnValueInstruction = IRETURN;
		break;
	case Type.INT:
		getterMethodName = "getInt";
		returnValueInstruction = IRETURN;
		break;
	case Type.FLOAT:
		getterMethodName = "getFloat";
		returnValueInstruction = FRETURN;
		break;
	case Type.LONG:
		getterMethodName = "getLong";
		returnValueInstruction = LRETURN;
		break;
	case Type.DOUBLE:
		getterMethodName = "getDouble";
		returnValueInstruction = DRETURN;
		break;
	default:
		getterMethodName = "get";
		returnValueInstruction = ARETURN;
		break;
	}
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, getterMethodName, "(Ljava/lang/Object;I)" + typeNameInternal, 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++) {
			Field field = fields.get(i);
			if (!labels[i].equals(labelForInvalidTypes)) {
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, classNameInternal);
				mv.visitFieldInsn(GETFIELD, field.getDeclaringClass().getName().replace('.', '/'), field.getName(),
					typeNameInternal);
				mv.visitInsn(returnValueInstruction);
			}
		}
		// 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, 3);
	mv.visitEnd();
}
 
Example 17
public MethodVisitor visitMethod(final int access, final String name, final String descriptor, final String signature, final String[] exceptions) {

		if (!Modifier.isStatic(access) &&  ((access & ACC_ABSTRACT ) != 0 && !descriptor.contains(Fiberizer.FIBER_SUFFIX)) ) {
			// replace with default method pointing to fiberized version
			{
				MethodVisitor methodVisitor = cv.visitMethod(access & ~ACC_ABSTRACT, name, descriptor, signature, null);
				//annotations indicating that this method is normally obligatory to implement! (i.e. normally not default)
				//@DefaultMethodRequiresImplementation
				
				{
					AnnotationVisitor annotationVisitor0 = methodVisitor.visitAnnotation("Lcom/concurnas/bootstrap/runtime/DefaultMethodRequiresImplementation;", true);
					annotationVisitor0.visitEnd();
				}
				methodVisitor.visitCode();
				
				methodVisitor.visitLabel(new Label());
				methodVisitor.visitVarInsn(ALOAD, 0);
				
				//load others
				int locVar=1;
				for(char c : ANFTransform.getPrimOrObj(descriptor)){//reload the stack from vars
					methodVisitor.visitVarInsn(ANFTransform.getLoadOp(c), locVar++);
					if(c == 'D' || c=='J'){
						locVar++;
					}
				}
				
				methodVisitor.visitMethodInsn(INVOKESTATIC, "com/concurnas/bootstrap/runtime/cps/Fiber", "getCurrentFiberWithCreate", "()Lcom/concurnas/bootstrap/runtime/cps/Fiber;", false);
				methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/concurnas/bootstrap/runtime/cps/Fiber", "begin", "()Lcom/concurnas/bootstrap/runtime/cps/Fiber;", false);
				
				methodVisitor.visitMethodInsn(INVOKEINTERFACE, this.name, name, descriptor.replace(")", Fiberizer.FIBER_SUFFIX), true);

				String dd = Type.getMethodType(descriptor).getReturnType().getDescriptor();
				methodVisitor.visitInsn(dd.startsWith("[")?ARETURN:ANFTransform.getReturnOp(descriptor.charAt(descriptor.length()-1)));//return
				
				methodVisitor.visitMaxs(2, 1);
				methodVisitor.visitEnd();
				return null;
			}
		}

		return cv.visitMethod(access, name, descriptor, signature, exceptions);
	}
 
Example 18
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;
}
 
Example 19
Source Project: JCTools   File: ProxyChannelFactory.java    License: Apache License 2.0 4 votes vote down vote up
private static void implementConstructor(ClassVisitor classVisitor,
        Class<? extends ProxyChannelRingBuffer> parentType,
        String generatedName,
        int primitiveMessageSize,
        int referenceMessageSize) {
    MethodVisitor methodVisitor = classVisitor.visitMethod(Opcodes.ACC_PUBLIC,
            "<init>",
            methodDescriptor(void.class,
                    int.class,
                    WaitStrategy.class),
            null,
            null);
    methodVisitor.visitCode();
    
    LocalsHelper locals = LocalsHelper.forInstanceMethod();
    int localIndexOfCapacity = locals.newLocal(int.class);
    int localIndexOfWaitStrategy = locals.newLocal(WaitStrategy.class);

    methodVisitor.visitVarInsn(Opcodes.ALOAD, LOCALS_INDEX_THIS);
    methodVisitor.visitVarInsn(Opcodes.ILOAD, localIndexOfCapacity);
    methodVisitor.visitLdcInsn(primitiveMessageSize);
    methodVisitor.visitLdcInsn(referenceMessageSize);
    
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
            Type.getInternalName(parentType),
            "<init>",
            methodDescriptor(void.class,
                    int.class,
                    int.class,
                    int.class),
            false);
    
    methodVisitor.visitVarInsn(Opcodes.ALOAD, LOCALS_INDEX_THIS);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, localIndexOfWaitStrategy);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedName, "waitStrategy", Type.getDescriptor(WaitStrategy.class));
    
    methodVisitor.visitInsn(Opcodes.RETURN);

    methodVisitor.visitMaxs(-1, -1);
    methodVisitor.visitEnd();
}
 
Example 20
Source Project: groovy   File: ProxyGeneratorAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
    Object key = Arrays.asList(name, desc);
    if (visitedMethods.contains(key)) return null;
    if (Modifier.isPrivate(access) || Modifier.isNative(access) || ((access & ACC_SYNTHETIC) != 0)) {
        // do not generate bytecode for private methods
        return null;
    }
    int accessFlags = access;
    visitedMethods.add(key);
    if ((objectDelegateMethods.contains(name + desc) || delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) && !Modifier.isStatic(access) && !Modifier.isFinal(access)) {
        if (!GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
            if (Modifier.isAbstract(access)) {
                // prevents the proxy from being abstract
                accessFlags -= ACC_ABSTRACT;
            }
            if (delegatedClosures.containsKey(name) || (!"<init>".equals(name) && hasWildcard)) {
                delegatedClosures.put(name, Boolean.TRUE);
                return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
            }
            if (generateDelegateField && objectDelegateMethods.contains(name + desc)) {
                return makeDelegateCall(name, desc, signature, exceptions, accessFlags);
            }
            delegatedClosures.put(name, Boolean.TRUE);
            return makeDelegateToClosureCall(name, desc, signature, exceptions, accessFlags);
        }
    } else if ("getProxyTarget".equals(name) && "()Ljava/lang/Object;".equals(desc)) {
        return createGetProxyTargetMethod(access, name, desc, signature, exceptions);
    } else if ("<init>".equals(name) && (Modifier.isPublic(access) || Modifier.isProtected(access))) {
        return createConstructor(access, name, desc, signature, exceptions);
    } else if (Modifier.isAbstract(access) && !GROOVYOBJECT_METHOD_NAMESS.contains(name)) {
        if (isImplemented(superClass, name, desc)) {
            return null;
        }
        accessFlags -= ACC_ABSTRACT;
        MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
        mv.visitCode();
        Type[] args = Type.getArgumentTypes(desc);
        if (emptyBody) {
            Type returnType = Type.getReturnType(desc);
            if (returnType == Type.VOID_TYPE) {
                mv.visitInsn(RETURN);
            } else {
                int loadIns = getLoadInsn(returnType);
                switch (loadIns) {
                    case ILOAD:
                        mv.visitInsn(ICONST_0);
                        break;
                    case LLOAD:
                        mv.visitInsn(LCONST_0);
                        break;
                    case FLOAD:
                        mv.visitInsn(FCONST_0);
                        break;
                    case DLOAD:
                        mv.visitInsn(DCONST_0);
                        break;
                    default:
                        mv.visitInsn(ACONST_NULL);
                }
                mv.visitInsn(getReturnInsn(returnType));
                mv.visitMaxs(2, registerLen(args) + 1);
            }
        } else {
            // for compatibility with the legacy proxy generator, we should throw an UnsupportedOperationException
            // instead of an AbtractMethodException
            mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
            mv.visitInsn(DUP);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "()V", false);
            mv.visitInsn(ATHROW);
            mv.visitMaxs(2, registerLen(args) + 1);
        }
        mv.visitEnd();
    }
    return null;
}