public static Application readJar(Path path) throws IOException { Application application = new Application(); try (JarInputStream in = new JarInputStream(new BufferedInputStream(Files.newInputStream(path)))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String name = entry.getName(); if (!name.endsWith(".class")) continue; name = name.replaceAll(".class$", ""); ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(in); reader.accept(node, ClassReader.SKIP_DEBUG); application.classes.put(name, node); } } return application; }
private GameInfo loadGameInfo(File file) { GameInfo.Builder builder = new GameInfo.Builder(file); try { JarFile jar = new JarFile(file); for (ZipEntry entry : Collections.list(jar.entries())) { if (!entry.getName().matches("(.+).(class)")) { continue; } ClassReader reader = new ClassReader(jar.getInputStream(entry)); reader.accept(new GameClassVisitor(builder), 0); } } catch (IOException e) { e.printStackTrace(); } return builder.build(); }
/** * Writes a modified *.class file to the output JAR file. */ private void rewriteClass( JarEntry entry, InputStream inputStream, JarOutputStream outputStream) throws IOException { ClassReader classReader = new ClassReader(inputStream); ClassNode classNode = new ClassNode(Opcodes.ASM5); classReader.accept(classNode, EMPTY_FLAGS); modifyClass(classNode); ClassWriter classWriter = new ClassWriter(0); classNode.accept(classWriter); outputStream.putNextEntry(new ZipEntry(entry.getName())); outputStream.write(classWriter.toByteArray()); }
private Set<String> getClassDependencies(ClassRelevancyFilter filter, ClassReader reader) { Set<String> out = new HashSet<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; }
private void remapClasses(File scriptCacheDir, File relocalizedDir, RemappingScriptSource source) { ScriptSource origin = source.getSource(); String className = origin.getClassName(); if (!relocalizedDir.exists()) { relocalizedDir.mkdir(); } File[] files = scriptCacheDir.listFiles(); if (files != null) { for (File file : files) { String renamed = file.getName(); if (renamed.startsWith(RemappingScriptSource.MAPPED_SCRIPT)) { renamed = className + renamed.substring(RemappingScriptSource.MAPPED_SCRIPT.length()); } ClassWriter cv = new ClassWriter(0); BuildScriptRemapper remapper = new BuildScriptRemapper(cv, origin); try { ClassReader cr = new ClassReader(Files.toByteArray(file)); cr.accept(remapper, 0); Files.write(cv.toByteArray(), new File(relocalizedDir, renamed)); } catch (IOException ex) { throw UncheckedException.throwAsUncheckedException(ex); } } } }
public byte[] transform(String name, byte[] basicClass) { int i = 0; while (i < transformers.size()) { if (transformers.get(i).is(name)) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(basicClass); classReader.accept(classNode, 0); transformers.get(i).transform(classNode); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); basicClass = writer.toByteArray(); System.out.println("[" + MineCamera.MODID + "] Patched " + transformers.get(i).className + " ..."); transformers.get(i).done(); i++; // transformers.remove(i); } else i++; } return basicClass; }
private void findAndMergeSuperMaps(String name) { try { String superName = null; String[] interfaces = new String[0]; byte[] classBytes = ClassPatchManager.INSTANCE.getPatchedResource(name, map(name), classLoader); if (classBytes != null) { ClassReader cr = new ClassReader(classBytes); superName = cr.getSuperName(); interfaces = cr.getInterfaces(); } mergeSuperMaps(name, superName, interfaces); } catch (IOException e) { e.printStackTrace(); } }
private void checkAnnotationContent(Path inputPath, Path outputPath) throws IOException, ExecutionException { ClassReader classReader = new ClassReader(new FileInputStream(inputPath.toFile())); ReadSourceDebugExtensionAttribute sourceDebugExtensionReader = new ReadSourceDebugExtensionAttribute(Opcodes.ASM5, null); classReader.accept(sourceDebugExtensionReader, 0); DexInspector dexInspector = new DexInspector(outputPath.resolve("classes.dex"), getGeneratedProguardMap()); ClassSubject classSubject = dexInspector.clazz("HelloKt"); AnnotationSubject annotationSubject = classSubject.annotation("dalvik.annotation.SourceDebugExtension"); Assert.assertTrue(annotationSubject.isPresent()); DexAnnotationElement[] annotationElement = annotationSubject.getAnnotation().elements; Assert.assertNotNull(annotationElement); Assert.assertTrue(annotationElement.length == 1); Assert.assertEquals("value", annotationElement[0].name.toString()); Assert.assertTrue(annotationElement[0].value instanceof DexValueString); Assert.assertEquals( sourceDebugExtensionReader.debugSourceExtension, ((DexValueString) annotationElement[0].value).value.toSourceString()); }
private void generateTests() throws IOException { ClassReader cr = new ClassReader(new FileInputStream(classNamePath.toFile())); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cr.accept( new ClassVisitor(Opcodes.ASM5, cw) { @Override public void visitEnd() { generateMethodTest1(cw); generateMethodTest2(cw); generateMethodTest3(cw); generateMethodTest4(cw); generateMethodTest5(cw); generateMethodTest6(cw); generateMethodTest7(cw); generateMethodTest8(cw); generateMethodTest9(cw); generateMethodTest10(cw); generateMethodTest11(cw); generateMethodTest12(cw); generateMethodTest13(cw); generateMethodMain(cw); super.visitEnd(); } }, 0); new FileOutputStream(classNamePath.toFile()).write(cw.toByteArray()); }
JavaClasses process(ClassFileSource source) { ClassFileImportRecord importRecord = new ClassFileImportRecord(); RecordAccessHandler accessHandler = new RecordAccessHandler(importRecord); ClassDetailsRecorder classDetailsRecorder = new ClassDetailsRecorder(importRecord); for (ClassFileLocation location : source) { try (InputStream s = location.openStream()) { JavaClassProcessor javaClassProcessor = new JavaClassProcessor(location.getUri(), classDetailsRecorder, accessHandler); new ClassReader(s).accept(javaClassProcessor, 0); importRecord.addAll(javaClassProcessor.createJavaClass().asSet()); } catch (Exception e) { LOG.warn(String.format("Couldn't import class from %s", location.getUri()), e); } } return new ClassGraphCreator(importRecord, getClassResolver(classDetailsRecorder)).complete(); }
public static Map<String, ClassNode> readJar(JarFile file, boolean skipDebug) throws IOException { Map<String, ClassNode> classes = new HashMap<>(); Enumeration<JarEntry> entries = file.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { try (InputStream inputStream = file.getInputStream(entry)) { ClassReader reader = new ClassReader(inputStream); ClassNode node = new ClassNode(); reader.accept(node, (skipDebug ? ClassReader.SKIP_DEBUG : 0) | ClassReader.SKIP_FRAMES); classes.put(node.name, node); } } } return classes; }
private String getCommonInterface(final ClassReader classReader1, final ClassReader classReader2) { final Set<String> interfaceHierarchy = new HashSet<String>(); traversalInterfaceHierarchy(interfaceHierarchy, classReader1); if (isInterface(classReader2)) { if (interfaceHierarchy.contains(classReader2.getClassName())) { return classReader2.getClassName(); } } final String interfaceInternalName = getImplementedInterface(interfaceHierarchy, classReader2); if (interfaceInternalName != null) { return interfaceInternalName; } return OBJECT_CLASS_INTERNAL_NAME; }
@Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(className.startsWith(TransformConfig.getInstance().getPackageScan())) { logger.log(Level.INFO, "-------------------CLASS---------------------"); logger.log(Level.INFO, "className: " + className); ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassVisitor classVisitor = new HookClassAdapter(Opcodes.ASM5, cw); cr.accept(classVisitor, ClassReader.SKIP_FRAMES); // try { // FileOutputStream fos = new FileOutputStream(new File("classMod.class")); // fos.write(cw.toByteArray()); // fos.close(); // } catch (IOException e) { // e.printStackTrace(); // } return cw.toByteArray(); } return null; }
public byte[] transformCode(String className, byte[] fb) { this.className = className; ClassReader cr = new ClassReader(fb); // ClassReader cr = new ClassReader(className); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS); ClassVisitor cv = new ClassInsert(cw); cr.accept(cv, ClassReader.EXPAND_FRAMES); /*byte[] code = cw.toByteArray(); File file = new File("Idtk.class"); try { FileUtils.writeByteArrayToFile(file,code); }catch (IOException e){ System.out.println("=======IOException======="); }*/ return cw.toByteArray(); }
private static void process(File jarFile) throws Throwable { ZipFile zipFile = new ZipFile(jarFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); try { while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory() && entry.getName().endsWith(".class")) { try (InputStream in = zipFile.getInputStream(entry)) { ClassReader cr = new ClassReader(in); ClassNode classNode = new ClassNode(); cr.accept(classNode, 0); findID(classNode); } } } } finally { zipFile.close(); } }
private List<ClassNode> indexJar() { ArrayList<ClassNode> classNodes = new ArrayList<ClassNode>(); Enumeration<JarEntry> enumeration = jarFile.entries(); while (enumeration.hasMoreElements()) { JarEntry jarEntry = enumeration.nextElement(); if (jarEntry != null) { if (jarEntry.getName().endsWith(".class")) { try { byte[] classBytes = IOUtils.readFully(jarFile.getInputStream(jarEntry), -1, false); ClassReader classReader = new ClassReader(classBytes); ClassNode classNode = new ClassNode(); classReader.accept(classNode, 0); classNodes.add(classNode); } catch (IOException e) { e.printStackTrace(); } } } } return classNodes; }
private byte[] classNodeToBytes(ClassNode classNode) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); byte[] bytes = writer.toByteArray(); // verify bytecode if (verifyAndPrint) { ClassReader reader = new ClassReader(bytes); ClassVisitor tracer = new TraceClassVisitor(new PrintWriter(System.out)); ClassVisitor checker = new CheckClassAdapter(tracer, true); reader.accept(checker, 0); } return bytes; }
private static Map<String, Set<String>> readClassAsEntry(InputStream input) { HashMap<String, Set<String>> map = new HashMap<>(); try { ClassReader reader = new ClassReader(input); String className = reader.getClassName().replace('/', '.'); reader.accept(new ClassVisitor(Opcodes.ASM6) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { String methodName = className + '.' + name; map.computeIfAbsent(methodName, __ -> new HashSet<>()).add(methodName + desc); return null; } }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG); } catch(IOException e) { throw new UncheckedIOException(e); } return map; }
/** * 是否需要忽略增强的类 * * @param cr ClassReader * @param targetClassLoader 目标ClassLoader * @return true:忽略增强;false:需要增强 */ private boolean isIgnoreClass(final ClassReader cr, final ClassLoader targetClassLoader) { final String[] annotationTypeArray = null; final int access = cr.getAccess(); // 对一些需要忽略的access进行过滤 return isIgnoreAccess(access) // 对一系列的ClassLoader进行过滤 || isIgnoreClassLoader(targetClassLoader) // 如果目标类的前缀是Sandbox的前缀,则放弃 || StringUtils.startsWith(toJavaClassName(cr.getClassName()), "com.alibaba.jvm.sandbox.") // 如果目标类是Lambda表达式生成的临时类,则放弃 || StringUtils.contains(toJavaClassName(cr.getClassName()), "$$Lambda$") // 按照Filter#doClassFilter()完成过滤 || !filter.doClassFilter(access, toJavaClassName(cr.getClassName()), toJavaClassName(cr.getSuperName()), toJavaClassNameArray(cr.getInterfaces()), toJavaClassNameArray(annotationTypeArray)); }
@SuppressWarnings("unchecked") private void analyzeClassesForLocalDeadCode(String dir, Set<String> classesToVisit) throws IOException, XMLStreamException { for (final String className : classesToVisit) { if (isInterrupted()) { break; } // les classes *SoapBindingStub générées par Apache Axis // contiennent beaucoup des variables locales non utilisées, // mais il est inutile de le signaler puisque c'est généré par Axis if (!className.endsWith("SoapBindingStub")) { final ClassNode classNode = new ClassNode(); final ClassReader classReader = createClassReader(dir, className); classReader.accept(classNode, ClassReader.EXPAND_FRAMES); for (final MethodNode methodNode : (List<MethodNode>) classNode.methods) { analyzeMethodForLocalDeadCode(dir, className, classNode, methodNode); analyzeMethodForSelfAssignments(className, methodNode); if (Factory.createStringToStringAnalyzer(methodNode).analyze()) { report.reportStringToString(className, methodNode); suspectCount++; } } } } }
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 ClassVisitor(Opcodes.ASM5) { @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); }
@Override protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) { // logger.log(pathName); if (reMapping.containsKey(pathName.substring(0, pathName.length() - 6))) { logger.info("[ClazzReplacer] remove class " + pathName + " form " + jarFile); return; } try { InputStream in = jarFile.getInputStream(ze); ClassReader cr = new ClassReader(in); ClassWriter cw = new ClassWriter(0); RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping)); cr.accept(remappingClassAdapter, ClassReader.EXPAND_FRAMES); InputStream inputStream = new ByteArrayInputStream(cw.toByteArray()); copyStreamToJar(inputStream, jos, pathName, ze.getTime()); } catch (Throwable e) { System.err.println("[ClazzReplacer] rewrite error > " + pathName); justCopy(jarFile, jos, ze, pathName); } }
public byte[] transformCode(byte[] b1, String className) throws IOException { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassReader cr = new ClassReader(b1); ClassNode classNode = new ClassNode(); Map<String, Boolean> methodInstructionTypeMap = new HashMap<>(); cr.accept(classNode, 0); final List<MethodNode> methods = classNode.methods; for (MethodNode m : methods) { InsnList inList = m.instructions; boolean isMethodInvoke = false; for (int i = 0; i < inList.size(); i++) { if (inList.get(i).getType() == AbstractInsnNode.METHOD_INSN) { isMethodInvoke = true; } } methodInstructionTypeMap.put(m.name + m.desc, isMethodInvoke); } InsertMethodBodyAdapter insertMethodBodyAdapter = new InsertMethodBodyAdapter(cw, className, methodInstructionTypeMap); cr.accept(insertMethodBodyAdapter, ClassReader.EXPAND_FRAMES); return cw.toByteArray(); }
/** * Verify class bytecode * * @param classBytes Class data * @return Class data, if it was valid * @throws ClassFormatError If class wasn't valid */ @Contract("null -> fail") public static byte[] checkGeneratedClass(byte[] classBytes) throws ClassFormatError { Ensure.notNull(classBytes, "Class data shouldn't be null!"); ClassReader cr = new ClassReader(classBytes); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { CheckClassAdapter.verify(cr, false, pw); } catch (Exception ignored) {} if(sw.toString().length() > 0) { throw new ClassFormatError(sw.toString()); } return classBytes; }
@Test public void onClasspath() throws Exception { final boolean[] has = {false}; final JvmClass[] clazz = new JvmClass[1]; Classpath.from(getClass().getClassLoader()).index().forEach((jvmClass -> { System.out.println(jvmClass.getName()); if (!has[0]) { has[0] = true; clazz[0] = jvmClass; } })); byte[] bytes = clazz[0].toBytes(); ClassReader classReader = new ClassReader(bytes); ClassNode classNode = new ClassNode(); classReader.accept(classNode, 0); classNode.name = "meow/Meow"; Classpath.from(getClass().getClassLoader()).loadClass(new JvmClass(classNode)); Class<?> newClazz = Class.forName("meow.Meow"); System.out.println(newClazz.getName()); }
/** * Returns true if the given type implements the given interface. * * @param type * the internal name of a class or interface. * @param info * the ClassReader corresponding to 'type'. * @param itf * the internal name of a interface. * @return true if 'type' implements directly or indirectly 'itf' * @throws IOException * if the bytecode of 'type' or of some of its ancestor class * cannot be loaded. */ private boolean typeImplements(String type, ClassReader info, String itf) throws IOException { while (!"java/lang/Object".equals(type)) { String[] itfs = info.getInterfaces(); for (int i = 0; i < itfs.length; ++i) { if (itfs[i].equals(itf)) { return true; } } for (int i = 0; i < itfs.length; ++i) { if (typeImplements(itfs[i], typeInfo(itfs[i]), itf)) { return true; } } type = info.getSuperName(); info = typeInfo(type); } return false; }
private Class<?> instrumentClass(ClassName className) throws ClassNotFoundException { try (InputStream is = classLoader.getResourceAsStream(className.getAsResourcePath())) { if (is == null) { System.out.println("Failed to find resource file for "+className.getAsResourcePath()); return null; } byte[] byteBuffer = instrumentator.transformBytes(this, className, new ClassReader(is)); createPackageDefinition(className.getFullNameWithDots()); Class<?> result = defineClass(className.getFullNameWithDots(), byteBuffer, 0, byteBuffer.length); classes.put(className.getFullNameWithDots(), result); return result; } catch (Throwable t) { throw new ClassNotFoundException("Error while loading class" + className.getFullNameWithDots() + " : " + t.getMessage(), t); } }
/** * Check to see if a class is well-formed. * * @param logger the logger to write to if a problem is found * @param logTag a tag to print to the log if a problem is found * @param classNode the class to check * @return true if the class is ok, false otherwise */ public static boolean isClassOk(final Logger logger, final String logTag, final ClassNode classNode) { final StringWriter sw = new StringWriter(); final ClassWriter verifyWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(verifyWriter); final ClassReader ver = new ClassReader(verifyWriter.toByteArray()); try { DrillCheckClassAdapter.verify(ver, false, new PrintWriter(sw)); } catch(final Exception e) { logger.info("Caught exception verifying class:"); logClass(logger, logTag, classNode); throw e; } final String output = sw.toString(); if (!output.isEmpty()) { logger.info("Invalid class:\n" + output); return false; } return true; }
public static void main(String[] args) throws Exception { final String k2 = "org/apache/drill/Pickle.class"; final URL url = Resources.getResource(k2); final byte[] clazz = Resources.toByteArray(url); final ClassReader cr = new ClassReader(clazz); final ClassWriter cw = writer(); final TraceClassVisitor visitor = new TraceClassVisitor(cw, new Textifier(), new PrintWriter(System.out)); final ValueHolderReplacementVisitor v2 = new ValueHolderReplacementVisitor(visitor, true); cr.accept(v2, ClassReader.EXPAND_FRAMES );//| ClassReader.SKIP_DEBUG); final byte[] output = cw.toByteArray(); Files.write(output, new File("/src/scratch/bytes/S.class")); check(output); final DrillConfig c = DrillConfig.forClient(); final SystemOptionManager m = new SystemOptionManager(c, new LocalPStoreProvider(c)); m.init(); try (QueryClassLoader ql = new QueryClassLoader(DrillConfig.create(), m)) { ql.injectByteCode("org.apache.drill.Pickle$OutgoingBatch", output); Class<?> clz = ql.loadClass("org.apache.drill.Pickle$OutgoingBatch"); clz.getMethod("x").invoke(null); } }
@Override public Map<String, ClassNode> load() throws IOException { Map<String, ClassNode> classes = new HashMap<String, ClassNode>(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(jar.getInputStream(entry)); reader.accept(node, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); classes.put(node.name.replace(".class", ""), node); } else { if (name.contains("MANIFEST")) { continue; } otherFiles.put(name, entry); loadResource(name, jar.getInputStream(entry)); } } return classes; }
public AsmFlagsPanel() { //@formatter:off setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createTitledBorder("Input Flags")); p1.setLayout(new GridLayout(0, 2)); p1.add(inE = new ActionCheckBox("Expand Frames", Access.hasAccess(getOptions().classFlagsInput, ClassReader.EXPAND_FRAMES), (b) -> update())); p1.add(inD = new ActionCheckBox("Skip Debug", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_DEBUG), (b) -> update())); p1.add(inF = new ActionCheckBox("Skip Frames", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_FRAMES), (b) -> update())); p1.add(inC = new ActionCheckBox("Skip Code", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_CODE), (b) -> update())); JPanel p2 = new JPanel(); p2.setBorder(BorderFactory.createTitledBorder("Output Flags")); p2.setLayout(new GridLayout(0, 2)); p2.add(outF = new ActionCheckBox("Compute Frames", Access.hasAccess(getOptions().classFlagsOutput, ClassWriter.COMPUTE_FRAMES), (b) -> update())); p2.add(outM = new ActionCheckBox("Compute Maxs", Access.hasAccess(getOptions().classFlagsOutput, ClassWriter.COMPUTE_MAXS), (b) -> update())); add(p1); add(p2); //@formatter:on }
private static List<Map<String, Object>> processInput(File input) { List<Map<String, Object>> output = new ArrayList<>(); InfoClassVisitor visitor = new InfoClassVisitor(output); try (ZipInputStream zip = new ZipInputStream(new FileInputStream(input))) { ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { if (!entry.getName().endsWith(".class")) { continue; } ClassReader cr = new ClassReader(zip); cr.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } } catch (IOException ex) { ex.printStackTrace(); return null; } return output; }
/** * Extracts an API class from a given original class. * * @param originalClassReader the reader containing the original class * @return bytecode of the API class extracted from the original class */ public byte[] extractApiClassFrom(ClassReader originalClassReader) { ClassWriter apiClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); originalClassReader.accept( new ApiMemberSelector(new MethodStubbingApiMemberAdapter(apiClassWriter), apiIncludesPackagePrivateMembers), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return apiClassWriter.toByteArray(); }
private byte[] remapClass(String className, byte[] bytes) { ClassReader classReader = new ClassReader(bytes); ClassWriter classWriter = new ClassWriter(0); ClassVisitor remappingVisitor = new ShadingClassRemapper(classWriter, remapper); try { classReader.accept(remappingVisitor, ClassReader.EXPAND_FRAMES); } catch (Exception e) { throw new GradleException("Error in ASM processing class: " + className, e); } return classWriter.toByteArray(); }
public ClassAnalysis getClassAnalysis(String className, InputStream input) throws IOException { ClassRelevancyFilter filter = new ClassRelevancyFilter(className); ClassReader reader = new Java9ClassReader(ByteStreams.toByteArray(input)); ClassDependenciesVisitor visitor = new ClassDependenciesVisitor(); reader.accept(visitor, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); Set<String> classDependencies = getClassDependencies(filter, reader); return new ClassAnalysis(classDependencies, visitor.dependentToAll); }
public static byte[] apply(final @Nonnull byte[] bytes, final @Nonnull String name, final @Nonnull TransformProvider context) { Validate.notNull(bytes); final ClassReader cr = new ClassReader(bytes); final ClassWriter cw = new ClassWriter(cr, context.flags); final ClassVisitor mod = context.createVisitor(name, cw); try { cr.accept(mod, 0); return cw.toByteArray(); } catch (final StopTransforming e) { return bytes; } }
@Override protected byte[] transform(String className, byte[] bytes) { ClassReader classReader = new Java9ClassReader(bytes); ClassWriter classWriter = new ClassWriter(0); classReader.accept(new TransformingAdapter(classWriter), 0); bytes = classWriter.toByteArray(); return bytes; }
/** * Returns a ClassReader corresponding to the given class or interface. * * @param type * the internal name of a class or interface. * @return the ClassReader corresponding to 'type'. * @throws IOException * if the bytecode of 'type' cannot be loaded. * @throws NullPointerException * if the bytecode of 'type' cannot be found. */ private ClassReader typeInfo(final String type) throws IOException, NullPointerException { InputStream is = l.getResourceAsStream(type + ".class"); try { if(is == null) throw new NullPointerException("Class not found "+type); return new ClassReader(is); } finally { if(is != null) is.close(); } }
@Override public byte[] apply(byte[] origin) { ClassReader reader = new ClassReader(origin); PredicateClassVisitor precondition = new PredicateClassVisitor(); reader.accept(precondition, SKIP_DEBUG | SKIP_FRAMES); if (!precondition.isAttemptToVisitR()) { return origin; } // don't pass reader to the writer. // or it will copy 'CONSTANT POOL' that contains no used entries to lead proguard running failed! ClassWriter writer = new ClassWriter(0); ClassVisitor visitor = new ShrinkRClassVisitor(writer, rSymbols); reader.accept(visitor, 0); return writer.toByteArray(); }
private void processEntry(final ZipInputStream zis, final ZipEntry ze, final ContentHandlerFactory handlerFactory) { ContentHandler handler = handlerFactory.createContentHandler(); try { // if (CODE2ASM.equals(command)) { // read bytecode and process it // // with TraceClassVisitor // ClassReader cr = new ClassReader(readEntry(zis, ze)); // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)), // false); // } boolean singleInputDocument = inRepresentation == SINGLE_XML; if (inRepresentation == BYTECODE) { // read bytecode and process it // with handler ClassReader cr = new ClassReader(readEntry(zis, ze)); cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0); } else { // read XML and process it with handler XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource( singleInputDocument ? (InputStream) new ProtectedInputStream( zis) : new ByteArrayInputStream(readEntry(zis, ze)))); } } catch (Exception ex) { update(ze.getName(), 0); update(ex, 0); } }