1 /*
  2  * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /**
 25  * @test
 26  * @library /test/lib
 27  * @modules jdk.compiler
 28  * @build jdk.test.lib.compiler.CompilerUtils
 29  * @run junit/othervm BadProvidersTest
 30  * @summary Basic test of ServiceLoader with bad provider and bad provider
 31  *          factories deployed on the module path
 32  */
 33 
 34 import java.lang.classfile.ClassFile;
 35 import java.lang.constant.ClassDesc;
 36 import java.lang.constant.MethodTypeDesc;
 37 import java.lang.module.Configuration;
 38 import java.lang.module.ModuleFinder;
 39 import java.lang.reflect.AccessFlag;
 40 import java.nio.file.Files;
 41 import java.nio.file.Path;
 42 import java.nio.file.Paths;
 43 import java.nio.file.StandardCopyOption;
 44 import java.util.List;
 45 import java.util.ServiceConfigurationError;
 46 import java.util.ServiceLoader;
 47 import java.util.ServiceLoader.Provider;
 48 import java.util.Set;
 49 import java.util.stream.Collectors;
 50 
 51 import jdk.test.lib.compiler.CompilerUtils;
 52 
 53 
 54 import static java.lang.classfile.ClassFile.ACC_PUBLIC;
 55 import static java.lang.classfile.ClassFile.ACC_STATIC;
 56 import static java.lang.constant.ConstantDescs.CD_Object;
 57 import static java.lang.constant.ConstantDescs.INIT_NAME;
 58 import static java.lang.constant.ConstantDescs.MTD_void;
 59 
 60 import org.junit.jupiter.api.Assertions;
 61 import static org.junit.jupiter.api.Assertions.*;
 62 import org.junit.jupiter.api.Test;
 63 import org.junit.jupiter.params.ParameterizedTest;
 64 import org.junit.jupiter.params.provider.ValueSource;
 65 
 66 /**
 67  * Basic test of `provides S with PF` and `provides S with P` where the provider
 68  * factory or provider
 69  */
 70 public class BadProvidersTest {
 71 
 72     private static final String TEST_SRC = System.getProperty("test.src");
 73 
 74     private static final Path USER_DIR   = Paths.get(System.getProperty("user.dir"));
 75     private static final Path SRC_DIR    = Paths.get(TEST_SRC, "modules");
 76 
 77     private static final Path BADFACTORIES_DIR = Paths.get(TEST_SRC, "badfactories");
 78     private static final Path BADPROVIDERS_DIR = Paths.get(TEST_SRC, "badproviders");
 79 
 80     private static final String TEST1_MODULE = "test1";
 81     private static final String TEST2_MODULE = "test2";
 82 
 83     private static final String TEST_SERVICE = "p.Service";
 84 
 85     /**
 86      * Compiles a module, returning a module path with the compiled module.
 87      */
 88     private Path compileTest(String moduleName) throws Exception {
 89         Path dir = Files.createTempDirectory(USER_DIR, "mods");
 90         Path output = Files.createDirectory(dir.resolve(moduleName));
 91         boolean compiled = CompilerUtils.compile(SRC_DIR.resolve(moduleName), output);
 92         assertTrue(compiled);
 93         return dir;
 94     }
 95 
 96     /**
 97      * Resolves a test module and loads it into its own layer. ServiceLoader
 98      * is then used to load all providers.
 99      */
100     private List<Provider> loadProviders(Path mp, String moduleName) throws Exception {
101         ModuleFinder finder = ModuleFinder.of(mp);
102 
103         ModuleLayer bootLayer = ModuleLayer.boot();
104 
105         Configuration cf = bootLayer.configuration()
106                 .resolveAndBind(finder, ModuleFinder.of(), Set.of(moduleName));
107 
108         ClassLoader scl = ClassLoader.getSystemClassLoader();
109 
110         ModuleLayer layer = ModuleLayer.boot().defineModulesWithOneLoader(cf, scl);
111 
112         Class<?> service = layer.findLoader(moduleName).loadClass(TEST_SERVICE);
113 
114         return ServiceLoader.load(layer, service)
115                 .stream()
116                 .collect(Collectors.toList());
117     }
118 
119     @Test
120     public void sanityTest1() throws Exception {
121         Path mods = compileTest(TEST1_MODULE);
122         List<Provider> list = loadProviders(mods, TEST1_MODULE);
123         assertTrue(list.size() == 1);
124 
125         // the provider is a singleton, enforced by the provider factory
126         Object p1 = list.get(0).get();
127         Object p2 = list.get(0).get();
128         assertTrue(p1 != null);
129         assertTrue(p1 == p2);
130     }
131 
132     @Test
133     public void sanityTest2() throws Exception {
134         Path mods = compileTest(TEST2_MODULE);
135         List<Provider> list = loadProviders(mods, TEST2_MODULE);
136         assertTrue(list.size() == 1);
137         Object p = list.get(0).get();
138         assertTrue(p != null);
139     }
140 
141     @ParameterizedTest
142     @ValueSource(strings = { "classnotpublic", "methodnotpublic", "badreturntype",
143             "returnsnull", "throwsexception" })
144     public void testBadFactory(String testName) throws Exception {
145         Path mods = compileTest(TEST1_MODULE);
146 
147         // compile the bad factory
148         Path source = BADFACTORIES_DIR.resolve(testName);
149         Path output = Files.createTempDirectory(USER_DIR, "tmp");
150         boolean compiled = CompilerUtils.compile(source, output);
151         assertTrue(compiled);
152 
153         // copy the compiled class into the module
154         Path classFile = Paths.get("p", "ProviderFactory.class");
155         Files.copy(output.resolve(classFile),
156                 mods.resolve(TEST1_MODULE).resolve(classFile),
157                 StandardCopyOption.REPLACE_EXISTING);
158 
159         Assertions.assertThrows(ServiceConfigurationError.class,
160                 // load providers and instantiate each one
161                 () -> loadProviders(mods, TEST1_MODULE).forEach(Provider::get)
162         );
163     }
164 
165     @ParameterizedTest
166     @ValueSource(strings = { "notpublic", "ctornotpublic", "notasubtype", "throwsexception" })
167     public void testBadProvider(String testName) throws Exception {
168         Path mods = compileTest(TEST2_MODULE);
169 
170         // compile the bad provider
171         Path source = BADPROVIDERS_DIR.resolve(testName);
172         Path output = Files.createTempDirectory(USER_DIR, "tmp");
173         boolean compiled = CompilerUtils.compile(source, output);
174         assertTrue(compiled);
175 
176         // copy the compiled class into the module
177         Path classFile = Paths.get("p", "Provider.class");
178         Files.copy(output.resolve(classFile),
179                 mods.resolve(TEST2_MODULE).resolve(classFile),
180                 StandardCopyOption.REPLACE_EXISTING);
181 
182         Assertions.assertThrows(ServiceConfigurationError.class,
183                 // load providers and instantiate each one
184                 () -> loadProviders(mods, TEST2_MODULE).forEach(Provider::get)
185         );
186     }
187 
188 
189     /**
190      * Test a service provider that defines more than one no-args
191      * public static "provider" method.
192      */
193     @Test
194     public void testWithTwoFactoryMethods() throws Exception {
195         Path mods = compileTest(TEST1_MODULE);
196 
197         var bytes = ClassFile.of().build(ClassDesc.of("p", "ProviderFactory"), clb -> {
198             clb.withSuperclass(CD_Object);
199             clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
200 
201             var providerFactory$1 = ClassDesc.of("p", "ProviderFactory$1");
202 
203             // public static p.Service provider()
204             clb.withMethodBody("provider", MethodTypeDesc.of(ClassDesc.of("p", "Service")),
205                     ACC_PUBLIC | ACC_STATIC, cob -> {
206                         cob.new_(providerFactory$1);
207                         cob.dup();
208                         cob.invokespecial(providerFactory$1, INIT_NAME, MTD_void);
209                         cob.areturn();
210                     });
211 
212             // public static p.ProviderFactory$1 provider()
213             clb.withMethodBody("provider", MethodTypeDesc.of(providerFactory$1),
214                     ACC_PUBLIC | ACC_STATIC, cob -> {
215                         cob.new_(providerFactory$1);
216                         cob.dup();
217                         cob.invokespecial(providerFactory$1, INIT_NAME, MTD_void);
218                         cob.areturn();
219                     });
220         });
221 
222         // write the class bytes into the compiled module directory
223         Path classFile = mods.resolve(TEST1_MODULE)
224                 .resolve("p")
225                 .resolve("ProviderFactory.class");
226         Files.write(classFile, bytes);
227 
228         Assertions.assertThrows(ServiceConfigurationError.class,
229                 // load providers and instantiate each one
230                 () -> loadProviders(mods, TEST1_MODULE).forEach(Provider::get)
231         );
232     }
233 
234 }
235