Package org.jboss.weaver.retro

Source Code of org.jboss.weaver.retro.WeaverRetroJdk14

/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.weaver.retro;

import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.annotation.Inherited;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CodeConverter;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ClassFileWriter;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Opcode;
import javassist.bytecode.annotation.Annotation;
import javassist.expr.ExprEditor;

import org.jboss.weaver.ClassFileInfo;
import org.jboss.weaver.Weaver;

/**
* Weaver configuration for converting class files to jdk1.4
*
* @author pgier
*
*/
public class WeaverRetroJdk14 extends Weaver
{
  
   private static Logger log = Logger.getLogger(WeaverRetroJdk14.class.getName());
  
   /**
    * Default resource from which to load the class renames mapping.
    */
   public final String DEFAULT_CLASS_RENAMES_RESOURCE = "/org/jboss/weaver/retro/class-renames.properties";
  
   /**
    *  This method should be called after the classpath
    *  has been set.
    */
   public void init() {
      initClassRenames();
     
      // Set up default converters and editors
      ClassPool pool = ClassPool.getDefault();
      try {
         if (this.getClasspath() != null) {
            pool.appendPathList(this.getClasspath());
         }
        
         addCodeConverter(new AutoboxCodeConverter(pool));
      } catch (NotFoundException nfe) {
         log.severe("Unable to construct default code converter");
         nfe.printStackTrace();
      } catch (CannotCompileException cce) {
         log.severe("Unable to construct default code converter");
         cce.printStackTrace();
      }
     
      addExprEditor(new ClassRedirectEditor());
   }
  
   /**
    * Initialize the classes that need to be renamed.
    */
   public void initClassRenames() {
      InputStream is = this.getClass().getResourceAsStream(DEFAULT_CLASS_RENAMES_RESOURCE);
      this.loadClassRenames(is);
   }

   public boolean doWeave(ClassLoader cl, ClassFileInfo info) throws BadBytecode, CannotCompileException
   {
      CtClass clazz = info.getClazz();
      ClassFile file = clazz.getClassFile();
      log.fine("weaving: " + info.getClassName());
     
      // Already done
      if (file.getMajorVersion() <= 48)
         return false;

      // Set the major version
      file.setMajorVersion(48);

      // Rename known classes
      file.renameClass(getClassRenames());

      ConstPool constPool = file.getConstPool();

      // Rename classes with + to have $
      HashMap<String, String> mapClasses = new HashMap<String, String>();
     
      for (String name : (Set<String>) constPool.getClassNames())
      {
         if (name.indexOf('+') != -1) {
            mapClasses.put(name, name.replace('+', '$'));
         }
      }
      if (mapClasses.size() != 0) {
         constPool.renameClass(mapClasses);
      }

      // Replace LDC/LDC_W
      for (MethodInfo method : (List<MethodInfo>) file.getMethods()) {
         rewriteLDC(constPool, method);
      }

      if (clazz.isAnnotation())
      {
         rewriteSystemAnnotations(file);
      }

      // Run the converters
      for (CodeConverter converter : this.getCodeConverters())
      {
         clazz.instrument(converter);
      }

      // Run the editors
      for (ExprEditor editor : this.getExprEditors())
      {
         clazz.instrument(editor);
      }

      if (log.isLoggable(Level.FINEST))
      {
         PrintWriter out = new PrintWriter(System.out, true);
         out.println("*** constant pool ***");
         file.getConstPool().print(out);
         out.println();
         out.println("*** members ***");
         ClassFileWriter.print(file, out);
      }
     
      return true;
   }


   /**
    * This rewrites the load constant ClassInfo
    * to be Class.forName()
    *
    * @param constPool the constant pool
    * @param method the method
    * @throws Exception for any error
    */
   public static void rewriteLDC(ConstPool constPool, MethodInfo method) throws BadBytecode
   {
      CodeAttribute code = method.getCodeAttribute();
      if (code == null)
         return;
      CodeIterator iterator = code.iterator();
      while (iterator.hasNext())
      {
         int index = iterator.next();
         int op = iterator.byteAt(index);

         if (op == Opcode.LDC || op == Opcode.LDC_W)
         {
            int index0 = iterator.byteAt(index + 1);
            int constIndex = index0;
            if (op == Opcode.LDC_W)
            {
               int index1 = iterator.byteAt(index + 2);
               constIndex = (index0 << 8) + index1;
            }
            if (7 == constPool.getTag(constIndex))
            {
               String className = constPool.getClassInfo(constIndex);
               int theClassName = constPool.addStringInfo(className.replace('/', '.'));
               if (op == Opcode.LDC_W)
               {
                  int b0 = theClassName >>> 8;
                  int b1 = theClassName & 0x0FF;
                  iterator.writeByte(b0, index + 1);
                  iterator.writeByte(b1, index + 2);
               }
               else
               {
                  iterator.writeByte(theClassName, index + 1);
               }
               int classClass = constPool.addClassInfo("java/lang/Class");
               int descriptor = constPool.addMethodrefInfo(classClass, "forName",
                     "(Ljava/lang/String;)Ljava/lang/Class;");
               iterator.insert(new byte[]
               {(byte) Opcode.INVOKESTATIC, (byte) (descriptor >>> 8), (byte) descriptor});
            }
         }
      }
   }

   private void rewriteSystemAnnotations(ClassFile file)
   {
      AnnotationsAttribute visible = (AnnotationsAttribute) file.getAttribute(AnnotationsAttribute.visibleTag);
      if (visible != null)
      {
         //Only bother with the @Inherited annotation for now, as this is the main thing affecting the container tests
         Annotation[] annotations = visible.getAnnotations();
         boolean changed = false;
         for (int i = 0; i < annotations.length; i++)
         {
            if (annotations[i].getTypeName().equals(Inherited.class.getName()))
            {
               annotations[i] = new Annotation("org/jboss/lang/annotation/Inherited", file.getConstPool());
               changed = true;
            }
         }
         if (changed)
         {
            visible.setAnnotations(annotations);
         }
      }
   }
  
}
TOP

Related Classes of org.jboss.weaver.retro.WeaverRetroJdk14

TOP
Copyright © 2018 www.massapi.com. 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.