Skip to content

Commit

Permalink
Make ClassPath search the contents of the "java.class.path" system pr…
Browse files Browse the repository at this point in the history
…operty for the system class loader in Java 9.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=168478543
  • Loading branch information
netdpb authored and cpovirk committed Sep 13, 2017
1 parent a49e1d0 commit 63898e2
Show file tree
Hide file tree
Showing 4 changed files with 234 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
package com.google.common.reflect;

import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.truth.Truth.assertThat;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closer;
import com.google.common.io.Files;
Expand All @@ -39,6 +42,7 @@
import java.net.URL;
import java.net.URLClassLoader;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
Expand Down Expand Up @@ -359,6 +363,40 @@ public void testGetPackageName() {

// Test that ResourceInfo.urls() returns identical content to ClassLoader.getResources()

public void testGetClassPathUrls() throws Exception {
String oldPathSeparator = PATH_SEPARATOR.value();
String oldClassPath = JAVA_CLASS_PATH.value();
System.setProperty(PATH_SEPARATOR.key(), ":");
System.setProperty(
JAVA_CLASS_PATH.key(),
Joiner.on(":")
.join(
"relative/path/to/some.jar",
"/absolute/path/to/some.jar",
"relative/path/to/class/root",
"/absolute/path/to/class/root"));
try {
ImmutableList<URL> urls = ClassPath.Scanner.parseJavaClassPath();

assertThat(urls.get(0).getProtocol()).isEqualTo("file");
assertThat(urls.get(0).getAuthority()).isNull();
assertThat(urls.get(0).getPath()).endsWith("/relative/path/to/some.jar");

assertThat(urls.get(1)).isEqualTo(new URL("file:///absolute/path/to/some.jar"));

assertThat(urls.get(2).getProtocol()).isEqualTo("file");
assertThat(urls.get(2).getAuthority()).isNull();
assertThat(urls.get(2).getPath()).endsWith("/relative/path/to/class/root");

assertThat(urls.get(3)).isEqualTo(new URL("file:///absolute/path/to/class/root"));

assertThat(urls).hasSize(4);
} finally {
System.setProperty(PATH_SEPARATOR.key(), oldPathSeparator);
System.setProperty(JAVA_CLASS_PATH.key(), oldClassPath);
}
}

private static boolean contentEquals(URL left, URL right) throws IOException {
return Resources.asByteSource(left).contentEquals(Resources.asByteSource(right));
}
Expand Down Expand Up @@ -387,32 +425,37 @@ public void testExistsThrowsSecurityException() throws IOException, URISyntaxExc
}

private void doTestExistsThrowsSecurityException() throws IOException, URISyntaxException {
URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
URL[] urls = myLoader.getURLs();
ImmutableList.Builder<File> filesBuilder = ImmutableList.builder();
for (URL url : urls) {
File file = null;
// In Java 9, Logger may read the TZ database. Only disallow reading the class path URLs.
final PermissionCollection readClassPathFiles =
new FilePermission("", "read").newPermissionCollection();
for (URL url : ClassPath.Scanner.parseJavaClassPath()) {
if (url.getProtocol().equalsIgnoreCase("file")) {
filesBuilder.add(new File(url.toURI()));
file = new File(url.toURI());
readClassPathFiles.add(new FilePermission(file.getAbsolutePath(), "read"));
}
}
ImmutableList<File> files = filesBuilder.build();
assertThat(files).isNotEmpty();
SecurityManager disallowFilesSecurityManager = new SecurityManager() {
@Override
public void checkPermission(Permission p) {
if (p instanceof FilePermission) {
throw new SecurityException("Disallowed: " + p);
}
}
};
assertThat(file).isNotNull();
SecurityManager disallowFilesSecurityManager =
new SecurityManager() {
@Override
public void checkPermission(Permission p) {
if (readClassPathFiles.implies(p)) {
throw new SecurityException("Disallowed: " + p);
}
}
};
System.setSecurityManager(disallowFilesSecurityManager);
try {
files.get(0).exists();
file.exists();
fail("Did not get expected SecurityException");
} catch (SecurityException expected) {
}
ClassPath classPath = ClassPath.from(myLoader);
assertThat(classPath.getResources()).isEmpty();
ClassPath classPath = ClassPath.from(getClass().getClassLoader());
// ClassPath may contain resources from the boot class loader; just not from the class path.
for (ResourceInfo resource : classPath.getResources()) {
assertThat(resource.getResourceName()).doesNotContain("com/google/common/reflect/");
}
}

private static ClassPath.ClassInfo findClass(
Expand Down
69 changes: 56 additions & 13 deletions android/guava/src/com/google/common/reflect/ClassPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static java.util.logging.Level.WARNING;

import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
Expand Down Expand Up @@ -55,8 +59,13 @@
/**
* Scans the source of a {@link ClassLoader} and finds all loadable classes and resources.
*
* <p><b>Warning:</b> Currently only {@link URLClassLoader} and only {@code file://} urls are
* supported.
* <p><b>Warning:</b> Current limitations:
*
* <ul>
* <li>Looks only for files and JARs in URLs available from {@link URLClassLoader} instances or
* the {@linkplain ClassLoader#getSystemClassLoader() system class loader}.
* <li>Only understands {@code file:} URLs.
* </ul>
*
* <p>In the case of directory classloaders, symlinks are supported but cycles are not traversed.
* This guarantees discovery of each <em>unique</em> loadable resource. However, not all possible
Expand Down Expand Up @@ -91,10 +100,16 @@ private ClassPath(ImmutableSet<ResourceInfo> resources) {

/**
* Returns a {@code ClassPath} representing all classes and resources loadable from {@code
* classloader} and its parent class loaders.
* classloader} and its ancestor class loaders.
*
* <p><b>Warning:</b> {@code ClassPath} can find classes and resources only from:
*
* <p><b>Warning:</b> Currently only {@link URLClassLoader} and only {@code file://} urls are
* supported.
* <ul>
* <li>{@link URLClassLoader} instances' {@code file:} URLs
* <li>the {@linkplain ClassLoader#getSystemClassLoader() system class loader}. To search the
* system class loader even when it is not a {@link URLClassLoader} (as in Java 9), {@code
* ClassPath} searches the files from the {@code java.class.path} system property.
* </ul>
*
* @throws IOException if the attempt to read class path resources (jar files or directories)
* failed.
Expand Down Expand Up @@ -432,20 +447,48 @@ static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classload
if (parent != null) {
entries.putAll(getClassPathEntries(parent));
}
if (classloader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) classloader;
for (URL entry : urlClassLoader.getURLs()) {
if (entry.getProtocol().equals("file")) {
File file = toFile(entry);
if (!entries.containsKey(file)) {
entries.put(file, classloader);
}
for (URL url : getClassLoaderUrls(classloader)) {
if (url.getProtocol().equals("file")) {
File file = toFile(url);
if (!entries.containsKey(file)) {
entries.put(file, classloader);
}
}
}
return ImmutableMap.copyOf(entries);
}

private static ImmutableList<URL> getClassLoaderUrls(ClassLoader classloader) {
if (classloader instanceof URLClassLoader) {
return ImmutableList.copyOf(((URLClassLoader) classloader).getURLs());
}
if (classloader.equals(ClassLoader.getSystemClassLoader())) {
return parseJavaClassPath();
}
return ImmutableList.of();
}

/**
* Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain
* System#getProperty system property}.
*/
@VisibleForTesting // TODO(b/65488446): Make this a public API.
static ImmutableList<URL> parseJavaClassPath() {
ImmutableList.Builder<URL> urls = ImmutableList.builder();
for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) {
try {
try {
urls.add(new File(entry).toURI().toURL());
} catch (SecurityException e) { // File.toURI checks to see if the file is a directory
urls.add(new URL("file", null, new File(entry).getAbsolutePath()));
}
} catch (MalformedURLException e) {
logger.log(WARNING, "malformed classpath entry: " + entry, e);
}
}
return urls.build();
}

/**
* Returns the absolute uri of the Class-Path entry value as specified in
* <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/jar/jar.html#Main_Attributes">
Expand Down
79 changes: 61 additions & 18 deletions guava-tests/test/com/google/common/reflect/ClassPathTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package com.google.common.reflect;

import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.io.MoreFiles.deleteRecursively;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.file.Files.createDirectory;
Expand All @@ -25,6 +27,7 @@
import static java.nio.file.Files.createTempDirectory;
import static java.util.logging.Level.WARNING;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Closer;
Expand All @@ -46,6 +49,7 @@
import java.net.URL;
import java.net.URLClassLoader;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
Expand Down Expand Up @@ -425,6 +429,40 @@ public void testGetPackageName() {

// Test that ResourceInfo.urls() returns identical content to ClassLoader.getResources()

public void testGetClassPathUrls() throws Exception {
String oldPathSeparator = PATH_SEPARATOR.value();
String oldClassPath = JAVA_CLASS_PATH.value();
System.setProperty(PATH_SEPARATOR.key(), ":");
System.setProperty(
JAVA_CLASS_PATH.key(),
Joiner.on(":")
.join(
"relative/path/to/some.jar",
"/absolute/path/to/some.jar",
"relative/path/to/class/root",
"/absolute/path/to/class/root"));
try {
ImmutableList<URL> urls = ClassPath.Scanner.parseJavaClassPath();

assertThat(urls.get(0).getProtocol()).isEqualTo("file");
assertThat(urls.get(0).getAuthority()).isNull();
assertThat(urls.get(0).getPath()).endsWith("/relative/path/to/some.jar");

assertThat(urls.get(1)).isEqualTo(new URL("file:///absolute/path/to/some.jar"));

assertThat(urls.get(2).getProtocol()).isEqualTo("file");
assertThat(urls.get(2).getAuthority()).isNull();
assertThat(urls.get(2).getPath()).endsWith("/relative/path/to/class/root");

assertThat(urls.get(3)).isEqualTo(new URL("file:///absolute/path/to/class/root"));

assertThat(urls).hasSize(4);
} finally {
System.setProperty(PATH_SEPARATOR.key(), oldPathSeparator);
System.setProperty(JAVA_CLASS_PATH.key(), oldClassPath);
}
}

private static boolean contentEquals(URL left, URL right) throws IOException {
return Resources.asByteSource(left).contentEquals(Resources.asByteSource(right));
}
Expand Down Expand Up @@ -453,32 +491,37 @@ public void testExistsThrowsSecurityException() throws IOException, URISyntaxExc
}

private void doTestExistsThrowsSecurityException() throws IOException, URISyntaxException {
URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
URL[] urls = myLoader.getURLs();
ImmutableList.Builder<File> filesBuilder = ImmutableList.builder();
for (URL url : urls) {
File file = null;
// In Java 9, Logger may read the TZ database. Only disallow reading the class path URLs.
final PermissionCollection readClassPathFiles =
new FilePermission("", "read").newPermissionCollection();
for (URL url : ClassPath.Scanner.parseJavaClassPath()) {
if (url.getProtocol().equalsIgnoreCase("file")) {
filesBuilder.add(new File(url.toURI()));
file = new File(url.toURI());
readClassPathFiles.add(new FilePermission(file.getAbsolutePath(), "read"));
}
}
ImmutableList<File> files = filesBuilder.build();
assertThat(files).isNotEmpty();
SecurityManager disallowFilesSecurityManager = new SecurityManager() {
@Override
public void checkPermission(Permission p) {
if (p instanceof FilePermission) {
throw new SecurityException("Disallowed: " + p);
}
}
};
assertThat(file).isNotNull();
SecurityManager disallowFilesSecurityManager =
new SecurityManager() {
@Override
public void checkPermission(Permission p) {
if (readClassPathFiles.implies(p)) {
throw new SecurityException("Disallowed: " + p);
}
}
};
System.setSecurityManager(disallowFilesSecurityManager);
try {
files.get(0).exists();
file.exists();
fail("Did not get expected SecurityException");
} catch (SecurityException expected) {
}
ClassPath classPath = ClassPath.from(myLoader);
assertThat(classPath.getResources()).isEmpty();
ClassPath classPath = ClassPath.from(getClass().getClassLoader());
// ClassPath may contain resources from the boot class loader; just not from the class path.
for (ResourceInfo resource : classPath.getResources()) {
assertThat(resource.getResourceName()).doesNotContain("com/google/common/reflect/");
}
}

private static ClassPath.ClassInfo findClass(
Expand Down
Loading

0 comments on commit 63898e2

Please sign in to comment.