List of usage examples for org.objectweb.asm Opcodes PUTFIELD
int PUTFIELD
To view the source code for org.objectweb.asm Opcodes PUTFIELD.
Click Source Link
From source file:org.kantega.notsoserial.CreateBytesIT.java
License:Apache License
private byte[] createTransletBytes() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "com/example/InvokingTranslet", null, Type.getType(AbstractTranslet.class).getInternalName(), new String[] { Type.getType(Serializable.class).getInternalName() }); MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); init.visitCode();//from w w w. j a v a 2 s .c om init.visitVarInsn(Opcodes.ALOAD, 0); init.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getType(AbstractTranslet.class).getInternalName(), "<init>", "()V"); init.visitVarInsn(Opcodes.ALOAD, 0); init.visitIntInsn(Opcodes.BIPUSH, 101); init.visitFieldInsn(Opcodes.PUTFIELD, Type.getType(AbstractTranslet.class).getInternalName(), "transletVersion", "I"); init.visitInsn(Opcodes.RETURN); init.visitMaxs(2, 2); init.visitEnd(); MethodVisitor transformMethod = cw.visitMethod(Opcodes.ACC_PUBLIC, "transform", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(DOM.class), Type.getType(DTMAxisIterator.class) }), null, new String[] { Type.getType(TransletException.class).getInternalName() }); transformMethod.visitCode(); transformMethod.visitInsn(Opcodes.RETURN); transformMethod.visitEnd(); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); mv.visitCode(); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("HMM.."); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitLdcInsn("pwned"); mv.visitLdcInsn("true"); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); mv.visitInsn(Opcodes.POP); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 0); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); }
From source file:org.kohsuke.accmod.impl.Checker.java
License:Open Source License
/** * Inspects a class for the restriction violations. *///from w w w .j a v a2 s . co m public void checkClass(File clazz) throws IOException { FileInputStream in = new FileInputStream(clazz); try { ClassReader cr = new ClassReader(in); cr.accept(new ClassVisitor(Opcodes.ASM5) { private String className; private String methodName, methodDesc; private int line; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.className = name; if (superName != null) getRestrictions(superName).usedAsSuperType(currentLocation, errorListener); if (interfaces != null) { for (String intf : interfaces) getRestrictions(intf).usedAsInterface(currentLocation, errorListener); } } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { this.methodName = name; this.methodDesc = desc; return new MethodVisitor(Opcodes.ASM5) { @Override public void visitLineNumber(int _line, Label start) { line = _line; } public void visitTypeInsn(int opcode, String type) { switch (opcode) { case Opcodes.NEW: getRestrictions(type).instantiated(currentLocation, errorListener); } } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { getRestrictions(owner + '.' + name + desc).invoked(currentLocation, errorListener); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { Restrictions r = getRestrictions(owner + '.' + name); switch (opcode) { case Opcodes.GETSTATIC: case Opcodes.GETFIELD: r.read(currentLocation, errorListener); break; case Opcodes.PUTSTATIC: case Opcodes.PUTFIELD: r.written(currentLocation, errorListener); break; } super.visitFieldInsn(opcode, owner, name, desc); } }; } /** * Constant that represents the current location. */ private final Location currentLocation = new Location() { public String getClassName() { return className.replace('/', '.'); } public String getMethodName() { return methodName; } public String getMethodDescriptor() { return methodDesc; } public int getLineNumber() { return line; } public String toString() { return className + ':' + line; } public ClassLoader getDependencyClassLoader() { return dependencies; } public boolean isInTheSameModuleAs(RestrictedElement e) { // TODO throw new UnsupportedOperationException(); } }; }, SKIP_FRAMES); } finally { in.close(); } }
From source file:org.lambdamatic.analyzer.ast.LambdaExpressionReader.java
License:Open Source License
/** * Reads the bytecode from the given {@link InsnCursor}'s <strong>current position</strong>, until * there is no further instruction to proceed. It is the responsability of the caller to set the * cursor position./*from w ww .j a v a 2s . c o m*/ * * @param insnCursor the instruction cursor used to read the bytecode. * @param expressionStack the expression stack to put on or pop from. * @param localVariables the local variables * @return a {@link List} of {@link Statement} containing the {@link Statement} */ private List<Statement> readStatements(final InsnCursor insnCursor, final Stack<Expression> expressionStack, final List<CapturedArgument> capturedArguments, final LocalVariables localVariables) { final List<Statement> statements = new ArrayList<>(); while (insnCursor.hasCurrent()) { final AbstractInsnNode currentInstruction = insnCursor.getCurrent(); switch (currentInstruction.getType()) { case AbstractInsnNode.VAR_INSN: final VarInsnNode varInstruction = (VarInsnNode) currentInstruction; switch (currentInstruction.getOpcode()) { // load a reference onto the stack from a local variable case Opcodes.ALOAD: case Opcodes.ILOAD: // load an int value from a local variable // Note: The 'var' operand is the index of a local variable // all captured arguments come before the local variable in the method signature, // which means that the local variables table is empty on the first slots which are // "allocated" // for the captured arguments. if (varInstruction.var < capturedArguments.size()) { // if the variable index matches a captured argument // note: not using actual captured argument but rather, use a _reference_ to it. final Object capturedArgumentValue = capturedArguments.get(varInstruction.var).getValue(); final Class<?> capturedArgumentValueType = capturedArgumentValue != null ? capturedArgumentValue.getClass() : Object.class; final CapturedArgumentRef capturedArgumentRef = new CapturedArgumentRef(varInstruction.var, capturedArgumentValueType); expressionStack.add(capturedArgumentRef); } else { // the variable index matches a local variable final LocalVariableNode var = localVariables.load(varInstruction.var); expressionStack.add(new LocalVariable(var.index, var.name, readSignature(var.desc))); } break; case Opcodes.ASTORE: // store a reference into a local variable localVariables.store(varInstruction.var); break; default: throw new AnalyzeException( "Unexpected Variable instruction code: " + varInstruction.getOpcode()); } break; case AbstractInsnNode.LDC_INSN: // let's move this instruction on top of the stack until it // is used as an argument during a method call final LdcInsnNode ldcInsnNode = (LdcInsnNode) currentInstruction; final Expression constant = ExpressionFactory.getExpression(ldcInsnNode.cst); LOGGER.trace("Stacking constant {}", constant); expressionStack.add(constant); break; case AbstractInsnNode.FIELD_INSN: final FieldInsnNode fieldInsnNode = (FieldInsnNode) currentInstruction; switch (fieldInsnNode.getOpcode()) { case Opcodes.GETSTATIC: final Type ownerType = Type.getType(fieldInsnNode.desc); final FieldAccess staticFieldAccess = new FieldAccess(new ClassLiteral(getType(ownerType)), fieldInsnNode.name); expressionStack.add(staticFieldAccess); break; case Opcodes.GETFIELD: final Expression fieldAccessParent = expressionStack.pop(); final FieldAccess fieldAccess = new FieldAccess(fieldAccessParent, fieldInsnNode.name); expressionStack.add(fieldAccess); break; case Opcodes.PUTFIELD: final Expression fieldAssignationValue = expressionStack.pop(); final Expression parentSource = expressionStack.pop(); final FieldAccess source = new FieldAccess(parentSource, fieldInsnNode.name); final Assignment assignmentExpression = new Assignment(source, fieldAssignationValue); statements.add(new ExpressionStatement(assignmentExpression)); break; default: throw new AnalyzeException("Unexpected field instruction type: " + fieldInsnNode.getOpcode()); } break; case AbstractInsnNode.METHOD_INSN: final MethodInsnNode methodInsnNode = (MethodInsnNode) currentInstruction; final Type[] argumentTypes = Type.getArgumentTypes(methodInsnNode.desc); final List<Expression> args = new ArrayList<>(); final List<Class<?>> parameterTypes = new ArrayList<>(); Stream.of(argumentTypes).forEach(argumentType -> { final Expression arg = expressionStack.pop(); final String argumentClassName = argumentType.getClassName(); args.add(castOperand(arg, argumentClassName)); try { parameterTypes.add(ClassUtils.getClass(argumentClassName)); } catch (Exception e) { throw new AnalyzeException("Failed to find class '" + argumentClassName + "'", e); } }); // arguments appear in reverse order in the bytecode Collections.reverse(args); switch (methodInsnNode.getOpcode()) { case Opcodes.INVOKEINTERFACE: case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: // object instantiation if (methodInsnNode.name.equals("<init>")) { final ObjectInstanciation objectVariable = (ObjectInstanciation) expressionStack.pop(); objectVariable.setInitArguments(args); } else { final Expression sourceExpression = expressionStack.pop(); final Method javaMethod = ReflectionUtils.findJavaMethod(sourceExpression.getJavaType(), methodInsnNode.name, parameterTypes); final Class<?> returnType = findReturnType(insnCursor, javaMethod); final MethodInvocation invokedMethod = new MethodInvocation(sourceExpression, javaMethod, returnType, args); expressionStack.add(invokedMethod); } break; case Opcodes.INVOKESTATIC: final Type type = Type.getObjectType(methodInsnNode.owner); try { final Class<?> sourceClass = Class.forName(type.getClassName()); final Method javaMethod = ReflectionUtils.findJavaMethod(sourceClass, methodInsnNode.name, parameterTypes); final Class<?> returnType = findReturnType(insnCursor, javaMethod); final MethodInvocation invokedStaticMethod = new MethodInvocation( new ClassLiteral(sourceClass), javaMethod, returnType, args); expressionStack.add(invokedStaticMethod); } catch (ClassNotFoundException e) { throw new AnalyzeException("Failed to retrieve class for " + methodInsnNode.owner, e); } break; default: throw new AnalyzeException("Unexpected method invocation type: " + methodInsnNode.getOpcode()); } break; case AbstractInsnNode.INVOKE_DYNAMIC_INSN: final InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) currentInstruction; final Handle handle = (Handle) invokeDynamicInsnNode.bsmArgs[1]; final int argNumber = Type.getArgumentTypes(invokeDynamicInsnNode.desc).length; final List<CapturedArgumentRef> lambdaArgs = new ArrayList<>(); for (int i = 0; i < argNumber; i++) { final Expression expr = expressionStack.pop(); if (expr.getExpressionType() != ExpressionType.CAPTURED_ARGUMENT_REF) { throw new AnalyzeException("Unexpected argument type when following InvokeDynamic call: " + expr.getExpressionType()); } lambdaArgs.add((CapturedArgumentRef) expr); // , expr.getValue() } Collections.reverse(lambdaArgs); final EmbeddedSerializedLambdaInfo lambdaInfo = new EmbeddedSerializedLambdaInfo(handle.getOwner(), handle.getName(), handle.getDesc(), lambdaArgs, capturedArguments); final LambdaExpression lambdaExpression = LambdaExpressionAnalyzer.getInstance() .analyzeExpression(lambdaInfo); expressionStack.add(lambdaExpression); break; case AbstractInsnNode.JUMP_INSN: statements.addAll( readJumpInstruction(insnCursor, expressionStack, capturedArguments, localVariables)); return statements; case AbstractInsnNode.INT_INSN: readIntInstruction((IntInsnNode) currentInstruction, expressionStack, localVariables); break; case AbstractInsnNode.INSN: final List<Statement> instructionStatement = readInstruction(insnCursor, expressionStack, capturedArguments, localVariables); statements.addAll(instructionStatement); break; case AbstractInsnNode.TYPE_INSN: readTypeInstruction((TypeInsnNode) currentInstruction, expressionStack, localVariables); break; default: throw new AnalyzeException( "This is embarrassing... We've reached an unexpected instruction operator: " + currentInstruction.getType()); } insnCursor.next(); } return statements; }
From source file:org.mbte.groovypp.compiler.bytecode.BytecodeExpr.java
License:Apache License
public void putField(FieldNode fld, String ownerName, MethodVisitor mv) { mv.visitFieldInsn(Opcodes.PUTFIELD, ownerName, fld.getName(), getTypeDescription(fld.getType())); }
From source file:org.mbte.groovypp.compiler.ClosureUtil.java
License:Apache License
public static void createClosureConstructor(final ClassNode newType, final Parameter[] constrParams, Expression superArgs, CompilerTransformer compiler) { final ClassNode superClass = newType.getSuperClass(); final Parameter[] finalConstrParams; final ArgumentListExpression superCallArgs = new ArgumentListExpression(); if (superArgs != null) { final ArgumentListExpression args = (ArgumentListExpression) superArgs; if (args.getExpressions().size() > 0) { Parameter[] newParams = new Parameter[constrParams.length + args.getExpressions().size()]; System.arraycopy(constrParams, 0, newParams, 0, constrParams.length); for (int i = 0; i != args.getExpressions().size(); ++i) { final Parameter parameter = new Parameter(args.getExpressions().get(i).getType(), "$super$param$" + i); newParams[i + constrParams.length] = parameter; superCallArgs.addExpression(new VariableExpression(parameter)); }/*from w w w . j av a 2 s . c om*/ finalConstrParams = newParams; } else finalConstrParams = constrParams; } else { if (superClass == ClassHelper.CLOSURE_TYPE) { if (constrParams.length > 0) { superCallArgs.addExpression(new VariableExpression(constrParams[0])); superCallArgs.addExpression(new VariableExpression(constrParams[0])); } else if (compiler.methodNode.isStatic() && !compiler.classNode.getName().endsWith("$TraitImpl")) { ClassNode cn = compiler.classNode; superCallArgs.addExpression(new ClassExpression(cn)); superCallArgs.addExpression(new ClassExpression(getOutermostClass(cn))); } else { superCallArgs.addExpression(ConstantExpression.NULL); superCallArgs.addExpression(ConstantExpression.NULL); } } finalConstrParams = constrParams; } ConstructorCallExpression superCall = new ConstructorCallExpression(ClassNode.SUPER, superCallArgs); BytecodeSequence fieldInit = new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { for (int i = 0, k = 1; i != constrParams.length; i++) { mv.visitVarInsn(Opcodes.ALOAD, 0); final ClassNode type = constrParams[i].getType(); if (ClassHelper.isPrimitiveType(type)) { if (type == ClassHelper.long_TYPE) { mv.visitVarInsn(Opcodes.LLOAD, k++); k++; } else if (type == ClassHelper.double_TYPE) { mv.visitVarInsn(Opcodes.DLOAD, k++); k++; } else if (type == ClassHelper.float_TYPE) { mv.visitVarInsn(Opcodes.FLOAD, k++); } else { mv.visitVarInsn(Opcodes.ILOAD, k++); } } else { mv.visitVarInsn(Opcodes.ALOAD, k++); } mv.visitFieldInsn(Opcodes.PUTFIELD, BytecodeHelper.getClassInternalName(newType), constrParams[i].getName(), BytecodeHelper.getTypeDescription(type)); } mv.visitInsn(Opcodes.RETURN); } }); BlockStatement code = new BlockStatement(); code.addStatement(new ExpressionStatement(superCall)); ConstructorNode cn = new ConstructorNode(Opcodes.ACC_PUBLIC, finalConstrParams, ClassNode.EMPTY_ARRAY, code); newType.addConstructor(cn); code.addStatement(fieldInit); CleaningVerifier.getCleaningVerifier().visitClass(newType); compiler.replaceMethodCode(newType, cn); if (newType.getOuterClass() != null && newType.getMethods("methodMissing").isEmpty()) { final ClassNode this0Type = (!compiler.methodNode.isStatic() || compiler.classNode.getName().endsWith("$TraitImpl")) ? newType.getOuterClass() : ClassHelper.CLASS_Type; newType.addMethod("methodMissing", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE, new Parameter[] { new Parameter(ClassHelper.STRING_TYPE, "name"), new Parameter(ClassHelper.OBJECT_TYPE, "args") }, ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() { public void visit(MethodVisitor mv) { mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitFieldInsn(Opcodes.GETFIELD, BytecodeHelper.getClassInternalName(newType), "this$0", BytecodeHelper.getTypeDescription(this0Type)); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper", "invokeMethod", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(Opcodes.ARETURN); } })); } }
From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomChecker.java
License:Apache License
public CollectionTypeWrappedInUnmodifiableIdiomChecker(FieldInsnNode fieldInsnNode, Type typeAssignedToField) { checkArgument(fieldInsnNode.getOpcode() == Opcodes.PUTFIELD, "Checking for unmodifiable wrap idiom requires PUTFIELD instruction"); this.fieldInsnNode = fieldInsnNode; this.typeAssignedToField = typeAssignedToField; }
From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomCheckerTest.java
License:Apache License
@Test public void doesNotAllowCopyingIntoAbritraryType() throws Exception { FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.PUTFIELD, "some/type/Name", "fieldName", "the/field/Type"); CollectionTypeWrappedInUnmodifiableIdiomChecker checker = new CollectionTypeWrappedInUnmodifiableIdiomChecker( fieldInsnNode, getType("the/assigned/Type")); assertThat(checker.checkWrappedInUnmodifiable(), is(UnmodifiableWrapResult.FIELD_TYPE_CANNOT_BE_WRAPPED)); }
From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomCheckerTest.java
License:Apache License
@Test public void findsThatAssignmentDoesNotCallNonWhitelistedMethod() throws Exception { final MethodInsnNode wrappingMethod = new MethodInsnNode(Opcodes.INVOKESTATIC, "some/non/whitelisted/Type", "nonWhitelistedMethod", "()V"); FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.PUTFIELD, "some/type/Name", "fieldName", "java/util/List") { @Override/*from ww w . j av a 2 s. co m*/ public AbstractInsnNode getPrevious() { return wrappingMethod; } }; CollectionTypeWrappedInUnmodifiableIdiomChecker checker = new CollectionTypeWrappedInUnmodifiableIdiomChecker( fieldInsnNode, Type.getType(List.class)); assertThat(checker.checkWrappedInUnmodifiable().invokesWhitelistedWrapperMethod, is(false)); assertThat(checker.checkWrappedInUnmodifiable(), is(DOES_NOT_WRAP_USING_WHITELISTED_METHOD)); }
From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomCheckerTest.java
License:Apache License
@Test public void findsThatAssignmentDoesNotIfCallsNonWhitelistedMethodIfPreviousInstructionWasNotAMethodInvocation() throws Exception { final VarInsnNode varInsn = new VarInsnNode(Opcodes.ASTORE, 2); FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.PUTFIELD, "some/type/Name", "fieldName", "java/util/List") { @Override/*w ww . j ava 2 s .c o m*/ public AbstractInsnNode getPrevious() { return varInsn; } }; CollectionTypeWrappedInUnmodifiableIdiomChecker checker = new CollectionTypeWrappedInUnmodifiableIdiomChecker( fieldInsnNode, Type.getType(List.class)); assertThat(checker.checkWrappedInUnmodifiable().invokesWhitelistedWrapperMethod, is(false)); assertThat(checker.checkWrappedInUnmodifiable(), is(DOES_NOT_WRAP_USING_WHITELISTED_METHOD)); }
From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomCheckerTest.java
License:Apache License
@Test public void findsThatAssignmentIsNotSafelyCopiedIfCallToUnmodifiableMethodIsNotPrecededByMethodInstruction() throws Exception { final VarInsnNode varInsn = new VarInsnNode(Opcodes.ASTORE, 2); final MethodInsnNode wrappingMethod = new MethodInsnNode(Opcodes.INVOKESTATIC, "java/util/Collections", "unmodifiableList", "") { @Override/* www . j a va2 s . com*/ public AbstractInsnNode getPrevious() { return varInsn; } }; FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.PUTFIELD, "some/type/Name", "fieldName", "java/util/List") { @Override public AbstractInsnNode getPrevious() { return wrappingMethod; } }; CollectionTypeWrappedInUnmodifiableIdiomChecker checker = new CollectionTypeWrappedInUnmodifiableIdiomChecker( fieldInsnNode, Type.getType(List.class)); assertThat(checker.checkWrappedInUnmodifiable().safelyCopiesBeforeWrapping, is(false)); assertThat(checker.checkWrappedInUnmodifiable(), is(WRAPS_BUT_DOES_NOT_COPY)); }