-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathDexFactory.java
More file actions
391 lines (324 loc) · 14.4 KB
/
Copy pathDexFactory.java
File metadata and controls
391 lines (324 loc) · 14.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package com.tns;
import android.util.Log;
import com.tns.bindings.AnnotationDescriptor;
import com.tns.bindings.ProxyGenerator;
import com.tns.bindings.desc.ClassDescriptor;
import com.tns.bindings.desc.reflection.ClassInfo;
import com.tns.system.classes.loading.ClassStorageService;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InvalidClassException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import dalvik.system.DexClassLoader;
public class DexFactory {
private static final String COM_TNS_GEN_PREFIX = "com.tns.gen.";
private final Logger logger;
private final File dexDir;
private final File odexDir;
private final String dexThumb;
private final ClassLoader classLoader;
private final ClassStorageService classStorageService;
private ProxyGenerator proxyGenerator;
private HashMap<String, Class<?>> injectedDexClasses = new HashMap<String, Class<?>>();
DexFactory(Logger logger, ClassLoader classLoader, File dexBaseDir, String dexThumb, ClassStorageService classStorageService) {
this.logger = logger;
this.classLoader = classLoader;
this.dexDir = dexBaseDir;
this.dexThumb = dexThumb;
this.odexDir = new File(this.dexDir, "odex");
this.proxyGenerator = new ProxyGenerator(this.dexDir.getAbsolutePath());
ProxyGenerator.IsLogEnabled = logger.isEnabled();
if (!dexDir.exists()) {
dexDir.mkdirs();
}
if (!odexDir.exists()) {
odexDir.mkdir();
}
if (!dexDir.exists() || !dexDir.canWrite()) {
Log.w("JS", "DexFactory: dexDir unusable at init path=" + dexDir.getAbsolutePath()
+ " exists=" + dexDir.exists() + " canWrite=" + dexDir.canWrite());
}
this.updateDexThumbAndPurgeCache();
this.proxyGenerator.setProxyThumb(this.dexThumb);
this.classStorageService = classStorageService;
}
static long totalGenTime = 0;
static long totalMultiDexTime = 0;
static long totalLoadDexTime = 0;
public Class<?> resolveClass(String baseClassName, String name, String className, String[] methodOverrides, String[] implementedInterfaces, boolean isInterface) throws ClassNotFoundException, IOException {
String fullClassName = className.replace("$", "_");
String originalFullClassName = fullClassName;
// try to get pre-generated binding classes
try {
if (logger.isEnabled()) {
logger.write("getting pre-generated proxy class with name: " + fullClassName.replace("-", "_"));
}
Class<?> pregeneratedClass = classLoader.loadClass(fullClassName.replace("-", "_"));
if (logger.isEnabled()) {
logger.write("Pre-generated class found: " + fullClassName.replace("-", "_"));
}
return pregeneratedClass;
} catch (Exception e) {
if (logger.isEnabled()) {
logger.write("Pre-generated class not found: " + fullClassName.replace("-", "_"));
}
}
//
// new: com.tns.gen.android.widget.DatePicker_MyActivity_59_56_
// old: com.tns.tests.Button1_fMyActivity_l56_c44__MyButton
// ne1: com.tns.tests.Button1_MyActivity_58_44_MyButton_0
Class<?> existingClass = this.injectedDexClasses.get(fullClassName);
if (existingClass != null) {
return existingClass;
}
String classToProxy;
if (!baseClassName.isEmpty()) {
classToProxy = this.getClassToProxyName(baseClassName);
} else {
classToProxy = this.getClassToProxyName(className);
}
// strip the `com.tns.gen` off the base extended class name
String desiredDexClassName = this.getClassToProxyName(fullClassName);
// when interfaces are extended as classes, we still want to preserve
// just the interface name without the extra file, line, column information
if (!baseClassName.isEmpty() && isInterface) {
fullClassName = COM_TNS_GEN_PREFIX + classToProxy;
}
File dexFile = this.getDexFile(desiredDexClassName);
// generate dex file
if (dexFile == null) {
long startGenTime = System.nanoTime();
if (logger.isEnabled()) {
logger.write("generating proxy in place");
}
String dexFilePath;
try {
if (isInterface) {
dexFilePath = this.generateDex(name, classToProxy, methodOverrides, implementedInterfaces, isInterface);
} else {
dexFilePath = this.generateDex(desiredDexClassName, classToProxy, methodOverrides, implementedInterfaces, isInterface);
}
} catch (IOException e) {
String diag = "DexFactory.generateDex failed class=" + className
+ " baseClass=" + baseClassName
+ " isInterface=" + isInterface
+ " dexDir=" + dexDir.getAbsolutePath()
+ " dexDir.exists=" + dexDir.exists()
+ " dexDir.canWrite=" + dexDir.canWrite()
+ " dexThumb=" + dexThumb;
Log.e("JS", diag + " | " + e.getMessage());
throw new IOException(diag + " | " + e.getMessage(), e);
}
dexFile = new File(dexFilePath);
long stopGenTime = System.nanoTime();
totalGenTime += stopGenTime - startGenTime;
if (logger.isEnabled()) {
logger.write("Finished inplace gen took: " + (stopGenTime - startGenTime) / 1000000.0 + "ms");
logger.write("TotalGenTime: " + totalGenTime / 1000000.0 + "ms");
}
}
// creates jar file from already generated dex file
String jarFilePath = dexFile.getPath().replace(".dex", ".jar");
File jarFile = new File(jarFilePath);
if (!jarFile.exists()) {
FileOutputStream jarFileStream = new FileOutputStream(jarFile);
ZipOutputStream out = new ZipOutputStream(jarFileStream);
out.putNextEntry(new ZipEntry("classes.dex"));
byte[] dexData = new byte[(int) dexFile.length()];
FileInputStream fi = new FileInputStream(dexFile);
fi.read(dexData, 0, dexData.length);
fi.close();
out.write(dexData);
out.closeEntry();
out.close();
}
jarFile.setReadOnly();
Class<?> result;
DexClassLoader dexClassLoader = new DexClassLoader(jarFilePath, this.odexDir.getAbsolutePath(), null, classLoader);
if (isInterface) {
result = dexClassLoader.loadClass(fullClassName);
} else {
result = dexClassLoader.loadClass(desiredDexClassName);
}
classStorageService.storeClass(result.getName(), result);
this.injectedDexClasses.put(originalFullClassName, result);
return result;
}
public Class<?> findClass(String className) throws ClassNotFoundException {
String canonicalName = className.replace('/', '.');
if (logger.isEnabled()) {
logger.write(canonicalName);
}
Class<?> existingClass = this.injectedDexClasses.get(canonicalName);
if (existingClass != null) {
return existingClass;
}
return classLoader.loadClass(canonicalName);
}
public static String strJoin(String[] array, String separator) {
if (array == null) {
return "";
}
StringBuilder sbStr = new StringBuilder();
for (int i = 0, il = array.length; i < il; i++) {
if (i > 0) {
sbStr.append(separator);
}
sbStr.append(array[i]);
}
return sbStr.toString();
}
private String getClassToProxyName(String className) throws InvalidClassException {
String classToProxy = className;
if (className.startsWith(COM_TNS_GEN_PREFIX)) {
classToProxy = className.substring(12);
}
if (classToProxy.startsWith(COM_TNS_GEN_PREFIX)) {
throw new InvalidClassException("Can't generate proxy of proxy");
}
return classToProxy;
}
private File getDexFile(String className) throws InvalidClassException {
String classToProxyFile = className.replace("$", "_");
if (this.dexThumb != null) {
classToProxyFile += "-" + this.dexThumb;
}
String dexFilePath = dexDir + "/" + classToProxyFile + ".dex";
File dexFile = new File(dexFilePath);
if (dexFile.exists()) {
if (logger.isEnabled()) {
logger.write("Looking for proxy file: " + dexFilePath + " Result: proxy file Found. ClassName: " + className);
}
return dexFile;
}
if (logger.isEnabled()) {
logger.write("Looking for proxy file: " + dexFilePath + " Result: NOT Found. Proxy Gen needed. ClassName: " + className);
}
return null;
}
private String generateDex(String proxyName, String className, String[] methodOverrides, String[] implementedInterfaces, boolean isInterface) throws ClassNotFoundException, IOException {
Class<?> classToProxy = Class.forName(className);
HashSet<String> methodOverridesSet = null;
HashSet<ClassDescriptor> implementedInterfacesSet = new HashSet<ClassDescriptor>();
if (methodOverrides != null) {
methodOverridesSet = new HashSet<String>();
for (int i = 0; i < methodOverrides.length; i++) {
String methodOverride = methodOverrides[i];
methodOverridesSet.add(methodOverride);
}
}
if (implementedInterfaces.length > 0) {
for (int j = 0; j < implementedInterfaces.length; j++) {
if (!implementedInterfaces[j].isEmpty()) {
implementedInterfacesSet.add(new ClassInfo(Class.forName(implementedInterfaces[j])));
}
}
}
AnnotationDescriptor[] annotations = null;
return proxyGenerator.generateProxy(proxyName, new ClassInfo(classToProxy), methodOverridesSet, implementedInterfacesSet, isInterface, annotations);
}
private void updateDexThumbAndPurgeCache() {
if (this.dexThumb == null) {
throw new RuntimeException("Error generating proxy thumb 1");
}
String oldDexThumb = this.getCachedProxyThumb(this.dexDir);
if (this.dexThumb.equals(oldDexThumb)) {
return;
}
if (oldDexThumb != null) {
this.purgeDexesByThumb(oldDexThumb, this.dexDir);
this.purgeDexesByThumb(oldDexThumb, this.odexDir);
} else {
// purge all dex files if no thumb file is found. This is crucial for CLI livesync
purgeAllProxies();
}
this.saveNewDexThumb(this.dexThumb, this.dexDir);
}
public void purgeAllProxies() {
this.purgeDexesByThumb(null, this.dexDir);
this.purgeDexesByThumb(null, this.odexDir);
}
private void saveNewDexThumb(String newDexThumb, File dexDir) {
File cachedThumbFile = new File(dexDir, "proxyThumb");
try {
FileOutputStream out = new FileOutputStream(cachedThumbFile, false);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
try {
writer.write(newDexThumb);
writer.newLine();
writer.flush();
} finally {
writer.close();
out.close();
}
} catch (FileNotFoundException e) {
Log.w("JS", String.format("Error while writing current proxy thumb: %s", e.getMessage()));
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
} catch (IOException e) {
Log.w("JS", String.format("Error while writing current proxy thumb: %s", e.getMessage()));
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
private void purgeDexesByThumb(String cachedDexThumb, File pathToPurge) {
if (!pathToPurge.exists()) {
return;
}
if (!pathToPurge.isDirectory()) {
logger.write("Purge proxies path not a directory. Path: " + pathToPurge);
throw new RuntimeException("Purge path not a directory");
}
String[] children = pathToPurge.list();
for (int i = 0; i < children.length; i++) {
String filename = children[i];
File purgeCandidate = new File(pathToPurge, filename);
if (purgeCandidate.isDirectory()) {
this.purgeDexesByThumb(cachedDexThumb, purgeCandidate);
} else {
if (cachedDexThumb != null && !filename.contains(cachedDexThumb)) {
continue;
}
if (!purgeCandidate.delete()) {
logger.write("Error purging cached proxy file: " + purgeCandidate.getAbsolutePath());
}
}
}
}
private String getCachedProxyThumb(File proxyDir) {
try {
File cachedThumbFile = new File(proxyDir, "proxyThumb");
if (cachedThumbFile.exists()) {
FileInputStream in = new FileInputStream(cachedThumbFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String cachedThumb = reader.readLine();
reader.close();
in.close();
return cachedThumb;
}
} catch (FileNotFoundException e) {
Log.w("JS", String.format("Error while writing current proxy thumb: %s", e.getMessage()));
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
} catch (IOException e) {
Log.w("JS", String.format("Error while writing current proxy thumb: %s", e.getMessage()));
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
return null;
}
}