Package org.apache.bcel.generic

Examples of org.apache.bcel.generic.MethodGen


    InstructionList patch  = new InstructionList();
    patch.append(new GETSTATIC(out));
    patch.append(new PUSH(cp, mesg));
    patch.append(new INVOKEVIRTUAL(println));
   
    MethodGen           mg  = new MethodGen(m, class_name, cp);
    InstructionList     il  = mg.getInstructionList();
    InstructionHandle[] ihs = il.getInstructionHandles();

    if(name.equals("<init>")) { // First let the super or other constructor be called
      for(int j=1; j < ihs.length; j++) {
  if(ihs[j].getInstruction() instanceof INVOKESPECIAL) {
    il.append(ihs[j], patch); // Should check: method name == "<init>"
    break;
  }
      }
    } else {
        il.insert(ihs[0], patch);
    }

    /* Stack size must be at least 2, since the println method takes 2 argument.
     */
    if(code.getMaxStack() < 2) {
        mg.setMaxStack(2);
    }

    m = mg.getMethod();

    il.dispose(); // Reuse instruction handles
   
    return m;
  }
View Full Code Here


  /**
   * Fifth pass, produce Java byte code.
   */
  public void byte_code(ClassGen class_gen, ConstantPoolGen cp) {
    MethodGen method=null;
    boolean main=false, ignore=false;
    String class_name = class_gen.getClassName();
    String fname      = name.getName();
    InstructionList il = new InstructionList();

    Type[] args = { new ArrayType(Type.STRING, 1) }; // default for `main'
    String[] arg_names = { "$argv" };

    if(fname.equals("main")) {
      method = new MethodGen(ACC_STATIC | ACC_PUBLIC,
           Type.VOID, args, arg_names,
           "main", class_name, il, cp);

      main = true;
    } else if(fname.equals("READ") || fname.equals("WRITE")) { // Do nothing
      ignore = true;
    } else {
      int    size  = argv.length;

      arg_names = new String[size];
      args      = new Type[size];

      for(int i = 0; i < size; i++) {
  args[i] = Type.INT;
  arg_names[i] =  argv[i].getName();
      }

      method = new MethodGen(ACC_STATIC | ACC_PRIVATE | ACC_FINAL,
           Type.INT, args, arg_names,
           fname, class_name, il, cp);

      LocalVariableGen[] lv = method.getLocalVariables();
      for(int i = 0; i < size; i++) {
  Variable entry = (Variable)env.get(arg_names[i]);
  entry.setLocalVariable(lv[i]);
      }

      method.addException("java.io.IOException");
    }

    if(!ignore) {
      body.byte_code(il, method, cp);

      if(main) {
  ObjectType e_type = new ObjectType("java.lang.Exception");
  InstructionHandle start = il.getStart(), end, handler, end_handler;
  LocalVariableGen exc = method.addLocalVariable("$e",
                   e_type,
                   null, null);
  int slot = exc.getIndex();

  il.append(InstructionConstants.POP); pop(); // Remove last element on stack
  end = il.append(InstructionConstants.RETURN); // Use instruction constants, if possible

  // catch
  handler = il.append(new ASTORE(slot)); // save exception object
  il.append(new GETSTATIC(cp.addFieldref("java.lang.System", "err",
                 "Ljava/io/PrintStream;")));
  il.append(new ALOAD(slot)); push(2);
  il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.PrintStream",
            "println",
            "(Ljava/lang/Object;)V")));
  pop(2);
  end_handler = il.append(InstructionConstants.RETURN);
  method.addExceptionHandler(start, end, handler, e_type);
  exc.setStart(handler); exc.setEnd(end_handler);
      } else {
        il.append(InstructionConstants.IRETURN); // Reuse object to save memory
    }

      method.removeNOPs(); // First optimization pass, provided by MethodGen
      optimizeIFs(il);     // Second optimization pass, application-specific
      method.setMaxStack(max_size);
      class_gen.addMethod(method.getMethod());
    }

    il.dispose(); // Dispose instruction handles for better memory utilization

    reset();
View Full Code Here

      ObjectType metadataType = new ObjectType(MBeanMetaData.class.getName());
      Type[] signature = new Type[]{metadataType, Type.STRING, new ArrayType(Type.STRING, 1), new ArrayType(Type.OBJECT, 1)};

      // Method definition
      MethodGen mthd = new MethodGen(Constants.ACC_PROTECTED, // Modifiers
                                     Type.OBJECT, // Return type
                                     signature, // Signature
                                     new String[]{"metadata", "method", "params", "args"}, // Parameter names
                                     "invokeImpl", // Method name
                                     clsName, // Class name
                                     implementation, // Implementation
                                     classGen.getConstantPool()); // Pool
      mthd.addException("java.lang.Throwable");

      // Now I should create the implementation
      InstructionFactory factory = new InstructionFactory(classGen);

      Method[] methods = metadata.getMBeanInterface().getMethods();
      List tests = new ArrayList();
      List catches = new ArrayList();
      for (int i = 0; i < methods.length; ++i)
      {
         Method method = methods[i];
         catches.addAll(generateDirectInvokeBranch(classGen, mthd, implementation, factory, metadata.getMBeanInterface().getName(), method, tests));
      }

      // To close the last branch, I must jump to super.invokeImpl(), so I need its first instruction here
      InstructionHandle invokeSuper = implementation.append(factory.createThis());
      for (int i = 0; i < tests.size(); ++i)
      {
         BranchInstruction branch = (BranchInstruction)tests.get(i);
         branch.setTarget(invokeSuper);
      }
      tests.clear();
      for (int i = 0; i < catches.size(); ++i)
      {
         BranchInstruction branch = (BranchInstruction)catches.get(i);
         branch.setTarget(invokeSuper);
      }
      catches.clear();

      //
      // return super.invokeImpl(metadata, method, params, args);
      //
      // Again, it's invokeImpl(super, args) instead of super.invokeImpl(args)
      // Use 'this' as first argument, and invokespecial instead of invokevirtual to call super
      // 'this' is created above, to close the last branch
      implementation.append(factory.createLoad(metadataType, 1));
      implementation.append(factory.createLoad(Type.STRING, 2));
      implementation.append(factory.createLoad(new ArrayType(Type.STRING, 1), 3));
      implementation.append(factory.createLoad(new ArrayType(Type.OBJECT, 1), 4));
      implementation.append(factory.createInvoke(BCELMBeanInvoker.class.getName(), "invokeImpl", Type.OBJECT, signature, Constants.INVOKESPECIAL));
      implementation.append(factory.createReturn(Type.OBJECT));

      mthd.setMaxStack();

      org.apache.bcel.classfile.Method method = mthd.getMethod();

      // Reuse instruction handles
      implementation.dispose();

      return method;
View Full Code Here

   
    Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!

    try{

      MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);

      icv.setMethodGen(mg);
       
      ////////////// DFA BEGINS HERE ////////////////
      if (! (mg.isAbstract() || mg.isNative()) ){ // IF mg HAS CODE (See pass 2)
       
        ControlFlowGraph cfg = new ControlFlowGraph(mg);

        // Build the initial frame situation for this method.
        Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
        if ( !mg.isStatic() ){
          if (mg.getName().equals(Constants.CONSTRUCTOR_NAME)){
            Frame._this = new UninitializedObjectType(new ObjectType(jc.getClassName()));
            f.getLocals().set(0, Frame._this);
          }
          else{
            Frame._this = null;
            f.getLocals().set(0, new ObjectType(jc.getClassName()));
          }
        }
        Type[] argtypes = mg.getArgumentTypes();
        int twoslotoffset = 0;
        for (int j=0; j<argtypes.length; j++){
          if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN){
            argtypes[j] = Type.INT;
          }
          f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
          if (argtypes[j].getSize() == 2){
            twoslotoffset++;
            f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
          }
        }
        circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
      }
    }
    catch (VerifierConstraintViolatedException ce){
      ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
      return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
View Full Code Here

   * @param joinpointPattern pattern of the joinpoints.
   */
  private void removeWrapper( int methodIdx, String joinpointPattern ) {
   
    // a method generator for the method
    MethodGen mGen =
      new MethodGen(
        targetClass.getMethods()[methodIdx],
        targetClass.getClassName(),
      constPoolGen );

    // a searcher to look for the joinpoints
    InstructionSearcher searcher =
      new InstructionSearcher( constPoolGen, mGen.getInstructionList() );
   
    // look for joinpoints
    List<CallMatch> targets =
      searcher.lookUpMethodCall(
          Pattern.compile( joinpointPattern ) );
View Full Code Here

    else {
   
      // no, so we install the wrapper first
     
      // get a method generator
      MethodGen mGen =
        new MethodGen(
          targetClass.getMethods()[methodIdx.intValue()],
          targetClass.getClassName(),
        constPoolGen );
     
      // get a searcher for the joinpoints
      InstructionSearcher searcher =
        new InstructionSearcher( constPoolGen, mGen.getInstructionList() );
           
      // look for joinpoints
      List<CallMatch> targets =
        searcher.lookUpMethodCall( joinpointPattern );
     
      // are there any joinpoints  matching the pattern in this methdod?
      if( !targets.isEmpty() ) {
       
        // yes, so we install a wrapper here
       
        // do we need to create the advice?
        if( advice == null ) {
          advice = (BeforeAfterAdvice)factory.getAdvice();
        }
       
        // do we have a joinpointPattern-map for this method yet?
        if( !callWrappers.containsKey( methodIdx ) ) {
          // create a map for all the joinpoinPattern->wrapper mappings
          // for this method
          callWrappers.put(
            methodIdx, new HashMap<String, CallWrapper>());
        }
       
        // create a wrapper
        CallWrapper cWrapper = new CallWrapper();
       
        Logger.info(
          "installing call wrapper for method %s " +
          "with index %s and pattern %s",
          mGen.getName(), methodIdx,
          joinpointPattern.pattern() );
       
        // install the wrapper to the method
        CallWrapperMethodPatcher mp =
          new CallWrapperMethodPatcher(
View Full Code Here

    ConstantPoolGen constPoolGen ) {

    // construct the method generator
        this.constPoolGen = constPoolGen;
       
    mGen = new MethodGen( m, javaClassName, constPoolGen );
    this.factory = new InstructionFactory( constPoolGen );
    this.iList = mGen.getInstructionList();
  }
View Full Code Here

       // build the getters instructions
       InstructionList iList = new InstructionList();
       InstructionFactory factory =
           new InstructionFactory(cGen);
      
       MethodGen mGen =
           new MethodGen(
               Constants.ACC_PRIVATE,
               interfaceType,
               Type.NO_ARGS,
               new String[] {},
               fieldNameBuffer.toString(),
               cGen.getClassName(),
               iList,
               constPoolGen );
      
       // a local variable
       iList.append( InstructionFactory.createLoad( Type.OBJECT, 0 ) );
       // load the member variable
       iList.append(
           factory.createFieldAccess(
               cGen.getClassName(),
               fieldName,
               interfaceType,
               Constants.GETFIELD  ) );
      
       // test for non null of the member variable          
       BranchInstruction bi =
           InstructionFactory.createBranchInstruction(
                   Constants.IFNONNULL, null );
      
       iList.append( bi );
      
       // create the delegate
       iList.append( InstructionFactory.createLoad( Type.OBJECT, 0 ) );
      
       iList.append( factory.createNew( implClass.getName() ) );
       iList.append( InstructionConstants.DUP );
       iList.append(
           factory.createInvoke(
               implClass.getName(),
               Constants.CONSTRUCTOR_NAME,
               Type.VOID, Type.NO_ARGS,
               Constants.INVOKESPECIAL ) );
      
       // use a factory if the implementation class is a factory
       if( MixInImplementationFactory.class.isAssignableFrom( implClass ) ) {

           iList.append(
               factory.createInvoke(
                       implClass.getName(),
                       "getInstance",
                       Type.OBJECT,
                       Type.NO_ARGS, Constants.INVOKEVIRTUAL ) );
          
           iList.append(
               factory.createCheckCast
                   new ObjectType( interfaceClass.getName() ) ) );
          
       }
       // store the created delgate object
       iList.append(
           factory.createFieldAccess(
               cGen.getClassName(),
               fieldName,
               interfaceType,
               Constants.PUTFIELD) );
      
       // load the delegate and return it
       InstructionHandle loadInstruction =
           iList.append( InstructionFactory.createLoad( Type.OBJECT, 0 ) );
      
       bi.setTarget( loadInstruction );
      
       iList.append(
               factory.createFieldAccess(
                   cGen.getClassName(),
                   fieldName,
                   interfaceType,
                   Constants.GETFIELD) );
      
       iList.append( InstructionFactory.createReturn( Type.OBJECT ) );

       mGen.setMaxStack();
       mGen.setMaxLocals();
       cGen.addMethod( mGen.getMethod() );
       iList.dispose();
      
       return fieldNameBuffer.toString();
   }
View Full Code Here

       InstructionList iList = new InstructionList();
      
       InstructionFactory factory =
           new InstructionFactory(cGen);
      
       MethodGen mGen =
           new MethodGen(
               Constants.ACC_PUBLIC,
               Type.getReturnType( sig ),
               Type.getArgumentTypes( sig ),
               argNames,m.getName(),
               cGen.getClassName(),
               iList,
               constPoolGen );
      
       // get the delegate
       iList.append( InstructionFactory.createLoad( Type.OBJECT, 0 ) );

       iList.append(
           factory.createInvoke(
               cGen.getClassName(),
               getterMethodName,
               Type.getType( interfaceClass ),
               Type.NO_ARGS,
               Constants.INVOKESPECIAL ) );
      
       // load the argument on to the stack
       int argIdx =1;
       for( Type t : Type.getArgumentTypes( sig ) ) {
          
           iList.append( InstructionFactory.createLoad( t, argIdx++ ) );
          
           if( Reflection.isCat2Type( t ) ) {
               argIdx++;
           }
          
       }

       // do the delegation
       iList.append(
           factory.createInvoke(
               interfaceClass.getName(),
               m.getName(),
               Type.getReturnType( sig ),
               Type.getArgumentTypes( sig ),
               Constants.INVOKEINTERFACE ) );
      
       // return the result from the delegation
       iList.append( InstructionFactory.createReturn( Type.getReturnType( sig ) ) );
      
       mGen.setMaxStack();
       mGen.setMaxLocals();
       cGen.addMethod( mGen.getMethod() );
       iList.dispose();
   }
View Full Code Here

    {
        InstructionList il = null;
        InstructionFactory factory = new InstructionFactory(newClass);
        Method clinit = null;
        InstructionList ilOriginal = null;
        MethodGen methodGen = null;

        MethodGen methodGenOriginal = null;
        {
            Method methods[] = newClass.getMethods();
            for (int i = 0; i < methods.length; i++)
            {
                if (methods[i].getName().equals(Constants.STATIC_INITIALIZER_NAME))
                {
                    clinit = methods[i];
                    methodGenOriginal = new MethodGen(clinit, className, constantPoolGen);
                    ilOriginal = methodGenOriginal.getInstructionList();
                    break;
                }
            }
        }

        il = new InstructionList();
        methodGen = new MethodGen(Constants.ACC_STATIC, Type.VOID, Type.NO_ARGS, null, Constants.STATIC_INITIALIZER_NAME,
            className, il, constantPoolGen);

        if (ilOriginal != null)
        {
            // remove return instruction and add to top of static initialization block
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.