forked from soot-oss/soot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDexFileProvider.java
More file actions
300 lines (262 loc) · 10.4 KB
/
DexFileProvider.java
File metadata and controls
300 lines (262 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package soot.dexpler;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.MultiDexContainer;
import org.jf.dexlib2.iface.MultiDexContainer.DexEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.CompilationDeathException;
import soot.G;
import soot.Scene;
import soot.Singletons;
import soot.options.Options;
/**
* Class providing dex files from a given source, e.g., jar, apk, dex, folder containing multiple dex files
*
* @author Manuel Benz created on 16.10.17
*/
public class DexFileProvider {
private static final Logger logger = LoggerFactory.getLogger(DexFileProvider.class);
private final static Comparator<DexContainer<? extends DexFile>> DEFAULT_PRIORITIZER
= new Comparator<DexContainer<? extends DexFile>>() {
@Override
public int compare(DexContainer<? extends DexFile> o1, DexContainer<? extends DexFile> o2) {
String s1 = o1.getDexName(), s2 = o2.getDexName();
// "classes.dex" has highest priority
if (s1.equals("classes.dex")) {
return 1;
} else if (s2.equals("classes.dex")) {
return -1;
}
// if one of the strings starts with "classes", we give it the edge right here
boolean s1StartsClasses = s1.startsWith("classes");
boolean s2StartsClasses = s2.startsWith("classes");
if (s1StartsClasses && !s2StartsClasses) {
return 1;
} else if (s2StartsClasses && !s1StartsClasses) {
return -1;
}
// otherwise, use natural string ordering
return s1.compareTo(s2);
}
};
/**
* Mapping of filesystem file (apk, dex, etc.) to mapping of dex name to dex file
*/
private final Map<String, Map<String, DexContainer<? extends DexFile>>> dexMap = new HashMap<>();
public DexFileProvider(Singletons.Global g) {
}
public static DexFileProvider v() {
return G.v().soot_dexpler_DexFileProvider();
}
/**
* Returns all dex files found in dex source sorted by the default dex prioritizer
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @return List of dex files derived from source
*/
public List<DexContainer<? extends DexFile>> getDexFromSource(File dexSource) throws IOException {
return getDexFromSource(dexSource, DEFAULT_PRIORITIZER);
}
/**
* Returns all dex files found in dex source sorted by the default dex prioritizer
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @param prioritizer
* A comparator that defines the ordering of dex files in the result list
* @return List of dex files derived from source
*/
public List<DexContainer<? extends DexFile>> getDexFromSource(File dexSource,
Comparator<DexContainer<? extends DexFile>> prioritizer) throws IOException {
ArrayList<DexContainer<? extends DexFile>> resultList = new ArrayList<>();
List<File> allSources = allSourcesFromFile(dexSource);
updateIndex(allSources);
for (File theSource : allSources) {
resultList.addAll(dexMap.get(theSource.getCanonicalPath()).values());
}
if (resultList.size() > 1) {
Collections.sort(resultList, Collections.reverseOrder(prioritizer));
}
return resultList;
}
/**
* Returns the first dex file with the given name found in the given dex source
*
* @param dexSource
* Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @return Dex file with given name in dex source
* @throws CompilationDeathException
* If no dex file with the given name exists
*/
public DexContainer<? extends DexFile> getDexFromSource(File dexSource, String dexName) throws IOException {
List<File> allSources = allSourcesFromFile(dexSource);
updateIndex(allSources);
// we take the first dex we find with the given name
for (File theSource : allSources) {
DexContainer<? extends DexFile> dexFile = dexMap.get(theSource.getCanonicalPath()).get(dexName);
if (dexFile != null) {
return dexFile;
}
}
throw new CompilationDeathException("Dex file with name '" + dexName + "' not found in " + dexSource);
}
private List<File> allSourcesFromFile(File dexSource) throws IOException {
if (dexSource.isDirectory()) {
List<File> dexFiles = getAllDexFilesInDirectory(dexSource);
if (dexFiles.size() > 1 && !Options.v().process_multiple_dex()) {
File file = dexFiles.get(0);
logger.warn("Multiple dex files detected, only processing '" + file.getCanonicalPath()
+ "'. Use '-process-multiple-dex' option to process them all.");
return Collections.singletonList(file);
} else {
return dexFiles;
}
} else {
String ext = com.google.common.io.Files.getFileExtension(dexSource.getName()).toLowerCase();
if ((ext.equals("jar") || ext.equals("zip")) && !Options.v().search_dex_in_archives()) {
return Collections.emptyList();
} else {
return Collections.singletonList(dexSource);
}
}
}
private void updateIndex(List<File> dexSources) throws IOException {
for (File theSource : dexSources) {
String key = theSource.getCanonicalPath();
Map<String, DexContainer<? extends DexFile>> dexFiles = dexMap.get(key);
if (dexFiles == null) {
try {
dexFiles = mappingForFile(theSource);
dexMap.put(key, dexFiles);
} catch (IOException e) {
throw new CompilationDeathException("Error parsing dex source", e);
}
}
}
}
/**
* @param dexSourceFile
* A file containing either one or multiple dex files (apk, zip, etc.) but no directory!
* @return
* @throws IOException
*/
private Map<String, DexContainer<? extends DexFile>> mappingForFile(File dexSourceFile) throws IOException {
int api = Scene.v().getAndroidAPIVersion();
boolean multiple_dex = Options.v().process_multiple_dex();
// load dex files from apk/folder/file
MultiDexContainer<? extends DexBackedDexFile> dexContainer
= DexFileFactory.loadDexContainer(dexSourceFile, Opcodes.forApi(api));
List<String> dexEntryNameList = dexContainer.getDexEntryNames();
int dexFileCount = dexEntryNameList.size();
if (dexFileCount < 1) {
if (Options.v().verbose()) {
logger.debug("" + String.format("Warning: No dex file found in '%s'", dexSourceFile));
}
return Collections.emptyMap();
}
Map<String, DexContainer<? extends DexFile>> dexMap = new HashMap<>(dexFileCount);
// report found dex files and add to list.
// We do this in reverse order to make sure that we add the first entry if there is no classes.dex file in single dex
// mode
ListIterator<String> entryNameIterator = dexEntryNameList.listIterator(dexFileCount);
while (entryNameIterator.hasPrevious()) {
String entryName = entryNameIterator.previous();
DexEntry<? extends DexFile> entry = dexContainer.getEntry(entryName);
entryName = deriveDexName(entryName);
logger.debug("" + String.format("Found dex file '%s' with %d classes in '%s'", entryName,
entry.getDexFile().getClasses().size(), dexSourceFile.getCanonicalPath()));
if (multiple_dex) {
dexMap.put(entryName, new DexContainer<>(entry, entryName, dexSourceFile));
} else if (dexMap.isEmpty() && (entryName.equals("classes.dex") || !entryNameIterator.hasPrevious())) {
// We prefer to have classes.dex in single dex mode.
// If we haven't found a classes.dex until the last element, take the last!
dexMap = Collections.singletonMap(entryName, new DexContainer<>(entry, entryName, dexSourceFile));
if (dexFileCount > 1) {
logger.warn("Multiple dex files detected, only processing '" + entryName
+ "'. Use '-process-multiple-dex' option to process them all.");
}
}
}
return Collections.unmodifiableMap(dexMap);
}
private String deriveDexName(String entryName) {
return new File(entryName).getName();
}
private List<File> getAllDexFilesInDirectory(File path) {
Queue<File> toVisit = new ArrayDeque<File>();
Set<File> visited = new HashSet<File>();
List<File> ret = new ArrayList<File>();
toVisit.add(path);
while (!toVisit.isEmpty()) {
File cur = toVisit.poll();
if (visited.contains(cur)) {
continue;
}
visited.add(cur);
if (cur.isDirectory()) {
toVisit.addAll(Arrays.asList(cur.listFiles()));
} else if (cur.isFile() && cur.getName().endsWith(".dex")) {
ret.add(cur);
}
}
return ret;
}
public static final class DexContainer<T extends DexFile> {
private final DexEntry<T> base;
private final String name;
private final File filePath;
public DexContainer(DexEntry<T> base, String name, File filePath) {
this.base = base;
this.name = name;
this.filePath = filePath;
}
public DexEntry<T> getBase() {
return base;
}
public String getDexName() {
return name;
}
public File getFilePath() {
return filePath;
}
}
}