Example usage for org.objectweb.asm Opcodes ASTORE

List of usage examples for org.objectweb.asm Opcodes ASTORE

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ASTORE.

Prototype

int ASTORE

To view the source code for org.objectweb.asm Opcodes ASTORE.

Click Source Link

Usage

From source file:org.springsource.loaded.test.infra.MethodPrinter.java

License:Apache License

public void visitVarInsn(int opcode, int var) {
    if (opcode == Opcodes.ALOAD) {
        to.println("    ALOAD " + var);
    } else if (opcode == Opcodes.ASTORE) {
        to.println("    ASTORE " + var);
    } else if (opcode == Opcodes.ILOAD) {
        to.println("    ILOAD " + var);
    } else if (opcode == FLOAD) {
        to.println("    FLOAD " + var);
    } else if (opcode == LLOAD) {
        to.println("    LLOAD " + var);
    } else if (opcode == DLOAD) {
        to.println("    DLOAD " + var);
    } else if (opcode == ISTORE) {
        to.println("    ISTORE " + var);
    } else if (opcode == LSTORE) {
        to.println("    LSTORE " + var);
    } else {//w  ww .j a va2s.co  m
        throw new IllegalStateException(":" + opcode);
    }
}

From source file:org.testeoa.estatica.AdapterDUG.java

License:Open Source License

@Override
public void visitVarInsn(int opcode, int var) {
    String ins = getInstrucao(opcode) + " " + var;
    addInstrucao(ins);/*from   www  . java2 s.  c  o m*/
    // Anlise do Fluxo de Dados
    if (opcode >= Opcodes.ILOAD && opcode <= Opcodes.ALOAD) {
        addUso(var);
    }
    if (opcode >= Opcodes.ISTORE && opcode <= Opcodes.ASTORE) {
        addDef(var);
    }
    super.visitVarInsn(opcode, var);
}

From source file:org.zoeey.ztpl.compiler.ByteCodeHelper.java

License:LGPL

/**
 * ??<br />/*from   w  ww .ja v  a2 s .  c o  m*/
 * @param obj ??
 * @return  ??
 */
public int newVar(Object obj) {
    int pos = tracker.next();
    visitObject(obj);
    mv.visitVarInsn(Opcodes.ASTORE, pos);
    return pos;
}

From source file:org.zoeey.ztpl.compiler.ByteCodeHelper.java

License:LGPL

/**
 * ?<br />/*from w  w  w. ja v  a 2 s .  c om*/
 * ? var paramsMap_* = new ParamsMap();<br />
 * ex. {echo varA="a" varB="b"} <br />
 * ?? map{"varA":"a","varB":"b"}
 *
 */
public int newMap() {
    int pos = tracker.next();
    mv.visitTypeInsn(Opcodes.NEW, "org/zoeey/ztpl/ParamsMap");
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/zoeey/ztpl/ParamsMap", "<init>", "()V");
    mv.visitVarInsn(Opcodes.ASTORE, pos);
    return pos;
}

From source file:org.zoeey.ztpl.compiler.ByteCodeHelper.java

License:LGPL

/**
 * ???ParamsMap/*  w w w  .jav  a 2 s .  c o m*/
 * ?paramsMap.get(key);
 * @param mapPos  ParamsMap?
 * @param key  
 * @param valuePos  ??
 * @return pos ?
 */
public int getFromMap(int mapPos, String key) {
    int pos = tracker.next();
    mv.visitVarInsn(Opcodes.ALOAD, mapPos);
    mv.visitLdcInsn(key);
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "get",
            "(Ljava/lang/Object;)Ljava/lang/Object;");
    mv.visitVarInsn(Opcodes.ASTORE, pos);
    return pos;
}

From source file:pku.sei.checkedcoverage.slicing.Slicer.java

License:Creative Commons License

/**
 * select the last location that was not checked, and create new slice criterion for it.
 * remove the relative lines from unchecked lines, until all location are sliced.
 * @return the new created slice location for every class.
 *///from  www  .  j  a v a 2s  .c o m
public static HashMap<String, TreeSet<Long>> sliceForUnchecked() {
    System.out.println("Trying to add checks");
    HashMap<String, TreeSet<Long>> sliceCreated = new HashMap<String, TreeSet<Long>>();
    HashMap<String, HashSet<Instruction>> uncheckedMap = getUncheckedMap();
    Iterator<String> it = uncheckedMap.keySet().iterator();
    List<String> cris = new ArrayList<String>();
    int crisNr = 0;
    while (it.hasNext()) {
        String key = it.next();
        sliceCreated.put(key, new TreeSet<Long>());
        HashSet<Instruction> insts = uncheckedMap.get(key);
        TreeSet<Integer> unchecked = new TreeSet<Integer>();
        HashMap<Integer, String> critInfoMap = new HashMap<Integer, String>();
        HashMap<Integer, HashSet<String>> varsMap = new HashMap<Integer, HashSet<String>>();
        for (Instruction inst : insts) {
            if (inst.getType().equals(InstructionType.FIELD) || inst.getType().equals(InstructionType.VAR)) {
                unchecked.add(inst.getLineNumber());
                if (!critInfoMap.containsKey(inst.getLineNumber())) {
                    critInfoMap.put(inst.getLineNumber(),
                            inst.getMethod().getReadClass().getName() + "." + inst.getMethod().getName());
                }
                if (!varsMap.containsKey(inst.getLineNumber())) {
                    varsMap.put(inst.getLineNumber(), new HashSet<String>());
                }
                if (inst.getType().equals(InstructionType.FIELD)) {
                    FieldInstruction fieldinst = (FieldInstruction) inst;
                    varsMap.get(inst.getLineNumber()).add(fieldinst.getFieldName());
                } else if (inst.getType().equals(InstructionType.VAR)) {
                    VarInstruction varinst = (VarInstruction) inst;
                    if (varinst.getOpcode() == Opcodes.DSTORE || varinst.getOpcode() == Opcodes.ASTORE
                            || varinst.getOpcode() == Opcodes.LSTORE || varinst.getOpcode() == Opcodes.ISTORE
                            || varinst.getOpcode() == Opcodes.FSTORE || varinst.getOpcode() == Opcodes.RET) {
                        String varname = inst.getMethod().getLocalVariables()[varinst.getLocalVarIndex()]
                                .getName();
                        varsMap.get(inst.getLineNumber()).add(varname);
                    }
                }
            }
        }
        while (!unchecked.isEmpty()) {
            int last = unchecked.last();
            String cri = critInfoMap.get(last) + ":" + last + ":*";
            cris.add(cri);
            System.out.println(++crisNr + " new check(s) added!" + cri);
            unchecked.removeAll(sliceUnchecked(cri));
            sliceCreated.get(key).add((long) last);
            unchecked.remove(last);
        }
    }
    System.out.println("Done!");
    return sliceCreated;
}

From source file:pku.sei.checkedcoverage.slicing.Slicer.java

License:Creative Commons License

public void process(ThreadId threadId, final List<SlicingCriterion> sc, boolean multithreaded)
        throws InterruptedException {
    DependencesExtractor<SlicerInstance> depExtractor = DependencesExtractor.forTrace(this.trace,
            SlicerInstanceFactory.instance);
    for (ProgressMonitor mon : this.progressMonitors)
        depExtractor.addProgressMonitor(mon);

    VisitorCapability[] capabilities = { VisitorCapability.CONTROL_DEPENDENCES,
            VisitorCapability.DATA_DEPENDENCES_READ_AFTER_WRITE, VisitorCapability.INSTRUCTION_EXECUTIONS,
            VisitorCapability.METHOD_ENTRY_LEAVE, VisitorCapability.CONTROL_DEPENDENCES };
    if (this.untracedCallVisitors.size() > 0)
        capabilities[capabilities.length - 1] = VisitorCapability.UNTRACED_METHOD_CALLS;

    final List<SliceVisitor> sliceVisitors0 = Slicer.this.sliceVisitors;
    final List<UntracedCallVisitor> untracedCallVisitors0 = Slicer.this.untracedCallVisitors;
    depExtractor.registerVisitor(new DependencesVisitorAdapter<SlicerInstance>() {
        private final List<SlicingCriterionInstance> slicingCritInst = instantiateSlicingCriteria(sc);
        @SuppressWarnings("unchecked")
        private IntegerMap<Object>[] interestingLocalVariables = (IntegerMap<Object>[]) new IntegerMap<?>[0];
        private long[] critOccurenceNumbers = new long[2]; // 0 if not in a criterion
        private final SliceVisitor[] sliceVisitorsArray = sliceVisitors0
                .toArray(new SliceVisitor[sliceVisitors0.size()]);
        private final UntracedCallVisitor[] untracedCallsVisitorsArray = untracedCallVisitors0
                .toArray(new UntracedCallVisitor[untracedCallVisitors0.size()]);

        private ReadMethod enteredMethod;

        private List<SlicingCriterionInstance> instantiateSlicingCriteria(List<SlicingCriterion> criteria) {
            if (criteria.isEmpty())
                return Collections.emptyList();
            else if (criteria.size() == 1)
                return Collections.singletonList(criteria.get(0).getInstance());
            else {
                List<SlicingCriterionInstance> instances = new ArrayList<SlicingCriterionInstance>(
                        criteria.size());
                for (SlicingCriterion crit : criteria)
                    instances.add(crit.getInstance());
                return instances;
            }//from   www.j a v  a 2s . c  o m
        }

        @Override
        public void visitInstructionExecution(SlicerInstance instance) {
            int stackDepth = instance.getStackDepth();
            if (this.critOccurenceNumbers.length <= stackDepth) {
                long[] newCritOccurenceNumbers = new long[2
                        * Math.max(this.critOccurenceNumbers.length, stackDepth)];
                System.arraycopy(this.critOccurenceNumbers, 0, newCritOccurenceNumbers, 0,
                        this.critOccurenceNumbers.length);
                this.critOccurenceNumbers = newCritOccurenceNumbers;
            }
            Instruction instruction = instance.getInstruction();
            for (SlicingCriterionInstance crit : this.slicingCritInst) {
                if (crit.matches(instance)) {
                    this.critOccurenceNumbers[stackDepth] = crit.getOccurenceNumber();
                    assert (this.critOccurenceNumbers[stackDepth] > 0);
                    // for each criterion, there are three cases:
                    //  - track all data read in this line
                    //  - track a given set of local variables
                    //  - track the control dependences of this instruction
                    // only in the last case, the instructions from that line are added to the dynamic slice
                    if (crit.matchAllData()) {
                        instance.allDataInteresting = true;
                        instance.onlyIfAfterCriterion = true;
                        instance.onDynamicSlice = true; // it's not really on the dynamic slice, but we have to set this
                        instance.criterionDistance = 0;
                    } else {
                        if (crit.hasLocalVariables()) {
                            if (this.interestingLocalVariables.length <= stackDepth) {
                                @SuppressWarnings("unchecked")
                                IntegerMap<Object>[] newInterestingLocalVariables = (IntegerMap<Object>[]) new IntegerMap<?>[Math
                                        .max(stackDepth + 1, this.interestingLocalVariables.length * 3 / 2)];
                                System.arraycopy(this.interestingLocalVariables, 0,
                                        newInterestingLocalVariables, 0, this.interestingLocalVariables.length);
                                this.interestingLocalVariables = newInterestingLocalVariables;
                            }
                            List<LocalVariable> localVariables = crit.getLocalVariables();
                            if (this.interestingLocalVariables[stackDepth] == null)
                                this.interestingLocalVariables[stackDepth] = new IntegerMap<Object>(
                                        localVariables.size() * 4 / 3 + 1);
                            for (LocalVariable i : localVariables)
                                this.interestingLocalVariables[stackDepth].put(i.getIndex(), null);
                        } else {
                            Instruction insn = instruction;
                            if (insn.getType() != InstructionType.LABEL)
                                for (SliceVisitor vis : this.sliceVisitorsArray)
                                    vis.visitMatchedInstance(instance);
                            instance.onDynamicSlice = true;
                            instance.criterionDistance = 0;
                        }
                    }
                } else if (this.critOccurenceNumbers[stackDepth] != 0) {
                    this.critOccurenceNumbers[stackDepth] = 0;
                }
            }
            if (this.interestingLocalVariables.length > stackDepth
                    && this.interestingLocalVariables[stackDepth] != null) {
                switch (instruction.getOpcode()) {
                case Opcodes.ISTORE:
                case Opcodes.ASTORE:
                case Opcodes.LSTORE:
                case Opcodes.FSTORE:
                case Opcodes.DSTORE:
                    VarInstruction varInsn = (VarInstruction) instruction;
                    if (this.interestingLocalVariables[stackDepth].containsKey(varInsn.getLocalVarIndex())) {
                        this.interestingLocalVariables[stackDepth].remove(varInsn.getLocalVarIndex());
                        if (this.interestingLocalVariables[stackDepth].isEmpty())
                            this.interestingLocalVariables[stackDepth] = null;
                        for (SliceVisitor vis : this.sliceVisitorsArray)
                            vis.visitMatchedInstance(instance);
                        instance.onDynamicSlice = true;
                        // and we want to know where the data comes from...
                        instance.allDataInteresting = true;
                        instance.criterionDistance = 0;
                    }
                    break;
                case Opcodes.INVOKEINTERFACE:
                case Opcodes.INVOKESPECIAL:
                case Opcodes.INVOKESTATIC:
                case Opcodes.INVOKEVIRTUAL:
                    if (this.enteredMethod != null) {
                        MethodInvocationInstruction mtdInvInsn = (MethodInvocationInstruction) instruction;
                        int paramCount = instruction.getOpcode() == INVOKESTATIC ? 0 : 1;
                        for (int param = mtdInvInsn.getParameterCount() - 1; param >= 0; --param)
                            paramCount += mtdInvInsn.parameterIsLong(param) ? 2 : 1;
                        boolean enteredMethodMatches = this.enteredMethod.getName()
                                .equals(mtdInvInsn.getInvokedMethodName())
                                && this.enteredMethod.getDesc().equals(mtdInvInsn.getInvokedMethodDesc());
                        if (enteredMethodMatches) {
                            boolean localVarsMatched = false;
                            for (int varNr = 0; varNr < paramCount; ++varNr) {
                                if (this.interestingLocalVariables[stackDepth].containsKey(varNr)) {
                                    this.interestingLocalVariables[stackDepth].remove(varNr);
                                    if (this.interestingLocalVariables[stackDepth].isEmpty())
                                        this.interestingLocalVariables[stackDepth] = null;
                                    localVarsMatched = true;
                                    instance.onDynamicSlice = true;
                                    // and we want to know where the data comes from...
                                    // TODO
                                    instance.allDataInteresting = true;
                                    instance.criterionDistance = 0;
                                }
                            }
                            if (localVarsMatched)
                                for (SliceVisitor vis : this.sliceVisitorsArray)
                                    vis.visitMatchedInstance(instance);
                        }
                    }
                }
            }
            this.enteredMethod = null;
        }

        @Override
        public void visitControlDependence(SlicerInstance from, SlicerInstance to) {
            if (from.onDynamicSlice) {
                Instruction insn = to.getInstruction();
                if (insn.getType() == InstructionType.LABEL || insn.getOpcode() == Opcodes.GOTO) {
                    if (to.predecessors == null)
                        to.predecessors = Collections.singleton(from);
                    else {
                        if (to.predecessors.size() == 1)
                            to.predecessors = new HashSet<SlicerInstance>(to.predecessors);
                        to.predecessors.add(from);
                    }
                    if (from.criterionDistance < to.criterionDistance)
                        to.criterionDistance = from.criterionDistance;
                } else if (from.predecessors != null) {
                    assert (!from.predecessors.isEmpty());
                    for (SlicerInstance pred : from.predecessors) {
                        int distance = pred.criterionDistance + 1;
                        delegateControlSliceDependence(pred, to, distance);
                        if (distance < to.criterionDistance)
                            to.criterionDistance = distance;
                    }
                } else {
                    int distance = from.criterionDistance + 1;
                    delegateControlSliceDependence(from, to, distance);
                    if (distance < to.criterionDistance)
                        to.criterionDistance = distance;
                }
                to.onDynamicSlice = true;
            }
        }

        private void delegateControlSliceDependence(SlicerInstance from, SlicerInstance to, int distance) {

            for (SliceVisitor vis : this.sliceVisitorsArray)
                vis.visitSliceDependence(from, to, null, distance);

            // since "to" controls the execution of "from", we want to track all data dependences of "to"
            // to find out why it took this decision
            // exception: method invocations; here we only want to track why the method was executed,
            // but not the data that it consumed
            // important to check that "from" comes from inside the method which is called by "from"
            boolean calledMethodDependence = false;
            if (to.getInstruction().getType() == InstructionType.METHODINVOCATION) {
                MethodInvocationInstruction mtdInv = (MethodInvocationInstruction) to.getInstruction();
                ReadMethod calledMethod = from.getInstruction().getMethod();
                if (mtdInv.getInvokedMethodName().equals(calledMethod.getName())
                        && mtdInv.getInvokedMethodDesc().equals(calledMethod.getDesc())) {
                    calledMethodDependence = true;
                }
            }
            if (!calledMethodDependence) {
                to.allDataInteresting = true;
            }
        }

        @Override
        public void visitDataDependence(SlicerInstance from, SlicerInstance to,
                Collection<? extends Variable> fromVars, Variable toVar, DataDependenceType type)
                throws InterruptedException {
            assert type == DataDependenceType.READ_AFTER_WRITE;

            if (from.onDynamicSlice && // from must definitively be on the dynamic slice
            ((from.allDataInteresting
                    && (!from.onlyIfAfterCriterion || this.critOccurenceNumbers[to.getStackDepth()] == 0)) || // and either we want to track all data dependencies
            (from.interestingVariable != null && ( // or (if the interestingVariable is set) ...
            from.interestingVariable.equals(toVar) || // the interestingVariable must be the one we are just visiting
            (from.moreInterestingVariables != null && from.moreInterestingVariables.contains(toVar)))))) { // or it must be in the set of more variables
                Instruction insn = to.getInstruction();
                assert insn.getType() != InstructionType.LABEL;
                if (from.onlyIfAfterCriterion) {
                    to.criterionDistance = 0;
                    for (SliceVisitor vis : this.sliceVisitorsArray)
                        vis.visitMatchedInstance(to);
                } else {
                    int distance = from.criterionDistance + 1;
                    if (distance < to.criterionDistance)
                        to.criterionDistance = distance;
                    for (SliceVisitor vis : this.sliceVisitorsArray)
                        vis.visitSliceDependence(from, to, toVar, distance);
                }
                if (!fromVars.isEmpty()) {
                    Iterator<? extends Variable> varIt = fromVars.iterator();
                    assert varIt
                            .hasNext() : "Iterator of a non-empty collection should have at least one element";
                    Variable first = varIt.next();
                    if (to.interestingVariable == null || to.interestingVariable.equals(first)) {
                        to.interestingVariable = first;
                        first = varIt.hasNext() ? varIt.next() : null;
                    }
                    if (first != null) {
                        if (to.moreInterestingVariables == null)
                            to.moreInterestingVariables = new HashSet<Variable>(8);
                        to.moreInterestingVariables.add(first);
                        while (varIt.hasNext())
                            to.moreInterestingVariables.add(varIt.next());
                    }
                }
                to.onDynamicSlice = true;
            }
        }

        @Override
        public void visitMethodLeave(ReadMethod method, int stackDepth) throws InterruptedException {
            if (this.interestingLocalVariables.length > stackDepth
                    && this.interestingLocalVariables[stackDepth] != null) {
                this.interestingLocalVariables[stackDepth] = null;
            }
        }

        @Override
        public void visitMethodEntry(ReadMethod method, int stackDepth) throws InterruptedException {
            if (this.interestingLocalVariables.length > stackDepth
                    && this.interestingLocalVariables[stackDepth] != null) {
                this.enteredMethod = method;
                this.interestingLocalVariables[stackDepth] = null;
            }
        }

        @Override
        public void visitUntracedMethodCall(SlicerInstance instrInstance) throws InterruptedException {
            for (UntracedCallVisitor vis : this.untracedCallsVisitorsArray)
                vis.visitUntracedMethodCall(instrInstance);
        }

    }, capabilities);

    depExtractor.processBackwardTrace(threadId, multithreaded);
}

From source file:pl.clareo.coroutines.core.ClassTransformer.java

License:Apache License

@SuppressWarnings("unchecked")
void transform() {
    for (MethodNode coroutine : coroutines) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Generating method for coroutine " + coroutine.name + coroutine.desc);
        }/*w w  w  .j  av a  2  s .  c o m*/
        String coroutineName = getCoroutineName(coroutine);
        MethodTransformer methodTransformer = new MethodTransformer(coroutine, thisType);
        MethodNode coroutineImpl = methodTransformer.transform(coroutineName, generateDebugCode);
        thisNode.methods.add(coroutineImpl);
        /*
         * generate co iterators and method stubs
         */
        log.finest("Generating CoIterator implementation and method stubs");
        String baseCoIteratorName;
        Map<String, Object> annotation = getCoroutineAnnotationValues(coroutine);
        if (getBoolean(annotation, "threadLocal")) {
            baseCoIteratorName = Type.getInternalName(ThreadLocalCoIterator.class);
        } else {
            baseCoIteratorName = Type.getInternalName(SingleThreadedCoIterator.class);
        }
        String coIteratorClassName = "pl/clareo/coroutines/core/CoIterator" + num;
        ClassNode coIteratorClass = new ClassNode();
        coIteratorClass.version = Opcodes.V1_6;
        coIteratorClass.access = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER;
        coIteratorClass.name = coIteratorClassName;
        coIteratorClass.superName = baseCoIteratorName;
        if (generateDebugCode) {
            /*
             * If debugging code is emitted create field keeping JDK logger
             */
            FieldNode loggerField = new FieldNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC,
                    "logger", "Ljava/util/logging/Logger;", null, null);
            coIteratorClass.fields.add(loggerField);
            MethodNode clinit = new MethodNode();
            clinit.access = Opcodes.ACC_STATIC;
            clinit.name = "<clinit>";
            clinit.desc = "()V";
            clinit.exceptions = Collections.EMPTY_LIST;
            String loggerName = thisType.getClassName();
            InsnList clinitCode = clinit.instructions;
            clinitCode.add(new LdcInsnNode(loggerName));
            clinitCode.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/util/logging/Logger", "getLogger",
                    "(Ljava/lang/String;)Ljava/util/logging/Logger;"));
            clinitCode.add(new FieldInsnNode(Opcodes.PUTSTATIC, coIteratorClassName, "logger",
                    "Ljava/util/logging/Logger;"));
            clinitCode.add(new InsnNode(Opcodes.RETURN));
            clinit.maxStack = 1;
            clinit.maxLocals = 0;
            coIteratorClass.methods.add(clinit);
        }
        /*
         * Generate constructor
         */
        MethodNode init = new MethodNode();
        init.access = Opcodes.ACC_PUBLIC;
        init.name = "<init>";
        init.desc = CO_ITERATOR_CONSTRUCTOR_DESCRIPTOR;
        init.exceptions = Collections.EMPTY_LIST;
        InsnList initCode = init.instructions;
        initCode.add(new VarInsnNode(Opcodes.ALOAD, 0));
        initCode.add(new VarInsnNode(Opcodes.ALOAD, 1));
        initCode.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, baseCoIteratorName, "<init>",
                CO_ITERATOR_CONSTRUCTOR_DESCRIPTOR));
        initCode.add(new InsnNode(Opcodes.RETURN));
        init.maxStack = 2;
        init.maxLocals = 2;
        coIteratorClass.methods.add(init);
        /*
         * Generate overriden call to coroutine
         */
        MethodNode call = new MethodNode();
        call.access = Opcodes.ACC_PROTECTED;
        call.name = "call";
        call.desc = CALL_METHOD_DESCRIPTOR;
        call.exceptions = Collections.EMPTY_LIST;
        InsnList callCode = call.instructions;
        /*
         * if debug needed generate call details
         */
        if (generateDebugCode) {
            String coroutineId = "Coroutine " + coroutine.name;
            callCode.add(loggingInstructions(coIteratorClassName, "logger", Level.FINER,
                    coroutineId + " call. Caller sent: ", 2));
            callCode.add(new FrameNode(Opcodes.F_SAME, 0, EMPTY_LOCALS, 0, EMPTY_STACK));
            callCode.add(loggingInstructions(coIteratorClassName, "logger", Level.FINEST,
                    coroutineId + " state ", 1));
            callCode.add(new FrameNode(Opcodes.F_SAME, 0, EMPTY_LOCALS, 0, EMPTY_STACK));
        }
        /*
         * push call arguments: this (if not static), frame, input, output
         */
        boolean isStatic = (coroutine.access & Opcodes.ACC_STATIC) != 0;
        if (!isStatic) {
            callCode.add(new VarInsnNode(Opcodes.ALOAD, 1));
            callCode.add(
                    new MethodInsnNode(Opcodes.INVOKEVIRTUAL, FRAME_NAME, "getThis", "()Ljava/lang/Object;"));
            callCode.add(new TypeInsnNode(Opcodes.CHECKCAST, thisType.getInternalName()));
        }
        callCode.add(new VarInsnNode(Opcodes.ALOAD, 1));
        callCode.add(new InsnNode(Opcodes.ACONST_NULL));
        callCode.add(new VarInsnNode(Opcodes.ALOAD, 2));
        callCode.add(new MethodInsnNode(isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKEVIRTUAL,
                thisType.getInternalName(), coroutineName, COROUTINE_METHOD_DESCRIPTOR));
        // stack: *
        if (!generateDebugCode) {
            callCode.add(new InsnNode(Opcodes.ARETURN));
        } else {
            // save result display suspension point (two more locals
            // needed)
            callCode.add(new VarInsnNode(Opcodes.ASTORE, 3));
            callCode.add(new VarInsnNode(Opcodes.ALOAD, 1));
            callCode.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, FRAME_NAME, "getLineOfCode", "()I"));
            callCode.add(box_int(Type.INT));
            callCode.add(new VarInsnNode(Opcodes.ASTORE, 4));
            callCode.add(loggingInstructions(coIteratorClassName, "logger", Level.FINER,
                    "Coroutine suspended at line ", 4, ". Yielded:", 3));
            callCode.add(new FrameNode(Opcodes.F_APPEND, 2,
                    new Object[] { "java/lang/Object", "java/lang/Integer" }, 0, EMPTY_STACK));
            callCode.add(new VarInsnNode(Opcodes.ALOAD, 3));
            callCode.add(new InsnNode(Opcodes.ARETURN));
        }
        coIteratorClass.methods.add(call);
        // if debugging code is emitted it needs space for two
        // additional locals and 5 stack operand
        if (generateDebugCode) {
            call.maxStack = 5;
            call.maxLocals = 5;
        } else {
            if (isStatic) {
                call.maxStack = 3;
            } else {
                call.maxStack = 4;
            }
            call.maxLocals = 3;
        }
        /*
         * CoIterator created - define it in the runtime and verify if
         * needed
         */
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Generated class " + coIteratorClassName);
        }
        ClassWriter cw = new ClassWriter(0);
        coIteratorClass.accept(cw);
        byte[] classBytes = cw.toByteArray();
        try {
            CoroutineInstrumentator.dumpClass(coIteratorClassName, classBytes);
        } catch (IOException e) {
            throw new CoroutineGenerationException("Unable to write class " + coIteratorClassName, e);
        }
        /*
         * start generating method - new method is named as the method in
         * user code, it: returns instance of appropriate CoIterator (see
         * above), saves arguments of call
         */
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Instrumenting method " + coroutine.name);
        }
        InsnList code = coroutine.instructions;
        code.clear();
        /*
         * create new Frame
         */
        boolean isDebugFramePossible = generateDebugCode && coroutine.localVariables != null;
        if (isDebugFramePossible) {
            code.add(createDebugFrame(coroutine));
        } else {
            code.add(createFrame(coroutine));
        }
        /*
         * save frame in the first, and locals array in the second local
         * variable
         */
        int argsSize = Type.getArgumentsAndReturnSizes(coroutine.desc) >> 2;
        if (isStatic) {
            argsSize -= 1;
        }
        code.add(new VarInsnNode(Opcodes.ASTORE, argsSize));
        code.add(new VarInsnNode(Opcodes.ALOAD, argsSize));
        code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, FRAME_NAME, "getLocals", "()[Ljava/lang/Object;"));
        int localsArrayIndex = argsSize + 1;
        code.add(new VarInsnNode(Opcodes.ASTORE, localsArrayIndex));
        /*
         * save all call arguments (along with this if this method is not
         * static) into locals array
         */
        Type[] argsTypes = Type.getArgumentTypes(coroutine.desc);
        if (!isStatic) {
            code.add(saveloc(localsArrayIndex, 0, 0, JAVA_LANG_OBJECT));
            code.add(savelocs(localsArrayIndex, 1, 1, argsTypes));
        } else {
            code.add(savelocs(localsArrayIndex, 0, 0, argsTypes));
        }
        /*
         * create CoIterator instance with saved frame, make initial call to
         * next if needed and return to caller
         */
        code.add(new TypeInsnNode(Opcodes.NEW, coIteratorClassName));
        code.add(new InsnNode(Opcodes.DUP));
        code.add(new VarInsnNode(Opcodes.ALOAD, argsSize));
        code.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, coIteratorClassName, "<init>",
                CO_ITERATOR_CONSTRUCTOR_DESCRIPTOR));
        if (!getBoolean(annotation, "generator", true)) {
            code.add(new InsnNode(Opcodes.DUP));
            code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, coIteratorClassName, "next",
                    "()Ljava/lang/Object;"));
            code.add(new InsnNode(Opcodes.POP));
        }
        code.add(new InsnNode(Opcodes.ARETURN));
        /*
         * end method generation; maxs can be statically determined 3
         * operands on stack (call to frame setLocals and CoIterator
         * constructor) + 1 if any argument is long or double (debug frame
         * needs 7 operands for variable names creation); locals = argsSize
         * + 1 reference to frame + 1 array of locals
         */
        if (isDebugFramePossible) {
            coroutine.maxStack = 7;
        } else {
            boolean isCategory2ArgumentPresent = false;
            for (Type argType : argsTypes) {
                int sort = argType.getSort();
                if (sort == Type.LONG || sort == Type.DOUBLE) {
                    isCategory2ArgumentPresent = true;
                    break;
                }
            }
            coroutine.maxStack = isCategory2ArgumentPresent ? 4 : 3;
        }
        coroutine.maxLocals = localsArrayIndex + 1;
        coroutine.localVariables.clear();
        coroutine.tryCatchBlocks.clear();
        num++;
    }
}

From source file:portablejim.veinminer.asm.ItemInWorldManagerTransformer.java

License:Open Source License

private InsnList buildBlockIdFunctionCall(String obfuscatedClassName, String worldType, int blockVarIndex) {
    InsnList blockIdFunctionCall = new InsnList();
    blockIdFunctionCall.add(new TypeInsnNode(Opcodes.NEW, blockIdClassName));
    blockIdFunctionCall.add(new InsnNode(Opcodes.DUP));
    blockIdFunctionCall.add(new VarInsnNode(Opcodes.ALOAD, 0));
    blockIdFunctionCall.add(new FieldInsnNode(Opcodes.GETFIELD, obfuscatedClassName.replace(".", "/"),
            getCorrectName("theWorld"), typemap.get(getCorrectName("theWorld"))));
    blockIdFunctionCall.add(new VarInsnNode(Opcodes.ILOAD, 1));
    blockIdFunctionCall.add(new VarInsnNode(Opcodes.ILOAD, 2));
    blockIdFunctionCall.add(new VarInsnNode(Opcodes.ILOAD, 3));
    blockIdFunctionCall.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, blockIdClassName, "<init>",
            String.format("(%sIII)V", worldType)));

    blockIdFunctionCall.add(new VarInsnNode(Opcodes.ASTORE, blockVarIndex));

    return blockIdFunctionCall;
}

From source file:pt.minha.kernel.instrument.SyncToMonitorClassVisitor.java

License:Open Source License

public void makeStub(int access, String name, String desc, String signature, String[] exceptions) {
    Method m = new Method(name, desc);

    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
    mv.visitCode();// w w w.ja v  a  2s .  com

    Label begin = new Label();
    Label pre_invoke = new Label();
    Label pos_leave = new Label();
    Label in_catch = new Label();
    Label pre_rethrow = new Label();
    Label end = new Label();

    mv.visitTryCatchBlock(pre_invoke, pos_leave, in_catch, null);
    mv.visitTryCatchBlock(in_catch, pre_rethrow, in_catch, null);

    mv.visitLabel(begin);

    int offset;
    if ((access & Opcodes.ACC_STATIC) == 0) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        offset = 1;
    } else {
        mv.visitFieldInsn(Opcodes.GETSTATIC, clz, "_fake_class",
                "L" + ClassConfig.fake_prefix + "java/lang/Object;");
        offset = 0;
    }

    int length = 0;
    for (Type t : m.getArgumentTypes())
        length += t.getSize();

    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ASTORE, offset + length);
    mv.visitInsn(Opcodes.MONITORENTER);

    mv.visitLabel(pre_invoke);

    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitVarInsn(Opcodes.ALOAD, 0);

    int i = offset;
    for (Type t : m.getArgumentTypes()) {
        // t.getOpcode() should work for long and double too... :-( 
        if (t.getClassName().equals("long"))
            mv.visitVarInsn(Opcodes.LLOAD, i);
        else if (t.getClassName().equals("double"))
            mv.visitVarInsn(Opcodes.DLOAD, i);
        else
            mv.visitVarInsn(t.getOpcode(Opcodes.ILOAD), i);
        i += t.getSize();
    }

    boolean itf = (access & Opcodes.ACC_INTERFACE) != 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, clz, "_" + name, desc, itf);
    else
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, clz, "_" + name, desc, itf);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pos_leave);

    if (m.getReturnType().equals(Type.VOID_TYPE))
        mv.visitInsn(Opcodes.RETURN);
    else
        mv.visitInsn(m.getReturnType().getOpcode(Opcodes.IRETURN));

    mv.visitLabel(in_catch);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pre_rethrow);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(end);

    i = 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitLocalVariable("this", "L" + clz + ";", null, begin, end, i++);
    for (Type t : m.getArgumentTypes())
        mv.visitLocalVariable("arg" + i, t.getDescriptor(), null, begin, end, i++);

    mv.visitMaxs(0, 0);
    mv.visitEnd();
}