List of usage examples for org.objectweb.asm Opcodes GETFIELD
int GETFIELD
To view the source code for org.objectweb.asm Opcodes GETFIELD.
Click Source Link
From source file:org.evosuite.instrumentation.testability.transformer.BooleanDefinitionTransformer.java
License:Open Source License
@Override protected AbstractInsnNode transformFieldInsnNode(MethodNode mn, FieldInsnNode fieldNode) { // This handles the else branch for field assignments if (DescriptorMapping.getInstance().isTransformedOrBooleanField( this.booleanTestabilityTransformation.className, fieldNode.name, fieldNode.desc)) { if (fieldNode.getNext() instanceof FieldInsnNode) { FieldInsnNode other = (FieldInsnNode) fieldNode.getNext(); if (fieldNode.owner.equals(other.owner) && fieldNode.name.equals(other.name) && fieldNode.desc.equals(other.desc)) { if (fieldNode.getOpcode() == Opcodes.GETFIELD && other.getOpcode() == Opcodes.PUTFIELD) { this.booleanTestabilityTransformation.insertGetBefore(other, mn.instructions); } else if (fieldNode.getOpcode() == Opcodes.GETSTATIC && other.getOpcode() == Opcodes.PUTSTATIC) { this.booleanTestabilityTransformation.insertGetBefore(other, mn.instructions); }//from w w w .j av a2 s. co m } } } return fieldNode; }
From source file:org.evosuite.instrumentation.testability.transformer.ImplicitElseTransformer.java
License:Open Source License
private void handleDependency(ControlDependency dependency, ControlDependenceGraph cdg, MethodNode mn, FieldInsnNode varNode, BytecodeInstruction parentLevel) { if (addedNodes.contains(dependency)) return;//from w w w .j av a2 s. co m // Get the basic blocks reachable if the dependency would evaluate different Set<BasicBlock> blocks = cdg.getAlternativeBlocks(dependency); addedNodes.add(dependency); Set<ControlDependency> dependencies = dependency.getBranch().getInstruction().getControlDependencies(); //if (dependencies.size() == 1) { // ControlDependency dep = dependencies.iterator().next(); for (ControlDependency dep : dependencies) { if (!addedNodes.contains(dep) && dep != dependency) handleDependency(dep, cdg, mn, varNode, dependency.getBranch().getInstruction()); } // TODO: Need to check that there is an assignment in every alternative path through CDG boolean hasAssignment = false; for (BasicBlock block : blocks) { // If this block also assigns a value to the same variable for (BytecodeInstruction instruction : block) { if (instruction.getASMNode().getOpcode() == Opcodes.PUTFIELD || instruction.getASMNode().getOpcode() == Opcodes.PUTSTATIC) { FieldInsnNode otherFieldNode = (FieldInsnNode) instruction.getASMNode(); FieldInsnNode thisFieldNode = varNode; if (otherFieldNode.owner.equals(thisFieldNode.owner) && otherFieldNode.name.equals(thisFieldNode.name)) { hasAssignment = true; break; } } } if (hasAssignment) { break; } } // The Flag assignment is is the dependency evaluates to the given value // We thus need to insert the tautoligical assignment either directly after the IF (if the value is true) // or before the jump target (if the value is false) if (!hasAssignment) { if (dependency.getBranch().getInstruction().isSwitch()) { BooleanTestabilityTransformation.logger.warn("Don't know how to handle Switches yet"); return; } TransformationStatistics.transformedImplicitElse(); JumpInsnNode jumpNode = (JumpInsnNode) dependency.getBranch().getInstruction().getASMNode(); FieldInsnNode newLoad = new FieldInsnNode( varNode.getOpcode() == Opcodes.PUTSTATIC ? Opcodes.GETSTATIC : Opcodes.GETFIELD, varNode.owner, varNode.name, varNode.desc); FieldInsnNode newStore = new FieldInsnNode(varNode.getOpcode(), varNode.owner, varNode.name, varNode.desc); AbstractInsnNode newOwnerLoad1 = null; AbstractInsnNode newOwnerLoad2 = null; if (varNode.getOpcode() == Opcodes.PUTFIELD) { // Need to copy the bloody owner // Check for VarInsn //if (varNode.getPrevious().getOpcode() == Opcodes.ALOAD) { newOwnerLoad1 = new VarInsnNode(Opcodes.ALOAD, 0); newOwnerLoad2 = new VarInsnNode(Opcodes.ALOAD, 0); /* } else { // Else use helper function // Insert DUP and logger.info("Wargh"); System.exit(0); fieldOwnerId++; InsnNode dupNode = new InsnNode(Opcodes.DUP); mn.instructions.insertBefore(varNode, new LdcInsnNode( fieldOwnerId)); mn.instructions.insertBefore(varNode, dupNode); registerInstruction(mn, varNode, dupNode); MethodInsnNode storeOwner = new MethodInsnNode( Opcodes.INVOKESTATIC, "org/evosuite/instrumentation/BooleanHelper", "setFieldOwner", "(ILjava/lang/Object;)V"); mn.instructions.insertBefore(varNode, storeOwner); registerInstruction(mn, varNode, storeOwner); newOwnerLoad1 = new MethodInsnNode(Opcodes.INVOKESTATIC, "org/evosuite/instrumentation/BooleanHelper", "getFieldOwner", "(I)Ljava/lang/Object;"); newOwnerLoad2 = new MethodInsnNode(Opcodes.INVOKESTATIC, "org/evosuite/instrumentation/BooleanHelper", "getFieldOwner", "(I)Ljava/lang/Object;"); } */ } if (dependency.getBranchExpressionValue()) { BooleanTestabilityTransformation.logger.info("Inserting after if"); // Insert directly after if mn.instructions.insert(jumpNode, newStore); mn.instructions.insert(jumpNode, newLoad); if (newOwnerLoad1 != null) { mn.instructions.insert(jumpNode, newOwnerLoad1); registerInstruction(mn, varNode, newOwnerLoad1); } if (newOwnerLoad2 != null) { mn.instructions.insert(jumpNode, newOwnerLoad2); registerInstruction(mn, varNode, newOwnerLoad2); } registerInstruction(mn, varNode, newStore); registerInstruction(mn, varNode, newLoad); } else { BooleanTestabilityTransformation.logger.info("Inserting as jump target"); // Insert as jump target LabelNode target = jumpNode.label; LabelNode newTarget = new LabelNode(new Label()); registerInstruction(mn, target, newStore); registerInstruction(mn, target, newLoad); InsnList assignment = new InsnList(); assignment.add(new JumpInsnNode(Opcodes.GOTO, target)); assignment.add(newTarget); if (newOwnerLoad1 != null) { assignment.add(newOwnerLoad1); registerInstruction(mn, target, newOwnerLoad1); } if (newOwnerLoad2 != null) { assignment.add(newOwnerLoad2); registerInstruction(mn, target, newOwnerLoad2); } assignment.add(newLoad); assignment.add(newStore); jumpNode.label = newTarget; mn.instructions.insertBefore(target, assignment); } addedInsns.add(newStore); addedInsns.add(newLoad); } }
From source file:org.evosuite.testcarver.instrument.Instrumenter.java
License:Open Source License
private void instrumentGETXXXFieldAccesses(final ClassNode cn, final String internalClassName, final MethodNode methodNode) { final InsnList instructions = methodNode.instructions; AbstractInsnNode ins = null;// w ww . j a v a2 s . c o m FieldInsnNode fieldIns = null; for (int i = 0; i < instructions.size(); i++) { ins = instructions.get(i); if (ins instanceof FieldInsnNode) { fieldIns = (FieldInsnNode) ins; /* * Is field referencing outermost instance? if yes, ignore it * http://tns-www.lcs.mit.edu/manuals/java-1.1.1/guide/innerclasses/spec/innerclasses.doc10.html */ if (fieldIns.name.endsWith("$0")) { continue; } final int opcode = ins.getOpcode(); if (opcode == Opcodes.GETFIELD || opcode == Opcodes.GETSTATIC) { final InsnList il = new InsnList(); if (opcode == Opcodes.GETFIELD) { Type fieldType = Type.getType(fieldIns.desc); if (fieldType.getSize() == 1) { instructions.insertBefore(fieldIns, new InsnNode(Opcodes.DUP)); il.add(new InsnNode(Opcodes.SWAP)); } else if (fieldType.getSize() == 2) { instructions.insertBefore(fieldIns, new InsnNode(Opcodes.DUP)); // v // GETFIELD // v, w il.add(new InsnNode(Opcodes.DUP2_X1)); // w, v, w il.add(new InsnNode(Opcodes.POP2)); // w, v // -> Call // w } } else il.add(new InsnNode(Opcodes.ACONST_NULL)); il.add(new LdcInsnNode(this.captureId)); il.add(new LdcInsnNode(fieldIns.owner)); il.add(new LdcInsnNode(fieldIns.name)); il.add(new LdcInsnNode(fieldIns.desc)); il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, PackageInfo.getNameWithSlash(org.evosuite.testcarver.capture.FieldRegistry.class), "notifyReadAccess", "(Ljava/lang/Object;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")); i += il.size(); instructions.insert(fieldIns, il); this.captureId++; } } } }
From source file:org.formulacompiler.compiler.internal.bytecode.ArrayAccessorForConstDataCompiler.java
License:Open Source License
@Override protected void compileBody() throws CompilerException { final GeneratorAdapter mv = mv(); final ArrayDescriptor dim = this.arrayNode.arrayDescriptor(); final int n = dim.numberOfElements(); final DataType eltDataType = this.arrayNode.getDataType(); final TypeCompiler eltCompiler = section().engineCompiler().typeCompiler(eltDataType); final Type eltType = eltCompiler.type(); // private double[] xy; final FieldVisitor fv = cw().visitField(Opcodes.ACC_PRIVATE, methodName(), arrayDescriptor(), null, null); fv.visitEnd();/* www .j a v a2 s .com*/ // if (this.xy == null) { final Label skipInit = mv.newLabel(); mv.loadThis(); mv.visitFieldInsn(Opcodes.GETFIELD, section().classInternalName(), methodName(), arrayDescriptor()); mv.ifNonNull(skipInit); // ... new double[ n ] mv.loadThis(); mv.push(n); mv.newArray(eltType); // ... { c1, c2, ... } int i = 0; for (ExpressionNode elt : this.arrayNode.arguments()) { if (elt instanceof ExpressionNodeForConstantValue) { mv.visitInsn(Opcodes.DUP); mv.push(i); final ExpressionNodeForConstantValue constElt = (ExpressionNodeForConstantValue) elt; eltCompiler.compileConst(mv, constElt.value()); mv.arrayStore(eltType); } i++; } // this.xy *=* new double[] { ... } mv.visitFieldInsn(Opcodes.PUTFIELD, section().classInternalName(), methodName(), arrayDescriptor()); // } // return this.xy; mv.mark(skipInit); mv.loadThis(); mv.visitFieldInsn(Opcodes.GETFIELD, section().classInternalName(), methodName(), arrayDescriptor()); mv.visitInsn(Opcodes.ARETURN); }
From source file:org.formulacompiler.compiler.internal.bytecode.ArrayAccessorForFullDataCompiler.java
License:Open Source License
@Override protected void compileBody() throws CompilerException { final GeneratorAdapter mv = mv(); final DataType eltDataType = this.arrayNode.getDataType(); final ExpressionCompiler eltCompiler = expressionCompiler(eltDataType); final Type eltType = eltCompiler.type(); final String initName = methodName() + "$init"; final String initDesc = "Z"; // private boolean xy$init; final FieldVisitor fv = cw().visitField(Opcodes.ACC_PRIVATE, initName, initDesc, null, null); fv.visitEnd();/*www . j a v a 2 s. c o m*/ // if (!this.xy$init) { final Label skipInit = mv.newLabel(); mv.loadThis(); mv.visitFieldInsn(Opcodes.GETFIELD, section().classInternalName(), initName, initDesc); mv.visitJumpInsn(Opcodes.IFNE, skipInit); // this.xy$init = true; mv.loadThis(); mv.push(true); mv.visitFieldInsn(Opcodes.PUTFIELD, section().classInternalName(), initName, initDesc); // this.xy = { ?, c1, c2, ... } mv.loadThis(); section().getArrayAccessorForConstDataOnly(this.arrayNode).compileCall(mv); int i = 0; for (ExpressionNode elt : this.arrayNode.arguments()) { if (!(elt instanceof ExpressionNodeForConstantValue)) { mv.visitInsn(Opcodes.DUP); mv.visitIntInsn(Opcodes.BIPUSH, i); eltCompiler.compile(elt); mv.arrayStore(eltType); } i++; } // return this.xy; mv.visitInsn(Opcodes.ARETURN); // } else // return this.xy; mv.mark(skipInit); mv.loadThis(); section().getArrayAccessorForConstDataOnly(this.arrayNode).compileCall(mv); mv.visitInsn(Opcodes.ARETURN); if (section().hasReset()) { final GeneratorAdapter reset = section().resetter(); // this.xy$init = false; reset.loadThis(); reset.push(false); reset.visitFieldInsn(Opcodes.PUTFIELD, section().classInternalName(), initName, initDesc); } }
From source file:org.gradle.api.internal.model.DefaultObjectFactory.java
License:Apache License
private ClassGeneratingLoader loaderFor(Class<?> publicClass) { ///*from w w w .j a v a 2s .co m*/ // Generate implementation class // FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector( "Named implementation class", ModelType.of(publicClass)); visitFields(publicClass, problemCollector); if (problemCollector.hasProblems()) { throw new GradleException(problemCollector.format()); } AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl"); Type implementationType = generator.getGeneratedType(); ClassWriter visitor = generator.getVisitor(); Type publicType = Type.getType(publicClass); Type superClass; String[] interfaces; if (publicClass.isInterface()) { superClass = OBJECT; interfaces = new String[] { publicType.getInternalName() }; } else { superClass = publicType; interfaces = EMPTY_STRINGS; } visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null, superClass.getInternalName(), interfaces); // // Add name field // visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null); // // Add constructor // MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call this.super() methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false); // Set this.name = param1 methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); // Done methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add `getName()` // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // return this.name methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add `toString()` // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // return this.name methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); visitor.visitEnd(); generator.define(); // // Generate factory class // generator = new AsmClassGenerator(publicClass, "$Factory"); visitor = generator.getVisitor(); visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null, Type.getType(ClassGeneratingLoader.class).getInternalName(), EMPTY_STRINGS); // // Add constructor // methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call this.super() methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getType(ClassGeneratingLoader.class).getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false); // Done methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add factory method // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", Type.getMethodDescriptor(OBJECT, STRING), null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call return new <implClass>(param1) methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName()); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING, false); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); visitor.visitEnd(); Class<Object> factoryClass = generator.define(); try { return (ClassGeneratingLoader) (factoryClass.newInstance()); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } }
From source file:org.gradle.api.internal.model.NamedObjectInstantiator.java
License:Apache License
private ClassGeneratingLoader loaderFor(Class<?> publicClass) { ////from w w w . j a v a 2 s . c o m // Generate implementation class // FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector( "Named implementation class", ModelType.of(publicClass)); visitFields(publicClass, problemCollector); if (problemCollector.hasProblems()) { throw new GradleException(problemCollector.format()); } AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl"); Type implementationType = generator.getGeneratedType(); ClassWriter visitor = generator.getVisitor(); Type publicType = Type.getType(publicClass); Type superClass; String[] interfaces; if (publicClass.isInterface()) { superClass = OBJECT; interfaces = new String[] { publicType.getInternalName(), MANAGED.getInternalName() }; } else { superClass = publicType; interfaces = INTERFACES_FOR_ABSTRACT_CLASS; } visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null, superClass.getInternalName(), interfaces); // // Add name field // visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null); // // Add constructor // MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call this.super() methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false); // Set this.name = param1 methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); // Done methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add `getName()` // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // return this.name methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add `toString()` // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // return this.name methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD, STRING.getDescriptor()); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); visitor.visitEnd(); generator.define(); // // Generate factory class // generator = new AsmClassGenerator(publicClass, "$Factory"); visitor = generator.getVisitor(); visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null, CLASS_GENERATING_LOADER.getInternalName(), EMPTY_STRINGS); // // Add constructor // methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call this.super() methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, CLASS_GENERATING_LOADER.getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false); // Done methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // // Add factory method // methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", RETURN_OBJECT_FROM_STRING, null, EMPTY_STRINGS); methodVisitor.visitCode(); // Call return new <implClass>(param1) methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName()); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING, false); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); visitor.visitEnd(); Class<Object> factoryClass = generator.define(); try { return (ClassGeneratingLoader) factoryClass.getConstructor().newInstance(); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } }
From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java
License:Apache License
private <T> Class<? extends T> doGenerate(Class<T> type) { ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS); String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware" + type.getSimpleName();/* w w w .j a v a 2s .co m*/ 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[] { Type.getType(LocationAwareException.class).getInternalName() }); Type helperType = Type.getType(ExceptionHelper.class); Type throwableType = Type.getType(Throwable.class); Type scriptSourceType = Type.getType(ScriptSource.class); Type integerType = Type.getType(Integer.class); // GENERATE private ExceptionHelper helper; visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null); // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber) String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType, scriptSourceType, integerType }); MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null, new String[0]); methodVisitor.visitCode(); boolean noArgsConstructor; try { type.getConstructor(type); noArgsConstructor = false; } catch (NoSuchMethodException e) { try { type.getConstructor(); noArgsConstructor = true; } catch (NoSuchMethodException e1) { throw new IllegalArgumentException(String.format( "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.", type.getName())); } } if (noArgsConstructor) { // GENERATE super() methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0])); // END super() } else { // GENERATE super(target) methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType })); // END super(target) } // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber) methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName()); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { throwableType, throwableType, scriptSourceType, integerType })); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper", helperType.getDescriptor()); // END helper = new ExceptionHelper(target) methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // END <init>(<type> target, ScriptSource source, Integer lineNumber) for (Method method : ExceptionHelper.class.getDeclaredMethods()) { // GENERATE public <type> <method>() { return helper.<method>(); } methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]); methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null, new String[0]); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper", helperType.getDescriptor()); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(), methodDescriptor); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); // END public <type> <method>() { return helper.<method>(); } } visitor.visitEnd(); byte[] bytecode = visitor.toByteArray(); return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass", new Object[] { typeName, bytecode, 0, bytecode.length }); }
From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java
@Override public void visit(AccessorExpression node) throws ASTVisitorException { node.getExpression().accept(this); //function access if (node.getExpressions() != null) { node.getExpressions().accept(this); //if expressionS length is 0, no args privided Type returnType;//w w w .ja v a2s . c o m Type exprClass = ASTUtils.getSafeType(node.getExpression()); SymTable<SymTableEntry> sTable = ASTUtils.getSafeEnv(node); SymTableEntry lookup = sTable.lookup(node.getIdentifier()); System.out.println( "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4 " + node.getIdentifier()); if (lookup != null) { mn.instructions.add( new MethodInsnNode(Opcodes.INVOKEVIRTUAL, exprClass.getInternalName(), node.getIdentifier(), Type.getMethodDescriptor(lookup.getType(), lookup.getParametersTypes()), false)); } else { Map<Type, SymTable<SymTableEntry>> classes = Registry.getInstance().getClasses(); Iterator<Map.Entry<Type, SymTable<SymTableEntry>>> entries = classes.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Type, SymTable<SymTableEntry>> entry = entries.next(); if (entry.getValue().lookup(node.getIdentifier()) != null) { SymTableEntry lookup1 = entry.getValue().lookup(node.getIdentifier()); System.out.println("entry key: " + entry.getKey().getDescriptor()); mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, entry.getKey().getInternalName(), node.getIdentifier(), Type.getMethodDescriptor(lookup1.getType(), lookup1.getParametersTypes()), false)); break; } } } } //field access else { System.out.println("+++++++++++++++++++++++++> HEY " + node.getIdentifier()); if (node.getExpression().getClass() != IdentifierExpression.class && previousIsIdentifier) { System.out.println("+++++++++++++++++++++++++++++++++++++++++++---> " + node.getIdentifier()); mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, cn.name, node.getIdentifier(), ASTUtils.getSafeType(node).getDescriptor())); } else { mn.instructions.add(new FieldInsnNode(Opcodes.PUTFIELD, cn.name, node.getIdentifier(), ASTUtils.getSafeType(node).getDescriptor())); } } }
From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java
@Override public void visit(IdentifierExpression node) throws ASTVisitorException { previousIsIdentifier = false;// www .j av a2 s . c o m if (node.getExpressions() != null) { node.getExpressions().accept(this); SymTable<SymTableEntry> symbols = Registry.getInstance() .getExistingClass(Type.getType("Lorg/hua/customclasses/" + cn.name + ";")); SymTableEntry sEntry = symbols.lookup(node.getIdentifier()); if (sEntry != null) { mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Type.getType("Lorg/hua/customclasses/" + cn.name + ";").getInternalName(), node.getIdentifier(), Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false)); } else { //search all classes //if the function is static and defined in another class, ok //else error String nodeId = node.getIdentifier(); boolean foundStaticOtherClass = false; String classFound; Map<Type, SymTable<SymTableEntry>> classes = Registry.getInstance().getClasses(); Iterator<Map.Entry<Type, SymTable<SymTableEntry>>> entries = classes.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Type, SymTable<SymTableEntry>> entry = entries.next(); if (entry.getValue().lookup(nodeId) != null) { if (entry.getValue().lookup(nodeId).isIsStatic()) { foundStaticOtherClass = true; classFound = entry.getKey().toString(); break; } } } if (!foundStaticOtherClass) { ASTUtils.error(node, "This static(?) method could not be found"); } } } else { Type type = ASTUtils.getSafeType(node); SymTable<SymTableEntry> symbols = Registry.getInstance() .getExistingClass(Type.getType("Lorg/hua/customclasses/" + cn.name + ";")); SymTableEntry csEntry = symbols.lookup(node.getIdentifier()); //i think this is useless, because fields are not seperate identifier, but string ids in accessorExpressions if (csEntry != null) { mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, cn.name, node.getIdentifier(), csEntry.getType().getDescriptor())); return; } SymTable<SymTableEntry> sTable = ASTUtils.getSafeEnv(node); SymTableEntry sEntry = sTable.lookup(node.getIdentifier()); previousIsIdentifier = true; mn.instructions.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), sEntry.getIndex())); System.out.println( "&&&&&&&&&&&&&&&&&&&&&&&&&&&& INDEX: " + sEntry.getIndex() + " id: " + node.getIdentifier()); } }