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(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", String.class, ClassLoader.class);
115         } catch (NoSuchMethodException nsme) {
116             throw new ClassNotFoundException("getMethod failed", nsme);
117         }
118 
119         try {
120             meth.invoke(mDexFile, name, this);
121         } catch (IllegalAccessException iae) {
122             throw new ClassNotFoundException("loadClass failed", iae);
123         } catch (InvocationTargetException ite) {
124             throw new ClassNotFoundException("loadClass failed",
125                 ite.getCause());
126         }
127 
128         return null;
129     }
130 
131     /**
132      * Finds the class with the specified binary name, from .class files.
133      */
findClassNonDalvik(String name)134     private Class<?> findClassNonDalvik(String name)
135         throws ClassNotFoundException {
136 
137         String pathName = CLASS_PATH + name + ".class";
138         //System.out.println("--- Fancy: looking for " + pathName);
139 
140         File path = new File(pathName);
141         RandomAccessFile raf;
142 
143         try {
144             raf = new RandomAccessFile(path, "r");
145         } catch (FileNotFoundException fnfe) {
146             throw new ClassNotFoundException("Not found: " + pathName);
147         }
148 
149         /* read the entire file in */
150         byte[] fileData;
151         try {
152             fileData = new byte[(int) raf.length()];
153             raf.readFully(fileData);
154         } catch (IOException ioe) {
155             throw new ClassNotFoundException("Read error: " + pathName);
156         } finally {
157             try {
158                 raf.close();
159             } catch (IOException ioe) {
160                 // drop
161             }
162         }
163 
164         /* create the class */
165         //System.out.println("--- Fancy: defining " + name);
166         try {
167             return defineClass(name, fileData, 0, fileData.length);
168         } catch (Throwable th) {
169             throw new ClassNotFoundException("defineClass failed", th);
170         }
171     }
172 
173     /**
174      * Load a class.
175      *
176      * Normally a class loader wouldn't override this, but we want our
177      * version of the class to take precedence over an already-loaded
178      * version.
179      *
180      * We still want the system classes (e.g. java.lang.Object) from the
181      * bootstrap class loader.
182      */
loadClass(String name, boolean resolve)183     protected Class<?> loadClass(String name, boolean resolve)
184         throws ClassNotFoundException
185     {
186         Class<?> res;
187 
188         /*
189          * 1. Invoke findLoadedClass(String) to check if the class has
190          * already been loaded.
191          *
192          * This doesn't change.
193          */
194         res = findLoadedClass(name);
195         if (res != null) {
196             System.out.println("FancyLoader.loadClass: "
197                 + name + " already loaded");
198             if (resolve)
199                 resolveClass(res);
200             return res;
201         }
202 
203         /*
204          * 3. Invoke the findClass(String) method to find the class.
205          */
206         try {
207             res = findClass(name);
208             if (resolve)
209                 resolveClass(res);
210         }
211         catch (ClassNotFoundException e) {
212             // we couldn't find it, so eat the exception and keep going
213         }
214 
215         /*
216          * 2. Invoke the loadClass method on the parent class loader.  If
217          * the parent loader is null the class loader built-in to the
218          * virtual machine is used, instead.
219          *
220          * (Since we're not in java.lang, we can't actually invoke the
221          * parent's loadClass() method, but we passed our parent to the
222          * super-class which can take care of it for us.)
223          */
224         res = super.loadClass(name, resolve);   // returns class or throws
225         return res;
226     }
227 }
228