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.

ClassPath.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /* ====================================================================
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2001, 2017 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution,
  20. * if any, must include the following acknowledgment:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowledgment may appear in the software itself,
  24. * if and wherever such third-party acknowledgments normally appear.
  25. *
  26. * 4. The names "Apache" and "Apache Software Foundation" and
  27. * "Apache BCEL" must not be used to endorse or promote products
  28. * derived from this software without prior written permission. For
  29. * written permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache",
  32. * "Apache BCEL", nor may "Apache" appear in their name, without
  33. * prior written permission of the Apache Software Foundation.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.aspectj.apache.bcel.util;
  55. import java.io.ByteArrayInputStream;
  56. import java.io.DataInputStream;
  57. import java.io.File;
  58. import java.io.FileInputStream;
  59. import java.io.FilenameFilter;
  60. import java.io.IOException;
  61. import java.io.InputStream;
  62. import java.io.Serializable;
  63. import java.net.URI;
  64. import java.nio.file.FileSystems;
  65. import java.nio.file.FileVisitResult;
  66. import java.nio.file.Files;
  67. import java.nio.file.Path;
  68. import java.nio.file.SimpleFileVisitor;
  69. import java.nio.file.attribute.BasicFileAttributeView;
  70. import java.nio.file.attribute.BasicFileAttributes;
  71. import java.util.ArrayList;
  72. import java.util.HashMap;
  73. import java.util.Iterator;
  74. import java.util.Map;
  75. import java.util.StringTokenizer;
  76. import java.util.zip.ZipEntry;
  77. import java.util.zip.ZipFile;
  78. /**
  79. * Responsible for loading (class) files from the CLASSPATH. Inspired by
  80. * sun.tools.ClassPath.
  81. *
  82. * @author M. Dahm
  83. * @author Mario Ivankovits
  84. * @author Andy Clement
  85. */
  86. public class ClassPath implements Serializable {
  87. private static final String JRT_FS = "jrt-fs.jar";
  88. private static ClassPath SYSTEM_CLASS_PATH = null;
  89. private PathEntry[] paths;
  90. private String class_path;
  91. public static ClassPath getSystemClassPath() {
  92. if (SYSTEM_CLASS_PATH == null) {
  93. SYSTEM_CLASS_PATH = new ClassPath();
  94. }
  95. return SYSTEM_CLASS_PATH;
  96. }
  97. /**
  98. * Search for classes in given path.
  99. */
  100. public ClassPath(String class_path) {
  101. this.class_path = class_path;
  102. ArrayList<PathEntry> vec = new ArrayList<PathEntry>();
  103. for (StringTokenizer tok = new StringTokenizer(class_path, System.getProperty("path.separator")); tok
  104. .hasMoreTokens();) {
  105. String path = tok.nextToken();
  106. if (!path.equals("")) {
  107. File file = new File(path);
  108. try {
  109. if (file.exists()) {
  110. if (file.isDirectory()) {
  111. vec.add(new Dir(path));
  112. } else if (file.getName().endsWith("jrt-fs.jar")) { // TODO a bit crude...
  113. vec.add(new JImage());
  114. } else {
  115. vec.add(new Zip(new ZipFile(file)));
  116. }
  117. }
  118. } catch (IOException e) {
  119. System.err.println("CLASSPATH component " + file + ": " + e);
  120. }
  121. }
  122. }
  123. paths = new PathEntry[vec.size()];
  124. vec.toArray(paths);
  125. }
  126. /**
  127. * Search for classes in CLASSPATH.
  128. *
  129. * @deprecated Use SYSTEM_CLASS_PATH constant
  130. */
  131. @Deprecated
  132. public ClassPath() {
  133. this(getClassPath());
  134. }
  135. /**
  136. * @return used class path string
  137. */
  138. @Override
  139. public String toString() {
  140. return class_path;
  141. }
  142. @Override
  143. public int hashCode() {
  144. return class_path.hashCode();
  145. }
  146. @Override
  147. public boolean equals(Object o) {
  148. if (o instanceof ClassPath) {
  149. return class_path.equals(((ClassPath) o).class_path);
  150. }
  151. return false;
  152. }
  153. private static final void getPathComponents(String path, ArrayList<String> list) {
  154. if (path != null) {
  155. StringTokenizer tok = new StringTokenizer(path, File.pathSeparator);
  156. while (tok.hasMoreTokens()) {
  157. String name = tok.nextToken();
  158. File file = new File(name);
  159. if (file.exists())
  160. list.add(name);
  161. }
  162. }
  163. }
  164. /**
  165. * Checks for class path components in the following properties:
  166. * "java.class.path", "sun.boot.class.path", "java.ext.dirs"
  167. *
  168. * @return class path as used by default by BCEL
  169. */
  170. public static final String getClassPath() {
  171. String class_path = System.getProperty("java.class.path");
  172. String boot_path = System.getProperty("sun.boot.class.path");
  173. String ext_path = System.getProperty("java.ext.dirs");
  174. String vm_version = System.getProperty("java.version");
  175. ArrayList<String> list = new ArrayList<String>();
  176. getPathComponents(class_path, list);
  177. getPathComponents(boot_path, list);
  178. ArrayList<String> dirs = new ArrayList<String>();
  179. getPathComponents(ext_path, dirs);
  180. for (Iterator<String> e = dirs.iterator(); e.hasNext();) {
  181. File ext_dir = new File(e.next());
  182. String[] extensions = ext_dir.list(new FilenameFilter() {
  183. @Override
  184. public boolean accept(File dir, String name) {
  185. name = name.toLowerCase();
  186. return name.endsWith(".zip") || name.endsWith(".jar");
  187. }
  188. });
  189. if (extensions != null)
  190. for (int i = 0; i < extensions.length; i++)
  191. list.add(ext_path + File.separatorChar + extensions[i]);
  192. }
  193. StringBuffer buf = new StringBuffer();
  194. for (Iterator<String> e = list.iterator(); e.hasNext();) {
  195. buf.append(e.next());
  196. if (e.hasNext())
  197. buf.append(File.pathSeparatorChar);
  198. }
  199. // On Java9 the sun.boot.class.path won't be set. System classes accessible through JRT filesystem
  200. if (vm_version.startsWith("9") || vm_version.startsWith("10") || vm_version.startsWith("11")) {
  201. buf.insert(0, File.pathSeparatorChar);
  202. buf.insert(0, System.getProperty("java.home") + File.separator + "lib" + File.separator + JRT_FS);
  203. }
  204. return buf.toString().intern();
  205. }
  206. /**
  207. * @param name
  208. * fully qualified class name, e.g. java.lang.String
  209. * @return input stream for class
  210. */
  211. public InputStream getInputStream(String name) throws IOException {
  212. return getInputStream(name, ".class");
  213. }
  214. /**
  215. * Return stream for class or resource on CLASSPATH.
  216. *
  217. * @param name
  218. * fully qualified file name, e.g. java/lang/String
  219. * @param suffix
  220. * file name ends with suff, e.g. .java
  221. * @return input stream for file on class path
  222. */
  223. public InputStream getInputStream(String name, String suffix) throws IOException {
  224. InputStream is = null;
  225. try {
  226. is = getClass().getClassLoader().getResourceAsStream(name + suffix);
  227. } catch (Exception e) {
  228. }
  229. if (is != null)
  230. return is;
  231. return getClassFile(name, suffix).getInputStream();
  232. }
  233. /**
  234. * @param name
  235. * fully qualified file name, e.g. java/lang/String
  236. * @param suffix
  237. * file name ends with suff, e.g. .java
  238. * @return class file for the java class
  239. */
  240. public ClassFile getClassFile(String name, String suffix) throws IOException {
  241. for (int i = 0; i < paths.length; i++) {
  242. ClassFile cf;
  243. if ((cf = paths[i].getClassFile(name, suffix)) != null)
  244. return cf;
  245. }
  246. throw new IOException("Couldn't find: " + name + suffix);
  247. }
  248. /**
  249. * @param name
  250. * fully qualified class name, e.g. java.lang.String
  251. * @return input stream for class
  252. */
  253. public ClassFile getClassFile(String name) throws IOException {
  254. return getClassFile(name, ".class");
  255. }
  256. /**
  257. * @param name
  258. * fully qualified file name, e.g. java/lang/String
  259. * @param suffix
  260. * file name ends with suffix, e.g. .java
  261. * @return byte array for file on class path
  262. */
  263. public byte[] getBytes(String name, String suffix) throws IOException {
  264. InputStream is = getInputStream(name, suffix);
  265. if (is == null)
  266. throw new IOException("Couldn't find: " + name + suffix);
  267. DataInputStream dis = new DataInputStream(is);
  268. byte[] bytes = new byte[is.available()];
  269. dis.readFully(bytes);
  270. dis.close();
  271. is.close();
  272. return bytes;
  273. }
  274. /**
  275. * @return byte array for class
  276. */
  277. public byte[] getBytes(String name) throws IOException {
  278. return getBytes(name, ".class");
  279. }
  280. /**
  281. * @param name
  282. * name of file to search for, e.g. java/lang/String.java
  283. * @return full (canonical) path for file
  284. */
  285. public String getPath(String name) throws IOException {
  286. int index = name.lastIndexOf('.');
  287. String suffix = "";
  288. if (index > 0) {
  289. suffix = name.substring(index);
  290. name = name.substring(0, index);
  291. }
  292. return getPath(name, suffix);
  293. }
  294. /**
  295. * @param name
  296. * name of file to search for, e.g. java/lang/String
  297. * @param suffix
  298. * file name suffix, e.g. .java
  299. * @return full (canonical) path for file, if it exists
  300. */
  301. public String getPath(String name, String suffix) throws IOException {
  302. return getClassFile(name, suffix).getPath();
  303. }
  304. private static abstract class PathEntry implements Serializable {
  305. abstract ClassFile getClassFile(String name, String suffix) throws IOException;
  306. }
  307. /**
  308. * Contains information about file/ZIP entry of the Java class.
  309. */
  310. public interface ClassFile {
  311. /**
  312. * @return input stream for class file.
  313. */
  314. public abstract InputStream getInputStream() throws IOException;
  315. /**
  316. * @return canonical path to class file.
  317. */
  318. public abstract String getPath();
  319. /**
  320. * @return base path of found class, i.e. class is contained relative to
  321. * that path, which may either denote a directory, or zip file
  322. */
  323. public abstract String getBase();
  324. /**
  325. * @return modification time of class file.
  326. */
  327. public abstract long getTime();
  328. /**
  329. * @return size of class file.
  330. */
  331. public abstract long getSize();
  332. }
  333. private static class Dir extends PathEntry {
  334. private String dir;
  335. Dir(String d) {
  336. dir = d;
  337. }
  338. @Override
  339. ClassFile getClassFile(String name, String suffix) throws IOException {
  340. final File file = new File(dir + File.separatorChar + name.replace('.', File.separatorChar) + suffix);
  341. return file.exists() ? new ClassFile() {
  342. @Override
  343. public InputStream getInputStream() throws IOException {
  344. return new FileInputStream(file);
  345. }
  346. @Override
  347. public String getPath() {
  348. try {
  349. return file.getCanonicalPath();
  350. } catch (IOException e) {
  351. return null;
  352. }
  353. }
  354. @Override
  355. public long getTime() {
  356. return file.lastModified();
  357. }
  358. @Override
  359. public long getSize() {
  360. return file.length();
  361. }
  362. @Override
  363. public String getBase() {
  364. return dir;
  365. }
  366. } : null;
  367. }
  368. @Override
  369. public String toString() {
  370. return dir;
  371. }
  372. }
  373. private static class JImage extends PathEntry {
  374. private static URI JRT_URI = URI.create("jrt:/"); //$NON-NLS-1$
  375. private static String MODULES_PATH = "modules"; //$NON-NLS-1$
  376. private static String JAVA_BASE_PATH = "java.base"; //$NON-NLS-1$
  377. private java.nio.file.FileSystem fs;
  378. private final Map<String, Path> fileMap;
  379. JImage() {
  380. fs = FileSystems.getFileSystem(JRT_URI);
  381. fileMap = buildFileMap();
  382. }
  383. private Map<String, Path> buildFileMap() {
  384. final Map<String, Path> fileMap = new HashMap<>();
  385. final java.nio.file.PathMatcher matcher = fs.getPathMatcher("glob:*.class");
  386. Iterable<java.nio.file.Path> roots = fs.getRootDirectories();
  387. for (java.nio.file.Path path : roots) {
  388. try {
  389. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  390. @Override
  391. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  392. if (file.getNameCount() > 2
  393. && matcher.matches(file.getFileName())) {
  394. Path classPath = file.subpath(2, file.getNameCount());
  395. fileMap.put(classPath.toString(), file);
  396. }
  397. return FileVisitResult.CONTINUE;
  398. }
  399. });
  400. }
  401. catch (IOException e) {
  402. throw new RuntimeException(e);
  403. }
  404. }
  405. return fileMap;
  406. }
  407. private static class ByteBasedClassFile implements ClassFile {
  408. private byte[] bytes;
  409. private ByteArrayInputStream bais;
  410. private String path;
  411. private String base;
  412. private long time;
  413. private long size;
  414. public ByteBasedClassFile(byte[] bytes, String path, String base, long time, long size) {
  415. this.bytes = bytes;
  416. this.path = path;
  417. this.base = base;
  418. this.time = time;
  419. this.size = size;
  420. }
  421. @Override
  422. public InputStream getInputStream() throws IOException {
  423. // TODO too costly to keep these in inflated form in memory?
  424. this.bais = new ByteArrayInputStream(bytes);
  425. return this.bais;
  426. }
  427. @Override
  428. public String getPath() {
  429. return this.path;
  430. }
  431. @Override
  432. public String getBase() {
  433. return this.base;
  434. }
  435. @Override
  436. public long getTime() {
  437. return this.time;
  438. }
  439. @Override
  440. public long getSize() {
  441. return this.size;
  442. }
  443. }
  444. @Override
  445. ClassFile getClassFile(String name, String suffix) throws IOException {
  446. // Class files are in here under names like this:
  447. // /modules/java.base/java/lang/Object.class (jdk9 b74)
  448. // so within a modules top level qualifier and then the java.base module
  449. String fileName = name.replace('.', '/') + suffix;
  450. Path p = fileMap.get(fileName);
  451. if (p == null) {
  452. return null;
  453. }
  454. byte[] bs = Files.readAllBytes(p);
  455. BasicFileAttributeView bfav = Files.getFileAttributeView(p, BasicFileAttributeView.class);
  456. BasicFileAttributes bfas = bfav.readAttributes();
  457. long time = bfas.lastModifiedTime().toMillis();
  458. long size = bfas.size();
  459. ClassFile cf = new ByteBasedClassFile(bs, "jimage",fileName,time,size);
  460. return cf;
  461. }
  462. }
  463. private static class Zip extends PathEntry {
  464. private ZipFile zip;
  465. Zip(ZipFile z) {
  466. zip = z;
  467. }
  468. @Override
  469. ClassFile getClassFile(String name, String suffix) throws IOException {
  470. final ZipEntry entry = zip.getEntry(name.replace('.', '/') + suffix);
  471. return (entry != null) ? new ClassFile() {
  472. @Override
  473. public InputStream getInputStream() throws IOException {
  474. return zip.getInputStream(entry);
  475. }
  476. @Override
  477. public String getPath() {
  478. return entry.toString();
  479. }
  480. @Override
  481. public long getTime() {
  482. return entry.getTime();
  483. }
  484. @Override
  485. public long getSize() {
  486. return entry.getSize();
  487. }
  488. @Override
  489. public String getBase() {
  490. return zip.getName();
  491. }
  492. } : null;
  493. }
  494. }
  495. }