aboutsummaryrefslogtreecommitdiff
path: root/dexlib2/src/main/java/org/jf/dexlib2/analysis/ClassPath.java
blob: 4b8920f425f549fe0199840e5715e37fe36cf992 (plain)
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
/*
 * Copyright 2013, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.jf.dexlib2.analysis;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.*;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.DexFileFactory.DexFileNotFound;
import org.jf.dexlib2.DexFileFactory.MultipleDexFilesException;
import org.jf.dexlib2.analysis.reflection.ReflectionClassDef;
import org.jf.dexlib2.dexbacked.OatFile.OatDexFile;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.immutable.ImmutableDexFile;
import org.jf.util.ExceptionWithContext;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClassPath {
    @Nonnull private final TypeProto unknownClass;
    @Nonnull private HashMap<String, ClassDef> availableClasses = Maps.newHashMap();
    private boolean checkPackagePrivateAccess;
    public boolean isArt;

    /**
     * Creates a new ClassPath instance that can load classes from the given dex files
     *
     * @param classPath An array of DexFile objects. When loading a class, these dex files will be searched in order
     */
    public ClassPath(DexFile... classPath) throws IOException {
        this(Lists.newArrayList(classPath), 15);
    }

    /**
     * Creates a new ClassPath instance that can load classes from the given dex files
     *
     * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
     * @param api API level
     */
    public ClassPath(@Nonnull Iterable<DexFile> classPath, int api) {
        this(Lists.newArrayList(classPath), api == 17);
    }

    /**
     * Creates a new ClassPath instance that can load classes from the given dex files
     *
     * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
     * @param checkPackagePrivateAccess Whether checkPackagePrivateAccess is needed, enabled for ONLY early API 17 by
     *                                  default
     */
    public ClassPath(@Nonnull Iterable<DexFile> classPath, boolean checkPackagePrivateAccess) {
        this(classPath, checkPackagePrivateAccess, false);
    }

    /**
     * Creates a new ClassPath instance that can load classes from the given dex files
     *
     * @param classPath An iterable of DexFile objects. When loading a class, these dex files will be searched in order
     * @param checkPackagePrivateAccess Whether checkPackagePrivateAccess is needed, enabled for ONLY early API 17 by
     *                                  default
     * @param isArt Whether this is ClassPath is for ART
     */
    public ClassPath(@Nonnull Iterable < DexFile > classPath, boolean checkPackagePrivateAccess, boolean isArt) {
        // add fallbacks for certain special classes that must be present
        Iterable<DexFile> dexFiles = Iterables.concat(classPath, Lists.newArrayList(getBasicClasses()));

        unknownClass = new UnknownClassProto(this);
        loadedClasses.put(unknownClass.getType(), unknownClass);
        this.checkPackagePrivateAccess = checkPackagePrivateAccess;
        this.isArt = isArt;

        loadPrimitiveType("Z");
        loadPrimitiveType("B");
        loadPrimitiveType("S");
        loadPrimitiveType("C");
        loadPrimitiveType("I");
        loadPrimitiveType("J");
        loadPrimitiveType("F");
        loadPrimitiveType("D");
        loadPrimitiveType("L");

        for (DexFile dexFile: dexFiles) {
            for (ClassDef classDef: dexFile.getClasses()) {
                ClassDef prev = availableClasses.get(classDef.getType());
                if (prev == null) {
                    availableClasses.put(classDef.getType(), classDef);
                }
            }
        }
    }

    private void loadPrimitiveType(String type) {
        loadedClasses.put(type, new PrimitiveProto(this, type));
    }

    private static DexFile getBasicClasses() {
        // fallbacks for some special classes that we assume are present
        return new ImmutableDexFile(ImmutableSet.of(
                new ReflectionClassDef(Class.class),
                new ReflectionClassDef(Cloneable.class),
                new ReflectionClassDef(Object.class),
                new ReflectionClassDef(Serializable.class),
                new ReflectionClassDef(String.class),
                new ReflectionClassDef(Throwable.class)));
    }

    @Nonnull
    public TypeProto getClass(@Nonnull CharSequence type) {
        return loadedClasses.getUnchecked(type.toString());
    }

    private final CacheLoader<String, TypeProto> classLoader = new CacheLoader<String, TypeProto>() {
        @Override public TypeProto load(String type) throws Exception {
            if (type.charAt(0) == '[') {
                return new ArrayProto(ClassPath.this, type);
            } else {
                return new ClassProto(ClassPath.this, type);
            }
        }
    };

    @Nonnull private LoadingCache<String, TypeProto> loadedClasses = CacheBuilder.newBuilder().build(classLoader);

    @Nonnull
    public ClassDef getClassDef(String type) {
        ClassDef ret = availableClasses.get(type);
        if (ret == null) {
            throw new UnresolvedClassException("Could not resolve class %s", type);
        }
        return ret;
    }

    @Nonnull
    public TypeProto getUnknownClass() {
        return unknownClass;
    }

    public boolean shouldCheckPackagePrivateAccess() {
        return checkPackagePrivateAccess;
    }

    @Nonnull
    public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                          int api, boolean experimental) {
        return fromClassPath(classPathDirs, classPath, dexFile, api, api == 17, experimental);
    }

    @Nonnull
    public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                          int api, boolean checkPackagePrivateAccess, boolean experimental) {
        ArrayList<DexFile> dexFiles = Lists.newArrayList();

        boolean isArt = false;

        for (String classPathEntry: classPath) {
            List<? extends DexFile> classPathDexFiles =
                    loadClassPathEntry(classPathDirs, classPathEntry, api, experimental);
            if (!isArt) {
                for (DexFile classPathDexFile: classPathDexFiles) {
                    if (classPathDexFile instanceof OatDexFile) {
                        isArt = true;
                        break;
                    }
                }
            }
            dexFiles.addAll(classPathDexFiles);
        }
        dexFiles.add(dexFile);
        return new ClassPath(dexFiles, checkPackagePrivateAccess, isArt);
    }

    @Nonnull
    public static ClassPath fromClassPath(Iterable<String> classPathDirs, Iterable<String> classPath, DexFile dexFile,
                                          int api, boolean checkPackagePrivateAccess, boolean experimental,
                                          boolean isArt) {
        ArrayList<DexFile> dexFiles = Lists.newArrayList();

        for (String classPathEntry: classPath) {
            dexFiles.addAll(loadClassPathEntry(classPathDirs, classPathEntry, api, experimental));
        }
        dexFiles.add(dexFile);
        return new ClassPath(dexFiles, checkPackagePrivateAccess, isArt);
    }

    private static final Pattern dalvikCacheOdexPattern = Pattern.compile("@([^@]+)@classes.dex$");

    @Nonnull
    private static List<? extends DexFile> loadClassPathEntry(@Nonnull Iterable<String> classPathDirs,
                                                              @Nonnull String bootClassPathEntry, int api,
                                                              boolean experimental) {
        File rawEntry = new File(bootClassPathEntry);
        // strip off the path - we only care about the filename
        String entryName = rawEntry.getName();

        // if it's a dalvik-cache entry, grab the name of the jar/apk
        if (entryName.endsWith("@classes.dex")) {
            Matcher m = dalvikCacheOdexPattern.matcher(entryName);

            if (!m.find()) {
                throw new ExceptionWithContext(String.format("Cannot parse dependency value %s", bootClassPathEntry));
            }

            entryName = m.group(1);
        }

        int extIndex = entryName.lastIndexOf(".");

        String baseEntryName;
        if (extIndex == -1) {
            baseEntryName = entryName;
        } else {
            baseEntryName = entryName.substring(0, extIndex);
        }

        for (String classPathDir: classPathDirs) {
            String[] extensions;

            if (entryName.endsWith(".oat")) {
                extensions = new String[] { ".oat" };
            } else {
                extensions = new String[] { "", ".odex", ".jar", ".apk", ".zip" };
            }

            for (String ext: extensions) {
                File file = new File(classPathDir, baseEntryName + ext);

                if (file.exists() && file.isFile()) {
                    if (!file.canRead()) {
                        System.err.println(String.format(
                                "warning: cannot open %s for reading. Will continue looking.", file.getPath()));
                    } else {
                        try {
                            return ImmutableList.of(DexFileFactory.loadDexFile(file, api, experimental));
                        } catch (DexFileNotFound ex) {
                            // ignore and continue
                        } catch (MultipleDexFilesException ex) {
                            return ex.oatFile.getDexFiles();
                        } catch (Exception ex) {
                            throw ExceptionWithContext.withContext(ex,
                                    "Error while reading boot class path entry \"%s\"", bootClassPathEntry);
                        }
                    }
                }
            }
        }
        throw new ExceptionWithContext("Cannot locate boot class path file %s", bootClassPathEntry);
    }

    private final Supplier<OdexedFieldInstructionMapper> fieldInstructionMapperSupplier = Suppliers.memoize(
            new Supplier<OdexedFieldInstructionMapper>() {
                @Override public OdexedFieldInstructionMapper get() {
                    return new OdexedFieldInstructionMapper(isArt);
                }
            });

    @Nonnull
    public OdexedFieldInstructionMapper getFieldInstructionMapper() {
        return fieldInstructionMapperSupplier.get();
    }
}