Java Code Examples for org.objectweb.asm.ClassReader#accept()

The following examples show how to use org.objectweb.asm.ClassReader#accept() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CyclicReferencesTestTest.java    From development with Apache License 2.0 6 votes vote down vote up
private void assertFiledTypes(final Class<?> type, String... expected)
        throws IOException {
    final ClassReader reader = new ClassReader(type.getName());
    final Set<String> actual = new HashSet<String>();
    reader.accept(new EmptyVisitor() {
        @Override
        public FieldVisitor visitField(int access, String name,
                String desc, String signature, Object value) {
            if ((access & Opcodes.ACC_SYNTHETIC) == 0) {
                if (signature == null) {
                    signature = desc;
                }
                cyclicRefsTest.getTypesFromSignature(signature, actual);
            }
            return null;
        }
    }, 0);
    assertEquals(new HashSet<String>(Arrays.asList(expected)), actual);
}
 
Example 2
Source File: TestUtils.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Load up a ZIP resource from the classpath and generate a {@link ClassNode} for each file with a class extension in that ZIP.
 * Behaviour is ZIP or classes within are not a parseable.
 * @param path path of ZIP resource
 * @return {@link ClassNode} representation of class files in ZIP
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if any IO error occurs
 * @throws IllegalArgumentException if {@code path} cannot be found
 */
public static Map<String, ClassNode> readZipResourcesAsClassNodes(String path) throws IOException {
    Validate.notNull(path);
    
    Map<String, byte[]> files = readZipFromResource(path);
    Map<String, ClassNode> ret = new LinkedHashMap<>();
    for (Entry<String, byte[]> entry : files.entrySet()) {
        if (!entry.getKey().toLowerCase().endsWith(".class")) {
            continue;
        }
        
        ClassReader cr = new ClassReader(new ByteArrayInputStream(entry.getValue()));
        ClassNode classNode = new ClassNode();
        cr.accept(classNode, 0);
        
        ret.put(entry.getKey(), classNode);
    }

    return ret;
}
 
Example 3
Source File: StringFogClassInjector.java    From StringFog with Apache License 2.0 6 votes vote down vote up
private void processClass(InputStream classIn, OutputStream classOut) throws IOException {
    ClassReader cr = new ClassReader(classIn);
    // skip module-info class, fixed #38
    if ("module-info".equals(cr.getClassName())) {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = classIn.read(buffer)) >= 0) {
            classOut.write(buffer, 0, read);
        }
    } else {
        ClassWriter cw = new ClassWriter(0);
        ClassVisitor cv = ClassVisitorFactory.create(mStringFogImpl, mMappingPrinter, mFogPackages,
                mKey, mFogClassName, cr.getClassName() , cw);
        cr.accept(cv, 0);
        classOut.write(cw.toByteArray());
        classOut.flush();
    }
}
 
Example 4
Source File: Java7CompatibilityTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a class implementing interfaces with bridge methods redeclares those bridges. This
 * is behavior of javac that we rely on.
 */
@Test
public void testConcreteClassRedeclaresBridges() throws Exception {
  ClassReader reader = new ClassReader(Impl.class.getName());
  ClassTester tester = new ClassTester();
  reader.accept(new Java7Compatibility(tester, null, null), 0);
  assertThat(tester.version).isEqualTo(Opcodes.V1_7);
  assertThat(tester.bridgeMethods).isEqualTo(2);
}
 
Example 5
Source File: PatchGuiGameOver.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiGameOver (%s)", Names.guiGameOver.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 6
Source File: MaxLocalFinderCache.java    From Concurnas with MIT License 5 votes vote down vote up
public HashMap<String, Integer> getMaxlocalMap(String name, ClassReader cr){
	HashMap<String, Integer> ret = localMaps.get(name);
	if(null == ret){
		MaxLocalFinder mlf = new MaxLocalFinder(name);
		cr.accept(mlf, ClassReader.EXPAND_FRAMES);
		ret = mlf.maxlocalMap;;
		localMaps.put(name, ret);
	}
	return ret;
}
 
Example 7
Source File: TryWithResourcesRewriterTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static DesugaredThrowableMethodCallCounter countDesugaredThrowableMethodCalls(
    Class<?> klass) {
  try {
    ClassReader reader = new ClassReader(klass.getName());
    DesugaredThrowableMethodCallCounter counter =
        new DesugaredThrowableMethodCallCounter(klass.getClassLoader());
    reader.accept(counter, 0);
    return counter;
  } catch (IOException e) {
    e.printStackTrace();
    fail(e.toString());
    return null;
  }
}
 
Example 8
Source File: ClassWrapper.java    From radon with GNU General Public License v3.0 5 votes vote down vote up
public ClassWrapper(ClassReader cr, boolean libraryNode) {
    ClassNode classNode = new ClassNode();
    cr.accept(classNode, libraryNode ? LIB_FLAGS : INPUT_FLAGS);

    this.classNode = classNode;
    this.originalName = classNode.name;
    this.libraryNode = libraryNode;

    this.entryPrefix = DEFAULT_ENTRY_PREFIX;
    this.access = new ClassAccess(this);
    classNode.methods.forEach(methodNode -> methods.add(new MethodWrapper(methodNode, this)));
    classNode.fields.forEach(fieldNode -> fields.add(new FieldWrapper(fieldNode, this)));
}
 
Example 9
Source File: PatchGuiIngame.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiIngame (%s)", Names.guiIngame.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 10
Source File: ASMReflector.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private static void readClassIndex(
    Map<ClassIndex, File> indexes, InputStream in, File file, boolean allowSuper)
    throws IOException {

  ClassReader classReader = new ClassReader(in);
  String className = ClassNameUtils.replaceSlash(classReader.getClassName());

  boolean projectOutput = file.isDirectory();

  int access = classReader.getAccess();

  boolean isPublic = (Opcodes.ACC_PUBLIC & access) == Opcodes.ACC_PUBLIC;
  boolean isProtected = (Opcodes.ACC_PROTECTED & access) == Opcodes.ACC_PROTECTED;

  boolean isInterface = (Opcodes.ACC_INTERFACE & access) == Opcodes.ACC_INTERFACE;
  boolean isAnnotation = (Opcodes.ACC_ANNOTATION & access) == Opcodes.ACC_ANNOTATION;

  boolean isSuper = false;

  if (allowSuper) {
    isSuper = (Opcodes.ACC_SUPER & access) == Opcodes.ACC_SUPER;
  }
  if (projectOutput || (isPublic || isProtected || isSuper)) {
    String pkg = ClassNameUtils.getPackage(className);
    boolean onlyClassName = !preloadClassPackages.contains(pkg);
    ClassAnalyzeVisitor classAnalyzeVisitor =
        new ClassAnalyzeVisitor(className, onlyClassName, false);
    classReader.accept(classAnalyzeVisitor, 0);
    ClassIndex classIndex = classAnalyzeVisitor.getClassIndex();
    if (!classIndex.isAnonymous) {
      classIndex.setInterface(isInterface);
      classIndex.setAnnotation(isAnnotation);
      indexes.put(classIndex, file);
      if (!onlyClassName) {
        innerCache.putIfAbsent(className, classAnalyzeVisitor.getMembers());
      }
    }
  }
}
 
Example 11
Source File: PatchMinecraft.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("Minecraft (%s)", Names.minecraft.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 12
Source File: PatchGuiTextfield.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiTextfield (%s)", Names.guiTextfield.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 13
Source File: SkyblockAddonsTransformer.java    From SkyblockAddons with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null) return null;

    Collection<ITransformer> transformers = transformerMap.get(transformedName);
    if (transformers.isEmpty()) return bytes;

    logger.info("Found {} transformers for {}", transformers.size(), transformedName);

    ClassReader reader = new ClassReader(bytes);
    ClassNode node = new ClassNode();
    reader.accept(node, ClassReader.EXPAND_FRAMES);

    MutableInt classWriterFlags = new MutableInt(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);

    transformers.forEach(transformer -> {
        logger.info("Applying transformer {} on {}...", transformer.getClass().getName(), transformedName);
        transformer.transform(node, transformedName);

        if (transformer instanceof FontRendererTransformer) {
            classWriterFlags.setValue(0);
        }
    });

    ClassWriter writer = new ClassWriter(classWriterFlags.getValue());

    try {
        node.accept(writer);
    } catch (Throwable t) {
        logger.error("Exception when transforming " + transformedName + " : " + t.getClass().getSimpleName());
        t.printStackTrace();
        outputBytecode(transformedName, writer);
        return bytes;
    }

    outputBytecode(transformedName, writer);

    return writer.toByteArray();
}
 
Example 14
Source File: PatchGuiAchievement.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("GuiAchievement (%s)", Names.guiAchievement.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 15
Source File: PatchEntityPlayerSP.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public byte[] transform(String s, String s1, byte[] bytes) {
	LogUtil.startClass("EntityPlayerSP (%s)", Names.abstractClientPlayer.getName());

	ClassReader reader = new ClassReader(bytes);
	ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
	ClassPatcher visitor = new ClassPatcher(writer);
	reader.accept(visitor, 0);
	LogUtil.endClass();
	return writer.toByteArray();
}
 
Example 16
Source File: AbstractMethodLister.java    From RetroFacebook with Apache License 2.0 4 votes vote down vote up
private ImmutableList<String> abstractNoArgMethodsX() throws IOException {
  ClassReader classReader = new ClassReader(inputStream);
  RecordingClassVisitor classVisitor = new RecordingClassVisitor();
  classReader.accept(classVisitor, 0);
  return classVisitor.abstractNoArgMethods.build();
}
 
Example 17
Source File: Desugar.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Desugar the classes that are in the inputs specified in the command line arguments. */
private void desugarClassesInInput(
    InputFileProvider inputFiles,
    OutputFileProvider outputFileProvider,
    ClassLoader loader,
    @Nullable ClassReaderFactory classpathReader,
    DependencyCollector depsCollector,
    ClassReaderFactory bootclasspathReader,
    @Nullable CoreLibrarySupport coreLibrarySupport,
    ClassVsInterface interfaceCache,
    ImmutableSet.Builder<String> interfaceLambdaMethodCollector,
    InvocationSiteTransformationRecordBuilder callSiteRecord,
    BootClassPathDigest bootClassPathDigest,
    ClassAttributeRecord classAttributeRecord,
    NestDigest nestDigest,
    ImmutableSet.Builder<ClassName> requiredRuntimeSupportTypes,
    ClassMemberRetargetConfig classMemberRetargetConfig)
    throws IOException {

  for (FileContentProvider<? extends InputStream> inputFileProvider :
      Iterables.concat(inputFiles.toInputFileStreams(), nestDigest.getCompanionFileProviders())) {
    String inputFilename = inputFileProvider.getBinaryPathName();
    if ("module-info.class".equals(inputFilename)
        || (inputFilename.endsWith("/module-info.class")
            && Pattern.matches("META-INF/versions/[0-9]+/module-info.class", inputFilename))) {
      continue; // Drop module-info.class since it has no meaning on Android
    }
    if (OutputFileProvider.DESUGAR_DEPS_FILENAME.equals(inputFilename)) {
      // TODO(kmb): rule out that this happens or merge input file with what's in depsCollector
      continue; // skip as we're writing a new file like this at the end or don't want it
    }

    try (InputStream content = inputFileProvider.get()) {
      // We can write classes uncompressed since they need to be converted to .dex format
      // for Android anyways. Resources are written as they were in the input jar to avoid
      // any danger of accidentally uncompressed resources ending up in an .apk.  We also simply
      // copy classes from Desugar's runtime library, which we build so they need no desugaring.
      // The runtime library typically uses constructs we'd otherwise desugar, so it's easier
      // to just skip it should it appear as a regular input (for idempotency).
      if (inputFilename.endsWith(".class")
          && ClassName.fromClassFileName(inputFilename).isDesugarEligible()) {
        ClassReader reader = rewriter.reader(content);
        UnprefixingClassWriter writer = rewriter.writer(ClassWriter.COMPUTE_MAXS);
        ClassVisitor visitor =
            createClassVisitorsForClassesInInputs(
                loader,
                classpathReader,
                depsCollector,
                bootclasspathReader,
                coreLibrarySupport,
                interfaceCache,
                interfaceLambdaMethodCollector,
                writer,
                reader,
                nestDigest,
                callSiteRecord,
                bootClassPathDigest,
                classAttributeRecord,
                requiredRuntimeSupportTypes,
                classMemberRetargetConfig);
        if (writer == visitor) {
          // Just copy the input if there are no rewritings
          outputFileProvider.write(inputFilename, reader.b);
        } else {
          reader.accept(visitor, customAttributes, ClassReader.EXPAND_FRAMES);
          String filename = writer.getClassName() + ".class";
          checkState(
              (options.coreLibrary && coreLibrarySupport != null)
                  || filename.equals(inputFilename));
          outputFileProvider.write(filename, writer.toByteArray());
        }
      } else {
        // Most other files (and directories) we want to just copy, but...
        String outputFilename = inputFilename;
        if (options.coreLibrary && coreLibrarySupport != null && inputFilename.endsWith("/")) {
          // rename core library directories together with files in them
          outputFilename = coreLibrarySupport.renameCoreLibrary(inputFilename);
        } else if (coreLibrarySupport != null
            && !inputFilename.endsWith("/")
            && inputFilename.startsWith("META-INF/services/")) {
          // rename j.u.ServiceLoader files for renamed core libraries so they're found
          String serviceName = inputFilename.substring("META-INF/services/".length());
          if (!serviceName.contains("/")
              && coreLibrarySupport.isRenamedCoreLibrary(serviceName.replace('.', '/'))) {
            outputFilename =
                "META-INF/services/"
                    + coreLibrarySupport
                        .renameCoreLibrary(serviceName.replace('.', '/'))
                        .replace('/', '.');
          }
        }
        outputFileProvider.copyFrom(inputFilename, inputFiles, outputFilename);
      }
    }
  }
}
 
Example 18
Source File: CacheonixAgent.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public byte[] transform(final ClassLoader loader, final String className,
                        final Class<?> classBeingRedefined,
                        final ProtectionDomain protectionDomain,
                        final byte[] classfileBuffer) throws IllegalClassFormatException {

   String strClassName = className;

   try {
      // if (className.startsWith("java")
      // || className.startsWith("cacheonix/"))
      // {
      // return null;
      // }
      // else if (className.startsWith("org/cacheonix/impl")
      // && !className.startsWith("org/cacheonix/impl/examples")
      // && !className.startsWith("org/cacheonix/impl/annotations/test") )
      // {
      // return null;
      // }
      // else if (className.startsWith("sun/nio")
      // || className.startsWith("sun/reflect")
      // || className.startsWith("sun/misc"))
      // {
      // return null;
      // }
      //
      // System.out.println("Processing -- " + className.replace('/',
      // '.'));

      final boolean b1 = className.endsWith("CacheAnnotatedTest");
      final boolean b2 = className.endsWith("CacheAnnotationsTest");

      if (!b1 && !b2) {
         return null;
      }

      strClassName = className.replace('/', '.');

      final ClassReader creader = new ClassReader(classfileBuffer);

      final CacheonixClassReader classCollector = new CacheonixClassReader();

      creader.accept(classCollector, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);

      final Map<String, AnnotationParameter> classLevelInfo = classCollector
              .getClassLevelAnnotationInfo();

      final Map<String, MethodMetaData> methodsInfo = classCollector
              .getMethodsInfo();

      if (!classLevelInfo.isEmpty() || !methodsInfo.isEmpty()) {
         // annotated fields present, generate the toString() method
         // Temporary System.out.println("Modifying " + strClassName);
         final ClassWriter writer = new ClassWriter(
                 ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);

         final CacheonixClassAdapter gen = new CacheonixClassAdapter(
                 writer, strClassName, classLevelInfo, methodsInfo);
         creader.accept(gen, 0); // ClassReader.SKIP_DEBUG
         return writer.toByteArray();

      }
   } catch (final IllegalStateException e) {
      throw new IllegalClassFormatException("Error: " + e.getMessage() + // NOPMD
              " on class " + strClassName); // NOPMD
   }
   return null;
}
 
Example 19
Source File: ExternalLibrary.java    From bytecode-viewer with GNU General Public License v3.0 4 votes vote down vote up
protected ClassNode create(byte[] b) {
    ClassReader cr = new ClassReader(b);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);
    return cn;
}
 
Example 20
Source File: MethodReplacer.java    From atlas with Apache License 2.0 3 votes vote down vote up
@Override
protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) {

    try {
        InputStream jarFileInputStream = jarFile.getInputStream(ze);

        ClassReader classReader = new ClassReader(jarFileInputStream);

        ClassWriter classWriter = new ClassWriter(0);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(jar.getAbsolutePath()).append(".").append(pathName);

        classReader.accept(new MethodReplaceClazzVisitor(Opcodes.ASM4, classWriter, methodStore, stringBuilder),
                           ClassReader.EXPAND_FRAMES);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(classWriter.toByteArray());
        copyStreamToJar(inputStream, jos, pathName, ze.getTime());
        IOUtils.closeQuietly(inputStream);

    } catch (Throwable e) {

        System.err.println("[MethodReplacer] rewrite error > " + pathName);
        justCopy(jarFile, jos, ze, pathName);
    }

}