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 52KB

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