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

The following examples show how to use org.objectweb.asm.MethodVisitor#visitFieldInsn() . 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: FieldAccessBridgeEmitter.java    From bazel with 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 2
Source File: TernaryTests.java    From Despector with MIT License 6 votes vote down vote up
@Test
public void testToField() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZI)V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    Label end = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitIntInsn(ILOAD, 0);
    mv.visitJumpInsn(IFEQ, l1);
    mv.visitIntInsn(BIPUSH, 6);
    mv.visitJumpInsn(GOTO, l2);
    mv.visitLabel(l1);
    mv.visitInsn(ICONST_3);
    mv.visitLabel(l2);
    mv.visitFieldInsn(PUTSTATIC, THIS_TYPE.getInternalName(), "afield", "I");
    mv.visitLabel(end);
    mv.visitInsn(RETURN);
    mv.visitLocalVariable("a", "Z", null, start, end, 0);
    mv.visitLocalVariable("i", "I", null, start, end, 1);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "org.spongepowered.test.decompile.TernaryTests.afield = a ? 6 : 3;";
    Assert.assertEquals(good, insn);
}
 
Example 3
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MethodVisitor createGetProxyTargetMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
    MethodVisitor mv = super.visitMethod(ACC_PUBLIC | ACC_FINAL, name, desc, signature, exceptions);
    mv.visitCode();
    mv.visitIntInsn(ALOAD, 0);
    mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass));
    mv.visitInsn(ARETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
    return null;
}
 
Example 4
Source File: CodeEmitter.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
public void emitStringSwitch(Map<String, Label> labels, Label defaultCase, boolean caseInsensitive) {
    MethodVisitor mv = getMethodVisitor();
    if (caseInsensitive) {
        mv.visitFieldInsn(GETSTATIC, "java/util/Locale", "ENGLISH", "Ljava/util/Locale;");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "toUpperCase", "(Ljava/util/Locale;)Ljava/lang/String;", false);
    }
    mv.visitInsn(DUP);
    AssignableValue tmp = allocate(String.class);
    tmp.write(BaseTypeAdapter.STRING).generate(this);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "hashCode", "()I", false);
    Multimap<Integer, SwitchLabel> keys = ArrayListMultimap.create();
    for (Map.Entry<String, Label> e : labels.entrySet()) {
        String name = e.getKey();
        if (caseInsensitive) {
            name = name.toUpperCase(Locale.ENGLISH);
        }
        keys.put(name.hashCode(), new SwitchLabel(name, e.getValue()));
    }
    List<Integer> codes = Lists.newArrayList(keys.keySet());
    Collections.sort(codes);
    int[] k = new int[codes.size()];
    Label[] kl = new Label[codes.size()];
    for (int i = 0; i < k.length; ++i) {
        k[i] = codes.get(i);
        kl[i] = new Label();
    }
    mv.visitLookupSwitchInsn(defaultCase, k, kl);
    for (int i = 0; i < k.length; ++i) {
        mv.visitLabel(kl[i]);
        for (SwitchLabel switchLabel : keys.get(k[i])) {
            mv.visitLdcInsn(switchLabel.name);
            tmp.read().generate(this);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false);
            mv.visitJumpInsn(IFNE, switchLabel.label);
        }
        mv.visitJumpInsn(GOTO, defaultCase);
    }
}
 
Example 5
Source File: FilterHelpers.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
static void staticInit(String className, MethodVisitor mv) {
  mv.visitLdcInsn("com.amadeus.session.debug");
  mv.visitMethodInsn(INVOKESTATIC, className, "$$getPropertySecured", "(Ljava/lang/String;)Ljava/lang/String;",
      false);
  mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "parseBoolean", "(Ljava/lang/String;)Z", false);
  mv.visitFieldInsn(PUTSTATIC, className, "$$debugMode", "Z");
  mv.visitMethodInsn(INVOKESTATIC, className, "$$isServlet3", "()Z", false);
  mv.visitFieldInsn(PUTSTATIC, className, "$$isServlet3", "Z");
}
 
Example 6
Source File: CacheonixMethodGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generated the byte instructions to write the message to System out stream
 *
 * @param mv      Method Visitor that writes byte instructions
 * @param message message that needs to be written to the out stream
 */
public static void printingToSysout(final MethodVisitor mv,
                                    final String message) {

   mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out",
           "Ljava/io/PrintStream;");
   mv.visitLdcInsn(message);
   mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream",
           "println", "(Ljava/lang/String;)V");
}
 
Example 7
Source File: GetField.java    From OSRS-Deobfuscator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void accept(MethodVisitor visitor)
{
	visitor.visitFieldInsn(this.getType().getCode(),
		field.getClazz().getName(),
		field.getName(),
		field.getType().toString()
	);
}
 
Example 8
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 9
Source File: BytecodeNegateExpression.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void generate(CodeEmitter code) {
    MethodVisitor mv = code.getMethodVisitor();
    Label isNull = new Label();
    TypeWidget mathType = getType().unboxed();

    if (!mathType.isPrimitive()) {
        mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(Maths.class), "INSTANCE", Type.getDescriptor(Maths.class));
    }

    boolean maybeNull = code.cast(mathType, leftExpr.getType(), isNull);
    // compute the result
    if (mathType.isPrimitive()) {
        mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.INEG));
    } else if (mathType.getValueCoreType() == YQLCoreType.ANY) {
        String desc = Type.getMethodDescriptor(getType().getJVMType(),
                Type.getType(Maths.class),
                leftExpr.getType().getJVMType());
        mv.visitInvokeDynamicInsn("dyn:callMethod:negate", desc, Dynamic.H_DYNALIB_BOOTSTRAP);
    } else {
        throw new ProgramCompileException(loc, "Math operation NEGATE is not defined for type %s", mathType.getJVMType());
    }

    if (!getType().isPrimitive() && mathType.isPrimitive()) {
        code.box(mathType);
    }

    if (maybeNull) {
        Label done = new Label();
        mv.visitJumpInsn(Opcodes.GOTO, done);
        mv.visitLabel(isNull);
        mv.visitInsn(Opcodes.ACONST_NULL);
        mv.visitLabel(done);
    }
}
 
Example 10
Source File: ASMConstants.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static void addSystemOut(MethodVisitor mv, String message) {
	mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
	mv.visitLdcInsn(message);
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}
 
Example 11
Source File: PanacheMongoEntityEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
protected void generateAccessorSetField(MethodVisitor mv, EntityField field) {
    mv.visitFieldInsn(Opcodes.PUTFIELD, thisClass.getInternalName(), field.name, field.descriptor);
}
 
Example 12
Source File: ASMConstants.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static void addSystemOut(MethodVisitor mv, String message) {
	mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
	mv.visitLdcInsn(message);
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}
 
Example 13
Source File: ASMConstants.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static void addSystemOut(MethodVisitor mv, String message) {
	mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
	mv.visitLdcInsn(message);
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}
 
Example 14
Source File: ASMConstants.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static void addSystemOut(MethodVisitor mv, String message) {
	mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
	mv.visitLdcInsn(message);
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}
 
Example 15
Source File: ReactivePanacheMongoEntityEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
protected void generateAccessorGetField(MethodVisitor mv, EntityField field) {
    mv.visitFieldInsn(Opcodes.GETFIELD, thisClass.getInternalName(), field.name, field.descriptor);
}
 
Example 16
Source File: AsmUtil.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Invokes the proper LDC Class Constant instructions for the given Jandex Type. This will properly create LDC instructions
 * for array types, class/parameterized classes, and primitive types by loading their equivalent <tt>TYPE</tt>
 * constants in their box types, as well as type variables (using the first bound or Object) and Void.
 * 
 * @param mv The MethodVisitor on which to visit the LDC instructions
 * @param jandexType the Jandex Type whose Class Constant to load.
 */
public static void visitLdc(MethodVisitor mv, Type jandexType) {
    switch (jandexType.kind()) {
        case ARRAY:
            mv.visitLdcInsn(org.objectweb.asm.Type.getType(jandexType.name().toString('/').replace('.', '/')));
            break;
        case CLASS:
        case PARAMETERIZED_TYPE:
            mv.visitLdcInsn(org.objectweb.asm.Type.getType("L" + jandexType.name().toString('/') + ";"));
            break;
        case PRIMITIVE:
            switch (jandexType.asPrimitiveType().primitive()) {
                case BOOLEAN:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
                    break;
                case BYTE:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Byte", "TYPE", "Ljava/lang/Class;");
                    break;
                case CHAR:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Character", "TYPE", "Ljava/lang/Class;");
                    break;
                case DOUBLE:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Double", "TYPE", "Ljava/lang/Class;");
                    break;
                case FLOAT:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Float", "TYPE", "Ljava/lang/Class;");
                    break;
                case INT:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;");
                    break;
                case LONG:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Long", "TYPE", "Ljava/lang/Class;");
                    break;
                case SHORT:
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Short", "TYPE", "Ljava/lang/Class;");
                    break;
                default:
                    throw new IllegalArgumentException("Unknown primitive type: " + jandexType);
            }
            break;
        case TYPE_VARIABLE:
            List<Type> bounds = jandexType.asTypeVariable().bounds();
            if (bounds.isEmpty())
                mv.visitLdcInsn(org.objectweb.asm.Type.getType(Object.class));
            else
                visitLdc(mv, bounds.get(0));
            break;
        case UNRESOLVED_TYPE_VARIABLE:
            mv.visitLdcInsn(org.objectweb.asm.Type.getType(Object.class));
            break;
        case VOID:
            mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Void", "TYPE", "Ljava/lang/Class;");
            break;
        case WILDCARD_TYPE:
            visitLdc(mv, jandexType.asWildcardType().extendsBound());
            break;
        default:
            throw new IllegalArgumentException("Unknown jandex type: " + jandexType);
    }
}
 
Example 17
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected MethodVisitor makeDelegateToClosureCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {
        MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);
//        TraceMethodVisitor tmv = new TraceMethodVisitor(mv);
//        mv = tmv;
        mv.visitCode();
        int stackSize = 0;
        // method body should be:
        //  this.$delegate$closure$methodName.call(new Object[] { method arguments })
        Type[] args = Type.getArgumentTypes(desc);
        int arrayStore = args.length + 1;
        BytecodeHelper.pushConstant(mv, args.length);
        mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); // stack size = 1
        stackSize = 1;
        int idx = 1;
        for (int i = 0; i < args.length; i++) {
            Type arg = args[i];
            mv.visitInsn(DUP); // stack size = 2
            BytecodeHelper.pushConstant(mv, i); // array index, stack size = 3
            // primitive types must be boxed
            boxPrimitiveType(mv, idx, arg);
            idx += registerLen(arg);
            stackSize = Math.max(4, 3 + registerLen(arg));
            mv.visitInsn(AASTORE); // store value into array
        }
        mv.visitVarInsn(ASTORE, arrayStore); // store array
        int arrayIndex = arrayStore;
        mv.visitVarInsn(ALOAD, 0); // load this
        mv.visitFieldInsn(GETFIELD, proxyName, CLOSURES_MAP_FIELD, "Ljava/util/Map;"); // load closure map
        mv.visitLdcInsn(name); // load method name
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
        arrayStore++;
        mv.visitVarInsn(ASTORE, arrayStore);
        // if null, test if wildcard exists
        Label notNull = new Label();
        mv.visitIntInsn(ALOAD, arrayStore);
        mv.visitJumpInsn(IFNONNULL, notNull);
        mv.visitVarInsn(ALOAD, 0); // load this
        mv.visitFieldInsn(GETFIELD, proxyName, CLOSURES_MAP_FIELD, "Ljava/util/Map;"); // load closure map
        mv.visitLdcInsn("*"); // load wildcard
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
        mv.visitVarInsn(ASTORE, arrayStore);
        mv.visitLabel(notNull);
        mv.visitVarInsn(ALOAD, arrayStore);
        mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(this.getClass()), "ensureClosure", "(Ljava/lang/Object;)Lgroovy/lang/Closure;", false);
        mv.visitVarInsn(ALOAD, arrayIndex); // load argument array
        stackSize++;
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Closure", "call", "([Ljava/lang/Object;)Ljava/lang/Object;", false); // call closure
        unwrapResult(mv, desc);
        mv.visitMaxs(stackSize, arrayStore + 1);
        mv.visitEnd();
//        System.out.println("tmv.getText() = " + tmv.getText());
        return null;
    }
 
Example 18
Source File: EventSubscriber.java    From Hyperium with GNU Lesser General Public License v3.0 4 votes vote down vote up
private Class<?> createHandler(Method callback) {
    // ClassName$methodName_EventClass_XXX
    String name = objName + "$" + callback.getName() + "_" + callback.getParameters()[0].getType().getSimpleName() + "_" + (ID++);
    String eventType = Type.getInternalName(callback.getParameterTypes()[0]);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    String desc = name.replace(".", "/");
    String instanceClassName = instance.getClass().getName().replace(".", "/");

    cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER, desc, null, "java/lang/Object", new String[]{ "cc/hyperium/event/EventSubscriber$EventHandler" });

    cw.visitSource(".dynamic", null);
    {
        cw.visitField(ACC_PUBLIC, "instance", "Ljava/lang/Object;", null, null).visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitFieldInsn(PUTFIELD, desc, "instance", "Ljava/lang/Object;");
        mv.visitInsn(RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "handle", "(Ljava/lang/Object;)V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, desc, "instance", "Ljava/lang/Object;");
        mv.visitTypeInsn(CHECKCAST, instanceClassName);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitTypeInsn(CHECKCAST, eventType);
        mv.visitMethodInsn(INVOKEVIRTUAL, instanceClassName, callback.getName(), Type.getMethodDescriptor(callback), false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }
    cw.visitEnd();

    byte[] handlerClassBytes = cw.toByteArray();
    return LOADER.define(name, handlerClassBytes);
}
 
Example 19
Source File: ListenerHelpers.java    From HttpSessionReplacer with MIT License 4 votes vote down vote up
static void staticInit(String className, MethodVisitor mv) {
  mv.visitMethodInsn(INVOKESTATIC, className,
      "$$isServlet3", "()Z", false);
  mv.visitFieldInsn(PUTSTATIC, className, "$$isServlet3",
      "Z");
}
 
Example 20
Source File: ObfMapping.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void visitFieldInsn(MethodVisitor mv, int opcode) {
	mv.visitFieldInsn(opcode, s_owner, s_name, s_desc);
}