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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. * <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>
  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. * <pre>
  72. * foo.bar();
  73. * </pre>
  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. * <pre>
  80. * :
  81. * Foo foo = (Foo)f.create(new Class[0], new Object[0], mi);
  82. * </pre>
  83. *
  84. * <p>To change the method handler during runtime,
  85. * execute the following code:
  86. *
  87. * <pre>
  88. * MethodHandler mi = ... ; // alternative handler
  89. * ((Proxy)foo).setHandler(mi);
  90. * </pre>
  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. * <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>
  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. * <pre>
  548. * ProxyFactory.classLoaderProvider = new ProxyFactory.ClassLoaderProvider() {
  549. * public ClassLoader get(ProxyFactory pf) {
  550. * return Thread.currentThread().getContextClassLoader();
  551. * }
  552. * };
  553. * </pre>
  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. /**
  646. * A unique class name generator.
  647. */
  648. public static interface UniqueName {
  649. /**
  650. * Returns a unique class name.
  651. *
  652. * @param classname the super class name of the proxy class.
  653. */
  654. String get(String classname);
  655. }
  656. /**
  657. * A unique class name generator.
  658. * Replacing this generator changes the algorithm to generate a
  659. * unique name. The <code>get</code> method does not have to be
  660. * a <code>synchronized</code> method since the access to this field
  661. * is mutually exclusive and thus thread safe.
  662. */
  663. public static UniqueName nameGenerator = new UniqueName() {
  664. private final String sep = "_$$_jvst" + Integer.toHexString(this.hashCode() & 0xfff) + "_";
  665. private int counter = 0;
  666. public String get(String classname) {
  667. return classname + sep + Integer.toHexString(counter++);
  668. }
  669. };
  670. private static String makeProxyName(String classname) {
  671. synchronized (nameGenerator) {
  672. return nameGenerator.get(classname);
  673. }
  674. }
  675. private ClassFile make() throws CannotCompileException {
  676. ClassFile cf = new ClassFile(false, classname, superName);
  677. cf.setAccessFlags(AccessFlag.PUBLIC);
  678. setInterfaces(cf, interfaces, hasGetHandler ? Proxy.class : ProxyObject.class);
  679. ConstPool pool = cf.getConstPool();
  680. // legacy: we only add the static field for the default interceptor if caching is disabled
  681. if (!factoryUseCache) {
  682. FieldInfo finfo = new FieldInfo(pool, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  683. finfo.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC);
  684. cf.addField(finfo);
  685. }
  686. // handler is per instance
  687. FieldInfo finfo2 = new FieldInfo(pool, HANDLER, HANDLER_TYPE);
  688. finfo2.setAccessFlags(AccessFlag.PRIVATE);
  689. cf.addField(finfo2);
  690. // filter signature is per class
  691. FieldInfo finfo3 = new FieldInfo(pool, FILTER_SIGNATURE_FIELD, FILTER_SIGNATURE_TYPE);
  692. finfo3.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC);
  693. cf.addField(finfo3);
  694. // the proxy class serial uid must always be a fixed value
  695. FieldInfo finfo4 = new FieldInfo(pool, SERIAL_VERSION_UID_FIELD, SERIAL_VERSION_UID_TYPE);
  696. finfo4.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC| AccessFlag.FINAL);
  697. cf.addField(finfo4);
  698. // HashMap allMethods = getMethods(superClass, interfaces);
  699. // int size = allMethods.size();
  700. makeConstructors(classname, cf, pool, classname);
  701. ArrayList forwarders = new ArrayList();
  702. int s = overrideMethods(cf, pool, classname, forwarders);
  703. addClassInitializer(cf, pool, classname, s, forwarders);
  704. addSetter(classname, cf, pool);
  705. if (!hasGetHandler)
  706. addGetter(classname, cf, pool);
  707. if (factoryWriteReplace) {
  708. try {
  709. cf.addMethod(makeWriteReplace(pool));
  710. }
  711. catch (DuplicateMemberException e) {
  712. // writeReplace() is already declared in the super class/interfaces.
  713. }
  714. }
  715. thisClass = null;
  716. return cf;
  717. }
  718. private void checkClassAndSuperName() {
  719. if (interfaces == null)
  720. interfaces = new Class[0];
  721. if (superClass == null) {
  722. superClass = OBJECT_TYPE;
  723. superName = superClass.getName();
  724. basename = interfaces.length == 0 ? superName
  725. : interfaces[0].getName();
  726. } else {
  727. superName = superClass.getName();
  728. basename = superName;
  729. }
  730. if (Modifier.isFinal(superClass.getModifiers()))
  731. throw new RuntimeException(superName + " is final");
  732. if (basename.startsWith("java."))
  733. basename = "org.javassist.tmp." + basename;
  734. }
  735. private void allocateClassName() {
  736. classname = makeProxyName(basename);
  737. }
  738. private static Comparator sorter = new Comparator() {
  739. public int compare(Object o1, Object o2) {
  740. Map.Entry e1 = (Map.Entry)o1;
  741. Map.Entry e2 = (Map.Entry)o2;
  742. String key1 = (String)e1.getKey();
  743. String key2 = (String)e2.getKey();
  744. return key1.compareTo(key2);
  745. }
  746. };
  747. private void makeSortedMethodList() {
  748. checkClassAndSuperName();
  749. hasGetHandler = false; // getMethods() may set this to true.
  750. HashMap allMethods = getMethods(superClass, interfaces);
  751. signatureMethods = new ArrayList(allMethods.entrySet());
  752. Collections.sort(signatureMethods, sorter);
  753. }
  754. private void computeSignature(MethodFilter filter) // throws CannotCompileException
  755. {
  756. makeSortedMethodList();
  757. int l = signatureMethods.size();
  758. int maxBytes = ((l + 7) >> 3);
  759. signature = new byte[maxBytes];
  760. for (int idx = 0; idx < l; idx++)
  761. {
  762. Map.Entry e = (Map.Entry)signatureMethods.get(idx);
  763. Method m = (Method)e.getValue();
  764. int mod = m.getModifiers();
  765. if (!Modifier.isFinal(mod) && !Modifier.isStatic(mod)
  766. && isVisible(mod, basename, m) && (filter == null || filter.isHandled(m))) {
  767. setBit(signature, idx);
  768. }
  769. }
  770. }
  771. private void installSignature(byte[] signature) // throws CannotCompileException
  772. {
  773. makeSortedMethodList();
  774. int l = signatureMethods.size();
  775. int maxBytes = ((l + 7) >> 3);
  776. if (signature.length != maxBytes) {
  777. throw new RuntimeException("invalid filter signature length for deserialized proxy class");
  778. }
  779. this.signature = signature;
  780. }
  781. private boolean testBit(byte[] signature, int idx) {
  782. int byteIdx = idx >> 3;
  783. if (byteIdx > signature.length) {
  784. return false;
  785. } else {
  786. int bitIdx = idx & 0x7;
  787. int mask = 0x1 << bitIdx;
  788. int sigByte = signature[byteIdx];
  789. return ((sigByte & mask) != 0);
  790. }
  791. }
  792. private void setBit(byte[] signature, int idx) {
  793. int byteIdx = idx >> 3;
  794. if (byteIdx < signature.length) {
  795. int bitIdx = idx & 0x7;
  796. int mask = 0x1 << bitIdx;
  797. int sigByte = signature[byteIdx];
  798. signature[byteIdx] = (byte)(sigByte | mask);
  799. }
  800. }
  801. private static void setInterfaces(ClassFile cf, Class[] interfaces, Class proxyClass) {
  802. String setterIntf = proxyClass.getName();
  803. String[] list;
  804. if (interfaces == null || interfaces.length == 0)
  805. list = new String[] { setterIntf };
  806. else {
  807. list = new String[interfaces.length + 1];
  808. for (int i = 0; i < interfaces.length; i++)
  809. list[i] = interfaces[i].getName();
  810. list[interfaces.length] = setterIntf;
  811. }
  812. cf.setInterfaces(list);
  813. }
  814. private static void addClassInitializer(ClassFile cf, ConstPool cp,
  815. String classname, int size, ArrayList forwarders)
  816. throws CannotCompileException
  817. {
  818. FieldInfo finfo = new FieldInfo(cp, HOLDER, HOLDER_TYPE);
  819. finfo.setAccessFlags(AccessFlag.PRIVATE | AccessFlag.STATIC);
  820. cf.addField(finfo);
  821. MethodInfo minfo = new MethodInfo(cp, "<clinit>", "()V");
  822. minfo.setAccessFlags(AccessFlag.STATIC);
  823. setThrows(minfo, cp, new Class[] { ClassNotFoundException.class });
  824. Bytecode code = new Bytecode(cp, 0, 2);
  825. code.addIconst(size * 2);
  826. code.addAnewarray("java.lang.reflect.Method");
  827. final int varArray = 0;
  828. code.addAstore(varArray);
  829. // forName() must be called here. Otherwise, the class might be
  830. // invisible.
  831. code.addLdc(classname);
  832. code.addInvokestatic("java.lang.Class",
  833. "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
  834. final int varClass = 1;
  835. code.addAstore(varClass);
  836. Iterator it = forwarders.iterator();
  837. while (it.hasNext()) {
  838. Find2MethodsArgs args = (Find2MethodsArgs)it.next();
  839. callFind2Methods(code, args.methodName, args.delegatorName,
  840. args.origIndex, args.descriptor, varClass, varArray);
  841. }
  842. code.addAload(varArray);
  843. code.addPutstatic(classname, HOLDER, HOLDER_TYPE);
  844. code.addLconst(SERIAL_VERSION_UID_VALUE);
  845. code.addPutstatic(classname, SERIAL_VERSION_UID_FIELD, SERIAL_VERSION_UID_TYPE);
  846. code.addOpcode(Bytecode.RETURN);
  847. minfo.setCodeAttribute(code.toCodeAttribute());
  848. cf.addMethod(minfo);
  849. }
  850. /**
  851. * @param thisMethod might be null.
  852. */
  853. private static void callFind2Methods(Bytecode code, String superMethod, String thisMethod,
  854. int index, String desc, int classVar, int arrayVar) {
  855. String findClass = RuntimeSupport.class.getName();
  856. String findDesc
  857. = "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/reflect/Method;)V";
  858. code.addAload(classVar);
  859. code.addLdc(superMethod);
  860. if (thisMethod == null)
  861. code.addOpcode(Opcode.ACONST_NULL);
  862. else
  863. code.addLdc(thisMethod);
  864. code.addIconst(index);
  865. code.addLdc(desc);
  866. code.addAload(arrayVar);
  867. code.addInvokestatic(findClass, "find2Methods", findDesc);
  868. }
  869. private static void addSetter(String classname, ClassFile cf, ConstPool cp)
  870. throws CannotCompileException
  871. {
  872. MethodInfo minfo = new MethodInfo(cp, HANDLER_SETTER,
  873. HANDLER_SETTER_TYPE);
  874. minfo.setAccessFlags(AccessFlag.PUBLIC);
  875. Bytecode code = new Bytecode(cp, 2, 2);
  876. code.addAload(0);
  877. code.addAload(1);
  878. code.addPutfield(classname, HANDLER, HANDLER_TYPE);
  879. code.addOpcode(Bytecode.RETURN);
  880. minfo.setCodeAttribute(code.toCodeAttribute());
  881. cf.addMethod(minfo);
  882. }
  883. private static void addGetter(String classname, ClassFile cf, ConstPool cp)
  884. throws CannotCompileException
  885. {
  886. MethodInfo minfo = new MethodInfo(cp, HANDLER_GETTER,
  887. HANDLER_GETTER_TYPE);
  888. minfo.setAccessFlags(AccessFlag.PUBLIC);
  889. Bytecode code = new Bytecode(cp, 1, 1);
  890. code.addAload(0);
  891. code.addGetfield(classname, HANDLER, HANDLER_TYPE);
  892. code.addOpcode(Bytecode.ARETURN);
  893. minfo.setCodeAttribute(code.toCodeAttribute());
  894. cf.addMethod(minfo);
  895. }
  896. private int overrideMethods(ClassFile cf, ConstPool cp, String className, ArrayList forwarders)
  897. throws CannotCompileException
  898. {
  899. String prefix = makeUniqueName("_d", signatureMethods);
  900. Iterator it = signatureMethods.iterator();
  901. int index = 0;
  902. while (it.hasNext()) {
  903. Map.Entry e = (Map.Entry)it.next();
  904. String key = (String)e.getKey();
  905. Method meth = (Method)e.getValue();
  906. if (ClassFile.MAJOR_VERSION < ClassFile.JAVA_5 || !isBridge(meth))
  907. if (testBit(signature, index)) {
  908. override(className, meth, prefix, index,
  909. keyToDesc(key, meth), cf, cp, forwarders);
  910. }
  911. index++;
  912. }
  913. return index;
  914. }
  915. private static boolean isBridge(Method m) {
  916. return m.isBridge();
  917. }
  918. private void override(String thisClassname, Method meth, String prefix,
  919. int index, String desc, ClassFile cf, ConstPool cp, ArrayList forwarders)
  920. throws CannotCompileException
  921. {
  922. Class declClass = meth.getDeclaringClass();
  923. String delegatorName = prefix + index + meth.getName();
  924. if (Modifier.isAbstract(meth.getModifiers()))
  925. delegatorName = null;
  926. else {
  927. MethodInfo delegator
  928. = makeDelegator(meth, desc, cp, declClass, delegatorName);
  929. // delegator is not a bridge method. See Sec. 15.12.4.5 of JLS 3rd Ed.
  930. delegator.setAccessFlags(delegator.getAccessFlags() & ~AccessFlag.BRIDGE);
  931. cf.addMethod(delegator);
  932. }
  933. MethodInfo forwarder
  934. = makeForwarder(thisClassname, meth, desc, cp, declClass,
  935. delegatorName, index, forwarders);
  936. cf.addMethod(forwarder);
  937. }
  938. private void makeConstructors(String thisClassName, ClassFile cf,
  939. ConstPool cp, String classname) throws CannotCompileException
  940. {
  941. Constructor[] cons = SecurityActions.getDeclaredConstructors(superClass);
  942. // legacy: if we are not caching then we need to initialise the default handler
  943. boolean doHandlerInit = !factoryUseCache;
  944. for (int i = 0; i < cons.length; i++) {
  945. Constructor c = cons[i];
  946. int mod = c.getModifiers();
  947. if (!Modifier.isFinal(mod) && !Modifier.isPrivate(mod)
  948. && isVisible(mod, basename, c)) {
  949. MethodInfo m = makeConstructor(thisClassName, c, cp, superClass, doHandlerInit);
  950. cf.addMethod(m);
  951. }
  952. }
  953. }
  954. private static String makeUniqueName(String name, List sortedMethods) {
  955. if (makeUniqueName0(name, sortedMethods.iterator()))
  956. return name;
  957. for (int i = 100; i < 999; i++) {
  958. String s = name + i;
  959. if (makeUniqueName0(s, sortedMethods.iterator()))
  960. return s;
  961. }
  962. throw new RuntimeException("cannot make a unique method name");
  963. }
  964. private static boolean makeUniqueName0(String name, Iterator it) {
  965. while (it.hasNext()) {
  966. Map.Entry e = (Map.Entry)it.next();
  967. String key = (String)e.getKey();
  968. if (key.startsWith(name))
  969. return false;
  970. }
  971. return true;
  972. }
  973. /**
  974. * Returns true if the method is visible from the package.
  975. *
  976. * @param mod the modifiers of the method.
  977. */
  978. private static boolean isVisible(int mod, String from, Member meth) {
  979. if ((mod & Modifier.PRIVATE) != 0)
  980. return false;
  981. else if ((mod & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0)
  982. return true;
  983. else {
  984. String p = getPackageName(from);
  985. String q = getPackageName(meth.getDeclaringClass().getName());
  986. if (p == null)
  987. return q == null;
  988. else
  989. return p.equals(q);
  990. }
  991. }
  992. private static String getPackageName(String name) {
  993. int i = name.lastIndexOf('.');
  994. if (i < 0)
  995. return null;
  996. else
  997. return name.substring(0, i);
  998. }
  999. /* getMethods() may set hasGetHandler to true.
  1000. */
  1001. private HashMap getMethods(Class superClass, Class[] interfaceTypes) {
  1002. HashMap hash = new HashMap();
  1003. HashSet set = new HashSet();
  1004. for (int i = 0; i < interfaceTypes.length; i++)
  1005. getMethods(hash, interfaceTypes[i], set);
  1006. getMethods(hash, superClass, set);
  1007. return hash;
  1008. }
  1009. private void getMethods(HashMap hash, Class clazz, Set visitedClasses) {
  1010. // This both speeds up scanning by avoiding duplicate interfaces and is needed to
  1011. // ensure that superinterfaces are always scanned before subinterfaces.
  1012. if (!visitedClasses.add(clazz))
  1013. return;
  1014. Class[] ifs = clazz.getInterfaces();
  1015. for (int i = 0; i < ifs.length; i++)
  1016. getMethods(hash, ifs[i], visitedClasses);
  1017. Class parent = clazz.getSuperclass();
  1018. if (parent != null)
  1019. getMethods(hash, parent, visitedClasses);
  1020. /* Java 5 or later allows covariant return types.
  1021. * It also allows contra-variant parameter types
  1022. * if a super class is a generics with concrete type arguments
  1023. * such as Foo<String>. So the method-overriding rule is complex.
  1024. */
  1025. Method[] methods = SecurityActions.getDeclaredMethods(clazz);
  1026. for (int i = 0; i < methods.length; i++)
  1027. if (!Modifier.isPrivate(methods[i].getModifiers())) {
  1028. Method m = methods[i];
  1029. String key = m.getName() + ':' + RuntimeSupport.makeDescriptor(m); // see keyToDesc().
  1030. if (key.startsWith(HANDLER_GETTER_KEY))
  1031. hasGetHandler = true;
  1032. // JIRA JASSIST-85
  1033. // put the method to the cache, retrieve previous definition (if any)
  1034. Method oldMethod = (Method)hash.put(key, m);
  1035. // JIRA JASSIST-244
  1036. // ignore a bridge method with the same signature that the overridden one has.
  1037. if (null != oldMethod && isBridge(m)
  1038. && !Modifier.isPublic(oldMethod.getDeclaringClass().getModifiers())
  1039. && !Modifier.isAbstract(oldMethod.getModifiers()) && !isOverloaded(i, methods))
  1040. hash.put(key, oldMethod);
  1041. // check if visibility has been reduced
  1042. if (null != oldMethod && Modifier.isPublic(oldMethod.getModifiers())
  1043. && !Modifier.isPublic(m.getModifiers()) ) {
  1044. // we tried to overwrite a public definition with a non-public definition,
  1045. // use the old definition instead.
  1046. hash.put(key, oldMethod);
  1047. }
  1048. }
  1049. }
  1050. private static boolean isOverloaded(int index, Method[] methods) {
  1051. String name = methods[index].getName();
  1052. for (int i = 0; i < methods.length; i++)
  1053. if (i != index)
  1054. if (name.equals(methods[i].getName()))
  1055. return true;
  1056. return false;
  1057. }
  1058. private static final String HANDLER_GETTER_KEY
  1059. = HANDLER_GETTER + ":()";
  1060. private static String keyToDesc(String key, Method m) {
  1061. return key.substring(key.indexOf(':') + 1);
  1062. }
  1063. private static MethodInfo makeConstructor(String thisClassName, Constructor cons,
  1064. ConstPool cp, Class superClass, boolean doHandlerInit) {
  1065. String desc = RuntimeSupport.makeDescriptor(cons.getParameterTypes(),
  1066. Void.TYPE);
  1067. MethodInfo minfo = new MethodInfo(cp, "<init>", desc);
  1068. minfo.setAccessFlags(Modifier.PUBLIC); // cons.getModifiers() & ~Modifier.NATIVE
  1069. setThrows(minfo, cp, cons.getExceptionTypes());
  1070. Bytecode code = new Bytecode(cp, 0, 0);
  1071. // legacy: if we are not using caching then we initialise the instance's handler
  1072. // from the class's static default interceptor and skip the next few instructions if
  1073. // it is non-null
  1074. if (doHandlerInit) {
  1075. code.addAload(0);
  1076. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1077. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1078. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1079. code.addOpcode(Opcode.IFNONNULL);
  1080. code.addIndex(10);
  1081. }
  1082. // if caching is enabled then we don't have a handler to initialise so this else branch will install
  1083. // the handler located in the static field of class RuntimeSupport.
  1084. code.addAload(0);
  1085. code.addGetstatic(NULL_INTERCEPTOR_HOLDER, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1086. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1087. int pc = code.currentPc();
  1088. code.addAload(0);
  1089. int s = addLoadParameters(code, cons.getParameterTypes(), 1);
  1090. code.addInvokespecial(superClass.getName(), "<init>", desc);
  1091. code.addOpcode(Opcode.RETURN);
  1092. code.setMaxLocals(s + 1);
  1093. CodeAttribute ca = code.toCodeAttribute();
  1094. minfo.setCodeAttribute(ca);
  1095. StackMapTable.Writer writer = new StackMapTable.Writer(32);
  1096. writer.sameFrame(pc);
  1097. ca.setAttribute(writer.toStackMapTable(cp));
  1098. return minfo;
  1099. }
  1100. private static MethodInfo makeDelegator(Method meth, String desc,
  1101. ConstPool cp, Class declClass, String delegatorName) {
  1102. MethodInfo delegator = new MethodInfo(cp, delegatorName, desc);
  1103. delegator.setAccessFlags(Modifier.FINAL | Modifier.PUBLIC
  1104. | (meth.getModifiers() & ~(Modifier.PRIVATE
  1105. | Modifier.PROTECTED
  1106. | Modifier.ABSTRACT
  1107. | Modifier.NATIVE
  1108. | Modifier.SYNCHRONIZED)));
  1109. setThrows(delegator, cp, meth);
  1110. Bytecode code = new Bytecode(cp, 0, 0);
  1111. code.addAload(0);
  1112. int s = addLoadParameters(code, meth.getParameterTypes(), 1);
  1113. code.addInvokespecial(declClass.getName(), meth.getName(), desc);
  1114. addReturn(code, meth.getReturnType());
  1115. code.setMaxLocals(++s);
  1116. delegator.setCodeAttribute(code.toCodeAttribute());
  1117. return delegator;
  1118. }
  1119. /**
  1120. * @param delegatorName null if the original method is abstract.
  1121. */
  1122. private static MethodInfo makeForwarder(String thisClassName,
  1123. Method meth, String desc, ConstPool cp,
  1124. Class declClass, String delegatorName, int index,
  1125. ArrayList forwarders) {
  1126. MethodInfo forwarder = new MethodInfo(cp, meth.getName(), desc);
  1127. forwarder.setAccessFlags(Modifier.FINAL
  1128. | (meth.getModifiers() & ~(Modifier.ABSTRACT
  1129. | Modifier.NATIVE
  1130. | Modifier.SYNCHRONIZED)));
  1131. setThrows(forwarder, cp, meth);
  1132. int args = Descriptor.paramSize(desc);
  1133. Bytecode code = new Bytecode(cp, 0, args + 2);
  1134. /*
  1135. * static {
  1136. * methods[index * 2]
  1137. * = RuntimeSupport.findSuperMethod(this, <overridden name>, <desc>);
  1138. * methods[index * 2 + 1]
  1139. * = RuntimeSupport.findMethod(this, <delegator name>, <desc>);
  1140. * or = null // the original method is abstract.
  1141. * }
  1142. * :
  1143. * return ($r)handler.invoke(this, methods[index * 2],
  1144. * methods[index * 2 + 1], $args);
  1145. */
  1146. int origIndex = index * 2;
  1147. int delIndex = index * 2 + 1;
  1148. int arrayVar = args + 1;
  1149. code.addGetstatic(thisClassName, HOLDER, HOLDER_TYPE);
  1150. code.addAstore(arrayVar);
  1151. forwarders.add(new Find2MethodsArgs(meth.getName(), delegatorName, desc, origIndex));
  1152. code.addAload(0);
  1153. code.addGetfield(thisClassName, HANDLER, HANDLER_TYPE);
  1154. code.addAload(0);
  1155. code.addAload(arrayVar);
  1156. code.addIconst(origIndex);
  1157. code.addOpcode(Opcode.AALOAD);
  1158. code.addAload(arrayVar);
  1159. code.addIconst(delIndex);
  1160. code.addOpcode(Opcode.AALOAD);
  1161. makeParameterList(code, meth.getParameterTypes());
  1162. code.addInvokeinterface(MethodHandler.class.getName(), "invoke",
  1163. "(Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;",
  1164. 5);
  1165. Class retType = meth.getReturnType();
  1166. addUnwrapper(code, retType);
  1167. addReturn(code, retType);
  1168. CodeAttribute ca = code.toCodeAttribute();
  1169. forwarder.setCodeAttribute(ca);
  1170. return forwarder;
  1171. }
  1172. static class Find2MethodsArgs {
  1173. String methodName, delegatorName, descriptor;
  1174. int origIndex;
  1175. Find2MethodsArgs(String mname, String dname, String desc, int index) {
  1176. methodName = mname;
  1177. delegatorName = dname;
  1178. descriptor = desc;
  1179. origIndex = index;
  1180. }
  1181. }
  1182. private static void setThrows(MethodInfo minfo, ConstPool cp, Method orig) {
  1183. Class[] exceptions = orig.getExceptionTypes();
  1184. setThrows(minfo, cp, exceptions);
  1185. }
  1186. private static void setThrows(MethodInfo minfo, ConstPool cp,
  1187. Class[] exceptions) {
  1188. if (exceptions.length == 0)
  1189. return;
  1190. String[] list = new String[exceptions.length];
  1191. for (int i = 0; i < exceptions.length; i++)
  1192. list[i] = exceptions[i].getName();
  1193. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1194. ea.setExceptions(list);
  1195. minfo.setExceptionsAttribute(ea);
  1196. }
  1197. private static int addLoadParameters(Bytecode code, Class[] params,
  1198. int offset) {
  1199. int stacksize = 0;
  1200. int n = params.length;
  1201. for (int i = 0; i < n; ++i)
  1202. stacksize += addLoad(code, stacksize + offset, params[i]);
  1203. return stacksize;
  1204. }
  1205. private static int addLoad(Bytecode code, int n, Class type) {
  1206. if (type.isPrimitive()) {
  1207. if (type == Long.TYPE) {
  1208. code.addLload(n);
  1209. return 2;
  1210. }
  1211. else if (type == Float.TYPE)
  1212. code.addFload(n);
  1213. else if (type == Double.TYPE) {
  1214. code.addDload(n);
  1215. return 2;
  1216. }
  1217. else
  1218. code.addIload(n);
  1219. }
  1220. else
  1221. code.addAload(n);
  1222. return 1;
  1223. }
  1224. private static int addReturn(Bytecode code, Class type) {
  1225. if (type.isPrimitive()) {
  1226. if (type == Long.TYPE) {
  1227. code.addOpcode(Opcode.LRETURN);
  1228. return 2;
  1229. }
  1230. else if (type == Float.TYPE)
  1231. code.addOpcode(Opcode.FRETURN);
  1232. else if (type == Double.TYPE) {
  1233. code.addOpcode(Opcode.DRETURN);
  1234. return 2;
  1235. }
  1236. else if (type == Void.TYPE) {
  1237. code.addOpcode(Opcode.RETURN);
  1238. return 0;
  1239. }
  1240. else
  1241. code.addOpcode(Opcode.IRETURN);
  1242. }
  1243. else
  1244. code.addOpcode(Opcode.ARETURN);
  1245. return 1;
  1246. }
  1247. private static void makeParameterList(Bytecode code, Class[] params) {
  1248. int regno = 1;
  1249. int n = params.length;
  1250. code.addIconst(n);
  1251. code.addAnewarray("java/lang/Object");
  1252. for (int i = 0; i < n; i++) {
  1253. code.addOpcode(Opcode.DUP);
  1254. code.addIconst(i);
  1255. Class type = params[i];
  1256. if (type.isPrimitive())
  1257. regno = makeWrapper(code, type, regno);
  1258. else {
  1259. code.addAload(regno);
  1260. regno++;
  1261. }
  1262. code.addOpcode(Opcode.AASTORE);
  1263. }
  1264. }
  1265. private static int makeWrapper(Bytecode code, Class type, int regno) {
  1266. int index = FactoryHelper.typeIndex(type);
  1267. String wrapper = FactoryHelper.wrapperTypes[index];
  1268. code.addNew(wrapper);
  1269. code.addOpcode(Opcode.DUP);
  1270. addLoad(code, regno, type);
  1271. code.addInvokespecial(wrapper, "<init>",
  1272. FactoryHelper.wrapperDesc[index]);
  1273. return regno + FactoryHelper.dataSize[index];
  1274. }
  1275. private static void addUnwrapper(Bytecode code, Class type) {
  1276. if (type.isPrimitive()) {
  1277. if (type == Void.TYPE)
  1278. code.addOpcode(Opcode.POP);
  1279. else {
  1280. int index = FactoryHelper.typeIndex(type);
  1281. String wrapper = FactoryHelper.wrapperTypes[index];
  1282. code.addCheckcast(wrapper);
  1283. code.addInvokevirtual(wrapper,
  1284. FactoryHelper.unwarpMethods[index],
  1285. FactoryHelper.unwrapDesc[index]);
  1286. }
  1287. }
  1288. else
  1289. code.addCheckcast(type.getName());
  1290. }
  1291. private static MethodInfo makeWriteReplace(ConstPool cp) {
  1292. MethodInfo minfo = new MethodInfo(cp, "writeReplace", "()Ljava/lang/Object;");
  1293. String[] list = new String[1];
  1294. list[0] = "java.io.ObjectStreamException";
  1295. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1296. ea.setExceptions(list);
  1297. minfo.setExceptionsAttribute(ea);
  1298. Bytecode code = new Bytecode(cp, 0, 1);
  1299. code.addAload(0);
  1300. code.addInvokestatic("javassist.util.proxy.RuntimeSupport",
  1301. "makeSerializedProxy",
  1302. "(Ljava/lang/Object;)Ljavassist/util/proxy/SerializedProxy;");
  1303. code.addOpcode(Opcode.ARETURN);
  1304. minfo.setCodeAttribute(code.toCodeAttribute());
  1305. return minfo;
  1306. }
  1307. }