Search in sources :

Example 21 with FileSystem

use of java.nio.file.FileSystem in project dex2jar by pxb1988.

the class Dex2jarMultiThreadCmd method run0.

private void run0(String fileName, final ExecutorService executorService) throws IOException {
    // long baseTS = System.currentTimeMillis();
    String baseName = getBaseName(new File(fileName).toPath());
    Path currentDir = new File(".").toPath();
    Path file = currentDir.resolve(baseName + "-dex2jar.jar");
    final Path errorFile = currentDir.resolve(baseName + "-error.zip");
    System.err.println("dex2jar " + fileName + " -> " + file);
    final BaksmaliBaseDexExceptionHandler exceptionHandler = new BaksmaliBaseDexExceptionHandler();
    BaseDexFileReader reader = MultiDexFileReader.open(Files.readAllBytes(new File(fileName).toPath()));
    DexFileNode fileNode = new DexFileNode();
    try {
        reader.accept(fileNode, DexFileReader.SKIP_DEBUG | DexFileReader.IGNORE_READ_EXCEPTION);
    } catch (Exception ex) {
        exceptionHandler.handleFileException(ex);
        throw ex;
    }
    final FileSystem fs = createZip(file);
    final Path dist = fs.getPath("/");
    ClassVisitorFactory cvf = new ClassVisitorFactory() {

        @Override
        public ClassVisitor create(final String name) {
            return new ClassVisitor(Opcodes.ASM4, new ClassWriter(ClassWriter.COMPUTE_MAXS)) {

                @Override
                public void visitEnd() {
                    super.visitEnd();
                    ClassWriter cw = (ClassWriter) super.cv;
                    byte[] data;
                    try {
                        // FIXME handle 'java.lang.RuntimeException: Method code too large!'
                        data = cw.toByteArray();
                    } catch (Exception ex) {
                        System.err.println(String.format("ASM fail to generate .class file: %s", name));
                        exceptionHandler.handleFileException(ex);
                        return;
                    }
                    try {
                        Path dist1 = dist.resolve(name + ".class");
                        BaseCmd.createParentDirectories(dist1);
                        Files.write(dist1, data);
                    } catch (IOException e) {
                        exceptionHandler.handleFileException(e);
                    }
                }
            };
        }
    };
    new ExDex2Asm(exceptionHandler) {

        @Override
        public void convertDex(DexFileNode fileNode, final ClassVisitorFactory cvf) {
            if (fileNode.clzs != null) {
                final Map<String, Clz> classes = collectClzInfo(fileNode);
                final List<Future<?>> results = new ArrayList<>(fileNode.clzs.size());
                for (final DexClassNode classNode : fileNode.clzs) {
                    results.add(executorService.submit(new Runnable() {

                        @Override
                        public void run() {
                            convertClass(classNode, cvf, classes);
                        }
                    }));
                }
                executorService.submit(new Runnable() {

                    @Override
                    public void run() {
                        for (Future<?> result : results) {
                            try {
                                result.get();
                            } catch (InterruptedException | ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                        BaksmaliBaseDexExceptionHandler exceptionHandler1 = (BaksmaliBaseDexExceptionHandler) exceptionHandler;
                        if (exceptionHandler1.hasException()) {
                            exceptionHandler1.dump(errorFile, new String[0]);
                        }
                        try {
                            fs.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }.convertDex(fileNode, cvf);
}
Also used : Path(java.nio.file.Path) ClassVisitor(org.objectweb.asm.ClassVisitor) IOException(java.io.IOException) IOException(java.io.IOException) ClassWriter(org.objectweb.asm.ClassWriter) DexClassNode(com.googlecode.d2j.node.DexClassNode) FileSystem(java.nio.file.FileSystem) DexFileNode(com.googlecode.d2j.node.DexFileNode) ClassVisitorFactory(com.googlecode.d2j.dex.ClassVisitorFactory) BaseDexFileReader(com.googlecode.d2j.reader.BaseDexFileReader) File(java.io.File) ExDex2Asm(com.googlecode.d2j.dex.ExDex2Asm)

Example 22 with FileSystem

use of java.nio.file.FileSystem in project dex2jar by pxb1988.

the class GenerateCompileStubFromOdex method doCommandLine.

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length == 0) {
        throw new HelpException("no odex");
    }
    if (output == null) {
        output = new File("stub.jar").toPath();
    }
    try (FileSystem fs = createZip(output)) {
        Path out = fs.getPath("/");
        for (String x : remainingArgs) {
            System.err.println("process " + x + " ...");
            ByteBuffer bs = ByteBuffer.wrap(Files.readAllBytes(new File(x).toPath())).order(ByteOrder.LITTLE_ENDIAN);
            int magic = bs.getInt(0) & 0x00FFFFFF;
            if (magic == MAGIC_ODEX) {
                int offset = bs.getInt(8);
                int length = bs.getInt(12);
                bs.position(offset);
                ByteBuffer n = (ByteBuffer) bs.slice().limit(length);
                doDex(n, out);
            } else if (magic == MAGIC_DEX) {
                doDex(bs, out);
            } else {
                throw new RuntimeException("file " + x + " is not an dex or odex");
            }
        }
    }
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) File(java.io.File) ByteBuffer(java.nio.ByteBuffer)

Example 23 with FileSystem

use of java.nio.file.FileSystem in project dex2jar by pxb1988.

the class Jar2Dex method doCommandLine.

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();
        return;
    }
    Path jar = new File(remainingArgs[0]).toPath();
    if (!Files.exists(jar)) {
        System.err.println(jar + " is not exists");
        usage();
        return;
    }
    if (output == null) {
        if (Files.isDirectory(jar)) {
            output = new File(jar.getFileName() + "-jar2dex.dex").toPath();
        } else {
            output = new File(getBaseName(jar.getFileName().toString()) + "-jar2dex.dex").toPath();
        }
    }
    if (Files.exists(output) && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    Path tmp = null;
    final Path realJar;
    try {
        if (Files.isDirectory(jar)) {
            realJar = Files.createTempFile("d2j", ".jar");
            tmp = realJar;
            System.out.println("zipping " + jar + " -> " + realJar);
            try (FileSystem fs = createZip(realJar)) {
                final Path outRoot = fs.getPath("/");
                walkJarOrDir(jar, new FileVisitorX() {

                    @Override
                    public void visitFile(Path file, String relative) throws IOException {
                        if (file.getFileName().toString().endsWith(".class")) {
                            Files.copy(file, outRoot.resolve(relative));
                        }
                    }
                });
            }
        } else {
            realJar = jar;
        }
        System.out.println("jar2dex " + realJar + " -> " + output);
        Class<?> c = Class.forName("com.android.dx.command.Main");
        Method m = c.getMethod("main", String[].class);
        List<String> ps = new ArrayList<String>();
        ps.addAll(Arrays.asList("--dex", "--no-strict", "--output=" + output.toAbsolutePath().toString(), realJar.toAbsolutePath().toString()));
        System.out.println("call com.android.dx.command.Main.main" + ps);
        m.invoke(null, new Object[] { ps.toArray(new String[ps.size()]) });
    } finally {
        if (tmp != null) {
            Files.deleteIfExists(tmp);
        }
    }
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Method(java.lang.reflect.Method) File(java.io.File)

Example 24 with FileSystem

use of java.nio.file.FileSystem in project dex2jar by pxb1988.

the class JarAccessCmd method doCommandLine.

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();
        return;
    }
    Path jar = new File(remainingArgs[0]).toPath();
    if (!Files.exists(jar)) {
        System.err.println(jar + " is not exists");
        usage();
        return;
    }
    if (output == null) {
        if (Files.isDirectory(jar)) {
            output = new File(jar.getFileName() + "-access.jar").toPath();
        } else {
            output = new File(getBaseName(jar.getFileName().toString()) + "-access.jar").toPath();
        }
    }
    if (Files.exists(output) && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }
    final int rf = ~str2acc(removeFieldAccess);
    final int rm = ~str2acc(removeMethodAccess);
    final int rc = ~str2acc(removeClassAccess);
    final int af = str2acc(addFieldAccess);
    final int am = str2acc(addMethodAccess);
    final int ac = str2acc(addClassAccess);
    final int flags = removeDebug ? ClassReader.SKIP_DEBUG : 0;
    try (FileSystem outFileSystem = createZip(output)) {
        final Path outRoot = outFileSystem.getPath("/");
        walkJarOrDir(jar, new FileVisitorX() {

            @Override
            public void visitFile(Path file, String relative) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    final ClassReader r = new ClassReader(Files.readAllBytes(file));
                    ClassWriter cr = new ClassWriter(0);
                    r.accept(new ClassVisitor(ASM4, cr) {

                        @Override
                        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
                            int na = (access & rc) | ac;
                            if (access != na) {
                                System.out.println("c " + name);
                            }
                            super.visit(version, na, name, signature, superName, interfaces);
                        }

                        @Override
                        public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
                            int na = (access & rf) | af;
                            if (na != access) {
                                System.out.println("f " + r.getClassName() + "." + name);
                            }
                            return super.visitField(na, name, desc, signature, value);
                        }

                        @Override
                        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                            int na = (access & rm) | am;
                            if (na != access) {
                                System.out.println("m " + r.getClassName() + "." + name + desc);
                            }
                            return super.visitMethod(na, name, desc, signature, exceptions);
                        }
                    }, flags | ClassReader.EXPAND_FRAMES);
                    Files.write(outRoot.resolve(relative), cr.toByteArray());
                } else {
                    Files.copy(file, outRoot.resolve(relative));
                }
            }
        });
    }
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) File(java.io.File)

Example 25 with FileSystem

use of java.nio.file.FileSystem in project dex2jar by pxb1988.

the class JarWeaverCmd method doCommandLine.

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length == 0) {
        throw new HelpException("no jar");
    }
    InvocationWeaver invocationWeaver = (InvocationWeaver) new InvocationWeaver().withConfig(config);
    try (FileSystem fs = createZip(output)) {
        final Path outRoot = fs.getPath("/");
        for (String str : remainingArgs) {
            Path p = new File(str).toPath();
            System.err.println(p + " -> " + output);
            if (Files.isDirectory(p)) {
                invocationWeaver.wave(p, outRoot);
            } else {
                try (FileSystem fs2 = openZip(p)) {
                    invocationWeaver.wave(fs2.getPath("/"), outRoot);
                }
            }
        }
        if (stub != null) {
            System.err.println(stub + " -> " + output);
            walkJarOrDir(stub, new FileVisitorX() {

                @Override
                public void visitFile(Path file, String relative) throws IOException {
                    Path out = outRoot.resolve(relative);
                    if (Files.exists(out)) {
                        System.err.println("skip " + relative + " in " + stub);
                    } else {
                        createParentDirectories(out);
                        Files.copy(file, out);
                    }
                }
            });
        }
    }
}
Also used : InvocationWeaver(com.googlecode.d2j.tools.jar.InvocationWeaver) Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) File(java.io.File)

Aggregations

FileSystem (java.nio.file.FileSystem)156 Path (java.nio.file.Path)109 Test (org.junit.Test)66 IOException (java.io.IOException)25 File (java.io.File)17 ArrayList (java.util.ArrayList)14 FilterFileSystem (org.apache.lucene.mockfile.FilterFileSystem)13 FilterPath (org.apache.lucene.mockfile.FilterPath)11 InputStream (java.io.InputStream)10 OutputStream (java.io.OutputStream)10 URI (java.net.URI)10 FileStore (java.nio.file.FileStore)8 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)6 HashMap (java.util.HashMap)6 DefaultProjectFilesystemDelegate (com.facebook.buck.io.DefaultProjectFilesystemDelegate)5 ProjectFilesystemDelegate (com.facebook.buck.io.ProjectFilesystemDelegate)5 WindowsFS (org.apache.lucene.mockfile.WindowsFS)5 FSDirectory (org.apache.lucene.store.FSDirectory)5 BuckConfig (com.facebook.buck.cli.BuckConfig)4 FakeBuckConfig (com.facebook.buck.cli.FakeBuckConfig)4