1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 import java.io.File;
18 import java.io.FileNotFoundException;
19 import java.io.IOException;
20 import java.io.RandomAccessFile;
21 import java.lang.reflect.Constructor;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.InvocationTargetException;
24 
25 /**
26  * A class loader with atypical behavior: we try to load a private
27  * class implementation before asking the system or boot loader.  This
28  * is used to create multiple classes with identical names in a single VM.
29  *
30  * If DexFile is available, we use that; if not, we assume we're not in
31  * Dalvik and instantiate the class with defineClass().
32  *
33  * The location of the DEX files and class data is dependent upon the
34  * test framework.
35  */
36 public class DefiningLoader extends ClassLoader {
37     static {
38         // For JVM, register as parallel capable.
39         // Android treats all class loaders as parallel capable and makes this a no-op.
registerAsParallelCapable()40         registerAsParallelCapable();
41     }
42 
43     /* this is where the .class files live */
44     static final String CLASS_PATH1 = "classes/";
45     static final String CLASS_PATH2 = "classes2/";
46 
47     /* this is the DEX/Jar file */
48     static final String DEX_FILE = System.getenv("DEX_LOCATION") + "/647-jni-get-field-id.jar";
49 
50     /* on Dalvik, this is a DexFile; otherwise, it's null */
51     private Class<?> mDexClass;
52 
53     private Object mDexFile;
54 
55     /**
56      * Construct DefiningLoader, grabbing a reference to the DexFile class
57      * if we're running under Dalvik.
58      */
DefiningLoader(ClassLoader parent)59     public DefiningLoader(ClassLoader parent) {
60         super(parent);
61 
62         try {
63             mDexClass = parent.loadClass("dalvik.system.DexFile");
64         } catch (ClassNotFoundException cnfe) {
65             // ignore -- not running Dalvik
66         }
67     }
68 
69     /**
70      * Finds the class with the specified binary name.
71      *
72      * We search for a file in CLASS_PATH or pull an entry from DEX_FILE.
73      * If we don't find a match, we throw an exception.
74      */
findClass(String name)75     protected Class<?> findClass(String name) throws ClassNotFoundException
76     {
77         if (mDexClass != null) {
78             return findClassDalvik(name);
79         } else {
80             return findClassNonDalvik(name);
81         }
82     }
83 
84     /**
85      * Finds the class with the specified binary name, from a DEX file.
86      */
findClassDalvik(String name)87     private Class<?> findClassDalvik(String name)
88         throws ClassNotFoundException {
89 
90         if (mDexFile == null) {
91             synchronized (DefiningLoader.class) {
92                 Constructor<?> ctor;
93                 /*
94                  * Construct a DexFile object through reflection.
95                  */
96                 try {
97                     ctor = mDexClass.getConstructor(String.class);
98                 } catch (NoSuchMethodException nsme) {
99                     throw new ClassNotFoundException("getConstructor failed",
100                         nsme);
101                 }
102 
103                 try {
104                     mDexFile = ctor.newInstance(DEX_FILE);
105                 } catch (InstantiationException ie) {
106                     throw new ClassNotFoundException("newInstance failed", ie);
107                 } catch (IllegalAccessException iae) {
108                     throw new ClassNotFoundException("newInstance failed", iae);
109                 } catch (InvocationTargetException ite) {
110                     throw new ClassNotFoundException("newInstance failed", ite);
111                 }
112             }
113         }
114 
115         /*
116          * Call DexFile.loadClass(String, ClassLoader).
117          */
118         Method meth;
119 
120         try {
121             meth = mDexClass.getMethod("loadClass", String.class, ClassLoader.class);
122         } catch (NoSuchMethodException nsme) {
123             throw new ClassNotFoundException("getMethod failed", nsme);
124         }
125 
126         try {
127             meth.invoke(mDexFile, name, this);
128         } catch (IllegalAccessException iae) {
129             throw new ClassNotFoundException("loadClass failed", iae);
130         } catch (InvocationTargetException ite) {
131             throw new ClassNotFoundException("loadClass failed",
132                 ite.getCause());
133         }
134 
135         return null;
136     }
137 
138     /**
139      * Finds the class with the specified binary name, from .class files.
140      */
findClassNonDalvik(String name)141     private Class<?> findClassNonDalvik(String name)
142         throws ClassNotFoundException {
143 
144         String[] pathNames = { CLASS_PATH1 + name + ".class", CLASS_PATH2 + name + ".class" };
145 
146         String pathName = null;
147         RandomAccessFile raf = null;
148 
149         for (String pn : pathNames) {
150             pathName = pn;
151             try {
152                 //System.out.println("--- Defining: looking for " + pathName);
153                 raf = new RandomAccessFile(new File(pathName), "r");
154                 break;
155             } catch (FileNotFoundException fnfe) {
156             }
157         }
158         if (raf == null) {
159             throw new ClassNotFoundException("Not found: " + pathNames[0] + ":" + pathNames[1]);
160         }
161 
162         /* read the entire file in */
163         byte[] fileData;
164         try {
165             fileData = new byte[(int) raf.length()];
166             raf.readFully(fileData);
167         } catch (IOException ioe) {
168             throw new ClassNotFoundException("Read error: " + pathName);
169         } finally {
170             try {
171                 raf.close();
172             } catch (IOException ioe) {
173                 // drop
174             }
175         }
176 
177         /* create the class */
178         //System.out.println("--- Defining: defining " + name);
179         try {
180             return defineClass(name, fileData, 0, fileData.length);
181         } catch (Throwable th) {
182             throw new ClassNotFoundException("defineClass failed", th);
183         }
184     }
185 
186     /**
187      * Load a class.
188      *
189      * Normally a class loader wouldn't override this, but we want our
190      * version of the class to take precedence over an already-loaded
191      * version.
192      *
193      * We still want the system classes (e.g. java.lang.Object) from the
194      * bootstrap class loader.
195      */
loadClass(String name, boolean resolve)196     synchronized protected Class<?> loadClass(String name, boolean resolve)
197         throws ClassNotFoundException
198     {
199         Class<?> res;
200 
201         /*
202          * 1. Invoke findLoadedClass(String) to check if the class has
203          * already been loaded.
204          *
205          * This doesn't change.
206          */
207         res = findLoadedClass(name);
208         if (res != null) {
209             // System.out.println("FancyLoader.loadClass: " + name + " already loaded");
210             if (resolve)
211                 resolveClass(res);
212             return res;
213         }
214 
215         /*
216          * 3. Invoke the findClass(String) method to find the class.
217          */
218         try {
219             res = findClass(name);
220             if (resolve)
221                 resolveClass(res);
222         }
223         catch (ClassNotFoundException e) {
224             // we couldn't find it, so eat the exception and keep going
225         }
226 
227         /*
228          * 2. Invoke the loadClass method on the parent class loader.  If
229          * the parent loader is null the class loader built-in to the
230          * virtual machine is used, instead.
231          *
232          * (Since we're not in java.lang, we can't actually invoke the
233          * parent's loadClass() method, but we passed our parent to the
234          * super-class which can take care of it for us.)
235          */
236         res = super.loadClass(name, resolve);   // returns class or throws
237         return res;
238     }
239 }
240