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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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, methods[i]);
  1035. // check if visibility has been reduced
  1036. if (null != oldMethod && Modifier.isPublic(oldMethod.getModifiers())
  1037. && !Modifier.isPublic(methods[i].getModifiers()) ) {
  1038. // we tried to overwrite a public definition with a non-public definition,
  1039. // use the old definition instead.
  1040. hash.put(key, oldMethod);
  1041. }
  1042. }
  1043. }
  1044. private static final String HANDLER_GETTER_KEY
  1045. = HANDLER_GETTER + ":()";
  1046. private static String keyToDesc(String key, Method m) {
  1047. return key.substring(key.indexOf(':') + 1);
  1048. }
  1049. private static MethodInfo makeConstructor(String thisClassName, Constructor cons,
  1050. ConstPool cp, Class superClass, boolean doHandlerInit) {
  1051. String desc = RuntimeSupport.makeDescriptor(cons.getParameterTypes(),
  1052. Void.TYPE);
  1053. MethodInfo minfo = new MethodInfo(cp, "<init>", desc);
  1054. minfo.setAccessFlags(Modifier.PUBLIC); // cons.getModifiers() & ~Modifier.NATIVE
  1055. setThrows(minfo, cp, cons.getExceptionTypes());
  1056. Bytecode code = new Bytecode(cp, 0, 0);
  1057. // legacy: if we are not using caching then we initialise the instance's handler
  1058. // from the class's static default interceptor and skip the next few instructions if
  1059. // it is non-null
  1060. if (doHandlerInit) {
  1061. code.addAload(0);
  1062. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1063. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1064. code.addGetstatic(thisClassName, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1065. code.addOpcode(Opcode.IFNONNULL);
  1066. code.addIndex(10);
  1067. }
  1068. // if caching is enabled then we don't have a handler to initialise so this else branch will install
  1069. // the handler located in the static field of class RuntimeSupport.
  1070. code.addAload(0);
  1071. code.addGetstatic(NULL_INTERCEPTOR_HOLDER, DEFAULT_INTERCEPTOR, HANDLER_TYPE);
  1072. code.addPutfield(thisClassName, HANDLER, HANDLER_TYPE);
  1073. int pc = code.currentPc();
  1074. code.addAload(0);
  1075. int s = addLoadParameters(code, cons.getParameterTypes(), 1);
  1076. code.addInvokespecial(superClass.getName(), "<init>", desc);
  1077. code.addOpcode(Opcode.RETURN);
  1078. code.setMaxLocals(s + 1);
  1079. CodeAttribute ca = code.toCodeAttribute();
  1080. minfo.setCodeAttribute(ca);
  1081. StackMapTable.Writer writer = new StackMapTable.Writer(32);
  1082. writer.sameFrame(pc);
  1083. ca.setAttribute(writer.toStackMapTable(cp));
  1084. return minfo;
  1085. }
  1086. private static MethodInfo makeDelegator(Method meth, String desc,
  1087. ConstPool cp, Class declClass, String delegatorName) {
  1088. MethodInfo delegator = new MethodInfo(cp, delegatorName, desc);
  1089. delegator.setAccessFlags(Modifier.FINAL | Modifier.PUBLIC
  1090. | (meth.getModifiers() & ~(Modifier.PRIVATE
  1091. | Modifier.PROTECTED
  1092. | Modifier.ABSTRACT
  1093. | Modifier.NATIVE
  1094. | Modifier.SYNCHRONIZED)));
  1095. setThrows(delegator, cp, meth);
  1096. Bytecode code = new Bytecode(cp, 0, 0);
  1097. code.addAload(0);
  1098. int s = addLoadParameters(code, meth.getParameterTypes(), 1);
  1099. code.addInvokespecial(declClass.getName(), meth.getName(), desc);
  1100. addReturn(code, meth.getReturnType());
  1101. code.setMaxLocals(++s);
  1102. delegator.setCodeAttribute(code.toCodeAttribute());
  1103. return delegator;
  1104. }
  1105. /**
  1106. * @param delegatorName null if the original method is abstract.
  1107. */
  1108. private static MethodInfo makeForwarder(String thisClassName,
  1109. Method meth, String desc, ConstPool cp,
  1110. Class declClass, String delegatorName, int index,
  1111. ArrayList forwarders) {
  1112. MethodInfo forwarder = new MethodInfo(cp, meth.getName(), desc);
  1113. forwarder.setAccessFlags(Modifier.FINAL
  1114. | (meth.getModifiers() & ~(Modifier.ABSTRACT
  1115. | Modifier.NATIVE
  1116. | Modifier.SYNCHRONIZED)));
  1117. setThrows(forwarder, cp, meth);
  1118. int args = Descriptor.paramSize(desc);
  1119. Bytecode code = new Bytecode(cp, 0, args + 2);
  1120. /*
  1121. * static {
  1122. * methods[index * 2]
  1123. * = RuntimeSupport.findSuperMethod(this, <overridden name>, <desc>);
  1124. * methods[index * 2 + 1]
  1125. * = RuntimeSupport.findMethod(this, <delegator name>, <desc>);
  1126. * or = null // the original method is abstract.
  1127. * }
  1128. * :
  1129. * return ($r)handler.invoke(this, methods[index * 2],
  1130. * methods[index * 2 + 1], $args);
  1131. */
  1132. int origIndex = index * 2;
  1133. int delIndex = index * 2 + 1;
  1134. int arrayVar = args + 1;
  1135. code.addGetstatic(thisClassName, HOLDER, HOLDER_TYPE);
  1136. code.addAstore(arrayVar);
  1137. forwarders.add(new Find2MethodsArgs(meth.getName(), delegatorName, desc, origIndex));
  1138. code.addAload(0);
  1139. code.addGetfield(thisClassName, HANDLER, HANDLER_TYPE);
  1140. code.addAload(0);
  1141. code.addAload(arrayVar);
  1142. code.addIconst(origIndex);
  1143. code.addOpcode(Opcode.AALOAD);
  1144. code.addAload(arrayVar);
  1145. code.addIconst(delIndex);
  1146. code.addOpcode(Opcode.AALOAD);
  1147. makeParameterList(code, meth.getParameterTypes());
  1148. code.addInvokeinterface(MethodHandler.class.getName(), "invoke",
  1149. "(Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;",
  1150. 5);
  1151. Class retType = meth.getReturnType();
  1152. addUnwrapper(code, retType);
  1153. addReturn(code, retType);
  1154. CodeAttribute ca = code.toCodeAttribute();
  1155. forwarder.setCodeAttribute(ca);
  1156. return forwarder;
  1157. }
  1158. static class Find2MethodsArgs {
  1159. String methodName, delegatorName, descriptor;
  1160. int origIndex;
  1161. Find2MethodsArgs(String mname, String dname, String desc, int index) {
  1162. methodName = mname;
  1163. delegatorName = dname;
  1164. descriptor = desc;
  1165. origIndex = index;
  1166. }
  1167. }
  1168. private static void setThrows(MethodInfo minfo, ConstPool cp, Method orig) {
  1169. Class[] exceptions = orig.getExceptionTypes();
  1170. setThrows(minfo, cp, exceptions);
  1171. }
  1172. private static void setThrows(MethodInfo minfo, ConstPool cp,
  1173. Class[] exceptions) {
  1174. if (exceptions.length == 0)
  1175. return;
  1176. String[] list = new String[exceptions.length];
  1177. for (int i = 0; i < exceptions.length; i++)
  1178. list[i] = exceptions[i].getName();
  1179. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1180. ea.setExceptions(list);
  1181. minfo.setExceptionsAttribute(ea);
  1182. }
  1183. private static int addLoadParameters(Bytecode code, Class[] params,
  1184. int offset) {
  1185. int stacksize = 0;
  1186. int n = params.length;
  1187. for (int i = 0; i < n; ++i)
  1188. stacksize += addLoad(code, stacksize + offset, params[i]);
  1189. return stacksize;
  1190. }
  1191. private static int addLoad(Bytecode code, int n, Class type) {
  1192. if (type.isPrimitive()) {
  1193. if (type == Long.TYPE) {
  1194. code.addLload(n);
  1195. return 2;
  1196. }
  1197. else if (type == Float.TYPE)
  1198. code.addFload(n);
  1199. else if (type == Double.TYPE) {
  1200. code.addDload(n);
  1201. return 2;
  1202. }
  1203. else
  1204. code.addIload(n);
  1205. }
  1206. else
  1207. code.addAload(n);
  1208. return 1;
  1209. }
  1210. private static int addReturn(Bytecode code, Class type) {
  1211. if (type.isPrimitive()) {
  1212. if (type == Long.TYPE) {
  1213. code.addOpcode(Opcode.LRETURN);
  1214. return 2;
  1215. }
  1216. else if (type == Float.TYPE)
  1217. code.addOpcode(Opcode.FRETURN);
  1218. else if (type == Double.TYPE) {
  1219. code.addOpcode(Opcode.DRETURN);
  1220. return 2;
  1221. }
  1222. else if (type == Void.TYPE) {
  1223. code.addOpcode(Opcode.RETURN);
  1224. return 0;
  1225. }
  1226. else
  1227. code.addOpcode(Opcode.IRETURN);
  1228. }
  1229. else
  1230. code.addOpcode(Opcode.ARETURN);
  1231. return 1;
  1232. }
  1233. private static void makeParameterList(Bytecode code, Class[] params) {
  1234. int regno = 1;
  1235. int n = params.length;
  1236. code.addIconst(n);
  1237. code.addAnewarray("java/lang/Object");
  1238. for (int i = 0; i < n; i++) {
  1239. code.addOpcode(Opcode.DUP);
  1240. code.addIconst(i);
  1241. Class type = params[i];
  1242. if (type.isPrimitive())
  1243. regno = makeWrapper(code, type, regno);
  1244. else {
  1245. code.addAload(regno);
  1246. regno++;
  1247. }
  1248. code.addOpcode(Opcode.AASTORE);
  1249. }
  1250. }
  1251. private static int makeWrapper(Bytecode code, Class type, int regno) {
  1252. int index = FactoryHelper.typeIndex(type);
  1253. String wrapper = FactoryHelper.wrapperTypes[index];
  1254. code.addNew(wrapper);
  1255. code.addOpcode(Opcode.DUP);
  1256. addLoad(code, regno, type);
  1257. code.addInvokespecial(wrapper, "<init>",
  1258. FactoryHelper.wrapperDesc[index]);
  1259. return regno + FactoryHelper.dataSize[index];
  1260. }
  1261. private static void addUnwrapper(Bytecode code, Class type) {
  1262. if (type.isPrimitive()) {
  1263. if (type == Void.TYPE)
  1264. code.addOpcode(Opcode.POP);
  1265. else {
  1266. int index = FactoryHelper.typeIndex(type);
  1267. String wrapper = FactoryHelper.wrapperTypes[index];
  1268. code.addCheckcast(wrapper);
  1269. code.addInvokevirtual(wrapper,
  1270. FactoryHelper.unwarpMethods[index],
  1271. FactoryHelper.unwrapDesc[index]);
  1272. }
  1273. }
  1274. else
  1275. code.addCheckcast(type.getName());
  1276. }
  1277. private static MethodInfo makeWriteReplace(ConstPool cp) {
  1278. MethodInfo minfo = new MethodInfo(cp, "writeReplace", "()Ljava/lang/Object;");
  1279. String[] list = new String[1];
  1280. list[0] = "java.io.ObjectStreamException";
  1281. ExceptionsAttribute ea = new ExceptionsAttribute(cp);
  1282. ea.setExceptions(list);
  1283. minfo.setExceptionsAttribute(ea);
  1284. Bytecode code = new Bytecode(cp, 0, 1);
  1285. code.addAload(0);
  1286. code.addInvokestatic("javassist.util.proxy.RuntimeSupport",
  1287. "makeSerializedProxy",
  1288. "(Ljava/lang/Object;)Ljavassist/util/proxy/SerializedProxy;");
  1289. code.addOpcode(Opcode.ARETURN);
  1290. minfo.setCodeAttribute(code.toCodeAttribute());
  1291. return minfo;
  1292. }
  1293. }