Package org.apache.bcel.generic

Examples of org.apache.bcel.generic.MethodGen


        for (Method method : methodList) {
            if (method.isAbstract() || method.isNative()) {
                continue;
            }

            MethodGen methodGen = classContext.getMethodGen(method);
            if (methodGen == null) {
                continue;
            }

            if (DEBUG_METHOD_NAME != null && !DEBUG_METHOD_NAME.equals(method.getName())) {
View Full Code Here


    }

    public void analyzeMethod(ClassContext classContext, Method method, ResourceTrackerType resourceTracker,
            ResourceCollection<Resource> resourceCollection) throws CFGBuilderException, DataflowAnalysisException {

        MethodGen methodGen = classContext.getMethodGen(method);
        if (methodGen == null) {
            return;
        }
        try {
            CFG cfg = classContext.getCFG(method);
            DepthFirstSearch dfs = classContext.getDepthFirstSearch(method);

            if (DEBUG) {
                System.out.println(SignatureConverter.convertMethodSignature(methodGen));
            }

            for (Iterator<Resource> i = resourceCollection.resourceIterator(); i.hasNext();) {
                Resource resource = i.next();

                ResourceValueAnalysis<Resource> analysis = new ResourceValueAnalysis<Resource>(methodGen, cfg, dfs,
                        resourceTracker, resource);
                Dataflow<ResourceValueFrame, ResourceValueAnalysis<Resource>> dataflow = new Dataflow<ResourceValueFrame, ResourceValueAnalysis<Resource>>(
                        cfg, analysis);

                Profiler profiler = Global.getAnalysisCache().getProfiler();
                profiler.start(resourceTracker.getClass());
                try {
                    dataflow.execute();
                } finally {
                    profiler.end(resourceTracker.getClass());
                }
                inspectResult(classContext, methodGen, cfg, dataflow, resource);
            }
        } catch (RuntimeException e) {
            AnalysisContext.logError("Exception while analyzing " + methodGen.getClassName() + "." + methodGen.getName() + ":"
                    + methodGen.getSignature(), e);
        }
    }
View Full Code Here

 
  for(int j = 0; j < methods.length; j++) {
    Method    m  = methods[j];

    if(!(m.isAbstract() || m.isNative())) {
      MethodGen mg = new MethodGen(m, argv[i], cp);

      int compiled_stack  = mg.getMaxStack();
      int compiled_locals = mg.getMaxLocals();
      mg.setMaxStack(); // Recompute value
      mg.setMaxLocals();
      int computed_stack  = mg.getMaxStack();
      int computed_locals = mg.getMaxLocals();

      mg.getInstructionList().dispose(); // Reuse instruction handles
     
      System.out.println(m);
     
      if(computed_stack == compiled_stack) {
            System.out.println("Stack ok(" + computed_stack + ")");
View Full Code Here

              "<generated>", Constants.ACC_PUBLIC |
              Constants.ACC_SUPER,
              null);
    ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool
    InstructionList il = new InstructionList();
    MethodGen       mg = new MethodGen(Constants.ACC_STATIC |
               Constants.ACC_PUBLIC,// access flags
               Type.VOID,              // return type
               new Type[] {            // argument types
           new ArrayType(Type.STRING, 1)
               },
               new String[] { "argv" }, // arg names
               "main", "HelloWorld",    // method, class
               il, cp);
    InstructionFactory factory = new InstructionFactory(cg);

    ObjectType i_stream = new ObjectType("java.io.InputStream");
    ObjectType p_stream = new ObjectType("java.io.PrintStream");

    /* Create BufferedReader object and store it in local variable `in'.
     */
    il.append(factory.createNew("java.io.BufferedReader"));
    il.append(InstructionConstants.DUP); // Use predefined constant, i.e. flyweight
    il.append(factory.createNew("java.io.InputStreamReader"));
    il.append(InstructionConstants.DUP);
    il.append(factory.createFieldAccess("java.lang.System", "in", i_stream,
          Constants.GETSTATIC));

    /* Call constructors, i.e. BufferedReader(InputStreamReader())
     */
    il.append(factory.createInvoke("java.io.InputStreamReader", "<init>",
           Type.VOID, new Type[] { i_stream },
           Constants.INVOKESPECIAL));
    il.append(factory.createInvoke("java.io.BufferedReader", "<init>", Type.VOID,
           new Type[] { new ObjectType("java.io.Reader") },
           Constants.INVOKESPECIAL));

    /* Create local variable `in'
     */
    LocalVariableGen lg = mg.addLocalVariable("in",
                new ObjectType("java.io.BufferedReader"),
                null, null);
    int in = lg.getIndex();
    lg.setStart(il.append(new ASTORE(in))); // `i' valid from here

    /* Create local variable `name'
     */
    lg = mg.addLocalVariable("name", Type.STRING, null, null);
    int name = lg.getIndex();
    il.append(InstructionConstants.ACONST_NULL);
    lg.setStart(il.append(new ASTORE(name))); // `name' valid from here

    /* try { ...
     */
    InstructionHandle try_start =
      il.append(factory.createFieldAccess("java.lang.System", "out", p_stream,
            Constants.GETSTATIC));

    il.append(new PUSH(cp, "Please enter your name> "));
    il.append(factory.createInvoke("java.io.PrintStream", "print", Type.VOID,
           new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL));
    il.append(new ALOAD(in));
    il.append(factory.createInvoke("java.io.BufferedReader", "readLine",
           Type.STRING, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    il.append(new ASTORE(name));

    /* Upon normal execution we jump behind exception handler,
     * the target address is not known yet.
     */
    GOTO g = new GOTO(null);
    InstructionHandle try_end = il.append(g);

    /* } catch() { ... }
     * Add exception handler: print exception and return from method
     */
    InstructionHandle handler =
      il.append(factory.createFieldAccess("java.lang.System", "out", p_stream,
            Constants.GETSTATIC));
    // Little trick in order not to save exception object temporarily
    il.append(InstructionConstants.SWAP);

    il.append(factory.createInvoke("java.io.PrintStream", "println", Type.VOID,
     new Type[] { Type.OBJECT }, Constants.INVOKEVIRTUAL));
    il.append(InstructionConstants.RETURN);
    mg.addExceptionHandler(try_start, try_end, handler,
         new ObjectType("java.io.IOException"));

    /* Normal code continues, now we can set the branch target of the GOTO
     * that jumps over the handler code.
     */
    InstructionHandle ih =
      il.append(factory.createFieldAccess("java.lang.System", "out", p_stream,
            Constants.GETSTATIC));
    g.setTarget(ih);

    /* String concatenation compiles to StringBuffer operations.
     */
    il.append(factory.createNew(Type.STRINGBUFFER));
    il.append(InstructionConstants.DUP);
    il.append(new PUSH(cp, "Hello, "));
    il.append(factory.createInvoke("java.lang.StringBuffer", "<init>",
           Type.VOID, new Type[] { Type.STRING },
           Constants.INVOKESPECIAL));
    il.append(new ALOAD(name));
   
    /* Concatenate strings using a StringBuffer and print them.
     */
    il.append(factory.createInvoke("java.lang.StringBuffer", "append",
           Type.STRINGBUFFER, new Type[] { Type.STRING },
           Constants.INVOKEVIRTUAL));
    il.append(factory.createInvoke("java.lang.StringBuffer", "toString",
           Type.STRING, Type.NO_ARGS,
           Constants.INVOKEVIRTUAL));
   
    il.append(factory.createInvoke("java.io.PrintStream", "println",
           Type.VOID, new Type[] { Type.STRING },
           Constants.INVOKEVIRTUAL));

    il.append(InstructionConstants.RETURN);

    mg.setMaxStack(5); // Needed stack size
    cg.addMethod(mg.getMethod());

    il.dispose(); // Reuse instruction handles

    /* Add public <init> method, i.e. empty constructor
     */
 
View Full Code Here

        JavaClass jclass = classContext.getJavaClass();
        Method[] methodList = jclass.getMethods();

        for (Method method : methodList) {
            MethodGen methodGen = classContext.getMethodGen(method);
            if (methodGen == null) {
                continue;
            }

            // Prescreening - must have IF_ACMPEQ, IF_ACMPNE,
View Full Code Here

    }

    private void analyzeMethod(ClassContext classContext, final Method method) throws CFGBuilderException,
    DataflowAnalysisException {

        MethodGen methodGen = classContext.getMethodGen(method);
        if (methodGen == null) {
            return;
        }

        JavaClass jclass = classContext.getJavaClass();
        ConstantPoolGen cpg = classContext.getConstantPoolGen();

        // Enqueue all of the potential violations we find in the method.
        // Normally we'll only report the first highest-priority warning,
        // but if in relaxed mode or if REPORT_ALL_REF_COMPARISONS is set,
        // then we'll report everything.
        LinkedList<WarningWithProperties> refComparisonList = new LinkedList<WarningWithProperties>();
        LinkedList<WarningWithProperties> stringComparisonList = new LinkedList<WarningWithProperties>();


        comparedForEqualityInThisMethod = new HashMap<String,Integer>();
        CFG cfg = classContext.getCFG(method);
        DepthFirstSearch dfs = classContext.getDepthFirstSearch(method);
        ExceptionSetFactory exceptionSetFactory = classContext.getExceptionSetFactory(method);

        // Perform type analysis using our special type merger
        // (which handles String types specially, keeping track of
        // which ones appear to be dynamically created)
        RefComparisonTypeMerger typeMerger = new RefComparisonTypeMerger(bugReporter, exceptionSetFactory);
        RefComparisonTypeFrameModelingVisitor visitor = new RefComparisonTypeFrameModelingVisitor(methodGen.getConstantPool(),
                typeMerger, bugReporter);
        TypeAnalysis typeAnalysis = new SpecialTypeAnalysis(method, methodGen, cfg, dfs, typeMerger, visitor, bugReporter,
                exceptionSetFactory);
        TypeDataflow typeDataflow = new TypeDataflow(cfg, typeAnalysis);
        Profiler profiler = Global.getAnalysisCache().getProfiler();
View Full Code Here

      int out     = cp.addFieldref("java.lang.System", "out",
           "Ljava/io/PrintStream;");
      int println = cp.addMethodref("java.io.PrintStream", "println",
          "(Ljava/lang/Object;)V");
      MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, Type.VOID,
           new Type[] {
             new ObjectType("java.awt.event.ActionEvent")
           }, null, "actionPerformed", "foo", il, cp);

      // System.out.println("actionPerformed:" + event);
      il.append(new GETSTATIC(out));
      il.append(factory.createNew("java.lang.StringBuffer"));
      il.append(InstructionConstants.DUP);
      il.append(new PUSH(cp, "actionPerformed:"));
      il.append(factory.createInvoke("java.lang.StringBuffer", "<init>", Type.VOID,
             new Type[] {Type.STRING}, Constants.INVOKESPECIAL));

      il.append(new ALOAD(1));
      il.append(factory.createAppend(Type.OBJECT));
      il.append(new INVOKEVIRTUAL(println));
      il.append(InstructionConstants.RETURN);

      mg.stripAttributes(true);
      mg.setMaxStack();
      mg.setMaxLocals();
      cg.addMethod(mg.getMethod());

      byte[] bytes = cg.getJavaClass().getBytes();

      System.out.println("Uncompressed class: " + bytes.length);
View Full Code Here

    int label_counter = 0;

    out.println(".limit stack " + code.getMaxStack());
    out.println(".limit locals " + code.getMaxLocals());

    MethodGen           mg  = new MethodGen(_method, class_name, cp);
    InstructionList     il  = mg.getInstructionList();
    InstructionHandle[] ihs = il.getInstructionHandles();

    /* Pass 1: Give all referenced instruction handles a symbolic name, i.e. a
     * label.
     */
    map = new Hashtable();

    for(int i=0; i < ihs.length; i++) {
      if(ihs[i] instanceof BranchHandle) {
  BranchInstruction bi = (BranchInstruction)ihs[i].getInstruction();
 
  if(bi instanceof Select) { // Special cases LOOKUPSWITCH and TABLESWITCH
    InstructionHandle[] targets = ((Select)bi).getTargets();
   
    for(int j=0; j < targets.length; j++) {
        put(targets[j], "Label" + label_counter++ + ":");
    }
  }

  InstructionHandle ih = bi.getTarget();
  put(ih, "Label" + label_counter++ + ":");
      }
    }

    LocalVariableGen[] lvs = mg.getLocalVariables();
    for(int i=0; i < lvs.length; i++) {
      InstructionHandle ih = lvs[i].getStart();
      put(ih, "Label" + label_counter++ + ":");
      ih = lvs[i].getEnd();
      put(ih, "Label" + label_counter++ + ":")
    }
   
    CodeExceptionGen[] ehs = mg.getExceptionHandlers();
    for(int i=0; i < ehs.length; i++) {
      CodeExceptionGen  c  = ehs[i];
      InstructionHandle ih = c.getStartPC();

      put(ih, "Label" + label_counter++ + ":")
      ih = c.getEndPC();
      put(ih, "Label" + label_counter++ + ":")
      ih = c.getHandlerPC();
      put(ih, "Label" + label_counter++ + ":")
    }

    LineNumberGen[] lns = mg.getLineNumbers();
    for(int i=0; i < lns.length; i++) {
      InstructionHandle ih = lns[i].getInstruction();
      put(ih, ".line " + lns[i].getSourceLine());
    }
View Full Code Here

      Method[]        methods = clazz.getMethods();
      ConstantPoolGen cp      = new ConstantPoolGen(clazz.getConstantPool());

      for(int i=0; i < methods.length; i++) {
  if(!(methods[i].isAbstract() || methods[i].isNative())) {
    MethodGen mg       = new MethodGen(methods[i],
               clazz.getClassName(), cp);
    Method    stripped = removeNOPs(mg);
   
    if(stripped != null) {
        methods[i] = stripped; // Overwrite with stripped method
View Full Code Here

    ClassGen cg = new ClassGen(clazz);

    Method[] methods = clazz.getMethods();

    for(int i=0; i < methods.length; i++) {
      MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cg.getConstantPool());
      cg.replaceMethod(methods[i], mg.getMethod());
    }

    Field[] fields = clazz.getFields();

    for(int i=0; i < fields.length; i++) {
View Full Code Here

TOP

Related Classes of org.apache.bcel.generic.MethodGen

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.