• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2023 Code Intelligence GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.code_intelligence.jazzer.android;
18 
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.lang.Math;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Enumeration;
29 import java.util.jar.JarEntry;
30 import java.util.jar.JarFile;
31 
32 public class DexFileManager {
33   private final static int MAX_READ_LENGTH = 2000000;
34 
getBytecodeFromDex(String jarPath, String dexFile)35   public static byte[] getBytecodeFromDex(String jarPath, String dexFile) throws IOException {
36     try (JarFile jarFile = new JarFile(jarPath)) {
37       JarEntry entry = jarFile.stream()
38                            .filter(jarEntry -> jarEntry.getName().equals(dexFile))
39                            .findFirst()
40                            .orElse(null);
41 
42       if (entry == null) {
43         throw new IOException("Could not find dex file: " + dexFile);
44       }
45 
46       try (InputStream is = jarFile.getInputStream(entry)) {
47         ByteArrayOutputStream out = new ByteArrayOutputStream();
48 
49         byte[] buffer = new byte[64 * 104 * 1024];
50         int read;
51         while ((read = is.read(buffer)) != -1) {
52           out.write(buffer, 0, read);
53         }
54 
55         return out.toByteArray();
56       }
57     }
58   }
59 
getDexFilesForJar(String jarpath)60   public static String[] getDexFilesForJar(String jarpath) throws IOException {
61     try (JarFile jarFile = new JarFile(jarpath)) {
62       return jarFile.stream()
63           .map(JarEntry::getName)
64           .filter(entry -> entry.endsWith(".dex"))
65           .toArray(String[] ::new);
66     }
67   }
68 }
69