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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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;
  17. import java.io.*;
  18. import java.util.Hashtable;
  19. import java.util.Vector;
  20. import java.security.ProtectionDomain;
  21. /**
  22. * The class loader for Javassist.
  23. *
  24. * <p>This is a sample class loader using <code>ClassPool</code>.
  25. * Unlike a regular class loader, this class loader obtains bytecode
  26. * from a <code>ClassPool</code>.
  27. *
  28. * <p>Note that Javassist can be used without this class loader; programmers
  29. * can define their own versions of class loader. They can run
  30. * a program even without any user-defined class loader if that program
  31. * is statically translated with Javassist.
  32. * This class loader is just provided as a utility class.
  33. *
  34. * <p>Suppose that an instance of <code>MyTranslator</code> implementing
  35. * the interface <code>Translator</code> is responsible for modifying
  36. * class files.
  37. * The startup program of an application using <code>MyTranslator</code>
  38. * should be something like this:
  39. *
  40. * <pre>
  41. * import javassist.*;
  42. *
  43. * public class Main {
  44. * public static void main(String[] args) throws Throwable {
  45. * MyTranslator myTrans = new MyTranslator();
  46. * ClassPool cp = ClassPool.getDefault();
  47. * Loader cl = new Loader(cp);
  48. * cl.addTranslator(cp, myTrans);
  49. * cl.run("MyApp", args);
  50. * }
  51. * }
  52. * </pre>
  53. *
  54. * <p>Class <code>MyApp</code> is the main program of the application.
  55. *
  56. * <p>This program should be executed as follows:
  57. *
  58. * <pre>
  59. * % java Main <i>arg1</i> <i>arg2</i>...
  60. * </pre>
  61. *
  62. * <p>It modifies the class <code>MyApp</code> with a <code>MyTranslator</code>
  63. * object before the JVM loads it.
  64. * Then it calls <code>main()</code> in <code>MyApp</code> with arguments
  65. * <i>arg1</i>, <i>arg2</i>, ...
  66. *
  67. * <p>This program execution is equivalent to:
  68. *
  69. * <pre>
  70. * % java MyApp <i>arg1</i> <i>arg2</i>...
  71. * </pre>
  72. *
  73. * <p>except that classes are translated by <code>MyTranslator</code>
  74. * at load time.
  75. *
  76. * <p>If only a particular class must be modified when it is loaded,
  77. * the startup program can be simpler; <code>MyTranslator</code> is
  78. * unnecessary. For example, if only a class <code>test.Rectangle</code>
  79. * is modified, the <code>main()</code> method above will be the following:
  80. *
  81. * <pre>
  82. * ClassPool cp = ClassPool.getDefault();
  83. * Loader cl = new Loader(cp);
  84. * CtClass ct = cp.get("test.Rectangle");
  85. * ct.setSuperclass(cp.get("test.Point"));
  86. * cl.run("MyApp", args);</pre>
  87. *
  88. * <p>This program changes the super class of the <code>test.Rectangle</code>
  89. * class.
  90. *
  91. * <p><b>Note 1:</b>
  92. *
  93. * <p>This class loader does not allow the users to intercept the loading
  94. * of <code>java.*</code> and <code>javax.*</code> classes (and
  95. * <code>sun.*</code>, <code>org.xml.*</code>, ...) unless
  96. * <code>Loader.doDelegation</code> is <code>false</code>. This is because
  97. * the JVM prohibits a user class loader from loading a system class.
  98. * Also see Note 2.
  99. * If this behavior is not appropriate, a subclass of <code>Loader</code>
  100. * must be defined and <code>loadClassByDelegation()</code> must be overridden.
  101. *
  102. * <p><b>Note 2:</b>
  103. *
  104. * <p>If classes are loaded with different class loaders, they belong to
  105. * separate name spaces. If class <code>C</code> is loaded by a class
  106. * loader <code>CL</code>, all classes that the class <code>C</code>
  107. * refers to are also loaded by <code>CL</code>. However, if <code>CL</code>
  108. * delegates the loading of the class <code>C</code> to <code>CL'</code>,
  109. * then those classes that the class <code>C</code> refers to
  110. * are loaded by a parent class loader <code>CL'</code>
  111. * instead of <code>CL</code>.
  112. *
  113. * <p>If an object of class <code>C</code> is assigned
  114. * to a variable of class <code>C</code> belonging to a different name
  115. * space, then a <code>ClassCastException</code> is thrown.
  116. *
  117. * <p>Because of the fact above, this loader delegates only the loading of
  118. * <code>javassist.Loader</code>
  119. * and classes included in package <code>java.*</code> and
  120. * <code>javax.*</code> to the parent class
  121. * loader. Other classes are directly loaded by this loader.
  122. *
  123. * <p>For example, suppose that <code>java.lang.String</code> would be loaded
  124. * by this loader while <code>java.io.File</code> is loaded by the parent
  125. * class loader. If the constructor of <code>java.io.File</code> is called
  126. * with an instance of <code>java.lang.String</code>, then it may throw
  127. * an exception since it accepts an instance of only the
  128. * <code>java.lang.String</code> loaded by the parent class loader.
  129. *
  130. * @see javassist.ClassPool
  131. * @see javassist.Translator
  132. */
  133. public class Loader extends ClassLoader {
  134. private Hashtable notDefinedHere; // must be atomic.
  135. private Vector notDefinedPackages; // must be atomic.
  136. private ClassPool source;
  137. private Translator translator;
  138. private ProtectionDomain domain;
  139. /**
  140. * Specifies the algorithm of class loading.
  141. *
  142. * <p>This class loader uses the parent class loader for
  143. * <code>java.*</code> and <code>javax.*</code> classes.
  144. * If this variable <code>doDelegation</code>
  145. * is <code>false</code>, this class loader does not delegate those
  146. * classes to the parent class loader.
  147. *
  148. * <p>The default value is <code>true</code>.
  149. */
  150. public boolean doDelegation = true;
  151. /**
  152. * Creates a new class loader.
  153. */
  154. public Loader() {
  155. this(null);
  156. }
  157. /**
  158. * Creates a new class loader.
  159. *
  160. * @param cp the source of class files.
  161. */
  162. public Loader(ClassPool cp) {
  163. init(cp);
  164. }
  165. /**
  166. * Creates a new class loader
  167. * using the specified parent class loader for delegation.
  168. *
  169. * @param parent the parent class loader.
  170. * @param cp the source of class files.
  171. */
  172. public Loader(ClassLoader parent, ClassPool cp) {
  173. super(parent);
  174. init(cp);
  175. }
  176. private void init(ClassPool cp) {
  177. notDefinedHere = new Hashtable();
  178. notDefinedPackages = new Vector();
  179. source = cp;
  180. translator = null;
  181. domain = null;
  182. delegateLoadingOf("javassist.Loader");
  183. }
  184. /**
  185. * Records a class so that the loading of that class is delegated
  186. * to the parent class loader.
  187. *
  188. * <p>If the given class name ends with <code>.</code> (dot), then
  189. * that name is interpreted as a package name. All the classes
  190. * in that package and the sub packages are delegated.
  191. */
  192. public void delegateLoadingOf(String classname) {
  193. if (classname.endsWith("."))
  194. notDefinedPackages.addElement(classname);
  195. else
  196. notDefinedHere.put(classname, this);
  197. }
  198. /**
  199. * Sets the protection domain for the classes handled by this class
  200. * loader. Without registering an appropriate protection domain,
  201. * the program loaded by this loader will not work with a security
  202. * manager or a signed jar file.
  203. */
  204. public void setDomain(ProtectionDomain d) {
  205. domain = d;
  206. }
  207. /**
  208. * Sets the soruce <code>ClassPool</code>.
  209. */
  210. public void setClassPool(ClassPool cp) {
  211. source = cp;
  212. }
  213. /**
  214. * Adds a translator, which is called whenever a class is loaded.
  215. *
  216. * @param cp the <code>ClassPool</code> object for obtaining
  217. * a class file.
  218. * @param t a translator.
  219. * @throws NotFoundException if <code>t.start()</code> throws an exception.
  220. * @throws CannotCompileException if <code>t.start()</code> throws an exception.
  221. */
  222. public void addTranslator(ClassPool cp, Translator t)
  223. throws NotFoundException, CannotCompileException {
  224. source = cp;
  225. translator = t;
  226. t.start(cp);
  227. }
  228. /**
  229. * Loads a class with an instance of <code>Loader</code>
  230. * and calls <code>main()</code> of that class.
  231. *
  232. * <p>This method calls <code>run()</code>.
  233. *
  234. * @param args command line parameters.
  235. * <br>&nbsp;&nbsp;{@code args[0]} is the class name to be loaded.
  236. * <br>&nbsp;&nbsp;{@code args[1..n]} are parameters passed
  237. * to the target {@code main()}.
  238. *
  239. * @see javassist.Loader#run(String[])
  240. */
  241. public static void main(String[] args) throws Throwable {
  242. Loader cl = new Loader();
  243. cl.run(args);
  244. }
  245. /**
  246. * Loads a class and calls <code>main()</code> in that class.
  247. *
  248. * @param args command line parameters.
  249. *
  250. * <br>&nbsp;&nbsp;{@code args[0]} is the class name to be loaded.
  251. * <br>&nbsp;&nbsp;{@code args[1..n]} are parameters passed
  252. * to the target {@code main()}.
  253. */
  254. public void run(String[] args) throws Throwable {
  255. int n = args.length - 1;
  256. if (n >= 0) {
  257. String[] args2 = new String[n];
  258. for (int i = 0; i < n; ++i)
  259. args2[i] = args[i + 1];
  260. run(args[0], args2);
  261. }
  262. }
  263. /**
  264. * Loads a class and calls <code>main()</code> in that class.
  265. *
  266. * @param classname the loaded class.
  267. * @param args parameters passed to <code>main()</code>.
  268. */
  269. public void run(String classname, String[] args) throws Throwable {
  270. Class c = loadClass(classname);
  271. try {
  272. c.getDeclaredMethod("main", new Class[] { String[].class }).invoke(
  273. null,
  274. new Object[] { args });
  275. }
  276. catch (java.lang.reflect.InvocationTargetException e) {
  277. throw e.getTargetException();
  278. }
  279. }
  280. /**
  281. * Requests the class loader to load a class.
  282. */
  283. protected Class loadClass(String name, boolean resolve)
  284. throws ClassFormatError, ClassNotFoundException {
  285. name = name.intern();
  286. synchronized (name) {
  287. Class c = findLoadedClass(name);
  288. if (c == null)
  289. c = loadClassByDelegation(name);
  290. if (c == null)
  291. c = findClass(name);
  292. if (c == null)
  293. c = delegateToParent(name);
  294. if (resolve)
  295. resolveClass(c);
  296. return c;
  297. }
  298. }
  299. /**
  300. * Finds the specified class using <code>ClassPath</code>.
  301. * If the source throws an exception, this returns null.
  302. *
  303. * <p>This method can be overridden by a subclass of
  304. * <code>Loader</code>. Note that the overridden method must not throw
  305. * an exception when it just fails to find a class file.
  306. *
  307. * @return null if the specified class could not be found.
  308. * @throws ClassNotFoundException if an exception is thrown while
  309. * obtaining a class file.
  310. */
  311. protected Class findClass(String name) throws ClassNotFoundException {
  312. byte[] classfile;
  313. try {
  314. if (source != null) {
  315. if (translator != null)
  316. translator.onLoad(source, name);
  317. try {
  318. classfile = source.get(name).toBytecode();
  319. }
  320. catch (NotFoundException e) {
  321. return null;
  322. }
  323. }
  324. else {
  325. String jarname = "/" + name.replace('.', '/') + ".class";
  326. InputStream in = this.getClass().getResourceAsStream(jarname);
  327. if (in == null)
  328. return null;
  329. classfile = ClassPoolTail.readStream(in);
  330. }
  331. }
  332. catch (Exception e) {
  333. throw new ClassNotFoundException(
  334. "caught an exception while obtaining a class file for "
  335. + name, e);
  336. }
  337. int i = name.lastIndexOf('.');
  338. if (i != -1) {
  339. String pname = name.substring(0, i);
  340. if (getPackage(pname) == null)
  341. try {
  342. definePackage(
  343. pname, null, null, null, null, null, null, null);
  344. }
  345. catch (IllegalArgumentException e) {
  346. // ignore. maybe the package object for the same
  347. // name has been created just right away.
  348. }
  349. }
  350. if (domain == null)
  351. return defineClass(name, classfile, 0, classfile.length);
  352. else
  353. return defineClass(name, classfile, 0, classfile.length, domain);
  354. }
  355. protected Class loadClassByDelegation(String name)
  356. throws ClassNotFoundException
  357. {
  358. /* The swing components must be loaded by a system
  359. * class loader.
  360. * javax.swing.UIManager loads a (concrete) subclass
  361. * of LookAndFeel by a system class loader and cast
  362. * an instance of the class to LookAndFeel for
  363. * (maybe) a security reason. To avoid failure of
  364. * type conversion, LookAndFeel must not be loaded
  365. * by this class loader.
  366. */
  367. Class c = null;
  368. if (doDelegation)
  369. if (name.startsWith("java.")
  370. || name.startsWith("javax.")
  371. || name.startsWith("sun.")
  372. || name.startsWith("com.sun.")
  373. || name.startsWith("org.w3c.")
  374. || name.startsWith("org.xml.")
  375. || notDelegated(name))
  376. c = delegateToParent(name);
  377. return c;
  378. }
  379. private boolean notDelegated(String name) {
  380. if (notDefinedHere.get(name) != null)
  381. return true;
  382. int n = notDefinedPackages.size();
  383. for (int i = 0; i < n; ++i)
  384. if (name.startsWith((String)notDefinedPackages.elementAt(i)))
  385. return true;
  386. return false;
  387. }
  388. protected Class delegateToParent(String classname)
  389. throws ClassNotFoundException
  390. {
  391. ClassLoader cl = getParent();
  392. if (cl != null)
  393. return cl.loadClass(classname);
  394. else
  395. return findSystemClass(classname);
  396. }
  397. }