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

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