You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by ma...@apache.org on 2023/11/14 06:19:03 UTC
(logging-log4j2) branch the-great-deletion updated (68a57ce0de -> 3118f47997)
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a change to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
from 68a57ce0de Use explicit Configuration in test
new 5237149e27 Access current thread group directly
new d0f7e533a3 Update changelog entry
new 295d5e460a Remove tests related to SecurityManager
new e15359668c Access system properties directly
new 79d21aee3a Remove SecurityManager checks from LoaderUtil
new 6e00230de9 Use system properties directly
new 3118f47997 Remove ServiceRegistry in favor of utility function
The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../log4j/test/junit/SecurityManagerTestRule.java | 93 -----------
...EnvironmentPropertySourceSecurityManagerIT.java | 83 ----------
...ropertyFilePropertySourceSecurityManagerIT.java | 89 ----------
.../logging/log4j/util/ServiceLoaderUtilTest.java | 27 +--
.../logging/log4j/util/StackLocatorTestIT.java | 64 -------
.../logging/log4j/util/StackLocatorUtilTest.java | 11 +-
...mPropertiesPropertySourceSecurityManagerIT.java | 92 -----------
.../logging/log4j/message/ThreadDumpMessage.java | 16 +-
.../apache/logging/log4j/spi/LoggingSystem.java | 9 +-
.../org/apache/logging/log4j/util/LoaderUtil.java | 184 +++++++--------------
.../util/PrivateSecurityManagerStackTraceUtil.java | 80 ---------
.../apache/logging/log4j/util/PropertiesUtil.java | 41 ++---
.../logging/log4j/util/ServiceLoaderUtil.java | 142 ++--------------
.../apache/logging/log4j/util/ServiceRegistry.java | 81 ---------
.../apache/logging/log4j/util/StackLocator.java | 4 -
.../org/apache/logging/log4j/util/Strings.java | 3 +-
.../log4j/util/SystemPropertiesPropertySource.java | 37 +----
.../log4j/core/impl/ThrowableProxyTest.java | 78 ---------
.../log4j/core/config/AbstractConfiguration.java | 11 +-
.../log4j/core/impl/ThreadContextDataInjector.java | 22 +--
.../log4j/core/util/Log4jThreadFactory.java | 4 +-
.../logging/log4j/core/util/WatchManager.java | 12 +-
.../logging/log4j/smtp/appender/SmtpManager.java | 3 +-
.../log4j/perf/jmh/ReflectionBenchmark.java | 13 --
.../org/apache/logging/log4j/plugins/di/DI.java | 8 +-
.../logging/log4j/smtp/appender/SmtpManager.java | 3 +-
.../.3.x.x/remove_legacy_osgi_support.xml | 23 +--
...bom.xml => remove_security_manager_support.xml} | 8 +-
28 files changed, 156 insertions(+), 1085 deletions(-)
delete mode 100644 log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/SecurityManagerTestRule.java
delete mode 100644 log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceSecurityManagerIT.java
delete mode 100644 log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertyFilePropertySourceSecurityManagerIT.java
delete mode 100644 log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java
delete mode 100644 log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceSecurityManagerIT.java
delete mode 100644 log4j-api/src/main/java/org/apache/logging/log4j/util/PrivateSecurityManagerStackTraceUtil.java
delete mode 100644 log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceRegistry.java
copy src/changelog/.3.x.x/{update_io_netty_netty_bom.xml => remove_security_manager_support.xml} (58%)
(logging-log4j2) 07/07: Remove ServiceRegistry in favor of utility function
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 3118f4799728d6b2b987a1858ac80b4c8579fc38
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Tue Nov 14 00:06:39 2023 -0600
Remove ServiceRegistry in favor of utility function
Without a need for tracking externally registered services, everywhere that was looking up services can do so more directly now.
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../logging/log4j/util/ServiceLoaderUtilTest.java | 27 ++--
.../logging/log4j/message/ThreadDumpMessage.java | 16 +--
.../apache/logging/log4j/spi/LoggingSystem.java | 9 +-
.../apache/logging/log4j/util/PropertiesUtil.java | 41 ++----
.../logging/log4j/util/ServiceLoaderUtil.java | 142 +++------------------
.../apache/logging/log4j/util/ServiceRegistry.java | 81 ------------
.../log4j/core/config/AbstractConfiguration.java | 11 +-
.../log4j/core/impl/ThreadContextDataInjector.java | 22 ++--
.../logging/log4j/core/util/WatchManager.java | 12 +-
.../org/apache/logging/log4j/plugins/di/DI.java | 8 +-
10 files changed, 76 insertions(+), 293 deletions(-)
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java
index e6d9d704bd..b82fb953b2 100644
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java
+++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java
@@ -16,10 +16,10 @@
*/
package org.apache.logging.log4j.util;
-import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
import java.util.stream.Collectors;
import org.apache.logging.log4j.Level;
@@ -32,29 +32,30 @@ import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
public class ServiceLoaderUtilTest {
@Test
public void testServiceResolution() {
- final List<Object> services = new ArrayList<>();
- assertDoesNotThrow(() -> ServiceLoaderUtil.loadServices(BetterService.class, MethodHandles.lookup(), false)
- .forEach(services::add));
- assertThat(services).hasSize(1);
- services.clear();
- assertDoesNotThrow(() -> ServiceLoaderUtil.loadServices(PropertySource.class, MethodHandles.lookup(), false)
- .forEach(services::add));
- assertThat(services).hasSize(3);
- }
+ final List<Object> services = new ArrayList<>();
+ final ClassLoader classLoader = getClass().getClassLoader();
+ assertDoesNotThrow(() -> ServiceLoaderUtil.safeStream(ServiceLoader.load(BetterService.class, classLoader))
+ .forEach(services::add));
+ assertThat(services).hasSize(1);
+ services.clear();
+ assertDoesNotThrow(() -> ServiceLoaderUtil.safeStream(ServiceLoader.load(PropertySource.class, classLoader))
+ .forEach(services::add));
+ assertThat(services).hasSize(3);
+ }
@Test
@UsingStatusListener
public void testBrokenServiceFile(final ListStatusListener listener) {
final List<Service> services = new ArrayList<>();
- assertDoesNotThrow(() -> ServiceLoaderUtil.loadServices(Service.class, MethodHandles.lookup(), false)
+ final ClassLoader classLoader = getClass().getClassLoader();
+ assertDoesNotThrow(() -> ServiceLoaderUtil.safeStream(ServiceLoader.load(Service.class, classLoader))
.forEach(services::add));
- assertEquals(2, services.size());
+ assertThat(services).hasSize(2);
// A warning for each broken service
final List<Throwable> errors = listener.findStatusData(Level.WARN).map(StatusData::getThrowable)
.collect(Collectors.toList());
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/ThreadDumpMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/ThreadDumpMessage.java
index cbfa241b5b..585728251f 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/message/ThreadDumpMessage.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/ThreadDumpMessage.java
@@ -16,16 +16,15 @@
*/
package org.apache.logging.log4j.message;
-import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.Map;
+import java.util.ServiceLoader;
import aQute.bnd.annotation.Cardinality;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceConsumer;
import org.apache.logging.log4j.message.ThreadDumpMessage.ThreadInfoFactory;
import org.apache.logging.log4j.util.Lazy;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
import org.apache.logging.log4j.util.StringBuilderFormattable;
import org.apache.logging.log4j.util.Strings;
@@ -33,13 +32,12 @@ import org.apache.logging.log4j.util.Strings;
* Captures information about all running Threads.
*/
@AsynchronouslyFormattable
-@ServiceConsumer(value = ThreadInfoFactory.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.SINGLE)
+@ServiceConsumer(value = ThreadInfoFactory.class, cardinality = Cardinality.SINGLE)
public class ThreadDumpMessage implements Message, StringBuilderFormattable {
- private static final Lazy<ThreadInfoFactory> FACTORY = Lazy.lazy(() -> {
- final var services = ServiceRegistry.getInstance()
- .getServices(ThreadInfoFactory.class, MethodHandles.lookup(), null);
- return services.isEmpty() ? new BasicThreadInfoFactory() : services.get(0);
- });
+ private static final Lazy<ThreadInfoFactory> FACTORY = Lazy.lazy(() ->
+ ServiceLoaderUtil.safeStream(ServiceLoader.load(ThreadInfoFactory.class, ThreadInfoFactory.class.getClassLoader()))
+ .findFirst()
+ .orElseGet(BasicThreadInfoFactory::new));
private final Map<ThreadInformation, StackTraceElement[]> threads;
private final String title;
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggingSystem.java b/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggingSystem.java
index 4691a74c48..55dbf3ecc3 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggingSystem.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggingSystem.java
@@ -18,13 +18,13 @@ package org.apache.logging.log4j.spi;
import java.io.IOException;
import java.io.InputStream;
-import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
+import java.util.ServiceLoader;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Supplier;
@@ -45,7 +45,7 @@ import org.apache.logging.log4j.util.LoaderUtil;
import org.apache.logging.log4j.util.LowLevelLogUtil;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.PropertyEnvironment;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
import static org.apache.logging.log4j.spi.LoggingSystemProperty.LOGGER_FLOW_MESSAGE_FACTORY_CLASS;
import static org.apache.logging.log4j.spi.LoggingSystemProperty.LOGGER_MESSAGE_FACTORY_CLASS;
@@ -187,8 +187,9 @@ public class LoggingSystem {
}
private static List<Provider> loadDefaultProviders() {
- return ServiceRegistry.getInstance()
- .getServices(Provider.class, MethodHandles.lookup(), provider -> validVersion(provider.getVersions()));
+ return ServiceLoaderUtil.safeStream(ServiceLoader.load(Provider.class, Provider.class.getClassLoader()))
+ .filter(provider -> validVersion(provider.getVersions()))
+ .collect(Collectors.toList());
}
private static List<Provider> loadLegacyProviders() {
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
index d656f89b5d..86a7a34c7c 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
@@ -20,7 +20,6 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -38,9 +37,9 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Collectors;
import aQute.bnd.annotation.Cardinality;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceConsumer;
import org.apache.logging.log4j.internal.CopyOnWriteNavigableSet;
@@ -58,7 +57,7 @@ import org.apache.logging.log4j.internal.CopyOnWriteNavigableSet;
* @see PropertySource
*/
@InternalApi
-@ServiceConsumer(value = PropertySource.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE)
+@ServiceConsumer(value = PropertySource.class, cardinality = Cardinality.MULTIPLE)
public class PropertiesUtil implements PropertyEnvironment {
private static final String LOG4J_NAMESPACE = "component";
@@ -66,6 +65,9 @@ public class PropertiesUtil implements PropertyEnvironment {
private static final String DELIMITER = ".";
private static final String META_INF = "META-INF/";
private static final String LOG4J_SYSTEM_PROPERTIES_FILE_NAME = "log4j2.system.properties";
+ private static final Lazy<List<PropertySource>> SERVICE_PROPERTY_SOURCES = Lazy.lazy(() ->
+ ServiceLoaderUtil.safeStream(ServiceLoader.load(PropertySource.class, PropertiesUtil.class.getClassLoader()))
+ .collect(Collectors.toList()));
private static final Lazy<PropertiesUtil> COMPONENT_PROPERTIES = Lazy.lazy(PropertiesUtil::new);
private static final ThreadLocal<PropertiesUtil> environments = new InheritableThreadLocal<>();
@@ -234,21 +236,6 @@ public class PropertiesUtil implements PropertyEnvironment {
return environment.getStringProperty(name);
}
- /**
- * Return the system properties or an empty Properties object if an error occurs.
- *
- * @return The system properties.
- */
- public static Properties getSystemProperties() {
- try {
- return new Properties(System.getProperties());
- } catch (final SecurityException ex) {
- LowLevelLogUtil.logException("Unable to access system properties.", ex);
- // Sandboxed - can't read System Properties
- return new Properties();
- }
- }
-
/**
* Reloads all properties. This is primarily useful for unit tests.
*
@@ -438,20 +425,14 @@ public class PropertiesUtil implements PropertyEnvironment {
private final String contextName;
private Environment(final String contextName, final List<PropertySource> propertySources) {
- try {
- final Properties sysProps = PropertyFilePropertySource.loadPropertiesFile(LOG4J_SYSTEM_PROPERTIES_FILE_NAME);
- for (String key : sysProps.stringPropertyNames()) {
- if (System.getProperty(key) == null) {
- System.setProperty(key, sysProps.getProperty(key));
- }
- };
- } catch (final SecurityException ex) {
- // Access to System Properties is restricted so just skip it.
+ final Properties sysProps = PropertyFilePropertySource.loadPropertiesFile(LOG4J_SYSTEM_PROPERTIES_FILE_NAME);
+ for (String key : sysProps.stringPropertyNames()) {
+ if (System.getProperty(key) == null) {
+ System.setProperty(key, sysProps.getProperty(key));
+ }
}
sources.addAll(propertySources);
- final ServiceRegistry registry = ServiceRegistry.getInstance();
- // Does not log errors using StatusLogger, which depends on PropertiesUtil being initialized.
- sources.addAll(registry.getServices(PropertySource.class, MethodHandles.lookup(), null, /*verbose=*/false));
+ sources.addAll(SERVICE_PROPERTY_SOURCES.get());
this.contextName = contextName;
reload();
}
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceLoaderUtil.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceLoaderUtil.java
index 95c9f3cef8..084555f36d 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceLoaderUtil.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceLoaderUtil.java
@@ -16,29 +16,18 @@
*/
package org.apache.logging.log4j.util;
-import java.lang.invoke.CallSite;
-import java.lang.invoke.LambdaMetafactory;
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles.Lookup;
-import java.lang.invoke.MethodType;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
-import java.util.Spliterator;
+import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.status.StatusLogger;
-
/**
- * This class should be considered internal.
+ * Handles {@link ServiceLoader} lookups with better error handling.
*/
@InternalApi
public final class ServiceLoaderUtil {
@@ -48,102 +37,21 @@ public final class ServiceLoaderUtil {
private ServiceLoaderUtil() {
}
- /**
- * Retrieves the available services from the caller's classloader.
- *
- * Broken services will be ignored.
- *
- * @param <T> The service type.
- * @param serviceType The class of the service.
- * @param lookup The calling class data.
- * @return A stream of service instances.
- */
- public static <T> Stream<T> loadServices(final Class<T> serviceType, final Lookup lookup) {
- return loadServices(serviceType, lookup, false);
- }
-
- /**
- * Retrieves the available services from the caller's classloader and possibly
- * the thread context classloader.
- *
- * Broken services will be ignored.
- *
- * @param <T> The service type.
- * @param serviceType The class of the service.
- * @param lookup The calling class data.
- * @param useTccl If true the thread context classloader will also be used.
- * @return A stream of service instances.
- */
- public static <T> Stream<T> loadServices(final Class<T> serviceType, final Lookup lookup, final boolean useTccl) {
- return loadServices(serviceType, lookup, useTccl, true);
- }
-
- static <T> Stream<T> loadServices(final Class<T> serviceType, final Lookup lookup, final boolean useTccl,
- final boolean verbose) {
- final ClassLoader classLoader = lookup.lookupClass().getClassLoader();
- Stream<T> services = loadClassloaderServices(serviceType, lookup, classLoader, verbose);
- if (useTccl) {
- final ClassLoader contextClassLoader = LoaderUtil.getThreadContextClassLoader();
- if (contextClassLoader != classLoader) {
- services = Stream.concat(services,
- loadClassloaderServices(serviceType, lookup, contextClassLoader, verbose));
- }
- }
+ public static <S> Stream<S> safeStream(final ServiceLoader<S> serviceLoader) {
final Set<Class<?>> classes = new HashSet<>();
- // only the first occurrence of a class
- return services.filter(service -> classes.add(service.getClass()));
- }
-
- static <T> Stream<T> loadClassloaderServices(final Class<T> serviceType, final Lookup lookup,
- final ClassLoader classLoader, final boolean verbose) {
- return StreamSupport.stream(new ServiceLoaderSpliterator<T>(serviceType, lookup, classLoader, verbose), false);
- }
-
- static <T> Iterable<T> callServiceLoader(final Lookup lookup, final Class<T> serviceType, final ClassLoader classLoader,
- final boolean verbose) {
- try {
- // Creates a lambda in the caller's domain that calls `ServiceLoader`
- final MethodHandle loadHandle = lookup.findStatic(ServiceLoader.class, "load",
- MethodType.methodType(ServiceLoader.class, Class.class, ClassLoader.class));
- final CallSite callSite = LambdaMetafactory.metafactory(lookup,
- "run",
- MethodType.methodType(PrivilegedAction.class, Class.class, ClassLoader.class),
- MethodType.methodType(Object.class),
- loadHandle,
- MethodType.methodType(ServiceLoader.class));
- final PrivilegedAction<ServiceLoader<T>> action = (PrivilegedAction<ServiceLoader<T>>) callSite
- .getTarget()//
- .bindTo(serviceType)
- .bindTo(classLoader)
- .invoke();
- final ServiceLoader<T> serviceLoader;
- if (System.getSecurityManager() == null) {
- serviceLoader = action.run();
- } else {
- final MethodHandle privilegedHandle = lookup.findStatic(AccessController.class, "doPrivileged",
- MethodType.methodType(Object.class, PrivilegedAction.class));
- serviceLoader = (ServiceLoader<T>) privilegedHandle.invoke(action);
- }
- return serviceLoader;
- } catch (Throwable e) {
- if (verbose) {
- StatusLogger.getLogger().error("Unable to load services for service {}", serviceType, e);
- }
- }
- return Collections.emptyList();
+ return StreamSupport.stream(new ServiceLoaderSpliterator<>(serviceLoader), false)
+ // only the first occurrence of a class
+ .filter(service -> classes.add(service.getClass()));
}
- private static class ServiceLoaderSpliterator<S> implements Spliterator<S> {
-
+ private static class ServiceLoaderSpliterator<S> extends Spliterators.AbstractSpliterator<S> {
private final Iterator<S> serviceIterator;
- private final Logger logger;
private final String serviceName;
- public ServiceLoaderSpliterator(final Class<S> serviceType, final Lookup lookup, final ClassLoader classLoader,
- final boolean verbose) {
- this.serviceIterator = callServiceLoader(lookup, serviceType, classLoader, verbose).iterator();
- this.logger = verbose ? StatusLogger.getLogger() : null;
- this.serviceName = serviceType.toString();
+ private ServiceLoaderSpliterator(final ServiceLoader<S> serviceLoader) {
+ super(Long.MAX_VALUE, ORDERED);
+ serviceIterator = serviceLoader.iterator();
+ serviceName = serviceLoader.toString();
}
@Override
@@ -155,34 +63,14 @@ public final class ServiceLoaderUtil {
action.accept(serviceIterator.next());
return true;
}
- } catch (ServiceConfigurationError | LinkageError e) {
- if (logger != null) {
- logger.warn("Unable to load service class for service {}", serviceName, e);
- }
- } catch (Throwable e) {
- if (logger != null) {
- logger.warn("Unable to load service class for service {}", serviceName, e);
- }
+ } catch (final ServiceConfigurationError | LinkageError e) {
+ LowLevelLogUtil.logException("Unable to load implementation for " + serviceName, e);
+ } catch (final Throwable e) {
+ LowLevelLogUtil.logException("Unexpected exception while loading implementation for " + serviceName, e);
throw e;
}
}
return false;
}
-
- @Override
- public Spliterator<S> trySplit() {
- return null;
- }
-
- @Override
- public long estimateSize() {
- return Long.MAX_VALUE;
- }
-
- @Override
- public int characteristics() {
- return NONNULL | IMMUTABLE;
- }
-
}
}
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceRegistry.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceRegistry.java
deleted file mode 100644
index b73b5b6f8f..0000000000
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceRegistry.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.lang.invoke.MethodHandles.Lookup;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-/**
- * Registry for service instances loaded from {@link ServiceLoader}. This abstracts the differences between using a flat
- * classpath versus a module path.
- *
- * @since 3.0.0
- */
-@InternalApi
-public final class ServiceRegistry {
- private static final Lazy<ServiceRegistry> INSTANCE = Lazy.relaxed(ServiceRegistry::new);
-
-
- /**
- * Returns the singleton ServiceRegistry instance.
- */
- public static ServiceRegistry getInstance() {
- return INSTANCE.get();
- }
-
- private final Map<Class<?>, List<?>> registry = new ConcurrentHashMap<>();
-
- private ServiceRegistry() {
- }
-
- /**
- * Gets service instances loaded from the calling context and any previously registered bundle services. The {@code loaderCallerContext} parameter is
- * provided to ensure the caller can specify which calling function context to
- * load services.
- *
- * @param serviceType service class
- * @param lookup MethodHandle lookup created in same module as caller context
- * to use for loading services
- * @param validator if non-null, used to validate service instances,
- * removing invalid instances from the returned list
- * @param <S> type of service
- * @return loaded service instances
- */
- public <S> List<S> getServices(final Class<S> serviceType, final Lookup lookup, final Predicate<S> validator) {
- return getServices(serviceType, lookup, validator, true);
- }
-
- /**
- * Set 'verbose' to false if the `StatusLogger` is not available yet.
- */
- <S> List<S> getServices(final Class<S> serviceType, final Lookup lookup, final Predicate<S> validator, final boolean verbose) {
- final List<?> existing = registry.get(serviceType);
- if (existing != null) {
- return Cast.cast(existing);
- }
- final List<S> services = ServiceLoaderUtil.loadServices(serviceType, lookup, false, verbose)
- .filter(validator != null ? validator : unused -> true)
- .collect(Collectors.toList());
- final List<S> oldValue = Cast.cast(registry.putIfAbsent(serviceType, services));
- return oldValue != null ? oldValue : services;
- }
-}
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java
index 10feed227d..bb4befedec 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java
@@ -16,7 +16,6 @@
*/
package org.apache.logging.log4j.core.config;
-import java.lang.invoke.MethodHandles;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
@@ -25,6 +24,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -35,7 +35,6 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceConsumer;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
@@ -88,12 +87,12 @@ import org.apache.logging.log4j.util.Lazy;
import org.apache.logging.log4j.util.NameUtil;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.PropertyEnvironment;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
/**
* The base Configuration. Many configuration implementations will extend this class.
*/
-@ServiceConsumer(value = ScriptManagerFactory.class, resolution = Resolution.OPTIONAL)
+@ServiceConsumer(ScriptManagerFactory.class)
public abstract class AbstractConfiguration extends AbstractFilterable implements Configuration {
/**
@@ -291,9 +290,7 @@ public abstract class AbstractConfiguration extends AbstractFilterable implement
private void initializeScriptManager() {
try {
- ServiceRegistry.getInstance()
- .getServices(ScriptManagerFactory.class, MethodHandles.lookup(), null)
- .stream()
+ ServiceLoaderUtil.safeStream(ServiceLoader.load(ScriptManagerFactory.class, AbstractConfiguration.class.getClassLoader()))
.findFirst()
.ifPresent(factory -> setScriptManager(factory.createScriptManager(this, getWatchManager())));
} catch (final LinkageError | Exception e) {
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjector.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjector.java
index db32a6852f..373df99619 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjector.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjector.java
@@ -16,17 +16,16 @@
*/
package org.apache.logging.log4j.core.impl;
-import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentLinkedDeque;
import aQute.bnd.annotation.Cardinality;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceConsumer;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.ContextDataInjector;
@@ -34,7 +33,7 @@ import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.util.ContextDataProvider;
import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap;
import org.apache.logging.log4j.util.ReadOnlyStringMap;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
import org.apache.logging.log4j.util.StringMap;
/**
@@ -52,7 +51,7 @@ import org.apache.logging.log4j.util.StringMap;
* @see ContextDataInjectorFactory
* @since 2.7
*/
-@ServiceConsumer(value = ContextDataProvider.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE)
+@ServiceConsumer(value = ContextDataProvider.class, cardinality = Cardinality.MULTIPLE)
public class ThreadContextDataInjector {
/**
@@ -65,13 +64,14 @@ public class ThreadContextDataInjector {
private static List<ContextDataProvider> getServiceProviders() {
final List<ContextDataProvider> providers = new ArrayList<>();
- final List<ContextDataProvider> services = ServiceRegistry.getInstance()
- .getServices(ContextDataProvider.class, MethodHandles.lookup(), null);
- for (final ContextDataProvider provider : services) {
- if (providers.stream().noneMatch((p) -> p.getClass().isAssignableFrom(provider.getClass()))) {
- providers.add(provider);
- }
- }
+ final ServiceLoader<ContextDataProvider> serviceLoader =
+ ServiceLoader.load(ContextDataProvider.class, ThreadContextDataInjector.class.getClassLoader());
+ ServiceLoaderUtil.safeStream(serviceLoader)
+ .forEachOrdered(provider -> {
+ if (providers.stream().noneMatch((p) -> p.getClass().isAssignableFrom(provider.getClass()))) {
+ providers.add(provider);
+ }
+ });
return Collections.unmodifiableList(providers);
}
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/WatchManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/WatchManager.java
index 9ed1f2dc5a..3e271182c8 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/WatchManager.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/WatchManager.java
@@ -17,21 +17,21 @@
package org.apache.logging.log4j.core.util;
import java.io.File;
-import java.lang.invoke.MethodHandles;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.ServiceLoader;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
import aQute.bnd.annotation.Cardinality;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceConsumer;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.AbstractLifeCycle;
@@ -39,7 +39,7 @@ import org.apache.logging.log4j.core.config.ConfigurationScheduler;
import org.apache.logging.log4j.plugins.Inject;
import org.apache.logging.log4j.plugins.Singleton;
import org.apache.logging.log4j.status.StatusLogger;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
/**
* Manages {@link FileWatcher}s.
@@ -48,7 +48,7 @@ import org.apache.logging.log4j.util.ServiceRegistry;
* @see ConfigurationScheduler
*/
@Singleton
-@ServiceConsumer(value = WatchEventService.class, resolution = Resolution.OPTIONAL, cardinality = Cardinality.MULTIPLE)
+@ServiceConsumer(value = WatchEventService.class, cardinality = Cardinality.MULTIPLE)
public class WatchManager extends AbstractLifeCycle {
private static final class ConfigurationMonitor {
@@ -140,8 +140,8 @@ public class WatchManager extends AbstractLifeCycle {
@Inject
public WatchManager(final ConfigurationScheduler scheduler) {
this.scheduler = Objects.requireNonNull(scheduler, "scheduler");
- eventServiceList = ServiceRegistry.getInstance()
- .getServices(WatchEventService.class, MethodHandles.lookup(), null);
+ eventServiceList = ServiceLoaderUtil.safeStream(ServiceLoader.load(WatchEventService.class, WatchManager.class.getClassLoader()))
+ .collect(Collectors.toList());
}
public void checkFiles() {
diff --git a/log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/di/DI.java b/log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/di/DI.java
index f831f3d262..1a9a538c55 100644
--- a/log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/di/DI.java
+++ b/log4j-plugins/src/main/java/org/apache/logging/log4j/plugins/di/DI.java
@@ -16,12 +16,12 @@
*/
package org.apache.logging.log4j.plugins.di;
-import java.lang.invoke.MethodHandles;
import java.util.Comparator;
+import java.util.ServiceLoader;
import org.apache.logging.log4j.plugins.di.spi.ConfigurableInstanceFactoryPostProcessor;
import org.apache.logging.log4j.plugins.util.OrderedComparator;
-import org.apache.logging.log4j.util.ServiceRegistry;
+import org.apache.logging.log4j.util.ServiceLoaderUtil;
/**
* Factory for {@linkplain InstanceFactory instance factories}.
@@ -75,9 +75,7 @@ public final class DI {
* @param factory the instance factory to initialize
*/
public static void initializeFactory(final ConfigurableInstanceFactory factory) {
- ServiceRegistry.getInstance()
- .getServices(ConfigurableInstanceFactoryPostProcessor.class, MethodHandles.lookup(), null)
- .stream()
+ ServiceLoaderUtil.safeStream(ServiceLoader.load(ConfigurableInstanceFactoryPostProcessor.class, DI.class.getClassLoader()))
.sorted(Comparator.comparing(ConfigurableInstanceFactoryPostProcessor::getClass, OrderedComparator.INSTANCE))
.forEachOrdered(processor -> processor.postProcessFactory(factory));
}
(logging-log4j2) 01/07: Access current thread group directly
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 5237149e270ac106e3ae1f58f3acac6f67ea6c8b
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Mon Nov 13 22:42:29 2023 -0600
Access current thread group directly
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java
index 65ed49c7c1..2a55c1a901 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java
@@ -75,9 +75,7 @@ public class Log4jThreadFactory implements ThreadFactory {
this.threadNamePrefix = PREFIX + FACTORY_NUMBER.getAndIncrement() + "-" + threadFactoryName + "-";
this.daemon = daemon;
this.priority = priority;
- final SecurityManager securityManager = System.getSecurityManager();
- this.group = securityManager != null ? securityManager.getThreadGroup()
- : Thread.currentThread().getThreadGroup();
+ this.group = Thread.currentThread().getThreadGroup();
}
@Override
(logging-log4j2) 02/07: Update changelog entry
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit d0f7e533a3769957b243d46cf9a93cf63dab2e27
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Mon Nov 13 22:42:43 2023 -0600
Update changelog entry
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../.3.x.x/remove_legacy_osgi_support.xml | 23 +++++-----------------
1 file changed, 5 insertions(+), 18 deletions(-)
diff --git a/src/changelog/.3.x.x/remove_legacy_osgi_support.xml b/src/changelog/.3.x.x/remove_legacy_osgi_support.xml
index 0b2656f6e4..a4f72a0670 100644
--- a/src/changelog/.3.x.x/remove_legacy_osgi_support.xml
+++ b/src/changelog/.3.x.x/remove_legacy_osgi_support.xml
@@ -1,21 +1,8 @@
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to You under the Apache license, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the license for the specific language governing permissions and
- ~ limitations under the license.
- -->
-
-<entry xmlns="http://logging.apache.org/log4j/changelog" type="removed">
+<?xml version="1.0" encoding="UTF-8"?>
+<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns="http://logging.apache.org/log4j/changelog"
+ xsi:schemaLocation="http://logging.apache.org/log4j/changelog https://logging.apache.org/log4j/changelog-0.1.2.xsd"
+ type="removed">
<author id="mattsicker"/>
<description format="asciidoc">Remove legacy OSGi integration. `ServiceLoader` mechanism should be used instead.</description>
</entry>
(logging-log4j2) 03/07: Remove tests related to SecurityManager
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 295d5e460a54fdf690d2780e4a891686779334e4
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Mon Nov 13 22:44:03 2023 -0600
Remove tests related to SecurityManager
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../log4j/test/junit/SecurityManagerTestRule.java | 93 ----------------------
...EnvironmentPropertySourceSecurityManagerIT.java | 83 -------------------
...ropertyFilePropertySourceSecurityManagerIT.java | 89 ---------------------
.../logging/log4j/util/StackLocatorTestIT.java | 64 ---------------
.../logging/log4j/util/StackLocatorUtilTest.java | 11 +--
...mPropertiesPropertySourceSecurityManagerIT.java | 92 ---------------------
.../util/PrivateSecurityManagerStackTraceUtil.java | 80 -------------------
.../apache/logging/log4j/util/StackLocator.java | 4 -
.../log4j/core/impl/ThrowableProxyTest.java | 78 ------------------
.../log4j/perf/jmh/ReflectionBenchmark.java | 13 ---
.../.3.x.x/remove_security_manager_support.xml | 10 +++
11 files changed, 11 insertions(+), 606 deletions(-)
diff --git a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/SecurityManagerTestRule.java b/log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/SecurityManagerTestRule.java
deleted file mode 100644
index c3a8a6f41e..0000000000
--- a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/SecurityManagerTestRule.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.test.junit;
-
-import org.junit.rules.TestRule;
-import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
-
-/**
- * Sets a security manager for a test run. The current security manager is first saved then restored after the test is
- * run.
- * <p>
- * Using a security manager can mess up other tests so this is best used from integration tests (classes that end in
- * "IT" instead of "Test" and "TestCase".)
- * </p>
- *
- * <p>
- * When this test rule is evaluated, it will:
- * </p>
- * <ol>
- * <li>Save the current SecurityManager.</li>
- * <li>Set the SecurityManager to the instance supplied to this rule.</li>
- * <li>Evaluate the test statement.</li>
- * <li>Reset the current SecurityManager to the one from step (1).</li>
- * </ol>
- *
- * @since 2.11.0
- */
-public class SecurityManagerTestRule implements TestRule {
-
- /**
- * Constructs a new instance with the given {@link SecurityManager}.
- * <p>
- * When this test rule is evaluated, it will:
- * </p>
- * <ol>
- * <li>Save the current SecurityManager.</li>
- * <li>Set the SecurityManager to the instance supplied to this rule.</li>
- * <li>Evaluate the test statement.</li>
- * <li>Reset the current SecurityManager to the one from step (1).</li>
- * </ol>
- *
- * @param securityManager
- * the {@link SecurityManager} to use while running a test.
- */
- public SecurityManagerTestRule(final SecurityManager securityManager) {
- super();
- this.securityManager = securityManager;
- }
-
- private SecurityManager securityManagerBefore;
- private final SecurityManager securityManager;
-
- @Override
- public Statement apply(final Statement base, final Description description) {
- return new Statement() {
- @Override
- public void evaluate() throws Throwable {
- before();
- try {
- base.evaluate();
- } finally {
- after();
- }
- }
-
- private void after() {
- System.setSecurityManager(securityManagerBefore);
- }
-
- private void before() {
- securityManagerBefore = System.getSecurityManager();
- System.setSecurityManager(securityManager);
-
- }
- };
- }
-
-}
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceSecurityManagerIT.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceSecurityManagerIT.java
deleted file mode 100644
index 238478c3c2..0000000000
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceSecurityManagerIT.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.security.Permission;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledForJreRange;
-import org.junit.jupiter.api.condition.JRE;
-import org.junit.jupiter.api.parallel.ResourceLock;
-
-/**
- * Tests <a href="https://issues.apache.org/jira/browse/LOG4J2-2274">LOG4J2-2274</a>.
- * <p>
- * Using a security manager can mess up other tests so this is best used from
- * integration tests (classes that end in "IT" instead of "Test" and
- * "TestCase".)
- * </p>
- *
- * @see EnvironmentPropertySource
- * @see SecurityManager
- * @see System#setSecurityManager(SecurityManager)
- */
-@ResourceLock("java.lang.SecurityManager")
-@DisabledForJreRange(min = JRE.JAVA_18) // custom SecurityManager instances throw UnsupportedOperationException
-public class EnvironmentPropertySourceSecurityManagerIT {
-
- /**
- * Always throws a SecurityException for any environment variables permission
- * check.
- */
- private static class TestSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(final Permission permission) {
- if ("getenv.*".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
- }
-
- /**
- * Makes sure we do not blow up with exception below due to a security manager
- * rejecting environment variable access in {@link EnvironmentPropertySource}.
- *
- * <pre>
- * java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
- * at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:78)
- * at org.apache.logging.log4j.core.AbstractLifeCycle.<clinit>(AbstractLifeCycle.java:38)
- * at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
- * at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
- * at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
- * at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
- * at org.apache.logging.log4j.core.config.builder.impl.DefaultConfigurationBuilder.build(DefaultConfigurationBuilder.java:172)
- * at org.apache.logging.log4j.core.config.builder.impl.DefaultConfigurationBuilder.build(DefaultConfigurationBuilder.java:161)
- * at org.apache.logging.log4j.core.config.builder.impl.DefaultConfigurationBuilder.build(DefaultConfigurationBuilder.java:1)
- * at org.apache.logging.log4j.util.EnvironmentPropertySourceSecurityManagerTest.test(EnvironmentPropertySourceSecurityManagerTest.java:55)
- * </pre>
- */
- @Test
- public void test() {
- final var existing = System.getSecurityManager();
- try {
- System.setSecurityManager(new TestSecurityManager());
- PropertiesUtil.getProperties();
- } finally {
- System.setSecurityManager(existing);
- }
- }
-}
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertyFilePropertySourceSecurityManagerIT.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertyFilePropertySourceSecurityManagerIT.java
deleted file mode 100644
index db6f6c6938..0000000000
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertyFilePropertySourceSecurityManagerIT.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.io.FilePermission;
-import java.nio.file.Paths;
-import java.security.Permission;
-import java.util.PropertyPermission;
-
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledForJreRange;
-import org.junit.jupiter.api.condition.JRE;
-import org.junit.jupiter.api.parallel.ResourceLock;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * Test related to <a href="https://issues.apache.org/jira/browse/LOG4J2-2274">LOG4J2-2274</a>.
- * <p>
- * Using a security manager can mess up other tests so this is best used from
- * integration tests (classes that end in "IT" instead of "Test" and
- * "TestCase".)
- * </p>
- *
- * @see PropertyFilePropertySource
- * @see SecurityManager
- * @see System#setSecurityManager(SecurityManager)
- * @see PropertyPermission
- */
-@ResourceLock("java.lang.SecurityManager")
-@DisabledForJreRange(min = JRE.JAVA_18) // custom SecurityManager instances throw UnsupportedOperationException
-public class PropertyFilePropertySourceSecurityManagerIT {
-
- @BeforeAll
- public static void beforeClass() {
- assertThat(Paths.get(TEST_FIXTURE_PATH)).exists();
- }
-
- private static final String TEST_FIXTURE_PATH = "src/test/resources/PropertiesUtilTest.properties";
-
- /**
- * Always throws a SecurityException for any environment variables permission
- * check.
- */
- private static class TestSecurityManager extends SecurityManager {
-
- @Override
- public void checkPermission(final Permission permission) {
- if (permission instanceof FilePermission && permission.getName().endsWith(TEST_FIXTURE_PATH)) {
- throw new SecurityException();
- }
- }
- }
-
- /**
- * Makes sure we do not blow up with exception below due to a security manager
- * rejecting environment variable access in
- * {@link SystemPropertiesPropertySource}.
- *
- * <pre>
- * </pre>
- */
- @Test
- public void test() {
- final var existing = System.getSecurityManager();
- try {
- System.setSecurityManager(new TestSecurityManager());
- final PropertiesUtil propertiesUtil = new PropertiesUtil(TEST_FIXTURE_PATH);
- assertThat(propertiesUtil.getStringProperty("a.1")).isNull();
- } finally {
- System.setSecurityManager(existing);
- }
- }
-}
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java
deleted file mode 100644
index 6f59db2549..0000000000
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.security.Permission;
-import java.util.Deque;
-
-import org.apache.logging.log4j.test.junit.SecurityManagerTestRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.parallel.ResourceLock;
-
-
-/**
- * Tests https://github.com/apache/logging-log4j2/pull/1214.
- * <p>
- * Using a security manager can mess up other tests so this is best used from
- * integration tests (classes that end in "IT" instead of "Test" and
- * "TestCase".)
- * </p>
- *
- * @see StackLocator
- * @see SecurityManager
- * @see System#setSecurityManager(SecurityManager)
- */
-@ResourceLock("java.lang.SecurityManager")
-public class StackLocatorTestIT {
- @Rule
- public final SecurityManagerTestRule rule = new SecurityManagerTestRule(new TestSecurityManager());
-
- /**
- * Always throws a SecurityException for any reques to create a new SecurityManager
- */
- private static class TestSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(final Permission permission) {
- if ("createSecurityManager".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
- }
-
- @Test
- public void testGetCurrentStacktraceSlowPath() {
- final StackLocator stackLocator = StackLocator.getInstance();
- final Deque<Class<?>> classes = stackLocator.getCurrentStackTrace();
- Assertions.assertSame(StackLocator.class, classes.getFirst());
- }
-}
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java
index 72f74876c7..1951c87893 100644
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java
+++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java
@@ -84,15 +84,6 @@ public class StackLocatorUtilTest {
assertSame(StackLocatorUtilTest.class, classes.removeFirst());
}
- @Test
- public void testTopElementInStackTrace() {
- final StackLocator stackLocator = StackLocator.getInstance();
- final Deque<Class<?>> classes = stackLocator.getCurrentStackTrace();
- //Removing private class in "PrivateSecurityManagerStackTraceUtil"
- classes.removeFirst();
- assertSame(PrivateSecurityManagerStackTraceUtil.class, classes.getFirst());
- }
-
@Test
public void testGetCallerClassViaName() throws Exception {
final Class<?> expected = InterceptingExecutableInvoker.class;
@@ -159,7 +150,7 @@ public class StackLocatorUtilTest {
final StackTraceElement element = new Foo().foo();
assertEquals("org.apache.logging.log4j.util.StackLocatorUtilTest$Foo", element.getClassName());
// The line number below may need adjustment if this file is changed.
- assertEquals(125, element.getLineNumber());
+ assertEquals(116, element.getLineNumber());
}
@Test
diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceSecurityManagerIT.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceSecurityManagerIT.java
deleted file mode 100644
index 22d85c9edc..0000000000
--- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceSecurityManagerIT.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.security.Permission;
-import java.util.PropertyPermission;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledForJreRange;
-import org.junit.jupiter.api.condition.JRE;
-import org.junit.jupiter.api.parallel.ResourceLock;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * Test related to <a href="https://issues.apache.org/jira/browse/LOG4J2-2274">LOG4J2-2274</a>.
- * <p>
- * Using a security manager can mess up other tests so this is best used from
- * integration tests (classes that end in "IT" instead of "Test" and
- * "TestCase".)
- * </p>
- *
- * @see SystemPropertiesPropertySource
- * @see SecurityManager
- * @see System#setSecurityManager(SecurityManager)
- * @see PropertyPermission
- */
-@ResourceLock("java.lang.SecurityManager")
-@DisabledForJreRange(min = JRE.JAVA_18) // custom SecurityManager instances throw UnsupportedOperationException
-public class SystemPropertiesPropertySourceSecurityManagerIT {
-
- /**
- * Always throws a SecurityException for any environment variables permission
- * check.
- */
- private static class TestSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(final Permission permission) {
- if (permission instanceof PropertyPermission) {
- throw new SecurityException();
- }
- }
- }
-
- /**
- * Makes sure we do not blow up with exception below due to a security manager
- * rejecting environment variable access in
- * {@link SystemPropertiesPropertySource}.
- *
- * <pre>
- * java.lang.ExceptionInInitializerError
- * at org.apache.logging.log4j.util.SystemPropertiesPropertySourceSecurityManagerTest.test(SystemPropertiesPropertySourceSecurityManagerTest.java:64)
- * ...
- * Caused by: java.lang.SecurityException
- * at org.apache.logging.log4j.util.SystemPropertiesPropertySourceSecurityManagerTest$TestSecurityManager.checkPermission(SystemPropertiesPropertySourceSecurityManagerTest.java:49)
- * at java.lang.SecurityManager.checkPropertiesAccess(SecurityManager.java:1265)
- * at java.lang.System.getProperties(System.java:624)
- * at org.apache.logging.log4j.util.SystemPropertiesPropertySource.forEach(SystemPropertiesPropertySource.java:40)
- * at org.apache.logging.log4j.util.PropertiesUtil$Environment.reload(PropertiesUtil.java:330)
- * at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:322)
- * at org.apache.logging.log4j.util.PropertiesUtil$Environment.<init>(PropertiesUtil.java:310)
- * at org.apache.logging.log4j.util.PropertiesUtil.<init>(PropertiesUtil.java:69)
- * at org.apache.logging.log4j.util.PropertiesUtil.<clinit>(PropertiesUtil.java:49)
- * ... 26 more
- * </pre>
- */
- @Test
- public void test() {
- final var existing = System.getSecurityManager();
- try {
- System.setSecurityManager(new TestSecurityManager());
- final PropertiesUtil propertiesUtil = new PropertiesUtil("src/test/resources/PropertiesUtilTest.properties");
- assertThat(propertiesUtil.getStringProperty("a.1")).isNull();
- } finally {
- System.setSecurityManager(existing);
- }
- }
-}
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/PrivateSecurityManagerStackTraceUtil.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/PrivateSecurityManagerStackTraceUtil.java
deleted file mode 100644
index db02a9454d..0000000000
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/PrivateSecurityManagerStackTraceUtil.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.util;
-
-import java.util.ArrayDeque;
-import java.util.Collections;
-import java.util.Deque;
-
-/**
- * Internal utility to share a fast implementation of {@code #getCurrentStackTrace()}
- * with the java 9 implementation of {@link StackLocator}.
- */
-final class PrivateSecurityManagerStackTraceUtil {
-
- private static final PrivateSecurityManager SECURITY_MANAGER;
-
- static {
- PrivateSecurityManager psm;
- try {
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("createSecurityManager"));
- }
- psm = new PrivateSecurityManager();
- } catch (final SecurityException ignored) {
- psm = null;
- }
-
- SECURITY_MANAGER = psm;
- }
-
- private PrivateSecurityManagerStackTraceUtil() {
- // Utility Class
- }
-
- static boolean isEnabled() {
- return SECURITY_MANAGER != null;
- }
-
- /**
- * Returns the current execution stack as a Deque of classes.
- * <p>
- * The size of the Deque is the number of methods on the execution stack. The first element is the class that started
- * execution on this thread, the next element is the class that was called next, and so on, until the last element: the
- * method that called {@link SecurityManager#getClassContext()} to capture the stack.
- * </p>
- *
- * @return the execution stack.
- */
- // benchmarks show that using the SecurityManager is much faster than looping through getCallerClass(int)
- static Deque<Class<?>> getCurrentStackTrace() {
- final Class<?>[] array = SECURITY_MANAGER.getClassContext();
- final Deque<Class<?>> classes = new ArrayDeque<>(array.length);
- Collections.addAll(classes, array);
- return classes;
- }
-
- private static final class PrivateSecurityManager extends SecurityManager {
-
- @Override
- protected Class<?>[] getClassContext() {
- return super.getClassContext();
- }
-
- }
-}
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/StackLocator.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/StackLocator.java
index 0f3dd1f99b..3c24511700 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/StackLocator.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/StackLocator.java
@@ -99,10 +99,6 @@ public final class StackLocator {
@PerformanceSensitive
public Deque<Class<?>> getCurrentStackTrace() {
- // benchmarks show that using the SecurityManager is much faster than looping through getCallerClass(int)
- if (PrivateSecurityManagerStackTraceUtil.isEnabled()) {
- return PrivateSecurityManagerStackTraceUtil.getCurrentStackTrace();
- }
final Deque<Class<?>> stack = new ArrayDeque<>();
return WALKER.walk(s -> {
s.forEach(f -> stack.add(f.getDeclaringClass()));
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java
index 04d4adba79..1d39f7bbf8 100644
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java
+++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java
@@ -17,21 +17,11 @@
package org.apache.logging.log4j.core.impl;
import java.io.IOException;
-import java.net.BindException;
-import java.net.InetSocketAddress;
-import java.nio.channels.ServerSocketChannel;
-import java.security.Permission;
-import java.security.SecureRandom;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.KeyGenerator;
-import javax.crypto.spec.IvParameterSpec;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
@@ -39,8 +29,6 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.pattern.PlainTextRenderer;
import org.apache.logging.log4j.util.Strings;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledForJreRange;
-import org.junit.jupiter.api.condition.JRE;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -121,72 +109,6 @@ public class ThrowableProxyTest {
});
}
- @Test
- @DisabledForJreRange(min = JRE.JAVA_18) // custom SecurityManager instances throw UnsupportedOperationException
- public void testLogStackTraceWithClassThatWillCauseSecurityException() throws IOException {
- final SecurityManager sm = System.getSecurityManager();
- try {
- System.setSecurityManager(
- new SecurityManager() {
- @Override
- public void checkPermission(final Permission perm) {
- if (perm instanceof RuntimePermission) {
- // deny access to the class to trigger the security exception
- if ("accessClassInPackage.sun.nio.ch".equals(perm.getName())) {
- throw new SecurityException(perm.toString());
- }
- }
- }
- });
- final BindException e = assertThrows(BindException.class, () -> {
- ServerSocketChannel.open().socket().bind(new InetSocketAddress("localhost", 9300));
- ServerSocketChannel.open().socket().bind(new InetSocketAddress("localhost", 9300));
- });
- assertDoesNotThrow(() -> new ThrowableProxy(e));
- } finally {
- // restore the security manager
- System.setSecurityManager(sm);
- }
- }
-
- @Test
- @DisabledForJreRange(min = JRE.JAVA_18) // custom SecurityManager instances throw UnsupportedOperationException
- public void testLogStackTraceWithClassLoaderThatWithCauseSecurityException() throws Exception {
- final SecurityManager sm = System.getSecurityManager();
- try {
- System.setSecurityManager(
- new SecurityManager() {
- @Override
- public void checkPermission(final Permission perm) {
- if (perm instanceof RuntimePermission) {
- // deny access to the classloader to trigger the security exception
- if ("getClassLoader".equals(perm.getName())) {
- throw new SecurityException(perm.toString());
- }
- }
- }
- });
- final String algorithm = "AES/CBC/PKCS5Padding";
- final Cipher ec = Cipher.getInstance(algorithm);
- final byte[] bytes = new byte[16]; // initialization vector
- final SecureRandom secureRandom = new SecureRandom();
- secureRandom.nextBytes(bytes);
- final KeyGenerator generator = KeyGenerator.getInstance("AES");
- generator.init(128);
- final IvParameterSpec algorithmParameterSpec = new IvParameterSpec(bytes);
- ec.init(Cipher.ENCRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
- final byte[] raw = new byte[0];
- final byte[] encrypted = ec.doFinal(raw);
- final Cipher dc = Cipher.getInstance(algorithm);
- dc.init(Cipher.DECRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
- final BadPaddingException e = assertThrows(BadPaddingException.class, () -> dc.doFinal(encrypted));
- assertDoesNotThrow(() -> new ThrowableProxy(e));
- } finally {
- // restore the existing security manager
- System.setSecurityManager(sm);
- }
- }
-
@Test
public void testSeparator_getExtendedStackTraceAsString() throws Exception {
final Throwable throwable = new IllegalArgumentException("This is a test");
diff --git a/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ReflectionBenchmark.java b/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ReflectionBenchmark.java
index 38a56553e3..30f9bfc272 100644
--- a/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ReflectionBenchmark.java
+++ b/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ReflectionBenchmark.java
@@ -60,14 +60,6 @@ public class ReflectionBenchmark {
}
}
- @State(Scope.Benchmark)
- public static class ClassContextManager extends SecurityManager {
- @Override
- protected Class[] getClassContext() {
- return super.getClassContext();
- }
- }
-
@Benchmark
public void baseline() {
}
@@ -127,11 +119,6 @@ public class ReflectionBenchmark {
return classes;
}
- @Benchmark
- public Class<?>[] test12_getClassContextViaSecurityManager(final ClassContextManager classContextManager) {
- return classContextManager.getClassContext();
- }
-
@Benchmark
public Class<?> reflectionUtilGetClass() {
diff --git a/src/changelog/.3.x.x/remove_security_manager_support.xml b/src/changelog/.3.x.x/remove_security_manager_support.xml
new file mode 100644
index 0000000000..adc165c72e
--- /dev/null
+++ b/src/changelog/.3.x.x/remove_security_manager_support.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns="http://logging.apache.org/log4j/changelog"
+ xsi:schemaLocation="http://logging.apache.org/log4j/changelog https://logging.apache.org/log4j/changelog-0.1.2.xsd"
+ type="removed">
+ <author id="mattsicker"/>
+ <description format="asciidoc">
+ Remove support for `SecurityManager`. Starting in Java 21, a custom `SecurityManager` cannot be used.
+ </description>
+</entry>
(logging-log4j2) 04/07: Access system properties directly
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit e15359668c1137bcc2280a375f408dac8dd0d61e
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Mon Nov 13 22:44:54 2023 -0600
Access system properties directly
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../org/apache/logging/log4j/util/Strings.java | 3 +-
.../log4j/util/SystemPropertiesPropertySource.java | 37 +++++-----------------
2 files changed, 9 insertions(+), 31 deletions(-)
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/Strings.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/Strings.java
index 6c02b6ba06..13cc9b7bfc 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/Strings.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/Strings.java
@@ -46,8 +46,7 @@ public final class Strings {
* OS-dependent line separator, defaults to {@code "\n"} if the system property {@code ""line.separator"} cannot be
* read.
*/
- public static final String LINE_SEPARATOR = SystemPropertiesPropertySource.getSystemProperty("line.separator",
- "\n");
+ public static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
private Strings() {
// empty
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/SystemPropertiesPropertySource.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/SystemPropertiesPropertySource.java
index f2275a58b3..169e7bc534 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/SystemPropertiesPropertySource.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/SystemPropertiesPropertySource.java
@@ -25,7 +25,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
-import aQute.bnd.annotation.Resolution;
import aQute.bnd.annotation.spi.ServiceProvider;
/**
@@ -35,7 +34,7 @@ import aQute.bnd.annotation.spi.ServiceProvider;
*
* @since 2.10.0
*/
-@ServiceProvider(value = PropertySource.class, resolution = Resolution.OPTIONAL)
+@ServiceProvider(PropertySource.class)
public class SystemPropertiesPropertySource extends ContextAwarePropertySource implements PropertySource {
private static final int DEFAULT_PRIORITY = 0;
@@ -53,18 +52,6 @@ public class SystemPropertiesPropertySource extends ContextAwarePropertySource i
super(null, SYSTEM_CONTEXT, true);
}
- /**
- * Used by bootstrap code to get system properties without loading PropertiesUtil.
- */
- public static String getSystemProperty(final String key, final String defaultValue) {
- try {
- return System.getProperty(key, defaultValue);
- } catch (SecurityException e) {
- // Silently ignore the exception
- return defaultValue;
- }
- }
-
@Override
public int getPriority() {
return DEFAULT_PRIORITY;
@@ -104,11 +91,11 @@ public class SystemPropertiesPropertySource extends ContextAwarePropertySource i
@Override
public String getProperty(final String contextName, final String key) {
if (contextName != null && !contextName.equals(SYSTEM_CONTEXT)) {
- return getSystemProperty(PREFIX + contextName + DELIM + key, null);
+ return System.getProperty(PREFIX + contextName + DELIM + key, null);
} else {
- String result = getSystemProperty(PREFIX + SYSTEM_CONTEXT + DELIM + key, null);
+ String result = System.getProperty(PREFIX + SYSTEM_CONTEXT + DELIM + key, null);
if (result == null) {
- result = getSystemProperty(key, null);
+ result = System.getProperty(key, null);
}
return result;
}
@@ -117,10 +104,10 @@ public class SystemPropertiesPropertySource extends ContextAwarePropertySource i
@Override
public boolean containsProperty(final String contextName, final String key) {
if (contextName != null && !contextName.equals(SYSTEM_CONTEXT)) {
- return getSystemProperty(PREFIX + contextName + DELIM + key, null) != null;
+ return System.getProperty(PREFIX + contextName + DELIM + key, null) != null;
} else {
- return getSystemProperty(PREFIX + SYSTEM_CONTEXT + DELIM + key, null) != null
- || getSystemProperty(key, null) != null;
+ return System.getProperty(PREFIX + SYSTEM_CONTEXT + DELIM + key, null) != null
+ || System.getProperty(key, null) != null;
}
}
@@ -137,7 +124,7 @@ public class SystemPropertiesPropertySource extends ContextAwarePropertySource i
*/
RELOAD_LOCK.lock();
try {
- final Properties props = getProperties();
+ final Properties props = System.getProperties();
if (props == null) {
return false;
}
@@ -166,12 +153,4 @@ public class SystemPropertiesPropertySource extends ContextAwarePropertySource i
return true;
}
- private static Properties getProperties() {
- try {
- return System.getProperties();
- } catch (final SecurityException e) {
- return null;
- }
- }
-
}
(logging-log4j2) 05/07: Remove SecurityManager checks from LoaderUtil
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 79d21aee3ad18415b312cb308fb8bd2fc8500581
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Mon Nov 13 22:45:12 2023 -0600
Remove SecurityManager checks from LoaderUtil
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../org/apache/logging/log4j/util/LoaderUtil.java | 184 +++++++--------------
1 file changed, 57 insertions(+), 127 deletions(-)
diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java b/log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
index 7a405fdafc..43d3f87c1c 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
@@ -20,8 +20,6 @@ import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashSet;
@@ -45,38 +43,11 @@ public final class LoaderUtil {
// this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil
// wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil.
private static Boolean ignoreTCCL;
-
- private static final RuntimePermission GET_CLASS_LOADER = new RuntimePermission("getClassLoader");
- private static final boolean GET_CLASS_LOADER_DISABLED;
-
static Boolean forceTcclOnly;
- private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
- private static final PrivilegedAction<ClassLoader[]> CLASSLOADER_ACCUMULATOR = new ClassLoaderAccumulator();
-
static {
if (System.getSecurityManager() != null) {
- boolean getClassLoaderDisabled;
- try {
- AccessController.checkPermission(GET_CLASS_LOADER);
- // seems like we'll be ok
- getClassLoaderDisabled = false;
- } catch (final SecurityException ignored) {
- try {
- // let's see if we can obtain that permission
- AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
- AccessController.checkPermission(GET_CLASS_LOADER);
- return null;
- }, null, GET_CLASS_LOADER);
- getClassLoaderDisabled = false;
- } catch (final SecurityException ignore) {
- // no chance
- getClassLoaderDisabled = true;
- }
- }
- GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled;
- } else {
- GET_CLASS_LOADER_DISABLED = false;
+ LowLevelLogUtil.log("A custom SecurityManager was detected; Log4j no longer supports security permissions.");
}
}
@@ -94,18 +65,13 @@ public final class LoaderUtil {
// TODO: this method could use some explanation
public static ClassLoader getClassLoader(final Class<?> class1, final Class<?> class2) {
- PrivilegedAction<ClassLoader> action = () -> {
- final ClassLoader loader1 = class1 == null ? null : class1.getClassLoader();
- final ClassLoader loader2 = class2 == null ? null : class2.getClassLoader();
- final ClassLoader referenceLoader = GET_CLASS_LOADER_DISABLED
- ? getThisClassLoader()
- : Thread.currentThread().getContextClassLoader();
- if (isChild(referenceLoader, loader1)) {
- return isChild(referenceLoader, loader2) ? referenceLoader : loader2;
- }
- return isChild(loader1, loader2) ? loader1 : loader2;
- };
- return AccessController.doPrivileged(action, null, GET_CLASS_LOADER);
+ final ClassLoader loader1 = class1 == null ? null : class1.getClassLoader();
+ final ClassLoader loader2 = class2 == null ? null : class2.getClassLoader();
+ final ClassLoader referenceLoader = Thread.currentThread().getContextClassLoader();
+ if (isChild(referenceLoader, loader1)) {
+ return isChild(referenceLoader, loader2) ? referenceLoader : loader2;
+ }
+ return isChild(loader1, loader2) ? loader1 : loader2;
}
/**
@@ -129,101 +95,74 @@ public final class LoaderUtil {
}
/**
- * Looks up the ClassLoader for this current thread. If this class does not have the runtime permission
- * {@code getClassLoader}, then the only ClassLoader this attempts to look up is the loader behind this
- * class. When a SecurityManager is installed, this attempts to make a privileged call to get the current
- * {@linkplain Thread#getContextClassLoader() thread context ClassLoader}, falling back to either the
+ * Looks up the ClassLoader for this current thread falling back to either the
* ClassLoader of this class or the {@linkplain ClassLoader#getSystemClassLoader() system ClassLoader}.
- * When no SecurityManager is present, the same lookups are performed without use of {@link AccessController}.
* If none of these strategies can obtain a ClassLoader, then this returns {@code null}.
*
* @return the current thread's ClassLoader, a fallback loader, or null if no fallback can be determined
*/
public static ClassLoader getThreadContextClassLoader() {
- if (GET_CLASS_LOADER_DISABLED) {
- // we can at least get this class's ClassLoader regardless of security context
- // however, if this is null, there's really no option left at this point
- try {
- return getThisClassLoader();
- } catch (final SecurityException ignored) {
- return null;
- }
+ final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ if (contextClassLoader != null) {
+ return contextClassLoader;
}
- return AccessController.doPrivileged(TCCL_GETTER, null, GET_CLASS_LOADER);
+ final ClassLoader thisClassLoader = getThisClassLoader();
+ if (thisClassLoader != null) {
+ return thisClassLoader;
+ }
+ return ClassLoader.getSystemClassLoader();
}
public static ClassLoader[] getClassLoaders() {
- return AccessController.doPrivileged(CLASSLOADER_ACCUMULATOR, null, GET_CLASS_LOADER);
+ final Collection<ClassLoader> classLoaders = new LinkedHashSet<>();
+ final ClassLoader tcl = getThreadContextClassLoader();
+ if (tcl != null) {
+ classLoaders.add(tcl);
+ }
+ final ModuleLayer layer = LoaderUtil.class.getModule().getLayer();
+ if (layer == null) {
+ if (!isForceTccl()) {
+ accumulateClassLoaders(getThisClassLoader(), classLoaders);
+ accumulateClassLoaders(tcl == null ? null : tcl.getParent(), classLoaders);
+ final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
+ if (systemClassLoader != null) {
+ classLoaders.add(systemClassLoader);
+ }
+ }
+ } else {
+ accumulateLayerClassLoaders(layer, classLoaders);
+ if (layer != ModuleLayer.boot()) {
+ for (final Module module : ModuleLayer.boot().modules()) {
+ accumulateClassLoaders(module.getClassLoader(), classLoaders);
+ }
+ }
+ }
+ return classLoaders.toArray(EMPTY_CLASS_LOADER_ARRAY);
}
private static ClassLoader getThisClassLoader() {
return LoaderUtil.class.getClassLoader();
}
- private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
- @Override
- public ClassLoader run() {
- final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- if (contextClassLoader != null) {
- return contextClassLoader;
- }
- final ClassLoader thisClassLoader = getThisClassLoader();
- if (thisClassLoader != null || GET_CLASS_LOADER_DISABLED) {
- return thisClassLoader;
- }
- return ClassLoader.getSystemClassLoader();
- }
- }
-
- private static class ClassLoaderAccumulator implements PrivilegedAction<ClassLoader[]> {
- @Override
- public ClassLoader[] run() {
- final Collection<ClassLoader> classLoaders = new LinkedHashSet<>();
- final ClassLoader tcl = TCCL_GETTER.run();
- if (tcl != null) {
- classLoaders.add(tcl);
- }
- final ModuleLayer layer = LoaderUtil.class.getModule().getLayer();
- if (layer == null) {
- if (!isForceTccl()) {
- accumulateClassLoaders(getThisClassLoader(), classLoaders);
- accumulateClassLoaders(tcl == null ? null : tcl.getParent(), classLoaders);
- final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
- if (systemClassLoader != null) {
- classLoaders.add(systemClassLoader);
- }
- }
- } else {
- accumulateLayerClassLoaders(layer, classLoaders);
- if (layer != ModuleLayer.boot()) {
- for (final Module module : ModuleLayer.boot().modules()) {
- accumulateClassLoaders(module.getClassLoader(), classLoaders);
- }
- }
- }
- return classLoaders.toArray(EMPTY_CLASS_LOADER_ARRAY);
+ private static void accumulateLayerClassLoaders(final ModuleLayer layer, final Collection<ClassLoader> classLoaders) {
+ for (final Module module : layer.modules()) {
+ accumulateClassLoaders(module.getClassLoader(), classLoaders);
}
-
- private static void accumulateLayerClassLoaders(final ModuleLayer layer, final Collection<ClassLoader> classLoaders) {
- for (final Module module : layer.modules()) {
- accumulateClassLoaders(module.getClassLoader(), classLoaders);
- }
- if (!layer.parents().isEmpty()) {
- for (final ModuleLayer parent : layer.parents()) {
- accumulateLayerClassLoaders(parent, classLoaders);
- }
+ if (!layer.parents().isEmpty()) {
+ for (final ModuleLayer parent : layer.parents()) {
+ accumulateLayerClassLoaders(parent, classLoaders);
}
}
+ }
- /**
- * Adds the provided loader to the loaders collection, and traverses up the tree until either a null
- * value or a classloader which has already been added is encountered.
- */
- private static void accumulateClassLoaders(final ClassLoader loader, final Collection<ClassLoader> loaders) {
- // Some implementations may use null to represent the bootstrap class loader.
- if (loader != null && loaders.add(loader)) {
- accumulateClassLoaders(loader.getParent(), loaders);
- }
+ /**
+ * Adds the provided loader to the loaders collection, and traverses up the tree until either a null
+ * value or a classloader which has already been added is encountered.
+ */
+ private static void accumulateClassLoaders(final ClassLoader loader, final Collection<ClassLoader> loaders) {
+ // Some implementations may use null to represent the bootstrap class loader.
+ if (loader != null && loaders.add(loader)) {
+ accumulateClassLoaders(loader.getParent(), loaders);
}
}
@@ -447,16 +386,7 @@ public final class LoaderUtil {
private static boolean isForceTccl() {
if (forceTcclOnly == null) {
// PropertiesUtil.getProperties() uses that code path so don't use that!
- final String key = LoggingSystemProperty.LOADER_FORCE_THREAD_CONTEXT_LOADER.getSystemKey();
- final SecurityManager securityManager = System.getSecurityManager();
- try {
- if (securityManager != null) {
- securityManager.checkPropertyAccess(key);
- }
- forceTcclOnly = Boolean.getBoolean(key);
- } catch (final SecurityException se) {
- forceTcclOnly = false;
- }
+ forceTcclOnly = Boolean.getBoolean(LoggingSystemProperty.LOADER_FORCE_THREAD_CONTEXT_LOADER.getSystemKey());
}
return forceTcclOnly;
}
(logging-log4j2) 06/07: Use system properties directly
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch the-great-deletion
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 6e00230de955c76ee8564472bb1cb74813388129
Author: Matt Sicker <ma...@apache.org>
AuthorDate: Tue Nov 14 00:01:40 2023 -0600
Use system properties directly
Signed-off-by: Matt Sicker <ma...@apache.org>
---
.../main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java | 3 +--
.../main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java | 3 +--
2 files changed, 2 insertions(+), 4 deletions(-)
diff --git a/log4j-jakarta-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java b/log4j-jakarta-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
index 1845d26453..35f9ec64f2 100644
--- a/log4j-jakarta-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
+++ b/log4j-jakarta-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
@@ -50,7 +50,6 @@ import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.core.util.CyclicBuffer;
import org.apache.logging.log4j.core.util.NetUtils;
import org.apache.logging.log4j.smtp.MimeMessageBuilder;
-import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.Strings;
/**
@@ -343,7 +342,7 @@ public class SmtpManager extends AbstractManager {
public SmtpManager createManager(final String name, final FactoryData data) {
final String prefix = "mail." + data.protocol;
- final Properties properties = PropertiesUtil.getSystemProperties();
+ final Properties properties = System.getProperties();
properties.setProperty("mail.transport.protocol", data.protocol);
if (properties.getProperty("mail.host") == null) {
// Prevent an UnknownHostException in Java 7
diff --git a/log4j-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java b/log4j-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
index 530a1f6fd8..d6182ece7d 100644
--- a/log4j-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
+++ b/log4j-smtp/src/main/java/org/apache/logging/log4j/smtp/appender/SmtpManager.java
@@ -50,7 +50,6 @@ import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.core.util.CyclicBuffer;
import org.apache.logging.log4j.core.util.NetUtils;
import org.apache.logging.log4j.smtp.MimeMessageBuilder;
-import org.apache.logging.log4j.util.PropertiesUtil;
import org.apache.logging.log4j.util.Strings;
/**
@@ -347,7 +346,7 @@ public class SmtpManager extends AbstractManager {
public SmtpManager createManager(final String name, final FactoryData data) {
final String prefix = "mail." + data.protocol;
- final Properties properties = PropertiesUtil.getSystemProperties();
+ final Properties properties = System.getProperties();
properties.setProperty("mail.transport.protocol", data.protocol);
if (properties.getProperty("mail.host") == null) {
// Prevent an UnknownHostException in Java 7