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