You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProxyFactory.java 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist.util.proxy;
  17. import java.lang.ref.Reference;
  18. import java.lang.ref.WeakReference;
  19. import java.lang.reflect.Constructor;
  20. import java.lang.reflect.Field;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Member;
  23. import java.lang.reflect.Method;
  24. import java.lang.reflect.Modifier;
  25. import java.security.ProtectionDomain;
  26. import java.util.ArrayList;
  27. import java.util.Collections;
  28. import java.util.Comparator;
  29. import java.util.HashMap;
  30. import java.util.HashSet;
  31. import java.util.Iterator;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.Set;
  35. import java.util.WeakHashMap;
  36. import javassist.CannotCompileException;
  37. import javassist.bytecode.AccessFlag;
  38. import javassist.bytecode.Bytecode;
  39. import javassist.bytecode.ClassFile;
  40. import javassist.bytecode.CodeAttribute;
  41. import javassist.bytecode.ConstPool;
  42. import javassist.bytecode.Descriptor;
  43. import javassist.bytecode.DuplicateMemberException;
  44. import javassist.bytecode.ExceptionsAttribute;
  45. import javassist.bytecode.FieldInfo;
  46. import javassist.bytecode.MethodInfo;
  47. import javassist.bytecode.Opcode;
  48. import javassist.bytecode.StackMapTable;
  49. /*
  50. * This class is implemented only with the lower-level API of Javassist.
  51. * This design decision is for maximizing performance.
  52. */
  53. /**
  54. * Factory of dynamic proxy classes.
  55. *
  56. * <p>This factory generates a class that extends the given super class and implements
  57. * the given interfaces. The calls of the methods inherited from the super class are
  58. * forwarded and then <code>invoke()</code> is called on the method handler
  59. * associated with instances of the generated class. The calls of the methods from
  60. * the interfaces are also forwarded to the method handler.
  61. *
  62. * <p>For example, if the following code is executed,
  63. *
  64. * <pre>
  65. * ProxyFactory f = new ProxyFactory();
  66. * f.setSuperclass(Foo.class);
  67. * f.setFilter(new MethodFilter() {
  68. * public boolean isHandled(Method m) {
  69. * // ignore finalize()
  70. * return !m.getName().equals("finalize");
  71. * }
  72. * });
  73. * Class c = f.createClass();
  74. * MethodHandler mi = new MethodHandler() {
  75. * public Object invoke(Object self, Method m, Method proceed,
  76. * Object[] args) throws Throwable {
  77. * System.out.println("Name: " + m.getName());
  78. * return proceed.invoke(self, args); // execute the original method.
  79. * }
  80. * };
  81. * Foo foo = (Foo)c.newInstance();
  82. * ((Proxy)foo).setHandler(mi);
  83. * </pre>
  84. *
  85. * <p>Here, <code>Method</code> is <code>java.lang.reflect.Method</code>.</p>
  86. *
  87. * <p>Then, the following method call will be forwarded to MethodHandler
  88. * <code>mi</code> and prints a message before executing the originally called method
  89. * <code>bar()</code> in <code>Foo</code>.
  90. *
  91. * <pre>
  92. * foo.bar();
  93. * </pre>
  94. *
  95. * <p>The last three lines of the code shown above can be replaced with a call to
  96. * the helper method <code>create</code>, which generates a proxy class, instantiates
  97. * it, and sets the method handler of the instance:
  98. *
  99. * <pre>
  100. * :
  101. * Foo foo = (Foo)f.create(new Class[0], new Object[0], mi);
  102. * </pre>
  103. *
  104. * <p>To change the method handler during runtime,
  105. * execute the following code:
  106. *
  107. * <pre>
  108. * MethodHandler mi = ... ; // alternative handler
  109. * ((Proxy)foo).setHandler(mi);
  110. * </pre>
  111. *
  112. * <p> If setHandler is never called for a proxy instance then it will
  113. * employ the default handler which proceeds by invoking the original method.
  114. * The behaviour of the default handler is identical to the following
  115. * handler:
  116. *
  117. * <pre>
  118. * class EmptyHandler implements MethodHandler {
  119. * public Object invoke(Object self, Method m,
  120. * Method proceed, Object[] args) throws Exception {
  121. * return proceed.invoke(self, args);
  122. * }
  123. * }
  124. * </pre>
  125. *
  126. * <p>A proxy factory caches and reuses proxy classes by default. It is possible to reset
  127. * this default globally by setting static field {@link ProxyFactory#useCache} to false.
  128. * Caching may also be configured for a specific factory by calling instance method
  129. * {@link ProxyFactory#setUseCache(boolean)}. It is strongly recommended that new clients
  130. * of class ProxyFactory enable caching. Failure to do so may lead to exhaustion of
  131. * the heap memory area used to store classes.
  132. *
  133. * <p>Caching is automatically disabled for any given proxy factory if deprecated instance
  134. * method {@link ProxyFactory#setHandler(MethodHandler)} is called. This method was
  135. * used to specify a default handler which newly created proxy classes should install
  136. * when they create their instances. It is only retained to provide backward compatibility
  137. * with previous releases of javassist. Unfortunately,this legacy behaviour makes caching
  138. * and reuse of proxy classes impossible. The current programming model expects javassist
  139. * clients to set the handler of a proxy instance explicitly by calling method
  140. * {@link Proxy#setHandler(MethodHandler)} as shown in the sample code above. New
  141. * clients are strongly recommended to use this model rather than calling
  142. * {@link ProxyFactory#setHandler(MethodHandler)}.
  143. *
  144. * <p>A proxy object generated by <code>ProxyFactory</code> is serializable
  145. * if its super class or any of its interfaces implement <code>java.io.Serializable</code>.
  146. * However, a serialized proxy object may not be compatible with future releases.
  147. * The serialization support should be used for short-term storage or RMI.
  148. *
  149. * <p>For compatibility with older releases serialization of proxy objects is implemented by
  150. * adding a writeReplace method to the proxy class. This allows a proxy to be serialized
  151. * to a conventional {@link java.io.ObjectOutputStream} and deserialized from a corresponding
  152. * {@link java.io.ObjectInputStream}. However this method suffers from several problems, the most
  153. * notable one being that it fails to serialize state inherited from the proxy's superclass.
  154. * <p>
  155. * An alternative method of serializing proxy objects is available which fixes these problems. It
  156. * requires inhibiting generation of the writeReplace method and instead using instances of
  157. * {@link javassist.util.proxy.ProxyObjectOutputStream} and {@link javassist.util.proxy.ProxyObjectInputStream}
  158. * (which are subclasses of {@link java.io.ObjectOutputStream} and {@link java.io.ObjectInputStream})
  159. * to serialize and deserialize, respectively, the proxy. These streams recognise javassist proxies and ensure
  160. * that they are serialized and deserialized without the need for the proxy class to implement special methods
  161. * such as writeReplace. Generation of the writeReplace method can be disabled globally by setting static field
  162. * {@link ProxyFactory#useWriteReplace} to false. Alternatively, it may be
  163. * configured per factory by calling instance method {@link ProxyFactory#setUseWriteReplace(boolean)}.
  164. *
  165. * @see MethodHandler
  166. * @since 3.1
  167. * @author Muga Nishizawa
  168. * @author Shigeru Chiba
  169. * @author Andrew Dinn
  170. */
  171. public class ProxyFactory {
  172. private Class<?> superClass;
  173. private Class<?>[] interfaces;
  174. private MethodFilter methodFilter;
  175. private MethodHandler handler; // retained for legacy usage
  176. private List<Map.Entry<String,Method>> signatureMethods;
  177. private boolean hasGetHandler;
  178. private byte[] signature;
  179. private String classname;
  180. private String basename;
  181. private String superName;
  182. private Class<?> thisClass;
  183. /**
  184. * per factory setting initialised from current setting for useCache but able to be reset before each create call
  185. */
  186. private boolean factoryUseCache;
  187. /**
  188. * per factory setting initialised from current setting for useWriteReplace but able to be reset before each create call
  189. */
  190. private boolean factoryWriteReplace;
  191. /**
  192. * <p>If true, only public/protected methods are forwarded to a proxy object.
  193. * The class for that proxy object is loaded by the {@code defineClass} method
  194. * in {@code java.lang.invoke.MethodHandles.Lookup}, which is available in
  195. * Java 9 or later. This works even when {@code sun.misc.Unsafe} is not
  196. * available for some reasons (it is already deprecated in Java 9).</p>
  197. *
  198. * <p>To load a class, Javassist first tries to use {@code sun.misc.Unsafe} and,
  199. * if not available, it uses a {@code protected} method in {@code java.lang.ClassLoader}
  200. * via {@code PrivilegedAction}. Since the latter approach is not available
  201. * any longer by default in Java 9 or later, the JVM argument
  202. * {@code --add-opens java.base/java.lang=ALL-UNNAMED} must be given to the JVM
  203. * when it is used (because of lack of {@code sun.misc.Unsafe}).
  204. * If this argument cannot be given to the JVM, {@code onlyPublicMethods} should
  205. * be set to {@code true}. Javassist will try to load by using
  206. * {@code java.lang.invoke.MethodHandles.Lookup}.</p>
  207. *
  208. * <p>The default value is {@code false}.</p>
  209. *
  210. * @see DefineClassHelper#toClass(String, ClassLoader, ProtectionDomain, byte[])
  211. * @since 3.22
  212. */
  213. public static boolean onlyPublicMethods = false;
  214. /**
  215. * If the value of this variable is not null, the class file of
  216. * the generated proxy class is written under the directory specified
  217. * by this variable. For example, if the value is
  218. * <code>"."</code>, then the class file is written under the current
  219. * directory. This method is for debugging.
  220. *
  221. * <p>The default value is null.
  222. */
  223. public String writeDirectory;
  224. private static final Class<?> OBJECT_TYPE = Object.class;
  225. private static final String HOLDER = "_methods_";
  226. private static final String HOLDER_TYPE = "[Ljava/lang/reflect/Method;";
  227. private static final String FILTER_SIGNATURE_FIELD = "_filter_signature";
  228. private static final String FILTER_SIGNATURE_TYPE = "[B";
  229. private static final String HANDLER = "handler";
  230. private static final String NULL_INTERCEPTOR_HOLDER = "javassist.util.proxy.RuntimeSupport";
  231. private static final String DEFAULT_INTERCEPTOR = "default_interceptor";
  232. private static final String HANDLER_TYPE
  233. = 'L' + MethodHandler.class.getName().replace('.', '/') + ';';
  234. private static final String HANDLER_SETTER = "setHandler";
  235. private static final String HANDLER_SETTER_TYPE = "(" + HANDLER_TYPE + ")V";
  236. private static final String HANDLER_GETTER = "getHandler";
  237. private static final String HANDLER_GETTER_TYPE = "()" + HANDLER_TYPE;
  238. private static final String SERIAL_VERSION_UID_FIELD = "serialVersionUID";
  239. private static final String SERIAL_VERSION_UID_TYPE = "J";
  240. private static final long SERIAL_VERSION_UID_VALUE = -1L;
  241. /**
  242. * If true, a generated proxy class is cached and it will be reused
  243. * when generating the proxy class with the same properties is requested.
  244. * The default value is true.
  245. *
  246. * Note that this value merely specifies the initial setting employed by any newly created
  247. * proxy factory. The factory setting may be overwritten by calling factory instance method
  248. * {@link #setUseCache(boolean)}
  249. *
  250. * @since 3.4
  251. */
  252. public static volatile boolean useCache = true;
  253. /**
  254. * If true, a generated proxy class will implement method writeReplace enabling
  255. * serialization of its proxies to a conventional ObjectOutputStream. this (default)
  256. * setting retains the old javassist behaviour which has the advantage that it
  257. * retains compatibility with older releases and requires no extra work on the part
  258. * of the client performing the serialization. However, it has the disadvantage that
  259. * state inherited from the superclasses of the proxy is lost during serialization.
  260. * if false then serialization/deserialization of the proxy instances will preserve
  261. * all fields. However, serialization must be performed via a {@link ProxyObjectOutputStream}
  262. * and deserialization must be via {@link ProxyObjectInputStream}. Any attempt to serialize
  263. * proxies whose class was created with useWriteReplace set to false via a normal
  264. * {@link java.io.ObjectOutputStream} will fail.
  265. *
  266. * Note that this value merely specifies the initial setting employed by any newly created
  267. * proxy factory. The factory setting may be overwritten by calling factory instance method
  268. * {@link #setUseWriteReplace(boolean)}
  269. *
  270. * @since 3.4
  271. */
  272. public static volatile boolean useWriteReplace = true;
  273. /*
  274. * methods allowing individual factory settings for factoryUseCache and factoryWriteReplace to be reset
  275. */
  276. /**
  277. * test whether this factory uses the proxy cache
  278. * @return true if this factory uses the proxy cache otherwise false
  279. */
  280. public boolean isUseCache()
  281. {
  282. return factoryUseCache;
  283. }
  284. /**
  285. * configure whether this factory should use the proxy cache
  286. * @param useCache true if this factory should use the proxy cache and false if it should not use the cache
  287. * @throws RuntimeException if a default interceptor has been set for the factory
  288. */
  289. public void setUseCache(boolean useCache)
  290. {
  291. // we cannot allow caching to be used if the factory is configured to install a default interceptor
  292. // field into generated classes
  293. if (handler != null && useCache) {
  294. throw new RuntimeException("caching cannot be enabled if the factory default interceptor has been set");
  295. }
  296. factoryUseCache = useCache;
  297. }
  298. /**
  299. * test whether this factory installs a writeReplace method in created classes
  300. * @return true if this factory installs a writeReplace method in created classes otherwise false
  301. */
  302. public boolean isUseWriteReplace()
  303. {
  304. return factoryWriteReplace;
  305. }
  306. /**
  307. * configure whether this factory should add a writeReplace method to created classes
  308. * @param useWriteReplace true if this factory should add a writeReplace method to created classes and false if it
  309. * should not add a writeReplace method
  310. */
  311. public void setUseWriteReplace(boolean useWriteReplace)
  312. {
  313. factoryWriteReplace = useWriteReplace;
  314. }
  315. private static Map<ClassLoader,Map<String,ProxyDetails>> proxyCache =
  316. new WeakHashMap<ClassLoader,Map<String,ProxyDetails>>();
  317. /**
  318. * determine if a class is a javassist proxy class
  319. * @param cl
  320. * @return true if the class is a javassist proxy class otherwise false
  321. */
  322. public static boolean isProxyClass(Class<?> cl)
  323. {
  324. // all proxies implement Proxy or ProxyObject. nothing else should.
  325. return (Proxy.class.isAssignableFrom(cl));
  326. }
  327. /**
  328. * used to store details of a specific proxy class in the second tier of the proxy cache. this entry
  329. * will be located in a hashmap keyed by the unique identifying name of the proxy class. the hashmap is
  330. * located in a weak hashmap keyed by the classloader common to all proxy classes in the second tier map.
  331. */
  332. static class ProxyDetails {
  333. /**
  334. * the unique signature of any method filter whose behaviour will be met by this class. each bit in
  335. * the byte array is set if the filter redirects the corresponding super or interface method and clear
  336. * if it does not redirect it.
  337. */
  338. byte[] signature;
  339. /**
  340. * a hexadecimal string representation of the signature bit sequence. this string also forms part
  341. * of the proxy class name.
  342. */
  343. Reference<Class<?>> proxyClass;
  344. /**
  345. * a flag which is true this class employs writeReplace to perform serialization of its instances
  346. * and false if serialization must employ of a ProxyObjectOutputStream and ProxyObjectInputStream
  347. */
  348. boolean isUseWriteReplace;
  349. ProxyDetails(byte[] signature, Class<?> proxyClass, boolean isUseWriteReplace)
  350. {
  351. this.signature = signature;
  352. this.proxyClass = new WeakReference<Class<?>>(proxyClass);
  353. this.isUseWriteReplace = isUseWriteReplace;
  354. }
  355. }
  356. /**
  357. * Constructs a factory of proxy class.
  358. */
  359. public ProxyFactory() {
  360. superClass = null;
  361. interfaces = null;
  362. methodFilter = null;
  363. handler = null;
  364. signature = null;
  365. signatureMethods = null;
  366. hasGetHandler = false;
  367. thisClass = null;
  368. writeDirectory = null;
  369. factoryUseCache = useCache;
  370. factoryWriteReplace = useWriteReplace;
  371. }
  372. /**
  373. * Sets the super class of a proxy class.
  374. */
  375. public void setSuperclass(Class<?> clazz) {
  376. superClass = clazz;
  377. // force recompute of signature
  378. signature = null;
  379. }
  380. /**
  381. * Obtains the super class set by <code>setSuperclass()</code>.
  382. *
  383. * @since 3.4
  384. */
  385. public Class<?> getSuperclass() { return superClass; }
  386. /**
  387. * Sets the interfaces of a proxy class.
  388. */
  389. public void setInterfaces(Class<?>[] ifs) {
  390. interfaces = ifs;
  391. // force recompute of signature
  392. signature = null;
  393. }
  394. /**
  395. * Obtains the interfaces set by <code>setInterfaces</code>.
  396. *
  397. * @since 3.4
  398. */
  399. public Class<?>[] getInterfaces() { return interfaces; }
  400. /**
  401. * Sets a filter that selects the methods that will be controlled by a handler.
  402. */
  403. public void setFilter(MethodFilter mf) {
  404. methodFilter = mf;
  405. // force recompute of signature
  406. signature = null;
  407. }
  408. /**
  409. * Generates a proxy class using the current filter.
  410. */
  411. public Class<?> createClass() {
  412. if (signature == null) {
  413. computeSignature(methodFilter);
  414. }
  415. return createClass1();
  416. }
  417. /**
  418. * Generates a proxy class using the supplied filter.
  419. */
  420. public Class<?> createClass(MethodFilter filter) {
  421. computeSignature(filter);
  422. return createClass1();
  423. }
  424. /**
  425. * Generates a proxy class with a specific signature.
  426. * access is package local so ProxyObjectInputStream can use this
  427. * @param signature
  428. * @return
  429. */
  430. Class<?> createClass(byte[] signature)
  431. {
  432. installSignature(signature);
  433. return createClass1();
  434. }
  435. private Class<?> createClass1() {
  436. Class<?> result = thisClass;
  437. if (result == null) {
  438. ClassLoader cl = getClassLoader();
  439. synchronized (proxyCache) {
  440. if (factoryUseCache)
  441. createClass2(cl);
  442. else
  443. createClass3(cl);
  444. result = thisClass;
  445. // don't retain any unwanted references
  446. thisClass = null;
  447. }
  448. }
  449. return result;
  450. }
  451. private static char[] hexDigits =
  452. { '0', '1', '2', '3', '4', '5', '6', '7',
  453. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  454. public String getKey(Class<?> superClass, Class<?>[] interfaces, byte[] signature, boolean useWriteReplace)
  455. {
  456. StringBuffer sbuf = new StringBuffer();
  457. if (superClass != null){
  458. sbuf.append(superClass.getName());
  459. }
  460. sbuf.append(":");
  461. for (int i = 0; i < interfaces.length; i++) {
  462. sbuf.append(interfaces[i].getName());
  463. sbuf.append(":");
  464. }
  465. for (int i = 0; i < signature.length; i++) {
  466. byte b = signature[i];
  467. int lo = b & 0xf;
  468. int hi = (b >> 4) & 0xf;
  469. sbuf.append(hexDigits[lo]);
  470. sbuf.append(hexDigits[hi]);
  471. }
  472. if (useWriteReplace) {
  473. sbuf.append(":w");
  474. }
  475. return sbuf.toString();
  476. }
  477. private void createClass2(ClassLoader cl) {
  478. String key = getKey(superClass, interfaces, signature, factoryWriteReplace);
  479. /*
  480. * Excessive concurrency causes a large memory footprint and slows the
  481. * execution speed down (with JDK 1.5). Thus, we use a jumbo lock for
  482. * reducing concrrency.
  483. */
  484. // synchronized (proxyCache) {
  485. Map<String,ProxyDetails> cacheForTheLoader = proxyCache.get(cl);
  486. ProxyDetails details;
  487. if (cacheForTheLoader == null) {
  488. cacheForTheLoader = new HashMap<String,ProxyDetails>();
  489. proxyCache.put(cl, cacheForTheLoader);
  490. }
  491. details = cacheForTheLoader.get(key);
  492. if (details != null) {
  493. Reference<Class<?>> reference = details.proxyClass;
  494. thisClass = reference.get();
  495. if (thisClass != null) {
  496. return;
  497. }
  498. }
  499. createClass3(cl);
  500. details = new ProxyDetails(signature, thisClass, factoryWriteReplace);
  501. cacheForTheLoader.put(key, details);
  502. // }
  503. }
  504. private void createClass3(ClassLoader cl) {
  505. // we need a new class so we need a new class name
  506. allocateClassName();
  507. try {
  508. ClassFile cf = make();
  509. if (writeDirectory != null)
  510. FactoryHelper.writeFile(cf, writeDirectory);
  511. thisClass = FactoryHelper.toClass(cf, cl, getDomain());
  512. setField(FILTER_SIGNATURE_FIELD, signature);
  513. // legacy behaviour : we only set the default interceptor static field if we are not using the cache
  514. if (!factoryUseCache) {
  515. setField(DEFAULT_INTERCEPTOR, handler);
  516. }
  517. }
  518. catch (CannotCompileException e) {
  519. throw new RuntimeException(e.getMessage(), e);
  520. }
  521. }
  522. private void setField(String fieldName, Object value) {
  523. if (thisClass != null && value != null)
  524. try {
  525. Field f = thisClass.getField(fieldName);
  526. SecurityActions.setAccessible(f, true);
  527. f.set(null, value);
  528. SecurityActions.setAccessible(f, false);
  529. }
  530. catch (Exception e) {
  531. throw new RuntimeException(e);
  532. }
  533. }
  534. static byte[] getFilterSignature(Class<?> clazz) {
  535. return (byte[])getField(clazz, FILTER_SIGNATURE_FIELD);
  536. }
  537. private static Object getField(Class<?> clazz, String fieldName) {
  538. try {
  539. Field f = clazz.getField(fieldName);
  540. f.setAccessible(true);
  541. Object value = f.get(null);
  542. f.setAccessible(false);
  543. return value;
  544. }
  545. catch (Exception e) {
  546. throw new RuntimeException(e);
  547. }
  548. }
  549. /**
  550. * Obtains the method handler of the given proxy object.
  551. *
  552. * @param p a proxy object.
  553. * @return the method handler.
  554. * @since 3.16
  555. */
  556. public static MethodHandler getHandler(Proxy p) {
  557. try {
  558. Field f = p.getClass().getDeclaredField(HANDLER);
  559. f.setAccessible(true);
  560. Object value = f.get(p);
  561. f.setAccessible(false);
  562. return (MethodHandler)value;
  563. }
  564. catch (Exception e) {
  565. throw new RuntimeException(e);
  566. }
  567. }
  568. /**
  569. * A provider of class loaders.
  570. *
  571. * @see #classLoaderProvider
  572. * @since 3.4
  573. */
  574. public static interface ClassLoaderProvider {
  575. /**
  576. * Returns a class loader.
  577. *
  578. * @param pf a proxy factory that is going to obtain a class loader.
  579. */
  580. public ClassLoader get(ProxyFactory pf);
  581. }
  582. /**
  583. * A provider used by <code>createClass()</code> for obtaining
  584. * a class loader.
  585. * <code>get()</code> on this <code>ClassLoaderProvider</code> object
  586. * is called to obtain a class loader.
  587. *
  588. * <p>The value of this field can be updated for changing the default
  589. * implementation.
  590. *
  591. * <p>Example:
  592. * <pre>
  593. * ProxyFactory.classLoaderProvider = new ProxyFactory.ClassLoaderProvider() {
  594. * public ClassLoader get(ProxyFactory pf) {
  595. * return Thread.currentThread().getContextClassLoader();
  596. * }
  597. * };
  598. * </pre>
  599. *
  600. * @since 3.4
  601. */
  602. public static ClassLoaderProvider classLoaderProvider =
  603. new ClassLoaderProvider() {
  604. @Override
  605. public ClassLoader get(ProxyFactory pf) {
  606. return pf.getClassLoader0();
  607. }
  608. };
  609. protected ClassLoader getClassLoader() {
  610. return classLoaderProvider.get(this);
  611. }
  612. protected ClassLoader getClassLoader0() {
  613. ClassLoader loader = null;
  614. if (superClass != null && !superClass.getName().equals("java.lang.Object"))
  615. loader = superClass.getClassLoader();
  616. else if (interfaces != null && interfaces.length > 0)
  617. loader = interfaces[0].getClassLoader();
  618. if (loader == null) {
  619. loader = getClass().getClassLoader();
  620. // In case javassist is in the endorsed dir
  621. if (loader == null) {
  622. loader = Thread.currentThread().getContextClassLoader();
  623. if (loader == null)
  624. loader = ClassLoader.getSystemClassLoader();
  625. }
  626. }
  627. return loader;
  628. }
  629. protected ProtectionDomain getDomain() {
  630. Class<?> clazz;
  631. if (superClass != null && !superClass.getName().equals("java.lang.Object"))
  632. clazz = superClass;
  633. else if (interfaces != null && interfaces.length > 0)
  634. clazz = interfaces[0];
  635. else
  636. clazz = this.getClass();
  637. return clazz.getProtectionDomain();
  638. }
  639. /**
  640. * Creates a proxy class and returns an instance of that class.
  641. *
  642. * @param paramTypes parameter types for a constructor.
  643. * @param args arguments passed to a constructor.
  644. * @param mh the method handler for the proxy class.
  645. * @since 3.4
  646. */
  647. public Object create(Class<?>[] paramTypes, Object[] args, MethodHandler mh)
  648. throws NoSuchMethodException, IllegalArgumentException,
  649. InstantiationException, IllegalAccessException, InvocationTargetException
  650. {
  651. Object obj = create(paramTypes, args);
  652. ((Proxy)obj).setHandler(mh);
  653. return obj;
  654. }
  655. /**
  656. * Creates a proxy class and returns an instance of that class.
  657. *
  658. * @param paramTypes parameter types for a constructor.
  659. * @param args arguments passed to a constructor.
  660. */
  661. public Object create(Class<?>[] paramTypes, Object[] args)
  662. throws NoSuchMethodException, IllegalArgumentException,
  663. InstantiationException, IllegalAccessException, InvocationTargetException
  664. {
  665. Class<?> c = createClass();
  666. Constructor<?> cons = c.getConstructor(paramTypes);
  667. return cons.newInstance(args);
  668. }
  669. /**
  670. * Sets the default invocation handler. This invocation handler is shared
  671. * among all the instances of a proxy class unless another is explicitly
  672. * specified.
  673. * @deprecated since 3.12
  674. * use of this method is incompatible with proxy class caching.
  675. * instead clients should call method {@link Proxy#setHandler(MethodHandler)} to set the handler
  676. * for each newly created proxy instance.
  677. * calling this method will automatically disable caching of classes created by the proxy factory.
  678. */
  679. @Deprecated
  680. public void setHandler(MethodHandler mi) {
  681. // if we were using the cache and the handler is non-null then we must stop caching
  682. if (factoryUseCache && mi != null) {
  683. factoryUseCache = false;
  684. // clear any currently held class so we don't try to reuse it or set its handler field
  685. thisClass = null;
  686. }
  687. handler = mi;
  688. // this retains the behaviour of the old code which resets any class we were holding on to
  689. // this is probably not what is wanted
  690. setField(DEFAULT_INTERCEPTOR, handler);
  691. }
  692. /**
  693. * A unique class name generator.
  694. */
  695. public static interface UniqueName {
  696. /**
  697. * Returns a unique class name.
  698. *
  699. * @param classname the super class name of the proxy class.
  700. */
  701. String get(String classname);
  702. }
  703. /**
  704. * A unique class name generator.
  705. * Replacing this generator changes the algorithm to generate a
  706. * unique name. The <code>get</code> method does not have to be
  707. * a <code>synchronized</code> method since the access to this field
  708. * is mutually exclusive and thus thread safe.
  709. */
  710. public static UniqueName nameGenerator = new UniqueName() {
  711. private final String sep = "_$$_jvst" + Integer.toHexString(this.hashCode() & 0xfff) + "_";
  712. private int counter = 0;
  713. @Override
  714. public String get(String classname) {
  715. return classname + sep + Integer.toHexString(counter++);
  716. }
  717. };
  718. private static String makeProxyName(String classname) {
  719. synchronized (nameGenerator) {
  720. return nameGenerator.get(classname);
  721. }
  722. }
  723. private ClassFile make() throws CannotCompileException {
  724. ClassFile cf = new ClassFile(false, classname, superName);
  725. cf.setAccessFlags(AccessFlag.PUBLIC);
  726. setInterfaces(cf, interfaces, hasGetHandler ? Proxy.class : ProxyObject.class);
  727. ConstPool pool = cf.getConstPool();
  728. // legacy: we only add the static field for the default interceptor if caching is disabled
  729. if (!factoryUseCache) {
  730. FieldInfo finfo = new FieldInfo(pool, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  731. finfo.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC);
  732. cf.addField(finfo);
  733. }
  734. // handler is per instance
  735. FieldInfo finfo2 = new FieldInfo(pool, HANDLER, HANDLER_TYPE);
  736. finfo2.setAccessFlags(AccessFlag.PRIVATE);
  737. cf.addField(finfo2);
  738. // filter signature is per class
  739. FieldInfo finfo3 = new FieldInfo(pool, FILTER_SIGNATURE_FIELD, FILTER_SIGNATURE_TYPE);
  740. finfo3.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC);
  741. cf.addField(finfo3);
  742. // the proxy class serial uid must always be a fixed value
  743. FieldInfo finfo4 = new FieldInfo(pool, SERIAL_VERSION_UID_FIELD, SERIAL_VERSION_UID_TYPE);
  744. finfo4.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC| AccessFlag.FINAL);
  745. cf.addField(finfo4);
  746. // HashMap allMethods = getMethods(superClass, interfaces);
  747. // int size = allMethods.size();
  748. makeConstructors(classname, cf, pool, classname);
  749. List<Find2MethodsArgs> forwarders = new ArrayList<Find2MethodsArgs>();
  750. int s = overrideMethods(cf, pool, classname, forwarders);
  751. addClassInitializer(cf, pool, classname, s, forwarders);
  752. addSetter(classname, cf, pool);
  753. if (!hasGetHandler)
  754. addGetter(classname, cf, pool);
  755. if (factoryWriteReplace) {
  756. try {
  757. cf.addMethod(makeWriteReplace(pool));
  758. }
  759. catch (DuplicateMemberException e) {
  760. // writeReplace() is already declared in the super class/interfaces.
  761. }
  762. }
  763. thisClass = null;
  764. return cf;
  765. }
  766. private void checkClassAndSuperName() {
  767. if (interfaces == null)
  768. interfaces = new Class[0];
  769. if (superClass == null) {
  770. superClass = OBJECT_TYPE;
  771. superName = superClass.getName();
  772. basename = interfaces.length == 0 ? superName
  773. : interfaces[0].getName();
  774. } else {
  775. superName = superClass.getName();
  776. basename = superName;
  777. }
  778. if (Modifier.isFinal(superClass.getModifiers()))
  779. throw new RuntimeException(superName + " is final");
  780. if (basename.startsWith("java.") || onlyPublicMethods)
  781. basename = "javassist.util.proxy." + basename.replace('.', '_');
  782. }
  783. private void allocateClassName() {
  784. classname = makeProxyName(basename);
  785. }
  786. private static Comparator<Map.Entry<String,Method>> sorter =
  787. new Comparator<Map.Entry<String,Method>>() {
  788. @Override
  789. public int compare(Map.Entry<String,Method> e1, Map.Entry<String,Method> e2) {
  790. return e1.getKey().compareTo(e2.getKey());
  791. }
  792. };
  793. private void makeSortedMethodList() {
  794. checkClassAndSuperName();
  795. hasGetHandler = false; // getMethods() may set this to true.
  796. Map<String,Method> allMethods = getMethods(superClass, interfaces);
  797. signatureMethods = new ArrayList<Map.Entry<String,Method>>(allMethods.entrySet());
  798. Collections.sort(signatureMethods, sorter);
  799. }
  800. private void computeSignature(MethodFilter filter) // throws CannotCompileException
  801. {
  802. makeSortedMethodList();
  803. int l = signatureMethods.size();
  804. int maxBytes = ((l + 7) >> 3);
  805. signature = new byte[maxBytes];
  806. for (int idx = 0; idx < l; idx++)
  807. {
  808. Method m = signatureMethods.get(idx).getValue();
  809. int mod = m.getModifiers();
  810. if (!Modifier.isFinal(mod) && !Modifier.isStatic(mod)
  811. && isVisible(mod, basename, m) && (filter == null || filter.isHandled(m))) {
  812. setBit(signature, idx);
  813. }
  814. }
  815. }
  816. private void installSignature(byte[] signature) // throws CannotCompileException
  817. {
  818. makeSortedMethodList();
  819. int l = signatureMethods.size();
  820. int maxBytes = ((l + 7) >> 3);
  821. if (signature.length != maxBytes) {
  822. throw new RuntimeException("invalid filter signature length for deserialized proxy class");
  823. }
  824. this.signature = signature;
  825. }
  826. private boolean testBit(byte[] signature, int idx) {
  827. int byteIdx = idx >> 3;
  828. if (byteIdx > signature.length)
  829. return false;
  830. int bitIdx = idx & 0x7;
  831. int mask = 0x1 << bitIdx;
  832. int sigByte = signature[byteIdx];
  833. return ((sigByte & mask) != 0);
  834. }
  835. private void setBit(byte[] signature, int idx) {
  836. int byteIdx = idx >> 3;
  837. if (byteIdx < signature.length) {
  838. int bitIdx = idx & 0x7;
  839. int mask = 0x1 << bitIdx;
  840. int sigByte = signature[byteIdx];
  841. signature[byteIdx] = (byte)(sigByte | mask);
  842. }
  843. }
  844. private static void setInterfaces(ClassFile cf, Class<?>[] interfaces, Class<?> proxyClass) {
  845. String setterIntf = proxyClass.getName();
  846. String[] list;
  847. if (interfaces == null || interfaces.length == 0)
  848. list = new String[] { setterIntf };
  849. else {
  850. list = new String[interfaces.length + 1];
  851. for (int i = 0; i < interfaces.length; i++)
  852. list[i] = interfaces[i].getName();
  853. list[interfaces.length] = setterIntf;
  854. }
  855. cf.setInterfaces(list);
  856. }
  857. private static void addClassInitializer(ClassFile cf, ConstPool cp,
  858. String classname, int size, List<Find2MethodsArgs> forwarders)
  859. throws CannotCompileException
  860. {
  861. FieldInfo finfo = new FieldInfo(cp, HOLDER, HOLDER_TYPE);
  862. finfo.setAccessFlags(AccessFlag.PRIVATE | AccessFlag.STATIC);
  863. cf.addField(finfo);
  864. MethodInfo minfo = new MethodInfo(cp, "<clinit>", "()V");
  865. minfo.setAccessFlags(AccessFlag.STATIC);
  866. setThrows(minfo, cp, new Class<?>[] { ClassNotFoundException.class });
  867. Bytecode code = new Bytecode(cp, 0, 2);
  868. code.addIconst(size * 2);
  869. code.addAnewarray("java.lang.reflect.Method");
  870. final int varArray = 0;
  871. code.addAstore(varArray);
  872. // forName() must be called here. Otherwise, the class might be
  873. // invisible.
  874. code.addLdc(classname);
  875. code.addInvokestatic("java.lang.Class",
  876. "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
  877. final int varClass = 1;
  878. code.addAstore(varClass);
  879. for (Find2MethodsArgs args:forwarders)
  880. callFind2Methods(code, args.methodName, args.delegatorName,
  881. args.origIndex, args.descriptor, varClass, varArray);
  882. code.addAload(varArray);
  883. code.addPutstatic(classname, HOLDER, HOLDER_TYPE);
  884. code.addLconst(SERIAL_VERSION_UID_VALUE);
  885. code.addPutstatic(classname, SERIAL_VERSION_UID_FIELD, SERIAL_VERSION_UID_TYPE);
  886. code.addOpcode(Bytecode.RETURN);
  887. minfo.setCodeAttribute(code.toCodeAttribute());
  888. cf.addMethod(minfo);
  889. }
  890. /**
  891. * @param thisMethod might be null.
  892. */
  893. private static void callFind2Methods(Bytecode code, String superMethod, String thisMethod,
  894. int index, String desc, int classVar, int arrayVar) {
  895. String findClass = RuntimeSupport.class.getName();
  896. String findDesc
  897. = "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/reflect/Method;)V";
  898. code.addAload(classVar);
  899. code.addLdc(superMethod);
  900. if (thisMethod == null)
  901. code.addOpcode(Opcode.ACONST_NULL);
  902. else
  903. code.addLdc(thisMethod);
  904. code.addIconst(index);
  905. code.addLdc(desc);
  906. code.addAload(arrayVar);
  907. code.addInvokestatic(findClass, "find2Methods", findDesc);
  908. }
  909. private static void addSetter(String classname, ClassFile cf, ConstPool cp)
  910. throws CannotCompileException
  911. {
  912. MethodInfo minfo = new MethodInfo(cp, HANDLER_SETTER,
  913. HANDLER_SETTER_TYPE);
  914. minfo.setAccessFlags(AccessFlag.PUBLIC);
  915. Bytecode code = new Bytecode(cp, 2, 2);
  916. code.addAload(0);
  917. code.addAload(1);
  918. code.addPutfield(classname, HANDLER, HANDLER_TYPE);
  919. code.addOpcode(Bytecode.RETURN);
  920. minfo.setCodeAttribute(code.toCodeAttribute());
  921. cf.addMethod(minfo);
  922. }
  923. private static void addGetter(String classname, ClassFile cf, ConstPool cp)
  924. throws CannotCompileException
  925. {
  926. MethodInfo minfo = new MethodInfo(cp, HANDLER_GETTER,
  927. HANDLER_GETTER_TYPE);
  928. minfo.setAccessFlags(AccessFlag.PUBLIC);
  929. Bytecode code = new Bytecode(cp, 1, 1);
  930. code.addAload(0);
  931. code.addGetfield(classname, HANDLER, HANDLER_TYPE);
  932. code.addOpcode(Bytecode.ARETURN);
  933. minfo.setCodeAttribute(code.toCodeAttribute());
  934. cf.addMethod(minfo);
  935. }
  936. private int overrideMethods(ClassFile cf, ConstPool cp, String className, List<Find2MethodsArgs> forwarders)
  937. throws CannotCompileException
  938. {
  939. String prefix = makeUniqueName("_d", signatureMethods);
  940. Iterator<Map.Entry<String,Method>> it = signatureMethods.iterator();
  941. int index = 0;
  942. while (it.hasNext()) {
  943. Map.Entry<String,Method> e = it.next();
  944. if (ClassFile.MAJOR_VERSION < ClassFile.JAVA_5 || !isBridge(e.getValue()))
  945. if (testBit(signature, index)) {
  946. override(className, e.getValue(), prefix, index,
  947. keyToDesc(e.getKey(), e.getValue()), cf, cp, forwarders);
  948. }
  949. index++;
  950. }
  951. return index;
  952. }
  953. private static boolean isBridge(Method m) {
  954. return m.isBridge();
  955. }
  956. private void override(String thisClassname, Method meth, String prefix,
  957. int index, String desc, ClassFile cf, ConstPool cp,
  958. List<Find2MethodsArgs> forwarders)
  959. throws CannotCompileException
  960. {
  961. Class<?> declClass = meth.getDeclaringClass();
  962. String delegatorName = prefix + index + meth.getName();
  963. if (Modifier.isAbstract(meth.getModifiers()))
  964. delegatorName = null;
  965. else {
  966. MethodInfo delegator
  967. = makeDelegator(meth, desc, cp, declClass, delegatorName);
  968. // delegator is not a bridge method. See Sec. 15.12.4.5 of JLS 3rd Ed.
  969. delegator.setAccessFlags(delegator.getAccessFlags() & ~AccessFlag.BRIDGE);
  970. cf.addMethod(delegator);
  971. }
  972. MethodInfo forwarder
  973. = makeForwarder(thisClassname, meth, desc, cp, declClass,
  974. delegatorName, index, forwarders);
  975. cf.addMethod(forwarder);
  976. }
  977. private void makeConstructors(String thisClassName, ClassFile cf,
  978. ConstPool cp, String classname) throws CannotCompileException
  979. {
  980. Constructor<?>[] cons = SecurityActions.getDeclaredConstructors(superClass);
  981. // legacy: if we are not caching then we need to initialise the default handler
  982. boolean doHandlerInit = !factoryUseCache;
  983. for (int i = 0; i < cons.length; i++) {
  984. Constructor<?> c = cons[i];
  985. int mod = c.getModifiers();
  986. if (!Modifier.isFinal(mod) && !Modifier.isPrivate(mod)
  987. && isVisible(mod, basename, c)) {
  988. MethodInfo m = makeConstructor(thisClassName, c, cp, superClass, doHandlerInit);
  989. cf.addMethod(m);
  990. }
  991. }
  992. }
  993. private static String makeUniqueName(String name, List<Map.Entry<String,Method>> sortedMethods) {
  994. if (makeUniqueName0(name, sortedMethods.iterator()))
  995. return name;
  996. for (int i = 100; i < 999; i++) {
  997. String s = name + i;
  998. if (makeUniqueName0(s, sortedMethods.iterator()))
  999. return s;
  1000. }
  1001. throw new RuntimeException("cannot make a unique method name");
  1002. }
  1003. private static boolean makeUniqueName0(String name, Iterator<Map.Entry<String,Method>> it) {
  1004. while (it.hasNext())
  1005. if (it.next().getKey().startsWith(name))
  1006. return false;
  1007. return true;
  1008. }
  1009. /**
  1010. * Returns true if the method is visible from the package.
  1011. *
  1012. * @param mod the modifiers of the method.
  1013. */
  1014. private static boolean isVisible(int mod, String from, Member meth) {
  1015. if ((mod & Modifier.PRIVATE) != 0)
  1016. return false;
  1017. else if ((mod & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0)
  1018. return true;
  1019. else {
  1020. String p = getPackageName(from);
  1021. String q = getPackageName(meth.getDeclaringClass().getName());
  1022. if (p == null)
  1023. return q == null;
  1024. return p.equals(q);
  1025. }
  1026. }
  1027. private static String getPackageName(String name) {
  1028. int i = name.lastIndexOf('.');
  1029. if (i < 0)
  1030. return null;
  1031. return name.substring(0, i);
  1032. }
  1033. /* getMethods() may set hasGetHandler to true.
  1034. */
  1035. private Map<String,Method> getMethods(Class<?> superClass, Class<?>[] interfaceTypes) {
  1036. Map<String,Method> hash = new HashMap<String,Method>();
  1037. Set<Class<?>> set = new HashSet<Class<?>>();
  1038. for (int i = 0; i < interfaceTypes.length; i++)
  1039. getMethods(hash, interfaceTypes[i], set);
  1040. getMethods(hash, superClass, set);
  1041. return hash;
  1042. }
  1043. private void getMethods(Map<String,Method> hash, Class<?> clazz, Set<Class<?>> visitedClasses) {
  1044. // This both speeds up scanning by avoiding duplicate interfaces and is needed to
  1045. // ensure that superinterfaces are always scanned before subinterfaces.
  1046. if (!visitedClasses.add(clazz))
  1047. return;
  1048. Class<?>[] ifs = clazz.getInterfaces();
  1049. for (int i = 0; i < ifs.length; i++)
  1050. getMethods(hash, ifs[i], visitedClasses);
  1051. Class<?> parent = clazz.getSuperclass();
  1052. if (parent != null)
  1053. getMethods(hash, parent, visitedClasses);
  1054. /* Java 5 or later allows covariant return types.
  1055. * It also allows contra-variant parameter types
  1056. * if a super class is a generics with concrete type arguments
  1057. * such as Foo<String>. So the method-overriding rule is complex.
  1058. */
  1059. Method[] methods = SecurityActions.getDeclaredMethods(clazz);
  1060. for (int i = 0; i < methods.length; i++)
  1061. if (!Modifier.isPrivate(methods[i].getModifiers())) {
  1062. Method m = methods[i];
  1063. String key = m.getName() + ':' + RuntimeSupport.makeDescriptor(m); // see keyToDesc().
  1064. if (key.startsWith(HANDLER_GETTER_KEY))
  1065. hasGetHandler = true;
  1066. // JIRA JASSIST-85
  1067. // put the method to the cache, retrieve previous definition (if any)
  1068. Method oldMethod = hash.put(key, m);
  1069. // JIRA JASSIST-244, 267
  1070. // ignore a bridge method to a method declared in a non-public class.
  1071. if (null != oldMethod && isBridge(m)
  1072. && !Modifier.isPublic(oldMethod.getDeclaringClass().getModifiers())
  1073. && !Modifier.isAbstract(oldMethod.getModifiers()) && !isDuplicated(i, methods))
  1074. hash.put(key, oldMethod);
  1075. // check if visibility has been reduced
  1076. if (null != oldMethod && Modifier.isPublic(oldMethod.getModifiers())
  1077. && !Modifier.isPublic(m.getModifiers())) {
  1078. // we tried to overwrite a public definition with a non-public definition,
  1079. // use the old definition instead.
  1080. hash.put(key, oldMethod);
  1081. }
  1082. }
  1083. }
  1084. private static boolean isDuplicated(int index, Method[] methods) {
  1085. String name = methods[index].getName();
  1086. for (int i = 0; i < methods.length; i++)
  1087. if (i != index)
  1088. if (name.equals(methods[i].getName()) && areParametersSame(methods[index], methods[i]))
  1089. return true;
  1090. return false;
  1091. }
  1092. private static boolean areParametersSame(Method method, Method targetMethod) {
  1093. Class<?>[] methodTypes = method.getParameterTypes();
  1094. Class<?>[] targetMethodTypes = targetMethod.getParameterTypes();
  1095. if (methodTypes.length == targetMethodTypes.length) {
  1096. for (int i = 0; i< methodTypes.length; i++) {
  1097. if (methodTypes[i].getName().equals(targetMethodTypes[i].getName())) {
  1098. continue;
  1099. } else {
  1100. return false;
  1101. }
  1102. }
  1103. return true;
  1104. }
  1105. return false;
  1106. }
  1107. private static final String HANDLER_GETTER_KEY
  1108. = HANDLER_GETTER + ":()";
  1109. private static String keyToDesc(String key, Method m) {
  1110. return key.substring(key.indexOf(':') + 1);
  1111. }
  1112. private static MethodInfo makeConstructor(String thisClassName, Constructor<?> cons,
  1113. ConstPool cp, Class<?> superClass, boolean doHandlerInit) {
  1114. String desc = RuntimeSupport.makeDescriptor(cons.getParameterTypes(),
  1115. Void.TYPE);
  1116. MethodInfo minfo = new MethodInfo(cp, "<init>", desc);
  1117. minfo.setAccessFlags(Modifier.PUBLIC); // cons.getModifiers() & ~Modifier.NATIVE
  1118. setThrows(minfo, cp, cons.getExceptionTypes());
  1119. Bytecode code = new Bytecode(cp, 0, 0);
  1120. // legacy: if we are not using caching then we initialise the instance's handler
  1121. // from the class's static default interceptor and skip the next few instructions if
  1122. // it is non-null
  1123. if (doHandlerInit) {
  1124. code.addAload(0);
  1125. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1126. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1127. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1128. code.addOpcode(Opcode.IFNONNULL);
  1129. code.addIndex(10);
  1130. }
  1131. // if caching is enabled then we don't have a handler to initialise so this else branch will install
  1132. // the handler located in the static field of class RuntimeSupport.
  1133. code.addAload(0);
  1134. code.addGetstatic(NULL_INTERCEPTOR_HOLDER, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1135. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1136. int pc = code.currentPc();
  1137. code.addAload(0);
  1138. int s = addLoadParameters(code, cons.getParameterTypes(), 1);
  1139. code.addInvokespecial(superClass.getName(), "<init>", desc);
  1140. code.addOpcode(Opcode.RETURN);
  1141. code.setMaxLocals(s + 1);
  1142. CodeAttribute ca = code.toCodeAttribute();
  1143. minfo.setCodeAttribute(ca);
  1144. StackMapTable.Writer writer = new StackMapTable.Writer(32);
  1145. writer.sameFrame(pc);
  1146. ca.setAttribute(writer.toStackMapTable(cp));
  1147. return minfo;
  1148. }
  1149. private MethodInfo makeDelegator(Method meth, String desc,
  1150. ConstPool cp, Class<?> declClass, String delegatorName) {
  1151. MethodInfo delegator = new MethodInfo(cp, delegatorName, desc);
  1152. delegator.setAccessFlags(Modifier.FINAL | Modifier.PUBLIC
  1153. | (meth.getModifiers() & ~(Modifier.PRIVATE
  1154. | Modifier.PROTECTED
  1155. | Modifier.ABSTRACT
  1156. | Modifier.NATIVE
  1157. | Modifier.SYNCHRONIZED)));
  1158. setThrows(delegator, cp, meth);
  1159. Bytecode code = new Bytecode(cp, 0, 0);
  1160. code.addAload(0);
  1161. int s = addLoadParameters(code, meth.getParameterTypes(), 1);
  1162. Class<?> targetClass = invokespecialTarget(declClass);
  1163. code.addInvokespecial(targetClass.isInterface(), cp.addClassInfo(targetClass.getName()),
  1164. meth.getName(), desc);
  1165. addReturn(code, meth.getReturnType());
  1166. code.setMaxLocals(++s);
  1167. delegator.setCodeAttribute(code.toCodeAttribute());
  1168. return delegator;
  1169. }
  1170. /* Suppose that the receiver type is S, the invoked method
  1171. * is declared in T, and U is the immediate super class of S
  1172. * (or its interface). If S <: U <: T (S <: T reads "S extends T"),
  1173. * the target type of invokespecial has to be not T but U.
  1174. */
  1175. private Class<?> invokespecialTarget(Class<?> declClass) {
  1176. if (declClass.isInterface())
  1177. for (Class<?> i: interfaces)
  1178. if (declClass.isAssignableFrom(i))
  1179. return i;
  1180. return superClass;
  1181. }
  1182. /**
  1183. * @param delegatorName null if the original method is abstract.
  1184. */
  1185. private static MethodInfo makeForwarder(String thisClassName,
  1186. Method meth, String desc, ConstPool cp,
  1187. Class<?> declClass, String delegatorName, int index,
  1188. List<Find2MethodsArgs> forwarders) {
  1189. MethodInfo forwarder = new MethodInfo(cp, meth.getName(), desc);
  1190. forwarder.setAccessFlags(Modifier.FINAL
  1191. | (meth.getModifiers() & ~(Modifier.ABSTRACT
  1192. | Modifier.NATIVE
  1193. | Modifier.SYNCHRONIZED)));
  1194. setThrows(forwarder, cp, meth);
  1195. int args = Descriptor.paramSize(desc);
  1196. Bytecode code = new Bytecode(cp, 0, args + 2);
  1197. /*
  1198. * static {
  1199. * methods[index * 2]
  1200. * = RuntimeSupport.findSuperMethod(this, <overridden name>, <desc>);
  1201. * methods[index * 2 + 1]
  1202. * = RuntimeSupport.findMethod(this, <delegator name>, <desc>);
  1203. * or = null // the original method is abstract.
  1204. * }
  1205. * :
  1206. * return ($r)handler.invoke(this, methods[index * 2],
  1207. * methods[index * 2 + 1], $args);
  1208. */
  1209. int origIndex = index * 2;
  1210. int delIndex = index * 2 + 1;
  1211. int arrayVar = args + 1;
  1212. code.addGetstatic(thisClassName, HOLDER, HOLDER_TYPE);
  1213. code.addAstore(arrayVar);
  1214. forwarders.add(new Find2MethodsArgs(meth.getName(), delegatorName, desc, origIndex));
  1215. code.addAload(0);
  1216. code.addGetfield(thisClassName, HANDLER, HANDLER_TYPE);
  1217. code.addAload(0);
  1218. code.addAload(arrayVar);
  1219. code.addIconst(origIndex);
  1220. code.addOpcode(Opcode.AALOAD);
  1221. code.addAload(arrayVar);
  1222. code.addIconst(delIndex);
  1223. code.addOpcode(Opcode.AALOAD);
  1224. makeParameterList(code, meth.getParameterTypes());
  1225. code.addInvokeinterface(MethodHandler.class.getName(), "invoke",
  1226. "(Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;",
  1227. 5);
  1228. Class<?> retType = meth.getReturnType();
  1229. addUnwrapper(code, retType);
  1230. addReturn(code, retType);
  1231. CodeAttribute ca = code.toCodeAttribute();
  1232. forwarder.setCodeAttribute(ca);
  1233. return forwarder;
  1234. }
  1235. static class Find2MethodsArgs {
  1236. String methodName, delegatorName, descriptor;
  1237. int origIndex;
  1238. Find2MethodsArgs(String mname, String dname, String desc, int index) {
  1239. methodName = mname;
  1240. delegatorName = dname;
  1241. descriptor = desc;
  1242. origIndex = index;
  1243. }
  1244. }
  1245. private static void setThrows(MethodInfo minfo, ConstPool cp, Method orig) {
  1246. Class<?>[] exceptions = orig.getExceptionTypes();
  1247. setThrows(minfo, cp, exceptions);
  1248. }
  1249. private static void setThrows(MethodInfo minfo, ConstPool cp,
  1250. Class<?>[] exceptions) {
  1251. if (exceptions.length == 0)
  1252. return;
  1253. String[] list = new String[exceptions.length];
  1254. for (int i = 0; i < exceptions.length; i++)
  1255. list[i] = exceptions[i].getName();
  1256. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1257. ea.setExceptions(list);
  1258. minfo.setExceptionsAttribute(ea);
  1259. }
  1260. private static int addLoadParameters(Bytecode code, Class<?>[] params,
  1261. int offset) {
  1262. int stacksize = 0;
  1263. int n = params.length;
  1264. for (int i = 0; i < n; ++i)
  1265. stacksize += addLoad(code, stacksize + offset, params[i]);
  1266. return stacksize;
  1267. }
  1268. private static int addLoad(Bytecode code, int n, Class<?> type) {
  1269. if (type.isPrimitive()) {
  1270. if (type == Long.TYPE) {
  1271. code.addLload(n);
  1272. return 2;
  1273. }
  1274. else if (type == Float.TYPE)
  1275. code.addFload(n);
  1276. else if (type == Double.TYPE) {
  1277. code.addDload(n);
  1278. return 2;
  1279. }
  1280. else
  1281. code.addIload(n);
  1282. }
  1283. else
  1284. code.addAload(n);
  1285. return 1;
  1286. }
  1287. private static int addReturn(Bytecode code, Class<?> type) {
  1288. if (type.isPrimitive()) {
  1289. if (type == Long.TYPE) {
  1290. code.addOpcode(Opcode.LRETURN);
  1291. return 2;
  1292. }
  1293. else if (type == Float.TYPE)
  1294. code.addOpcode(Opcode.FRETURN);
  1295. else if (type == Double.TYPE) {
  1296. code.addOpcode(Opcode.DRETURN);
  1297. return 2;
  1298. }
  1299. else if (type == Void.TYPE) {
  1300. code.addOpcode(Opcode.RETURN);
  1301. return 0;
  1302. }
  1303. else
  1304. code.addOpcode(Opcode.IRETURN);
  1305. }
  1306. else
  1307. code.addOpcode(Opcode.ARETURN);
  1308. return 1;
  1309. }
  1310. private static void makeParameterList(Bytecode code, Class<?>[] params) {
  1311. int regno = 1;
  1312. int n = params.length;
  1313. code.addIconst(n);
  1314. code.addAnewarray("java/lang/Object");
  1315. for (int i = 0; i < n; i++) {
  1316. code.addOpcode(Opcode.DUP);
  1317. code.addIconst(i);
  1318. Class<?> type = params[i];
  1319. if (type.isPrimitive())
  1320. regno = makeWrapper(code, type, regno);
  1321. else {
  1322. code.addAload(regno);
  1323. regno++;
  1324. }
  1325. code.addOpcode(Opcode.AASTORE);
  1326. }
  1327. }
  1328. private static int makeWrapper(Bytecode code, Class<?> type, int regno) {
  1329. int index = FactoryHelper.typeIndex(type);
  1330. String wrapper = FactoryHelper.wrapperTypes[index];
  1331. code.addNew(wrapper);
  1332. code.addOpcode(Opcode.DUP);
  1333. addLoad(code, regno, type);
  1334. code.addInvokespecial(wrapper, "<init>",
  1335. FactoryHelper.wrapperDesc[index]);
  1336. return regno + FactoryHelper.dataSize[index];
  1337. }
  1338. private static void addUnwrapper(Bytecode code, Class<?> type) {
  1339. if (type.isPrimitive()) {
  1340. if (type == Void.TYPE)
  1341. code.addOpcode(Opcode.POP);
  1342. else {
  1343. int index = FactoryHelper.typeIndex(type);
  1344. String wrapper = FactoryHelper.wrapperTypes[index];
  1345. code.addCheckcast(wrapper);
  1346. code.addInvokevirtual(wrapper,
  1347. FactoryHelper.unwarpMethods[index],
  1348. FactoryHelper.unwrapDesc[index]);
  1349. }
  1350. }
  1351. else
  1352. code.addCheckcast(type.getName());
  1353. }
  1354. private static MethodInfo makeWriteReplace(ConstPool cp) {
  1355. MethodInfo minfo = new MethodInfo(cp, "writeReplace", "()Ljava/lang/Object;");
  1356. String[] list = new String[1];
  1357. list[0] = "java.io.ObjectStreamException";
  1358. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1359. ea.setExceptions(list);
  1360. minfo.setExceptionsAttribute(ea);
  1361. Bytecode code = new Bytecode(cp, 0, 1);
  1362. code.addAload(0);
  1363. code.addInvokestatic("javassist.util.proxy.RuntimeSupport",
  1364. "makeSerializedProxy",
  1365. "(Ljava/lang/Object;)Ljavassist/util/proxy/SerializedProxy;");
  1366. code.addOpcode(Opcode.ARETURN);
  1367. minfo.setCodeAttribute(code.toCodeAttribute());
  1368. return minfo;
  1369. }
  1370. }