Thu, 31 Aug 2017 15:18:52 +0800
merge
1 /*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.xml.internal.bind.v2.runtime.reflect.opt;
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Method;
30 import java.lang.ref.WeakReference;
31 import java.security.AccessController;
32 import java.security.PrivilegedAction;
33 import java.util.concurrent.locks.Lock;
34 import java.util.concurrent.locks.ReentrantReadWriteLock;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.WeakHashMap;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import com.sun.xml.internal.bind.Util;
42 import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
44 /**
45 * A {@link ClassLoader} used to "inject" optimized accessor classes
46 * into the VM.
47 *
48 * <p>
49 * Its parent class loader needs to be set to the one that can see the user
50 * class.
51 *
52 * @author Kohsuke Kawaguchi
53 */
54 final class Injector {
56 /**
57 * {@link Injector}s keyed by their parent {@link ClassLoader}.
58 *
59 * We only need one injector per one user class loader.
60 */
61 private static final ReentrantReadWriteLock irwl = new ReentrantReadWriteLock();
62 private static final Lock ir = irwl.readLock();
63 private static final Lock iw = irwl.writeLock();
64 private static final Map<ClassLoader, WeakReference<Injector>> injectors =
65 new WeakHashMap<ClassLoader, WeakReference<Injector>>();
66 private static final Logger logger = Util.getClassLogger();
68 /**
69 * Injects a new class into the given class loader.
70 *
71 * @return null
72 * if it fails to inject.
73 */
74 static Class inject(ClassLoader cl, String className, byte[] image) {
75 Injector injector = get(cl);
76 if (injector != null) {
77 return injector.inject(className, image);
78 } else {
79 return null;
80 }
81 }
83 /**
84 * Returns the already injected class, or null.
85 */
86 static Class find(ClassLoader cl, String className) {
87 Injector injector = get(cl);
88 if (injector != null) {
89 return injector.find(className);
90 } else {
91 return null;
92 }
93 }
95 /**
96 * Gets or creates an {@link Injector} for the given class loader.
97 *
98 * @return null
99 * if it fails.
100 */
101 private static Injector get(ClassLoader cl) {
102 Injector injector = null;
103 WeakReference<Injector> wr;
104 ir.lock();
105 try {
106 wr = injectors.get(cl);
107 } finally {
108 ir.unlock();
109 }
110 if (wr != null) {
111 injector = wr.get();
112 }
113 if (injector == null) {
114 try {
115 wr = new WeakReference<Injector>(injector = new Injector(cl));
116 iw.lock();
117 try {
118 if (!injectors.containsKey(cl)) {
119 injectors.put(cl, wr);
120 }
121 } finally {
122 iw.unlock();
123 }
124 } catch (SecurityException e) {
125 logger.log(Level.FINE, "Unable to set up a back-door for the injector", e);
126 return null;
127 }
128 }
129 return injector;
130 }
131 /**
132 * Injected classes keyed by their names.
133 */
134 private final Map<String, Class> classes = new HashMap<String, Class>();
135 private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
136 private final Lock r = rwl.readLock();
137 private final Lock w = rwl.writeLock();
138 private final ClassLoader parent;
139 /**
140 * True if this injector is capable of injecting accessors.
141 * False otherwise, which happens if this classloader can't see {@link Accessor}.
142 */
143 private final boolean loadable;
144 private static final Method defineClass;
145 private static final Method resolveClass;
146 private static final Method findLoadedClass;
148 static {
149 try {
150 defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE);
151 resolveClass = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class);
152 findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
153 } catch (NoSuchMethodException e) {
154 // impossible
155 throw new NoSuchMethodError(e.getMessage());
156 }
157 AccessController.doPrivileged(new PrivilegedAction<Void>() {
159 @Override
160 public Void run() {
161 // TODO: check security implication
162 // do these setAccessible allow anyone to call these methods freely?s
163 defineClass.setAccessible(true);
164 resolveClass.setAccessible(true);
165 findLoadedClass.setAccessible(true);
166 return null;
167 }
168 });
169 }
171 private Injector(ClassLoader parent) {
172 this.parent = parent;
173 assert parent != null;
175 boolean loadableCheck = false;
177 try {
178 loadableCheck = parent.loadClass(Accessor.class.getName()) == Accessor.class;
179 } catch (ClassNotFoundException e) {
180 // not loadable
181 }
183 this.loadable = loadableCheck;
184 }
186 @SuppressWarnings("LockAcquiredButNotSafelyReleased")
187 private Class inject(String className, byte[] image) {
188 if (!loadable) // this injector cannot inject anything
189 {
190 return null;
191 }
193 boolean wlocked = false;
194 boolean rlocked = false;
195 try {
197 r.lock();
198 rlocked = true;
200 Class c = classes.get(className);
202 // Unlock now during the findLoadedClass process to avoid
203 // deadlocks
204 r.unlock();
205 rlocked = false;
207 //find loaded class from classloader
208 if (c == null) {
210 try {
211 c = (Class) findLoadedClass.invoke(parent, className.replace('/', '.'));
212 } catch (IllegalArgumentException e) {
213 logger.log(Level.FINE, "Unable to find " + className, e);
214 } catch (IllegalAccessException e) {
215 logger.log(Level.FINE, "Unable to find " + className, e);
216 } catch (InvocationTargetException e) {
217 Throwable t = e.getTargetException();
218 logger.log(Level.FINE, "Unable to find " + className, t);
219 }
221 if (c != null) {
223 w.lock();
224 wlocked = true;
226 classes.put(className, c);
228 w.unlock();
229 wlocked = false;
231 return c;
232 }
233 }
235 if (c == null) {
237 r.lock();
238 rlocked = true;
240 c = classes.get(className);
242 // Unlock now during the define/resolve process to avoid
243 // deadlocks
244 r.unlock();
245 rlocked = false;
247 if (c == null) {
249 // we need to inject a class into the
250 try {
251 c = (Class) defineClass.invoke(parent, className.replace('/', '.'), image, 0, image.length);
252 resolveClass.invoke(parent, c);
253 } catch (IllegalAccessException e) {
254 logger.log(Level.FINE, "Unable to inject " + className, e);
255 return null;
256 } catch (InvocationTargetException e) {
257 Throwable t = e.getTargetException();
258 if (t instanceof LinkageError) {
259 logger.log(Level.FINE, "duplicate class definition bug occured? Please report this : " + className, t);
260 } else {
261 logger.log(Level.FINE, "Unable to inject " + className, t);
262 }
263 return null;
264 } catch (SecurityException e) {
265 logger.log(Level.FINE, "Unable to inject " + className, e);
266 return null;
267 } catch (LinkageError e) {
268 logger.log(Level.FINE, "Unable to inject " + className, e);
269 return null;
270 }
272 w.lock();
273 wlocked = true;
275 // During the time we were unlocked, we could have tried to
276 // load the class from more than one thread. Check now to see
277 // if someone else beat us to registering this class
278 if (!classes.containsKey(className)) {
279 classes.put(className, c);
280 }
282 w.unlock();
283 wlocked = false;
284 }
285 }
286 return c;
287 } finally {
288 if (rlocked) {
289 r.unlock();
290 }
291 if (wlocked) {
292 w.unlock();
293 }
294 }
295 }
297 private Class find(String className) {
298 r.lock();
299 try {
300 return classes.get(className);
301 } finally {
302 r.unlock();
303 }
304 }
305 }