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.

Loader.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. * <ul><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></ul>
  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. * <ul><pre>
  59. * % java Main <i>arg1</i> <i>arg2</i>...
  60. * </pre></ul>
  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. * <ul><pre>
  70. * % java MyApp <i>arg1</i> <i>arg2</i>...
  71. * </pre></ul>
  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. * <ul><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></ul>
  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. * <ul>
  236. * <code>args[0]</code> is the class name to be loaded.
  237. * <br><code>args[1..n]</code> are parameters passed
  238. * to the target <code>main()</code>.
  239. * </ul>
  240. *
  241. * @see javassist.Loader#run(String[])
  242. */
  243. public static void main(String[] args) throws Throwable {
  244. Loader cl = new Loader();
  245. cl.run(args);
  246. }
  247. /**
  248. * Loads a class and calls <code>main()</code> in that class.
  249. *
  250. * @param args command line parameters.
  251. * <ul>
  252. * <code>args[0]</code> is the class name to be loaded.
  253. * <br><code>args[1..n]</code> are parameters passed
  254. * to the target <code>main()</code>.
  255. * </ul>
  256. */
  257. public void run(String[] args) throws Throwable {
  258. int n = args.length - 1;
  259. if (n >= 0) {
  260. String[] args2 = new String[n];
  261. for (int i = 0; i < n; ++i)
  262. args2[i] = args[i + 1];
  263. run(args[0], args2);
  264. }
  265. }
  266. /**
  267. * Loads a class and calls <code>main()</code> in that class.
  268. *
  269. * @param classname the loaded class.
  270. * @param args parameters passed to <code>main()</code>.
  271. */
  272. public void run(String classname, String[] args) throws Throwable {
  273. Class c = loadClass(classname);
  274. try {
  275. c.getDeclaredMethod("main", new Class[] { String[].class }).invoke(
  276. null,
  277. new Object[] { args });
  278. }
  279. catch (java.lang.reflect.InvocationTargetException e) {
  280. throw e.getTargetException();
  281. }
  282. }
  283. /**
  284. * Requests the class loader to load a class.
  285. */
  286. protected Class loadClass(String name, boolean resolve)
  287. throws ClassFormatError, ClassNotFoundException {
  288. name = name.intern();
  289. synchronized (name) {
  290. Class c = findLoadedClass(name);
  291. if (c == null)
  292. c = loadClassByDelegation(name);
  293. if (c == null)
  294. c = findClass(name);
  295. if (c == null)
  296. c = delegateToParent(name);
  297. if (resolve)
  298. resolveClass(c);
  299. return c;
  300. }
  301. }
  302. /**
  303. * Finds the specified class using <code>ClassPath</code>.
  304. * If the source throws an exception, this returns null.
  305. *
  306. * <p>This method can be overridden by a subclass of
  307. * <code>Loader</code>. Note that the overridden method must not throw
  308. * an exception when it just fails to find a class file.
  309. *
  310. * @return null if the specified class could not be found.
  311. * @throws ClassNotFoundException if an exception is thrown while
  312. * obtaining a class file.
  313. */
  314. protected Class findClass(String name) throws ClassNotFoundException {
  315. byte[] classfile;
  316. try {
  317. if (source != null) {
  318. if (translator != null)
  319. translator.onLoad(source, name);
  320. try {
  321. classfile = source.get(name).toBytecode();
  322. }
  323. catch (NotFoundException e) {
  324. return null;
  325. }
  326. }
  327. else {
  328. String jarname = "/" + name.replace('.', '/') + ".class";
  329. InputStream in = this.getClass().getResourceAsStream(jarname);
  330. if (in == null)
  331. return null;
  332. classfile = ClassPoolTail.readStream(in);
  333. }
  334. }
  335. catch (Exception e) {
  336. throw new ClassNotFoundException(
  337. "caught an exception while obtaining a class file for "
  338. + name, e);
  339. }
  340. int i = name.lastIndexOf('.');
  341. if (i != -1) {
  342. String pname = name.substring(0, i);
  343. if (getPackage(pname) == null)
  344. try {
  345. definePackage(
  346. pname, null, null, null, null, null, null, null);
  347. }
  348. catch (IllegalArgumentException e) {
  349. // ignore. maybe the package object for the same
  350. // name has been created just right away.
  351. }
  352. }
  353. if (domain == null)
  354. return defineClass(name, classfile, 0, classfile.length);
  355. else
  356. return defineClass(name, classfile, 0, classfile.length, domain);
  357. }
  358. protected Class loadClassByDelegation(String name)
  359. throws ClassNotFoundException
  360. {
  361. /* The swing components must be loaded by a system
  362. * class loader.
  363. * javax.swing.UIManager loads a (concrete) subclass
  364. * of LookAndFeel by a system class loader and cast
  365. * an instance of the class to LookAndFeel for
  366. * (maybe) a security reason. To avoid failure of
  367. * type conversion, LookAndFeel must not be loaded
  368. * by this class loader.
  369. */
  370. Class c = null;
  371. if (doDelegation)
  372. if (name.startsWith("java.")
  373. || name.startsWith("javax.")
  374. || name.startsWith("sun.")
  375. || name.startsWith("com.sun.")
  376. || name.startsWith("org.w3c.")
  377. || name.startsWith("org.xml.")
  378. || notDelegated(name))
  379. c = delegateToParent(name);
  380. return c;
  381. }
  382. private boolean notDelegated(String name) {
  383. if (notDefinedHere.get(name) != null)
  384. return true;
  385. int n = notDefinedPackages.size();
  386. for (int i = 0; i < n; ++i)
  387. if (name.startsWith((String)notDefinedPackages.elementAt(i)))
  388. return true;
  389. return false;
  390. }
  391. protected Class delegateToParent(String classname)
  392. throws ClassNotFoundException
  393. {
  394. ClassLoader cl = getParent();
  395. if (cl != null)
  396. return cl.loadClass(classname);
  397. else
  398. return findSystemClass(classname);
  399. }
  400. protected Package getPackage(String name) {
  401. return super.getPackage(name);
  402. }
  403. /*
  404. // Package p = super.getPackage(name);
  405. Package p = null;
  406. if (p == null)
  407. return definePackage(name, null, null, null,
  408. null, null, null, null);
  409. else
  410. return p;
  411. }
  412. */
  413. }