org.objectweb.asm.ClassReader Java Examples
The following examples show how to use
org.objectweb.asm.ClassReader.
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: ClassFileStructurePrinter.java From scott with MIT License | 6 votes |
public static void viewByteCode(byte[] bytecode) { ClassReader classReader = new ClassReader(bytecode); ClassNode classNode = new ClassNode(); classReader.accept(classNode, 0); final List<MethodNode> methodNodes = classNode.methods; Printer printer = new Textifier(); TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(printer); for (MethodNode methodNode : methodNodes) { InsnList insnList = methodNode.instructions; System.out.println(methodNode.name); for (int i = 0; i < insnList.size(); i++) { insnList.get(i).accept(traceMethodVisitor); StringWriter sw = new StringWriter(); printer.print(new PrintWriter(sw)); printer.getText().clear(); System.out.print(sw.toString()); } } }
Example #2
Source File: ClassFileDebugInfoExtractor.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
public String getDebugInfo(File file) { if (file.isFile() && file.getName().endsWith(".class")) { try { ClassReader cr = new ClassReader(Files.toByteArray(file)); ClassVisitor visitor = new ClassVisitor(file.getName()); cr.accept(visitor, 0); return visitor.toString(); } catch (IOException e) { throw new RuntimeException(e); } } else if (file.isDirectory()) { List<String> children = Lists.newArrayList(); for (File child : file.listFiles()) { String info = getDebugInfo(child); if (!Strings.isEmpty(info)) children.add(info); } Collections.sort(children); StringBuffer buf = new StringBuffer(); buf.append("// " + file.getName() + " {\n"); buf.append(" " + Joiner.on("\n\n").join(children).replace("\n", "\n ") + "\n"); buf.append("}"); return buf.toString(); } return null; }
Example #3
Source File: HotSwapTool.java From HotswapAgent with GNU General Public License v2.0 | 6 votes |
private static void loadAdaptedClass(File file, Map<String, String> typeMappnigs, Map<Class<?>, byte[]> result) throws IOException, ClassNotFoundException { ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); TestClassAdapter adapter = new TestClassAdapter(writer, typeMappnigs); InputStream in = new FileInputStream(file); try { new ClassReader(in).accept(adapter, ClassReader.EXPAND_FRAMES); } finally { try { in.close(); } catch (IOException e) { // Ignore. } } byte[] bytes = writer.toByteArray(); String className = adapter.getClassName().replace('/', '.'); result.put(Class.forName(className), bytes); // FIXME: ClassLoader... }
Example #4
Source File: Input.java From JRemapper with MIT License | 6 votes |
/** * Try to add the class contained in the given stream to the classes map. * * @param name * Entry name. * @param is * Stream of entry. * @throws IOException * Thrown if stream could not be read or if ClassNode could not be * derived from the streamed content. */ protected void addClass(String name, InputStream is) { try { byte[] value = Streams.from(is); ClassReader cr = new ClassReader(value); String className = cr.getClassName(); // Add missing debug information if needed ClassWriter cw = new ClassWriter(0); VariableFixer fixer = new VariableFixer(); cr.accept(fixer, 0); fixer.accept(cw); if (fixer.isDirty()) value = cw.toByteArray(); // Put value in map rawNodeMap.put(className, value); } catch (Exception e) { Logging.error("Could not parse class: " + name); e.printStackTrace(); } }
Example #5
Source File: ObfuscatorImpl.java From obfuscator with MIT License | 6 votes |
private void loadJar(File file) { try (JarFile jarFile = new JarFile(file)) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); try (InputStream inputStream = jarFile.getInputStream(jarEntry)) { final byte[] bytes = IOUtils.toByteArray(inputStream); if (!jarEntry.getName().endsWith(".class")) { this.fileMap.put(jarEntry.getName(), bytes); continue; } final ClassNode classNode = new ClassNode(); final ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, ClassReader.EXPAND_FRAMES); this.classMap.put(classNode.name, classNode); } } } catch (IOException ex) { throw new ObfuscatorException(ex); } }
Example #6
Source File: JavaLanguageAdapter.java From fabric-loader with Apache License 2.0 | 6 votes |
public static Class<?> getClass(String className, Options options) throws ClassNotFoundException, IOException { String classFilename = className.replace('.', '/') + ".class"; InputStream stream = FabricLauncherBase.getLauncher().getResourceAsStream(classFilename); if (stream == null) { throw new ClassNotFoundException("Could not find or load class " + classFilename); } ClassReader reader = new ClassReader(stream); for (String s : reader.getInterfaces()) { if (!canApplyInterface(s)) { switch (options.getMissingSuperclassBehavior()) { case RETURN_NULL: stream.close(); return null; case CRASH: default: stream.close(); throw new ClassNotFoundException("Could not find or load class " + s); } } } stream.close(); return FabricLauncherBase.getClass(className); }
Example #7
Source File: TypeSystem.java From spring-boot-graal-feature with Apache License 2.0 | 6 votes |
private void scanArchive(File f) { try (ZipFile zf = new ZipFile(f)) { Enumeration<? extends ZipEntry> entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { ClassReader reader = new ClassReader(zf.getInputStream(entry)); ClassNode node = new ClassNode(); reader.accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); AnnotationInfo ai = new AnnotationInfo(this, node); if (ai.hasData()) { System.out.println("From " + entry.toString() + " got " + ai.toAnnotationString()); annotatedTypes.put(node.name, ai); } } // TODO resources? } } catch (IOException ioe) { throw new IllegalStateException(ioe); } }
Example #8
Source File: ByteCodeTypePrinter.java From bazel with Apache License 2.0 | 6 votes |
public static void printClassesWithTypes(Path inputJarFile, PrintWriter printWriter) throws IOException { Preconditions.checkState( Files.exists(inputJarFile), "The input jar file %s does not exist.", inputJarFile); try (ZipFile jarFile = new ZipFile(inputJarFile.toFile())) { for (ZipEntry entry : getSortedClassEntriess(jarFile)) { try (InputStream classStream = jarFile.getInputStream(entry)) { printWriter.println("\nClass: " + entry.getName()); ClassReader classReader = new ClassReader(classStream); ClassVisitor visitor = new ClassWithTypeDumper(printWriter); classReader.accept(visitor, 0); } printWriter.println("\n"); } } }
Example #9
Source File: PluginDetailBuilder.java From glowroot with Apache License 2.0 | 6 votes |
@OnlyUsedByTests private static PointcutClass buildAdviceClassLookAtSuperClass(String internalName) throws IOException { URL url = checkNotNull(PluginDetailBuilder.class.getResource("/" + internalName + ".class")); byte[] bytes = Resources.asByteSource(url).read(); MemberClassVisitor mcv = new MemberClassVisitor(); new ClassReader(bytes).accept(mcv, ClassReader.SKIP_CODE); ImmutablePointcutClass pointcutClass = mcv.buildPointcutClass(bytes, false, null); String superName = checkNotNull(mcv.superName); if (!"java/lang/Object".equals(superName)) { pointcutClass = ImmutablePointcutClass.builder() .copyFrom(pointcutClass) .addAllMethods(buildAdviceClassLookAtSuperClass(superName).methods()) .build(); } return pointcutClass; }
Example #10
Source File: JAXRSArchiveImpl.java From thorntail with Apache License 2.0 | 6 votes |
private static boolean isJAXRS(ArchivePath path, Asset asset) { if (asset == null) { return false; } if (asset instanceof ArchiveAsset) { return isJAXRS(((ArchiveAsset) asset).getArchive()); } if (!path.get().endsWith(".class")) { return false; } try (InputStream in = asset.openStream()) { ClassReader reader = new ClassReader(in); JAXRSAnnotationSeekingClassVisitor visitor = new JAXRSAnnotationSeekingClassVisitor(); reader.accept(visitor, 0); return visitor.isFound(); } catch (IOException ignored) { } return false; }
Example #11
Source File: JarUtils.java From bytecode-viewer with GNU General Public License v3.0 | 6 votes |
/** * Creates a new ClassNode instances from the provided byte[] * * @param bytez the class file's byte[] * @return the ClassNode instance */ public static ClassNode getNode(final byte[] bytez) throws Exception { ClassReader cr = new ClassReader(bytez); ClassNode cn = new ClassNode(); try { cr.accept(cn, ClassReader.EXPAND_FRAMES); } catch (Exception e) { try { cr.accept(cn, ClassReader.SKIP_FRAMES); } catch (Exception e2) { throw e2; } } cr = null; return cn; }
Example #12
Source File: ClassDependenciesAnalyzer.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
private List<String> getClassDependencies(ClassRelevancyFilter filter, ClassReader reader) { List<String> out = new LinkedList<String>(); char[] charBuffer = new char[reader.getMaxStringLength()]; for (int i = 1; i < reader.getItemCount(); i++) { int itemOffset = reader.getItem(i); if (itemOffset > 0 && reader.readByte(itemOffset - 1) == 7) { // A CONSTANT_Class entry, read the class descriptor String classDescriptor = reader.readUTF8(itemOffset, charBuffer); Type type = Type.getObjectType(classDescriptor); while (type.getSort() == Type.ARRAY) { type = type.getElementType(); } if (type.getSort() != Type.OBJECT) { // A primitive type continue; } String name = type.getClassName(); if (filter.isRelevant(name)) { out.add(name); } } } return out; }
Example #13
Source File: RenameHandler.java From EasyRouter with Apache License 2.0 | 6 votes |
@Override public void onClassFetch(QualifiedContent content, Status status, String relativePath, byte[] bytes) throws IOException { File outputFile = context.getRelativeFile(content); byte[] finalBytes = bytes; if (relativePath.endsWith(".class") && relativePath.contains("com/zane/easyrouter_generated")) { ClassReader classReader = new ClassReader(finalBytes); ClassWriter classWriter = new ClassWriter(0); RenameClassVisistor classVisistor = new RenameClassVisistor(classWriter); classReader.accept(classVisistor, 0); if (classVisistor.isFindTarget()) { relativePath = classVisistor.getFinalName() + ".class"; finalBytes = classWriter.toByteArray(); } } directoryWriter.write(outputFile, relativePath, finalBytes); }
Example #14
Source File: Bug62456849TestDataGenerator.java From bazel with Apache License 2.0 | 6 votes |
private static byte[] convertClass(ZipFile file, ZipEntry entry) throws IOException { try (InputStream content = file.getInputStream(entry)) { ClassReader reader = new ClassReader(content); ClassWriter writer = new ClassWriter(0); ClassVisitor converter = new ClassVisitor(Opcodes.ASM5, writer) { @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { if (name.startsWith("lambda$") && (access & Opcodes.ACC_SYNTHETIC) == 0) { access |= Opcodes.ACC_SYNTHETIC; } return super.visitMethod(access, name, desc, signature, exceptions); } }; reader.accept(converter, 0); return writer.toByteArray(); } }
Example #15
Source File: CheckParserUsagesDT.java From sql-layer with GNU Affero General Public License v3.0 | 6 votes |
@Before public void initializeFinder() throws Exception { finder = new PropertyFinder(); for (Class<? extends QueryTreeNode> nodeClass : queryTreeNodes) { try { ClassReader reader = new ClassReader(nodeClass.getName()); reader.accept(finder, 0); } catch (IOException e) { throw new Exception("Could not open class to scan: " + nodeClass.getName(), e); } } // Remove any base class methods here, before they get propagated down finder.getNodes().get("com/foundationdb/sql/parser/DDLStatementNode") .removeMethod("getRelativeName", "()Ljava/lang/String;") .removeMethod("getFullName", "()Ljava/lang/String;"); finder.finalizeState(); // Remove any concrete class methods here, base class methods have already been propagated down removeTemporarilyIgnoredUnused(finder); }
Example #16
Source File: ASMUtils.java From JByteMod-Beta with GNU General Public License v2.0 | 6 votes |
/** * Gets a ClassNode based on given bytes * * @param bytez * @return */ public static ClassNode getNode(final byte[] bytez) { ClassReader cr = new ClassReader(bytez); ClassNode cn = new ClassNode(); try { cr.accept(cn, ClassReader.EXPAND_FRAMES); } catch (Exception e) { try { cr.accept(cn, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); } catch (Exception e2) { // e2.printStackTrace(); } } cr = null; return cn; }
Example #17
Source File: GregorMutater.java From pitest with Apache License 2.0 | 6 votes |
@Override public Mutant getMutation(final MutationIdentifier id) { final ClassContext context = new ClassContext(); context.setTargetMutation(Optional.ofNullable(id)); final Optional<byte[]> bytes = this.byteSource.getBytes(id.getClassName() .asJavaName()); final ClassReader reader = new ClassReader(bytes.get()); final ClassWriter w = new ComputeClassWriter(this.byteSource, this.computeCache, FrameOptions.pickFlags(bytes.get())); final MutatingClassVisitor mca = new MutatingClassVisitor(w, context, filterMethods(), FCollection.filter(this.mutators, isMutatorFor(id))); reader.accept(mca, ClassReader.EXPAND_FRAMES); final List<MutationDetails> details = context.getMutationDetails(context .getTargetMutation().get()); return new Mutant(details.get(0), w.toByteArray()); }
Example #18
Source File: PatchGuiTextfield.java From The-5zig-Mod with MIT License | 5 votes |
@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 #19
Source File: PatchGuiConnecting.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiConnecting (%s)", Names.guiConnecting.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 #20
Source File: DefaultMethodClassFixerTest.java From bazel with Apache License 2.0 | 5 votes |
private byte[] desugar(ClassReader reader) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); DefaultMethodClassFixer fixer = new DefaultMethodClassFixer( writer, /*useGeneratedBaseClasses=*/ false, classpathReader, DependencyCollector.NoWriteCollectors.FAIL_ON_MISSING, /*coreLibrarySupport=*/ null, bootclassPath, classLoader); reader.accept(fixer, 0); return writer.toByteArray(); }
Example #21
Source File: JClassPatcher.java From rscplus with GNU General Public License v3.0 | 5 votes |
public byte[] patch(byte[] data) { ClassReader reader = new ClassReader(data); ClassNode node = new ClassNode(); reader.accept(node, ClassReader.SKIP_DEBUG); if (node.name.equals("ua")) patchRenderer(node); else if (node.name.equals("e")) patchApplet(node); else if (node.name.equals("qa")) patchMenu(node); else if (node.name.equals("m")) patchData(node); else if (node.name.equals("client")) patchClient(node); else if (node.name.equals("f")) patchRandom(node); else if (node.name.equals("da")) patchGameApplet(node); else if (node.name.equals("lb")) patchRendererHelper(node); // Patch applied to all classes patchGeneric(node); if (Settings.DISASSEMBLE.get(Settings.currentProfile)) { Settings.Dir.DUMP = Dir.JAR + "/" + Settings.DISASSEMBLE_DIRECTORY.get("custom"); Util.makeDirectory(Dir.DUMP); Logger.Info("Disassembling file: " + node.name + ".class"); dumpClass(node); } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); return writer.toByteArray(); }
Example #22
Source File: ModuleResolutionAttribute.java From Concurnas with MIT License | 5 votes |
@Override protected Attribute read( final ClassReader classReader, final int offset, final int length, final char[] charBuffer, final int codeOffset, final Label[] labels) { return new ModuleResolutionAttribute(classReader.readUnsignedShort(offset)); }
Example #23
Source File: SimpleClassWriterTest.java From coroutines with GNU Lesser General Public License v3.0 | 5 votes |
@BeforeEach public void setUp() throws IOException { byte[] classData = readZipFromResource("SimpleStub.zip").get("SimpleStub.class"); ClassReader classReader = new ClassReader(classData); classNode = new ClassNode(); classReader.accept(classNode, 0); methodNode = classNode.methods.get(1); // stub should be here }
Example #24
Source File: SimpleVerifierTest.java From coroutines with GNU Lesser General Public License v3.0 | 5 votes |
@BeforeEach public void setUp() throws IOException { classRepo = new ClassResourceClassInformationRepository(TestUtils.class.getClassLoader()); byte[] classData = readZipFromResource("SimpleStub.zip").get("SimpleStub.class"); ClassReader classReader = new ClassReader(classData); classNode = new ClassNode(); classReader.accept(classNode, 0); methodNode = classNode.methods.get(1); // stub should be here }
Example #25
Source File: PatchMinecraft.java From The-5zig-Mod with MIT License | 5 votes |
@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 #26
Source File: InstrumentTask.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public CustomClassDescriptor(byte[] bytecode) throws Exception { this.bytecode = bytecode; ClassReader reader = new ClassReader( new ByteArrayInputStream( bytecode ) ); String[] names = ClassNameReader.getClassInfo( reader ); this.name = names[0]; boolean instrumented = false; for ( int i = 1; i < names.length; i++ ) { if ( InterceptFieldEnabled.class.getName().equals( names[i] ) ) { instrumented = true; break; } } this.isInstrumented = instrumented; }
Example #27
Source File: PatchGuiEditSign.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiEditSign (%s)", Names.guiEditSign.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 #28
Source File: PatchGuiEditSign.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiEditSign (%s)", Names.guiEditSign.getName()); ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example #29
Source File: Instrument.java From dacapobench with Apache License 2.0 | 5 votes |
/** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub if (args.length != 4) System.exit(1); String infile = args[0]; String outfile = args[1]; String name = args[2]; String commandLineOptions = args[3]; try { ClassReader reader = readClassFromFile(infile); System.out.println("Instrument["+infile+", "+outfile+", "+name+", "+commandLineOptions+"]: class name="+reader.getClassName()); ClassWriter writer = makeClassWriter(reader); processOptions(writer, new Options(commandLineOptions)); writeClassToFile(writer,outfile); } catch (Exception e) { System.err.println("failed to process class "+name); System.err.println("exception "+e); e.printStackTrace(); System.exit(1); } }
Example #30
Source File: Checker.java From forbidden-apis with Apache License 2.0 | 5 votes |
/** Parses a class and checks for valid method invocations */ private int checkClass(final ClassReader reader, Pattern suppressAnnotationsPattern) throws ForbiddenApiException { final String className = Type.getObjectType(reader.getClassName()).getClassName(); final ClassScanner scanner = new ClassScanner(this, forbiddenSignatures, suppressAnnotationsPattern); try { reader.accept(scanner, ClassReader.SKIP_FRAMES); } catch (RelatedClassLoadingException rcle) { final Exception cause = rcle.getException(); final StringBuilder msg = new StringBuilder() .append("Check for forbidden API calls failed while scanning class '") .append(className) .append('\''); final String source = scanner.getSourceFile(); if (source != null) { msg.append(" (").append(source).append(')'); } msg.append(": ").append(cause); msg.append(" (while looking up details about referenced class '").append(rcle.getClassName()).append("')"); assert cause != null && (cause instanceof IOException || cause instanceof ClassNotFoundException); throw new ForbiddenApiException(msg.toString(), cause); } final List<ForbiddenViolation> violations = scanner.getSortedViolations(); final Pattern splitter = Pattern.compile(Pattern.quote(ForbiddenViolation.SEPARATOR)); for (final ForbiddenViolation v : violations) { for (final String line : splitter.split(v.format(className, scanner.getSourceFile()))) { logger.error(line); } } return violations.size(); }