List of usage examples for org.objectweb.asm Opcodes ACC_STATIC
int ACC_STATIC
To view the source code for org.objectweb.asm Opcodes ACC_STATIC.
Click Source Link
From source file:org.codehaus.groovy.transform.trait.TraitComposer.java
License:Apache License
private static void createForwarderMethod(ClassNode trait, ClassNode targetNode, MethodNode helperMethod, MethodNode originalMethod, ClassNode helperClassNode, Map<String, ClassNode> genericsSpec, Parameter[] helperMethodParams, Parameter[] traitMethodParams, Parameter[] forwarderParams, ArgumentListExpression helperMethodArgList, SourceUnit unit) { MethodCallExpression mce = new MethodCallExpression(new ClassExpression(helperClassNode), helperMethod.getName(), helperMethodArgList); mce.setImplicitThis(false);/*from w ww. ja va 2 s . c o m*/ genericsSpec = GenericsUtils.addMethodGenerics(helperMethod, genericsSpec); ClassNode[] exceptionNodes = correctToGenericsSpecRecurse(genericsSpec, copyExceptions(helperMethod.getExceptions())); ClassNode fixedReturnType = correctToGenericsSpecRecurse(genericsSpec, helperMethod.getReturnType()); boolean noCastRequired = genericsSpec.isEmpty() || fixedReturnType.getName().equals(ClassHelper.VOID_TYPE.getName()); Expression forwardExpression = noCastRequired ? mce : new CastExpression(fixedReturnType, mce); // we could rely on the first parameter name ($static$self) but that information is not // guaranteed to be always present boolean isHelperForStaticMethod = helperMethodParams[0].getOriginType().equals(ClassHelper.CLASS_Type); if (helperMethod.isPrivate() && !isHelperForStaticMethod) { // GROOVY-7213: do not create forwarder for private methods return; } int modifiers = helperMethod.getModifiers(); if (!isHelperForStaticMethod) { modifiers ^= Opcodes.ACC_STATIC; } MethodNode forwarder = new MethodNode(helperMethod.getName(), modifiers, fixedReturnType, forwarderParams, exceptionNodes, new ExpressionStatement(forwardExpression)); List<AnnotationNode> copied = new LinkedList<>(); List<AnnotationNode> notCopied = Collections.emptyList(); // at this point, should *always* stay empty GeneralUtils.copyAnnotatedNodeAnnotations(helperMethod, copied, notCopied); if (!copied.isEmpty()) { forwarder.addAnnotations(copied); } if (originalMethod != null) { GenericsType[] newGt = GenericsUtils.applyGenericsContextToPlaceHolders(genericsSpec, originalMethod.getGenericsTypes()); newGt = removeNonPlaceHolders(newGt); forwarder.setGenericsTypes(newGt); } else { // null indicates a static method which may still need generics correction GenericsType[] genericsTypes = helperMethod.getGenericsTypes(); if (genericsTypes != null) { Map<String, ClassNode> methodSpec = GenericsUtils.addMethodGenerics(helperMethod, Collections.emptyMap()); GenericsType[] newGt = GenericsUtils.applyGenericsContextToPlaceHolders(methodSpec, helperMethod.getGenericsTypes()); forwarder.setGenericsTypes(newGt); } } // add a helper annotation indicating that it is a bridge method AnnotationNode bridgeAnnotation = new AnnotationNode(Traits.TRAITBRIDGE_CLASSNODE); bridgeAnnotation.addMember("traitClass", new ClassExpression(trait)); bridgeAnnotation.addMember("desc", new ConstantExpression( BytecodeHelper.getMethodDescriptor(helperMethod.getReturnType(), traitMethodParams))); forwarder.addAnnotation(bridgeAnnotation); MethodNode existingMethod = findExistingMethod(targetNode, forwarder); if (existingMethod != null) { if (!forwarder.isStatic() && existingMethod.isStatic()) { // found an existing static method that is going to conflict with interface unit.addError(createException(trait, targetNode, forwarder, existingMethod)); return; } } if (!shouldSkipMethod(targetNode, forwarder.getName(), forwarderParams)) { targetNode.addMethod(forwarder); } createSuperForwarder(targetNode, forwarder, genericsSpec); }
From source file:org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.java
License:Open Source License
/** * Build JDT TypeDeclarations for the groovy type declarations that were parsed from the source file. *///from w w w .j a v a 2 s. com private void createTypeDeclarations(ModuleNode moduleNode) { List<ClassNode> moduleClassNodes = moduleNode.getClasses(); List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>(); Map<ClassNode, TypeDeclaration> fromClassNodeToDecl = new HashMap<ClassNode, TypeDeclaration>(); char[] mainName = toMainName(compilationResult.getFileName()); boolean isInner = false; List<ClassNode> classNodes = null; classNodes = moduleClassNodes; Map<ClassNode, List<TypeDeclaration>> innersToRecord = new HashMap<ClassNode, List<TypeDeclaration>>(); for (ClassNode classNode : classNodes) { if (!classNode.isPrimaryClassNode()) { continue; } GroovyTypeDeclaration typeDeclaration = new GroovyTypeDeclaration(compilationResult, classNode); typeDeclaration.annotations = transformAnnotations(classNode.getAnnotations()); // FIXASC duplicates code further down, tidy this up if (classNode instanceof InnerClassNode) { InnerClassNode innerClassNode = (InnerClassNode) classNode; ClassNode outerClass = innerClassNode.getOuterClass(); String outername = outerClass.getNameWithoutPackage(); String newInner = innerClassNode.getNameWithoutPackage().substring(outername.length() + 1); typeDeclaration.name = newInner.toCharArray(); isInner = true; } else { typeDeclaration.name = classNode.getNameWithoutPackage().toCharArray(); isInner = false; } // classNode.getInnerClasses(); // classNode. boolean isInterface = classNode.isInterface(); int mods = classNode.getModifiers(); if ((mods & Opcodes.ACC_ENUM) != 0) { // remove final mods = mods & ~Opcodes.ACC_FINAL; } // FIXASC should this modifier be set? // mods |= Opcodes.ACC_PUBLIC; // FIXASC should not do this for inner classes, just for top level types // FIXASC does this make things visible that shouldn't be? mods = mods & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED); if (!isInner) { if ((mods & Opcodes.ACC_STATIC) != 0) { mods = mods & ~(Opcodes.ACC_STATIC); } } typeDeclaration.modifiers = mods & ~(isInterface ? Opcodes.ACC_ABSTRACT : 0); if (!(classNode instanceof InnerClassNode)) { if (!CharOperation.equals(typeDeclaration.name, mainName)) { typeDeclaration.bits |= ASTNode.IsSecondaryType; } } fixupSourceLocationsForTypeDeclaration(typeDeclaration, classNode); if (classNode.getGenericsTypes() != null) { GenericsType[] genericInfo = classNode.getGenericsTypes(); // Example case here: Foo<T extends Number & I> // the type parameter is T, the 'type' is Number and the bounds for the type parameter are just the extra bound // I. typeDeclaration.typeParameters = new TypeParameter[genericInfo.length]; for (int tp = 0; tp < genericInfo.length; tp++) { TypeParameter typeParameter = new TypeParameter(); typeParameter.name = genericInfo[tp].getName().toCharArray(); ClassNode[] upperBounds = genericInfo[tp].getUpperBounds(); if (upperBounds != null) { // FIXASC (M3) Positional info for these references? typeParameter.type = createTypeReferenceForClassNode(upperBounds[0]); typeParameter.bounds = (upperBounds.length > 1 ? new TypeReference[upperBounds.length - 1] : null); for (int b = 1, max = upperBounds.length; b < max; b++) { typeParameter.bounds[b - 1] = createTypeReferenceForClassNode(upperBounds[b]); typeParameter.bounds[b - 1].bits |= ASTNode.IsSuperType; } } typeDeclaration.typeParameters[tp] = typeParameter; } } boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) != 0; configureSuperClass(typeDeclaration, classNode.getSuperClass(), isEnum); configureSuperInterfaces(typeDeclaration, classNode); typeDeclaration.methods = createMethodAndConstructorDeclarations(classNode, isEnum, compilationResult); typeDeclaration.fields = createFieldDeclarations(classNode); typeDeclaration.properties = classNode.getProperties(); if (classNode instanceof InnerClassNode) { InnerClassNode innerClassNode = (InnerClassNode) classNode; ClassNode outerClass = innerClassNode.getOuterClass(); String outername = outerClass.getNameWithoutPackage(); String newInner = innerClassNode.getNameWithoutPackage().substring(outername.length() + 1); typeDeclaration.name = newInner.toCharArray(); // Record that we need to set the parent of this inner type later List<TypeDeclaration> inners = innersToRecord.get(outerClass); if (inners == null) { inners = new ArrayList<TypeDeclaration>(); innersToRecord.put(outerClass, inners); } inners.add(typeDeclaration); } else { typeDeclarations.add(typeDeclaration); } fromClassNodeToDecl.put(classNode, typeDeclaration); } // For inner types, now attach them to their parents. This was not done earlier as sometimes the types are processed in // such an order that inners are dealt with before outers for (Map.Entry<ClassNode, List<TypeDeclaration>> innersToRecordEntry : innersToRecord.entrySet()) { TypeDeclaration outerTypeDeclaration = fromClassNodeToDecl.get(innersToRecordEntry.getKey()); // Check if there is a problem locating the parent for the inner if (outerTypeDeclaration == null) { throw new GroovyEclipseBug( "Failed to find the type declaration for " + innersToRecordEntry.getKey().getName()); } List<TypeDeclaration> newInnersList = innersToRecordEntry.getValue(); outerTypeDeclaration.memberTypes = newInnersList.toArray(new TypeDeclaration[newInnersList.size()]); } types = typeDeclarations.toArray(new TypeDeclaration[typeDeclarations.size()]); }
From source file:org.coldswap.asm.field.PrivateStaticFieldReplacer.java
License:Open Source License
public byte[] replace() { final ClassNode cn = new ClassNode(Opcodes.ASM5); ClassReader cr = new ClassReader(bytes); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); cr.accept(cn, 0);/*from www. j a va2 s .c o m*/ // get a list of public/protected/package/private fields but exclude // inherited fields. Field[] refFields = aClass.getDeclaredFields(); List asmFields = cn.fields; Iterator iterator = asmFields.iterator(); while (iterator.hasNext()) { final FieldNode fNode = (FieldNode) iterator.next(); int privateStatic = Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE; // search only for private static fields if ((fNode.access == privateStatic)) { // check if this field exist in the old loaded class // and if not proceed with the trick. boolean foundIt = false; for (Field refField : refFields) { if (fNode.name.equals(refField.getName())) { if (fNode.desc.equals(Type.getType(refField.getType()).getDescriptor())) { foundIt = true; break; } } } if (!foundIt) { String contClass = cn.name.substring(cn.name.lastIndexOf("/") + 1); String className = TransformerNameGenerator.getPrivateStaticFieldClassName(contClass, fNode.name); // remove the static reference from <clinit> InsnList insnList = cleanClInit(cn, fNode); // create a new class that contains the field // before anything change the field access to public static so that it can be referenced // from other classes. fNode.access = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; byte[] newBClass = ByteCodeGenerator.newFieldClass(cn, fNode, insnList, classPackage + className); try { String cp = ClassUtil.getClassPath(aClass); ByteCodeClassWriter.setClassPath(cp); ByteCodeClassWriter.writeClass(className, newBClass); } catch (IOException e) { logger.warning(e.toString()); } iterator.remove(); // replace every reference replaceReferences(cn, fNode); } } } cn.accept(cw); return cw.toByteArray(); }
From source file:org.coldswap.asm.field.ProtectedStaticFieldReplacer.java
License:Open Source License
public byte[] replace() { final ClassNode cn = new ClassNode(Opcodes.ASM5); ClassReader cr = new ClassReader(bytes); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); cr.accept(cn, 0);/* ww w. j a va2 s. c o m*/ // get a list of public/protected fields. Field[] refFields = aClass.getDeclaredFields(); List asmFields = getFields(cn); Iterator iterator = asmFields.iterator(); while (iterator.hasNext()) { final FieldNode fNode = (FieldNode) iterator.next(); int protectedStatic = Opcodes.ACC_STATIC | Opcodes.ACC_PROTECTED; // search only for protected static fields if ((fNode.access == protectedStatic)) { // check if this field exist in the old loaded class // and if not proceed with the trick. boolean foundIt = false; for (Field refField : refFields) { if (fNode.name.equals(refField.getName())) { if (fNode.desc.equals(Type.getType(refField.getType()).getDescriptor())) { foundIt = true; break; } } } if (!foundIt) { // register a public static reference replacer String contClass = cn.name.substring(cn.name.lastIndexOf("/") + 1); String className = TransformerNameGenerator.getProtectedStaticFieldClassName(contClass, fNode.name); // make field access as public static fNode.access = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; replacerManager.registerFieldReferenceReplacer(new ProtectedStaticFieldReferenceReplacer( contClass, fNode, classPackage + className, contClass)); // remove the static reference from <clinit> InsnList insnList = cleanClInit(cn, fNode, true); // because the field might be inherited from superclass we need to copy // the initializer from the parent. if ((insnList == null) || (insnList.size() > 0)) { insnList = inheritedInitCode.get(fNode); } // create a new class that contains the field // before anything change the field access to public static so that it can be referenced // from other classes. fNode.access = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; byte[] newBClass = ByteCodeGenerator.newFieldClass(cn, fNode, insnList, classPackage + className); try { String cp = ClassUtil.getClassPath(aClass); ByteCodeClassWriter.setClassPath(cp); ByteCodeClassWriter.writeClass(className, newBClass); } catch (IOException e) { logger.warning(e.toString()); } iterator.remove(); // replace every reference replaceReferences(cn, fNode); } } } cn.accept(cw); return cw.toByteArray(); }
From source file:org.coldswap.asm.field.ProtectedStaticFieldReplacer.java
License:Open Source License
/** * Returns an array of fields that where declared in this class. In * addition there are also the protected fields that were inherited. * * @param classNode {@link ClassNode} containing the new class version. * @return a list of all fields including the inherited fields. *//*from w w w . j av a 2 s. c o m*/ private List<FieldNode> getFields(ClassNode classNode) { List<FieldNode> toRet = classNode.fields; // get inherited package fields try { String superName = classNode.superName; // filter superclasses for (String pack : ClassUtil.skipTransforming) { if (superName.startsWith(pack)) { return toRet; } } Class<?> c = Class.forName(superName); String path = ClassUtil.getClassPath(c); path = path + ClassUtil.fileSeparator + superName + ".class"; byte[] clazz = ByteCodeClassLoader.loadClassBytes(path); ClassNode cNode = new ClassNode(Opcodes.ASM5); ClassReader cr = new ClassReader(clazz); cr.accept(cNode, 0); List<FieldNode> superFields = cNode.fields; for (FieldNode fieldNode : superFields) { if (fieldNode.access == (Opcodes.ACC_STATIC | Opcodes.ACC_PROTECTED)) { toRet.add(fieldNode); InsnList code = cleanClInit(cNode, fieldNode, false); inheritedInitCode.put(fieldNode, code); } } } catch (ClassNotFoundException e) { logger.warning(e.toString()); } return toRet; }
From source file:org.coldswap.asm.field.PublicStaticFieldReplacer.java
License:Open Source License
public byte[] replace() { final ClassNode cn = new ClassNode(Opcodes.ASM5); ClassReader cr = new ClassReader(bytes); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); cr.accept(cn, 0);//w w w. j av a2 s. co m // get a list of public/protected/package/private fields but exclude // inherited fields. Field[] refFields = aClass.getDeclaredFields(); List asmFields = cn.fields; Iterator iterator = asmFields.iterator(); while (iterator.hasNext()) { final FieldNode fNode = (FieldNode) iterator.next(); int publicStatic = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC; //int publicStaticFinal = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; // search only for public static fields if ((fNode.access == publicStatic)) { // check if this field exist in the old loaded class // and if not proceed with the trick. boolean foundIt = false; for (Field refField : refFields) { if (fNode.name.equals(refField.getName())) { if (fNode.desc.equals(Type.getType(refField.getType()).getDescriptor())) { foundIt = true; break; } } } if (!foundIt) { // register a public static reference replacer String contClass = cn.name.substring(cn.name.lastIndexOf("/") + 1); String className = TransformerNameGenerator.getPublicStaticFieldClassName(contClass, fNode.name); replacerManager.registerFieldReferenceReplacer( new PublicStaticFieldReferenceReplacer(contClass, fNode, classPackage + className)); // remove the static reference from <clinit> InsnList insnList = cleanClInit(cn, fNode); // create a new class that contains the field byte[] newBClass = ByteCodeGenerator.newFieldClass(cn, fNode, insnList, classPackage + className); try { String cp = ClassUtil.getClassPath(aClass); ByteCodeClassWriter.setClassPath(cp); ByteCodeClassWriter.writeClass(className, newBClass); } catch (IOException e) { logger.warning(e.toString()); } iterator.remove(); // replace every reference replaceReferences(cn, fNode); } } } cn.accept(cw); return cw.toByteArray(); }
From source file:org.coldswap.transformer.ClInitTransformer.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from w w w. j a v a 2s. c o m*/ public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException { if (s != null && !"".equals(s)) { for (String pack : ClassUtil.skipTransforming) { if (s.startsWith(pack)) { return bytes; } } ClassNode cn = new ClassNode(Opcodes.ASM5); ClassReader cr = new ClassReader(bytes); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); // create adapter for method insertion. cr.accept(cn, 0); // insert <clinit>V if it is not inserted List methods = cn.methods; boolean clInitFound = false; for (MethodNode methodNode : (List<MethodNode>) methods) { if ("<clinit>".equals(methodNode.name)) { clInitFound = true; } } if (!clInitFound) { MethodNode mn = new MethodNode(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); InsnList insnList = mn.instructions; insnList.add(new LabelNode()); insnList.add(new InsnNode(Opcodes.RETURN)); cn.methods.add(mn); } cn.accept(cw); byte[] toRet = cw.toByteArray(); if (toRet != null) { logger.info("Successful transformation!"); return toRet; } else { logger.severe("Could not transform class"); return bytes; } } return bytes; }
From source file:org.coldswap.util.ByteCodeGenerator.java
License:Open Source License
/** * Creates a new class containing the new static field. * * @param classNode containing the old class. * @param fieldNode containing the old field. * @param initInstructions a list of instructions that goes into <clinit>. * @param className the name of the new class to be generated. * @return an array of bytes which builds the new class. *//* w w w. j a v a 2 s . c o m*/ @SuppressWarnings("unchecked") public static byte[] newFieldClass(ClassNode classNode, FieldNode fieldNode, InsnList initInstructions, String className) { ClassNode newClass = new ClassNode(); newClass.version = classNode.version; newClass.access = Opcodes.ACC_PUBLIC; newClass.signature = "L" + className + ";"; newClass.name = className; newClass.superName = "java/lang/Object"; newClass.fields.add( new FieldNode(fieldNode.access, fieldNode.name, fieldNode.desc, fieldNode.desc, fieldNode.value)); if (initInstructions != null) { if (initInstructions.size() > 0) { MethodNode mn = new MethodNode(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); InsnList il = mn.instructions; il.add(new LabelNode()); il.add(initInstructions); il.add(new FieldInsnNode(Opcodes.PUTSTATIC, className, fieldNode.name, fieldNode.desc)); il.add(new InsnNode(Opcodes.RETURN)); newClass.methods.add(mn); } } ClassWriter newCWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); newClass.accept(newCWriter); return newCWriter.toByteArray(); }
From source file:org.compass.core.config.binding.metadata.AsmClassMetaData.java
License:Apache License
public void visitInnerClass(String name, String outerName, String innerName, int access) { if (outerName != null && this.className.equals(ClassUtils.convertResourcePathToClassName(name))) { this.enclosingClassName = ClassUtils.convertResourcePathToClassName(outerName); this.independentInnerClass = ((access & Opcodes.ACC_STATIC) != 0); }/*from w w w .j a v a 2 s . c o m*/ }
From source file:org.eclipse.objectteams.otredyn.bytecode.AbstractBoundClass.java
License:Open Source License
/** * Number of outer instances required in an instance of this class. */// w w w . j a va 2 s .c o m public int nestingDepth() { parseBytecode(); if ((this.modifiers & Opcodes.ACC_STATIC) != 0) return 0; if (this.enclosingClass != null) return this.enclosingClass.nestingDepth() + 1; return 0; }