8345153: Clean up SecurityManager references from jdk.compiler module

Reviewed-by: alanb, jlahoda, darcy
This commit is contained in:
Jaikiran Pai 2024-12-05 01:24:29 +00:00
parent 7a0cc79668
commit 63d095169a
8 changed files with 42 additions and 316 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -54,14 +54,12 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipException;
@ -327,7 +325,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
} else {
try {
fs = new ArchiveContainer(path);
} catch (ProviderNotFoundException | SecurityException ex) {
} catch (ProviderNotFoundException ex) {
throw new IOException(ex);
}
}
@ -556,7 +554,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
private final FileSystem fileSystem;
private final Map<RelativeDirectory, Path> packages;
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException {
this.archivePath = archivePath;
if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1760,12 +1760,6 @@ public class ClassWriter extends ClassFile {
}
long getLastModified(FileObject filename) {
long mod = 0;
try {
mod = filename.getLastModified();
} catch (SecurityException e) {
throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
}
return mod;
return filename.getLastModified();
}
}

View File

@ -39,7 +39,6 @@ import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import jdk.internal.misc.MethodFinder;
import jdk.internal.misc.VM;
@ -74,7 +73,6 @@ public final class SourceLauncher {
public static void main(String... args) throws Throwable {
try {
new SourceLauncher(System.err)
.checkSecurityManager()
.run(VM.getRuntimeArguments(), args);
} catch (Fault f) {
System.err.println(f.getMessage());
@ -108,19 +106,6 @@ public final class SourceLauncher {
this.out = out;
}
/**
* Checks if a security manager is present and throws an exception if so.
* @return this object
* @throws Fault if a security manager is present
*/
@SuppressWarnings("removal")
private SourceLauncher checkSecurityManager() throws Fault {
if (System.getSecurityManager() != null) {
throw new Fault(Errors.SecurityManager);
}
return this;
}
/**
* Compiles a source file, and executes the main method it contains.
*

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -30,9 +30,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Predicate;
@ -62,7 +59,6 @@ import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.Modules;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.model.JavacElements;
@ -167,7 +163,6 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
private ClassLoader processorClassLoader;
private ServiceLoader<Processor> serviceLoader;
private SecurityException processorLoaderException;
private final JavaFileManager fileManager;
@ -268,28 +263,24 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
}
private void initProcessorLoader() {
try {
if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) {
try {
serviceLoader = fileManager.getServiceLoader(ANNOTATION_PROCESSOR_MODULE_PATH, Processor.class);
} catch (IOException e) {
throw new Abort(e);
}
} else {
// If processorpath is not explicitly set, use the classpath.
processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
: fileManager.getClassLoader(CLASS_PATH);
if (options.isSet("accessInternalAPI"))
ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule());
if (processorClassLoader != null && processorClassLoader instanceof Closeable closeable) {
compiler.closeables = compiler.closeables.prepend(closeable);
}
if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) {
try {
serviceLoader = fileManager.getServiceLoader(ANNOTATION_PROCESSOR_MODULE_PATH, Processor.class);
} catch (IOException e) {
throw new Abort(e);
}
} else {
// If processorpath is not explicitly set, use the classpath.
processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
: fileManager.getClassLoader(CLASS_PATH);
if (options.isSet("accessInternalAPI"))
ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule());
if (processorClassLoader != null && processorClassLoader instanceof Closeable closeable) {
compiler.closeables = compiler.closeables.prepend(closeable);
}
} catch (SecurityException e) {
processorLoaderException = e;
}
}
@ -305,35 +296,24 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
} else if (processors != null) {
processorIterator = processors.iterator();
} else {
if (processorLoaderException == null) {
/*
* If the "-processor" option is used, search the appropriate
* path for the named class. Otherwise, use a service
* provider mechanism to create the processor iterator.
*
* Note: if an explicit processor path is not set,
* only the class path and _not_ the module path are
* searched for processors.
*/
String processorNames = options.get(Option.PROCESSOR);
if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) {
processorIterator = (processorNames == null) ?
new ServiceIterator(serviceLoader, log) :
new NameServiceIterator(serviceLoader, log, processorNames);
} else if (processorNames != null) {
processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
} else {
processorIterator = new ServiceIterator(processorClassLoader, log);
}
/*
* If the "-processor" option is used, search the appropriate
* path for the named class. Otherwise, use a service
* provider mechanism to create the processor iterator.
*
* Note: if an explicit processor path is not set,
* only the class path and _not_ the module path are
* searched for processors.
*/
String processorNames = options.get(Option.PROCESSOR);
if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) {
processorIterator = (processorNames == null) ?
new ServiceIterator(serviceLoader, log) :
new NameServiceIterator(serviceLoader, log, processorNames);
} else if (processorNames != null) {
processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
} else {
/*
* A security exception will occur if we can't create a classloader.
* Ignore the exception if, with hindsight, we didn't need it anyway
* (i.e. no processor was specified either explicitly, or implicitly,
* in service configuration file.) Otherwise, we cannot continue.
*/
processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader",
processorLoaderException);
processorIterator = new ServiceIterator(processorClassLoader, log);
}
}
PlatformDescription platformProvider = context.get(PlatformDescription.class);
@ -363,47 +343,6 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
}
}
/**
* Returns an empty processor iterator if no processors are on the
* relevant path, otherwise if processors are present, logs an
* error. Called when a service loader is unavailable for some
* reason, either because a service loader class cannot be found
* or because a security policy prevents class loaders from being
* created.
*
* @param key The resource key to use to log an error message
* @param e If non-null, pass this exception to Abort
*/
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
if (fileManager instanceof JavacFileManager standardFileManager) {
Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH)
: standardFileManager.getLocationAsPaths(CLASS_PATH);
if (needClassLoader(options.get(Option.PROCESSOR), workingPath) )
handleException(key, e);
} else {
handleException(key, e);
}
return Collections.emptyIterator();
}
/**
* Handle a security exception thrown during initializing the
* Processor iterator.
*/
private void handleException(String key, Exception e) {
if (e != null) {
log.error(key, e.getLocalizedMessage());
throw new Abort(e);
} else {
log.error(key);
throw new Abort();
}
}
/**
* Use a service loader appropriate for the platform to provide an
* iterator over annotations processors; fails if a loader is
@ -417,13 +356,8 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
ServiceIterator(ClassLoader classLoader, Log log) {
this.log = log;
try {
try {
loader = ServiceLoader.load(Processor.class, classLoader);
this.iterator = loader.iterator();
} catch (Exception e) {
// Fail softly if a loader is not actually needed.
this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
}
loader = ServiceLoader.load(Processor.class, classLoader);
this.iterator = loader.iterator();
} catch (Throwable t) {
log.error(Errors.ProcServiceProblem);
throw new Abort(t);
@ -1548,32 +1482,6 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
return fo.isNameCompatible("module-info", kind);
}
/*
* Called retroactively to determine if a class loader was required,
* after we have failed to create one.
*/
private boolean needClassLoader(String procNames, Iterable<? extends Path> workingpath) {
if (procNames != null)
return true;
URL[] urls = new URL[1];
for(Path pathElement : workingpath) {
try {
urls[0] = pathElement.toUri().toURL();
if (ServiceProxy.hasService(Processor.class, urls))
return true;
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
catch (ServiceProxy.ServiceConfigurationError e) {
log.error(Errors.ProcBadConfigFile(e.getLocalizedMessage()));
return true;
}
}
return false;
}
class ImplicitCompleter implements Completer {
private final JCCompilationUnit topLevel;

View File

@ -1,152 +0,0 @@
/*
* Copyright (c) 2006, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.processing;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Utility class to determine if a service can be found on the
* path that might be used to create a class loader.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
*/
// based on sun.misc.Service
class ServiceProxy {
static class ServiceConfigurationError extends Error {
static final long serialVersionUID = 7732091036771098303L;
ServiceConfigurationError(String msg) {
super(msg);
}
}
private static final String prefix = "META-INF/services/";
private static void fail(Class<?> service, String msg)
throws ServiceConfigurationError {
throw new ServiceConfigurationError(service.getName() + ": " + msg);
}
private static void fail(Class<?> service, URL u, int line, String msg)
throws ServiceConfigurationError {
fail(service, u + ":" + line + ": " + msg);
}
/**
* Parse the content of the given URL as a provider-configuration file.
*
* @param service
* The service class for which providers are being sought;
* used to construct error detail strings
*
* @param u
* The URL naming the configuration file to be parsed
*
* @return true if the name of a service is found
*
* @throws ServiceConfigurationError
* If an I/O error occurs while reading from the given URL, or
* if a configuration-file format error is detected
*/
private static boolean parse(Class<?> service, URL u) throws ServiceConfigurationError {
InputStream in = null;
BufferedReader r = null;
try {
in = u.openStream();
r = new BufferedReader(new InputStreamReader(in, UTF_8));
int lc = 1;
String ln;
while ((ln = r.readLine()) != null) {
int ci = ln.indexOf('#');
if (ci >= 0) ln = ln.substring(0, ci);
ln = ln.trim();
int n = ln.length();
if (n != 0) {
if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
fail(service, u, lc, "Illegal configuration-file syntax");
int cp = ln.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
fail(service, u, lc, "Illegal provider-class name: " + ln);
for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
cp = ln.codePointAt(i);
if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
fail(service, u, lc, "Illegal provider-class name: " + ln);
}
return true;
}
}
} catch (FileNotFoundException x) {
return false;
} catch (IOException x) {
fail(service, ": " + x);
} finally {
try {
if (r != null) r.close();
} catch (IOException y) {
fail(service, ": " + y);
}
try {
if (in != null) in.close();
} catch (IOException y) {
fail(service, ": " + y);
}
}
return false;
}
/**
* Return true if a description for at least one service is found in the
* service configuration files in the given URLs.
*/
public static boolean hasService(Class<?> service, URL[] urls)
throws ServiceConfigurationError {
for (URL url: urls) {
try {
String fullName = prefix + service.getName();
@SuppressWarnings("deprecation")
URL u = new URL(url, fullName);
boolean found = parse(service, u);
if (found)
return true;
} catch (MalformedURLException e) {
// should not happen; ignore it if it does
}
}
return false;
}
}

View File

@ -1179,9 +1179,6 @@ compiler.misc.user.selected.completion.failure=\
compiler.err.proc.no.explicit.annotation.processing.requested=\
Class names, ''{0}'', are only accepted if annotation processing is explicitly requested
compiler.err.proc.no.service=\
A ServiceLoader was not usable and is required for annotation processing.
# 0: string, 1: string
compiler.err.proc.processor.bad.option.name=\
Bad option name ''{0}'' provided by processor ''{1}''

View File

@ -84,9 +84,6 @@ launcher.error=\
launcher.err.no.args=\
no path for source file
launcher.err.security.manager=\
cannot use source-code launcher with a security manager enabled
# 0: string
launcher.err.invalid.filename=\
invalid path for source file: {0}

View File

@ -34,7 +34,6 @@ compiler.err.proc.bad.config.file # JavacProcessingEnviron
compiler.err.proc.cant.access # completion failure
compiler.err.proc.cant.access.1 # completion failure, no stack trace
compiler.err.proc.cant.create.loader # security exception from service loader
compiler.err.proc.no.service # JavacProcessingEnvironment: no service loader available
compiler.err.proc.processor.bad.option.name # cannot happen? masked by javac.err.invalid.A.key
compiler.err.proc.service.problem # JavacProcessingEnvironment: catch Throwable from service loader
compiler.err.proc.cant.load.class # JavacProcessingEnvironment: cant load the class/jar file