1 /*
   2  * Copyright (c) 2020, 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  * @summary Test that a hidden class has the same module as its lookup class.
  27  * @library /test/lib
  28  * @modules java.compiler
  29  *          java.management
  30  * @compile pkg/HasNamedModule.java
  31  * @run main/othervm HiddenGetModule
  32  */
  33 
  34 import java.io.ByteArrayOutputStream;
  35 import java.io.File;
  36 import java.io.FileInputStream;
  37 import java.lang.invoke.MethodType;
  38 import java.lang.invoke.MethodHandles;
  39 import java.lang.invoke.MethodHandles.Lookup;
  40 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*;
  41 import java.io.IOException;
  42 import java.lang.ModuleLayer;
  43 import java.lang.module.Configuration;
  44 import java.lang.module.ModuleDescriptor;
  45 import java.lang.module.ModuleFinder;
  46 import java.lang.module.ModuleReader;
  47 import java.lang.module.ModuleReference;
  48 import java.lang.reflect.Method;
  49 import java.net.URI;
  50 import java.nio.ByteBuffer;
  51 import java.nio.channels.FileChannel;
  52 import java.util.HashMap;
  53 import java.util.HashSet;
  54 import java.util.Map;
  55 import java.util.Objects;
  56 import java.util.Optional;
  57 import java.util.Set;
  58 
  59 import jdk.test.lib.compiler.InMemoryJavaCompiler;
  60 
  61 public class HiddenGetModule {
  62 
  63    static byte unnamedKlassbuf[] = InMemoryJavaCompiler.compile("TestClass",
  64        "public class TestClass { " +
  65        "    public static void concat(String one, String two) throws Throwable { " +
  66        "        System.out.println(one + two);" +
  67        " } } ");
  68 
  69     public static ModuleFinder finderOf(ModuleDescriptor... descriptors) {
  70 
  71         // Create a ModuleReference for each module
  72         Map<String, ModuleReference> namesToReference = new HashMap<>();
  73 
  74         for (ModuleDescriptor descriptor : descriptors) {
  75             String name = descriptor.name();
  76 
  77             URI uri = URI.create("module:/" + name);
  78 
  79             ModuleReference mref = new ModuleReference(descriptor, uri) {
  80                 @Override
  81                 public ModuleReader open() {
  82                     throw new UnsupportedOperationException();
  83                 }
  84             };
  85 
  86             namesToReference.put(name, mref);
  87         }
  88 
  89         return new ModuleFinder() {
  90             @Override
  91             public Optional<ModuleReference> find(String name) {
  92                 Objects.requireNonNull(name);
  93                 return Optional.ofNullable(namesToReference.get(name));
  94             }
  95             @Override
  96             public Set<ModuleReference> findAll() {
  97                 return new HashSet<>(namesToReference.values());
  98             }
  99         };
 100     }
 101 
 102     public static void main(String[] args) throws Throwable {
 103 
 104         // Test unnamed module.
 105         Lookup lookup = MethodHandles.lookup();
 106         Class<?> cl = lookup.defineHiddenClass(unnamedKlassbuf, false, NESTMATE).lookupClass();
 107         if (cl.getModule() != HiddenGetModule.class.getModule()) {
 108             throw new RuntimeException("hidden class and lookup class have different unnamed modules");
 109         }
 110 
 111         // Test named module.
 112         MyClassLoader myClassLoader = new MyClassLoader();
 113 
 114         // Define a module named HiddenModule containing package pkg.
 115         ModuleDescriptor descriptor = ModuleDescriptor.newModule("HiddenModule")
 116                 .requires("java.base")
 117                 .exports("pkg")
 118                 .build();
 119 
 120         // Set up a ModuleFinder containing the module for this layer.
 121         ModuleFinder finder = finderOf(descriptor);
 122 
 123         // Resolves "HiddenModule"
 124         Configuration cf = ModuleLayer.boot()
 125                 .configuration()
 126                 .resolve(finder, ModuleFinder.of(), Set.of("HiddenModule"));
 127 
 128         // map module to class loader
 129         Map<String, ClassLoader> map = new HashMap<>();
 130         map.put("HiddenModule", myClassLoader);
 131 
 132         // Create layer that contains HiddenModule
 133         ModuleLayer layer = ModuleLayer.boot().defineModules(cf, map::get);
 134 
 135         byte klassbuf[] = InMemoryJavaCompiler.compile("pkg.TestClass",
 136             "package pkg; " +
 137             "public class TestClass { " +
 138             "    public static void concat(String one, String two) throws Throwable { " +
 139             "        System.out.println(one + two);" +
 140             " } } ");
 141 
 142         // Load the class and call the method that defines a hidden class and compares modules.
 143         Class<?>c = Class.forName("pkg.HasNamedModule", true, myClassLoader);
 144         if (c.getClassLoader() != myClassLoader) {
 145             throw new RuntimeException("pkg.HasNamedModule defined by wrong classloader: " + c.getClassLoader());
 146         }
 147         Method m = c.getDeclaredMethod("compareModules", byte[].class);
 148         m.invoke(null, klassbuf);
 149     }
 150 
 151 
 152     public static class MyClassLoader extends ClassLoader {
 153 
 154         public static final String CLASS_NAME = "HasNamedModule";
 155 
 156         static ByteBuffer readClassFile(String name) {
 157             File f = new File(System.getProperty("test.classes", "."), name);
 158             try (FileInputStream fin = new FileInputStream(f);
 159                  FileChannel fc = fin.getChannel()) {
 160                 return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
 161             } catch (IOException e) {
 162                 throw new RuntimeException("Can't open file: " + name + ", " + e.toString());
 163             }
 164         }
 165 
 166         protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
 167             Class<?> c;
 168             if (!name.contains(CLASS_NAME)) {
 169                 c = super.loadClass(name, resolve);
 170             } else {
 171                 // should not delegate to the system class loader
 172                 c = findClass(name);
 173                 if (resolve) {
 174                     resolveClass(c);
 175                 }
 176             }
 177             return c;
 178         }
 179 
 180         protected Class<?> findClass(String name) throws ClassNotFoundException {
 181             if (!name.contains(CLASS_NAME)) {
 182                 throw new ClassNotFoundException("Unexpected class: " + name);
 183             }
 184             return defineClass(name, readClassFile(name.replace(".", File.separator) + ".class"), null);
 185         }
 186     } /* MyClassLoader */
 187 
 188 }